SPB Git

Repository Public

Secrets.swift 6.0 KB 147 lines swift

1import Foundation2import Security34/// A secret (API key) whose textual representations are always redacted.5///6/// The only way to read the value is ``reveal()``. `description`, `debugDescription`,7/// string interpolation, `dump` and `Mirror` never expose it, and the type is8/// deliberately not `Codable`.9public struct SecretValue: Sendable, Equatable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {10    private let storage: String1112    /// Wraps a raw secret.13    public init(_ rawValue: String) { self.storage = rawValue }1415    /// Returns the raw secret. Call only at the point of use (building a header).16    public func reveal() -> String { storage }1718    /// `true` when the secret is the empty string.19    public var isEmpty: Bool { storage.isEmpty }2021    public var description: String { "SecretValue(<redacted>)" }22    public var debugDescription: String { "SecretValue(<redacted>)" }23    public var customMirror: Mirror { Mirror(self, children: [], displayStyle: .struct) }24}2526/// Errors thrown by secret stores. They carry a status code, never a secret.27public enum SecretStoreError: Error, Sendable, Equatable, CustomStringConvertible {28    /// The keychain returned an unexpected `OSStatus`.29    case keychain(status: Int32)30    /// The stored item is not valid UTF-8.31    case invalidData3233    public var description: String {34        switch self {35        case .keychain(let status): "Keychain error (OSStatus \(status))"36        case .invalidData: "Stored secret is not valid text"37        }38    }39}4041/// Storage for provider API keys, addressed by account (the provider config `id`).42public protocol SecretStore: Sendable {43    /// Stores or replaces the secret for `account`.44    func setSecret(_ secret: SecretValue, for account: String) throws45    /// Returns the secret for `account`, or `nil` when none is stored.46    func secret(for account: String) throws -> SecretValue?47    /// Deletes the secret for `account`. Deleting a missing secret is not an error.48    func deleteSecret(for account: String) throws49    /// Whether a secret exists for `account` (does not read the value).50    func hasSecret(for account: String) throws -> Bool51}5253/// Keychain-backed store using generic-password items54/// (`kSecAttrAccessibleWhenUnlockedThisDeviceOnly`).55public struct KeychainSecretStore: SecretStore {56    /// Default keychain service name.57    public static let defaultService = "ai.spboucher.spterm.ai"5859    /// Keychain service under which items are stored.60    public let service: String61    /// When `true`, items go to the data-protection keychain (requires a signed app62    /// with a keychain access group). When `false` the login keychain is used; the63    /// accessibility attribute is still set but only the data-protection keychain enforces it.64    public let useDataProtectionKeychain: Bool6566    /// Creates a store for `service`.67    public init(service: String = KeychainSecretStore.defaultService, useDataProtectionKeychain: Bool = false) {68        self.service = service69        self.useDataProtectionKeychain = useDataProtectionKeychain70    }7172    private func baseQuery(_ account: String) -> [String: Any] {73        var query: [String: Any] = [74            kSecClass as String: kSecClassGenericPassword,75            kSecAttrService as String: service,76            kSecAttrAccount as String: account,77        ]78        if useDataProtectionKeychain { query[kSecUseDataProtectionKeychain as String] = true }79        return query80    }8182    public func setSecret(_ secret: SecretValue, for account: String) throws {83        try deleteSecret(for: account)84        var query = baseQuery(account)85        query[kSecValueData as String] = Data(secret.reveal().utf8)86        query[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly87        let status = SecItemAdd(query as CFDictionary, nil)88        guard status == errSecSuccess else { throw SecretStoreError.keychain(status: status) }89    }9091    public func secret(for account: String) throws -> SecretValue? {92        var query = baseQuery(account)93        query[kSecReturnData as String] = true94        query[kSecMatchLimit as String] = kSecMatchLimitOne95        var item: CFTypeRef?96        let status = SecItemCopyMatching(query as CFDictionary, &item)97        if status == errSecItemNotFound { return nil }98        guard status == errSecSuccess else { throw SecretStoreError.keychain(status: status) }99        guard let data = item as? Data, let text = String(data: data, encoding: .utf8) else {100            throw SecretStoreError.invalidData101        }102        return SecretValue(text)103    }104105    public func deleteSecret(for account: String) throws {106        let status = SecItemDelete(baseQuery(account) as CFDictionary)107        guard status == errSecSuccess || status == errSecItemNotFound else {108            throw SecretStoreError.keychain(status: status)109        }110    }111112    public func hasSecret(for account: String) throws -> Bool {113        var query = baseQuery(account)114        query[kSecMatchLimit as String] = kSecMatchLimitOne115        query[kSecReturnAttributes as String] = true116        let status = SecItemCopyMatching(query as CFDictionary, nil)117        if status == errSecItemNotFound { return false }118        guard status == errSecSuccess else { throw SecretStoreError.keychain(status: status) }119        return true120    }121}122123/// Volatile store for tests and previews. Nothing is written to disk.124public final class InMemorySecretStore: SecretStore, @unchecked Sendable {125    private let lock = NSLock()126    private var values: [String: SecretValue] = [:]127128    /// Creates an empty store.129    public init() {}130131    public func setSecret(_ secret: SecretValue, for account: String) throws {132        lock.withLock { values[account] = secret }133    }134135    public func secret(for account: String) throws -> SecretValue? {136        lock.withLock { values[account] }137    }138139    public func deleteSecret(for account: String) throws {140        lock.withLock { _ = values.removeValue(forKey: account) }141    }142143    public func hasSecret(for account: String) throws -> Bool {144        lock.withLock { values[account] != nil }145    }146}147
Files main
Menu

Theme