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

@@ -0,0 +1,81 @@
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Instance;
using Khaemhat.Data.Migrations;
using Khaemhat.Infrastructure.Logging;
namespace Khaemhat.Web.Hosting;
/// <summary>
/// Runs the start sequence in the background, so that <c>/health/live</c> answers at once and <c>/health/ready</c>
/// answers 503 until the databases are migrated. A failure stops the process with exit code 1: the container restart
/// policy retries, and the log says why.
/// </summary>
/// <param name="orchestrator">The start sequence.</param>
/// <param name="state">The start state.</param>
/// <param name="logSink">The database log, flushed at shutdown.</param>
/// <param name="lifetime">Stops the host on failure.</param>
/// <param name="logger">The log.</param>
internal sealed partial class BootstrapService(
StartupOrchestrator orchestrator, BootstrapState state, DbLogSink logSink, IHostApplicationLifetime lifetime, ILogger<BootstrapService> logger)
: BackgroundService
{
/// <summary>
/// Migrates the system database before the host serves anything (this service is registered before DataProtection,
/// whose key ring lives there), then lets the rest of the sequence run in the background. A failure here stops the
/// start: without the system database nothing can work.
/// </summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public override async Task StartAsync(CancellationToken cancellationToken)
{
try
{
await orchestrator.PrepareSystemDatabaseAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
state.MarkFailed(Describe(ex));
LogStartFailed(logger, ex, Describe(ex));
throw;
}
await base.StartAsync(cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken).ConfigureAwait(false);
await logSink.DisposeAsync().ConfigureAwait(false);
}
/// <inheritdoc />
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await orchestrator.RunAsync(stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
}
catch (Exception ex)
{
var reason = Describe(ex);
state.MarkFailed(reason);
LogStartFailed(logger, ex, reason);
Environment.ExitCode = 1;
lifetime.StopApplication();
}
}
private static string Describe(Exception ex) => ex switch
{
ConfigurationException config => string.Join(" ", config.Errors),
MigrationException migration => migration.Message,
_ => ex.GetType().Name + ": " + ex.Message,
};
[LoggerMessage(Level = LogLevel.Critical, Message = "Khaemhat cannot start: {Reason}")]
private static partial void LogStartFailed(ILogger logger, Exception exception, string reason);
}
+15 -9
View File
@@ -1,3 +1,4 @@
using Khaemhat.Application.Instance;
using Khaemhat.Core.Common;
namespace Khaemhat.Web.Hosting;
@@ -5,13 +6,14 @@ namespace Khaemhat.Web.Hosting;
/// <summary>
/// Health endpoints for Docker and reverse proxies (SPEC §16.1, ADR 0012):
/// <c>/health/live</c> says the process answers (the image HEALTHCHECK), <c>/health/ready</c> says it can serve
/// requests (from M1 it also checks the system database), <c>/health</c> summarises both with the version.
/// requests (the start sequence completed: databases migrated), <c>/health</c> summarises both with the version.
/// They carry no personal or configuration data and need no authentication.
/// </summary>
public static class HealthEndpoints
{
/// <summary>Maps the three health endpoints.</summary>
/// <param name="endpoints">The application's route builder.</param>
/// <returns>The route builder.</returns>
public static IEndpointRouteBuilder MapHealthEndpoints(this IEndpointRouteBuilder endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
@@ -19,22 +21,26 @@ public static class HealthEndpoints
endpoints.MapGet("/health/live", () => Results.Text("live", "text/plain"))
.ExcludeFromDescription();
endpoints.MapGet("/health/ready", () => Results.Text("ready", "text/plain"))
endpoints.MapGet("/health/ready", (BootstrapState state) => state.IsReady
? Results.Text("ready", "text/plain")
: Results.Text(state.Phase == BootstrapPhase.Failed ? "failed" : "starting", "text/plain", statusCode: StatusCodes.Status503ServiceUnavailable))
.ExcludeFromDescription();
endpoints.MapGet("/health", (ProductVersion version) => Results.Json(new HealthReport(
Status: "ok",
Live: true,
Ready: true,
Version: version.Version,
Revision: version.Revision)))
endpoints.MapGet("/health", (ProductVersion version, BootstrapState state) => Results.Json(
new HealthReport(
Status: state.IsReady ? "ok" : state.Phase == BootstrapPhase.Failed ? "failed" : "starting",
Live: true,
Ready: state.IsReady,
Version: version.Version,
Revision: version.Revision),
statusCode: state.IsReady ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable))
.ExcludeFromDescription();
return endpoints;
}
/// <summary>The body of <c>/health</c>.</summary>
/// <param name="Status"><c>ok</c> when the instance is live and ready.</param>
/// <param name="Status"><c>ok</c> when the instance is live and ready, <c>starting</c> or <c>failed</c> otherwise.</param>
/// <param name="Live">Whether the process answers.</param>
/// <param name="Ready">Whether the instance can serve requests.</param>
/// <param name="Version">Product version (SemVer).</param>
+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");
});
}
@@ -0,0 +1,141 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Notifications;
using Khaemhat.Application.Security;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Execution;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Migrations;
using Khaemhat.Data.PostgreSql;
using Khaemhat.Data.Sqlite;
using Khaemhat.Infrastructure.Caching;
using Khaemhat.Infrastructure.Licensing;
using Khaemhat.Infrastructure.Logging;
using Khaemhat.Infrastructure.Security;
using Khaemhat.Web.Security;
namespace Khaemhat.Web.Hosting;
/// <summary>
/// The composition of the instance (SPEC §3): data access on the configured databases, security, licences, log and
/// the start sequence. Services are singletons: they hold no per-request state and open a unit of work per call.
/// </summary>
internal static class KhaemhatServices
{
/// <summary>Registers every service of the instance.</summary>
/// <param name="services">The container.</param>
/// <param name="options">The validated variables.</param>
/// <param name="logSink">The database log queue, already plugged into the logging pipeline.</param>
/// <returns>The container.</returns>
public static IServiceCollection AddKhaemhat(this IServiceCollection services, KhaemhatOptions options, DbLogSink logSink)
{
var dataAssembly = typeof(CompanyRegistry).Assembly;
services.AddSingleton(options);
services.AddSingleton(logSink);
services.AddSingleton(TimeProvider.System);
services.AddSingleton<BootstrapState>();
services.AddHttpContextAccessor();
services.AddSingleton<CurrentUserName>();
// Secrets and data access.
services.AddSingleton(SecretKey.FromBase64(options.SecretKey!));
services.AddSingleton<SecretProtector>();
services.AddSingleton<ISecretProtector>(sp => sp.GetRequiredService<SecretProtector>());
services.AddSingleton(new DbProviderCatalog(new SqliteProvider(), new PostgresProvider()));
services.AddSingleton(new MapRegistry().AddFromAssembly(dataAssembly));
services.AddSingleton(sp =>
{
var slow = sp.GetRequiredService<ILoggerFactory>().CreateLogger("Khaemhat.Performance.SlowQueries");
var user = sp.GetRequiredService<CurrentUserName>();
return new DataAccessContext(sp.GetRequiredService<TimeProvider>(), user.Get)
{
SlowQueryObserver = query =>
{
using var section = slow.BeginScope(LogSections.Scope(LogSection.Performance));
slow.LogWarning(
"Slow query on {Database}: {Milliseconds} ms. {Sql}",
query.Database, (long)query.Duration.TotalMilliseconds, query.Sql.Length > 2000 ? query.Sql[..2000] : query.Sql);
},
};
});
services.AddSingleton(sp => sp.GetRequiredService<DbProviderCatalog>().Resolve(options.SystemDatabase));
services.AddSingleton<ICompanyRegistry>(sp => new CompanyRegistry(
sp.GetRequiredService<DatabaseTarget>(), sp.GetRequiredService<DbProviderCatalog>(), sp.GetRequiredService<ISecretProtector>(),
sp.GetRequiredService<MapRegistry>(), sp.GetRequiredService<DataAccessContext>()));
services.AddSingleton<IDatabaseLocator>(sp => new DatabaseLocator(sp.GetRequiredService<DatabaseTarget>(), sp.GetRequiredService<ICompanyRegistry>()));
services.AddSingleton<IUnitOfWorkFactory, UnitOfWorkFactory>();
services.AddSingleton<MigrationRunner>();
services.AddSingleton(new InstanceDatabases(
options.SystemDatabase, options.CompanyServer, MigrationCatalog.ForSystem(dataAssembly), MigrationCatalog.ForCompany(dataAssembly)));
// Cache: in memory, or on Redis when KHAEMHAT_REDIS is set (falling back to memory while Redis is down).
if (options.Redis is { } redis)
{
services.AddSingleton(new RedisClient(RedisEndpoint.Parse(redis)));
services.AddSingleton<ICacheProvider>(sp => new RedisCacheProvider(
sp.GetRequiredService<RedisClient>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<RedisCacheProvider>>()));
}
else
{
services.AddSingleton<ICacheProvider>(sp => new MemoryCacheProvider(sp.GetRequiredService<TimeProvider>()));
}
// Security.
services.AddSingleton(new SecurityPolicyOptions());
services.AddSingleton<PasswordPolicy>();
services.AddSingleton<AccountSecurity>();
services.AddSingleton<ISecurityAuditLog, SecurityAuditLog>();
services.AddSingleton<SystemSettingsStore>();
services.AddSingleton(ModuleRegistry.Default);
services.AddSingleton(LicenseVerifier.Product);
services.AddSingleton(new LicenseSettings(options.License, options.Mode));
services.AddSingleton<LicenseGate>();
services.AddSingleton<ILicenseGate>(sp => sp.GetRequiredService<LicenseGate>());
services.AddSingleton<ILicenseActivationService, OfflineActivationService>();
services.AddSingleton<PermissionService>();
services.AddSingleton<RoleService>();
services.AddSingleton<SystemUserService>();
services.AddSingleton<UserService>();
services.AddSingleton<SessionStore>();
services.AddSingleton<NotificationDispatcher>();
services.AddSingleton<SignInService>();
// Companies and start.
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
services.AddSingleton(sp => new StartupOrchestrator(
sp.GetRequiredService<InstanceDatabases>(), sp.GetRequiredService<DbProviderCatalog>(), sp.GetRequiredService<MigrationRunner>(),
sp.GetRequiredService<SystemSettingsStore>(), sp.GetRequiredService<RoleService>(), sp.GetRequiredService<ILicenseGate>(),
sp.GetRequiredService<SystemUserService>(), sp.GetRequiredService<CompanyService>(), options, sp.GetRequiredService<IUnitOfWorkFactory>(),
logSink, sp.GetRequiredService<BootstrapState>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<StartupOrchestrator>>()));
services.AddHostedService<BootstrapService>();
// History of the records and scheduled tasks.
services.AddSingleton<AuditTrail>();
services.AddSingleton<IScheduledJob, SessionCleanupJob>();
services.AddSingleton<IScheduledJob, LicenseCheckJob>();
services.AddSingleton<IScheduledJob, LogRetentionJob>();
services.AddSingleton<JobScheduler>();
services.AddHostedService<JobSchedulerService>();
return services;
}
}
/// <summary>The user name written in the audit columns: the signed-in user of the current request, else <c>system</c>.</summary>
/// <param name="accessor">The current request.</param>
internal sealed class CurrentUserName(IHttpContextAccessor accessor)
{
/// <summary>The name.</summary>
/// <returns>The user name, or <see langword="null"/> outside requests.</returns>
public string? Get() => accessor.HttpContext?.User.Identity is { IsAuthenticated: true, Name: { } name } ? name : null;
}
+186
View File
@@ -0,0 +1,186 @@
using System.Diagnostics;
using System.Net;
using System.Threading.RateLimiting;
using Khaemhat.Application.Instance;
using Khaemhat.Core.Logging;
using Khaemhat.Web.Security;
namespace Khaemhat.Web.Hosting;
/// <summary>The middleware of the instance, in pipeline order.</summary>
internal static class KhaemhatMiddleware
{
/// <summary>
/// Security headers on every response (SPEC §7.3): a content security policy without inline scripts, no framing,
/// no MIME sniffing, no referrer outside the site.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app) => app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
var headers = context.Response.Headers;
headers.ContentSecurityPolicy =
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; " +
"connect-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; object-src 'none'";
headers.XContentTypeOptions = "nosniff";
headers.XFrameOptions = "DENY";
headers["Referrer-Policy"] = "same-origin";
headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=(), payment=()";
headers["Cross-Origin-Opener-Policy"] = "same-origin";
return Task.CompletedTask;
});
await next(context).ConfigureAwait(false);
});
/// <summary>
/// While the start sequence runs (migrations), every request except health checks and static files gets a 503 page
/// that refreshes itself.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseStartingPage(this IApplicationBuilder app) => app.Use(async (context, next) =>
{
var state = context.RequestServices.GetRequiredService<BootstrapState>();
var path = context.Request.Path;
if (state.IsReady || path.StartsWithSegments("/health") || Path.HasExtension(path.Value) || path.StartsWithSegments("/_framework"))
{
await next(context).ConfigureAwait(false);
return;
}
var message = state.Phase == BootstrapPhase.Failed
? "Avvio non riuscito: controlla il log del container."
: "Avvio in corso: aggiornamento dei database. La pagina si ricarica da sola.";
await WriteUnavailablePageAsync(context, message, refreshSeconds: 5).ConfigureAwait(false);
});
/// <summary>
/// Company states (SPEC §5.4): a company in maintenance answers 503 to company accounts (the API with a JSON body,
/// pages with a notice), a disabled company to everybody; an API call whose <c>X-Company</c> names another company
/// than the account's own gets 403. Sign-in, health checks and static files are never blocked.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseCompanyAvailability(this IApplicationBuilder app) => app.Use(async (context, next) =>
{
var path = context.Request.Path;
var actor = SessionCookie.ActorOf(context.User);
if (actor is null || Path.HasExtension(path.Value) || path.StartsWithSegments("/_framework") || path.StartsWithSegments("/_blazor")
|| path.StartsWithSegments("/health") || path.StartsWithSegments("/login") || path.StartsWithSegments("/logout"))
{
await next(context).ConfigureAwait(false);
return;
}
var isApi = path.StartsWithSegments("/api");
var resolver = context.RequestServices.GetRequiredService<CompanyContextResolver>();
var requested = isApi ? context.Request.Headers[CompanyContextResolver.Header].ToString() : null;
var result = await resolver.ResolveAsync(actor, requested, context.RequestAborted).ConfigureAwait(false);
var refused = isApi && result.Access is CompanyAccess.Forbidden or CompanyAccess.NotFound;
if (!result.IsUnavailable && !refused)
{
await next(context).ConfigureAwait(false);
return;
}
if (isApi)
{
context.Response.StatusCode = result.IsUnavailable ? StatusCodes.Status503ServiceUnavailable
: result.Access == CompanyAccess.Forbidden ? StatusCodes.Status403Forbidden : StatusCodes.Status404NotFound;
if (result.IsUnavailable)
{
context.Response.Headers.RetryAfter = "60";
}
await context.Response.WriteAsJsonAsync(new { error = ErrorCode(result.Access) }, context.RequestAborted).ConfigureAwait(false);
return;
}
var message = result.Access == CompanyAccess.Maintenance
? "L'azienda è in manutenzione. Riprova tra qualche minuto."
: "L'azienda è disattivata. Rivolgiti all'amministratore.";
await WriteUnavailablePageAsync(context, message, refreshSeconds: result.Access == CompanyAccess.Maintenance ? 60 : null).ConfigureAwait(false);
});
/// <summary>
/// Puts trace identifier, request, user and company in the logging scope of the request (SPEC §9.5: one trace
/// identifier follows the request across the log) and returns the identifier in <c>X-Trace-Id</c>.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseLogScope(this IApplicationBuilder app) => app.Use(async (context, next) =>
{
var traceId = Activity.Current?.TraceId.ToString() ?? context.TraceIdentifier;
context.Response.Headers["X-Trace-Id"] = traceId;
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("Khaemhat.Web.Requests");
var actor = SessionCookie.ActorOf(context.User);
using var scope = logger.BeginScope(new Dictionary<string, object?>
{
[LogSections.TraceIdKey] = traceId,
[LogSections.RequestKey] = context.Request.Method + " " + context.Request.Path,
[LogSections.UserKey] = actor?.UserName,
[LogSections.CompanyKey] = actor?.CompanyCode,
});
await next(context).ConfigureAwait(false);
});
/// <summary>
/// Limits sign-in attempts per client address (SPEC §7.3): 10 posts a minute on the login pages; beyond that 429.
/// Account lockout after 5 wrong passwords is separate and lives in the account.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseLoginRateLimit(this IApplicationBuilder app)
{
var limiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
return app.Use(async (context, next) =>
{
if (HttpMethods.IsPost(context.Request.Method) && context.Request.Path.StartsWithSegments("/login"))
{
using var lease = await limiter.AcquireAsync(context, 1, context.RequestAborted).ConfigureAwait(false);
if (!lease.IsAcquired)
{
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
context.Response.Headers.RetryAfter = "60";
await context.Response.WriteAsync("Troppi tentativi di accesso: riprova tra un minuto.", context.RequestAborted).ConfigureAwait(false);
return;
}
}
await next(context).ConfigureAwait(false);
});
}
private static string ErrorCode(CompanyAccess access) => access switch
{
CompanyAccess.Maintenance => "company_maintenance",
CompanyAccess.Disabled => "company_disabled",
CompanyAccess.Forbidden => "company_forbidden",
_ => "company_not_found",
};
private static Task WriteUnavailablePageAsync(HttpContext context, string message, int? refreshSeconds)
{
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
context.Response.ContentType = "text/html; charset=utf-8";
var refresh = string.Empty;
if (refreshSeconds is { } seconds)
{
var text = seconds.ToString(System.Globalization.CultureInfo.InvariantCulture);
context.Response.Headers.RetryAfter = text;
refresh = "<meta http-equiv=\"refresh\" content=\"" + text + "\">";
}
return context.Response.WriteAsync(
"<!DOCTYPE html><html lang=\"it\"><head><meta charset=\"utf-8\">" + refresh +
"<title>Khaemhat</title><link rel=\"stylesheet\" href=\"/app.css\"></head><body><main class=\"kh-construction\"><section class=\"hero\">" +
"<img class=\"mark\" src=\"/icon.svg\" alt=\"\" width=\"96\" height=\"96\"><h1>Khaemhat</h1><p class=\"state\">" + WebUtility.HtmlEncode(message) +
"</p></section></main></body></html>",
context.RequestAborted);
}
}