Add settings for batch auth handling. (#870)

This commit is contained in:
Max Goedjen authored and GitHub committed 2026-11-17 07:15:56 +00:00
1 parent 164aacc94e
commit 56c2f841ed
10 files changed
+191 -20

No files matched your search

+1 -1
View File
@@ -87,7 +87,7 @@ let package = Package(
), ),
.target( .target(
name: "SecretAgentKit", name: "SecretAgentKit",
dependencies: ["SecretKit", "SSHProtocolKit", "CertificateKit", "Common", "Formatters"], dependencies: ["SecretKit", "SSHProtocolKit", "CertificateKit", "Common", "Formatters", "SettingsKit"],
resources: [localization], resources: [localization],
swiftSettings: swiftSettings, swiftSettings: swiftSettings,
), ),
@@ -22015,6 +22015,61 @@
}, },
"shouldTranslate" : false "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" : { "setup_agent_activity_monitor_description" : {
"extractionState" : "manual", "extractionState" : "manual",
"localizations" : { "localizations" : {
@@ -1,6 +1,7 @@
@unsafe @preconcurrency import LocalAuthentication @unsafe @preconcurrency import LocalAuthentication
import SecretKit import SecretKit
import OSLog import OSLog
import SettingsKit
/// A context describing a persisted authentication. /// A context describing a persisted authentication.
public final class AuthenticationContext: AuthenticationContextProtocol { public final class AuthenticationContext: AuthenticationContextProtocol {
@@ -103,8 +104,10 @@ public final class AuthenticationContext: AuthenticationContextProtocol {
private var lastBatchAuthPresentation: Set<SignatureRequest>? private var lastBatchAuthPresentation: Set<SignatureRequest>?
private var presentPendingAuth: (() async throws -> Void)? private var presentPendingAuth: (() async throws -> Void)?
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "AuthenticationHandler") 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) { public func setPendingRequestHandler(_ handler: @escaping () async throws -> Void) {
@@ -134,11 +137,15 @@ public final class AuthenticationContext: AuthenticationContextProtocol {
waitingRequests.remove(request) waitingRequests.remove(request)
} }
if waitingRequests.count > 1 { if settingsStore.multipleRequestScreenEnabled && waitingRequests.count >= settingsStore.multipleRequestScreenCountThreshold {
return try await waitUntilRequestActedOn(request) 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 activeContext = context
let currentTask = Task<Bool, any Error> { let currentTask = Task<Bool, any Error> {
logger.log("Beginning individual auth prompt") logger.log("Beginning individual auth prompt")
@@ -147,8 +154,10 @@ public final class AuthenticationContext: AuthenticationContextProtocol {
return result return result
} }
activeTask = currentTask activeTask = currentTask
let result = try? await activeTask?.value let result = try await currentTask.value
if result == false && activeTask?.isCancelled == false { activeTask = nil
activeContext = nil
if result == false && currentTask.isCancelled == false {
waitingRequests.remove(request) waitingRequests.remove(request)
throw CancellationError() throw CancellationError()
} else if currentTask.isCancelled { } else if currentTask.isCancelled {
@@ -161,7 +170,7 @@ public final class AuthenticationContext: AuthenticationContextProtocol {
logger.log("Auth prompt was cancelled, waiting for explicit auth") 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. // 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) { 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. // 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") logger.log("Multiple pending requests exist, cancelling existing auth prompt")
activeTask?.cancel() activeTask?.cancel()
@@ -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 }
}
}
@@ -11,7 +11,7 @@ import CertificateKit
// MARK: Identity Listing // MARK: Identity Listing
@Test func emptyStores() async throws { @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 request = try SSHAgentInputParser().parse(data: Constants.Requests.requestIdentities)
let response = await agent.handle(request: request, provenance: .test, hosts: nil) let response = await agent.handle(request: request, provenance: .test, hosts: nil)
#expect(response == Constants.Responses.requestIdentitiesEmpty) #expect(response == Constants.Responses.requestIdentitiesEmpty)
@@ -19,7 +19,7 @@ import CertificateKit
@Test func identitiesList() async throws { @Test func identitiesList() async throws {
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) 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 request = try SSHAgentInputParser().parse(data: Constants.Requests.requestIdentities)
let response = await agent.handle(request: request, provenance: .test, hosts: nil) let response = await agent.handle(request: request, provenance: .test, hosts: nil)
@@ -33,7 +33,7 @@ import CertificateKit
@Test func noMatchingIdentities() async throws { @Test func noMatchingIdentities() async throws {
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) 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 request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignatureWithNoneMatching)
let response = await agent.handle(request: request, provenance: .test, hosts: nil) let response = await agent.handle(request: request, provenance: .test, hosts: nil)
#expect(response == Constants.Responses.requestFailure) #expect(response == Constants.Responses.requestFailure)
@@ -43,7 +43,7 @@ import CertificateKit
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature) let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
guard case SSHAgent.Request.signRequest(let context) = request else { return } guard case SSHAgent.Request.signRequest(let context) = request else { return }
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) 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 response = await agent.handle(request: request, provenance: .test, hosts: nil)
let responseReader = OpenSSHReader(data: response) let responseReader = OpenSSHReader(data: response)
let length = try responseReader.readNextBytes(as: UInt32.self) let length = try responseReader.readNextBytes(as: UInt32.self)
@@ -78,7 +78,7 @@ import CertificateKit
let witness = StubWitness(speakNow: { _,_ in let witness = StubWitness(speakNow: { _,_ in
return true return true
}, witness: { _, _ in }) }, 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) let response = await agent.handle(request: .signRequest(.empty), provenance: .test, hosts: nil)
#expect(response == Constants.Responses.requestFailure) #expect(response == Constants.Responses.requestFailure)
} }
@@ -91,7 +91,7 @@ import CertificateKit
}, witness: { _, trace in }, witness: { _, trace in
witnessed = true 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) let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
_ = await agent.handle(request: request, provenance: .test, hosts: nil) _ = await agent.handle(request: request, provenance: .test, hosts: nil)
#expect(witnessed) #expect(witnessed)
@@ -107,7 +107,7 @@ import CertificateKit
}, witness: { _, trace in }, witness: { _, trace in
witnessTrace = trace 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) let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
_ = await agent.handle(request: request, provenance: .test, hosts: nil) _ = await agent.handle(request: request, provenance: .test, hosts: nil)
#expect(witnessTrace == speakNowTrace) #expect(witnessTrace == speakNowTrace)
@@ -120,7 +120,7 @@ import CertificateKit
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
let store = list.stores.first?.base as! Stub.Store let store = list.stores.first?.base as! Stub.Store
store.shouldThrow = true 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 request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
let response = await agent.handle(request: request, provenance: .test, hosts: nil) let response = await agent.handle(request: request, provenance: .test, hosts: nil)
#expect(response == Constants.Responses.requestFailure) #expect(response == Constants.Responses.requestFailure)
@@ -129,7 +129,7 @@ import CertificateKit
// MARK: Unsupported // MARK: Unsupported
@Test func unhandledAdd() async throws { @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) let response = await agent.handle(request: .addIdentity, provenance: .test, hosts: nil)
#expect(response == Constants.Responses.requestFailure) #expect(response == Constants.Responses.requestFailure)
} }
@@ -67,7 +67,7 @@ public struct TestSecret: Secret {
@MainActor @Suite struct AuthenticationHandlerTests { @MainActor @Suite struct AuthenticationHandlerTests {
let handler = AuthenticationHandler() let handler = AuthenticationHandler(settingsStore: .init())
@Test func singleImmediatelyRequests() async throws { @Test func singleImmediatelyRequests() async throws {
var calledPresentPending = false var calledPresentPending = false
+11 -1
View File
@@ -9,6 +9,7 @@ import Observation
import Common import Common
import SwiftUI import SwiftUI
import CertificateKit import CertificateKit
import SettingsKit
@main @main
struct SecretAgent: App { struct SecretAgent: App {
@@ -26,7 +27,7 @@ struct SecretAgent: App {
private let updater = Updater(checkOnLaunch: true) private let updater = Updater(checkOnLaunch: true)
private let notifier = Notifier() 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) private let publicKeyFileStoreController = PublicKeyFileStoreController(publicKeysURL: URL.publicKeyDirectory, certificatesURL: URL.certificatesDirectory)
@Environment(\.openWindow) var openWindow @Environment(\.openWindow) var openWindow
@@ -117,3 +118,12 @@ struct SecretAgent: App {
} }
struct PendingRequestsViewIdentifier: Codable, Hashable {} struct PendingRequestsViewIdentifier: Codable, Hashable {}
extension EnvironmentValues {
@MainActor fileprivate static let _settingsStore = SettingsStore()
@MainActor var settingsStore: SettingsStore {
EnvironmentValues._settingsStore
}
}
@@ -3,11 +3,14 @@ import SecretKit
import SecretAgentKit import SecretAgentKit
import SmartCardSecretKit import SmartCardSecretKit
import Common import Common
import ApplicationServices
import SettingsKit
struct PendingRequestsView: View { struct PendingRequestsView: View {
private let authenticationHandler: any AuthenticationHandlerProtocol private let authenticationHandler: any AuthenticationHandlerProtocol
@Environment(\.dismissWindow) var dismiss @Environment(\.dismissWindow) var dismiss
@Environment(\.settingsStore) var settingsStore
init(authenticationHandler: some AuthenticationHandlerProtocol) { init(authenticationHandler: some AuthenticationHandlerProtocol) {
self.authenticationHandler = authenticationHandler self.authenticationHandler = authenticationHandler
@@ -92,6 +95,19 @@ struct PendingRequestsView: View {
} }
} }
.safeAreaPadding(20) .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))
}
} }
} }
@@ -377,6 +377,9 @@
}, { }, {
"product-name": "SecureEnclaveSecretKit", "product-name": "SecureEnclaveSecretKit",
"build-phase": { "build-phase": "frameworks" }, "build-phase": { "build-phase": "frameworks" },
}, {
"product-name": "SettingsKit",
"build-phase": { "build-phase": "frameworks" },
}, { }, {
"product-name": "SharedXPCServices", "product-name": "SharedXPCServices",
"build-phase": { "build-phase": "frameworks" }, "build-phase": { "build-phase": "frameworks" },
@@ -3,12 +3,50 @@ import SettingsKit
struct SettingsView: View { struct SettingsView: View {
enum TabID {
case general
case agent
}
@Environment(\.settingsStore) var settingsStore @Environment(\.settingsStore) var settingsStore
@State var selection: TabID = .agent
var body: some View { 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) .frame(minWidth: 480, minHeight: 320)
} }
} }