SPB Git

Repository Public

SecretStore.swift 2.8 KB 57 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Security/SecretStore.swift3// Description: Secret storage abstraction with a Keychain implementation (production) and an in-memory one (tests).4import Foundation5import Security67/// Where session tokens live. Nothing secret is ever written to UserDefaults, files or logs.8public protocol SecretStore: Sendable {9    func read(_ key: String) -> String?10    func write(_ value: String, for key: String) throws11    func delete(_ key: String)12}1314public struct KeychainError: Error, CustomStringConvertible, Sendable {15    public let status: OSStatus16    public var description: String { "Keychain error \(status): " + (SecCopyErrorMessageString(status, nil) as String? ?? "unknown") }17}1819/// Generic-password items scoped to one service, readable only on this device after first unlock, never synchronised.20public struct KeychainStore: SecretStore {21    public let service: String22    public init(service: String) { self.service = service }2324    private func base(_ key: String) -> [String: Any] {25        [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: key, kSecAttrSynchronizable as String: false]26    }2728    public func read(_ key: String) -> String? {29        var q = base(key); q[kSecReturnData as String] = true; q[kSecMatchLimit as String] = kSecMatchLimitOne30        var out: CFTypeRef?31        guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data else { return nil }32        return String(data: d, encoding: .utf8)33    }3435    public func write(_ value: String, for key: String) throws {36        let data = Data(value.utf8)37        let update = SecItemUpdate(base(key) as CFDictionary, [kSecValueData as String: data] as CFDictionary)38        if update == errSecSuccess { return }39        guard update == errSecItemNotFound else { throw KeychainError(status: update) }40        var q = base(key); q[kSecValueData as String] = data; q[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly41        let add = SecItemAdd(q as CFDictionary, nil)42        guard add == errSecSuccess else { throw KeychainError(status: add) }43    }4445    public func delete(_ key: String) { SecItemDelete(base(key) as CFDictionary) }46}4748public final class InMemorySecretStore: SecretStore, @unchecked Sendable {49    private let lock = NSLock()50    private var values: [String: String] = [:]51    public init() {}52    public func read(_ key: String) -> String? { lock.withLock { values[key] } }53    public func write(_ value: String, for key: String) throws { lock.withLock { values[key] = value } }54    public func delete(_ key: String) { lock.withLock { values[key] = nil } }55    public var isEmpty: Bool { lock.withLock { values.isEmpty } }56}57
Files main
Menu

Theme