Class MultiRegionKeyProvider
- Namespace
- Excalibur.Compliance.Encryption
- Assembly
- Excalibur.Compliance.dll
Wraps two IKeyManagementProvider instances (primary and secondary) to provide multi-region disaster recovery with automatic failover.
public sealed class MultiRegionKeyProvider : IMultiRegionKeyProvider, IKeyManagementProvider, IServiceProvider, IDisposable, IKeyManagementAdmin, IKeyDestructionStatusProvider, IMultiRegionHealthMonitor, IAsyncDisposable
- Inheritance
-
MultiRegionKeyProvider
- Implements
- Inherited Members
Remarks
This provider implements active-passive failover:
- Single writer: Only the active region performs write operations
- Automatic failover: Triggered after consecutive health check failures
- Manual failback: Requires explicit confirmation to prevent split-brain
- Async replication: Keys replicated at configurable intervals
Cloud Provider Support:
- Azure Key Vault: Standard tier (manual replication) or Premium (auto-replication)
- AWS KMS: Multi-Region Keys (MRKs) with automatic synchronization
- HashiCorp Vault: Enterprise with replication or OSS with manual sync
Constructors
MultiRegionKeyProvider(IKeyManagementProvider, IKeyManagementProvider, MultiRegionOptions, ILogger<MultiRegionKeyProvider>)
Initializes a new instance of the MultiRegionKeyProvider class.
public MultiRegionKeyProvider(IKeyManagementProvider primaryProvider, IKeyManagementProvider secondaryProvider, MultiRegionOptions options, ILogger<MultiRegionKeyProvider> logger)
Parameters
primaryProviderIKeyManagementProviderThe key management provider for the primary region.
secondaryProviderIKeyManagementProviderThe key management provider for the secondary region.
optionsMultiRegionOptionsConfiguration options for multi-region behavior.
loggerILogger<MultiRegionKeyProvider>The logger for diagnostics.
Exceptions
- ArgumentNullException
Thrown when any required parameter is null.
Properties
ActiveRegionId
Gets the identifier of the currently active region.
public string ActiveRegionId { get; }
Property Value
- string
The region identifier (e.g., "westeurope", "us-east-1") of the region currently handling key management operations.
IsInFailoverMode
Gets a value indicating whether the provider is currently operating in failover mode.
public bool IsInFailoverMode { get; }
Property Value
- bool
trueif the secondary region is active due to primary failure;falseif the primary region is active.
Methods
CreateKeyIfAbsentAsync(string, EncryptionAlgorithm, string?, CancellationToken)
Ensures a key exists at keyId, creating one only if none is there, and returns its
current metadata.
public Task<KeyMetadata> CreateKeyIfAbsentAsync(string keyId, EncryptionAlgorithm algorithm, string? purpose, CancellationToken cancellationToken)
Parameters
keyIdstringThe unique identifier for the key.
algorithmEncryptionAlgorithmThe encryption algorithm to use if a key has to be created.
purposestringOptional purpose or scope for a key that has to be created.
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<KeyMetadata>
The metadata of the key now at
keyId. Never null.
Remarks
This is not a rotation and must never behave like one. If a key already exists at
keyId, this call adds no version, changes no version's status, and alters no
attribute of the key: it returns what GetKeyAsync(string, CancellationToken) returns for it. A caller that wanted a
key to exist has no reason to retire the one that already does, and RotateKeyAsync(string, EncryptionAlgorithm, string?, DateTimeOffset?, CancellationToken) is
create-OR-rotate, so using it to mean "create" demotes a live key whenever two callers race.
A lost creation race is a no-op that yields the winner's key, never an error. Two callers that both find the key absent must both come away with the same key.
What atomicity a backend can offer is the backend's to state, and it varies. A store with a conditional insert creates at most one key. A store whose only create operation also adds a version -- Azure Key Vault's key-create endpoint is the same request either way, with no conditional form -- may, under a genuinely concurrent lost race, leave more than one version behind. That is permitted. What is NOT permitted, on any backend, is demoting or retiring a version that was already there, because that is the harm this operation exists to avoid.
The returned metadata may differ from the arguments. An existing key keeps the algorithm and purpose it was created with; a caller that requires a particular algorithm must check the result rather than assume the arguments were applied.
Failure is thrown, never returned, and the result is never null. A caller cannot proceed without the value, so it cannot mistake a failed provisioning for a usable key handle -- which a result object reporting success by property makes easy to do and easy to miss.
Exceptions
- ArgumentException
Thrown when
keyIdis null or empty.
DeleteKeyAsync(string, int, CancellationToken)
Destroys a key, or schedules it for irreversible destruction, and reports which of the two occurred.
public Task<KeyDestructionOutcome> DeleteKeyAsync(string keyId, int retentionDays, CancellationToken cancellationToken)
Parameters
keyIdstringThe unique identifier of the key to delete.
retentionDaysintThe requested number of days to retain the key before irreversible destruction. A value of
0requests immediate destruction. Implementations MUST NOT silently substitute a longer window: where a backend imposes a mandatory minimum retention, the effective irreversibility instant MUST be surfaced through the returned IrreversibleAt rather than clamped in silence.cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<KeyDestructionOutcome>
A KeyDestructionOutcome whose State distinguishes a key that is irrecoverable on return (Completed) from one merely scheduled and still recoverable until IrreversibleAt (ScheduledIrreversible), or a key that did not exist (NotFound, an idempotent no-op).
Remarks
For GDPR Right to Erasure, crypto-shredding is achieved by destroying the encryption key, rendering all data encrypted with that key unrecoverable. Callers issuing a completion attestation MUST treat only Completed as irrecoverable-now: a ScheduledIrreversible key remains recoverable until its window elapses and MUST NOT be attested as erased. On failure of the underlying destruction primitive, implementations MUST fail closed (surface the failure), never report a false success.
Dispose()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public void Dispose()
DisposeAsync()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
public ValueTask DisposeAsync()
Returns
- ValueTask
A task that represents the asynchronous dispose operation.
FailbackToPrimaryAsync(string, CancellationToken)
Returns operations to the primary region after failover.
public Task FailbackToPrimaryAsync(string reason, CancellationToken cancellationToken)
Parameters
reasonstringThe reason for failback (for audit purposes).
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task
A task representing the asynchronous failback operation.
Remarks
Failback is always manual to prevent split-brain scenarios where a recovering primary might conflict with the active secondary.
Before failback, keys created during failover are synchronized from secondary to primary.
This operation is audited via FailbackCompletedEvent.
Exceptions
- InvalidOperationException
Thrown when not in failover mode or primary is unhealthy.
ForceFailoverAsync(string, CancellationToken)
Manually triggers failover to the secondary region.
public Task ForceFailoverAsync(string reason, CancellationToken cancellationToken)
Parameters
reasonstringThe reason for manual failover (for audit purposes).
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task
A task representing the asynchronous failover operation.
Remarks
Use this for planned failover during maintenance or when automatic failover thresholds have not been met but manual intervention is needed.
This operation is audited via FailoverInitiatedEvent.
Exceptions
- InvalidOperationException
Thrown when already in failover mode or secondary is unhealthy.
GetActiveKeyAsync(string?, CancellationToken)
Gets the currently active key for encryption operations.
public Task<KeyMetadata?> GetActiveKeyAsync(string? purpose, CancellationToken cancellationToken)
Parameters
purposestringOptional purpose to filter keys.
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<KeyMetadata>
The active key metadata, or null if no active key exists.
GetKeyAsync(string, CancellationToken)
Retrieves metadata for a specific encryption key.
public Task<KeyMetadata?> GetKeyAsync(string keyId, CancellationToken cancellationToken)
Parameters
keyIdstringThe unique identifier of the key.
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<KeyMetadata>
The key metadata, or null if the key does not exist.
Exceptions
- ArgumentNullException
Thrown when
keyIdis null or empty.
GetKeyVersionAsync(string, int, CancellationToken)
Retrieves metadata for a specific version of an encryption key.
public Task<KeyMetadata?> GetKeyVersionAsync(string keyId, int version, CancellationToken cancellationToken)
Parameters
keyIdstringThe unique identifier of the key.
versionintThe key version to retrieve.
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<KeyMetadata>
The key metadata for the specified version, or null if not found.
GetPrimaryHealthAsync(CancellationToken)
Gets the health status for the primary region.
public Task<RegionHealth> GetPrimaryHealthAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<RegionHealth>
The current health status of the primary region.
GetReplicationStatusAsync(CancellationToken)
Gets the current replication status between regions.
public Task<ReplicationStatus> GetReplicationStatusAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<ReplicationStatus>
The replication status including lag and pending keys.
Remarks
Use this to monitor whether RPO (Recovery Point Objective) targets are being met.
GetSecondaryHealthAsync(CancellationToken)
Gets the health status for the secondary region.
public Task<RegionHealth> GetSecondaryHealthAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<RegionHealth>
The current health status of the secondary region.
GetService(Type)
Gets the service object of the specified type.
public object? GetService(Type serviceType)
Parameters
serviceTypeTypeAn object that specifies the type of service object to get.
Returns
- object
A service object of type
serviceType.-or-
null if there is no service object of type
serviceType.
Remarks
A decorator that does not forward silently disables every capability beneath it, which the interface says in its own words. This type wraps two providers and implements only some capabilities itself, so without this override a consumer asking for anything else got null — not an error, not a warning, just an absent capability that the wrapped provider was supplying.
The one that mattered is IDurableKeyProvider. This type does not implement it and the cloud providers do, so a multi-region deployment backed by a real key vault reported as having NO durable-key capability — which the durability gate reads as a VOLATILE key store, for keys that are in fact durable. Capabilities this type implements itself are answered first, because for those the decorator's own behaviour is the correct answer and the wrapped provider's is not.
IsKeyDestroyedAsync(string, CancellationToken)
Determines whether the backend still holds any recoverable copy of a key handle's material.
public Task<bool> IsKeyDestroyedAsync(string keyId, CancellationToken cancellationToken)
Parameters
keyIdstringThe key identifier, in the same form accepted by GetKeyAsync(string, CancellationToken).
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<bool>
true only when the backend holds no recoverable copy of the handle's material. false when the key is live, or deleted but still recoverable.
Remarks
The whole of what an implementation asserts by answering true is "I hold no recoverable copy of this handle." That is a statement about what the backend can serve or restore now. It is NOT a statement that the material was destroyed, and it is NOT a statement that this backend destroyed it -- a handle this backend never held answers true for the same reason a purged one does, and nothing here can separate the two.
Absence is never evidence of destruction. An implementation MUST NOT derive true from a lookup that merely failed to produce an answer -- a not-found response, a missing sidecar record, an absent marker, an empty cache entry. Those are states in which the question was not answered, and reporting them as "destroyed" manufactures an attestation out of a failure. The only legitimate basis for true is a backend statement that no recoverable copy remains.
An answer that cannot be obtained is thrown, never reported as either value, so a caller can never mistake "could not ask" for "destroyed" -- nor for "not destroyed", which would certify an erasure as incomplete on an outage.
ListKeysAsync(KeyStatus?, string?, CancellationToken)
Lists all keys matching the specified filter criteria.
public Task<IReadOnlyList<KeyMetadata>> ListKeysAsync(KeyStatus? status, string? purpose, CancellationToken cancellationToken)
Parameters
statusKeyStatus?Optional filter by key status. Null returns all statuses.
purposestringOptional filter by key purpose. Null returns all purposes.
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<IReadOnlyList<KeyMetadata>>
A list of key metadata matching the criteria.
ReactivateKeyAsync(string, CancellationToken)
Reactivates a previously suspended key, restoring its use for cryptographic operations.
public Task<bool> ReactivateKeyAsync(string keyId, CancellationToken cancellationToken)
Parameters
keyIdstringThe unique identifier of the key to reactivate.
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
Remarks
This is the inverse of SuspendKeyAsync(string, string, CancellationToken). A key that is not suspended is returned to (or left in) the active state.
ReplicateKeysAsync(string?, CancellationToken)
Replicates keys from the primary region to the secondary region.
public Task ReplicateKeysAsync(string? keyId, CancellationToken cancellationToken)
Parameters
keyIdstringOptional specific key to replicate. If null, replicates all keys.
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task
A task representing the asynchronous replication operation.
Remarks
Most cloud providers handle replication automatically. This method is primarily for manual replication scenarios or after key imports.
For providers with automatic replication (Azure KV Premium, AWS KMS MRKs), this may be a no-op or trigger an immediate sync.
RotateKeyAsync(string, EncryptionAlgorithm, string?, DateTimeOffset?, CancellationToken)
Creates a new encryption key or rotates an existing key to a new version.
public Task<KeyRotationResult> RotateKeyAsync(string keyId, EncryptionAlgorithm algorithm, string? purpose, DateTimeOffset? expiresAt, CancellationToken cancellationToken)
Parameters
keyIdstringThe unique identifier for the key. If the key exists, creates a new version.
algorithmEncryptionAlgorithmThe encryption algorithm for this key.
purposestringOptional purpose or scope for the key.
expiresAtDateTimeOffset?Optional expiration date for the key.
cancellationTokenCancellationTokenA token to cancel the operation.
Returns
- Task<KeyRotationResult>
The result of the rotation/creation operation.
SuspendKeyAsync(string, string, CancellationToken)
Suspends a key, preventing its use for any cryptographic operations.
public Task<bool> SuspendKeyAsync(string keyId, string reason, CancellationToken cancellationToken)
Parameters
keyIdstringThe unique identifier of the key to suspend.
reasonstringThe reason for suspension (for audit purposes).
cancellationTokenCancellationTokenA token to cancel the operation.