Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cmd/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ func formatRPCError(err *jsonrpc.RPCError) string {
return fmt.Sprintf("%s\nAuthenticate via Touch ID to proceed.", err.Message)
case jsonrpc.CodeSecretNotFound:
return fmt.Sprintf("%s\nRun 'tsm list' to see available secrets.", err.Message)
case jsonrpc.CodeAuthUnavailable:
return fmt.Sprintf("%s\nNo Touch ID prompt was shown. Fix the cause above, then try again.", err.Message)
default:
return err.Message
}
Expand Down
23 changes: 23 additions & 0 deletions cmd/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"bytes"
"encoding/json"
"strings"
"testing"

"tsm/internal/jsonrpc"
Expand Down Expand Up @@ -36,3 +37,25 @@ func TestPrintJSON(t *testing.T) {
t.Fatalf("output is not valid JSON: %s", buf.String())
}
}

func TestFormatError_AuthUnavailable_DoesNotAskForTouchID(t *testing.T) {
err := &jsonrpc.RPCError{
Code: jsonrpc.CodeAuthUnavailable,
Message: "No fingerprints are enrolled for Touch ID. Add one in System Settings > Touch ID & Password.",
}
msg := formatRPCError(err)
if !strings.Contains(msg, "No fingerprints are enrolled") {
t.Errorf("expected daemon's reason in message, got %q", msg)
}
if strings.Contains(msg, "Authenticate via Touch ID to proceed") {
t.Errorf("no prompt was shown; message must not ask for Touch ID: %q", msg)
}
if !strings.Contains(msg, "No Touch ID prompt was shown") {
t.Errorf("expected guidance that no prompt was shown, got %q", msg)
}
// The daemon's reason carries the fix; a fixed lid/keyboard hint would be
// wrong for lockout or enrollment causes.
if strings.Contains(msg, "lid") || strings.Contains(msg, "keyboard") {
t.Errorf("CLI must not add a cause-specific hint: %q", msg)
}
}
7 changes: 4 additions & 3 deletions internal/jsonrpc/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ func (e *RPCError) Error() string {

// Well-known tsm error codes.
const (
CodeVaultLocked = -32001
CodeAuthRequired = -32002
CodeSecretNotFound = -32003
CodeVaultLocked = -32001
CodeAuthRequired = -32002
CodeSecretNotFound = -32003
CodeAuthUnavailable = -32004
)
2 changes: 2 additions & 0 deletions plugin/skills/credential-usage/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ Entries with `"confirm": true` prompt Touch ID on every access, even inside the

With no GUI login session (ssh without a console session, cron, CI), `tsm run` refuses and names the secret. Hand the user a command to run where Touch ID is available; dropping the gate with `tsm edit` is their call.

"No Touch ID prompt was shown" in an error (JSON code `-32004`) means macOS refused to show one. The causes: a Magic Keyboard with Touch ID lost its pairing while the lid is closed (macOS blames the lid; a USB cable pairs it again), Touch ID is locked out, or no finger is enrolled. Retrying fails the same way. Tell the user the reason in one line and wait for them to fix it.

## A credential the user pastes into chat

Use it for the task in hand, then hand off the save. The value must not pass through a command line at any step:
Expand Down
37 changes: 36 additions & 1 deletion tsmd/Sources/tsmd/Auth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ struct TouchIDAuth: AuthProvider, Sendable {
var error: NSError?

guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
throw VaultError.authFailed
// No prompt was shown. Say why, so the caller doesn't wait for (or
// tell the user to touch) a dialog that will never appear.
throw VaultError.authUnavailable(Self.unavailableReason(error))
}

do {
Expand All @@ -30,4 +32,37 @@ struct TouchIDAuth: AuthProvider, Sendable {
throw VaultError.authFailed
}
}

/// Human-readable cause for a failed `canEvaluatePolicy`. macOS often puts
/// the real cause only in the debug description. When a Magic Keyboard
/// with Touch ID loses its pairing with a Mac whose lid is closed, macOS
/// returns `systemCancel` ("Authentication canceled.") and the debug text
/// "Touch ID is not available in closed clamshell mode." That text names
/// the lid, but a paired keyboard works with the lid closed; connecting
/// the keyboard with a USB cable pairs it again.
static func unavailableReason(_ error: NSError?) -> String {
guard let error else { return "Touch ID is not available." }
if error.domain == LAErrorDomain {
switch LAError.Code(rawValue: error.code) {
case .biometryLockout:
return "Touch ID is locked after too many failed attempts. "
+ "Unlock your Mac with your password to turn it back on."
case .biometryNotEnrolled:
return "No fingerprints are enrolled for Touch ID. "
+ "Add one in System Settings > Touch ID & Password."
case .passcodeNotSet:
return "Touch ID requires a login password, and none is set."
default:
break
}
}
let detail = (error.userInfo[NSDebugDescriptionErrorKey] as? String)
?? error.localizedDescription
if detail.contains("clamshell") {
return "\(detail) If you use a Magic Keyboard with Touch ID, it may have "
+ "lost its pairing with this Mac. Connect it with a USB cable to pair it again."
}
if detail.hasPrefix("Touch ID") { return detail }
return "Touch ID is not available: \(detail)"
}
}
6 changes: 6 additions & 0 deletions tsmd/Sources/tsmd/JSONRPCHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,12 @@ actor JSONRPCHandler {
message: "Authentication required",
data: ["auth_method": .string("touchid")]
)
case .authUnavailable(let reason):
return JSONRPCError(
code: RPCErrorCode.authUnavailable,
message: reason,
data: ["auth_method": .string("touchid")]
)
case .secretNotFound(let name):
return JSONRPCError(
code: RPCErrorCode.secretNotFound,
Expand Down
1 change: 1 addition & 0 deletions tsmd/Sources/tsmd/JSONRPCTypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,5 @@ enum RPCErrorCode {
static let vaultLocked = -32001
static let authRequired = -32002
static let secretNotFound = -32003
static let authUnavailable = -32004
}
4 changes: 4 additions & 0 deletions tsmd/Sources/tsmd/Vault.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ enum VaultError: Error, Equatable {
case secretAlreadyExists(String)
case authRequired
case authFailed
/// Touch ID could not be presented at all (lid closed, locked out, not
/// enrolled...). Carries the reason. Distinct from authFailed, where a
/// prompt was shown and the user failed or canceled it.
case authUnavailable(String)
case invalidName(String)
case invalidConfig(String) // NEW
}
Expand Down
25 changes: 25 additions & 0 deletions tsmd/Tests/tsmdTests/JSONRPCHandlerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,31 @@ final class JSONRPCHandlerTests: XCTestCase {
"auth.can_confirm must reflect the daemon's biometric presentability, not the caller's TTY")
}

