Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraCore/Sources/Credentials.swift10// Module : Packages11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Security9091/// Stores bring-your-own-key secrets. The app only ever uses the Keychain implementation; tests use the in-memory one.92public protocol CredentialStore: Sendable {93 func secret(for account: String) throws -> String?94 func setSecret(_ secret: String, for account: String) throws95 func removeSecret(for account: String) throws96 func accounts() throws -> [String]97}9899public enum CredentialAccount {100 public static func provider(_ kind: ProviderKind) -> String { "provider." + kind.rawValue }101 public static func endpoint(_ id: String) -> String { "endpoint." + id }102 public static let huggingFace = "hub.huggingface"103}104105public enum CredentialError: Error, LocalizedError, Sendable, Hashable {106 case keychain(Int32)107 case empty108 public var errorDescription: String? {109 switch self {110 case .keychain(let status): "The Keychain refused the operation (status \(status))."111 case .empty: "The key is empty."112 }113 }114}115116/// Generic-password items, readable only while the device is unlocked, never synced to iCloud and never included in backups117/// restored to another device (`kSecAttrAccessibleWhenUnlockedThisDeviceOnly`).118public struct KeychainCredentialStore: CredentialStore {119 public let service: String120 public init(service: String = "ai.spboucher.orix.astra.credentials") { self.service = service }121122 private func base(_ account: String?) -> [String: Any] {123 var q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,124 kSecAttrSynchronizable as String: false]125 if let account { q[kSecAttrAccount as String] = account }126 return q127 }128129 public func secret(for account: String) throws -> String? {130 var q = base(account)131 q[kSecReturnData as String] = true132 q[kSecMatchLimit as String] = kSecMatchLimitOne133 var out: CFTypeRef?134 let status = SecItemCopyMatching(q as CFDictionary, &out)135 if status == errSecItemNotFound { return nil }136 guard status == errSecSuccess, let data = out as? Data else { throw CredentialError.keychain(status) }137 return String(data: data, encoding: .utf8)138 }139140 public func setSecret(_ secret: String, for account: String) throws {141 let trimmed = secret.trimmingCharacters(in: .whitespacesAndNewlines)142 guard !trimmed.isEmpty else { throw CredentialError.empty }143 let data = Data(trimmed.utf8)144 let update = SecItemUpdate(base(account) as CFDictionary, [kSecValueData as String: data] as CFDictionary)145 if update == errSecSuccess { return }146 guard update == errSecItemNotFound else { throw CredentialError.keychain(update) }147 var q = base(account)148 q[kSecValueData as String] = data149 q[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly150 let add = SecItemAdd(q as CFDictionary, nil)151 guard add == errSecSuccess else { throw CredentialError.keychain(add) }152 }153154 public func removeSecret(for account: String) throws {155 let status = SecItemDelete(base(account) as CFDictionary)156 guard status == errSecSuccess || status == errSecItemNotFound else { throw CredentialError.keychain(status) }157 }158159 public func accounts() throws -> [String] {160 var q = base(nil)161 q[kSecReturnAttributes as String] = true162 q[kSecMatchLimit as String] = kSecMatchLimitAll163 var out: CFTypeRef?164 let status = SecItemCopyMatching(q as CFDictionary, &out)165 if status == errSecItemNotFound { return [] }166 guard status == errSecSuccess, let items = out as? [[String: Any]] else { throw CredentialError.keychain(status) }167 return items.compactMap { $0[kSecAttrAccount as String] as? String }.sorted()168 }169170 /// Removes every secret this app stored (used by "Delete all data").171 public func removeAll() throws {172 let status = SecItemDelete(base(nil) as CFDictionary)173 guard status == errSecSuccess || status == errSecItemNotFound else { throw CredentialError.keychain(status) }174 }175}176177public final class InMemoryCredentialStore: CredentialStore, @unchecked Sendable {178 private let lock = NSLock()179 private var values: [String: String]180 public init(_ values: [String: String] = [:]) { self.values = values }181 public func secret(for account: String) throws -> String? { lock.withLock { values[account] } }182 public func setSecret(_ secret: String, for account: String) throws {183 let t = secret.trimmingCharacters(in: .whitespacesAndNewlines)184 guard !t.isEmpty else { throw CredentialError.empty }185 lock.withLock { values[account] = t }186 }187 public func removeSecret(for account: String) throws { lock.withLock { values[account] = nil } }188 public func accounts() throws -> [String] { lock.withLock { values.keys.sorted() } }189}190191/// A user-configured OpenAI-compatible endpoint. The secret lives in the credential store under `CredentialAccount.endpoint(id)`.192public struct EndpointProfile: Sendable, Codable, Hashable, Identifiable {193 public var id: String194 public var name: String195 /// Base URL up to and including the version segment, for example `https://host/v1`.196 public var baseURL: String197 public var defaultModelID: String?198 public var allowInsecureHTTP: Bool199 /// Extra non-secret headers. Names that carry credentials are refused at save time.200 public var extraHeaders: [String: String]201 public var createdAt: Date202 public init(id: String = UUID().uuidString, name: String, baseURL: String, defaultModelID: String? = nil, allowInsecureHTTP: Bool = false,203 extraHeaders: [String: String] = [:], createdAt: Date = Date()) {204 self.id = id; self.name = name; self.baseURL = baseURL; self.defaultModelID = defaultModelID205 self.allowInsecureHTTP = allowInsecureHTTP; self.extraHeaders = extraHeaders; self.createdAt = createdAt206 }207208 /// Validates the profile: URL policy plus header hygiene.209 public func validated() throws -> URL {210 let url = try EndpointPolicy.validate(baseURL, allowInsecure: allowInsecureHTTP)211 for (name, value) in extraHeaders {212 let lower = name.lowercased().trimmingCharacters(in: .whitespaces)213 guard !lower.isEmpty, lower.range(of: #"^[a-z0-9\-_]+$"#, options: .regularExpression) != nil else {214 throw AstraError.invalidRequest("“\(name)” is not a valid header name.")215 }216 guard !Redactor.sensitiveHeaders.contains(lower), lower != "host", lower != "content-length" else {217 throw AstraError.invalidRequest("Put credentials in the API key field, not in the “\(name)” header.")218 }219 // scalar check: "\r\n" is a single Character in Swift, so a Character-level search would miss it220 guard !value.unicodeScalars.contains(where: { $0.value < 0x20 || $0.value == 0x7F }) else { throw AstraError.invalidRequest("Header values cannot contain line breaks or control characters.") }221 }222 return url223 }224}225