Improved type safety, local auth support, and better error handling

This commit is contained in:
2025-07-07 18:30:06 +03:00
parent cea23bb06e
commit bb3d349993
14 changed files with 556 additions and 576 deletions

View File

@@ -0,0 +1,272 @@
import Foundation
import LocalAuthentication
import Security
/// A type-safe storage abstraction over the Keychain service.
///
/// Supports storing, retrieving, and deleting generic data associated with
/// accounts and services, with optional local authentication context support.
///
/// ## Topics
///
/// ### Initializers
///
/// - ``init(service:context:)``
///
/// ### Instance Properties
///
/// - ``service``
/// - ``context``
///
/// ### Retrieving Values
///
/// - ``get(_:)-5u61a``
/// - ``get(_:)-502rt``
/// - ``get(_:)-63a3x``
/// - ``get(_:decoder:)``
///
/// ### Storing Values
///
/// - ``set(_:for:)-7053g``
/// - ``set(_:for:)-99s6o``
/// - ``set(_:for:)-2e1p6``
/// - ``set(_:for:encoder:)``
///
/// ### Deleting Values
///
/// - ``delete(_:)``
public final class KeychainStorage<
Account: KeychainAccountProtocol,
Service: KeychainServiceProtocol
>: KeychainStorageProtocol {
// MARK: - Properties
/// The service metadata associated with this Keychain storage instance.
public let service: Service?
/// An optional local authentication context used for biometric or passcode protection.
public let context: LAContext?
// MARK: - Inits
/// Creates a new `KeychainStorage` instance with the given service and authentication context.
///
/// - Parameters:
/// - service: An optional `Service` instance representing the keychain service metadata.
/// - context: An optional `LAContext` instance for authentication protection.
public init(service: Service?, context: LAContext?) {
self.service = service
self.context = context
}
// MARK: - Methods
/// Retrieves raw `Data` stored in Keychain for the specified account.
///
/// - Parameter account: The account identifier conforming to `KeychainAccountProtocol`.
/// - Returns: The raw data associated with the given account.
/// - Throws: ``KeychainError/itemNotFound`` when no keychain item matches the query.
/// - Throws: ``KeychainError/authenticationFailed`` if biometric or device authentication fails.
/// - Throws: ``KeychainError/unexpectedData`` if the stored data is missing or corrupted.
/// - Throws: ``KeychainError/unexpectedCode(_:)`` for any other OSStatus error returned by the Keychain API.
public func get(_ account: Account) throws(KeychainError) -> Data {
var query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrAccount: account.identifier,
kSecAttrSynchronizable: account.synchronizable,
kSecUseDataProtectionKeychain: true,
kSecMatchLimit: kSecMatchLimitOne,
kSecReturnAttributes: true,
kSecReturnData: true
]
query[kSecAttrService] = service?.identifier
query[kSecAttrAccessGroup] = service?.accessGroup
query[kSecUseAuthenticationContext] = context
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
switch status {
case errSecSuccess:
guard
let item = queryResult as? [CFString : AnyObject],
let data = item[kSecValueData] as? Data
else { throw KeychainError.unexpectedData }
return data
case errSecItemNotFound:
throw KeychainError.itemNotFound
case errSecAuthFailed:
throw KeychainError.authenticationFailed
default:
throw KeychainError.unexpectedCode(status)
}
}
/// Retrieves a UTF-8 encoded string stored in Keychain for the specified account.
///
/// - Parameter account: The account identifier conforming to `KeychainAccountProtocol`.
/// - Returns: The stored string value associated with the account.
/// - Throws: ``KeychainError/itemNotFound`` when no keychain item matches the query.
/// - Throws: ``KeychainError/authenticationFailed`` if biometric or device authentication fails.
/// - Throws: ``KeychainError/unexpectedData`` if the stored data cannot be decoded as UTF-8.
/// - Throws: ``KeychainError/unexpectedCode(_:)`` for any other OSStatus error returned by the Keychain API.
public func get(_ account: Account) throws(KeychainError) -> String {
guard let value = String(data: try get(account), encoding: .utf8) else {
throw KeychainError.unexpectedData
}
return value
}
/// Retrieves a `UUID` stored in Keychain for the specified account.
///
/// - Parameter account: The account identifier conforming to `KeychainAccountProtocol`.
/// - Returns: The stored UUID value associated with the account.
/// - Throws: ``KeychainError/itemNotFound`` when no keychain item matches the query.
/// - Throws: ``KeychainError/authenticationFailed`` if biometric or device authentication fails.
/// - Throws: ``KeychainError/unexpectedData`` if the stored string is missing or is not a valid UUID.
/// - Throws: ``KeychainError/unexpectedCode(_:)`` for any other OSStatus error returned by the Keychain API.
public func get(_ account: Account) throws(KeychainError) -> UUID {
guard let value = UUID(uuidString: try get(account)) else {
throw KeychainError.unexpectedData
}
return value
}
/// Retrieves a value of type `T` stored in Keychain, decoded from JSON using the provided decoder.
///
/// - Parameters:
/// - account: The account identifier conforming to `KeychainAccountProtocol`.
/// - decoder: The `JSONDecoder` instance used to decode the data (default is a new instance).
/// - Returns: The decoded value of type `T`.
/// - Throws: ``KeychainError/itemNotFound`` when no keychain item matches the query.
/// - Throws: ``KeychainError/authenticationFailed`` if biometric or device authentication fails.
/// - Throws: ``KeychainError/unexpectedData`` if the stored data is missing or corrupted.
/// - Throws: ``KeychainError/unexpectedCode(_:)`` for any OSStatus error returned by the Keychain API.
/// - Throws: ``KeychainError/unexpectedError(_:)`` if decoding the data into `T` fails.
public func get<T: Decodable>(
_ account: Account,
decoder: JSONDecoder = .init()
) throws(KeychainError) -> T {
let value: Data = try get(account)
do {
return try decoder.decode(T.self, from: value)
} catch {
throw KeychainError.unexpectedError(error)
}
}
/// Stores raw `Data` in the Keychain for the specified account, replacing any existing value.
///
/// - Parameters:
/// - value: The raw data to store in the Keychain.
/// - account: The account identifier conforming to `KeychainAccountProtocol`.
/// - Throws: ``KeychainError/unexpectedError(_:)`` if access control creation fails.
/// - Throws: ``KeychainError/unexpectedCode(_:)`` if adding the item to the Keychain fails.
/// - Throws: Any error thrown by ``delete(_:)`` if the previous value cannot be removed.
public func set(_ value: Data, for account: Account) throws(KeychainError) {
try delete(account)
var error: Unmanaged<CFError>?
let access = SecAccessControlCreateWithFlags(
nil, account.protection, account.accessFlags, &error
)
guard let access else {
throw KeychainError.unexpectedError(error?.takeUnretainedValue())
}
var query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrAccount: account.identifier,
kSecAttrSynchronizable: account.synchronizable,
kSecUseDataProtectionKeychain: true,
kSecAttrAccessControl: access,
kSecValueData: value
]
query[kSecAttrService] = service?.identifier
query[kSecAttrAccessGroup] = service?.accessGroup
query[kSecUseAuthenticationContext] = context
let status = SecItemAdd(query as CFDictionary, nil)
guard status == noErr else {
throw KeychainError.unexpectedCode(status)
}
}
/// Stores a UTF-8 encoded string in the Keychain for the specified account.
///
/// - Parameters:
/// - value: The string value to store.
/// - account: The account identifier conforming to `KeychainAccountProtocol`.
/// - Throws: ``KeychainError/unexpectedError(_:)`` if access control creation fails.
/// - Throws: ``KeychainError/unexpectedCode(_:)`` if adding the item to the Keychain fails.
/// - Throws: Any error thrown by ``set(_:for:)-7053g`` if encoding or insertion fails.
public func set(_ value: String, for account: Account) throws(KeychainError) {
try set(value.data(using: .utf8)!, for: account)
}
/// Stores a `UUID` value as a string in the Keychain for the specified account.
///
/// - Parameters:
/// - value: The UUID value to store.
/// - account: The account identifier conforming to `KeychainAccountProtocol`.
/// - Throws: ``KeychainError/unexpectedError(_:)`` if access control creation fails.
/// - Throws: ``KeychainError/unexpectedCode(_:)`` if adding the item to the Keychain fails.
/// - Throws: Any error thrown by ``set(_:for:)-7053g`` if encoding or insertion fails.
public func set(_ value: UUID, for account: Account) throws(KeychainError) {
try set(value.uuidString, for: account)
}
/// Stores an `Encodable` value in the Keychain as JSON-encoded data for the specified account.
///
/// - Parameters:
/// - value: The value to encode and store.
/// - account: The account identifier conforming to `KeychainAccountProtocol`.
/// - encoder: The `JSONEncoder` to use for encoding the value (default is a new instance).
/// - Throws: ``KeychainError/unexpectedError(_:)`` if encoding fails.
/// - Throws: ``KeychainError/unexpectedError(_:)`` if access control creation fails.
/// - Throws: ``KeychainError/unexpectedCode(_:)`` if adding the item to the Keychain fails.
/// - Throws: Any error thrown by ``set(_:for:)-7053g`` if insertion fails.
public func set<T: Encodable>(
_ value: T,
for account: Account,
encoder: JSONEncoder = .init()
) throws(KeychainError) {
do {
let data = try encoder.encode(value)
try set(data, for: account)
} catch let error as KeychainError {
throw error
} catch {
throw KeychainError.unexpectedError(error)
}
}
/// Deletes the item associated with the specified account from the Keychain.
///
/// If no item exists for the given account, the method does nothing and does not throw an error.
///
/// - Parameter account: The account identifier conforming to `KeychainAccountProtocol`.
/// - Throws: ``KeychainError/unexpectedCode(_:)`` if deletion fails with an unexpected OSStatus.
public func delete(_ account: Account) throws(KeychainError) {
var query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrAccount: account.identifier,
kSecAttrSynchronizable: account.synchronizable,
kSecUseDataProtectionKeychain: true
]
query[kSecAttrService] = service?.identifier
query[kSecAttrAccessGroup] = service?.accessGroup
query[kSecUseAuthenticationContext] = context
let status = SecItemDelete(query as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw KeychainError.unexpectedCode(status)
}
}
}

