Files
Heimdall/src/Heimdall.Web/Program.cs
T

232 lines
9.5 KiB
C#
Raw Normal View History

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Security;
using Heimdall.Web.Components;
using Heimdall.Web.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.IdentityModel.Tokens;
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<HeimdallAuthStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(
sp => sp.GetRequiredService<HeimdallAuthStateProvider>());
// ── 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<HeimdallApiClient>();
var apiBaseUrl = builder.Configuration.GetValue<string>("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<AuthState>();
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<App>()
.AddInteractiveServerRenderMode();
// ── 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);
}
});
// ── Cookie auth endpoints (called from Blazor via JS fetch) ───────
// /_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, ILogger<Program> logger) =>
{
if (string.IsNullOrEmpty(request.AccessToken))
{
logger.LogWarning("Signin attempt without access token");
return Results.BadRequest(new { error = "AccessToken is required" });
}
// Validate the JWT server-side — extract claims from the validated token, not from client
try
{
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
};
var principal = handler.ValidateToken(request.AccessToken, validationParams, out _);
// 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))
{
logger.LogWarning("Signin attempt with valid JWT but missing user claims: UserId={UserId}, Email={Email}", userId, email);
return Results.BadRequest(new { error = "Invalid token: missing user claims" });
}
logger.LogInformation("Signing in user {Email} ({UserId}) — creating auth cookie", email, userId);
// 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);
logger.LogInformation("Auth cookie created for {Email} ({UserId})", email, userId);
return Results.Ok();
}
catch (SecurityTokenExpiredException)
{
logger.LogWarning("Signin attempt with expired JWT");
return Results.Unauthorized();
}
catch (Exception ex)
{
logger.LogError(ex, "Signin failed — JWT validation error");
return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" });
}
});
app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger<Program> logger) =>
{
var email = httpContext.User.FindFirst(ClaimTypes.Email)?.Value ?? "(anonymous)";
logger.LogInformation("Signing out user {Email}", email);
await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Results.Ok();
});
app.Run();
// ─── DTO for the cookie sign-in request ───────────────────────────
internal sealed record SignInRequest(
string AccessToken);