diff --git a/docs/requirements/Component-ConfigurationDatabase.md b/docs/requirements/Component-ConfigurationDatabase.md index 007beb67..8101a487 100644 --- a/docs/requirements/Component-ConfigurationDatabase.md +++ b/docs/requirements/Component-ConfigurationDatabase.md @@ -507,4 +507,30 @@ persisted key ring. Keep a coordinated pre-upgrade database/key-ring backup. Dow while protected protocol rows exist. The existing same-database key-ring storage remains defence in depth; this change does not introduce external key management. +### Deployment configuration encryption at rest (code review 2026-12-02 CDB-1) + +The flattened deployment configuration embeds each bound data connection's **decrypted** +protocol JSON (endpoints and any inline credentials — `FlattenedConfiguration.Connections`), so +`PendingDeployments.ConfigurationJson` and `DeployedConfigSnapshots.ConfigurationJson` are now +protected in full by `DeploymentConfigSecretConverter` (its own Data Protection purpose, versioned +`dp:config:v1:` prefix). Before this the credentials the `dp:protocol:v1:` converter protects on +`DataConnections` sat in plaintext in both tables and every backup. Both columns were already +`nvarchar(max)`; no schema migration. Every write is protected; schema-only contexts reject writes +(`GuardSecretWritesHaveAKeyRing`). Every consumer reads through EF (the notify-and-fetch endpoint +that serves the site, the deployment diff), so all of them see plaintext transparently. + +Unlike the protocol upgrade, **reads accept legacy plaintext** (a JSON document never starts with +the prefix), so un-migrated rows keep working. `DeploymentConfigSecretUpgrade` re-protects them at +startup from `MigrationHelper`, after `DataConnectionSecretUpgrade`: a **startup backfill, not an +EF migration**, because protecting needs the Data Protection key ring, which a SQL migration script +cannot reach. It reads only rows whose value lacks the prefix (`NOT LIKE 'dp:config:v1:%'`), pages +by primary key (64 rows), and updates with a binary-collation compare-and-swap on the old value, so +both central nodes may run it at once and a rerun is a no-op. It is **not a startup gate**: a +failure is logged at Warning and retried at the next start. Upgrade both central nodes together — +old binaries cannot read protected rows (they would hand the site ciphertext). Check after the first +start: `SELECT COUNT(*) FROM DeployedConfigSnapshots WHERE ConfigurationJson NOT LIKE 'dp:config:v1:%'` +(and the same for `PendingDeployments`) returns 0. The deployment comparison diff still shows the +decrypted connection configuration to an authorized operator; that is a display concern, not +storage. + Trace replay reads keyset pages of eight rows, so EF retry buffering cannot materialize a whole trace before the consumer applies its byte budget. SQL omits an oversized DetailsJson value before transfer; all other projected strings have schema length limits. Canonical serialized UTF-8 size, including escaping and metadata, determines the final 1 MiB limit. diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/DeploymentConfigSecretConverter.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/DeploymentConfigSecretConverter.cs new file mode 100644 index 00000000..1685c946 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/DeploymentConfigSecretConverter.cs @@ -0,0 +1,57 @@ +using Microsoft.AspNetCore.DataProtection; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase; + +/// +/// Data Protection at rest for the flattened deployment configuration JSON stored in +/// PendingDeployments.ConfigurationJson and DeployedConfigSnapshots.ConfigurationJson +/// (code review 2026-12-02 CDB-1). +/// +/// +/// +/// The flattener copies each bound data connection's DECRYPTED protocol JSON — endpoints and +/// any inline credentials — into FlattenedConfiguration.Connections, and the whole +/// object was persisted verbatim, so the credentials +/// protects on DataConnections sat in plaintext in two more tables (and every backup). +/// The whole column is protected: it is only ever read back whole (served to the site by the +/// notify-and-fetch endpoint, or deserialized for the deployment diff), never queried into. +/// +/// +/// Plaintext is still READ (a value without passes through +/// unchanged) so rows written before this change keep working until +/// re-protects them at startup. Every WRITE is +/// protected. A JSON document always starts with { or [, so it can never be +/// mistaken for a prefixed value. +/// +/// +public sealed class DeploymentConfigSecretConverter(IDataProtector protector) : ValueConverter( + value => Protect(protector, value), + value => Unprotect(protector, value)) +{ + /// Versioned marker on protected values. + internal const string Prefix = "dp:config:v1:"; + + /// Purpose string, distinct from every other protected column. + internal const string Purpose = EncryptedStringConverter.ProtectorPurpose + ".DeploymentConfig"; + + /// True when is already protected. + /// The stored column value. + /// Whether the value carries the protected prefix. + internal static bool IsProtected(string? stored) => + stored is not null && stored.StartsWith(Prefix, StringComparison.Ordinal); + + /// Protects plaintext configuration JSON; an already-protected value is left as is. + /// The data protector. + /// The value to store. + /// The prefixed protected value. + internal static string Protect(IDataProtector protector, string value) => + IsProtected(value) ? value : Prefix + protector.Protect(value); + + /// Unprotects a stored value; a legacy plaintext value passes through unchanged. + /// The data protector. + /// The stored column value. + /// The plaintext configuration JSON. + internal static string Unprotect(IDataProtector protector, string stored) => + IsProtected(stored) ? protector.Unprotect(stored[Prefix.Length..]) : stored; +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/DeploymentConfigSecretUpgrade.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/DeploymentConfigSecretUpgrade.cs new file mode 100644 index 00000000..5ca5c2e2 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/DeploymentConfigSecretUpgrade.cs @@ -0,0 +1,139 @@ +using System.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase; + +/// +/// One-time, idempotent startup re-protect of deployment configuration JSON written before +/// existed (code review 2026-12-02 CDB-1). +/// +/// +/// +/// Why a startup backfill and not an EF migration: protecting a row needs the Data +/// Protection key ring, which lives behind IDataProtectionProvider in the running host +/// and is not reachable from a SQL migration script (production applies migrations as generated +/// SQL). It runs from in both development and production, after +/// the schema check, exactly like . +/// +/// +/// It is plaintext-detecting (only rows whose value lacks the protected prefix are +/// read), bounded (pages by primary key), idempotent (a second run finds nothing), +/// and concurrency-safe: the UPDATE is a compare-and-swap on the exact old value, so a +/// row the peer central node already re-protected, or a deploy that rewrote it meanwhile, is +/// left alone. Unlike the data-connection upgrade it is not a startup gate — the +/// converter still reads plaintext — so a failure is logged and startup continues; the next +/// start retries. +/// +/// +public static class DeploymentConfigSecretUpgrade +{ + private const int PageSize = 64; + + /// The tables whose ConfigurationJson column is protected. + internal static readonly string[] Tables = ["PendingDeployments", "DeployedConfigSnapshots"]; + + /// Re-protects every plaintext ConfigurationJson row in both tables. + /// A context constructed with the Data Protection provider. + /// Optional logger. + /// Token to cancel the upgrade. + /// The number of rows re-protected. + public static async Task UpgradeAsync( + ScadaBridgeDbContext db, ILogger? logger = null, CancellationToken cancellationToken = default) + { + var total = 0; + try + { + if (!db.HasSecretEncryptionProvider) + { + logger?.LogWarning( + "Skipping the deployment-configuration re-protect: the context has no Data Protection provider."); + return 0; + } + + var protector = db.DeploymentConfigProtector; + var connection = db.Database.GetDbConnection(); + var opened = connection.State != ConnectionState.Open; + if (opened) await connection.OpenAsync(cancellationToken); + try + { + foreach (var table in Tables) + total += await UpgradeTableAsync(db, connection, table, protector, cancellationToken); + } + finally + { + if (opened) await connection.CloseAsync(); + } + + if (total > 0) + { + logger?.LogInformation( + "Re-protected {Count} plaintext deployment-configuration row(s) at rest (CDB-1).", total); + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Not a gate: the converter still reads plaintext rows, so the system keeps working; + // the next startup retries whatever is left. + logger?.LogWarning(ex, + "Deployment-configuration re-protect stopped after {Count} row(s); remaining plaintext rows are " + + "still readable and will be retried at the next startup.", total); + } + + return total; + } + + private static async Task UpgradeTableAsync( + ScadaBridgeDbContext db, System.Data.Common.DbConnection connection, string table, + Microsoft.AspNetCore.DataProtection.IDataProtector protector, CancellationToken cancellationToken) + { + var sqlServer = db.Database.IsSqlServer(); + var upgraded = 0; + var lastId = 0; + while (true) + { + var rows = new List<(int Id, string Json)>(); + await using (var read = connection.CreateCommand()) + { + // Plaintext-detecting: already-protected rows are never read back. + var predicate = $"Id > @last AND ConfigurationJson NOT LIKE '{DeploymentConfigSecretConverter.Prefix}%'"; + read.CommandText = sqlServer + ? $"SELECT TOP ({PageSize}) Id, ConfigurationJson FROM {table} WHERE {predicate} ORDER BY Id" + : $"SELECT Id, ConfigurationJson FROM {table} WHERE {predicate} ORDER BY Id LIMIT {PageSize}"; + Add(read, "@last", lastId); + await using var reader = await read.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + rows.Add((reader.GetInt32(0), reader.GetString(1))); + } + + if (rows.Count == 0) return upgraded; + + foreach (var (id, json) in rows) + { + lastId = id; + if (DeploymentConfigSecretConverter.IsProtected(json)) continue; + + await using var update = connection.CreateCommand(); + // Compare-and-swap on the exact old value (binary collation on SQL Server, so a + // case-only difference is still a difference). + update.CommandText = sqlServer + ? $"UPDATE {table} SET ConfigurationJson = @protected WHERE Id = @id " + + "AND ConfigurationJson COLLATE Latin1_General_100_BIN2 = @old COLLATE Latin1_General_100_BIN2" + : $"UPDATE {table} SET ConfigurationJson = @protected WHERE Id = @id AND ConfigurationJson = @old"; + Add(update, "@id", id); + Add(update, "@protected", DeploymentConfigSecretConverter.Protect(protector, json)); + Add(update, "@old", json); + upgraded += await update.ExecuteNonQueryAsync(cancellationToken); + } + } + } + + private static void Add(System.Data.Common.DbCommand command, string name, object value) + { + var parameter = command.CreateParameter(); + parameter.ParameterName = name; + parameter.Value = value; + if (value is not int) { parameter.DbType = DbType.String; parameter.Size = -1; } + command.Parameters.Add(parameter); + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/MigrationHelper.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/MigrationHelper.cs index 3eb21e66..20526d12 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/MigrationHelper.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/MigrationHelper.cs @@ -66,6 +66,11 @@ public static class MigrationHelper await DataConnectionSecretUpgrade.UpgradeAsync(dbContext, cancellationToken); + // CDB-1: re-protect deployment configuration JSON written before it was encrypted at + // rest. Not a gate (plaintext rows stay readable); failures are logged and retried at + // the next start. + await DeploymentConfigSecretUpgrade.UpgradeAsync(dbContext, logger, cancellationToken); + // Safety-net normalizer: rewrite any already-persisted List attribute values from the // old array-of-strings JSON form to the new native-typed form. Idempotent and never // aborts startup for data reasons (per-row skip + log). Safe even if both central diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs index d72c4b04..0d1bf49d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs @@ -262,6 +262,11 @@ public class ScadaBridgeDbContext : DbContext, IDataProtectionKeyContext ?? throw new InvalidOperationException("Data Protection is required to migrate protocol credentials.")) .CreateProtector(DataConnectionSecretConverter.Purpose); + /// Data Protection protector for deployment configuration JSON (CDB-1); throws when no provider was supplied. + internal IDataProtector DeploymentConfigProtector => (_dataProtectionProvider + ?? throw new InvalidOperationException("Data Protection is required to protect deployment configuration.")) + .CreateProtector(DeploymentConfigSecretConverter.Purpose); + /// True when this context was constructed with a real Data Protection provider. internal bool HasSecretEncryptionProvider => _dataProtectionProvider is not null; @@ -291,6 +296,9 @@ public class ScadaBridgeDbContext : DbContext, IDataProtectionKeyContext DatabaseConnectionDefinition => nameof(DatabaseConnectionDefinition.ConnectionString), DataConnection connection when connection.PrimaryConfiguration is not null => nameof(DataConnection.PrimaryConfiguration), DataConnection => nameof(DataConnection.BackupConfiguration), + // CDB-1: the flattened config embeds the bound connections' protocol JSON. + PendingDeployment => nameof(PendingDeployment.ConfigurationJson), + DeployedConfigSnapshot => nameof(DeployedConfigSnapshot.ConfigurationJson), _ => null }; if (secretProperty is null) @@ -385,6 +393,17 @@ public class ScadaBridgeDbContext : DbContext, IDataProtectionKeyContext var protocolConverter = new DataConnectionSecretConverter(protocolProtector); modelBuilder.Entity().Property(d => d.PrimaryConfiguration).HasConversion(protocolConverter); modelBuilder.Entity().Property(d => d.BackupConfiguration).HasConversion(protocolConverter); + + // Code review 2026-12-02 CDB-1: the flattened deployment configuration carries each + // bound connection's decrypted protocol JSON, so both staged and deployed copies are + // protected too. The converter still READS legacy plaintext rows (re-protected at + // startup by DeploymentConfigSecretUpgrade). + IDataProtector configProtector = _dataProtectionProvider is { } configProvider + ? configProvider.CreateProtector(DeploymentConfigSecretConverter.Purpose) + : SchemaOnlyDataProtector.Instance; + var configConverter = new DeploymentConfigSecretConverter(configProtector); + modelBuilder.Entity().Property(p => p.ConfigurationJson).HasConversion(configConverter); + modelBuilder.Entity().Property(s => s.ConfigurationJson).HasConversion(configConverter); } /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/DeploymentConfigEncryptionTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/DeploymentConfigEncryptionTests.cs new file mode 100644 index 00000000..5aaf1f18 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/DeploymentConfigEncryptionTests.cs @@ -0,0 +1,221 @@ +using Microsoft.EntityFrameworkCore; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase; + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests; + +/// +/// Code review 2026-12-02 CDB-1: the flattened deployment configuration embeds each bound data +/// connection's decrypted protocol JSON (endpoints, inline credentials), and it used to be stored +/// verbatim in PendingDeployments and DeployedConfigSnapshots. Both columns are now +/// Data-Protection-encrypted; legacy plaintext rows stay readable and are re-protected by the +/// startup . +/// +public class DeploymentConfigEncryptionTests : IDisposable +{ + private const string Secret = "cdb1-userIdentity-password-never-plaintext"; + + private static readonly string ConfigJson = + """{"InstanceUniqueName":"Pump1","Connections":{"OPC1":{"Protocol":"OpcUa","ConfigurationJson":"{\"endpointUrl\":\"opc.tcp://plc:4840\",\"userIdentity\":{\"password\":\"SECRET\"}}"}}}""" + .Replace("SECRET", Secret, StringComparison.Ordinal); + + private readonly ScadaBridgeDbContext _db = SqliteTestHelper.CreateInMemoryContext(); + + /// + public void Dispose() + { + _db.Database.CloseConnection(); + _db.Dispose(); + } + + private async Task SeedInstanceAsync() + { + var site = new Site("S", "s-" + Guid.NewGuid().ToString("N")[..6]); + var template = new Template("T-" + Guid.NewGuid().ToString("N")[..6]); + _db.Sites.Add(site); + _db.Templates.Add(template); + await _db.SaveChangesAsync(); + var instance = new Instance("I-" + Guid.NewGuid().ToString("N")[..6]) { SiteId = site.Id, TemplateId = template.Id }; + _db.Instances.Add(instance); + await _db.SaveChangesAsync(); + return instance.Id; + } + + private async Task RawAsync(string table, int id) + { + await using var cmd = _db.Database.GetDbConnection().CreateCommand(); + cmd.CommandText = $"SELECT ConfigurationJson FROM {table} WHERE Id = {id}"; + return Assert.IsType(await cmd.ExecuteScalarAsync()); + } + + /// A staged pending deployment is encrypted at rest and reads back unchanged. + /// A task that represents the asynchronous operation. + [Fact] + public async Task PendingDeployment_ConfigurationJson_IsEncryptedAndRoundTrips() + { + var instanceId = await SeedInstanceAsync(); + var now = DateTimeOffset.UtcNow; + var pending = new PendingDeployment("dep-1", instanceId, "rev", ConfigJson, "tok", now, now.AddMinutes(5)); + _db.PendingDeployments.Add(pending); + await _db.SaveChangesAsync(); + _db.ChangeTracker.Clear(); + + var raw = await RawAsync("PendingDeployments", pending.Id); + Assert.StartsWith(DeploymentConfigSecretConverter.Prefix, raw); + Assert.DoesNotContain(Secret, raw); + Assert.DoesNotContain("opc.tcp", raw); + + var read = await _db.PendingDeployments.AsNoTracking().SingleAsync(p => p.Id == pending.Id); + Assert.Equal(ConfigJson, read.ConfigurationJson); + } + + /// A deployed snapshot is encrypted at rest and reads back unchanged. + /// A task that represents the asynchronous operation. + [Fact] + public async Task DeployedSnapshot_ConfigurationJson_IsEncryptedAndRoundTrips() + { + var instanceId = await SeedInstanceAsync(); + var snapshot = new DeployedConfigSnapshot("dep-1", "rev", ConfigJson) { InstanceId = instanceId }; + _db.DeployedConfigSnapshots.Add(snapshot); + await _db.SaveChangesAsync(); + _db.ChangeTracker.Clear(); + + var raw = await RawAsync("DeployedConfigSnapshots", snapshot.Id); + Assert.StartsWith(DeploymentConfigSecretConverter.Prefix, raw); + Assert.DoesNotContain(Secret, raw); + + var read = await _db.DeployedConfigSnapshots.AsNoTracking().SingleAsync(s => s.Id == snapshot.Id); + Assert.Equal(ConfigJson, read.ConfigurationJson); + } + + /// + /// A legacy plaintext row (written before the converter) is still readable, and the startup + /// upgrade re-protects it in both tables, idempotently. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task LegacyPlaintextRows_AreReadable_ThenReProtectedByTheStartupUpgrade() + { + var instanceId = await SeedInstanceAsync(); + var now = DateTimeOffset.UtcNow.ToString("o"); + await _db.Database.ExecuteSqlRawAsync( + "INSERT INTO PendingDeployments (DeploymentId, InstanceId, RevisionHash, ConfigurationJson, Token, CreatedAtUtc, ExpiresAtUtc) " + + "VALUES ('legacy-p', {0}, 'rev', {1}, 'tok', {2}, {2})", instanceId, ConfigJson, now); + await _db.Database.ExecuteSqlRawAsync( + "INSERT INTO DeployedConfigSnapshots (InstanceId, DeploymentId, RevisionHash, ConfigurationJson, DeployedAt) " + + "VALUES ({0}, 'legacy-s', 'rev', {1}, {2})", instanceId, ConfigJson, now); + + // Readable as-is before the upgrade (no "requires the upgrade" gate). + Assert.Equal(ConfigJson, (await _db.PendingDeployments.AsNoTracking().SingleAsync(p => p.DeploymentId == "legacy-p")).ConfigurationJson); + Assert.Equal(ConfigJson, (await _db.DeployedConfigSnapshots.AsNoTracking().SingleAsync(s => s.DeploymentId == "legacy-s")).ConfigurationJson); + + Assert.Equal(2, await DeploymentConfigSecretUpgrade.UpgradeAsync(_db)); + + var pendingId = (await _db.PendingDeployments.AsNoTracking().SingleAsync(p => p.DeploymentId == "legacy-p")).Id; + var snapshotId = (await _db.DeployedConfigSnapshots.AsNoTracking().SingleAsync(s => s.DeploymentId == "legacy-s")).Id; + var rawPending = await RawAsync("PendingDeployments", pendingId); + var rawSnapshot = await RawAsync("DeployedConfigSnapshots", snapshotId); + Assert.DoesNotContain(Secret, rawPending); + Assert.DoesNotContain(Secret, rawSnapshot); + + // Idempotent: nothing left to do, ciphertext untouched. + Assert.Equal(0, await DeploymentConfigSecretUpgrade.UpgradeAsync(_db)); + Assert.Equal(rawPending, await RawAsync("PendingDeployments", pendingId)); + + // And still reads back as the original plaintext. + _db.ChangeTracker.Clear(); + Assert.Equal(ConfigJson, (await _db.PendingDeployments.AsNoTracking().SingleAsync(p => p.Id == pendingId)).ConfigurationJson); + Assert.Equal(ConfigJson, (await _db.DeployedConfigSnapshots.AsNoTracking().SingleAsync(s => s.Id == snapshotId)).ConfigurationJson); + } + + /// An already-protected value is never double-protected on write. + [Fact] + public void Protect_IsIdempotent_AndPlaintextPassesThroughOnRead() + { + var protector = new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider() + .CreateProtector(DeploymentConfigSecretConverter.Purpose); + var once = DeploymentConfigSecretConverter.Protect(protector, ConfigJson); + Assert.Equal(once, DeploymentConfigSecretConverter.Protect(protector, once)); + Assert.Equal(ConfigJson, DeploymentConfigSecretConverter.Unprotect(protector, once)); + Assert.Equal(ConfigJson, DeploymentConfigSecretConverter.Unprotect(protector, ConfigJson)); + } + + /// A schema-only context (no key ring) refuses to persist deployment configuration. + /// A task that represents the asynchronous operation. + [Fact] + public async Task SchemaOnlyContext_RefusesToWriteDeploymentConfiguration() + { + var options = new DbContextOptionsBuilder() + .UseSqlite(_db.Database.GetDbConnection()) + .Options; + await using var schemaOnly = new ScadaBridgeDbContext(options); + schemaOnly.DeployedConfigSnapshots.Add(new DeployedConfigSnapshot("d", "r", ConfigJson) { InstanceId = 1 }); + + var ex = await Assert.ThrowsAsync(() => schemaOnly.SaveChangesAsync()); + Assert.Contains("ConfigurationJson", ex.Message); + } +} + +/// +/// The CDB-1 startup re-protect against real SQL Server (its own SQL dialect: TOP, +/// NOT LIKE, binary-collation compare-and-swap). +/// +public class DeploymentConfigSecretUpgradeSqlServerTests : IClassFixture +{ + private static readonly Microsoft.AspNetCore.DataProtection.IDataProtectionProvider KeyRing = + new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider(); + + private readonly ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations.MsSqlMigrationFixture _fixture; + + /// Initializes the suite with the shared MS SQL fixture. + /// The shared MS SQL migration fixture. + public DeploymentConfigSecretUpgradeSqlServerTests( + ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations.MsSqlMigrationFixture fixture) => _fixture = fixture; + + private ScadaBridgeDbContext Create() => new( + new DbContextOptionsBuilder().UseSqlServer(_fixture.ConnectionString).Options, KeyRing); + + /// Plaintext snapshot and pending rows are re-protected, idempotently, and read back unchanged. + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task Upgrade_ReProtectsPlaintextRows_OnSqlServer() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + const string json = """{"Connections":{"OPC1":{"ConfigurationJson":"{\"password\":\"sql-cdb1-secret\"}"}}}"""; + var tag = Guid.NewGuid().ToString("N")[..8]; + + await using var db = Create(); + var site = new Site("S" + tag, "s-" + tag); + var template = new Template("T" + tag); + db.Sites.Add(site); + db.Templates.Add(template); + await db.SaveChangesAsync(); + var instance = new Instance("I" + tag) { SiteId = site.Id, TemplateId = template.Id }; + db.Instances.Add(instance); + await db.SaveChangesAsync(); + + var now = DateTimeOffset.UtcNow; + await db.Database.ExecuteSqlRawAsync( + "INSERT INTO PendingDeployments (DeploymentId, InstanceId, RevisionHash, ConfigurationJson, Token, CreatedAtUtc, ExpiresAtUtc) " + + "VALUES ({0}, {1}, 'rev', {2}, 'tok', {3}, {3})", "p-" + tag, instance.Id, json, now); + await db.Database.ExecuteSqlRawAsync( + "INSERT INTO DeployedConfigSnapshots (InstanceId, DeploymentId, RevisionHash, ConfigurationJson, DeployedAt) " + + "VALUES ({0}, {1}, 'rev', {2}, {3})", instance.Id, "s-" + tag, json, now); + + Assert.True(await DeploymentConfigSecretUpgrade.UpgradeAsync(db) >= 2); + Assert.Equal(0, await DeploymentConfigSecretUpgrade.UpgradeAsync(db)); + + var plaintextLeft = await db.Database + .SqlQueryRaw( + "SELECT COUNT(*) AS [Value] FROM DeployedConfigSnapshots WHERE ConfigurationJson NOT LIKE 'dp:config:v1:%'") + .SingleAsync(); + Assert.Equal(0, plaintextLeft); + + db.ChangeTracker.Clear(); + Assert.Equal(json, (await db.PendingDeployments.AsNoTracking().SingleAsync(p => p.DeploymentId == "p-" + tag)).ConfigurationJson); + Assert.Equal(json, (await db.DeployedConfigSnapshots.AsNoTracking().SingleAsync(s => s.DeploymentId == "s-" + tag)).ConfigurationJson); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/PendingDeploymentRepositoryIntegrationTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/PendingDeploymentRepositoryIntegrationTests.cs index 58cf956b..9ed651d9 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/PendingDeploymentRepositoryIntegrationTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/PendingDeploymentRepositoryIntegrationTests.cs @@ -137,11 +137,17 @@ public class PendingDeploymentRepositoryIntegrationTests : IClassFixture() .UseSqlServer(_fixture.ConnectionString) .Options; - return new ScadaBridgeDbContext(options); + return new ScadaBridgeDbContext(options, KeyRing); } }