Makes a redeploy safe for the key ring and the schema
Nothing here is visible in normal operation. Its whole purpose is that swapping the release directory on deploy cannot silently destroy state. Data Protection secures the API keys that authenticate master/slave communication. Two separate defaults would each have destroyed them: keys are held on the filesystem, which a release swap discards, and the application discriminator is derived from the content root path, which changes with every release directory — so even keys stored in a database would have stopped being derivable. Keys now live in ApplicationDbContext and the discriminator is a fixed constant. Losing them produces no error. It produces stored keys that no longer decrypt, which presents as an apparent network fault between a Master and its slaves and is easily misdiagnosed. That is also why the tests assert the resulting configuration rather than the registration: the XmlRepository must be the EF one and the discriminator must be the constant, plus a round-trip proving a value encrypted before a deploy is readable after one. A test that only checked "Data Protection is registered" would have passed in the broken case too. Both modules previously called AddDataProtection() themselves. Module registration runs after the host's, so those calls re-registered the configuration chain and would have overridden the persistent store while IDataProtector still resolved. They are removed, with a comment at each site — the deletion otherwise looks like a regression. Each module's own test project now guards against it being reintroduced. ApplicationDbContext also migrates itself at startup. Deploy targets offer no CLI, so migrations cannot be a manual step on the server. Failures are classified rather than treated alike: a connection failure means the database is not up yet, normal when the app and the database start together after a reboot, and is retried with backoff; a migration failure means something is broken and fails at once. Either way the process does not start, which is what makes the liveness health check trustworthy — an application that cannot reach its schema never answers /health, so monitoring goes red instead of reporting a healthy instance that cannot serve a request. The cost of migrating without a human gate is that migrations must stay forward-compatible and non-destructive, since rollback is "redeploy the previous release". The new migration is purely additive. Also wires this and the preceding hosting commit into both hosts, as they touch the same lines of Program.cs. Two constraints are enforced by documentation rather than code, and belong in the deployment instructions: the key table must never be pruned, and only one instance may migrate a given database at a time. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HHoJpxYXzHACSQguHrC5fw
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SlpModularCms.Core.Data;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Configures ASP.NET Core Data Protection so encrypted values survive a redeploy.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Data Protection secures the API keys that authenticate master/slave communication. Losing the
|
||||
/// key ring does not produce an error — it produces stored keys that no longer decrypt, which
|
||||
/// presents as an apparent network fault between a Master and its slaves and is easily
|
||||
/// misdiagnosed. Two separate defaults would each cause exactly that:
|
||||
///
|
||||
/// 1. Keys are held on the filesystem by default. Deployments swap the release directory
|
||||
/// atomically, so a filesystem key ring is discarded on every deploy.
|
||||
/// 2. The application discriminator is derived from the content root path by default. That path
|
||||
/// changes with every release directory, so even keys stored in the database would stop being
|
||||
/// derivable.
|
||||
///
|
||||
/// This method closes both. It MUST be called before module service registration — see the
|
||||
/// remarks on <see cref="AddCmsDataProtection"/>.
|
||||
/// </remarks>
|
||||
public static class DataProtectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Stable identity of this application for key derivation.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A constant rather than a configuration value, deliberately. Every configurable knob here
|
||||
/// is a way to reintroduce the silent failure this whole mechanism exists to prevent — a
|
||||
/// discriminator set differently on one instance, or forgotten during a host migration,
|
||||
/// makes previously encrypted values unreadable with no error to point at.
|
||||
/// </remarks>
|
||||
public const string ApplicationDiscriminator = "SlpModularCms";
|
||||
|
||||
/// <summary>
|
||||
/// Registers Data Protection with a database-backed key ring and a fixed application
|
||||
/// discriminator.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// MUST be called before <c>ModuleOrchestrator.RegisterModuleServices</c>. Modules must not
|
||||
/// call <c>AddDataProtection()</c> themselves: module registration runs after the host's, and
|
||||
/// a later bare call re-registers the configuration chain, silently discarding the persistent
|
||||
/// key store configured here. <c>IDataProtector</c> resolves either way, so such a regression
|
||||
/// passes registration tests and only surfaces after the first release switch.
|
||||
/// </remarks>
|
||||
public static IServiceCollection AddCmsDataProtection(this IServiceCollection services)
|
||||
{
|
||||
services
|
||||
.AddDataProtection()
|
||||
.SetApplicationName(ApplicationDiscriminator)
|
||||
.PersistKeysToDbContext<ApplicationDbContext>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SlpModularCms.Core.Data;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Applies the Core database migrations at startup.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Deployment targets are shared hosts where no CLI is available, so migrations cannot be a
|
||||
/// manual step on the server. Applying them at startup makes a deployment self-contained.
|
||||
///
|
||||
/// The cost of that convenience is that a migration now runs without a human gate — which is why
|
||||
/// migrations must stay forward-compatible and non-destructive (rollback is "redeploy the previous
|
||||
/// release", and that only works if older code can run against the newer schema), and why a
|
||||
/// database backup precedes every production deploy.
|
||||
/// </remarks>
|
||||
public static class DatabaseMigrationExtensions
|
||||
{
|
||||
/// <summary>Attempts made when the database is not reachable yet.</summary>
|
||||
public const int MaxConnectionAttempts = 5;
|
||||
|
||||
private static readonly TimeSpan BaseRetryDelay = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>
|
||||
/// Applies pending <see cref="ApplicationDbContext"/> migrations before the application
|
||||
/// serves traffic.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Failures are classified rather than treated alike:
|
||||
/// <list type="bullet">
|
||||
/// <item><description>A <b>connection</b> failure means the database is not up yet — normal
|
||||
/// when the application and the database server start together after a host reboot. Retried
|
||||
/// with increasing delay.</description></item>
|
||||
/// <item><description>A <b>migration</b> failure means a migration is invalid or conflicts.
|
||||
/// Retrying only delays the inevitable and fills the log, so it fails at once.</description></item>
|
||||
/// </list>
|
||||
/// Either way the exception ultimately propagates and the process does not start. That is
|
||||
/// deliberate and is what makes the liveness health check meaningful: an application that
|
||||
/// cannot reach its schema never answers <c>/health</c>, so monitoring goes red instead of
|
||||
/// reporting a healthy instance that cannot serve a single request.
|
||||
/// </remarks>
|
||||
public static WebApplication MigrateCoreDatabase(this WebApplication app)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(app);
|
||||
|
||||
var logger = app.Services.GetRequiredService<ILoggerFactory>()
|
||||
.CreateLogger(typeof(DatabaseMigrationExtensions).FullName!);
|
||||
|
||||
using var scope = app.Services.CreateScope();
|
||||
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
context.Database.Migrate();
|
||||
logger.LogInformation("Core database migrations applied successfully.");
|
||||
return app;
|
||||
}
|
||||
catch (Exception ex) when (IsTransientConnectionFailure(ex) && attempt < MaxConnectionAttempts)
|
||||
{
|
||||
var delay = BaseRetryDelay * attempt;
|
||||
|
||||
logger.LogWarning(
|
||||
"Database not reachable on attempt {Attempt} of {MaxAttempts}. Retrying in {DelaySeconds}s. Reason: {Reason}",
|
||||
attempt,
|
||||
MaxConnectionAttempts,
|
||||
delay.TotalSeconds,
|
||||
ex.Message);
|
||||
|
||||
Thread.Sleep(delay);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Logged with the failure reason but never the connection string or credentials —
|
||||
// this message travels to the console and to Sentry.
|
||||
logger.LogCritical(
|
||||
ex,
|
||||
"Core database migration failed after {Attempts} attempt(s). The application will not start.",
|
||||
attempt);
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Distinguishes "the database is not there yet" from "the migration is broken".
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Wrong credentials are treated as a connection failure too. Telling them apart from an
|
||||
/// unreachable server would add branching for no benefit: the outcome is identical — retries
|
||||
/// are exhausted and the process does not start.
|
||||
/// </remarks>
|
||||
private static bool IsTransientConnectionFailure(Exception exception)
|
||||
{
|
||||
for (var current = exception; current is not null; current = current.InnerException)
|
||||
{
|
||||
if (current is SqlException or TimeoutException)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user