From a6324e8a3272850353459a6baf514e4da0075789 Mon Sep 17 00:00:00 2001 From: Michael Charland Date: Mon, 23 Nov 2026 15:17:39 -0500 Subject: [PATCH] Sign in with Touch ID using the saved Apple ID password After a user signs in by typing their password on a Mac with Touch ID, offer once to use Touch ID next time. When it's on, an expired Apple session is restored with a Touch ID prompt instead of the sign-in window, and the sign-in window offers "Sign in with Touch ID". If Touch ID fails, is cancelled, or isn't available, the normal sign-in window is shown. Concurrent session checks share one prompt, and no prompt is shown while the app is in the background. Signing out turns Touch ID off and offers it again on the next sign-in. Co-Authored-By: Claude Opus 5.5 --- Xcodes/Backend/AppState.swift | 193 +++++++++++++- Xcodes/Backend/Environment.swift | 47 ++++ Xcodes/Frontend/Common/XcodesAlert.swift | 2 + Xcodes/Frontend/MainWindow.swift | 11 + .../SignIn/SignInCredentialsView.swift | 31 ++- Xcodes/Resources/Localizable.xcstrings | 80 ++++++ XcodesTests/AppStateTests.swift | 243 ++++++++++++++++++ XcodesTests/Environment+Mock.swift | 13 +- 8 files changed, 609 insertions(+), 11 deletions(-) diff --git a/Xcodes/Backend/AppState.swift b/Xcodes/Backend/AppState.swift index 96249de0..99e7e2b2 100644 --- a/Xcodes/Backend/AppState.swift +++ b/Xcodes/Backend/AppState.swift @@ -114,6 +114,12 @@ class AppState: ObservableObject { @Published var error: Error? @Published var authError: Error? + /// Set when the user types a password, so the app can offer Touch ID once sign-in finishes. + private var shouldOfferTouchIDAfterSignIn = false + /// `true` while a Touch ID prompt for the saved password is on screen. + @Published private(set) var isAuthenticatingWithTouchID = false + /// The Touch ID prompt in progress, shared so that callers checking the session at the same time see one prompt. + private var touchIDPasswordTask: Task? // MARK: Advanced Preferences @Published var localPath = "" { @@ -174,6 +180,13 @@ class AppState: ObservableObject { } } + /// When `true`, Touch ID is required before the saved Apple ID password is used to sign in again. + @Published private(set) var requireTouchIDForSavedPassword = false { + didSet { + Current.defaults.set(requireTouchIDForSavedPassword, forKey: "requireTouchIDForSavedPassword") + } + } + @Published var terminateAfterLastWindowClosed = false { didSet { Current.defaults.set(terminateAfterLastWindowClosed, forKey: "terminateAfterLastWindowClosed") @@ -290,6 +303,7 @@ class AppState: ObservableObject { installPath = Current.defaults.string(forKey: "installPath") ?? Path.defaultInstallDirectory.string showOpenInRosettaOption = Current.defaults.bool(forKey: "showOpenInRosettaOption") ?? false terminateAfterLastWindowClosed = Current.defaults.bool(forKey: "terminateAfterLastWindowClosed") ?? false + requireTouchIDForSavedPassword = Current.defaults.bool(forKey: "requireTouchIDForSavedPassword") ?? false enableGroupedXcodeList = Current.defaults.get(forKey: PreferenceKey.enableGroupedXcodeList.rawValue) as? Bool ?? true usePrivilegedHelperForFileOperations = Current.defaults.bool(forKey: PreferenceKey.usePrivilegeHelperForFileOperations.rawValue) ?? false showTags = Current.defaults.get(forKey: PreferenceKey.showTags.rawValue) as? Bool ?? true @@ -325,6 +339,10 @@ class AppState: ObservableObject { } func signInIfNeededAsync() async throws { + try await signInIfNeededAsync(presentSignInOnTouchIDFailure: false) + } + + private func signInIfNeededAsync(presentSignInOnTouchIDFailure: Bool) async throws { do { let authenticationState = try await validateSessionAsync() try Task.checkCancellation() @@ -337,24 +355,167 @@ class AppState: ObservableObject { guard error as? AuthenticationError == .invalidSession || Self.isUnauthorizedInstallError(error) else { throw error } - guard - let username = savedUsername, - let password = try? Current.keychain.getString(username) - else { + guard let username = savedUsername else { throw error } + + switch await savedPasswordResult(for: username) { + case let .password(password): + // An automatic sign-in isn't the user typing a password, so don't offer Touch ID for it. + shouldOfferTouchIDAfterSignIn = false + _ = try await signInAsync(username: username, password: password) + case .touchIDFailed: + try Task.checkCancellation() + if presentSignInOnTouchIDFailure { + presentedSheet = .signIn + } throw error + case .none: + throw error + } + } + } + + enum SavedPasswordResult: Sendable, Equatable { + /// The saved password, unlocked with Touch ID if the user turned it on. + case password(String) + /// No password is saved for this account. + case none + /// Touch ID is required but failed, was cancelled, or isn't available right now. + case touchIDFailed + } + + /// Reads the saved Apple ID password, returning `nil` if there isn't one or Touch ID didn't succeed. + func savedPasswordAsync(for username: String) async -> String? { + if case let .password(password) = await savedPasswordResult(for: username) { + return password + } + return nil + } + + /// Reads the saved Apple ID password, first requiring Touch ID when the user has turned it on. + /// + /// Callers that ask at the same time share one Touch ID prompt. No prompt is shown while the app + /// is in the background (for example, from the auto-install timer), since nobody may be there to answer it. + private func savedPasswordResult(for username: String) async -> SavedPasswordResult { + guard requireTouchIDForSavedPassword else { + guard let password = try? Current.keychain.getString(username) else { return .none } + return .password(password) + } + if let touchIDPasswordTask { + return await touchIDPasswordTask.value + } + guard (try? Current.keychain.getString(username)) != nil else { return .none } + guard Current.biometrics.isAvailable(), Current.biometrics.isAppActive() else { return .touchIDFailed } + + let task = Task { @MainActor () -> SavedPasswordResult in + let reason = String(format: localizeString("TouchIDReason.UseSavedPassword"), username) + guard await Current.biometrics.authenticate(reason: reason), + let password = try? Current.keychain.getString(username) else { + return .touchIDFailed } + return .password(password) + } + touchIDPasswordTask = task + isAuthenticatingWithTouchID = true + defer { + touchIDPasswordTask = nil + isAuthenticatingWithTouchID = false + } + // Cancelling the caller cancels the prompt too, so a stale prompt can't finish later. + return await withTaskCancellationHandler { + await task.value + } onCancel: { + task.cancel() + } + } - _ = try await signInAsync(username: username, password: password) + /// After the first sign-in with a typed password, asks once whether to use Touch ID next time. + private func offerTouchIDIfNeeded() { + guard + !requireTouchIDForSavedPassword, + Current.defaults.bool(forKey: "hasOfferedTouchID") != true, + Current.biometrics.isAvailable() + else { return } + Task { @MainActor in + // Wait for the sign-in sheet to close and for any other alert to be dismissed, so the offer + // neither gets dropped by SwiftUI nor replaces a message the user needs to see. + for _ in 0..<60 { + try? await Task.sleep(for: .milliseconds(500)) + guard !requireTouchIDForSavedPassword else { return } + if presentedSheet == nil, presentedAlert == nil { + presentedAlert = .offerTouchID + return + } + } + } + } + + /// Records the user's answer to the Touch ID offer so it isn't shown again. + func respondToTouchIDOffer(useTouchID: Bool) async { + Current.defaults.set(true, forKey: "hasOfferedTouchID") + if useTouchID { + await setRequireTouchIDForSavedPassword(true) + } + } + + /// Whether the sign-in window can offer Touch ID instead of typing the password for this account. + func canSignInWithTouchID(username: String) -> Bool { + let username = username.lowercased() + guard + !username.isEmpty, + requireTouchIDForSavedPassword, + Current.biometrics.isAvailable() + else { return false } + return (try? Current.keychain.getString(username)) != nil + } + + /// Signs in with the saved password after the user authenticates with Touch ID. + func signInWithTouchID(username: String) { + guard !isAuthenticatingWithTouchID else { return } + authError = nil + shouldOfferTouchIDAfterSignIn = false + let username = username.lowercased() + startAuthenticationTask { + let result = await self.savedPasswordResult(for: username) + // Ignore a result that arrives after the user cancelled or started another sign-in. + try Task.checkCancellation() + guard case .signIn = self.presentedSheet else { return } + guard case let .password(password) = result else { + self.authError = TouchIDSignInError.failed + return + } + _ = try await self.signInAsync(username: username, password: password) + } + } + + /// Cancels an in-progress sign-in, including an open Touch ID prompt. + func cancelSignIn() { + authenticationTask?.cancel() + authError = nil + presentedSheet = nil + } + + /// Turns the Touch ID requirement on or off. Turning it on asks for Touch ID first, + /// so the user knows it works before the app relies on it. + func setRequireTouchIDForSavedPassword(_ isRequired: Bool) async { + guard isRequired else { + requireTouchIDForSavedPassword = false + return + } + guard Current.biometrics.isAvailable() else { return } + if await Current.biometrics.authenticate(reason: localizeString("TouchIDReason.Enable")) { + requireTouchIDForSavedPassword = true } } func restoreAuthenticationStateIfNeeded() async throws { guard hasSavedUsername else { return } - try await signInIfNeededAsync() + // At launch, if the user cancels or fails Touch ID, show the sign-in window rather than nothing. + try await signInIfNeededAsync(presentSignInOnTouchIDFailure: true) } func signIn(username: String, password: String?) { authError = nil + shouldOfferTouchIDAfterSignIn = password?.isEmpty == false startAuthenticationTask { _ = try await self.signInAsync(username: username.lowercased(), password: password) } @@ -454,11 +615,18 @@ class AppState: ObservableObject { // Explicit sign-out owns removal of the saved account and password. Logger.appState.error("Authentication error: \(error.legibleDescription)") self.authError = error + shouldOfferTouchIDAfterSignIn = false } private func handleAuthenticationFlowSuccess() { switch self.authenticationState { - case .authenticated, .unauthenticated, .notAppleDeveloper: + case .authenticated: + self.presentedSheet = nil + if shouldOfferTouchIDAfterSignIn { + shouldOfferTouchIDAfterSignIn = false + offerTouchIDIfNeeded() + } + case .unauthenticated, .notAppleDeveloper: self.presentedSheet = nil case .waitingForFederatedAuthentication: break @@ -1142,6 +1310,9 @@ class AppState: ObservableObject { try? Current.keychain.remove(username) } Current.defaults.removeObject(forKey: "username") + // Signing out removes the saved password, so turn Touch ID off and offer it again on the next sign-in. + requireTouchIDForSavedPassword = false + Current.defaults.removeObject(forKey: "hasOfferedTouchID") } @@ -1153,3 +1324,11 @@ class AppState: ObservableObject { var id: String { title + message } } } + +enum TouchIDSignInError: LocalizedError { + case failed + + var errorDescription: String? { + localizeString("TouchIDSignInFailed") + } +} diff --git a/Xcodes/Backend/Environment.swift b/Xcodes/Backend/Environment.swift index 4373d470..7caf5573 100644 --- a/Xcodes/Backend/Environment.swift +++ b/Xcodes/Backend/Environment.swift @@ -1,6 +1,8 @@ +import AppKit import Foundation import Path import KeychainAccess +import LocalAuthentication import XcodesKit import XcodesLoginKit import os @@ -20,6 +22,7 @@ public struct Environment: Sendable { public var date: @Sendable () -> Date = { Date() } public var helper = Helper() public var notificationManager = NotificationManager() + public var biometrics = Biometrics() } private let currentEnvironment = CurrentEnvironmentStorage(Environment()) @@ -237,6 +240,50 @@ public struct Keychain: Sendable { } } +/// Touch ID checks used to protect the Apple ID password saved in the keychain. +public struct Biometrics: Sendable { + /// Returns `true` when this Mac can currently authenticate with Touch ID. + public var isAvailable: @Sendable () -> Bool = { + LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) + } + + /// Returns `true` when the app is frontmost, so a Touch ID prompt has someone to answer it. + public var isAppActive: @MainActor @Sendable () -> Bool = { + NSApplication.shared.isActive + } + + /// Asks the user to authenticate with Touch ID, returning `true` only on success. + /// Cancelling the calling task closes the prompt. + /// + /// The reason is shown in the system prompt after "Xcodes is trying to". + public var authenticate: @Sendable (_ reason: String) async -> Bool = { reason in + let box = LAContextBox() + return await withTaskCancellationHandler { + do { + return try await box.context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) + } catch { + return false + } + } onCancel: { + box.context.invalidate() + } + } + public func authenticate(reason: String) async -> Bool { + await authenticate(reason) + } +} + +/// Lets the cancellation handler close the Touch ID prompt. `LAContext.invalidate()` is safe to call from any thread. +private final class LAContextBox: @unchecked Sendable { + let context: LAContext + + init() { + context = LAContext() + // Hide the "Enter Password" button: the fallback is the app's own sign-in window. + context.localizedFallbackTitle = "" + } +} + public struct Defaults: Sendable { public var string: @Sendable (String) -> String? = { UserDefaults.standard.string(forKey: $0) } public func string(forKey key: String) -> String? { diff --git a/Xcodes/Frontend/Common/XcodesAlert.swift b/Xcodes/Frontend/Common/XcodesAlert.swift index d35786b5..e72eaa38 100644 --- a/Xcodes/Frontend/Common/XcodesAlert.swift +++ b/Xcodes/Frontend/Common/XcodesAlert.swift @@ -13,6 +13,7 @@ enum XcodesAlert: Identifiable { case unauthenticated case deletePlatform(runtime: DownloadableRuntime) case noActiveXcode(runtime: DownloadableRuntime, xcode: Xcode?) + case offerTouchID var id: Int { switch self { @@ -26,6 +27,7 @@ enum XcodesAlert: Identifiable { case .unauthenticated: return 6 case .deletePlatform: return 8 case .noActiveXcode: return 9 + case .offerTouchID: return 11 } } } diff --git a/Xcodes/Frontend/MainWindow.swift b/Xcodes/Frontend/MainWindow.swift index b6a6213b..4df99366 100644 --- a/Xcodes/Frontend/MainWindow.swift +++ b/Xcodes/Frontend/MainWindow.swift @@ -236,6 +236,17 @@ struct MainWindow: View { ) case let .noActiveXcode(runtime, xcode): return .noActiveXcode(appState: appState, runtime: runtime, xcode: xcode, inSettings: false) + case .offerTouchID: + return Alert( + title: Text("Alert.OfferTouchID.Title"), + message: Text("Alert.OfferTouchID.Message"), + primaryButton: .default(Text("Alert.OfferTouchID.Button"), action: { + Task { await appState.respondToTouchIDOffer(useTouchID: true) } + }), + secondaryButton: .cancel(Text("NotNow"), action: { + Task { await appState.respondToTouchIDOffer(useTouchID: false) } + }) + ) case let .deletePlatform(runtime): return Alert( title: Text(String(format: localizeString("Alert.DeletePlatform.Title"), runtime.name)), diff --git a/Xcodes/Frontend/SignIn/SignInCredentialsView.swift b/Xcodes/Frontend/SignIn/SignInCredentialsView.swift index 15f2ac21..593c9160 100644 --- a/Xcodes/Frontend/SignIn/SignInCredentialsView.swift +++ b/Xcodes/Frontend/SignIn/SignInCredentialsView.swift @@ -9,6 +9,7 @@ struct SignInCredentialsView: View { @State private var username: String = "" @State private var password: String = "" @FocusState private var focusedField: FocusedField? + @State private var canSignInWithTouchID = false var body: some View { VStack(alignment: .leading) { @@ -42,10 +43,17 @@ struct SignInCredentialsView: View { } HStack { + if canSignInWithTouchID { + Button { + appState.signInWithTouchID(username: username) + } label: { + Label("SignInWithTouchID", systemImage: "touchid") + } + .disabled(appState.isProcessingAuthRequest || appState.isAuthenticatingWithTouchID) + } Spacer() Button("Cancel") { - appState.authError = nil - appState.presentedSheet = nil + appState.cancelSignIn() } .keyboardShortcut(.cancelAction) ProgressButton( @@ -55,12 +63,29 @@ struct SignInCredentialsView: View { Text("Next") } ) - .disabled(username.isEmpty) + .disabled(username.isEmpty || appState.isAuthenticatingWithTouchID) .keyboardShortcut(.defaultAction) } .frame(height: 25) } .padding() + .onAppear { + if username.isEmpty, let savedUsername = appState.savedUsername { + username = savedUsername + } + } + .task(id: username) { + // Wait for typing to pause before checking the keychain, instead of reading it on every keystroke. + if !canSignInWithTouchID { + try? await Task.sleep(for: .milliseconds(400)) + guard !Task.isCancelled else { return } + } + updateCanSignInWithTouchID() + } + } + + private func updateCanSignInWithTouchID() { + canSignInWithTouchID = appState.canSignInWithTouchID(username: username) } } diff --git a/Xcodes/Resources/Localizable.xcstrings b/Xcodes/Resources/Localizable.xcstrings index c0d1763a..53fc0a1a 100644 --- a/Xcodes/Resources/Localizable.xcstrings +++ b/Xcodes/Resources/Localizable.xcstrings @@ -31596,6 +31596,86 @@ } } }, + "SignInWithTouchID" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sign in with Touch ID" + } + } + } + }, + "TouchIDSignInFailed" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Touch ID didn't succeed. Enter your password to sign in." + } + } + } + }, + "Alert.OfferTouchID.Title" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Use Touch ID next time?" + } + } + } + }, + "Alert.OfferTouchID.Message" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Xcodes saved your Apple ID password in your keychain. Instead of typing it again, you can sign in with your fingerprint." + } + } + } + }, + "Alert.OfferTouchID.Button" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Use Touch ID" + } + } + } + }, + "NotNow" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Not Now" + } + } + } + }, + "TouchIDReason.UseSavedPassword" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "use the saved Apple ID password for %@" + } + } + } + }, + "TouchIDReason.Enable" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "use Touch ID to sign in to your Apple ID" + } + } + } + }, "Reveal simulator runtimes in Finder" : { "localizations" : { "ca" : { diff --git a/XcodesTests/AppStateTests.swift b/XcodesTests/AppStateTests.swift index 325ebabc..7ac406ac 100644 --- a/XcodesTests/AppStateTests.swift +++ b/XcodesTests/AppStateTests.swift @@ -653,6 +653,249 @@ class AppStateTests: XCTestCase { XCTAssertNil(subject.authError) } + func test_SavedPassword_WithoutTouchIDRequirement_DoesNotPrompt() async { + let didPrompt = TestLockedBox(false) + Current.keychain.getString = { _ in "password" } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in + didPrompt.withValue { $0 = true } + return true + } + + let password = await subject.savedPasswordAsync(for: "jane@example.com") + + XCTAssertEqual(password, "password") + XCTAssertFalse(didPrompt.read { $0 }) + } + + func test_SetRequireTouchID_TouchIDSuccess_TurnsOnAndSaves() async { + let savedValue = TestLockedBox(nil) + Current.defaults.set = { value, key in + guard key == "requireTouchIDForSavedPassword" else { return } + let isRequired = value as? Bool + savedValue.withValue { $0 = isRequired } + } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + + await subject.setRequireTouchIDForSavedPassword(true) + + XCTAssertTrue(subject.requireTouchIDForSavedPassword) + XCTAssertEqual(savedValue.read { $0 }, true) + } + + func test_SetRequireTouchID_TouchIDFailure_StaysOff() async { + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in false } + + await subject.setRequireTouchIDForSavedPassword(true) + + XCTAssertFalse(subject.requireTouchIDForSavedPassword) + } + + func test_SetRequireTouchID_Unavailable_StaysOffWithoutPrompting() async { + let didPrompt = TestLockedBox(false) + Current.biometrics.isAvailable = { false } + Current.biometrics.authenticate = { _ in + didPrompt.withValue { $0 = true } + return true + } + + await subject.setRequireTouchIDForSavedPassword(true) + + XCTAssertFalse(subject.requireTouchIDForSavedPassword) + XCTAssertFalse(didPrompt.read { $0 }) + } + + func test_SavedPassword_WithTouchIDSuccess_ReturnsPassword() async { + Current.keychain.getString = { _ in "password" } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + await subject.setRequireTouchIDForSavedPassword(true) + + let reason = TestLockedBox(nil) + Current.biometrics.authenticate = { text in + reason.withValue { $0 = text } + return true + } + let password = await subject.savedPasswordAsync(for: "jane@example.com") + + XCTAssertEqual(password, "password") + XCTAssertEqual(reason.read { $0 }, "use the saved Apple ID password for jane@example.com") + } + + func test_SavedPassword_WithTouchIDFailure_ReturnsNil() async { + Current.keychain.getString = { _ in "password" } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + await subject.setRequireTouchIDForSavedPassword(true) + Current.biometrics.authenticate = { _ in false } + + let password = await subject.savedPasswordAsync(for: "jane@example.com") + + XCTAssertNil(password) + } + + func test_SavedPassword_WithTouchIDUnavailable_ReturnsNil() async { + Current.keychain.getString = { _ in "password" } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + await subject.setRequireTouchIDForSavedPassword(true) + Current.biometrics.isAvailable = { false } + + let password = await subject.savedPasswordAsync(for: "jane@example.com") + + XCTAssertNil(password) + } + + func test_SignInIfNeeded_TouchIDFailure_DoesNotSignInWithSavedPassword() async throws { + let didSignIn = TestLockedBox(false) + Current.defaults.string = { key in key == "username" ? "jane@example.com" : nil } + Current.keychain.getString = { _ in "password" } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + await subject.setRequireTouchIDForSavedPassword(true) + Current.biometrics.authenticate = { _ in false } + Current.network.session = MockURLProtocol.session { _ in + didSignIn.withValue { $0 = true } + throw URLError(.timedOut) + } + // Set after `session`, which resets the session validation closure. + Current.network.validateSessionAsync = { throw AuthenticationError.invalidSession } + + do { + try await subject.signInIfNeededAsync() + XCTFail("Expected the invalid session error so the sign-in window is shown") + } catch { + XCTAssertEqual(error as? AuthenticationError, .invalidSession) + } + + XCTAssertFalse(didSignIn.read { $0 }) + } + + func test_CanSignInWithTouchID_RequiresSettingAndSavedPassword() async { + Current.keychain.getString = { key in key == "jane@example.com" ? "password" : nil } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + + XCTAssertFalse(subject.canSignInWithTouchID(username: "jane@example.com")) + + await subject.setRequireTouchIDForSavedPassword(true) + + XCTAssertTrue(subject.canSignInWithTouchID(username: "Jane@Example.com")) + XCTAssertFalse(subject.canSignInWithTouchID(username: "other@example.com")) + XCTAssertFalse(subject.canSignInWithTouchID(username: "")) + + Current.biometrics.isAvailable = { false } + XCTAssertFalse(subject.canSignInWithTouchID(username: "jane@example.com")) + } + + func test_SignInWithTouchID_Failure_ShowsErrorWithoutSigningIn() async throws { + let didSignIn = TestLockedBox(false) + Current.keychain.getString = { _ in "password" } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + await subject.setRequireTouchIDForSavedPassword(true) + Current.biometrics.authenticate = { _ in false } + Current.network.session = MockURLProtocol.session { _ in + didSignIn.withValue { $0 = true } + throw URLError(.timedOut) + } + + subject.presentedSheet = .signIn + subject.signInWithTouchID(username: "jane@example.com") + for _ in 0..<100 where subject.authError == nil { + try await Task.sleep(for: .milliseconds(10)) + } + + XCTAssertTrue(subject.authError is TouchIDSignInError) + XCTAssertFalse(didSignIn.read { $0 }) + } + + func test_SavedPassword_ConcurrentCallers_ShareOneTouchIDPrompt() async { + let promptCount = TestLockedBox(0) + Current.keychain.getString = { _ in "password" } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + await subject.setRequireTouchIDForSavedPassword(true) + Current.biometrics.authenticate = { _ in + promptCount.withValue { $0 += 1 } + try? await Task.sleep(for: .milliseconds(200)) + return true + } + + let appState: AppState = subject + let first = Task { @MainActor in await appState.savedPasswordAsync(for: "jane@example.com") } + let second = Task { @MainActor in await appState.savedPasswordAsync(for: "jane@example.com") } + let passwords = [await first.value, await second.value] + + XCTAssertEqual(passwords, ["password", "password"]) + XCTAssertEqual(promptCount.read { $0 }, 1) + } + + func test_SavedPassword_AppInBackground_DoesNotPrompt() async { + let didPrompt = TestLockedBox(false) + Current.keychain.getString = { _ in "password" } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + await subject.setRequireTouchIDForSavedPassword(true) + Current.biometrics.isAppActive = { false } + Current.biometrics.authenticate = { _ in + didPrompt.withValue { $0 = true } + return true + } + + let password = await subject.savedPasswordAsync(for: "jane@example.com") + + XCTAssertNil(password) + XCTAssertFalse(didPrompt.read { $0 }) + } + + func test_RestoreAuthenticationState_TouchIDFailure_ShowsSignInWindow() async throws { + Current.defaults.string = { key in key == "username" ? "jane@example.com" : nil } + Current.keychain.getString = { _ in "password" } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + await subject.setRequireTouchIDForSavedPassword(true) + Current.biometrics.authenticate = { _ in false } + Current.network.validateSessionAsync = { throw AuthenticationError.invalidSession } + + try? await subject.restoreAuthenticationStateIfNeeded() + + guard case .signIn = subject.presentedSheet else { + return XCTFail("Expected the sign-in window after Touch ID failed at launch") + } + } + + func test_SignOut_TurnsOffTouchIDAndOffersItAgain() async { + let removedKeys = TestLockedBox<[String]>([]) + Current.defaults.removeObject = { key in removedKeys.withValue { $0.append(key) } } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + await subject.setRequireTouchIDForSavedPassword(true) + + subject.signOut() + + XCTAssertFalse(subject.requireTouchIDForSavedPassword) + XCTAssertTrue(removedKeys.read { $0.contains("hasOfferedTouchID") }) + } + + func test_RespondToTouchIDOffer_RecordsAnswer() async { + let savedKeys = TestLockedBox<[String]>([]) + Current.defaults.set = { _, key in savedKeys.withValue { $0.append(key) } } + Current.biometrics.isAvailable = { true } + Current.biometrics.authenticate = { _ in true } + + await subject.respondToTouchIDOffer(useTouchID: false) + + XCTAssertTrue(savedKeys.read { $0.contains("hasOfferedTouchID") }) + XCTAssertFalse(subject.requireTouchIDForSavedPassword) + + await subject.respondToTouchIDOffer(useTouchID: true) + + XCTAssertTrue(subject.requireTouchIDForSavedPassword) + } + func test_SignIn_NetworkFailurePreservesSavedCredentials() async throws { let removedCredentials = TestLockedBox<[String]>([]) Current.keychain.remove = { key in removedCredentials.withValue { $0.append(key) } } diff --git a/XcodesTests/Environment+Mock.swift b/XcodesTests/Environment+Mock.swift index 6bcf95f9..315c783c 100644 --- a/XcodesTests/Environment+Mock.swift +++ b/XcodesTests/Environment+Mock.swift @@ -16,7 +16,8 @@ extension Xcodes.Environment { keychain: .mock, defaults: .mock, date: Date.mock, - helper: .mock + helper: .mock, + biometrics: .mock ) } } @@ -87,6 +88,16 @@ extension Network { } } +extension Biometrics { + static var mock: Biometrics { + Biometrics( + isAvailable: { false }, + isAppActive: { true }, + authenticate: { _ in false } + ) + } +} + extension Keychain { static var mock: Keychain { Keychain(