fix(config-db): encrypt deployment configuration JSON at rest (CDB-1, WP1 task 1.8)

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).
This commit is contained in:
Joseph Doherty
2026-12-03 10:28:39 -05:00
parent 5a052c6327
commit d4e13d3aa4
7 changed files with 474 additions and 1 deletions
@@ -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 while protected protocol rows exist. The existing same-database key-ring storage remains
defence in depth; this change does not introduce external key management. 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. 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.
@@ -0,0 +1,57 @@
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
/// <summary>
/// Data Protection at rest for the flattened deployment configuration JSON stored in
/// <c>PendingDeployments.ConfigurationJson</c> and <c>DeployedConfigSnapshots.ConfigurationJson</c>
/// (code review 2026-12-02 CDB-1).
/// </summary>
/// <remarks>
/// <para>
/// The flattener copies each bound data connection's DECRYPTED protocol JSON — endpoints and
/// any inline credentials — into <c>FlattenedConfiguration.Connections</c>, and the whole
/// object was persisted verbatim, so the credentials <see cref="DataConnectionSecretConverter"/>
/// protects on <c>DataConnections</c> 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.
/// </para>
/// <para>
/// <b>Plaintext is still READ</b> (a value without <see cref="Prefix"/> passes through
/// unchanged) so rows written before this change keep working until
/// <see cref="DeploymentConfigSecretUpgrade"/> re-protects them at startup. Every WRITE is
/// protected. A JSON document always starts with <c>{</c> or <c>[</c>, so it can never be
/// mistaken for a prefixed value.
/// </para>
/// </remarks>
public sealed class DeploymentConfigSecretConverter(IDataProtector protector) : ValueConverter<string, string>(
value => Protect(protector, value),
value => Unprotect(protector, value))
{
/// <summary>Versioned marker on protected values.</summary>
internal const string Prefix = "dp:config:v1:";
/// <summary>Purpose string, distinct from every other protected column.</summary>
internal const string Purpose = EncryptedStringConverter.ProtectorPurpose + ".DeploymentConfig";
/// <summary>True when <paramref name="stored"/> is already protected.</summary>
/// <param name="stored">The stored column value.</param>
/// <returns>Whether the value carries the protected prefix.</returns>
internal static bool IsProtected(string? stored) =>
stored is not null && stored.StartsWith(Prefix, StringComparison.Ordinal);
/// <summary>Protects plaintext configuration JSON; an already-protected value is left as is.</summary>
/// <param name="protector">The data protector.</param>
/// <param name="value">The value to store.</param>
/// <returns>The prefixed protected value.</returns>
internal static string Protect(IDataProtector protector, string value) =>
IsProtected(value) ? value : Prefix + protector.Protect(value);
/// <summary>Unprotects a stored value; a legacy plaintext value passes through unchanged.</summary>
/// <param name="protector">The data protector.</param>
/// <param name="stored">The stored column value.</param>
/// <returns>The plaintext configuration JSON.</returns>
internal static string Unprotect(IDataProtector protector, string stored) =>
IsProtected(stored) ? protector.Unprotect(stored[Prefix.Length..]) : stored;
}
@@ -0,0 +1,139 @@
using System.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
/// <summary>
/// One-time, idempotent startup re-protect of deployment configuration JSON written before
/// <see cref="DeploymentConfigSecretConverter"/> existed (code review 2026-12-02 CDB-1).
/// </summary>
/// <remarks>
/// <para>
/// <b>Why a startup backfill and not an EF migration:</b> protecting a row needs the Data
/// Protection key ring, which lives behind <c>IDataProtectionProvider</c> in the running host
/// and is not reachable from a SQL migration script (production applies migrations as generated
/// SQL). It runs from <see cref="MigrationHelper"/> in both development and production, after
/// the schema check, exactly like <see cref="DataConnectionSecretUpgrade"/>.
/// </para>
/// <para>
/// It is <b>plaintext-detecting</b> (only rows whose value lacks the protected prefix are
/// read), <b>bounded</b> (pages by primary key), <b>idempotent</b> (a second run finds nothing),
/// and <b>concurrency-safe</b>: 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 <b>not a startup gate</b> — the
/// converter still reads plaintext — so a failure is logged and startup continues; the next
/// start retries.
/// </para>
/// </remarks>
public static class DeploymentConfigSecretUpgrade
{
private const int PageSize = 64;
/// <summary>The tables whose <c>ConfigurationJson</c> column is protected.</summary>
internal static readonly string[] Tables = ["PendingDeployments", "DeployedConfigSnapshots"];
/// <summary>Re-protects every plaintext <c>ConfigurationJson</c> row in both tables.</summary>
/// <param name="db">A context constructed with the Data Protection provider.</param>
/// <param name="logger">Optional logger.</param>
/// <param name="cancellationToken">Token to cancel the upgrade.</param>
/// <returns>The number of rows re-protected.</returns>
public static async Task<int> 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<int> 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);
}
}
@@ -66,6 +66,11 @@ public static class MigrationHelper
await DataConnectionSecretUpgrade.UpgradeAsync(dbContext, cancellationToken); 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 // 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 // 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 // aborts startup for data reasons (per-row skip + log). Safe even if both central
@@ -262,6 +262,11 @@ public class ScadaBridgeDbContext : DbContext, IDataProtectionKeyContext
?? throw new InvalidOperationException("Data Protection is required to migrate protocol credentials.")) ?? throw new InvalidOperationException("Data Protection is required to migrate protocol credentials."))
.CreateProtector(DataConnectionSecretConverter.Purpose); .CreateProtector(DataConnectionSecretConverter.Purpose);
/// <summary>Data Protection protector for deployment configuration JSON (CDB-1); throws when no provider was supplied.</summary>
internal IDataProtector DeploymentConfigProtector => (_dataProtectionProvider
?? throw new InvalidOperationException("Data Protection is required to protect deployment configuration."))
.CreateProtector(DeploymentConfigSecretConverter.Purpose);
/// <summary>True when this context was constructed with a real Data Protection provider.</summary> /// <summary>True when this context was constructed with a real Data Protection provider.</summary>
internal bool HasSecretEncryptionProvider => _dataProtectionProvider is not null; internal bool HasSecretEncryptionProvider => _dataProtectionProvider is not null;
@@ -291,6 +296,9 @@ public class ScadaBridgeDbContext : DbContext, IDataProtectionKeyContext
DatabaseConnectionDefinition => nameof(DatabaseConnectionDefinition.ConnectionString), DatabaseConnectionDefinition => nameof(DatabaseConnectionDefinition.ConnectionString),
DataConnection connection when connection.PrimaryConfiguration is not null => nameof(DataConnection.PrimaryConfiguration), DataConnection connection when connection.PrimaryConfiguration is not null => nameof(DataConnection.PrimaryConfiguration),
DataConnection => nameof(DataConnection.BackupConfiguration), DataConnection => nameof(DataConnection.BackupConfiguration),
// CDB-1: the flattened config embeds the bound connections' protocol JSON.
PendingDeployment => nameof(PendingDeployment.ConfigurationJson),
DeployedConfigSnapshot => nameof(DeployedConfigSnapshot.ConfigurationJson),
_ => null _ => null
}; };
if (secretProperty is null) if (secretProperty is null)
@@ -385,6 +393,17 @@ public class ScadaBridgeDbContext : DbContext, IDataProtectionKeyContext
var protocolConverter = new DataConnectionSecretConverter(protocolProtector); var protocolConverter = new DataConnectionSecretConverter(protocolProtector);
modelBuilder.Entity<DataConnection>().Property(d => d.PrimaryConfiguration).HasConversion(protocolConverter); modelBuilder.Entity<DataConnection>().Property(d => d.PrimaryConfiguration).HasConversion(protocolConverter);
modelBuilder.Entity<DataConnection>().Property(d => d.BackupConfiguration).HasConversion(protocolConverter); modelBuilder.Entity<DataConnection>().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<PendingDeployment>().Property(p => p.ConfigurationJson).HasConversion(configConverter);
modelBuilder.Entity<DeployedConfigSnapshot>().Property(s => s.ConfigurationJson).HasConversion(configConverter);
} }
/// <summary> /// <summary>
@@ -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;
/// <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);
}
}
@@ -137,11 +137,17 @@ public class PendingDeploymentRepositoryIntegrationTests : IClassFixture<MsSqlMi
return instance.Id; return instance.Id;
} }
// CDB-1: PendingDeployments.ConfigurationJson is encrypted at rest, so a write-capable
// context needs a key ring; one shared provider lets every context in a test read the
// others' writes.
private static readonly Microsoft.AspNetCore.DataProtection.IDataProtectionProvider KeyRing =
new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider();
private ScadaBridgeDbContext CreateContext() private ScadaBridgeDbContext CreateContext()
{ {
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>() var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
.UseSqlServer(_fixture.ConnectionString) .UseSqlServer(_fixture.ConnectionString)
.Options; .Options;
return new ScadaBridgeDbContext(options); return new ScadaBridgeDbContext(options, KeyRing);
} }
} }