SPB Git

Repository Public License

KeychainSecretStore.swift 4.4 KB 97 lines swift

1import Foundation2import NavigatorCore3import Security45/// `SecretStore` backed by Keychain generic-password items.6///7/// - Items are `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`: readable by background work after the first8///   unlock, never included in backups restored to another device.9/// - Items are not synchronizable (no iCloud Keychain).10/// - `service` namespaces the store; the secret's key is the item's account.11///12/// On macOS the accessibility class is only honoured by the data-protection keychain, which requires a signed13/// app with an application identifier. `useDataProtectionKeychain: false` selects the legacy file-based login14/// keychain for unsigned development builds and command-line tests; never ship with it.15public actor KeychainSecretStore: SecretStore {16    public nonisolated let service: String17    public nonisolated let accessGroup: String?18    public nonisolated let useDataProtectionKeychain: Bool1920    public init(service: String, accessGroup: String? = nil, useDataProtectionKeychain: Bool = true) {21        self.service = service22        self.accessGroup = accessGroup23        self.useDataProtectionKeychain = useDataProtectionKeychain24    }2526    private func baseQuery(account: String?) -> [String: Any] {27        var query: [String: Any] = [28            kSecClass as String: kSecClassGenericPassword,29            kSecAttrService as String: service,30            kSecAttrSynchronizable as String: false,31        ]32        if let account { query[kSecAttrAccount as String] = account }33        if let accessGroup { query[kSecAttrAccessGroup as String] = accessGroup }34        #if os(macOS)35        if useDataProtectionKeychain { query[kSecUseDataProtectionKeychain as String] = true }36        #endif37        return query38    }3940    public func setSecret(_ value: Data, for key: String) throws {41        let update: [String: Any] = [42            kSecValueData as String: value,43            kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,44        ]45        var status = SecItemUpdate(baseQuery(account: key) as CFDictionary, update as CFDictionary)46        if status == errSecItemNotFound {47            var item = baseQuery(account: key)48            item.merge(update) { _, new in new }49            status = SecItemAdd(item as CFDictionary, nil)50        }51        guard status == errSecSuccess else { throw SecretStoreError(operation: "write", status: status) }52    }5354    public func secret(for key: String) throws -> Data? {55        var query = baseQuery(account: key)56        query[kSecReturnData as String] = true57        query[kSecMatchLimit as String] = kSecMatchLimitOne58        var result: CFTypeRef?59        let status = SecItemCopyMatching(query as CFDictionary, &result)60        if status == errSecItemNotFound { return nil }61        guard status == errSecSuccess else { throw SecretStoreError(operation: "read", status: status) }62        return result as? Data63    }6465    public func removeSecret(for key: String) throws {66        let status = SecItemDelete(baseQuery(account: key) as CFDictionary)67        guard status == errSecSuccess || status == errSecItemNotFound else {68            throw SecretStoreError(operation: "delete", status: status)69        }70    }7172    public func removeAllSecrets() throws {73        var query = baseQuery(account: nil)74        #if os(macOS)75        // The legacy keychain deletes a single item unless asked for all; the data-protection keychain (and76        // iOS) deletes every match and rejects the key.77        if !useDataProtectionKeychain { query[kSecMatchLimit as String] = kSecMatchLimitAll }78        #endif79        let status = SecItemDelete(query as CFDictionary)80        guard status == errSecSuccess || status == errSecItemNotFound else {81            throw SecretStoreError(operation: "delete all", status: status)82        }83    }8485    public func secretKeys() throws -> [String] {86        var query = baseQuery(account: nil)87        query[kSecReturnAttributes as String] = true88        query[kSecMatchLimit as String] = kSecMatchLimitAll89        var result: CFTypeRef?90        let status = SecItemCopyMatching(query as CFDictionary, &result)91        if status == errSecItemNotFound { return [] }92        guard status == errSecSuccess else { throw SecretStoreError(operation: "list", status: status) }93        let items = result as? [[String: Any]] ?? []94        return items.compactMap { $0[kSecAttrAccount as String] as? String }.sorted()95    }96}97
Files main
Menu

Theme