feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
CI / Build and test (SQLite) (pull_request) Successful in 55s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Failing after 2m4s

The instance now starts on its own from KHAEMHAT_* variables: it migrates the system
and company databases, creates the super user and the first company, and only then
reports ready. Users sign in with password and TOTP through revocable database
sessions, and licences decide which modules and how many companies are available.

- Configuration: every wrong variable reported at once (exit code 2), _FILE variants
- Accounts, password policy and lockout, TOTP with recovery codes, session states
  with token rotation, security audit with a hash chain
- Sign-in pages (mockups 001-003), authorization attributes, security headers and a
  CSP without inline scripts, login rate limit
- Signed licences, activation codes, test mode, licence tool
- DataProtection keys in the system database, encrypted with the instance key
- Memory or Redis cache (in-house RESP client) that falls back to memory
- Database log by section with trace id; cron scheduler with locks and system jobs;
  record history (audit_log)
- Company creation, states, company context and X-Company, 503 in maintenance
- In-memory SQLite databases stay alive for the process (tests, demo)
- Tests for all of the above, ADR 0019, wiki, SECURITY, CHANGELOG, STATUS, DATA-MODEL

Refs #15 #16 #17 #18 #19 #20 #21 #22 #23 #24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 15:29:24 +01:00
1 parent 4582837b70
commit 032c602b49
107 files changed
+12202 -116

No files matched your search

