diff --git a/App/CompositionRoot.swift b/App/CompositionRoot.swift index 3bf844a..9e96454 100644 --- a/App/CompositionRoot.swift +++ b/App/CompositionRoot.swift @@ -209,7 +209,8 @@ final class CompositionRoot { } /// Confirms when live sessions exist, then persists the workspace before - /// AppKit finishes quitting. + /// AppKit finishes quitting. If the workspace can't be saved, the user + /// chooses between quitting without it and staying. func prepareForTermination() -> NSApplication.TerminateReply { guard let sessions else { return .terminateNow } if sessions.needsQuitConfirmation { @@ -222,12 +223,30 @@ final class CompositionRoot { } sessions.disconnectAllForTermination() Task { - try? await sessions.persistWorkspace() - NSApplication.shared.reply(toApplicationShouldTerminate: true) + do { + try await sessions.persistWorkspace() + NSApplication.shared.reply(toApplicationShouldTerminate: true) + } catch { + NSApplication.shared.reply(toApplicationShouldTerminate: Self.quitWithoutWorkspace(error)) + } } return .terminateLater } + private static func quitWithoutWorkspace(_ error: any Error) -> Bool { + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = "Couldn’t save your open tabs" + alert.informativeText = """ + If you quit now, these tabs won’t reopen next time. + + \(error.localizedDescription) + """ + alert.addButton(withTitle: "Quit Anyway") + alert.addButton(withTitle: "Cancel") + return alert.runModal() == .alertFirstButtonReturn + } + /// `~/Library/Application Support/Constellation/library.sqlite`, or /// `CONSTELLATION_LIBRARY_PATH` for development runs. static func libraryPath() -> String { diff --git a/App/MachineStore.swift b/App/MachineStore.swift index 436ab35..4341aa1 100644 --- a/App/MachineStore.swift +++ b/App/MachineStore.swift @@ -44,8 +44,11 @@ final class MachineStore { } } - /// Saves an editor draft: library change first, then vault writes, so a - /// rejected draft leaves no stray Keychain items. + /// Saves an editor draft. Secrets are written before the library refers to + /// them, and put back as they were if the vault or the library fails, so a + /// profile is never saved without the password it was given and a rejected + /// draft leaves no stray Keychain items. Secrets the draft dropped are + /// removed only once the library no longer refers to them. func save(_ draft: MachineDraft) async -> Bool { let change: MachineLibraryChange do { @@ -54,21 +57,69 @@ final class MachineStore { presentedError = error.localizedDescription return false } - guard await save(change) else { return false } + var replaced: [(id: CredentialID, previous: Secret?)] = [] do { for pending in draft.pendingSecrets { + let previous = try existingSecret(pending.credentialID) try vault.store(pending.secret, for: pending.credentialID) - } - for id in draft.removedCredentialIDs where snapshot.credential(id) == nil { - try vault.remove(id: id) + replaced.append((pending.credentialID, previous)) } } catch { - presentedError = error.localizedDescription + presentedError = error.localizedDescription + restoreNote(restore(replaced)) return false } + let before = snapshot + guard await save(change) else { + presentedError = (presentedError ?? "") + restoreNote(restore(replaced)) + return false + } + var kept: [CredentialReference] = [] + var failure: (any Error)? + for id in draft.removedCredentialIDs where snapshot.credential(id) == nil { + do { + try vault.remove(id: id) + } catch { + failure = failure ?? error + if let reference = before.credential(id) { kept.append(reference) } + } + } + if let failure { + // Restoring the reference leaves it orphaned, so it is offered for + // removal again rather than lingering unseen in the Keychain. + if !kept.isEmpty { await save(.batch(kept.map { .upsertCredential($0) })) } + presentedError = "The machine was saved, but a password it no longer uses couldn’t be removed from the Keychain. \(failure.localizedDescription)" + } return true } + /// `nil` when the vault has nothing for `id`; any other failure throws so a + /// rollback never deletes a secret it could not read. + private func existingSecret(_ id: CredentialID) throws -> Secret? { + do { + return try vault.retrieve(id: id) + } catch CredentialVaultError.notFound { + return nil + } + } + + /// Puts back what `save(_ draft:)` replaced, newest first. Returns whether + /// every secret was restored. + private func restore(_ replaced: [(id: CredentialID, previous: Secret?)]) -> Bool { + var restored = true + for (id, previous) in replaced.reversed() { + do { + if let previous { try vault.store(previous, for: id) } else { try vault.remove(id: id) } + } catch { + restored = false + } + } + return restored + } + + private func restoreNote(_ restored: Bool) -> String { + restored ? "" : " The Keychain could not be returned to its previous state; re-enter the passwords for this machine." + } + /// Deletes the machine and returns credentials that no remaining profile /// uses, so the caller can confirm removing them from the Keychain. func deleteMachine(_ id: MachineID) async -> [CredentialReference] { @@ -76,10 +127,25 @@ final class MachineStore { return snapshot.orphanedCredentials } + /// Removes secrets from the vault first and drops the library's reference + /// only to those that are gone, so one the Keychain refused stays orphaned + /// and is offered for removal again. func removeCredentials(_ credentials: [CredentialReference]) async { - guard await save(.batch(credentials.map { .deleteCredential($0.id) })) else { return } + var removed: [CredentialID] = [] + var failure: (any Error)? for credential in credentials { - try? vault.remove(id: credential.id) + do { + try vault.remove(id: credential.id) + removed.append(credential.id) + } catch { + failure = failure ?? error + } + } + if !removed.isEmpty { + guard await save(.batch(removed.map { .deleteCredential($0) })) else { return } + } + if let failure { + presentedError = "Some passwords couldn’t be removed from the Keychain. \(failure.localizedDescription)" } } diff --git a/App/Sessions/RDPSessionDriver.swift b/App/Sessions/RDPSessionDriver.swift index 0108512..3418c25 100644 --- a/App/Sessions/RDPSessionDriver.swift +++ b/App/Sessions/RDPSessionDriver.swift @@ -39,6 +39,7 @@ final class FreeRDPSessionDriver: RDPSessionDriving { private let scrollSpeed: @MainActor () -> Double private let credentialPrompt: @MainActor (RDPCredentialPrompt) -> RDPCredentialEntry? private let certificatePrompt: @MainActor (RDPCertificate, String, Bool) -> RDPTrustDecision + private let trustNotSaved: @MainActor (RDPCertificate, String, any Error) -> Void private let entraSignInPrompt: @MainActor @Sendable (RDPEntraSignInRequest, String) async -> String? init( @@ -48,6 +49,7 @@ final class FreeRDPSessionDriver: RDPSessionDriving { scrollSpeed: @escaping @MainActor () -> Double = { 1 }, credentialPrompt: @escaping @MainActor (RDPCredentialPrompt) -> RDPCredentialEntry? = RDPCredentialPrompter.ask, certificatePrompt: @escaping @MainActor (RDPCertificate, String, Bool) -> RDPTrustDecision = RDPCertificatePrompter.ask, + trustNotSaved: @escaping @MainActor (RDPCertificate, String, any Error) -> Void = RDPCertificatePrompter.reportTrustNotSaved, entraSignInPrompt: @escaping @MainActor @Sendable (RDPEntraSignInRequest, String) async -> String? = RDPEntraSignInPrompter.ask ) { self.vault = vault @@ -56,6 +58,7 @@ final class FreeRDPSessionDriver: RDPSessionDriving { self.scrollSpeed = scrollSpeed self.credentialPrompt = credentialPrompt self.certificatePrompt = certificatePrompt + self.trustNotSaved = trustNotSaved self.entraSignInPrompt = entraSignInPrompt } @@ -99,6 +102,7 @@ final class FreeRDPSessionDriver: RDPSessionDriving { connectionQuality: settings.connectionQuality, gateway: gateway) let certificatePrompt = self.certificatePrompt + let trustNotSaved = self.trustNotSaved let trustStore = self.trustStore let machineName = request.machineName let entraSignInPrompt = self.entraSignInPrompt @@ -108,7 +112,9 @@ final class FreeRDPSessionDriver: RDPSessionDriving { password: { password }, gatewayPassword: { [gatewayPassword] in gatewayPassword }, verifyCertificate: { certificate in - await resolveCertificate(certificate, machineName: machineName, trustStore: trustStore, prompt: certificatePrompt) + await resolveCertificate( + certificate, machineName: machineName, trustStore: trustStore, + prompt: certificatePrompt, trustNotSaved: trustNotSaved) }, entraSignIn: { request in await entraSignInPrompt(request, machineName) }, // Only a desktop that refuses its Entra ID sign-in gets here; the @@ -196,13 +202,15 @@ private extension RDPAzureDesktopSignIn { /// fingerprint the store already trusts connects silently; anything else /// prompts, and "Always Trust" records the decision for next time. Returning /// `.acceptOnce` to FreeRDP for every accept keeps the store the single source -/// of trust rather than FreeRDP's own known-hosts file. +/// of trust rather than FreeRDP's own known-hosts file. If "Always Trust" +/// cannot be saved, the user is told and this connection still goes ahead. @MainActor func resolveCertificate( _ certificate: RDPCertificate, machineName: String, trustStore: any TrustStore, - prompt: @MainActor (RDPCertificate, String, Bool) -> RDPTrustDecision + prompt: @MainActor (RDPCertificate, String, Bool) -> RDPTrustDecision, + trustNotSaved: @MainActor (RDPCertificate, String, any Error) -> Void ) async -> RDPCertificateVerdict { let stored = try? await trustStore.trusted(host: certificate.host, port: certificate.port) if let stored, stored.matches(fingerprint: certificate.fingerprint) { @@ -217,14 +225,18 @@ func resolveCertificate( case .connectOnce: return .acceptOnce case .trustAlways: - try? await trustStore.trust(TrustedCertificate( - host: certificate.host, - port: certificate.port, - fingerprint: certificate.fingerprint, - subject: certificate.subject, - issuer: certificate.issuer, - commonName: certificate.commonName, - trustedAt: Date())) + do { + try await trustStore.trust(TrustedCertificate( + host: certificate.host, + port: certificate.port, + fingerprint: certificate.fingerprint, + subject: certificate.subject, + issuer: certificate.issuer, + commonName: certificate.commonName, + trustedAt: Date())) + } catch { + trustNotSaved(certificate, machineName, error) + } return .acceptOnce } } @@ -359,4 +371,17 @@ enum RDPCertificatePrompter { default: return .reject } } + + static func reportTrustNotSaved(_ certificate: RDPCertificate, machineName: String, error: any Error) { + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = "Couldn’t save the certificate for \(machineName)" + alert.informativeText = """ + This connection will continue, but you will be asked to verify the certificate again next time. + + \(error.localizedDescription) + """ + alert.addButton(withTitle: "OK") + alert.runModal() + } } diff --git a/PRIVACY.md b/PRIVACY.md index 92d4241..fe1165f 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -14,7 +14,12 @@ machines you configure. It is made by Wolff.Tech. `~/Library/Application Support/Constellation/trust.sqlite`. - Saved passwords and passphrases in the macOS login Keychain, as items labelled "Constellation credential". -- Terminal appearance settings and window state in the app's preferences. +- Terminal appearance settings, window state and update settings in the + app's preferences. +- Microsoft sign-in cookies, if you use Azure Virtual Desktop, in the app's + web data (`~/Library/WebKit/tech.wolff.Constellation` and + `~/Library/HTTPStorages/tech.wolff.Constellation`). They keep you signed in + to Microsoft Entra ID so the next connection need not ask again. SSH host keys are handled by the system's OpenSSH and stored in `~/.ssh/known_hosts`, as with any ssh client. If you turn on "Use my Ghostty @@ -24,10 +29,24 @@ and does not write to them. ## What leaves your Mac -Only the connections you start: SSH, VNC and RDP traffic to the hosts you -configure, and clipboard text for RDP profiles where you turned sharing on. -Constellation has no accounts, no analytics, no telemetry, no crash -reporting and no update checks, and contacts no server of its own. +- The connections you start: SSH, VNC and RDP traffic to the hosts you + configure, and clipboard text for RDP profiles where you turned sharing on. +- Update checks. Constellation uses Sparkle to fetch its update feed and + update downloads from the project's GitHub releases. After asking once, it + checks automatically unless you turn that off in Settings; you can also + check from the app menu. GitHub sees your IP address and the app version + in the request. No other system information is sent. +- Azure Virtual Desktop sign-in, only when you add or connect to an Azure + Virtual Desktop. The sign-in page is Microsoft's own + (`login.microsoftonline.com`, or `login.microsoftonline.us` for Azure US + Government), shown in a window inside the app, and what you enter there + goes to Microsoft. Constellation then asks Azure Virtual Desktop + (`rdweb.wvd.microsoft.com` or `rdweb.wvd.azure.us`) for your assigned + desktops and their connection details, and connects through its gateway. + Access tokens are kept in memory only. + +Constellation has no accounts, no analytics, no telemetry and no crash +reporting, and contacts no server of its own. ## Support bundles @@ -42,7 +61,10 @@ unless you send it. ## Removing your data Delete the app, the `~/Library/Application Support/Constellation` folder, -the `tech.wolff.Constellation` preferences, and the "Constellation +the `tech.wolff.Constellation` preferences, the +`~/Library/WebKit/tech.wolff.Constellation`, +`~/Library/HTTPStorages/tech.wolff.Constellation` and +`~/Library/Caches/tech.wolff.Constellation` folders, and the "Constellation credential" items in Keychain Access. ## Contact diff --git a/Packages/ConstellationTerminal/Sources/ConstellationTerminal/GhosttyConfig.swift b/Packages/ConstellationTerminal/Sources/ConstellationTerminal/GhosttyConfig.swift index 8911fe1..d3c9ffe 100644 --- a/Packages/ConstellationTerminal/Sources/ConstellationTerminal/GhosttyConfig.swift +++ b/Packages/ConstellationTerminal/Sources/ConstellationTerminal/GhosttyConfig.swift @@ -47,10 +47,18 @@ final class GhosttyConfig { } self.diagnostics = diagnostics for message in diagnostics { - Log.terminal.warning("ghostty config diagnostic: \(message, privacy: .public)") + Log.terminal.warning("ghostty config diagnostic: \(Self.redactingHome(message), privacy: .public)") } } + /// Diagnostics name config file paths, and support bundles copy this log, + /// so the home directory (and with it the macOS account name) becomes `~`. + /// Settings still show the full message. + nonisolated static func redactingHome(_ message: String, home: String = NSHomeDirectory()) -> String { + guard !home.isEmpty else { return message } + return message.replacingOccurrences(of: home, with: "~") + } + deinit { ghostty_config_free(handle) } diff --git a/Packages/ConstellationTerminal/Tests/ConstellationTerminalTests/GhosttyConfigTests.swift b/Packages/ConstellationTerminal/Tests/ConstellationTerminalTests/GhosttyConfigTests.swift index a9e656b..a417cf0 100644 --- a/Packages/ConstellationTerminal/Tests/ConstellationTerminalTests/GhosttyConfigTests.swift +++ b/Packages/ConstellationTerminal/Tests/ConstellationTerminalTests/GhosttyConfigTests.swift @@ -43,6 +43,11 @@ struct GhosttyConfigTests { #expect(appConfig.diagnostics.isEmpty) } + @Test func loggedDiagnosticsHideTheHomeDirectory() { + let message = "/Users/nick/.config/ghostty/config:3: unknown field" + #expect(GhosttyConfig.redactingHome(message, home: "/Users/nick") == "~/.config/ghostty/config:3: unknown field") + } + private func fontSize(of config: GhosttyConfig) -> Float? { var value: Float = 0 let key = "font-size" diff --git a/Tests/App/MachineStoreTests.swift b/Tests/App/MachineStoreTests.swift index f99342d..d555cc3 100644 --- a/Tests/App/MachineStoreTests.swift +++ b/Tests/App/MachineStoreTests.swift @@ -55,4 +55,119 @@ struct MachineStoreTests { #expect(store.snapshot == .empty) #expect(draft.pendingSecrets.allSatisfy { !vault.contains(id: $0.credentialID) }) } + + @Test func keychainFailureLeavesTheLibraryUntouched() async throws { + let vault = ScriptedVault() + vault.failsStore = true + let store = MachineStore(library: try GRDBMachineLibrary.inMemory(), vault: vault) + #expect(await store.save(passwordDraft("maymaymay")) == false) + #expect(store.presentedError != nil) + #expect(store.snapshot == .empty) + } + + @Test func rejectedLibraryChangeRestoresTheOldPassword() async throws { + let vault = ScriptedVault() + let library = ScriptedLibrary(try GRDBMachineLibrary.inMemory()) + let store = MachineStore(library: library, vault: vault) + #expect(await store.save(passwordDraft("old"))) + let machine = try #require(store.snapshot.machines.first) + let credentialID = try #require(store.snapshot.profiles(for: machine.id).first?.credentialID) + + var edit = MachineDraft(editing: machine, in: store.snapshot) + edit.profiles[0].enteredSecret = "new" + library.failsSave = true + #expect(await store.save(edit) == false) + #expect(try vault.retrieve(id: credentialID).withValue { $0 } == "old") + + // A new profile's secret is removed instead. + var draft = passwordDraft("fresh") + let freshID = try #require(draft.pendingSecrets.first?.credentialID) + #expect(await store.save(draft) == false) + #expect(!vault.contains(id: freshID)) + } + + @Test func refusedKeychainRemovalKeepsTheCredentialOffered() async throws { + let vault = ScriptedVault() + let store = MachineStore(library: try GRDBMachineLibrary.inMemory(), vault: vault) + #expect(await store.save(passwordDraft("maymaymay"))) + let machine = try #require(store.snapshot.machines.first) + let orphans = await store.deleteMachine(machine.id) + let credentialID = try #require(orphans.first?.id) + + vault.failsRemove = true + await store.removeCredentials(orphans) + #expect(store.presentedError != nil) + #expect(vault.contains(id: credentialID)) + #expect(store.snapshot.orphanedCredentials.map(\.id) == [credentialID]) + + vault.failsRemove = false + store.presentedError = nil + await store.removeCredentials(store.snapshot.orphanedCredentials) + #expect(store.presentedError == nil) + #expect(!vault.contains(id: credentialID)) + #expect(store.snapshot.credentials.isEmpty) + } + + @Test func refusedRemovalOfADroppedPasswordKeepsItOrphaned() async throws { + let vault = ScriptedVault() + let store = MachineStore(library: try GRDBMachineLibrary.inMemory(), vault: vault) + var draft = passwordDraft("maymaymay") + draft.addVNCProfile() + #expect(await store.save(draft)) + let machine = try #require(store.snapshot.machines.first) + let credentialID = try #require(draft.pendingSecrets.first?.credentialID) + + var edit = MachineDraft(editing: machine, in: store.snapshot) + edit.removeProfile(edit.profiles[0].id) + vault.failsRemove = true + #expect(await store.save(edit), "the library change itself succeeded") + #expect(store.presentedError != nil) + #expect(store.snapshot.orphanedCredentials.map(\.id) == [credentialID]) + } + + private func passwordDraft(_ secret: String) -> MachineDraft { + var draft = MachineDraft(newMachine: "alpha") + draft.addresses[0].host = "192.0.2.18" + draft.profiles[0].profile.username = "temp" + draft.profiles[0].authMode = .password + draft.profiles[0].enteredSecret = secret + return draft + } +} + +/// An in-memory vault whose writes and deletes can be made to fail like a +/// locked or denied Keychain. +private final class ScriptedVault: CredentialVault, @unchecked Sendable { + private let inner = InMemoryCredentialVault() + var failsStore = false + var failsRemove = false + + func store(_ secret: Secret, for id: CredentialID) throws { + if failsStore { throw CredentialVaultError.keychain(status: -25308, operation: "add") } + try inner.store(secret, for: id) + } + + func retrieve(id: CredentialID) throws -> Secret { try inner.retrieve(id: id) } + + func remove(id: CredentialID) throws { + if failsRemove { throw CredentialVaultError.keychain(status: -25308, operation: "delete") } + try inner.remove(id: id) + } + + func contains(id: CredentialID) -> Bool { inner.contains(id: id) } +} + +private final class ScriptedLibrary: MachineLibrary, @unchecked Sendable { + struct Refused: Error {} + private let inner: any MachineLibrary + var failsSave = false + + init(_ inner: any MachineLibrary) { self.inner = inner } + + func snapshot() async throws -> MachineLibrarySnapshot { try await inner.snapshot() } + + func save(_ change: MachineLibraryChange) async throws { + if failsSave { throw Refused() } + try await inner.save(change) + } } diff --git a/Tests/App/RDPTrustTests.swift b/Tests/App/RDPTrustTests.swift index 3476994..7c870b0 100644 --- a/Tests/App/RDPTrustTests.swift +++ b/Tests/App/RDPTrustTests.swift @@ -29,11 +29,22 @@ struct RDPTrustTests { } } + private func resolve( + _ certificate: RDPCertificate, + machineName: String, + trustStore: any TrustStore, + prompt: @MainActor (RDPCertificate, String, Bool) -> RDPTrustDecision + ) async -> RDPCertificateVerdict { + await resolveCertificate( + certificate, machineName: machineName, trustStore: trustStore, prompt: prompt, + trustNotSaved: { _, _, error in Issue.record(error, "trust decision unexpectedly not saved") }) + } + @Test func trustedFingerprintConnectsWithoutPrompting() async throws { let store = InMemoryTrustStore() try await store.trust(TrustedCertificate(host: "win11", port: 3389, fingerprint: "AA:BB:CC", subject: "", issuer: "", commonName: "")) let prompt = Prompt(.reject) - let verdict = await resolveCertificate(cert(), machineName: "win11", trustStore: store, prompt: prompt.ask) + let verdict = await resolve(cert(), machineName: "win11", trustStore: store, prompt: prompt.ask) #expect(verdict == .acceptOnce) #expect(prompt.calls.isEmpty) } @@ -41,7 +52,7 @@ struct RDPTrustTests { @Test func unknownCertificatePromptsAsFirstUse() async throws { let store = InMemoryTrustStore() let prompt = Prompt(.connectOnce) - let verdict = await resolveCertificate(cert(), machineName: "win11", trustStore: store, prompt: prompt.ask) + let verdict = await resolve(cert(), machineName: "win11", trustStore: store, prompt: prompt.ask) #expect(verdict == .acceptOnce) #expect(prompt.calls.count == 1) #expect(prompt.calls.first?.1 == false) @@ -52,7 +63,7 @@ struct RDPTrustTests { @Test func alwaysTrustPersistsTheFingerprint() async throws { let store = InMemoryTrustStore() let prompt = Prompt(.trustAlways) - let verdict = await resolveCertificate(cert(), machineName: "win11", trustStore: store, prompt: prompt.ask) + let verdict = await resolve(cert(), machineName: "win11", trustStore: store, prompt: prompt.ask) #expect(verdict == .acceptOnce) #expect(try await store.trusted(host: "win11", port: 3389)?.fingerprint == "AA:BB:CC") } @@ -62,7 +73,7 @@ struct RDPTrustTests { try await store.trust(TrustedCertificate(host: "win11", port: 3389, fingerprint: "AA:BB:CC", subject: "", issuer: "", commonName: "")) try await store.forget(host: "win11", port: 3389) let prompt = Prompt(.connectOnce) - let verdict = await resolveCertificate(cert(), machineName: "win11", trustStore: store, prompt: prompt.ask) + let verdict = await resolve(cert(), machineName: "win11", trustStore: store, prompt: prompt.ask) #expect(verdict == .acceptOnce) #expect(prompt.calls.count == 1) #expect(prompt.calls.first?.1 == false, "a forgotten server is not a changed one") @@ -71,7 +82,7 @@ struct RDPTrustTests { @Test func alwaysTrustRecordsWhenTheDecisionWasMade() async throws { let store = InMemoryTrustStore() let before = Date() - _ = await resolveCertificate(cert(), machineName: "win11", trustStore: store, prompt: Prompt(.trustAlways).ask) + _ = await resolve(cert(), machineName: "win11", trustStore: store, prompt: Prompt(.trustAlways).ask) let trustedAt = try #require(try await store.trusted(host: "win11", port: 3389)?.trustedAt) #expect(trustedAt >= before && trustedAt <= Date()) } @@ -80,8 +91,25 @@ struct RDPTrustTests { let store = InMemoryTrustStore() try await store.trust(TrustedCertificate(host: "win11", port: 3389, fingerprint: "OLD", subject: "", issuer: "", commonName: "")) let prompt = Prompt(.reject) - let verdict = await resolveCertificate(cert(fingerprint: "NEW"), machineName: "win11", trustStore: store, prompt: prompt.ask) + let verdict = await resolve(cert(fingerprint: "NEW"), machineName: "win11", trustStore: store, prompt: prompt.ask) #expect(verdict == .reject) #expect(prompt.calls.first?.1 == true, "expected the changed warning") } + + @Test func unsavedAlwaysTrustIsReportedAndStillConnects() async { + var reported: [String] = [] + let verdict = await resolveCertificate( + cert(), machineName: "win11", trustStore: RefusingTrustStore(), prompt: Prompt(.trustAlways).ask, + trustNotSaved: { _, name, _ in reported.append(name) }) + #expect(verdict == .acceptOnce) + #expect(reported == ["win11"]) + } +} + +private struct RefusingTrustStore: TrustStore { + struct Refused: Error {} + func trusted(host: String, port: Int) async throws -> TrustedCertificate? { nil } + func trust(_ certificate: TrustedCertificate) async throws { throw Refused() } + func forget(host: String, port: Int) async throws {} + func all() async throws -> [TrustedCertificate] { [] } }