Skip to content
Open
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
193 changes: 186 additions & 7 deletions Xcodes/Backend/AppState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<SavedPasswordResult, Never>?

// MARK: Advanced Preferences
@Published var localPath = "" {
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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)
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")

}

Expand All @@ -1153,3 +1324,11 @@ class AppState: ObservableObject {
var id: String { title + message }
}
}

enum TouchIDSignInError: LocalizedError {
case failed

var errorDescription: String? {
localizeString("TouchIDSignInFailed")
}
}
47 changes: 47 additions & 0 deletions Xcodes/Backend/Environment.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import AppKit
import Foundation
import Path
import KeychainAccess
import LocalAuthentication
import XcodesKit
import XcodesLoginKit
import os
Expand All @@ -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())
Expand Down Expand Up @@ -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? {
Expand Down
2 changes: 2 additions & 0 deletions Xcodes/Frontend/Common/XcodesAlert.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -26,6 +27,7 @@ enum XcodesAlert: Identifiable {
case .unauthenticated: return 6
case .deletePlatform: return 8
case .noActiveXcode: return 9
case .offerTouchID: return 11
}
}
}
Expand Down
11 changes: 11 additions & 0 deletions Xcodes/Frontend/MainWindow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down
Loading
Loading