using System.Collections; using Anubis.Access; using Anubis.Core; using Anubis.Demo; using Anubis.Platform; using Anubis.Server.Components; using Anubis.Supervision; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.DataProtection; namespace Anubis.Server; /// Builds the web application. Kept apart from Program so tests can host it. internal static class ServerApp { public static WebApplication Build(string[] args, ServerOverrides? overrides = null) { var environment = overrides?.Environment ?? ReadEnvironment(); var options = ServerOptions.Parse(args, environment); IClock clock = overrides?.Clock ?? (options.Demo ? new ManualClock(DemoMode.Now) : new Anubis.Core.SystemClock()); // Demo mode never reads the configured database: it gets a brand-new folder of its own (trap 27). var config = options.Demo ? DemoMode.Config(DemoMode.CreateFolder(new Anubis.Core.SystemClock())) : options.LoadConfig(environment); RegisterSecrets(config); var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = options.AspNetArgs, ApplicationName = typeof(ServerApp).Assembly.GetName().Name, ContentRootPath = AppContext.BaseDirectory, }); if (!options.AspNetArgs.Any(a => a.StartsWith("--urls", StringComparison.Ordinal))) { // Outside a container (development, tests, demo) only the computer itself; the container on every interface (ADR 0022). builder.WebHost.UseUrls((options.LocalOnly ? "http://127.0.0.1:" : "http://0.0.0.0:") + config.Port.ToString(System.Globalization.CultureInfo.InvariantCulture)); } builder.WebHost.ConfigureKestrel(k => { // No form of Anubis is larger than a few kilobytes; nothing is uploaded. k.Limits.MaxRequestBodySize = 1024 * 1024; k.AddServerHeader = false; }); builder.Logging.ClearProviders(); // Created by the container so it is disposed with the application and releases the log file. builder.Services.AddSingleton(_ => new JsonLogProvider(config.Data.Logs, clock, console: true)); builder.Logging.SetMinimumLevel(LogLevel.Information); builder.Logging.AddFilter("Microsoft", LogLevel.Warning); builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Information); // The form-token keys sit unencrypted in the data folder, which only the app's user can read (ADR 0007). builder.Logging.AddFilter("Microsoft.AspNetCore.DataProtection", LogLevel.Error); var services = builder.Services; services.AddSingleton(options); services.AddSingleton(config); services.AddSingleton(environment); services.AddSingleton(clock); services.AddSingleton(overrides ?? new ServerOverrides()); services.AddSingleton(); // Started by the guard (SPEC 9.3): the channel to it. Never in demo mode, which protects nothing. services.AddSingleton(sp => new AnubisHost(options, config, environment, clock, sp.GetRequiredService(), sp.GetRequiredService>(), overrides) { Guard = options.Demo ? null : GuardLink.FromEnvironment(environment, sp.GetRequiredService>()), }); services.AddHostedService(sp => sp.GetRequiredService()); services.AddSingleton(new LoginLimiter(clock)); services.AddSingleton(); services.AddSingleton(); services.AddAuthentication(SessionAuthentication.SchemeName) .AddScheme(SessionAuthentication.SchemeName, null); // What a new page or route forgets to say stays closed: only those marked anonymous answer without a session. services.AddAuthorization(o => o.FallbackPolicy = o.DefaultPolicy); services.AddAntiforgery(o => { o.Cookie.Name = "anubis_csrf"; o.Cookie.SameSite = SameSiteMode.Strict; o.Cookie.HttpOnly = true; o.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; o.HeaderName = Endpoints.CsrfHeader; o.FormFieldName = "__csrf"; }); // The keys behind the form tokens live in the data folder, so a restart or a new container keeps open pages working // (otherwise ASP.NET would use a home folder that in Docker belongs to root, or keys lost at every start). services.AddDataProtection() .SetApplicationName("Anubis") .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(config.Data.Root, "web-keys"))); services.AddRazorComponents(); // Pages in Italian stay readable: letters with accents and the euro sign are written as they are. services.AddSingleton(System.Text.Encodings.Web.HtmlEncoder.Create(System.Text.Unicode.UnicodeRanges.All)); var app = builder.Build(); var host = app.Services.GetRequiredService(); if (host.Guard is { } guard) { // The guard asks for an orderly stop when the container stops; every stop of the engine is announced to it. guard.StopRequested = app.Lifetime.StopApplication; app.Lifetime.ApplicationStopping.Register(() => guard.AnnounceAsync("uscita").GetAwaiter().GetResult()); app.Lifetime.ApplicationStopped.Register(() => guard.DisposeAsync().AsTask().GetAwaiter().GetResult()); } app.Use(SecurityHeaders); app.Use((context, next) => LocalOnly(context, next, options)); app.Use((context, next) => Gate.InvokeAsync(context, next, host)); app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(20) }); app.UseRouting(); app.UseAuthentication(); app.Use(MustChangePassword); app.UseAuthorization(); app.UseAntiforgery(); Endpoints.Map(app); app.MapRazorComponents().RequireAuthorization(); return app; } private static Dictionary ReadEnvironment() { var result = new Dictionary(StringComparer.Ordinal); foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) { result[(string)entry.Key] = entry.Value as string; } return result; } // Every secret the startup configuration knows is masked in logs and messages from the first line on. private static void RegisterSecrets(StartupConfig config) { Redactor.Register(config.Db?.Password); Redactor.Register(config.Db?.UrlPassword); Redactor.Register(config.HeartbeatUrl); Redactor.Register(config.AdminPassword); foreach (var value in config.EnvironmentKeys.Values) { Redactor.Register(value); } } private static Task SecurityHeaders(HttpContext context, Func next) { var headers = context.Response.Headers; headers.XContentTypeOptions = "nosniff"; headers.XFrameOptions = "DENY"; headers["Referrer-Policy"] = "same-origin"; headers.ContentSecurityPolicy = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; " + "font-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'"; headers["Cross-Origin-Opener-Policy"] = "same-origin"; headers["Permissions-Policy"] = "camera=(), geolocation=(), microphone=(), payment=(), usb=()"; if (!Gate.IsAlwaysOpen(context.Request.Path)) { // Accounts, trades, registers: nothing stays in the browser or in a proxy. headers.CacheControl = "no-cache, no-store"; } return next(); } // Defence in depth: even if someone binds the server to every address, outside a container it answers only the computer itself. private static Task LocalOnly(HttpContext context, Func next, ServerOptions options) { if (options.LocalOnly && !CurrentUser.IsLocal(context)) { context.Response.StatusCode = StatusCodes.Status403Forbidden; return context.Response.WriteAsync("Fuori dal container Anubis risponde solo da questo computer (sviluppo, prove, modalità dimostrativa)."); } return next(); } // Docker: the initial password works once, then the interface asks for a new one before anything else (SPEC 13.1). private static Task MustChangePassword(HttpContext context, Func next) { if (context.User.Identity?.IsAuthenticated != true || !CurrentUser.MustChangePassword(context.User)) { return next(); } var path = context.Request.Path; if (path.StartsWithSegments("/primo-accesso", StringComparison.Ordinal) || path.StartsWithSegments("/azioni/primo-accesso", StringComparison.Ordinal) || path.StartsWithSegments("/azioni/esci", StringComparison.Ordinal) || Gate.IsAlwaysOpen(path)) { return next(); } if (SessionAuthentication.IsApi(context.Request)) { context.Response.StatusCode = StatusCodes.Status403Forbidden; return context.Response.WriteAsJsonAsync(new ApiError("password_da_cambiare", "Scegli una nuova password prima di continuare.")); } context.Response.Redirect("/primo-accesso"); return Task.CompletedTask; } } /// /// While the application is not ready, every page is the service page (the error page): the engine does not start /// and no other database is ever opened (SPEC 15.1). Health, logo and style always answer. /// internal static class Gate { public static bool IsAlwaysOpen(PathString path) => path.StartsWithSegments("/health", StringComparison.Ordinal) || path.StartsWithSegments("/assets", StringComparison.Ordinal) || path.StartsWithSegments("/brand", StringComparison.Ordinal) || path == "/favicon.ico"; public static async Task InvokeAsync(HttpContext context, Func next, AnubisHost host) { var path = context.Request.Path; var mode = host.Status.Mode; if (IsAlwaysOpen(path)) { await next().ConfigureAwait(false); return; } if (mode == HostMode.Ready) { if (path.StartsWithSegments("/servizio", StringComparison.Ordinal)) { context.Response.Redirect("/"); return; } await next().ConfigureAwait(false); return; } var api = SessionAuthentication.IsApi(context.Request); if (path.StartsWithSegments("/azioni/servizio", StringComparison.Ordinal)) { await next().ConfigureAwait(false); return; } if (api) { context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; await context.Response.WriteAsJsonAsync(new ApiError("non_pronto", ServiceText.Title(mode))).ConfigureAwait(false); return; } if (!HttpMethods.IsGet(context.Request.Method) && !HttpMethods.IsHead(context.Request.Method)) { context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; await context.Response.WriteAsync(ServiceText.Title(mode)).ConfigureAwait(false); return; } // The service page answers in place of whatever was asked, with 503 so nothing caches it. context.Request.Path = "/servizio"; await next().ConfigureAwait(false); } }