View File

@@ -0,0 +1,15 @@
import Foundation
/// Errors that can occur during Keychain operations.
public enum KeychainError: Error {
/// Authentication failed, e.g., due to biometric or passcode denial.
case authenticationFailed
/// No item found matching the query.
case itemNotFound
/// Unexpected or corrupted data found in Keychain item.
case unexpectedData
/// An unexpected OSStatus error code returned by Keychain API.
case unexpectedCode(OSStatus)
/// A generic unexpected error, with optional underlying error info.
case unexpectedError(Error?)
}

View File

@@ -1,117 +0,0 @@
//
// Keychain.swift
// keychain-kit
//
// Created by Aleksey Zgurskiy on 02.02.2020.
// Copyright © 2020 mr.noone. All rights reserved.
//
import Foundation
public protocol KeychainProtocol {
func get(_ key: String) throws -> Data
func get(_ key: String) throws -> String
func get(_ key: String) throws -> UUID
func get<T>(_ key: String, decoder: JSONDecoder) throws -> T where T: Decodable
func set(_ data: Data, for key: String) throws
func set(_ value: String, for key: String) throws
func set(_ uuid: UUID, for key: String) throws
func set<T>(_ value: T, for key: String, encoder: JSONEncoder) throws where T: Encodable
func delete(_ key: String) throws
}
public struct Keychain: KeychainProtocol {
public enum Error: Swift.Error {
case noData
case unexpectedData
case unexpected(code: OSStatus)
}
// MARK: - Inits
public init() {}
// MARK: - Public methods
public func get(_ key: String) throws -> Data {
let query: [CFString : AnyObject] = [
kSecClass : kSecClassGenericPassword,
kSecAttrAccount : key as AnyObject,
kSecMatchLimit : kSecMatchLimitOne,
kSecReturnAttributes : kCFBooleanTrue,
kSecReturnData : kCFBooleanTrue
]
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
guard status != errSecItemNotFound else { throw Error.noData }
guard status == noErr else { throw Error.unexpected(code: status) }
guard
let item = queryResult as? [CFString : AnyObject],
let data = item[kSecValueData] as? Data
else { throw Error.noData }
return data
}
public func get(_ key: String) throws -> String {
guard let value = String(data: try get(key), encoding: .utf8) else {
throw Error.unexpectedData
}
return value
}
public func get(_ key: String) throws -> UUID {
guard let value = UUID(uuidString: try get(key)) else {
throw Error.unexpectedData
}
return value
}
public func get<T>(_ key: String, decoder: JSONDecoder = JSONDecoder()) throws -> T where T: Decodable {
return try decoder.decode(T.self, from: get(key))
}
public func set(_ data: Data, for key: String) throws {
try delete(key)
let query: [CFString : AnyObject] = [
kSecClass : kSecClassGenericPassword,
kSecAttrAccount : key as AnyObject,
kSecValueData : data as AnyObject
]
let status = SecItemAdd(query as CFDictionary, nil)
guard status == noErr else { throw Error.unexpected(code: status) }
}
public func set(_ value: String, for key: String) throws {
try set(value.data(using: .utf8)!, for: key)
}
public func set(_ uuid: UUID, for key: String) throws {
try set(uuid.uuidString, for: key)
}
public func set<T>(_ value: T, for key: String, encoder: JSONEncoder = JSONEncoder()) throws where T: Encodable {
try set(encoder.encode(value), for: key)
}
public func delete(_ key: String) throws {
let query: [CFString : AnyObject] = [
kSecClass : kSecClassGenericPassword,
kSecAttrAccount : key as AnyObject
]
let status = SecItemDelete(query as CFDictionary)
guard status == noErr || status == errSecItemNotFound else {
throw Error.unexpected(code: status)
}
}
}

