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
@@ -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);
// 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
@@ -262,6 +262,11 @@ public class ScadaBridgeDbContext : DbContext, IDataProtectionKeyContext
?? throw new InvalidOperationException("Data Protection is required to migrate protocol credentials."))
.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>
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<DataConnection>().Property(d => d.PrimaryConfiguration).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>