From 222b4fe117e121458a5b3181aae2a5493902c2b3 Mon Sep 17 00:00:00 2001 From: sudoHG Date: Mon, 16 Nov 2026 10:58:48 +0800 Subject: [PATCH 1/3] Vault: keep the card and flag under a stored pairing ID A write that kept a stored entry's device ID and pairing ID but carried another card was treated as an add, so with the pairing authorization it could change the entry's approval flag or swap its approval key, and the Broker kept the pairing's active-approver generation. The stored entry is now the one with the same pairing ID. A flag change for it (same device ID and pairing ID, whatever the card) is refused as approverNotAuthorized, as ADR 0014 words it, and another card under that pairing ID as pairingNotAuthorized, since pairing again derives a new pairing ID. The Broker removal also compares the card. ADR 0014 names the card case in the Vault write rule. --- Sources/AskKeyVault/Vault+Devices.swift | 53 ++++---- .../DeviceApproverFlagTests.swift | 119 +++++++++++++++--- docs/adr/0014-remote-approval.md | 2 +- 3 files changed, 137 insertions(+), 37 deletions(-) diff --git a/Sources/AskKeyVault/Vault+Devices.swift b/Sources/AskKeyVault/Vault+Devices.swift index 1097bcc..65f15d0 100644 --- a/Sources/AskKeyVault/Vault+Devices.swift +++ b/Sources/AskKeyVault/Vault+Devices.swift @@ -18,11 +18,14 @@ public enum DeviceStorageError: Error, Equatable, Sendable { /// decode. It is refused, not repaired; resetting the identity deletes it. case listRefused /// A list change would add a device the person did not authorize, with - /// system authentication, in the current pairing session. + /// system authentication, in the current pairing session, or store + /// another card under a pairing ID the list already stores, which no + /// pairing does: pairing again derives a new pairing ID. case pairingNotAuthorized /// 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). + /// already stored, whatever card the change carries (same device ID and + /// pairing ID; ADR 0014 → Approvers). case approverNotAuthorized /// A local erase is running or was interrupted; device storage stays /// closed until it finishes. @@ -337,31 +340,37 @@ extension Vault { } } - /// Writes a list the registry prepared. A device that was not on the - /// 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 - /// 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). + /// Writes a list the registry prepared. An entry whose pairing ID is not + /// on the stored list 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 entry's card says iOS. A pairing + /// ID names one pairing, so an entry under a stored pairing ID is that + /// stored entry: the write may change its name and delivery records, but + /// changing its flag (same device ID and pairing ID, whatever the card) + /// is refused as `approverNotAuthorized`, and storing another card under + /// its pairing ID as `pairingNotAuthorized`, because pairing again + /// derives a new pairing ID. 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() 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. + // The stored entry is the one with the same pairing ID, and it + // keeps its card, so no write swaps the approval key that checks + // every Allow, or the flag, while the Broker's set, keyed by + // pairing ID, keeps that pairing's generation. func storedEntry(_ device: PairedDevice) -> PairedDevice? { - stored.devices.first { - $0.deviceID == device.deviceID && $0.pairingID == device.pairingID && $0.card == device.card + stored.devices.first { $0.pairingID == device.pairingID } + } + for device in list.devices { + guard let entry = storedEntry(device) else { continue } + if entry.deviceID == device.deviceID, entry.isApprover != device.isApprover { + throw DeviceStorageError.approverNotAuthorized } + if entry.card != device.card { throw DeviceStorageError.pairingNotAuthorized } } - 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 } if !added.isEmpty { try requireDeviceManagementSessionDroppingAuthorization() @@ -372,8 +381,10 @@ extension Vault { throw DeviceStorageError.approverNotAuthorized } } + // An approver stays in the set only if the write keeps its entry + // with the same pairing ID, card and flag. for device in stored.devices where device.isApprover && !list.devices.contains(where: { - $0.deviceID == device.deviceID && $0.pairingID == device.pairingID && $0.isApprover + $0.pairingID == device.pairingID && $0.card == device.card && $0.isApprover }) { approvalRequests.removeActiveApprover(pairingID: device.pairingID.rawValue) } diff --git a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift index b2914b8..c2198f7 100644 --- a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift +++ b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift @@ -1,6 +1,7 @@ @testable import AskKeyBroker @testable import AskKeyDevices import AskKeyDevicesTestSupport +import CryptoKit import Foundation import XCTest @testable import AskKeyVault @@ -30,6 +31,21 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { return changed } + /// An identity with this message key, so with its device ID, and new + /// agreement and approval keys. + private func sameDeviceID(as messageKey: P256.Signing.PrivateKey) -> SoftwareDeviceIdentity { + SoftwareDeviceIdentity(messageKey: messageKey, agreementKey: .init(), approvalKey: .init()) + } + + /// An entry under the pairing ID made of `byte`, with a card that + /// `identity` signed at `seconds`. + private func entry(_ identity: SoftwareDeviceIdentity, platform: DevicePlatform = .iOS, + signedAt seconds: TimeInterval = 1_800_000_000, pairingID byte: UInt8) throws -> PairedDevice { + let card = try DeviceCard.make(identity: identity, platform: platform, createdAt: Date(timeIntervalSince1970: seconds)) + return PairedDevice(card: card, pairingID: try XCTUnwrap(PairingID(rawValue: Data(repeating: byte, count: 16))), + displayName: "Synthetic Phone", pairedAt: Date(timeIntervalSince1970: seconds + 100)) + } + private func isApprover(_ device: PairedDevice, in library: AgentAccessPolicyLibrary) async throws -> Bool { try await library.vault.pairedDeviceRegistry().list().device(device.deviceID)?.isApprover == true } @@ -135,26 +151,74 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { 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) + let messageKey = P256.Signing.PrivateKey() + let identity = sameDeviceID(as: messageKey) + let phone = try entry(identity, pairingID: 0x3C) 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 generation = try activate(phone, in: library.vault) + // Same device ID and pairing ID, flag kept, another card. Each used to + // be an add, which the pairing authorization let through while the + // Broker kept the pairing's generation. + let swaps = [("another approval key", try entry(sameDeviceID(as: messageKey), pairingID: 0x3C)), + ("a newer card", try entry(identity, signedAt: 1_800_000_600, pairingID: 0x3C)), + ("a Mac card", try entry(identity, platform: .macOS, pairingID: 0x3C))] 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))) + let epoch = library.vault.deviceState.currentEpoch + for (name, swap) in swaps { + XCTAssertEqual(swap.deviceID, phone.deviceID, name) + XCTAssertNotEqual(swap.card, phone.card, name) + await assertRefused(.pairingNotAuthorized, library, "\(name) without the pairing authorization") { + try await registry.apply(.add(self.flagged(swap))) + } + try library.vault.authorizeDevicePairing(with: phone.deviceID, using: .allow) + await assertRefused(.pairingNotAuthorized, library, "\(name) under the pairing authorization") { + try await registry.apply(.add(self.flagged(swap))) + } + let stored = try await registry.list() + await assertRefused(.pairingNotAuthorized, library, "\(name) in a list written directly") { + try library.vault.savePairedDevices(try self.list(stored, replacing: self.flagged(swap)), epoch: epoch) + } + } + // Another device cannot take the stored pairing ID either. + let other = try entry(SoftwareDeviceIdentity(), pairingID: 0x3C) + try library.vault.authorizeDevicePairing(with: other.deviceID, using: .allow) + await assertRefused(.pairingNotAuthorized, library, "another device under the stored pairing ID") { + try await registry.apply(.add(self.flagged(other))) + } + let stored = try await registry.list().devices + XCTAssertEqual(stored, [flagged(phone)]) + XCTAssertEqual(library.vault.approvalRequests.activeApproverGeneration(pairingID: phone.pairingID.rawValue), generation, + "the pairing keeps its authority with the card it was granted for") + } + + func testACardSwapCannotChangeTheFlag() async throws { + let library = try makeLibrary() + let phoneKey = P256.Signing.PrivateKey() + let otherKey = P256.Signing.PrivateKey() + let phone = try entry(sameDeviceID(as: phoneKey), pairingID: 0x3C) + let unflagged = try entry(sameDeviceID(as: otherKey), pairingID: 0x4D) + try await pairApprover(phone, in: library) + try await pair(unflagged, in: library) + let generation = try activate(phone, in: library.vault) + let registry = try library.vault.pairedDeviceRegistry() + // Under the device's pairing authorization, which used to make a card swap an add with any flag. + try library.vault.authorizeDevicePairing(with: unflagged.deviceID, using: .allow) + let flaggedSwap = flagged(try entry(sameDeviceID(as: otherKey), pairingID: 0x4D)) + await assertRefused(.approverNotAuthorized, library, "a stored entry's flag turned on with another iOS card") { + try await registry.apply(.add(flaggedSwap)) } 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 unflaggedSwap = try entry(sameDeviceID(as: phoneKey), pairingID: 0x3C) + await assertRefused(.approverNotAuthorized, library, "a stored flag turned off with another card") { + try await registry.apply(.add(unflaggedSwap)) } - let stored = try await registry.list().device(phone.deviceID) - XCTAssertEqual(stored?.card, phone.card) + let phoneFlag = try await isApprover(phone, in: library) + let otherFlag = try await isApprover(unflagged, in: library) + XCTAssertTrue(phoneFlag) + XCTAssertFalse(otherFlag) + XCTAssertTrue(try library.vault.activateStoredApprovers(only: unflagged.pairingID).isEmpty, + "the unflagged pairing never joins the set") + XCTAssertEqual(library.vault.approvalRequests.activeApproverGeneration(pairingID: phone.pairingID.rawValue), generation) } func testOtherChangesToAnApproverNeedNoAuthorization() async throws { @@ -216,6 +280,31 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { } } + /// A device's card changes only by pairing again, under a new pairing ID: + /// the old pairing leaves the Broker's set and the new entry is flagged. + func testPairingAgainWithANewCardEndsTheOldAuthorityAndFlagsTheNewEntry() async throws { + for start in ["flagged", "unflagged"] { + let library = try makeLibrary() + let approvals = library.vault.approvalRequests + let messageKey = P256.Signing.PrivateKey() + let phone = try entry(sameDeviceID(as: messageKey), pairingID: 0x3C) + if start == "flagged" { try await pairApprover(phone, in: library) } else { try await pair(phone, in: library) } + let old = start == "flagged" ? try activate(phone, in: library.vault) : nil + let before = approvals.activeApproverRevocationCount() + let again = try entry(sameDeviceID(as: messageKey), signedAt: 1_800_000_600, pairingID: 0x5C) + try await pairApprover(again, in: library) + let stored = try await library.vault.pairedDeviceRegistry().list().devices + XCTAssertEqual(stored, [flagged(again)], start) + XCTAssertNil(approvals.activeApproverGeneration(pairingID: phone.pairingID.rawValue), start) + if old != nil { + XCTAssertGreaterThan(approvals.activeApproverRevocationCount(), before, "the old pairing left the set first") + } + let added = try library.vault.activateStoredApprovers(only: again.pairingID) + XCTAssertEqual(Set(added.keys), [again.pairingID], start) + if let old { XCTAssertGreaterThan(try XCTUnwrap(added[again.pairingID]), old, start) } + } + } + func testARefusedWriteLeavesTheBrokerSetAlone() async throws { let library = try makeLibrary() let device = try syntheticDevice() diff --git a/docs/adr/0014-remote-approval.md b/docs/adr/0014-remote-approval.md index acf719a..6d06dd7 100644 --- a/docs/adr/0014-remote-approval.md +++ b/docs/adr/0014-remote-approval.md @@ -42,7 +42,7 @@ This ADR records those decisions as decided and fixes what #308 left open. Where - **Pairing makes an approver** ([#336](https://github.com/sudoHG/AskKey/issues/336)). An iPhone that a pairing adds to the Mac's list becomes an **approver** with that list write, for every Ask credential, and can decide requests once the App has added it to the Broker's active-approver set right after (see below); a Mac that a pairing adds to an iPhone's list is one whose requests that iPhone accepts. Neither device has a switch, an approver code or a per-credential setting, and only removing the pairing ends approval (see [Revocation](#revocation-removal-and-account-changes)). - **What the person agrees to.** Pairing exists only for approval, so the consent is part of it. On the Mac, the pairing sheet says before the QR code, and again before the system authentication that confirms the pairing, that the iPhone will be able to approve this Mac's agent read requests, and the second time also what a request sends to it: the agent's name, the credential's name, the command and folder and the delivered names, encrypted to that iPhone; never a value. On the iPhone, the screen with **Confirm Pairing** says the same before Face ID. That Face ID is the one ADR 0013 already asks for: it signs the iPhone's pairing confirmation (kind 3), `AskKey pairing confirmation v1` ‖ role 2 ‖ the iPhone's device ID ‖ the transcript hash, with the approval key and a new authentication context, and the Mac verifies that signature with the approval key in the iPhone's card before it adds the device. No other statement or message kind is involved. - **Storage.** Each paired-device list entry keeps the approval flag of list serialization version 2: the Boolean JSON key `approver`, which version 2 requires; version 1 lists decode with every flag off, and every write produces version 2. On the Mac it means "this iPhone may decide my requests", on the iPhone "I accept requests from this Mac". The pairing session sets it in the entry it adds 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 in stage 3, adds its entries without the flag. The platform is what each card declares (ADR 0013), so this is a policy filter, not a check against impostors, which declare iOS. The flag never changes for the life of an entry. An entry stored before #336 keeps the flag it had; one without it neither approves nor is approved for until the person removes it and pairs again. The entry disappears on removal, and pairing again creates a new entry and pairing ID. -- **Vault write rule.** The Mac's list keeps its HMAC label and key (ADR 0013). The Vault accepts a flag that is on only in an entry the write adds, which already needs the management session and the pairing authorization for that device, and only when that entry's card says iOS. It refuses, as `approverNotAuthorized`, a write that adds a flagged entry with another platform or changes the flag of an entry it already stores (same device ID and pairing ID). A device whose flagged entry a write removes or replaces leaves the Broker's active-approver set before the write commits. On the iPhone only the app writes the list. The agent access policy item is not used, so its merge, recovery and delivery-comparison rules do not change. +- **Vault write rule.** The Mac's list keeps its HMAC label and key (ADR 0013). The Vault accepts a flag that is on only in an entry the write adds, which already needs the management session and the pairing authorization for that device, and only when that entry's card says iOS. It refuses, as `approverNotAuthorized`, a write that adds a flagged entry with another platform or changes the flag of an entry it already stores (same device ID and pairing ID, whatever card the write carries). It also refuses, as `pairingNotAuthorized`, a write that stores another card under a pairing ID the list already stores: a pairing ID names one pairing, and pairing again derives a new one, so the card behind a flag, and behind a pairing ID in the active-approver set, never changes either. A device whose flagged entry a write removes or replaces leaves the Broker's active-approver set before the write commits. On the iPhone only the app writes the list. The agent access policy item is not used, so its merge, recovery and delivery-comparison rules do not change. - **Active-approver set.** The Broker keeps an in-memory set of active approvers: for each, its pairing ID as an opaque 16-byte value (`AskKeyBroker` does not depend on `AskKeyDevices`) and an **enablement generation**, a number the Broker assigns from a counter that only grows. It also keeps a **revocation counter**, which every removal from the set and every emptying of it increments. To add approvers, when the device services become ready (every flagged entry), and after a pairing that added a flagged entry commits or whenever the App finds a flagged entry missing from the set while the services are ready (only that pairing ID, so the others keep their generations), the App reads the revocation counter, then reads the list, then asks the Broker to add the entries whose flag is on, passing the counter it read; the Broker refuses the whole addition if the counter has changed, and the App starts again. Every added entry gets a new generation, so reloading the set after a suspension never revives an earlier generation. Every path that ends or suspends a device's authority first removes it from the set under the Broker's approval lock, and only then writes storage or closes requests (see [Revocation](#revocation-removal-and-account-changes)). When it seals a request, the App records the approver's current generation in the outstanding entry, and the Broker's remote path requires the pairing ID to be in the set with that generation, inside the same locked transition from pending. A revocation that has returned therefore wins over every decision not yet applied, including one for a request sealed before an account change suspended the set and a reload restored it. The set is the linearization point. ### When a request goes to an approver From 2df8f6506b9a9f68eb53f9f5c33dde8ec24cf150 Mon Sep 17 00:00:00 2001 From: sudoHG Date: Mon, 16 Nov 2026 12:03:52 +0800 Subject: [PATCH 2/3] Vault: match a shared pairing ID's own entry first; tighten tests Review fixes for the card and flag rule: - Check each entry against the stored entry with the same device ID and pairing ID first, so a list an earlier build stored with one pairing ID on two devices can still be renamed and emptied; no third device joins that pairing ID. - End the pairing authorization before each unauthorized swap attempt, correct the note on the Mac card swap, and show that a swap refuses a write that also carries an authorized add without using it up. - Doc and comment wording: a write may change anything but the card and flag; the card comparison in the Broker removal is defense in depth. --- Sources/AskKeyVault/Vault+Devices.swift | 24 ++++++--- .../DeviceApproverFlagTests.swift | 54 +++++++++++++++++-- 2 files changed, 66 insertions(+), 12 deletions(-) diff --git a/Sources/AskKeyVault/Vault+Devices.swift b/Sources/AskKeyVault/Vault+Devices.swift index 65f15d0..74354ea 100644 --- a/Sources/AskKeyVault/Vault+Devices.swift +++ b/Sources/AskKeyVault/Vault+Devices.swift @@ -346,13 +346,15 @@ extension Vault { /// 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 pairing /// ID names one pairing, so an entry under a stored pairing ID is that - /// stored entry: the write may change its name and delivery records, but - /// changing its flag (same device ID and pairing ID, whatever the card) + /// stored entry: the write may change anything but its card and flag. + /// Changing its flag (same device ID and pairing ID, whatever the card) /// is refused as `approverNotAuthorized`, and storing another card under /// its pairing ID as `pairingNotAuthorized`, because pairing again - /// derives a new pairing ID. 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). + /// derives a new pairing ID; when one write breaks the rule twice, the + /// first such entry decides the error. 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() @@ -360,9 +362,13 @@ extension Vault { // The stored entry is the one with the same pairing ID, and it // keeps its card, so no write swaps the approval key that checks // every Allow, or the flag, while the Broker's set, keyed by - // pairing ID, keeps that pairing's generation. + // pairing ID, keeps that pairing's generation. The entry with the + // same device ID too comes first, so a list that an earlier + // build stored with a pairing ID shared by two devices can still + // be renamed and have either entry removed. func storedEntry(_ device: PairedDevice) -> PairedDevice? { - stored.devices.first { $0.pairingID == device.pairingID } + stored.devices.first { $0.pairingID == device.pairingID && $0.deviceID == device.deviceID } + ?? stored.devices.first { $0.pairingID == device.pairingID } } for device in list.devices { guard let entry = storedEntry(device) else { continue } @@ -382,7 +388,9 @@ extension Vault { } } // An approver stays in the set only if the write keeps its entry - // with the same pairing ID, card and flag. + // with the same pairing ID, card and flag. The checks above + // already refuse another card under a kept pairing ID; comparing + // the card here too keeps the set right if they ever change. for device in stored.devices where device.isApprover && !list.devices.contains(where: { $0.pairingID == device.pairingID && $0.card == device.card && $0.isApprover }) { diff --git a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift index c2198f7..cb52f03 100644 --- a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift +++ b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift @@ -156,9 +156,10 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { let phone = try entry(identity, pairingID: 0x3C) try await pairApprover(phone, in: library) let generation = try activate(phone, in: library.vault) - // Same device ID and pairing ID, flag kept, another card. Each used to - // be an add, which the pairing authorization let through while the - // Broker kept the pairing's generation. + // Same device ID and pairing ID, flag kept, another card. The iOS + // cards used to be adds, which the pairing authorization let through + // while the Broker kept the pairing's generation; the Mac card failed + // only the platform check. let swaps = [("another approval key", try entry(sameDeviceID(as: messageKey), pairingID: 0x3C)), ("a newer card", try entry(identity, signedAt: 1_800_000_600, pairingID: 0x3C)), ("a Mac card", try entry(identity, platform: .macOS, pairingID: 0x3C))] @@ -167,6 +168,7 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { for (name, swap) in swaps { XCTAssertEqual(swap.deviceID, phone.deviceID, name) XCTAssertNotEqual(swap.card, phone.card, name) + library.vault.endDevicePairingAuthorization() await assertRefused(.pairingNotAuthorized, library, "\(name) without the pairing authorization") { try await registry.apply(.add(self.flagged(swap))) } @@ -185,12 +187,56 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { await assertRefused(.pairingNotAuthorized, library, "another device under the stored pairing ID") { try await registry.apply(.add(self.flagged(other))) } + // A swap refuses the whole write, even beside the add the pairing + // authorization covers, and leaves that authorization for the add. + let tablet = try entry(SoftwareDeviceIdentity(), pairingID: 0x4D) + try library.vault.authorizeDevicePairing(with: tablet.deviceID, using: .allow) + let before = try await registry.list() + let swap = flagged(try entry(sameDeviceID(as: messageKey), pairingID: 0x3C)) + await assertRefused(.pairingNotAuthorized, library, "a swap written with an authorized add") { + var list = try self.list(before, replacing: swap) + try list.apply(.add(self.flagged(tablet))) + try library.vault.savePairedDevices(list, epoch: epoch) + } + try await registry.apply(.add(flagged(tablet))) let stored = try await registry.list().devices - XCTAssertEqual(stored, [flagged(phone)]) + XCTAssertEqual(stored, [flagged(phone), flagged(tablet)]) XCTAssertEqual(library.vault.approvalRequests.activeApproverGeneration(pairingID: phone.pairingID.rawValue), generation, "the pairing keeps its authority with the card it was granted for") } + /// A list that an earlier build stored with one pairing ID on two + /// devices stays writable: each entry is checked against its own stored + /// entry, and no third device joins that pairing ID. + func testAStoredListWithASharedPairingIDCanStillBeRenamedAndEmptied() async throws { + let library = try makeLibrary() + let first = flagged(try entry(SoftwareDeviceIdentity(), pairingID: 0x3C)) + let second = try entry(SoftwareDeviceIdentity(), pairingID: 0x3C) + library.keys.deviceItems[.pairedDevices] = try PairedDeviceListAuthentication.seal( + try PairedDeviceList(devices: [first, second]), using: library.key) + _ = try activate(first, in: library.vault) + let registry = try library.vault.pairedDeviceRegistry() + let third = try entry(SoftwareDeviceIdentity(), pairingID: 0x3C) + try library.vault.authorizeDevicePairing(with: third.deviceID, using: .allow) + await assertRefused(.pairingNotAuthorized, library, "a third device under the shared pairing ID") { + try await registry.apply(.add(third)) + } + await assertRefused(.approverNotAuthorized, library, "the second entry's flag turned on") { + try await registry.apply(.add(self.flagged(second))) + } + library.vault.endManagementSession() + try await registry.apply(.rename(second.deviceID, pairingID: second.pairingID, displayName: "Renamed Phone")) + try await registry.apply(.remove(first.deviceID, pairingID: first.pairingID)) + XCTAssertNil(library.vault.approvalRequests.activeApproverGeneration(pairingID: first.pairingID.rawValue), + "removing the flagged entry ends the pairing ID's authority") + let remaining = try await registry.list().devices + XCTAssertEqual(remaining.map(\.deviceID), [second.deviceID]) + XCTAssertEqual(remaining.first?.displayName, "Renamed Phone") + try await registry.apply(.remove(second.deviceID, pairingID: second.pairingID)) + let empty = try await registry.list().devices + XCTAssertTrue(empty.isEmpty) + } + func testACardSwapCannotChangeTheFlag() async throws { let library = try makeLibrary() let phoneKey = P256.Signing.PrivateKey() From f8e205a6ab0c890d67c3d4d347e155572ba4edb3 Mon Sep 17 00:00:00 2001 From: sudoHG Date: Mon, 16 Nov 2026 12:13:05 +0800 Subject: [PATCH 3/3] Vault tests: cover a swap beside a rename and a shared ID's card swap Round 2 review fixes: - A card swap written with a rename of another entry is one add under the device's authorization, which the card-blind rule accepted; it is now refused. - In a list stored with a shared pairing ID, another approval key for an entry is refused. - The write rule's doc comment names the shared pairing ID case. --- Sources/AskKeyVault/Vault+Devices.swift | 4 +++- .../DeviceApproverFlagTests.swift | 18 +++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Sources/AskKeyVault/Vault+Devices.swift b/Sources/AskKeyVault/Vault+Devices.swift index 74354ea..5942836 100644 --- a/Sources/AskKeyVault/Vault+Devices.swift +++ b/Sources/AskKeyVault/Vault+Devices.swift @@ -346,7 +346,9 @@ extension Vault { /// 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 pairing /// ID names one pairing, so an entry under a stored pairing ID is that - /// stored entry: the write may change anything but its card and flag. + /// stored entry (in a list an earlier build stored with a pairing ID + /// shared by two devices, the one with its device ID): the write may + /// change anything but its card and flag. /// Changing its flag (same device ID and pairing ID, whatever the card) /// is refused as `approverNotAuthorized`, and storing another card under /// its pairing ID as `pairingNotAuthorized`, because pairing again diff --git a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift index cb52f03..e487a67 100644 --- a/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift +++ b/Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift @@ -199,6 +199,16 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { try library.vault.savePairedDevices(list, epoch: epoch) } try await registry.apply(.add(flagged(tablet))) + // The swap as the only change to the phone's entry, beside a rename + // of the tablet: one add under the phone's authorization, which the + // card-blind rule accepted. + try library.vault.authorizeDevicePairing(with: phone.deviceID, using: .allow) + let paired = try await registry.list() + await assertRefused(.pairingNotAuthorized, library, "a swap written with a rename") { + var list = try self.list(paired, replacing: swap) + try list.apply(.rename(tablet.deviceID, pairingID: tablet.pairingID, displayName: "Renamed Tablet")) + try library.vault.savePairedDevices(list, epoch: epoch) + } let stored = try await registry.list().devices XCTAssertEqual(stored, [flagged(phone), flagged(tablet)]) XCTAssertEqual(library.vault.approvalRequests.activeApproverGeneration(pairingID: phone.pairingID.rawValue), generation, @@ -210,8 +220,9 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { /// entry, and no third device joins that pairing ID. func testAStoredListWithASharedPairingIDCanStillBeRenamedAndEmptied() async throws { let library = try makeLibrary() + let secondKey = P256.Signing.PrivateKey() let first = flagged(try entry(SoftwareDeviceIdentity(), pairingID: 0x3C)) - let second = try entry(SoftwareDeviceIdentity(), pairingID: 0x3C) + let second = try entry(sameDeviceID(as: secondKey), pairingID: 0x3C) library.keys.deviceItems[.pairedDevices] = try PairedDeviceListAuthentication.seal( try PairedDeviceList(devices: [first, second]), using: library.key) _ = try activate(first, in: library.vault) @@ -224,6 +235,11 @@ final class DeviceApproverFlagTests: RemoteApprovalVaultTestCase { await assertRefused(.approverNotAuthorized, library, "the second entry's flag turned on") { try await registry.apply(.add(self.flagged(second))) } + try library.vault.authorizeDevicePairing(with: second.deviceID, using: .allow) + let secondSwap = try entry(sameDeviceID(as: secondKey), pairingID: 0x3C) + await assertRefused(.pairingNotAuthorized, library, "another approval key for the second entry") { + try await registry.apply(.add(secondSwap)) + } library.vault.endManagementSession() try await registry.apply(.rename(second.deviceID, pairingID: second.pairingID, displayName: "Renamed Phone")) try await registry.apply(.remove(first.deviceID, pairingID: first.pairingID))