Files
slp-modular-cms/src/SlpModularCms.Core/Hosting/CmsHost.cs
T
SluijsensandClaude Sonnet 5 fa389e42ee
Continuous Integration / config (pull_request) Successful in 11s
Continuous Integration / changes (pull_request) Successful in 21s
Continuous Integration / backend-build (pull_request) Successful in 6m10s
Continuous Integration / vulnerability-scan (pull_request) Successful in 4m59s
Continuous Integration / frontend-prepare (pull_request) Successful in 1m27s
Continuous Integration / backend-test (pull_request) Failing after 7m48s
Continuous Integration / frontend-build (pull_request) Successful in 2m5s
Continuous Integration / frontend-test (pull_request) Successful in 4m24s
Continuous Integration / frontend-lint (pull_request) Successful in 2m0s
Continuous Integration / publish-test (pull_request) Skipped
Continuous Integration / publish-production (pull_request) Skipped
Continuous Integration / deploy-test (pull_request) Skipped
Continuous Integration / deploy-production (pull_request) Skipped
Adds SlpModularCms.Api.SlpSoftware and extracts shared CmsHost composition
Unit 1 of the slpsoftware-api feature (FR-1/FR-2/FR-3): a new Client project
in the Clients solution folder, intended to eventually become the deployed
API for test.slpsoftware.nl/slpsoftware.nl, hosting the same four modules as
SlpModularCms.Api plus a future Offerings module.

- Extracts SlpModularCms.Api/Program.cs's hosting-pipeline composition into
  SlpModularCms.Core.Hosting.CmsHost (ConfigureServices/ConfigurePipeline),
  shared by both Client projects so they cannot drift apart
- Moves StaticContentExtensions.cs + WebsitePlaceholder.html from Api into
  Core, since CmsHost cannot live in Api but Core cannot depend on Api
- Adds SlpModularCms.Api.SlpSoftware with its own isolated local dev database
  and dev ports (5286/7223, distinct from Api's and Api.Slave's)
- Adds SlpModularCms.Api.Tests with WebApplicationFactory-based pipeline
  regression tests (security headers, health check, SPA fallback, rate
  limiting), scoped to Api per NFR Design
- Adds a frontend dev:slpsoftware pnpm script mirroring dev:slave
- Fixes GlobalExceptionHandler logging routine 401s (e.g. an expired/missing
  refresh token) as unhandled errors -- pre-existing, unrelated to this
  feature's own scope, found while testing the new instance

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FWyStNL2ZsjrS7FLd7xvvN
2026-08-02 01:28:39 +02:00

150 lines
7.3 KiB
C#

