using System.Security.Claims; using Heimdall.Infrastructure.Security; using Heimdall.Web.Components; using Heimdall.Web.Services; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Components.Authorization; using MudBlazor.Services; // ── Sentry (GlitchTip) — DSN from env var only ─────────────────── var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN"); var builder = WebApplication.CreateBuilder(args); // ── Sentry ──────────────────────────────────────────────────────── if (sentryDsn is not null) { builder.WebHost.UseSentry(options => { options.Dsn = sentryDsn; options.MinimumBreadcrumbLevel = LogLevel.Debug; options.MinimumEventLevel = LogLevel.Error; options.TracesSampleRate = 0.1; }); } builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); // ── 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; }); 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)); } }); builder.Services.AddCascadingAuthenticationState(); // Blazor auth state provider (reads JWT from ProtectedLocalStorage) // Register the concrete type so @inject HeimdallAuthStateProvider works in pages, // then make the base AuthenticationStateProvider resolve to the same instance. builder.Services.AddScoped(); builder.Services.AddScoped( sp => sp.GetRequiredService()); // ── MudBlazor ───────────────────────────────────────────────────── builder.Services.AddMudServices(config => { config.SnackbarConfiguration.PositionClass = "mud-alert-center-top"; config.SnackbarConfiguration.PreventDuplicates = true; config.SnackbarConfiguration.ShowCloseIcon = true; config.SnackbarConfiguration.VisibleStateDuration = 4000; }); // ── HTTP client for Heimdall API ────────────────────────────────── builder.Services.AddScoped(); var apiBaseUrl = builder.Configuration.GetValue("ApiBaseUrl") ?? Environment.GetEnvironmentVariable("API_BASE_URL") ?? "http://localhost:5000"; builder.Services.AddHttpClient("HeimdallApi", client => { client.BaseAddress = new Uri(apiBaseUrl.TrimEnd('/') + "/"); client.Timeout = TimeSpan.FromSeconds(30); }); // Auth state (shared between services and components) builder.Services.AddScoped(); var app = builder.Build(); // ── Middleware pipeline ──────────────────────────────────────────── if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseHsts(); } app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); app.UseHttpsRedirection(); app.UseAntiforgery(); app.UseStaticFiles(); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorComponents() .AddInteractiveServerRenderMode(); // ── Cookie auth endpoints (called from Blazor via JS fetch) ─────── // /_auth/signin — Creates an authentication cookie after successful API login // /_auth/signout — Clears the authentication cookie on logout 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" }); var claims = new List { new(ClaimTypes.NameIdentifier, request.Id), new(ClaimTypes.Email, request.Email), new(ClaimTypes.Name, request.DisplayName ?? request.Email), }; if (request.Roles is not null) { foreach (var role in request.Roles) claims.Add(new Claim(ClaimTypes.Role, role)); // 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)); } 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) => { if (!await antiforgery.IsRequestValidAsync(httpContext)) return Results.BadRequest(new { error = "Invalid anti-forgery token" }); await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Results.Ok(); }); app.Run(); // ─── DTO for the cookie sign-in request ─────────────────────────── internal sealed record SignInRequest( string Id, string Email, string? DisplayName, IList? Roles);