Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/MigrationHelper.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

125 lines
5.6 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
/// <summary>
/// Provides environment-aware migration behavior for the ScadaBridge configuration database.
/// </summary>
public static class MigrationHelper
{
/// <summary>Command timeout applied to the development auto-apply of migrations.</summary>
internal static readonly TimeSpan MigrationCommandTimeout = TimeSpan.FromMinutes(30);
/// <summary>
/// Applies pending migrations (development mode) or validates schema version (production mode).
/// </summary>
/// <param name="dbContext">The database context to migrate or validate.</param>
/// <param name="isDevelopment">When true, auto-applies migrations. When false, validates schema version matches.</param>
/// <param name="logger">Optional logger for readiness-wait diagnostics.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public static async Task ApplyOrValidateMigrationsAsync(
ScadaBridgeDbContext dbContext,
bool isDevelopment,
ILogger? logger = null,
CancellationToken cancellationToken = default)
{
// Wait for the target database to accept connections before invoking MigrateAsync.
// On a fresh MSSQL container, user databases recover asynchronously after the server
// starts accepting connections — DB_ID(@dbName) returns null until recovery completes.
// Without this wait, MigrateAsync sees the database as missing and falls through to
// CREATE DATABASE, which fails for non-privileged app logins.
await WaitForDatabaseReadyAsync(dbContext, logger, cancellationToken);
if (isDevelopment)
{
// Index builds over a large AuditLog (millions of rows on the rig) take minutes,
// and the peer central node waits on EF's migration applock for the same span —
// the default 30 s command timeout fails both. Production applies migrations from
// the generated SQL scripts, so this only widens the dev auto-apply path.
var previousTimeout = dbContext.Database.GetCommandTimeout();
dbContext.Database.SetCommandTimeout(MigrationCommandTimeout);
try
{
await dbContext.Database.MigrateAsync(cancellationToken);
}
finally
{
dbContext.Database.SetCommandTimeout(previousTimeout);
}
}
else
{
var pendingMigrations = await dbContext.Database.GetPendingMigrationsAsync(cancellationToken);
var pending = pendingMigrations.ToList();
if (pending.Count > 0)
{
throw new InvalidOperationException(
$"Database schema is out of date. {pending.Count} pending migration(s): {string.Join(", ", pending)}. " +
"Apply migrations using 'dotnet ef database update' or the generated SQL scripts before starting in production mode.");
}
}
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
// nodes run it concurrently on startup.
await ListValueNormalizer.NormalizeAsync(dbContext, logger, cancellationToken);
}
private static async Task WaitForDatabaseReadyAsync(
ScadaBridgeDbContext dbContext,
ILogger? logger,
CancellationToken cancellationToken)
{
var timeout = TimeSpan.FromSeconds(60);
var pollInterval = TimeSpan.FromSeconds(2);
var deadline = DateTimeOffset.UtcNow + timeout;
var attempt = 0;
Exception? lastException = null;
while (DateTimeOffset.UtcNow < deadline)
{
attempt++;
try
{
if (await dbContext.Database.CanConnectAsync(cancellationToken))
{
if (attempt > 1)
{
logger?.LogInformation(
"Configuration database ready after {Attempt} attempt(s).", attempt);
}
return;
}
logger?.LogDebug(
"Configuration database not yet reachable (attempt {Attempt}).", attempt);
}
catch (Exception ex)
{
lastException = ex;
logger?.LogDebug(ex,
"Configuration database not yet reachable (attempt {Attempt}).", attempt);
}
await Task.Delay(pollInterval, cancellationToken);
}
throw new InvalidOperationException(
$"Configuration database not ready after {timeout.TotalSeconds:N0}s ({attempt} attempts). " +
"Verify SQL Server is running and the configuration database exists and is attached.",
lastException);
}
}