Update key management for database service
This commit is contained in:
@@ -1,124 +1,53 @@
|
||||
import Foundation
|
||||
import DataLiteCore
|
||||
|
||||
/// A protocol for supplying encryption keys to `DatabaseService` instances.
|
||||
/// A protocol for providing encryption keys to a database service.
|
||||
///
|
||||
/// `DatabaseServiceKeyProvider` encapsulates all responsibilities for managing encryption keys
|
||||
/// for one or more `DatabaseService` instances. It allows a database service to delegate key
|
||||
/// retrieval, secure storage, rotation, and access control, enabling advanced security strategies
|
||||
/// such as per-user key derivation, hardware-backed keys, biometric authentication, or ephemeral
|
||||
/// in-memory secrets.
|
||||
/// `DatabaseServiceKeyProvider` is responsible for managing encryption keys used
|
||||
/// by a database service. This makes it possible to implement different strategies for storing
|
||||
/// and retrieving keys: static, dynamic, hardware-backed, biometric, and others.
|
||||
///
|
||||
/// The provider is queried automatically by the database service whenever a new connection
|
||||
/// is created or re-established (for example, during service initialization, after a reconnect,
|
||||
/// or when the service requests a key rotation).
|
||||
/// - The service requests a key when establishing or restoring a connection.
|
||||
/// - If decryption fails, the service may ask the provider whether it should attempt to reconnect.
|
||||
/// - If applying a key fails (for example, the key does not match or the
|
||||
/// ``databaseService(keyFor:)`` method throws an error), this error is reported
|
||||
/// to the provider through ``databaseService(_:didReceive:)``.
|
||||
///
|
||||
/// Error handling and diagnostics related specifically to encryption or key operations
|
||||
/// (such as when a key is unavailable, authentication is denied, or decryption fails)
|
||||
/// are reported to the provider via the optional ``databaseService(_:didReceive:)`` callback.
|
||||
/// The provider is **not** notified of generic database or connection errors unrelated to
|
||||
/// encryption.
|
||||
/// - Important: The provider does not receive notifications about general database errors.
|
||||
///
|
||||
/// - Important: This protocol is **exclusively** for cryptographic key management.
|
||||
/// It must not be used for generic database error handling or for concerns unrelated to
|
||||
/// encryption, authorization, or key lifecycle.
|
||||
/// ## Topics
|
||||
///
|
||||
/// ## Key Availability
|
||||
/// ### Instance Methods
|
||||
///
|
||||
/// There are two distinct scenarios for returning a key:
|
||||
///
|
||||
/// - **No Encryption Needed:**
|
||||
/// Return `nil` if the target database does not require encryption (i.e., should be opened
|
||||
/// in plaintext mode). This is not an error; the database service will attempt to open the
|
||||
/// database without a key. If the database is in fact encrypted, this will result in a
|
||||
/// decryption error at the SQLite level (e.g., `SQLITE_NOTADB`), which is handled by the
|
||||
/// database service as a normal failure.
|
||||
///
|
||||
/// - **Key Temporarily Unavailable:**
|
||||
/// Also return `nil` if the key is *temporarily* unavailable for any reason (for example,
|
||||
/// the user has not yet authenticated, the device is locked, a remote key is still loading,
|
||||
/// or UI authorization has not been granted).
|
||||
/// Returning `nil` in this case means the database service will not attempt to open
|
||||
/// the database with a key. This will not trigger an error callback.
|
||||
/// When the key later becomes available (for example, after user authentication or
|
||||
/// successful network retrieval), **the provider is responsible for calling**
|
||||
/// ``DatabaseService/reconnect()`` on the service to re-attempt the operation with the key.
|
||||
///
|
||||
/// - **Error Situations:**
|
||||
/// Only throw an error if a *permanent* or *unexpected* failure occurs (for example,
|
||||
/// a hardware security error, a fatal storage problem, or a cryptographic failure
|
||||
/// that cannot be resolved by waiting or user action).
|
||||
/// Thrown errors will be reported to the provider via the error callback, and may be
|
||||
/// surfaced to the UI or logs.
|
||||
///
|
||||
/// - Tip: Never throw for temporary unavailability (such as "user has not unlocked" or
|
||||
/// "still waiting for user action")—just return `nil` in these cases.
|
||||
/// Use thrown errors only for non-recoverable or unexpected failures.
|
||||
///
|
||||
/// ## Error Callback
|
||||
///
|
||||
/// The method ``databaseService(_:didReceive:)`` will be called only for errors thrown by
|
||||
/// ``databaseServiceKey(_:)`` or by the key application process (such as if the key fails
|
||||
/// to decrypt the database).
|
||||
/// It will *not* be called for generic database or connection errors.
|
||||
///
|
||||
/// Implement this method if you wish to log, recover from, or respond to permanent key-related
|
||||
/// failures (such as prompting the user, resetting state, or displaying errors).
|
||||
public protocol DatabaseServiceKeyProvider: AnyObject {
|
||||
/// Returns the encryption key to be applied to the given database service.
|
||||
/// - ``databaseService(keyFor:)``
|
||||
/// - ``databaseService(shouldReconnect:)``
|
||||
/// - ``databaseService(_:didReceive:)``
|
||||
public protocol DatabaseServiceKeyProvider: AnyObject, Sendable {
|
||||
/// Returns the encryption key for the specified database service.
|
||||
///
|
||||
/// This method is invoked by the `DatabaseService` during connection initialization,
|
||||
/// reconnection, or explicit key rotation. Implementations may return a static key,
|
||||
/// derive it from external data, fetch it from secure hardware, or perform required
|
||||
/// user authentication.
|
||||
/// May return `nil` if the encryption key is currently unavailable or if the database
|
||||
/// does not require encryption.
|
||||
///
|
||||
/// - Parameter service: The requesting database service.
|
||||
/// - Returns: A `Connection.Key` representing the encryption key, or `nil` if encryption is
|
||||
/// not required for this database or the key is temporarily unavailable. Returning `nil`
|
||||
/// will cause the database service to attempt opening the database in plaintext mode.
|
||||
/// If the database is actually encrypted, access will fail with a decryption error.
|
||||
/// - Throws: Only throw for unrecoverable or unexpected errors (such as hardware failure,
|
||||
/// fatal storage issues, or irrecoverable cryptographic errors). Do **not** throw for
|
||||
/// temporary unavailability; instead, return `nil` and call ``DatabaseService/reconnect()``
|
||||
/// later when the key becomes available.
|
||||
///
|
||||
/// - Note: This method may be called multiple times during the lifecycle of a service,
|
||||
/// including after a failed decryption attempt or key rotation event.
|
||||
func databaseServiceKey(_ service: DatabaseService) throws -> Connection.Key?
|
||||
/// - Parameter service: The service requesting the key.
|
||||
/// - Returns: The encryption key or `nil`.
|
||||
/// - Throws: An error if the key cannot be retrieved.
|
||||
func databaseService(keyFor service: DatabaseServiceProtocol) throws -> Connection.Key?
|
||||
|
||||
/// Notifies the provider that the database service encountered an error
|
||||
/// related to key retrieval or application.
|
||||
/// Indicates whether the service should attempt to reconnect if applying the key fails.
|
||||
///
|
||||
/// This method is called **only** when the service fails to retrieve or apply an
|
||||
/// encryption key (e.g., if ``databaseServiceKey(_:)`` throws, or if the key fails
|
||||
/// to decrypt the database due to a password/key mismatch).
|
||||
///
|
||||
/// Use this callback to report diagnostics, trigger recovery logic, prompt the user
|
||||
/// for authentication, or update internal state.
|
||||
/// By default, this method does nothing; implement it only if you need to respond
|
||||
/// to key-related failures.
|
||||
/// - Parameter service: The database service.
|
||||
/// - Returns: `true` to attempt reconnection. Defaults to `false`.
|
||||
func databaseService(shouldReconnect service: DatabaseServiceProtocol) -> Bool
|
||||
|
||||
/// Notifies the provider of an error that occurred while retrieving or applying the key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - service: The database service reporting the error.
|
||||
/// - error: The error encountered during key retrieval or application.
|
||||
func databaseService(_ service: DatabaseService, didReceive error: Error)
|
||||
|
||||
/// Informs the service whether it should attempt to reconnect automatically.
|
||||
///
|
||||
/// Return `true` if the service should retry connecting (for example, if the key may
|
||||
/// become available shortly). By default, returns `false`.
|
||||
///
|
||||
/// - Parameter service: The database service.
|
||||
/// - Returns: `true` to retry, `false` to abort.
|
||||
func databaseServiceShouldReconnect(_ service: DatabaseService) -> Bool
|
||||
func databaseService(_ service: DatabaseServiceProtocol, didReceive error: Error)
|
||||
}
|
||||
|
||||
public extension DatabaseServiceKeyProvider {
|
||||
/// Default no-op implementation for key-related error reporting.
|
||||
func databaseService(_ service: DatabaseService, didReceive error: Error) {}
|
||||
|
||||
/// Default implementation disables automatic reconnect attempts.
|
||||
func databaseServiceShouldReconnect(_ service: DatabaseService) -> Bool {
|
||||
false
|
||||
}
|
||||
func databaseService(shouldReconnect service: DatabaseServiceProtocol) -> Bool { false }
|
||||
func databaseService(_ service: DatabaseServiceProtocol, didReceive error: Error) {}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import Foundation
|
||||
import DataLiteCore
|
||||
|
||||
/// A protocol that defines a common interface for working with a database connection.
|
||||
/// A protocol for a database service.
|
||||
///
|
||||
/// `DatabaseServiceProtocol` abstracts the core operations required to safely interact with a
|
||||
/// SQLite-compatible database. Conforming types provide thread-safe execution of closures with a live
|
||||
/// `Connection`, optional transaction support, reconnection logic, and pluggable encryption key
|
||||
/// management via a ``DatabaseServiceKeyProvider``.
|
||||
/// `DatabaseServiceProtocol` defines the core capabilities required for
|
||||
/// reliable interaction with a database. Conforming implementations provide
|
||||
/// execution of client closures with a live connection, transaction wrapping,
|
||||
/// reconnection logic, and flexible encryption key management.
|
||||
///
|
||||
/// This protocol forms the foundation for safe, modular service layers on top of a database.
|
||||
/// This enables building safe and extensible service layers on top of
|
||||
/// a database.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
@@ -16,6 +17,7 @@ import DataLiteCore
|
||||
///
|
||||
/// - ``DatabaseServiceKeyProvider``
|
||||
/// - ``keyProvider``
|
||||
/// - ``applyKeyProvider()``
|
||||
///
|
||||
/// ### Connection Management
|
||||
///
|
||||
@@ -26,63 +28,63 @@ import DataLiteCore
|
||||
/// - ``Perform``
|
||||
/// - ``perform(_:)``
|
||||
/// - ``perform(in:closure:)``
|
||||
public protocol DatabaseServiceProtocol: AnyObject {
|
||||
/// A closure that performs a database operation using an active connection.
|
||||
public protocol DatabaseServiceProtocol: AnyObject, Sendable {
|
||||
/// A closure executed with an active database connection.
|
||||
///
|
||||
/// The `Perform<T>` type alias defines a closure signature for a database operation that
|
||||
/// receives a live `Connection` and returns a value or throws an error. This enables
|
||||
/// callers to express discrete, atomic database operations for execution via
|
||||
/// ``perform(_:)`` or ``perform(in:closure:)``.
|
||||
/// Used by the service to safely provide access to `Connection`
|
||||
/// within the appropriate execution context.
|
||||
///
|
||||
/// - Parameter connection: The active database connection.
|
||||
/// - Returns: The result of the operation.
|
||||
/// - Throws: Any error thrown during execution of the operation.
|
||||
/// - Returns: The value returned by the closure.
|
||||
/// - Throws: An error if the closure execution fails.
|
||||
typealias Perform<T> = (Connection) throws -> T
|
||||
|
||||
/// The object responsible for providing encryption keys for the database connection.
|
||||
/// The encryption key provider for the database service.
|
||||
///
|
||||
/// When assigned, the key provider will be queried for a key and applied to the current
|
||||
/// connection, if available. If key retrieval or application fails, the error is reported
|
||||
/// via `databaseService(_:didReceive:)` and not thrown from the setter.
|
||||
///
|
||||
/// - Important: Setting this property does not guarantee that the connection becomes available;
|
||||
/// error handling is asynchronous via callback.
|
||||
/// Enables external management of encryption keys.
|
||||
/// When set, the service can request a key when establishing or
|
||||
/// restoring a connection, and can also notify about errors
|
||||
/// encountered while applying a key.
|
||||
var keyProvider: DatabaseServiceKeyProvider? { get set }
|
||||
|
||||
/// Re-establishes the database connection using the stored provider.
|
||||
/// Applies the encryption key from the current provider.
|
||||
///
|
||||
/// If a `keyProvider` is set, the method attempts to retrieve and apply a key
|
||||
/// to the new connection. All errors encountered during connection creation or
|
||||
/// key application are thrown. If an error occurs that is related to encryption key
|
||||
/// retrieval or application, it is also reported to the `DatabaseServiceKeyProvider`
|
||||
/// via its `databaseService(_:didReceive:)` callback.
|
||||
/// Calls the configured ``keyProvider`` to obtain a key and applies
|
||||
/// it to the active connection. If the key is unavailable or an
|
||||
/// error occurs while applying it, the method throws.
|
||||
///
|
||||
/// - Throws: Any error that occurs during connection creation or key application.
|
||||
/// - Throws: An error if the key cannot be retrieved or applied.
|
||||
func applyKeyProvider() throws
|
||||
|
||||
/// Reopens the database connection.
|
||||
///
|
||||
/// Creates a new connection using the provider and applies the
|
||||
/// encryption key if ``keyProvider`` is set. Typically used when
|
||||
/// the previous connection has become invalid.
|
||||
///
|
||||
/// - Throws: An error if the new connection cannot be created or the key cannot be applied.
|
||||
func reconnect() throws
|
||||
|
||||
/// Executes the given closure with a live connection in a thread-safe manner.
|
||||
/// Executes the given closure with an active connection.
|
||||
///
|
||||
/// All invocations are serialized to prevent concurrent database access.
|
||||
/// The closure receives the connection and may perform any
|
||||
/// database operations within the current context.
|
||||
///
|
||||
/// - Parameter closure: The database operation to perform.
|
||||
/// - Returns: The result produced by the closure.
|
||||
/// - Throws: Any error thrown by the closure.
|
||||
/// - Parameter closure: The closure that accepts a connection.
|
||||
/// - Returns: The value returned by the closure.
|
||||
/// - Throws: An error if one occurs during closure execution.
|
||||
func perform<T>(_ closure: Perform<T>) rethrows -> T
|
||||
|
||||
/// Executes the given closure within a transaction.
|
||||
///
|
||||
/// If no transaction is active, a new transaction of the specified type is started. The closure
|
||||
/// is executed atomically: if it succeeds, the transaction is committed; if it throws, the
|
||||
/// transaction is rolled back. If a transaction is already active, the closure is executed
|
||||
/// without starting a new one.
|
||||
/// If the connection is in autocommit mode, the method automatically
|
||||
/// begins a transaction, executes the closure, and commits the changes.
|
||||
/// In case of failure, the transaction is rolled back.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - transaction: The type of transaction to begin (e.g., `deferred`, `immediate`, `exclusive`).
|
||||
/// - closure: The database operation to perform within the transaction.
|
||||
/// - Returns: The result produced by the closure.
|
||||
/// - Throws: Any error thrown by the closure or transaction control statements.
|
||||
func perform<T>(
|
||||
in transaction: TransactionType,
|
||||
closure: Perform<T>
|
||||
) rethrows -> T
|
||||
/// - transaction: The type of transaction to begin.
|
||||
/// - closure: The closure that accepts a connection.
|
||||
/// - Returns: The value returned by the closure.
|
||||
/// - Throws: An error if one occurs during closure execution.
|
||||
func perform<T>(in transaction: TransactionType, closure: Perform<T>) rethrows -> T
|
||||
}
|
||||
|
||||
@@ -1,21 +1,38 @@
|
||||
import Foundation
|
||||
|
||||
/// Protocol for managing and running database schema migrations.
|
||||
public protocol MigrationServiceProtocol: AnyObject {
|
||||
/// Type representing the schema version for migrations.
|
||||
/// Protocol for managing and executing database schema migrations.
|
||||
///
|
||||
/// Conforming types are responsible for registering migrations, applying
|
||||
/// encryption keys (if required), and executing pending migrations in
|
||||
/// ascending version order.
|
||||
///
|
||||
/// Migrations ensure that the database schema evolves consistently across
|
||||
/// application versions without requiring manual intervention.
|
||||
public protocol MigrationServiceProtocol: AnyObject, Sendable {
|
||||
/// Type representing the schema version used for migrations.
|
||||
associatedtype Version: VersionRepresentable
|
||||
|
||||
/// Provider of encryption keys for the database service.
|
||||
/// Encryption key provider for the database service.
|
||||
var keyProvider: DatabaseServiceKeyProvider? { get set }
|
||||
|
||||
/// Adds a migration to be executed by the service.
|
||||
/// Applies an encryption key to the current database connection.
|
||||
///
|
||||
/// - Throws: Any error that occurs while retrieving or applying the key.
|
||||
func applyKeyProvider() throws
|
||||
|
||||
/// Recreates the database connection and reapplies the encryption key if available.
|
||||
///
|
||||
/// - Throws: Any error that occurs while creating the connection or applying the key.
|
||||
func reconnect() throws
|
||||
|
||||
/// Registers a migration to be executed by the service.
|
||||
///
|
||||
/// - Parameter migration: The migration to register.
|
||||
/// - Throws: ``MigrationError/duplicateMigration(_:)`` if a migration with
|
||||
/// the same version or script URL is already registered.
|
||||
func add(_ migration: Migration<Version>) throws(MigrationError<Version>)
|
||||
|
||||
/// Runs all pending migrations in ascending version order.
|
||||
/// Executes all pending migrations in ascending version order.
|
||||
///
|
||||
/// - Throws: ``MigrationError/emptyMigrationScript(_:)`` if a migration
|
||||
/// script is empty.
|
||||
@@ -26,10 +43,11 @@ public protocol MigrationServiceProtocol: AnyObject {
|
||||
|
||||
@available(iOS 13.0, *)
|
||||
@available(macOS 10.15, *)
|
||||
public extension MigrationServiceProtocol where Self: Sendable {
|
||||
/// Asynchronously runs all pending migrations in ascending order.
|
||||
public extension MigrationServiceProtocol {
|
||||
/// Asynchronously executes all pending migrations in ascending order.
|
||||
///
|
||||
/// Performs the same logic as ``migrate()``, but runs asynchronously.
|
||||
/// Performs the same logic as ``migrate()``, but runs asynchronously
|
||||
/// on a background task with `.utility` priority.
|
||||
///
|
||||
/// - Throws: ``MigrationError/emptyMigrationScript(_:)`` if a migration
|
||||
/// script is empty.
|
||||
|
||||
Reference in New Issue
Block a user