View File

@@ -0,0 +1,47 @@
import Foundation
/// A protocol that defines the required properties for a keychain account descriptor.
///
/// Types conforming to this protocol provide metadata for configuring secure storage
/// and access behavior for keychain items.
public protocol KeychainAccountProtocol {
/// A unique string used to identify the keychain account.
var identifier: String { get }
/// The keychain data protection level for the account.
///
/// Defaults to `kSecAttrAccessibleAfterFirstUnlock`. You may override it to use other
/// accessibility levels, such as `kSecAttrAccessibleWhenUnlocked`
/// or `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly`.
var protection: CFString { get }
/// The access control flags used to define authentication requirements.
///
/// Defaults to `[]` (no additional access control). Can be overridden to specify
/// constraints such as `.userPresence`, `.biometryAny`, or `.devicePasscode`.
var accessFlags: SecAccessControlCreateFlags { get }
/// Whether the item should be marked as synchronizable via iCloud Keychain.
///
/// Defaults to `false`. Set to `true` if the item should sync across devices.
var synchronizable: Bool { get }
}
public extension KeychainAccountProtocol {
/// Default value for `protection`: accessible after first unlock.
var protection: CFString { kSecAttrAccessibleAfterFirstUnlock }
/// Default value for `accessFlags`: no access control constraints.
var accessFlags: SecAccessControlCreateFlags { [] }
/// Default value for `synchronizable`: not synchronized across devices.
var synchronizable: Bool { false }
}
public extension KeychainAccountProtocol where Self: RawRepresentable, Self.RawValue == String {
/// Provides a default `identifier` implementation for `RawRepresentable` types
/// whose `RawValue` is `String`.
///
/// The `identifier` is derived from the raw string value.
var identifier: String { rawValue }
}

