d4e13d3aa4
The flattened config embeds each bound data connection's decrypted protocol JSON, and PendingDeployments / DeployedConfigSnapshots stored it verbatim - the credentials dp:protocol:v1 protects on DataConnections sat in plaintext in two more tables and every backup. - DeploymentConfigSecretConverter (own DP purpose, dp:config:v1: prefix) on both ConfigurationJson columns: every write protected, reads accept legacy plaintext so un-migrated rows keep working. Schema-only contexts refuse the write. - DeploymentConfigSecretUpgrade: one-time startup re-protect from MigrationHelper (after the protocol upgrade). A startup backfill, not an EF migration, because the Data Protection key ring is not reachable from a SQL migration script. Plaintext-detecting (NOT LIKE prefix), paged by Id, binary compare-and-swap (both centrals may run it), idempotent, and not a startup gate (logged + retried next start). - No EF model change (has-pending-model-changes: none); no migration. Tests: SQLite round-trip (raw column has no secret, EF read equals original) for both tables, legacy plaintext readable then re-protected idempotently, schema-only write refused, and the upgrade on real SQL Server. PendingDeploymentRepositoryIntegrationTests now supplies a key ring. Deploy gate: upgrade both central nodes together (old binaries cannot read protected rows).
222 lines
12 KiB
C#
222 lines
12 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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 <c>PendingDeployments</c> and <c>DeployedConfigSnapshots</c>. Both columns are now
|
|
/// Data-Protection-encrypted; legacy plaintext rows stay readable and are re-protected by the
|
|
/// startup <see cref="DeploymentConfigSecretUpgrade"/>.
|
|
/// </summary>
|
|
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();
|
|
|
|
/// <inheritdoc />
|
|
public void Dispose()
|
|
{
|
|
_db.Database.CloseConnection();
|
|
_db.Dispose();
|
|
}
|
|
|
|
private async Task<int> 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<string> 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<string>(await cmd.ExecuteScalarAsync());
|
|
}
|
|
|
|
/// <summary>A staged pending deployment is encrypted at rest and reads back unchanged.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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);
|
|
}
|
|
|
|
/// <summary>A deployed snapshot is encrypted at rest and reads back unchanged.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A legacy plaintext row (written before the converter) is still readable, and the startup
|
|
/// upgrade re-protects it in both tables, idempotently.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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);
|
|
}
|
|
|
|
/// <summary>An already-protected value is never double-protected on write.</summary>
|
|
[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));
|
|
}
|
|
|
|
/// <summary>A schema-only context (no key ring) refuses to persist deployment configuration.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SchemaOnlyContext_RefusesToWriteDeploymentConfiguration()
|
|
{
|
|
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
|
.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<InvalidOperationException>(() => schemaOnly.SaveChangesAsync());
|
|
Assert.Contains("ConfigurationJson", ex.Message);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The CDB-1 startup re-protect against real SQL Server (its own SQL dialect: <c>TOP</c>,
|
|
/// <c>NOT LIKE</c>, binary-collation compare-and-swap).
|
|
/// </summary>
|
|
public class DeploymentConfigSecretUpgradeSqlServerTests : IClassFixture<ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations.MsSqlMigrationFixture>
|
|
{
|
|
private static readonly Microsoft.AspNetCore.DataProtection.IDataProtectionProvider KeyRing =
|
|
new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider();
|
|
|
|
private readonly ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations.MsSqlMigrationFixture _fixture;
|
|
|
|
/// <summary>Initializes the suite with the shared MS SQL fixture.</summary>
|
|
/// <param name="fixture">The shared MS SQL migration fixture.</param>
|
|
public DeploymentConfigSecretUpgradeSqlServerTests(
|
|
ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations.MsSqlMigrationFixture fixture) => _fixture = fixture;
|
|
|
|
private ScadaBridgeDbContext Create() => new(
|
|
new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlServer(_fixture.ConnectionString).Options, KeyRing);
|
|
|
|
/// <summary>Plaintext snapshot and pending rows are re-protected, idempotently, and read back unchanged.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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<int>(
|
|
"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);
|
|
}
|
|
}
|