chore: apply auto-fixes and code improvements

- AuthService: fix public registration logic revert
- JwtService: add ILogger dependency
- SoftDeleteInterceptor removed (merged)
- XML doc comments on all services
- Error boundary + error page in Blazor
- Optimize StatsService queries
- ApiClient error handling improvements
This commit is contained in:
Arnaud Dartois committed 2026-07-20 09:50:43 +00:00
1 parent 9917d49601
commit a33a436c26
48 files changed
+814 -10337

No files matched your search

+65 -28
View File
@@ -1,4 +1,6 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Heimdall.Infrastructure.Security;
using Heimdall.Web.Components;
using Heimdall.Web.Services;
@@ -6,6 +8,7 @@ using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.IdentityModel.Tokens;
using MudBlazor.Services;
// ── Sentry (GlitchTip) — DSN from env var only ───────────────────
@@ -111,42 +114,79 @@ app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
// ── Cookie auth endpoints (called from Blazor via JS fetch) ───────
// /_auth/signin — Creates an authentication cookie after successful API login
// /_auth/signin — Validates the JWT access token and creates an auth cookie
// /_auth/signout — Clears the authentication cookie on logout
//
// IMPORTANT: The JWT is validated server-side — never trust client-supplied claims.
var jwtKey = builder.Configuration["Jwt:Key"]
?? Environment.GetEnvironmentVariable("JWT__KEY")
?? throw new InvalidOperationException("JWT:Key is not configured");
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall";
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api";
app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, IAntiforgery antiforgery) =>
{
if (!await antiforgery.IsRequestValidAsync(httpContext))
return Results.BadRequest(new { error = "Invalid anti-forgery token" });
if (string.IsNullOrEmpty(request.Id) || string.IsNullOrEmpty(request.Email))
return Results.BadRequest(new { error = "Id and Email are required" });
if (string.IsNullOrEmpty(request.AccessToken))
return Results.BadRequest(new { error = "AccessToken is required" });
var claims = new List<Claim>
// Validate the JWT server-side — extract claims from the validated token, not from client
try
{
new(ClaimTypes.NameIdentifier, request.Id),
new(ClaimTypes.Email, request.Email),
new(ClaimTypes.Name, request.DisplayName ?? request.Email),
};
var handler = new JwtSecurityTokenHandler();
var validationParams = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
ValidateIssuer = true,
ValidIssuer = jwtIssuer,
ValidateAudience = true,
ValidAudience = jwtAudience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
if (request.Roles is not null)
{
foreach (var role in request.Roles)
claims.Add(new Claim(ClaimTypes.Role, role));
var principal = handler.ValidateToken(request.AccessToken, validationParams, out _);
// Resolve permissions from roles (same mapping as JWT token generation)
var permissions = request.Roles
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
.Distinct();
foreach (var permission in permissions)
claims.Add(new Claim("permission", permission));
// Extract claims from the validated JWT only
var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var email = principal.FindFirst(ClaimTypes.Email)?.Value;
var displayName = principal.FindFirst(ClaimTypes.Name)?.Value;
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email))
return Results.BadRequest(new { error = "Invalid token: missing user claims" });
// Re-build claims identity from validated token claims (never from client body)
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, userId),
new(ClaimTypes.Email, email),
new(ClaimTypes.Name, displayName ?? email),
};
foreach (var role in principal.FindAll(ClaimTypes.Role))
claims.Add(new Claim(ClaimTypes.Role, role.Value));
foreach (var permission in principal.FindAll("permission"))
claims.Add(new Claim("permission", permission.Value));
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var cookiePrincipal = new ClaimsPrincipal(identity);
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, cookiePrincipal);
return Results.Ok();
}
catch (SecurityTokenExpiredException)
{
return Results.Unauthorized();
}
catch (Exception ex)
{
return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" });
}
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return Results.Ok();
});
app.MapPost("/_auth/signout", async (HttpContext httpContext, IAntiforgery antiforgery) =>
@@ -163,7 +203,4 @@ app.Run();
// ─── DTO for the cookie sign-in request ───────────────────────────
internal sealed record SignInRequest(
string Id,
string Email,
string? DisplayName,
IList<string>? Roles);
string AccessToken);