Separates website and admin roots, adds /health, hardens the availability gate
Prepares the single-host layout for deployment. The customer's public website moves from wwwroot/ to wwwroot/web/, so a CMS deploy can no longer overwrite content it does not own: with the website in its own directory, the release directory can be swapped without touching it. Each front-end gets its own file provider, and both tolerate a missing directory at startup — a fresh deployment has no website until a separate workspace deploys one, and the CMS must still serve /admin and the API. When the website's index.html is absent, an embedded placeholder is served instead of a 404, which also doubles as proof the CMS itself is running. The placeholder is embedded in the assembly rather than shipped into wwwroot/web/, because that directory is owned and overwritten by the website workspace. Adds GET /health for uptime monitoring. It reports infrastructure liveness only and is deliberately NOT the same thing as /api/v1/Availability/status or /api/v1/System/capabilities: those are CMS domain state that also serve the master/slave protocol. A healthy instance can be switched off by design, and a switched-on instance can be unhealthy, so conflating them would alert on business state and stay silent on real outages. /health is on the availability gate's bypass list for the same reason. Fixes a real defect in the gate's admin bypass. It parsed the bearer token with ReadJwtToken, which reads claims without verifying the signature, so an unauthenticated caller could forge an unsigned token carrying an Owner role claim and bypass the gate that suspends a customer's site. Protected endpoints still rejected them, so nothing leaked — but the gate itself was bypassable. The token is now fully validated against the same parameters as the bearer scheme, resolved from one shared source so the two cannot drift apart. Host wiring for these changes lands with the data-durability commit, since both units touch the same lines of Program.cs. 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,69 @@
|
||||
using System.Reflection;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Health;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the infrastructure liveness endpoint.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Deliberately takes no options parameter. Adding a database probe or any other dependency
|
||||
/// check must therefore be a visible code change here rather than a configuration setting
|
||||
/// someone can flip — liveness-only is enforced by the shape of this API, not by discipline.
|
||||
///
|
||||
/// Why liveness alone is a meaningful signal: startup applies database migrations and fails
|
||||
/// fast when they cannot be applied (see <see cref="DatabaseMigrationExtensions"/>). A process
|
||||
/// that cannot reach its database therefore never starts, so <c>/health</c> stops answering
|
||||
/// entirely. The unhealthy signal is the absence of a response, not a response saying so.
|
||||
/// </remarks>
|
||||
public static class HealthCheckExtensions
|
||||
{
|
||||
/// <summary>Path of the liveness endpoint. Also present in the availability gate's bypass list.</summary>
|
||||
public const string HealthPath = "/health";
|
||||
|
||||
public static IServiceCollection AddCmsHealthChecks(this IServiceCollection services)
|
||||
{
|
||||
services.AddHealthChecks();
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps <c>GET /health</c>, returning a JSON report composed from in-process state only.
|
||||
/// </summary>
|
||||
public static IEndpointRouteBuilder MapCmsHealthChecks(this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapGet(HealthPath, (HttpContext context) =>
|
||||
{
|
||||
var orchestrator = context.RequestServices.GetService<ModuleOrchestrator>();
|
||||
|
||||
var report = new HealthReport(
|
||||
Status: "Healthy",
|
||||
Timestamp: DateTimeOffset.UtcNow,
|
||||
Version: GetVersion(),
|
||||
// Module names are already public via /api/v1/System/capabilities, so including
|
||||
// them here discloses nothing new. They are included because ModuleOrchestrator
|
||||
// logs rather than throws when a module fails to load: an instance can start
|
||||
// "successfully" with a missing capability, and this is the only way to detect
|
||||
// that after a deploy without host access.
|
||||
Modules: orchestrator?.ModuleNames ?? []);
|
||||
|
||||
return Results.Ok(report);
|
||||
})
|
||||
.AllowAnonymous()
|
||||
.WithName("HealthCheck");
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
private static string GetVersion()
|
||||
{
|
||||
var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
|
||||
|
||||
return assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion
|
||||
?? assembly.GetName().Version?.ToString()
|
||||
?? "unknown";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Health;
|
||||
|
||||
/// <summary>
|
||||
/// Response model for the infrastructure liveness endpoint.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Reports infrastructure liveness ONLY. This is deliberately not the same thing as the CMS's
|
||||
/// own availability state (<c>/api/v1/Availability/status</c>) or its loaded-capability report
|
||||
/// (<c>/api/v1/System/capabilities</c>), both of which are domain functionality that also serve
|
||||
/// the master/slave protocol. A healthy instance can be switched off by design, and a switched-on
|
||||
/// instance can be unhealthy — so the two must never be conflated in monitoring.
|
||||
///
|
||||
/// Every field is derived from in-process state. Nothing here may require a database query,
|
||||
/// file read or network call.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed record HealthReport(
|
||||
string Status,
|
||||
DateTimeOffset Timestamp,
|
||||
string Version,
|
||||
IReadOnlyList<string> Modules);
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Text;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Single source of the JWT validation parameters used across the application.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// These parameters are consumed in two places: the JWT bearer authentication scheme,
|
||||
/// and the availability gate's admin bypass (see <c>IAdminTokenValidator</c>).
|
||||
///
|
||||
/// They MUST come from here rather than being configured separately in each place.
|
||||
/// If the two ever drifted apart and the gate became the more permissive of the two,
|
||||
/// a token the bearer scheme rejects could still bypass the availability gate — which
|
||||
/// is exactly the defect the validated admin bypass was introduced to close.
|
||||
/// </remarks>
|
||||
public static class JwtTokenValidation
|
||||
{
|
||||
/// <summary>
|
||||
/// Builds the validation parameters for the given settings.
|
||||
/// </summary>
|
||||
public static TokenValidationParameters Create(JwtSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
|
||||
return new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = settings.Issuer,
|
||||
ValidAudience = settings.Audience,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.Secret)),
|
||||
// Exact expiry — a token is valid until its expiry moment and not a second longer.
|
||||
ClockSkew = TimeSpan.Zero
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Validates a bearer token against the application's JWT validation parameters and checks
|
||||
/// for an administrative role.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This replaces an earlier implementation that parsed the token with
|
||||
/// <c>JwtSecurityTokenHandler.ReadJwtToken</c> — which reads claims WITHOUT verifying the
|
||||
/// signature. Under that implementation an unauthenticated caller could present a self-made,
|
||||
/// unsigned token carrying an Owner role claim and bypass the availability gate. Protected
|
||||
/// endpoints still rejected such a caller, so no data was exposed, but the gate that suspends
|
||||
/// a customer's site could be bypassed by anyone who knew the claim name.
|
||||
/// </remarks>
|
||||
public sealed class AdminTokenValidator : IAdminTokenValidator
|
||||
{
|
||||
private const string BearerPrefix = "Bearer ";
|
||||
|
||||
private static readonly string[] AdminRoles = ["Owner", "Administrator"];
|
||||
|
||||
private readonly TokenValidationParameters _validationParameters;
|
||||
private readonly JwtSecurityTokenHandler _handler = new();
|
||||
|
||||
public AdminTokenValidator(TokenValidationParameters validationParameters)
|
||||
{
|
||||
_validationParameters = validationParameters ?? throw new ArgumentNullException(nameof(validationParameters));
|
||||
}
|
||||
|
||||
public bool IsVerifiedAdmin(string? authorizationHeader)
|
||||
{
|
||||
if (string.IsNullOrEmpty(authorizationHeader) ||
|
||||
!authorizationHeader.StartsWith(BearerPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var token = authorizationHeader[BearerPrefix.Length..].Trim();
|
||||
if (token.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
ClaimsPrincipal principal;
|
||||
try
|
||||
{
|
||||
// Validates signature, issuer, audience and lifetime. A forged or expired token
|
||||
// throws here and is treated as "not an admin" rather than as an error — deciding
|
||||
// whether to serve is this component's job; returning 401 is not.
|
||||
principal = _handler.ValidateToken(token, _validationParameters, out _);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return AdminRoles.Any(role => principal.IsInRole(role))
|
||||
|| principal.FindAll(ClaimTypes.Role).Any(c => AdminRoles.Contains(c.Value))
|
||||
|| principal.FindAll("role").Any(c => AdminRoles.Contains(c.Value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Decides whether a request carries a genuinely valid Owner or Administrator token.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Used by the availability gate, which runs before authentication middleware and therefore
|
||||
/// cannot read <c>HttpContext.User</c>. Validation uses the same parameters as the JWT bearer
|
||||
/// scheme (see <see cref="JwtTokenValidation"/>), so the gate can never be more permissive
|
||||
/// than authentication itself.
|
||||
/// </remarks>
|
||||
public interface IAdminTokenValidator
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns true only when the supplied Authorization header contains a bearer token that
|
||||
/// validates successfully and carries the Owner or Administrator role.
|
||||
/// </summary>
|
||||
/// <param name="authorizationHeader">Raw Authorization header value; may be null or empty.</param>
|
||||
/// <returns>
|
||||
/// True when the caller is a verified Owner or Administrator; false in every other case,
|
||||
/// including an absent, malformed, forged, expired or non-admin token. Never throws.
|
||||
/// </returns>
|
||||
bool IsVerifiedAdmin(string? authorizationHeader);
|
||||
}
|
||||
@@ -11,11 +11,11 @@ using Microsoft.IdentityModel.Tokens;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Exceptions;
|
||||
using SlpModularCms.Core.Hosting.Security;
|
||||
using SlpModularCms.Core.Identity.Authorization;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
using System.Text;
|
||||
using System.Threading.RateLimiting;
|
||||
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -56,6 +56,16 @@ public static class ServiceCollectionExtensions
|
||||
services.AddScoped<ISetupService, SetupService>();
|
||||
|
||||
// 4. Authentication
|
||||
//
|
||||
// The validation parameters are built once and shared: the bearer scheme below and the
|
||||
// availability gate's admin bypass (IAdminTokenValidator) both use this same instance.
|
||||
// Configuring them separately would allow the two to drift, and a gate more permissive
|
||||
// than the bearer scheme would let a token that authentication rejects still bypass the
|
||||
// availability gate.
|
||||
var tokenValidationParameters = JwtTokenValidation.Create(jwtSettings);
|
||||
services.AddSingleton(tokenValidationParameters);
|
||||
services.AddSingleton<IAdminTokenValidator>(_ => new AdminTokenValidator(tokenValidationParameters));
|
||||
|
||||
services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
@@ -63,17 +73,7 @@ public static class ServiceCollectionExtensions
|
||||
})
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtSettings.Issuer,
|
||||
ValidAudience = jwtSettings.Audience,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secret)),
|
||||
ClockSkew = TimeSpan.Zero
|
||||
};
|
||||
options.TokenValidationParameters = tokenValidationParameters;
|
||||
});
|
||||
|
||||
// 5. Authorization
|
||||
|
||||
Reference in New Issue
Block a user