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
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:
1 parent
4582837b70
commit
032c602b49
107 files changed
+12202
-116
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user