Files
Anubis/src/Anubis.Server/SessionAuthentication.cs
T
Alby96andClaude Opus 5.5 f9d71559e8
ci / test (postgres) (push) Successful in 2m22s
ci / test (sqlite) (push) Failing after 2m27s
ci / image (push) Skipped
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>
2026-11-10 12:40:15 +01:00

125 lines
5.4 KiB
C#

using System.Globalization;
using System.Net;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Anubis.Access;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
namespace Anubis.Server;
/// <summary>
/// Sign-in by session cookie (SPEC 15.4): the cookie holds a random token, the database only its hash. HttpOnly,
/// SameSite=Strict, Secure when the request is HTTPS. In demo mode everyone on the computer itself is signed in.
/// </summary>
internal sealed class SessionAuthentication(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
AnubisHost host) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
public const string SchemeName = "anubis";
public const string Cookie = "anubis_session";
public const string SessionClaim = "anubis:session";
public const string MustChangeClaim = "anubis:must_change";
public const string SecondFactorClaim = "anubis:second_factor";
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var services = host.Services;
if (services is null)
{
return AuthenticateResult.NoResult();
}
if (host.IsDemo)
{
var user = await services.Access.GetUserAsync(Context.RequestAborted).ConfigureAwait(false);
return user is null ? AuthenticateResult.NoResult() : Success(user, Guid.Empty);
}
if (!Request.Cookies.TryGetValue(Cookie, out var token) || string.IsNullOrEmpty(token))
{
return AuthenticateResult.NoResult();
}
var session = await services.Access.ValidateAsync(token, Context.RequestAborted).ConfigureAwait(false);
return session is null ? AuthenticateResult.Fail("Sessione scaduta") : Success(session.User, session.Id);
}
private static AuthenticateResult Success(User user, Guid session)
{
Claim[] claims =
[
new(ClaimTypes.NameIdentifier, user.Id.ToString("D")),
new(ClaimTypes.Name, user.Username),
new(SessionClaim, session.ToString("D")),
new(MustChangeClaim, user.MustChangePassword ? "1" : "0"),
new(SecondFactorClaim, user.HasSecondFactor ? "1" : "0"),
];
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, SchemeName));
return AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName));
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
if (IsApi(Request))
{
Response.StatusCode = StatusCodes.Status401Unauthorized;
return Response.WriteAsJsonAsync(new ApiError("non_autenticato", "Accedi di nuovo."));
}
var back = Request.Path + Request.QueryString;
Response.Redirect("/accesso" + (back == "/" ? "" : "?ritorno=" + Uri.EscapeDataString(back)));
return Task.CompletedTask;
}
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.StatusCode = StatusCodes.Status403Forbidden;
return Task.CompletedTask;
}
internal static bool IsApi(HttpRequest request) =>
request.Path.StartsWithSegments("/api", StringComparison.Ordinal) || request.Path.StartsWithSegments("/ws", StringComparison.Ordinal);
public static void WriteCookie(HttpContext context, string token) =>
context.Response.Cookies.Append(Cookie, token, new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Secure = context.Request.IsHttps,
Path = "/",
MaxAge = AccessStore.MaxLifetime,
IsEssential = true,
});
public static void ClearCookie(HttpContext context) =>
context.Response.Cookies.Delete(Cookie, new CookieOptions { Path = "/", HttpOnly = true, SameSite = SameSiteMode.Strict, Secure = context.Request.IsHttps });
}
/// <summary>Who is signed in, read from the claims.</summary>
internal static class CurrentUser
{
public static Guid Id(ClaimsPrincipal user) => Guid.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier)!, CultureInfo.InvariantCulture);
public static Guid Session(ClaimsPrincipal user) => Guid.Parse(user.FindFirstValue(SessionAuthentication.SessionClaim) ?? Guid.Empty.ToString(), CultureInfo.InvariantCulture);
public static bool MustChangePassword(ClaimsPrincipal user) => user.FindFirstValue(SessionAuthentication.MustChangeClaim) == "1";
public static bool HasSecondFactor(ClaimsPrincipal user) => user.FindFirstValue(SessionAuthentication.SecondFactorClaim) == "1";
/// <summary>
/// The request comes from the computer the server runs on, addressed to it by a local name. The name matters too:
/// a web page that points its own name at 127.0.0.1 (DNS rebinding) arrives from the loopback with a foreign Host.
/// </summary>
public static bool IsLocal(HttpContext context) =>
context.Connection.RemoteIpAddress is { } address && IPAddress.IsLoopback(address) && IsLocalName(context.Request.Host.Host);
internal static bool IsLocalName(string host) =>
host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || host is "127.0.0.1" or "[::1]" or "::1";
}
/// <summary>Error body of the API: a code for programs and a sentence for people.</summary>
internal sealed record ApiError(string Code, string Message);