// MARK: - Touch ID unavailable

func testUnlockWhenTouchIDUnavailableReturnsAuthUnavailableWithReason() async {
_ = await handler.handle(makeRequest(method: "vault.init"), sessionID: sid)
await vault.lockAll()
auth.unavailableReason = "Touch ID is not available in closed clamshell mode."

let resp = await handler.handle(makeRequest(method: "vault.unlock"), sessionID: sid)

XCTAssertEqual(resp.error?.code, RPCErrorCode.authUnavailable,
"an unavailable sensor must not look like a failed or pending Touch ID check")
XCTAssertEqual(resp.error?.message,
"Touch ID is not available in closed clamshell mode.")
}

func testUnlockWhenTouchIDFailsStillReturnsAuthRequired() async {
_ = await handler.handle(makeRequest(method: "vault.init"), sessionID: sid)
await vault.lockAll()
auth.shouldFail = true

let resp = await handler.handle(makeRequest(method: "vault.unlock"), sessionID: sid)

XCTAssertEqual(resp.error?.code, RPCErrorCode.authRequired)
}

// MARK: - CRUD

func testVaultAddAndGet() async {
Expand Down
1 change: 1 addition & 0 deletions tsmd/Tests/tsmdTests/JSONRPCTypesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,6 @@ final class JSONRPCTypesTests: XCTestCase {
XCTAssertEqual(RPCErrorCode.vaultLocked, -32001)
XCTAssertEqual(RPCErrorCode.authRequired, -32002)
XCTAssertEqual(RPCErrorCode.secretNotFound, -32003)
XCTAssertEqual(RPCErrorCode.authUnavailable, -32004)
}
}
4 changes: 4 additions & 0 deletions tsmd/Tests/tsmdTests/Mocks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,13 @@ final class MockAuth: AuthProvider, @unchecked Sendable {
var shouldFail = false
var authenticateCalled = false
var canAuthenticateResult = true
/// When set, authenticate() throws authUnavailable with this reason, as
/// TouchIDAuth does when LAContext refuses to evaluate the policy.
var unavailableReason: String?

func authenticate(reason: String) async throws {
authenticateCalled = true
if let unavailable = unavailableReason { throw VaultError.authUnavailable(unavailable) }
if shouldFail { throw VaultError.authFailed }
}

Expand Down
53 changes: 53 additions & 0 deletions tsmd/Tests/tsmdTests/TouchIDAuthTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import LocalAuthentication
import XCTest
@testable import tsmd

/// TouchIDAuth must say why LocalAuthentication refused to evaluate the
/// biometric policy. A generic "Authentication required" tells the user to
/// touch a sensor that no prompt was shown for.
final class TouchIDAuthTests: XCTestCase {
private func laError(_ code: LAError.Code, debug: String? = nil) -> NSError {
var info: [String: Any] = [NSLocalizedDescriptionKey: "Authentication canceled."]
if let debug { info[NSDebugDescriptionErrorKey] = debug }
return NSError(domain: LAErrorDomain, code: code.rawValue, userInfo: info)
}

func testClamshellReasonPointsAtKeyboardPairing() {
// What macOS returns from canEvaluatePolicy with the lid closed when the
// Magic Keyboard with Touch ID has lost its pairing with this Mac:
// systemCancel, with only the lid named in the debug text. A paired
// keyboard works with the lid closed, so the fix is to pair it again.
let reason = TouchIDAuth.unavailableReason(
laError(.systemCancel, debug: "Touch ID is not available in closed clamshell mode."))
XCTAssertTrue(reason.hasPrefix("Touch ID is not available in closed clamshell mode."), reason)
XCTAssertTrue(reason.contains("USB cable"), reason)
XCTAssertFalse(reason.contains("not available: Touch ID is not available"),
"don't repeat macOS's own prefix: \(reason)")
}

func testDebugTextIsPrefixedWhenItDoesNotNameTouchID() {
let reason = TouchIDAuth.unavailableReason(
laError(.systemCancel, debug: "No console session."))
XCTAssertEqual(reason, "Touch ID is not available: No console session.")
}

func testLockoutReasonTellsUserToUsePassword() {
let reason = TouchIDAuth.unavailableReason(laError(.biometryLockout))
XCTAssertTrue(reason.contains("locked"), reason)
XCTAssertTrue(reason.contains("password"), reason)
}

func testNotEnrolledReason() {
let reason = TouchIDAuth.unavailableReason(laError(.biometryNotEnrolled))
XCTAssertTrue(reason.contains("No fingerprints"), reason)
}

func testFallsBackToLocalizedDescription() {
let reason = TouchIDAuth.unavailableReason(laError(.biometryNotAvailable))
XCTAssertEqual(reason, "Touch ID is not available: Authentication canceled.")
}

func testNilErrorStillGivesAReason() {
XCTAssertEqual(TouchIDAuth.unavailableReason(nil), "Touch ID is not available.")
}
}
Loading