Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 42 additions & 21 deletions Sources/AskKeyVault/Vault+Devices.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -337,31 +340,45 @@ 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 (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
/// 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()
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. 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.deviceID == device.deviceID && $0.pairingID == device.pairingID && $0.card == device.card
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 }
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()
Expand All @@ -372,8 +389,12 @@ 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. 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.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)
}
Expand Down
181 changes: 166 additions & 15 deletions Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
@testable import AskKeyBroker
@testable import AskKeyDevices
import AskKeyDevicesTestSupport
import CryptoKit
import Foundation
import XCTest
@testable import AskKeyVault
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -135,26 +151,136 @@ 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)
let generation = try activate(phone, in: library.vault)
// 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))]
let registry = try library.vault.pairedDeviceRegistry()
let epoch = library.vault.deviceState.currentEpoch
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)))
}
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)))
}
// 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)))
// 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,
"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 secondKey = P256.Signing.PrivateKey()
let first = flagged(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)
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)))
}
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))
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()
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)
// 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)
try await pair(unflagged, in: library)
let generation = try activate(phone, in: library.vault)
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)))
// 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 {
Expand Down Expand Up @@ -216,6 +342,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()
Expand Down
Loading
Loading