diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index ef0b61a7..939bd710 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,4 +1,4 @@ # These are supported funding model platforms github: [magiccodingman] -custom: ['https://sayou.biz/support', 'https://paypal.me/lancewr'] +custom: ['https://sayou.io/support', 'https://paypal.me/lancewr'] diff --git a/.github/workflows/validate-migrations.yml b/.github/workflows/validate-migrations.yml index 64f01f3a..f880ca76 100644 --- a/.github/workflows/validate-migrations.yml +++ b/.github/workflows/validate-migrations.yml @@ -36,7 +36,7 @@ jobs: node-version: 24 - name: Validate canonical JSON and portable document safety - run: node --test tests/migrations/protocol.test.mjs tests/migrations/protected-protocol.test.mjs tests/migrations/protected-adapter.test.mjs tests/migrations/registration.test.mjs + run: node --test tests/migrations/protocol.test.mjs tests/migrations/protected-protocol.test.mjs tests/migrations/protected-adapter.test.mjs tests/migrations/registration.test.mjs tests/migrations/rotation-record.test.mjs tests/migrations/rotation-journal.test.mjs packaged-cli: name: Packaged CLI contract diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6a9429cc..34ae9cb8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,6 +18,10 @@ You can contribute by: Contributions of all sizes are appreciated. +## Domain neutrality + +Keep implementation, APIs, tests, fixtures, benchmarks, and developer documentation domain-neutral. Use fictional data in examples and avoid application-specific workflows, private infrastructure, and internal endpoints. Preserve authentic compatibility fixtures, applicable notices, and intentional project licensing, funding, and attribution references. + ## Development philosophy Magic IndexedDB aims to provide a reliable, intuitive, strongly typed, and production-oriented experience for developers working with browser-based databases. @@ -70,7 +74,7 @@ If you discover a potential security vulnerability, please use the project's pri Avoid publicly disclosing sensitive vulnerability details before the maintainers have had an opportunity to investigate and respond. -Do not include confidential information, production credentials, patient records, or other sensitive data in public issues or pull requests. +Do not include confidential information, production credentials, or other sensitive data in public issues or pull requests. ## Community conduct diff --git a/Magic.IndexedDb.UnitTests/ProtectedMigrationFactoryTests.cs b/Magic.IndexedDb.UnitTests/ProtectedMigrationFactoryTests.cs index dfebe732..49c0eb1e 100644 --- a/Magic.IndexedDb.UnitTests/ProtectedMigrationFactoryTests.cs +++ b/Magic.IndexedDb.UnitTests/ProtectedMigrationFactoryTests.cs @@ -29,7 +29,7 @@ public async Task AuthorizationPrecedesManagedInitialization() public async Task LockCanRevokeAuthorizationWhileMigrationIsWaiting() { var browser = new Browser { HoldMigration = true }; - await using var factory = Create(browser, new()); + await using var factory = Create(browser, new Provider()); var unlocking = factory.UnlockDetailedAsync(Repository.Database); await browser.MigrationStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); @@ -41,11 +41,50 @@ public async Task LockCanRevokeAuthorizationWhileMigrationIsWaiting() Assert.IsTrue(browser.Calls.Contains("lockProtectedDatabase")); } + [TestMethod] + public async Task LockReachesBrowserBeforePendingRotationAuthorizationCompletes() + { + var browser = new Browser { HoldRotationAuthorization = true }; + await using var factory = Create(browser, new RotationProvider()); + var unlocking = factory.UnlockDetailedAsync(Repository.Database); + await browser.RotationStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + try + { + await factory.LockAsync(Repository.Database).WaitAsync(TimeSpan.FromSeconds(5)); + Assert.IsTrue(browser.Calls.Contains("lockProtectedDatabase")); + Assert.IsFalse(browser.RotationFinished.Task.IsCompleted); + } + finally + { + browser.RotationFinished.TrySetResult(); + } + + Assert.AreEqual(MagicUnlockResult.Cancelled, await unlocking.WaitAsync(TimeSpan.FromSeconds(5))); + Assert.IsFalse(browser.Calls.Contains("ensureProtectedMigration")); + Assert.IsFalse(browser.Calls.Contains("scheduleManagedKeyRotationResume")); + } + + [TestMethod] + public async Task ReadyRotationStatusReportsOrdinaryReadAndWriteAvailability() + { + var browser = new Browser(); + await using var factory = Create(browser, new Provider()); + Assert.IsTrue(await factory.EnsureUnlockedAsync(Repository.Database)); + + var status = await factory.GetKeyRotationStatusAsync(Repository.Database); + + Assert.AreEqual(MagicKeyRotationPhase.NotStarted, status.Phase); + Assert.IsTrue(status.ReadsAllowed); + Assert.IsTrue(status.WritesAllowed); + Assert.IsFalse(status.RetirementReady); + } + [TestMethod] public async Task ExplicitBrowserCancellationReportsCancelled() { var browser = new Browser { MigrationDiagnostic = "MAGDB_CANCELLED: Migration was cancelled." }; - await using var factory = Create(browser, new()); + await using var factory = Create(browser, new Provider()); Assert.AreEqual(MagicUnlockResult.Cancelled, await factory.UnlockDetailedAsync(Repository.Database)); } @@ -72,7 +111,7 @@ public async Task RecoveryAuthorizesWithoutRetryingTheFailedOriginalMigration() public async Task UnavailableAuthorizationDoesNotStartRecovery() { var browser = new Browser(); - await using var factory = Create(browser, new() { Available = false }); + await using var factory = Create(browser, new Provider { Available = false }); var database = await factory.Database(Repository.Database); var error = await Assert.ThrowsExactlyAsync(() => @@ -87,7 +126,7 @@ public async Task UnavailableAuthorizationDoesNotStartRecovery() public async Task ExplicitPhysicalBindingIsRetainedAndDestroyCarriesItsRegisteredRoute() { var browser = new Browser(); - await using var factory = Create(browser, new(), "existing-browser-records"); + await using var factory = Create(browser, new Provider(), "existing-browser-records"); Assert.IsTrue(await factory.EnsureUnlockedAsync(Repository.Database)); var registered = browser.Registration!.Value; Assert.AreEqual("existing-browser-records", registered.GetProperty("encryption").GetProperty("physicalName").GetString()); @@ -100,12 +139,12 @@ public async Task ExplicitPhysicalBindingIsRetainedAndDestroyCarriesItsRegistere Assert.AreEqual(registered.GetProperty("name").GetString(), browser.DestroyedRoute); } - private static MagicDbFactory Create(Browser browser, Provider provider, string? physicalName = null) => new(browser, 1024, false, + private static MagicDbFactory Create(Browser browser, IMagicEncryptionKeyProvider provider, string? physicalName = null) => new(browser, 1024, false, tableTypes: [typeof(Row)], repositoryTypes: [typeof(Repository)], encryption: new Dictionary { [Repository.Database.DatabaseName] = new(new MagicEncryptionOptions(Repository.Database.DatabaseName, "account", "key") - { PhysicalDatabaseName = physicalName }) + { PhysicalDatabaseName = physicalName, ResumeKeyRotationOnUnlock = true }) }, keyProvider: provider); private sealed class Provider : IMagicEncryptionKeyProvider @@ -119,6 +158,15 @@ private sealed class Provider : IMagicEncryptionKeyProvider } } + private sealed class RotationProvider : IMagicEncryptionRotationKeyProvider + { + public ValueTask GetKeyAsync(MagicEncryptionKeyRequest request, CancellationToken cancellationToken) => + ValueTask.FromResult(MagicEncryptionKey.FromBytes(new byte[32])); + + public ValueTask CanReacquireKeysAsync(MagicEncryptionKeyRequest source, MagicEncryptionKeyRequest target, + CancellationToken cancellationToken) => ValueTask.FromResult(true); + } + private sealed class Browser : IJSRuntime, IJSObjectReference { public List Calls { get; } = []; @@ -128,6 +176,9 @@ private sealed class Browser : IJSRuntime, IJSObjectReference public string? DestroyedPhysicalName { get; private set; } public string? DestroyedRoute { get; private set; } public bool HoldMigration { get; init; } + public bool HoldRotationAuthorization { get; init; } + public TaskCompletionSource RotationStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource RotationFinished { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public string? MigrationDiagnostic { get; init; } public TaskCompletionSource MigrationStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); private TaskCompletionSource MigrationFinished { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -151,6 +202,16 @@ public ValueTask InvokeAsync(string identifier, CancellationToken cancella DestroyedPhysicalName = (string)parameters[0]!; DestroyedRoute = (string?)parameters[1]; } + if (method == "getManagedKeyRotationStatus") + return ValueTask.FromResult((T)(object)JsonSerializer.SerializeToElement(new + { phase = "not-started", readsAllowed = true, writesAllowed = true, retirementReady = false })); + if (method == "getManagedEncryptionKeyHints") + return ValueTask.FromResult((T)(object)JsonSerializer.SerializeToElement(new { keyId = "key", targetKeyId = "next" })); + if (method == "authorizeManagedKeyRotation" && HoldRotationAuthorization) + { + RotationStarted.TrySetResult(); + return WaitForRotation(); + } return ValueTask.FromResult((T)(object)(method != "isProtectedDatabaseUnlocked")); } Calls.Add(identifier); @@ -170,6 +231,7 @@ public ValueTask InvokeAsync(string identifier, CancellationToken cancella } private async ValueTask WaitForMigration() { await MigrationFinished.Task; return default!; } + private async ValueTask WaitForRotation() { await RotationFinished.Task; return default!; } public ValueTask DisposeAsync() => ValueTask.CompletedTask; } diff --git a/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt b/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt index 3c764c67..fe64434f 100644 --- a/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt +++ b/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt @@ -121,6 +121,8 @@ interface Magic.IndexedDb.IMagicEncryptionContexts method System.Threading.Tasks.Task ActivateAsync(System.Collections.Generic.IEnumerable databases) interface Magic.IndexedDb.IMagicEncryptionKeyProvider method System.Threading.Tasks.ValueTask GetKeyAsync(Magic.IndexedDb.MagicEncryptionKeyRequest request, System.Threading.CancellationToken cancellationToken) +interface Magic.IndexedDb.IMagicEncryptionRotationKeyProvider : Magic.IndexedDb.IMagicEncryptionKeyProvider + method System.Threading.Tasks.ValueTask CanReacquireKeysAsync(Magic.IndexedDb.MagicEncryptionKeyRequest source, Magic.IndexedDb.MagicEncryptionKeyRequest target, System.Threading.CancellationToken cancellationToken) interface Magic.IndexedDb.IMagicExecute method System.Collections.Generic.IAsyncEnumerable AsAsyncEnumerable(System.Threading.CancellationToken cancellationToken = null) method System.Threading.Tasks.Task> ToListAsync() @@ -138,6 +140,12 @@ interface Magic.IndexedDb.IMagicIndexedDbEncryption interface Magic.IndexedDb.IMagicIndexedDbEncryptionLifecycle : Magic.IndexedDb.IMagicIndexedDbEncryption method System.Threading.Tasks.Task GetStateAsync(Magic.IndexedDb.IndexedDbSet database, System.Threading.CancellationToken cancellationToken = null) method System.Threading.Tasks.Task UnlockDetailedAsync(Magic.IndexedDb.IndexedDbSet database, System.Boolean initialize = false, System.Threading.CancellationToken cancellationToken = null) +interface Magic.IndexedDb.IMagicIndexedDbKeyRotation + method System.Threading.Tasks.Task CancelKeyRotationAsync(Magic.IndexedDb.IndexedDbSet database) + method System.Threading.Tasks.Task GetKeyRotationStatusAsync(Magic.IndexedDb.IndexedDbSet database, System.Threading.CancellationToken cancellationToken = null) + method System.Threading.Tasks.Task PauseKeyRotationAsync(Magic.IndexedDb.IndexedDbSet database, System.Threading.CancellationToken cancellationToken = null) + method System.Threading.Tasks.Task ResumeKeyRotationAsync(Magic.IndexedDb.IndexedDbSet database, System.Int32 batchSize = 128, System.Threading.CancellationToken cancellationToken = null) + method System.Threading.Tasks.Task RotateEncryptionKeyAsync(Magic.IndexedDb.IndexedDbSet database, Magic.IndexedDb.MagicKeyRotationOptions options, System.Threading.CancellationToken cancellationToken = null) interface Magic.IndexedDb.IMagicQuery : Magic.IndexedDb.IMagicExecute method Magic.IndexedDb.IMagicCursor Cursor(System.Linq.Expressions.Expression> predicate) method Magic.IndexedDb.IMagicQueryFinal Skip(System.Int32 amount) @@ -252,6 +260,7 @@ class Magic.IndexedDb.MagicEncryptionContext : System.IEquatable> RecordPolicies) + property System.Boolean ResumeKeyRotationOnUnlock { get; set; } property System.Collections.Generic.IReadOnlyDictionary> RecordPolicies { get; set; } property System.String AccountScope { get; set; } property System.String DatabaseName { get; set; } @@ -289,6 +299,49 @@ enum Magic.IndexedDb.MagicEncryptionState : System.IComparable, System.IConverti field static Magic.IndexedDb.MagicEncryptionState PolicyMismatch = 3 field static Magic.IndexedDb.MagicEncryptionState Uninitialized = 0 field static Magic.IndexedDb.MagicEncryptionState Unlocked = 2 +enum Magic.IndexedDb.MagicKeyRotationMode : System.IComparable, System.IConvertible, System.IFormattable, System.ISpanFormattable + field System.Int32 value__ + field static Magic.IndexedDb.MagicKeyRotationMode Exclusive = 0 + field static Magic.IndexedDb.MagicKeyRotationMode Online = 2 + field static Magic.IndexedDb.MagicKeyRotationMode ReadOnly = 1 +class Magic.IndexedDb.MagicKeyRotationOptions : System.IEquatable + ctor Magic.IndexedDb.MagicKeyRotationOptions(System.String TargetKeyId, Magic.IndexedDb.MagicKeyRotationMode Mode = Exclusive, System.Int32 BatchSize = 128, System.Boolean YieldBetweenBatches = false) + method Magic.IndexedDb.MagicKeyRotationOptions $() + method System.Boolean Equals(Magic.IndexedDb.MagicKeyRotationOptions other) + method System.Boolean Equals(System.Object obj) + method System.Int32 GetHashCode() + method System.String ToString() + method System.Void Deconstruct(out System.String TargetKeyId, out Magic.IndexedDb.MagicKeyRotationMode Mode, out System.Int32 BatchSize, out System.Boolean YieldBetweenBatches) + property Magic.IndexedDb.MagicKeyRotationMode Mode { get; set; } + property System.Boolean YieldBetweenBatches { get; set; } + property System.Int32 BatchSize { get; set; } + property System.String TargetKeyId { get; set; } +enum Magic.IndexedDb.MagicKeyRotationPhase : System.IComparable, System.IConvertible, System.IFormattable, System.ISpanFormattable + field System.Int32 value__ + field static Magic.IndexedDb.MagicKeyRotationPhase AuthorizationRequired = 1 + field static Magic.IndexedDb.MagicKeyRotationPhase Completed = 4 + field static Magic.IndexedDb.MagicKeyRotationPhase Converting = 2 + field static Magic.IndexedDb.MagicKeyRotationPhase NotStarted = 0 + field static Magic.IndexedDb.MagicKeyRotationPhase Verifying = 3 +class Magic.IndexedDb.MagicKeyRotationStatus : System.IEquatable + ctor Magic.IndexedDb.MagicKeyRotationStatus(Magic.IndexedDb.MagicKeyRotationPhase Phase, System.String RotationId, System.String SourceKeyId, System.String TargetKeyId, System.Nullable Mode, System.Boolean Paused, System.Int64 Converted, System.Int64 Verified, System.Boolean ReadsAllowed, System.Boolean WritesAllowed, System.Boolean RetirementReady) + method Magic.IndexedDb.MagicKeyRotationStatus $() + method System.Boolean Equals(Magic.IndexedDb.MagicKeyRotationStatus other) + method System.Boolean Equals(System.Object obj) + method System.Int32 GetHashCode() + method System.String ToString() + method System.Void Deconstruct(out Magic.IndexedDb.MagicKeyRotationPhase Phase, out System.String RotationId, out System.String SourceKeyId, out System.String TargetKeyId, out System.Nullable Mode, out System.Boolean Paused, out System.Int64 Converted, out System.Int64 Verified, out System.Boolean ReadsAllowed, out System.Boolean WritesAllowed, out System.Boolean RetirementReady) + property Magic.IndexedDb.MagicKeyRotationPhase Phase { get; set; } + property System.Boolean Paused { get; set; } + property System.Boolean ReadsAllowed { get; set; } + property System.Boolean RetirementReady { get; set; } + property System.Boolean WritesAllowed { get; set; } + property System.Int64 Converted { get; set; } + property System.Int64 Verified { get; set; } + property System.Nullable Mode { get; set; } + property System.String RotationId { get; set; } + property System.String SourceKeyId { get; set; } + property System.String TargetKeyId { get; set; } enum Magic.IndexedDb.MagicNumericStorageMode : System.IComparable, System.IConvertible, System.IFormattable, System.ISpanFormattable field System.Int32 value__ field static Magic.IndexedDb.MagicNumericStorageMode Legacy = 0 diff --git a/Magic.IndexedDb/Encryption/EncryptionConfiguration.cs b/Magic.IndexedDb/Encryption/EncryptionConfiguration.cs index ea7859e0..df41290e 100644 --- a/Magic.IndexedDb/Encryption/EncryptionConfiguration.cs +++ b/Magic.IndexedDb/Encryption/EncryptionConfiguration.cs @@ -17,6 +17,7 @@ internal sealed class EncryptionConfiguration public MagicEncryptionKeyRequest Request { get; } public string PhysicalName { get; } public string Route { get; } + internal bool ResumeKeyRotationOnUnlock => _options.ResumeKeyRotationOnUnlock; internal bool HasExplicitPhysicalBinding => _options.PhysicalDatabaseName is not null; internal IReadOnlyDictionary> RecordPolicies => _recordPolicies.ToDictionary(pair => pair.Key, pair => (IReadOnlyCollection)pair.Value, StringComparer.Ordinal); diff --git a/Magic.IndexedDb/Encryption/EncryptionUnlock.cs b/Magic.IndexedDb/Encryption/EncryptionUnlock.cs index 5583f612..71ba9871 100644 --- a/Magic.IndexedDb/Encryption/EncryptionUnlock.cs +++ b/Magic.IndexedDb/Encryption/EncryptionUnlock.cs @@ -1,4 +1,5 @@ using System.Security.Cryptography; +using System.Text.Json; using Microsoft.JSInterop; namespace Magic.IndexedDb; @@ -67,39 +68,83 @@ private async Task RunUnlockAsync(Func> getModule, bool await previousLock; token.ThrowIfCancellationRequested(); var module = await getModule().WaitAsync(token); - if (await InvokeAsync(module, "isProtectedDatabaseUnlocked", false, configuration.Route)) + if (await InvokeAsync(module, "isProtectedDatabaseUnlocked", false, configuration.Route, + provider is IMagicEncryptionRotationKeyProvider)) { token.ThrowIfCancellationRequested(); attempt.Result.TrySetResult(MagicUnlockResult.AlreadyUnlocked); return; } - var key = await provider.GetKeyAsync(configuration.Request, token); - await _browser.WaitAsync(token); - try + var request = configuration.Request; + string? targetId = null; + if (!initialize && provider is IMagicEncryptionRotationKeyProvider) { - token.ThrowIfCancellationRequested(); - if (key is not null) + var hints = await InvokeAsync(module, "getManagedEncryptionKeyHints", false, configuration.Route); + if (hints.ValueKind == JsonValueKind.Object) + { + if (hints.TryGetProperty("keyId", out var keyId) && keyId.GetString() is { Length: > 0 } active) + request = request with { KeyId = active }; + if (hints.TryGetProperty("targetKeyId", out var target) && target.GetString() is { Length: > 0 } id) + targetId = id; + } + } + var key = await provider.GetKeyAsync(request, token); + var targetKey = key is not null && targetId is not null + ? await provider.GetKeyAsync(request with { KeyId = targetId }, token) : null; + var available = key is not null && (targetId is null || targetKey is not null); + if (available) + { + var temporary = (key!.Material as byte[])?.ToArray(); + var temporaryTarget = (targetKey?.Material as byte[])?.ToArray(); + try { - var temporary = (key.Material as byte[])?.ToArray(); + await _browser.WaitAsync(token); + ValueTask rotation = default; try { - await InvokeAsync(module, "unlockProtectedDatabase", true, - configuration.Route, configuration.Request.KeyId, temporary ?? key.Material, initialize); + token.ThrowIfCancellationRequested(); + if (targetKey is null) + await InvokeAsync(module, "unlockProtectedDatabase", true, + configuration.Route, request.KeyId, temporary ?? key.Material, initialize); + else + rotation = InvokeAsync(module, "authorizeManagedKeyRotation", false, + configuration.Route, request.KeyId, temporary ?? key.Material, + targetId, temporaryTarget ?? targetKey.Material); } finally { - if (temporary is not null) CryptographicOperations.ZeroMemory(temporary); + _browser.Release(); } - } - token.ThrowIfCancellationRequested(); - attempt.Result.TrySetResult(key is null ? MagicUnlockResult.KeyUnavailable : MagicUnlockResult.Unlocked); - } - finally - { - _browser.Release(); + if (targetKey is not null) + { + // The invocation has started. Its browser authorization can now + // be revoked while deployment validation is still awaiting I/O. + await rotation; + if (configuration.ResumeKeyRotationOnUnlock) + { + await _browser.WaitAsync(token); + try + { + token.ThrowIfCancellationRequested(); + await InvokeAsync(module, "scheduleManagedKeyRotationResume", true, configuration.Route); + } + finally + { + _browser.Release(); + } + } + } + } + finally + { + if (temporary is not null) CryptographicOperations.ZeroMemory(temporary); + if (temporaryTarget is not null) CryptographicOperations.ZeroMemory(temporaryTarget); + } } + token.ThrowIfCancellationRequested(); + attempt.Result.TrySetResult(available ? MagicUnlockResult.Unlocked : MagicUnlockResult.KeyUnavailable); } catch (OperationCanceledException) when (token.IsCancellationRequested) { diff --git a/Magic.IndexedDb/Encryption/MagicEncryptionContext.cs b/Magic.IndexedDb/Encryption/MagicEncryptionContext.cs index f0476715..9c6299fa 100644 --- a/Magic.IndexedDb/Encryption/MagicEncryptionContext.cs +++ b/Magic.IndexedDb/Encryption/MagicEncryptionContext.cs @@ -3,7 +3,11 @@ namespace Magic.IndexedDb; /// An account-bound view of the database and encryption APIs. -public sealed record MagicEncryptionContext(IMagicIndexedDb Database, IMagicIndexedDbEncryptionLifecycle Encryption); +public sealed record MagicEncryptionContext(IMagicIndexedDb Database, IMagicIndexedDbEncryptionLifecycle Encryption) +{ + public IMagicIndexedDbKeyRotation KeyRotation => Encryption as IMagicIndexedDbKeyRotation + ?? throw new InvalidOperationException("This encryption context does not support key rotation."); +} /// Manages protected account contexts within an existing service scope. public interface IMagicEncryptionContexts diff --git a/Magic.IndexedDb/Encryption/MagicEncryptionOptions.cs b/Magic.IndexedDb/Encryption/MagicEncryptionOptions.cs index de4243e1..bcc13f99 100644 --- a/Magic.IndexedDb/Encryption/MagicEncryptionOptions.cs +++ b/Magic.IndexedDb/Encryption/MagicEncryptionOptions.cs @@ -15,6 +15,9 @@ public sealed record MagicEncryptionOptions( /// Use a reviewed migration history/baseline and retire older writers before enrollment. /// Retain this binding after enrollment, including when every record field becomes public again. public string? PhysicalDatabaseName { get; init; } + + /// Resume an interrupted rotation after both keys are authorized. A durable pause is respected. + public bool ResumeKeyRotationOnUnlock { get; init; } } public sealed record MagicEncryptionKeyRequest(string DatabaseName, string AccountScope, string KeyId); diff --git a/Magic.IndexedDb/Encryption/MagicKeyRotation.cs b/Magic.IndexedDb/Encryption/MagicKeyRotation.cs new file mode 100644 index 00000000..52c1722e --- /dev/null +++ b/Magic.IndexedDb/Encryption/MagicKeyRotation.cs @@ -0,0 +1,62 @@ +namespace Magic.IndexedDb; + +public enum MagicKeyRotationMode +{ + Exclusive, + ReadOnly, + Online +} + +/// Controls availability and the bounded browser work per batch. +public sealed record MagicKeyRotationOptions( + string TargetKeyId, + MagicKeyRotationMode Mode = MagicKeyRotationMode.Exclusive, + int BatchSize = 128, + bool YieldBetweenBatches = false); + +public enum MagicKeyRotationPhase +{ + NotStarted, + AuthorizationRequired, + Converting, + Verifying, + Completed +} + +/// Rotation metadata. Counts reflect only committed work. +public sealed record MagicKeyRotationStatus( + MagicKeyRotationPhase Phase, + string? RotationId, + string? SourceKeyId, + string? TargetKeyId, + MagicKeyRotationMode? Mode, + bool Paused, + long Converted, + long Verified, + bool ReadsAllowed, + bool WritesAllowed, + bool RetirementReady); + +/// Opt in to dynamic generation lookup and attest restart recovery of both keys. +public interface IMagicEncryptionRotationKeyProvider : IMagicEncryptionKeyProvider +{ + /// + /// Confirms the application can recover both keys after interruption. + /// The browser can authenticate supplied keys but cannot verify future provider access. + /// + ValueTask CanReacquireKeysAsync(MagicEncryptionKeyRequest source, MagicEncryptionKeyRequest target, + CancellationToken cancellationToken); +} + +/// Controls rotation for an authorized managed database. +public interface IMagicIndexedDbKeyRotation +{ + Task RotateEncryptionKeyAsync(IndexedDbSet database, MagicKeyRotationOptions options, + CancellationToken cancellationToken = default); + Task ResumeKeyRotationAsync(IndexedDbSet database, int batchSize = 128, + CancellationToken cancellationToken = default); + Task GetKeyRotationStatusAsync(IndexedDbSet database, + CancellationToken cancellationToken = default); + Task PauseKeyRotationAsync(IndexedDbSet database, CancellationToken cancellationToken = default); + Task CancelKeyRotationAsync(IndexedDbSet database); +} diff --git a/Magic.IndexedDb/Factories/MagicDbFactory.cs b/Magic.IndexedDb/Factories/MagicDbFactory.cs index fd39294d..80066e9f 100644 --- a/Magic.IndexedDb/Factories/MagicDbFactory.cs +++ b/Magic.IndexedDb/Factories/MagicDbFactory.cs @@ -7,12 +7,13 @@ using Magic.IndexedDb.LinqTranslation.Models; using Magic.IndexedDb.Migrations; using System.Collections.Concurrent; +using System.Security.Cryptography; using System.Text.Json; using System.Text.Json.Nodes; namespace Magic.IndexedDb.Factories; -internal class MagicDbFactory : IMagicIndexedDb, IMagicIndexedDbEncryptionLifecycle, IAsyncDisposable +internal class MagicDbFactory : IMagicIndexedDb, IMagicIndexedDbEncryptionLifecycle, IMagicIndexedDbKeyRotation, IAsyncDisposable { // null value indicates that the factory is disposed Lazy>? _jsModule; @@ -458,6 +459,132 @@ public Task LockAsync(IndexedDbSet database) return GetUnlock(database).LockAsync(() => js.Value); } + public async Task RotateEncryptionKeyAsync(IndexedDbSet database, + MagicKeyRotationOptions options, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentException.ThrowIfNullOrWhiteSpace(options.TargetKeyId); + if (_keyProvider is not IMagicEncryptionRotationKeyProvider provider) + throw new InvalidOperationException("The application must provide a rotation-capable encryption key provider."); + if (!await EnsureUnlockedAsync(database, cancellationToken)) + throw new InvalidOperationException("Unlock the managed vault before starting key rotation."); + + var configuration = _encryption[database.DatabaseName]; + var module = await RotationModuleAsync(database, cancellationToken); + var admission = await EncryptionUnlock.InvokeAsync(module, "getManagedRotationAdmission", false, + configuration.Route); + var source = configuration.Request with { KeyId = admission.GetProperty("keyId").GetString()! }; + var target = source with { KeyId = options.TargetKeyId }; + if (!await provider.CanReacquireKeysAsync(source, target, cancellationToken)) + throw new InvalidOperationException("The provider could not attest that both keys can be reacquired."); + var key = await provider.GetKeyAsync(target, cancellationToken) + ?? throw new InvalidOperationException("The provider did not supply the target key."); + cancellationToken.ThrowIfCancellationRequested(); + var payload = new Dictionary + { + ["targetKeyId"] = options.TargetKeyId, + ["mode"] = options.Mode switch + { + MagicKeyRotationMode.Exclusive => "exclusive", + MagicKeyRotationMode.ReadOnly => "read-only", + MagicKeyRotationMode.Online => "online", + _ => throw new ArgumentOutOfRangeException(nameof(options)) + }, + ["batchSize"] = options.BatchSize, + ["yieldBetweenBatches"] = options.YieldBetweenBatches, + ["recoverable"] = true, + ["authorizationId"] = admission.GetProperty("authorizationId").GetString() + }; + return await StartRotationAsync(module, configuration.Route, payload, key).WaitAsync(cancellationToken); + } + + private static async Task StartRotationAsync(IJSObjectReference module, string route, + Dictionary options, MagicEncryptionKey key) + { + var temporary = (key.Material as byte[])?.ToArray(); + try + { + return ReadRotationStatus(await EncryptionUnlock.InvokeAsync(module, + "rotateManagedEncryptionKey", false, route, options, temporary ?? key.Material)); + } + finally + { + if (temporary is not null) CryptographicOperations.ZeroMemory(temporary); + } + } + + public async Task ResumeKeyRotationAsync(IndexedDbSet database, int batchSize = 128, + CancellationToken cancellationToken = default) + { + if (!await EnsureUnlockedAsync(database, cancellationToken)) + throw new InvalidOperationException("Both rotation keys must be authorized before resuming."); + return await RotationStatusAsync(database, "resumeManagedEncryptionKeyRotation", cancellationToken, + new Dictionary { ["batchSize"] = batchSize }); + } + + public Task PauseKeyRotationAsync(IndexedDbSet database, + CancellationToken cancellationToken = default) => + RotationStatusAsync(database, "pauseManagedEncryptionKeyRotation", cancellationToken); + + public Task GetKeyRotationStatusAsync(IndexedDbSet database, + CancellationToken cancellationToken = default) => + RotationStatusAsync(database, "getManagedKeyRotationStatus", cancellationToken); + + public async Task CancelKeyRotationAsync(IndexedDbSet database) + { + var module = await RotationModuleAsync(database, CancellationToken.None); + await EncryptionUnlock.InvokeAsync(module, "cancelManagedEncryptionKeyRotation", true, + _encryption[database.DatabaseName].Route); + } + + private async Task RotationModuleAsync(IndexedDbSet database, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(database); + var js = _jsModule; + ObjectDisposedException.ThrowIf(js is null || _lifetime.IsCancellationRequested, this); + if (!_encryption.ContainsKey(database.DatabaseName)) + throw new InvalidOperationException("This database does not have a Magic encryption policy."); + var module = await js.Value.WaitAsync(cancellationToken); + await RegisterDatabaseAsync(Definition(database.DatabaseName), database.DatabaseName).WaitAsync(cancellationToken); + return module; + } + + private async Task RotationStatusAsync(IndexedDbSet database, string method, + CancellationToken cancellationToken, Dictionary? options = null) + { + var module = await RotationModuleAsync(database, cancellationToken); + var route = _encryption[database.DatabaseName].Route; + var pending = options is null + ? EncryptionUnlock.InvokeAsync(module, method, false, route) + : EncryptionUnlock.InvokeAsync(module, method, false, route, options); + return ReadRotationStatus(await pending.AsTask().WaitAsync(cancellationToken)); + } + + private static MagicKeyRotationStatus ReadRotationStatus(JsonElement json) + { + string? String(string field) => json.TryGetProperty(field, out var value) ? value.GetString() : null; + long Count(string field) => json.TryGetProperty(field, out var value) ? value.GetInt64() : 0; + bool Flag(string field) => json.TryGetProperty(field, out var value) && value.GetBoolean(); + var phase = String("phase") switch + { + "not-started" => MagicKeyRotationPhase.NotStarted, + "authorization-required" => MagicKeyRotationPhase.AuthorizationRequired, + "converting" => MagicKeyRotationPhase.Converting, + "verifying" => MagicKeyRotationPhase.Verifying, + "completed" => MagicKeyRotationPhase.Completed, + _ => throw new InvalidOperationException("The browser returned an unknown rotation phase.") + }; + MagicKeyRotationMode? mode = String("mode") switch + { + "exclusive" => MagicKeyRotationMode.Exclusive, + "read-only" => MagicKeyRotationMode.ReadOnly, + "online" => MagicKeyRotationMode.Online, + _ => null + }; + return new(phase, String("rotationId"), String("sourceKeyId"), String("targetKeyId"), mode, Flag("paused"), + Count("converted"), Count("verified"), Flag("readsAllowed"), Flag("writesAllowed"), Flag("retirementReady")); + } + private EncryptionUnlock GetUnlock(IndexedDbSet database) { ArgumentNullException.ThrowIfNull(database); diff --git a/Magic.IndexedDb/wwwroot/magicDB.js b/Magic.IndexedDb/wwwroot/magicDB.js index d5bbb34f..2ebc6d4f 100644 --- a/Magic.IndexedDb/wwwroot/magicDB.js +++ b/Magic.IndexedDb/wwwroot/magicDB.js @@ -14,6 +14,12 @@ import { import { debugLog } from "./utilities/utilityHelpers.js"; import { recoverDatabase, ensureDatabase, assertDatabaseReady, inspectDatabase, subscribeMigrationEvents, MigrationError } from "./migrations/migrationEngine.js"; import { canonicalJson, metadataStore } from "./migrations/protocol.js"; +import { inspectKeyRoutingHints, notifyManagedLifecycle, verifyRotationDeployment } from "./migrations/migrationEngine.js"; +import { portableProtectionPolicy } from "./utilities/protectionPolicy.js"; +import { advanceRotationPass } from "./utilities/rotationPass.js"; +import { rotationJournalKey } from "./utilities/rotationJournal.js"; +import { admitRotation, enterRotationVerification, finishRotation, openRotation, rotationCoordinator, + setRotationPaused } from "./utilities/rotationLifecycle.js"; /** * @typedef {Object} DatabasesItem * @property {string} name @@ -62,9 +68,9 @@ function requireMigrationAuthorization(registration) { async function authorizeProtectedMigration(registration, keyId, input, initialize) { if (registration.pending && registration.authorization?.adapter && !registration.authorization.controller.signal.aborted) - return; // Concurrent callers share the active authorization and attempt. + return registration.authorization; // Concurrent callers share the active authorization and attempt. registration.authorization?.controller.abort(); - const authorization = { controller: new AbortController(), adapter: null, key: null, keyId, initialize }; + const authorization = { controller: new AbortController(), adapter: null, key: null, keyId, initialize, id: crypto.randomUUID() }; authorization.assertCurrent = () => { if (registration.stale || registration.authorization !== authorization || authorization.controller.signal.aborted) throw new MigrationError("MAGDB_AUTHORIZATION_LOST", "The migration authorization was revoked. Unlock again to resume.", {}, true); @@ -84,6 +90,7 @@ async function authorizeProtectedMigration(registration, keyId, input, initializ account: registration.account, keyId, key, signal: authorization.controller.signal, assertCurrent: authorization.assertCurrent }); authorization.assertCurrent(); + return authorization; } catch (error) { authorization.controller.abort(); authorization.key = null; @@ -92,9 +99,20 @@ async function authorizeProtectedMigration(registration, keyId, input, initializ } } +async function publishProtectedReadiness(registration, result, authorization) { + await assertDatabaseReady(registration.db.backendDB(), result, authorization.adapter); + registration.protection.setManagedReadiness(result); + await registration.protection.unlock(authorization.keyId, authorization.key, false); + authorization.assertCurrent(); + registration.result = result; +} + export async function ensureProtectedMigration(name) { const registration = managedDatabases.get(name); if (!registration?.protected) return; + // Finalization has committed but the target session may still be opening. + if (registration.rotationTask && !registration.rotation && !registration.result) + await registration.rotationTask; return runProtectedMigration(registration); } @@ -102,6 +120,11 @@ async function runProtectedMigration(registration, recovery) { if (registration.stale) throw new MigrationError("MAGDB_DATABASE_INCOMPATIBLE", "This account's database changed in another application. Reload before continuing."); const authorization = requireMigrationAuthorization(registration); + if (registration.rotation) { + if (recovery) throw new Error("MAGIC_ROTATION_IN_PROGRESS: Complete key rotation before migration recovery."); + await registration.protection.assertRotationReadiness(); + return registration.result; + } if (registration.pending) { if (recovery) throw new MigrationError("MAGDB_RECOVERY_IN_PROGRESS", "This connection already has an authenticated migration attempt."); return registration.pending; @@ -133,11 +156,7 @@ async function runProtectedMigration(registration, recovery) { const result = await ensureDatabase(options); authorization.assertCurrent(); await registration.db.open(); - await assertDatabaseReady(registration.db.backendDB(), result, authorization.adapter); - registration.protection.setManagedReadiness(result); - await registration.protection.unlock(authorization.keyId, authorization.key, false); - authorization.assertCurrent(); - registration.result = result; + await publishProtectedReadiness(registration, result, authorization); return result; } catch (error) { registration.result = null; @@ -273,12 +292,288 @@ export function unlockProtectedDatabase(name, keyId, key, initialize = false) { const storage = protectedDatabases.get(name); if (!storage) throw new Error("The database does not have a Magic encryption policy."); const managed = managedDatabases.get(name); - if (managed?.protected) return authorizeProtectedMigration(managed, keyId, key, initialize); + if (managed?.protected) return authorizeProtectedMigration(managed, keyId, key, initialize).then(() => undefined); return storage.unlock(keyId, key, initialize); } -export function isProtectedDatabaseUnlocked(name) { - return protectedDatabases.get(name)?.isUnlocked() ?? false; +function managedRotationRegistration(name) { + const registration = managedDatabases.get(name); + if (!registration?.protected || registration.stale) + throw new Error("MAGIC_ROTATION_MANAGED_REQUIRED: Key rotation requires a managed protected vault."); + return registration; +} + +async function rotationKey(input) { + const key = input instanceof Uint8Array ? await importEncryptionKey(input) : input; + assertEncryptionKey(key); + return key; +} + +function rotationContext(registration, keys, signal) { + const authorization = requireMigrationAuthorization(registration); + return { db: registration.db.backendDB(), vault: { database: registration.db.name, account: registration.account }, + schema: registration.schema, ready: registration.result, authorization: authorization.adapter, + keys, assertCurrent: authorization.assertCurrent, authorizationSignal: authorization.controller.signal, signal }; +} + +const rotationListeners = new Set(); + +export function subscribeKeyRotationEvents(listener) { + if (typeof listener !== "function") throw new TypeError("A rotation observer must be a function."); + rotationListeners.add(listener); + return () => rotationListeners.delete(listener); +} + +function notifyRotation(registration, status) { + const event = Object.freeze({ database: registration.name, ...status }); + for (const listener of rotationListeners) { + try { Promise.resolve(listener(event)).catch(() => {}); } catch { /* Observers cannot affect committed state. */ } + } + notifyManagedLifecycle({ name: registration.name, schema: registration.schema }, "key-rotation", { + rotation: status, processedRecords: status.converted, verifiedRecords: status.verified + }); + return status; +} + +function rotationStatus(document) { + const { rotationId, sourceKeyId, targetKeyId, mode, phase, paused, converted, verified } = document.state; + return { rotationId, sourceKeyId, targetKeyId, mode, phase, paused, converted, verified, retirementReady: false, + readsAllowed: mode !== "exclusive", writesAllowed: mode === "online" && phase === "converting" }; +} + +async function attachRotation(registration, active, context, ready) { + if (ready) { + registration.protection.setManagedReadiness(ready); + } + await registration.protection.setRotationAccess(active.document, active.fence, context.keys, context.assertCurrent, context.authorizationSignal); + context.assertCurrent(); + if (ready) registration.result = ready; + registration.rotation = { active, keys: context.keys }; +} + +// Key IDs here are untrusted routing hints. They do not authorize access or +// become status until the supplied keys verify the durable proofs. +export async function getManagedEncryptionKeyHints(name) { + const managed = managedDatabases.get(name); + if (!managed?.protected) return null; + if (managed.pending && managed.authorization?.adapter) + return { active: false, keyId: managed.authorization.keyId }; + return inspectKeyRoutingHints(managed.db.name, rotationJournalKey); +} + +export async function authorizeManagedKeyRotation(name, sourceKeyId, sourceInput, targetKeyId, targetInput) { + const managed = managedRotationRegistration(name); + const authorization = await authorizeProtectedMigration(managed, sourceKeyId, sourceInput, false); + authorization.assertCurrent(); + try { + const target = await rotationKey(targetInput); + const keys = new Map([[sourceKeyId, authorization.key], [targetKeyId, target]]); + authorization.assertCurrent(); + await managed.db.open(); + authorization.assertCurrent(); + const context = rotationContext(managed, keys, authorization.controller.signal); + const active = await openRotation(context); + if (!active) throw new Error("MAGIC_ROTATION_NOT_ACTIVE: No incomplete rotation was found."); + await verifyRotationDeployment({ schema: managed.schema, manifestUrl: managed.manifestUrl, + signal: authorization.controller.signal }, active.ready.revision); + authorization.assertCurrent(); + await attachRotation(managed, active, context, active.ready); + return rotationStatus(active.document); + } catch (error) { + if (managed.authorization === authorization) lockProtectedDatabase(name); + throw error; + } +} + +export async function getManagedKeyRotationStatus(name) { + const managed = managedRotationRegistration(name); + const rotation = managed.rotation; + if (rotation) { + const previous = rotation.active.document.state; + const current = await openRotation(rotationContext(managed, rotation.keys)); + if (current) assertRotationProgress(previous, current.document.state); + if (!current) throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: Reauthorize the finalized vault."); + return rotationStatus(current.document); + } + if (!managed.authorization?.adapter || !managed.result) return { phase: "authorization-required", retirementReady: false }; + await assertDatabaseReady(managed.db.backendDB(), managed.result, managed.authorization.adapter); + const lineage = managed.authorization.adapter.keyLineage; + return lineage ? { phase: "completed", rotationId: lineage.completed.rotationId, + sourceKeyId: lineage.generations.at(-2), targetKeyId: lineage.generations.at(-1), + converted: lineage.completed.converted, verified: lineage.completed.verified, retirementReady: true, + readsAllowed: true, writesAllowed: true } : { phase: "not-started", retirementReady: false, readsAllowed: true, writesAllowed: true }; +} + +function assertRotationProgress(previous, current) { + if (previous.rotationId !== current.rotationId || current.sequence < previous.sequence) + throw new Error("MAGIC_ROTATION_STATE_INVALID: Authenticated progress was replaced by an earlier state."); +} + +async function runRotation(registration, options, start) { + if (registration.rotationTask || registration.pending) + throw new Error("MAGIC_ROTATION_IN_PROGRESS: This connection is already running a vault lifecycle operation."); + const attempt = runRotationAttempt(registration, options, start); + registration.rotationTask = attempt; + try { + return await attempt; + } finally { + registration.rotationTask = null; + } +} + +async function runRotationAttempt(registration, options, start) { + const authorization = requireMigrationAuthorization(registration); + const controller = new AbortController(); + const revoke = () => controller.abort(); + authorization.controller.signal.addEventListener("abort", revoke, { once: true }); + registration.rotationController = controller; + const batchSize = options.batchSize ?? 128; + try { + if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 4096) + throw new RangeError("Magic rotation batch size must be between 1 and 4096."); + const task = rotationCoordinator(registration.db, controller.signal, async () => { + const { active: initial, context } = await start(controller.signal); + let active = initial; + const { policies } = portableProtectionPolicy(context.schema); + if (active.document.state.paused) { + active = await setRotationPaused({ ...context, ...active, paused: false }); + } + await attachRotation(registration, active, context); + notifyRotation(registration, rotationStatus(active.document)); + for (;;) { + controller.signal.throwIfAborted(); + const result = await advanceRotationPass({ ...context, document: active.document, policies, batchSize, + expectations: [...active.checks, { store: encryptionMetadataStore, key: "policy", value: active.fence }] }); + if (result.outcome === "paused") return rotationStatus(result.document); + if (result.outcome === "retry") { + const current = await openRotation(context); + if (!current || canonicalJson(current.document.state) !== canonicalJson(active.document.state)) + throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: Rotation metadata changed during a batch."); + await new Promise(resolve => setTimeout(resolve, 0)); + continue; + } + if (result.outcome === "advanced") { + active = { ...active, document: result.document }; + registration.rotation.active = active; + notifyRotation(registration, rotationStatus(active.document)); + if (options.yieldBetweenBatches) await new Promise(resolve => setTimeout(resolve, 0)); + continue; + } + if (active.document.state.phase === "converting") { + active = await enterRotationVerification({ ...context, ...active }); + await attachRotation(registration, active, context); + notifyRotation(registration, rotationStatus(active.document)); + continue; + } + const finalized = await finishRotation({ ...context, ...active }); + const { targetKeyId } = active.document.state; + const target = context.keys.get(targetKeyId); + authorization.assertCurrent(); + registration.protection.lock(); + registration.result = null; + registration.rotation = null; + return { finalized, targetKeyId, target }; + } + }); + const result = await task; + if (!result.finalized) return result; + // Reauthorize with the target only after releasing the lifecycle lock. + // A concurrent application lock must never be undone here. + authorization.assertCurrent(); + await authorizeProtectedMigration(registration, result.targetKeyId, result.target, false); + const targetAuthorization = requireMigrationAuthorization(registration); + // Rotation reseals the same ready revision. Authenticate that exact + // state on the existing connection without disrupting foreground reads. + await targetAuthorization.adapter.verifyPolicy(result.finalized.ready.policySeal, registration.schema); + await publishProtectedReadiness(registration, result.finalized.ready, targetAuthorization); + return notifyRotation(registration, await getManagedKeyRotationStatus(registration.name)); + } finally { + authorization.controller.signal.removeEventListener("abort", revoke); + registration.rotationController = null; + } +} + +export function getManagedRotationAdmission(name) { + const managed = managedRotationRegistration(name); + const authorization = requireMigrationAuthorization(managed); + return { authorizationId: authorization.id, keyId: authorization.keyId }; +} + +export async function rotateManagedEncryptionKey(name, options, targetInput) { + const managed = managedRotationRegistration(name); + if (!managed.result || managed.rotation) + throw new Error("MAGIC_ROTATION_AUTHORIZATION_REQUIRED: Unlock a ready vault, or resume its active rotation."); + return runRotation(managed, options, async signal => { + const authorization = requireMigrationAuthorization(managed); + if (options.authorizationId && options.authorizationId !== authorization.id) + throw new Error("MAGDB_AUTHORIZATION_LOST: The rotation admission authorization was replaced."); + const target = await rotationKey(targetInput); + authorization.assertCurrent(); + const keys = new Map([[authorization.keyId, authorization.key], [options.targetKeyId, target]]); + const context = rotationContext(managed, keys, signal); + // Keep the two identities distinct before constructing the key map. + if (options.targetKeyId === authorization.keyId) + throw new Error("MAGIC_ROTATION_KEY_REUSED: The target key identifier is already active."); + const active = await admitRotation({ ...context, targetKeyId: options.targetKeyId, + mode: options.mode ?? "exclusive", recoverable: options.recoverable }); + return { active, context }; + }); +} + +export async function resumeManagedEncryptionKeyRotation(name, options = {}) { + const managed = managedRotationRegistration(name); + if (!managed.rotation) throw new Error("MAGIC_ROTATION_AUTHORIZATION_REQUIRED: Authorize both rotation keys before resuming."); + return runRotation(managed, options, async signal => { + const rotation = managed.rotation; + const previous = rotation.active.document.state; + const context = rotationContext(managed, rotation.keys, signal); + const active = await openRotation(context); + if (!active) throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: Reauthorize the finalized vault."); + assertRotationProgress(previous, active.document.state); + return { active, context }; + }); +} + +export function scheduleManagedKeyRotationResume(name) { + const managed = managedRotationRegistration(name); + if (!managed.rotation || managed.rotation.active.document.state.paused || managed.rotationTask) return; + void resumeManagedEncryptionKeyRotation(name, { yieldBetweenBatches: true }).catch(error => { + if (error.name === "AbortError") return; + notifyManagedLifecycle({ name, schema: managed.schema }, "key-rotation-failed", { + code: "MAGIC_ROTATION_RESUME_FAILED", retryable: false + }); + }); +} + +export function cancelManagedEncryptionKeyRotation(name) { + managedDatabases.get(name)?.rotationController?.abort(); +} + +export async function pauseManagedEncryptionKeyRotation(name) { + const managed = managedRotationRegistration(name); + const rotation = managed.rotation; + if (!rotation) throw new Error("MAGIC_ROTATION_AUTHORIZATION_REQUIRED: Authorize both rotation keys before pausing."); + cancelManagedEncryptionKeyRotation(name); + const authorization = requireMigrationAuthorization(managed); + return rotationCoordinator(managed.db, authorization.controller.signal, async () => { + const context = rotationContext(managed, rotation.keys, authorization.controller.signal); + const active = await openRotation(context); + if (!active) throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: Reauthorize the finalized vault."); + const paused = await setRotationPaused({ ...context, ...active, paused: true }); + rotation.active = paused; + return notifyRotation(managed, rotationStatus(paused.document)); + }); +} + +export async function isProtectedDatabaseUnlocked(name, refreshGeneration = false) { + try { return await (protectedDatabases.get(name)?.isUnlocked() ?? false); } + catch (error) { + if (!refreshGeneration || !managedDatabases.get(name)?.protected || + !/^(MAGIC_ENCRYPTION_POLICY_MISMATCH|MAGIC_ROTATION_CONCURRENT_CHANGE|MAGDB_PROTECTION_STATE_INVALID):/.test(error.message)) + throw error; + lockProtectedDatabase(name); + return false; + } } export function getProtectedDatabaseState(name) { @@ -293,6 +588,7 @@ export function lockProtectedDatabase(name) { managed.authorization?.controller.abort(); if (managed.authorization) managed.authorization.key = null; managed.authorization = null; + managed.rotation = null; managed.result = null; } protectedDatabases.get(name)?.lock(); diff --git a/Magic.IndexedDb/wwwroot/migrations/migrationEngine.js b/Magic.IndexedDb/wwwroot/migrations/migrationEngine.js index 47500105..d66b12c1 100644 --- a/Magic.IndexedDb/wwwroot/migrations/migrationEngine.js +++ b/Magic.IndexedDb/wwwroot/migrations/migrationEngine.js @@ -1,6 +1,6 @@ import { MigrationError, metadataStore, canonicalJson, sha256, requirePlainSchema, requireProtectedSchema, hasProtection, validateManifest, validateCompletedHistory, validateMigration, validateRecovery, requireCondition, physicalStores, samePhysical, compareNames } from "./protocol.js"; -import { isProtectedMigrationAdapter, equalEnvelope } from "./protectedMigrationAdapter.js"; +import { isProtectedMigrationAdapter, equalEnvelope, recoveryEvidenceKey, retainedRecoveries, sameRecoveryEvidence } from "./protectedMigrationAdapter.js"; import { encryptionMetadataStore, encryptionMetadataKey } from "../utilities/encryptionPolicy.js"; export { MigrationError }; @@ -24,6 +24,8 @@ function notify(options, phase, details = {}) { } } +export { notify as notifyManagedLifecycle }; + function abortCheck(signal) { if (signal?.aborted) throw new MigrationError("MAGDB_CANCELLED", "Migration was cancelled; committed checkpoints are retained.", {}, true); } @@ -103,7 +105,7 @@ function nativeStores(db, transaction) { }).sort((a, b) => compareNames(a.name, b.name)); } -async function inspectOpen(db) { +export async function inspectOpen(db, rotationKey = null) { if (!db.objectStoreNames.length) return { name: db.name, nativeVersion: db.version, stores: [], state: null, numericPolicy: null }; const transaction = db.transaction([...db.objectStoreNames], "readonly"); const done = transactionDone(transaction); @@ -111,22 +113,31 @@ async function inspectOpen(db) { const protection = db.objectStoreNames.contains(encryptionMetadataStore) ? transaction.objectStore(encryptionMetadataStore) : null; if (protection) requireCondition(protection.keyPath === null && !protection.autoIncrement && !protection.indexNames.length, "MAGDB_PROTECTION_INVALID", "The authenticated metadata store has an unsupported layout."); - const [state, numericPolicy, protectionPolicy, protectionState] = await Promise.all([ + const [state, numericPolicy, protectionPolicy, protectionState, rotation] = await Promise.all([ db.objectStoreNames.contains(metadataStore) ? requestResult(transaction.objectStore(metadataStore).get(stateKey)) : null, db.objectStoreNames.contains(numericStore) ? requestResult(transaction.objectStore(numericStore).get("policy")) : null, protection ? requestResult(protection.get(encryptionMetadataKey)) : null, - protection ? requestResult(protection.get(protectedStateKey)) : null + protection ? requestResult(protection.get(protectedStateKey)) : null, + protection && rotationKey ? requestResult(protection.get(rotationKey)) : null ]); await done; return { name: db.name, nativeVersion: db.version, stores, state: state ?? null, numericPolicy: numericPolicy ?? null, hasNumericMetadata: db.objectStoreNames.contains(numericStore), - hasProtectionMetadata: Boolean(protection), protectionPolicy: protectionPolicy ?? null, protectionState: protectionState ?? null }; + hasProtectionMetadata: Boolean(protection), protectionPolicy: protectionPolicy ?? null, protectionState: protectionState ?? null, + ...(rotationKey ? { rotation } : {}) }; } -async function inspectDatabaseInternal(name, signal) { +async function inspectDatabaseInternal(name, signal, rotationKey = null) { const db = await openExisting(name, signal); if (!db) return null; - try { return await inspectOpen(db); } finally { db.close(); } + try { return await inspectOpen(db, rotationKey); } finally { db.close(); } +} + +export async function inspectKeyRoutingHints(name, rotationKey) { + const snapshot = await inspectDatabaseInternal(name, undefined, rotationKey); + return snapshot?.rotation ? { active: true, keyId: snapshot.rotation.state?.sourceKeyId, + targetKeyId: snapshot.rotation.state?.targetKeyId } + : snapshot?.protectionPolicy?.keyId ? { active: false, keyId: snapshot.protectionPolicy.keyId } : null; } /** Inspect metadata only. Durable record keys are never exposed in diagnostics. */ @@ -162,7 +173,7 @@ function writeNumericPolicy(db, transaction, schema) { store.put({ version: 1, mode: "lossless", schema: physicalStores(schema) }, "policy"); } -function assertNumericPolicy(snapshot, schema, legacyProtected = false) { +export function assertNumericPolicy(snapshot, schema, legacyProtected = false) { if (schema.numericFormat === "lossless-v1") { // The released protected adapter authenticated its numeric mode in the // legacy sentinel without provisioning a separate numeric policy store. @@ -471,6 +482,47 @@ async function authenticateSnapshot(options, snapshot, schema) { checkAuthorization(options); } +async function prepareRecoveryEvidenceEnrollment(options, state) { + const entries = retainedRecoveries(state); + if (!entries.length) return []; + const db = await openExisting(options.name, options.signal); + requireCondition(db, "MAGDB_DATABASE_MISSING", "Storage disappeared before authenticated adoption."); + let evidence; + try { + const transaction = db.transaction(metadataStore, "readonly"); + const done = transactionDone(transaction); + const metadata = transaction.objectStore(metadataStore); + try { + evidence = await Promise.all(entries.map(entry => requestResult(metadata.get(recoveryEvidenceKey(entry.recovery.id))))); + await done; + } catch (failure) { + await done.catch(() => {}); + throw failure; + } + } finally { db.close(); } + return Promise.all(entries.map(async (entry, index) => { + const audit = evidence[index]; + requireCondition(audit, "MAGDB_PROTECTION_STATE_INVALID", "Retained recovery evidence is missing."); + return { key: recoveryEvidenceKey(entry.recovery.id), audit, seal: await options.protection.sealRecoveryEvidence(audit, entry) }; + })); +} + +function enrollRecoveryEvidence(metadata, evidence, finalize, fail) { + if (!evidence.length) return finalize(); + let remaining = evidence.length; + for (const { key, audit, seal } of evidence) { + const lookup = metadata.get(key); + lookup.onsuccess = () => { + try { + requireCondition(sameRecoveryEvidence(lookup.result, audit), + "MAGDB_CONCURRENT_CHANGE", "Retained recovery evidence changed before authenticated adoption."); + metadata.put(seal, key); + if (--remaining === 0) finalize(); + } catch (failure) { fail(failure); } + }; + } +} + async function prepareProtection(options, state, schema, replacePolicy = false) { if (!options.protection) return null; checkAuthorization(options); @@ -622,11 +674,9 @@ async function runManaged(options, recovering) { } } -async function ensureLocked(options, recovering) { - notify(options, "preflight"); - abortCheck(options.signal); - const expectedHash = await sha256(canonicalJson(options.schema)); - let manifest, base = new URL(options.manifestUrl ?? ".", globalThis.location.href).href; +async function loadPinnedManifest(options) { + let manifest; + const base = new URL(options.manifestUrl ?? ".", globalThis.location.href).href; requireCondition(new URL(base).origin === globalThis.location.origin && ["http:", "https:"].includes(new URL(base).protocol), "MAGDB_ASSET_ORIGIN", "The application-pinned manifest must use the application's HTTP(S) origin."); if (options.manifestUrl) { @@ -635,6 +685,22 @@ async function ensureLocked(options, recovering) { } else if (options.manifest) manifest = structuredClone(options.manifest); else manifest = null; + return { manifest, base }; +} + +export async function verifyRotationDeployment(options, revision) { + const { manifest } = await loadPinnedManifest(options); + if (manifest) validateManifest(manifest, options.schema.schemaId); + requireCondition((manifest?.targetRevision ?? 1) === revision, + "MAGIC_ROTATION_DEPLOYMENT_CHANGED", "Resume rotation from the deployment that admitted it before upgrading this vault."); +} + +async function ensureLocked(options, recovering) { + notify(options, "preflight"); + abortCheck(options.signal); + const expectedHash = await sha256(canonicalJson(options.schema)); + const { manifest, base } = await loadPinnedManifest(options); + const models = new Map(); async function model(revision) { if (models.has(revision)) return models.get(revision); @@ -747,16 +813,21 @@ async function ensureLocked(options, recovering) { expectedState = adopted; } else if (options.protection && snapshot.state.protocolVersion !== 3) { const adopted = { ...snapshot.state, protocolVersion: 3 }; + const evidence = await prepareRecoveryEvidenceEnrollment(options, snapshot.state); const prepared = await prepareProtection(options, adopted, initial.schema, true); db = await upgrade(options, snapshot.nativeVersion + 1, (connection, transaction, oldVersion, fail) => { requireCondition(oldVersion === snapshot.nativeVersion && samePhysical(nativeStores(connection, transaction), initial.schema), "MAGDB_CONCURRENT_CHANGE", "Database changed before authenticated adoption."); - const request = transaction.objectStore(metadataStore).get(stateKey); + const metadata = transaction.objectStore(metadataStore); + const request = metadata.get(stateKey); request.onsuccess = () => guardStoragePolicy(options, connection, transaction, initial.schema, () => { requireCondition(sameState(request.result, snapshot.state), "MAGDB_CONCURRENT_CHANGE", "The journal changed before authenticated adoption."); - transaction.objectStore(metadataStore).put(adopted, stateKey); - writeNumericPolicy(connection, transaction, initial.schema); - writeProtection(connection, transaction, prepared); + enrollRecoveryEvidence(metadata, evidence, () => { + checkAuthorization(options); + metadata.put(adopted, stateKey); + writeNumericPolicy(connection, transaction, initial.schema); + writeProtection(connection, transaction, prepared); + }, fail); }, fail); }); options.protectionSnapshot = prepared; @@ -1006,9 +1077,9 @@ async function recoverLocked(options, snapshot, manifest, base, model) { const completed = readyState(manifest.schemaId, edge.toRevision, to.hash, history, options.protection ? 3 : 2); const prepared = await prepareProtection(options, completed, to.schema, true); const audit = { original: state.active, recovery: state.recovery }; - const evidence = options.protection ? await options.protection.sealState(audit) : audit; + const evidence = options.protection ? await options.protection.sealRecoveryEvidence(audit, history.at(-1)) : audit; await recoveryTransaction(options, db, state, to.schema, (_tx, metadata) => { - metadata.add(evidence, "recovery:" + binding.id); + metadata.add(evidence, recoveryEvidenceKey(binding.id)); metadata.put(completed, stateKey); }, prepared); notify(options, "recovered", { recoveryId: binding.id, migrationId: edge.id, revision: edge.toRevision, diff --git a/Magic.IndexedDb/wwwroot/migrations/protectedMigrationAdapter.js b/Magic.IndexedDb/wwwroot/migrations/protectedMigrationAdapter.js index 6cb03f78..b66144a3 100644 --- a/Magic.IndexedDb/wwwroot/migrations/protectedMigrationAdapter.js +++ b/Magic.IndexedDb/wwwroot/migrations/protectedMigrationAdapter.js @@ -2,9 +2,12 @@ import { assertEncryptionKey, importEncryptionKey, encryptValue, decryptValue } import { openRecord, sealRecord } from "../utilities/encryptionRecord.js"; import { encryptionMetadataStore, encryptionMetadataKey } from "../utilities/encryptionPolicy.js"; import { portableProtectionPolicy, matchesProtectionFingerprint } from "../utilities/protectionPolicy.js"; -import { canonicalJson, MigrationError } from "./protocol.js"; +import { canonicalJson, metadataStore, MigrationError } from "./protocol.js"; +import { parsePolicyDocument, serializePolicyDocument, validLineage } from "../utilities/encryptionPolicyDocument.js"; export const protectedStateKey = "migration-state"; +export const recoveryEvidenceKey = id => "recovery:" + id; +export const retainedRecoveries = ready => ready.history.filter(entry => entry.outcome === "recovered"); const adapters = new WeakSet(); export function isProtectedMigrationAdapter(value) { return adapters.has(value); } @@ -36,6 +39,34 @@ function authenticatedValue(value) { throw new MigrationError("MAGDB_PROTECTION_STATE_INVALID", "The migration state contains an unsupported value."); } +const stateValue = state => JSON.stringify(["Magic.IndexedDb/migration-state", 1, authenticatedValue(state)]); + +export function sameRecoveryEvidence(left, right) { + try { return stateValue(left) === stateValue(right); } + catch { return false; } +} + +function assertRecoveryEvidence(value, entry) { + let evidence; + try { + const [domain, version, payload] = JSON.parse(value); + if (domain === "Magic.IndexedDb/migration-state" && version === 1) evidence = payload; + } catch { /* reported without evidence contents below */ } + const member = (node, name) => node?.[0] === "object" && Array.isArray(node[1]) + ? node[1].find(item => item?.[0] === name)?.[1] : undefined; + const matches = (node, name, expected) => { + const property = member(node, name); + return property?.[0] === "string" && property[1] === expected; + }; + const original = member(evidence, "original"); + const recovery = member(evidence, "recovery"); + if (!matches(original, "id", entry.id) || !matches(original, "sha256", entry.sha256) || + !matches(recovery, "id", entry.recovery.id) || !matches(recovery, "sha256", entry.recovery.sha256)) { + throw error("MAGDB_PROTECTION_STATE_INVALID", "Recovery evidence does not match authenticated history."); + } + return value; +} + function error(code, message) { return new MigrationError(code, message); } /** @@ -87,39 +118,72 @@ export async function createProtectedMigrationAdapter(options) { assertCurrent(); return envelope; }; - const fenceValue = binding => canonicalJson(["Magic.IndexedDb/migration-fence", 1, binding]); - const stateValue = state => JSON.stringify(["Magic.IndexedDb/migration-state", 1, authenticatedValue(state)]); + let lineage = null; + const fenceValue = (binding, history = lineage) => canonicalJson(history === null + ? ["Magic.IndexedDb/migration-fence", 1, binding] + : ["Magic.IndexedDb/migration-fence", 2, binding, history]); + const recoveryContext = entry => context(recoveryEvidenceKey(entry.recovery.id), metadataStore); + async function openRecoveryEvidence(envelope, entry, acceptLegacy) { + let value; + try { + value = await decrypt(envelope, recoveryContext(entry), "MAGDB_PROTECTION_STATE_INVALID"); + } catch (failure) { + if (!acceptLegacy) throw failure; + value = await decrypt(envelope, context(protectedStateKey), "MAGDB_PROTECTION_STATE_INVALID"); + } + return assertRecoveryEvidence(value, entry); + } const adapter = Object.freeze({ name, account, keyId, signal, assertCurrent, fingerprint: schema => portableProtectionPolicy(schema).policyFingerprint, async verifyPolicy(envelope, schema, { legacyOnly = false } = {}) { const value = await decrypt(envelope, context(encryptionMetadataKey), "MAGDB_AUTHORIZATION_REJECTED"); - let parsed; - try { parsed = JSON.parse(value); } catch { /* redacted below */ } - if (!Array.isArray(parsed) || parsed.length !== 3 || parsed[0] !== "Magic.IndexedDb/policy" || parsed[1] !== 1 || - !matchesProtectionFingerprint(parsed[2], schema)) + const parsed = parsePolicyDocument(value, keyId); + if (!parsed || !matchesProtectionFingerprint(parsed.fingerprint, schema)) throw error("MAGDB_PROTECTION_POLICY_MISMATCH", "The authenticated protection policy differs from the installed model."); // A valid managed sentinel is evidence that authenticated history // already existed. Removing its journal/proof must never turn it // back into an adoptable legacy vault and replay old transforms. - const managed = parsed[2] === portableProtectionPolicy(schema).policyFingerprint; + const managed = parsed.fingerprint === portableProtectionPolicy(schema).policyFingerprint; if (legacyOnly && managed) throw error("MAGDB_PROTECTION_STATE_INVALID", "A managed protection policy requires its authenticated migration journal."); if (!legacyOnly && !managed) throw error("MAGDB_PROTECTION_STATE_INVALID", "An authenticated migration journal requires a managed protection policy."); + if (parsed.lineage !== null && !managed) + throw error("MAGDB_PROTECTION_STATE_INVALID", "Rotated protection requires authenticated history."); + lineage = parsed.lineage; return structuredClone(envelope); }, + get keyLineage() { return structuredClone(lineage); }, createPolicy(schema) { const fingerprint = portableProtectionPolicy(schema).policyFingerprint; - return encrypt(JSON.stringify(["Magic.IndexedDb/policy", 1, fingerprint]), context(encryptionMetadataKey)); + return encrypt(serializePolicyDocument(fingerprint, lineage), context(encryptionMetadataKey)); }, createFence: binding => encrypt(fenceValue(binding), context(encryptionMetadataKey)), async authenticateFence(envelope, binding) { const actual = await decrypt(envelope, context(encryptionMetadataKey), "MAGDB_AUTHORIZATION_REJECTED"); - if (actual !== fenceValue(binding)) + if (actual === fenceValue(binding, null)) { + lineage = null; + return; + } + let parsed; + try { parsed = JSON.parse(actual); } catch { /* redacted below */ } + const history = Array.isArray(parsed) && parsed.length === 4 && validLineage(parsed[3], keyId) ? parsed[3] : null; + if (!history || actual !== fenceValue(binding, history)) throw error("MAGDB_PROTECTION_STATE_INVALID", "The authenticated migration fence does not match the interrupted edge."); + lineage = history; }, sealState: state => encrypt(stateValue(state), context(protectedStateKey)), + sealRecoveryEvidence(audit, entry) { + return encrypt(assertRecoveryEvidence(stateValue(audit), entry), recoveryContext(entry)); + }, + verifyRecoveryEvidence: (envelope, entry) => openRecoveryEvidence(envelope, entry, false), + async rotateRecoveryEvidence(envelope, entry, source) { + const value = await source.openRetainedRecoveryEvidence(envelope, entry); + return encrypt(value, recoveryContext(entry)); + }, + // v3.0 sealed recovery evidence with migration-state associated data. + openRetainedRecoveryEvidence: (envelope, entry) => openRecoveryEvidence(envelope, entry, true), async verifyState(envelope, state) { const actual = await decrypt(envelope, context(protectedStateKey), "MAGDB_PROTECTION_STATE_INVALID"); if (actual !== stateValue(state)) diff --git a/Magic.IndexedDb/wwwroot/utilities/encryptionPolicy.js b/Magic.IndexedDb/wwwroot/utilities/encryptionPolicy.js index 85f9b20f..5e01f26c 100644 --- a/Magic.IndexedDb/wwwroot/utilities/encryptionPolicy.js +++ b/Magic.IndexedDb/wwwroot/utilities/encryptionPolicy.js @@ -1,8 +1,8 @@ import { decryptValue, encryptValue } from "./encryptionEnvelope.js"; +import { parsePolicyDocument, serializePolicyDocument } from "./encryptionPolicyDocument.js"; export const encryptionMetadataStore = "__magic_encryption"; export const encryptionMetadataKey = "policy"; -const policyVersion = 1; function checkContext(db, account) { return { @@ -14,14 +14,10 @@ function checkContext(db, account) { }; } -function checkValue(policyFingerprint) { - return JSON.stringify(["Magic.IndexedDb/policy", policyVersion, policyFingerprint]); -} - // Creating the sentinel is an explicit operation for empty databases. Ordinary // unlock never reinitializes missing metadata, even when all stores are empty. export async function verifyEncryptionPolicy(db, { - account, policyFingerprint, keyId, key, initialize = false, signal + account, policyFingerprint, keyId, key, initialize = false, allowRotated = false, signal }) { if (typeof policyFingerprint !== "string" || !policyFingerprint) { throw new TypeError("Magic encryption requires a storage policy fingerprint."); @@ -32,7 +28,7 @@ export async function verifyEncryptionPolicy(db, { } const metadata = db.table(encryptionMetadataStore); const context = checkContext(db, account); - const expected = checkValue(policyFingerprint); + const expected = serializePolicyDocument(policyFingerprint); signal?.throwIfAborted(); let saved = await metadata.get(encryptionMetadataKey); @@ -71,7 +67,8 @@ export async function verifyEncryptionPolicy(db, { throw new Error("MAGIC_ENCRYPTION_INVALID_KEY: The key or stored policy envelope could not be authenticated.", { cause }); } signal?.throwIfAborted(); - if (actual !== expected) { + const policy = parsePolicyDocument(actual, keyId); + if (!policy || policy.fingerprint !== policyFingerprint || policy.lineage !== null && !allowRotated) { throw new Error("MAGIC_ENCRYPTION_POLICY_MISMATCH: Magic encryption storage policy does not match the persisted policy."); } return saved; diff --git a/Magic.IndexedDb/wwwroot/utilities/encryptionPolicyDocument.js b/Magic.IndexedDb/wwwroot/utilities/encryptionPolicyDocument.js new file mode 100644 index 00000000..3d3c315a --- /dev/null +++ b/Magic.IndexedDb/wwwroot/utilities/encryptionPolicyDocument.js @@ -0,0 +1,31 @@ +// The legacy format remains stable. Managed vaults only use version 2 after +// rotation has authenticated the first complete generation history. +const label = "Magic.IndexedDb/policy"; + +export function validLineage(value, keyId) { + return value && Object.getPrototypeOf(value) === Object.prototype && + Object.keys(value).length === 2 && + Array.isArray(value.generations) && value.generations.length >= 2 && + value.generations.every(id => typeof id === "string" && id.length > 0) && + new Set(value.generations).size === value.generations.length && + value.generations.at(-1) === keyId && + value.completed && Object.getPrototypeOf(value.completed) === Object.prototype && + Object.keys(value.completed).length === 3 && + typeof value.completed.rotationId === "string" && value.completed.rotationId.length > 0 && + [value.completed.converted, value.completed.verified].every(count => Number.isSafeInteger(count) && count >= 0); +} + +export function serializePolicyDocument(fingerprint, lineage = null) { + return JSON.stringify(lineage === null ? [label, 1, fingerprint] : [label, 2, fingerprint, lineage]); +} + +export function parsePolicyDocument(value, keyId) { + let parsed; + try { parsed = JSON.parse(value); } catch { return null; } + if (!Array.isArray(parsed) || parsed[0] !== label || typeof parsed[2] !== "string") return null; + if (parsed[1] === 1 && parsed.length === 3) return { fingerprint: parsed[2], lineage: null }; + if (parsed[1] === 2 && parsed.length === 4 && validLineage(parsed[3], keyId)) { + return { fingerprint: parsed[2], lineage: parsed[3] }; + } + return null; +} diff --git a/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js b/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js index eee8a50f..026b1ef5 100644 --- a/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js +++ b/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js @@ -7,6 +7,9 @@ import { canonicalJson, metadataStore as migrationMetadataStore, MigrationError import { equalEnvelope, protectedStateKey } from "../migrations/protectedMigrationAdapter.js"; import { numericMetadataStore } from "./numericStorage.js"; import { magicQueryYield } from "../magicLinqToIndexedDb.js"; +import { openRotatingRecord } from "./rotationRecord.js"; +import { verifyRotationJournal } from "./rotationJournal.js"; +import { verifyRotationFence } from "./rotationFence.js"; export const protectedDatabasePrefix = "__magic_protected__:"; const locked = "MAGIC_ENCRYPTION_LOCKED"; @@ -68,44 +71,83 @@ export function createProtectedStorage(db, account, schemas, numericStorage = nu const session = new EncryptionSession(); let verified; let readiness; + let rotation; let mismatch = false; let disposed = false; const assertLive = () => { if (disposed) throw new Error("MAGIC_ENCRYPTION_POLICY_REQUIRED: This protected connection was released."); }; - const assertPolicy = async () => { + const assertPolicy = async (write = false, enforceAvailability = true) => { assertLive(); - const snapshot = verified; + const access = rotation; + if (enforceAvailability && access && (access.state.mode === "exclusive" || + write && (access.state.mode !== "online" || access.state.phase === "verifying"))) { + throw new Error("MAGIC_ROTATION_ACCESS_FENCED: This operation is unavailable during key rotation."); + } + access?.assertCurrent(); + const snapshot = access?.fence ?? verified; if (!snapshot) { throw new Error("MAGIC_ENCRYPTION_POLICY_REQUIRED: Unlock this connection to authenticate its storage policy."); } - await assertPersistedEncryptionPolicy(db.table(encryptionMetadataStore), snapshot); if (options.managedSchema) { const numeric = db.tables.find(table => table.name === numericMetadataStore); const journal = await db.table(migrationMetadataStore).get("state"); const seal = await db.table(encryptionMetadataStore).get(protectedStateKey); - if (!readiness || !equalEnvelope(snapshot, readiness.policySeal) || + if (!readiness || !access && !equalEnvelope(snapshot, readiness.policySeal) || canonicalJson(journal ?? null) !== readiness.journal || !equalEnvelope(seal, readiness.seal)) throw new MigrationError("MAGDB_PROTECTION_STATE_INVALID", "The authenticated ready state changed. Reinitialize before accessing records."); const numericPolicy = await numeric?.get("policy"); if (canonicalJson(numericPolicy ?? null) !== readiness.numericPolicy) throw new MigrationError("MAGDB_CODEC_POLICY_MISMATCH", "The authenticated connection's numeric policy changed."); } + // Admission can change only the policy. Read it after the other + // metadata, immediately before authorizing delivery or mutation. + await assertPersistedEncryptionPolicy(db.table(encryptionMetadataStore), snapshot); + if (rotation !== access) throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: Rotation access changed during the operation."); + access?.assertCurrent(); assertLive(); }; return { + async setRotationAccess(document, fence, keys, assertCurrent, signal) { + if (!options.managedSchema || !readiness) { + throw new Error("MAGIC_ROTATION_AUTHORIZATION_REQUIRED: An authorized managed connection is required."); + } + const vault = { database: db.name, account }; + const state = await verifyRotationJournal(document, keys, vault, assertCurrent); + if (state.policyFingerprint !== policyFingerprint || state.modelHash !== JSON.parse(readiness.journal).schemaHash) { + throw new Error("MAGIC_ROTATION_STATE_INVALID: Rotation belongs to a different managed model."); + } + await verifyRotationFence(fence, state, keys.get(state.targetKeyId), vault, assertCurrent); + await assertPersistedEncryptionPolicy(db.table(encryptionMetadataStore), fence); + assertCurrent(); + assertLive(); + await session.ensureUnlocked(signal => { + signal.throwIfAborted(); + assertCurrent(); + return { key: keys.get(state.sourceKeyId), keyId: state.sourceKeyId }; + }); + assertCurrent(); + rotation = { state, fence: structuredClone(fence), keys: new Map(keys), assertCurrent, signal }; + }, + assertRotationReadiness: () => assertPolicy(false, false), setManagedReadiness: result => { if (!options.managedSchema || result?.journal?.protocolVersion !== 3 || result.journal.status !== "ready" || !equalEnvelope(result.journalSeal, result.journalSeal) || !equalEnvelope(result.policySeal, result.policySeal)) throw new MigrationError("MAGDB_PROTECTION_STATE_INVALID", "An authenticated ready journal is required."); + if (verified && !equalEnvelope(verified, result.policySeal)) { + // A separately authenticated managed transition has replaced + // the policy. Never reuse the previous key or snapshot. + verified = undefined; + session.lock(); + } readiness = { journal: canonicalJson(result.journal), seal: structuredClone(result.journalSeal), policySeal: structuredClone(result.policySeal), numericPolicy: canonicalJson(result.numericPolicy) }; }, forTable: name => { const policy = policies.get(name); if (!policy) throw new Error("MAGIC_ENCRYPTION_POLICY_REQUIRED: The store is outside the configured storage policy."); - return new ProtectedTable(db, account, name, policy, session, assertPolicy, assertLive, Boolean(options.managedSchema)); + return new ProtectedTable(db, account, name, policy, session, assertPolicy, assertLive, Boolean(options.managedSchema), () => rotation); }, unlock: (keyId, input, initialize) => session.ensureUnlocked(async signal => { await db.open(); @@ -119,7 +161,7 @@ export function createProtectedStorage(db, account, schemas, numericStorage = nu } try { if (verified) await assertPolicy(); - const snapshot = await verifyEncryptionPolicy(db, { account, policyFingerprint, keyId, key, initialize, signal }); + const snapshot = await verifyEncryptionPolicy(db, { account, policyFingerprint, keyId, key, initialize, allowRotated: Boolean(options.managedSchema), signal }); signal.throwIfAborted(); verified = snapshot; if (options.managedSchema) await assertPolicy(); @@ -132,18 +174,18 @@ export function createProtectedStorage(db, account, schemas, numericStorage = nu }), isUnlocked: async () => { if (!session.isUnlocked) return false; - await assertPolicy(); + await assertPolicy(false, false); return session.isUnlocked; }, state: async () => { await db.open(); - if (!verified) { + if (!verified && !rotation) { if (mismatch || !db.tables.some(table => table.name === encryptionMetadataStore)) return "PolicyMismatch"; return await db.table(encryptionMetadataStore).get(encryptionMetadataKey) === undefined ? "Uninitialized" : "Locked"; } try { - await assertPolicy(); + await assertPolicy(false, false); return session.isUnlocked ? "Unlocked" : "Locked"; } catch (error) { if (!error.message.startsWith("MAGIC_ENCRYPTION_POLICY_MISMATCH:") && @@ -152,18 +194,22 @@ export function createProtectedStorage(db, account, schemas, numericStorage = nu return "PolicyMismatch"; } }, - lock: () => session.lock(), + lock: () => { + rotation = undefined; + session.lock(); + }, dispose: () => { disposed = true; verified = undefined; readiness = undefined; + rotation = undefined; session.dispose(); } }; } class ProtectedTable { - constructor(db, account, name, policy, session, assertPolicy, assertLive, managed = false) { + constructor(db, account, name, policy, session, assertPolicy, assertLive, managed, getRotation) { this.db = db; this.table = db.table(name); this.account = account; @@ -172,6 +218,7 @@ class ProtectedTable { this.assertPolicy = assertPolicy; this.assertLive = assertLive; this.managed = managed; + this.getRotation = getRotation; } context(primaryKey) { @@ -213,7 +260,17 @@ class ProtectedTable { async access(operation) { try { - return await this.session.useKey(operation); + const rotation = this.getRotation(); + return await this.session.useKey((ordinary, assertSession) => { + const assertCurrent = () => { + assertSession(); + if (this.getRotation() !== rotation) + throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: Rotation access changed during the operation."); + rotation?.assertCurrent(); + }; + const keyId = rotation?.state.writeKeyId ?? ordinary.keyId; + return operation(rotation ? { key: rotation.keys.get(keyId), keyId, rotation } : ordinary, assertCurrent); + }); } catch (error) { if (error.message.startsWith("Magic encryption session is locked") || error.message.startsWith("Magic encryption session was locked")) { @@ -231,12 +288,26 @@ class ProtectedTable { const numeric = this.db.tables.find(table => table.name === numericMetadataStore); if (numeric) stores.push(numeric); } - return this.db.transaction("rw", stores, async () => { - await this.assertPolicy(); - this.assertLive(); - assertCurrent(); - return operation(this.table); - }); + const rotation = this.getRotation(); + let abort; + try { + return await this.db.transaction("rw", stores, async () => { + if (rotation?.signal) { + const transaction = this.db.constructor.currentTransaction; + abort = () => transaction.abort(); + rotation.signal.addEventListener("abort", abort, { once: true }); + rotation.signal.throwIfAborted(); + } + await this.assertPolicy(true); + this.assertLive(); + assertCurrent(); + const result = await operation(this.table); + assertCurrent(); + return result; + }); + } finally { + if (abort) rotation.signal.removeEventListener("abort", abort); + } } mutate(operation) { @@ -267,22 +338,32 @@ class ProtectedTable { return this.managed ? this.mutate(update) : this.fencedWrite(update); } + async openStoredRecord(row, primaryKey, { key, keyId, rotation }) { + const context = this.context(primaryKey); + return rotation ? (await openRotatingRecord(row, this.policy, rotation.keys, context)).record + : openRecord(row, this.policy, key, keyId, context); + } + async *query(predicate, additions, forceCursor, projection = null) { if (projection !== null) this.requirePublic(projection); + const rotation = this.getRotation(); // Even an empty full query requires an unlocked session. const lease = projection === null ? await this.access((_, assertCurrent) => assertCurrent) : null; this.validateQuery(predicate, additions); await this.db.open(); await this.assertPolicy(); for await (const row of magicQueryYield(this.db, this.table, predicate, additions, forceCursor)) { + if (projection !== null && this.managed) await this.assertPolicy(); + if (this.getRotation() !== rotation) + throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: Restart the stream after the rotation access change."); if (projection !== null) { this.assertLive(); yield Object.fromEntries(projection.filter(name => Object.hasOwn(row, name)).map(name => [name, row[name]])); continue; } this.assertLease(lease); - const opened = await this.access(({ key, keyId }) => - openRecord(row, this.policy, key, keyId, this.context(this.key(row)))); + const opened = await this.access(keys => this.openStoredRecord(row, this.key(row), keys)); + if (this.managed) await this.assertPolicy(); this.assertLease(lease); yield opened; } @@ -297,10 +378,13 @@ class ProtectedTable { } read(primaryKey) { - return this.access(async ({ key, keyId }) => { + return this.access(async (keys, assertCurrent) => { await this.assertPolicy(); const row = await this.table.get(primaryKey); - return row === undefined ? undefined : openRecord(row, this.policy, key, keyId, this.context(primaryKey)); + const opened = row === undefined ? undefined : await this.openStoredRecord(row, primaryKey, keys); + if (this.managed) await this.assertPolicy(); + assertCurrent(); + return opened; }); } } diff --git a/Magic.IndexedDb/wwwroot/utilities/rotationBatch.js b/Magic.IndexedDb/wwwroot/utilities/rotationBatch.js new file mode 100644 index 00000000..f8777bde --- /dev/null +++ b/Magic.IndexedDb/wwwroot/utilities/rotationBatch.js @@ -0,0 +1,121 @@ +// Native transactions here contain only IndexedDB requests. Prepare encryption +// or authentication before opening the write transaction. +const requestResult = request => new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); +}); + +const transactionDone = transaction => new Promise((resolve, reject) => { + transaction.oncomplete = resolve; + transaction.onabort = () => reject(transaction.error ?? new Error("Magic rotation transaction aborted.")); +}); + +function bytes(value) { + if (value instanceof ArrayBuffer) return new Uint8Array(value); + if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + return null; +} + +function sameStoredValue(left, right, ancestors = new WeakSet()) { + if (Object.is(left, right)) return true; + if (!left || !right || typeof left !== "object" || typeof right !== "object" || + Object.getPrototypeOf(left) !== Object.getPrototypeOf(right)) return false; + + const leftBytes = bytes(left); + if (leftBytes) { + const rightBytes = bytes(right); + return leftBytes.length === rightBytes.length && leftBytes.every((value, index) => value === rightBytes[index]); + } + if (left instanceof Date) return left.getTime() === right.getTime(); + if (Array.isArray(left) && left.length !== right.length) return false; + if (ancestors.has(left) || (!Array.isArray(left) && Object.getPrototypeOf(left) !== Object.prototype)) + throw new Error("MAGIC_ROTATION_RECORD_UNSUPPORTED: A stored representation cannot be compared safely."); + ancestors.add(left); + try { + const keys = Object.keys(left); + return keys.length === Object.keys(right).length && + keys.every(key => Object.hasOwn(right, key) && sameStoredValue(left[key], right[key], ancestors)); + } finally { + ancestors.delete(left); + } +} + +export async function readRotationBatch(db, storeName, afterKey, batchSize) { + if (!Number.isSafeInteger(batchSize) || batchSize < 1) throw new RangeError("Magic rotation requires a positive batch size."); + const range = afterKey === null ? null : IDBKeyRange.lowerBound(afterKey, true); + const tx = db.transaction(storeName, "readonly"); + const done = transactionDone(tx); + const rows = []; + try { + await new Promise((resolve, reject) => { + const cursor = tx.objectStore(storeName).openCursor(range); + cursor.onerror = () => reject(cursor.error); + cursor.onsuccess = () => { + const row = cursor.result; + if (!row) return resolve(); + rows.push({ key: row.primaryKey, record: row.value }); + if (rows.length === batchSize) resolve(); + else row.continue(); + }; + }); + await done; + } catch (error) { + await done.catch(() => {}); + throw error; + } + return rows; +} + +export async function readRotationEntries(db, storeName, keys) { + const transaction = db.transaction(storeName, "readonly"); + const done = transactionDone(transaction); + const store = transaction.objectStore(storeName); + try { + const values = await Promise.all(keys.map(key => requestResult(store.get(key)))); + await done; + return values; + } catch (error) { + await done.catch(() => {}); + throw error; + } +} + +// Check the exact authenticated metadata and stored rows before any writes. +// A concurrent delete, replacement, or public patch forces a fresh preparation. +export async function commitRotationBatch(db, expectations, writes, assertCurrent, signal) { + signal?.throwIfAborted(); + assertCurrent(); + const names = [...new Set([...expectations, ...writes].map(item => item.store))]; + const tx = db.transaction(names, "readwrite"); + const done = transactionDone(tx); + const abort = () => { + try { tx.abort(); } catch { /* The transaction already finished. */ } + }; + signal?.addEventListener("abort", abort, { once: true }); + try { + const current = await Promise.all(expectations.map(item => requestResult(tx.objectStore(item.store).get(item.key)))); + signal?.throwIfAborted(); + assertCurrent(); + if (!expectations.every((item, index) => sameStoredValue(item.value, current[index]))) { + await done; + return false; + } + + // Native record stores have inline keys. Metadata uses out-of-line keys. + await Promise.all(writes.map(item => { + const store = tx.objectStore(item.store); + if (item.delete === true) return requestResult(store.delete(item.key)); + return requestResult(store.keyPath === null ? store.put(item.value, item.key) : store.put(item.value)); + })); + signal?.throwIfAborted(); + assertCurrent(); + await done; + return true; + } catch (error) { + abort(); + await done.catch(() => {}); + throw error; + } finally { + signal?.removeEventListener("abort", abort); + } +} diff --git a/Magic.IndexedDb/wwwroot/utilities/rotationFence.js b/Magic.IndexedDb/wwwroot/utilities/rotationFence.js new file mode 100644 index 00000000..b5b7d42f --- /dev/null +++ b/Magic.IndexedDb/wwwroot/utilities/rotationFence.js @@ -0,0 +1,56 @@ +import { canonicalJson } from "../migrations/protocol.js"; +import { assertEncryptionKey, decryptValue, encryptValue } from "./encryptionEnvelope.js"; +import { encryptionMetadataKey, encryptionMetadataStore } from "./encryptionPolicy.js"; + +function context(vault, member) { + return { ...vault, store: encryptionMetadataStore, primaryKey: encryptionMetadataKey, member }; +} + +function fenceValue(state) { + // Batch checkpoints do not invalidate a foreground writer. Admission and + // entry to the verification barrier do. + return canonicalJson(["Magic.IndexedDb/rotation-fence", state.version, state.rotationId, + state.sourceKeyId, state.targetKeyId, state.mode, state.modelHash, state.policyFingerprint, + state.writeKeyId, state.priorKeyIds, state.phase]); +} + +export async function assertDistinctRotationKeys(source, target, sourceKeyId, vault, assertCurrent) { + assertEncryptionKey(source); + assertEncryptionKey(target); + assertCurrent(); + const challengeContext = context(vault, "rotation-key-challenge"); + const challenge = await encryptValue(null, source, sourceKeyId, challengeContext); + let same = true; + try { + await decryptValue(challenge, target, sourceKeyId, challengeContext); + } catch (error) { + if (error.cause?.name !== "OperationError") throw error; + same = false; + } + assertCurrent(); + if (same) throw new Error("MAGIC_ROTATION_KEY_REUSED: The target must be a different data encryption key."); +} + +export async function sealRotationFence(state, target, vault, assertCurrent) { + assertCurrent(); + // Keep the policy location and ordinary AAD layout. Legacy clients cannot + // interpret the authenticated rotation value as a normal protection policy. + const seal = await encryptValue(fenceValue(state), target, state.targetKeyId, context(vault, null)); + assertCurrent(); + return seal; +} + +export async function verifyRotationFence(seal, state, target, vault, assertCurrent) { + assertCurrent(); + let actual; + try { + actual = await decryptValue(seal, target, state.targetKeyId, context(vault, null)); + } catch { + assertCurrent(); + throw new Error("MAGIC_ROTATION_STATE_INVALID: The rotation fence could not be authenticated."); + } + assertCurrent(); + if (actual !== fenceValue(state)) { + throw new Error("MAGIC_ROTATION_STATE_INVALID: The rotation fence differs from the admitted state."); + } +} diff --git a/Magic.IndexedDb/wwwroot/utilities/rotationJournal.js b/Magic.IndexedDb/wwwroot/utilities/rotationJournal.js new file mode 100644 index 00000000..3b330a63 --- /dev/null +++ b/Magic.IndexedDb/wwwroot/utilities/rotationJournal.js @@ -0,0 +1,83 @@ +import { canonicalJson } from "../migrations/protocol.js"; +import { encryptValue, decryptValue } from "./encryptionEnvelope.js"; +import { encryptionMetadataStore } from "./encryptionPolicy.js"; + +export const rotationJournalKey = "key-rotation"; +const stateFields = new Set([ + "version", "rotationId", "sourceKeyId", "targetKeyId", "mode", "modelHash", "policyFingerprint", + "writeKeyId", "priorKeyIds", "sequence", "phase", "storeIndex", "afterKey", "converted", "verified", "paused" +]); +const modes = new Set(["exclusive", "read-only", "online"]); +const phases = new Set(["converting", "verifying"]); +const nonempty = value => typeof value === "string" && value.length > 0; +const natural = value => Number.isSafeInteger(value) && value >= 0; +const keyPart = value => typeof value === "string" || Number.isFinite(value); +const checkpoint = value => value === null || keyPart(value) || + Array.isArray(value) && value.length > 0 && value.every(keyPart); + +function invalidJournal() { + return new Error("MAGIC_ROTATION_STATE_INVALID: The rotation journal could not be authenticated."); +} + +function validateState(state) { + if (!state || Object.getPrototypeOf(state) !== Object.prototype || + Object.keys(state).length !== stateFields.size || Object.keys(state).some(name => !stateFields.has(name)) || + state.version !== 1 || !nonempty(state.rotationId) || !nonempty(state.sourceKeyId) || + !nonempty(state.targetKeyId) || state.sourceKeyId === state.targetKeyId || + !modes.has(state.mode) || !phases.has(state.phase) || state.writeKeyId !== state.targetKeyId || + !Array.isArray(state.priorKeyIds) || !state.priorKeyIds.every(nonempty) || + new Set(state.priorKeyIds).size !== state.priorKeyIds.length || + state.priorKeyIds.at(-1) !== state.sourceKeyId || state.priorKeyIds.includes(state.targetKeyId) || + !nonempty(state.modelHash) || !nonempty(state.policyFingerprint) || + ![state.sequence, state.storeIndex, state.converted, state.verified].every(natural) || + !checkpoint(state.afterKey) || typeof state.paused !== "boolean" || + state.phase === "converting" && state.verified !== 0) throw invalidJournal(); +} + +function context(vault, member) { + return { ...vault, store: encryptionMetadataStore, primaryKey: rotationJournalKey, member }; +} + +function canonicalState(state) { + validateState(state); + return canonicalJson(["Magic.IndexedDb/key-rotation", state]); +} + +function requiredKeys(state, keys) { + const source = keys.get(state.sourceKeyId); + const target = keys.get(state.targetKeyId); + if (!source || !target) throw new Error("MAGIC_ROTATION_KEY_UNAVAILABLE: Both authorized keys are required."); + return { source, target }; +} + +export async function sealRotationJournal(state, keys, vault, assertCurrent) { + const value = canonicalState(state); + const { source, target } = requiredKeys(state, keys); + assertCurrent(); + const [sourceSeal, targetSeal] = await Promise.all([ + encryptValue(value, source, state.sourceKeyId, context(vault, "source")), + encryptValue(value, target, state.targetKeyId, context(vault, "target")) + ]); + assertCurrent(); + return { state: structuredClone(state), sourceSeal, targetSeal }; +} + +export async function verifyRotationJournal(document, keys, vault, assertCurrent) { + const state = structuredClone(document?.state); + const value = canonicalState(state); + const { source, target } = requiredKeys(state, keys); + assertCurrent(); + let authenticated; + try { + authenticated = await Promise.all([ + decryptValue(document.sourceSeal, source, state.sourceKeyId, context(vault, "source")), + decryptValue(document.targetSeal, target, state.targetKeyId, context(vault, "target")) + ]); + } catch { + assertCurrent(); + throw invalidJournal(); + } + assertCurrent(); + if (authenticated.some(item => item !== value)) throw invalidJournal(); + return state; +} diff --git a/Magic.IndexedDb/wwwroot/utilities/rotationLifecycle.js b/Magic.IndexedDb/wwwroot/utilities/rotationLifecycle.js new file mode 100644 index 00000000..597f336f --- /dev/null +++ b/Magic.IndexedDb/wwwroot/utilities/rotationLifecycle.js @@ -0,0 +1,190 @@ +import { assertDatabaseReady, assertNumericPolicy, inspectOpen } from "../migrations/migrationEngine.js"; +import { canonicalJson, metadataStore, samePhysical, sha256 } from "../migrations/protocol.js"; +import { createProtectedMigrationAdapter, protectedStateKey, recoveryEvidenceKey, retainedRecoveries } from "../migrations/protectedMigrationAdapter.js"; +import { encryptValue } from "./encryptionEnvelope.js"; +import { serializePolicyDocument } from "./encryptionPolicyDocument.js"; +import { encryptionMetadataKey, encryptionMetadataStore } from "./encryptionPolicy.js"; +import { numericMetadataStore } from "./numericStorage.js"; +import { portableProtectionPolicy } from "./protectionPolicy.js"; +import { commitRotationBatch, readRotationEntries } from "./rotationBatch.js"; +import { rotationPassCount } from "./rotationPass.js"; +import { assertDistinctRotationKeys, sealRotationFence, verifyRotationFence } from "./rotationFence.js"; +import { rotationJournalKey, sealRotationJournal, verifyRotationJournal } from "./rotationJournal.js"; + +const policyEntry = value => ({ store: encryptionMetadataStore, key: encryptionMetadataKey, value }); +const rotationEntry = value => ({ store: encryptionMetadataStore, key: rotationJournalKey, value }); + +function unchangedReadyMetadata(db, ready) { + const checks = [ + { store: metadataStore, key: "state", value: ready.journal }, + { store: encryptionMetadataStore, key: protectedStateKey, value: ready.journalSeal } + ]; + if (db.objectStoreNames.contains(numericMetadataStore)) { + checks.push({ store: numericMetadataStore, key: "policy", value: ready.numericPolicy }); + } + return checks; +} + +async function recoveryEvidenceChecks(db, ready, verify, signal) { + const recoveries = retainedRecoveries(ready); + if (!recoveries.length) return []; + const keys = recoveries.map(entry => recoveryEvidenceKey(entry.recovery.id)); + const audits = await readRotationEntries(db, metadataStore, keys); + const checks = []; + for (const [index, entry] of recoveries.entries()) { + signal?.throwIfAborted(); + await verify(audits[index], entry); + checks.push({ store: metadataStore, key: keys[index], value: audits[index] }); + } + return checks; +} + +export function rotationCoordinator(db, signal, operation) { + if (!navigator.locks?.request) throw new Error("MAGIC_ROTATION_LOCK_UNAVAILABLE: Web Locks are required for managed rotation."); + // Schema migration and rotation serialize on the physical database, while + // ordinary operations enforce the persisted admission policy independently. + return navigator.locks.request(`magic-indexeddb:migrate:${db.name}`, { mode: "exclusive", signal }, operation); +} + +export async function admitRotation({ + db, vault, ready, schema, authorization, keys, targetKeyId, mode, recoverable, signal +}) { + const { assertCurrent, keyId: sourceKeyId } = authorization; + signal?.throwIfAborted(); + assertCurrent(); + if (db.name !== vault.database || authorization.account !== vault.account) { + throw new Error("MAGIC_ROTATION_STATE_INVALID: The authorization belongs to another vault."); + } + if (recoverable !== true) { + throw new Error("MAGIC_ROTATION_KEYS_NOT_RECOVERABLE: The provider must attest recovery of both keys."); + } + if (sourceKeyId === targetKeyId) { + throw new Error("MAGIC_ROTATION_KEY_REUSED: The target key identifier was previously used."); + } + const source = keys.get(sourceKeyId); + const target = keys.get(targetKeyId); + if (!source || !target) throw new Error("MAGIC_ROTATION_KEY_UNAVAILABLE: Both authorized keys are required."); + + await assertDatabaseReady(db, ready, authorization); + const sourceProof = await createProtectedMigrationAdapter({ + name: vault.database, account: vault.account, keyId: sourceKeyId, key: source, assertCurrent, signal + }); + await sourceProof.verifyPolicy(ready.policySeal, schema); + // Detect damaged or historically unsealed evidence before fencing CRUD. + const auditChecks = await recoveryEvidenceChecks(db, ready, sourceProof.openRetainedRecoveryEvidence, signal); + const priorKeyIds = sourceProof.keyLineage?.generations ?? [sourceKeyId]; + if (priorKeyIds.includes(targetKeyId)) + throw new Error("MAGIC_ROTATION_KEY_REUSED: The target key identifier was previously used."); + await assertDistinctRotationKeys(source, target, sourceKeyId, vault, assertCurrent); + const { policyFingerprint } = portableProtectionPolicy(schema); + const state = { + version: 1, rotationId: crypto.randomUUID(), sourceKeyId, targetKeyId, mode, writeKeyId: targetKeyId, + modelHash: ready.schemaHash, policyFingerprint, priorKeyIds, sequence: 0, phase: "converting", + storeIndex: 0, afterKey: null, converted: 0, verified: 0, paused: false + }; + const [document, fence] = await Promise.all([ + sealRotationJournal(state, keys, vault, assertCurrent), + sealRotationFence(state, target, vault, assertCurrent) + ]); + const checks = unchangedReadyMetadata(db, ready); + if (!await commitRotationBatch(db, [...checks, ...auditChecks, policyEntry(ready.policySeal), rotationEntry(undefined)], + [policyEntry(fence), rotationEntry(document)], assertCurrent, signal)) { + throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: The vault changed before rotation admission."); + } + return { document, fence, checks }; +} + +export async function enterRotationVerification({ db, vault, ready, schema, document, fence, checks, keys, assertCurrent, signal }) { + const state = await verifyRotationJournal(document, keys, vault, assertCurrent); + const target = keys.get(state.targetKeyId); + await verifyRotationFence(fence, state, target, vault, assertCurrent); + const { policies } = portableProtectionPolicy(schema); + const storeCount = rotationPassCount(policies, ready); + if (state.phase !== "converting" || state.storeIndex !== storeCount || state.afterKey !== null || state.paused) { + throw new Error("MAGIC_ROTATION_STATE_INVALID: Conversion has not completed."); + } + + const verifying = { ...state, phase: "verifying", sequence: state.sequence + 1, storeIndex: 0 }; + const [prepared, barrier] = await Promise.all([ + sealRotationJournal(verifying, keys, vault, assertCurrent), + sealRotationFence(verifying, target, vault, assertCurrent) + ]); + if (!await commitRotationBatch(db, [...checks, policyEntry(fence), rotationEntry(document)], + [policyEntry(barrier), rotationEntry(prepared)], assertCurrent, signal)) { + throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: The vault changed before verification."); + } + return { document: prepared, fence: barrier, checks }; +} + +export async function finishRotation({ + db, vault, ready, schema, document, fence, checks, keys, assertCurrent, signal +}) { + const state = await verifyRotationJournal(document, keys, vault, assertCurrent); + const target = keys.get(state.targetKeyId); + await verifyRotationFence(fence, state, target, vault, assertCurrent); + const { policies, policyFingerprint } = portableProtectionPolicy(schema); + if (state.phase !== "verifying" || state.storeIndex !== rotationPassCount(policies, ready) || state.afterKey !== null || + state.paused || state.policyFingerprint !== policyFingerprint || state.modelHash !== ready.schemaHash) { + throw new Error("MAGIC_ROTATION_STATE_INVALID: Target-only verification is incomplete."); + } + const lineage = { + generations: [...state.priorKeyIds, state.targetKeyId], + completed: { rotationId: state.rotationId, converted: state.converted, verified: state.verified } + }; + const adapter = await createProtectedMigrationAdapter({ + name: vault.database, account: vault.account, keyId: state.targetKeyId, key: target, assertCurrent, signal + }); + // Compare target-authenticated audit envelopes in the final transaction + // too, so removing or replacing a verified audit cannot retire its key. + const auditChecks = await recoveryEvidenceChecks(db, ready, adapter.verifyRecoveryEvidence, signal); + + const [policySeal, journalSeal] = await Promise.all([ + encryptValue(serializePolicyDocument(policyFingerprint, lineage), target, state.targetKeyId, + { ...vault, store: encryptionMetadataStore, primaryKey: encryptionMetadataKey, member: null }), + adapter.sealState(ready.journal) + ]); + if (!await commitRotationBatch(db, [...checks, ...auditChecks, policyEntry(fence), rotationEntry(document)], + [policyEntry(policySeal), { store: encryptionMetadataStore, key: protectedStateKey, value: journalSeal }, + { store: encryptionMetadataStore, key: rotationJournalKey, delete: true }], assertCurrent, signal)) { + throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: The vault changed before finalization."); + } + return { ready: { ...ready, policySeal, journalSeal }, lineage }; +} + +export async function openRotation({ db, vault, schema, authorization, keys }) { + const { assertCurrent } = authorization; + const snapshot = await inspectOpen(db, rotationJournalKey); + if (!snapshot.rotation) return null; + const state = await verifyRotationJournal(snapshot.rotation, keys, vault, assertCurrent); + const { policyFingerprint } = portableProtectionPolicy(schema); + const expectedHash = await sha256(canonicalJson(schema)); + if (db.name !== vault.database || authorization.account !== vault.account || + state.sourceKeyId !== authorization.keyId || snapshot.state?.status !== "ready" || + snapshot.state.protocolVersion !== 3 || snapshot.state.schemaId !== schema.schemaId || + state.modelHash !== expectedHash || state.modelHash !== snapshot.state.schemaHash || + state.policyFingerprint !== policyFingerprint || !samePhysical(snapshot.stores, schema)) { + throw new Error("MAGIC_ROTATION_STATE_INVALID: The rotation does not match the installed vault model."); + } + assertNumericPolicy(snapshot, schema); + await authorization.verifyState(snapshot.protectionState, snapshot.state); + await verifyRotationFence(snapshot.protectionPolicy, state, keys.get(state.targetKeyId), vault, assertCurrent); + + const ready = { + name: db.name, schemaId: schema.schemaId, revision: snapshot.state.revision, schemaHash: expectedHash, + nativeVersion: snapshot.nativeVersion, protocolVersion: 3, history: snapshot.state.history, + journal: snapshot.state, journalSeal: snapshot.protectionState, numericPolicy: snapshot.numericPolicy, + policySeal: snapshot.protectionPolicy + }; + return { ready, document: snapshot.rotation, fence: snapshot.protectionPolicy, checks: unchangedReadyMetadata(db, ready) }; +} + +export async function setRotationPaused({ db, vault, document, fence, checks, keys, paused, assertCurrent, signal }) { + const state = await verifyRotationJournal(document, keys, vault, assertCurrent); + if (state.paused === paused) return { document, fence, checks }; + const next = await sealRotationJournal({ ...state, paused, sequence: state.sequence + 1 }, keys, vault, assertCurrent); + if (!await commitRotationBatch(db, [...checks, policyEntry(fence), rotationEntry(document)], + [rotationEntry(next)], assertCurrent, signal)) { + throw new Error("MAGIC_ROTATION_CONCURRENT_CHANGE: The vault changed before rotation pause or resume."); + } + return { document: next, fence, checks }; +} diff --git a/Magic.IndexedDb/wwwroot/utilities/rotationPass.js b/Magic.IndexedDb/wwwroot/utilities/rotationPass.js new file mode 100644 index 00000000..b765c6db --- /dev/null +++ b/Magic.IndexedDb/wwwroot/utilities/rotationPass.js @@ -0,0 +1,105 @@ +import { metadataStore } from "../migrations/protocol.js"; +import { createProtectedMigrationAdapter, recoveryEvidenceKey, retainedRecoveries } from "../migrations/protectedMigrationAdapter.js"; +import { commitRotationBatch, readRotationBatch, readRotationEntries } from "./rotationBatch.js"; +import { encryptionMetadataStore } from "./encryptionPolicy.js"; +import { rotationJournalKey, sealRotationJournal, verifyRotationJournal } from "./rotationJournal.js"; +import { openRotatingRecord, prepareRotatedRecord } from "./rotationRecord.js"; + +const protectedStores = policies => [...policies].filter(([, policy]) => policy.exposed !== null || policy.fields.size > 0); + +const hasRecoveryEvidence = ready => ready?.history.some(entry => entry.outcome === "recovered") ?? false; + +export function rotationPassCount(policies, ready) { + return protectedStores(policies).length + Number(hasRecoveryEvidence(ready)); +} + +async function prepareRecoveryEvidence({ db, ready, vault, state, keys, assertCurrent, signal, batchSize }) { + const entries = retainedRecoveries(ready).map(entry => ({ entry, key: recoveryEvidenceKey(entry.recovery.id) })); + entries.sort((left, right) => left.key < right.key ? -1 : Number(left.key > right.key)); + const start = state.afterKey === null ? 0 : entries.findIndex(item => item.key === state.afterKey) + 1; + if (state.afterKey !== null && start === 0) throw new Error("MAGIC_ROTATION_STATE_INVALID: Invalid recovery evidence checkpoint."); + const batch = entries.slice(start, start + batchSize); + if (!batch.length) return { afterKey: null, comparisons: [], writes: [] }; + const adapter = keyId => createProtectedMigrationAdapter({ name: vault.database, account: vault.account, + keyId, key: keys.get(keyId), assertCurrent, signal }); + const target = await adapter(state.targetKeyId); + const source = state.phase === "converting" ? await adapter(state.sourceKeyId) : null; + const records = await readRotationEntries(db, metadataStore, batch.map(item => item.key)); + const comparisons = []; + const writes = []; + for (const [index, { entry, key }] of batch.entries()) { + signal?.throwIfAborted(); + const value = records[index]; + comparisons.push({ store: metadataStore, key, value }); + if (source && value?.keyId !== state.targetKeyId) { + writes.push({ store: metadataStore, key, value: await target.rotateRecoveryEvidence(value, entry, source) }); + } else { + await target.verifyRecoveryEvidence(value, entry); + } + } + return { afterKey: batch.at(-1).key, comparisons, writes }; +} + +// The caller acquires an authenticated ready-state snapshot and the vault +// coordinator. This step still compares persisted state inside the write +// transaction because an advisory coordinator cannot fence other writers. +export async function advanceRotationPass({ + db, vault, document, keys, policies, ready, expectations, batchSize, assertCurrent, signal +}) { + signal?.throwIfAborted(); + const state = await verifyRotationJournal(document, keys, vault, assertCurrent); + if (state.paused) return { outcome: "paused", document }; + + const stores = protectedStores(policies); + const count = stores.length + Number(hasRecoveryEvidence(ready)); + if (state.storeIndex > count || state.storeIndex === count && state.afterKey !== null) { + throw new Error("MAGIC_ROTATION_STATE_INVALID: The rotation cursor is outside the authenticated model."); + } + if (state.storeIndex === count) return { outcome: "pass-complete", document }; + + const evidence = state.storeIndex === stores.length; + const batch = evidence + ? await prepareRecoveryEvidence({ db, ready, vault, state, keys, assertCurrent, signal, batchSize }) + : await prepareApplicationRows({ db, vault, state, keys, batchSize, assertCurrent, signal, + storePolicy: stores[state.storeIndex] }); + const comparisons = [...expectations, { store: encryptionMetadataStore, key: rotationJournalKey, value: document }, + ...batch.comparisons]; + const next = { + ...state, + sequence: state.sequence + 1, + storeIndex: state.storeIndex + (batch.afterKey === null ? 1 : 0), + afterKey: batch.afterKey, + converted: state.converted + (evidence ? 0 : batch.writes.length), + verified: state.verified + (evidence ? 0 : batch.verified) + }; + const writes = batch.writes; + const prepared = await sealRotationJournal(next, keys, vault, assertCurrent); + writes.push({ store: encryptionMetadataStore, key: rotationJournalKey, value: prepared }); + if (!await commitRotationBatch(db, comparisons, writes, assertCurrent, signal)) { + return { outcome: "retry", document }; + } + return { outcome: "advanced", document: prepared }; +} + +async function prepareApplicationRows({ db, vault, state, keys, batchSize, assertCurrent, signal, storePolicy }) { + const [store, policy] = storePolicy; + const rows = await readRotationBatch(db, store, state.afterKey, batchSize); + const comparisons = []; + const writes = []; + let verified = 0; + const verificationKeys = state.phase === "verifying" ? new Map([[state.targetKeyId, keys.get(state.targetKeyId)]]) : null; + for (const row of rows) { + signal?.throwIfAborted(); + assertCurrent(); + const context = { ...vault, store, primaryKey: row.key }; + if (verificationKeys) { + await openRotatingRecord(row.record, policy, verificationKeys, context); + verified++; + } else { + const converted = await prepareRotatedRecord(row.record, policy, keys, state.targetKeyId, context); + if (converted !== null) writes.push({ store, key: row.key, value: converted }); + } + comparisons.push({ store, key: row.key, value: row.record }); + } + return { afterKey: rows.length ? rows.at(-1).key : null, comparisons, writes, verified }; +} diff --git a/Magic.IndexedDb/wwwroot/utilities/rotationRecord.js b/Magic.IndexedDb/wwwroot/utilities/rotationRecord.js new file mode 100644 index 00000000..3a83d338 --- /dev/null +++ b/Magic.IndexedDb/wwwroot/utilities/rotationRecord.js @@ -0,0 +1,38 @@ +import { encryptedRecordMember, openRecord, sealRecord } from "./encryptionRecord.js"; + +function recordGeneration(record, policy) { + const members = policy.exposed !== null ? [encryptedRecordMember] : [...policy.fields]; + if (!members.length) return null; + + const keyId = record[members[0]]?.keyId; + if (typeof keyId !== "string" || !keyId || members.some(member => record[member]?.keyId !== keyId)) { + throw new Error("MAGIC_ROTATION_RECORD_INVALID: The protected record has inconsistent key identifiers."); + } + return keyId; +} + +// A stored key identifier only selects a candidate key. Every protected member +// must still authenticate to that key and its original IndexedDB location. +export async function openRotatingRecord(record, policy, authorizedKeys, context) { + const keyId = recordGeneration(record, policy); + if (keyId === null) return { record, keyId }; + + const key = authorizedKeys.get(keyId); + if (!key) throw new Error("MAGIC_ROTATION_KEY_UNAVAILABLE: An authorized record key is required."); + + try { + return { record: await openRecord(record, policy, key, keyId, context), keyId }; + } catch { + throw new Error("MAGIC_ROTATION_RECORD_INVALID: The protected record could not be authenticated."); + } +} + +export async function prepareRotatedRecord(record, policy, authorizedKeys, targetKeyId, context) { + const targetKey = authorizedKeys.get(targetKeyId); + if (!targetKey) throw new Error("MAGIC_ROTATION_KEY_UNAVAILABLE: The authorized target key is required."); + + const opened = await openRotatingRecord(record, policy, authorizedKeys, context); + if (opened.keyId === null || opened.keyId === targetKeyId) return null; + + return sealRecord(opened.record, policy, targetKey, targetKeyId, context); +} diff --git a/README.md b/README.md index 3b8c77e3..9a427c55 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,8 @@ This is a breaking major release: old all-tables deployment becomes explicit membership, and existing databases require a reviewed adoption path. Version 3 includes [authenticated migrations](docs/guides/encrypted-migrations.md), including adding and removing record protection while preserving database identity. -Data-key rotation, numeric codec cutovers, and key-changing resumable migrations -remain unsupported. See [test and release acceptance](docs/contributing/migration-testing.md) +[Managed key rotation](docs/guides/managed-key-rotation.md) is separate from schema migrations. +Numeric codec cutovers and key-changing resumable migrations remain unsupported. See [test and release acceptance](docs/contributing/migration-testing.md) and the [implementation handoff](docs/engineering/v3-handoff.md). ## Why use Magic IndexedDB? diff --git a/docs/README.md b/docs/README.md index e91907e8..575ebacc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -28,6 +28,7 @@ Start with the four pages below. The guides and reference pages are there when y - [Schema evolution](guides/schema-evolution.md) — model and persisted-data change planning - [Managed migrations](guides/migrations.md) — static assets, readiness, events, and recovery - [Encrypted migrations](guides/encrypted-migrations.md) — authorization, protection changes, and in-place enrollment +- [Managed key rotation](guides/managed-key-rotation.md) — availability, resumability, and key retirement - [Legacy writer cutover](guides/legacy-writer-cutover.md) - [Migration CLI](guides/migration-cli.md) — tool installation, project export, validation, and publication - [Migration schema declarations](guides/migration-schema.md) — default/explicit membership and shared C# model export @@ -50,6 +51,7 @@ Start with the four pages below. The guides and reference pages are there when y - [Migration protocol and capabilities](architecture/migration-protocol.md) - [Partial migration recovery](architecture/adr-partial-migration-recovery.md) - [Authenticated migration contract](architecture/adr-authenticated-migrations.md) +- [Managed key rotation contract](architecture/adr-managed-key-rotation.md) - [Version 3 implementation contract](architecture/v3-implementation-contract.md) ## Contributing diff --git a/docs/architecture/adr-authenticated-migrations.md b/docs/architecture/adr-authenticated-migrations.md index 4789a1ee..e331acac 100644 --- a/docs/architecture/adr-authenticated-migrations.md +++ b/docs/architecture/adr-authenticated-migrations.md @@ -44,13 +44,13 @@ Changing only protection does not require handwritten crypto or a custom JavaScript transform. The built-in operation is: ```json -{"op":"reprotect","store":"supportLogs"} +{"op":"reprotect","store":"documents"} ``` A declassification decision belongs to the affected store operation: ```json -{"op":"reprotect","store":"supportLogs","allowProtectionLoss":true} +{"op":"reprotect","store":"documents","allowProtectionLoss":true} ``` The same decision can accompany a custom `transform` or another supported data diff --git a/docs/architecture/adr-managed-key-rotation.md b/docs/architecture/adr-managed-key-rotation.md new file mode 100644 index 00000000..27a4e7ed --- /dev/null +++ b/docs/architecture/adr-managed-key-rotation.md @@ -0,0 +1,110 @@ +# Managed data encryption key rotation + +Status: implementation under validation. + +## Existing boundaries + +The browser engine owns IndexedDB transactions. AES-GCM envelope version 1 already +authenticates the key ID alongside the origin, physical database, account, store, +native primary key and protected member. Existing field and whole-record formats +can carry a new generation without rewriting unchanged databases. Reuse +`encryptionRecord.js` for the protected record representation and preserve native +keys, public indexes, public field values and lossless numeric wire values. + +Managed vaults already authenticate their protection policy and migration journal. +Protected writers compare the authenticated policy and journal snapshots in the +write transaction. Reuse that boundary for rotation admission, while keeping +rotation progress separate from schema revisions. The C# provider keeps key +custody and resolves generation IDs. It must explicitly attest that both keys +can be reacquired after restart. The library verifies usable keys and +authentication locally. It cannot verify the provider's future availability. + +## Admission and authorization + +Rotate a ready authenticated managed vault, independently of its schema or native +IndexedDB version. An uninitialized vault, an unresolved migration or recovery, +a conflicting rotation, a reused generation ID, or a target key that cannot be +recovered under the provider contract fails before record mutation. + +Admission atomically replaces the existing policy sentinel with an authenticated +rotation fence, publishes the target write generation and adds a rotation +journal. Compare the previous authenticated policy, migration proof, journal, +numeric metadata and layout before committing. An older cooperating connection +will reject the changed sentinel in its existing transactional guard. An older +reopening engine cannot interpret the rotation sentinel as an ordinary policy. +Uncooperative raw IndexedDB writers require an application-owned cutover. + +Bind each rotation to the vault/account identity, original and target generations, +verified schema/model identity, immutable mode and operation identity. A dual-key +transition proof binds both keys to the same admission and progress state. +A generation ID is a routing hint until AES-GCM authenticates the envelope +against its key and storage context. Retain authenticated generation lineage so +a previously used ID cannot be bound to a different key. Detect modification, +mismatched proof and checkpoint replacement relative to the admitted session. +Restoring a complete internally consistent old storage snapshot cannot be +detected without a trusted freshness anchor outside local storage. + +## Access and transaction invariants + +| Mode | Reads | Mutations | +| --- | --- | --- | +| Exclusive | Fenced | Fenced | +| Read-only | Authorized dual-generation reads | Fenced | +| Online | Authorized dual-generation reads | Target-generation only | + +The coordinator is scoped to a vault; Web Locks may serialize coordinators, but +the persisted state comparison in each transaction enforces correctness. All CRUD +entry points, including deletes, bulk writes and public patches, enforce the +same state guards. A write prepared before a generation or authorization change +must abort when its transaction observes that change. Reads and streams check +the applicable fence and authorization before releasing data. A stream may fail +during transitions and can be restarted; it must stop releasing newly acquired +data once its authorization is invalid. + +Capture bounded native cursor batches and prepare cryptography outside the +write transaction. Compare the complete current stored snapshot and the exact +authenticated progress snapshot inside the transaction before writing. A +concurrent delete remains deleted. A concurrent target write survives. A public +patch requires retry from the current snapshot when it changes the record +contents used by the conversion. A checkpoint advances only with committed +record writes or with proof that a skipped record is now target generation or +absent. Keep reads and mutations on unrelated databases independent. Do not +expose keys, plaintext, or native checkpoint keys in diagnostics. + +## Resume and retirement + +Pause, interruption, cancellation or lock retains atomic checkpoints and the +selected availability mode. Resume authenticates persisted admission and +progress and reacquires required keys. Missing authorization, wrong keys and +integrity errors must leave the vault recoverable, without deleting or silently +recreating data. Lock revokes the browser session and its pending operations; +cancelling a .NET wait remains distinct from aborting browser work. + +A finalization fence blocks writes long enough to establish a complete, +resumable authentication pass with the target key. Cursor completion alone +never permits retirement. Finalization commits the target-only active policy, +reseals managed authentication metadata and commits retirement evidence +atomically. Admission authenticates retained recovery evidence before fencing access. +Retained encrypted recovery evidence is part of conversion and target-only +verification. The pass follows the authenticated history's recovery bindings and +commits each audit rewrite with its checkpoint. Finalization compares the +target-authenticated evidence in the metadata transaction. Historical v3.0 +envelopes are opened under their old binding, checked against the original and +recovery identities and digests, and resealed for their actual metadata slot. +Reported record counts describe application records only. + +Subsequent managed migrations must preserve authenticated generation +lineage. Reopening a completed vault requires only the target key. Logical +readiness for retirement applies to the active managed vault and supported +cooperating connections. It is separate from provider key destruction, +backup retention, physical storage erasure and other contexts' memory. + +## Acceptance + +Exercise each mode at every transaction boundary in real IndexedDB and Web +Crypto. Cover mixed generations, all write routes, concurrent coordinators, +stale snapshots, revocation, tampering, crash or page termination, target-only +reopen, genuine stable-package adoption, and later authenticated migration. +The hosted matrix must include Chromium, Firefox, Linux and macOS WebKit and +published trimmed/AOT Blazor. Benchmarks should measure conversion, verification +and foreground latency without setting timing-sensitive pass thresholds. diff --git a/docs/engineering/protected-migrations-handoff.md b/docs/engineering/protected-migrations-handoff.md index 02cf0f7c..1c7457a9 100644 --- a/docs/engineering/protected-migrations-handoff.md +++ b/docs/engineering/protected-migrations-handoff.md @@ -57,11 +57,9 @@ exact-candidate JSON/JUnit and published probe reports to distinguish executed browser and trimmed/AOT coverage from compilation alone. For local setups, see the [testing guide](../contributing/migration-testing.md). -## Required work for the validating agent +## Validation procedures -Use the existing source checkout. Fetch the branch, preserve unrelated work, and -record its exact SHA before testing. Review the implementation, tests, and docs -against the invariants below. Record any failure and its focused regression. +Record the checkout SHA and verify the tests and implementation against the invariants below. ### 1. Execute the mandatory gates on the same final commit @@ -69,7 +67,7 @@ Run the ordinary unit/browser gates, portable protocol/crypto suite, actual packed-and-installed CLI tests, the configured native migration browser suite, and the published trimmed/AOT Blazor fixtures. Use all four CI browser configurations. The runner intentionally fails on missing cases and skipped -required fixture modes. The configured native suite currently requires 126 cases +required fixture modes. The configured native suite currently requires 134 cases per browser; the published matrix requires 13 per browser and build mode (104 total). Verify these counts from code and reports, not from earlier approvals. @@ -162,22 +160,3 @@ cross-database moves, numeric-format changes and repair of a failed recovery remain unsupported. A whole internally consistent storage-snapshot replay cannot be detected without an external monotonic authority. Preserve these boundaries and call out any proposed API/protocol expansion for independent review. - -## Required response to bring back for peer review - -1. PR/branch and exact tested SHA; list any changes made after the last full run. -2. A matrix of actual pass/fail/skip/executed counts, commands, SDK/browser/OS - versions and links to CI/evidence artifacts. Separate local, CI and unexecuted - scenarios. -3. Every defect: reproducible failure, root cause, fix, focused regression and - commit. Include security/integrity findings even if all current tests passed. -4. Data-preservation evidence for every protection direction, adoption path, - interruption/recovery stage and published trimmed/AOT lifecycle exercised. -5. Any changes to public API, protocol, error/event semantics or compatibility. -6. Remaining blockers, known unsupported features and optional improvements in - separate categories. Identify the application-owned release decisions. -7. A clear recommendation: ready for another independent review, ready for stable - release, or not ready, with the specific evidence supporting it. - -Do not merge the PR or publish either package. The maintainer will return your -report to the original reviewer and decide the next step. diff --git a/docs/engineering/v3-handoff.md b/docs/engineering/v3-handoff.md index e5b59bfe..a1c608d3 100644 --- a/docs/engineering/v3-handoff.md +++ b/docs/engineering/v3-handoff.md @@ -90,22 +90,5 @@ remain unverified. - Review the [implemented bounded recovery contract](../architecture/adr-partial-migration-recovery.md). A deterministic failure requires developer intervention and an explicitly approved package. An ordinary later revision starts only after recovery commits. - Keep resumable and recovery support in preview pending implementation acceptance. -- Keep the preview PR draft. The maintainer owns final release and separate - verification of the trusted publisher scopes. - -## Required response for peer review - -Return a concise executive status followed by: - -1. PR/branch and exact tested commit SHA; any later untested changes. -2. Test matrix with pass/fail/skip/executed counts, commands, environments, and evidence. -3. Every bug found: reproducer, original failure, root cause, fix, regression, commit. -4. Data-preservation findings: old package/baseline versions, rows/invariants tested, - atomic rollback, resumable restart, native schema/policy/journal consistency. -5. API/protocol decisions or compatibility changes needing the maintainer's judgment. -6. Remaining blockers and unsupported operations, separated from optional polish. -7. A merge-readiness recommendation with concrete evidence; do not merge yourself. - -The user will bring that response back to the original agent for an independent peer -review and another iteration. + Validate resumable migration and recovery against the application’s actual rollout conditions. +- Verify trusted publishing scopes for both package IDs before publishing. diff --git a/docs/guides/managed-key-rotation.md b/docs/guides/managed-key-rotation.md new file mode 100644 index 00000000..a71c7ee3 --- /dev/null +++ b/docs/guides/managed-key-rotation.md @@ -0,0 +1,121 @@ +# Rotate a managed database's encryption key + +Use key rotation after opening an authenticated managed database. Rotation does +not change the schema revision, move the database, or rewrite its public keys and +indexes. Rewrapping the same data key with a new password, PIN, or wrapping key is +an application operation and does not require this API. + +## C# quick start + +Implement `IMagicEncryptionRotationKeyProvider` on the application's existing +provider. The same provider should resolve both IDs and attest that it can +reacquire both keys after a browser restart. The library checks the supplied keys +against authenticated vault state. The provider controls user authorization, +wrapped key persistence, backups and permanent retirement. + +```csharp +await context.Encryption.EnsureUnlockedAsync(database); +var result = await context.KeyRotation.RotateEncryptionKeyAsync( + database, new("generation-2", MagicKeyRotationMode.Online, BatchSize: 128)); + +if (result.RetirementReady) +{ + // Apply the application's backup and retirement policy for result.SourceKeyId. +} +``` + +Use opaque browser AES-GCM keys when feasible. Raw 32-byte provider values are +accepted through the existing key wrapper. Neither raw keys nor decrypted values +are written to rotation metadata or progress diagnostics. + +## Choose availability + +- **Exclusive** is the default. Ordinary operations on this vault reject while + rotation is active. Resume or finish rotation, then retry the operation. +- **ReadOnly** preserves authorized reads while both generations coexist. Record + mutations, including deletes and public-field patches, reject. +- **Online** preserves authorized reads and mutations during conversion. New + writes use the target key. Final verification rejects writes in all modes until the target-only scan + completes. Retry an interrupted write after the vault is available. + +Application code that receives a rotation fence or authenticated readiness +change can reauthorize and retry. +A stream invalidated by authorization or a phase change should restart. Unrelated +vaults continue operating. Retire raw or otherwise uncooperative IndexedDB writers +before starting. Use the [legacy writer cutover](legacy-writer-cutover.md) when +deploying to an origin with older application shells. + +## Observe, cancel, and resume + +`GetKeyRotationStatusAsync` reports the authenticated phase, available operations, +committed conversion and verification totals, and retirement readiness. Counts +are committed work totals. They are not an estimate of remaining records during +online rotation. + +`CancelKeyRotationAsync` aborts work in the current browser context. It preserves +committed checkpoints and availability. `PauseKeyRotationAsync` persists the pause. +When ready to continue, unlock with the rotation-capable provider and call +`ResumeKeyRotationAsync`. Set `MagicEncryptionOptions.ResumeKeyRotationOnUnlock` +to schedule background resumption on unlock. An explicit pause still requires +an explicit resume. Existing `ObserveMigrationsAsync` subscriptions receive +`key-rotation` events with metadata in `Details["rotation"]`. + +A .NET caller's cancellation token cancels its wait. +Lock the vault to revoke browser authorization and pending work. Missing keys and +invalid authentication leave the vault fenced until correct authorization is available. + +Rotation is offline when the existing managed registration and application-owned +key-provider dependencies are available offline. The application owns recovery if +a required key is lost. Do not destroy either key while the rotation is incomplete. + +## JavaScript + +The browser APIs use the logical route registered by `createDb`. Unlock and +initialize the managed vault before calling `rotateManagedEncryptionKey`. + +```js +const stop = api.subscribeKeyRotationEvents(({ phase, converted }) => { + console.log(phase, converted); +}); +try { + const status = await api.rotateManagedEncryptionKey(route, + { targetKeyId, mode: "online", batchSize: 128, recoverable: true }, targetKey); + // status.retirementReady applies to the active managed vault. +} finally { + stop(); +} +``` + +After reload, get routing hints with `getManagedEncryptionKeyHints`, independently +authorize the requested keys, then supply them with `authorizeManagedKeyRotation`. +Hints are untrusted until the browser authenticates the journal and policy fence. +Call `resumeManagedEncryptionKeyRotation` to continue. Use +`pauseManagedEncryptionKeyRotation` or `cancelManagedEncryptionKeyRotation` to stop +the current attempt. Progress events report metadata only, after commit. + +## Retirement and tuning + +Retirement readiness follows a verified target-only scan and atomic finalization. +It applies to the active vault. Retain old keys required by backups and exports. +The browser cannot prove physical erasure or detect replay of a complete consistent +storage snapshot without an external trusted freshness anchor. + +Rotation includes retained encrypted audit evidence from authenticated migration +recovery. Missing or invalid audit evidence blocks retirement. If an older +runtime enrolled a previously recovered plaintext managed database and left its +audit evidence unsealed, rotation cannot establish that evidence's authenticity +and rejects admission. Existing access remains available under the original +policy. New authenticated enrollments seal retained plaintext evidence during +enrollment. + +Rotation compares portable stored records, including native dates and byte arrays. +Unsupported values written by external IndexedDB clients, such as cyclic +structures or maps, stop conversion without committing the affected batch. Keep +both keys and address the incompatible data with the application’s recovery policy. + +Start with 128 records per batch. Reduce the batch size for large records or +foreground contention, and enable yielding if the application needs more +responsiveness. Larger batches can reduce transaction overhead but increase +preparation memory and retry work. Rotation and schema migration serialize on the +physical vault. Complete rotation from the admitting deployment before applying a newer manifest or managed schema. +See the [architecture contract](../architecture/adr-managed-key-rotation.md). diff --git a/docs/licensing/faq.md b/docs/licensing/faq.md index 35ef0d20..441a0bec 100644 --- a/docs/licensing/faq.md +++ b/docs/licensing/faq.md @@ -244,7 +244,7 @@ Where possible, tell us: Additional information may be requested where necessary. -You should not send confidential patient information, sensitive client records, passwords, or unrelated proprietary information as part of your inquiry. +You should not send confidential records, credentials, or unrelated proprietary information as part of your inquiry. ### Where do I request permission? diff --git a/docs/licensing/request-authorization.md b/docs/licensing/request-authorization.md index d98e64ce..62c786d4 100644 --- a/docs/licensing/request-authorization.md +++ b/docs/licensing/request-authorization.md @@ -2,6 +2,6 @@ Restricted does not mean unwelcome. We welcome inquiries about related and competing applications, and authorization may be free or paid, depending on the project. No fee, registration, or permission request is required for otherwise permitted uses. -Contact Sayou using the contact information at [sayou.io](https://sayou.io). Include your organization or name, a contact method, the product or project and its intended users, the proposed role of Magic IndexedDB, anticipated versions, and whether the application is internal, distributed, or hosted. Please do not send patient records, credentials, or sensitive proprietary information. +Contact Sayou using the contact information at [sayou.io](https://sayou.io). Include your organization or name, a contact method, the product or project and its intended users, the proposed role of Magic IndexedDB, anticipated versions, and whether the application is internal, distributed, or hosted. Please do not send confidential records, credentials, or sensitive proprietary information. A request alone is not authorization. Qualifying evaluation remains permitted under Section 6.3; restricted development beyond reasonable evaluation and restricted operational use require prior written authorization. An authorization should specify the permitted parties, uses, versions, scope, and any conditions. Only a person authorized by the relevant rights holder can issue it. diff --git a/docs/reference/public-api.md b/docs/reference/public-api.md index 305a96ef..40d82995 100644 --- a/docs/reference/public-api.md +++ b/docs/reference/public-api.md @@ -179,6 +179,11 @@ binding for reviewed in-place enrollment and requires a pinned manifest. Keep that account context after all fields become public. See [encrypted migrations](../guides/encrypted-migrations.md). +`MagicEncryptionContext.KeyRotation` exposes managed key rotation. Implement +`IMagicEncryptionRotationKeyProvider` for dynamic generation lookup. Rotation +provides exclusive, read-only, and online availability and supports status, +pause, resume, and cancellation. See [managed key rotation](../guides/managed-key-rotation.md). + `RetryMigrationAsync` retries failed initialization or resumes committed progress; its token cancels the .NET wait. `CancelMigrationAsync` cancels the browser attempt at a safe boundary. `ObserveMigrationsAsync` returns a disposable subscription for diff --git a/tests/migrations/ProtectedWasm/App/App.razor b/tests/migrations/ProtectedWasm/App/App.razor index 680dd3e4..73d459f6 100644 --- a/tests/migrations/ProtectedWasm/App/App.razor +++ b/tests/migrations/ProtectedWasm/App/App.razor @@ -85,8 +85,9 @@ await Contexts.DeactivateAsync(); Require(await resumed.Encryption.GetStateAsync(records) == MagicEncryptionState.Inactive, "Sign-out did not release the account context."); Require(FixtureKeys.Requests >= 3, "Explicit locking did not require fresh authorization."); + await ExerciseEncryptedRotation(fixture); state = "passed"; - message = "Authenticated legacy adoption, lock/resume, field-to-record encryption and approved declassification passed."; + message = "Authenticated legacy adoption, lock/resume, field-to-record encryption, approved declassification, and interrupted encrypted key rotation passed."; } catch (Exception error) { @@ -95,9 +96,73 @@ } } + private async Task ExerciseEncryptedRotation(IJSObjectReference fixture) + { + var records = ProtectedRepository.RotationRecords; + var context = await Activate("published-account"); + Require(await context.Encryption.InitializeAsync(records), "The encrypted rotation fixture could not initialize."); + var database = await context.Database.Database(records); + var table = await database.Query(); + foreach (var id in new[] { 1, 2, 3 }) + await table.AddAsync(new RotationRow { Id = id, Secret = "Document " + id }); + var ready = await context.KeyRotation.GetKeyRotationStatusAsync(records); + Require(ready.Phase == MagicKeyRotationPhase.NotStarted && ready.ReadsAllowed && ready.WritesAllowed && + !ready.RetirementReady, "A ready vault reported incorrect availability before its first rotation."); + await fixture.InvokeVoidAsync("assertRotationCiphertext", ProtectedRepository.RotationPhysicalName, + new[] { "rotation-source", "rotation-source", "rotation-source" }); + + await fixture.InvokeVoidAsync("holdRotationAfterFirstRecord"); + var running = context.KeyRotation.RotateEncryptionKeyAsync(records, + new("rotation-target", MagicKeyRotationMode.Online, BatchSize: 1)); + try + { + await fixture.InvokeVoidAsync("waitForRotationCrypto"); + await context.KeyRotation.CancelKeyRotationAsync(records); + } + finally { await fixture.InvokeVoidAsync("releaseRotationCrypto"); } + try + { + await running; + throw new InvalidOperationException("The rotation unexpectedly completed after cancellation."); + } + catch (JSException error) when (error.Message.Contains("abort", StringComparison.OrdinalIgnoreCase)) { } + + var interrupted = await context.KeyRotation.GetKeyRotationStatusAsync(records); + Require(interrupted.Phase == MagicKeyRotationPhase.Converting && interrupted.Converted == 1 && + !interrupted.RetirementReady, "Cancellation did not preserve the expected conversion checkpoint."); + await fixture.InvokeVoidAsync("assertRotationCiphertext", ProtectedRepository.RotationPhysicalName, + new[] { "rotation-target", "rotation-source", "rotation-source" }); + await Contexts.DeactivateAsync(); + + FixtureKeys.RotationRequests.Clear(); + context = await Activate("published-account"); + var completed = await context.KeyRotation.ResumeKeyRotationAsync(records, batchSize: 1); + Require(FixtureKeys.RotationRequests.SequenceEqual(new[] { "rotation-source", "rotation-target" }), + "Resuming did not reacquire both generations through the provider."); + Require(completed.Phase == MagicKeyRotationPhase.Completed && completed.RetirementReady && + completed.Converted == 3 && completed.Verified == 3 && completed.TargetKeyId == "rotation-target", + "Resuming did not complete the verified encrypted rotation."); + await fixture.InvokeVoidAsync("assertRotationCiphertext", ProtectedRepository.RotationPhysicalName, + new[] { "rotation-target", "rotation-target", "rotation-target" }); + + await Contexts.DeactivateAsync(); + FixtureKeys.RotationSourceAvailable = false; + FixtureKeys.RotationRequests.Clear(); + context = await Activate("published-account"); + Require(await context.Encryption.EnsureUnlockedAsync(records), "The completed vault did not reopen with only the target key."); + Require(FixtureKeys.RotationRequests.SequenceEqual(new[] { "rotation-target" }), "Reopening requested the retired key."); + database = await context.Database.Database(records); + table = await database.Query(); + var rows = await table.ToListAsync(); + Require(rows.Count == 3 && rows.All(row => row.Secret == "Document " + row.Id), "Rotation changed typed data."); + await Contexts.DeactivateAsync(); + } + private Task Activate(string account) => Contexts.ActivateAsync( [new MagicEncryptionOptions("protected-wasm", account, "fixture-key") - { PhysicalDatabaseName = ProtectedRepository.PhysicalName }]); + { PhysicalDatabaseName = ProtectedRepository.PhysicalName }, + new MagicEncryptionOptions("rotation-wasm", account, "rotation-source") + { PhysicalDatabaseName = ProtectedRepository.RotationPhysicalName }]); private static void Require(bool condition, string message) { diff --git a/tests/migrations/ProtectedWasm/App/Program.cs b/tests/migrations/ProtectedWasm/App/Program.cs index 6b16ff3e..8d9d2c43 100644 --- a/tests/migrations/ProtectedWasm/App/Program.cs +++ b/tests/migrations/ProtectedWasm/App/Program.cs @@ -4,21 +4,38 @@ var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add("#app"); builder.Services.AddMagicBlazorDB(BlazorInteropMode.WASM, false, - [typeof(ProtectedRow)], [typeof(ProtectedRepository)]); + [typeof(ProtectedRow), typeof(RotationRow)], [typeof(ProtectedRepository)]); builder.Services.AddMagicIndexedDbEncryption(_ => [new MagicEncryptionOptions("protected-wasm", "published-account", "fixture-key") { PhysicalDatabaseName = ProtectedRepository.PhysicalName }]); await builder.Build().RunAsync(); -public sealed class FixtureKeys : IMagicEncryptionKeyProvider +public sealed class FixtureKeys : IMagicEncryptionRotationKeyProvider { public static byte? KeyByte { get; set; } = 55; + public static bool RotationSourceAvailable { get; set; } = true; + public static List RotationRequests { get; } = []; public static int Requests { get; private set; } public ValueTask GetKeyAsync(MagicEncryptionKeyRequest request, CancellationToken cancellationToken) { Requests++; + if (request.DatabaseName == ProtectedRepository.RotationRecords.DatabaseName) + { + RotationRequests.Add(request.KeyId); + byte? key = request.KeyId switch + { + "rotation-source" when RotationSourceAvailable => 71, + "rotation-target" => 89, + _ => null + }; + return ValueTask.FromResult(key is { } material + ? MagicEncryptionKey.FromBytes(Enumerable.Repeat(material, 32).ToArray()) : null); + } return ValueTask.FromResult(KeyByte is { } value - ? MagicEncryptionKey.FromBytes(Enumerable.Repeat(value, 32).ToArray()) - : null); + ? MagicEncryptionKey.FromBytes(Enumerable.Repeat(value, 32).ToArray()) : null); } + + public ValueTask CanReacquireKeysAsync(MagicEncryptionKeyRequest source, MagicEncryptionKeyRequest target, + CancellationToken cancellationToken) => ValueTask.FromResult( + source.KeyId == "rotation-source" && target.KeyId == "rotation-target"); } diff --git a/tests/migrations/ProtectedWasm/App/wwwroot/protected-fixture.mjs b/tests/migrations/ProtectedWasm/App/wwwroot/protected-fixture.mjs index 7ede432b..33778fcf 100644 --- a/tests/migrations/ProtectedWasm/App/wwwroot/protected-fixture.mjs +++ b/tests/migrations/ProtectedWasm/App/wwwroot/protected-fixture.mjs @@ -3,8 +3,8 @@ import * as api from './_content/Magic.IndexedDb/magicDB.js'; const physical = '__magic_protected__:published-migration-fixture'; const route = physical + ':seed'; -async function rawRows() { - const opening = indexedDB.open(physical); +async function rawRows(name = physical, store = 'records') { + const opening = indexedDB.open(name); opening.onupgradeneeded = () => opening.transaction.abort(); const db = await new Promise((resolve, reject) => { opening.onsuccess = () => resolve(opening.result); @@ -12,7 +12,7 @@ async function rawRows() { }); try { return await new Promise((resolve, reject) => { - const request = db.transaction('records').objectStore('records').getAll(); + const request = db.transaction(store).objectStore(store).getAll(); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); @@ -65,3 +65,37 @@ export async function assertFinalPlaintext() { Object.hasOwn(row, '__magic_record'))) throw new Error('The approved declassification did not preserve the logical records.'); } + +export async function assertRotationCiphertext(name, expected) { + const rows = await rawRows(name, 'rotation-records'); + if (rows.length !== expected.length || rows.some((row, index) => row.Id !== index + 1 || + row.Secret?.keyId !== expected[index] || !(row.Secret.ciphertext instanceof ArrayBuffer) || + row.Secret.ciphertext.byteLength === 0)) + throw new Error('Persisted ciphertext does not match the expected rotation generations.'); +} + +let releaseRotation; +let unsubscribeRotation; +export function holdRotationAfterFirstRecord() { + unsubscribeRotation = api.subscribeKeyRotationEvents(event => { + if (event.phase !== 'converting' || event.targetKeyId !== 'rotation-target' || event.converted !== 1) return; + unsubscribeRotation(); + const encrypt = crypto.subtle.encrypt.bind(crypto.subtle); + crypto.subtle.encrypt = async (...args) => { + await new Promise(resolve => { releaseRotation = resolve; }); + return encrypt(...args); + }; + }); +} + +export async function waitForRotationCrypto() { + const deadline = performance.now() + 15_000; + while (!releaseRotation && performance.now() < deadline) await new Promise(resolve => setTimeout(resolve, 20)); + if (!releaseRotation) throw new Error('Rotation did not commit its first batch and start the next.'); +} + +export function releaseRotationCrypto() { + unsubscribeRotation?.(); + delete crypto.subtle.encrypt; + releaseRotation?.(); +} diff --git a/tests/migrations/ProtectedWasm/Exporter/Program.cs b/tests/migrations/ProtectedWasm/Exporter/Program.cs index 1cf4bf75..5d7fc416 100644 --- a/tests/migrations/ProtectedWasm/Exporter/Program.cs +++ b/tests/migrations/ProtectedWasm/Exporter/Program.cs @@ -1,4 +1,4 @@ using Magic.IndexedDb.Migrations; -return MagicSchemaExporter.Run(args, [typeof(ProtectedRow)], [typeof(ProtectedRepository)], - new MagicSchemaOptions { ProtectedDatabases = ["protected-wasm"] }); +return MagicSchemaExporter.Run(args, [typeof(ProtectedRow), typeof(RotationRow)], [typeof(ProtectedRepository)], + new MagicSchemaOptions { ProtectedDatabases = ["protected-wasm", "rotation-wasm"] }); diff --git a/tests/migrations/ProtectedWasm/Model.cs b/tests/migrations/ProtectedWasm/Model.cs index 14184ad6..2ca30aa3 100644 --- a/tests/migrations/ProtectedWasm/Model.cs +++ b/tests/migrations/ProtectedWasm/Model.cs @@ -1,8 +1,12 @@ using Magic.IndexedDb; using Magic.IndexedDb.Interfaces; +using Magic.IndexedDb.SchemaAnnotations; public sealed class ProtectedRepository : IMagicRepository { + public const string RotationPhysicalName = "__magic_protected__:published-rotation-fixture"; + public static readonly IndexedDbSet RotationRecords = new IndexedDbSet("rotation-wasm") + .WithMigrations("releases/rotation/rotation-wasm/manifest.json"); public const string PhysicalName = "__magic_protected__:published-migration-fixture"; public static readonly IndexedDbSet Records = new IndexedDbSet("protected-wasm") .WithMigrations("releases/final/protected-wasm/manifest.json"); @@ -22,3 +26,14 @@ public sealed class ProtectedRow : MagicTableTool, IMagicTable, IMagicTable +{ + public ProtectedRepository Databases { get; } = new(); + public IndexedDbSet GetDefaultDatabase() => ProtectedRepository.RotationRecords; + public string GetTableName() => "rotation-records"; + public IMagicCompoundKey GetKeys() => CreatePrimaryKey(row => row.Id, false); + public List GetCompoundIndexes() => []; + public int Id { get; set; } + [MagicEncrypt] public string Secret { get; set; } = ""; +} diff --git a/tests/migrations/ProtectedWasm/author.mjs b/tests/migrations/ProtectedWasm/author.mjs index cb25f31c..04115e30 100644 --- a/tests/migrations/ProtectedWasm/author.mjs +++ b/tests/migrations/ProtectedWasm/author.mjs @@ -6,7 +6,10 @@ import path from 'node:path'; const [cli, targetFile] = process.argv.slice(2); const exported = JSON.parse(await readFile(targetFile, 'utf8')); -const target = exported.schemas?.[0] ?? exported; +const target = exported.schemas.find(schema => schema.schemaId === 'protected-wasm'); +const rotation = exported.schemas.find(schema => schema.schemaId === 'rotation-wasm'); +assert.deepEqual(rotation.stores[0].encryptedFields, ['Secret']); +await writeFile('rotation-model.json', JSON.stringify(rotation)); assert.equal(target.schemaId, 'protected-wasm'); assert.deepEqual(target.requiredCapabilities, ['authenticatedMigrationsV1']); const fieldModel = structuredClone(target); @@ -58,6 +61,10 @@ await transform(3, `export async function transform(row) { run(['migrations', 'validate', '--schema', 'public-model.json']); run(['migrations', 'publish', '--schema', 'public-model.json', '--output', 'App/wwwroot/releases/final']); +run(['migrations', 'add', 'EncryptedRecords', '--schema', 'rotation-model.json']); +run(['migrations', 'validate', '--schema', 'rotation-model.json']); +run(['migrations', 'publish', '--schema', 'rotation-model.json', '--output', 'App/wwwroot/releases/rotation']); + for (const legacyProtected of [false, true]) { const source = structuredClone(fieldModel); source.schemaId = legacyProtected ? 'released-numeric-vault' : 'released-numeric-enrollment'; diff --git a/tests/migrations/ReleasedUpgrade/run.mjs b/tests/migrations/ReleasedUpgrade/run.mjs index 737364e6..924c50cf 100644 --- a/tests/migrations/ReleasedUpgrade/run.mjs +++ b/tests/migrations/ReleasedUpgrade/run.mjs @@ -321,16 +321,31 @@ try { const manifest = await (await fetch(manifestUrl)).json(); const reference = manifest.schemas.find(schema => schema.revision === manifest.targetRevision); const model = await (await fetch(new URL(reference.path, location.href))).json(); - await api.createDb({ name: route, ...numeric, migrationManifestUrl: manifestUrl, migrationSchema: model, + const config = { name: route, ...numeric, migrationManifestUrl: manifestUrl, migrationSchema: model, encryption: { ...encryption, explicitPhysicalBinding: true }, - storeSchemas: [{ ...store, ...(legacyProtected ? { exposedFields: ['Name', 'Id'] } : { encryptedFields: ['Secret'] }) }] }); + storeSchemas: [{ ...store, ...(legacyProtected ? { exposedFields: ['Name', 'Id'] } : { encryptedFields: ['Secret'] }) }] }; + const read = () => Promise.all(rows.map(row => api.findItem(route, 'records', [row.Name, row.Id]))); + await api.createDb(config); await api.unlockProtectedDatabase(route, 'fixture-key', new Uint8Array(32).fill(55), !legacyProtected); await api.ensureProtectedMigration(route); - const result = await Promise.all(rows.map(row => api.findItem(route, 'records', [row.Name, row.Id]))); + const adopted = await read(); + const newKeyId = 'rotated-numeric-key'; + const newKey = new Uint8Array(32).fill(91); + const rotation = await api.rotateManagedEncryptionKey(route, { targetKeyId: newKeyId, + mode: 'online', batchSize: 1, recoverable: true }, newKey); api.releaseProtectedDatabase(route); - return result; + await api.createDb(config); + await api.unlockProtectedDatabase(route, newKeyId, newKey); + await api.ensureProtectedMigration(route); + const reopened = await read(); + api.releaseProtectedDatabase(route); + return { adopted, rotation, reopened }; }, { manifestUrl, route, numeric, store, encryption, rows, legacyProtected }); - assert.deepEqual(after, rows); + assert.deepEqual(after.adopted, rows); + assert.deepEqual(after.reopened, rows); + assert.equal(after.rotation.retirementReady, true); + assert.equal(after.rotation.converted, rows.length); + assert.equal(after.rotation.verified, rows.length); const final = await snapshot(current, physical, legacyProtected ? '__magic_record' : 'Secret'); assert.deepEqual(final.data.records.keys, before.data.records.keys); assert.deepEqual(final.data.records.indexes, before.data.records.indexes); @@ -338,6 +353,8 @@ try { assert.equal(final.data.__magic_migrations__.rows[0].revision, 2); assert.equal(final.data.__magic_numeric_policy.rows[0].mode, 'lossless'); assert.deepEqual(final.data.records.ciphertext, [true, true, true]); + assert.ok(final.data.records.rows.every(row => + row[legacyProtected ? '__magic_record' : 'Secret'].keyId === 'rotated-numeric-key')); if (legacyProtected) assert.ok(final.data.records.rows.every(row => !Object.hasOwn(row, 'Secret') && !Object.hasOwn(row, 'Wide') && !Object.hasOwn(row, 'Reference'))); else assert.ok(final.data.records.rows.every((row, index) => diff --git a/tests/migrations/protected-adapter.test.mjs b/tests/migrations/protected-adapter.test.mjs index 136f6b48..6cb7ee87 100644 --- a/tests/migrations/protected-adapter.test.mjs +++ b/tests/migrations/protected-adapter.test.mjs @@ -40,6 +40,24 @@ test('managed policy authenticates its identity and rejects wrong keys, accounts await rejects(adapter.verifyPolicy(changed, schema), 'MAGDB_AUTHORIZATION_REJECTED'); }); +test('recovery evidence rotation preserves the legacy payload and binds it to its metadata slot', async () => { + const source = await createProtectedMigrationAdapter(identity); + const target = await createProtectedMigrationAdapter({ ...identity, keyId: 'next', + key: await importEncryptionKey(crypto.getRandomValues(new Uint8Array(32))) }); + const entry = { id: 'edge', sha256: binding.migrationHash, recovery: { id: 'repair', sha256: binding.schemaHash } }; + const audit = { original: { id: entry.id, sha256: entry.sha256, lastKey: new Date(42) }, + recovery: { ...entry.recovery, lastKey: new Uint8Array([7, 9]) } }; + const legacy = await source.sealState(audit); + const expected = await source.openRetainedRecoveryEvidence(legacy, entry); + const converted = await target.rotateRecoveryEvidence(legacy, entry, source); + assert.equal(await target.verifyRecoveryEvidence(converted, entry), expected); + await rejects(source.openRetainedRecoveryEvidence(converted, entry), 'MAGDB_PROTECTION_STATE_INVALID'); + await rejects(target.verifyRecoveryEvidence(converted, { ...entry, recovery: { ...entry.recovery, id: 'other' } }), + 'MAGDB_PROTECTION_STATE_INVALID'); + await rejects(source.openRetainedRecoveryEvidence(legacy, { ...entry, sha256: entry.recovery.sha256 }), + 'MAGDB_PROTECTION_STATE_INVALID'); +}); + test('legacy protected policy fingerprints stay exact and can be adopted semantically', async () => { const source = native(); const legacy = createProtectionPolicy(source); diff --git a/tests/migrations/protected-engine-browser.mjs b/tests/migrations/protected-engine-browser.mjs index d414e596..ec49c60e 100644 --- a/tests/migrations/protected-engine-browser.mjs +++ b/tests/migrations/protected-engine-browser.mjs @@ -38,6 +38,126 @@ export function registerProtectedEngineTests({ test, schema, bundle, copy, inspe row.__magic_record?.ciphertext instanceof ArrayBuffer ? 'record' : row.name?.ciphertext instanceof ArrayBuffer ? 'field' : 'public')); + test('managed rotation admits only recoverable distinct keys and fences the older migration path', async ({ page }) => { + const source = model({ encryptedFields: ['name'] }); + await seed(page, source); + const result = await page.evaluate(async schema => { + const { admitRotation, rotationCoordinator, enterRotationVerification } = await import('/engine/utilities/rotationLifecycle.js'); + const { importEncryptionKey } = await import('/engine/utilities/encryptionEnvelope.js'); + const ready = await engine.ensureDatabase({ name: 'test', schema, protection: protectionAdapter }); + const db = await openRaw('test'); + const vault = { database: db.name, account: 'protected-test' }; + const key = byte => importEncryptionKey(new Uint8Array(32).fill(byte)); + const keys = new Map([['test-key', await key(73)], ['target', await key(76)]]); + const make = patch => ({ db, vault, ready, schema, authorization: protectionAdapter, keys, + targetKeyId: 'target', mode: 'online', recoverable: true, priorKeyIds: new Set(), ...patch }); + const rejected = async options => { + try { await admitRotation(options); return false; } catch { return true; } + }; + const ephemeral = await rejected(make({ recoverable: false })); + const sameKey = await rejected(make({ keys: new Map(keys).set('target', await key(73)) })); + const wrongSource = await rejected(make({ keys: new Map(keys).set('test-key', await key(75)) })); + await engine.assertDatabaseReady(db, ready, protectionAdapter); + const admitted = await rotationCoordinator(db, undefined, () => admitRotation(make())); + let oldOpenFenced = false; + try { await engine.assertDatabaseReady(db, ready, protectionAdapter); } + catch { oldOpenFenced = true; } + let prematureVerification = false; + try { + await enterRotationVerification({ ...admitted, db, vault, schema, keys, + assertCurrent: protectionAdapter.assertCurrent }); + } catch { prematureVerification = true; } + db.close(); + return { ephemeral, sameKey, wrongSource, oldOpenFenced, prematureVerification, + writeGeneration: admitted.document.state.writeKeyId }; + }, source); + assert.deepEqual(result, { ephemeral: true, sameKey: true, wrongSource: true, oldOpenFenced: true, + prematureVerification: true, writeGeneration: 'target' }); + }); + + for (const mode of ['exclusive', 'read-only', 'online']) for (const [layout, policy] of [ + ['field', { encryptedFields: ['name'] }], + ['whole-record', { exposedFields: ['id', 'visits'] }] + ]) { + test(`rotation storage enforces ${mode} access for ${layout} protection and restores a target-only vault`, async ({ page }) => { + const source = model(policy); + await seed(page, source); + const observed = await page.evaluate(async ({ schema, mode, policy }) => { + const { Dexie } = await import('/engine/dexie/dexie.js'); + const { createProtectedStorage } = await import('/engine/utilities/protectedStorage.js'); + const { admitRotation, enterRotationVerification, finishRotation } = await import('/engine/utilities/rotationLifecycle.js'); + const { advanceRotationPass } = await import('/engine/utilities/rotationPass.js'); + const { importEncryptionKey } = await import('/engine/utilities/encryptionEnvelope.js'); + const { createProtectedMigrationAdapter } = await import('/engine/migrations/protectedMigrationAdapter.js'); + const { portableProtectionPolicy } = await import('/engine/utilities/protectionPolicy.js'); + const ready = await engine.ensureDatabase({ name: 'test', schema, protection: protectionAdapter }); + const dexie = new Dexie('test'); + await dexie.open(); + const db = dexie.backendDB(); + const vault = { database: db.name, account: 'protected-test' }; + const storage = createProtectedStorage(dexie, vault.account, [{ tableName: 'clients', + columnNamesInCompoundKey: ['id'], primaryKeyAuto: false, indexes: [], uniqueIndexes: [], + columnNamesInCompoundIndex: [], ...policy }], null, { managedSchema: schema }); + const keys = new Map([['test-key', await importEncryptionKey(new Uint8Array(32).fill(73))], + ['target', await importEncryptionKey(new Uint8Array(32).fill(76))]]); + storage.setManagedReadiness(ready); + await storage.unlock('test-key', keys.get('test-key'), false); + const table = storage.forTable('clients'); + const common = { db, vault, ready, schema, keys, assertCurrent: protectionAdapter.assertCurrent }; + let active = await admitRotation({ ...common, authorization: protectionAdapter, targetKeyId: 'target', + mode, recoverable: true }); + const attach = () => storage.setRotationAccess(active.document, active.fence, keys, common.assertCurrent); + await attach(); + const attempt = async action => { + try { return { allowed: true, value: await action() }; } + catch (err) { return { allowed: false, fenced: err.message.startsWith('MAGIC_ROTATION_ACCESS_FENCED:') }; } + }; + const read = await attempt(() => table.read(1)); + const write = await attempt(() => table.write([{ id: 4, name: 'New generation', visits: 0 }], + (store, sealed) => store.put(sealed[0]))); + const policies = portableProtectionPolicy(schema).policies; + const run = async () => { + for (let index = 0; index < 12; index++) { + const step = await advanceRotationPass({ ...common, document: active.document, policies, batchSize: 1, + expectations: [...active.checks, { store: '__magic_encryption', key: 'policy', value: active.fence }] }); + if (step.outcome === 'pass-complete') return; + if (step.outcome !== 'advanced') throw Error('The rotation step did not advance.'); + active.document = step.document; + } + throw Error('The bounded pass did not complete.'); + }; + await run(); + active = await enterRotationVerification({ ...common, ...active }); + await attach(); + const verificationWrite = await attempt(() => table.patch(1, { visits: 10 })); + await run(); + const finalized = await finishRotation({ ...common, ...active }); + dexie.close(); + const target = await createProtectedMigrationAdapter({ name: 'test', account: vault.account, keyId: 'target', key: keys.get('target') }); + const reopened = await engine.ensureDatabase({ name: 'test', schema, protection: target }); + const raw = await readRows('test'); + const logical = []; + for (const row of raw) logical.push(await target.openRecord(row, schema, 'clients', row.id)); + return { read, write, verificationWrite, lineage: target.keyLineage.generations, + retirement: finalized.lineage.completed, revision: reopened.revision, logical, + publicRows: raw.map(row => ({ id: row.id, visits: row.visits })), + deployed: raw.map(row => (row.__magic_record ?? row.name).keyId) }; + }, { schema: source, mode, policy }); + assert.equal(observed.read.allowed, mode !== 'exclusive'); + if (!observed.read.allowed) assert.equal(observed.read.fenced, true); + assert.equal(observed.write.allowed, mode === 'online'); + if (!observed.write.allowed) assert.equal(observed.write.fenced, true); + assert.deepEqual(observed.verificationWrite, { allowed: false, fenced: true }); + assert.deepEqual(observed.lineage, ['test-key', 'target']); + assert.equal(observed.retirement.converted, 3); + assert.equal(observed.retirement.verified, mode === 'online' ? 4 : 3); + assert.equal(observed.revision, 1); + assert.deepEqual(observed.logical, mode === 'online' ? [...rows, { id: 4, name: 'New generation', visits: 0 }] : rows); + assert.deepEqual(observed.publicRows, observed.logical.map(({ id, visits }) => ({ id, visits }))); + assert.ok(observed.deployed.every(generation => generation === 'target')); + }); + } + for (const [label, before, after, loss] of [ ['plaintext to field encryption', {}, { encryptedFields: ['name'] }, false], ['field encryption to plaintext', { encryptedFields: ['name'] }, {}, true], @@ -457,6 +577,182 @@ export function registerProtectedEngineTests({ test, schema, bundle, copy, inspe assert.deepEqual(await logical(reopened, target), expected.map(row => ({ ...row, normalized: true }))); }); + test('rotation resumes retained authenticated recovery evidence and verifies it with only the target key', async ({ page, context }) => { + const source = model({ encryptedFields: ['name'] }); + await seed(page, source, rows.map(row => ({ ...row, value: 1 }))); + const plan = planFor(source, source, [{ op: 'transform', store: 'clients' }], { module: ` + export function transform(row) { if (row.id === 2) throw new Error(row.name); return { ...row, value: 11 }; }` }); + const recovery = recoveryPackage(plan); + const failed = await run(page, plan); + assert.equal(failed.error?.code, 'MAGDB_HOOK_FAILED'); + assert.equal((await inspect(page)).state.active.processedRecords, 1); + const options = { name: 'test', schema: source, manifestUrl: plan.url, batchSize: 1 }; + const recovered = await page.evaluate(async ({ options, recovery }) => + tryEnsure({ ...options, recovery, protection: protectionAdapter }, true), { options, recovery }); + assert.equal(recovered.value?.outcome, 'recovered', JSON.stringify(recovered)); + + const partial = await page.evaluate(async options => { + const api = await import('/engine/magicDB.js'); + const { importEncryptionKey, encryptValue } = await import('/engine/utilities/encryptionEnvelope.js'); + const ready = await engine.ensureDatabase({ ...options, protection: protectionAdapter }); + const entry = ready.history[0]; + const old = new Uint8Array(32).fill(73), target = new Uint8Array(32).fill(76); + const key = 'recovery:' + entry.recovery.id; + const db = await openRaw('test'); + const store = mode => db.transaction('__magic_migrations__', mode).objectStore('__magic_migrations__'); + const evidence = await request(store('readonly').get(key)); + const plaintext = await protectionAdapter.verifyRecoveryEvidence(evidence, entry); + // Recreate the exact v3.0 envelope binding for the retained evidence + // produced by the real recovery above. + const legacyEvidence = await encryptValue(plaintext, await importEncryptionKey(old), 'test-key', + { database: 'test', account: 'protected-test', store: '__magic_encryption', primaryKey: 'migration-state', member: null }); + await request(store('readwrite').put(legacyEvidence, key)); + db.close(); + const config = { name: '__magic_protected__:recovery-rotation', migrationSchema: options.schema, + migrationManifestUrl: options.manifestUrl, + encryption: { physicalName: 'test', account: 'protected-test', explicitPhysicalBinding: true }, + storeSchemas: [{ tableName: 'clients', columnNamesInCompoundKey: ['id'], primaryKeyAuto: false, + indexes: [], uniqueIndexes: [], columnNamesInCompoundIndex: [], encryptedFields: ['name'] }] }; + await api.createDb(config); + await api.unlockProtectedDatabase(config.name, 'test-key', old); + await api.ensureProtectedMigration(config.name); + const { rotationJournalKey } = await import('/engine/utilities/rotationJournal.js'); + // Prevent the next crypto preparation from completing after the + // metadata batch commits. The native checkpoint is the barrier. + const decrypt = crypto.subtle.decrypt.bind(crypto.subtle); + crypto.subtle.decrypt = async (...args) => { + const opened = await openRaw('test'); + let progress; + try { progress = await request(opened.transaction('__magic_encryption').objectStore('__magic_encryption').get(rotationJournalKey)); } + finally { opened.close(); } + if (progress?.state.afterKey === key) { + globalThis.evidenceCheckpointReached = true; + await new Promise(() => {}); + } + return decrypt(...args); + }; + void api.rotateManagedEncryptionKey(config.name, { targetKeyId: 'next', mode: 'online', + batchSize: 1, recoverable: true }, target).catch(error => { globalThis.rotationFailure = error.message; }); + return { config, plaintext, key }; + }, options); + await page.waitForFunction(() => globalThis.evidenceCheckpointReached || globalThis.rotationFailure); + assert.equal(await page.evaluate(() => globalThis.rotationFailure ?? null), null); + await page.close(); + + const resumed = await loadPage(context); + const result = await resumed.evaluate(async ({ config, key, plaintext }) => { + const api = await import('/engine/magicDB.js'); + const { createProtectedMigrationAdapter } = await import('/engine/migrations/protectedMigrationAdapter.js'); + const { rotationJournalKey } = await import('/engine/utilities/rotationJournal.js'); + const source = new Uint8Array(32).fill(73), target = new Uint8Array(32).fill(76); + const readMetadata = async (name, id) => { + const db = await openRaw('test'); + try { return await request(db.transaction(name).objectStore(name).get(id)); } + finally { db.close(); } + }; + const progress = await readMetadata('__magic_encryption', rotationJournalKey); + const converted = await readMetadata('__magic_migrations__', key); + await api.createDb(config); + const partialStatus = await api.authorizeManagedKeyRotation(config.name, 'test-key', source, 'next', target); + const changeEvidence = async (action, ...args) => { + const db = await openRaw('test'); + try { await request(db.transaction('__magic_migrations__', 'readwrite').objectStore('__magic_migrations__')[action](...args)); } + finally { db.close(); } + }; + await changeEvidence('delete', key); + let missingEvidenceRejected = false; + try { await api.resumeManagedEncryptionKeyRotation(config.name, { batchSize: 1 }); } + catch (failure) { missingEvidenceRejected = failure.code === 'MAGDB_PROTECTION_STATE_INVALID'; } + const blocked = await api.getManagedKeyRotationStatus(config.name); + await changeEvidence('put', converted, key); + const completed = await api.resumeManagedEncryptionKeyRotation(config.name, { batchSize: 1 }); + api.releaseProtectedDatabase(config.name); + await api.createDb(config); + await api.unlockProtectedDatabase(config.name, 'next', target); + const ready = await api.ensureProtectedMigration(config.name); + const entry = ready.history[0]; + const evidence = await readMetadata('__magic_migrations__', key); + const adapter = keyId => createProtectedMigrationAdapter({ name: 'test', account: config.encryption.account, + keyId, key: keyId === 'next' ? target : source }); + const intact = await (await adapter('next')).verifyRecoveryEvidence(evidence, entry) === plaintext; + let oldKeyRejected = false; + try { await (await adapter('test-key')).openRetainedRecoveryEvidence(evidence, entry); } + catch { oldKeyRejected = true; } + return { progress: progress.state.afterKey, convertedKey: converted.keyId, partialStatus, blocked, missingEvidenceRejected, completed, intact, + oldKeyRejected, history: ready.history, ciphertextUnchanged: [...new Uint8Array(converted.ciphertext)].join() === + [...new Uint8Array(evidence.ciphertext)].join(), rows: await api.toArray(config.name, 'clients') }; + }, partial); + assert.equal(result.progress, partial.key); + assert.equal(result.convertedKey, 'next'); + assert.equal(result.partialStatus.retirementReady, false); + assert.equal(result.missingEvidenceRejected, true); + assert.equal(result.blocked.phase, 'verifying'); + assert.equal(result.blocked.retirementReady, false); + assert.equal(result.completed.retirementReady, true); + assert.equal(result.intact, true); + assert.equal(result.oldKeyRejected, true); + assert.equal(result.ciphertextUnchanged, true); + assert.equal(result.history[0].recovery.id, recovery.id); + assert.deepEqual(result.rows, rows.map(row => ({ ...row, value: 10, repairs: 1 }))); + }); + + test('authenticated enrollment seals evidence retained by a prior plaintext managed recovery', async ({ page }) => { + const source = schema(); + const name = 'test'; + await page.evaluate(async ({ source, rows }) => { + await engine.ensureDatabase({ name: 'test', schema: source }); + await writeRows('test', rows); + }, { source, rows: rows.map(row => ({ ...row, value: 1 })) }); + const plan = bundle(source, source, [{ op: 'transform', store: 'clients' }], { mode: 'resumable', module: ` + export function transform(row) { if (row.id === 2) throw new Error('Fixture failure'); return { ...row, value: 11 }; }` }); + const recovery = recoveryPackage(plan); + const options = { name, schema: source, manifestUrl: plan.url, batchSize: 1 }; + const failed = await page.evaluate(options => tryEnsure(options), options); + assert.equal(failed.error?.code, 'MAGDB_HOOK_FAILED'); + const recovered = await page.evaluate(options => tryEnsure(options, true), { ...options, recovery }); + assert.equal(recovered.value?.outcome, 'recovered', JSON.stringify(recovered)); + assert.equal((await inspect(page)).state.protocolVersion, 2); + const plaintextAudit = await page.evaluate(async id => { + const db = await openRaw('test'); + try { return await request(db.transaction('__magic_migrations__').objectStore('__magic_migrations__').get('recovery:' + id)); } + finally { db.close(); } + }, recovery.id); + plan.manifest.requiredCapabilities.push(capability); + jsonAsset(plan.base + '/manifest.json', plan.manifest); + + await authorize(page); + const enrolled = await page.evaluate(async ({ options, plaintextAudit }) => { + const ready = await engine.ensureDatabase({ ...options, initialize: true, protection: protectionAdapter }); + const entry = ready.history[0]; + const db = await openRaw('test'); + try { + const key = 'recovery:' + entry.recovery.id; + const meta = mode => db.transaction('__magic_migrations__', mode).objectStore('__magic_migrations__'); + const audit = await request(meta('readonly').get(key)); + const plaintext = await protectionAdapter.verifyRecoveryEvidence(audit, entry); + // Older v3 enrollment could have left the v2 audit unsealed. + await request(meta('readwrite').put(plaintextAudit, key)); + const { admitRotation } = await import('/engine/utilities/rotationLifecycle.js'); + const { importEncryptionKey } = await import('/engine/utilities/encryptionEnvelope.js'); + const from = await importEncryptionKey(new Uint8Array(32).fill(73)); + const to = await importEncryptionKey(new Uint8Array(32).fill(76)); + let rejectedBeforeAdmission = false; + try { + await admitRotation({ db, ready, schema: options.schema, authorization: protectionAdapter, + vault: { database: db.name, account: 'protected-test' }, keys: new Map([['test-key', from], ['next', to]]), + targetKeyId: 'next', mode: 'exclusive', recoverable: true }); + } catch (failure) { rejectedBeforeAdmission = failure.code === 'MAGDB_PROTECTION_STATE_INVALID'; } + await engine.assertDatabaseReady(db, ready, protectionAdapter); + await request(meta('readwrite').put(audit, key)); + return { protocol: ready.protocolVersion, sealed: audit.ciphertext instanceof ArrayBuffer && + audit.keyId === 'test-key' && !Object.hasOwn(audit, 'original'), payloadPreserved: plaintext.includes('processedRecords'), + rejectedBeforeAdmission }; + } finally { db.close(); } + }, { options, plaintextAudit }); + assert.deepEqual(enrolled, { protocol: 3, sealed: true, payloadPreserved: true, rejectedBeforeAdmission: true }); + assert.deepEqual(await read(page), rows.map(row => ({ ...row, value: 10, repairs: 1 }))); + }); + if (cliFixture) test('installed CLI protected history executes all encryption directions and later structural revision', async ({ page }) => { const directory = path.join(path.dirname(cliFixture), 'protected-transition'); const manifest = JSON.parse(await readFile(path.join(directory, 'manifest.json'), 'utf8')); diff --git a/tests/migrations/protected-registration-browser.mjs b/tests/migrations/protected-registration-browser.mjs index 33e3c515..1acc540f 100644 --- a/tests/migrations/protected-registration-browser.mjs +++ b/tests/migrations/protected-registration-browser.mjs @@ -48,6 +48,7 @@ export function registerProtectedRegistrationTests({ test, schema, bundle, appen record: { id: 1, name: 'Public', secret: 'Never persist this plaintext' } }); const raw = (await readRows(physical))[0]; const initial = await engine.inspectDatabase(physical); + const firstRotation = await api.getManagedKeyRotationStatus(config.name); api.lockProtectedDatabase(config.name); let lockedCode; try { await api.findItem(config.name, 'clients', 1); } @@ -58,12 +59,14 @@ export function registerProtectedRegistrationTests({ test, schema, bundle, appen const reopened = await engine.inspectDatabase(physical); api.releaseProtectedDatabase(config.name); return { beforeAuthorization, afterAuthorization, rawSecretType: typeof raw.secret, - ciphertextBytes: raw.secret.ciphertext.byteLength, initial, reopened, lockedCode, row }; + ciphertextBytes: raw.secret.ciphertext.byteLength, initial, firstRotation, reopened, lockedCode, row }; }, { config, physical }); assert.equal(result.beforeAuthorization, null); assert.equal(result.afterAuthorization, null); assert.equal(result.rawSecretType, 'object'); assert.ok(result.ciphertextBytes > 0); + assert.deepEqual(result.firstRotation, + { phase: 'not-started', retirementReady: false, readsAllowed: true, writesAllowed: true }); assert.equal(result.initial.state.protocolVersion, 3); assert.equal(result.initial.state.status, 'ready'); assert.equal(result.lockedCode, 'MAGDB_AUTHORIZATION_REQUIRED'); @@ -71,6 +74,450 @@ export function registerProtectedRegistrationTests({ test, schema, bundle, appen assert.deepEqual(result.row, { id: 1, name: 'Public', secret: 'Never persist this plaintext' }); }); + test('public rotation API resumes after release and unlocks with the new key only', async ({ page }) => { + const physical = '__magic_protected__:public-rotation'; + const target = model(); + const config = configuration(physical, 'route', target, initial(target).url); + const value = await page.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + const old = new Uint8Array(32).fill(41), next = new Uint8Array(32).fill(83); + await api.createDb(config); + await api.unlockProtectedDatabase(config.name, 'first', old, true); + await api.ensureProtectedMigration(config.name); + for (const id of [1, 2, 3]) await api.addItem({ dbName: config.name, storeName: 'clients', + record: { id, name: 'Document ' + id, secret: 'Content ' + id } }); + const events = []; + const unsubscribe = api.subscribeKeyRotationEvents(event => { + events.push([event.phase, event.converted]); + if (event.phase === 'converting' && event.converted === 1) api.cancelManagedEncryptionKeyRotation(config.name); + }); + let cancelled = false; + try { await api.rotateManagedEncryptionKey(config.name, { targetKeyId: 'next', mode: 'online', batchSize: 1, + recoverable: true }, next); } + catch (error) { cancelled = error.name === 'AbortError'; } + unsubscribe(); + const partial = await api.getManagedKeyRotationStatus(config.name); + const during = await api.findItem(config.name, 'clients', 2); + api.releaseProtectedDatabase(config.name); + await api.createDb(config); + const hints = await api.getManagedEncryptionKeyHints(config.name); + await api.authorizeManagedKeyRotation(config.name, 'first', old, 'next', next); + const completed = await api.resumeManagedEncryptionKeyRotation(config.name, { batchSize: 1 }); + api.releaseProtectedDatabase(config.name); + await api.createDb(config); + const active = await api.getManagedEncryptionKeyHints(config.name); + await api.unlockProtectedDatabase(config.name, 'next', next); + await api.ensureProtectedMigration(config.name); + const row = await api.findItem(config.name, 'clients', 1); + const close = IDBDatabase.prototype.close; + let connectionCloses = 0; + IDBDatabase.prototype.close = function () { + if (this.name === config.encryption.physicalName) connectionCloses++; + return close.call(this); + }; + let second; + try { + second = await api.rotateManagedEncryptionKey(config.name, { + targetKeyId: 'third', mode: 'read-only', recoverable: true, batchSize: 1 + }, new Uint8Array(32).fill(94)); + } finally { IDBDatabase.prototype.close = close; } + let reused = false; + try { + await api.rotateManagedEncryptionKey(config.name, { targetKeyId: 'first', recoverable: true }, old); + } catch (error) { reused = error.message.startsWith('MAGIC_ROTATION_KEY_REUSED:'); } + const retained = await api.findItem(config.name, 'clients', 1); + api.releaseProtectedDatabase(config.name); + return { cancelled, partial, during, hints, completed, active, row, events, second, retained, reused, connectionCloses }; + }, config); + assert.equal(value.cancelled, true); + assert.equal(value.partial.converted, 1); + assert.equal(value.partial.retirementReady, false); + assert.equal(value.during.secret, 'Content 2'); + assert.deepEqual(value.hints, { active: true, keyId: 'first', targetKeyId: 'next' }); + assert.equal(value.completed.retirementReady, true); + assert.equal(value.completed.converted, 3); + assert.equal(value.completed.verified, 3); + assert.deepEqual(value.active, { active: false, keyId: 'next' }); + assert.deepEqual(value.row, { id: 1, name: 'Document 1', secret: 'Content 1' }); + assert.deepEqual(value.events, [['converting', 0], ['converting', 1]]); + assert.equal(value.second.retirementReady, true); + assert.equal(value.second.targetKeyId, 'third'); + assert.equal(value.connectionCloses, 0); + assert.deepEqual(value.retained, value.row); + assert.equal(value.reused, true); + }); + + test('online rotation preserves independently authorized tab mutations while paused and resumed', async ({ page, context }) => { + const physical = '__magic_protected__:rotation-shared-tabs'; + const target = model(); + const config = configuration(physical, 'route', target, initial(target).url); + await page.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + await api.createDb(config); + await api.unlockProtectedDatabase(config.name, 'original', new Uint8Array(32).fill(41), true); + await api.ensureProtectedMigration(config.name); + for (const id of [1, 2, 3]) await api.addItem({ dbName: config.name, storeName: 'clients', + record: { id, name: 'Document ' + id, secret: 'Content ' + id } }); + const unsubscribe = api.subscribeKeyRotationEvents(event => { + if (event.converted === 1) api.cancelManagedEncryptionKeyRotation(config.name); + }); + try { + await api.rotateManagedEncryptionKey(config.name, { targetKeyId: 'target', mode: 'online', + batchSize: 1, recoverable: true }, new Uint8Array(32).fill(55)); + throw new Error('Expected rotation interruption.'); + } catch (error) { + if (error.name !== 'AbortError') throw error; + } finally { unsubscribe(); } + const paused = await api.pauseManagedEncryptionKeyRotation(config.name); + if (!paused.paused || !paused.writesAllowed) throw new Error('The pause changed the online write policy.'); + }, config); + const peer = await context.newPage(); + await peer.goto(page.url()); + await peer.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + await api.createDb(config); + await api.authorizeManagedKeyRotation(config.name, 'original', new Uint8Array(32).fill(41), + 'target', new Uint8Array(32).fill(55)); + const row = await api.findItem(config.name, 'clients', 2); + if (row.secret !== 'Content 2') throw new Error('The source generation was not readable.'); + await api.putItem({ dbName: config.name, storeName: 'clients', + record: { id: 2, name: 'Updated in peer', secret: 'Updated content' } }); + await api.deleteItem({ dbName: config.name, storeName: 'clients', record: { id: 3 } }); + await api.addItem({ dbName: config.name, storeName: 'clients', + record: { id: 4, name: 'Inserted in peer', secret: 'New content' } }); + }, config); + const completed = await page.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + const status = await api.resumeManagedEncryptionKeyRotation(config.name, { batchSize: 1 }); + return { status, rows: await api.toArray(config.name, 'clients') }; + }, config); + assert.equal(completed.status.retirementReady, true); + assert.equal(completed.status.verified, 3); + assert.deepEqual(completed.rows, [ + { id: 1, name: 'Document 1', secret: 'Content 1' }, + { id: 2, name: 'Updated in peer', secret: 'Updated content' }, + { id: 4, name: 'Inserted in peer', secret: 'New content' } + ]); + const rejected = await peer.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + try { await api.putItem({ dbName: config.name, storeName: 'clients', + record: { id: 1, name: 'Stale write', secret: 'Must fail' } }); return false; } + catch { return true; } + }, config); + assert.equal(rejected, true); + await peer.close(); + }); + + test('lock and release revoke pending rotation authorization while a manifest response is withheld', async ({ page, context }) => { + const source = model(); + const deployment = initial(source); + const config = configuration('__magic_protected__:rotation-auth-lock', 'route', source, deployment.url); + await page.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + await api.createDb(config); + await api.unlockProtectedDatabase(config.name, 'first', new Uint8Array(32).fill(41), true); + await api.ensureProtectedMigration(config.name); + await api.addItem({ dbName: config.name, storeName: 'clients', record: { id: 1, name: 'Document', secret: 'Content' } }); + const stop = api.subscribeKeyRotationEvents(event => { + if (event.converted === 0) api.cancelManagedEncryptionKeyRotation(config.name); + }); + try { + await api.rotateManagedEncryptionKey(config.name, { targetKeyId: 'next', mode: 'online', + batchSize: 1, recoverable: true }, new Uint8Array(32).fill(83)); + throw new Error('Rotation should have been interrupted.'); + } catch (error) { if (error.name !== 'AbortError') throw error; } + finally { stop(); api.releaseProtectedDatabase(config.name); } + }, config); + const before = await page.evaluate(async physical => { + const db = await openRaw(physical); + try { return (await readRows(physical))[0].secret.keyId; } finally { db.close(); } + }, config.encryption.physicalName); + assert.equal(before, 'first'); + + for (const action of ['lockProtectedDatabase', 'releaseProtectedDatabase']) { + const peer = await context.newPage(); + await peer.goto(page.url()); + let releaseResponse; + const responseGate = new Promise(resolve => { releaseResponse = resolve; }); + let reached; + const intercepted = new Promise(resolve => { reached = resolve; }); + await peer.route(deployment.url, async route => { + reached(); + await responseGate; + await route.continue().catch(() => {}); // Aborting fetch may cancel the intercepted request. + }); + try { + await peer.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + await api.createDb(config); + const fetchResource = globalThis.fetch.bind(globalThis); + globalThis.fetch = (url, init) => { + if (String(url) === config.migrationManifestUrl) + init.signal.addEventListener('abort', () => { globalThis.resumeFetchAborted = true; }, { once: true }); + return fetchResource(url, init); + }; + globalThis.pendingAuthorization = api.authorizeManagedKeyRotation(config.name, 'first', new Uint8Array(32).fill(41), + 'next', new Uint8Array(32).fill(83)).then(() => ({ attached: true }), error => ({ + attached: false, name: error.name, code: error.code + })); + }, config); + await intercepted; + const revoked = await peer.evaluate(async ({ config, action }) => { + const api = await import('/engine/magicDB.js'); + api[action](config.name); + return { aborted: globalThis.resumeFetchAborted === true, + unlocked: await api.isProtectedDatabaseUnlocked(config.name), + state: await api.getProtectedDatabaseState(config.name) }; + }, { config, action }); + assert.deepEqual(revoked, { aborted: true, unlocked: false, + state: action === 'lockProtectedDatabase' ? 'Locked' : 'Inactive' }); + releaseResponse(); + const after = await peer.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + const outcome = await globalThis.pendingAuthorization; + if (outcome.attached) api.scheduleManagedKeyRotationResume(config.name); + return { outcome, unlocked: await api.isProtectedDatabaseUnlocked(config.name) }; + }, config); + assert.equal(after.outcome.attached, false); + assert.equal(after.unlocked, false); + } finally { + releaseResponse(); + await peer.close(); + } + } + const resumed = await page.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + await api.createDb(config); + const status = await api.authorizeManagedKeyRotation(config.name, 'first', new Uint8Array(32).fill(41), + 'next', new Uint8Array(32).fill(83)); + return { before: status.converted, + after: (await api.resumeManagedEncryptionKeyRotation(config.name, { batchSize: 1 })).converted }; + }, config); + assert.deepEqual(resumed, { before: 0, after: 1 }); + }); + + test('existing managed streams and a decrypting point read are fenced by exclusive admission in another tab', async ({ page, context }) => { + const source = model(); + const config = configuration('__magic_protected__:rotation-stream-fence', 'route', source, initial(source).url); + const initialReads = await page.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + await api.createDb(config); + await api.unlockProtectedDatabase(config.name, 'first', new Uint8Array(32).fill(41), true); + await api.ensureProtectedMigration(config.name); + for (const id of [1, 2, 3]) await api.addItem({ dbName: config.name, storeName: 'clients', + record: { id, name: 'Document ' + id, secret: 'Content ' + id } }); + globalThis.fullStream = api.wrapperMagicQueryYield(config.name, 'clients', null); + globalThis.projectionStream = api.projectRecordStream(config.name, 'clients', null, [], false, ['id', 'name']); + const first = [await fullStream.next(), await projectionStream.next()]; + const originalDecrypt = crypto.subtle.decrypt.bind(crypto.subtle); + crypto.subtle.decrypt = async (...args) => { + const result = await originalDecrypt(...args); + await new Promise(resolve => { globalThis.releasePointRead = resolve; }); + return result; + }; + globalThis.pointRead = api.findItem(config.name, 'clients', 2) + .then(value => ({ value }), error => ({ error: error.message })); + return first; + }, config); + assert.deepEqual(initialReads.map(item => item.value), [ + { id: 1, name: 'Document 1', secret: 'Content 1' }, { id: 1, name: 'Document 1' } + ]); + await page.waitForFunction(() => typeof globalThis.releasePointRead === 'function'); + const peer = await context.newPage(); + await peer.goto(page.url()); + try { + await peer.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + await api.createDb(config); + await api.unlockProtectedDatabase(config.name, 'first', new Uint8Array(32).fill(41)); + await api.ensureProtectedMigration(config.name); + const stop = api.subscribeKeyRotationEvents(() => api.cancelManagedEncryptionKeyRotation(config.name)); + try { + await api.rotateManagedEncryptionKey(config.name, { targetKeyId: 'next', mode: 'exclusive', + batchSize: 1, recoverable: true }, new Uint8Array(32).fill(83)); + throw new Error('Rotation should have been interrupted after admission.'); + } catch (error) { if (error.name !== 'AbortError') throw error; } + finally { stop(); } + }, config); + const outcomes = await page.evaluate(async () => { + delete crypto.subtle.decrypt; + globalThis.releasePointRead(); + const attempt = stream => stream.next().then(value => ({ value }), error => ({ error: error.message })); + return Promise.all([attempt(fullStream), attempt(projectionStream), pointRead]); + }); + for (const outcome of outcomes) { + assert.equal(outcome.value, undefined); + assert.match(outcome.error, /^MAGIC_ENCRYPTION_POLICY_MISMATCH:/); + } + } finally { await peer.close(); } + }); + + test('abrupt tab termination releases rotation ownership to a worker without replaying a committed batch', async ({ page, context }) => { + const physical = '__magic_protected__:rotation-tab-close'; + const source = model(); + const config = configuration(physical, 'route', source, initial(source).url); + const workerUrl = '/rotation-resume-worker.js'; + assets.set(workerUrl, { type: 'text/javascript', body: ` + import * as api from '/engine/magicDB.js'; + self.onmessage = async ({ data: config }) => { + try { + await api.createDb(config); + const partial = await api.authorizeManagedKeyRotation(config.name, 'original', new Uint8Array(32).fill(41), + 'target', new Uint8Array(32).fill(55)); + const completed = await api.resumeManagedEncryptionKeyRotation(config.name, { batchSize: 1 }); + self.postMessage({ partial, completed, rows: await api.toArray(config.name, 'clients') }); + } catch (error) { self.postMessage({ error: error.message }); } + finally { api.releaseProtectedDatabase(config.name); } + }; + ` }); + const readCiphertext = async physicalName => { + const db = await new Promise((resolve, reject) => { + const request = indexedDB.open(physicalName); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + try { + return await new Promise((resolve, reject) => { + const request = db.transaction('clients').objectStore('clients').get(1); + request.onsuccess = () => resolve(request.result.secret); + request.onerror = () => reject(request.error); + }); + } finally { db.close(); } + }; + const peer = await context.newPage(); + await peer.goto(page.url()); + await page.evaluate(async config => { + const api = await import('/engine/magicDB.js'); + await api.createDb(config); + await api.unlockProtectedDatabase(config.name, 'original', new Uint8Array(32).fill(41), true); + await api.ensureProtectedMigration(config.name); + for (const id of [1, 2, 3]) await api.addItem({ dbName: config.name, storeName: 'clients', + record: { id, name: 'Document ' + id, secret: 'Content ' + id } }); + api.subscribeKeyRotationEvents(event => { + if (event.phase !== 'converting' || event.converted !== 1) return; + crypto.subtle.encrypt = () => { + globalThis.rotationEncryptionPending = true; + return new Promise(() => {}); + }; + }); + void api.rotateManagedEncryptionKey(config.name, { + targetKeyId: 'target', mode: 'online', batchSize: 1, recoverable: true + }, new Uint8Array(32).fill(55)).catch(error => { globalThis.rotationFailure = error.message; }); + }, config); + await page.waitForFunction(() => globalThis.rotationEncryptionPending || globalThis.rotationFailure); + assert.equal(await page.evaluate(() => globalThis.rotationFailure ?? null), null); + const committed = await peer.evaluate(readCiphertext, physical); + assert.equal(typeof committed, 'object'); + await page.close(); + const result = await peer.evaluate(async ({ config, workerUrl }) => { + const worker = new Worker(workerUrl, { type: 'module' }); + try { + return await new Promise((resolve, reject) => { + worker.onmessage = event => resolve(event.data); + worker.onerror = event => reject(new Error(event.message)); + worker.postMessage(config); + }); + } finally { worker.terminate(); } + }, { config, workerUrl }); + assert.equal(result.error, undefined); + assert.equal(result.partial.converted, 1); + assert.equal(result.completed.converted, 3); + assert.equal(result.completed.verified, 3); + assert.equal(result.completed.retirementReady, true); + assert.deepEqual(await peer.evaluate(readCiphertext, physical), committed); + assert.deepEqual(result.rows.map(row => row.secret), ['Content 1', 'Content 2', 'Content 3']); + await peer.close(); + }); + + if (process.env.MAGIC_ROTATION_BENCHMARK === '1') { + for (const records of [1000, 10000, 100000]) for (const mode of ['exclusive', 'read-only', 'online']) { + test(`rotation benchmark: ${mode}, ${records} documents`, async ({ page }) => { + const source = model(); + const config = configuration('__magic_protected__:rotation-benchmark', 'route', source, initial(source).url); + const result = await page.evaluate(async ({ config, records, mode }) => { + const api = await import('/engine/magicDB.js'); + const route = config.name; + const sourceKey = new Uint8Array(32).fill(71), targetKey = new Uint8Array(32).fill(91); + await api.createDb(config); + await api.unlockProtectedDatabase(route, 'source', sourceKey, true); + await api.ensureProtectedMigration(route); + const payload = 'Text '.repeat(25); + for (let offset = 0; offset < records; offset += 256) { + const rows = Array.from({ length: Math.min(256, records - offset) }, (_, index) => ({ + id: offset + index + 1, name: 'Example', secret: payload + })); + await api.bulkAddItem(route, 'clients', rows); + } + const usage = () => navigator.storage.estimate().then(value => value.usage ?? null).catch(() => null); + const startUsage = await usage(); + const readSamples = [], writeSamples = []; + let observe; + let sampleError; + let verifyStart; + let verificationReadinessFences = 0; + let maxTimerLag = 0; + let peakHeap = performance.memory?.usedJSHeapSize ?? null; + let previous = performance.now(); + const read = () => api.findItem(route, 'clients', 1); + const sample = async (fn, values) => { + const start = performance.now(); + try { await fn(); values.push(performance.now() - start); } + catch (error) { + if (verifyStart !== undefined && error.message.startsWith('MAGDB_PROTECTION_STATE_INVALID:')) { + verificationReadinessFences++; + return; + } + if (!/^(MAGIC_ROTATION_ACCESS_FENCED|MAGIC_ROTATION_CONCURRENT_CHANGE|MAGIC_ENCRYPTION_POLICY_MISMATCH|MAGDB_AUTHORIZATION_REQUIRED):/.test(error.message)) throw error; + } + }; + const baseline = []; + for (let i = 0; i < 12; i++) await sample(read, baseline); + const unsubscribe = api.subscribeKeyRotationEvents(event => { + if (event.phase === 'verifying') verifyStart ??= performance.now(); + }); + const interval = setInterval(() => { + const now = performance.now(); + maxTimerLag = Math.max(maxTimerLag, now - previous - 20); + previous = now; + if (peakHeap !== null) peakHeap = Math.max(peakHeap, performance.memory.usedJSHeapSize); + if (observe || mode === 'exclusive') return; + observe = (async () => { + await sample(read, readSamples); + if (mode === 'online') await sample(() => api.putItem({ dbName: route, storeName: 'clients', + record: { id: records, name: 'Concurrent', secret: payload } }), writeSamples); + })().catch(error => { sampleError = error; }).finally(() => { observe = undefined; }); + }, 20); + const started = performance.now(); + let status; + let elapsed; + try { + status = await api.rotateManagedEncryptionKey(route, { + targetKeyId: 'target', mode, batchSize: 128, yieldBetweenBatches: true, recoverable: true + }, targetKey); + elapsed = performance.now() - started; + } finally { + clearInterval(interval); + unsubscribe(); + await observe; + } + if (sampleError) throw sampleError; + const percentile = values => values.length ? [...values].sort((a, b) => a - b) + [Math.min(values.length - 1, Math.floor(values.length * 0.95))] : null; + const endUsage = await usage(); + return { records, mode, elapsed, verificationElapsed: verifyStart === undefined ? null : + elapsed - (verifyStart - started), converted: status.converted, verified: status.verified, + retirementReady: status.retirementReady, baselineReadP95: percentile(baseline), + foregroundReadP95: percentile(readSamples), foregroundWriteP95: percentile(writeSamples), + foregroundReads: readSamples.length, foregroundWrites: writeSamples.length, + verificationReadinessFences, maxTimerLag, peakHeap, startUsage, endUsage }; + }, { config, records, mode }); + assert.equal(result.retirementReady, true); + assert.equal(result.verified, records); + console.log('ROTATION_BENCHMARK ' + JSON.stringify(result)); + }); + } + } + test('authenticated registration adopts a legacy vault and retires the older protected route', async ({ page }) => { const physical = '__magic_protected__:managed-legacy-adoption'; const before = model(); diff --git a/tests/migrations/rotation-journal.test.mjs b/tests/migrations/rotation-journal.test.mjs new file mode 100644 index 00000000..37d0371c --- /dev/null +++ b/tests/migrations/rotation-journal.test.mjs @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { importEncryptionKey } from '../../Magic.IndexedDb/wwwroot/utilities/encryptionEnvelope.js'; +import { sealRotationJournal, verifyRotationJournal } from '../../Magic.IndexedDb/wwwroot/utilities/rotationJournal.js'; + +globalThis.location = { origin: 'https://rotation.example.test' }; +const generate = () => importEncryptionKey(crypto.getRandomValues(new Uint8Array(32))); +const keys = new Map([['old', await generate()], ['new', await generate()]]); +const vault = { database: 'catalog', account: 'account' }; +const lease = () => {}; +const state = { + version: 1, rotationId: 'operation-1', sourceKeyId: 'old', targetKeyId: 'new', + mode: 'online', modelHash: 'model', policyFingerprint: 'policy', writeKeyId: 'new', priorKeyIds: ['old'], + sequence: 1, phase: 'converting', storeIndex: 0, afterKey: ['documents', 42], + converted: 2, verified: 0, paused: false +}; + +test('both keys authenticate exact rotation progress and the native compound checkpoint', async () => { + const document = await sealRotationJournal(state, keys, vault, lease); + assert.deepEqual(await verifyRotationJournal(document, keys, vault, lease), state); + await assert.rejects(verifyRotationJournal(document, new Map([['new', keys.get('new')]]), vault, lease), /KEY_UNAVAILABLE/); + await assert.rejects(verifyRotationJournal(document, new Map(keys).set('old', await generate()), vault, lease), /STATE_INVALID/); +}); + +test('journal binds mode, account, database, write generation and checkpoint', async () => { + const document = await sealRotationJournal(state, keys, vault, lease); + for (const patch of [{ mode: 'exclusive' }, { afterKey: ['documents', 43] }, { writeKeyId: 'old' }]) { + await assert.rejects(verifyRotationJournal({ ...document, state: { ...state, ...patch } }, keys, vault, lease), /STATE_INVALID/); + } + await assert.rejects(verifyRotationJournal(document, keys, { ...vault, account: 'other' }, lease), /STATE_INVALID/); + await assert.rejects(verifyRotationJournal(document, keys, { ...vault, database: 'other' }, lease), /STATE_INVALID/); +}); + +test('mixed checkpoints, missing seals and revoked leases cannot authenticate', async () => { + const first = await sealRotationJournal(state, keys, vault, lease); + const second = await sealRotationJournal({ ...state, sequence: 2, converted: 3 }, keys, vault, lease); + await assert.rejects(verifyRotationJournal({ ...second, sourceSeal: first.sourceSeal }, keys, vault, lease), /STATE_INVALID/); + await assert.rejects(verifyRotationJournal({ ...first, targetSeal: undefined }, keys, vault, lease), /STATE_INVALID/); + let checks = 0; + await assert.rejects(verifyRotationJournal(first, keys, vault, () => { + if (++checks > 1) throw new Error('authorization revoked'); + }), /authorization revoked/); +}); + +test('foreground write fence changes at verification but not on ordinary progress', async () => { + const { sealRotationFence, verifyRotationFence } = await import('../../Magic.IndexedDb/wwwroot/utilities/rotationFence.js'); + const target = keys.get('new'); + const fence = await sealRotationFence(state, target, vault, lease); + await verifyRotationFence(fence, { ...state, sequence: 2, converted: 3 }, target, vault, lease); + await assert.rejects(verifyRotationFence(fence, { ...state, phase: 'verifying' }, target, vault, lease), /STATE_INVALID/); + await assert.rejects(verifyRotationFence(fence, { ...state, mode: 'exclusive' }, target, vault, lease), /STATE_INVALID/); +}); + +test('admission rejects two non-extractable references to the same key material', async () => { + const { assertDistinctRotationKeys } = await import('../../Magic.IndexedDb/wwwroot/utilities/rotationFence.js'); + const bytes = crypto.getRandomValues(new Uint8Array(32)); + const first = await importEncryptionKey(bytes); + const second = await importEncryptionKey(bytes); + bytes.fill(0); + await assert.rejects(assertDistinctRotationKeys(first, second, 'original', vault, lease), /KEY_REUSED/); + await assertDistinctRotationKeys(first, keys.get('new'), 'original', vault, lease); +}); diff --git a/tests/migrations/rotation-record.test.mjs b/tests/migrations/rotation-record.test.mjs new file mode 100644 index 00000000..37c46855 --- /dev/null +++ b/tests/migrations/rotation-record.test.mjs @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { importEncryptionKey } from '../../Magic.IndexedDb/wwwroot/utilities/encryptionEnvelope.js'; +import { encryptedRecordMember, openRecord, sealRecord } from '../../Magic.IndexedDb/wwwroot/utilities/encryptionRecord.js'; +import { openRotatingRecord, prepareRotatedRecord } from '../../Magic.IndexedDb/wwwroot/utilities/rotationRecord.js'; + +globalThis.location = { origin: 'https://rotation.example.test' }; + +const original = await importEncryptionKey(crypto.getRandomValues(new Uint8Array(32))); +const target = await importEncryptionKey(crypto.getRandomValues(new Uint8Array(32))); +const keys = new Map([['original', original], ['target', target]]); +const context = { database: 'example', account: 'owner', store: 'documents', primaryKey: ['catalog', 7] }; +const row = { group: 'catalog', id: 7, label: 'Example', details: { exact: '9007199254740993' } }; + +for (const [name, policy, member] of [ + ['field', { fields: new Set(['details', 'optional']), exposed: null }, 'details'], + ['record', { fields: new Set(), exposed: new Set(['group', 'id', 'label']) }, encryptedRecordMember], +]) { + test(`authenticates and converts a ${name}-protected record without changing public or nested values`, async () => { + const saved = await sealRecord(row, policy, original, 'original', context); + assert.deepEqual(await openRotatingRecord(saved, policy, keys, context), { record: row, keyId: 'original' }); + const rotated = await prepareRotatedRecord(saved, policy, keys, 'target', context); + assert.equal(rotated.label, row.label); + assert.notDeepEqual(rotated[member].nonce, saved[member].nonce); + assert.deepEqual(await openRotatingRecord(rotated, policy, new Map([['target', target]]), context), + { record: row, keyId: 'target' }); + await assert.rejects(openRecord(rotated, policy, original, 'target', context), /authentication failed/); + assert.equal(await prepareRotatedRecord(rotated, policy, keys, 'target', context), null); + }); + + test(`rejects unauthorized or invalid generation hints for a ${name}-protected record`, async () => { + const saved = await sealRecord(row, policy, original, 'original', context); + await assert.rejects(openRotatingRecord(saved, policy, new Map(), context), /KEY_UNAVAILABLE/); + await assert.rejects(openRotatingRecord(saved, policy, keys, { ...context, database: 'different' }), /RECORD_INVALID/); + const altered = structuredClone(saved); + altered[member].keyId = 'target'; + await assert.rejects(prepareRotatedRecord(altered, policy, keys, 'target', context), /RECORD_INVALID/); + }); +} + +test('records without protected members require no conversion', async () => { + const policy = { fields: new Set(), exposed: null }; + assert.deepEqual(await openRotatingRecord(row, policy, new Map(), context), { record: row, keyId: null }); + assert.equal(await prepareRotatedRecord(row, policy, keys, 'target', context), null); +}); diff --git a/tests/migrations/run.mjs b/tests/migrations/run.mjs index 600a32ca..3ae5abf1 100644 --- a/tests/migrations/run.mjs +++ b/tests/migrations/run.mjs @@ -1625,10 +1625,144 @@ if (cliFixture) for (const [codecCase, sourceHasCodec] of [['absent-to-null', fa }); } +test('rotation batch preserves a concurrent write and commits conversion with its checkpoint', async ({ page }) => { + await page.goto(origin + '/'); + const result = await page.evaluate(async () => { + const { readRotationBatch, commitRotationBatch } = await import('/engine/utilities/rotationBatch.js'); + const open = indexedDB.open('rotation-transaction-fixture'); + const request = operation => new Promise((resolve, reject) => { + operation.onsuccess = () => resolve(operation.result); + operation.onerror = () => reject(operation.error); + }); + open.onupgradeneeded = () => { + open.result.createObjectStore('documents', { keyPath: ['group', 'id'] }); + open.result.createObjectStore('metadata'); + }; + const db = await request(open); + const put = async (store, value, key) => { + const tx = db.transaction(store, 'readwrite'); + return await request(key === undefined ? tx.objectStore(store).put(value) : tx.objectStore(store).put(value, key)); + }; + const key = ['catalog', 1]; + const original = { group: 'catalog', id: 1, label: 'original', ciphertext: Uint8Array.of(1) }; + const patch = { ...original, label: 'concurrent' }; + await put('documents', original); + await put('metadata', { phase: 0 }, 'progress'); + const [snapshot] = await readRotationBatch(db, 'documents', null, 1); + await put('documents', patch); + const progress = { store: 'metadata', key: 'progress', value: { phase: 0 } }; + const next = { ...progress, value: { phase: 1 } }; + const expect = { store: 'documents', key, value: snapshot.record }; + const write = { store: 'documents', key, value: { ...patch, ciphertext: Uint8Array.of(2) } }; + const stale = await commitRotationBatch(db, [expect, progress], [write, next], () => {}); + const afterStale = await request(db.transaction('metadata').objectStore('metadata').get('progress')); + const fresh = await commitRotationBatch(db, [{ ...expect, value: patch }, progress], [write, next], () => {}); + const final = await request(db.transaction('metadata').objectStore('metadata').get('progress')); + const [row] = await readRotationBatch(db, 'documents', null, 1); + const remainder = await readRotationBatch(db, 'documents', key, 1); + const unsupported = { ...row.record, foreign: new Map([['example', 'content']]) }; + await put('documents', unsupported); + const [foreign] = await readRotationBatch(db, 'documents', null, 1); + let unsupportedCode = null; + try { + await commitRotationBatch(db, [{ store: 'documents', key, value: foreign.record }, + { ...progress, value: { phase: 1 } }], [write, { ...next, value: { phase: 2 } }], () => {}); + } catch (error) { unsupportedCode = error.message.split(':')[0]; } + const protectedProgress = await request(db.transaction('metadata').objectStore('metadata').get('progress')); + const [retained] = await readRotationBatch(db, 'documents', null, 1); + db.close(); + return { stale, fresh, afterStale, final, label: row.record.label, bytes: [...row.record.ciphertext], remainder, + unsupportedCode, protectedProgress, retained: [...retained.record.foreign] }; + }); + assert.deepEqual(result, { stale: false, fresh: true, afterStale: { phase: 0 }, final: { phase: 1 }, + label: 'concurrent', bytes: [2], remainder: [], unsupportedCode: 'MAGIC_ROTATION_RECORD_UNSUPPORTED', + protectedProgress: { phase: 1 }, retained: [['example', 'content']] }); +}); + +test('rotation checkpoints preserve compound keys across protected and public stores', async ({ page }) => { + await page.goto(origin + '/'); + const result = await page.evaluate(async () => { + const { advanceRotationPass } = await import('/engine/utilities/rotationPass.js'); + const { sealRotationJournal, rotationJournalKey } = await import('/engine/utilities/rotationJournal.js'); + const { encryptionMetadataStore } = await import('/engine/utilities/encryptionPolicy.js'); + const { sealRecord, openRecord } = await import('/engine/utilities/encryptionRecord.js'); + const { importEncryptionKey } = await import('/engine/utilities/encryptionEnvelope.js'); + const generate = () => importEncryptionKey(crypto.getRandomValues(new Uint8Array(32))); + const keys = new Map([['old', await generate()], ['new', await generate()]]); + const open = indexedDB.open('rotation-checkpoint-fixture'); + const request = operation => new Promise((resolve, reject) => { + operation.onsuccess = () => resolve(operation.result); + operation.onerror = () => reject(operation.error); + }); + open.onupgradeneeded = () => { + open.result.createObjectStore('documents', { keyPath: ['group', 'id'] }).createIndex('byGroup', 'group'); + open.result.createObjectStore('archive', { keyPath: 'id' }); + open.result.createObjectStore('settings', { keyPath: 'id' }); + open.result.createObjectStore(encryptionMetadataStore); + }; + const db = await request(open); + const vault = { database: db.name, account: 'catalog-account' }; + const policy = { fields: new Set(['content']), exposed: null }; + const context = primaryKey => ({ ...vault, store: 'documents', primaryKey }); + const put = async (storeName, value, key) => { + const store = db.transaction(storeName, 'readwrite').objectStore(storeName); + await request(key === undefined ? store.put(value) : store.put(value, key)); + }; + const get = (storeName, key) => request(db.transaction(storeName).objectStore(storeName).get(key)); + const group = 'catalog'; + const documentKeys = ['9007199254740993', '9007199254740994'].map(id => [group, id]); + const contents = documentKeys.map(([, id]) => ({ nested: [{ exact: id, decimal: '1.00000000000000000001' }] })); + for (const [index, key] of documentKeys.entries()) + await put('documents', await sealRecord({ group, id: key[1], content: contents[index] }, policy, keys.get('old'), 'old', context(key))); + await put('settings', { id: 1, label: 'Public configuration' }); + const assertCurrent = () => {}; + const document = await sealRotationJournal({ + version: 1, rotationId: 'rotation', sourceKeyId: 'old', targetKeyId: 'new', mode: 'exclusive', + modelHash: 'model', policyFingerprint: 'policy', writeKeyId: 'new', priorKeyIds: ['old'], sequence: 0, + phase: 'converting', storeIndex: 0, afterKey: null, converted: 0, verified: 0, paused: false + }, keys, vault, assertCurrent); + await put(encryptionMetadataStore, document, rotationJournalKey); + const install = async state => put(encryptionMetadataStore, await sealRotationJournal(state, keys, vault, assertCurrent), rotationJournalKey); + const step = async () => advanceRotationPass({ db, vault, keys, document: await get(encryptionMetadataStore, rotationJournalKey), + policies: new Map([['archive', policy], ['documents', policy], + ['settings', { fields: new Set(), exposed: null }]]), expectations: [], batchSize: 1, assertCurrent }); + await step(); // Skip the empty protected store. + await step(); // Commit one record and its compound checkpoint. + const mixed = await Promise.all(documentKeys.map(async key => (await get('documents', key)).content.keyId)); + const finishPass = async () => { + for (let i = 0; i < 6; i++) if ((await step()).outcome === 'pass-complete') return; + throw new Error('The bounded rotation pass did not finish.'); + }; + await finishPass(); + const converted = (await get(encryptionMetadataStore, rotationJournalKey)).state; + // Exercise the verification scan against a persisted phase. The full + // lifecycle coordinator installs its finalization fence at this boundary. + await install({ ...converted, phase: 'verifying', storeIndex: 0 }); + await finishPass(); + const final = (await get(encryptionMetadataStore, rotationJournalKey)).state; + const rows = []; + for (const key of documentKeys) + rows.push(await openRecord(await get('documents', key), policy, keys.get('new'), 'new', context(key))); + let oldKeyRejected = false; + try { + const key = documentKeys[0]; + await openRecord(await get('documents', key), policy, keys.get('old'), 'new', context(key)); + } catch { oldKeyRejected = true; } + const indexedKeys = await request(db.transaction('documents').objectStore('documents').index('byGroup').getAllKeys(group)); + const publicRow = await get('settings', 1); + db.close(); + return { mixed, converted: final.converted, verified: final.verified, rows, indexedKeys, publicRow, oldKeyRejected }; + }); + const ids = ['9007199254740993', '9007199254740994']; + assert.deepEqual(result, { mixed: ['new', 'old'], converted: 2, verified: 2, + rows: ids.map(id => ({ group: 'catalog', id, content: { nested: [{ exact: id, decimal: '1.00000000000000000001' }] } })), + indexedKeys: ids.map(id => ['catalog', id]), publicRow: { id: 1, label: 'Public configuration' }, oldKeyRejected: true }); +}); + registerProtectedEngineTests({ test, schema, bundle, copy, inspect, read, loadPage, recoveryPackage, appendRevision, jsonAsset, assets, cliFixture, getOrigin: () => origin }); registerProtectedRegistrationTests({ test, schema, bundle, jsonAsset, copy, registrationStore, inspect, appendRevision, assets }); -const expectedScenarioCount = cliFixture ? 126 : 122; +const expectedScenarioCount = (cliFixture ? 142 : 138) + (process.env.MAGIC_ROTATION_BENCHMARK === "1" ? 9 : 0); assert.equal(tests.length, expectedScenarioCount, 'Unexpected migration scenario count.'); if (listOnly) { @@ -1693,7 +1827,8 @@ try { let timer; try { await Promise.race([scenario.run({ page, context }), new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error('Scenario exceeded 35 seconds.')), 35_000); + const timeout = scenario.name.startsWith('rotation benchmark:') ? 900_000 : 35_000; + timer = setTimeout(() => reject(new Error(`Scenario exceeded ${timeout / 1000} seconds.`)), timeout); })]); } finally { clearTimeout(timer); } if (pageErrors.length) throw new Error('Unhandled browser error:\n' + pageErrors.join('\n'));