using System.Data; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase; /// /// One-time, idempotent startup re-protect of deployment configuration JSON written before /// existed (code review 2026-12-02 CDB-1). /// /// /// /// Why a startup backfill and not an EF migration: protecting a row needs the Data /// Protection key ring, which lives behind IDataProtectionProvider in the running host /// and is not reachable from a SQL migration script (production applies migrations as generated /// SQL). It runs from in both development and production, after /// the schema check, exactly like . /// /// /// It is plaintext-detecting (only rows whose value lacks the protected prefix are /// read), bounded (pages by primary key), idempotent (a second run finds nothing), /// and concurrency-safe: 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 not a startup gate — the /// converter still reads plaintext — so a failure is logged and startup continues; the next /// start retries. /// /// public static class DeploymentConfigSecretUpgrade { private const int PageSize = 64; /// The tables whose ConfigurationJson column is protected. internal static readonly string[] Tables = ["PendingDeployments", "DeployedConfigSnapshots"]; /// Re-protects every plaintext ConfigurationJson row in both tables. /// A context constructed with the Data Protection provider. /// Optional logger. /// Token to cancel the upgrade. /// The number of rows re-protected. public static async Task 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 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); } }