// THIS DEVICE'S VAULT KEY — the X25519 private half that opens the passwords. // // The model is `crates/cotton-core/src/vault` and Cotton note "The vault — the honest sentence". // // A second key beside `DeviceKey`, and the two must never be confused. The // device key is Ed25519 and it SIGNS: it is who this phone is, the server // approves it, and every owner request carries it in a header. This one is // X25519 and it UNWRAPS: the server wraps the workspace's vault master key for // its public half, and holding the private half is what lets this phone open a // password without asking anybody. Neither can do the other's job — a signing // key is not a key-agreement key — which is why there are two rather than one // clever one. // // ## Three decisions, each with the failure it avoids // // **THE GUARD IS THE SCREEN'S, NOT THE ITEM'S (e2e rulings R7, R8, R9; 16 Nov // 2026).** Until then the item carried `kSecAccessControlUserPresence`, so // every READ was the Face ID sheet. Recovery needs the key read with nobody // asked: the first sign-in founds with no question (R8), a phone re-opens by // itself once another device approves it, a recovery code or a trusted // person's help opens a new phone, and the iCloud Keychain copy is made in the // background (R7). So the item is now plain, and the prompt moved to // ``VaultKeyring/privateKey()`` (`VaultPresence`, `LAContext`'s // `.deviceOwnerAuthentication`: Face ID, Touch ID or the passcode), which every // reveal, Approve, Allow and Show still goes through; the prompt-free paths // call ``VaultKeyring/quietPrivateKey()`` and nothing else. The data key that // opens every sealed table was already kept this way (`DataKey.swift`). A // phone with no passcode is never blocked (R7): the act runs, as on Android. // // **`AfterFirstUnlockThisDeviceOnly`.** `ThisDeviceOnly` is load-bearing for // the same reason it is on the device key: a restore onto another phone must // not carry the vault (a new iPhone opens through the iCloud Keychain copy // instead, `recovery.openPlatform`, which is a different item made for that). // `AfterFirstUnlock` because the re-open after an approval and the help poll // may run as the app comes back behind the lock screen. // // **A LOST ITEM IS NOT A DISASTER.** If the slot is gone the phone mints a new // key and publishes it (`vault.publishKey`), and another vault device that is // already approved wraps the VMK for it once its code is typed there // (`signin.approve`): the Worker // holds no VMK, so device approval is the only wrap path. So unlike the device key — where an unreadable slot is // a named refusal and never a re-mint, because minting over an identity is a // different phone — this store MAY replace what it cannot read. Nothing is lost // by doing so: the passwords are sealed under the workspace's key, not under // this one. // // ## The Keychain search-attribute trap // // `DeviceKey`'s own header names it and it applies here twice over. **A search // attribute FILTERS.** `kSecAttrAccessible` or `kSecAttrAccessControl` in a // MATCH query means "an item filed exactly this way", so a query carrying them // would not match an item written under any other value: the read answers // `errSecItemNotFound`, the app decides there is no key, mints a second one, // and the wrap the server already wrote is orphaned. So `matchQuery` carries // the class, the service and the account and NOTHING else, exactly as // `KeychainDeviceKeyStore` does, and the access control appears only in the // dictionary handed to `SecItemAdd`. // // ## Never on the main thread // // `SecItemCopyMatching` on a presence-guarded item BLOCKS while the system // draws the Face ID sheet. `CottonCore` is an actor and the reveal reads it // there. // // ## On the simulator // // A simulator with no passcode and no enrolled Face ID asks nothing: the key // is minted, read and used as on a phone with no passcode. Features → Face ID // → Enrolled puts the sheet in front of a reveal, an Approve and an Allow. import CryptoKit import Foundation import LocalAuthentication import Security /// Where this device's vault private key is kept. /// /// A protocol for the reason `DeviceKeyStore` is one: a simulator's Keychain is /// shared between test runs, and a test that mints into the real one is a test /// that passes once. public protocol VaultKeyStore: Sendable { /// The stored key, or `nil` when there is none yet. /// /// Throws when the store answered something that is not a secret — which, /// on a presence-guarded item, includes the person cancelling the prompt. /// A cancel is a decision, not a fault, and the caller draws it as one. func read() throws -> String? /// Is there an item at all — **without reading it, and so without asking /// the person for their face.** /// /// This is the whole reason the protocol has three members rather than two. /// A presence-guarded item prompts on every READ, so a launch that checked /// for a key by reading one would put a Face ID sheet in front of the app /// every time it opened. A match query that returns ATTRIBUTES and not /// DATA decrypts nothing and prompts for nothing, which is exactly the /// question "have I minted yet" needs. func exists() -> Bool /// Store a key unless one is already there — **without reading what is /// there.** `true` when this key was stored, `false` when another was /// already in the slot. /// /// It answers a Bool and not "the key that is actually there" on purpose: /// answering the key would mean READING a presence-guarded item, and the /// launch mints through here. The one caller that wants the key after a /// lost race (`VaultKey.key`, a reveal) reads it itself, where a prompt /// belongs. func add(_ key: String) throws -> Bool /// Forget it. Only ever from a deliberate act. func forget() } /// What the store said when it would not answer. public enum VaultKeyError: Error, Equatable { /// The store answered, and the answer was not a secret. case storeUnreadable(OSStatus) /// A key could not be written. case notWritten(OSStatus) /// The system could not give random bytes. case noRandom /// The device cannot guard an item behind presence at all — no passcode and /// no enrolled biometry. On a phone this is a person with no passcode; on /// the simulator it is Features → Face ID → Enrolled, unticked. case noPresence /// The person cancelled the Face ID / passcode prompt. A decision, drawn as /// one, and never retried on its own. case cancelled /// The slot is present and its contents are not a 32-byte key. case slotUnreadable /// macOS, and this build is not the signed app. /// /// A Mac's items live in the legacy file-based keychain, where access is /// gated by the CODE SIGNATURE that created the item — so a `swift build` /// binary asking for one raises a SecurityAgent dialog that a launch with /// no session cannot draw, and the app waits for ever (`Keychain`'s own /// header, and design M8). An unpackaged build therefore does not ask, and /// this is the state the screen draws instead of a prompt nobody can see. case notPackaged } public enum VaultKey { /// The service every item in this app is filed under. /// /// **Two spellings, because there are two apps.** On the phone it is the /// bundle id, beside the device key. On the Mac it is the Mac app's own /// service, so this key is the FOURTH item beside the three /// `CottonHost/Client/Keychain.swift` already keeps — which is load-bearing /// rather than tidy: the Mac's boot reads that item and hands the private /// half to the core at `cotton_open`, and these screens read the SAME item /// for a reveal. Two items would be two keys, one of them wrapped for and /// one of them not. `CottonHostTests` asserts the two spellings agree. /// /// The ACCOUNT is what separates this key from the device key, on both. #if os(macOS) public static let service = AppFlavor.current.macKeychainService #else public static let service = DeviceKey.service #endif /// The account name. `device-key` is the Ed25519 identity; this is the /// X25519 half that opens the passwords. public static let account = "vault-key" /// The keychain group the app shares with its Keys provider, as the /// build stamped it (`CottonKeychainGroup`: /// `$(AppIdentifierPrefix)$(COTTON_KEYCHAIN_GROUP)`); `nil` on the Mac, /// in a bundle that names none, and where the stamp did not resolve. public static var accessGroup: String? { #if os(macOS) return nil #else guard let group = Bundle.main.object(forInfoDictionaryKey: "CottonKeychainGroup") as? String else { return nil } return teamPrefixed(group) #endif } /// `group` when it starts with a team prefix (ten capitals or digits and /// a dot) — what a signed build stamps. An unsigned build stamps /// `$(AppIdentifierPrefix)` as nothing, and then there is no group to /// name: the item stays where the system files it. static func teamPrefixed(_ group: String) -> String? { guard let dot = group.firstIndex(of: "."), group.index(after: dot) < group.endIndex else { return nil } let team = group[.. String { if let existing = try store.read() { if isKey(existing) { return existing } store.forget() } let minted = try mint() if try store.add(minted) { return minted } // Somebody won the race. Theirs is the one this install has — read on // the reveal path, which is where a prompt belongs. guard let existing = try store.read(), isKey(existing) else { throw VaultKeyError.storeUnreadable(errSecDuplicateItem) } return existing } /// Mint a key IF there is none, and answer it — **only when it was just /// minted.** /// /// `nil` means "there was already one", which is the launch-time answer: it /// says the key exists without reading it, so nothing prompts. The caller /// publishes the public half of a freshly-minted key and, for one that was /// already there, publishes the half it cached at mint. /// /// **It never reads.** An `exists()` that answers no for an item that is /// there (a race, or a Keychain that will not say) ends in `add` finding /// the slot taken, and that is answered as "there was already one" — never /// by reading the item, which on the phone is the presence prompt at launch. public static func mintIfAbsent(store: some VaultKeyStore) throws -> String? { if store.exists() { return nil } let minted = try mint() return try store.add(minted) ? minted : nil } /// Start this phone's vault over: a new key, published, re-wrapped. public static func forget(store: some VaultKeyStore) { store.forget() } /// Is this what we wrote — 43 base64url characters decoding to 32 bytes? public static func isKey(_ text: String) -> Bool { guard text.count == keyLength else { return false } return DeviceKey.decode(text)?.count == keyBytes } /// The PUBLIC half, which is what `vault.publishKey` and the join carry. /// /// Curve25519 key agreement, from CryptoKit: the public half of an X25519 /// scalar, base64url, the spelling `cotton_core::vault::wrap` reads. public static func publicHalf(of key: String) -> String? { guard let bytes = DeviceKey.decode(key), bytes.count == keyBytes else { return nil } guard let secret = try? Curve25519.KeyAgreement.PrivateKey(rawRepresentation: bytes) else { return nil } return DeviceKey.encode(secret.publicKey.rawRepresentation) } static func mint() throws -> String { var bytes = [UInt8](repeating: 0, count: keyBytes) guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw VaultKeyError.noRandom } // CLAMPED by X25519 itself on use — `cotton_core::vault::wrap` and // CryptoKit both do it — so 32 random bytes are a valid scalar and no // clamping is done here. Doing it in two places would be two opinions // about what the key IS. return DeviceKey.encode(Data(bytes)) } } /// The real store. public struct KeychainVaultKeyStore: VaultKeyStore { private let service: String private let account: String /// What the prompt says above the Face ID sheet. Plain words: this is the /// one sentence a person reads with their thumb on the sensor. private let reason: String /// THE SHARED ACCESS GROUP (Cotton Keys, 8 Nov 2026): the keychain group /// the app shares with its Keys provider extension /// (`$(AppIdentifierPrefix)$(COTTON_KEYCHAIN_GROUP)`), so the provider /// opens the vault under the same presence check. `nil` on the Mac and in /// a build that names none: the item lives where the system files it. private let accessGroup: String? /// Where an item minted before the shared group was filed — the app's /// own group (``). Read once, moved into /// `accessGroup` and deleted there, in that order (`read`). private let legacyGroup: String? /// Guarded by presence on the item itself. Never by default: the guard is /// the screen's (`VaultPresence`, see the header); `true` is kept only for /// a test that wants an item filed the old way. private let guarded: Bool public init( service: String = VaultKey.service, account: String = VaultKey.account, reason: String = VaultPresence.reason, accessGroup: String? = VaultKey.accessGroup, legacyGroup: String? = VaultKey.legacyGroup, guarded: Bool = false ) { self.service = service self.account = account self.reason = reason self.accessGroup = accessGroup self.legacyGroup = accessGroup == nil ? nil : legacyGroup self.guarded = guarded } /// The key, from the shared group; an item still filed in the app's own /// group is moved there on the way (``moved(from:)``). public func read() throws -> String? { // A build that does not hold the shared group (an entitlement that did // not land) reads nothing there, and keeps using the old item. let found: String? do { found = try read(in: accessGroup) } catch VaultKeyError.storeUnreadable(errSecMissingEntitlement) where legacyGroup != nil { found = nil } if let found { return found } guard let legacyGroup, let old = try read(in: legacyGroup) else { return nil } moved(old, from: legacyGroup) return old } /// THE ONE MOVE: the old item has been READ (the prompt already shown); /// it is WRITTEN into the shared group, and only once that write landed /// (or the group already holds it) is the old one DELETED. Any failure /// leaves the old item where it was, and the next read tries again. private func moved(_ key: String, from old: String) { guard let accessGroup else { return } let added: Bool do { added = try add(key, in: accessGroup) || exists(in: accessGroup) } catch { return } guard added else { return } SecItemDelete(KeychainVaultKeyStore.matchQuery(service: service, account: account, group: old) as CFDictionary) } private func read(in group: String?) throws -> String? { KeychainGate.check(service: service, account: account) if let refusal = KeychainVaultKeyStore.unpackaged() { throw refusal } var query = KeychainVaultKeyStore.matchQuery(service: service, account: account, group: group) query[kSecReturnData as String] = true query[kSecMatchLimit as String] = kSecMatchLimitOne // The sentence the system draws. It is an OPERATION prompt, not a // search attribute, so it narrows nothing — see the trap in the header. // On the Mac the item carries no access control, so nothing is drawn // and this is simply ignored; the Touch ID prompt in front of a reveal // there is the SCREEN's (`VaultAccess`), not the item's. query[kSecUseOperationPrompt as String] = reason var found: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &found) if status == errSecItemNotFound { return nil } if status == errSecUserCanceled || status == errSecAuthFailed { throw VaultKeyError.cancelled } guard status == errSecSuccess, let data = found as? Data else { throw VaultKeyError.storeUnreadable(status) } return String(decoding: data, as: UTF8.self) } public func exists() -> Bool { exists(in: accessGroup) || legacyGroup.map { exists(in: $0) } == true } private func exists(in group: String?) -> Bool { KeychainGate.check(service: service, account: account) if KeychainVaultKeyStore.unpackaged() != nil { return false } var query = KeychainVaultKeyStore.matchQuery(service: service, account: account, group: group) // ATTRIBUTES, never DATA — see the protocol. Returning data would // decrypt the item and draw the Face ID sheet; returning attributes // answers "is it there" off the keychain's own index. query[kSecReturnAttributes as String] = true query[kSecMatchLimit as String] = kSecMatchLimitOne // And no UI, whatever the item asks: a context that may not interact // turns any authentication the query would need into // `errSecInteractionNotAllowed` — which still says the item is there. let context = LAContext() context.interactionNotAllowed = true query[kSecUseAuthenticationContext as String] = context var found: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &found) return status == errSecSuccess || status == errSecInteractionNotAllowed } public func add(_ key: String) throws -> Bool { // A key filed in the old group is the one this install has: never a // second beside it in the new one. if let legacyGroup, exists(in: legacyGroup) { return false } return try add(key, in: accessGroup) } private func add(_ key: String, in group: String?) throws -> Bool { KeychainGate.check(service: service, account: account) if let refusal = KeychainVaultKeyStore.unpackaged() { throw refusal } var attributes = KeychainVaultKeyStore.matchQuery(service: service, account: account, group: group) #if os(macOS) // NO ACCESS CONTROL, and `ThisDeviceOnly` in its place. The server // opens an assistant's API key with nobody at the keyboard and the // placement applier writes a file into a build nobody is watching; // an item that prompted would stop both. The login session is the // guard, and the reveal screen's Touch ID prompt is a courtesy the // screen performs — see the type's header, and spec §7.1. // // The attribute is written the way `CottonHost`'s own three items // are, because that file puts `kSecAttrAccessible` in its MATCH // query: an item written without it would be filed as plain // `WhenUnlocked` and the Mac's boot would not find it. attributes[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly #else if guarded { guard let control = KeychainVaultKeyStore.presence() else { throw VaultKeyError.noPresence } attributes[kSecAttrAccessControl as String] = control } else { attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly } #endif attributes[kSecValueData as String] = Data(key.utf8) let status = SecItemAdd(attributes as CFDictionary, nil) // Somebody won the race: theirs is the one this install has, and it is // NOT read here (see the protocol). if status == errSecDuplicateItem { return false } guard status == errSecSuccess else { throw VaultKeyError.notWritten(status) } return true } public func forget() { KeychainGate.check(service: service, account: account) for group in [accessGroup, legacyGroup] where group != nil || accessGroup == nil { SecItemDelete( KeychainVaultKeyStore.matchQuery(service: service, account: account, group: group) as CFDictionary ) } } /// `nil` on the phone, and on a packaged Mac app: both may ask the /// Keychain. A `swift build` Mac binary may NOT — see /// ``VaultKeyError/notPackaged``. static func unpackaged() -> VaultKeyError? { #if os(macOS) return Bundle.main.bundleIdentifier == nil ? .notPackaged : nil #else return nil #endif } /// Face ID, Touch ID, or the passcode — re-asked on every read. /// /// `nil` when the device can guard nothing behind presence: no passcode and /// no enrolled biometry, which is a simulator out of the box. The caller /// turns that into `VaultKeyError.noPresence`, a line on the screen. static func presence() -> SecAccessControl? { SecAccessControlCreateWithFlags( nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil ) } /// How the item is FOUND — class, service, account, and DELIBERATELY no /// accessibility and no access control. /// /// **A search attribute filters**, so either of those in a match query /// would mean "an item filed exactly this way" and would miss an item /// written under any other value — the read answers not-found, the app /// mints a second key, and the wrap the server already wrote is orphaned. /// `KeychainDeviceKeyStore.matchQuery` carries the same three keys for the /// same reason. /// /// The access GROUP is the one filter added, and on purpose: it is what /// tells the shared group's item from one still filed in the app's own. static func matchQuery(service: String, account: String, group: String? = nil) -> [String: Any] { var query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account, ] if let group { query[kSecAttrAccessGroup as String] = group } return query } } /// A store in memory — what every `VaultKey` test drives, and the only way to /// reproduce a cancelled prompt or a device with no passcode without a phone. public final class InMemoryVaultKeyStore: VaultKeyStore, @unchecked Sendable { private let lock = NSLock() private var stored: String? private var failure: VaultKeyError? private let indexed: Bool public private(set) var mintCount = 0 /// Every read of the stored key — on the phone, every one is the presence /// prompt. What the launch guards count. public private(set) var readCount = 0 /// `indexed: false` is a store whose `exists()` answers no while a key IS /// there — a Keychain that would not say, or a race lost between the /// question and the write. public init(seeded: String? = nil, failing: VaultKeyError? = nil, indexed: Bool = true) { stored = seeded failure = failing self.indexed = indexed } public func read() throws -> String? { lock.lock() defer { lock.unlock() } readCount += 1 if let failure { throw failure } return stored } public func exists() -> Bool { lock.lock() defer { lock.unlock() } return indexed && stored != nil } public func add(_ key: String) throws -> Bool { lock.lock() defer { lock.unlock() } if let failure { throw failure } if stored != nil { return false } stored = key mintCount += 1 return true } public func forget() { lock.lock() defer { lock.unlock() } stored = nil } }