Files
Anubis/src/Anubis.Server/ServerApp.cs
T
Alby96andClaude Opus 5.5 4d92a39fef Close what the security review found
A session alone could change the password, switch the second factor on or
off, send the key of the language model to another address and remove the
rules that stop purchases. Each now needs the password and the code, with
one limit on wrong attempts that a restart of the services does not clear,
and the other sessions end when the password or the factor changes.

Requests to the brokers pass a list of allowed calls, never follow a
redirect with a key and are signed by one client only. Pages are closed by
default, nothing is cached, requests are limited to 1 MB, secrets are
masked in logs and notifications, exported tables cannot run as formulas,
archives carry no sessions and the container refuses to run as root.

refs #68

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

276 lines
12 KiB
C#

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;
/// <summary>Builds the web application. Kept apart from Program so tests can host it.</summary>
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)))
{
// Desktop and demo listen only on the computer itself unless the user allowed the home network (SPEC 15.6).
var local = options.Demo || (config.Platform == PlatformKind.Desktop && !config.AllowNetwork);
builder.WebHost.UseUrls((local ? "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<ILoggerProvider>(_ => 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<EventBus>();
// 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<EventBus>(),
sp.GetRequiredService<ILogger<AnubisHost>>(), overrides)
{
Guard = options.Demo ? null : GuardLink.FromEnvironment(environment, sp.GetRequiredService<ILogger<GuardLink>>()),
});
services.AddHostedService(sp => sp.GetRequiredService<AnubisHost>());
services.AddSingleton(new LoginLimiter(clock));
services.AddSingleton<ShellData>();
services.AddSingleton<SecondFactorDrafts>();
services.AddAuthentication(SessionAuthentication.SchemeName)
.AddScheme<AuthenticationSchemeOptions, SessionAuthentication>(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<AnubisHost>();
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, config));
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<App>().RequireAuthorization();
return app;
}
private static Dictionary<string, string?> ReadEnvironment()
{
var result = new Dictionary<string, string?>(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<Task> 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, desktop and demo answer only the computer itself.
private static Task LocalOnly(HttpContext context, Func<Task> next, ServerOptions options, StartupConfig config)
{
var localOnly = options.Demo || (config.Platform == PlatformKind.Desktop && !config.AllowNetwork);
if (localOnly && !CurrentUser.IsLocal(context))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return context.Response.WriteAsync("Anubis risponde solo dal computer su cui gira.");
}
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<Task> 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;
}
}
/// <summary>
/// While the application is not ready, every page is the service page (error, first run): the engine does not start
/// and no other database is ever opened (SPEC 15.1). Health, logo and style always answer.
/// </summary>
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<Task> 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) || path.StartsWithSegments("/primo-avvio", StringComparison.Ordinal))
{
context.Response.Redirect("/");
return;
}
await next().ConfigureAwait(false);
return;
}
var api = SessionAuthentication.IsApi(context.Request);
if (mode == HostMode.FirstRun)
{
if (path.StartsWithSegments("/primo-avvio", StringComparison.Ordinal) || path.StartsWithSegments("/azioni/primo-avvio", StringComparison.Ordinal))
{
await next().ConfigureAwait(false);
return;
}
if (!api && HttpMethods.IsGet(context.Request.Method))
{
context.Response.Redirect("/primo-avvio");
return;
}
}
else 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);
}
}