SPB Git

Repository Public

SecureStore.swift 5.0 KB 107 lines swift

1import Foundation2import Security34/// Secret storage abstraction. Production: `KeychainSecureStore`. Tests: `InMemorySecureStore`.5public protocol SecureStore: Sendable {6    func read(_ account: String) throws -> Data?7    func write(_ data: Data, account: String) throws8    func delete(_ account: String) throws9}1011public struct SecureStoreError: Error, Sendable, Equatable, CustomStringConvertible {12    public let status: Int3213    public let operation: String14    public var description: String {15        let text = SecCopyErrorMessageString(status, nil) as String? ?? "unknown"16        return "Keychain \(operation) failed (\(status)): \(text)"17    }18}1920/// Generic-password items in the Keychain: `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`, never synchronised21/// to iCloud, optional access group (to share the session with an extension later).22///23/// `dataProtection` selects the data-protection keychain (the only keychain on iOS; on macOS it requires a signed24/// app with an application identifier, which the shipped app has). An unsigned binary (command-line tests) must25/// pass `false`, which uses the login keychain on macOS, where the accessibility attribute is not applicable.26public struct KeychainSecureStore: SecureStore {27    public let service: String28    public let accessGroup: String?29    public let dataProtection: Bool3031    public init(service: String, accessGroup: String? = nil, dataProtection: Bool = true) {32        self.service = service33        self.accessGroup = accessGroup34        self.dataProtection = dataProtection35    }3637    private func base(_ account: String) -> [String: Any] {38        var q: [String: Any] = [39            kSecClass as String: kSecClassGenericPassword,40            kSecAttrService as String: service,41            kSecAttrAccount as String: account,42            kSecAttrSynchronizable as String: false,43        ]44        if dataProtection { q[kSecUseDataProtectionKeychain as String] = true }45        if let g = accessGroup { q[kSecAttrAccessGroup as String] = g }46        return q47    }4849    public func read(_ account: String) throws -> Data? {50        var q = base(account)51        q[kSecReturnData as String] = true52        q[kSecMatchLimit as String] = kSecMatchLimitOne53        var out: CFTypeRef?54        let status = SecItemCopyMatching(q as CFDictionary, &out)55        if status == errSecItemNotFound { return nil }56        guard status == errSecSuccess else { throw SecureStoreError(status: status, operation: "read") }57        return out as? Data58    }5960    public func write(_ data: Data, account: String) throws {61        let q = base(account)62        var attrs: [String: Any] = [kSecValueData as String: data]63        if dataProtection { attrs[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly }64        var status = SecItemUpdate(q as CFDictionary, attrs as CFDictionary)65        if status == errSecItemNotFound {66            status = SecItemAdd(q.merging(attrs) { $1 } as CFDictionary, nil)67        }68        guard status == errSecSuccess else { throw SecureStoreError(status: status, operation: "write") }69    }7071    public func delete(_ account: String) throws {72        let status = SecItemDelete(base(account) as CFDictionary)73        guard status == errSecSuccess || status == errSecItemNotFound else { throw SecureStoreError(status: status, operation: "delete") }74    }75}7677/// Volatile store for tests.78public final class InMemorySecureStore: SecureStore, @unchecked Sendable {79    private let lock = NSLock()80    private var items: [String: Data] = [:]81    public var failWrites = false82    public init() {}83    public func read(_ account: String) throws -> Data? { lock.withLock { items[account] } }84    public func write(_ data: Data, account: String) throws {85        if failWrites { throw SecureStoreError(status: errSecNotAvailable, operation: "write") }86        lock.withLock { items[account] = data }87    }88    public func delete(_ account: String) throws { lock.withLock { items[account] = nil } }89    public var accounts: [String] { lock.withLock { items.keys.sorted() } }90}9192#if DEBUG93/// DEBUG ONLY — plain file inside the app container, selected by the UI tests so that a signed-in state can survive94/// relaunches of an ad-hoc signed build (whose Keychain identity changes at every build). Never compiled in Release.95public struct DebugFileSecureStore: SecureStore {96    public let directory: URL97    public init(directory: URL) { self.directory = directory }98    private func url(_ account: String) -> URL { directory.appendingPathComponent(account.replacingOccurrences(of: "/", with: "_") + ".secret") }99    public func read(_ account: String) throws -> Data? { try? Data(contentsOf: url(account)) }100    public func write(_ data: Data, account: String) throws {101        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)102        try data.write(to: url(account), options: [.atomic])103    }104    public func delete(_ account: String) throws { try? FileManager.default.removeItem(at: url(account)) }105}106#endif107
Files main
Menu

Theme