// This phone's identity — an Ed25519 seed minted once, held in the Keychain, // never rotated, never shared. The PUBLIC half is the device id the server // approves, so a request carries its own key and the server needs no key // column. // // Swift owns the Keychain and nothing else of the identity (design P15, the // Mac's M8): the seed is read here, handed down at `cotton_open` as // `OpenConfig.deviceSecret`, and Rust derives the id and signs. Nothing under // `crates/` calls a Keychain API and nothing else in this app does // either — a second reader would be a second opinion about where this phone's // identity lives. // // Four rules, all of them the Mac's and all of them measured there: // // * **A read is idempotent and never replaces what it finds.** A seed IS an // identity; minting a new one over an old one is not a recovery, it is a // different phone. So a read that FAILS is reported and never repaired. // * **`AfterFirstUnlockThisDeviceOnly`.** `ThisDeviceOnly` is the load-bearing // half: an iCloud or iTunes restore onto another phone carries no key, so a // restored phone is a NEW device and pairs again — the whole point of the // key being an identity rather than a setting, since two phones answering to // one device id is two writers on one approval. // // `AfterFirstUnlock` rather than `WhenUnlocked` because the app does not // only run when somebody is looking at it. A launch while the phone is // locked — a notification's background fetch, the app // resumed behind a lock screen — read `errSecInteractionNotAllowed` on the // stricter setting, which this app turns into `device_key_unreadable`: a // screen whose only button MINTS A NEW IDENTITY. A key that cannot be read // for a few seconds is not a key that is gone. After the first unlock since // boot the item is readable, which is every moment the app can actually run. // Guard: `DeviceKeyTests`. // * **A slot that exists and cannot be read is `device_key_unreadable`, NEVER // a second identity.** Minting over an unreadable slot would strand every // approval the first one holds, silently. The way out is deliberate: // ``DeviceKey/forget(store:)`` from the refusal screen's destructive pill. // * **Never on the main thread.** `SecItemCopyMatching` blocks on a // SecurityAgent prompt whenever the binary's signature has changed since the // item was written. `CottonCore` is an actor and the boot reads it there. // // **The previous app's slot is deliberately not read.** `cotton.device.key` // held a JSON envelope in a different secure store; this app writes a bare // base64url seed under its own account name. A phone upgrading from that build // therefore re-pairs as a NEW device, which is acceptable under // [i-m-the-only-cotton-user-the-app-carries-no-backward-compatibili] and is // written down in Cotton note "The phone and Mac app — how a screen is built". Reading the old slot would // mean carrying that envelope and its keychain service name into a build that // has neither. import Foundation import Security /// Where the seed is kept. A protocol so `DeviceKey`'s rules are provable /// without a Keychain — a simulator's Keychain is shared between test runs and /// a test that mints into it is a test that passes once. public protocol DeviceKeyStore: Sendable { /// The stored seed, or `nil` when there is none yet. Throws only when the /// store itself answered something that is not a secret. func read() throws -> String? /// Store a seed. Refuses to overwrite: answers what is actually there. func writeIfAbsent(_ seed: String) throws -> String /// Forget it. Only ever from a deliberate act. func forget() /// Put `seed` in the slot, over whatever is there. Only ever a re-key's /// promotion (`DeviceKey.promote`), after the server answered the new key. func replace(_ seed: String) throws } /// What the store said when it would not answer. public enum DeviceKeyError: Error, Equatable { /// The store answered, and the answer was not a secret. case storeUnreadable(OSStatus) /// A secret could not be written. case notWritten(OSStatus) /// The system could not give random bytes. case noRandom /// The slot is present and its contents are not a 32-byte seed. NOT "no /// key": this is the refusal the screen calls `device_key_unreadable`. case slotUnreadable } public enum DeviceKey { /// The service every item is filed under. Stable for the life of the app: /// changing it is losing this phone's identity. Per flavor /// (`AppFlavor.phoneKeychainService`) — the real app's is its bundle id, /// `com.cottondb.cotton`, and Cotton Dev never names it. public static let service = AppFlavor.current.phoneKeychainService /// The account name. The previous build's was `cotton.device.key`; see /// above. public static let account = "device-key" /// Where "Re-key this device" keeps the NEW key while its approval is /// asked: beside the key in use, never over it, until the new key's row is /// live (`promote`). A second press finds the same successor here. public static let successorAccount = "device-key-successor" /// A 32-byte seed, base64url unpadded — 43 characters. public static let seedBytes = 32 public static let seedLength = 43 /// The seed, minting one the first time. /// /// Throws ``DeviceKeyError/slotUnreadable`` when the slot is present and /// unreadable, which is the one failure this function must never repair. public static func seed(store: some DeviceKeyStore) throws -> String { if let existing = try store.read() { guard isSeed(existing) else { throw DeviceKeyError.slotUnreadable } return existing } return try store.writeIfAbsent(mint()) } /// Start this phone over: a NEW identity next time. The server will know it /// as a new device, to be paired again. public static func forget(store: some DeviceKeyStore) { store.forget() } /// THE RE-KEY'S LAST STEP, once the server has answered the successor: /// the successor goes into the key's slot and only then leaves its own, /// so a process killed between the two finds the same key in both and a /// launch finishes it (`successorPending`). Answers whether anything moved. @discardableResult public static func promote(successor: some DeviceKeyStore, into current: some DeviceKeyStore) throws -> Bool { guard let next = try successor.read() else { return false } guard isSeed(next) else { throw DeviceKeyError.slotUnreadable } if try current.read() != next { try current.replace(next) } successor.forget() return true } /// The successor a launch must still ask about: present and not already /// the key in use. One that IS the key in use is a promotion that was cut /// short after its first half, and is finished here. public static func successorPending(successor: some DeviceKeyStore, current: some DeviceKeyStore) -> String? { guard let next = try? successor.read(), isSeed(next) else { return nil } if (try? current.read()) == next { successor.forget() return nil } return next } /// Is this what we wrote — 43 base64url characters decoding to 32 bytes? public static func isSeed(_ text: String) -> Bool { guard text.count == seedLength else { return false } return decode(text)?.count == seedBytes } static func mint() throws -> String { var bytes = [UInt8](repeating: 0, count: seedBytes) guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw DeviceKeyError.noRandom } return encode(Data(bytes)) } /// base64url, unpadded — what Rust decodes and what `x-cotton-device` /// carries. public static func encode(_ data: Data) -> String { data.base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") } public static func decode(_ text: String) -> Data? { var padded = text .replacingOccurrences(of: "-", with: "+") .replacingOccurrences(of: "_", with: "/") while padded.count % 4 != 0 { padded.append("=") } return Data(base64Encoded: padded) } } /// The real store — the Security framework's whole surface in this app. public struct KeychainDeviceKeyStore: DeviceKeyStore { private let service: String private let account: String public init(service: String = DeviceKey.service, account: String = DeviceKey.account) { self.service = service self.account = account } public func read() throws -> String? { KeychainGate.check(service: service, account: account) var query = KeychainDeviceKeyStore.matchQuery(service: service, account: account) query[kSecReturnData as String] = true query[kSecMatchLimit as String] = kSecMatchLimitOne var found: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &found) if status == errSecItemNotFound { return nil } guard status == errSecSuccess, let data = found as? Data else { throw DeviceKeyError.storeUnreadable(status) } migrateAccessibility() return String(decoding: data, as: UTF8.self) } /// Move an item written by an earlier build onto /// `AfterFirstUnlockThisDeviceOnly`. /// /// **The phone in somebody's pocket already HAS a key**, written under /// `WhenUnlockedThisDeviceOnly`. Shipping the new attribute without this /// would leave that phone reading its old item for ever — and reading it /// only while unlocked, which is the failure being repaired. `SecItemUpdate` /// re-files the same bytes: the identity does not change, so no server /// re-approves anything. /// /// Best effort and never reported: the seed has already been read by here, /// and failing a launch because an accessibility attribute could not be /// updated would be worse than the thing it fixes. The next read tries /// again. private func migrateAccessibility() { KeychainGate.check(service: service, account: account) let query = KeychainDeviceKeyStore.matchQuery(service: service, account: account) let attributes: [String: Any] = [ kSecAttrAccessible as String: KeychainDeviceKeyStore.accessibility ] _ = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) } public func replace(_ seed: String) throws { KeychainGate.check(service: service, account: account) let query = KeychainDeviceKeyStore.matchQuery(service: service, account: account) let status = SecItemUpdate(query as CFDictionary, [kSecValueData as String: Data(seed.utf8)] as CFDictionary) if status == errSecItemNotFound { _ = try writeIfAbsent(seed) return } guard status == errSecSuccess else { throw DeviceKeyError.notWritten(status) } } public func writeIfAbsent(_ seed: String) throws -> String { KeychainGate.check(service: service, account: account) var attributes = KeychainDeviceKeyStore.addAttributes(service: service, account: account) attributes[kSecValueData as String] = Data(seed.utf8) let status = SecItemAdd(attributes as CFDictionary, nil) if status == errSecDuplicateItem { // Somebody won the race. Theirs is the one this install has. guard let existing = try read() else { throw DeviceKeyError.storeUnreadable(status) } return existing } guard status == errSecSuccess else { throw DeviceKeyError.notWritten(status) } return seed } public func forget() { KeychainGate.check(service: service, account: account) SecItemDelete( KeychainDeviceKeyStore.matchQuery(service: service, account: account) as CFDictionary ) } /// How the item is filed: readable after the first unlock since boot, and /// never carried onto another phone. /// /// One place, read by the ADD and by the migration, so the two cannot come /// to disagree about what this build writes. static var accessibility: CFString { kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly } /// How the item is FOUND — class, service, account, and deliberately no /// accessibility. /// /// **A search attribute filters, and that is the trap.** `kSecAttrAccessible` /// in a match query means "an item filed THIS way", so a query carrying the /// new value would not match the item the last build wrote: the read would /// answer `errSecItemNotFound`, the app would treat it as a phone with no /// key, mint a second identity, and every approval the first one holds /// would be stranded — the exact failure `DeviceKey`'s own header refuses, /// arrived at by changing one line. static func matchQuery(service: String, account: String) -> [String: Any] { [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account, ] } /// How the item is WRITTEN: the match query plus this build's /// accessibility. static func addAttributes(service: String, account: String) -> [String: Any] { var attributes = matchQuery(service: service, account: account) attributes[kSecAttrAccessible as String] = accessibility return attributes } } /// A store in memory — the double every `DeviceKey` test drives, and the one /// way to reproduce `device_key_unreadable` without corrupting a real Keychain. public final class InMemoryDeviceKeyStore: DeviceKeyStore, @unchecked Sendable { private let lock = NSLock() private var stored: String? public private(set) var mintCount = 0 public init(seeded: String? = nil) { stored = seeded } public func read() throws -> String? { lock.lock() defer { lock.unlock() } return stored } public func writeIfAbsent(_ seed: String) throws -> String { lock.lock() defer { lock.unlock() } if let stored { return stored } stored = seed mintCount += 1 return seed } public func forget() { lock.lock() defer { lock.unlock() } stored = nil } public func replace(_ seed: String) throws { lock.lock() defer { lock.unlock() } stored = seed } }