// The data key sealed tables open with (sealing plan §2.1, §2.4), kept on // this phone so a background pull opens sealed rows. // // It is NOT the vault key. The vault key opens passwords and is guarded by // presence: reading it draws Face ID. The data key opens messages and mail, // and a pull that runs while the phone sits in a pocket must open them with // nobody looking, so its item carries no access control and is readable // after the first unlock since boot (`AfterFirstUnlockThisDeviceOnly`), never // restored onto another phone. Losing it costs nothing: the next vault open // takes it again from the object's `seal_key` row. // // One item per database (account `data-key:`), the base64url // text the core hands over (`seal.heldKey`) and takes back (`seal.useKey`). import Foundation import Security /// Where this phone keeps each database's data key. public protocol DataKeyKeeping: Sendable { func read(database: String) -> String? @discardableResult func write(_ key: String, database: String) -> Bool func forget(database: String) } /// The Keychain's data keys: no presence, after first unlock, this device only. public struct DataKeychain: DataKeyKeeping { private let service: String public init(service: String = DeviceKey.service) { self.service = service } static func account(_ database: String) -> String { "data-key:\(database)" } public func read(database: String) -> String? { var query = base(database) query[kSecReturnData as String] = true query[kSecMatchLimit as String] = kSecMatchLimitOne var found: CFTypeRef? guard SecItemCopyMatching(query as CFDictionary, &found) == errSecSuccess, let data = found as? Data else { return nil } let text = String(decoding: data, as: UTF8.self) return text.isEmpty ? nil : text } @discardableResult public func write(_ key: String, database: String) -> Bool { SecItemDelete(base(database) as CFDictionary) var attributes = base(database) attributes[kSecValueData as String] = Data(key.utf8) // Set on the add only: a search attribute filters, so a read never names it. attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly return SecItemAdd(attributes as CFDictionary, nil) == errSecSuccess } public func forget(database: String) { SecItemDelete(base(database) as CFDictionary) } private func base(_ database: String) -> [String: Any] { [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: Self.account(database), ] } } /// A keeper in memory, for tests. final class InMemoryDataKeys: DataKeyKeeping, @unchecked Sendable { private let lock = NSLock() private var keys: [String: String] = [:] public init() {} public func read(database: String) -> String? { lock.withLock { keys[database] } } @discardableResult public func write(_ key: String, database: String) -> Bool { lock.withLock { keys[database] = key }; return true } public func forget(database: String) { _ = lock.withLock { keys.removeValue(forKey: database) } } }