Files
Chronos/src/Titano.Server/Security/AuthenticationMiddleware.cs
T
Claude c78747053e feat(server): API v1 with auth, uploads, sync, jobs, render nodes and events
- Security: PBKDF2-SHA512 (210,000 iterations) hashes, opaque bearer tokens
  stored as SHA-256 with sliding expiry and revocation, HttpOnly/Secure/
  SameSite=Strict admin cookie with a session-bound CSRF token, sign-in rate
  limit and lockout, role/permission metadata on every endpoint, audit log,
  first-run administrator bootstrap.
- Sequences with keyset paging, ETags and settings_version conflicts; sync
  manifest; frames, proxies, thumbnails and exports streamed with Range.
- Chunked resumable uploads with hash short-circuit, quota and disk checks,
  staging on the archive volume, SHA-256 verification and IArchiveIngest.
- Job engine host, jobs API, render nodes with heartbeat timeout and
  reassignment, WebSocket events, LAN discovery beacon, upload cleanup.
- Windows service host over advapi32 (--service, --install-service,
  --uninstall-service); fails fast without the archive module services.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 11:32:19 +00:00

80 lines
3.3 KiB
C#

using Titano.Core.Model;
using Titano.Server.Api;
namespace Titano.Server.Security;
/// <summary>
/// Resolves the caller of every <c>/api</c> request (bearer token or admin cookie) and enforces the endpoint's
/// <see cref="AccessRule"/>: 401 without a valid token, 403 for a missing permission, a missing CSRF header on a
/// cookie request, or a pending password change. Runs after routing, so the endpoint's metadata is known.
/// </summary>
public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService tokens)
{
public async Task InvokeAsync(HttpContext context)
{
var rule = context.GetEndpoint()?.Metadata.GetMetadata<AccessRule>();
if (rule is null && !context.Request.Path.StartsWithSegments("/api"))
{
await next(context);
return;
}
rule ??= AccessRule.SignedIn;
if (rule.AllowAnonymous)
{
await next(context);
return;
}
var caller = await AuthenticateAsync(context);
if (caller is null)
{
context.Response.Headers.WWWAuthenticate = "Bearer";
await ApiErrors.WriteAsync(context, StatusCodes.Status401Unauthorized, "unauthorized");
return;
}
if (caller.Source == CredentialSource.Cookie && !IsSameSiteRequest(context, caller))
{
await ApiErrors.WriteAsync(context, StatusCodes.Status403Forbidden, "csrf_failed");
return;
}
if (caller.User.MustChangePassword && !rule.DuringPasswordChange)
{
await ApiErrors.WriteAsync(context, StatusCodes.Status403Forbidden, "password_change_required");
return;
}
if (rule.AnyOf != Permissions.None && !caller.Has(rule.AnyOf))
{
await ApiErrors.WriteAsync(context, StatusCodes.Status403Forbidden, "forbidden");
return;
}
context.Features.Set(caller);
await next(context);
}
private Task<Caller?> AuthenticateAsync(HttpContext context)
{
var authorization = context.Request.Headers.Authorization.ToString();
if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
return tokens.ValidateAsync(authorization[7..].Trim(), CredentialSource.Bearer, context.RequestAborted);
if (context.Request.Cookies.TryGetValue(SessionCookies.Session, out var cookie))
return tokens.ValidateAsync(cookie, CredentialSource.Cookie, context.RequestAborted);
return Task.FromResult<Caller?>(null);
}
/// <summary>
/// Cookie requests must prove they come from the admin panel: unsafe methods carry the CSRF header, WebSocket
/// upgrades (which cannot) must come from this origin.
/// </summary>
private static bool IsSameSiteRequest(HttpContext context, Caller caller)
{
if (context.WebSockets.IsWebSocketRequest)
{
var origin = context.Request.Headers.Origin.ToString();
return origin.Equals($"{context.Request.Scheme}://{context.Request.Host}", StringComparison.OrdinalIgnoreCase);
}
var method = context.Request.Method;
if (HttpMethods.IsGet(method) || HttpMethods.IsHead(method) || HttpMethods.IsOptions(method)) return true;
return SessionCookies.HasValidCsrf(context, caller);
}
}