using Khaemhat.Application.Configuration;
using Khaemhat.Application.Instance;
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;
///
/// Builds the Khaemhat web host: one process per instance (ADR 0001), Blazor Interactive Server (ADR 0003).
/// Kept apart from Program.cs so tests can start the real host on a free port.
///
public static class KhaemhatApp
{
/// Creates the configured application, ready to run.
/// Command-line arguments (ASP.NET Core host conventions, e.g. --urls; also --KHAEMHAT_*=value).
/// The application.
/// The KHAEMHAT_* variables are missing or not valid.
public static WebApplication Build(string[] args)
{
// ApplicationName pins the static web assets manifest to this assembly, also when tests host the app.
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
ApplicationName = typeof(KhaemhatApp).Assembly.GetName().Name,
});
// 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 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();
builder.Logging.AddJsonConsole(o =>
{
o.IncludeScopes = true;
o.UseUtcTimestamp = true;
o.TimestampFormat = "yyyy-MM-ddTHH:mm:ss.fffZ";
});
}
builder.Logging.AddProvider(new DbLoggerProvider(logSink));
builder.Logging.AddFilter("Microsoft", LogLevel.Warning);
builder.Logging.AddFilter("System", LogLevel.Warning);
builder.Logging.AddFilter(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>(sp => new ConfigureOptions(o =>
{
o.XmlRepository = new DataProtectionKeyStore(sp.GetRequiredService());
o.XmlEncryptor = new SecretKeyXmlEncryptor(sp.GetRequiredService());
}));
// Sign-in with the session cookie (SPEC §7.3) and policies for permissions, levels and modules.
builder.Services.AddAuthentication(SessionCookie.Scheme)
.AddScheme(SessionCookie.Scheme, null);
builder.Services.AddAuthorization();
builder.Services.AddSingleton();
builder.Services.AddSingleton();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped();
builder.Services.AddSingleton(ProductVersion.FromAssembly(typeof(KhaemhatApp).Assembly));
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
var app = builder.Build();
// TLS ends at the reverse proxy in front of the container (docs/DEPLOY.md): no HTTPS redirection here.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
}
app.UseSecurityHeaders();
// Numbers, dates and texts in Italian (SPEC §10.8); a circuit keeps the culture of the request that opened it.
app.UseRequestLocalization(new RequestLocalizationOptions()
.SetDefaultCulture(KhaemhatServices.ItalianCulture.Name)
.AddSupportedCultures(KhaemhatServices.ItalianCulture.Name)
.AddSupportedUICultures(KhaemhatServices.ItalianCulture.Name));
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.MapHealthEndpoints();
app.UseStartingPage();
app.UseAuthentication();
app.UseLogScope();
app.UseCompanyAvailability();
app.UseLoginRateLimit();
app.UseAuthorization();
app.UseAntiforgery();
app.MapStaticAssets();
app.MapSignOut();
app.MapCompanySwitch();
app.MapRazorComponents()
.AddInteractiveServerRenderMode();
return app;
}
// 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.
if (!string.IsNullOrWhiteSpace(options.Urls) && !args.Any(a => a.StartsWith("--urls", StringComparison.Ordinal)))
{
builder.WebHost.UseUrls(options.Urls);
}
if (!string.IsNullOrWhiteSpace(options.LogLevel) && Enum.TryParse(options.LogLevel, ignoreCase: true, out var level))
{
builder.Configuration["Logging:LogLevel:Default"] = level.ToString();
}
}
// POST /session/company: an instance account chooses the company of its session (top bar, SPEC §10.2). The page
// is reloaded, so the new circuit starts in the new company.
private static void MapCompanySwitch(this IEndpointRouteBuilder endpoints) =>
endpoints.MapPost("/session/company", async (HttpContext context, SessionStore sessions, CompanyContextResolver companies, IAntiforgery antiforgery) =>
{
if (!await antiforgery.IsRequestValidAsync(context).ConfigureAwait(false))
{
return Results.BadRequest();
}
var actor = SessionCookie.ActorOf(context.User);
var cookie = SessionCookie.Read(context);
var form = await context.Request.ReadFormAsync(context.RequestAborted).ConfigureAwait(false);
var code = form["code"].ToString();
if (actor is not { IsInstanceAccount: true } || cookie is null || string.IsNullOrWhiteSpace(code))
{
return Results.Forbid();
}
var result = await companies.ResolveAsync(actor, code, context.RequestAborted).ConfigureAwait(false);
if (result.Access != CompanyAccess.Granted || result.Company is null)
{
return Results.Redirect("/");
}
await sessions.SetCompanyAsync(cookie, result.Company.Code, context.RequestAborted).ConfigureAwait(false);
return Results.Redirect("/");
});
// 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");
});
}