Files
Khaemhat/src/Khaemhat.Web/Hosting/Middleware.cs
T
Alby96andClaude Opus 5.5 8198e0a754 feat: attachments panel, file previews, print preview and history (#34)
Documents need to show, upload and generate their files from the interface,
and users need to see who changed a record. This adds the attachment list
(upload, preview, download, lock, trash and restore, older versions, ZIP,
generate/regenerate), in-app previews for PDF, images, XML, text, CSV and
XLSX, an A4 print preview with "save as attachment", and an audit history
list read through a permission-checked AuditTrailService.

Files are served by /files endpoints that require a signed-in user and the
company permissions; only PDF and images open inline, with their own CSP
that allows framing by this site only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:59:37 +01:00

193 lines
9.6 KiB
C#

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(() =>
{
// 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);
});
/// <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-unavailable\"><section>" +
"<img class=\"mark\" src=\"/icon.svg\" alt=\"\" width=\"96\" height=\"96\"><h1>Khaemhat</h1><p>" + WebUtility.HtmlEncode(message) +
"</p></section></main></body></html>",
context.RequestAborted);
}
}