diff --git a/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj b/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj index f31f06b3..18ffabeb 100644 --- a/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj +++ b/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj @@ -7,7 +7,7 @@ true magicdb Magic.IndexedDb.Cli - 3.0.0 + 3.1.0 Magic Man Code-first, language-independent migration planning, validation, and static publishing for Magic IndexedDB. https://github.com/magiccodingman/Magic.IndexedDb diff --git a/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt b/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt index fe64434f..7bb2419f 100644 --- a/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt +++ b/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt @@ -247,7 +247,14 @@ enum Magic.IndexedDb.LinqTranslation.Models.FilterNodeType : System.IComparable, field System.Int32 value__ field static Magic.IndexedDb.LinqTranslation.Models.FilterNodeType Condition = 1 field static Magic.IndexedDb.LinqTranslation.Models.FilterNodeType Logical = 0 +enum Magic.IndexedDb.MagicConditionalMutationResult : System.IComparable, System.IConvertible, System.IFormattable, System.ISpanFormattable + field System.Int32 value__ + field static Magic.IndexedDb.MagicConditionalMutationResult Applied = 1 + field static Magic.IndexedDb.MagicConditionalMutationResult Conflict = 0 static class Magic.IndexedDb.MagicEncryptedQueryExtensions + method static System.Threading.Tasks.Task DeleteProtectedIfCurrentAsync(Magic.IndexedDb.IMagicQuery source, T expectedRecord, System.Linq.Expressions.Expression> revision, Magic.IndexedDb.IMagicQuery workspace, TWorkspace expectedWorkspace, System.Linq.Expressions.Expression> generation, System.Threading.CancellationToken cancellationToken = null) + method static System.Threading.Tasks.Task InsertProtectedIfCurrentAsync(Magic.IndexedDb.IMagicQuery source, T record, Magic.IndexedDb.IMagicQuery workspace, TWorkspace expectedWorkspace, System.Linq.Expressions.Expression> generation, System.Threading.CancellationToken cancellationToken = null) + method static System.Threading.Tasks.Task ReplaceProtectedIfCurrentAsync(Magic.IndexedDb.IMagicQuery source, T expectedRecord, T replacement, System.Linq.Expressions.Expression> revision, Magic.IndexedDb.IMagicQuery workspace, TWorkspace expectedWorkspace, System.Linq.Expressions.Expression> generation, System.Threading.CancellationToken cancellationToken = null) method static System.Threading.Tasks.Task> SelectPublicAsync(Magic.IndexedDb.IMagicExecute source, System.Linq.Expressions.Expression> member, System.Threading.CancellationToken cancellationToken = null) method static System.Threading.Tasks.Task PatchPublicAsync(Magic.IndexedDb.IMagicQuery source, T recordWithKey, System.Linq.Expressions.Expression> member, System.Threading.CancellationToken cancellationToken = null) class Magic.IndexedDb.MagicEncryptionContext : System.IEquatable diff --git a/Magic.IndexedDb.UnitTests/WireProtocolTests.cs b/Magic.IndexedDb.UnitTests/WireProtocolTests.cs index f79c5a79..8e29a740 100644 --- a/Magic.IndexedDb.UnitTests/WireProtocolTests.cs +++ b/Magic.IndexedDb.UnitTests/WireProtocolTests.cs @@ -27,7 +27,7 @@ public async Task VersionTwoEnvelope_WritesArgumentsAsJsonValues() }; await using var stream = new MemoryStream(); - await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package, settings); + await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package); stream.Position = 0; using var document = await JsonDocument.ParseAsync(stream); var root = document.RootElement; diff --git a/Magic.IndexedDb/Encryption/EncryptionConfiguration.cs b/Magic.IndexedDb/Encryption/EncryptionConfiguration.cs index df41290e..86c772e2 100644 --- a/Magic.IndexedDb/Encryption/EncryptionConfiguration.cs +++ b/Magic.IndexedDb/Encryption/EncryptionConfiguration.cs @@ -2,6 +2,7 @@ using System.Reflection; using System.Security.Cryptography; using System.Text.Json; +using System.Text.Json.Nodes; using Magic.IndexedDb.Helpers; using Magic.IndexedDb.SchemaAnnotations; @@ -106,35 +107,43 @@ public JsonElement CreateDatabase(IEnumerable<(Type Type, StoreSchema Schema)> s "Configure whole-record encryption with an explicit public allowlist instead."); } - return new + return new JsonObject { - entry.Schema.TableName, - entry.Schema.PrimaryKeyAuto, - entry.Schema.ColumnNamesInCompoundKey, - entry.Schema.Indexes, - entry.Schema.UniqueIndexes, - entry.Schema.ColumnNamesInCompoundIndex, - EncryptedFields = protectedFields, - ExposedFields = exposedFields + ["tableName"] = entry.Schema.TableName, + ["primaryKeyAuto"] = entry.Schema.PrimaryKeyAuto, + ["columnNamesInCompoundKey"] = Strings(entry.Schema.ColumnNamesInCompoundKey), + ["indexes"] = Strings(entry.Schema.Indexes), + ["uniqueIndexes"] = Strings(entry.Schema.UniqueIndexes), + ["columnNamesInCompoundIndex"] = new JsonArray(entry.Schema.ColumnNamesInCompoundIndex.Select(Strings).ToArray()), + ["encryptedFields"] = Strings(protectedFields), + ["exposedFields"] = exposedFields is null ? null : Strings(exposedFields) }; }).ToArray(); - if (_recordPolicies.Keys.Any(table => !rows.Any(row => row.TableName == table))) + if (_recordPolicies.Keys.Any(table => !rows.Any(row => row["tableName"]!.GetValue() == table))) throw new InvalidOperationException("A Magic record policy names an unregistered table."); - var payload = new Dictionary + var payload = new JsonObject { ["name"] = Route, ["version"] = 1, - ["storeSchemas"] = rows, - ["encryption"] = new { Account = Request.AccountScope, PhysicalName, - ExplicitPhysicalBinding = HasExplicitPhysicalBinding } + ["storeSchemas"] = new JsonArray(rows), + ["encryption"] = new JsonObject + { + ["account"] = Request.AccountScope, + ["physicalName"] = PhysicalName, + ["explicitPhysicalBinding"] = HasExplicitPhysicalBinding + } }; if (_numericMode == MagicNumericStorageMode.Lossless) { - payload["numericStorage"] = NumericStorageConfiguration.Policy; + payload["numericStorage"] = new JsonObject { ["version"] = 1, ["mode"] = "lossless" }; payload["numericLegacyName"] = _legacyPhysicalName; } - return JsonSerializer.SerializeToElement(payload, new JsonSerializerOptions(JsonSerializerDefaults.Web)); + using var document = JsonDocument.Parse(payload.ToJsonString()); + return document.RootElement.Clone(); } + + private static JsonArray Strings(IEnumerable values) => + new(values.Select(value => (JsonNode?)JsonValue.Create(value)).ToArray()); } diff --git a/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs b/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs index a3c360bd..dd987683 100644 --- a/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs +++ b/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs @@ -58,6 +58,61 @@ public static Task PatchPublicAsync( JsonSerializer.SerializeToElement(new Dictionary { [name] = value }), cancellationToken); } + /// Replaces a protected record if its revision and the workspace generation still match. + public static Task ReplaceProtectedIfCurrentAsync( + this IMagicQuery source, T expectedRecord, T replacement, Expression> revision, + IMagicQuery workspace, TWorkspace expectedWorkspace, Expression> generation, + CancellationToken cancellationToken = default) where T : class where TWorkspace : class + { + ArgumentNullException.ThrowIfNull(replacement); + return MutateIfCurrent(source, expectedRecord, replacement, revision, workspace, expectedWorkspace, generation, cancellationToken); + } + + /// Deletes a protected record if its revision and the workspace generation still match. + public static Task DeleteProtectedIfCurrentAsync( + this IMagicQuery source, T expectedRecord, Expression> revision, + IMagicQuery workspace, TWorkspace expectedWorkspace, Expression> generation, + CancellationToken cancellationToken = default) where T : class where TWorkspace : class => + MutateIfCurrent(source, expectedRecord, null, revision, workspace, expectedWorkspace, generation, cancellationToken); + + /// Inserts a protected record with an unused key if the workspace generation still matches. + public static Task InsertProtectedIfCurrentAsync( + this IMagicQuery source, T record, IMagicQuery workspace, TWorkspace expectedWorkspace, + Expression> generation, CancellationToken cancellationToken = default) + where T : class where TWorkspace : class => + MutateIfCurrent(source, record, record, null, workspace, expectedWorkspace, + generation, cancellationToken); + + private static async Task MutateIfCurrent( + IMagicQuery source, T expectedRecord, T? replacement, Expression>? revision, + IMagicQuery workspace, TWorkspace expectedWorkspace, Expression> generation, + CancellationToken token) where T : class where TWorkspace : class + { + if (source is not MagicQuery query || workspace is not MagicQuery workspaceQuery || + query.Manager != workspaceQuery.Manager || query.DatabaseName != workspaceQuery.DatabaseName) + throw new ArgumentException("Both tables must belong to the same managed database context."); + ArgumentNullException.ThrowIfNull(expectedRecord); + ArgumentNullException.ThrowIfNull(expectedWorkspace); + var settings = query.Manager.Settings(query.DatabaseName); + var record = MagicSerializationHelper.SerializeObjectToJsonElement(expectedRecord, settings); + var workspaceRecord = MagicSerializationHelper.SerializeObjectToJsonElement(expectedWorkspace, settings); + var revisionName = revision is null ? null : MappedMember(revision).JsPropertyName; + var generationName = MappedMember(generation).JsPropertyName; + var next = replacement is null ? (JsonElement?)null : MagicSerializationHelper.SerializeObjectToJsonElement(replacement, settings); + var applied = await query.Manager.ConditionalProtectedMutationAsync(query, workspaceQuery.SchemaName, + KeyOf(expectedRecord, record), revisionName, revisionName is null ? null : record.GetProperty(revisionName), + KeyOf(expectedWorkspace, workspaceRecord), generationName, workspaceRecord.GetProperty(generationName), next, token); + return applied ? MagicConditionalMutationResult.Applied : MagicConditionalMutationResult.Conflict; + } + + private static System.Text.Json.Nodes.JsonObject KeyOf(T item, JsonElement serialized) where T : class + { + var key = new System.Text.Json.Nodes.JsonObject(); + foreach (var part in AttributeHelpers.GetPrimaryKeys(item)) + key[part.JsName] = System.Text.Json.Nodes.JsonNode.Parse(serialized.GetProperty(part.JsName).GetRawText()); + return key; + } + private static MagicPropertyEntry MappedMember(Expression> member) { ArgumentNullException.ThrowIfNull(member); @@ -72,3 +127,10 @@ private static MagicPropertyEntry MappedMember(ExpressionThe outcome of an atomic conditional protected mutation. +public enum MagicConditionalMutationResult +{ + Conflict, + Applied +} diff --git a/Magic.IndexedDb/Extensions/MagicJsInvoke.cs b/Magic.IndexedDb/Extensions/MagicJsInvoke.cs index 083c000a..2e093028 100644 --- a/Magic.IndexedDb/Extensions/MagicJsInvoke.cs +++ b/Magic.IndexedDb/Extensions/MagicJsInvoke.cs @@ -108,7 +108,7 @@ internal async Task CallInvokeVoidDefaultJsAsync(string modulePath, string funct string instanceId = Guid.NewGuid().ToString(); using var stream = new MemoryStream(); - await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package, settings, token); + await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package, token); stream.Position = 0; @@ -146,7 +146,7 @@ internal async Task CallInvokeVoidDefaultJsAsync(string modulePath, string funct string instanceId = Guid.NewGuid().ToString(); using var stream = new MemoryStream(); - await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package, settings, token); + await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package, token); stream.Position = 0; using var streamRef = new DotNetStreamReference(stream); diff --git a/Magic.IndexedDb/Extensions/ServiceCollectionExtensions.cs b/Magic.IndexedDb/Extensions/ServiceCollectionExtensions.cs index a7260646..bc624f91 100644 --- a/Magic.IndexedDb/Extensions/ServiceCollectionExtensions.cs +++ b/Magic.IndexedDb/Extensions/ServiceCollectionExtensions.cs @@ -1,4 +1,5 @@ -using Magic.IndexedDb.Factories; +using System.Diagnostics.CodeAnalysis; +using Magic.IndexedDb.Factories; using Magic.IndexedDb.Helpers; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -63,7 +64,7 @@ public static IServiceCollection AddMagicBlazorDB(this IServiceCollection servic } /// Registers account-bound encryption policies and an application-supplied key provider. - public static IServiceCollection AddMagicIndexedDbEncryption(this IServiceCollection services, + public static IServiceCollection AddMagicIndexedDbEncryption<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TProvider>(this IServiceCollection services, Func> configure) where TProvider : class, IMagicEncryptionKeyProvider { @@ -81,7 +82,7 @@ public static IServiceCollection AddMagicIndexedDbEncryption(this ISe } /// Registers an application key provider for runtime account activation. - public static IServiceCollection AddMagicIndexedDbEncryption(this IServiceCollection services) + public static IServiceCollection AddMagicIndexedDbEncryption<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TProvider>(this IServiceCollection services) where TProvider : class, IMagicEncryptionKeyProvider => services.AddMagicIndexedDbEncryption(_ => []); diff --git a/Magic.IndexedDb/Factories/MagicDbFactory.cs b/Magic.IndexedDb/Factories/MagicDbFactory.cs index 80066e9f..067bd7a9 100644 --- a/Magic.IndexedDb/Factories/MagicDbFactory.cs +++ b/Magic.IndexedDb/Factories/MagicDbFactory.cs @@ -207,7 +207,8 @@ private async Task CreateDatabaseAsync(ResolvedMagicDatabase resolved, string in var document = JsonNode.Parse(payload.GetRawText())!.AsObject(); document["migrationSchema"] = JsonNode.Parse(MagicSchemaJson.Serialize(resolved.Schema)); document["migrationManifestUrl"] = resolved.Definition.ManifestUrl; - payload = JsonSerializer.SerializeToElement(document); + using var wireDocument = JsonDocument.Parse(document.ToJsonString()); + payload = wireDocument.RootElement.Clone(); var module = await _jsModule!.Value; if (_encryption.ContainsKey(name) || _numericStorage.Mode(name) == MagicNumericStorageMode.Lossless) await EncryptionUnlock.InvokeAsync(module, IndexedDbFunctions.CREATE_LEGACY, true, payload); diff --git a/Magic.IndexedDb/Helpers/MagicSerializationHelper.cs b/Magic.IndexedDb/Helpers/MagicSerializationHelper.cs index 35f95581..11e571f3 100644 --- a/Magic.IndexedDb/Helpers/MagicSerializationHelper.cs +++ b/Magic.IndexedDb/Helpers/MagicSerializationHelper.cs @@ -1,6 +1,9 @@ using Magic.IndexedDb.Interfaces; using Magic.IndexedDb.Models; using System.Text.Json; +using System.Diagnostics.CodeAnalysis; +using Magic.IndexedDb.LinqTranslation.Models; +using Magic.IndexedDb.Models.UniversalOperations; namespace Magic.IndexedDb.Helpers; @@ -28,6 +31,12 @@ public static string[] SerializeObjectsToString(ITypedArgument[] objs, MagicJson return objs.Select(arg => arg.SerializeToJsonString(settings)).ToArray(); } + [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(StoreRecord<>))] + [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(UpdateRecord<>))] + [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(PrimaryKeys))] + [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(FilterNode))] + [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(FilterCondition))] + [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(StoredMagicQuery))] public static JsonElement SerializeObjectToJsonElement(T value, MagicJsonSerializationSettings? settings = null) { if (settings == null) @@ -70,16 +79,26 @@ public static async Task SerializeObjectToStreamAsync(Stream stream, T value, internal static async Task SerializeJsPackageToStreamAsync( Stream stream, MagicJsPackage package, - MagicJsonSerializationSettings settings, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(stream); ArgumentNullException.ThrowIfNull(package); - // The envelope is infrastructure JSON. Its JsonElement parameters have already - // been serialized with Magic's contracts and must be written as raw JSON values. - var options = new JsonSerializerOptions(settings.Options); - await JsonSerializer.SerializeAsync(stream, package, options, cancellationToken); + // The wire envelope has stable names under both the standard and + // fully linked runtimes. Arguments already carry their own contracts. + using var writer = new Utf8JsonWriter(stream); + writer.WriteStartObject(); + writer.WriteNumber("protocolVersion", package.ProtocolVersion); + writer.WriteBoolean("yieldResults", package.YieldResults); + writer.WriteString("modulePath", package.ModulePath); + writer.WriteString("methodName", package.MethodName); + writer.WriteBoolean("isVoid", package.IsVoid); + writer.WriteStartArray("parameters"); + foreach (var parameter in package.Parameters) + parameter.WriteTo(writer); + writer.WriteEndArray(); + writer.WriteEndObject(); + await writer.FlushAsync(cancellationToken); await stream.FlushAsync(cancellationToken); } diff --git a/Magic.IndexedDb/IndexDbManager.cs b/Magic.IndexedDb/IndexDbManager.cs index a358c851..01ba2122 100644 --- a/Magic.IndexedDb/IndexDbManager.cs +++ b/Magic.IndexedDb/IndexDbManager.cs @@ -356,6 +356,33 @@ internal Task PatchPublicAsync(MagicQuery query, object key, JsonElem new TypedArgument(JsonSerializer.SerializeToElement(key)), new TypedArgument(changes)); + internal Task ConditionalProtectedMutationAsync(MagicQuery query, string workspaceStore, + System.Text.Json.Nodes.JsonObject record, string? revision, JsonElement? expectedRevision, + System.Text.Json.Nodes.JsonObject workspace, string generation, JsonElement expectedGeneration, + JsonElement? replacement, CancellationToken token) where T : class + { + using var payload = JsonDocument.Parse(new System.Text.Json.Nodes.JsonObject + { + ["record"] = record, + ["revision"] = expectedRevision is null ? null : new System.Text.Json.Nodes.JsonObject + { + ["member"] = revision, + ["expected"] = System.Text.Json.Nodes.JsonNode.Parse(expectedRevision.Value.GetRawText()) + }, + ["generation"] = new System.Text.Json.Nodes.JsonObject + { + ["member"] = generation, + ["expected"] = System.Text.Json.Nodes.JsonNode.Parse(expectedGeneration.GetRawText()), + ["record"] = workspace + }, + ["replacement"] = replacement.HasValue + ? System.Text.Json.Nodes.JsonNode.Parse(replacement.Value.GetRawText()) : null + }.ToJsonString()); + return Invocation(query.DatabaseName).CallJsAsync(Cache.MagicDbJsImportPath, "conditionalProtectedMutation", + token, new TypedArgument(Route(query.DatabaseName)), new TypedArgument(query.SchemaName), + new TypedArgument(workspaceStore), new TypedArgument(payload.RootElement.Clone())); + } + internal async Task DeleteAsync(T item, string dbName, CancellationToken cancellationToken = default) where T : class { string schemaName = SchemaHelper.GetTableName(); diff --git a/Magic.IndexedDb/Magic.IndexedDb.csproj b/Magic.IndexedDb/Magic.IndexedDb.csproj index 46245e42..6de3b105 100644 --- a/Magic.IndexedDb/Magic.IndexedDb.csproj +++ b/Magic.IndexedDb/Magic.IndexedDb.csproj @@ -12,11 +12,11 @@ IndexedDB;Blazor;Blazor WebAssembly;LINQ;offline-first;client-side database;browser storage;PWA;Dexie wizardHatIcon.png True - 3.0.0.0 + 3.1.0.0 README.md LICENSE.txt - 3.0.0.0 - 3.0.0 + 3.1.0.0 + 3.1.0 diff --git a/Magic.IndexedDb/Migrations/MagicMigrationDiagnostics.cs b/Magic.IndexedDb/Migrations/MagicMigrationDiagnostics.cs index f990f30b..8fd11124 100644 --- a/Magic.IndexedDb/Migrations/MagicMigrationDiagnostics.cs +++ b/Magic.IndexedDb/Migrations/MagicMigrationDiagnostics.cs @@ -57,8 +57,37 @@ internal async Task StartAsync(CancellationToken cancellationToken) } } - [JSInvokable] - public async Task OnMigrationEvent(MagicMigrationEvent notification) + [JSInvokable("OnMigrationEvent")] + public Task ReceiveMigrationEvent(JsonElement payload) + { + var metadata = payload.EnumerateObject() + .ToDictionary(property => property.Name, property => property.Value.Clone(), StringComparer.OrdinalIgnoreCase); + JsonElement Take(string name) => metadata.Remove(name, out var value) ? value : default; + string? Text(string name) => Take(name) is { ValueKind: JsonValueKind.String } value ? value.GetString() : null; + int? Int(string name) => Take(name) is { ValueKind: JsonValueKind.Number } value ? value.GetInt32() : null; + long? Long(string name) => Take(name) is { ValueKind: JsonValueKind.Number } value ? value.GetInt64() : null; + + return OnMigrationEvent(new MagicMigrationEvent + { + ProtocolVersion = Int("protocolVersion") ?? 0, + Name = Text("name"), + SchemaId = Text("schemaId"), + Phase = Text("phase") ?? "", + Code = Text("code"), + Retryable = Take("retryable").ValueKind == JsonValueKind.True, + Revision = Int("revision"), + TargetRevision = Int("targetRevision"), + MigrationId = Text("migrationId"), + RecoveryId = Text("recoveryId"), + RecoveryPhase = Text("recoveryPhase"), + VerifiedRecords = Long("verifiedRecords"), + ProcessedRecords = Long("processedRecords"), + DocumentationUrl = Text("documentationUrl"), + Details = metadata.Count == 0 ? null : metadata + }); + } + + internal async Task OnMigrationEvent(MagicMigrationEvent notification) { var observer = Volatile.Read(ref _observer); if (observer is null) return; diff --git a/Magic.IndexedDb/Migrations/MagicSchemaJson.cs b/Magic.IndexedDb/Migrations/MagicSchemaJson.cs index fe22db50..2a7716f9 100644 --- a/Magic.IndexedDb/Migrations/MagicSchemaJson.cs +++ b/Magic.IndexedDb/Migrations/MagicSchemaJson.cs @@ -2,6 +2,7 @@ using System.Text; using System.Text.Encodings.Web; using System.Text.Json; +using System.Text.Json.Serialization; using Magic.IndexedDb.Protocol; namespace Magic.IndexedDb.Migrations; @@ -15,7 +16,9 @@ public static class MagicSchemaJson WriteIndented = false }; - public static JsonElement ToElement(T value) => JsonSerializer.SerializeToElement(value, CreateSerializerOptions()); + public static JsonElement ToElement(T value) => value is MagicSchemaDocument schema + ? JsonSerializer.SerializeToElement(schema, SchemaJsonContext.Default.MagicSchemaDocument) + : JsonSerializer.SerializeToElement(value, CreateSerializerOptions()); public static string Serialize(T value) => Canonicalize(ToElement(value)); @@ -32,3 +35,9 @@ public static string Canonicalize(JsonElement element) } } } + + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] +[JsonSerializable(typeof(MagicSchemaDocument))] +[JsonSerializable(typeof(string[]))] +internal partial class SchemaJsonContext : JsonSerializerContext; diff --git a/Magic.IndexedDb/wwwroot/magicDB.js b/Magic.IndexedDb/wwwroot/magicDB.js index 2ebc6d4f..7d8ff151 100644 --- a/Magic.IndexedDb/wwwroot/magicDB.js +++ b/Magic.IndexedDb/wwwroot/magicDB.js @@ -621,6 +621,13 @@ export async function destroyProtectedDatabase(physicalName, registeredRoute = n await Dexie.delete(physicalName); } +export function conditionalProtectedMutation(name, store, workspaceStore, { record, revision, generation, replacement }) { + const table = protectedTable(name, store); + const workspace = protectedTable(name, workspaceStore); + if (!table || !workspace) throw new Error("MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: Protected tables are required."); + return table.conditionalMutation(record, revision, workspace, generation, replacement); +} + export function patchPublicRecord(name, store, key, changes) { const table = protectedTable(name, store); if (!table) throw new Error("A public patch requires a protected table."); diff --git a/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js b/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js index 026b1ef5..ad9d893c 100644 --- a/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js +++ b/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js @@ -1,3 +1,4 @@ +import { sameStoredValue } from "./rotationBatch.js"; import { assertEncryptionKey, importEncryptionKey } from "./encryptionEnvelope.js"; import { assertPersistedEncryptionPolicy, verifyEncryptionPolicy, encryptionMetadataKey, encryptionMetadataStore } from "./encryptionPolicy.js"; import { openRecord, sealRecord, encryptedRecordMember } from "./encryptionRecord.js"; @@ -280,9 +281,9 @@ class ProtectedTable { } } - async fencedWrite(operation, assertCurrent = () => {}) { + async fencedWrite(operation, assertCurrent = () => {}, additionalTables = []) { await this.db.open(); - const stores = [this.table, this.db.table(encryptionMetadataStore)]; + const stores = [this.table, this.db.table(encryptionMetadataStore), ...additionalTables]; if (this.managed) { stores.push(this.db.table(migrationMetadataStore)); const numeric = this.db.tables.find(table => table.name === numericMetadataStore); @@ -327,6 +328,50 @@ class ProtectedTable { }); } + conditionalMutation(record, revision, workspace, generation, replacement) { + if (!this.managed || !workspace.managed || workspace.db !== this.db) + throw new Error("MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: Conditions require one protected managed database."); + const check = condition => { + validateMember(condition.member); + if (typeof condition.expected !== "string" && !Number.isSafeInteger(condition.expected)) + throw new Error("MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: Expected tokens must be strings or safe integers."); + }; + if (revision !== null) check(revision); + check(generation); + if (revision === null && replacement === null) + throw new Error("MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: Insert requires a record."); + + return this.access(async (keys, assertCurrent) => { + await this.assertPolicy(true); + const primaryKey = this.key(record); + const generationKey = workspace.key(generation.record); + if (replacement !== null && indexedDB.cmp(primaryKey, this.key(replacement)) !== 0) + throw new Error("MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: A replacement must retain the primary key."); + + const sameRow = workspace.table.name === this.table.name && indexedDB.cmp(primaryKey, generationKey) === 0; + const current = await this.table.get(primaryKey); + const workspaceRecord = sameRow ? current : await workspace.table.get(generationKey); + const matches = (row, condition) => row && Object.hasOwn(row, condition.member) && + row[condition.member] === condition.expected; + if (!workspaceRecord || (revision === null ? current !== undefined : current === undefined)) return false; + const opened = current === undefined ? undefined : await this.openStoredRecord(current, primaryKey, keys); + const fence = sameRow ? opened : await workspace.openStoredRecord(workspaceRecord, generationKey, keys); + if (!matches(fence, generation) || (revision !== null && !matches(opened, revision))) return false; + assertCurrent(); + const sealed = replacement === null ? null : await sealRecord(replacement, this.policy, keys.key, keys.keyId, + this.context(primaryKey)); + + return this.fencedWrite(async table => { + if (!sameStoredValue(current, await table.get(primaryKey)) || + (!sameRow && !sameStoredValue(workspaceRecord, await workspace.table.get(generationKey)))) return false; + if (sealed === null) await table.delete(primaryKey); + else if (revision === null) await table.add(sealed); + else await table.put(sealed); + return true; + }, assertCurrent, workspace.table.name === this.table.name ? [] : [workspace.table]); + }); + } + async patch(primaryKey, changes) { const names = Object.keys(changes); for (const name of names) validateMember(name); diff --git a/Magic.IndexedDb/wwwroot/utilities/rotationBatch.js b/Magic.IndexedDb/wwwroot/utilities/rotationBatch.js index f8777bde..71cd4ed5 100644 --- a/Magic.IndexedDb/wwwroot/utilities/rotationBatch.js +++ b/Magic.IndexedDb/wwwroot/utilities/rotationBatch.js @@ -16,7 +16,7 @@ function bytes(value) { return null; } -function sameStoredValue(left, right, ancestors = new WeakSet()) { +export 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; diff --git a/docs/guides/managed-key-rotation.md b/docs/guides/managed-key-rotation.md index a71c7ee3..2456297b 100644 --- a/docs/guides/managed-key-rotation.md +++ b/docs/guides/managed-key-rotation.md @@ -119,3 +119,25 @@ 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). + + +## Conditional protected writes + +Use `ReplaceProtectedIfCurrentAsync`, `DeleteProtectedIfCurrentAsync`, or +`InsertProtectedIfCurrentAsync` on an unlocked managed table. Select a direct +persisted revision or commit token and a workspace generation token. Both +tables must belong to the same managed database context. Tokens may be +encrypted and must serialize as strings or safe integers. + +Magic authenticates the relevant records, then compares the exact stored +snapshots in the same transaction that applies the mutation. It returns +`Conflict` for a missing fence, a token mismatch, a concurrent change, or a +guarded insert with an occupied key. Replacements preserve the primary key. +The workspace row can guard its own replacement. Applications can write a +fresh generation token through that guarded replacement to retire the previous +generation. + +Full trimming still requires the app to preserve persisted model members used +through reflection. Root the relevant model types in the application linker +descriptor and mark infrastructure-only properties with `[MagicNotMapped]` so +the exporter and runtime agree on the persisted schema. diff --git a/tests/migrations/ProtectedWasm/App/App.csproj b/tests/migrations/ProtectedWasm/App/App.csproj index 48a9683b..1462eb23 100644 --- a/tests/migrations/ProtectedWasm/App/App.csproj +++ b/tests/migrations/ProtectedWasm/App/App.csproj @@ -8,5 +8,6 @@ + diff --git a/tests/migrations/ProtectedWasm/App/App.razor b/tests/migrations/ProtectedWasm/App/App.razor index 73d459f6..1e202f4f 100644 --- a/tests/migrations/ProtectedWasm/App/App.razor +++ b/tests/migrations/ProtectedWasm/App/App.razor @@ -105,6 +105,29 @@ var table = await database.Query(); foreach (var id in new[] { 1, 2, 3 }) await table.AddAsync(new RotationRow { Id = id, Secret = "Document " + id }); + var expected = new RotationRow { Id = 1 }; + var workspace = new RotationRow { Id = 2 }; + var next = new RotationRow { Id = 1, Revision = 1, Secret = "Document 1" }; + Require(await table.ReplaceProtectedIfCurrentAsync(expected, next, row => row.Revision, + table, workspace, row => row.Generation) == MagicConditionalMutationResult.Applied, "The matching mutation failed."); + Require(await table.DeleteProtectedIfCurrentAsync(expected, row => row.Revision, + table, workspace, row => row.Generation) == MagicConditionalMutationResult.Conflict, "A stale revision deleted a record."); + Require(await table.InsertProtectedIfCurrentAsync(new RotationRow { Id = 4, Generation = 1, Secret = "Temporary document" }, + table, workspace, row => row.Generation) == MagicConditionalMutationResult.Applied, "The guarded insert failed."); + workspace.Generation = 1; + workspace.Id = 4; + Require(await table.DeleteProtectedIfCurrentAsync(next, row => row.Revision, table, + new RotationRow { Id = 4 }, row => row.Generation) == MagicConditionalMutationResult.Conflict, "A stale generation deleted a record."); + Require(await table.DeleteProtectedIfCurrentAsync(workspace, row => row.Revision, table, + workspace, row => row.Generation) == MagicConditionalMutationResult.Applied, "The matching delete failed."); + Require((await table.ToListAsync()).Any(row => row.Id == 1 && row.Revision == 1 && row.Secret == "Document 1"), + "A conflict changed the protected record."); + var oldFence = new RotationRow { Id = 2 }; + var advancedFence = new RotationRow { Id = 2, Revision = 1, Generation = 1, Secret = "Document 2" }; + Require(await table.ReplaceProtectedIfCurrentAsync(oldFence, advancedFence, row => row.Revision, + table, oldFence, row => row.Generation) == MagicConditionalMutationResult.Applied, "The fence could not advance itself."); + Require(await table.InsertProtectedIfCurrentAsync(new RotationRow { Id = 4, Secret = "Stale generation" }, + table, oldFence, row => row.Generation) == MagicConditionalMutationResult.Conflict, "The retired generation inserted a record."); 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."); diff --git a/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml b/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml new file mode 100644 index 00000000..3b26052e --- /dev/null +++ b/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/tests/migrations/ProtectedWasm/App/Program.cs b/tests/migrations/ProtectedWasm/App/Program.cs index 8d9d2c43..c766fd8a 100644 --- a/tests/migrations/ProtectedWasm/App/Program.cs +++ b/tests/migrations/ProtectedWasm/App/Program.cs @@ -1,3 +1,4 @@ +using Microsoft.JSInterop; using Magic.IndexedDb; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; @@ -10,7 +11,7 @@ [new MagicEncryptionOptions("protected-wasm", "published-account", "fixture-key" { PhysicalDatabaseName = ProtectedRepository.PhysicalName }]); await builder.Build().RunAsync(); -public sealed class FixtureKeys : IMagicEncryptionRotationKeyProvider +public sealed class FixtureKeys(IJSRuntime runtime) : IMagicEncryptionRotationKeyProvider { public static byte? KeyByte { get; set; } = 55; public static bool RotationSourceAvailable { get; set; } = true; @@ -18,6 +19,7 @@ public sealed class FixtureKeys : IMagicEncryptionRotationKeyProvider public static int Requests { get; private set; } public ValueTask GetKeyAsync(MagicEncryptionKeyRequest request, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(runtime); Requests++; if (request.DatabaseName == ProtectedRepository.RotationRecords.DatabaseName) { diff --git a/tests/migrations/ProtectedWasm/App/wwwroot/protected-fixture.mjs b/tests/migrations/ProtectedWasm/App/wwwroot/protected-fixture.mjs index 33778fcf..f0f4d8cc 100644 --- a/tests/migrations/ProtectedWasm/App/wwwroot/protected-fixture.mjs +++ b/tests/migrations/ProtectedWasm/App/wwwroot/protected-fixture.mjs @@ -69,8 +69,8 @@ export async function assertFinalPlaintext() { 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)) + row.__magic_record?.keyId !== expected[index] || !(row.__magic_record.ciphertext instanceof ArrayBuffer) || + row.__magic_record.ciphertext.byteLength === 0 || Object.hasOwn(row, "Revision") || Object.hasOwn(row, "Generation"))) throw new Error('Persisted ciphertext does not match the expected rotation generations.'); } diff --git a/tests/migrations/ProtectedWasm/Model.cs b/tests/migrations/ProtectedWasm/Model.cs index 2ca30aa3..9af73f88 100644 --- a/tests/migrations/ProtectedWasm/Model.cs +++ b/tests/migrations/ProtectedWasm/Model.cs @@ -16,6 +16,7 @@ public sealed class ProtectedRepository : IMagicRepository // context and authenticated history remain after explicit declassification. public sealed class ProtectedRow : MagicTableTool, IMagicTable { + [MagicNotMapped] public ProtectedRepository Databases { get; } = new(); public IndexedDbSet GetDefaultDatabase() => ProtectedRepository.Records; public string GetTableName() => "records"; @@ -27,13 +28,17 @@ public sealed class ProtectedRow : MagicTableTool, IMagicTable, IMagicTable { + [MagicNotMapped] 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; } = ""; + public int Revision { get; set; } + public int Generation { get; set; } + public string Secret { get; set; } = ""; } diff --git a/tests/migrations/ProtectedWasm/author.mjs b/tests/migrations/ProtectedWasm/author.mjs index 04115e30..2630d1d2 100644 --- a/tests/migrations/ProtectedWasm/author.mjs +++ b/tests/migrations/ProtectedWasm/author.mjs @@ -8,7 +8,7 @@ const [cli, targetFile] = process.argv.slice(2); const exported = JSON.parse(await readFile(targetFile, 'utf8')); 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']); +assert.deepEqual(rotation.stores[0].exposedFields, ['Id']); await writeFile('rotation-model.json', JSON.stringify(rotation)); assert.equal(target.schemaId, 'protected-wasm'); assert.deepEqual(target.requiredCapabilities, ['authenticatedMigrationsV1']); diff --git a/tests/migrations/ProtectedWasm/build.sh b/tests/migrations/ProtectedWasm/build.sh index 573ff6a7..ca51d53d 100644 --- a/tests/migrations/ProtectedWasm/build.sh +++ b/tests/migrations/ProtectedWasm/build.sh @@ -16,5 +16,5 @@ for mode in "$@"; do if [[ "$mode" == aot ]]; then aot=true; fi dotnet publish "$app/App/App.csproj" -c Release -o "$output/published/$mode/protected" \ --artifacts-path "$output/app-build/$mode/protected" \ - -p:RunAOTCompilation="$aot" -p:PublishTrimmed=true + -p:RunAOTCompilation="$aot" -p:PublishTrimmed=true -p:TrimMode=full done diff --git a/tests/migrations/protected-registration-browser.mjs b/tests/migrations/protected-registration-browser.mjs index 1acc540f..9a5815a8 100644 --- a/tests/migrations/protected-registration-browser.mjs +++ b/tests/migrations/protected-registration-browser.mjs @@ -74,6 +74,79 @@ export function registerProtectedRegistrationTests({ test, schema, bundle, appen assert.deepEqual(result.row, { id: 1, name: 'Public', secret: 'Never persist this plaintext' }); }); + test('conditional protected mutations check record revision and workspace generation atomically', async ({ page, context }) => { + const source = model(); + const workspace = structuredClone(source.stores[0]); + workspace.name = 'workspaces'; + delete workspace.encryptedFields; + source.stores.push(workspace); + const config = configuration('__magic_protected__:conditional-mutation', 'route', source, initial(source).url); + config.storeSchemas.push({ ...registrationStore(), tableName: 'workspaces' }); + const open = (tab, initialize) => tab.evaluate(async ({ config, initialize }) => { + globalThis.api = await import('/engine/magicDB.js'); + await api.createDb(config); + await api.unlockProtectedDatabase(config.name, 'key', new Uint8Array(32).fill(41), initialize); + await api.ensureProtectedMigration(config.name); + }, { config, initialize }); + await open(page, true); + await page.evaluate(async config => { + await api.addItem({ dbName: config.name, storeName: 'clients', record: { id: 1, name: 'r0', secret: 'Original' } }); + await api.addItem({ dbName: config.name, storeName: 'workspaces', record: { id: 2, name: 'g0' } }); + }, config); + const peer = await context.newPage(); + try { + await peer.goto(page.url()); + await open(peer, false); + const apply = (tab, revision, generation, replacement) => tab.evaluate( + ({ config, revision, generation, replacement }) => api.conditionalProtectedMutation(config.name, 'clients', 'workspaces', { + record: { id: 1 }, revision: { member: 'name', expected: revision }, + generation: { record: { id: 2 }, member: 'name', expected: generation }, replacement + }), { config, revision, generation, replacement }); + const replacement = { id: 1, name: 'r1', secret: 'Replacement' }; + const outcomes = await Promise.all([ + apply(page, 'r0', 'g0', replacement), apply(peer, 'r0', 'g0', replacement) + ]); + assert.deepEqual(outcomes.sort(), [false, true]); + await peer.evaluate(config => api.putItem({ dbName: config.name, storeName: 'workspaces', + record: { id: 2, name: 'g1' } }), config); + assert.equal(await apply(page, 'r1', 'g0', null), false); + assert.deepEqual(await page.evaluate(config => api.findItem(config.name, 'clients', 1), config), replacement); + assert.equal(await apply(page, 'r0', 'g1', null), false); + + const race = async (id, expectedRevision, generation, nextGeneration) => { + await page.evaluate(async ({ config, id, expectedRevision, generation }) => { + const encrypt = crypto.subtle.encrypt.bind(crypto.subtle); + crypto.subtle.encrypt = async (...args) => { + const ciphertext = await encrypt(...args); + await new Promise(resolve => { globalThis.unblockPreparation = resolve; }); + return ciphertext; + }; + globalThis.pendingConditional = api.conditionalProtectedMutation(config.name, 'clients', 'workspaces', { + record: { id }, revision: expectedRevision === null ? null : { member: 'name', expected: expectedRevision }, + generation: { record: { id: 2 }, member: 'name', expected: generation }, + replacement: { id, name: 'uncommitted', secret: 'Must not replace' } + }); + }, { config, id, expectedRevision, generation }); + await page.waitForFunction(() => typeof globalThis.unblockPreparation === 'function'); + await peer.evaluate(({ config, nextGeneration }) => api.putItem({ dbName: config.name, storeName: 'workspaces', + record: { id: 2, name: nextGeneration } }), { config, nextGeneration }); + const applied = await page.evaluate(() => { + delete crypto.subtle.encrypt; + globalThis.unblockPreparation(); + delete globalThis.unblockPreparation; + return globalThis.pendingConditional; + }); + assert.equal(applied, false); + }; + await race(1, 'r1', 'g1', 'g2'); + await race(3, null, 'g2', 'g3'); + assert.deepEqual(await page.evaluate(config => api.findItem(config.name, 'clients', 1), config), replacement); + assert.equal(await page.evaluate(config => api.findItem(config.name, 'clients', 3), config), undefined); + assert.equal(await apply(page, 'r1', 'g3', null), true); + assert.equal(await page.evaluate(config => api.findItem(config.name, 'clients', 1), config), undefined); + } finally { await peer.close(); } + }); + 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(); diff --git a/tests/migrations/run.mjs b/tests/migrations/run.mjs index 3ae5abf1..f776c8ca 100644 --- a/tests/migrations/run.mjs +++ b/tests/migrations/run.mjs @@ -1762,7 +1762,7 @@ test('rotation checkpoints preserve compound keys across protected and public st 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 ? 142 : 138) + (process.env.MAGIC_ROTATION_BENCHMARK === "1" ? 9 : 0); +const expectedScenarioCount = (cliFixture ? 143 : 139) + (process.env.MAGIC_ROTATION_BENCHMARK === "1" ? 9 : 0); assert.equal(tests.length, expectedScenarioCount, 'Unexpected migration scenario count.'); if (listOnly) {