diff --git a/README.md b/README.md index 9be3662..3ccdf5a 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Once the iPhone is paired, a read request that waits for you also goes to it: at A request sent to the iPhone contains the agent's name and the purpose it states (both declared by the agent, not verified), the credential's name, the command line and working directory as the approval prompt shows them, the program's name, the names the credential is delivered as (environment variables and temporary files) with each part's name for a credential that has several, the deadline, the decisions offered with the length of a timed allowance, when Ask Key last started on the Mac, and a random ID and a digest that tie the answer to this one request. It never contains a credential's value or the content of any of its parts, file contents, the rest of the environment, the content of a write, the vault key, anything about Hidden credentials, or the Mac's name. -The iPhone's notification shows the request as one sentence, for example “Codex” on “MacBook Pro” wants to use “GitHub Token” to run deploy.sh, and only after Ask Key on the iPhone has fetched, decrypted and verified it as a request from a Mac you turned approval on for. Otherwise it says “A paired device sent a message.” A notification never shows a credential's value, the command's arguments, the folder or the variable names. The iPhone's Show Previews setting decides whether the details appear on the Lock Screen (by default only when the iPhone is unlocked), and delivered notifications stay in Notification Center until you clear them. Decide on the card in the Ask Key app, not on a notification's text: anyone who can write to your iCloud can make your devices show a notification with any text under Ask Key's name. The design is recorded in [ADR 0014](docs/adr/0014-remote-approval.md). +The iPhone's notification shows the request as one sentence, for example “Codex” on “MacBook Pro” wants to use “GitHub Token” to run deploy.sh, and only after Ask Key on the iPhone has fetched, decrypted and verified it as a request from a paired Mac whose requests this iPhone approves. Otherwise it says “A paired device sent a message.” A notification never shows a credential's value, the command's arguments, the folder or the variable names. The iPhone's Show Previews setting decides whether the details appear on the Lock Screen (by default only when the iPhone is unlocked), and delivered notifications stay in Notification Center until you clear them. Decide on the card in the Ask Key app, not on a notification's text: anyone who can write to your iCloud can make your devices show a notification with any text under Ask Key's name. The design is recorded in [ADR 0014](docs/adr/0014-remote-approval.md). ## Upgrade diff --git a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift index 2adebb5..7fff03b 100644 --- a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift +++ b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift @@ -11,18 +11,17 @@ extension DeviceCoordinator { /// its failure counts as "not applied". static let applyAttempts = 3 - /// The handler `AskKeyDevices` calls with every verified kind 10–14 + /// The handler `AskKeyDevices` calls with every verified kind 10–13 /// 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 - /// a decision or a receipt; an approver confirmation, retired by #336, - /// is refused like any kind the Mac does not expect. + /// a decision or a receipt. 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 .request, .closed, .confirmation: + case .request, .closed: return .refused(.unexpectedKind) } } diff --git a/Sources/AskKeyBroker/BrokerApprovalStateMachine+Approvers.swift b/Sources/AskKeyBroker/BrokerApprovalStateMachine+Approvers.swift index 69aaeeb..0ca2149 100644 --- a/Sources/AskKeyBroker/BrokerApprovalStateMachine+Approvers.swift +++ b/Sources/AskKeyBroker/BrokerApprovalStateMachine+Approvers.swift @@ -16,9 +16,10 @@ extension BrokerApprovalStateMachine { /// `revocationCount`. Refuses the whole addition if any removal or /// emptying happened since. Every added entry gets a new generation from /// a counter that only grows, also one already in the set, so neither a - /// reload nor turning approval off and on revives an earlier generation - /// (ADR 0014). After a flag write, add only the newly enabled device, so - /// other approvers keep theirs. Returns the generation of every given ID. + /// reload nor a repeated addition revives an earlier generation (ADR + /// 0014). After a pairing's add, or for a flagged entry the set is + /// missing, add only that pairing ID, so other approvers keep theirs. + /// Returns the generation of every given ID. @discardableResult package func addActiveApprovers( _ pairingIDs: [Data], revocationCount: UInt64 diff --git a/Sources/AskKeyDevices/Approval/ApprovalMessages.swift b/Sources/AskKeyDevices/Approval/ApprovalMessages.swift index cf77362..e31da79 100644 --- a/Sources/AskKeyDevices/Approval/ApprovalMessages.swift +++ b/Sources/AskKeyDevices/Approval/ApprovalMessages.swift @@ -185,53 +185,6 @@ public struct ApprovalReceipt: Hashable, Sendable { } } -/// Kind 14, the iPhone's approver confirmation, 113 bytes: -/// -/// pairing ID (16) ‖ layout version (1) ‖ code proof (32) -/// ‖ approval-key signature (64) over the confirmation statement -public struct ApproverConfirmation: Hashable, Sendable { - public static let byteCount = 113 - - public let pairingID: PairingID - /// The App compares it in constant time with its own (`ApproverCode`). - public let codeProof: Data - let signature: Data - - /// `AskKey approver confirmation v1\0` ‖ iPhone's device ID ‖ Mac's - /// device ID ‖ pairing ID ‖ code proof. - public static func statement(phone: DeviceID, mac: DeviceID, pairingID: PairingID, codeProof: Data) -> Data { - var writer = ByteWriter() - writer.append(DomainLabel.approverConfirmation) - writer.append(phone.rawValue) - writer.append(mac.rawValue) - writer.append(pairingID.rawValue) - writer.append(codeProof) - return writer.data - } - - static func encode(pairingID: PairingID, codeProof: Data, signature: Data) -> Data { - var writer = ByteWriter() - ApprovalLayout.writeHeader(pairingID, into: &writer) - writer.append(codeProof) - writer.append(signature) - return writer.data - } - - init(decoding payload: Data) throws { - self = try MessagePayload.decode(payload) { reader in - ApproverConfirmation(pairingID: try ApprovalLayout.readHeader(&reader), - codeProof: try ApprovalLayout.readDigest(&reader), - signature: try reader.readBytes(ApprovalLayout.signatureByteCount)) - } - } - - private init(pairingID: PairingID, codeProof: Data, signature: Data) { - self.pairingID = pairingID - self.codeProof = codeProof - self.signature = signature - } -} - /// The binding digest (ADR 0014 → Encodings): SHA-256 over /// `AskKey approval binding v1\0` and eight length-prefixed UTF-8 strings, /// exactly as the Broker holds them, with no case folding or normalization. diff --git a/Sources/AskKeyDevices/Approval/ApprovalTypes.swift b/Sources/AskKeyDevices/Approval/ApprovalTypes.swift index 1d62cf4..74ce1a3 100644 --- a/Sources/AskKeyDevices/Approval/ApprovalTypes.swift +++ b/Sources/AskKeyDevices/Approval/ApprovalTypes.swift @@ -39,7 +39,7 @@ public enum ApprovalClosedOutcome: UInt8, Hashable, Sendable, CaseIterable { case decidedOnAnotherApprover = 3 case expired = 4 /// The agent cancelled, the credential changed, agent access was - /// paused, or this approver was turned off or removed. + /// paused, or this approver was removed or its pairing replaced. case cancelled = 5 /// The Mac verified the decision but could not apply it as signed. case notApplied = 6 @@ -111,7 +111,7 @@ public enum ApprovalMessageError: Error, Equatable, Sendable { case invalidClosedOutcome } -/// The rules shared by every kind 10–14 payload (ADR 0014 → Encodings): +/// The rules shared by every kind 10–13 payload (ADR 0014 → Encodings): /// each starts with the pairing ID and the layout version, and text fields /// are length-prefixed UTF-8 without control or line-break characters. enum ApprovalLayout { diff --git a/Sources/AskKeyDevices/Approval/ApprovalVerification.swift b/Sources/AskKeyDevices/Approval/ApprovalVerification.swift index 2517260..50e6266 100644 --- a/Sources/AskKeyDevices/Approval/ApprovalVerification.swift +++ b/Sources/AskKeyDevices/Approval/ApprovalVerification.swift @@ -1,20 +1,19 @@ import CryptoKit import Foundation -/// The content of a verified kind 10–14 message. +/// The content of a verified kind 10–13 message. public enum ApprovalMessage: Hashable, Sendable { case request(ApprovalRequest) case decision(ApprovalDecision) case closed(ApprovalClosed) case receipt(ApprovalReceipt) - case confirmation(ApproverConfirmation) } -/// A kind 10–14 message that passed every rule `AskKeyDevices` checks: +/// A kind 10–13 message that passed every rule `AskKeyDevices` checks: /// ADR 0013's refusal rules, the payload layout, the pairing ID against the -/// sender's current entry, and the approval-key signature of decisions and -/// confirmations (ADR 0014 → Verifying and applying a decision, checks 1, 3 -/// and 6). The App checks the rest against its own state. +/// sender's current entry, and the approval-key signature of decisions +/// (ADR 0014 → Verifying and applying a decision, checks 1, 3 and 6). The +/// App checks the rest against its own state. public struct VerifiedApprovalMessage: Hashable, Sendable { /// The sender's entry on this device's list when the message was verified. public let sender: PairedDevice @@ -34,15 +33,13 @@ public struct VerifiedApprovalMessage: Hashable, Sendable { public var senderID: DeviceID { sender.deviceID } /// The request this message is about: a request's own digest, or the - /// request digest a decision, closed message or receipt carries; nil - /// for a confirmation. - public var requestDigest: Data? { + /// request digest a decision, closed message or receipt carries. + public var requestDigest: Data { switch message { case .request: return digest case .decision(let decision): return decision.requestDigest case .closed(let closed): return closed.requestDigest case .receipt(let receipt): return receipt.requestDigest - case .confirmation: return nil } } /// The pairing ID the payload carries, which is the sender's current one. @@ -61,19 +58,19 @@ public enum ApprovalMessageHandling: Hashable, Sendable { case failed } -/// Handles verified kind 10–14 messages for the App. Calls for one message +/// Handles verified kind 10–13 messages for the App. Calls for one message /// ID never overlap; calls for different messages can, when the zone poll /// and a named fetch run at the same time, so the handler keeps its own /// state consistent. public typealias ApprovalMessageHandler = @Sendable (VerifiedApprovalMessage) async -> ApprovalMessageHandling enum ApprovalVerification { - /// The checks of a kind 10–14 message whose sender is `entry` and whose + /// The checks of a kind 10–13 message whose sender is `entry` and whose /// message-key signature already verified: the payload layout /// (`malformed`), the pairing ID against the entry (`bindingMismatch`), /// a request's times against its inner message's, and the approval-key - /// signature of an Allow or a confirmation over the statement rebuilt - /// from the signed fields (`badSignature`). + /// signature of an Allow over the statement rebuilt from the signed + /// fields (`badSignature`). static func verify(_ inner: InnerMessage, from entry: PairedDevice) -> Result { let message: ApprovalMessage let pairingID: PairingID @@ -91,9 +88,6 @@ enum ApprovalVerification { case .approvalReceipt: let receipt = try ApprovalReceipt(decoding: inner.payload) (message, pairingID) = (.receipt(receipt), receipt.pairingID) - case .approverConfirmation: - let confirmation = try ApproverConfirmation(decoding: inner.payload) - (message, pairingID) = (.confirmation(confirmation), confirmation.pairingID) default: return .failure(.unexpectedKind) } @@ -114,13 +108,6 @@ enum ApprovalVerification { return .failure(.badSignature) } } - case .confirmation(let confirmation): - let statement = ApproverConfirmation.statement(phone: inner.sender, mac: inner.recipient, - pairingID: confirmation.pairingID, - codeProof: confirmation.codeProof) - guard isValid(confirmation.signature, over: statement, by: entry.card.approvalPublicKey) else { - return .failure(.badSignature) - } case .closed, .receipt: break } diff --git a/Sources/AskKeyDevices/Approval/ApproverCode.swift b/Sources/AskKeyDevices/Approval/ApproverCode.swift deleted file mode 100644 index 7c6dcf4..0000000 --- a/Sources/AskKeyDevices/Approval/ApproverCode.swift +++ /dev/null @@ -1,67 +0,0 @@ -import CryptoKit -import Foundation - -/// The six-digit approver code of ADR 0014 → Approvers. The Mac draws it -/// and shows it as `123 456`; the person types it on the iPhone, which -/// sends only its code proof. It is never sent, logged or put in a -/// notification, so its description and mirror are redacted. -public struct ApproverCode: Sendable, CustomStringConvertible, CustomDebugStringConvertible, - CustomReflectable { - /// 0 ..< 1,000,000. - let value: UInt32 - - init(value: UInt32) { - precondition(value < 1_000_000) - self.value = value - } - - /// Drawn uniformly from 000000–999999 with the system's random number generator. - public static func random() -> ApproverCode { - var generator = SystemRandomNumberGenerator() - return ApproverCode(value: UInt32.random(in: 0...999_999, using: &generator)) - } - - /// The code typed on the iPhone: exactly six ASCII digits once white - /// space (the Unicode `White_Space` property) is removed; nil otherwise, - /// and then nothing may be sent. - public init?(typed text: String) { - let scalars = text.unicodeScalars.filter { !$0.properties.isWhitespace } - guard scalars.count == 6, scalars.allSatisfy({ (0x30...0x39).contains($0.value) }) else { return nil } - value = scalars.reduce(UInt32(0)) { $0 * 10 + ($1.value - 0x30) } - } - - /// Six digits with leading zeros, such as `042917`. - public var digits: String { - let text = String(value) - return String(repeating: "0", count: 6 - text.count) + text - } - - /// The digits in two groups of three, such as `042 917`. - public var formatted: String { "\(digits.prefix(3)) \(digits.suffix(3))" } - - public var description: String { "ApproverCode(redacted)" } - public var debugDescription: String { description } - public var customMirror: Mirror { Mirror(self, children: [:]) } - - /// HMAC-SHA256 over the Mac's device ID ‖ the iPhone's device ID ‖ the - /// pairing ID, keyed with HKDF-SHA256 of the six ASCII digits (salt: the - /// pairing ID; info: `AskKey approver code v1\0`; 32 bytes). - public func proof(mac: DeviceID, phone: DeviceID, pairingID: PairingID) -> Data { - let key = HKDF.deriveKey(inputKeyMaterial: SymmetricKey(data: Data(digits.utf8)), - salt: pairingID.rawValue, info: DomainLabel.approverCode, outputByteCount: 32) - let code = HMAC.authenticationCode(for: mac.rawValue + phone.rawValue + pairingID.rawValue, using: key) - return Data(code) - } - - /// Whether a received proof is this code's proof for the three IDs. The - /// comparison takes the same time wherever the proofs differ. - public func matches(proof received: Data, mac: DeviceID, phone: DeviceID, pairingID: PairingID) -> Bool { - let expected = proof(mac: mac, phone: phone, pairingID: pairingID) - guard received.count == expected.count else { return false } - var difference: UInt8 = 0 - for (lhs, rhs) in zip(expected, received) { - difference |= lhs ^ rhs - } - return difference == 0 - } -} diff --git a/Sources/AskKeyDevices/Approval/DeviceMessageSealer.swift b/Sources/AskKeyDevices/Approval/DeviceMessageSealer.swift index 192f85c..d3a8b49 100644 --- a/Sources/AskKeyDevices/Approval/DeviceMessageSealer.swift +++ b/Sources/AskKeyDevices/Approval/DeviceMessageSealer.swift @@ -20,7 +20,7 @@ public struct SealedApprovalRequest: Hashable, Sendable { public var requestDigest: Data { sealed.digest } } -/// Seals kind 10–14 messages and delivery check replies without any state, +/// Seals kind 10–13 messages and delivery check replies without any state, /// for a recipient entry the caller holds: the messenger's current list, or /// the card the Mac held before a removal for a closing message. Every /// message uses base-mode HPKE; its sent time is this sealer's clock when it @@ -108,21 +108,6 @@ public struct DeviceMessageSealer: Sendable { messageID: ApprovalReceipt.receiptID(for: content.responseID)) } - /// Kind 14 to the Mac `mac`: the code proof for the typed code, signed - /// with the approval key over the confirmation statement, which asks for - /// Face ID or Touch ID. Throws `DeviceIdentityError` from the prompt. - public func sealApproverConfirmation(_ code: ApproverCode, to mac: PairedDevice, - approvalReason: String) async throws -> SealedDeviceMessage { - let phone = identity.deviceID - let proof = code.proof(mac: mac.deviceID, phone: phone, pairingID: mac.pairingID) - let statement = ApproverConfirmation.statement(phone: phone, mac: mac.deviceID, pairingID: mac.pairingID, - codeProof: proof) - let signature = try await identity.signWithApprovalKey(statement, reason: approvalReason) - guard signature.count == ApprovalLayout.signatureByteCount else { throw DeviceIdentityError.authenticationFailed } - let payload = ApproverConfirmation.encode(pairingID: mac.pairingID, codeProof: proof, signature: signature) - return try sealApprovalKind(.approverConfirmation, payload, to: mac) - } - /// Kind 8 for a verified delivery check, signed with the message key, as /// the notification extension answers on a locked phone. public func sealDeliveryCheckReply(answering check: VerifiedDeliveryCheck) throws -> SealedDeviceMessage { diff --git a/Sources/AskKeyDevices/Approval/DeviceMessageVerifier.swift b/Sources/AskKeyDevices/Approval/DeviceMessageVerifier.swift index de6b7b5..b7edb7f 100644 --- a/Sources/AskKeyDevices/Approval/DeviceMessageVerifier.swift +++ b/Sources/AskKeyDevices/Approval/DeviceMessageVerifier.swift @@ -19,7 +19,7 @@ public enum DeviceMessageVerdict: Hashable, Sendable { /// Extension): against the list it is given, it applies the same envelope, /// signature, payload, pairing-ID and approval-signature checks as /// `DeviceMessenger`, in the same order, for delivery checks and kinds -/// 10–14. It does not check replay, does not hold a message from an open +/// 10–13. It does not check replay, does not hold a message from an open /// pairing session's peer as the messenger does, and does not know the /// caller's handler or state: `.approval` means only that the checks /// `AskKeyDevices` owns passed. It deletes nothing, writes nothing and never diff --git a/Sources/AskKeyDevices/Encoding/ByteCoding.swift b/Sources/AskKeyDevices/Encoding/ByteCoding.swift index f886d60..59929ba 100644 --- a/Sources/AskKeyDevices/Encoding/ByteCoding.swift +++ b/Sources/AskKeyDevices/Encoding/ByteCoding.swift @@ -107,8 +107,6 @@ enum DomainLabel { static let approvalBinding = label("AskKey approval binding v1") static let approvalDecision = label("AskKey approval decision v1") static let approvalReceiptID = label("AskKey approval receipt id v1") - static let approverConfirmation = label("AskKey approver confirmation v1") - static let approverCode = label("AskKey approver code v1") private static func label(_ text: String) -> Data { precondition(text.allSatisfy(\.isASCII)) diff --git a/Sources/AskKeyDevices/Messages/MessageKind.swift b/Sources/AskKeyDevices/Messages/MessageKind.swift index 67059bc..885b279 100644 --- a/Sources/AskKeyDevices/Messages/MessageKind.swift +++ b/Sources/AskKeyDevices/Messages/MessageKind.swift @@ -24,13 +24,16 @@ public enum MessageKind: UInt8, Hashable, Sendable, CaseIterable { case approvalDecision = 11 case approvalClosed = 12 case approvalReceipt = 13 - case approverConfirmation = 14 + // 14 is reserved: it was the approver confirmation, retired by #336 + // (ADR 0014). Like any kind this build does not know, a record of kind + // 14 is refused as `unknownKind` and an inner message of kind 14 as + // `malformed`. A later kind takes a new number. /// Pairing messages live at most as long as a session. public static let pairingLifetime: TimeInterval = 10 * 60 public static let deliveryCheckLifetime: TimeInterval = 10 * 60 public static let unpairNoticeLifetime: TimeInterval = 30 * 24 * 60 * 60 - /// Kinds 10–14 (ADR 0014). + /// Kinds 10–13 (ADR 0014). public static let approvalLifetime: TimeInterval = 10 * 60 /// Delivery checks and approval requests may show a notification on an @@ -52,15 +55,15 @@ public enum MessageKind: UInt8, Hashable, Sendable, CaseIterable { .pairingReveal: return true case .unpairNotice, .deliveryCheck, .deliveryCheckReply, .approvalRequest, .approvalDecision, .approvalClosed, - .approvalReceipt, .approverConfirmation: + .approvalReceipt: return false } } - /// Kinds 10–14, which carry remote approval (ADR 0014). + /// Kinds 10–13, which carry remote approval (ADR 0014). public var isApproval: Bool { switch self { - case .approvalRequest, .approvalDecision, .approvalClosed, .approvalReceipt, .approverConfirmation: + case .approvalRequest, .approvalDecision, .approvalClosed, .approvalReceipt: return true default: return false @@ -76,7 +79,7 @@ public enum MessageKind: UInt8, Hashable, Sendable, CaseIterable { return Self.deliveryCheckLifetime case .unpairNotice: return Self.unpairNoticeLifetime - case .approvalRequest, .approvalDecision, .approvalClosed, .approvalReceipt, .approverConfirmation: + case .approvalRequest, .approvalDecision, .approvalClosed, .approvalReceipt: return Self.approvalLifetime } } diff --git a/Sources/AskKeyDevices/Messenger/DeviceMessenger+Approval.swift b/Sources/AskKeyDevices/Messenger/DeviceMessenger+Approval.swift index cb26e77..ab89faf 100644 --- a/Sources/AskKeyDevices/Messenger/DeviceMessenger+Approval.swift +++ b/Sources/AskKeyDevices/Messenger/DeviceMessenger+Approval.swift @@ -18,7 +18,7 @@ public struct NamedFetchReport: Hashable, Sendable { struct ApprovalHandlerFailure: Error {} extension DeviceMessenger { - /// Kinds 10–14 from a device on the list whose message-key signature + /// Kinds 10–13 from a device on the list whose message-key signature /// verified: `AskKeyDevices` checks the payload, the pairing ID and the /// approval-key signature, then the handler checks the rest and commits /// the effect. A handler failure counts toward the three failures. With diff --git a/Sources/AskKeyDevices/Messenger/DeviceMessenger+Inbox.swift b/Sources/AskKeyDevices/Messenger/DeviceMessenger+Inbox.swift index 3bb1946..351a506 100644 --- a/Sources/AskKeyDevices/Messenger/DeviceMessenger+Inbox.swift +++ b/Sources/AskKeyDevices/Messenger/DeviceMessenger+Inbox.swift @@ -207,7 +207,7 @@ extension DeviceMessenger { return nil } - /// Kinds 6–8 and 10–14 come from a device on the list. A message from the open + /// Kinds 6–8 and 10–13 come from a device on the list. A message from the open /// session's peer that is not on the list yet, that is bound to the /// pairing this session is replacing, or that is an unpair notice, is /// held until the session ends, so a notice from before a removal and a diff --git a/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift b/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift index 9813cc4..d3f1d22 100644 --- a/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift +++ b/Sources/AskKeyDevices/Messenger/DeviceMessenger.swift @@ -122,7 +122,7 @@ public actor DeviceMessenger { /// The inbox change token after the last fully processed fetch. public internal(set) var inboxToken: InboxChangeToken? - /// `approvalHandler` receives every verified kind 10–14 message (ADR + /// `approvalHandler` receives every verified kind 10–13 message (ADR /// 0014); without one they are refused as `unexpectedKind`. /// `removalHook` is called with each entry before any removal of it /// commits, including one caused by an unpair notice or by pairing again. @@ -140,7 +140,7 @@ public actor DeviceMessenger { deviceID = DeviceID(messagePublicKey: identity.messagePublicKey) } - /// Seals kind 10–14 messages with this device's identity and clock. + /// Seals kind 10–13 messages with this device's identity and clock. public nonisolated var sealer: DeviceMessageSealer { DeviceMessageSealer(identity: identity, clock: clock) } diff --git a/Sources/AskKeyDevices/PairedDevices/PairedDeviceList.swift b/Sources/AskKeyDevices/PairedDevices/PairedDeviceList.swift index 42dade2..3524a3a 100644 --- a/Sources/AskKeyDevices/PairedDevices/PairedDeviceList.swift +++ b/Sources/AskKeyDevices/PairedDevices/PairedDeviceList.swift @@ -70,10 +70,6 @@ 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. 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) } public enum PairedDeviceChangeOutcome: Hashable, Sendable { @@ -142,8 +138,6 @@ public struct PairedDeviceList: Hashable, Sendable { device.lastDeliveryCheck = result if case .replied(let date) = result { device.markReached(date) } } - case .setApprover(let id, let pairingID, let enabled): - return update(id, pairingID) { $0.isApprover = enabled } } } diff --git a/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift b/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift index 0aba22a..4a98d8a 100644 --- a/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift +++ b/Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift @@ -188,12 +188,12 @@ final class RemoteApprovalPairingTests: AskKeyAppTestCase { XCTAssertEqual(Set(harness.entries(pending).map(\.approverID)), [harness.phone.deviceID, second.deviceID]) } - func testARetiredApproverConfirmationIsRefusedAsAnUnexpectedKind() async throws { + func testARecordOfTheRetiredKind14IsRefusedAsAnUnknownKind() async throws { try await harness.pairApprover() let generation = try harness.generation(of: harness.phone) - try await harness.phone.sendRetiredApproverConfirmation(to: XCTUnwrap(harness.macDeviceID)) + try await harness.phone.sendRecordOfRetiredKind14(to: XCTUnwrap(harness.macDeviceID)) await harness.coordinator.refresh() - XCTAssertTrue(harness.refusals.contains(.unexpectedKind)) + XCTAssertEqual(harness.refusals, [.unknownKind]) XCTAssertEqual(try harness.generation(of: harness.phone), generation, "nothing changed") XCTAssertEqual(harness.coordinator.devices.map(\.isApprover), [true]) } diff --git a/Tests/AskKeyBrokerTests/ActiveApproverSetTests.swift b/Tests/AskKeyBrokerTests/ActiveApproverSetTests.swift index 32e4bf3..161967b 100644 --- a/Tests/AskKeyBrokerTests/ActiveApproverSetTests.swift +++ b/Tests/AskKeyBrokerTests/ActiveApproverSetTests.swift @@ -33,7 +33,7 @@ final class ActiveApproverSetTests: RemoteApprovalTestCase { let machine = configuredMachine() let first = try machine.addActiveApprovers([phone], revocationCount: machine.activeApproverRevocationCount()) let phoneGeneration = try XCTUnwrap(first[phone]) - // After the tablet's flag write only the tablet is added; the phone keeps its generation. + // After the tablet's pairing adds it, only the tablet is added; the phone keeps its generation. let tabletGeneration = try XCTUnwrap(try machine.addActiveApprovers( [tablet], revocationCount: machine.activeApproverRevocationCount())[tablet]) XCTAssertGreaterThan(tabletGeneration, phoneGeneration) diff --git a/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift b/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift index e8fc29c..db1666a 100644 --- a/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift +++ b/Tests/AskKeyDevicesTests/ApprovalFlagTests.swift @@ -13,20 +13,21 @@ final class ApprovalFlagTests: XCTestCase { pairingID: PairingID(rawValue: Data(repeating: pairing, count: 16))!, displayName: name, pairedAt: now) } - func testTheFlagStartsOffAndOnlySetApproverChangesIt() throws { + func testTheFlagStartsOffAndNoListChangeTurnsItOn() throws { let device = try entry() - XCTAssertFalse(device.isApprover) + XCTAssertFalse(device.isApprover, "the initializer leaves the flag off") + let id = device.deviceID var list = try PairedDeviceList(devices: [device]) - XCTAssertEqual(try list.apply(.setApprover(device.deviceID, pairingID: device.pairingID, enabled: true)), .applied) - XCTAssertTrue(list.devices[0].isApprover) - let otherPairing = PairingID(rawValue: Data(repeating: 9, count: 16))! - XCTAssertEqual(try list.apply(.setApprover(device.deviceID, pairingID: otherPairing, enabled: false)), .dropped, - "a change prepared against another pairing is dropped") - XCTAssertTrue(list.devices[0].isApprover) - XCTAssertEqual(try list.apply(.setApprover(device.deviceID, pairingID: device.pairingID, enabled: false)), .applied) - XCTAssertFalse(list.devices[0].isApprover) - XCTAssertEqual(try list.apply(.setApprover(SoftwareDeviceIdentity().deviceID, pairingID: device.pairingID, - enabled: true)), .dropped) + 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: .replied(at: now.addingTimeInterval(7))), + .add(device), + ] + for change in changes { + try list.apply(change) + XCTAssertFalse(try XCTUnwrap(list.device(id)).isApprover, "\(change) leaves the flag off") + } } func testEveryListChangeKeepsTheFlagAndAnAddStoresTheFlagItCarries() throws { @@ -62,10 +63,9 @@ final class ApprovalFlagTests: XCTestCase { } func testSerializationVersionTwoCarriesTheFlag() throws { - let first = try entry(name: "One") - let second = try entry(pairing: 2, name: "Two") - var list = try PairedDeviceList(devices: [first, second]) - try list.apply(.setApprover(second.deviceID, pairingID: second.pairingID, enabled: true)) + var second = try entry(pairing: 2, name: "Two") + second.isApprover = true + let list = try PairedDeviceList(devices: [try entry(name: "One"), second]) let data = try list.serialized() let decoded = try PairedDeviceList(serialized: data) XCTAssertEqual(decoded, list) @@ -78,8 +78,9 @@ final class ApprovalFlagTests: XCTestCase { } func testVersionOneDecodesWithEveryFlagOffAndVersionTwoRequiresIt() throws { - var list = try PairedDeviceList(devices: [try entry(name: "One"), try entry(pairing: 2, name: "Two")]) - try list.apply(.setApprover(list.devices[0].deviceID, pairingID: list.devices[0].pairingID, enabled: true)) + var first = try entry(name: "One") + first.isApprover = true + let list = try PairedDeviceList(devices: [first, try entry(pairing: 2, name: "Two")]) var json = try XCTUnwrap(JSONSerialization.jsonObject(with: try list.serialized()) as? [String: Any]) var entries = try XCTUnwrap(json["devices"] as? [[String: Any]]) diff --git a/Tests/AskKeyDevicesTests/ApprovalFlowTests.swift b/Tests/AskKeyDevicesTests/ApprovalFlowTests.swift index 39b7875..6a0e208 100644 --- a/Tests/AskKeyDevicesTests/ApprovalFlowTests.swift +++ b/Tests/AskKeyDevicesTests/ApprovalFlowTests.swift @@ -4,12 +4,12 @@ import CryptoKit import XCTest /// Two simulated devices with software keys over the in-memory transport: -/// each kind 10–14 message round-trips (ADR 0014; #310 acceptance 2). +/// each kind 10–13 message round-trips (ADR 0014; #310 acceptance 2). final class ApprovalFlowTests: XCTestCase { func testKindsUseTheirRecordTypesLifetimesAndBaseMode() { - let approval: [MessageKind] = [.approvalRequest, .approvalDecision, .approvalClosed, .approvalReceipt, - .approverConfirmation] - XCTAssertEqual(approval.map(\.rawValue), [10, 11, 12, 13, 14]) + let approval: [MessageKind] = [.approvalRequest, .approvalDecision, .approvalClosed, .approvalReceipt] + XCTAssertEqual(approval.map(\.rawValue), [10, 11, 12, 13]) + XCTAssertNil(MessageKind(rawValue: 14), "kind 14 is reserved (#336)") for kind in approval { XCTAssertEqual(kind.recordType, kind == .approvalRequest ? .alert : .quiet) XCTAssertEqual(kind.maximumLifetime, 600) @@ -139,7 +139,7 @@ final class ApprovalFlowTests: XCTestCase { } } - func testClosedReceiptAndConfirmationRoundTrip() async throws { + func testClosedAndReceiptRoundTrip() async throws { let fixture = try await ApprovalFixture.make() let sealed = try await fixture.sendRequest() try await fixture.phone.poll() @@ -180,23 +180,6 @@ final class ApprovalFlowTests: XCTestCase { to: macEntry)) { XCTAssertEqual($0 as? ApprovalMessageError, .invalidClosedOutcome) } - - // Confirmation: the phone sends the proof of the typed code; the Mac's handler compares it. - let code = ApproverCode.random() - let typed = try XCTUnwrap(ApproverCode(typed: code.formatted)) - let confirmation = try await fixture.phone.messenger.sealer.sealApproverConfirmation( - typed, to: try await fixture.phoneEntryForMac(), approvalReason: "Approve requests") - XCTAssertEqual(fixture.phone.identity.approvalReasons.last, "Approve requests") - try await fixture.harness.transport.send(confirmation.envelope) - await XCTAssertEqualAsync(try await fixture.mac.poll().processed, 1) - let confirmed = try XCTUnwrap(fixture.outstanding.messages.last) - guard case .confirmation(let content) = confirmed.message else { return XCTFail("confirmation") } - XCTAssertNil(confirmed.requestDigest) - XCTAssertEqual(confirmed.senderID, fixture.phone.id) - XCTAssertTrue(code.matches(proof: content.codeProof, mac: fixture.mac.id, phone: fixture.phone.id, - pairingID: confirmed.pairingID)) - XCTAssertFalse(ApproverCode(typed: code.digits == "000000" ? "000001" : "000000")! - .matches(proof: content.codeProof, mac: fixture.mac.id, phone: fixture.phone.id, pairingID: confirmed.pairingID)) } func testAClosedMessageIsHandledBeforeTheRequestItEnds() async throws { @@ -232,18 +215,28 @@ final class ApprovalFlowTests: XCTestCase { XCTAssertNotEqual(new.pairingID, old.pairingID, "the phone holds the new pairing") await XCTAssertEqualAsync(try await fixture.macEntryForPhone().pairingID, old.pairingID) - let confirmation = try await phone.messenger.sealer.sealApproverConfirmation(ApproverCode.random(), to: new, - approvalReason: "Approve") - try await harness.transport.send(confirmation.envelope) + // A request the Mac seals for the entry it is about to add, and the phone's receipt for it. + let upcoming = PairedDevice(card: old.card, pairingID: new.pairingID, displayName: old.displayName, + pairedAt: old.pairedAt) + let sealed = try mac.messenger.sealer.sealApprovalRequest( + ApprovalVectorTests.vectorDisplay, bindingDigest: ApprovalFixture.binding, + deadline: mac.clock.now().addingTimeInterval(120), launchTime: Date(timeIntervalSince1970: 1_799_000_000), + offers: .denyOnly, timedDuration: 0, to: upcoming) + fixture.outstanding.record(sealed, to: phone.id) + try await harness.transport.send(sealed.sealed.envelope) + try await phone.poll() + let receipt = try phone.messenger.sealer.sealApprovalReceipt(answering: fixture.phoneRequest()) + try await harness.transport.send(receipt.envelope) let early = try await mac.poll() - XCTAssertEqual(early.outcomes[confirmation.envelope.recordName], .keptForSession) + XCTAssertEqual(early.outcomes[receipt.envelope.recordName], .keptForSession) XCTAssertTrue(fixture.outstanding.messages.isEmpty, "the handler has not seen it") - XCTAssertEqual(harness.transport.records(in: mac.id).map(\.recordName), [confirmation.envelope.recordName]) + XCTAssertEqual(harness.transport.records(in: mac.id).map(\.recordName), [receipt.envelope.recordName]) harness.transport.releaseDelayed() let later = try await mac.poll() - XCTAssertEqual(later.outcomes[confirmation.envelope.recordName], .processed) + XCTAssertEqual(later.outcomes[receipt.envelope.recordName], .processed) XCTAssertEqual(fixture.outstanding.messages.map(\.pairingID), [new.pairingID]) + XCTAssertEqual(fixture.outstanding.entry(sealed.request.responseID)?.delivered, true) XCTAssertEqual(fixture.removals.entries.map(\.pairingID), [old.pairingID], "the old entry was announced first") } diff --git a/Tests/AskKeyDevicesTests/ApprovalPayloadTests.swift b/Tests/AskKeyDevicesTests/ApprovalPayloadTests.swift index 586dde3..2b63fc1 100644 --- a/Tests/AskKeyDevicesTests/ApprovalPayloadTests.swift +++ b/Tests/AskKeyDevicesTests/ApprovalPayloadTests.swift @@ -2,7 +2,7 @@ import AskKeyDevicesTestSupport import XCTest -/// The kind 10–14 layouts and every malformed case ADR 0014 → Encodings names. +/// The kind 10–13 layouts and every malformed case ADR 0014 → Encodings names. final class ApprovalPayloadTests: XCTestCase { private func fields() throws -> ApprovalRequest.Fields { ApprovalRequest.Fields(pairingID: ApprovalVectorTests.pairingID, responseID: ApprovalVectorTests.responseID, @@ -244,7 +244,7 @@ final class ApprovalPayloadTests: XCTestCase { } } - // MARK: Kinds 11–14 + // MARK: Kinds 11–13 private let header = ApprovalVectorTests.pairingID.rawValue + [1] private let digest = ApprovalVectorTests.requestDigest @@ -340,28 +340,17 @@ final class ApprovalPayloadTests: XCTestCase { } } - func testReceiptAndConfirmationLayouts() throws { + func testReceiptLayout() throws { let receipt = header + digest XCTAssertEqual(receipt.count, ApprovalReceipt.byteCount) XCTAssertEqual(try ApprovalReceipt(decoding: receipt).requestDigest, digest) - let confirmation = header + Data(repeating: 0xCD, count: 32) + Data(repeating: 0xEF, count: 64) - XCTAssertEqual(confirmation.count, ApproverConfirmation.byteCount) - XCTAssertEqual(try ApproverConfirmation(decoding: confirmation).codeProof, Data(repeating: 0xCD, count: 32)) var receiptVersion = receipt receiptVersion[16] = 2 - var confirmationVersion = confirmation - confirmationVersion[16] = 2 let malformedReceipts = [receipt.dropLast(), receipt + [0], receiptVersion] - let malformedConfirmations = [confirmation.dropLast(), confirmation + [0], confirmationVersion] for payload in malformedReceipts { XCTAssertThrowsError(try ApprovalReceipt(decoding: Data(payload))) { XCTAssertEqual($0 as? DeviceMessageRefusal, .malformed) } } - for payload in malformedConfirmations { - XCTAssertThrowsError(try ApproverConfirmation(decoding: Data(payload))) { - XCTAssertEqual($0 as? DeviceMessageRefusal, .malformed) - } - } } } diff --git a/Tests/AskKeyDevicesTests/ApprovalRefusalTests.swift b/Tests/AskKeyDevicesTests/ApprovalRefusalTests.swift index 9a2a936..d3fc467 100644 --- a/Tests/AskKeyDevicesTests/ApprovalRefusalTests.swift +++ b/Tests/AskKeyDevicesTests/ApprovalRefusalTests.swift @@ -3,9 +3,9 @@ import AskKeyDevicesTestSupport import CryptoKit import XCTest -/// Every refusal rule for kinds 10–14, each refused without effect and -/// deleted, and the stateless verifier's verdict for the same envelope -/// (#310 acceptance 3 and 5). +/// Every refusal rule for kinds 10–13 and for kind 14, which is reserved, +/// each refused without effect and deleted, and the stateless verifier's +/// verdict for the same envelope (#310 acceptance 3 and 5; #343). final class ApprovalRefusalTests: XCTestCase { private var fixture: ApprovalFixture! private var request: SealedApprovalRequest! @@ -204,7 +204,7 @@ final class ApprovalRefusalTests: XCTestCase { // MARK: The other kinds' bindings - func testRequestClosedReceiptAndConfirmationWithAnotherPairingIDAreRefused() async throws { + func testRequestClosedAndReceiptWithAnotherPairingIDAreRefused() async throws { let other = PairingID(rawValue: RandomBytes.make(16))! let digest = request.requestDigest var requestFields = ApprovalRequest.Fields(decoding: request.request) @@ -222,31 +222,70 @@ final class ApprovalRefusalTests: XCTestCase { messageID: ApprovalReceipt.receiptID(for: request.request.responseID), sentAt: now), at: fixture.mac, .bindingMismatch) - let proof = Data(repeating: 1, count: 32) - let statement = ApproverConfirmation.statement(phone: fixture.phone.id, mac: fixture.mac.id, pairingID: other, - codeProof: proof) - let signature = try await fixture.phone.identity.signWithApprovalKey(statement, reason: "test") - try await assertRefused(try ApprovalFixture.seal(.approverConfirmation, ApproverConfirmation.encode( - pairingID: other, codeProof: proof, signature: signature), from: fixture.phone, to: fixture.mac, sentAt: now), - at: fixture.mac, .bindingMismatch) } - func testConfirmationNotSignedByTheApprovalKeyOverItsStatementIsRefused() async throws { + // MARK: Kind 14, reserved + + /// Kind 14 was the approver confirmation, retired by #336. A record of + /// kind 14, as an older build sealed it, is refused as an unknown kind + /// from its plaintext kind, before decryption, and an inner message of + /// kind 14 in a record of a known kind is refused as malformed by the + /// inner layout, exactly as for kind 15, which was never assigned: in + /// both directions, through a poll and a named fetch, and with the same + /// verdict from the stateless verifier. + func testKind14IsRefusedLikeAnyUnknownKind() async throws { let pairingID = try await fixture.phoneEntryForMac().pairingID - let proof = ApproverCode.random().proof(mac: fixture.mac.id, phone: fixture.phone.id, pairingID: pairingID) - let statement = ApproverConfirmation.statement(phone: fixture.phone.id, mac: fixture.mac.id, pairingID: pairingID, - codeProof: proof) - let otherMac = ApproverConfirmation.statement(phone: fixture.phone.id, mac: SoftwareDeviceIdentity().deviceID, - pairingID: pairingID, codeProof: proof) - let signatures = [try fixture.phone.identity.signWithMessageKey(statement), - try await fixture.phone.identity.signWithApprovalKey(otherMac, reason: "test"), - try P256.Signing.PrivateKey().signature(for: statement).rawRepresentation] - for signature in signatures { - let payload = ApproverConfirmation.encode(pairingID: pairingID, codeProof: proof, signature: signature) - try await assertRefused(try ApprovalFixture.seal(.approverConfirmation, payload, from: fixture.phone, - to: fixture.mac, sentAt: now), - at: fixture.mac, .badSignature) + // The retired 113-byte layout: pairing ID, layout version, code proof, signature. + let payload = pairingID.rawValue + [1] + Data(repeating: 0xCD, count: 32) + Data(repeating: 0xEF, count: 64) + let routes: [(SimulatedDevice, SimulatedDevice, knownKind: Int64)] = [ + (fixture.phone, fixture.mac, 13), (fixture.mac, fixture.phone, 12), + ] + for kind: UInt8 in [14, 15] { + XCTAssertNil(MessageKind(rawValue: kind)) + for (sender, recipient, knownKind) in routes { + for (recordKind, refusal) in [(Int64(kind), DeviceMessageRefusal.unknownKind), (knownKind, .malformed)] { + try await assertRefused(try ApprovalFixture.seal(rawKind: kind, inRecordOfKind: recordKind, payload, + from: sender, to: recipient, sentAt: now), + at: recipient, refusal) + try await assertRefusedByNamedFetch(try ApprovalFixture.seal(rawKind: kind, inRecordOfKind: recordKind, + payload, from: sender, to: recipient, + sentAt: now), + at: recipient, refusal) + } + } } + // Nothing was handled, and the genuine request is still outstanding. + XCTAssertTrue(fixture.outstanding.messages.isEmpty) + XCTAssertEqual(fixture.phoneInbox.messages.count, 1) + XCTAssertEqual(fixture.outstanding.entry(request.request.responseID)?.delivered, false) + + // The helper seals a valid message for a known kind: the phone's receipt reaches the Mac. + let receipt = try ApprovalFixture.seal(rawKind: MessageKind.approvalReceipt.rawValue, inRecordOfKind: 13, + ApprovalReceipt.encode(pairingID: pairingID, + requestDigest: request.requestDigest), + from: fixture.phone, to: fixture.mac, + messageID: ApprovalReceipt.receiptID(for: request.request.responseID), + sentAt: now) + fixture.harness.transport.insert(receipt, intoInboxOf: fixture.mac.id) + await XCTAssertEqualAsync(try await fixture.mac.poll().processed, 1) + XCTAssertEqual(fixture.outstanding.entry(request.request.responseID)?.delivered, true) + } + + /// A named fetch refuses the record with `refusal`, deletes it, leaves + /// the inbox token, the list and the handler untouched. + private func assertRefusedByNamedFetch(_ envelope: DeviceEnvelope, at device: SimulatedDevice, + _ refusal: DeviceMessageRefusal, file: StaticString = #filePath, + line: UInt = #line) async throws { + fixture.harness.transport.insert(envelope, intoInboxOf: device.id) + let storedList = device.store.storedBytes + let token = await device.messenger.inboxToken + let handledBefore = fixture.handled(by: device) + let report = try await device.messenger.fetchNamedMessages([envelope.recordName]) + XCTAssertEqual(report.outcomes, [envelope.recordName: .refused(refusal)], file: file, line: line) + XCTAssertEqual(fixture.harness.transport.records(in: device.id), [], "refused and deleted", file: file, line: line) + XCTAssertEqual(fixture.handled(by: device), handledBefore, "the handler never ran", file: file, line: line) + XCTAssertEqual(device.store.storedBytes, storedList, "the list is unchanged", file: file, line: line) + await XCTAssertEqualAsync(await device.messenger.inboxToken, token, "the token stays", file: file, line: line) } func testRequestTimesAreCheckedAgainstItsInnerMessage() async throws { diff --git a/Tests/AskKeyDevicesTests/ApprovalTestSupport.swift b/Tests/AskKeyDevicesTests/ApprovalTestSupport.swift index 660bc3b..d10e662 100644 --- a/Tests/AskKeyDevicesTests/ApprovalTestSupport.swift +++ b/Tests/AskKeyDevicesTests/ApprovalTestSupport.swift @@ -88,8 +88,6 @@ final class OutstandingRequests: @unchecked Sendable { } entries[responseID]?.delivered = true return .processed - case .confirmation: - return .processed case .request, .closed: return .refused(.unexpectedKind) } @@ -137,7 +135,7 @@ final class Gate: @unchecked Sendable { /// A Mac and an iPhone paired over the in-memory transport, with the /// Mac's outstanding table and the iPhone's inbox as their handlers, and -/// the approval flag on in both lists. +/// the approval flag the pairing set in both lists (#336). final class ApprovalFixture { let harness = DeviceHarness() let outstanding = OutstandingRequests() @@ -152,8 +150,8 @@ final class ApprovalFixture { return fixture } - /// Makes both devices, runs `beforePairing` for each, pairs them and - /// turns the approval flag on in both lists. + /// Makes both devices, runs `beforePairing` for each and pairs them, + /// which sets the approval flag in both lists. func setUp(beforePairing: ((SimulatedDevice) async throws -> Void)? = nil) async throws { mac = harness.makeDevice(.macOS, approvalHandler: outstanding.handler, removalHook: removals.hook(fixture: self)) phone = harness.makeDevice(.iOS, approvalHandler: phoneInbox.handler) @@ -162,8 +160,7 @@ final class ApprovalFixture { harness.clock.advance(by: 11 * 60) // Past every pairing message's lifetime. for (device, other) in [(mac!, phone!), (phone!, mac!)] { let entry = try await XCTUnwrapAsync(try await device.entry(for: other)) - try await PairedDeviceRegistry(store: device.store).apply(.setApprover(other.id, pairingID: entry.pairingID, - enabled: true)) + XCTAssertTrue(entry.isApprover, "the pairing set the approval flag") } } @@ -248,6 +245,32 @@ final class ApprovalFixture { recipientKey: recipient.identity.agreementPublicKey, preSharedKey: nil, sentAt: sentAt, expiresAt: sentAt + lifetime, messageID: messageID).envelope } + + /// Seals `payload` as an inner message whose kind byte is `innerKind`, + /// in a `QuietMessage` record whose kind field is `recordKind`, with the + /// sender's real message key, so it can carry a kind this build does not + /// know, as an older build or a writer with that key could. + static func seal(rawKind innerKind: UInt8, inRecordOfKind recordKind: Int64, _ payload: Data, + from sender: SimulatedDevice, to recipient: SimulatedDevice, messageID: MessageID = .random(), + sentAt: Int64, lifetime: Int64 = 600) throws -> DeviceEnvelope { + var writer = ByteWriter() + writer.append(InnerMessage.version) + writer.append(innerKind) + writer.append(sender.id.rawValue) + writer.append(recipient.id.rawValue) + writer.append(messageID.rawValue) + writer.appendTime(sentAt) + writer.appendTime(sentAt + lifetime) + writer.appendLengthPrefixed(payload) + writer.append(try sender.identity.signWithMessageKey(DomainLabel.message + writer.data)) + var context = try HPKE.Sender(recipientKey: recipient.identity.agreementPublicKey, + ciphersuite: MessageCodec.ciphersuite, + info: MessageCodec.info(sender: sender.id, recipient: recipient.id)) + let body = Data([MessageCodec.bodyVersion]) + context.encapsulatedKey + (try context.seal(writer.data)) + return DeviceEnvelope(recordType: .quiet, recordName: messageID.text, sender: sender.id.text, + recipient: recipient.id.text, kind: recordKind, sentAt: UnixTime.date(sentAt), + expiresAt: UnixTime.date(sentAt + lifetime), body: body) + } } /// Records each entry the removal hook receives, and whether the entry was diff --git a/Tests/AskKeyDevicesTests/ApprovalTransportRuleTests.swift b/Tests/AskKeyDevicesTests/ApprovalTransportRuleTests.swift index bd09e89..bef87f9 100644 --- a/Tests/AskKeyDevicesTests/ApprovalTransportRuleTests.swift +++ b/Tests/AskKeyDevicesTests/ApprovalTransportRuleTests.swift @@ -3,7 +3,7 @@ import AskKeyDevicesTestSupport import CryptoKit import XCTest -/// ADR 0013's refusal rules apply to each of kinds 10–14: each case is +/// ADR 0013's refusal rules apply to each of kinds 10–13: each case is /// refused without effect and deleted, and the stateless verifier gives the /// same verdict (#310 acceptance 3 and 5). final class ApprovalTransportRuleTests: XCTestCase { @@ -36,20 +36,12 @@ final class ApprovalTransportRuleTests: XCTestCase { appliedDuration: 0), fixture.mac, fixture.phone, 600) case .approvalReceipt: return (ApprovalReceipt.encode(pairingID: pairingID, requestDigest: digest), fixture.phone, fixture.mac, 600) - case .approverConfirmation: - let proof = ApproverCode.random().proof(mac: fixture.mac.id, phone: fixture.phone.id, pairingID: pairingID) - let statement = ApproverConfirmation.statement(phone: fixture.phone.id, mac: fixture.mac.id, - pairingID: pairingID, codeProof: proof) - let signature = try await fixture.phone.identity.signWithApprovalKey(statement, reason: "test") - return (ApproverConfirmation.encode(pairingID: pairingID, codeProof: proof, signature: signature), - fixture.phone, fixture.mac, 600) default: fatalError("not an approval kind") } } - private static let kinds: [MessageKind] = [.approvalRequest, .approvalDecision, .approvalClosed, .approvalReceipt, - .approverConfirmation] + private static let kinds: [MessageKind] = [.approvalRequest, .approvalDecision, .approvalClosed, .approvalReceipt] private func sealed(_ kind: MessageKind, sentAtOffset: Int64 = 0, lifetime: Int64? = nil, identity: (any DeviceIdentity)? = nil) async throws -> (DeviceEnvelope, SimulatedDevice) { @@ -105,6 +97,7 @@ final class ApprovalTransportRuleTests: XCTestCase { ("sender", .routingMismatch, { var e = $0; e.sender = stranger; return e }), ("ciphertext", .decryptionFailed, { var e = $0; e.body[e.body.count - 1] ^= 1; return e }), ("unknown kind", .unknownKind, { var e = $0; e.kind = 15; return e }), + ("reserved kind 14", .unknownKind, { var e = $0; e.kind = 14; e.recordType = .quiet; return e }), ("non-canonical name", .malformed, { var e = $0; e.recordName = e.recordName.uppercased(); return e }), ("fractional time", .malformed, { var e = $0; e.sentAt += 0.5; return e }), ("pairing request kind", .noSession, { var e = $0; e.kind = 1; e.recordType = .quiet; return e }), diff --git a/Tests/AskKeyDevicesTests/ApprovalVectorTests.swift b/Tests/AskKeyDevicesTests/ApprovalVectorTests.swift index 075c7eb..7cc0c09 100644 --- a/Tests/AskKeyDevicesTests/ApprovalVectorTests.swift +++ b/Tests/AskKeyDevicesTests/ApprovalVectorTests.swift @@ -5,7 +5,7 @@ import XCTest /// Fixed vectors of ADR 0014 → Encodings, with the inputs the ADR lists; /// the expected outputs come from an independent Python implementation -/// (hashlib, hmac) recorded in the pull request. +/// (hashlib) recorded in the pull request. final class ApprovalVectorTests: XCTestCase { static let approver = DeviceID(rawValue: Data(0x10...0x1F))! static let requester = DeviceID(rawValue: Data(0x20...0x2F))! @@ -53,43 +53,6 @@ final class ApprovalVectorTests: XCTestCase { XCTAssertEqual(Data(SHA256.hash(data: once)).hex, "0d3be7ecd11377e27d282442edde99f766ae0ea0124721beb8c07afa86901c0e") } - func testCodeProofAndConfirmationStatement() throws { - let code = try XCTUnwrap(ApproverCode(typed: "042917")) - let proof = code.proof(mac: Self.requester, phone: Self.approver, pairingID: Self.pairingID) - XCTAssertEqual(proof.hex, "720c17b6e53689724891e64a1740f0e12d7647cfe0f6dcb3397915136a1fb8a4") - let statement = ApproverConfirmation.statement(phone: Self.approver, mac: Self.requester, pairingID: Self.pairingID, - codeProof: proof) - XCTAssertEqual(Data(SHA256.hash(data: statement)).hex, - "b2c73c19ef9f9350261cfc26c2a2084b9d4e46d4d8267c6fc8274ec92c65cc73") - XCTAssertTrue(code.matches(proof: proof, mac: Self.requester, phone: Self.approver, pairingID: Self.pairingID)) - var wrong = proof - wrong[31] ^= 1 - XCTAssertFalse(code.matches(proof: wrong, mac: Self.requester, phone: Self.approver, pairingID: Self.pairingID)) - XCTAssertFalse(code.matches(proof: proof.prefix(31), mac: Self.requester, phone: Self.approver, - pairingID: Self.pairingID)) - XCTAssertFalse(code.matches(proof: proof, mac: Self.approver, phone: Self.requester, pairingID: Self.pairingID), - "the proof names the Mac and the iPhone in order") - } - - func testApproverCodeEntryAndRedaction() throws { - let code = try XCTUnwrap(ApproverCode(typed: " 042\t917\n")) - XCTAssertEqual(code.digits, "042917") - XCTAssertEqual(code.formatted, "042 917") - XCTAssertEqual(ApproverCode(typed: "042\u{3000}917")?.digits, "042917", "the full-width space is white space") - for invalid in ["04291", "0429170", "04291a", "\u{FF10}42917", "", "042-917", "٠٤٢٩١٧"] { - XCTAssertNil(ApproverCode(typed: invalid), invalid) - } - XCTAssertEqual(String(describing: code), "ApproverCode(redacted)") - XCTAssertFalse(String(reflecting: code).contains("042")) - XCTAssertFalse("\(code)".contains("917")) - var dumped = "" - dump(code, to: &dumped) - XCTAssertFalse(dumped.contains("42917")) - let drawn = (0..<200).map { _ in ApproverCode.random().digits } - XCTAssertTrue(drawn.allSatisfy { $0.count == 6 && $0.allSatisfy(\.isASCII) }) - XCTAssertGreaterThan(Set(drawn).count, 190) - } - // MARK: Requests static let vectorDisplay = ApprovalRequestDisplay( diff --git a/Tests/AskKeyDevicesTests/NamedFetchTests.swift b/Tests/AskKeyDevicesTests/NamedFetchTests.swift index 4fb0458..f314221 100644 --- a/Tests/AskKeyDevicesTests/NamedFetchTests.swift +++ b/Tests/AskKeyDevicesTests/NamedFetchTests.swift @@ -119,10 +119,12 @@ final class NamedFetchTests: XCTestCase { let phone = harness.makeDevice(.iOS) try await harness.pair(mac, phone) harness.clock.advance(by: 11 * 60) - let confirmation = try await phone.messenger.sealer.sealApproverConfirmation( - ApproverCode.random(), to: try await XCTUnwrapAsync(try await phone.entry(for: mac)), approvalReason: "Approve") - try await harness.transport.send(confirmation.envelope) - let name = confirmation.envelope.recordName + let pairingID = try await XCTUnwrapAsync(try await phone.entry(for: mac)).pairingID + let receipt = try ApprovalFixture.seal(.approvalReceipt, ApprovalReceipt.encode( + pairingID: pairingID, requestDigest: Data(repeating: 0x50, count: 32)), from: phone, to: mac, + sentAt: UnixTime.seconds(harness.clock.now())) + try await harness.transport.send(receipt) + let name = receipt.recordName let first = try await mac.poll() XCTAssertEqual(first.outcomes[name], .failed) diff --git a/Tests/AskKeyTestSupport/FakeDeviceServices.swift b/Tests/AskKeyTestSupport/FakeDeviceServices.swift index 3bee674..920c982 100644 --- a/Tests/AskKeyTestSupport/FakeDeviceServices.swift +++ b/Tests/AskKeyTestSupport/FakeDeviceServices.swift @@ -296,17 +296,19 @@ package final class SimulatedPairingPhone: @unchecked Sendable { return sealed } - /// Sends an approver confirmation (kind 14) of an older build, which an - /// amended Mac refuses (#336). Goes with kind 14's code. + /// Sends a record of kind 14, the approver confirmation that older + /// builds sent and #336 retired. The Mac refuses it as an unknown kind + /// from the record's kind alone, so the body is any message sealed to it. @discardableResult - package func sendRetiredApproverConfirmation(to mac: DeviceID) async throws -> SealedDeviceMessage { + package func sendRecordOfRetiredKind14(to mac: DeviceID) async throws -> DeviceEnvelope { 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 + var envelope = try messenger.sealer.sealApprovalClosed(.expired, requestDigest: Data(repeating: 0x5A, count: 32), + to: entry).envelope + envelope.kind = 14 + try await transport.send(envelope) + return envelope } /// Saves an envelope to the Mac's inbox as it is, for example to re-insert one. @@ -333,7 +335,7 @@ package final class SimulatedApproverInbox: @unchecked Sendable { case .closed: receivedClosed.append(message) return .processed - case .decision, .receipt, .confirmation: + case .decision, .receipt: return .refused(.unexpectedKind) } } diff --git a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift index 0651242..b2914b8 100644 --- a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift +++ b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift @@ -22,6 +22,14 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { try await pair(flagged(device), in: library) } + /// `list` with `entry` in place of the entry with its device ID, flag + /// as given, as a write that bypasses the pairing session would hold it. + private func list(_ list: PairedDeviceList, replacing entry: PairedDevice) throws -> PairedDeviceList { + var changed = list + try changed.apply(.add(entry)) + return changed + } + private func isApprover(_ device: PairedDevice, in library: AgentAccessPolicyLibrary) async throws -> Bool { try await library.vault.pairedDeviceRegistry().list().device(device.deviceID)?.isApprover == true } @@ -100,11 +108,13 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { 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)) + let stored = try await registry.list() + let epoch = library.vault.deviceState.currentEpoch + await assertRefused(.approverNotAuthorized, library, "a list written directly turning a stored flag off") { + try library.vault.savePairedDevices(try self.list(stored, replacing: phone), epoch: epoch) } - await assertRefused(.approverNotAuthorized, library, "turning a stored entry's flag on") { - try await registry.apply(.setApprover(unflagged.deviceID, pairingID: unflagged.pairingID, enabled: true)) + await assertRefused(.approverNotAuthorized, library, "a list written directly turning a stored entry's flag on") { + try library.vault.savePairedDevices(try self.list(stored, replacing: self.flagged(unflagged)), epoch: epoch) } // A fresh pairing authorization for the device does not cover its stored entry. try library.vault.authorizeDevicePairing(with: unflagged.deviceID, using: .allow) @@ -114,10 +124,8 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { 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) + await assertRefused(.approverNotAuthorized, library, "the same list written directly under that authorization") { + try library.vault.savePairedDevices(try self.list(stored, replacing: self.flagged(unflagged)), epoch: epoch) } let phoneFlag = try await isApprover(phone, in: library) let otherFlag = try await isApprover(unflagged, in: library) @@ -214,10 +222,12 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { try await pairApprover(device, in: library) let generation = try activate(device, in: library.vault) do { - try await library.vault.pairedDeviceRegistry().apply(.setApprover(device.deviceID, pairingID: device.pairingID, - enabled: false)) + // The stored entry again without its flag. + try await library.vault.pairedDeviceRegistry().apply(.add(device)) XCTFail("A stored flag never changes") - } catch {} + } catch { + XCTAssertEqual(error as? DeviceStorageError, .approverNotAuthorized) + } XCTAssertEqual(library.vault.approvalRequests.activeApproverGeneration(pairingID: device.pairingID.rawValue), generation) } diff --git a/docs/adr/0014-remote-approval.md b/docs/adr/0014-remote-approval.md index d726582..acf719a 100644 --- a/docs/adr/0014-remote-approval.md +++ b/docs/adr/0014-remote-approval.md @@ -133,7 +133,7 @@ For outcomes 2–6 the applied code and duration are 0. Other outcomes are malfo | Approval receipt | 13 | `QuietMessage` | iPhone → Mac | message key | 10 min | 49 | pairing ID and request digest; message ID = the receipt ID | | Reserved | 14 | — | — | — | — | — | — | -Kind 14 was the approver confirmation, retired by [#336](https://github.com/sudoHG/AskKey/issues/336). No amended build sends it, and every amended build refuses a record or inner message of kind 14 (as an unknown kind once `AskKeyDevices` drops it); a later kind takes a new number rather than reusing it. +Kind 14 was the approver confirmation, retired by [#336](https://github.com/sudoHG/AskKey/issues/336). No amended build sends it, and every amended build refuses a record or inner message of kind 14 at the same point and in the same way as any kind it does not know: a record as an unknown kind, from its plaintext kind and before decryption, and an inner message as malformed, when its layout is parsed. A later kind takes a new number rather than reusing it. Within one fetch, pairing kinds come first (ADR 0013), then kind 12, then the other kinds, so a closed message stored before its request keeps the request from being shown. The iPhone refuses a request whose transport expiry is later than its deadline plus 5 minutes. diff --git a/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift b/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift index 0534a33..142c66d 100644 --- a/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift +++ b/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift @@ -25,8 +25,7 @@ extension AppModel { // MARK: Handler - /// Verified kinds 10–13 (a retired kind 14 approver confirmation is - /// refused as unexpected). `AskKeyDevices` checked the envelope, the + /// Verified kinds 10–13. `AskKeyDevices` checked the envelope, the /// signatures, the payload and the pairing ID; this checks the /// direction and the approval flag: a Mac sends only requests and /// closed messages, and only a Mac whose entry carries this iPhone's @@ -43,7 +42,7 @@ extension AppModel { return await accept(request, message, services: services, generation: generation) case .closed(let closed): return await accept(closed, message, services: services, generation: generation) - case .decision, .receipt, .confirmation: + case .decision, .receipt: return .refused(.unexpectedKind) } } diff --git a/iOS/AskKeyiOSKit/Services/DeviceServices.swift b/iOS/AskKeyiOSKit/Services/DeviceServices.swift index ae0b80b..1a46e10 100644 --- a/iOS/AskKeyiOSKit/Services/DeviceServices.swift +++ b/iOS/AskKeyiOSKit/Services/DeviceServices.swift @@ -98,10 +98,9 @@ final class DeviceServices { typealias Handler = @Sendable (VerifiedApprovalMessage, _ generation: Int) async -> ApprovalMessageHandling - /// `approvalHandler` receives verified approval messages (kinds 10–13, - /// and a retired kind 14, which it refuses) with the messenger's - /// generation, and `removalHook` runs before any removal of a Mac - /// commits. + /// `approvalHandler` receives verified approval messages (kinds 10–13) + /// with the messenger's generation, and `removalHook` runs before any + /// removal of a Mac commits. init(identity: any DeviceIdentity, transport: any InboxTransport, listStore: any PairedDeviceListStore, clock: any DeviceClock, inboxToken: InboxChangeToken?, approvalHandler: Handler? = nil, removalHook: PairedDeviceRemovalHook? = nil) { diff --git a/iOS/AskKeyiOSKitTests/LocalizationTests.swift b/iOS/AskKeyiOSKitTests/LocalizationTests.swift index 5f0e8b9..8cc59f3 100644 --- a/iOS/AskKeyiOSKitTests/LocalizationTests.swift +++ b/iOS/AskKeyiOSKitTests/LocalizationTests.swift @@ -49,9 +49,9 @@ final class LocalizationTests: XCTestCase { func testNoRetiredApproverStringRemains() throws { let english = try table("en") let chinese = try table("zh-Hans") - let chineseApproverCode = "\u{5BA1}\u{6279}\u{7801}" + let chineseApprovalCode = "\u{5BA1}\u{6279}\u{7801}" for key in english.keys { - XCTAssertFalse(try XCTUnwrap(chinese[key]).contains(chineseApproverCode), key) + XCTAssertFalse(try XCTUnwrap(chinese[key]).contains(chineseApprovalCode), key) XCTAssertFalse(key.hasPrefix("approver.") || key.hasPrefix("mac.approve") || key.hasPrefix("mac.stop"), key) let value = try XCTUnwrap(english[key]) XCTAssertFalse(value.localizedCaseInsensitiveContains("approver code"), key) diff --git a/iOS/AskKeyiOSNotificationService/Sources/NotificationProcessor.swift b/iOS/AskKeyiOSNotificationService/Sources/NotificationProcessor.swift index 137cca1..8209090 100644 --- a/iOS/AskKeyiOSNotificationService/Sources/NotificationProcessor.swift +++ b/iOS/AskKeyiOSNotificationService/Sources/NotificationProcessor.swift @@ -136,8 +136,8 @@ struct NotificationProcessor: Sendable { } guard !Task.isCancelled else { return .generic(.timedOut) } guard let envelope, envelope.recordName == recordName else { return .generic(.notFound) } - // Read after the fetch, so approval stopped or a Mac removed while - // CloudKit answered is already in the list the checks use. + // Read after the fetch, so a Mac removed while CloudKit answered is + // already gone from the list the checks use. let list: PairedDeviceList do { list = try environment.keychain.pairedDeviceList() diff --git a/iOS/AskKeyiOSNotificationService/Tests/NotificationProcessorTests.swift b/iOS/AskKeyiOSNotificationService/Tests/NotificationProcessorTests.swift index 9296738..7465d88 100644 --- a/iOS/AskKeyiOSNotificationService/Tests/NotificationProcessorTests.swift +++ b/iOS/AskKeyiOSNotificationService/Tests/NotificationProcessorTests.swift @@ -289,7 +289,7 @@ final class NotificationProcessorTests: XCTestCase { try await assertGeneric(world, push, .fetchFailed) } - func testApprovalStoppedWhileTheRecordIsFetchedStaysGeneric() async throws { + func testAMacRemovedWhileTheRecordIsFetchedStaysGeneric() async throws { let world = try NotificationWorld() let push = try world.sendRequest().push let gate = Gate() @@ -297,12 +297,12 @@ final class NotificationProcessorTests: XCTestCase { let environment = try world.environment() let running = Task { await NotificationProcessor(environment: environment).process(PushInfo(userInfo: push)) } while gate.arrived == 0 { await Task.yield() } - try world.setApprover(world.mac, enabled: false) + try world.removeMac(world.mac) gate.open() let decision = await running.value - XCTAssertEqual(decision, .generic(.notApprover)) + XCTAssertEqual(decision, .generic(.refused(.unknownSender))) XCTAssertEqual(world.sent, []) } diff --git a/iOS/AskKeyiOSNotificationService/Tests/NotificationWorld.swift b/iOS/AskKeyiOSNotificationService/Tests/NotificationWorld.swift index 38ec087..3615c58 100644 --- a/iOS/AskKeyiOSNotificationService/Tests/NotificationWorld.swift +++ b/iOS/AskKeyiOSNotificationService/Tests/NotificationWorld.swift @@ -1,4 +1,4 @@ -import AskKeyDevices +@testable import AskKeyDevices import CloudKit import Foundation import UserNotifications @@ -63,23 +63,27 @@ final class NotificationWorld { let identity = TestIdentity() let pairingID = try XCTUnwrap(PairingID(rawValue: Data((0..<16).map { _ in UInt8.random(in: 0...255) }))) let card = try DeviceCard.make(identity: identity, platform: platform, createdAt: clock.now()) - try phoneList.apply(.add(PairedDevice(card: card, pairingID: pairingID, displayName: name, pairedAt: clock.now()))) - if approver { try phoneList.apply(.setApprover(identity.id, pairingID: pairingID, enabled: true)) } + // The approval flag as a pairing sets it (#336); off for an entry stored before #336. + var macEntry = PairedDevice(card: card, pairingID: pairingID, displayName: name, pairedAt: clock.now()) + macEntry.isApprover = approver + try phoneList.apply(.add(macEntry)) keychain.seed(try phoneList.serialized(), for: DeviceKeychainAccount.pairedDevices) let phoneCard = try DeviceCard.make(identity: phone, platform: .iOS, createdAt: clock.now()) var macList = PairedDeviceList() - try macList.apply(.add(PairedDevice(card: phoneCard, pairingID: pairingID, displayName: "Test iPhone", - pairedAt: clock.now()))) - try macList.apply(.setApprover(phone.id, pairingID: pairingID, enabled: true)) + var phoneEntry = PairedDevice(card: phoneCard, pairingID: pairingID, displayName: "Test iPhone", + pairedAt: clock.now()) + phoneEntry.isApprover = true + try macList.apply(.add(phoneEntry)) let mac = Mac(identity: identity, pairingID: pairingID, phoneEntry: try XCTUnwrap(macList.device(phone.id)), listStore: try TestListStore(macList)) macs.append(mac) return mac } - /// Turns a Mac's approval flag on or off on this iPhone, as the app would. - func setApprover(_ mac: Mac, enabled: Bool) throws { - try phoneList.apply(.setApprover(mac.identity.id, pairingID: mac.pairingID, enabled: enabled)) + /// Removes a Mac from this iPhone's list, as the app would; removal is + /// how approval stops (#336). + func removeMac(_ mac: Mac) throws { + try phoneList.apply(.remove(mac.identity.id, pairingID: mac.pairingID)) keychain.seed(try phoneList.serialized(), for: DeviceKeychainAccount.pairedDevices) }