SPB Git

Repository Public

KeychainStore.swift 7.8 KB 192 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraStorage/KeychainStore.swift8// Module           : Qyvora Storage9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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 QyvoraMath44import Security4546/// Protection class of a Keychain item.47public enum KeychainAccess: Sendable, Equatable {48    /// `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly`: readable while the device is unlocked, never migrated49    /// to another device, deleted by the system when the passcode is removed.50    case passcodeSetThisDeviceOnly51    /// The same class plus a `SecAccessControl` with `.biometryCurrentSet`: every read needs Face ID / Touch ID,52    /// and the item becomes unreadable when the enrolled biometrics change.53    case biometryCurrentSet54}5556/// Generic-password storage. The vault only talks to this protocol, so tests run on `InMemoryKeychainStore`.57/// Items are never synchronizable (no iCloud Keychain).58public protocol KeychainStore: Sendable {59    /// Creates or replaces the item.60    func set(_ value: Bytes, account: String, access: KeychainAccess) throws(StorageError)61    /// Reads the item; `prompt` is the reason shown by the biometric sheet. Throws `notFound` when absent.62    func get(account: String, prompt: String?) throws(StorageError) -> Bytes63    /// Deletes the item. A missing item is not an error.64    func delete(account: String) throws(StorageError)65    /// True when the item exists; never prompts.66    func contains(account: String) -> Bool67}6869/// The real Keychain (data-protection Keychain on macOS).70public struct SystemKeychainStore: KeychainStore {71    public let service: String7273    public init(service: String = "ai.spboucher.qyvora.vault") {74        self.service = service75    }7677    private func baseQuery(_ account: String) -> [String: Any] {78        [79            kSecClass as String: kSecClassGenericPassword,80            kSecAttrService as String: service,81            kSecAttrAccount as String: account,82            kSecAttrSynchronizable as String: false,83            kSecUseDataProtectionKeychain as String: true,84        ]85    }8687    private static func map(_ status: OSStatus) -> StorageError {88        switch status {89        case errSecItemNotFound: return .notFound90        case errSecUserCanceled, errSecAuthFailed: return .authenticationFailed91        case errSecInteractionNotAllowed: return .interactionNotAllowed92        default: return .keychain(status: status)93        }94    }9596    public func set(_ value: Bytes, account: String, access: KeychainAccess) throws(StorageError) {97        try delete(account: account)98        var query = baseQuery(account)99        query[kSecValueData as String] = Data(value)100        switch access {101        case .passcodeSetThisDeviceOnly:102            query[kSecAttrAccessible as String] = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly103        case .biometryCurrentSet:104            var error: Unmanaged<CFError>?105            guard let control = SecAccessControlCreateWithFlags(106                nil, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, .biometryCurrentSet, &error)107            else {108                error?.release()109                throw .keychain(status: errSecParam)110            }111            query[kSecAttrAccessControl as String] = control112        }113        let status = SecItemAdd(query as CFDictionary, nil)114        guard status == errSecSuccess else { throw Self.map(status) }115    }116117    public func get(account: String, prompt: String?) throws(StorageError) -> Bytes {118        var query = baseQuery(account)119        query[kSecReturnData as String] = true120        query[kSecMatchLimit as String] = kSecMatchLimitOne121        if let prompt {122            let context = LAContext()123            context.localizedReason = prompt124            query[kSecUseAuthenticationContext as String] = context125        }126        var item: CFTypeRef?127        let status = SecItemCopyMatching(query as CFDictionary, &item)128        guard status == errSecSuccess else { throw Self.map(status) }129        guard let data = item as? Data else { throw .invalidData }130        return Bytes(data)131    }132133    public func delete(account: String) throws(StorageError) {134        let status = SecItemDelete(baseQuery(account) as CFDictionary)135        guard status == errSecSuccess || status == errSecItemNotFound else { throw Self.map(status) }136    }137138    public func contains(account: String) -> Bool {139        var query = baseQuery(account)140        query[kSecMatchLimit as String] = kSecMatchLimitOne141        let context = LAContext()142        context.interactionNotAllowed = true143        query[kSecUseAuthenticationContext as String] = context144        let status = SecItemCopyMatching(query as CFDictionary, nil)145        return status == errSecSuccess || status == errSecInteractionNotAllowed146    }147}148149/// Test double of the Keychain: a dictionary behind a lock. It can simulate a failed biometric check and150/// a change of enrolled biometrics.151public final class InMemoryKeychainStore: KeychainStore, @unchecked Sendable {152    private let lock = NSLock()153    private var items: [String: (value: Bytes, access: KeychainAccess)] = [:]154    private var biometryPasses = true155156    public init() {}157158    /// When false, reading an item protected by `.biometryCurrentSet` throws `authenticationFailed`.159    public func setBiometryPasses(_ passes: Bool) {160        lock.withLock { biometryPasses = passes }161    }162163    /// Simulates a change of enrolled biometrics: every `.biometryCurrentSet` item disappears.164    public func invalidateBiometricItems() {165        lock.withLock { items = items.filter { $0.value.access != .biometryCurrentSet } }166    }167168    /// Accounts currently stored (sorted).169    public var accounts: [String] {170        lock.withLock { items.keys.sorted() }171    }172173    public func set(_ value: Bytes, account: String, access: KeychainAccess) throws(StorageError) {174        lock.withLock { items[account] = (value, access) }175    }176177    public func get(account: String, prompt: String?) throws(StorageError) -> Bytes {178        let (item, passes) = lock.withLock { (items[account], biometryPasses) }179        guard let item else { throw .notFound }180        if item.access == .biometryCurrentSet, !passes { throw .authenticationFailed }181        return item.value182    }183184    public func delete(account: String) throws(StorageError) {185        lock.withLock { items[account] = nil }186    }187188    public func contains(account: String) -> Bool {189        lock.withLock { items[account] != nil }190    }191}192
Files main
Menu

Theme