From 3594e361248780fa432e6d3d53b628c1c102f2d8 Mon Sep 17 00:00:00 2001 From: sudoHG Date: Sun, 15 Nov 2026 17:52:59 +0800 Subject: [PATCH 1/4] Make a paired iPhone an approver Pairing a macOS initiator with an iOS responder now writes the approval flag in the add on both sides (ADR 0014, amendment of #336). The Vault accepts the flag only in an add that pairing authorized for an iOS card and refuses any change to a stored entry's flag; the approver authorization is gone. The Mac adds a newly paired iPhone alone to the Broker's active-approver set as soon as it learns of the add, and adds any flagged entry missing from the set at every list read with the services ready and the account available. A pairing ID whose removal began never joins the set again. Requests pending before the first pairing stay on the Mac. The approval switch, the approver sheet, its system authentication, disableApprover and the confirmation state machine are removed; Remove is how approval stops. The Mac pairing sheet says before the QR code, and again before system authentication with what a request sends, that the iPhone will approve agent requests; the Devices row says whether an iPhone approves. The iPhone's code screen, Face ID reason and paired state say the same. The required flow that clicked the switch is replaced by one that checks the row's approval text and removes the iPhone (still 18 flows). Closes #341 --- Sources/AskKeyAppKit/AppLanguage.swift | 2 +- .../Devices/DeviceCoordinator+Approvers.swift | 265 +++------------- .../Devices/DeviceCoordinator+Pairing.swift | 7 +- .../DeviceCoordinator+RemoteApproval.swift | 39 +-- .../DeviceCoordinator+RemoteDecisions.swift | 17 +- .../Devices/DeviceCoordinator.swift | 17 +- .../Devices/DeviceServicesBackend.swift | 8 +- .../Devices/RemoteApprovalState.swift | 53 ---- .../ManagementAuthenticationProcess.swift | 5 +- .../Resources/Localizable.xcstrings | 264 +++------------ .../Settings/ApproverConfirmationSheet.swift | 158 --------- .../Settings/ApproverSheetPresentation.swift | 132 -------- .../Views/Settings/DevicePairingSheet.swift | 28 +- .../Views/Settings/DevicesPresentation.swift | 29 +- .../Views/Settings/DevicesSettingsModel.swift | 78 +---- .../Settings/DevicesSettingsSection.swift | 70 +--- .../Settings/PairingSheetPresentation.swift | 36 ++- .../Messenger/DeviceMessenger.swift | 4 + .../PairedDevices/PairedDeviceList.swift | 20 +- .../Pairing/PairingSession.swift | 18 +- Sources/AskKeyVault/Vault+Devices.swift | 113 ++----- .../AskKeyVault/Vault+RemoteApproval.swift | 7 +- .../ApproverConfirmationTests.swift | 176 ---------- .../DevicesApproverSheetTests.swift | 209 ------------ .../DevicesSettingsModelTests.swift | 8 +- ...ManagementAuthenticationProcessTests.swift | 27 +- .../RemoteApprovalDecisionTests.swift | 10 +- .../RemoteApprovalPairingTests.swift | 157 +++++++++ .../RemoteApprovalRenderTests.swift | 251 +++++++-------- .../RemoteApprovalRevocationTests.swift | 32 +- .../RemoteApprovalSendingTests.swift | 16 +- .../RemoteApprovalTestSupport.swift | 24 +- .../ApprovalFlagTests.swift | 23 +- .../PairingApproverTests.swift | 86 +++++ Tests/AskKeyE2ETests/DevicesE2ETests.swift | 54 ++-- Tests/AskKeyE2ETests/ScreenshotE2ETests.swift | 40 +-- .../AskKeyTestSupport/E2EDeviceScenario.swift | 37 +-- .../FakeDeviceServices.swift | 20 +- .../DeviceApproverFlagTests.swift | 300 +++++++----------- Tests/UI/required-flows.json | 2 +- docs/features.md | 2 +- docs/glossary.md | 2 +- docs/testing.md | 18 +- .../Pairing/PairingFlowModel.swift | 6 +- .../Resources/Localizable.xcstrings | 29 +- iOS/AskKeyiOSKit/Views/PairingFlowView.swift | 3 + .../ApprovalRequestTests.swift | 2 + iOS/AskKeyiOSKitTests/ApproverTests.swift | 3 + .../Fakes/ApprovalFakes.swift | 16 + iOS/AskKeyiOSKitTests/PairingFlowTests.swift | 15 + 50 files changed, 944 insertions(+), 1994 deletions(-) delete mode 100644 Sources/AskKeyAppKit/Views/Settings/ApproverConfirmationSheet.swift delete mode 100644 Sources/AskKeyAppKit/Views/Settings/ApproverSheetPresentation.swift delete mode 100644 Tests/AskKeyAppTests/ApproverConfirmationTests.swift delete mode 100644 Tests/AskKeyAppTests/DevicesApproverSheetTests.swift create mode 100644 Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift create mode 100644 Tests/AskKeyDevicesTests/PairingApproverTests.swift diff --git a/Sources/AskKeyAppKit/AppLanguage.swift b/Sources/AskKeyAppKit/AppLanguage.swift index 40a95e8d..0cc072fd 100644 --- a/Sources/AskKeyAppKit/AppLanguage.swift +++ b/Sources/AskKeyAppKit/AppLanguage.swift @@ -187,7 +187,7 @@ enum AppLanguage { "Expired without decision", "Open Ask Key to review pending requests.", "Disable system authentication for read approvals", - "Pair a device with this Mac", + "Pair an iPhone that can approve Agent requests", "Ask Key could not save an access record. Credential operations continue, and this warning will remain until recording succeeds.", "Ask Key could not prepare Agent access. Open the app to review the vault state.", "Ask Key could not apply this decision. Open Pending requests to retry or reject it.", diff --git a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift index f94d2e26..98a79516 100644 --- a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift +++ b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift @@ -2,240 +2,63 @@ import AskKeyDevices import AskKeyVault import Foundation -/// Turning a paired iPhone's approval on and off (ADR 0014 → Approvers). +/// Which paired iPhones the Broker's active-approver set holds (ADR 0014 → +/// Approvers, #336). Pairing an iPhone writes its approval flag in the same +/// list write that adds it; the coordinator then adds that pairing ID alone +/// to the set, and repairs any flagged entry the set is missing whenever it +/// reads the list. Removing the pairing is the only way approval stops. extension DeviceCoordinator { - /// The approver code exists for at most this long. - static let approverCodeLifetime: TimeInterval = 5 * 60 - static let approverCodeAttempts = 3 - /// The inbox's zone poll runs about once a second while the sheet waits, - /// because a confirmation has a random message ID. - static let approverPollInterval: TimeInterval = 1 - - /// **Approve agent requests**, step 1, in the management session: asks - /// for system authentication, records it with the Vault for this device - /// and pairing, then shows a new six-digit code for at most 5 minutes - /// and polls for the iPhone's confirmation. The open sheet keeps the - /// management session from expiring for idleness. - package func startApproverConfirmation(for id: DeviceID) async { - guard approverConfirmation?.isActive != true else { return } - guard let services, availability == .ready, account == .available, - let row = devices.first(where: { $0.id == id }), row.platform == .iOS, !row.isApprover else { - approverConfirmation = .ended(.unavailable) - return - } - guard managementSessionIsOpen() else { - approverConfirmation = .ended(.managementRequired) - return - } - approverGeneration += 1 - let generation = approverGeneration - approverConfirmation = .authenticating(device: row) - acquireApproverExpiryHold() - let authenticate = environment.authenticate - let reason = ManagementAuthenticationAction.approveDevice.reasonKey - let prompt = Task { @MainActor in await authenticate(reason) } - approverAuthentication = prompt - let result = await prompt.value - guard generation == approverGeneration else { return } - approverAuthentication = nil - // The sheet may have closed, management locked, the services or the - // device's entry changed while the prompt was open. - guard !prompt.isCancelled, managementSessionIsOpen(), self.services === services, - devices.contains(where: { $0.id == row.id && $0.pairingID == row.pairingID && !$0.isApprover }) else { - return endApproverAttempt(.authenticationCancelled) - } - switch result { - case .authenticated(let authenticator): - do { - try vault.authorizeDeviceApprover(row.id, pairingID: row.pairingID, using: authenticator) - } catch { - return endApproverAttempt(.authenticationFailed) - } - case .cancelled: - return endApproverAttempt(.authenticationCancelled) - case .failed: - return endApproverAttempt(.authenticationFailed) - } - let code = ApproverCode.random() - let expiresAt = now.addingTimeInterval(Self.approverCodeLifetime) - approverAttempt = ApproverAttempt(device: row, code: code, expiresAt: expiresAt, - attemptsRemaining: Self.approverCodeAttempts) - approverCode = code - approverConfirmation = .waitingForIPhone(device: row, expiresAt: expiresAt, - attemptsRemaining: Self.approverCodeAttempts) - startApproverPolling() - } - - /// **Cancel** or closing the sheet: discards the code and the authorization. - package func cancelApproverConfirmation() { - guard approverConfirmation != nil else { return } - approverGeneration += 1 - finishApproverAttempt() - approverConfirmation = nil - } - - func endApproverAttempt(_ reason: ApproverConfirmationEndReason) { - approverGeneration += 1 - finishApproverAttempt() - approverConfirmation = .ended(reason) - } - - /// Drops the code, the polling, the hold on idle expiry and the Vault's - /// approver authorization. - func finishApproverAttempt() { - approverAuthentication?.cancel() - approverAuthentication = nil - approverAttempt = nil - approverCode = nil - approverPollTask?.cancel() - approverPollTask = nil - approverExpiryHold?.release() - approverExpiryHold = nil - vault.endDeviceApproverAuthorization() - } - - /// Step 3: a confirmation from the selected entry whose code proof - /// matches turns approval on; one with another proof counts as a wrong - /// code, and the third ends the attempt. A matching confirmation from - /// any other entry ends the attempt, because that device knows the code; - /// one that does not match is refused without counting. - func handleApproverConfirmation(_ message: VerifiedApprovalMessage, - _ confirmation: ApproverConfirmation) async -> ApprovalMessageHandling { - guard let mac = services?.deviceID, var attempt = approverAttempt, !attempt.enabling, - case .waitingForIPhone = approverConfirmation else { return .refused(.noSession) } - guard now < attempt.expiresAt else { - endApproverAttempt(.expired) - return .refused(.noSession) - } - let matches = attempt.code.matches(proof: confirmation.codeProof, mac: mac, phone: message.senderID, - pairingID: message.pairingID) - guard message.senderID == attempt.device.id, message.pairingID == attempt.device.pairingID else { - if matches { - environment.log(.approverCodeEnteredElsewhere) - endApproverAttempt(.enteredOnOtherDevice(name: message.sender.displayName)) - } - return .refused(.bindingMismatch) - } - guard matches else { - attempt.attemptsRemaining -= 1 - guard attempt.attemptsRemaining > 0 else { - endApproverAttempt(.tooManyWrongCodes) - return .refused(.bindingMismatch) - } - approverAttempt = attempt - approverConfirmation = .waitingForIPhone(device: attempt.device, expiresAt: attempt.expiresAt, - attemptsRemaining: attempt.attemptsRemaining) - return .refused(.bindingMismatch) - } - attempt.enabling = true - approverAttempt = attempt - await enableApprover(attempt.device) - return .processed + /// Device services ready with the list's account available. + var canActivateApprovers: Bool { + services != nil && availability == .ready && account == .available } - /// Writes the flag, which uses the Vault's authorization up, then adds - /// only this device to the Broker's set, so other approvers keep their - /// generations. - private func enableApprover(_ row: PairedDeviceRow) async { - guard let services else { return } - let generation = approverGeneration - let outcome: PairedDeviceChangeOutcome? + /// Loads the set from the list once the services are ready with the + /// list's account: every flagged entry gets a new generation. + func activateApproversIfNeeded() { + guard canActivateApprovers, !approversLoaded else { return } do { - outcome = try await services.registry.apply(.setApprover(row.id, pairingID: row.pairingID, enabled: true)) + try vault.activateStoredApprovers() + approversLoaded = true } catch { - outcome = nil - } - if outcome == .applied { - if approversLoaded { - do { - try vault.activateStoredApprovers(only: row.pairingID) - } catch { - // Added alone at the next account check, so the other - // approvers keep their generations. - approversAwaitingActivation.insert(row.pairingID) - environment.log(.approverActivationFailed) - } - } else { - activateApproversIfNeeded() - } - environment.log(.approverEnabled) - } - await publish() - guard generation == approverGeneration else { return } - switch outcome { - case .applied?: - let updated = devices.first { $0.id == row.id && $0.pairingID == row.pairingID } ?? row - approverGeneration += 1 - finishApproverAttempt() - approverConfirmation = .enabled(device: updated) - case nil: - endApproverAttempt(.notSaved) - default: - endApproverAttempt(.deviceRemoved) + environment.log(.approverActivationFailed) } } - /// Turns a device's approval off, in the management session: it leaves - /// the Broker's set first, then the flag is written, then its outstanding - /// requests close with outcome 5 (ADR 0014 → Revocation). Reducing - /// authority needs no fresh authentication. - @discardableResult - package func disableApprover(_ row: PairedDeviceRow) async -> Bool { - guard let services else { return false } - guard managementSessionIsOpen() else { - lastIssue = .managementRequired - return false - } - lastIssue = nil - vault.approvalRequests.removeActiveApprover(pairingID: row.pairingID.rawValue) - let lifecycle = self.lifecycle - var applied = false - do { - let outcome = try await services.registry.apply(.setApprover(row.id, pairingID: row.pairingID, enabled: false)) - applied = outcome == .applied - if outcome == .dropped, lifecycle == self.lifecycle { lastIssue = .deviceNotFound } - } catch { - if lifecycle == self.lifecycle { lastIssue = .actionFailed } - } - guard lifecycle == self.lifecycle else { return applied } - closeRemoteRequests(of: row.id, pairingID: row.pairingID) - await publish() - return applied + /// A pairing added `pairingID` to the list: it joins the set alone as + /// soon as the coordinator learns of the add, whether or not the pairing + /// sheet is still open, so the other approvers keep their generations. + func pairingAdded(_ pairingID: PairingID) { + guard canActivateApprovers else { return } + guard approversLoaded else { return activateApproversIfNeeded() } + activateMissingApprover(pairingID) } - // MARK: Schedule - - func startApproverPolling() { - approverPollTask?.cancel() - approverPollTask = nil - guard environment.automaticPolling else { return } - let sleep = environment.sleep - approverPollTask = Task { [weak self] in - while !Task.isCancelled { - try? await sleep(Self.approverPollInterval) - guard let self, !Task.isCancelled, await self.approverLoopStep() else { return } - } + /// Every list read with the services ready and the account available: + /// each flagged entry missing from the set is added alone, so a missed + /// or failed addition is repaired without new generations for the others. + func reconcileActiveApprovers(with list: [PairedDevice]) { + guard canActivateApprovers else { return } + guard approversLoaded else { return activateApproversIfNeeded() } + for device in list where device.isApprover { + activateMissingApprover(device.pairingID) } } - /// One turn of the open sheet: ends the attempt when its code expired or - /// management closed, otherwise keeps management open and polls. - /// Returns whether to go on. - func approverLoopStep() async -> Bool { - guard let attempt = approverAttempt, case .waitingForIPhone = approverConfirmation else { return false } - guard now < attempt.expiresAt else { - endApproverAttempt(.expired) - return false - } - guard managementSessionIsOpen() else { - cancelApproverConfirmation() - return false + /// Adds one pairing ID unless it is in the set already or its removal + /// has begun. The Vault reads the revocation counter and the stored list + /// itself, so an entry removed meanwhile is not added, and a removal that + /// races the addition makes the Broker refuse it (ADR 0014 → Revocation). + private func activateMissingApprover(_ pairingID: PairingID) { + guard !revokedApprovers.contains(pairingID), + vault.approvalRequests.activeApproverGeneration(pairingID: pairingID.rawValue) == nil else { return } + do { + if !(try vault.activateStoredApprovers(only: pairingID)).isEmpty { + environment.log(.approverActivated) + } + } catch { + // The next list read tries again. + environment.log(.approverActivationFailed) } - await refresh() - return approverAttempt != nil - } - - func acquireApproverExpiryHold() { - if approverExpiryHold == nil { approverExpiryHold = SessionPolicy.holdIdleExpiry() } } } diff --git a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Pairing.swift b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Pairing.swift index cb2b7b70..87715e43 100644 --- a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Pairing.swift +++ b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Pairing.swift @@ -171,9 +171,7 @@ extension DeviceCoordinator { } /// The management session ended (locked, expired or its window closed). - /// An open approver sheet ends too, with its code and authorization. package func managementSessionEnded() async { - if approverConfirmation?.isActive == true { cancelApproverConfirmation() } guard pairingIsLive else { finishPairingSession() return @@ -250,7 +248,7 @@ extension DeviceCoordinator { pairing = .codeAccepted(peer: peer) case .waitingForPeer(let peer): pairing = .waitingForIPhoneConfirmation(peer: peer) - case .paired(let peer, _): + case .paired(let peer, let pairingID): pairing = .paired(peer: peer) pairingFeedback = nil environment.log(.devicePaired) @@ -260,6 +258,9 @@ extension DeviceCoordinator { isAuthenticatingPairing = false vault.endDevicePairingAuthorization() deliveryCheckAfterPairing = peer.deviceID + // The add wrote the iPhone's flag; it joins the set now. A sheet + // that closed first is covered by the next list read. + pairingAdded(pairingID) case .ended(let reason): pairing = .ended(reason) environment.log(.pairingEnded(reason)) diff --git a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteApproval.swift b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteApproval.swift index 9d9a1555..08fe4af3 100644 --- a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteApproval.swift +++ b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteApproval.swift @@ -48,28 +48,6 @@ extension DeviceCoordinator { // MARK: Approvers - /// Loads the Broker's active-approver set from the list once the services - /// are ready with the list's account (ADR 0014 → Approvers). - func activateApproversIfNeeded() { - guard services != nil, availability == .ready, account == .available else { return } - guard approversLoaded else { - do { - try vault.activateStoredApprovers() - approversLoaded = true - approversAwaitingActivation = [] - } catch { - environment.log(.approverActivationFailed) - } - return - } - // A device whose flag was written but whose activation failed is - // added alone, so the others keep their generations. - for pairingID in approversAwaitingActivation { - guard (try? vault.activateStoredApprovers(only: pairingID)) != nil else { continue } - approversAwaitingActivation.remove(pairingID) - } - } - /// An account change, sign-out or restriction: empties the set first, /// then forgets every outstanding request without sending, because /// nothing is sent while the account is unavailable. The flags stay. @@ -77,7 +55,6 @@ extension DeviceCoordinator { vault.approvalRequests.removeAllActiveApprovers() approversLoaded = false forgetOutstandingRemoteRequests() - if approverConfirmation?.isActive == true { endApproverAttempt(.unavailable) } } /// The requests still pending stay on the Mac, also once the account is @@ -94,15 +71,13 @@ extension DeviceCoordinator { } } - /// The services stopped or were replaced. + /// The services stopped or were replaced. Requests still pending stay on + /// the Mac, also once services open again, for example at the next + /// first pairing. func stopRemoteApproval() { approversLoaded = false - dropRemoteState() - if approverConfirmation != nil { - approverGeneration += 1 - finishApproverAttempt() - approverConfirmation = nil - } + revokedApprovers = [] + forgetOutstandingRemoteRequests() } private func dropRemoteState() { @@ -146,8 +121,10 @@ extension DeviceCoordinator { startRemoteLoopIfNeeded() } + /// Runs also without device services, so a request pending before the + /// first pairing is marked as staying on the Mac and never goes to the + /// iPhone that pairing adds (ADR 0014 → When a request goes to an approver). func reconcileRemoteRequests() { - guard services != nil else { return } let pending = vault.approvalRequests.pendingRequests() let pendingIDs = Set(pending.map(\.requestID)) for requestID in remoteRequests.keys where !pendingIDs.contains(requestID) { diff --git a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift index 4fe5d980..2adebb58 100644 --- a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift +++ b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift @@ -14,16 +14,15 @@ extension DeviceCoordinator { /// The handler `AskKeyDevices` calls with every verified kind 10–14 /// message, after it checked the envelope, the payload, the pairing ID and /// the approval-key signature (checks 1, 3 and 6). The Mac accepts only - /// what an iPhone sends it. + /// a decision or a receipt; an approver confirmation, retired by #336, + /// is refused like any kind the Mac does not expect. func handleApprovalMessage(_ message: VerifiedApprovalMessage) async -> ApprovalMessageHandling { switch message.message { case .decision(let decision): return await handleRemoteDecision(message, decision) case .receipt(let receipt): return handleReceipt(message, receipt) - case .confirmation(let confirmation): - return await handleApproverConfirmation(message, confirmation) - case .request, .closed: + case .request, .closed, .confirmation: return .refused(.unexpectedKind) } } @@ -199,7 +198,7 @@ extension DeviceCoordinator { } /// Ends one approver's outstanding requests with outcome 5 after it was - /// turned off, removed, paired again or found inactive; for an inactive + /// removed, paired again or found inactive; for an inactive /// generation, only the requests sealed under it. Entries whose decision /// is being applied keep their own outcome. func closeRemoteRequests(of device: DeviceID, pairingID: PairingID, generation: UInt64? = nil) { @@ -264,13 +263,13 @@ extension DeviceCoordinator { /// The removal hook `AskKeyDevices` calls before any removal of `entry` /// commits: a removal here, an unpair notice, an undone pairing or /// pairing again. The device leaves the Broker's set first; then its - /// requests close (ADR 0014 → Revocation). + /// requests close (ADR 0014 → Revocation). A removed pairing ID never + /// joins the set again, so an addition that runs after this, before the + /// write commits, cannot bring it back. func deviceWillBeRemoved(_ entry: PairedDevice) { + revokedApprovers.insert(entry.pairingID) vault.approvalRequests.removeActiveApprover(pairingID: entry.pairingID.rawValue) closeRemoteRequests(of: entry.deviceID, pairingID: entry.pairingID) - if let attempt = approverAttempt, attempt.device.id == entry.deviceID, attempt.device.pairingID == entry.pairingID { - endApproverAttempt(.deviceRemoved) - } } // MARK: Helpers diff --git a/Sources/AskKeyAppKit/Devices/DeviceCoordinator.swift b/Sources/AskKeyAppKit/Devices/DeviceCoordinator.swift index 7ed29b39..87c6e3d6 100644 --- a/Sources/AskKeyAppKit/Devices/DeviceCoordinator.swift +++ b/Sources/AskKeyAppKit/Devices/DeviceCoordinator.swift @@ -152,11 +152,6 @@ package final class DeviceCoordinator { package internal(set) var remoteApprovals: [String: RemoteApprovalStatus] = [:] /// The last decision from an approver that moved a request out of pending. package internal(set) var lastRemoteDecision: RemoteAppliedDecision? - /// The open "Approve agent requests" sheet's state; nil when none is open. - package internal(set) var approverConfirmation: ApproverConfirmationState? - /// The code the open sheet shows while it waits for the iPhone. Its - /// description is redacted; only the sheet shows `formatted`. - package internal(set) var approverCode: ApproverCode? @ObservationIgnored let launchTime: Date @ObservationIgnored var remoteRequests: [String: RemoteRequestTrack] = [:] @ObservationIgnored var closedMessages: [MessageID: PendingClosedMessage] = [:] @@ -174,14 +169,8 @@ package final class DeviceCoordinator { /// Whether the Broker's active-approver set was loaded from the list for /// the current services and account. @ObservationIgnored var approversLoaded = false - /// Approvers whose flag was written but whose activation failed. - @ObservationIgnored var approversAwaitingActivation: Set = [] - @ObservationIgnored var approverAttempt: ApproverAttempt? - /// Changes whenever an approver confirmation starts or is left. - @ObservationIgnored var approverGeneration = 0 - @ObservationIgnored var approverAuthentication: Task? - @ObservationIgnored var approverPollTask: Task? - @ObservationIgnored var approverExpiryHold: SessionExpiryHold? + /// Pairing IDs whose removal began; they never join the set again. + @ObservationIgnored var revokedApprovers: Set = [] @ObservationIgnored var registeredForRemoteNotifications = false package init(environment: DeviceCoordinatorEnvironment) { @@ -363,7 +352,6 @@ package final class DeviceCoordinator { // Nothing can be sealed or opened any more; sealed closing messages // still go out. forgetOutstandingRemoteRequests(keepingClosed: true) - if approverConfirmation?.isActive == true { endApproverAttempt(.unavailable) } availability = .identityUnusable } @@ -541,6 +529,7 @@ package final class DeviceCoordinator { if let list { listedDevices = list.devices unreachableDevices = unreachableDevices.filter { id in list.device(id) != nil } + reconcileActiveApprovers(with: list.devices) publishRows() } if services.messenger === messenger { applyPairingPhase(phase) } diff --git a/Sources/AskKeyAppKit/Devices/DeviceServicesBackend.swift b/Sources/AskKeyAppKit/Devices/DeviceServicesBackend.swift index c722ba17..cb3f4de6 100644 --- a/Sources/AskKeyAppKit/Devices/DeviceServicesBackend.swift +++ b/Sources/AskKeyAppKit/Devices/DeviceServicesBackend.swift @@ -149,11 +149,11 @@ package enum DeviceServicesEvent: Hashable, Sendable { case accountChanged case inboxPreparationFailed case pollFailed - /// The Broker's active-approver set could not be loaded from the list. + /// The Broker's active-approver set could not be loaded from the list, + /// or a newly paired or missing approver could not be added to it. case approverActivationFailed - case approverEnabled - /// A matching approver code arrived from a device other than the one selected. - case approverCodeEnteredElsewhere + /// A newly paired or missing approver joined the active-approver set. + case approverActivated case remoteRequestNotSealed case closedMessageNotSealed case knownRecordFetchFailed diff --git a/Sources/AskKeyAppKit/Devices/RemoteApprovalState.swift b/Sources/AskKeyAppKit/Devices/RemoteApprovalState.swift index 693bc063..e6e76af0 100644 --- a/Sources/AskKeyAppKit/Devices/RemoteApprovalState.swift +++ b/Sources/AskKeyAppKit/Devices/RemoteApprovalState.swift @@ -27,48 +27,6 @@ package struct RemoteAppliedDecision: Equatable, Sendable { package let approved: Bool } -/// The "Approve agent requests" sheet (ADR 0014 → Approvers). No case -/// carries the approver code; `DeviceCoordinator.approverCode` holds it -/// while the sheet waits for the iPhone. -package enum ApproverConfirmationState: Equatable, Sendable { - /// System authentication for turning approval on is open. - case authenticating(device: PairedDeviceRow) - /// Show the code until `expiresAt`, with what will leave the Mac; the - /// person types it on that iPhone. - case waitingForIPhone(device: PairedDeviceRow, expiresAt: Date, attemptsRemaining: Int) - /// The device is an approver now. - case enabled(device: PairedDeviceRow) - case ended(ApproverConfirmationEndReason) - - var isActive: Bool { - switch self { - case .authenticating, .waitingForIPhone: return true - case .enabled, .ended: return false - } - } -} - -package enum ApproverConfirmationEndReason: Equatable, Sendable { - /// Turning approval on needs the management session. - case managementRequired - /// The device services, the iCloud account or the device's entry are - /// not available. - case unavailable - case authenticationCancelled - case authenticationFailed - /// Five minutes passed without a matching confirmation. - case expired - /// The selected iPhone sent three wrong codes. - case tooManyWrongCodes - /// The code was entered on a different device than the one selected, - /// named as the Mac calls it. - case enteredOnOtherDevice(name: String) - /// The selected device was removed, or paired again, meanwhile. - case deviceRemoved - /// The approval flag could not be saved. - case notSaved -} - /// Holds the process activity that keeps App Nap and idle sleep away while a /// request needs it (ADR 0014 → When a request goes to an approver). package struct DeviceProcessActivity { @@ -162,14 +120,3 @@ struct PendingClosedMessage { /// Nil while a send is out. var retryAt: Date? } - -/// The open approver confirmation (ADR 0014 → Approvers, step 3). -struct ApproverAttempt { - let device: PairedDeviceRow - let code: ApproverCode - let expiresAt: Date - var attemptsRemaining: Int - /// A matching confirmation arrived and the flag is being written; any - /// further confirmation is refused without counting. - var enabling = false -} diff --git a/Sources/AskKeyAppKit/ManagementAuthenticationProcess.swift b/Sources/AskKeyAppKit/ManagementAuthenticationProcess.swift index 271f37dc..a716385d 100644 --- a/Sources/AskKeyAppKit/ManagementAuthenticationProcess.swift +++ b/Sources/AskKeyAppKit/ManagementAuthenticationProcess.swift @@ -8,7 +8,7 @@ enum ManagementAuthenticationAction: CaseIterable { case clearAccessRecords, eraseLibrary, revealFrozenFile case approveRead, approveWrite, permanentlyDelete, replaceImportedCredential case disableReadAuthentication, changeTimedAllowanceEnd, legacyRelease, legacyUnlock - case exportBackup, importBackup, pairDevice, approveDevice + case exportBackup, importBackup, pairDevice var reasonKey: String { switch self { @@ -29,8 +29,7 @@ enum ManagementAuthenticationAction: CaseIterable { case .legacyUnlock: "Unlock the AskKey vault for %@" case .exportBackup: CredentialManagementCopy.exportBackupReason case .importBackup: CredentialManagementCopy.importBackupReason - case .pairDevice: "Pair a device with this Mac" - case .approveDevice: "Let a paired iPhone approve Agent requests" + case .pairDevice: "Pair an iPhone that can approve Agent requests" } } diff --git a/Sources/AskKeyAppKit/Resources/Localizable.xcstrings b/Sources/AskKeyAppKit/Resources/Localizable.xcstrings index 961cda80..608b593d 100644 --- a/Sources/AskKeyAppKit/Resources/Localizable.xcstrings +++ b/Sources/AskKeyAppKit/Resources/Localizable.xcstrings @@ -7566,6 +7566,14 @@ } } }, + "Pair an iPhone that can approve Agent requests": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Pair an iPhone that can approve Agent requests" } }, + "zh-Hans": { "stringUnit": { "state": "translated", "value": "确认配对一台可以审批 Agent 请求的 iPhone" } }, + "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Pair an iPhone that can approve Agent requests!!]" } } + } + }, "Dismiss error": { "extractionState": "extracted_with_value", "localizations": { @@ -16888,6 +16896,22 @@ "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Not reached yet!!]" } } } }, + "Can approve agent requests.": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Can approve agent requests." } }, + "zh-Hans": { "stringUnit": { "state": "translated", "value": "可以审批 Agent 请求。" } }, + "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Can approve agent requests.!!]" } } + } + }, + "Can't approve agent requests. To let it approve, remove it and pair again.": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Can't approve agent requests. To let it approve, remove it and pair again." } }, + "zh-Hans": { "stringUnit": { "state": "translated", "value": "不能审批 Agent 请求。要让它审批,请移除后重新配对。" } }, + "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Can't approve agent requests. To let it approve, remove it and pair again.!!]" } } + } + }, "Last reached %@": { "extractionState": "manual", "localizations": { @@ -16976,6 +17000,14 @@ "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!This Mac stops trusting “%@” at once. Ask Key tries to tell the device so it can remove this Mac. If it still lists this Mac, remove this Mac on that device too.!!]" } } } }, + "“%@” stops approving agent requests at once, and the requests sent to it close. Ask Key tries to tell the iPhone so it can remove this Mac. If it still lists this Mac, remove this Mac on that iPhone too.": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "“%@” stops approving agent requests at once, and the requests sent to it close. Ask Key tries to tell the iPhone so it can remove this Mac. If it still lists this Mac, remove this Mac on that iPhone too." } }, + "zh-Hans": { "stringUnit": { "state": "translated", "value": "“%@”将立即停止审批 Agent 请求,已发给它的请求随即关闭。请旨会尝试通知这台 iPhone 移除这台 Mac;如果它仍列出这台 Mac,请在那台 iPhone 上手动移除。" } }, + "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!“%@” stops approving agent requests at once, and the requests sent to it close. Ask Key tries to tell the iPhone so it can remove this Mac. If it still lists this Mac, remove this Mac on that iPhone too.!!]" } } + } + }, "Preparing…": { "extractionState": "manual", "localizations": { @@ -17056,6 +17088,14 @@ "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!The code matches. Confirm to finish pairing; Ask Key asks for system authentication.!!]" } } } }, + "The code matches. If you confirm, “%@” can approve agents' requests to use credentials on this Mac, with Face ID or Touch ID. Ask Key then asks for system authentication.": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "The code matches. If you confirm, “%@” can approve agents' requests to use credentials on this Mac, with Face ID or Touch ID. Ask Key then asks for system authentication." } }, + "zh-Hans": { "stringUnit": { "state": "translated", "value": "配对码正确。确认后,“%@”可以用面容 ID 或触控 ID 审批 Agent 使用这台 Mac 上凭证的请求。接下来请旨会要求系统验证。" } }, + "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!The code matches. If you confirm, “%@” can approve agents' requests to use credentials on this Mac, with Face ID or Touch ID. Ask Key then asks for system authentication.!!]" } } + } + }, "Confirm on the iPhone": { "extractionState": "manual", "localizations": { @@ -17088,6 +17128,14 @@ "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!This Mac and “%@” are paired. Ask Key sent a delivery check; until the device answers, it shows as “Not reached yet”.!!]" } } } }, + "This Mac and “%@” are paired. The iPhone can now approve agents' requests to use credentials on this Mac. Ask Key sent a delivery check; until the iPhone answers, it shows as “Not reached yet”.": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "This Mac and “%@” are paired. The iPhone can now approve agents' requests to use credentials on this Mac. Ask Key sent a delivery check; until the iPhone answers, it shows as “Not reached yet”." } }, + "zh-Hans": { "stringUnit": { "state": "translated", "value": "这台 Mac 已与“%@”配对,这台 iPhone 现在可以审批 Agent 使用这台 Mac 上凭证的请求。请旨已发送送达检查,在这台 iPhone 回应之前,它会显示为“还没联系上”。" } }, + "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!This Mac and “%@” are paired. The iPhone can now approve agents' requests to use credentials on this Mac. Ask Key sent a delivery check; until the iPhone answers, it shows as “Not reached yet”.!!]" } } + } + }, "Pairing Ended": { "extractionState": "manual", "localizations": { @@ -17448,14 +17496,6 @@ "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!That code doesn't match. %lld attempt left.!!]" } } } }, - "Pair a device with this Mac": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Pair a device with this Mac" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "确认将设备与这台 Mac 配对" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Pair a device with this Mac!!]" } } - } - }, "Ask Key found a device-message-key item outside login.keychain-db or duplicate device-message-key items. Quit Ask Key. In Keychain Access, remove the Ask Key device-message-key items that are not in the login keychain, then reopen Ask Key. If Devices then reports that this Mac's device identity is unusable, reset it and pair your devices again. Do not remove vault-key items.": { "extractionState": "manual", "localizations": { @@ -17512,14 +17552,6 @@ "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Confirm Pairing!!]" } } } }, - "Let a paired iPhone approve Agent requests": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Let a paired iPhone approve Agent requests" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "确认让已配对的 iPhone 审批 Agent 请求" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Let a paired iPhone approve Agent requests!!]" } } - } - }, "iPhone": { "extractionState": "manual", "localizations": { @@ -17584,78 +17616,6 @@ "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Sent to iPhone!!]" } } } }, - "Type This Code on “%@”": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Type This Code on “%@”" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "在“%@”上输入这个审批码" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Type This Code on “%@”!!]" } } - } - }, - "In Ask Key on that iPhone, open this Mac in Paired Macs, choose Approve Requests from This Mac or Enter a New Approval Code, type this code and confirm with Face ID or Touch ID.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "In Ask Key on that iPhone, open this Mac in Paired Macs, choose Approve Requests from This Mac or Enter a New Approval Code, type this code and confirm with Face ID or Touch ID." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "在那台 iPhone 上的请旨中,从“已配对的 Mac”打开这台 Mac,选择“审批这台 Mac 的请求”或“重新输入审批码”,输入这个审批码,然后用面容 ID 或触控 ID 确认。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!In Ask Key on that iPhone, open this Mac in Paired Macs, choose Approve Requests from This Mac or Enter a New Approval Code, type this code and confirm with Face ID or Touch ID.!!]" } } - } - }, - "The code typed on the iPhone doesn't match. %lld attempts left.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "The code typed on the iPhone doesn't match. %lld attempts left." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "iPhone 上输入的审批码不正确,还可以再试 %lld 次。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!The code typed on the iPhone doesn't match. %lld attempts left.!!]" } } - } - }, - "The code typed on the iPhone doesn't match. %lld attempt left.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "The code typed on the iPhone doesn't match. %lld attempt left." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "iPhone 上输入的审批码不正确,还可以再试 %lld 次。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!The code typed on the iPhone doesn't match. %lld attempt left.!!]" } } - } - }, - "Approval Is On": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Approval Is On" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "已开启审批" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Approval Is On!!]" } } - } - }, - "“%@” now approves agent requests from this Mac. Allowing always needs Face ID or Touch ID on the iPhone. You can turn this off here at any time.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "“%@” now approves agent requests from this Mac. Allowing always needs Face ID or Touch ID on the iPhone. You can turn this off here at any time." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "“%@”现在会审批这台 Mac 上 Agent 的请求。在 iPhone 上允许始终需要面容 ID 或触控 ID。你可以随时在这里关闭。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!“%@” now approves agent requests from this Mac. Allowing always needs Face ID or Touch ID on the iPhone. You can turn this off here at any time.!!]" } } - } - }, - "Approval Stays Off": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Approval Stays Off" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "审批未开启" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Approval Stays Off!!]" } } - } - }, - "Let “%@” Approve Agent Requests?": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Let “%@” Approve Agent Requests?" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "让“%@”审批 Agent 请求?" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Let “%@” Approve Agent Requests?!!]" } } - } - }, - "When this Mac is locked, or a request waits here for 20 seconds, Ask Key also sends it to this iPhone. Allowing on the iPhone needs Face ID or Touch ID.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "When this Mac is locked, or a request waits here for 20 seconds, Ask Key also sends it to this iPhone. Allowing on the iPhone needs Face ID or Touch ID." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "这台 Mac 锁定时,或请求在这里等待 20 秒后,请旨也会把它发到这台 iPhone。在 iPhone 上允许需要面容 ID 或触控 ID。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!When this Mac is locked, or a request waits here for 20 seconds, Ask Key also sends it to this iPhone. Allowing on the iPhone needs Face ID or Touch ID.!!]" } } - } - }, "Sent to this iPhone, encrypted: the agent's name, the credential's name, the command and folder, and the names the credential is delivered as. Never a credential value.": { "extractionState": "manual", "localizations": { @@ -17664,126 +17624,6 @@ "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Sent to this iPhone, encrypted: the agent's name, the credential's name, the command and folder, and the names the credential is delivered as. Never a credential value.!!]" } } } }, - "Next, Ask Key asks for system authentication, then shows a code to type on this iPhone.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Next, Ask Key asks for system authentication, then shows a code to type on this iPhone." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "接下来,请旨会请求系统验证,然后显示一个要在这台 iPhone 上输入的审批码。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Next, Ask Key asks for system authentication, then shows a code to type on this iPhone.!!]" } } - } - }, - "This code appears only on this Mac. Never type it anywhere else or send it to anyone.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "This code appears only on this Mac. Never type it anywhere else or send it to anyone." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "这个审批码只显示在这台 Mac 上。不要在别处输入,也不要发给任何人。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!This code appears only on this Mac. Never type it anywhere else or send it to anyone.!!]" } } - } - }, - "Approval can't be turned on now. Check that this Mac can reach iCloud and that the device is still paired.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Approval can't be turned on now. Check that this Mac can reach iCloud and that the device is still paired." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "现在无法开启审批。请确认这台 Mac 能连接 iCloud,并且该设备仍处于配对状态。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Approval can't be turned on now. Check that this Mac can reach iCloud and that the device is still paired.!!]" } } - } - }, - "System authentication was cancelled. Nothing changed.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "System authentication was cancelled. Nothing changed." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "系统验证已取消,没有任何更改。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!System authentication was cancelled. Nothing changed.!!]" } } - } - }, - "System authentication didn't succeed. Nothing changed.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "System authentication didn't succeed. Nothing changed." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "系统验证未通过,没有任何更改。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!System authentication didn't succeed. Nothing changed.!!]" } } - } - }, - "The code expired before the iPhone confirmed it. Start again to get a new code.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "The code expired before the iPhone confirmed it. Start again to get a new code." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "iPhone 确认之前,审批码已过期。请重新开始,获取新的审批码。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!The code expired before the iPhone confirmed it. Start again to get a new code.!!]" } } - } - }, - "The code typed on the iPhone didn't match three times, so this attempt ended. Start again to get a new code.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "The code typed on the iPhone didn't match three times, so this attempt ended. Start again to get a new code." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "iPhone 上输入的审批码三次都不正确,本次尝试已结束。请重新开始,获取新的审批码。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!The code typed on the iPhone didn't match three times, so this attempt ended. Start again to get a new code.!!]" } } - } - }, - "The code was typed on “%@”, not on the iPhone you chose, so this attempt ended. If you didn't type it there, remove that device. Otherwise start again and type the code on the iPhone you chose.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "The code was typed on “%@”, not on the iPhone you chose, so this attempt ended. If you didn't type it there, remove that device. Otherwise start again and type the code on the iPhone you chose." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "审批码是在“%@”上输入的,不是你选择的 iPhone,所以本次尝试已结束。如果不是你在那里输入的,请移除该设备;否则请重新开始,并在你选择的 iPhone 上输入。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!The code was typed on “%@”, not on the iPhone you chose, so this attempt ended. If you didn't type it there, remove that device. Otherwise start again and type the code on the iPhone you chose.!!]" } } - } - }, - "The device was removed or paired again meanwhile, so approval stays off.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "The device was removed or paired again meanwhile, so approval stays off." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "期间该设备已被移除或重新配对,所以审批未开启。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!The device was removed or paired again meanwhile, so approval stays off.!!]" } } - } - }, - "Ask Key couldn't save the setting. Start again.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Ask Key couldn't save the setting. Start again." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "请旨未能保存这项设置。请重新开始。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Ask Key couldn't save the setting. Start again.!!]" } } - } - }, - "Approver code": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Approver code" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "审批码" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Approver code!!]" } } - } - }, - "Start Again": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Start Again" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "重新开始" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Start Again!!]" } } - } - }, - "Approve agent requests": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Approve agent requests" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "审批 Agent 请求" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Approve agent requests!!]" } } - } - }, - "Agent requests can also be decided on this iPhone.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Agent requests can also be decided on this iPhone." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "Agent 请求也可以在这台 iPhone 上审批。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Agent requests can also be decided on this iPhone.!!]" } } - } - }, - "Agent requests aren't sent to this iPhone.": { - "extractionState": "manual", - "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Agent requests aren't sent to this iPhone." } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "Agent 请求不会发到这台 iPhone。" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Agent requests aren't sent to this iPhone.!!]" } } - } - }, "Before you scan, install Ask Key on the iPhone:": { "extractionState": "manual", "localizations": { @@ -17792,12 +17632,12 @@ "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Before you scan, install Ask Key on the iPhone:!!]" } } } }, - "Approve agent requests on “%@”": { + "The iPhone you pair can approve agents' requests to use credentials on this Mac. Pair only your own iPhone.": { "extractionState": "manual", "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Approve agent requests on “%@”" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "在“%@”上审批 Agent 请求" } }, - "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!Approve agent requests on “%@”!!]" } } + "en": { "stringUnit": { "state": "translated", "value": "The iPhone you pair can approve agents' requests to use credentials on this Mac. Pair only your own iPhone." } }, + "zh-Hans": { "stringUnit": { "state": "translated", "value": "配对的 iPhone 可以审批 Agent 使用这台 Mac 上凭证的请求。只配对你自己的 iPhone。" } }, + "qps-ploc": { "stringUnit": { "state": "translated", "value": "[!!The iPhone you pair can approve agents' requests to use credentials on this Mac. Pair only your own iPhone.!!]" } } } } }, diff --git a/Sources/AskKeyAppKit/Views/Settings/ApproverConfirmationSheet.swift b/Sources/AskKeyAppKit/Views/Settings/ApproverConfirmationSheet.swift deleted file mode 100644 index 0eedf443..00000000 --- a/Sources/AskKeyAppKit/Views/Settings/ApproverConfirmationSheet.swift +++ /dev/null @@ -1,158 +0,0 @@ -import AskKeyDevices -import SwiftUI - -/// The **Approve agent requests** sheet (ADR 0014 → Approvers): what will -/// leave the Mac, system authentication, the approver code until the iPhone -/// confirms it, then the result. The code is drawn only in the code box and -/// is hidden from accessibility; no identifier, label or value carries it. -struct ApproverConfirmationSheet: View { - @Bindable var model: DevicesSettingsModel - /// The last state, kept while the sheet animates away after it closed. - @State private var shown: ApproverSheetPresentation? - - var body: some View { - let _ = AppLanguage.store.resolved - let sheet = model.approverSheet ?? shown - Group { - if let sheet { - BackupSheetLayout(title: sheet.title, message: sheet.message) { - content(sheet) - } actions: { - actions(sheet) - } - .controlSize(.large) - } - } - .onAppear { shown = model.approverSheet } - .onChange(of: model.approverSheet) { _, new in - if let new { shown = new } - } - } - - @ViewBuilder - private func content(_ sheet: ApproverSheetPresentation) -> some View { - VStack(alignment: .leading, spacing: Theme.Spacing.lg) { - if case .code(let expiresAt) = sheet.stage { - codeBox(expiresAt: expiresAt) - } - if let feedback = sheet.feedback { - Text(feedback) - .font(Theme.Fonts.secondary) - .foregroundStyle(sheet.feedbackIsWarning ? Theme.warning : Theme.textSecondary) - .fixedSize(horizontal: false, vertical: true) - .accessibilityIdentifier("devices-approver-feedback") - } - if sheet.stage != .enabled { - deviceCard(sheet.device) - } - if sheet.showsWhatLeaves { - BackupNotice(text: ApproverSheetPresentation.whatLeaves, isWarning: false) - Text(ApproverSheetPresentation.nextSteps) - .font(Theme.Fonts.secondary) - .foregroundStyle(Theme.textSecondary) - .fixedSize(horizontal: false, vertical: true) - } - if case .code = sheet.stage { - BackupNotice(text: ApproverSheetPresentation.codeNotice) - } - } - } - - /// The code, its label and the time left. Only this view reads the code. - private func codeBox(expiresAt: Date) -> some View { - TimelineView(.periodic(from: .now, by: 1)) { context in - VStack(spacing: Theme.Spacing.xs) { - Text(appLocalized("Approver code")) - .font(Theme.Fonts.caption) - .foregroundStyle(Theme.textTertiary) - Text(verbatim: model.coordinator.approverCode?.formatted ?? "") - .font(Theme.Fonts.title.monospacedDigit()) - .foregroundStyle(Theme.text) - .textSelection(.disabled) - .accessibilityHidden(true) - HStack(spacing: Theme.Spacing.sm) { - ProgressView() - .controlSize(.small) - Text(appLocalizedFormat("Expires in %@", FrozenCountdown.format(deadline: expiresAt, now: context.date))) - .font(Theme.Fonts.secondary.monospacedDigit()) - .foregroundStyle(Theme.textSecondary) - } - .accessibilityElement(children: .combine) - .accessibilityIdentifier("devices-approver-waiting") - } - .frame(maxWidth: .infinity) - .padding(Theme.Spacing.md) - .background(Theme.surface, in: .rect(cornerRadius: Theme.Radius.group)) - .overlay(RoundedRectangle(cornerRadius: Theme.Radius.group).stroke(Theme.separator)) - } - } - - /// The selected iPhone: its name, the platform it declared, the paired - /// date and the last delivery check. - private func deviceCard(_ device: PairedDeviceRow) -> some View { - HStack(alignment: .center, spacing: Theme.Spacing.md) { - Image(systemName: DevicesPresentation.platformSymbol(device.platform)) - .font(Theme.Icon.inlineStatus) - .foregroundStyle(Theme.textSecondary) - .frame(width: 24) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - Text(device.displayName) - .font(Theme.Fonts.body.weight(.semibold)) - .foregroundStyle(Theme.text) - .lineLimit(1) - .truncationMode(.middle) - Text(DevicesPresentation.approverDeviceSummary(device)) - .font(Theme.Fonts.secondary) - .foregroundStyle(Theme.textSecondary) - Text((DevicesPresentation.rowDeliveryCheck(device) ?? DevicesPresentation.rowReachability(device)).text) - .font(Theme.Fonts.secondary) - .foregroundStyle(Theme.textSecondary) - } - Spacer(minLength: 0) - } - .padding(Theme.Spacing.md) - .background(Theme.surface, in: .rect(cornerRadius: Theme.Radius.group)) - .overlay(RoundedRectangle(cornerRadius: Theme.Radius.group).stroke(Theme.separator)) - } - - @ViewBuilder - private func actions(_ sheet: ApproverSheetPresentation) -> some View { - Spacer(minLength: 0) - switch sheet.stage { - case .intro, .authenticating: - cancelButton - Button(appLocalized("Continue")) { Task { await model.continueApprover() } } - .buttonStyle(.borderedProminent) - .tint(Theme.accent) - .keyboardShortcut(.defaultAction) - .disabled(sheet.stage == .authenticating) - .accessibilityIdentifier("devices-approver-continue") - case .code: - cancelButton - case .enabled: - Button(appLocalized("Done")) { model.closeApproverSheet() } - .buttonStyle(.borderedProminent) - .tint(Theme.accent) - .keyboardShortcut(.defaultAction) - .accessibilityIdentifier("devices-approver-done") - case .ended(let canStartAgain): - Button(appLocalized("Close")) { model.closeApproverSheet() } - .keyboardShortcut(canStartAgain ? .cancelAction : .defaultAction) - .accessibilityIdentifier("devices-approver-close") - if canStartAgain { - Button(appLocalized("Start Again")) { Task { await model.startApproverAgain() } } - .buttonStyle(.borderedProminent) - .tint(Theme.accent) - .keyboardShortcut(.defaultAction) - .accessibilityIdentifier("devices-approver-start-again") - } - } - } - - private var cancelButton: some View { - Button(appLocalized("Cancel")) { model.closeApproverSheet() } - .keyboardShortcut(.cancelAction) - .accessibilityIdentifier("devices-approver-cancel") - } -} diff --git a/Sources/AskKeyAppKit/Views/Settings/ApproverSheetPresentation.swift b/Sources/AskKeyAppKit/Views/Settings/ApproverSheetPresentation.swift deleted file mode 100644 index b915e353..00000000 --- a/Sources/AskKeyAppKit/Views/Settings/ApproverSheetPresentation.swift +++ /dev/null @@ -1,132 +0,0 @@ -import AskKeyDevices -import Foundation - -/// What the **Approve agent requests** sheet shows for one coordinator state -/// (ADR 0014 → Approvers): first what will leave the Mac, then system -/// authentication, then the approver code until the iPhone confirms it, then -/// the result. No state carries the code; only the sheet's code box reads -/// `DeviceCoordinator.approverCode`, so no title, message or accessibility -/// text here can contain it. -struct ApproverSheetPresentation: Equatable { - enum Stage: Equatable { - /// What will leave the Mac; **Continue** asks for system authentication. - case intro - case authenticating - /// The code box, until `expiresAt`. - case code(expiresAt: Date) - case enabled - case ended(canStartAgain: Bool) - } - - let stage: Stage - /// The iPhone the person selected, as the Mac lists it. - let device: PairedDeviceRow - let title: String - let message: String? - /// A wrong code from the iPhone, or the authentication prompt. - let feedback: String? - let feedbackIsWarning: Bool - - @MainActor - init(device selected: PairedDeviceRow, state: ApproverConfirmationState?) { - var device = selected - var feedback: String? - var feedbackIsWarning = true - let stage: Stage - let title: String - let message: String? - switch state { - case nil: - stage = .intro - title = Self.introTitle(device) - message = Self.introMessage - case .authenticating(let row)?: - device = row - stage = .authenticating - title = Self.introTitle(device) - message = Self.introMessage - feedback = appLocalized("Waiting for system authentication…") - feedbackIsWarning = false - case .waitingForIPhone(let row, let expiresAt, let remaining)?: - device = row - stage = .code(expiresAt: expiresAt) - title = appLocalizedFormat("Type This Code on “%@”", row.displayName) - message = appLocalized("In Ask Key on that iPhone, open this Mac in Paired Macs, choose Approve Requests from This Mac or Enter a New Approval Code, type this code and confirm with Face ID or Touch ID.") - if remaining < DeviceCoordinator.approverCodeAttempts { - feedback = AppLanguage.localizedCount("The code typed on the iPhone doesn't match. %lld attempts left.", - oneKey: "The code typed on the iPhone doesn't match. %lld attempt left.", - count: remaining, language: AppLanguage.current) - } - case .enabled(let row)?: - device = row - stage = .enabled - title = appLocalized("Approval Is On") - message = appLocalizedFormat("“%@” now approves agent requests from this Mac. Allowing always needs Face ID or Touch ID on the iPhone. You can turn this off here at any time.", row.displayName) - case .ended(let reason)?: - stage = .ended(canStartAgain: Self.canStartAgain(after: reason)) - title = appLocalized("Approval Stays Off") - message = Self.endMessage(reason) - } - self.stage = stage - self.device = device - self.title = title - self.message = message - self.feedback = feedback - self.feedbackIsWarning = feedbackIsWarning - } - - /// The intro and authentication steps list what will leave the Mac. - var showsWhatLeaves: Bool { stage == .intro || stage == .authenticating } - - static func introTitle(_ device: PairedDeviceRow) -> String { - appLocalizedFormat("Let “%@” Approve Agent Requests?", device.displayName) - } - - static var introMessage: String { - appLocalized("When this Mac is locked, or a request waits here for 20 seconds, Ask Key also sends it to this iPhone. Allowing on the iPhone needs Face ID or Touch ID.") - } - - static var whatLeaves: String { - appLocalized("Sent to this iPhone, encrypted: the agent's name, the credential's name, the command and folder, and the names the credential is delivered as. Never a credential value.") - } - - static var nextSteps: String { - appLocalized("Next, Ask Key asks for system authentication, then shows a code to type on this iPhone.") - } - - static var codeNotice: String { - appLocalized("This code appears only on this Mac. Never type it anywhere else or send it to anyone.") - } - - static func canStartAgain(after reason: ApproverConfirmationEndReason) -> Bool { - switch reason { - case .authenticationCancelled, .authenticationFailed, .expired, .tooManyWrongCodes, .enteredOnOtherDevice, .notSaved: - return true - case .managementRequired, .unavailable, .deviceRemoved: - return false - } - } - - static func endMessage(_ reason: ApproverConfirmationEndReason) -> String { - switch reason { - case .managementRequired: - return appLocalized("Credential management is locked. Unlock it, then try again.") - case .unavailable: - return appLocalized("Approval can't be turned on now. Check that this Mac can reach iCloud and that the device is still paired.") - case .authenticationCancelled: - return appLocalized("System authentication was cancelled. Nothing changed.") - case .authenticationFailed: - return appLocalized("System authentication didn't succeed. Nothing changed.") - case .expired: - return appLocalized("The code expired before the iPhone confirmed it. Start again to get a new code.") - case .tooManyWrongCodes: - return appLocalized("The code typed on the iPhone didn't match three times, so this attempt ended. Start again to get a new code.") - case .enteredOnOtherDevice(let name): - return appLocalizedFormat("The code was typed on “%@”, not on the iPhone you chose, so this attempt ended. If you didn't type it there, remove that device. Otherwise start again and type the code on the iPhone you chose.", name) - case .deviceRemoved: - return appLocalized("The device was removed or paired again meanwhile, so approval stays off.") - case .notSaved: - return appLocalized("Ask Key couldn't save the setting. Start again.") - } - } -} diff --git a/Sources/AskKeyAppKit/Views/Settings/DevicePairingSheet.swift b/Sources/AskKeyAppKit/Views/Settings/DevicePairingSheet.swift index 42c9d8e0..3401c7b9 100644 --- a/Sources/AskKeyAppKit/Views/Settings/DevicePairingSheet.swift +++ b/Sources/AskKeyAppKit/Views/Settings/DevicePairingSheet.swift @@ -3,7 +3,9 @@ import SwiftUI /// The **Pair a Device…** sheet (ADR 0013 → Pairing): the QR code, then the /// device that scanned it, then the code the iPhone shows, then the result. -/// It never shows the Mac's code: no state it reads carries one. +/// It says before the QR code, and again before the person confirms, that +/// the iPhone will approve this Mac's agent requests (ADR 0014, #336). It +/// never shows the Mac's code: no state it reads carries one. struct DevicePairingSheet: View { @Bindable var model: DevicesSettingsModel /// The last state, kept while the sheet animates away after the session closed. @@ -52,6 +54,10 @@ struct DevicePairingSheet: View { if sheet.stage == .codeEntry(accepted: false) { codeField } + if let contents = sheet.requestContents { + BackupNotice(text: contents, isWarning: false) + .accessibilityIdentifier("devices-pairing-request-contents") + } if let feedback = sheet.feedback { Text(feedback) .font(Theme.Fonts.secondary) @@ -94,21 +100,29 @@ struct DevicePairingSheet: View { } } - /// The iPhone app comes from a fixed link (ADR 0014 → Mac App). + /// The iPhone app comes from a fixed link (ADR 0014 → Mac App), and the + /// iPhone paired here becomes an approver (#336). private var installReminder: some View { HStack(alignment: .firstTextBaseline, spacing: Theme.Spacing.sm) { Image(systemName: "info.circle.fill") .font(Theme.Fonts.secondary) .foregroundStyle(Theme.accent) .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - Text(PairingSheetPresentation.installReminder) + VStack(alignment: .leading, spacing: Theme.Spacing.sm) { + VStack(alignment: .leading, spacing: 2) { + Text(PairingSheetPresentation.installReminder) + .font(Theme.Fonts.secondary) + .foregroundStyle(Theme.text) + .fixedSize(horizontal: false, vertical: true) + Link(PairingSheetPresentation.installLinkText, destination: PairingSheetPresentation.installURL) + .font(Theme.Fonts.secondary) + .accessibilityIdentifier("devices-pairing-install-link") + } + Text(PairingSheetPresentation.approvalStatement) .font(Theme.Fonts.secondary) .foregroundStyle(Theme.text) .fixedSize(horizontal: false, vertical: true) - Link(PairingSheetPresentation.installLinkText, destination: PairingSheetPresentation.installURL) - .font(Theme.Fonts.secondary) - .accessibilityIdentifier("devices-pairing-install-link") + .accessibilityIdentifier("devices-pairing-approval-statement") } Spacer(minLength: 0) } diff --git a/Sources/AskKeyAppKit/Views/Settings/DevicesPresentation.swift b/Sources/AskKeyAppKit/Views/Settings/DevicesPresentation.swift index 85dd2501..f72e7d07 100644 --- a/Sources/AskKeyAppKit/Views/Settings/DevicesPresentation.swift +++ b/Sources/AskKeyAppKit/Views/Settings/DevicesPresentation.swift @@ -92,12 +92,6 @@ enum DevicesPresentation { appLocalizedFormat("%1$@ · Paired %2$@", platformName(row.platform), date(row.pairedAt, time: false)) } - /// "iPhone (not verified) · Paired ", for the approver sheet. - static func approverDeviceSummary(_ row: PairedDeviceRow) -> String { - appLocalizedFormat("%1$@ · Paired %2$@", appLocalizedFormat("%@ (not verified)", platformName(row.platform)), - date(row.pairedAt, time: false)) - } - /// Whether the device was reached since pairing. static func rowReachability(_ row: PairedDeviceRow) -> Notice { switch row.reachability { @@ -123,11 +117,16 @@ enum DevicesPresentation { } } - /// The line under **Approve agent requests** on an iPhone's row. - static func approverCaption(_ row: PairedDeviceRow) -> String { - row.isApprover - ? appLocalized("Agent requests can also be decided on this iPhone.") - : appLocalized("Agent requests aren't sent to this iPhone.") + /// Whether an iPhone approves this Mac's agent requests (ADR 0014 → Mac + /// App, #336). Pairing sets the flag; an entry without it, paired + /// before #336, approves only once it is removed and paired again. Mac + /// rows say nothing. + static func rowApproval(_ row: PairedDeviceRow) -> Notice? { + guard row.platform == .iOS else { return nil } + return row.isApprover + ? Notice(text: appLocalized("Can approve agent requests."), isWarning: false) + : Notice(text: appLocalized("Can't approve agent requests. To let it approve, remove it and pair again."), + isWarning: true) } static func issueMessage(_ issue: DeviceActionIssue) -> String { @@ -145,8 +144,12 @@ enum DevicesPresentation { } } - static func removalWarning(_ name: String) -> String { - appLocalizedFormat("This Mac stops trusting “%@” at once. Ask Key tries to tell the device so it can remove this Mac. If it still lists this Mac, remove this Mac on that device too.", name) + /// **Remove**'s confirmation. Removal is how an iPhone stops approving. + static func removalWarning(_ row: PairedDeviceRow) -> String { + guard row.isApprover else { + return appLocalizedFormat("This Mac stops trusting “%@” at once. Ask Key tries to tell the device so it can remove this Mac. If it still lists this Mac, remove this Mac on that device too.", row.displayName) + } + return appLocalizedFormat("“%@” stops approving agent requests at once, and the requests sent to it close. Ask Key tries to tell the iPhone so it can remove this Mac. If it still lists this Mac, remove this Mac on that iPhone too.", row.displayName) } static func date(_ date: Date, time: Bool) -> String { diff --git a/Sources/AskKeyAppKit/Views/Settings/DevicesSettingsModel.swift b/Sources/AskKeyAppKit/Views/Settings/DevicesSettingsModel.swift index 7ad93974..0f7f2f8a 100644 --- a/Sources/AskKeyAppKit/Views/Settings/DevicesSettingsModel.swift +++ b/Sources/AskKeyAppKit/Views/Settings/DevicesSettingsModel.swift @@ -23,8 +23,6 @@ final class DevicesSettingsModel { private(set) var isSubmitting = false /// **Pair Again** is replacing the session; the sheet stays open meanwhile. private(set) var isRestarting = false - /// The iPhone whose **Approve agent requests** sheet is open. - private(set) var approverSheetDevice: PairedDeviceRow? @ObservationIgnored private var qrCache: (text: String, image: NSImage)? @@ -85,7 +83,6 @@ final class DevicesSettingsModel { cancelRename() removalCandidate = nil confirmingReset = false - if approverSheetDevice != nil { closeApproverSheet() } await coordinator.devicesOpened() } @@ -197,7 +194,8 @@ final class DevicesSettingsModel { await coordinator.sendDeliveryCheck(to: row.id) } - /// **Remove** asks first; only the confirmation removes the device. + /// **Remove** asks first; only the confirmation removes the device. For + /// an iPhone it is how approval stops (ADR 0014 → Revocation). func requestRemoval(_ row: PairedDeviceRow) { cancelRename() removalCandidate = row.id @@ -218,78 +216,6 @@ final class DevicesSettingsModel { } } - // MARK: Approver - - var isApproverSheetPresented: Bool { approverSheetDevice != nil } - - var approverSheet: ApproverSheetPresentation? { - approverSheetDevice.map { ApproverSheetPresentation(device: $0, state: coordinator.approverConfirmation) } - } - - /// Turning approval on needs the device services and the account the - /// devices were paired in, which carries the iPhone's confirmation. - var canTurnApproverOn: Bool { - coordinator.availability == .ready && coordinator.account == .available - } - - /// Turning it off only writes this Mac's list, so it also works while - /// iCloud can't be reached. - var canTurnApproverOff: Bool { coordinator.availability == .ready } - - func canChangeApprover(_ row: PairedDeviceRow) -> Bool { - row.isApprover ? canTurnApproverOff : canTurnApproverOn - } - - /// The switch. Turning it on opens the sheet on its first step, which - /// only explains what will leave the Mac; turning it off takes effect at - /// once and asks for no authentication. Mac rows have no switch. - func setApprover(_ row: PairedDeviceRow, enabled: Bool) async { - guard row.platform == .iOS, enabled != row.isApprover, canChangeApprover(row) else { return } - guard enabled else { - await coordinator.disableApprover(row) - return - } - guard approverSheetDevice == nil else { return } - cancelRename() - removalCandidate = nil - // An attempt that ended earlier leaves its state; this one starts fresh. - coordinator.cancelApproverConfirmation() - approverSheetDevice = row - } - - /// **Continue**: system authentication, then the code. - func continueApprover() async { - guard let row = approverSheetDevice, coordinator.approverConfirmation == nil else { return } - await coordinator.startApproverConfirmation(for: row.id) - } - - /// **Start Again** after an attempt ended: system authentication again, - /// then a new code. - func startApproverAgain() async { - guard let row = approverSheetDevice, case .ended? = coordinator.approverConfirmation else { return } - coordinator.cancelApproverConfirmation() - await coordinator.startApproverConfirmation(for: row.id) - } - - /// **Cancel**, **Done**, **Close** or closing the sheet: the code and - /// the authorization are discarded. - func closeApproverSheet() { - approverSheetDevice = nil - coordinator.cancelApproverConfirmation() - } - - /// The section left the screen, for example because management locked: - /// the approver sheet must not come back on the next visit. - func sectionClosed() { - if approverSheetDevice != nil { closeApproverSheet() } - } - - /// The coordinator dropped an open attempt itself, for example when - /// management locked; the sheet closes with it. - func approverStateChanged(from old: ApproverConfirmationState?, to new: ApproverConfirmationState?) { - if old?.isActive == true, new == nil, approverSheetDevice != nil { closeApproverSheet() } - } - // MARK: Reset /// **Reset Device Identity…** asks first; only the confirmation deletes diff --git a/Sources/AskKeyAppKit/Views/Settings/DevicesSettingsSection.swift b/Sources/AskKeyAppKit/Views/Settings/DevicesSettingsSection.swift index 44d3017f..6bd88a77 100644 --- a/Sources/AskKeyAppKit/Views/Settings/DevicesSettingsSection.swift +++ b/Sources/AskKeyAppKit/Views/Settings/DevicesSettingsSection.swift @@ -2,8 +2,9 @@ import AskKeyDevices import SwiftUI /// Settings → Devices (ADR 0013 → Mac App): **Pair a Device…**, the paired -/// devices with **Rename**, **Test Delivery** and **Remove**, and why pairing -/// or reaching them is unavailable. Builds without CloudKit show nothing. +/// devices with **Rename**, **Test Delivery** and **Remove**, whether each +/// iPhone approves agent requests (ADR 0014, #336), and why pairing or +/// reaching them is unavailable. Builds without CloudKit show nothing. struct DevicesSettingsSection: View { /// Held by `VaultViewModel` for the coordinator's life and passed in, as /// the Backup section receives the vault; this view owns no model. @@ -92,24 +93,7 @@ private struct DevicesSectionContent: View { .accessibilityIdentifier("settings-devices-issue") } } - // The approver sheet ends only through its buttons or when the - // coordinator drops the attempt; a dismissal SwiftUI reports while - // the code shows does not cancel it. - .sheet(isPresented: Binding( - get: { model.isApproverSheetPresented }, - set: { presented in - if !presented, model.coordinator.approverConfirmation?.isActive != true { model.closeApproverSheet() } - } - )) { - ApproverConfirmationSheet(model: model) - } - .onChange(of: model.coordinator.approverConfirmation) { old, new in - model.approverStateChanged(from: old, to: new) - } .onAppear { Task { await model.sectionOpened() } } - // Locking management replaces the page; an open approver sheet and - // its code go with it (ADR 0014 → Approvers). - .onDisappear { model.sectionClosed() } } /// Stands in for the list while no device is listed. @@ -136,8 +120,9 @@ private struct DevicesSectionContent: View { } } -/// One paired device: name, platform, paired date, last reached and the -/// last delivery check, with its actions or an open rename or removal. +/// One paired device: name, platform, paired date, whether an iPhone +/// approves agent requests, last reached and the last delivery check, with +/// its actions or an open rename or removal. private struct DeviceRow: View { @Bindable var model: DevicesSettingsModel let row: PairedDeviceRow @@ -148,6 +133,7 @@ private struct DeviceRow: View { let isRenaming = model.renaming == row.id let reachability = DevicesPresentation.rowReachability(row) let check = DevicesPresentation.rowDeliveryCheck(row) + let approval = DevicesPresentation.rowApproval(row) VStack(alignment: .leading, spacing: 0) { HStack(alignment: .center, spacing: Theme.Spacing.md) { Image(systemName: DevicesPresentation.platformSymbol(row.platform)) @@ -175,6 +161,10 @@ private struct DeviceRow: View { Text(DevicesPresentation.rowSummary(row)) .font(Theme.Fonts.secondary) .foregroundStyle(Theme.textSecondary) + if let approval { + statusLine(approval) + .accessibilityIdentifier("devices-row-approval") + } statusLine(reachability) .accessibilityIdentifier("devices-row-reachability") if let check { @@ -207,17 +197,12 @@ private struct DeviceRow: View { } .padding(.horizontal, Theme.Spacing.lg) .padding(.vertical, Theme.Spacing.md) - if row.platform == .iOS { - approverControl - .padding(.leading, Theme.Spacing.lg + 24 + Theme.Spacing.md) - .padding(.trailing, Theme.Spacing.lg) - .padding(.bottom, Theme.Spacing.md) - } if model.removalCandidate == row.id { GroupedListSeparator() - DevicesConfirmationRow(warning: DevicesPresentation.removalWarning(row.displayName)) { + DevicesConfirmationRow(warning: DevicesPresentation.removalWarning(row)) { Button(appLocalized("Cancel")) { model.cancelRemoval() } .buttonStyle(.secondaryAction) + .accessibilityIdentifier("devices-cancel-remove") Button(appLocalized("Remove"), role: .destructive) { Task { await model.confirmRemoval() } } .buttonStyle(FrozenDangerButtonStyle()) .accessibilityIdentifier("devices-confirm-remove") @@ -226,35 +211,6 @@ private struct DeviceRow: View { } } - /// **Approve agent requests**, off until the person turns it on with - /// system authentication and the code typed on this iPhone (ADR 0014). - /// It sits in the device's own row, below the Pairing row, so the box - /// never holds a single row with a control (#299). - private var approverControl: some View { - HStack(alignment: .center, spacing: Theme.Spacing.md) { - VStack(alignment: .leading, spacing: 2) { - Text(appLocalized("Approve agent requests")) - .font(Theme.Fonts.body) - .foregroundStyle(Theme.text) - Text(DevicesPresentation.approverCaption(row)) - .font(Theme.Fonts.secondary) - .foregroundStyle(Theme.textSecondary) - .fixedSize(horizontal: false, vertical: true) - .accessibilityIdentifier("devices-approver-caption") - } - Spacer(minLength: Theme.Spacing.md) - Toggle(appLocalized("Approve agent requests"), isOn: Binding( - get: { row.isApprover }, - set: { enabled in Task { await model.setApprover(row, enabled: enabled) } } - )) - .toggleStyle(.switch) - .labelsHidden() - .accessibilityLabel(appLocalizedFormat("Approve agent requests on “%@”", row.displayName)) - .dimmedAndDisabled(!model.canChangeApprover(row)) - .accessibilityIdentifier("devices-approver-toggle") - } - } - private func statusLine(_ line: DevicesPresentation.Notice) -> some View { Text(line.text) .font(Theme.Fonts.secondary) diff --git a/Sources/AskKeyAppKit/Views/Settings/PairingSheetPresentation.swift b/Sources/AskKeyAppKit/Views/Settings/PairingSheetPresentation.swift index 3817eb16..ea7465cd 100644 --- a/Sources/AskKeyAppKit/Views/Settings/PairingSheetPresentation.swift +++ b/Sources/AskKeyAppKit/Views/Settings/PairingSheetPresentation.swift @@ -4,7 +4,9 @@ import Foundation /// What the pairing sheet shows for one coordinator state (ADR 0013 → /// Pairing). The state carries no code, so neither does anything here: /// the sheet never shows the Mac's code. Before the person confirms on the -/// Mac, nothing says whether the iPhone has confirmed. +/// Mac, nothing says whether the iPhone has confirmed. Pairing an iPhone +/// makes it an approver (ADR 0014, #336), so the sheet says so before the +/// QR code and again before the system authentication that confirms it. struct PairingSheetPresentation: Equatable { enum Stage: Equatable { case preparing @@ -26,6 +28,9 @@ struct PairingSheetPresentation: Equatable { let peer: PairingPeer? /// A warning shown on the subtle warning surface. let notice: String? + /// What a request sends to the iPhone, shown before the person confirms + /// a pairing that makes it an approver. + let requestContents: String? /// The result of the person's last action, shown under the field. let feedback: String? /// A wrong or malformed entry, or a cancelled or failed authentication. @@ -34,6 +39,7 @@ struct PairingSheetPresentation: Equatable { init(state: PairingSheetState, feedback: PairingFeedback?, isAuthenticating: Bool) { var peer: PairingPeer? var notice: String? + var requestContents: String? var feedbackText: String? var feedbackIsWarning = true let stage: Stage @@ -65,7 +71,12 @@ struct PairingSheetPresentation: Equatable { stage = .codeEntry(accepted: true) peer = acceptedPeer title = appLocalized("Confirm Pairing") - message = appLocalized("The code matches. Confirm to finish pairing; Ask Key asks for system authentication.") + if Self.becomesApprover(acceptedPeer) { + message = appLocalizedFormat("The code matches. If you confirm, “%@” can approve agents' requests to use credentials on this Mac, with Face ID or Touch ID. Ask Key then asks for system authentication.", acceptedPeer.displayName) + requestContents = Self.requestContentsText + } else { + message = appLocalized("The code matches. Confirm to finish pairing; Ask Key asks for system authentication.") + } if isAuthenticating { feedbackText = appLocalized("Waiting for system authentication…") feedbackIsWarning = false @@ -80,7 +91,9 @@ struct PairingSheetPresentation: Equatable { case .paired(let pairedPeer): stage = .paired title = appLocalized("Paired") - message = appLocalizedFormat("This Mac and “%@” are paired. Ask Key sent a delivery check; until the device answers, it shows as “Not reached yet”.", pairedPeer.displayName) + message = Self.becomesApprover(pairedPeer) + ? appLocalizedFormat("This Mac and “%@” are paired. The iPhone can now approve agents' requests to use credentials on this Mac. Ask Key sent a delivery check; until the iPhone answers, it shows as “Not reached yet”.", pairedPeer.displayName) + : appLocalizedFormat("This Mac and “%@” are paired. Ask Key sent a delivery check; until the device answers, it shows as “Not reached yet”.", pairedPeer.displayName) case .ended(let reason): stage = .ended(canPairAgain: reason != .identityUnusable && reason != .deviceLimitReached) title = appLocalized("Pairing Ended") @@ -95,6 +108,7 @@ struct PairingSheetPresentation: Equatable { self.message = message self.peer = peer self.notice = notice + self.requestContents = requestContents self.feedback = feedbackText self.feedbackIsWarning = feedbackIsWarning } @@ -116,6 +130,22 @@ struct PairingSheetPresentation: Equatable { appLocalized("Before you scan, install Ask Key on the iPhone:") } + /// Next to the install reminder, before the QR code. + static var approvalStatement: String { + appLocalized("The iPhone you pair can approve agents' requests to use credentials on this Mac. Pair only your own iPhone.") + } + + /// What leaves the Mac in a request, encrypted to the iPhone. + static var requestContentsText: String { + appLocalized("Sent to this iPhone, encrypted: the agent's name, the credential's name, the command and folder, and the names the credential is delivered as. Never a credential value.") + } + + /// A pairing with a device whose card says iOS adds it with the approval + /// flag; the platform is what the device declares (ADR 0014 → Approvers). + static func becomesApprover(_ peer: PairingPeer) -> Bool { + peer.platform == .iOS + } + static var codeInstruction: String { appLocalized("Enter the code shown on the iPhone's Ask Key pairing screen. Never enter a code from a notification or a message. If that screen shows no code, cancel.") } diff --git a/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift b/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift index 80a4cc62..a4989825 100644 --- a/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift +++ b/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift @@ -340,6 +340,10 @@ public actor DeviceMessenger { await flushOutbox() } + /// Adds the session's peer with the entry the session built, which + /// carries the approval flag when a macOS initiator pairs with an iOS + /// responder (ADR 0014 → Approvers), on both sides. On the Mac the + /// Vault accepts that flag only in this add. private func addSessionPeer(generation: Int) async { let now = clock.now() guard let current = session, current.needsAdd, current.isOpen(at: now), diff --git a/Sources/AskKeyDevices/PairedDevices/PairedDeviceList.swift b/Sources/AskKeyDevices/PairedDevices/PairedDeviceList.swift index 4c72c27d..42dade2c 100644 --- a/Sources/AskKeyDevices/PairedDevices/PairedDeviceList.swift +++ b/Sources/AskKeyDevices/PairedDevices/PairedDeviceList.swift @@ -29,7 +29,10 @@ public struct PairedDevice: Hashable, Sendable { public internal(set) var lastDeliveryCheck: DeliveryCheckResult? /// The approval flag (ADR 0014 → Approvers). On a Mac: this iPhone may /// decide its requests. On an iPhone: it accepts requests from this Mac. - /// Every entry starts with it off; only `setApprover` turns it on. + /// The initializer leaves it off. A pairing session sets it in the entry + /// it adds when the initiator's card says macOS and the responder's says + /// iOS, and it never changes for the life of the entry: the Mac's Vault + /// refuses any change to a stored entry's flag. public internal(set) var isApprover = false public init(card: DeviceCard, pairingID: PairingID, displayName: String, pairedAt: Date, @@ -56,9 +59,9 @@ public struct PairedDevice: Hashable, Sendable { /// pairing cannot bring back or alter the wrong entry. public enum PairedDeviceChange: Hashable, Sendable { /// Adds a device; pairing again with a device already on the list - /// replaces its entry and pairing ID. The new entry's approval flag is - /// off; adding an entry with the stored pairing ID again keeps the - /// stored flag. + /// replaces its entry and pairing ID. The entry is stored as given, + /// approval flag included: the pairing session that adds it decides the + /// flag (ADR 0014 → Approvers). case add(PairedDevice) case rename(DeviceID, pairingID: PairingID, displayName: String) case remove(DeviceID, pairingID: PairingID) @@ -67,8 +70,9 @@ public enum PairedDeviceChange: Hashable, Sendable { /// The state of the delivery check this device sent. A reply also marks /// the peer as reached; "no reply" applies only to the check still pending. case recordDeliveryCheck(DeviceID, pairingID: PairingID, result: DeliveryCheckResult) - /// Turns the entry's approval flag on or off. On the Mac the Vault - /// decides who may write it (ADR 0014 → Approvers). + /// Turns the entry's approval flag on or off. The Mac's Vault refuses + /// it, because a stored entry's flag never changes (ADR 0014 → + /// Approvers); it goes with the retired approver code. case setApprover(DeviceID, pairingID: PairingID, enabled: Bool) } @@ -115,9 +119,7 @@ public struct PairedDeviceList: Hashable, Sendable { @discardableResult public mutating func apply(_ change: PairedDeviceChange) throws -> PairedDeviceChangeOutcome { switch change { - case .add(var device): - let stored = self.device(device.deviceID) - device.isApprover = stored?.pairingID == device.pairingID && stored?.isApprover == true + case .add(let device): try insert(device) return .applied case .rename(let id, let pairingID, let name): diff --git a/Sources/AskKeyDevices/Pairing/PairingSession.swift b/Sources/AskKeyDevices/Pairing/PairingSession.swift index af378624..89259474 100644 --- a/Sources/AskKeyDevices/Pairing/PairingSession.swift +++ b/Sources/AskKeyDevices/Pairing/PairingSession.swift @@ -186,9 +186,25 @@ struct PairingSession { } } + /// The entry this session adds to its own list. It carries the approval + /// flag (ADR 0014 → Approvers) when the initiator's card says macOS and + /// the responder's card says iOS, on both sides: the Mac's entry for the + /// iPhone and the iPhone's entry for the Mac. Any other pairing, such as + /// two Macs, adds its entry without the flag. Each platform is what that + /// device's card declares, so this is a policy filter, not a check + /// against impostors. func entry(pairedAt: Date) -> PairedDevice? { guard let peer, let pairingID else { return nil } - return PairedDevice(card: peer.card, pairingID: pairingID, displayName: peer.displayName, pairedAt: pairedAt) + var entry = PairedDevice(card: peer.card, pairingID: pairingID, displayName: peer.displayName, pairedAt: pairedAt) + entry.isApprover = Self.addsApprover(initiator: role == .initiator ? ownCard : peer.card, + responder: role == .initiator ? peer.card : ownCard) + return entry + } + + /// Whether a pairing of these two cards makes the iPhone an approver and + /// the Mac one whose requests the iPhone accepts. + static func addsApprover(initiator: DeviceCard, responder: DeviceCard) -> Bool { + initiator.platform == .macOS && responder.platform == .iOS } // MARK: Incoming messages diff --git a/Sources/AskKeyVault/Vault+Devices.swift b/Sources/AskKeyVault/Vault+Devices.swift index 84dbd47d..ffddfbcd 100644 --- a/Sources/AskKeyVault/Vault+Devices.swift +++ b/Sources/AskKeyVault/Vault+Devices.swift @@ -20,8 +20,9 @@ public enum DeviceStorageError: Error, Equatable, Sendable { /// A list change would add a device the person did not authorize, with /// system authentication, in the current pairing session. case pairingNotAuthorized - /// A list change would turn on a device's approval flag without the - /// approver authorization for that device and pairing (ADR 0014). + /// A list change would set a device's approval flag outside the add that + /// pairing authorized for an iOS card, or change the flag of an entry + /// already stored (ADR 0014 → Approvers). case approverNotAuthorized /// A local erase is running or was interrupted; device storage stays /// closed until it finishes. @@ -52,22 +53,13 @@ public struct DeviceInboxState: Codable, Equatable, Sendable { } /// What the Vault keeps in memory for the device services: the storage -/// epoch, the epoch's only list registry, the pairing and approver -/// authorizations, and the handler that stops the services before a local erase. +/// epoch, the epoch's only list registry, the pairing authorization, and the +/// handler that stops the services before a local erase. final class VaultDeviceState: @unchecked Sendable { - struct Approver: Equatable { - let deviceID: DeviceID - let pairingID: PairingID - } - private let lock = NSRecursiveLock() private var epoch = 0 private var registry: PairedDeviceRegistry? private var authorizedPeer: DeviceID? - private var authorizedApprover: (approver: Approver, expiresAt: Date)? - /// Advances whenever the approver authorization is installed or ended, - /// so an authentication that started before an end cannot install one. - private var approverRevision: UInt64 = 0 private var stopHandler: (@Sendable () -> Void)? func withLock(_ body: () throws -> T) rethrows -> T { @@ -93,38 +85,9 @@ final class VaultDeviceState: @unchecked Sendable { func isAuthorized(_ peer: DeviceID) -> Bool { withLock { authorizedPeer == peer } } - /// Read before the system authentication that grants an approver authorization. - func approverAuthorizationMark() -> (revision: UInt64, epoch: Int) { withLock { (approverRevision, epoch) } } - - /// Installs the authorization only if none was installed or ended, and - /// the epoch did not end, since `mark`. - func authorizeApprover(_ approver: Approver, until expiresAt: Date, - ifUnchangedSince mark: (revision: UInt64, epoch: Int)) -> Bool { - withLock { - guard approverRevision == mark.revision, epoch == mark.epoch else { return false } - approverRevision &+= 1 - authorizedApprover = (approver, expiresAt) - return true - } - } - - func endApproverAuthorization() { - withLock { - approverRevision &+= 1 - authorizedApprover = nil - } - } - - func isApproverAuthorized(_ approver: Approver, at now: Date) -> Bool { - withLock { authorizedApprover.map { $0.approver == approver && now < $0.expiresAt } ?? false } - } - - /// Drops both authorizations, when the management session has ended. + /// Drops the pairing authorization, when the management session has ended. func dropAuthorizations() { - withLock { - authorizedPeer = nil - endApproverAuthorization() - } + withLock { authorizedPeer = nil } } /// Closes the current epoch: its store refuses every later operation and @@ -135,7 +98,6 @@ final class VaultDeviceState: @unchecked Sendable { epoch += 1 registry = nil authorizedPeer = nil - endApproverAuthorization() return stopHandler } } @@ -353,42 +315,13 @@ extension Vault { deviceState.authorize(nil) } - /// How long an approver authorization lasts: the approver sheet's code - /// exists for at most 5 minutes (ADR 0014 → Approvers). - static let deviceApproverAuthorizationLifetime: TimeInterval = 5 * 60 - - /// Records step 1's system authentication for turning on approval for one - /// paired device (ADR 0014 → Approvers). The App writes the flag only - /// after a verified confirmation whose code proof matches; that one list - /// write uses the authorization up, and it lapses after 5 minutes. - /// Requires the management session before and after the authentication; - /// stores nothing if the authenticator does not confirm, or if the - /// attempt was ended, another one was authorized, or the storage epoch - /// ended while it ran. - package func authorizeDeviceApprover(_ deviceID: DeviceID, pairingID: PairingID, - using authenticator: ManagementAuthenticator) throws { - let mark = deviceState.approverAuthorizationMark() - try requireManagementSession() - try authorizeManagement(authenticator, reason: Self.devicePairingReason) - try requireManagementSession() - guard deviceState.authorizeApprover( - .init(deviceID: deviceID, pairingID: pairingID), - until: currentDate.addingTimeInterval(Self.deviceApproverAuthorizationLifetime), ifUnchangedSince: mark - ) else { throw DeviceStorageError.approverNotAuthorized } - } - - /// The approver sheet closed, its code expired or was refused, or management locked. - package func endDeviceApproverAuthorization() { - deviceState.endApproverAuthorization() - } - /// Renaming and removing a device need the management session; an open /// pairing sheet also uses this to keep it from expiring for idleness. public func requireDeviceManagementSession() throws { try requireDeviceManagementSessionDroppingAuthorization() } - /// A management session that has ended also ends any pairing or approver authorization. + /// A management session that has ended also ends the pairing authorization. private func requireDeviceManagementSessionDroppingAuthorization() throws { do { try requireManagementSession() @@ -407,13 +340,13 @@ extension Vault { /// Writes a list the registry prepared. A device that was not on the /// stored list, or is there with another pairing ID, is an add: it needs /// the management session and this pairing session's authorization for - /// that device, which the write then uses up. Turning a device's approval - /// flag on widens authority the same way: it needs the management session - /// and the approver authorization for that device and pairing ID, which - /// the write uses up. Turning it off needs the management session. A - /// device whose flag the write turns off, or whose flagged entry it - /// removes or replaces, leaves the Broker's active-approver set before - /// the write commits, so its authority ends first (ADR 0014 → Revocation). + /// that device, which the write then uses up. The approval flag (ADR + /// 0014 → Approvers) may be on only in that add, and only when the added + /// entry's card says iOS; a write that changes the flag of an entry the + /// list already stores (same device ID and pairing ID) is refused. A + /// device whose flagged entry the write removes or replaces leaves the + /// Broker's active-approver set before the write commits, so its + /// authority ends first (ADR 0014 → Revocation). func savePairedDevices(_ list: PairedDeviceList, epoch: Int) throws { try withDeviceStorage(epoch: epoch) { keys in let vaultKey = try requireKey() @@ -421,21 +354,16 @@ extension Vault { func storedEntry(_ device: PairedDevice) -> PairedDevice? { stored.devices.first { $0.deviceID == device.deviceID && $0.pairingID == device.pairingID } } + guard !list.devices.contains(where: { device in + storedEntry(device).map { $0.isApprover != device.isApprover } ?? false + }) else { throw DeviceStorageError.approverNotAuthorized } let added = list.devices.filter { storedEntry($0) == nil } - let enabled = list.devices.filter { $0.isApprover && storedEntry($0)?.isApprover != true } - let disabled = list.devices.contains { !$0.isApprover && storedEntry($0)?.isApprover == true } - if !added.isEmpty || !enabled.isEmpty || disabled { - try requireDeviceManagementSessionDroppingAuthorization() - } if !added.isEmpty { + try requireDeviceManagementSessionDroppingAuthorization() guard added.count == 1, deviceState.isAuthorized(added[0].deviceID) else { throw DeviceStorageError.pairingNotAuthorized } - } - if !enabled.isEmpty { - guard enabled.count == 1, - deviceState.isApproverAuthorized(.init(deviceID: enabled[0].deviceID, - pairingID: enabled[0].pairingID), at: currentDate) else { + guard !added[0].isApprover || added[0].platform == .iOS else { throw DeviceStorageError.approverNotAuthorized } } @@ -446,7 +374,6 @@ extension Vault { } try keys.saveDeviceItem(PairedDeviceListAuthentication.seal(list, using: vaultKey), account: .pairedDevices) if !added.isEmpty { deviceState.authorize(nil) } - if !enabled.isEmpty { deviceState.endApproverAuthorization() } } } diff --git a/Sources/AskKeyVault/Vault+RemoteApproval.swift b/Sources/AskKeyVault/Vault+RemoteApproval.swift index 73396aa4..3e20890d 100644 --- a/Sources/AskKeyVault/Vault+RemoteApproval.swift +++ b/Sources/AskKeyVault/Vault+RemoteApproval.swift @@ -67,9 +67,10 @@ extension Vault { /// (ADR 0014 → Approvers): reads the revocation counter, then the list, /// then adds the entries whose flag is on, and starts again if a /// revocation raced, at most three times. Every added entry gets a new - /// generation. Pass the pairing ID a flag write just turned on, so other - /// approvers keep their generations; pass nil when the device services - /// become ready. Returns the generations of the added entries. + /// generation. Pass the pairing ID of a flagged entry a pairing just + /// added, or of one found missing from the set, so other approvers keep + /// their generations; pass nil when the device services become ready. + /// Returns the generations of the added entries. @discardableResult package func activateStoredApprovers(only pairingID: PairingID? = nil) throws -> [PairingID: UInt64] { for _ in 0..<3 { diff --git a/Tests/AskKeyAppTests/ApproverConfirmationTests.swift b/Tests/AskKeyAppTests/ApproverConfirmationTests.swift deleted file mode 100644 index de70d7d0..00000000 --- a/Tests/AskKeyAppTests/ApproverConfirmationTests.swift +++ /dev/null @@ -1,176 +0,0 @@ -import AskKeyDevicesTestSupport -import AskKeyTestSupport -import Foundation -import XCTest -@testable import AskKeyAppKit -@testable import AskKeyDevices -@testable import AskKeyVault - -/// Turning a paired iPhone's approval on with system authentication and the -/// six-digit approver code (ADR 0014 → Approvers). -@MainActor -final class ApproverConfirmationTests: AskKeyAppTestCase { - private var harness: DeviceCoordinatorHarness! - - override func setUp() async throws { - harness = try DeviceCoordinatorHarness() - await harness.coordinator.launch() - try await harness.pairPhone() - } - - override func tearDown() async throws { - try harness.close() - harness = nil - } - - private var coordinator: DeviceCoordinator { harness.coordinator } - - private func row() throws -> PairedDeviceRow { - try XCTUnwrap(coordinator.devices.first { $0.id == harness.phone.deviceID }) - } - - private func start() async throws -> ApproverCode { - await coordinator.startApproverConfirmation(for: harness.phone.deviceID) - return try XCTUnwrap(coordinator.approverCode) - } - - private func wrongCode(_ code: ApproverCode) -> String { - String(format: "%06d", ((Int(code.digits) ?? 0) + 1) % 1_000_000) - } - - private func confirm(_ phone: SimulatedPairingPhone, typing code: String) async throws { - try await phone.confirmApprover(typing: code, for: XCTUnwrap(harness.macDeviceID)) - await coordinator.refresh() - } - - func testMatchingCodeFromTheSelectedIPhoneTurnsApprovalOn() async throws { - XCTAssertFalse(try row().isApprover) - let code = try await start() - XCTAssertEqual(harness.script.authenticationReasons.last, ManagementAuthenticationAction.approveDevice.reasonKey) - guard case .waitingForIPhone(_, let expiresAt, let remaining) = coordinator.approverConfirmation else { - return XCTFail("the sheet waits for the iPhone") - } - XCTAssertEqual(expiresAt, harness.clock.now().addingTimeInterval(300)) - XCTAssertEqual(remaining, 3) - XCTAssertEqual(code.formatted.count, 7) - XCTAssertFalse(String(reflecting: coordinator.approverConfirmation).contains(code.digits)) - XCTAssertFalse(String(reflecting: code).contains(code.digits), "the code's description is redacted") - try await confirm(harness.phone, typing: code.formatted) - guard case .enabled(let device) = coordinator.approverConfirmation else { - return XCTFail("approval is on, not \(String(describing: coordinator.approverConfirmation))") - } - XCTAssertTrue(device.isApprover) - XCTAssertTrue(try row().isApprover, "the flag was written through the Vault") - XCTAssertNotNil(try harness.generation(of: harness.phone), "the device is in the active-approver set") - XCTAssertNil(coordinator.approverCode) - XCTAssertTrue(harness.script.loggedEvents.contains(.approverEnabled)) - XCTAssertFalse(harness.script.loggedEvents.map { String(describing: $0) }.joined().contains(code.digits)) - } - - func testWrongCodesCountAndTheThirdEndsTheAttempt() async throws { - let code = try await start() - try await confirm(harness.phone, typing: wrongCode(code)) - guard case .waitingForIPhone(_, _, 2) = coordinator.approverConfirmation else { - return XCTFail("one wrong code counts") - } - try await confirm(harness.phone, typing: wrongCode(code)) - try await confirm(harness.phone, typing: wrongCode(code)) - XCTAssertEqual(coordinator.approverConfirmation, .ended(.tooManyWrongCodes)) - XCTAssertNil(coordinator.approverCode) - XCTAssertFalse(try row().isApprover) - // The Vault's approver authorization ended with the attempt. - let registry = try harness.vault.pairedDeviceRegistry() - let current = try row() - do { - _ = try await registry.apply(.setApprover(current.id, pairingID: current.pairingID, enabled: true)) - XCTFail("the flag needs a new authorization") - } catch { - XCTAssertEqual(error as? DeviceStorageError, .approverNotAuthorized) - } - } - - func testFiveMinutesEndTheAttempt() async throws { - let code = try await start() - harness.clock.advance(by: 299) - let goesOn = await coordinator.approverLoopStep() - XCTAssertTrue(goesOn) - harness.clock.advance(by: 1) - let stopped = await coordinator.approverLoopStep() - XCTAssertFalse(stopped) - XCTAssertEqual(coordinator.approverConfirmation, .ended(.expired)) - try await confirm(harness.phone, typing: code.formatted) - XCTAssertFalse(try row().isApprover, "a confirmation after the expiry does nothing") - XCTAssertTrue(harness.refusals.contains(.noSession)) - } - - func testMatchingCodeFromAnotherDeviceEndsTheAttemptAndIsReported() async throws { - let second = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) - try await harness.pair(second, name: "Synthetic Phone Two") - let code = try await start() - try await confirm(second, typing: code.formatted) - XCTAssertEqual(coordinator.approverConfirmation, .ended(.enteredOnOtherDevice(name: "Synthetic Phone Two"))) - XCTAssertTrue(harness.script.loggedEvents.contains(.approverCodeEnteredElsewhere)) - XCTAssertTrue(coordinator.devices.allSatisfy { !$0.isApprover }) - XCTAssertNil(try harness.generation(of: second)) - } - - func testNonMatchingCodeFromAnotherDeviceIsRefusedWithoutCounting() async throws { - let second = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) - try await harness.pair(second, name: "Synthetic Phone Two") - let code = try await start() - try await confirm(second, typing: wrongCode(code)) - guard case .waitingForIPhone(_, _, 3) = coordinator.approverConfirmation else { - return XCTFail("not counted") - } - XCTAssertTrue(harness.refusals.contains(.bindingMismatch)) - try await confirm(harness.phone, typing: code.formatted) - XCTAssertTrue(try row().isApprover) - } - - func testCancelledOrFailedAuthenticationShowsNoCode() async throws { - harness.script.authenticationResults = [.cancelled, .failed] - await coordinator.startApproverConfirmation(for: harness.phone.deviceID) - XCTAssertEqual(coordinator.approverConfirmation, .ended(.authenticationCancelled)) - await coordinator.startApproverConfirmation(for: harness.phone.deviceID) - XCTAssertEqual(coordinator.approverConfirmation, .ended(.authenticationFailed)) - XCTAssertNil(coordinator.approverCode) - } - - func testClosingTheSheetDuringAuthenticationShowsNoCode() async throws { - harness.script.duringAuthentication = { [weak self] in self?.coordinator.cancelApproverConfirmation() } - await coordinator.startApproverConfirmation(for: harness.phone.deviceID) - XCTAssertNil(coordinator.approverConfirmation) - XCTAssertNil(coordinator.approverCode) - } - - func testTurningApprovalOnNeedsTheManagementSession() async throws { - let prompts = harness.script.authenticationReasons.count - harness.script.managementActive = false - await coordinator.startApproverConfirmation(for: harness.phone.deviceID) - XCTAssertEqual(coordinator.approverConfirmation, .ended(.managementRequired)) - XCTAssertEqual(harness.script.authenticationReasons.count, prompts, "no prompt opened") - } - - func testAnUnusableIdentityEndsTheAttempt() async throws { - _ = try await start() - coordinator.identityBecameUnusable() - XCTAssertEqual(coordinator.approverConfirmation, .ended(.unavailable)) - XCTAssertNil(coordinator.approverCode) - } - - func testClosingTheSheetOrLockingManagementDiscardsTheCode() async throws { - let first = try await start() - coordinator.cancelApproverConfirmation() - XCTAssertNil(coordinator.approverConfirmation) - XCTAssertNil(coordinator.approverCode) - try await confirm(harness.phone, typing: first.formatted) - XCTAssertFalse(try row().isApprover) - - let second = try await start() - harness.script.managementActive = false - await coordinator.managementSessionEnded() - XCTAssertNil(coordinator.approverConfirmation) - try await confirm(harness.phone, typing: second.formatted) - XCTAssertFalse(try row().isApprover) - } -} diff --git a/Tests/AskKeyAppTests/DevicesApproverSheetTests.swift b/Tests/AskKeyAppTests/DevicesApproverSheetTests.swift deleted file mode 100644 index d5192758..00000000 --- a/Tests/AskKeyAppTests/DevicesApproverSheetTests.swift +++ /dev/null @@ -1,209 +0,0 @@ -import AskKeyDevicesTestSupport -import AskKeyTestSupport -import Foundation -import XCTest -@testable import AskKeyAppKit -@testable import AskKeyDevices - -/// Settings → Devices → **Approve agent requests** and its sheet (ADR 0014 -/// → Approvers): off by default, what leaves the Mac before system -/// authentication, then the code, every way an attempt ends, and turning it -/// off without authentication. Nothing the sheet's text or the model -/// publishes carries the code. -@MainActor -final class DevicesApproverSheetTests: AskKeyAppTestCase { - private var harness: DeviceCoordinatorHarness! - private var model: DevicesSettingsModel! - private var previousLanguage = AppLanguage.current - - override func setUp() async throws { - previousLanguage = AppLanguage.current - AppLanguage.current = "en" - harness = try DeviceCoordinatorHarness() - await harness.coordinator.launch() - try await harness.pairPhone() - model = DevicesSettingsModel(coordinator: harness.coordinator) - } - - override func tearDown() async throws { - try harness.close() - harness = nil - model = nil - AppLanguage.current = previousLanguage - } - - private var coordinator: DeviceCoordinator { harness.coordinator } - - private func row() throws -> PairedDeviceRow { - try XCTUnwrap(coordinator.devices.first { $0.id == harness.phone.deviceID }) - } - - private func sheet() throws -> ApproverSheetPresentation { - try XCTUnwrap(model.approverSheet) - } - - private func typeOnPhone(_ code: String, phone: SimulatedPairingPhone? = nil) async throws { - try await (phone ?? harness.phone).confirmApprover(typing: code, for: XCTUnwrap(harness.macDeviceID)) - await coordinator.refresh() - } - - /// The system authentication prompts for turning approval on. - private var approverPrompts: Int { - harness.script.authenticationReasons.filter { $0 == ManagementAuthenticationAction.approveDevice.reasonKey }.count - } - - private func wrong(_ code: ApproverCode) -> String { - String(format: "%06d", ((Int(code.digits) ?? 0) + 1) % 1_000_000) - } - - /// Everything the sheet says, for checks that nothing names the code. - private func sheetText(_ sheet: ApproverSheetPresentation) -> String { - [sheet.title, sheet.message ?? "", sheet.feedback ?? "", String(reflecting: sheet.stage), - String(reflecting: coordinator.approverConfirmation)].joined(separator: "\n") - } - - func testApprovalIsOffAndTurningItOnFirstSaysWhatLeavesTheMac() async throws { - XCTAssertFalse(try row().isApprover) - XCTAssertEqual(DevicesPresentation.approverCaption(try row()), "Agent requests aren't sent to this iPhone.") - await model.setApprover(try row(), enabled: true) - let intro = try sheet() - XCTAssertEqual(intro.stage, .intro) - XCTAssertTrue(intro.showsWhatLeaves) - XCTAssertEqual(intro.title, "Let “Synthetic Phone” Approve Agent Requests?") - XCTAssertNil(coordinator.approverConfirmation) - XCTAssertNil(coordinator.approverCode, "no code before system authentication") - XCTAssertEqual(approverPrompts, 0, "the first step only explains") - } - - func testContinueAuthenticatesThenShowsTheCodeUntilTheIPhoneConfirmsIt() async throws { - await model.setApprover(try row(), enabled: true) - await model.continueApprover() - XCTAssertEqual(harness.script.authenticationReasons.last, ManagementAuthenticationAction.approveDevice.reasonKey) - XCTAssertEqual(approverPrompts, 1) - let code = try XCTUnwrap(coordinator.approverCode) - guard case .code(let expiresAt) = try sheet().stage else { return XCTFail("the code step") } - XCTAssertEqual(expiresAt, harness.clock.now().addingTimeInterval(300)) - XCTAssertEqual(try sheet().title, "Type This Code on “Synthetic Phone”") - XCTAssertNil(try sheet().feedback) - XCTAssertFalse(sheetText(try sheet()).contains(code.digits)) - XCTAssertFalse(sheetText(try sheet()).contains(code.formatted)) - - try await typeOnPhone(wrong(code)) - XCTAssertEqual(try sheet().feedback, "The code typed on the iPhone doesn't match. 2 attempts left.") - try await typeOnPhone(wrong(code)) - XCTAssertEqual(try sheet().feedback, "The code typed on the iPhone doesn't match. 1 attempt left.") - XCTAssertFalse(sheetText(try sheet()).contains(code.digits)) - - try await typeOnPhone(code.formatted) - XCTAssertEqual(try sheet().stage, .enabled) - XCTAssertEqual(try sheet().title, "Approval Is On") - XCTAssertTrue(try row().isApprover) - model.closeApproverSheet() - XCTAssertFalse(model.isApproverSheetPresented) - XCTAssertEqual(DevicesPresentation.approverCaption(try row()), "Agent requests can also be decided on this iPhone.") - } - - func testTurningApprovalOffAsksForNoAuthentication() async throws { - try await harness.enableApprover(harness.phone) - let prompts = harness.script.authenticationReasons.count - XCTAssertTrue(try row().isApprover) - await model.setApprover(try row(), enabled: false) - XCTAssertFalse(try row().isApprover) - XCTAssertEqual(harness.script.authenticationReasons.count, prompts) - XCTAssertFalse(model.isApproverSheetPresented) - XCTAssertNil(try harness.generation(of: harness.phone), "the device left the active-approver set") - } - - func testThreeWrongCodesExpiryAndStartingAgain() async throws { - await model.setApprover(try row(), enabled: true) - await model.continueApprover() - let first = try XCTUnwrap(coordinator.approverCode) - for _ in 0..<3 { try await typeOnPhone(wrong(first)) } - XCTAssertEqual(try sheet().stage, .ended(canStartAgain: true)) - XCTAssertEqual(try sheet().title, "Approval Stays Off") - XCTAssertEqual(try sheet().message, "The code typed on the iPhone didn't match three times, so this attempt ended. Start again to get a new code.") - - await model.startApproverAgain() - XCTAssertEqual(approverPrompts, 2, "starting again repeats system authentication") - guard case .code = try sheet().stage else { return XCTFail("a new code") } - harness.clock.advance(by: 301) - _ = await coordinator.approverLoopStep() - XCTAssertEqual(try sheet().message, "The code expired before the iPhone confirmed it. Start again to get a new code.") - XCTAssertNil(coordinator.approverCode) - XCTAssertFalse(try row().isApprover) - } - - func testACodeTypedOnAnotherIPhoneEndsTheAttemptAndNamesIt() async throws { - let other = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) - try await harness.pair(other, name: "Other Phone") - await model.setApprover(try row(), enabled: true) - await model.continueApprover() - let code = try XCTUnwrap(coordinator.approverCode) - try await typeOnPhone(code.formatted, phone: other) - XCTAssertEqual(try sheet().stage, .ended(canStartAgain: true)) - XCTAssertEqual(try sheet().message, "The code was typed on “Other Phone”, not on the iPhone you chose, so this attempt ended. If you didn't type it there, remove that device. Otherwise start again and type the code on the iPhone you chose.") - XCTAssertEqual(try sheet().device.id, harness.phone.deviceID, "the card still names the iPhone the person chose") - } - - func testCancelledAuthenticationAndLockingManagementCloseNothingOpen() async throws { - harness.script.authenticationResults = [.cancelled] - await model.setApprover(try row(), enabled: true) - await model.continueApprover() - XCTAssertEqual(try sheet().message, "System authentication was cancelled. Nothing changed.") - XCTAssertEqual(try sheet().stage, .ended(canStartAgain: true)) - await model.startApproverAgain() - guard case .code = try sheet().stage else { return XCTFail("the code after authenticating again") } - let open = coordinator.approverConfirmation - await coordinator.managementSessionEnded() - model.approverStateChanged(from: open, to: coordinator.approverConfirmation) - XCTAssertFalse(model.isApproverSheetPresented, "the sheet closes with the attempt") - XCTAssertNil(coordinator.approverCode) - } - - func testMacRowsAndUnavailableServicesOfferNoApproval() async throws { - let phone = try row() - let mac = PairedDeviceRow(id: phone.id, pairingID: phone.pairingID, displayName: "Synthetic Mac", platform: .macOS, - pairedAt: phone.pairedAt, lastDeliveryCheck: nil, reachability: .notReachedYet, - isApprover: false) - await model.setApprover(mac, enabled: true) - XCTAssertFalse(model.isApproverSheetPresented) - harness.backend.accountState = .noAccount - await coordinator.devicesOpened() - XCTAssertFalse(model.canChangeApprover(try row())) - await model.setApprover(try row(), enabled: true) - XCTAssertFalse(model.isApproverSheetPresented) - } - - /// A lost iPhone's approval can be turned off while the Mac can't reach iCloud. - func testApprovalTurnsOffWhileICloudIsUnavailable() async throws { - try await harness.enableApprover(harness.phone) - harness.backend.accountState = .temporarilyUnavailable - await coordinator.devicesOpened() - XCTAssertNotEqual(coordinator.account, .available) - XCTAssertTrue(model.canChangeApprover(try row())) - await model.setApprover(try row(), enabled: false) - XCTAssertFalse(try row().isApprover) - XCTAssertNil(try harness.generation(of: harness.phone)) - } - - func testLeavingTheSectionClosesTheSheetAndDiscardsTheCode() async throws { - await model.setApprover(try row(), enabled: true) - await model.continueApprover() - XCTAssertNotNil(coordinator.approverCode) - model.sectionClosed() - XCTAssertFalse(model.isApproverSheetPresented, "the next visit opens no sheet") - XCTAssertNil(coordinator.approverCode) - XCTAssertNil(coordinator.approverConfirmation) - } - - func testEveryEndReasonSaysWhetherStartingAgainHelps() { - let restartable: [ApproverConfirmationEndReason] = [.authenticationCancelled, .authenticationFailed, .expired, - .tooManyWrongCodes, .enteredOnOtherDevice(name: "x"), .notSaved] - let final: [ApproverConfirmationEndReason] = [.managementRequired, .unavailable, .deviceRemoved] - XCTAssertTrue(restartable.allSatisfy(ApproverSheetPresentation.canStartAgain(after:))) - XCTAssertFalse(final.contains(where: ApproverSheetPresentation.canStartAgain(after:))) - for reason in restartable + final { - XCTAssertFalse(ApproverSheetPresentation.endMessage(reason).isEmpty) - } - } -} diff --git a/Tests/AskKeyAppTests/DevicesSettingsModelTests.swift b/Tests/AskKeyAppTests/DevicesSettingsModelTests.swift index 5768e052..873c2c77 100644 --- a/Tests/AskKeyAppTests/DevicesSettingsModelTests.swift +++ b/Tests/AskKeyAppTests/DevicesSettingsModelTests.swift @@ -113,7 +113,8 @@ final class DevicesSettingsModelTests: AskKeyAppTestCase { "the matching code asks for system authentication with the pairing reason at once") XCTAssertEqual(model.sheet?.stage, .codeEntry(accepted: true)) XCTAssertEqual(model.sheet?.title, "Confirm Pairing") - XCTAssertEqual(model.sheet?.message, "The code matches. Confirm to finish pairing; Ask Key asks for system authentication.") + XCTAssertEqual(model.sheet?.message, "The code matches. If you confirm, “Synthetic Phone” can approve agents' requests to use credentials on this Mac, with Face ID or Touch ID. Ask Key then asks for system authentication.") + XCTAssertNotNil(model.sheet?.requestContents, "it says what a request sends before system authentication") XCTAssertEqual(model.sheet?.feedback, "System authentication was cancelled. Nothing was sent; you can confirm again.") XCTAssertEqual(model.codeEntry, "", "the accepted entry is not shown again") XCTAssertTrue(model.canConfirm, "confirming again needs no new entry") @@ -210,8 +211,9 @@ final class DevicesSettingsModelTests: AskKeyAppTestCase { model.requestRemoval(row) XCTAssertEqual(model.removalCandidate, row.id) XCTAssertEqual(harness.coordinator.devices.count, 1, "asking removes nothing") - XCTAssertEqual(DevicesPresentation.removalWarning(row.displayName), - "This Mac stops trusting “Synthetic Phone” at once. Ask Key tries to tell the device so it can remove this Mac. If it still lists this Mac, remove this Mac on that device too.") + XCTAssertEqual(DevicesPresentation.removalWarning(row), + "“Synthetic Phone” stops approving agent requests at once, and the requests sent to it close. Ask Key tries to tell the iPhone so it can remove this Mac. If it still lists this Mac, remove this Mac on that iPhone too.") + XCTAssertEqual(DevicesPresentation.rowApproval(row)?.text, "Can approve agent requests.") model.cancelRemoval() await model.confirmRemoval() XCTAssertEqual(harness.coordinator.devices.count, 1, "a cancelled confirmation removes nothing") diff --git a/Tests/AskKeyAppTests/ManagementAuthenticationProcessTests.swift b/Tests/AskKeyAppTests/ManagementAuthenticationProcessTests.swift index 74983f4b..ee4b50a3 100644 --- a/Tests/AskKeyAppTests/ManagementAuthenticationProcessTests.swift +++ b/Tests/AskKeyAppTests/ManagementAuthenticationProcessTests.swift @@ -84,11 +84,12 @@ final class ManagementAuthenticationProcessTests: AskKeyAppTestCase { } } - /// Pairing confirmation asks with its own reason (#288), which the - /// authentication subprocess accepts and shows in either language. + /// Pairing confirmation asks with its own reason (#288), which says the + /// iPhone will approve agent requests (#336); the authentication + /// subprocess accepts it and shows it in either language. func testPackagedSubprocessAcceptsAndDescribesThePairingReason() throws { let action = ManagementAuthenticationAction.pairDevice - XCTAssertEqual(action.reasonKey, "Pair a device with this Mac") + XCTAssertEqual(action.reasonKey, "Pair an iPhone that can approve Agent requests") XCTAssertNotEqual(action.reasonKey, CredentialManagementCopy.manageReason) XCTAssertTrue(ManagementAuthenticationSubprocess.accepts(reasonKey: action.reasonKey, argumentCount: 0)) XCTAssertFalse(ManagementAuthenticationSubprocess.accepts(reasonKey: action.reasonKey, argumentCount: 1)) @@ -96,27 +97,11 @@ final class ManagementAuthenticationProcessTests: AskKeyAppTestCase { presentation: ManagementAuthenticationPresentation(reasonKey: action.reasonKey, language: "zh-Hans") ) XCTAssertEqual(chinese.title, "请旨") - XCTAssertEqual(chinese.reason, "确认将设备与这台 Mac 配对") + XCTAssertEqual(chinese.reason, "确认配对一台可以审批 Agent 请求的 iPhone") let english = try describePackagedAuthentication( presentation: ManagementAuthenticationPresentation(reasonKey: action.reasonKey, language: "en") ) - XCTAssertEqual(english.reason, "Pair a device with this Mac") - } - - /// Turning a paired iPhone's approval on asks with its own reason (#313). - func testPackagedSubprocessAcceptsAndDescribesTheApproverReason() throws { - let action = ManagementAuthenticationAction.approveDevice - XCTAssertEqual(action.reasonKey, "Let a paired iPhone approve Agent requests") - XCTAssertNotEqual(action.reasonKey, CredentialManagementCopy.manageReason) - XCTAssertTrue(ManagementAuthenticationSubprocess.accepts(reasonKey: action.reasonKey, argumentCount: 0)) - let chinese = try describePackagedAuthentication( - presentation: ManagementAuthenticationPresentation(reasonKey: action.reasonKey, language: "zh-Hans") - ) - XCTAssertEqual(chinese.reason, "确认让已配对的 iPhone 审批 Agent 请求") // i18n-literal: Assert the Simplified Chinese catalog value. - let english = try describePackagedAuthentication( - presentation: ManagementAuthenticationPresentation(reasonKey: action.reasonKey, language: "en") - ) - XCTAssertEqual(english.reason, "Let a paired iPhone approve Agent requests") + XCTAssertEqual(english.reason, "Pair an iPhone that can approve Agent requests") } func testAuthenticationArgumentsRejectUnknownDuplicateAndMixedModes() { diff --git a/Tests/AskKeyAppTests/RemoteApprovalDecisionTests.swift b/Tests/AskKeyAppTests/RemoteApprovalDecisionTests.swift index ba27e243..c8125ea2 100644 --- a/Tests/AskKeyAppTests/RemoteApprovalDecisionTests.swift +++ b/Tests/AskKeyAppTests/RemoteApprovalDecisionTests.swift @@ -145,7 +145,6 @@ final class RemoteApprovalDecisionTests: AskKeyAppTestCase { func testEveryApproverThatHadTheRequestOpenLearnsHowItEnded() async throws { let second = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) try await harness.pair(second, name: "Synthetic Phone Two") - try await harness.enableApprover(second) let pending = try harness.submitRead() try await harness.waitForRequests(harness.macSent(.approvalRequest).count + 2) let fetched3 = try await harness.phoneRequests() @@ -255,10 +254,12 @@ final class RemoteApprovalDecisionTests: AskKeyAppTestCase { let stale = try XCTUnwrap(harness.entries(first).first) harness.coordinator.remoteRequests[first.requestID]?.entries[0].decided = true harness.coordinator.remoteRequests[first.requestID]?.applying = 1 - // Turned off and on again while that decision is being applied. + // The Broker lost the generation while that decision is being + // applied, and the next list read added the approver again (#336). let row = try XCTUnwrap(harness.coordinator.devices.first) - await harness.coordinator.disableApprover(row) - try await harness.enableApprover(harness.phone) + harness.vault.approvalRequests.removeActiveApprover(pairingID: row.pairingID.rawValue) + await harness.coordinator.refresh() + XCTAssertNotNil(try harness.generation(of: harness.phone)) let (second, _) = try await outstandingRead() XCTAssertNotEqual(harness.entries(second).first?.generation, stale.generation) harness.coordinator.finishRemoteDecision(.outcome(.approverInactive), code: .allowOnce, entry: stale, @@ -288,7 +289,6 @@ final class RemoteApprovalDecisionTests: AskKeyAppTestCase { func testRequestEndedDuringARevokedApproversDecisionStillClosesForTheOthers() async throws { let second = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) try await harness.pair(second, name: "Synthetic Phone Two") - try await harness.enableApprover(second) let pending = try harness.submitRead() try await harness.waitForRequests(harness.macSent(.approvalRequest).count + 2) let deciding = try XCTUnwrap(harness.entries(pending).first { $0.approverID == harness.phone.deviceID }) diff --git a/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift b/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift new file mode 100644 index 00000000..34d0d23d --- /dev/null +++ b/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift @@ -0,0 +1,157 @@ +import AskKeyBroker +import AskKeyDevicesTestSupport +import AskKeyTestSupport +import Foundation +import XCTest +@testable import AskKeyAppKit +@testable import AskKeyDevices +@testable import AskKeyVault + +/// Pairing makes an iPhone an approver (ADR 0014 → Approvers, decision 4 of +/// #336): it joins the Broker's active-approver set as soon as the +/// coordinator learns of the add, a flagged entry missing from the set is +/// added at the next list read, and a removal that races either wins. +@MainActor +final class RemoteApprovalPairingTests: AskKeyAppTestCase { + private var harness: DeviceCoordinatorHarness! + + override func setUp() async throws { + harness = try DeviceCoordinatorHarness() + await harness.coordinator.launch() + } + + override func tearDown() async throws { + try harness.close() + harness = nil + } + + func testANewlyPairedIPhoneJoinsTheSetWithANewGenerationWhileTheSheetShowsPaired() async throws { + try await harness.pairPhoneLeavingSheetOpen() + let row = try XCTUnwrap(harness.coordinator.devices.first) + XCTAssertTrue(row.isApprover, "the add wrote the flag") + let first = try XCTUnwrap(try harness.generation(of: harness.phone), "joined before the sheet closed") + XCTAssertTrue(harness.script.loggedEvents.contains(.approverActivated)) + await harness.coordinator.cancelPairing() + + // A second iPhone joins alone: the first keeps its generation. + let second = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) + try await harness.pair(second, name: "Synthetic Phone Two") + let added = try XCTUnwrap(try harness.generation(of: second)) + XCTAssertGreaterThan(added, first) + XCTAssertEqual(try harness.generation(of: harness.phone), first) + } + + /// The sheet closed while the messenger was committing the add, so the + /// coordinator never saw the paired phase: the next list read adds it. + func testAnIPhoneAddedAfterTheSheetClosedJoinsAtTheNextListRead() async throws { + let code = try await harness.reachCodeEntry() + await harness.coordinator.enterPairingCode(code) + await harness.coordinator.confirmPairing() + guard case .waitingForIPhoneConfirmation = harness.coordinator.pairing else { + return XCTFail("the Mac waits for the iPhone, not \(String(describing: harness.coordinator.pairing))") + } + harness.coordinator.pairing = nil + try await harness.phone.confirm() + await harness.coordinator.refresh() + let row = try XCTUnwrap(harness.coordinator.devices.first, "the Mac added the iPhone") + XCTAssertTrue(row.isApprover) + XCTAssertNil(harness.coordinator.pairing, "no sheet showed the add") + XCTAssertNotNil(try harness.generation(of: harness.phone)) + } + + func testAFlaggedEntryMissingFromTheSetIsAddedAloneAtTheNextListRead() async throws { + try await harness.pairApprover() + let second = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) + try await harness.pair(second, name: "Synthetic Phone Two") + let kept = try XCTUnwrap(try harness.generation(of: second)) + let lost = try XCTUnwrap(try harness.generation(of: harness.phone)) + // The addition failed or the Broker lost the entry. + let row = try XCTUnwrap(harness.coordinator.devices.first { $0.id == harness.phone.deviceID }) + harness.vault.approvalRequests.removeActiveApprover(pairingID: row.pairingID.rawValue) + XCTAssertNil(try harness.generation(of: harness.phone)) + await harness.coordinator.refresh() + let repaired = try XCTUnwrap(try harness.generation(of: harness.phone)) + XCTAssertGreaterThan(repaired, lost, "a new generation, never the old one") + XCTAssertEqual(try harness.generation(of: second), kept, "the other approver keeps its generation") + // A request goes to both. + try harness.submitRead() + try await harness.waitForRequests(2) + } + + func testNoListReadAddsAnEntryWithoutTheFlag() async throws { + try await harness.pairPhone() + await harness.coordinator.removeDevice(harness.phone.deviceID) + try await harness.addUnflaggedEntry(for: harness.phone, name: "Synthetic Phone") + await harness.coordinator.refresh() + XCTAssertEqual(harness.coordinator.devices.map(\.isApprover), [false]) + XCTAssertNil(try harness.generation(of: harness.phone)) + } + + func testNoListReadAddsAnEntryWhileTheAccountIsUnavailable() async throws { + try await harness.pairApprover() + harness.backend.accountState = .available(userRecordName: "_synthetic-account-2") + await harness.coordinator.devicesOpened() + XCTAssertEqual(harness.coordinator.account, .accountChanged) + await harness.coordinator.refresh() + XCTAssertNil(try harness.generation(of: harness.phone), "an account change suspends approvers") + } + + /// The removal hook took the pairing out of the set, and the list still + /// holds it until the write commits: a list read in that window must not + /// bring it back. + func testARemovalThatRacesTheAdditionWins() async throws { + try await harness.pairApprover() + let registry = try XCTUnwrap(harness.coordinator.services?.registry) + let devices = try await registry.list().devices + let entry = try XCTUnwrap(devices.first) + harness.coordinator.deviceWillBeRemoved(entry) + XCTAssertNil(try harness.generation(of: harness.phone)) + await harness.coordinator.refresh() + XCTAssertEqual(harness.coordinator.devices.count, 1, "the write has not committed yet") + XCTAssertNil(try harness.generation(of: harness.phone), "a list read does not undo the removal") + harness.coordinator.pairingAdded(entry.pairingID) + XCTAssertNil(try harness.generation(of: harness.phone), "nor does a late add notice") + } + + func testAnIPhoneThatUndoesThePairingRightAfterTheAddNeverStaysInTheSet() async throws { + // The iPhone confirms first, so the Mac adds it as soon as it confirms. + let code = try await harness.reachCodeEntry() + try await harness.phone.confirm() + await harness.coordinator.enterPairingCode(code) + await harness.coordinator.confirmPairing() + await harness.coordinator.refresh() + guard case .paired = harness.coordinator.pairing else { + return XCTFail("the Mac paired, not \(String(describing: harness.coordinator.pairing))") + } + XCTAssertNotNil(try harness.generation(of: harness.phone)) + let pairingID = try XCTUnwrap(harness.coordinator.devices.first).pairingID + // The iPhone cancels before it added the Mac, which undoes the pairing (ADR 0013, step 7). + await harness.phone.cancel() + await harness.coordinator.refresh() + XCTAssertTrue(harness.coordinator.devices.isEmpty) + XCTAssertNil(harness.vault.approvalRequests.activeApproverGeneration(pairingID: pairingID.rawValue)) + } + + func testAnEligibleRequestStillWaitingReachesANewlyPairedIPhoneAtItsMark() async throws { + try await harness.pairApprover() + harness.script.screenUnlocked = true + let pending = try harness.submitRead() + let second = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) + try await harness.pair(second, name: "Synthetic Phone Two") + XCTAssertTrue(harness.macSent(.approvalRequest).isEmpty, "it waits for its 20-second mark") + harness.clock.advance(by: 20) + await harness.coordinator.remoteApprovalTick() + try await harness.waitForRequests(2) + XCTAssertEqual(Set(harness.entries(pending).map(\.approverID)), [harness.phone.deviceID, second.deviceID]) + } + + func testARetiredApproverConfirmationIsRefusedAsAnUnexpectedKind() async throws { + try await harness.pairApprover() + let generation = try harness.generation(of: harness.phone) + try await harness.phone.sendRetiredApproverConfirmation(to: XCTUnwrap(harness.macDeviceID)) + await harness.coordinator.refresh() + XCTAssertTrue(harness.refusals.contains(.unexpectedKind)) + XCTAssertEqual(try harness.generation(of: harness.phone), generation, "nothing changed") + XCTAssertEqual(harness.coordinator.devices.map(\.isApprover), [true]) + } +} diff --git a/Tests/AskKeyAppTests/RemoteApprovalRenderTests.swift b/Tests/AskKeyAppTests/RemoteApprovalRenderTests.swift index c397944c..76396ec3 100644 --- a/Tests/AskKeyAppTests/RemoteApprovalRenderTests.swift +++ b/Tests/AskKeyAppTests/RemoteApprovalRenderTests.swift @@ -7,18 +7,27 @@ import XCTest @testable import AskKeyAppKit @testable import AskKeyDevices -/// Renders every new remote-approval state of the Mac App offscreen, in -/// English and Simplified Chinese, as 2x PNGs (#313): the pending-requests -/// list in the real management window, Settings → Devices with approval off -/// and on at the window's content width, each step of the approver sheet and -/// the pairing sheet's install reminder at their own size (a SwiftUI sheet -/// can't be captured offscreen), and the approval panel through the -/// production panel factory. No window is -/// ordered in. Set `REMOTE_APPROVAL_RENDER_DIRECTORY` to keep the PNGs. +/// Renders every remote-approval state of the Mac App offscreen, in English +/// and Simplified Chinese, as 2x PNGs (#313, #336): the pending-requests +/// list in the real management window; Settings → Devices at the window's +/// content width with an iPhone that approves, one paired before #336 +/// without approval, and Remove's confirmation; every step of the pairing +/// sheet with its approval statements at its own size (a SwiftUI sheet can't +/// be captured offscreen); and the approval panel through the production +/// panel factory. No window is ordered in. Set +/// `REMOTE_APPROVAL_RENDER_DIRECTORY` to keep the PNGs, and also +/// `REMOTE_APPROVAL_WINDOW_RENDERS=1` on a desktop session to render the +/// Devices section in the real Settings window, scrolled to it. @MainActor final class RemoteApprovalRenderTests: AskKeyAppTestCase { private var directory: URL! private var keepsRenders = false + /// On the CI runner a programmatic scroll of the offscreen Settings + /// window draws an empty content column (184335b), so the scrolled + /// window is rendered only when asked for. + private var rendersWindow: Bool { + keepsRenders && ProcessInfo.processInfo.environment["REMOTE_APPROVAL_WINDOW_RENDERS"] == "1" + } private var previousIcon: NSImage? override func setUp() async throws { @@ -55,128 +64,142 @@ final class RemoteApprovalRenderTests: AskKeyAppTestCase { for language in ["en", "zh-Hans"] { AppLanguage.current = language let tag = language == "en" ? "en" : "zh" + names += try await renderPairingSheet(tag: tag) let harness = try DeviceCoordinatorHarness() defer { try? harness.close() } await harness.coordinator.launch() try await harness.pairPhone() DeviceServicesHost.install(harness.coordinator) names += try await renderDevices(harness, language: language, tag: tag) - names += try await renderApproverSheet(harness, tag: tag) names += try renderPanel(tag: tag) names += try renderPendingList(harness, language: language, tag: tag) - names += try await renderPairingReminder(tag: tag) } let files = try FileManager.default.contentsOfDirectory(atPath: directory.path).filter { $0.hasSuffix(".png") } XCTAssertEqual(Set(files), Set(names.map { $0 + ".png" })) - XCTAssertEqual(names.count, 44) + XCTAssertEqual(names.count, rendersWindow ? 32 : 30) } // MARK: Settings → Devices - /// The Devices section at the management window's content width. A - /// programmatic scroll of the offscreen Settings window drew nothing on - /// the CI runner, so the real window's Devices captures come from the - /// desktop screenshot flow (30/35 off, 44/47 on). + /// The Devices section at the management window's content width: an + /// iPhone that approves, Remove's confirmation, and an iPhone paired + /// before #336 without approval next to it. A programmatic scroll of the + /// offscreen Settings window drew nothing on the CI runner, so the real + /// window's capture is taken only when asked for; CI's desktop + /// screenshot flow captures the window (30/35, 43/45). private func renderDevices(_ harness: DeviceCoordinatorHarness, language: String, tag: String) async throws -> [String] { let model = DevicesSettingsModel(coordinator: harness.coordinator) let width = WorkspaceVisualContract.windowWidth - WorkspaceVisualContract.sidebarWidth var names: [String] = [] - for enabled in [false, true] { - try await drain(harness) - if enabled { try await enable(harness) } - let name = "\(enabled ? "02" : "01")-\(tag)-devices-approval-\(enabled ? "on" : "off")" + func section(_ name: String) throws { try renderAlone(DevicesSettingsSection(model: model) .padding(Theme.Spacing.xxl) .frame(width: width) .background(Theme.windowBackground), as: name) names.append(name) } - XCTAssertTrue(try XCTUnwrap(harness.coordinator.devices.first).isApprover) try await drain(harness) - // Off again for the sheet's steps; turning it off asks for nothing. - await model.setApprover(try XCTUnwrap(harness.coordinator.devices.first), enabled: false) - XCTAssertFalse(try XCTUnwrap(harness.coordinator.devices.first).isApprover) + let row = try XCTUnwrap(harness.coordinator.devices.first) + XCTAssertTrue(row.isApprover, "pairing made the iPhone an approver") + try section("01-\(tag)-devices-iphone-approves") + model.requestRemoval(row) + try section("03-\(tag)-devices-remove-confirmation") + model.cancelRemoval() + let older = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) + try await harness.addUnflaggedEntry(for: older, name: "Older iPhone") + try await drain(harness) + XCTAssertEqual(harness.coordinator.devices.map(\.isApprover), [true, false]) + try section("02-\(tag)-devices-iphone-cannot-approve") + if rendersWindow { names.append(try renderSettingsWindow(language: language, tag: tag)) } return names } - // MARK: Approver sheet + /// Settings in the real management window, built as + /// `ensureManagementWindow` builds it, scrolled to the Devices section. + private func renderSettingsWindow(language: String, tag: String) throws -> String { + let fixture = try NoticeLayoutFixtures.Model(language: language, state: .management, recovery: false, broker: false) + defer { fixture.close() } + let navigation = ManagementNavigation() + navigation.route = .settings + let window = ManagementWindowConfiguration.makeWindow(rootView: SettingsView(navigation: navigation) + .environment(fixture.vault) + .environment(\.locale, fixture.vault.appLocale)) + defer { window.close() } + ManagementWindowConfiguration.apply(to: window) + window.appearance = NSAppearance(named: .aqua) + settle(window) + XCTAssertFalse(window.isVisible) + let scroll = try settingsScrollView(in: try XCTUnwrap(window.contentView)) + let document = try XCTUnwrap(scroll.documentView) + let bottom = max(0, document.bounds.height - scroll.contentView.bounds.height) + scroll.contentView.scroll(to: NSPoint(x: 0, y: document.isFlipped ? bottom : 0)) + scroll.reflectScrolledClipView(scroll.contentView) + settle(window) + let name = "16-\(tag)-settings-window-devices" + try export(try XCTUnwrap(window.contentView?.superview), as: name, contentFrom: WorkspaceVisualContract.sidebarWidth) + return name + } + + private func settingsScrollView(in root: NSView) throws -> NSScrollView { + var pending = [root] + var found: [NSScrollView] = [] + while let view = pending.popLast() { + if let scroll = view as? NSScrollView, + scroll.convert(scroll.bounds, to: nil).midX > WorkspaceVisualContract.sidebarWidth { + found.append(scroll) + } + pending.append(contentsOf: view.subviews) + } + return try XCTUnwrap(found.max { $0.bounds.height < $1.bounds.height }) + } + + // MARK: Pairing sheet - private func renderApproverSheet(_ harness: DeviceCoordinatorHarness, tag: String) async throws -> [String] { + /// Every step of the pairing sheet: the QR code with the install reminder + /// and the approval statement, the code matched with what a request + /// sends, system authentication, waiting for the iPhone, and paired. + private func renderPairingSheet(tag: String) async throws -> [String] { + let harness = try DeviceCoordinatorHarness() + defer { try? harness.close() } + await harness.coordinator.launch() let coordinator = harness.coordinator let model = DevicesSettingsModel(coordinator: coordinator) - let mac = try XCTUnwrap(harness.macDeviceID) var names: [String] = [] - @discardableResult - func sheet(_ number: Int, _ label: String) throws -> NSView { - let name = String(format: "%02d-%@-approver-sheet-%@", number, tag, label) + func sheet(_ number: Int, _ label: String) throws { + let name = String(format: "%02d-%@-pairing-%@", number, tag, label) names.append(name) - return try renderAlone(ApproverConfirmationSheet(model: model), as: name) - } - func wrong(_ code: ApproverCode) -> String { String(format: "%06d", ((Int(code.digits) ?? 0) + 1) % 1_000_000) } - func remaining() -> Int { - if case .waitingForIPhone(_, _, let remaining)? = coordinator.approverConfirmation { return remaining } - return 0 - } - func type(_ code: String, on phone: SimulatedPairingPhone, until done: () -> Bool) async throws { - try await phone.confirmApprover(typing: code, for: mac) - try await refresh(coordinator, until: done) - } - let row = try XCTUnwrap(coordinator.devices.first { $0.id == harness.phone.deviceID }) - await model.setApprover(row, enabled: true) - _ = try sheet(3, "intro") - coordinator.approverConfirmation = .authenticating(device: row) - _ = try sheet(4, "authenticating") - coordinator.approverConfirmation = nil - - await model.continueApprover() - let code = try XCTUnwrap(coordinator.approverCode) - // The PNGs show a fixed placeholder, never a code that was issued. - let placeholder = try XCTUnwrap(ApproverCode(typed: "123456")) - func codeSheet(_ number: Int, _ label: String) throws { - coordinator.approverCode = placeholder - defer { coordinator.approverCode = code } - _ = try sheet(number, label) - } - try codeSheet(5, "code") - try await type(wrong(code), on: harness.phone, until: { remaining() == 2 }) - try codeSheet(6, "wrong-code") - try await type(wrong(code), on: harness.phone, until: { remaining() == 1 }) - try await type(wrong(code), on: harness.phone, until: { coordinator.approverConfirmation == .ended(.tooManyWrongCodes) }) - _ = try sheet(7, "too-many-wrong-codes") - - await model.startApproverAgain() - harness.clock.advance(by: DeviceCoordinator.approverCodeLifetime + 1) - _ = await coordinator.approverLoopStep() - _ = try sheet(8, "expired") - - try await drain(harness) - let spare = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) - try await harness.pair(spare, name: "Spare iPhone") - await model.startApproverAgain() - try await type(try XCTUnwrap(coordinator.approverCode).formatted, on: spare, until: { - coordinator.approverConfirmation == .ended(.enteredOnOtherDevice(name: "Spare iPhone")) - }) - _ = try sheet(9, "entered-on-other-device") - let ends: [(ApproverConfirmationEndReason, String)] = [ - (.managementRequired, "management-required"), (.unavailable, "unavailable"), - (.authenticationCancelled, "authentication-cancelled"), (.authenticationFailed, "authentication-failed"), - (.deviceRemoved, "device-removed"), (.notSaved, "not-saved"), - ] - let other = coordinator.approverConfirmation - for (offset, (reason, label)) in ends.enumerated() { - coordinator.approverConfirmation = .ended(reason) - _ = try sheet(17 + offset, "ended-" + label) + try renderAlone(DevicePairingSheet(model: model), as: name) } - coordinator.approverConfirmation = other - - await model.startApproverAgain() - try await type(try XCTUnwrap(coordinator.approverCode).formatted, on: harness.phone, until: { - if case .enabled? = coordinator.approverConfirmation { return true } - return false - }) - guard case .enabled = coordinator.approverConfirmation else { throw SyntheticRemoteFailure() } - _ = try sheet(10, "enabled") - model.closeApproverSheet() + await model.pairDevice() + guard case .qrCode(let text, _) = try XCTUnwrap(model.sheet).stage else { throw SyntheticRemoteFailure() } + XCTAssertEqual(model.sheet?.showsInstallReminder, true) + try sheet(4, "qr-code") + try await harness.phone.scan(text) + await coordinator.refresh() + try sheet(5, "waiting") + try await harness.phone.poll() + await coordinator.refresh() + try sheet(6, "code-entry") + let shown = await harness.phone.shownCode() + // The code matched; the person has not confirmed yet. + harness.script.authenticationResults = [.cancelled] + model.codeEntry = try XCTUnwrap(shown) + await model.confirm() + coordinator.pairingFeedback = nil + XCTAssertNotNil(model.sheet?.requestContents, "the sheet says what a request sends") + try sheet(7, "code-accepted") + coordinator.isAuthenticatingPairing = true + try sheet(8, "authenticating") + coordinator.isAuthenticatingPairing = false + await model.confirm() + guard case .waitingForIPhoneConfirmation = coordinator.pairing else { throw SyntheticRemoteFailure() } + try sheet(9, "waiting-for-iphone") + try await harness.phone.confirm() + try await harness.phone.poll() + await coordinator.refresh() + guard case .paired = coordinator.pairing else { throw SyntheticRemoteFailure() } + try sheet(10, "paired") + await model.closeSheet() return names } @@ -264,21 +287,6 @@ final class RemoteApprovalRenderTests: AskKeyAppTestCase { return [name] } - // MARK: Pairing sheet - - private func renderPairingReminder(tag: String) async throws -> [String] { - let harness = try DeviceCoordinatorHarness() - defer { try? harness.close() } - await harness.coordinator.launch() - let model = DevicesSettingsModel(coordinator: harness.coordinator) - await model.pairDevice() - XCTAssertEqual(model.sheet?.showsInstallReminder, true) - let name = "16-\(tag)-pairing-install-reminder" - _ = try renderAlone(DevicePairingSheet(model: model), as: name) - await model.closeSheet() - return [name] - } - // MARK: Coordinator /// The Devices section's window starts a poll when it appears. A refresh @@ -291,28 +299,6 @@ final class RemoteApprovalRenderTests: AskKeyAppTestCase { try await harness.waitUntil { harness.coordinator.pollTask == nil } } - private func refresh(_ coordinator: DeviceCoordinator, until done: () -> Bool) async throws { - for _ in 0..<100 where !done() { - await coordinator.refresh() - if done() { return } - try await Task.sleep(for: .milliseconds(10)) - } - XCTAssertTrue(done(), "the Mac processed the iPhone's message") - } - - /// Turns approval on through the sheet's coordinator steps. - private func enable(_ harness: DeviceCoordinatorHarness) async throws { - let coordinator = harness.coordinator - await coordinator.startApproverConfirmation(for: harness.phone.deviceID) - let code = try XCTUnwrap(coordinator.approverCode, "the sheet shows a code") - try await harness.phone.confirmApprover(typing: code.formatted, for: XCTUnwrap(harness.macDeviceID)) - try await refresh(coordinator) { - if case .enabled? = coordinator.approverConfirmation { return true } - return false - } - coordinator.cancelApproverConfirmation() - } - // MARK: Rendering private func settle(_ window: NSWindow) { @@ -349,6 +335,7 @@ final class RemoteApprovalRenderTests: AskKeyAppTestCase { } } XCTAssertGreaterThan(colors.count, 8, "\(name) drew nothing") + XCTAssertGreaterThan(colors.count, 1, "\(name) is a single color") let png = try XCTUnwrap(bitmap.representation(using: .png, properties: [:])) XCTAssertGreaterThan(png.count, 5_000, "\(name) did not render") try png.write(to: directory.appendingPathComponent(name + ".png"), options: .atomic) diff --git a/Tests/AskKeyAppTests/RemoteApprovalRevocationTests.swift b/Tests/AskKeyAppTests/RemoteApprovalRevocationTests.swift index cc57757a..e3fd71f1 100644 --- a/Tests/AskKeyAppTests/RemoteApprovalRevocationTests.swift +++ b/Tests/AskKeyAppTests/RemoteApprovalRevocationTests.swift @@ -58,26 +58,9 @@ final class RemoteApprovalRevocationTests: AskKeyAppTestCase { XCTAssertEqual(try harness.state(pending), .pending, "a later Deny is refused too", file: file, line: line) } - func testTurningApprovalOffRevokesBeforeClosing() async throws { - let (pending, request) = try await outstandingRead() - let order = watchClosingOrder() - let row = try XCTUnwrap(harness.coordinator.devices.first) - let disabled = await harness.coordinator.disableApprover(row) - XCTAssertTrue(disabled) - XCTAssertNil(generation) - XCTAssertEqual(harness.coordinator.devices.first?.isApprover, false) - let outcomes = try await harness.phoneClosed().map(\.outcome) - XCTAssertEqual(outcomes, [.cancelled]) - XCTAssertEqual(order.stillActive, [false]) - try await assertLaterDecisionsRefused(request, pending) - // A new request no longer goes to it. - try harness.submitRead() - await harness.coordinator.remoteApprovalTick() - XCTAssertEqual(harness.macSent(.approvalRequest).count, 1) - } - + /// Removing the iPhone on the Mac is how approval stops (#336). func testRemovalRevokesBeforeClosing() async throws { - let (pending, _) = try await outstandingRead() + let (pending, request) = try await outstandingRead() let order = watchClosingOrder() let removed = await harness.coordinator.removeDevice(harness.phone.deviceID) XCTAssertTrue(removed) @@ -86,6 +69,13 @@ final class RemoteApprovalRevocationTests: AskKeyAppTestCase { XCTAssertEqual(harness.macSent(.approvalClosed).count, 1) XCTAssertEqual(order.stillActive, [false]) XCTAssertTrue(harness.entries(pending).isEmpty) + try await assertLaterDecisionsRefused(request, pending) + // A new request no longer goes to it, and no list read adds it back. + try harness.submitRead() + await harness.coordinator.refresh() + await harness.coordinator.remoteApprovalTick() + XCTAssertEqual(harness.macSent(.approvalRequest).count, 1) + XCTAssertNil(generation) } func testUnpairNoticeRevokesThroughTheRemovalHook() async throws { @@ -143,7 +133,9 @@ final class RemoteApprovalRevocationTests: AskKeyAppTestCase { harness.vault.stopDeviceServicesForLocalErase() XCTAssertNil(generation) harness.coordinator.stopForLocalErase() - XCTAssertTrue(harness.coordinator.remoteRequests.isEmpty) + // Nothing stays outstanding; a request still pending stays on the Mac. + XCTAssertTrue(harness.coordinator.remoteRequests.values.allSatisfy { $0.entries.isEmpty && $0.phase == .stayingOnMac }) + XCTAssertTrue(harness.coordinator.closedMessages.isEmpty) XCTAssertFalse(harness.script.activityHeld) } diff --git a/Tests/AskKeyAppTests/RemoteApprovalSendingTests.swift b/Tests/AskKeyAppTests/RemoteApprovalSendingTests.swift index a939bf4d..fb72362c 100644 --- a/Tests/AskKeyAppTests/RemoteApprovalSendingTests.swift +++ b/Tests/AskKeyAppTests/RemoteApprovalSendingTests.swift @@ -25,7 +25,11 @@ final class RemoteApprovalSendingTests: AskKeyAppTestCase { } func testWithoutAnApproverNothingIsSentAndNoCloudKitRequestIsMade() async throws { + // An iPhone paired before #336 without approval: its entry has no flag. try await harness.pairPhone() + await harness.coordinator.removeDevice(harness.phone.deviceID) + try await harness.addUnflaggedEntry(for: harness.phone, name: "Synthetic Phone") + XCTAssertEqual(harness.coordinator.devices.map(\.isApprover), [false]) try harness.addCredential() let sentBefore = harness.transport.sentEnvelopes.count try harness.submitRead() @@ -42,11 +46,13 @@ final class RemoteApprovalSendingTests: AskKeyAppTestCase { XCTAssertEqual(harness.script.activityBegins, 0) } - func testRequestThatAppearedBeforeApprovalWasOnStaysOnTheMac() async throws { - try await harness.pairPhone() + func testRequestThatAppearedBeforeTheFirstIPhonePairedStaysOnTheMac() async throws { try harness.addCredential() let pending = try harness.submitRead() - try await harness.enableApprover(harness.phone) + XCTAssertNil(harness.coordinator.services, "this Mac has no device identity yet") + XCTAssertEqual(harness.coordinator.remoteRequests[pending.requestID]?.phase, .stayingOnMac) + try await harness.pairPhone() + XCTAssertNotNil(try harness.generation(of: harness.phone)) harness.coordinator.approvalRequestsChanged() await harness.coordinator.remoteApprovalTick() XCTAssertTrue(harness.macSent(.approvalRequest).isEmpty) @@ -56,11 +62,10 @@ final class RemoteApprovalSendingTests: AskKeyAppTestCase { } func testUnlockedRequestNotEligibleWhenCreatedStaysOnTheMac() async throws { - try await harness.pairPhone() try harness.addCredential() harness.script.screenUnlocked = true let pending = try harness.submitRead() - try await harness.enableApprover(harness.phone) + try await harness.pairPhone() harness.clock.advance(by: 20) await harness.coordinator.remoteApprovalTick() XCTAssertTrue(harness.macSent(.approvalRequest).isEmpty) @@ -197,7 +202,6 @@ final class RemoteApprovalSendingTests: AskKeyAppTestCase { try await harness.pairApprover() let second = SimulatedPairingPhone(transport: harness.transport, clock: harness.clock) try await harness.pair(second, name: "Synthetic Phone Two") - try await harness.enableApprover(second) harness.transport.failNextSends(with: [.networkUnavailable]) let pending = try harness.submitRead() try await harness.waitForRequests(2) diff --git a/Tests/AskKeyAppTests/RemoteApprovalTestSupport.swift b/Tests/AskKeyAppTests/RemoteApprovalTestSupport.swift index b75bdf7c..6c292cf3 100644 --- a/Tests/AskKeyAppTests/RemoteApprovalTestSupport.swift +++ b/Tests/AskKeyAppTests/RemoteApprovalTestSupport.swift @@ -16,10 +16,10 @@ extension DeviceCoordinatorHarness { var vault: Vault { library.vault } - /// Pairs the simulated iPhone and turns its approval on through the sheet. + /// Pairs the simulated iPhone, which makes it an approver (#336), and + /// adds an Ask credential. func pairApprover() async throws { try await pairPhone() - try await enableApprover(phone) try addCredential() } @@ -43,18 +43,16 @@ extension DeviceCoordinatorHarness { await coordinator.refresh() } - /// Opens the approver sheet for `phone`, types the shown code on it and - /// lets the Mac process the confirmation. - func enableApprover(_ phone: SimulatedPairingPhone) async throws { - await coordinator.startApproverConfirmation(for: phone.deviceID) - let code = try XCTUnwrap(coordinator.approverCode, "the sheet shows a code") - try await phone.confirmApprover(typing: code.formatted, for: XCTUnwrap(macDeviceID)) + /// An entry without the approval flag, as a pairing made before #336 + /// left it: the Vault's pairing authorization allows the add, and the + /// default initializer never sets the flag. + func addUnflaggedEntry(for other: SimulatedPairingPhone, name: String) async throws { + let card = try DeviceCard.make(identity: other.identity, platform: .iOS, createdAt: clock.now()) + let entry = PairedDevice(card: card, pairingID: try XCTUnwrap(PairingID(rawValue: RandomBytes.make(16))), + displayName: name, pairedAt: clock.now()) + try vault.authorizeDevicePairing(with: entry.deviceID, using: .allow) + try await XCTUnwrap(coordinator.services).registry.apply(.add(entry)) await coordinator.refresh() - guard case .enabled = coordinator.approverConfirmation else { - XCTFail("approval is on, not \(String(describing: coordinator.approverConfirmation))") - throw SyntheticRemoteFailure() - } - coordinator.cancelApproverConfirmation() } func addCredential(name: String = DeviceCoordinatorHarness.credentialName) throws { diff --git a/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift b/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift index 0719c93e..6e4a5075 100644 --- a/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift +++ b/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift @@ -29,33 +29,36 @@ final class ApprovalFlagTests: XCTestCase { enabled: true)), .dropped) } - func testEveryListChangeKeepsTheFlagAndPairingAgainClearsIt() throws { + func testEveryListChangeKeepsTheFlagAndAnAddStoresTheFlagItCarries() throws { let identity = SoftwareDeviceIdentity() let device = try entry(identity) let id = device.deviceID - var list = try PairedDeviceList(devices: [device, try entry(pairing: 2, name: "Other")]) - try list.apply(.setApprover(id, pairingID: device.pairingID, enabled: true)) + var flagged = device + flagged.isApprover = true + var list = try PairedDeviceList(devices: [flagged, try entry(pairing: 2, name: "Other")]) let changes: [PairedDeviceChange] = [ .rename(id, pairingID: device.pairingID, displayName: "Renamed"), .recordReached(id, pairingID: device.pairingID, at: now.addingTimeInterval(5)), .recordDeliveryCheck(id, pairingID: device.pairingID, result: .pending(sentAt: now.addingTimeInterval(6))), .recordDeliveryCheck(id, pairingID: device.pairingID, result: .noReply(sentAt: now.addingTimeInterval(6))), .recordDeliveryCheck(id, pairingID: device.pairingID, result: .replied(at: now.addingTimeInterval(7))), - .add(device), + .add(flagged), .remove(list.devices[1].deviceID, pairingID: list.devices[1].pairingID), ] for change in changes { try list.apply(change) XCTAssertTrue(try XCTUnwrap(list.device(id)).isApprover, "\(change) keeps the flag") } - var flagged = device - flagged.isApprover = true try list.apply(.remove(id, pairingID: device.pairingID)) try list.apply(.add(flagged)) - XCTAssertFalse(try XCTUnwrap(list.device(id)).isApprover, "a new entry starts with the flag off") - try list.apply(.setApprover(id, pairingID: device.pairingID, enabled: true)) + XCTAssertTrue(try XCTUnwrap(list.device(id)).isApprover, "an add stores the flag the pairing set (#336)") try list.apply(.add(try entry(identity, pairing: 3))) - XCTAssertFalse(try XCTUnwrap(list.device(id)).isApprover, "pairing again gives a new entry with the flag off") + XCTAssertFalse(try XCTUnwrap(list.device(id)).isApprover, "an entry added without the flag replaces it as given") + var again = try entry(identity, pairing: 4) + again.isApprover = true + try list.apply(.add(again)) + XCTAssertEqual(list.device(id)?.pairingID, again.pairingID) + XCTAssertTrue(try XCTUnwrap(list.device(id)).isApprover, "pairing again stores the new entry's flag") } func testSerializationVersionTwoCarriesTheFlag() throws { @@ -144,7 +147,7 @@ final class ApprovalFlagTests: XCTestCase { try await mac.poll() let new = try await fixture.macEntryForPhone() XCTAssertNotEqual(new.pairingID, old.pairingID) - XCTAssertFalse(new.isApprover, "pairing again starts with approval off") + XCTAssertTrue(new.isApprover, "pairing again flags the new entry (#336)") XCTAssertEqual(fixture.removals.entries.map(\.pairingID), [old.pairingID], "the replaced entry was announced") XCTAssertTrue(fixture.removals.allBeforeCommit) diff --git a/Tests/AskKeyDevicesTests/PairingApproverTests.swift b/Tests/AskKeyDevicesTests/PairingApproverTests.swift new file mode 100644 index 00000000..f31c6a03 --- /dev/null +++ b/Tests/AskKeyDevicesTests/PairingApproverTests.swift @@ -0,0 +1,86 @@ +@testable import AskKeyDevices +import AskKeyDevicesTestSupport +import XCTest + +/// Pairing makes the approver (ADR 0014 → Approvers, #336): the entry a +/// pairing adds carries the approval flag on both sides when a macOS +/// initiator pairs with an iOS responder, and no other pairing sets it. +final class PairingApproverTests: XCTestCase { + func testPairingAMacWithAnIPhoneFlagsTheEntryOnBothSides() async throws { + let harness = DeviceHarness() + let mac = harness.makeDevice(.macOS) + let phone = harness.makeDevice(.iOS) + try await harness.pair(mac, phone) + let macEntry = try await XCTUnwrapAsync(try await mac.entry(for: phone)) + let phoneEntry = try await XCTUnwrapAsync(try await phone.entry(for: mac)) + XCTAssertTrue(macEntry.isApprover, "the Mac's entry for the iPhone: it may decide the Mac's requests") + XCTAssertTrue(phoneEntry.isApprover, "the iPhone's entry for the Mac: it accepts the Mac's requests") + XCTAssertEqual(macEntry.pairingID, phoneEntry.pairingID) + } + + func testPairingTwoMacsTwoIPhonesOrAnIPhoneInitiatorAddsNoFlag() async throws { + for (initiator, responder) in [(DevicePlatform.macOS, DevicePlatform.macOS), (.iOS, .iOS), (.iOS, .macOS)] { + let harness = DeviceHarness() + let first = harness.makeDevice(initiator) + let second = harness.makeDevice(responder) + try await harness.pair(first, second) + let firstEntry = try await XCTUnwrapAsync(try await first.entry(for: second)) + let secondEntry = try await XCTUnwrapAsync(try await second.entry(for: first)) + XCTAssertFalse(firstEntry.isApprover, "\(initiator) initiator, \(responder) responder") + XCTAssertFalse(secondEntry.isApprover, "\(initiator) initiator, \(responder) responder") + } + } + + func testPairingAgainFlagsTheNewEntry() async throws { + let harness = DeviceHarness() + let mac = harness.makeDevice(.macOS) + let phone = harness.makeDevice(.iOS) + try await harness.pair(mac, phone) + let old = try await XCTUnwrapAsync(try await mac.entry(for: phone)) + harness.clock.advance(by: 11 * 60) // The first session has expired. + try await harness.pair(mac, phone) + let macEntry = try await XCTUnwrapAsync(try await mac.entry(for: phone)) + let phoneEntry = try await XCTUnwrapAsync(try await phone.entry(for: mac)) + XCTAssertNotEqual(macEntry.pairingID, old.pairingID, "pairing again gives a new entry") + XCTAssertEqual(macEntry.pairingID, phoneEntry.pairingID) + XCTAssertTrue(macEntry.isApprover) + XCTAssertTrue(phoneEntry.isApprover) + } + + /// The Mac adds the iPhone and seals a request before the iPhone holds + /// the Mac's confirmation: the iPhone keeps it for the session and + /// processes it once the Mac is listed with its flag. + func testARequestFromTheSessionPeerIsHeldAndProcessedOnceTheMacIsAdded() async throws { + let harness = DeviceHarness() + let inbox = ApprovalInbox() + let mac = harness.makeDevice(.macOS) + let phone = harness.makeDevice(.iOS, approvalHandler: inbox.handler) + let qr = try await mac.messenger.startPairing(displayName: "Studio Mac") + try await phone.messenger.joinPairing(scannedText: qr.text, displayName: "Pocket Phone") + try await mac.poll() + try await phone.poll() + try await mac.poll() + harness.transport.delaying(.pairingConfirmation, from: mac.id) + try await phone.confirm() + try await mac.confirm() + try await mac.poll() + let entry = try await XCTUnwrapAsync(try await mac.entry(for: phone)) + XCTAssertTrue(entry.isApprover, "the Mac added the iPhone with its flag") + let sealed = try mac.messenger.sealer.sealApprovalRequest( + ApprovalVectorTests.vectorDisplay, bindingDigest: ApprovalFixture.binding, + deadline: harness.clock.now().addingTimeInterval(60), launchTime: harness.clock.now(), offers: .denyOnly, + timedDuration: 0, to: entry) + try await harness.transport.send(sealed.sealed.envelope) + + let early = try await phone.poll() + XCTAssertEqual(early.outcomes[sealed.sealed.envelope.recordName], .keptForSession) + XCTAssertTrue(inbox.messages.isEmpty, "the handler has not seen it") + await XCTAssertNilAsync(try await phone.entry(for: mac)) + + harness.transport.releaseDelayed() + let later = try await phone.poll() + XCTAssertEqual(later.outcomes[sealed.sealed.envelope.recordName], .processed) + XCTAssertEqual(inbox.messages.map(\.digest), [sealed.requestDigest]) + XCTAssertEqual(inbox.messages.first?.sender.isApprover, true, "the Mac is listed with the iPhone's flag") + } +} diff --git a/Tests/AskKeyE2ETests/DevicesE2ETests.swift b/Tests/AskKeyE2ETests/DevicesE2ETests.swift index 50197d61..6e295895 100644 --- a/Tests/AskKeyE2ETests/DevicesE2ETests.swift +++ b/Tests/AskKeyE2ETests/DevicesE2ETests.swift @@ -12,23 +12,22 @@ final class DevicesE2ETests: E2EBaseCase { XCTAssertTrue(app.windows["settings"].sheets.firstMatch.waitForExistence(timeout: 8), "Pair a Device… opened no sheet") } - /// With exactly one paired iPhone, the runner turns **Approve agent - /// requests** on: the sheet first says what leaves the Mac, then shows - /// the code after (simulated) system authentication, the code is in no - /// accessibility label or value, and the iPhone typing it turns approval - /// on (#313). - func testApproveAgentRequestsTurnsOnWithTheCodeTypedOnTheIPhone() throws { + /// Pairing makes the iPhone an approver (#336): with exactly one paired + /// iPhone, its row says it approves agent requests, and the runner's real + /// clicks on **Remove** and its confirmation, the Mac's only way to stop + /// an iPhone approving, take the row away (#299, #300). + func testPairedIPhoneApprovesAgentRequestsUntilRemoved() throws { let page = openDevicesSettings(language: "en") pairSyntheticIPhone(page: page) - clickApproverToggle(page: page) - XCTAssertTrue(app.windows["settings"].sheets.firstMatch.waitForExistence(timeout: 8), "the switch opened no sheet") - click("devices-approver-continue") - XCTAssertTrue(app.descendants(matching: .any)["devices-approver-waiting"].waitForExistence(timeout: 8), "no code") - try writeAccessibilityTreeForApproverCheck() - try deviceFixture("approver-check-hidden") - try deviceFixture("approver-confirm") - click("devices-approver-done") - waitUntilShown("devices-approver-caption", "Agent requests can also be decided on this iPhone.") + page.scroll(byDeltaX: 0, deltaY: -900) // the whole row in view + waitUntilShown("devices-row-approval", "Can approve agent requests.") + clickInPage("devices-remove", page: page) + clickInPage("devices-confirm-remove", page: page) + let rename = app.buttons["devices-rename"].firstMatch + let gone = NSPredicate { _, _ in !rename.exists } + XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: gone, object: nil)], timeout: 8), .completed, + "the removed iPhone is still listed") + XCTAssertTrue(app.staticTexts["settings-devices-empty"].firstMatch.waitForExistence(timeout: 8), "No empty list row") } } @@ -83,23 +82,12 @@ extension E2EBaseCase { for _ in 0..<6 where !rename.isHittable { page.scroll(byDeltaX: 0, deltaY: -300) } } - /// The real click on the one paired iPhone's **Approve agent requests** switch. - func clickApproverToggle(page: XCUIElement) { - let toggle = app.descendants(matching: .any)["devices-approver-toggle"].firstMatch - XCTAssertTrue(toggle.waitForExistence(timeout: 8), "Missing control: devices-approver-toggle") - for _ in 0..<6 where !toggle.isHittable { page.scroll(byDeltaX: 0, deltaY: -300) } - XCTAssertTrue(toggle.isHittable, "Control is not visible: devices-approver-toggle") - toggle.click() - } - - /// Writes the approver sheet's accessibility tree, with every identifier, - /// label and value, for the App-side check that the code is not in it. - /// The code shows only in this sheet; a snapshot of the whole Settings - /// window can hang in CI once a text field had focus (#288). - func writeAccessibilityTreeForApproverCheck() throws { - let sheet = app.windows["settings"].sheets.firstMatch - XCTAssertTrue(sheet.waitForExistence(timeout: 8)) - try Data(sheet.debugDescription.utf8).write( - to: runDirectory.appendingPathComponent("approver-accessibility-tree.txt"), options: .atomic) + /// The runner's real click on a Devices button, scrolled into view first. + func clickInPage(_ identifier: String, page: XCUIElement, file: StaticString = #filePath, line: UInt = #line) { + let button = app.buttons[identifier].firstMatch + XCTAssertTrue(button.waitForExistence(timeout: 8), "Missing control: \(identifier)", file: file, line: line) + for _ in 0..<6 where !button.isHittable { page.scroll(byDeltaX: 0, deltaY: -300) } + XCTAssertTrue(button.isHittable, "Control is not visible: \(identifier)", file: file, line: line) + button.click() } } diff --git a/Tests/AskKeyE2ETests/ScreenshotE2ETests.swift b/Tests/AskKeyE2ETests/ScreenshotE2ETests.swift index 8f514ea7..ad574a51 100644 --- a/Tests/AskKeyE2ETests/ScreenshotE2ETests.swift +++ b/Tests/AskKeyE2ETests/ScreenshotE2ETests.swift @@ -344,23 +344,23 @@ final class ScreenshotE2ETests: E2EBaseCase { } func testDevicesScreensInEnglish() throws { - try captureDevicesScreens(language: "en", tag: "en", firstNumber: 30, emptyNumber: 40, approverNumber: 42) + try captureDevicesScreens(language: "en", tag: "en", firstNumber: 30, emptyNumber: 40, approvalNumber: 42) } func testDevicesScreensInChinese() throws { - try captureDevicesScreens(language: "zh-Hans", tag: "zh", firstNumber: 35, emptyNumber: 41, approverNumber: 45) + try captureDevicesScreens(language: "zh-Hans", tag: "zh", firstNumber: 35, emptyNumber: 41, approvalNumber: 44) } - /// The empty list, the sheet's QR code, waiting and code entry steps, the list with one iPhone, - /// the approver sheet's first and last steps and the list with approval on, and iCloud signed out. The runner - /// clicks Pair a Device… and Approve agent requests; the fixture plays the iPhone, including - /// typing the codes. Texts are found by identifier: after the code field had focus, + /// The empty list, the sheet's QR code, waiting and code entry steps, the paired step that says the + /// iPhone now approves agent requests, the list with one approving iPhone, Remove's confirmation, and + /// iCloud signed out (#336). The runner clicks Pair a Device… and Remove; the fixture plays the + /// iPhone, including typing its code. Texts are found by identifier: after the code field had focus, /// whole-window snapshots can hang on the cursor's remote element in CI. private func captureDevicesScreens(language: String, tag: String, firstNumber: Int, emptyNumber: Int, - approverNumber: Int) throws { + approvalNumber: Int) throws { func name(_ offset: Int, _ label: String) -> String { String(format: "%02d-%@-%@", firstNumber + offset, tag, label) } - func approverName(_ offset: Int, _ label: String) -> String { - String(format: "%02d-%@-%@", approverNumber + offset, tag, label) + func approvalName(_ offset: Int, _ label: String) -> String { + String(format: "%02d-%@-%@", approvalNumber + offset, tag, label) } func fixture(_ command: String) throws { try deviceFixture(command) } let page = openDevicesSettings(language: language) @@ -378,6 +378,8 @@ final class ScreenshotE2ETests: E2EBaseCase { XCTAssertTrue(app.textFields["devices-pairing-code"].waitForExistence(timeout: 8)) captureSheet(name(3, "devices-pairing-code-entry")) try fixture("phone-complete") + XCTAssertTrue(app.buttons["devices-pairing-done"].waitForExistence(timeout: 8)) + captureSheet(approvalName(0, "devices-pairing-paired")) click("devices-pairing-done") try fixture("phone-poll") let rename = app.buttons["devices-rename"].firstMatch @@ -385,21 +387,13 @@ final class ScreenshotE2ETests: E2EBaseCase { for _ in 0..<6 where !rename.isHittable { page.scroll(byDeltaX: 0, deltaY: -300) } page.scroll(byDeltaX: 0, deltaY: -900) // the whole row in view, whatever the language's line breaks waitUntilShown("devices-row-reachability", language == "en" ? "Last reached" : "\u{4E0A}\u{6B21}\u{8054}\u{7CFB}") + waitUntilShown("devices-row-approval", language == "en" ? "Can approve" : "\u{53EF}\u{4EE5}\u{5BA1}\u{6279}") attachScreenshot(of: app.windows["settings"].firstMatch, name(0, "devices-list")) - clickApproverToggle(page: page) - XCTAssertTrue(app.buttons["devices-approver-continue"].waitForExistence(timeout: 8), "No approver sheet") - captureSheet(approverName(0, "devices-approver-intro")) - // No capture shows the code: the offscreen renders draw a placeholder for that step. - click("devices-approver-continue") - XCTAssertTrue(app.descendants(matching: .any)["devices-approver-waiting"].waitForExistence(timeout: 8)) - try fixture("approver-confirm") - XCTAssertTrue(app.buttons["devices-approver-done"].waitForExistence(timeout: 8)) - captureSheet(approverName(1, "devices-approver-enabled")) - click("devices-approver-done") - waitUntilShown("devices-approver-caption", language == "en" - ? "can also be decided" : "Agent \u{8BF7}\u{6C42}\u{4E5F}\u{53EF}\u{4EE5}") - page.scroll(byDeltaX: 0, deltaY: -900) // the whole row in view - attachScreenshot(of: app.windows["settings"].firstMatch, approverName(2, "devices-approval-on")) + clickInPage("devices-remove", page: page) + XCTAssertTrue(app.buttons["devices-confirm-remove"].waitForExistence(timeout: 8), "No removal confirmation") + page.scroll(byDeltaX: 0, deltaY: -900) // the row and its confirmation in view + attachScreenshot(of: app.windows["settings"].firstMatch, approvalName(1, "devices-remove-confirmation")) + clickInPage("devices-cancel-remove", page: page) try fixture("account-signed-out") waitUntilShown("settings-devices-notice", language == "en" ? "iCloud is signed out" : "iCloud \u{5DF2}\u{9000}\u{51FA}\u{767B}\u{5F55}") attachScreenshot(of: app.windows["settings"].firstMatch, name(4, "devices-icloud-signed-out")) diff --git a/Tests/AskKeyTestSupport/E2EDeviceScenario.swift b/Tests/AskKeyTestSupport/E2EDeviceScenario.swift index a8bb544b..57971eb0 100644 --- a/Tests/AskKeyTestSupport/E2EDeviceScenario.swift +++ b/Tests/AskKeyTestSupport/E2EDeviceScenario.swift @@ -8,20 +8,18 @@ import Observation /// factory from #287. The runner clicks the App's real controls and plays /// the iPhone and the iCloud account through one-shot fixture commands. /// The iPhone's code never leaves this process: the step that enters it -/// plays the person typing it, and nothing writes it anywhere. The same -/// holds for the Mac's approver code, which the iPhone's steps type (#313). +/// plays the person typing it, and nothing writes it anywhere. Pairing makes +/// the simulated iPhone an approver (#336). @MainActor enum E2EDeviceScenario { static let scenarioPrefix = "screenshots-devices" static let phoneName = "Synthetic iPhone" - static let commands = ["phone-scan", "phone-reveal", "phone-complete", "phone-poll", "account-signed-out", - "approver-check-hidden", "approver-confirm"] + static let commands = ["phone-scan", "phone-reveal", "phone-complete", "phone-poll", "account-signed-out"] private static var backend: FakeDeviceServicesBackend? private static var phone: SimulatedPairingPhone? private static var task: Task? private static var transitions: [String] = [] - private static var control: URL? static func isRequested(_ scenario: String) -> Bool { scenario.hasPrefix(scenarioPrefix) @@ -38,7 +36,6 @@ enum E2EDeviceScenario { /// Runs each command once when its file appears, then removes the file /// and writes `device-.json` with the outcome. static func start(control: URL) { - self.control = control recordPairingTransitions(control: control) task = Task { @MainActor in while !Task.isCancelled { @@ -142,37 +139,11 @@ enum E2EDeviceScenario { case "account-signed-out": backend.accountState = .noAccount backend.signalAccountChange() - case "approver-check-hidden": - // The runner wrote the App's accessibility tree while the sheet - // showed the approver code; the code must not be in it (#313). - // Only the outcome leaves this process, and the tree is deleted. - guard let code = coordinator.approverCode, let control else { throw E2EDeviceScenarioError.noCode } - let file = control.appendingPathComponent("approver-accessibility-tree.txt") - defer { try? FileManager.default.removeItem(at: file) } - let tree = try String(contentsOf: file, encoding: .utf8) - guard tree.contains("devices-approver-waiting") else { throw E2EDeviceScenarioError.noSheet } - guard !tree.contains(code.digits), !tree.contains(code.formatted) else { throw E2EDeviceScenarioError.codeExposed } - case "approver-confirm": - // The person types the code the Mac shows on the iPhone and - // passes Face ID there (simulated). - guard let code = coordinator.approverCode else { throw E2EDeviceScenarioError.noCode } - try await phone.confirmApprover(typing: code.formatted, for: macID(phone)) - try await repeatUntil { - await coordinator.refresh() - if case .enabled = coordinator.approverConfirmation { return true } - return false - } default: throw E2EDeviceScenarioError.unknownCommand } } - /// The Mac as the simulated iPhone lists it. - private static func macID(_ phone: SimulatedPairingPhone) async throws -> DeviceID { - guard let mac = try await phone.pairedDevices().first?.deviceID else { throw E2EDeviceScenarioError.notPaired } - return mac - } - /// Repeats `step` for up to ten seconds until it reports success. private static func repeatUntil(_ step: () async throws -> Bool) async throws { for _ in 0..<50 { @@ -184,5 +155,5 @@ enum E2EDeviceScenario { } enum E2EDeviceScenarioError: Error { - case notInstalled, noQRCode, noCode, timedOut, unknownCommand, notPaired, noSheet, codeExposed + case notInstalled, noQRCode, noCode, timedOut, unknownCommand } diff --git a/Tests/AskKeyTestSupport/FakeDeviceServices.swift b/Tests/AskKeyTestSupport/FakeDeviceServices.swift index 09084073..3bee674f 100644 --- a/Tests/AskKeyTestSupport/FakeDeviceServices.swift +++ b/Tests/AskKeyTestSupport/FakeDeviceServices.swift @@ -221,9 +221,9 @@ extension FakeDeviceInbox: NamedInboxFetching { } /// An iPhone in the same process: software keys, its own list in memory, -/// and the backend's transport and clock. It pairs, and acts as an approver -/// (ADR 0014): it keeps every verified request and closed message, and sends -/// decisions, receipts and approver confirmations. The person's steps on the +/// and the backend's transport and clock. It pairs, which makes it an +/// approver (ADR 0014, #336): it keeps every verified request and closed +/// message, and sends decisions and receipts. The person's steps on the /// phone are its methods. package final class SimulatedPairingPhone: @unchecked Sendable { package let identity = SoftwareDeviceIdentity() @@ -296,13 +296,17 @@ package final class SimulatedPairingPhone: @unchecked Sendable { return sealed } - /// Types the code under the Mac's entry and sends the confirmation. - package func confirmApprover(typing code: String, for mac: DeviceID) async throws { - guard let entry = try await messenger.pairedDevices().first(where: { $0.deviceID == mac }), - let typed = ApproverCode(typed: code) else { throw DeviceMessengerError.unknownDevice } - let sealed = try await messenger.sealer.sealApproverConfirmation(typed, to: entry, + /// Sends an approver confirmation (kind 14) of an older build, which an + /// amended Mac refuses (#336). Goes with kind 14's code. + @discardableResult + package func sendRetiredApproverConfirmation(to mac: DeviceID) async throws -> SealedDeviceMessage { + guard let entry = try await messenger.pairedDevices().first(where: { $0.deviceID == mac }) else { + throw DeviceMessengerError.unknownDevice + } + let sealed = try await messenger.sealer.sealApproverConfirmation(.random(), to: entry, approvalReason: "Synthetic phone confirmation") try await transport.send(sealed.envelope) + return sealed } /// Saves an envelope to the Mac's inbox as it is, for example to re-insert one. diff --git a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift index 9c981e75..58987bb0 100644 --- a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift +++ b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift @@ -1,172 +1,141 @@ @testable import AskKeyBroker -import AskKeyDevices +@testable import AskKeyDevices +import AskKeyDevicesTestSupport import Foundation import XCTest @testable import AskKeyVault /// The approval flag's write rule on the Mac and the remote entry with the -/// flag on (ADR 0014 → Approvers, Vault entry). Every value is synthetic. +/// flag on (ADR 0014 → Approvers, Vault entry; #336). Every value is synthetic. final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { - private func enable(_ device: PairedDevice, in library: AgentAccessPolicyLibrary) async throws { - try library.vault.authorizeDeviceApprover(device.deviceID, pairingID: device.pairingID, using: .allow) - try await library.vault.pairedDeviceRegistry().apply(.setApprover(device.deviceID, pairingID: device.pairingID, - enabled: true)) + /// The entry a pairing adds for an iPhone: the pairing session sets the + /// flag; tests reach it through `@testable` access only. + private func flagged(_ device: PairedDevice) -> PairedDevice { + var entry = device + entry.isApprover = true + return entry + } + + /// Pairs the device as a pairing of this Mac with an iPhone does: the + /// add that the pairing authorization allows carries the flag. + private func pairApprover(_ device: PairedDevice, in library: AgentAccessPolicyLibrary) async throws { + try await pair(flagged(device), in: library) } private func isApprover(_ device: PairedDevice, in library: AgentAccessPolicyLibrary) async throws -> Bool { try await library.vault.pairedDeviceRegistry().list().device(device.deviceID)?.isApprover == true } - private func setApprover(_ device: PairedDevice, _ enabled: Bool, in library: AgentAccessPolicyLibrary) async throws { - try await library.vault.pairedDeviceRegistry().apply(.setApprover(device.deviceID, pairingID: device.pairingID, - enabled: enabled)) + private func syntheticMac() throws -> PairedDevice { + let card = try DeviceCard.make(identity: SoftwareDeviceIdentity(), platform: .macOS, + createdAt: Date(timeIntervalSince1970: 1_800_000_000)) + let pairingID = try XCTUnwrap(PairingID(rawValue: Data((0..<16).map { _ in UInt8.random(in: .min ... .max) }))) + return PairedDevice(card: card, pairingID: pairingID, displayName: "Synthetic Mac", + pairedAt: Date(timeIntervalSince1970: 1_800_000_100)) } - // MARK: Write rule - - func testTurningApprovalOnNeedsAMatchingAuthorizationAndWritesNothingOtherwise() async throws { - let library = try makeLibrary() - let device = try syntheticDevice() - let other = try syntheticDevice(name: "Other Phone") - try await pair(device, in: library) - try await pair(other, in: library) + private func assertRefused(_ expected: DeviceStorageError, _ library: AgentAccessPolicyLibrary, _ message: String, + file: StaticString = #filePath, line: UInt = #line, + _ write: () async throws -> Void) async { let stored = library.keys.deviceItems[.pairedDevices] - let otherPairing = try XCTUnwrap(PairingID(rawValue: Data(repeating: 0x7A, count: 16))) - let refusals: [(DeviceID, PairingID)?] = [nil, (other.deviceID, other.pairingID), (device.deviceID, otherPairing)] - for authorization in refusals { - library.vault.endDeviceApproverAuthorization() - if let authorization { - try library.vault.authorizeDeviceApprover(authorization.0, pairingID: authorization.1, using: .allow) - } - do { - try await setApprover(device, true, in: library) - XCTFail("Turning approval on needs the approver authorization for this device and pairing") - } catch { - XCTAssertEqual(error as? DeviceStorageError, .approverNotAuthorized) - } - XCTAssertEqual(library.keys.deviceItems[.pairedDevices], stored, "Nothing is written") + do { + try await write() + XCTFail(message, file: file, line: line) + } catch { + XCTAssertEqual(error as? DeviceStorageError, expected, message, file: file, line: line) } - try await enable(device, in: library) - let enabled = try await isApprover(device, in: library) - XCTAssertTrue(enabled) + XCTAssertEqual(library.keys.deviceItems[.pairedDevices], stored, "Nothing is written: \(message)", file: file, line: line) } - func testTurningApprovalOnNeedsTheManagementSession() async throws { + // MARK: Write rule + + func testAnAddThatPairingAuthorizedMayCarryTheFlagForAnIPhone() async throws { let library = try makeLibrary() - let device = try syntheticDevice() - try await pair(device, in: library) - try library.vault.authorizeDeviceApprover(device.deviceID, pairingID: device.pairingID, using: .allow) - library.vault.endManagementSession() - let stored = library.keys.deviceItems[.pairedDevices] - do { - try await setApprover(device, true, in: library) - XCTFail("Turning approval on needs the management session") - } catch {} - XCTAssertEqual(library.keys.deviceItems[.pairedDevices], stored) - // The ended session also dropped the authorization. - try library.vault.beginManagementSession(using: .allow) - do { - try await setApprover(device, true, in: library) - XCTFail("The authorization ended with the session") - } catch { - XCTAssertEqual(error as? DeviceStorageError, .approverNotAuthorized) - } + let phone = try syntheticDevice() + let unflagged = try syntheticDevice(name: "Unflagged Phone") + try await pairApprover(phone, in: library) + try await pair(unflagged, in: library) + let phoneFlag = try await isApprover(phone, in: library) + let otherFlag = try await isApprover(unflagged, in: library) + XCTAssertTrue(phoneFlag, "the flag is written in the add itself") + XCTAssertFalse(otherFlag, "an add without the flag stays without it") } - func testTheWriteUsesTheAuthorizationUp() async throws { + func testAFlagOnAnAddOfAnotherPlatformIsRefused() async throws { let library = try makeLibrary() - let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) - try await setApprover(device, false, in: library) - do { - try await setApprover(device, true, in: library) - XCTFail("One authorization turns approval on once") - } catch { - XCTAssertEqual(error as? DeviceStorageError, .approverNotAuthorized) + let mac = try syntheticMac() + await assertRefused(.approverNotAuthorized, library, "only an iOS card may carry the flag") { + try await self.pairApprover(mac, in: library) } - let enabled = try await isApprover(device, in: library) - XCTAssertFalse(enabled) + try await pair(mac, in: library) + let flag = try await isApprover(mac, in: library) + XCTAssertFalse(flag, "a Mac pairs without the flag") } - func testTurningApprovalOffNeedsOnlyTheManagementSession() async throws { + func testAFlaggedAddStillNeedsThePairingAuthorizationAndTheManagementSession() async throws { let library = try makeLibrary() - let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) + let phone = try syntheticDevice() + let other = try syntheticDevice(name: "Other Phone") + await assertRefused(.pairingNotAuthorized, library, "no pairing authorization") { + try await library.vault.pairedDeviceRegistry().apply(.add(self.flagged(phone))) + } + try library.vault.authorizeDevicePairing(with: other.deviceID, using: .allow) + await assertRefused(.pairingNotAuthorized, library, "the authorization is for another device") { + try await library.vault.pairedDeviceRegistry().apply(.add(self.flagged(phone))) + } + try library.vault.authorizeDevicePairing(with: phone.deviceID, using: .allow) library.vault.endManagementSession() + let stored = library.keys.deviceItems[.pairedDevices] do { - try await setApprover(device, false, in: library) - XCTFail("Turning approval off needs the management session") + try await library.vault.pairedDeviceRegistry().apply(.add(flagged(phone))) + XCTFail("An add needs the management session") } catch {} - var enabled = try await isApprover(device, in: library) - XCTAssertTrue(enabled) - try library.vault.beginManagementSession(using: .allow) - try await setApprover(device, false, in: library) - enabled = try await isApprover(device, in: library) - XCTAssertFalse(enabled) + XCTAssertEqual(library.keys.deviceItems[.pairedDevices], stored) } - func testOneWriteCannotTurnOnTwoDevices() async throws { + func testNoWriteChangesTheFlagOfAStoredEntry() async throws { let library = try makeLibrary() - let first = try syntheticDevice() - let second = try syntheticDevice(name: "Second Phone") - try await pair(first, in: library) - try await pair(second, in: library) - try library.vault.authorizeDeviceApprover(first.deviceID, pairingID: first.pairingID, using: .allow) - var list = try await library.vault.pairedDeviceRegistry().list() - try list.apply(.setApprover(first.deviceID, pairingID: first.pairingID, enabled: true)) - try list.apply(.setApprover(second.deviceID, pairingID: second.pairingID, enabled: true)) - XCTAssertThrowsError(try library.vault.savePairedDevices(list, epoch: library.vault.deviceState.currentEpoch)) { - XCTAssertEqual($0 as? DeviceStorageError, .approverNotAuthorized) + let phone = try syntheticDevice() + let unflagged = try syntheticDevice(name: "Unflagged Phone") + try await pairApprover(phone, in: library) + try await pair(unflagged, in: library) + let registry = try library.vault.pairedDeviceRegistry() + await assertRefused(.approverNotAuthorized, library, "turning a stored flag off") { + try await registry.apply(.setApprover(phone.deviceID, pairingID: phone.pairingID, enabled: false)) } - } - - func testAnAttemptEndedDuringItsAuthenticationInstallsNothing() async throws { - for end in ["sheet", "management", "epoch"] { - let library = try makeLibrary() - let device = try syntheticDevice() - try await pair(device, in: library) - let vault = library.vault - let late = ManagementAuthenticator { _ in - switch end { - case "sheet": vault.endDeviceApproverAuthorization() - case "management": vault.endManagementSession() - default: vault.deviceState.endEpoch() - } - return true - } - XCTAssertThrowsError(try vault.authorizeDeviceApprover(device.deviceID, pairingID: device.pairingID, using: late), end) - try vault.beginManagementSession(using: .allow) - XCTAssertFalse(vault.deviceState.isApproverAuthorized(.init(deviceID: device.deviceID, pairingID: device.pairingID), - at: Date()), end) - if end != "epoch" { - do { - try await setApprover(device, true, in: library) - XCTFail("A cancelled attempt cannot turn approval on (\(end))") - } catch { - XCTAssertEqual(error as? DeviceStorageError, .approverNotAuthorized, end) - } - } + await assertRefused(.approverNotAuthorized, library, "turning a stored entry's flag on") { + try await registry.apply(.setApprover(unflagged.deviceID, pairingID: unflagged.pairingID, enabled: true)) + } + // A fresh pairing authorization for the device does not cover its stored entry. + try library.vault.authorizeDevicePairing(with: unflagged.deviceID, using: .allow) + await assertRefused(.approverNotAuthorized, library, "adding the stored entry again with the flag") { + try await registry.apply(.add(self.flagged(unflagged))) + } + await assertRefused(.approverNotAuthorized, library, "adding the stored entry again without the flag") { + try await registry.apply(.add(phone)) } + var list = try await registry.list() + try list.apply(.setApprover(unflagged.deviceID, pairingID: unflagged.pairingID, enabled: true)) + await assertRefused(.approverNotAuthorized, library, "a list written directly") { + try library.vault.savePairedDevices(list, epoch: library.vault.deviceState.currentEpoch) + } + let phoneFlag = try await isApprover(phone, in: library) + let otherFlag = try await isApprover(unflagged, in: library) + XCTAssertTrue(phoneFlag) + XCTAssertFalse(otherFlag) } - func testTheAuthorizationLapsesAfterFiveMinutes() async throws { - let clock = RemoteApprovalTestClock(Date(timeIntervalSince1970: 1_800_000_000)) - let library = try makeLibrary(now: { clock.now }) + func testOtherChangesToAnApproverNeedNoAuthorization() async throws { + let library = try makeLibrary() let device = try syntheticDevice() - try await pair(device, in: library) - try library.vault.authorizeDeviceApprover(device.deviceID, pairingID: device.pairingID, using: .allow) - clock.advance(by: 200) - // The open sheet keeps the management session from expiring for idleness. - try library.vault.requireDeviceManagementSession() - clock.advance(by: 101) - do { - try await setApprover(device, true, in: library) - XCTFail("The authorization lasts 5 minutes") - } catch { - XCTAssertEqual(error as? DeviceStorageError, .approverNotAuthorized) - } + try await pairApprover(device, in: library) + library.vault.endManagementSession() + // A delivery check runs in the background, without the management session. + try await library.vault.pairedDeviceRegistry().apply(.recordReached(device.deviceID, pairingID: device.pairingID, + at: Date(timeIntervalSince1970: 1_800_000_200))) + let entry = try await library.vault.pairedDeviceRegistry().list().device(device.deviceID) + XCTAssertEqual(entry?.isApprover, true) + XCTAssertNotNil(entry?.lastReachedAt) } func testActivatingStoredApproversAddsFlaggedEntriesWithNewGenerations() async throws { @@ -174,13 +143,13 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { let phone = try syntheticDevice() let tablet = try syntheticDevice(name: "Synthetic Tablet") let unflagged = try syntheticDevice(name: "Unflagged Phone") - for device in [phone, tablet, unflagged] { try await pair(device, in: library) } - try await enable(phone, in: library) + try await pairApprover(phone, in: library) + try await pair(unflagged, in: library) let approvals = library.vault.approvalRequests let first = try library.vault.activateStoredApprovers() XCTAssertEqual(Set(first.keys), [phone.pairingID]) - try await enable(tablet, in: library) - // After the tablet's flag write, only the tablet is added; the phone keeps its generation. + try await pairApprover(tablet, in: library) + // After the tablet's pairing, only the tablet is added; the phone keeps its generation. let added = try library.vault.activateStoredApprovers(only: tablet.pairingID) XCTAssertEqual(Set(added.keys), [tablet.pairingID]) XCTAssertEqual(approvals.activeApproverGeneration(pairingID: phone.pairingID.rawValue), first[phone.pairingID]) @@ -193,39 +162,22 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { XCTAssertGreaterThan(try XCTUnwrap(reloaded[phone.pairingID]), try XCTUnwrap(added[tablet.pairingID])) } - func testOtherChangesToAnApproverNeedNoAuthorization() async throws { - let library = try makeLibrary() - let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) - library.vault.endManagementSession() - // A delivery check runs in the background, without the management session. - try await library.vault.pairedDeviceRegistry().apply(.recordReached(device.deviceID, pairingID: device.pairingID, - at: Date(timeIntervalSince1970: 1_800_000_200))) - let entry = try await library.vault.pairedDeviceRegistry().list().device(device.deviceID) - XCTAssertEqual(entry?.isApprover, true) - XCTAssertNotNil(entry?.lastReachedAt) - } - // MARK: Revocation reaches the Broker first - func testTurningOffRemovingOrReplacingAnApproverEndsItsBrokerAuthority() async throws { - for change in ["off", "remove", "replace"] { + func testRemovingOrReplacingAnApproverEndsItsBrokerAuthority() async throws { + for change in ["remove", "replace"] { let library = try makeLibrary() let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) + try await pairApprover(device, in: library) _ = try activate(device, in: library.vault) let before = library.vault.approvalRequests.activeApproverRevocationCount() - switch change { - case "off": try await setApprover(device, false, in: library) - case "remove": + if change == "remove" { try await library.vault.pairedDeviceRegistry().apply(.remove(device.deviceID, pairingID: device.pairingID)) - default: + } else { // Pairing again gives the same device a new entry and pairing ID. let again = PairedDevice(card: device.card, pairingID: try XCTUnwrap(PairingID(rawValue: Data(repeating: 0x5C, count: 16))), displayName: device.displayName, pairedAt: device.pairedAt) - try await pair(again, in: library) + try await pairApprover(again, in: library) } XCTAssertNil(library.vault.approvalRequests.activeApproverGeneration(pairingID: device.pairingID.rawValue), change) XCTAssertGreaterThan(library.vault.approvalRequests.activeApproverRevocationCount(), before, change) @@ -235,13 +187,12 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { func testARefusedWriteLeavesTheBrokerSetAlone() async throws { let library = try makeLibrary() let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) + try await pairApprover(device, in: library) let generation = try activate(device, in: library.vault) - library.vault.endManagementSession() do { - try await setApprover(device, false, in: library) - XCTFail("Turning approval off needs the management session") + try await library.vault.pairedDeviceRegistry().apply(.setApprover(device.deviceID, pairingID: device.pairingID, + enabled: false)) + XCTFail("A stored flag never changes") } catch {} XCTAssertEqual(library.vault.approvalRequests.activeApproverGeneration(pairingID: device.pairingID.rawValue), generation) } @@ -250,8 +201,7 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { for path in ["reset", "erase"] { let library = try makeLibrary() let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) + try await pairApprover(device, in: library) _ = try activate(device, in: library.vault) if path == "reset" { try library.vault.resetDeviceIdentity() } else { library.vault.stopDeviceServicesForLocalErase() } XCTAssertNil(library.vault.approvalRequests.activeApproverGeneration(pairingID: device.pairingID.rawValue), path) @@ -267,8 +217,7 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { return false } let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) + try await pairApprover(device, in: library) let generation = try activate(device, in: library.vault) let pending = try pendingRead(in: library.vault) XCTAssertEqual(try decide(library.vault, pending, by: device, generation: generation, .allowOnce), @@ -287,8 +236,7 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { let library = try makeLibrary() try library.vault.updateTimedAllowance(enabled: true, minutes: 15) let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) + try await pairApprover(device, in: library) let generation = try activate(device, in: library.vault) let pending = try pendingRead(in: library.vault) XCTAssertEqual(try decide(library.vault, pending, by: device, generation: generation, .timedAllowance, ceiling: 7_200), @@ -307,8 +255,7 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { func testCeilingThatIsNotAsSignedIsRefusedRatherThanCappedByTheSetting() async throws { let library = try makeLibrary() let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) + try await pairApprover(device, in: library) let generation = try activate(device, in: library.vault) let pending = try pendingRead(in: library.vault) for ceiling in [7_201, 0, -1, .infinity, .nan] as [TimeInterval] { @@ -319,14 +266,13 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { XCTAssertTrue(library.vault.approvalRequests.activeTimedAllowances().isEmpty) } - func testFlagTurnedOffIsRefusedEvenWhileTheBrokerStillListsTheApprover() async throws { + func testAnEntryWithoutTheFlagIsRefusedEvenWhileTheBrokerListsItsPairing() async throws { let library = try makeLibrary() let device = try syntheticDevice() try await pair(device, in: library) - try await enable(device, in: library) + // Paired before #336 without approval, yet somehow in the set. let generation = try activate(device, in: library.vault) let pending = try pendingRead(in: library.vault) - try await setApprover(device, false, in: library) XCTAssertEqual(try decide(library.vault, pending, by: device, generation: generation, .allowOnce), .approverInactive) XCTAssertEqual(try state(library.vault, pending), .pending) } @@ -337,8 +283,7 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { for change in ["pause", "timed off", "end on lock"] { let library = try makeLibrary() let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) + try await pairApprover(device, in: library) let second = try makeSecondVault(library) let generation = try activate(device, in: second) let pending = try pendingRead(in: second) @@ -368,8 +313,7 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { for change in ["credential", "timed off"] { let library = try makeLibrary() let device = try syntheticDevice() - try await pair(device, in: library) - try await enable(device, in: library) + try await pairApprover(device, in: library) let generation = try activate(device, in: library.vault) let pending = try pendingRead(in: library.vault) if change == "credential" { diff --git a/Tests/UI/required-flows.json b/Tests/UI/required-flows.json index 4054f277..b4800268 100644 --- a/Tests/UI/required-flows.json +++ b/Tests/UI/required-flows.json @@ -16,5 +16,5 @@ "testClosingManagementWindowRequiresUnlockWhenReopened", "testAboutPanelFromAppMenuKeepsAskKeyInFront", "testPairADeviceOpensItsSheet", - "testApproveAgentRequestsTurnsOnWithTheCodeTypedOnTheIPhone" + "testPairedIPhoneApprovesAgentRequestsUntilRemoved" ] diff --git a/docs/features.md b/docs/features.md index 1939ecda..3277a9ee 100644 --- a/docs/features.md +++ b/docs/features.md @@ -204,7 +204,7 @@ Stage 2 and stage 4 of the multi-device roadmap ([#269](https://github.com/sudoH | Feature | One-line description | Decision | Legacy source files | Legacy test files | |---|---|---|---|---| | Devices section and pairing | Settings → **Devices** appears only in builds with CloudKit configured, which every `Release` build is from stage 4 on (E2E device scenarios show it with fake device services). **Pair a Device…** needs the management session and creates the identity; the Mac shows a QR code, the person types the code the iPhone shows and confirms with system authentication, and the list offers rename, delivery check and removal for up to 8 devices on the same Apple Account. The Broker gains no operation, so agents cannot list, pair or remove devices. | **Keep** | `Sources/AskKeyAppKit/Devices/CloudKitGate.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator+Pairing.swift`
`Sources/AskKeyAppKit/Views/Settings/DevicesSettingsSection.swift`
`Sources/AskKeyDevices/Pairing/PairingSession.swift`
`Sources/AskKeyDevices/Messenger/DeviceMessenger.swift` | `Tests/AskKeyAppTests/CloudKitGateTests.swift`
`Tests/AskKeyAppTests/DeviceCoordinatorPairingTests.swift`
`Tests/AskKeyDevicesTests/PairingFlowTests.swift`
`Tests/AskKeyE2ETests/DevicesE2ETests.swift` | -| iPhone approver | Pairing an iPhone makes it an approver (ADR 0014 as amended by #336); there is no separate switch or code, and removing the pairing on either device ends it. Read requests go to approvers at once while the Mac is locked or its lock state is unknown, otherwise after 20 seconds without a decision or when it locks; the first decision wins; Allow needs Face ID or Touch ID and Deny does not; writes, organize operations and group allowances stay on the Mac. | **Keep** | `Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteApproval.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift`
`Sources/AskKeyDevices/Approval/ApprovalRequest.swift`
`iOS/AskKeyiOSKit/Approvals/RequestCard.swift` | `Tests/AskKeyAppTests/ApproverConfirmationTests.swift`
`Tests/AskKeyAppTests/RemoteApprovalSendingTests.swift`
`Tests/AskKeyAppTests/RemoteApprovalDecisionTests.swift`
`Tests/AskKeyDevicesTests/ApprovalVectorTests.swift`
`iOS/AskKeyiOSKitTests/ApprovalDecisionTests.swift` | +| iPhone approver | Pairing an iPhone makes it an approver (ADR 0014 as amended by #336); there is no separate switch or code, and removing the pairing on either device ends it. Read requests go to approvers at once while the Mac is locked or its lock state is unknown, otherwise after 20 seconds without a decision or when it locks; the first decision wins; Allow needs Face ID or Touch ID and Deny does not; writes, organize operations and group allowances stay on the Mac. | **Keep** | `Sources/AskKeyDevices/Pairing/PairingSession.swift`
`Sources/AskKeyVault/Vault+Devices.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteApproval.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift`
`Sources/AskKeyDevices/Approval/ApprovalRequest.swift`
`iOS/AskKeyiOSKit/Approvals/RequestCard.swift` | `Tests/AskKeyDevicesTests/PairingApproverTests.swift`
`Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift`
`Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift`
`Tests/AskKeyAppTests/RemoteApprovalSendingTests.swift`
`Tests/AskKeyAppTests/RemoteApprovalDecisionTests.swift`
`Tests/AskKeyDevicesTests/ApprovalVectorTests.swift`
`iOS/AskKeyiOSKitTests/ApprovalDecisionTests.swift` | | What leaves the Mac | Until someone chooses **Pair a Device…**, update checks stay the only outbound requests: no identity, no CloudKit request, no push registration. Once the identity exists, until a local erase, the App uses the iCloud account's private CloudKit database and Apple's push service, sending routing data and end-to-end encrypted messages. A remote request carries the requester's name and purpose (not verified), the credential's name, the command line, the working directory, the executable's name, the delivered variable names with a bundle's component names, the deadline, the offers, the Mac App's launch time, a response ID and a binding digest; never a credential value, a component's content, file contents, inherited environment, write payload, the vault key, anything about Hidden credentials or the Mac's name. | **Keep** | `Sources/AskKeyAppKit/App/AppDelegate+Devices.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator.swift`
`Sources/AskKeyDevices/Approval/ApprovalRequestDisplay.swift`
`Sources/AskKeyDevices/CloudKit/CloudKitDeviceTransport.swift`
`scripts/build-app.sh` | `Tests/AskKeyAppTests/DeviceCoordinatorDevicesTests.swift`
`Tests/AskKeyAppTests/RemoteApprovalSendingTests.swift`
`Tests/AskKeyDevicesTests/ApprovalPayloadTests.swift`
`Tests/Automation/test_build_app_cloudkit.py` | | iPhone notifications | The notification extension shows the card sentence (requester, the iPhone's name for the Mac, credential and executable name) only for a request it fetched, decrypted and verified from a Mac the iPhone approves for, and generic text otherwise; never a credential value, arguments, the working directory or variable names. Show Previews decides what the Lock Screen shows, and Notification Center keeps them until removed. Ask Key never asks the person to act on a notification's text. | **Keep** | `iOS/AskKeyiOSNotificationService/Sources/NotificationProcessor.swift`
`iOS/AskKeyiOSNotificationService/Sources/NotificationText.swift`
`Sources/AskKeyDevices/Approval/DeviceMessageVerifier.swift` | `iOS/AskKeyiOSNotificationService/Tests/NotificationProcessorTests.swift`
`iOS/AskKeyiOSNotificationService/Tests/NotificationContentTests.swift` | | iPhone home | The iPhone app has three tabs: Requests (requests that can still be decided or wait for the Mac, with a badge counting those that can still be decided), History and Macs (the paired Macs, pairing, and this iPhone's iCloud, notification, delivery-check and version status). A finished request moves to History once its open page is closed, or at once if its page was closed; a request arriving while the app is open shows a banner and never opens its page by itself; a page opened from a notification shows a placeholder without content, never the notification's text, until the app has verified the request. Specified in ADR 0014 as amended by #345 and built by #346, #347 and #348, which update this row's files. | **Keep** (planned) | `iOS/AskKeyiOSKit/Views/RootView.swift`
`iOS/AskKeyiOSKit/Views/PairedMacsView.swift`
`iOS/AskKeyiOSKit/Views/RequestCardView.swift` | `iOS/AskKeyiOSKitTests/ScreenRenderTests.swift` | diff --git a/docs/glossary.md b/docs/glossary.md index 62ec3cf8..890651f2 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -41,7 +41,7 @@ The Chinese UI column quotes labels or relevant phrases from [Localizable.xcstri | Pair | 配对; 配对设备… | Adding a device to this Mac's list: the Mac shows a QR code, the iPhone scans it, and the person enters the iPhone's pairing code on the Mac and confirms with system authentication, and on the iPhone with Face ID or Touch ID. Pairing an iPhone makes it an approver. Needs the management session; agents cannot pair, list or remove devices. | | Pairing code | 配对码 | Only the six digits the iPhone shows on its Ask Key pairing screen, typed on the Mac. The Mac never shows it, and Ask Key never sends it in a notification or a message. The image the iPhone scans is always the QR code (二维码), never a pairing code. | | Delivery check | 送达检查; 测试送达; 还没联系上 | A message the Mac sends to a paired device to confirm it can be reached through iCloud. Until the first check succeeds, the device shows as "Not reached yet" (还没联系上). | -| Approver | 审批 Agent 请求 | A paired iPhone that may decide this Mac's agent read requests. Pairing an iPhone makes it an approver; there is no separate switch or code. Removing it on the Mac ends its approval at once; removing the Mac on the iPhone ends it when the Mac receives the unpair notice. Writes, group changes and group allowances stay on the Mac. See [ADR 0014](adr/0014-remote-approval.md). | +| Approver | 可以审批 Agent 请求 | A paired iPhone that may decide this Mac's agent read requests. Pairing an iPhone makes it an approver; there is no separate switch or code. Removing it on the Mac ends its approval at once; removing the Mac on the iPhone ends it when the Mac receives the unpair notice. Writes, group changes and group allowances stay on the Mac. See [ADR 0014](adr/0014-remote-approval.md). | | Remote request | 已发到 iPhone | A read request the Mac also sends, encrypted, to its approvers while its screen is locked or after the request waited 20 seconds. The agent's name, the credential's name, the command, the folder and the delivered names leave the Mac, never a value. The first decision, on the Mac or an approver, wins; the panel's Details show where the request went and whether it was delivered. | | Request history | — | The iPhone's encrypted summary of the requests its app verified, kept for 30 days after each one ends and at most 500 entries: requester, credential, program, the Mac's name at the time, times and outcome; never the command, folder, delivered names, purpose or a value. It is not a view of the access records and lists nothing the app did not verify. The iPhone label comes with #349. See [ADR 0014](adr/0014-remote-approval.md). | | Client adapter | — | The boundary that checks, previews, applies, verifies and rolls back a supported client's MCP configuration. Current clients are Claude Code, Codex, Cursor and Grok CLI; adapters share the Broker's security model. | diff --git a/docs/testing.md b/docs/testing.md index 6f5b5305..374f9d49 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -78,7 +78,7 @@ The `basic-ui-flows` job runs `bash scripts/run-e2e.sh` on a clean macOS runner. [The runner](../scripts/run-e2e.sh) builds the test-only `AskKeyE2EApp` through [build-app.sh](../scripts/build-app.sh), generates the XCUITest project from [Tests/UI/project.yml](../Tests/UI/project.yml), and runs [Tests/AskKeyE2ETests](../Tests/AskKeyE2ETests). It uses a separate E2E identity, ad hoc signing, per-run synthetic state, and controlled process cleanup. It does not install the production application. -[Tests/UI/required-flows.json](../Tests/UI/required-flows.json) currently lists 18 required flows. They cover explicit connection checks, completion feedback, missing discovery, cancellation and retry, denial, one-time approval and replay, pending cancellation, active-helper disconnection, pending-approval invalidation after restart, credential management persistence, management-window locking, the About panel staying in front of the management window, a real click on Settings → Devices → **Pair a Device…** opening its sheet, and a real click on a paired iPhone's **Approve agent requests** turning approval on. Every required flow must pass with zero failed tests, skips, or expected failures. A subset or zero executed tests is not acceptance. +[Tests/UI/required-flows.json](../Tests/UI/required-flows.json) currently lists 18 required flows. They cover explicit connection checks, completion feedback, missing discovery, cancellation and retry, denial, one-time approval and replay, pending cancellation, active-helper disconnection, pending-approval invalidation after restart, credential management persistence, management-window locking, the About panel staying in front of the management window, a real click on Settings → Devices → **Pair a Device…** opening its sheet, and a paired iPhone's row saying it approves agent requests until real clicks on **Remove** and its confirmation take it away. Every required flow must pass with zero failed tests, skips, or expected failures. A subset or zero executed tests is not acceptance. [e2e-report.py](../scripts/e2e-report.py) generates local receipts from [run-e2e.sh](../scripts/run-e2e.sh), and [e2e-gate.py](../scripts/e2e-gate.py) rereads the original xcresult and checks required names, result consistency, evidence hashes, and a source fingerprint. The fingerprint covers source, tests, scripts, CI workflows, and package inputs; changed inputs invalidate prior evidence. Hand-written result JSON cannot substitute for the original bundle. This detects stale or inconsistent evidence, not maliciously relabeled provenance. Local receipts remain part of the desktop runner; app builds use the CI gate below. @@ -123,7 +123,7 @@ The backup flow (#274) adds eight captures with synthetic credentials, in Englis 29-zh-backup-import-result.png ``` -The Devices section (#288, #313) adds eighteen captures in English (`30`–`34`, `40`, `42`–`44`) and Simplified Chinese (`35`–`39`, `41`, `45`–`47`). The `screenshots-devices` scenario gives the E2E App fake device services with software keys, an in-memory transport and a simulated iPhone named "Synthetic iPhone" (`Tests/AskKeyTestSupport/E2EDeviceScenario.swift`); every other scenario keeps the build without CloudKit and shows no Devices section. The runner clicks the App's controls, including **Pair a Device…**, which starts the pairing session; fixture commands play the iPhone scanning, revealing, entering its code on the Mac and confirming, answering the delivery check, typing the approver code, and the iCloud account signing out. `testPairADeviceOpensItsSheet` checks that the runner's click on **Pair a Device…** opens the pairing sheet. `testApproveAgentRequestsTurnsOnWithTheCodeTypedOnTheIPhone` pairs one iPhone, clicks its **Approve agent requests** switch, continues past what leaves the Mac, writes the sheet's accessibility tree for the App-side check that the approver code is not in any identifier, label or value, has the iPhone type the code, and checks that approval is on ([#313](https://github.com/sudoHG/AskKey/issues/313)). On macOS 26, **Pair a Device…** received no clicks while the Devices box held a single row; the empty list row keeps a second row there ([#299](https://github.com/sudoHG/AskKey/issues/299)). Both click tests are required flows (`DevicesE2ETests`, [#301](https://github.com/sudoHG/AskKey/issues/301)) on the same scenario, so a regression fails `basic-ui-flows`; the Devices captures run in the optional screenshot step. Neither the iPhone's pairing code nor the Mac's approver code leaves the App process in a passing run, and no capture shows either: the screenshots skip the approver code step, and the offscreen renders draw a fixed placeholder there. If a flow fails while the code step shows, XCTest's failure evidence can contain that run's synthetic code. Like the backup captures, take them from the attachments of `basic-flows.xcresult`: +The Devices section (#288, #313, #336) adds sixteen captures in English (`30`–`34`, `40`, `42`–`43`) and Simplified Chinese (`35`–`39`, `41`, `44`–`45`). The `screenshots-devices` scenario gives the E2E App fake device services with software keys, an in-memory transport and a simulated iPhone named "Synthetic iPhone" (`Tests/AskKeyTestSupport/E2EDeviceScenario.swift`); every other scenario keeps the build without CloudKit and shows no Devices section. The runner clicks the App's controls, including **Pair a Device…**, which starts the pairing session; fixture commands play the iPhone scanning, revealing, entering its code on the Mac and confirming, answering the delivery check, and the iCloud account signing out. Pairing makes the simulated iPhone an approver ([#336](https://github.com/sudoHG/AskKey/issues/336)). `testPairADeviceOpensItsSheet` checks that the runner's click on **Pair a Device…** opens the pairing sheet. `testPairedIPhoneApprovesAgentRequestsUntilRemoved` pairs one iPhone, checks that its row says it can approve agent requests, then clicks **Remove** and its confirmation, the Mac's only way to stop an iPhone approving, and checks that the row is gone ([#336](https://github.com/sudoHG/AskKey/issues/336)). On macOS 26, **Pair a Device…** received no clicks while the Devices box held a single row; the empty list row keeps a second row there ([#299](https://github.com/sudoHG/AskKey/issues/299)). Both click tests are required flows (`DevicesE2ETests`, [#301](https://github.com/sudoHG/AskKey/issues/301)) on the same scenario, so a regression fails `basic-ui-flows`; the Devices captures run in the optional screenshot step. The iPhone's pairing code never leaves the App process in a passing run, and no capture shows it. If a flow fails while the code step shows, XCTest's failure evidence can contain that run's synthetic code. Like the backup captures, take them from the attachments of `basic-flows.xcresult`: ```text 30-en-devices-list.png the list with one paired iPhone @@ -138,15 +138,13 @@ The Devices section (#288, #313) adds eighteen captures in English (`30`–`34`, 39-zh-devices-icloud-signed-out.png 40-en-devices-empty.png no paired device yet 41-zh-devices-empty.png -42-en-devices-approver-intro.png Approve agent requests: what leaves the Mac -43-en-devices-approver-enabled.png approval is on -44-en-devices-approval-on.png the list with approval on -45-zh-devices-approver-intro.png -46-zh-devices-approver-enabled.png -47-zh-devices-approval-on.png +42-en-devices-pairing-paired.png paired: the iPhone can now approve agent requests +43-en-devices-remove-confirmation.png Remove's confirmation: the iPhone stops approving +44-zh-devices-pairing-paired.png +45-zh-devices-remove-confirmation.png ``` -Remote approval states the desktop flows can't reach are rendered offscreen in the `build-and-test` job by `RemoteApprovalRenderTests`, in English and Simplified Chinese at twice the point size: the pending-requests list in the production management window, Devices with approval off and on at the window's content width (the real window's Devices captures are `30`/`35` and `44`/`47` above), every step of the approver sheet (including wrong codes, expiry, a code typed on another iPhone and every other end state; the code step shows a fixed placeholder) and the pairing sheet's install reminder at their own size, and the approval panel's Details with where a request went and an approver's decision through the production panel factory. No window is ordered in, so controls inside the management window and the panel draw in their inactive style. `AccessRecordRenderTests` adds Access records in the production management window, with a remote Allow Once, reads under a remote timed allowance, a remote Deny and local records for comparison, then the longest device name a Mac keeps, in the artifact's `access-records/` folder. Download `askkey-remote-approval-renders` from the run's artifacts; set `REMOTE_APPROVAL_RENDER_DIRECTORY` to keep the PNGs locally. +Remote approval states the desktop flows can't reach are rendered offscreen in the `build-and-test` job by `RemoteApprovalRenderTests`, in English and Simplified Chinese at twice the point size: the pending-requests list in the production management window, Devices at the window's content width with an iPhone that approves, Remove's confirmation, and an iPhone paired before #336 without approval (the real window's Devices captures are `30`/`35` and `43`/`45` above; with `REMOTE_APPROVAL_WINDOW_RENDERS=1` also set on a desktop session, the test also renders the real Settings window scrolled to Devices, which draws an empty column on the CI runner), every step of the pairing sheet with its approval statements at its own size (the QR code with the install reminder, the code matched with what a request sends, system authentication, waiting for the iPhone, and paired), and the approval panel's Details with where a request went and an approver's decision through the production panel factory. No window is ordered in, so controls inside the management window and the panel draw in their inactive style. `AccessRecordRenderTests` adds Access records in the production management window, with a remote Allow Once, reads under a remote timed allowance, a remote Deny and local records for comparison, then the longest device name a Mac keeps, in the artifact's `access-records/` folder. Download `askkey-remote-approval-renders` from the run's artifacts; set `REMOTE_APPROVAL_RENDER_DIRECTORY` to keep the PNGs locally. An optional capture failure is diagnostic: inspect the screenshot step, its log and xcresult, and the exported subset. A green required-flow job alone does not prove screenshot completeness; #146 acceptance also requires every PNG listed above in the artifact. Delete downloaded evidence after review. @@ -281,7 +279,7 @@ The read-back prints the Team ID: read it in the terminal and never paste it int - **Internal testing** ([#319](https://github.com/sudoHG/AskKey/issues/319)): add the build to an internal group of App Store Connect users; it needs no review. Install it with the TestFlight app. - **External testing** ([#320](https://github.com/sudoHG/AskKey/issues/320)): after the website deploy with the privacy policy, fill in TestFlight → Test Information: the Beta App Description, the feedback email, the privacy policy URL `https://askkey.sudohg.com/privacy/` (Simplified Chinese: `https://askkey.sudohg.com/zh/privacy/`), and Beta App Review Information (contact, no sign-in required, the review notes). Create the external group, add the build with its What to Test text and submit it to Beta App Review, which reviews the first build; later builds may not need a full review. After approval, enable the public link and point `/iphone` in `site/_redirects` at it; until then it points at the placeholder page `site/iphone-soon/`. -- **Beta App Review notes and demo video.** The reviewer has no Mac running Ask Key, so the app cannot pair. The notes say that Ask Key for iPhone only approves requests from Ask Key for Mac (free, open source, `https://askkey.sudohg.com`) on the person's own Mac through their own iCloud, that there is no account or sign-in, and that without a Mac the reviewer can see the welcome screen and the pairing scanner; they link to the demo video, because the review form has no attachment field (the notes allow 4,000 characters). The video, unlisted at a link the maintainer chooses, shows pairing with the QR code and the code, turning on approval on the Mac with the approver code, an agent request arriving as a notification with its card sentence, Allow with Face ID and Deny, and the Mac's result. It shows no credential value, Team ID or device ID. +- **Beta App Review notes and demo video.** The reviewer has no Mac running Ask Key, so the app cannot pair. The notes say that Ask Key for iPhone only approves requests from Ask Key for Mac (free, open source, `https://askkey.sudohg.com`) on the person's own Mac through their own iCloud, that there is no account or sign-in, and that without a Mac the reviewer can see the welcome screen and the pairing scanner; they link to the demo video, because the review form has no attachment field (the notes allow 4,000 characters). The video, unlisted at a link the maintainer chooses, shows pairing with the QR code and the code, which makes the iPhone an approver, an agent request arriving as a notification with its card sentence, Allow with Face ID and Deny, and the Mac's result. It shows no credential value, Team ID or device ID. - **Build expiry.** A TestFlight build can be tested for 90 days after upload ([TestFlight overview](https://developer.apple.com/help/app-store-connect/test-a-beta-version/testflight-overview)), and the public link installs only builds that have not expired. Before the current build expires, upload a fresh build with a higher build number, add it to the external group (with the maintainer's approval) and check that the public link installs it. Each build's expiry date shows in TestFlight. ## Pre-release checks on the maintainer's Mac diff --git a/iOS/AskKeyiOSKit/Pairing/PairingFlowModel.swift b/iOS/AskKeyiOSKit/Pairing/PairingFlowModel.swift index ab34114e..c6dfa7ac 100644 --- a/iOS/AskKeyiOSKit/Pairing/PairingFlowModel.swift +++ b/iOS/AskKeyiOSKit/Pairing/PairingFlowModel.swift @@ -165,8 +165,10 @@ public final class PairingFlowModel: Identifiable { } /// Signs the confirmation with the approval key, which asks for Face ID - /// or Touch ID every time with no passcode button. A cancelled or failed - /// prompt sends nothing; the person can confirm again. + /// or Touch ID every time with no passcode button. This Face ID is also + /// the consent to approve the Mac's agent requests (ADR 0014, #336), so + /// its reason names the Mac and approval. A cancelled or failed prompt + /// sends nothing; the person can confirm again. public func confirm() async { guard case .code(let display) = stage, !display.confirmed, !isConfirming, !finished else { return } isConfirming = true diff --git a/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings b/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings index aad3a70c..bd1851f9 100644 --- a/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings +++ b/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings @@ -1004,6 +1004,23 @@ } } }, + "pairing.approval %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Confirming lets this iPhone approve agents' requests to use credentials on “%@”. Each request shows the agent, the credential, the command and folder, and the names it's delivered as, never a credential value. Allowing always needs Face ID or Touch ID." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "确认后,这台 iPhone 可以审批 Agent 使用“%@”上凭证的请求。每个请求会显示 Agent、凭证、命令、目录和交出的名称,绝不包括凭证的值。允许时始终需要面容 ID 或触控 ID。" + } + } + } + }, "pairing.cancel": { "extractionState": "manual", "localizations": { @@ -1129,13 +1146,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "Confirm pairing with “%@”" + "value": "Pair with “%@” to approve its agent requests" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "确认与“%@”配对" + "value": "与“%@”配对,以审批它的 Agent 请求" } } } @@ -1163,13 +1180,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "Confirmed on this iPhone. Enter the code on your Mac to finish pairing." + "value": "Confirmed on this iPhone. Enter the code on your Mac to finish pairing. Agent requests from that Mac will then appear in Ask Key." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "已在这台 iPhone 上确认。请在 Mac 上输入配对码以完成配对。" + "value": "已在这台 iPhone 上确认。请在 Mac 上输入配对码以完成配对,之后那台 Mac 上 Agent 的请求会出现在请旨里。" } } } @@ -1350,13 +1367,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "This iPhone and “%@” are paired." + "value": "This iPhone and “%@” are paired. Agent requests from that Mac will appear in Ask Key. Allowing always needs Face ID or Touch ID." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "这台 iPhone 已与“%@”配对。" + "value": "这台 iPhone 已与“%@”配对。那台 Mac 上 Agent 的请求会出现在请旨里。允许时始终需要面容 ID 或触控 ID。" } } } diff --git a/iOS/AskKeyiOSKit/Views/PairingFlowView.swift b/iOS/AskKeyiOSKit/Views/PairingFlowView.swift index 2f436019..1bd5bf85 100644 --- a/iOS/AskKeyiOSKit/Views/PairingFlowView.swift +++ b/iOS/AskKeyiOSKit/Views/PairingFlowView.swift @@ -117,6 +117,8 @@ struct ScannerContent: View { /// The pairing code to enter on the Mac. Before the challenge and the /// reveal it says there is no code yet; in both states it says the code /// appears only here and is never sent in a notification or a message. +/// Before **Confirm Pairing** it says that confirming makes this iPhone +/// approve that Mac's agent requests (ADR 0014, #336). struct PairingCodeContent: View { let display: PairingCodeDisplay? let isConfirming: Bool @@ -162,6 +164,7 @@ struct PairingCodeContent: View { if display.confirmed { NoticeCard(symbol: "checkmark.circle.fill", tone: .success, text: Text("pairing.confirmed", bundle: .kit)) } else { + NoticeCard(symbol: "checkmark.shield", text: Text("pairing.approval \(display.macName)", bundle: .kit)) if let problem { NoticeCard(symbol: "exclamationmark.triangle.fill", tone: .warning, text: Text(Self.explanation(problem), bundle: .kit)) diff --git a/iOS/AskKeyiOSKitTests/ApprovalRequestTests.swift b/iOS/AskKeyiOSKitTests/ApprovalRequestTests.swift index a7c49faf..38002555 100644 --- a/iOS/AskKeyiOSKitTests/ApprovalRequestTests.swift +++ b/iOS/AskKeyiOSKitTests/ApprovalRequestTests.swift @@ -90,6 +90,7 @@ final class ApprovalRequestTests: XCTestCase { func testARequestFromAMacWithoutTheApprovalFlagIsRefused() async throws { let other = world.makeMac(name: "Office Mac") try await world.pair(other) + try await world.storeWithoutApprovalFlag(other) let phoneID = try world.phone.deviceID try await world.sendRequest(from: other) await world.model.processInbox() @@ -158,6 +159,7 @@ final class ApprovalRequestTests: XCTestCase { func testAClosedMessageFromAMacWithoutTheFlagIsRefused() async throws { let other = world.makeMac(name: "Office Mac") try await world.pair(other) + try await world.storeWithoutApprovalFlag(other) let foreign = try await world.sealRequest(from: other) try await world.sendClosed(.expired, for: foreign, from: other) await world.model.processInbox() diff --git a/iOS/AskKeyiOSKitTests/ApproverTests.swift b/iOS/AskKeyiOSKitTests/ApproverTests.swift index 24382cae..bce1346c 100644 --- a/iOS/AskKeyiOSKitTests/ApproverTests.swift +++ b/iOS/AskKeyiOSKitTests/ApproverTests.swift @@ -13,6 +13,9 @@ final class ApproverTests: XCTestCase { world = TestWorld() await world.setUpPhone() try await world.pair() + // The approver confirmation applies to a Mac paired before #336 + // without approval; pairing now sets the flag. + try await world.storeWithoutApprovalFlag() } override func tearDown() async throws { diff --git a/iOS/AskKeyiOSKitTests/Fakes/ApprovalFakes.swift b/iOS/AskKeyiOSKitTests/Fakes/ApprovalFakes.swift index d19db8c6..bfcf4779 100644 --- a/iOS/AskKeyiOSKitTests/Fakes/ApprovalFakes.swift +++ b/iOS/AskKeyiOSKitTests/Fakes/ApprovalFakes.swift @@ -116,6 +116,22 @@ extension TestWorld { model.closeApproverConfirmation() } + /// Stores the iPhone's entry for `peer` again without the approval flag, + /// as a Mac paired before #336 without approval is stored: every pairing + /// with a Mac now sets the flag, and the default initializer never does. + func storeWithoutApprovalFlag(_ peer: MacPeer? = nil) async throws { + let peer = peer ?? primaryMac + let store = PairedDeviceListKeychainStore(store: keychain) + let devices = try store.loadPairedDeviceList().devices.map { device in + guard device.deviceID == peer.deviceID else { return device } + return PairedDevice(card: device.card, pairingID: device.pairingID, displayName: device.displayName, + pairedAt: device.pairedAt, lastReachedAt: device.lastReachedAt, + lastDeliveryCheck: device.lastDeliveryCheck) + } + try store.savePairedDeviceList(try PairedDeviceList(devices: devices)) + await model.refreshList() + } + /// Pairs another Mac and turns approval on for it. func pairAndApprove(_ peer: MacPeer) async throws { try await pair(peer) diff --git a/iOS/AskKeyiOSKitTests/PairingFlowTests.swift b/iOS/AskKeyiOSKitTests/PairingFlowTests.swift index a795a8b0..bc403bf0 100644 --- a/iOS/AskKeyiOSKitTests/PairingFlowTests.swift +++ b/iOS/AskKeyiOSKitTests/PairingFlowTests.swift @@ -115,6 +115,21 @@ final class PairingFlowTests: XCTestCase { XCTAssertEqual(macList.map(\.deviceID), [phone.deviceID]) } + /// The Face ID that confirms pairing is the consent (#336): its reason + /// names the Mac and approval, and the paired Mac's requests are accepted + /// with no further step, on both sides. + func testPairingMakesThisIPhoneAcceptTheMacsRequests() async throws { + let phone = try world.phone + try await world.pair() + XCTAssertEqual(phone.approvalReasons.first, String(localized: "pairing.confirm.reason \(TestWorld.macName)", bundle: .kit)) + XCTAssertEqual(world.model.pairedMacs.first?.isApprover, true, "the iPhone's entry for the Mac carries the flag") + let macEntry = try await world.phoneEntry() + XCTAssertTrue(macEntry.isApprover, "the Mac's entry for the iPhone carries it too") + try await world.sendRequest() + await world.model.processInbox() + XCTAssertEqual(world.model.requests.count, 1, "no approve step before the first request") + } + func testCancelledFaceIDSendsNothingAndCanBeRetried() async throws { let phone = try world.phone let (flow, _) = try await world.reachCode() From 6fb2c73559b6d3cb92aa869c880960f2c39ced3d Mon Sep 17 00:00:00 2001 From: sudoHG Date: Sun, 15 Nov 2026 18:10:34 +0800 Subject: [PATCH 2/4] Keep a removal's pairing out of every activation and pin stored cards Review fixes for #341. Reloading the active-approver set after a suspension now skips a pairing ID whose removal began, as the per-entry paths already did, so a removal whose write failed or is pending cannot come back after an account change. The Vault treats an entry as stored only when its card matches too, so a write cannot swap the card, and with it the approval key, under a flag that pairing granted. --- .../Devices/DeviceCoordinator+Approvers.swift | 5 ++-- Sources/AskKeyVault/Vault+Devices.swift | 9 +++++-- .../AskKeyVault/Vault+RemoteApproval.swift | 6 +++-- .../RemoteApprovalPairingTests.swift | 18 ++++++++++++++ .../DeviceApproverFlagTests.swift | 24 +++++++++++++++++++ 5 files changed, 56 insertions(+), 6 deletions(-) diff --git a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift index 98a79516..f3cb3b53 100644 --- a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift +++ b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift @@ -14,11 +14,12 @@ extension DeviceCoordinator { } /// Loads the set from the list once the services are ready with the - /// list's account: every flagged entry gets a new generation. + /// list's account: every flagged entry gets a new generation, except one + /// whose removal began, also when its write failed or is still pending. func activateApproversIfNeeded() { guard canActivateApprovers, !approversLoaded else { return } do { - try vault.activateStoredApprovers() + try vault.activateStoredApprovers(excluding: revokedApprovers) approversLoaded = true } catch { environment.log(.approverActivationFailed) diff --git a/Sources/AskKeyVault/Vault+Devices.swift b/Sources/AskKeyVault/Vault+Devices.swift index ffddfbcd..1097bccb 100644 --- a/Sources/AskKeyVault/Vault+Devices.swift +++ b/Sources/AskKeyVault/Vault+Devices.swift @@ -338,7 +338,7 @@ extension Vault { } /// Writes a list the registry prepared. A device that was not on the - /// stored list, or is there with another pairing ID, is an add: it needs + /// stored list, or is there with another pairing ID or card, is an add: it needs /// the management session and this pairing session's authorization for /// that device, which the write then uses up. The approval flag (ADR /// 0014 → Approvers) may be on only in that add, and only when the added @@ -351,8 +351,13 @@ extension Vault { try withDeviceStorage(epoch: epoch) { keys in let vaultKey = try requireKey() let stored = try storedPairedDevices(keys: keys, vaultKey: vaultKey) + // An entry is the stored one only with the same card too, so a + // write cannot swap the card, and with it the approval key that + // checks every Allow, under a flag a pairing granted. func storedEntry(_ device: PairedDevice) -> PairedDevice? { - stored.devices.first { $0.deviceID == device.deviceID && $0.pairingID == device.pairingID } + stored.devices.first { + $0.deviceID == device.deviceID && $0.pairingID == device.pairingID && $0.card == device.card + } } guard !list.devices.contains(where: { device in storedEntry(device).map { $0.isApprover != device.isApprover } ?? false diff --git a/Sources/AskKeyVault/Vault+RemoteApproval.swift b/Sources/AskKeyVault/Vault+RemoteApproval.swift index 3e20890d..a6a29af6 100644 --- a/Sources/AskKeyVault/Vault+RemoteApproval.swift +++ b/Sources/AskKeyVault/Vault+RemoteApproval.swift @@ -70,13 +70,15 @@ extension Vault { /// generation. Pass the pairing ID of a flagged entry a pairing just /// added, or of one found missing from the set, so other approvers keep /// their generations; pass nil when the device services become ready. + /// Pairing IDs in `excluded`, whose removal has begun, are never added. /// Returns the generations of the added entries. @discardableResult - package func activateStoredApprovers(only pairingID: PairingID? = nil) throws -> [PairingID: UInt64] { + package func activateStoredApprovers(only pairingID: PairingID? = nil, + excluding excluded: Set = []) throws -> [PairingID: UInt64] { for _ in 0..<3 { let count = approvalRequests.activeApproverRevocationCount() let flagged = try storedPairedDeviceList().devices - .filter { $0.isApprover && (pairingID == nil || $0.pairingID == pairingID) } + .filter { $0.isApprover && (pairingID == nil || $0.pairingID == pairingID) && !excluded.contains($0.pairingID) } .map(\.pairingID) do { let generations = try approvalRequests.addActiveApprovers(flagged.map(\.rawValue), revocationCount: count) diff --git a/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift b/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift index 34d0d23d..2468669f 100644 --- a/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift +++ b/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift @@ -113,6 +113,24 @@ final class RemoteApprovalPairingTests: AskKeyAppTestCase { XCTAssertNil(try harness.generation(of: harness.phone), "nor does a late add notice") } + /// A removal whose write failed or is still pending: reloading the set + /// after the account returns does not bring the pairing back either. + func testAReloadAfterAnAccountChangeSkipsAPairingWhoseRemovalBegan() async throws { + try await harness.pairApprover() + let registry = try XCTUnwrap(harness.coordinator.services?.registry) + let devices = try await registry.list().devices + let entry = try XCTUnwrap(devices.first) + harness.coordinator.deviceWillBeRemoved(entry) + harness.backend.accountState = .available(userRecordName: "_synthetic-account-2") + await harness.coordinator.devicesOpened() + XCTAssertEqual(harness.coordinator.account, .accountChanged) + harness.backend.accountState = .available(userRecordName: "_synthetic-account-1") + await harness.coordinator.devicesOpened() + XCTAssertEqual(harness.coordinator.account, .available) + XCTAssertEqual(harness.coordinator.devices.count, 1, "the entry is still stored") + XCTAssertNil(try harness.generation(of: harness.phone), "the reload skipped it") + } + func testAnIPhoneThatUndoesThePairingRightAfterTheAddNeverStaysInTheSet() async throws { // The iPhone confirms first, so the Mac adds it as soon as it confirms. let code = try await harness.reachCodeEntry() diff --git a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift index 58987bb0..0651242b 100644 --- a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift +++ b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift @@ -125,6 +125,30 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { XCTAssertFalse(otherFlag) } + func testAWriteCannotSwapTheCardOfAFlaggedEntry() async throws { + let library = try makeLibrary() + let identity = SoftwareDeviceIdentity() + let created = Date(timeIntervalSince1970: 1_800_000_000) + let pairingID = try XCTUnwrap(PairingID(rawValue: Data(repeating: 0x3C, count: 16))) + let phone = PairedDevice(card: try DeviceCard.make(identity: identity, platform: .iOS, createdAt: created), + pairingID: pairingID, displayName: "Synthetic Phone", pairedAt: created) + try await pairApprover(phone, in: library) + // Same device ID and pairing ID, another card: an add, not the stored entry. + let swapped = PairedDevice(card: try DeviceCard.make(identity: identity, platform: .macOS, createdAt: created), + pairingID: pairingID, displayName: "Synthetic Phone", pairedAt: created) + XCTAssertEqual(swapped.deviceID, phone.deviceID) + let registry = try library.vault.pairedDeviceRegistry() + await assertRefused(.pairingNotAuthorized, library, "a card swap without the pairing authorization") { + try await registry.apply(.add(self.flagged(swapped))) + } + try library.vault.authorizeDevicePairing(with: phone.deviceID, using: .allow) + await assertRefused(.approverNotAuthorized, library, "a flagged card that is not iOS") { + try await registry.apply(.add(self.flagged(swapped))) + } + let stored = try await registry.list().device(phone.deviceID) + XCTAssertEqual(stored?.card, phone.card) + } + func testOtherChangesToAnApproverNeedNoAuthorization() async throws { let library = try makeLibrary() let device = try syntheticDevice() From c118368506cb61793c1121b5c6a4d4ece1b00059 Mon Sep 17 00:00:00 2001 From: sudoHG Date: Sun, 15 Nov 2026 18:23:56 +0800 Subject: [PATCH 3/4] Retry a failed rollback and track requests before an approver joins Second-round review fixes for #341. When the add of a session that ended during the write cannot be removed, the messenger keeps the rollback and retries it from advanceTimers() until it commits, so a cancelled pairing does not leave a flagged entry behind for the next launch. Before adding an approver to the active-approver set, the coordinator tracks every pending request against the set as it was, so a request whose Broker notification has not arrived yet stays on the Mac. --- .../Devices/DeviceCoordinator+Approvers.swift | 11 ++++ .../Messenger/DeviceMessenger.swift | 25 +++++++- .../RemoteApprovalPairingTests.swift | 25 ++++++++ .../ApprovalFlagTests.swift | 58 +++++++++++++++++++ 4 files changed, 118 insertions(+), 1 deletion(-) diff --git a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift index f3cb3b53..11061fe7 100644 --- a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift +++ b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift @@ -18,6 +18,7 @@ extension DeviceCoordinator { /// whose removal began, also when its write failed or is still pending. func activateApproversIfNeeded() { guard canActivateApprovers, !approversLoaded else { return } + trackPendingRequestsBeforeActivation() do { try vault.activateStoredApprovers(excluding: revokedApprovers) approversLoaded = true @@ -53,6 +54,7 @@ extension DeviceCoordinator { private func activateMissingApprover(_ pairingID: PairingID) { guard !revokedApprovers.contains(pairingID), vault.approvalRequests.activeApproverGeneration(pairingID: pairingID.rawValue) == nil else { return } + trackPendingRequestsBeforeActivation() do { if !(try vault.activateStoredApprovers(only: pairingID)).isEmpty { environment.log(.approverActivated) @@ -62,4 +64,13 @@ extension DeviceCoordinator { environment.log(.approverActivationFailed) } } + + /// Eligibility is decided when a request is created, but the Broker's + /// notification reaches the coordinator later, and can be merged into a + /// later one. Tracking every pending request against the set as it is + /// before an addition keeps a request the coordinator has not seen yet + /// from going to an approver that joined after it. + private func trackPendingRequestsBeforeActivation() { + reconcileRemoteRequests() + } } diff --git a/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift b/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift index a4989825..9813cc45 100644 --- a/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift +++ b/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift @@ -82,6 +82,13 @@ public actor DeviceMessenger { let expiresAt: Date } + /// An entry added for a session that ended during the write, whose + /// removal has not committed yet. + struct PendingRollback: Hashable { + let deviceID: DeviceID + let pairingID: PairingID + } + public nonisolated let deviceID: DeviceID public nonisolated let platform: DevicePlatform let identity: any DeviceIdentity @@ -104,6 +111,8 @@ public actor DeviceMessenger { /// effect once. var inFlight: Set = [] var pendingChecks: [MessageID: PendingCheck] = [:] + /// Rollbacks whose removal failed; `advanceTimers()` retries them. + var pendingRollbacks: [PendingRollback] = [] /// When each record was first fetched, for the 30-second freezing rule. var firstFetched: [String: Date] = [:] var failureCounts: [String: Int] = [:] @@ -297,6 +306,7 @@ public actor DeviceMessenger { let now = clock.now() processed.prune(now: now) await adoptStoredChecks() + for rollback in pendingRollbacks { await roll(back: rollback) } retiredSessions.removeAll { !$0.isOpen(at: now) } await perform(session?.tick(now: now) ?? []) if session?.needsAdd == true { await perform([.addPeer]) } @@ -356,7 +366,7 @@ public actor DeviceMessenger { // The session may have ended while the list was written, for // example by Cancel, a cancellation or a removal; then it stores nothing. guard generation == sessionGeneration, let current = session, current.isOpen(at: clock.now()) else { - _ = try? await commit(.remove(entry.deviceID, pairingID: entry.pairingID)) + await roll(back: PendingRollback(deviceID: entry.deviceID, pairingID: entry.pairingID)) return } session?.peerAdded() @@ -370,6 +380,19 @@ public actor DeviceMessenger { } } + /// Removes an entry whose session ended while it was written. A removal + /// that fails is kept and retried by `advanceTimers()` until it commits + /// or the entry is gone or replaced, because the entry can carry the + /// approval flag of a pairing the person cancelled (ADR 0014, #336). + func roll(back rollback: PendingRollback) async { + do { + try await commit(.remove(rollback.deviceID, pairingID: rollback.pairingID)) + pendingRollbacks.removeAll { $0 == rollback } + } catch { + if !pendingRollbacks.contains(rollback) { pendingRollbacks.append(rollback) } + } + } + /// Sends each queued session message once. A message that fails stays /// queued and is resent with the same message ID; an expired one is dropped. func flushOutbox() async { diff --git a/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift b/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift index 2468669f..0aba22a4 100644 --- a/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift +++ b/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift @@ -150,6 +150,31 @@ final class RemoteApprovalPairingTests: AskKeyAppTestCase { XCTAssertNil(harness.vault.approvalRequests.activeApproverGeneration(pairingID: pairingID.rawValue)) } + /// The Broker's notification of a request has not reached the + /// coordinator when the first iPhone joins: the request still stays on + /// the Mac. + func testARequestNotSeenYetWhenTheFirstIPhoneJoinsStaysOnTheMac() async throws { + try harness.addCredential() + let code = try await harness.reachCodeEntry() + await harness.coordinator.enterPairingCode(code) + await harness.coordinator.confirmPairing() + // Created now; the observer has not told the coordinator yet. + let run = BrokerTextRunRequest(command: ["/usr/bin/true"], credentialNames: [DeviceCoordinatorHarness.credentialName], + callerName: "Synthetic Agent") + guard case .approvalRequired = try harness.vault.brokerTextCredentials(for: run, cancellation: .init()) else { + return XCTFail("a pending read") + } + let pending = try XCTUnwrap(harness.vault.approvalRequests.pendingRequests().last) + XCTAssertNil(harness.coordinator.remoteRequests[pending.requestID]) + try await harness.phone.confirm() + await harness.coordinator.refresh() + XCTAssertNotNil(try harness.generation(of: harness.phone), "the iPhone joined") + XCTAssertEqual(harness.coordinator.remoteRequests[pending.requestID]?.phase, .stayingOnMac) + harness.coordinator.approvalRequestsChanged() + await harness.coordinator.remoteApprovalTick() + XCTAssertTrue(harness.macSent(.approvalRequest).isEmpty) + } + func testAnEligibleRequestStillWaitingReachesANewlyPairedIPhoneAtItsMark() async throws { try await harness.pairApprover() harness.script.screenUnlocked = true diff --git a/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift b/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift index 6e4a5075..e8fc29c4 100644 --- a/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift +++ b/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift @@ -195,6 +195,43 @@ final class ApprovalFlagTests: XCTestCase { await XCTAssertNilAsync(try await mac.entry(for: phone), "the ended session stores nothing") } + /// The rollback of an add whose session ended fails to write: the + /// flagged entry is removed at the next timer pass, not left behind. + func testAFailedRollbackOfAFlaggedAddIsRetriedUntilItCommits() async throws { + let harness = DeviceHarness() + let store = InMemoryPairedDeviceListStore() + let canceller = Canceller() + let failer = FailFirstRollback() + let mac = SimulatedDevice(identity: SoftwareDeviceIdentity(), store: store, platform: .macOS, harness: harness, + options: .init(removalHook: { entry in + await canceller.cancel(onRemovalOf: entry) + if failer.shouldFail(entry) { store.failNextSaves(1) } + })) + let phone = harness.makeDevice(.iOS) + try await harness.pair(mac, phone) + harness.clock.advance(by: 11 * 60) + let old = try await XCTUnwrapAsync(try await mac.entry(for: phone)) + canceller.arm(mac.messenger, cancellingOn: old.pairingID) + failer.arm(keeping: old.pairingID) + + // Pairing again; Cancel arrives while the replacing write waits for + // the hook, and the rollback's own write then fails. + let qr = try await mac.messenger.startPairing(displayName: "Studio Mac") + try await phone.messenger.joinPairing(scannedText: qr.text, displayName: "Pocket Phone") + try await mac.poll() + try await phone.poll() + try await mac.poll() + try await mac.confirm() + try await phone.confirm() + try await mac.poll() + if try await mac.entry(for: phone) != nil { + // The poll's own timer pass had not run yet. + await mac.messenger.advanceTimers() + } + XCTAssertEqual(failer.rollbackAttempts, 2, "the failed rollback, then its retry") + await XCTAssertNilAsync(try await mac.entry(for: phone), "the retried rollback removed the flagged entry") + } + func testTheRegistryAnnouncesEveryEntryAWriteRemovesEvenWhenTheListChangesDuringTheHook() async throws { let identity = SoftwareDeviceIdentity() let first = try entry(identity, pairing: 1) @@ -257,3 +294,24 @@ private final class Canceller: @unchecked Sendable { await target?.cancelPairing() } } + +/// Makes the first removal of an entry other than `kept` fail its write. +private final class FailFirstRollback: @unchecked Sendable { + private let lock = NSLock() + private var kept: PairingID? + private var attempts = 0 + + var rollbackAttempts: Int { lock.withLock { attempts } } + + func arm(keeping pairingID: PairingID) { + lock.withLock { kept = pairingID } + } + + func shouldFail(_ entry: PairedDevice) -> Bool { + lock.withLock { + guard let kept, entry.pairingID != kept else { return false } + attempts += 1 + return attempts == 1 + } + } +} From ab63a24cbd43e7b7fb7acec367049a39e3f1a60f Mon Sep 17 00:00:00 2001 From: sudoHG Date: Sun, 15 Nov 2026 22:42:15 +0800 Subject: [PATCH 4/4] Store the Mac without the flag in the opened-request refusal test #340's test pairs a second Mac and expects its request to be refused as from a Mac without the approval flag. Pairing now sets the flag (#336), so the test rewrites that entry as a pre-#336 pairing first. --- iOS/AskKeyiOSKitTests/OpenedRequestTests.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/iOS/AskKeyiOSKitTests/OpenedRequestTests.swift b/iOS/AskKeyiOSKitTests/OpenedRequestTests.swift index d06e7ac2..a817df45 100644 --- a/iOS/AskKeyiOSKitTests/OpenedRequestTests.swift +++ b/iOS/AskKeyiOSKitTests/OpenedRequestTests.swift @@ -332,6 +332,8 @@ final class OpenedRequestTests: XCTestCase { func testARequestFromAMacWithoutTheApprovalFlagShowsUnavailable() async throws { let other = world.makeMac(name: "Office Mac") try await world.pair(other) + // Pairing sets the flag (#336); this is a Mac paired before it without approval. + try await world.storeWithoutApprovalFlag(other) let name = try await world.sendRequest(from: other).sealed.messageID.text try await tap(name) XCTAssertTrue(world.model.requests.isEmpty)