2026-07-20 09:50:43 +00:00
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
2026-07-16 21:19:16 +00:00
|
|
|
using System.Security.Claims;
|
2026-07-20 09:50:43 +00:00
|
|
|
using System.Text;
|
2026-07-20 17:12:16 +00:00
|
|
|
using Heimdall.Infrastructure.Data;
|
2026-07-19 07:04:25 +00:00
|
|
|
using Heimdall.Infrastructure.Security;
|
2026-07-16 19:09:28 +00:00
|
|
|
using Heimdall.Web.Components;
|
2026-07-16 21:19:16 +00:00
|
|
|
using Heimdall.Web.Services;
|
2026-07-18 20:59:38 +00:00
|
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
2026-07-16 21:19:16 +00:00
|
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
2026-07-20 09:50:43 +00:00
|
|
|
using Microsoft.IdentityModel.Tokens;
|
2026-07-16 21:19:16 +00:00
|
|
|
using MudBlazor.Services;
|
2026-07-16 19:09:28 +00:00
|
|
|
|
2026-07-19 19:33:10 +00:00
|
|
|
// ── Sentry (GlitchTip) — DSN from env var only ───────────────────
|
|
|
|
|
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN");
|
2026-07-18 19:41:57 +00:00
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
|
|
2026-07-18 19:41:57 +00:00
|
|
|
// ── Sentry ────────────────────────────────────────────────────────
|
2026-07-19 19:33:10 +00:00
|
|
|
if (sentryDsn is not null)
|
2026-07-18 19:41:57 +00:00
|
|
|
{
|
2026-07-19 19:33:10 +00:00
|
|
|
builder.WebHost.UseSentry(options =>
|
|
|
|
|
{
|
|
|
|
|
options.Dsn = sentryDsn;
|
|
|
|
|
options.MinimumBreadcrumbLevel = LogLevel.Debug;
|
|
|
|
|
options.MinimumEventLevel = LogLevel.Error;
|
|
|
|
|
options.TracesSampleRate = 0.1;
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-07-18 19:41:57 +00:00
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
builder.Services.AddRazorComponents()
|
|
|
|
|
.AddInteractiveServerComponents();
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// ── Authentication (Microsoft Identity pattern: cookie auth) ──────
|
|
|
|
|
// The app uses JWT auth via the Heimdall API at the application level.
|
|
|
|
|
// At the ASP.NET Core middleware level, we use cookie authentication
|
|
|
|
|
// to persist the user session across requests.
|
|
|
|
|
// The cookie is created after successful API login (see /_auth/signin).
|
|
|
|
|
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
|
|
|
|
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
|
|
|
|
|
{
|
|
|
|
|
options.LoginPath = "/login";
|
|
|
|
|
options.LogoutPath = "/_auth/signout";
|
|
|
|
|
options.AccessDeniedPath = "/not-found";
|
|
|
|
|
options.Cookie.Name = ".Heimdall.Auth";
|
|
|
|
|
options.Cookie.HttpOnly = true;
|
|
|
|
|
options.Cookie.SameSite = SameSiteMode.Lax;
|
|
|
|
|
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
|
|
|
|
options.ExpireTimeSpan = TimeSpan.FromDays(7);
|
|
|
|
|
options.SlidingExpiration = true;
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-19 07:04:25 +00:00
|
|
|
builder.Services.AddAuthorizationCore(options =>
|
|
|
|
|
{
|
|
|
|
|
// Register all permission-based policies from AppPermissions
|
|
|
|
|
var allPermissions = AppPermissions.RolePermissions.Values
|
|
|
|
|
.SelectMany(p => p).Distinct();
|
|
|
|
|
foreach (var permission in allPermissions)
|
|
|
|
|
{
|
|
|
|
|
options.AddPolicy(permission, policy =>
|
|
|
|
|
policy.RequireClaim("permission", permission));
|
|
|
|
|
}
|
|
|
|
|
});
|
2026-07-18 18:58:20 +00:00
|
|
|
builder.Services.AddCascadingAuthenticationState();
|
2026-07-16 21:19:16 +00:00
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// Blazor auth state provider (reads JWT from ProtectedLocalStorage)
|
2026-07-18 21:08:08 +00:00
|
|
|
// Register the concrete type so @inject HeimdallAuthStateProvider works in pages,
|
|
|
|
|
// then make the base AuthenticationStateProvider resolve to the same instance.
|
|
|
|
|
builder.Services.AddScoped<HeimdallAuthStateProvider>();
|
|
|
|
|
builder.Services.AddScoped<AuthenticationStateProvider>(
|
|
|
|
|
sp => sp.GetRequiredService<HeimdallAuthStateProvider>());
|
2026-07-18 20:59:38 +00:00
|
|
|
|
|
|
|
|
// ── MudBlazor ─────────────────────────────────────────────────────
|
2026-07-16 21:19:16 +00:00
|
|
|
builder.Services.AddMudServices(config =>
|
|
|
|
|
{
|
|
|
|
|
config.SnackbarConfiguration.PositionClass = "mud-alert-center-top";
|
|
|
|
|
config.SnackbarConfiguration.PreventDuplicates = true;
|
|
|
|
|
config.SnackbarConfiguration.ShowCloseIcon = true;
|
|
|
|
|
config.SnackbarConfiguration.VisibleStateDuration = 4000;
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// ── HTTP client for Heimdall API ──────────────────────────────────
|
2026-07-16 21:19:16 +00:00
|
|
|
builder.Services.AddScoped<HeimdallApiClient>();
|
2026-07-17 13:22:02 +00:00
|
|
|
var apiBaseUrl = builder.Configuration.GetValue<string>("ApiBaseUrl")
|
|
|
|
|
?? Environment.GetEnvironmentVariable("API_BASE_URL")
|
|
|
|
|
?? "http://localhost:5000";
|
2026-07-16 21:19:16 +00:00
|
|
|
builder.Services.AddHttpClient("HeimdallApi", client =>
|
|
|
|
|
{
|
2026-07-17 13:22:02 +00:00
|
|
|
client.BaseAddress = new Uri(apiBaseUrl.TrimEnd('/') + "/");
|
2026-07-16 21:19:16 +00:00
|
|
|
client.Timeout = TimeSpan.FromSeconds(30);
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// Auth state (shared between services and components)
|
2026-07-16 21:19:16 +00:00
|
|
|
builder.Services.AddScoped<AuthState>();
|
|
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
var app = builder.Build();
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// ── Middleware pipeline ────────────────────────────────────────────
|
2026-07-16 19:09:28 +00:00
|
|
|
if (!app.Environment.IsDevelopment())
|
|
|
|
|
{
|
|
|
|
|
app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
|
|
|
|
app.UseHsts();
|
|
|
|
|
}
|
2026-07-16 21:19:16 +00:00
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
|
|
|
|
|
app.UseHttpsRedirection();
|
|
|
|
|
app.UseAntiforgery();
|
2026-07-19 18:37:52 +00:00
|
|
|
app.UseStaticFiles();
|
2026-07-18 20:59:38 +00:00
|
|
|
|
|
|
|
|
app.UseAuthentication();
|
|
|
|
|
app.UseAuthorization();
|
|
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
app.MapRazorComponents<App>()
|
|
|
|
|
.AddInteractiveServerRenderMode();
|
|
|
|
|
|
2026-07-20 17:12:16 +00:00
|
|
|
// ── Health check endpoints for Docker ─────────────────────────────
|
|
|
|
|
app.MapGet("/healthz", () =>
|
|
|
|
|
Results.Ok(new { status = "healthy", timestamp = DateTime.UtcNow }));
|
|
|
|
|
|
|
|
|
|
app.MapGet("/readyz", async (HttpContext context) =>
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var scope = context.RequestServices.CreateScope();
|
|
|
|
|
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
|
|
|
_ = await db.Database.CanConnectAsync();
|
|
|
|
|
return Results.Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
return Results.StatusCode(503);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// ── Cookie auth endpoints (called from Blazor via JS fetch) ───────
|
2026-07-20 09:50:43 +00:00
|
|
|
// /_auth/signin — Validates the JWT access token and creates an auth cookie
|
2026-07-18 20:59:38 +00:00
|
|
|
// /_auth/signout — Clears the authentication cookie on logout
|
2026-07-20 09:50:43 +00:00
|
|
|
//
|
|
|
|
|
// 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";
|
2026-07-18 20:59:38 +00:00
|
|
|
|
2026-07-20 17:12:16 +00:00
|
|
|
app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, ILogger<Program> logger) =>
|
2026-07-18 20:59:38 +00:00
|
|
|
{
|
2026-07-20 09:50:43 +00:00
|
|
|
if (string.IsNullOrEmpty(request.AccessToken))
|
2026-07-20 17:12:16 +00:00
|
|
|
{
|
|
|
|
|
logger.LogWarning("Signin attempt without access token");
|
2026-07-20 09:50:43 +00:00
|
|
|
return Results.BadRequest(new { error = "AccessToken is required" });
|
2026-07-20 17:12:16 +00:00
|
|
|
}
|
2026-07-18 20:59:38 +00:00
|
|
|
|
2026-07-20 09:50:43 +00:00
|
|
|
// Validate the JWT server-side — extract claims from the validated token, not from client
|
|
|
|
|
try
|
2026-07-18 20:59:38 +00:00
|
|
|
{
|
2026-07-20 09:50:43 +00:00
|
|
|
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
|
|
|
|
|
};
|
2026-07-18 20:59:38 +00:00
|
|
|
|
2026-07-20 09:50:43 +00:00
|
|
|
var principal = handler.ValidateToken(request.AccessToken, validationParams, out _);
|
2026-07-19 07:04:25 +00:00
|
|
|
|
2026-07-20 09:50:43 +00:00
|
|
|
// 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))
|
2026-07-20 17:12:16 +00:00
|
|
|
{
|
|
|
|
|
logger.LogWarning("Signin attempt with valid JWT but missing user claims: UserId={UserId}, Email={Email}", userId, email);
|
2026-07-20 09:50:43 +00:00
|
|
|
return Results.BadRequest(new { error = "Invalid token: missing user claims" });
|
2026-07-20 17:12:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.LogInformation("Signing in user {Email} ({UserId}) — creating auth cookie", email, userId);
|
2026-07-20 09:50:43 +00:00
|
|
|
|
|
|
|
|
// 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);
|
2026-07-20 17:12:16 +00:00
|
|
|
logger.LogInformation("Auth cookie created for {Email} ({UserId})", email, userId);
|
2026-07-20 09:50:43 +00:00
|
|
|
return Results.Ok();
|
|
|
|
|
}
|
|
|
|
|
catch (SecurityTokenExpiredException)
|
|
|
|
|
{
|
2026-07-20 17:12:16 +00:00
|
|
|
logger.LogWarning("Signin attempt with expired JWT");
|
2026-07-20 09:50:43 +00:00
|
|
|
return Results.Unauthorized();
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-07-20 17:12:16 +00:00
|
|
|
logger.LogError(ex, "Signin failed — JWT validation error");
|
2026-07-20 09:50:43 +00:00
|
|
|
return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" });
|
2026-07-18 20:59:38 +00:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-20 17:12:16 +00:00
|
|
|
app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger<Program> logger) =>
|
2026-07-18 20:59:38 +00:00
|
|
|
{
|
2026-07-20 17:12:16 +00:00
|
|
|
var email = httpContext.User.FindFirst(ClaimTypes.Email)?.Value ?? "(anonymous)";
|
|
|
|
|
logger.LogInformation("Signing out user {Email}", email);
|
2026-07-18 20:59:38 +00:00
|
|
|
await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
|
|
|
|
return Results.Ok();
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
app.Run();
|
2026-07-18 20:59:38 +00:00
|
|
|
|
|
|
|
|
// ─── DTO for the cookie sign-in request ───────────────────────────
|
|
|
|
|
|
|
|
|
|
internal sealed record SignInRequest(
|
2026-07-20 09:50:43 +00:00
|
|
|
string AccessToken);
|