Files
Anubis/src/Anubis.Server/ServerApp.cs
T
Alby96andClaude Opus 5.5 e9ac6dccc9 Phase 10: new course and Docker only
Record the course the user chose on 2 December 2026 and make the
container the only form of Anubis.

- ADR 0021-0026: new roadmap (phases 10-24, readings per phase, the
  spec-to-ADR table, merge and tag only after the user's yes),
  Docker only, maths-only decisions, bans turned into limits on margin
  accounts, eToro Demo as currency venue and forward tests, strategy
  championship. ROADMAP rewritten from phase 10; STATE, CLAUDE.md,
  SVILUPPO, README, API-NOTES and the manuals without the desktop.
- Remove the desktop: Anubis.Desktop, Anubis.Setup, deploy/windows,
  release-win and desktop-win, config.toml, PlatformKind,
  ANUBIS_PLATFORM, DPAPI with the ProtectedData package and the
  first-run wizard. Outside a container the server needs --data-dir,
  listens on 127.0.0.1 only and refuses foreign hosts; server and guard
  refuse --platform desktop with an Italian message and exit code 2.
  The demo keeps its key in a file and its error-page choices need no
  startup password. The diagnostics report says where the server runs
  from its own environment.
- Lighter image: restore and publish for linux-x64 only, and leave out
  the Windows libraries ONNX Runtime copies anyway (829 MB to 410 MB on
  disk, /app from 282 MB to 42 MB). Rotating Docker logs in the Unraid
  template, the manual and the compose; backtest and learning run as
  one-shot commands. tasks dev uses artifacts/dev-data.

refs #113 #114 #115 #78 #80 #81

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

260 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)))
{
// 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<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));
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, outside a container it answers only the computer itself.
private static Task LocalOnly(HttpContext context, Func<Task> 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<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 (the error page): 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))
{
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);
}
}