using Titano.Core.Model;
using Titano.Server.Api;
namespace Titano.Server.Security;
///
/// Resolves the caller of every /api request (bearer token or admin cookie) and enforces the endpoint's
/// : 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.
///
public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService tokens)
{
public async Task InvokeAsync(HttpContext context)
{
var rule = context.GetEndpoint()?.Metadata.GetMetadata();
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 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(null);
}
///
/// 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.
///
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);
}
}