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; /// The middleware of the instance, in pipeline order. internal static class KhaemhatMiddleware { /// /// 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. /// /// The application. /// The application. public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app) => app.Use(async (context, next) => { context.Response.OnStarting(() => { // A file shown in the preview of the attachments sets its own, narrower policy that allows this site only // to frame it (FileEndpoints); every other response gets the default. var headers = context.Response.Headers; if (headers.ContentSecurityPolicy != FileEndpoints.InlinePolicy) { 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.XFrameOptions = "DENY"; } headers.XContentTypeOptions = "nosniff"; 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); }); /// /// While the start sequence runs (migrations), every request except health checks and static files gets a 503 page /// that refreshes itself. /// /// The application. /// The application. public static IApplicationBuilder UseStartingPage(this IApplicationBuilder app) => app.Use(async (context, next) => { var state = context.RequestServices.GetRequiredService(); 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); }); /// /// 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 X-Company names another company /// than the account's own gets 403. Sign-in, health checks and static files are never blocked. /// /// The application. /// The application. 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(); 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); }); /// /// 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 X-Trace-Id. /// /// The application. /// The application. 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().CreateLogger("Khaemhat.Web.Requests"); var actor = SessionCookie.ActorOf(context.User); using var scope = logger.BeginScope(new Dictionary { [LogSections.TraceIdKey] = traceId, [LogSections.RequestKey] = context.Request.Method + " " + context.Request.Path, [LogSections.UserKey] = actor?.UserName, [LogSections.CompanyKey] = actor?.CompanyCode, }); await next(context).ConfigureAwait(false); }); /// /// 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. /// /// The application. /// The application. public static IApplicationBuilder UseLoginRateLimit(this IApplicationBuilder app) { var limiter = PartitionedRateLimiter.Create(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 = ""; } return context.Response.WriteAsync( "" + refresh + "Khaemhat
" + "\"\"

Khaemhat

" + WebUtility.HtmlEncode(message) + "

", context.RequestAborted); } }