View File

@@ -0,0 +1,28 @@
import Foundation
/// A protocol that defines the required properties for a keychain service descriptor.
///
/// Types conforming to this protocol provide an identifier used to distinguish stored items
/// and may optionally specify an access group to enable keychain sharing between apps.
public protocol KeychainServiceProtocol {
/// A unique string used to identify the keychain service.
var identifier: String { get }
/// An optional keychain access group identifier to support shared access between apps.
///
/// The default implementation returns `nil`, indicating no access group is specified.
var accessGroup: String? { get }
}
public extension KeychainServiceProtocol {
/// The default implementation returns `nil`, indicating that no access group is specified.
var accessGroup: String? { nil }
}
public extension KeychainServiceProtocol where Self: RawRepresentable, Self.RawValue == String {
/// Provides a default `identifier` implementation for `RawRepresentable` types
/// whose `RawValue` is `String`.
///
/// The `identifier` is derived from the raw string value.
var identifier: String { rawValue }
}

View File

@@ -0,0 +1,124 @@
import Foundation
/// A protocol that defines a type-safe interface for storing and retrieving values
/// in the system keychain.
///
/// This protocol provides generic support for `Data`, `String`, `UUID`, and `Codable` types.
/// It allows configuring the associated account and service context for each operation.
///
/// Types conforming to this protocol must specify concrete types for `Account`
/// and `Service`, which describe keychain item identity and service grouping.
///
/// ## Topics
///
/// ### Associated Types
///
/// - ``Account``
/// - ``Service``
///
/// ### Instance Properties
///
/// - ``service``
///
/// ### Retrieving Values
///
/// - ``get(_:)-2gcee``
/// - ``get(_:)-23z7h``
/// - ``get(_:)-4xbe6``
/// - ``get(_:decoder:)``
///
/// ### Storing Values
///
/// - ``set(_:for:)-21dla``
/// - ``set(_:for:)-6nzkf``
/// - ``set(_:for:)-2smpc``
/// - ``set(_:for:encoder:)``
///
/// ### Deleting Values
///
/// - ``delete(_:)``
public protocol KeychainStorageProtocol {
/// A type that describes a keychain account and its security configuration.
associatedtype Account: KeychainAccountProtocol
/// A type that identifies a keychain service context (e.g., app or subsystem).
associatedtype Service: KeychainServiceProtocol
/// The service associated with this keychain storage instance.
///
/// This value is used as the `kSecAttrService` when interacting with the keychain.
/// If `nil`, the default service behavior is used.
var service: Service? { get }
/// Retrieves the value stored in the keychain for the specified account as raw `Data`.
///
/// - Parameter account: The keychain account whose value should be retrieved.
/// - Returns: The data associated with the given account.
/// - Throws: An error if the item is not found, access is denied, or another keychain error occurs.
func get(_ account: Account) throws(KeychainError) -> Data
/// Retrieves the value stored in the keychain for the specified account as a UTF-8 string.
///
/// - Parameter account: The keychain account whose value should be retrieved.
/// - Returns: A string decoded from the stored data using UTF-8 encoding.
/// - Throws: An error if the item is not found, the data is not valid UTF-8,
/// or a keychain access error occurs.
func get(_ account: Account) throws(KeychainError) -> String
/// Retrieves the value stored in the keychain for the specified account as a `UUID`.
///
/// - Parameter account: The keychain account whose value should be retrieved.
/// - Returns: A UUID decoded from a 16-byte binary representation stored in the keychain.
/// - Throws: An error if the item is not found, the data is not exactly 16 bytes,
/// or a keychain access error occurs.
func get(_ account: Account) throws(KeychainError) -> UUID
/// Retrieves and decodes a value of type `T` stored in the keychain for the specified account.
///
/// - Parameters:
/// - account: The keychain account whose value should be retrieved.
/// - decoder: The `JSONDecoder` instance used to decode the stored data.
/// - Returns: A decoded instance of type `T`.
/// - Throws: An error if the item is not found, decoding fails, or a keychain access error occurs.
func get<T: Decodable>(_ account: Account, decoder: JSONDecoder) throws(KeychainError) -> T
/// Stores raw `Data` in the keychain for the specified account.
///
/// - Parameters:
/// - value: The data to store in the keychain.
/// - account: The keychain account under which the data will be saved.
/// - Throws: An error if storing the data fails.
func set(_ value: Data, for account: Account) throws(KeychainError)
/// Stores a UTF-8 encoded `String` in the keychain for the specified account.
///
/// - Parameters:
/// - value: The string to store in the keychain.
/// - account: The keychain account under which the string will be saved.
/// - Throws: An error if storing the string fails.
func set(_ value: String, for account: Account) throws(KeychainError)
/// Stores a `UUID` in the keychain for the specified account.
///
/// - Parameters:
/// - value: The UUID to store in the keychain (stored in 16-byte binary format).
/// - account: The keychain account under which the UUID will be saved.
/// - Throws: An error if storing the UUID fails.
func set(_ value: UUID, for account: Account) throws(KeychainError)
/// Encodes and stores a value of type `T` in the keychain for the specified account.
///
/// - Parameters:
/// - value: The value to encode and store.
/// - account: The keychain account under which the encoded data will be saved.
/// - encoder: The `JSONEncoder` used to encode the value.
/// - Throws: An error if encoding or storing the value fails.
func set<T: Encodable>(_ value: T, for account: Account, encoder: JSONEncoder) throws(KeychainError)
/// Deletes the keychain item associated with the specified account.
///
/// - Parameter account: The keychain account whose stored value should be deleted.
/// - Note: If the item does not exist, the method completes silently without error.
/// - Throws: An error only if the item exists but removal fails.
func delete(_ account: Account) throws(KeychainError)
}