feat(server): web server, interface shell, demo mode and Docker image (refs #11 #12 #13 #14 #15 #16 #17)
Phase 1 completed on top of the library foundations: - Server: startup state machine (config, first run, database down, schema, identity, ready) with an error page that retries by itself; the configured database is the only one ever opened, and a vanished SQLite file is never recreated. REST API and status WebSocket; session cookie auth, CSRF on every form and write call; desktop and demo answer only the computer itself. - Interface: static Blazor rendering with plain forms (no interactive runtime), menu, top bar and phone bottom bar as in the mockups, light and dark themes with appendix C tokens and a contrast test, Panoramica, Diario, Rischio, Impostazioni; service pages for sign-in, first access, desktop first run and the database error page with its choices. - Demo mode (tasks seed-demo): appendix F in a database of its own under the temp folder, frozen clock, never touches the configured installation. - Docker: entrypoint gives /data to PUID:PGID and drops root with setpriv, HEALTHCHECK through bash /dev/tcp; proven with SQLite, PostgreSQL, a wrong configuration and a database that goes away and comes back. - tasks screenshots drives the installed Edge/Chrome through DevTools for exact 1440 and 390 pixel shots; anubis db export|import on the command line. Fixes from the independent review: return paths without control characters, Host check against DNS rebinding, attempt limit counted before the check and also on the error-page password, one-use TOTP codes and a code to switch the second factor off, error-page choices serialized with the startup loop, identity checked before migrating, restore restarts with "Ferma tutto" on, damaged archives reported instead of crashing. Running the server tests on PostgreSQL exposed pages rendered before their data arrived; data-loading components now load first (LoadedComponent). Decisions in ADR 0007. Tests: 100 on SQLite and on PostgreSQL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
53ca01b7c3
commit
f9d71559e8
71 files changed
+5853
-80
No files matched your search
@@ -1,18 +1,245 @@
|
||||
using System.Collections;
|
||||
using Anubis.Access;
|
||||
using Anubis.Core;
|
||||
using Anubis.Demo;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Server.Components;
|
||||
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)
|
||||
public static WebApplication Build(string[] args, ServerOverrides? overrides = null)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var app = builder.Build();
|
||||
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());
|
||||
|
||||
app.MapGet("/health", () => Results.Ok(new HealthResponse("ok", AnubisInfo.Name, AnubisInfo.Version)));
|
||||
// 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.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>();
|
||||
services.AddSingleton(sp => new AnubisHost(options, config, environment, clock, sp.GetRequiredService<EventBus>(),
|
||||
sp.GetRequiredService<ILogger<AnubisHost>>(), overrides));
|
||||
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);
|
||||
services.AddAuthorization();
|
||||
services.AddAntiforgery(o =>
|
||||
{
|
||||
o.Cookie.Name = "anubis_csrf";
|
||||
o.Cookie.SameSite = SameSiteMode.Strict;
|
||||
o.Cookie.HttpOnly = true;
|
||||
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>();
|
||||
|
||||
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.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'";
|
||||
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>Answer of <c>GET /health</c>.</summary>
|
||||
internal sealed record HealthResponse(string Status, string Name, string Version);
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user