using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SlpModularCms.Core.Hosting.Health;
using SlpModularCms.Core.Hosting.Observability;
using SlpModularCms.Core.Hosting.Security;
using Scalar.AspNetCore;
namespace SlpModularCms.Core.Hosting;
/// <summary>
/// Shared hosting composition for every Client project (<c>Api</c>, <c>Api.SlpSoftware</c>, ...).
/// </summary>
/// <remarks>
/// Extracted from what was originally <c>SlpModularCms.Api/Program.cs</c> in full, so that adding a
/// second (and any future) Client project does not mean duplicating this composition — a change
/// made here applies to every Client project automatically. The two methods mirror the two halves
/// of a minimal ASP.NET Core <c>Program.cs</c>: service registration (before <c>builder.Build()</c>)
/// and pipeline configuration (after it). Each caller's own <c>Program.cs</c> keeps only the two
/// lines that must stay per-project: constructing the <see cref="WebApplicationBuilder"/> itself and
/// loading that project's own <c>appsettings.local.json</c>.
/// </remarks>
public static class CmsHost
{
/// <summary>
/// Registers every service a Client project needs: logging, Sentry, module discovery and
/// registration, core infrastructure, and MVC controllers.
/// </summary>
/// <returns>
/// The <see cref="ModuleOrchestrator"/> used during registration, so the caller can pass the
/// same instance into <see cref="ConfigurePipeline"/> after <c>builder.Build()</c>.
/// </returns>
public static ModuleOrchestrator ConfigureServices(WebApplicationBuilder builder, CmsHostOptions options)
{
// Logging FIRST, so a problem initialising Sentry below is itself logged. Puts the W3C trace id
// into the scope of every entry from every category — the correlation id that also travels to
// the slave via traceparent and appears as `traceId` in ProblemDetails responses.
builder.Logging.AddCmsLogging(builder.Environment);
// Then Sentry. Does nothing at all when no DSN is configured, which is a normal, fully
// supported state rather than an error.
builder.WebHost.UseCmsSentry(builder.Configuration);
// 1. Initialize Module Orchestrator
var loggerFactory = LoggerFactory.Create(lb => lb.AddConsole());
var orchestrator = new ModuleOrchestrator(loggerFactory.CreateLogger<ModuleOrchestrator>());
orchestrator.DiscoverModules();
// 2. Add Core Infrastructure
builder.Services.AddCoreInfrastructure(builder.Configuration);
builder.Services.AddCmsCors(builder.Configuration);
builder.Services.AddCmsRateLimiting(builder.Configuration);
builder.Services.AddCmsHealthChecks();
builder.Services.AddCmsSecurityHeaders(builder.Configuration);
builder.Services.AddCmsObservability(builder.Configuration);
// Registered BEFORE module services: modules must not configure Data Protection themselves,
// because a later registration would override this persistent key store (see
// DataProtectionExtensions).
builder.Services.AddCmsDataProtection();
// 3. Add Module Services
orchestrator.RegisterModuleServices(builder.Services);
builder.Services.AddSingleton(orchestrator);
// 4. Global Controller Configuration with Conventions
builder.Services.AddControllers(controllerOptions =>
{
controllerOptions.Conventions.Add(new ApiPrefixConvention("api/v1"));
})
.AddJsonOptions(jsonOptions =>
{
jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
return orchestrator;
}
/// <summary>
/// Configures the HTTP pipeline every Client project needs, in the exact order the original
/// <c>Api/Program.cs</c> used — that order encodes real constraints, documented inline below.
/// </summary>
public static void ConfigurePipeline(WebApplication app, ModuleOrchestrator orchestrator, CmsHostOptions options)
{
// Bring the Core schema up to date before serving any traffic. Runs before the module
// middleware below, because the Data Protection keys table lives in this context and the
// modules resolve an IDataProtector as soon as they start. Fails fast: a host that cannot
// migrate does not start, so /health goes silent and monitoring goes red — which is exactly
// what makes a liveness-only health check trustworthy.
app.MigrateCoreDatabase();
// 5. Global Exception Handling
app.UseExceptionHandler();
// First thing INSIDE the exception handler, and before the static-file middleware below.
// Both directions matter: the exception handler re-executes the pipeline from within itself,
// so anything registered outside it never sees the ProblemDetails response; and static files
// short-circuit the pipeline, so anything after them is invisible to the public website —
// which is almost all of the HTML this host serves.
app.UseCmsSecurityHeaders();
app.UseRateLimiter();
// 6. Configure Pipeline
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
}
app.UseHttpsRedirection();
// Serve the public website ('/') and the CMS admin SPA ('/admin') from wwwroot.
// wwwroot/web/index.html + assets -> public website (built and deployed separately, not part of this repo)
// wwwroot/admin/index.html + assets -> CMS admin build (see frontend/, copied in on publish)
// Registered before the module middleware below: static files short-circuit the pipeline, so
// anything that must observe them has to come first.
app.UseCmsStaticContent();
app.UseCors();
// 7. Use Module Middleware
orchestrator.UseModules(app);
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Infrastructure liveness. Deliberately outside /api/v1 and on the availability gate's bypass
// list: this reports whether the process is alive, which is a different question from whether
// the CMS is switched on (/api/v1/Availability/status) or which modules it carries
// (/api/v1/System/capabilities). Those are CMS domain state and must not be used for monitoring.
app.MapCmsHealthChecks();
// Forwards browser Sentry envelopes through this origin, because ad blockers block requests to
// Sentry domains outright. Mapped before the SPA catch-all below, and deliberately NOT on the
// availability gate's bypass list: if the instance is switched off, losing admin-SPA error
// reports is acceptable, and that is one fewer anonymous outbound-capable endpoint reachable on
// a disabled instance.
app.MapSentryTunnel();
// SPA fallbacks so client-side routes (e.g. /admin/dashboard) resolve to the right index.html
// instead of 404ing. The "nonfile" constraint keeps genuinely missing assets (e.g. /admin/assets/x.js) as 404s.
app.MapCmsSpaFallbacks();
}
}