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); } }