From 56c2f841ed6400b43b60c4c94c36e172e3f7407d Mon Sep 17 00:00:00 2001 From: Max Goedjen Date: Mon, 16 Nov 2026 23:15:56 -0800 Subject: [PATCH] Add settings for batch auth handling. (#870) --- Sources/Packages/Package.swift | 2 +- .../Packages/Resources/Localizable.xcstrings | 55 +++++++++++++++++++ .../AuthenticationHandler.swift | 21 +++++-- .../Sources/SettingsKit/SettingKeys.swift | 40 ++++++++++++++ .../SecretAgentKitTests/AgentTests.swift | 18 +++--- .../AuthenticationHandlerTests.swift | 2 +- Sources/SecretAgent/App.swift | 12 +++- Sources/SecretAgent/PendingRequestsView.swift | 16 ++++++ Sources/Secretive.xcodeproj/project.xcproj | 3 + .../Views/Secrets/SettingsView.swift | 42 +++++++++++++- 10 files changed, 191 insertions(+), 20 deletions(-) diff --git a/Sources/Packages/Package.swift b/Sources/Packages/Package.swift index 0fd392d..91bf34e 100644 --- a/Sources/Packages/Package.swift +++ b/Sources/Packages/Package.swift @@ -87,7 +87,7 @@ let package = Package( ), .target( name: "SecretAgentKit", - dependencies: ["SecretKit", "SSHProtocolKit", "CertificateKit", "Common", "Formatters"], + dependencies: ["SecretKit", "SSHProtocolKit", "CertificateKit", "Common", "Formatters", "SettingsKit"], resources: [localization], swiftSettings: swiftSettings, ), diff --git a/Sources/Packages/Resources/Localizable.xcstrings b/Sources/Packages/Resources/Localizable.xcstrings index f5ed051..b68952a 100644 --- a/Sources/Packages/Resources/Localizable.xcstrings +++ b/Sources/Packages/Resources/Localizable.xcstrings @@ -22015,6 +22015,61 @@ }, "shouldTranslate" : false }, + "settings_agent_tab_title" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Agent" + } + } + } + }, + "settings_multiple_authentication_enabled_label" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Show Pending Requests Screen" + } + } + } + }, + "settings_multiple_authentication_section_title" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pending Requests Screen" + } + } + } + }, + "settings_multiple_authentication_shows_dock_icon_label" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Show Dock Item for Pending Requests Screen" + } + } + } + }, + "settings_multiple_authentication_threshold_label" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Minimum Pending Requests Before Pending Screen" + } + } + } + }, "setup_agent_activity_monitor_description" : { "extractionState" : "manual", "localizations" : { diff --git a/Sources/Packages/Sources/SecretAgentKit/AuthenticationHandler.swift b/Sources/Packages/Sources/SecretAgentKit/AuthenticationHandler.swift index 3db48e9..ba7ca54 100644 --- a/Sources/Packages/Sources/SecretAgentKit/AuthenticationHandler.swift +++ b/Sources/Packages/Sources/SecretAgentKit/AuthenticationHandler.swift @@ -1,6 +1,7 @@ @unsafe @preconcurrency import LocalAuthentication import SecretKit import OSLog +import SettingsKit /// A context describing a persisted authentication. public final class AuthenticationContext: AuthenticationContextProtocol { @@ -103,8 +104,10 @@ public final class AuthenticationContext: AuthenticationContextProtocol { private var lastBatchAuthPresentation: Set? private var presentPendingAuth: (() async throws -> Void)? private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "AuthenticationHandler") + private let settingsStore: SettingsStore - public init() { + public init(settingsStore: SettingsStore) { + self.settingsStore = settingsStore } public func setPendingRequestHandler(_ handler: @escaping () async throws -> Void) { @@ -134,11 +137,15 @@ public final class AuthenticationContext: AuthenticationContextProtocol { waitingRequests.remove(request) } - if waitingRequests.count > 1 { + if settingsStore.multipleRequestScreenEnabled && waitingRequests.count >= settingsStore.multipleRequestScreenCountThreshold { return try await waitUntilRequestActedOn(request) + } else { + while activeTask != nil { + try await Task.sleep(for: .milliseconds(100)) + } } - // Hold onto the task and context so we can cancel them when prsenting pending. + // Hold onto the task and context so we can cancel them when presenting pending. activeContext = context let currentTask = Task { logger.log("Beginning individual auth prompt") @@ -147,8 +154,10 @@ public final class AuthenticationContext: AuthenticationContextProtocol { return result } activeTask = currentTask - let result = try? await activeTask?.value - if result == false && activeTask?.isCancelled == false { + let result = try await currentTask.value + activeTask = nil + activeContext = nil + if result == false && currentTask.isCancelled == false { waitingRequests.remove(request) throw CancellationError() } else if currentTask.isCancelled { @@ -161,7 +170,7 @@ public final class AuthenticationContext: AuthenticationContextProtocol { logger.log("Auth prompt was cancelled, waiting for explicit auth") // At this point, we essentially just block the task until either the request has been authenticated "externally" via the pending view. while waitingRequests.contains(request) { - if waitingRequests != lastBatchAuthPresentation { + if waitingRequests != lastBatchAuthPresentation && waitingRequests.count >= settingsStore.multipleRequestScreenCountThreshold { // If we're about to present a batch, we cancel the individual auth prompt, and show the batch one. logger.log("Multiple pending requests exist, cancelling existing auth prompt") activeTask?.cancel() diff --git a/Sources/Packages/Sources/SettingsKit/SettingKeys.swift b/Sources/Packages/Sources/SettingsKit/SettingKeys.swift index 4663529..e082b0f 100644 --- a/Sources/Packages/Sources/SettingsKit/SettingKeys.swift +++ b/Sources/Packages/Sources/SettingsKit/SettingKeys.swift @@ -12,3 +12,43 @@ extension SettingsStore { } } + +struct MultipleRequestScreenEnabledSettingsKey: SettingsStore.SettingsKey { + static let defaultValue: Bool = true +} + +extension SettingsStore { + + public var multipleRequestScreenEnabled: Bool { + get { self[MultipleRequestScreenEnabledSettingsKey.self] } + set { self[MultipleRequestScreenEnabledSettingsKey.self] = newValue } + } + +} + +struct MultipleRequestScreenCountThresholdSettingsKey: SettingsStore.SettingsKey { + static let defaultValue: Int = 2 +} + +extension SettingsStore { + + public var multipleRequestScreenCountThreshold: Int { + get { self[MultipleRequestScreenCountThresholdSettingsKey.self] } + set { self[MultipleRequestScreenCountThresholdSettingsKey.self] = newValue } + } + +} + +struct ShowDockItemWithPendingRequestsScreenSettingsKey: SettingsStore.SettingsKey { + static let defaultValue: Bool = true +} + +extension SettingsStore { + + public var showDockItemWithPendingRequestsScreen: Bool { + get { self[ShowDockItemWithPendingRequestsScreenSettingsKey.self] } + set { self[ShowDockItemWithPendingRequestsScreenSettingsKey.self] = newValue } + } + +} + diff --git a/Sources/Packages/Tests/SecretAgentKitTests/AgentTests.swift b/Sources/Packages/Tests/SecretAgentKitTests/AgentTests.swift index b3a56f1..6e98873 100644 --- a/Sources/Packages/Tests/SecretAgentKitTests/AgentTests.swift +++ b/Sources/Packages/Tests/SecretAgentKitTests/AgentTests.swift @@ -11,7 +11,7 @@ import CertificateKit // MARK: Identity Listing @Test func emptyStores() async throws { - let agent = Agent(storeList: SecretStoreList(), certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler()) + let agent = Agent(storeList: SecretStoreList(), certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(settingsStore: .init())) let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestIdentities) let response = await agent.handle(request: request, provenance: .test, hosts: nil) #expect(response == Constants.Responses.requestIdentitiesEmpty) @@ -19,7 +19,7 @@ import CertificateKit @Test func identitiesList() async throws { let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) - let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler()) + let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(settingsStore: .init())) let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestIdentities) let response = await agent.handle(request: request, provenance: .test, hosts: nil) @@ -33,7 +33,7 @@ import CertificateKit @Test func noMatchingIdentities() async throws { let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) - let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler()) + let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(settingsStore: .init())) let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignatureWithNoneMatching) let response = await agent.handle(request: request, provenance: .test, hosts: nil) #expect(response == Constants.Responses.requestFailure) @@ -43,7 +43,7 @@ import CertificateKit let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature) guard case SSHAgent.Request.signRequest(let context) = request else { return } let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) - let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler()) + let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(settingsStore: .init())) let response = await agent.handle(request: request, provenance: .test, hosts: nil) let responseReader = OpenSSHReader(data: response) let length = try responseReader.readNextBytes(as: UInt32.self) @@ -78,7 +78,7 @@ import CertificateKit let witness = StubWitness(speakNow: { _,_ in return true }, witness: { _, _ in }) - let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(), witness: witness) + let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(settingsStore: .init()), witness: witness) let response = await agent.handle(request: .signRequest(.empty), provenance: .test, hosts: nil) #expect(response == Constants.Responses.requestFailure) } @@ -91,7 +91,7 @@ import CertificateKit }, witness: { _, trace in witnessed = true }) - let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(), witness: witness) + let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(settingsStore: .init()), witness: witness) let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature) _ = await agent.handle(request: request, provenance: .test, hosts: nil) #expect(witnessed) @@ -107,7 +107,7 @@ import CertificateKit }, witness: { _, trace in witnessTrace = trace }) - let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(), witness: witness) + let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(settingsStore: .init()), witness: witness) let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature) _ = await agent.handle(request: request, provenance: .test, hosts: nil) #expect(witnessTrace == speakNowTrace) @@ -120,7 +120,7 @@ import CertificateKit let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) let store = list.stores.first?.base as! Stub.Store store.shouldThrow = true - let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler()) + let agent = Agent(storeList: list, certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(settingsStore: .init())) let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature) let response = await agent.handle(request: request, provenance: .test, hosts: nil) #expect(response == Constants.Responses.requestFailure) @@ -129,7 +129,7 @@ import CertificateKit // MARK: Unsupported @Test func unhandledAdd() async throws { - let agent = Agent(storeList: SecretStoreList(), certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler()) + let agent = Agent(storeList: SecretStoreList(), certificateStore: CertificateStore(), authenticationHandler: AuthenticationHandler(settingsStore: .init())) let response = await agent.handle(request: .addIdentity, provenance: .test, hosts: nil) #expect(response == Constants.Responses.requestFailure) } diff --git a/Sources/Packages/Tests/SecretAgentKitTests/AuthenticationHandlerTests.swift b/Sources/Packages/Tests/SecretAgentKitTests/AuthenticationHandlerTests.swift index 5d177e7..f79a082 100644 --- a/Sources/Packages/Tests/SecretAgentKitTests/AuthenticationHandlerTests.swift +++ b/Sources/Packages/Tests/SecretAgentKitTests/AuthenticationHandlerTests.swift @@ -67,7 +67,7 @@ public struct TestSecret: Secret { @MainActor @Suite struct AuthenticationHandlerTests { - let handler = AuthenticationHandler() + let handler = AuthenticationHandler(settingsStore: .init()) @Test func singleImmediatelyRequests() async throws { var calledPresentPending = false diff --git a/Sources/SecretAgent/App.swift b/Sources/SecretAgent/App.swift index 43c45e8..6f4cdcb 100644 --- a/Sources/SecretAgent/App.swift +++ b/Sources/SecretAgent/App.swift @@ -9,6 +9,7 @@ import Observation import Common import SwiftUI import CertificateKit +import SettingsKit @main struct SecretAgent: App { @@ -26,7 +27,7 @@ struct SecretAgent: App { private let updater = Updater(checkOnLaunch: true) private let notifier = Notifier() - private let authenticationHandler = AuthenticationHandler() + private let authenticationHandler = AuthenticationHandler(settingsStore: EnvironmentValues._settingsStore) private let publicKeyFileStoreController = PublicKeyFileStoreController(publicKeysURL: URL.publicKeyDirectory, certificatesURL: URL.certificatesDirectory) @Environment(\.openWindow) var openWindow @@ -117,3 +118,12 @@ struct SecretAgent: App { } struct PendingRequestsViewIdentifier: Codable, Hashable {} + +extension EnvironmentValues { + + @MainActor fileprivate static let _settingsStore = SettingsStore() + @MainActor var settingsStore: SettingsStore { + EnvironmentValues._settingsStore + } + +} diff --git a/Sources/SecretAgent/PendingRequestsView.swift b/Sources/SecretAgent/PendingRequestsView.swift index ce13a91..0f2bfa7 100644 --- a/Sources/SecretAgent/PendingRequestsView.swift +++ b/Sources/SecretAgent/PendingRequestsView.swift @@ -3,11 +3,14 @@ import SecretKit import SecretAgentKit import SmartCardSecretKit import Common +import ApplicationServices +import SettingsKit struct PendingRequestsView: View { private let authenticationHandler: any AuthenticationHandlerProtocol @Environment(\.dismissWindow) var dismiss + @Environment(\.settingsStore) var settingsStore init(authenticationHandler: some AuthenticationHandlerProtocol) { self.authenticationHandler = authenticationHandler @@ -92,6 +95,19 @@ struct PendingRequestsView: View { } } .safeAreaPadding(20) + .onAppear { + guard settingsStore.showDockItemWithPendingRequestsScreen else { return } + var process = ProcessSerialNumber(highLongOfPSN: 0, lowLongOfPSN: UInt32(kCurrentProcess)) + unsafe TransformProcessType(&process, ProcessApplicationTransformState(kProcessTransformToForegroundApplication)) + NSApplication.shared.dockTile.showsApplicationBadge = true + NSApplication.shared.dockTile.display() + NSApplication.shared.requestUserAttention(.criticalRequest) + } + .onDisappear { + guard settingsStore.showDockItemWithPendingRequestsScreen else { return } + var process = ProcessSerialNumber(highLongOfPSN: 0, lowLongOfPSN: UInt32(kCurrentProcess)) + unsafe TransformProcessType(&process, ProcessApplicationTransformState(kProcessTransformToBackgroundApplication)) + } } } diff --git a/Sources/Secretive.xcodeproj/project.xcproj b/Sources/Secretive.xcodeproj/project.xcproj index deaecc2..d247048 100644 --- a/Sources/Secretive.xcodeproj/project.xcproj +++ b/Sources/Secretive.xcodeproj/project.xcproj @@ -377,6 +377,9 @@ }, { "product-name": "SecureEnclaveSecretKit", "build-phase": { "build-phase": "frameworks" }, + }, { + "product-name": "SettingsKit", + "build-phase": { "build-phase": "frameworks" }, }, { "product-name": "SharedXPCServices", "build-phase": { "build-phase": "frameworks" }, diff --git a/Sources/Secretive/Views/Secrets/SettingsView.swift b/Sources/Secretive/Views/Secrets/SettingsView.swift index bc2b418..e43984e 100644 --- a/Sources/Secretive/Views/Secrets/SettingsView.swift +++ b/Sources/Secretive/Views/Secrets/SettingsView.swift @@ -3,12 +3,50 @@ import SettingsKit struct SettingsView: View { + enum TabID { + case general + case agent + } + @Environment(\.settingsStore) var settingsStore + @State var selection: TabID = .agent var body: some View { - Form { + @Bindable var settingsStore = settingsStore + NavigationSplitView { + List(selection: $selection) { + NavigationLink(.settingsAgentTabTitle, value: TabID.agent) + } + .toolbar(removing: .sidebarToggle) + } detail: { + switch selection { + case .general: + // Placeholder + EmptyView() + case .agent: + Form { + Section(.settingsMultipleAuthenticationSectionTitle) { + Toggle(isOn: $settingsStore.multipleRequestScreenEnabled) { + Text(.settingsMultipleAuthenticationEnabledLabel) + } + Group { + Toggle(isOn: $settingsStore.showDockItemWithPendingRequestsScreen) { + Text(.settingsMultipleAuthenticationShowsDockIconLabel) + } + // Value binding here is a hack to get around annoying Stepper behavior where it + // won't draw the number of any non-floating point value (ie, ints) + Stepper(.settingsMultipleAuthenticationThresholdLabel, value: .init(get: { + Double(settingsStore.multipleRequestScreenCountThreshold) + }, set: { newValue in + settingsStore.multipleRequestScreenCountThreshold = Int(newValue) + }), in: 2...100, format: .number) + } + .disabled(!settingsStore.multipleRequestScreenEnabled) + } + } + } } - .padding() + .formStyle(.grouped) .frame(minWidth: 480, minHeight: 320) } }