+72 -23
View File
@@ -1,6 +1,17 @@
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Security;
using Khaemhat.Core.Common;
using Khaemhat.Infrastructure.Logging;
using Khaemhat.Infrastructure.Security;
using Khaemhat.Web.Components;
using Khaemhat.Web.Security;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Options;
namespace Khaemhat.Web.Hosting;
@@ -11,7 +22,9 @@ namespace Khaemhat.Web.Hosting;
public static class KhaemhatApp
{
/// <summary>Creates the configured application, ready to run.</summary>
/// <param name="args">Command-line arguments (ASP.NET Core host conventions, e.g. <c>--urls</c>).</param>
/// <param name="args">Command-line arguments (ASP.NET Core host conventions, e.g. <c>--urls</c>; also <c>--KHAEMHAT_*=value</c>).</param>
/// <returns>The application.</returns>
/// <exception cref="ConfigurationException">The <c>KHAEMHAT_*</c> variables are missing or not valid.</exception>
public static WebApplication Build(string[] args)
{
// ApplicationName pins the static web assets manifest to this assembly, also when tests host the app.
@@ -21,9 +34,13 @@ public static class KhaemhatApp
ApplicationName = typeof(KhaemhatApp).Assembly.GetName().Name,
});
ApplyInstanceVariables(builder, args);
// The variables of SPEC §6, with the _FILE variants of ADR 0014; any problem stops the start with every message.
var options = new EnvironmentConfigurationReader(name => builder.Configuration[name]).Read();
options.EnsureValid();
ApplyHostVariables(builder, options, args);
// One JSON line per event on stdout outside development (SPEC §9.5); the database sink arrives in M2.
// One pipeline (SPEC §9.5): JSON lines on stdout outside development, and the database sink everywhere.
var logSink = new DbLogSink();
if (!builder.Environment.IsDevelopment())
{
builder.Logging.ClearProviders();
@@ -35,11 +52,29 @@ public static class KhaemhatApp
});
}
// Until the database key store of M2 exists, keys live in memory: nothing is written outside the data
// folder (SPEC §1.5). Antiforgery and circuit tokens therefore reset when the container restarts.
builder.Services.AddDataProtection()
.SetApplicationName("Khaemhat")
.UseEphemeralDataProtectionProvider();
builder.Logging.AddProvider(new DbLoggerProvider(logSink));
builder.Logging.AddFilter<DbLoggerProvider>("Microsoft", LogLevel.Warning);
builder.Logging.AddFilter<DbLoggerProvider>("System", LogLevel.Warning);
builder.Logging.AddFilter<DbLoggerProvider>(typeof(SessionAuthenticationHandler).FullName, LogLevel.Warning);
builder.Services.AddKhaemhat(options, logSink);
// DataProtection keys in the system database, encrypted with the instance key (SPEC §1.5).
builder.Services.AddDataProtection().SetApplicationName("Khaemhat");
builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(sp => new ConfigureOptions<KeyManagementOptions>(o =>
{
o.XmlRepository = new DataProtectionKeyStore(sp.GetRequiredService<Data.IUnitOfWorkFactory>());
o.XmlEncryptor = new SecretKeyXmlEncryptor(sp.GetRequiredService<Core.Security.ISecretProtector>());
}));
// Sign-in with the session cookie (SPEC §7.3) and policies for permissions, levels and modules.
builder.Services.AddAuthentication(SessionCookie.Scheme)
.AddScheme<AuthenticationSchemeOptions, SessionAuthenticationHandler>(SessionCookie.Scheme, null);
builder.Services.AddAuthorization();
builder.Services.AddSingleton<IAuthorizationPolicyProvider, KhaemhatPolicyProvider>();
builder.Services.AddSingleton<IAuthorizationHandler, KhaemhatAuthorizationHandler>();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<AuthenticationStateProvider, SessionRevalidatingStateProvider>();
builder.Services.AddSingleton(ProductVersion.FromAssembly(typeof(KhaemhatApp).Assembly));
builder.Services.AddRazorComponents()
@@ -53,37 +88,51 @@ public static class KhaemhatApp
app.UseExceptionHandler("/Error", createScopeForErrors: true);
}
app.UseSecurityHeaders();
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.MapHealthEndpoints();
app.UseStartingPage();
app.UseAuthentication();
app.UseLogScope();
app.UseCompanyAvailability();
app.UseLoginRateLimit();
app.UseAuthorization();
app.UseAntiforgery();
app.MapHealthEndpoints();
app.MapStaticAssets();
app.MapSignOut();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
return app;
}
// The KHAEMHAT_* variables of SPEC §6 that the host itself needs. The full validation (KhaemhatOptions) is M1.
private static void ApplyInstanceVariables(WebApplicationBuilder builder, string[] args)
// Host settings taken from the variables: listening addresses and log level.
private static void ApplyHostVariables(WebApplicationBuilder builder, KhaemhatOptions options, string[] args)
{
// KHAEMHAT_URLS wins over ASPNETCORE_HTTP_PORTS of the image; an explicit --urls argument wins over both.
var urls = builder.Configuration["KHAEMHAT_URLS"];
if (!string.IsNullOrWhiteSpace(urls) && !args.Any(a => a.StartsWith("--urls", StringComparison.Ordinal)))
if (!string.IsNullOrWhiteSpace(options.Urls) && !args.Any(a => a.StartsWith("--urls", StringComparison.Ordinal)))
{
builder.WebHost.UseUrls(urls);
builder.WebHost.UseUrls(options.Urls);
}
var level = builder.Configuration["KHAEMHAT_LOG_LEVEL"];
if (!string.IsNullOrWhiteSpace(level))
if (!string.IsNullOrWhiteSpace(options.LogLevel) && Enum.TryParse<LogLevel>(options.LogLevel, ignoreCase: true, out var level))
{
if (!Enum.TryParse<LogLevel>(level, ignoreCase: true, out var parsed) || !Enum.IsDefined(parsed))
{
throw new InvalidOperationException(
$"KHAEMHAT_LOG_LEVEL '{level}' is not valid: use Trace, Debug, Information, Warning, Error, Critical or None.");
}
builder.Configuration["Logging:LogLevel:Default"] = parsed.ToString();
builder.Configuration["Logging:LogLevel:Default"] = level.ToString();
}
}
// POST /logout: closes the session and removes the cookie; a form with the antiforgery token posts here.
private static void MapSignOut(this IEndpointRouteBuilder endpoints) =>
endpoints.MapPost("/logout", async (HttpContext context, SignInService signIn, IAntiforgery antiforgery) =>
{
if (!await antiforgery.IsRequestValidAsync(context).ConfigureAwait(false))
{
return Results.BadRequest();
}
await signIn.SignOutAsync(SessionCookie.Read(context), context.RequestAborted).ConfigureAwait(false);
SessionCookie.Clear(context);
return Results.Redirect("/login");
});
}