Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/DeploymentConfigSecretUpgrade.cs
T
Joseph Doherty d4e13d3aa4 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).
2026-12-03 10:28:39 -05:00

140 lines
6.5 KiB
C#

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