Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Sources/DocAI/DocCredentialStore.swift10// Description : Where ORIX Docs keeps bring-your-own API keys on a Mac:11// generic-password items of the macOS Keychain under one12// service, readable while the Mac is unlocked, never13// synchronised, never migrated to another device. Implements14// the `CredentialStore` protocol of ORIX Astra, so every15// Astra provider adapter reads keys from it unchanged.16// Module : DocAI17// Repository : https://git.spboucher.ai/orix-docs18// Created : 2026-11-2219// Last Modified : 2026-11-2220//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import AstraCore94import Foundation95import Security9697/// Names used by ORIX Docs in the Keychain.98public enum DocCredentials {99 /// `kSecAttrService` of every key stored by ORIX Docs. Queries are always restricted to it: items of other apps are never read.100 public static let service = "ai.spboucher.orix.docs.providers"101102 /// The store the app uses.103 public static func keychain() -> MacKeychainCredentialStore { MacKeychainCredentialStore(service: service) }104 /// A store that lives in memory, for tests and previews (ORIX Astra's implementation).105 public static func inMemory(_ values: [String: String] = [:]) -> InMemoryCredentialStore { InMemoryCredentialStore(values) }106}107108/// macOS Keychain store.109///110/// ORIX Astra's `KeychainCredentialStore` targets iOS, where there is only one kind of keychain. A Mac has two:111/// - the **data protection keychain** (the iOS-style one): `kSecAttrAccessibleWhenUnlockedThisDeviceOnly` is enforced and items112/// belong to the app's access group. It needs an app signed with an application identifier, which ORIX Docs is;113/// - the **login keychain** (file based): the accessibility attribute is ignored, items are protected by the login password and by114/// an access-control list naming the application that created them, and they never leave the Mac unless the user copies the file.115///116/// `.automatic` uses the data protection keychain and falls back to the login keychain only when the process has no entitlement for117/// it (`errSecMissingEntitlement`: unsigned development builds and command-line test runs). Once the system has refused, the store118/// stays on the login keychain for its whole life, so one process never splits its items between the two.119public struct MacKeychainCredentialStore: CredentialStore {120 public enum Backend: String, Sendable, Hashable, Codable {121 /// Data protection keychain, login keychain when the process is not entitled.122 case automatic123 /// Data protection keychain only: an unentitled process gets `CredentialError.keychain(errSecMissingEntitlement)`.124 case dataProtection125 /// Login (file-based) keychain only.126 case login127 }128129 public let service: String130 public let backend: Backend131 private let resolved = ResolvedBackend()132133 public init(service: String = DocCredentials.service, backend: Backend = .automatic) {134 self.service = service; self.backend = backend135 }136137 /// The backend in use. In `.automatic` mode: the data protection keychain until the system has refused it for lack of138 /// entitlement, the login keychain from then on.139 public var effectiveBackend: Backend { backend == .automatic ? (resolved.value ?? .dataProtection) : backend }140141 /// The query every operation starts from. Internal so tests can check the attributes without touching the Keychain.142 static func baseQuery(service: String, account: String?, dataProtection: Bool) -> [String: Any] {143 var q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service]144 // `kSecAttrSynchronizable` (even false) and `kSecAttrAccessible` belong to the data protection keychain: on macOS their mere145 // presence sends a query there, and an unentitled process then gets errSecMissingEntitlement. Login-keychain items are146 // never synchronised in the first place.147 if dataProtection { q[kSecUseDataProtectionKeychain as String] = true; q[kSecAttrSynchronizable as String] = false }148 if let account { q[kSecAttrAccount as String] = account }149 return q150 }151152 /// Attributes of a new item, beyond the base query.153 static func addAttributes(data: Data, label: String, dataProtection: Bool) -> [String: Any] {154 var a: [String: Any] = [kSecValueData as String: data, kSecAttrLabel as String: label, kSecAttrDescription as String: "API key"]155 if dataProtection { a[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly }156 return a157 }158159 /// Runs `body` against the right keychain, settling `.automatic` on the first call.160 private func withBackend<T>(_ body: (_ dataProtection: Bool) -> (OSStatus, T)) -> (OSStatus, T) {161 switch backend {162 case .dataProtection: return body(true)163 case .login: return body(false)164 case .automatic:165 if resolved.value == .login { return body(false) }166 // An unentitled process can query the data protection keychain (it finds nothing) but cannot add to it: the refusal167 // may therefore come on a later call than the first. Nothing can have been stored there before it, so switching is safe.168 let first = body(true)169 guard first.0 == errSecMissingEntitlement else { return first }170 resolved.set(.login)171 return body(false)172 }173 }174175 public func secret(for account: String) throws -> String? {176 let (status, out) = withBackend { dataProtection -> (OSStatus, CFTypeRef?) in177 var q = Self.baseQuery(service: service, account: account, dataProtection: dataProtection)178 q[kSecReturnData as String] = true179 q[kSecMatchLimit as String] = kSecMatchLimitOne180 var out: CFTypeRef?181 let status = SecItemCopyMatching(q as CFDictionary, &out)182 return (status, out)183 }184 if status == errSecItemNotFound { return nil }185 guard status == errSecSuccess, let data = out as? Data else { throw CredentialError.keychain(status) }186 return String(data: data, encoding: .utf8)187 }188189 public func setSecret(_ secret: String, for account: String) throws {190 let trimmed = secret.trimmingCharacters(in: .whitespacesAndNewlines)191 guard !trimmed.isEmpty else { throw CredentialError.empty }192 let data = Data(trimmed.utf8)193 let (status, _) = withBackend { dataProtection -> (OSStatus, Void) in194 let base = Self.baseQuery(service: service, account: account, dataProtection: dataProtection)195 let update = SecItemUpdate(base as CFDictionary, [kSecValueData as String: data] as CFDictionary)196 guard update == errSecItemNotFound else { return (update, ()) }197 let add = base.merging(Self.addAttributes(data: data, label: "ORIX Docs: \(account)", dataProtection: dataProtection)) { _, new in new }198 return (SecItemAdd(add as CFDictionary, nil), ())199 }200 guard status == errSecSuccess else { throw CredentialError.keychain(status) }201 }202203 public func removeSecret(for account: String) throws {204 let (status, _) = withBackend { dataProtection -> (OSStatus, Void) in205 (SecItemDelete(Self.baseQuery(service: service, account: account, dataProtection: dataProtection) as CFDictionary), ())206 }207 guard status == errSecSuccess || status == errSecItemNotFound else { throw CredentialError.keychain(status) }208 }209210 public func accounts() throws -> [String] {211 let (status, out) = withBackend { dataProtection -> (OSStatus, CFTypeRef?) in212 var q = Self.baseQuery(service: service, account: nil, dataProtection: dataProtection)213 q[kSecReturnAttributes as String] = true214 q[kSecMatchLimit as String] = kSecMatchLimitAll215 var out: CFTypeRef?216 let status = SecItemCopyMatching(q as CFDictionary, &out)217 return (status, out)218 }219 if status == errSecItemNotFound { return [] }220 guard status == errSecSuccess, let items = out as? [[String: Any]] else { throw CredentialError.keychain(status) }221 return items.compactMap { $0[kSecAttrAccount as String] as? String }.sorted()222 }223224 /// Removes every key ORIX Docs stored under this service ("Delete all AI data"). Items of other services are untouched.225 public func removeAll() throws {226 for account in try accounts() { try removeSecret(for: account) }227 }228}229230/// Remembers which keychain answered. A lock-protected optional: the store is a value type shared across tasks.231/// `@unchecked Sendable` is justified by the lock: `stored` is only read or written while holding it.232private final class ResolvedBackend: @unchecked Sendable {233 private let lock = NSLock()234 private var stored: MacKeychainCredentialStore.Backend?235 var value: MacKeychainCredentialStore.Backend? { lock.withLock { stored } }236 func set(_ backend: MacKeychainCredentialStore.Backend) { lock.withLock { if stored == nil { stored = backend } } }237}238