Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Core/Biometrics/KeyProtector.swift8// Module : SPVault9// Repository : https://git.spboucher.ai/sp-id-card-vault10// Project Website : Not specified11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import LocalAuthentication43import Security4445/// What the device can do biometrically right now.46enum BiometryState: Equatable, Sendable {47 case available(kind: Kind)48 case notEnrolled49 case lockedOut50 case unavailable5152 enum Kind: String, Sendable { case faceID = "Face ID", touchID = "Touch ID", opticID = "Optic ID" }5354 var isAvailable: Bool { if case .available = self { true } else { false } }55 var name: String { if case .available(let kind) = self { kind.rawValue } else { "Face ID" } }56}5758enum KeyProtectorError: Error, Equatable {59 case cancelled60 case authenticationFailed61 case biometryUnavailable62 case biometryNotEnrolled63 case biometryLockedOut64 /// The Keychain item is gone: the biometric set changed (`biometryCurrentSet`)65 /// or the item was never created. Recovery passphrase or backup is required.66 case keyInvalidated67 case passcodeNotSet68 case keychain(OSStatus)69}7071/// Guards the 256-bit vault master key. Reading the key is the unlock: there is no72/// UI-only gate, the bytes simply cannot be obtained without the biometric check.73protocol KeyProtector: Sendable {74 func biometryState() -> BiometryState75 /// True when a master key item exists, checked without prompting.76 func masterKeyExists() -> Bool77 func storeMasterKey(_ key: Data) throws78 /// Prompts for biometry and returns the key.79 func loadMasterKey(reason: String) async throws -> Data80 func deleteMasterKey() throws81 /// Human-readable, truthful description for the Security Center.82 var protectionDescription: String { get }83}8485func currentBiometryState() -> BiometryState {86 let context = LAContext()87 var error: NSError?88 if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {89 switch context.biometryType {90 case .touchID: return .available(kind: .touchID)91 case .opticID: return .available(kind: .opticID)92 default: return .available(kind: .faceID)93 }94 }95 switch (error as? LAError)?.code {96 case .biometryNotEnrolled: return .notEnrolled97 case .biometryLockout: return .lockedOut98 default: return .unavailable99 }100}101102/// Production protector: generic-password Keychain item, this device only, readable103/// only while a passcode is set and only after a successful match against the104/// *current* biometric set. Adding or removing a face invalidates the item.105struct KeychainBiometricKeyProtector: KeyProtector {106 static let service = "ai.spboucher.idcardvault.masterkey"107 static let account = "vault-master-v1"108109 var protectionDescription: String {110 "Keychain · this device only · passcode required · biometryCurrentSet"111 }112113 func biometryState() -> BiometryState { currentBiometryState() }114115 private var baseQuery: [String: Any] {116 [kSecClass as String: kSecClassGenericPassword,117 kSecAttrService as String: Self.service,118 kSecAttrAccount as String: Self.account,119 kSecUseDataProtectionKeychain as String: true]120 }121122 func masterKeyExists() -> Bool {123 let context = LAContext()124 context.interactionNotAllowed = true125 var query = baseQuery126 query[kSecUseAuthenticationContext as String] = context127 query[kSecReturnAttributes as String] = true128 let status = SecItemCopyMatching(query as CFDictionary, nil)129 return status == errSecSuccess || status == errSecInteractionNotAllowed || status == errSecAuthFailed130 }131132 func storeMasterKey(_ key: Data) throws {133 try? deleteMasterKey()134 var cfError: Unmanaged<CFError>?135 guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,136 .biometryCurrentSet, &cfError) else {137 throw KeyProtectorError.keychain(errSecParam)138 }139 var query = baseQuery140 query[kSecAttrAccessControl as String] = access141 query[kSecValueData as String] = key142 let status = SecItemAdd(query as CFDictionary, nil)143 switch status {144 case errSecSuccess: return145 case errSecNotAvailable: throw KeyProtectorError.passcodeNotSet146 default: throw KeyProtectorError.keychain(status)147 }148 }149150 func loadMasterKey(reason: String) async throws -> Data {151 let state = biometryState()152 switch state {153 case .notEnrolled: throw KeyProtectorError.biometryNotEnrolled154 case .lockedOut: throw KeyProtectorError.biometryLockedOut155 case .unavailable: throw KeyProtectorError.biometryUnavailable156 case .available: break157 }158 var query = baseQuery159 query[kSecReturnData as String] = true160 query[kSecMatchLimit as String] = kSecMatchLimitOne161 let context = LAContext()162 context.localizedReason = reason163 context.localizedFallbackTitle = "" // no passcode fallback: biometry only164 query[kSecUseAuthenticationContext as String] = context165 nonisolated(unsafe) let cfQuery = query as CFDictionary166 return try await Task.detached(priority: .userInitiated) {167 var item: CFTypeRef?168 let status = SecItemCopyMatching(cfQuery, &item)169 switch status {170 case errSecSuccess:171 guard let data = item as? Data, data.count == 32 else { throw KeyProtectorError.keychain(errSecDecode) }172 return data173 case errSecItemNotFound: throw KeyProtectorError.keyInvalidated174 case errSecUserCanceled: throw KeyProtectorError.cancelled175 case errSecAuthFailed:176 throw currentBiometryState() == .lockedOut ? KeyProtectorError.biometryLockedOut177 : KeyProtectorError.authenticationFailed178 default: throw KeyProtectorError.keychain(status)179 }180 }.value181 }182183 func deleteMasterKey() throws {184 let status = SecItemDelete(baseQuery as CFDictionary)185 guard status == errSecSuccess || status == errSecItemNotFound else { throw KeyProtectorError.keychain(status) }186 }187}188189#if targetEnvironment(simulator)190/// Simulator only (compiled out of device builds). The simulator has no passcode191/// and no Secure Enclave, so `WhenPasscodeSet` + `biometryCurrentSet` items cannot192/// be created. This protector keeps the key in a plain simulator Keychain item and193/// gates the read with a real `LAContext` evaluation, so Face ID match / non-match194/// can be exercised from Features ▸ Face ID. It also emulates invalidation when195/// the enrolled biometric set changes (`evaluatedPolicyDomainState`).196struct SimulatorKeyProtector: KeyProtector {197 static let service = "ai.spboucher.idcardvault.simulator"198 var protectionDescription: String { "Simulator Keychain (development only, not hardware-backed)" }199200 func biometryState() -> BiometryState { currentBiometryState() }201202 private func query(_ account: String) -> [String: Any] {203 [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: Self.service,204 kSecAttrAccount as String: account]205 }206207 private func read(_ account: String) -> Data? {208 var q = query(account)209 q[kSecReturnData as String] = true210 var item: CFTypeRef?211 return SecItemCopyMatching(q as CFDictionary, &item) == errSecSuccess ? item as? Data : nil212 }213214 private func write(_ account: String, _ data: Data) throws {215 SecItemDelete(query(account) as CFDictionary)216 var q = query(account)217 q[kSecValueData as String] = data218 q[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly219 let status = SecItemAdd(q as CFDictionary, nil)220 guard status == errSecSuccess else { throw KeyProtectorError.keychain(status) }221 }222223 private func domainState() -> Data {224 let context = LAContext()225 _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)226 return context.domainState.biometry.stateHash ?? Data()227 }228229 func masterKeyExists() -> Bool { read("key") != nil }230231 func storeMasterKey(_ key: Data) throws {232 try write("key", key)233 try write("domain", domainState())234 }235236 func loadMasterKey(reason: String) async throws -> Data {237 switch biometryState() {238 case .notEnrolled: throw KeyProtectorError.biometryNotEnrolled239 case .lockedOut: throw KeyProtectorError.biometryLockedOut240 case .unavailable: throw KeyProtectorError.biometryUnavailable241 case .available: break242 }243 guard let key = read("key") else { throw KeyProtectorError.keyInvalidated }244 if let stored = read("domain"), !stored.isEmpty, stored != domainState() {245 try? deleteMasterKey()246 throw KeyProtectorError.keyInvalidated247 }248 let context = LAContext()249 context.localizedFallbackTitle = ""250 do {251 try await context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason)252 return key253 } catch let error as LAError {254 switch error.code {255 case .userCancel, .appCancel, .systemCancel, .userFallback: throw KeyProtectorError.cancelled256 case .biometryLockout: throw KeyProtectorError.biometryLockedOut257 default: throw KeyProtectorError.authenticationFailed258 }259 }260 }261262 func deleteMasterKey() throws {263 SecItemDelete(query("key") as CFDictionary)264 SecItemDelete(query("domain") as CFDictionary)265 }266}267#endif268269#if DEBUG270/// Test double (Debug builds only, absent from Release binaries). Scripted outcomes271/// let unit and UI tests exercise acceptance, refusal, lockout and invalidation.272final class ScriptedKeyProtector: KeyProtector, @unchecked Sendable {273 private let lock = NSLock()274 private var key: Data?275 private var _nextError: KeyProtectorError?276 private var _state: BiometryState = .available(kind: .faceID)277 private(set) var promptCount = 0278279 var protectionDescription: String { "Scripted test protector (Debug only)" }280281 func setNextError(_ error: KeyProtectorError?) { lock.withLock { _nextError = error } }282 func setState(_ state: BiometryState) { lock.withLock { _state = state } }283 /// Emulates a change of the enrolled biometric set.284 func invalidate() { lock.withLock { key = nil } }285286 func biometryState() -> BiometryState { lock.withLock { _state } }287 func masterKeyExists() -> Bool { lock.withLock { key != nil } }288 func storeMasterKey(_ key: Data) throws { lock.withLock { self.key = key } }289 func deleteMasterKey() throws { lock.withLock { key = nil } }290291 func loadMasterKey(reason: String) async throws -> Data {292 try lock.withLock {293 promptCount += 1294 if let error = _nextError { _nextError = nil; throw error }295 guard let key else { throw KeyProtectorError.keyInvalidated }296 return key297 }298 }299}300#endif301302enum KeyProtectors {303 static func platformDefault() -> any KeyProtector {304 #if targetEnvironment(simulator)305 SimulatorKeyProtector()306 #else307 KeychainBiometricKeyProtector()308 #endif309 }310}311