using System.Security.Claims; using Ghostnet.Dashboard.Components; using Ghostnet.Dashboard.Services; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.HttpOverrides; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); // Monitoring endpoints (GNMON-001 sections 4-7); host-local in the // workstation development phase, quadlet-internal on the server. builder.Services.AddHttpClient(client => { client.BaseAddress = new Uri( builder.Configuration["Monitoring:VictoriaMetrics"] ?? "http://127.0.0.1:8428"); client.Timeout = TimeSpan.FromSeconds(5); }); builder.Services.AddHttpClient(client => { client.BaseAddress = new Uri( builder.Configuration["Monitoring:Loki"] ?? "http://127.0.0.1:3100"); client.Timeout = TimeSpan.FromSeconds(5); }); builder.Services.AddHttpClient(client => { client.BaseAddress = new Uri( builder.Configuration["Monitoring:Alertmanager"] ?? "http://127.0.0.1:9093"); client.Timeout = TimeSpan.FromSeconds(5); }); // --- OIDC (GNMON-001 section 6, M6) ------------------------------------ // Auth is purely configuration-driven: disabled (workstation/local // deployments) the DashboardAccess policy authorizes everyone; enabled // the app requires a Keycloak login with a realm role ai-dashboard or // ai-dashboard-admin (Betreiber-Namenskonvention im Realm Ghost.net). var authEnabled = builder.Configuration.GetValue("Auth:Enabled"); // Realm roles that grant dashboard access (comma-separated, configurable // so the Keycloak naming does not require an app rebuild). var allowedRoles = (builder.Configuration["Auth:AllowedRoles"] ?? "ai-dashboard,ai-dashboard-admin") .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (authEnabled) { var authority = builder.Configuration["Auth:Authority"] ?? throw new InvalidOperationException("Auth:Enabled requires Auth:Authority"); var clientId = builder.Configuration["Auth:ClientId"] ?? throw new InvalidOperationException("Auth:Enabled requires Auth:ClientId"); // The client secret never enters the repository or the image; it is // mounted via the environment (quadlet Environment= or secrets file). var clientSecret = builder.Configuration["Auth:ClientSecret"] ?? throw new InvalidOperationException( "Auth:Enabled requires the client secret via Auth:ClientSecret (environment)"); builder.Services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) // Forbid after endpoint authorization lands on the COOKIE scheme // (DefaultForbidScheme), so its AccessDeniedPath must point at the page — // the OIDC default /Account/AccessDenied does not exist in this app and // produced a redirect loop (Befund 09.11.2026). .AddCookie(cookie => cookie.AccessDeniedPath = "/access-denied") .AddOpenIdConnect(options => { options.Authority = authority; options.ClientId = clientId; options.ClientSecret = clientSecret; options.ResponseType = "code"; // authorization code flow + PKCE options.UsePkce = true; // The redirect URI is derived from the request host; behind NPM the // X-Forwarded-Host/X-Forwarded-Proto headers (see UseForwardedHeaders // below) restore the external name mon.ghostnet.selfhost.eu, so the // computed https://mon.ghostnet.selfhost.eu/signin-oidc matches the // URI registered in Keycloak. .NET 10 has no RedirectUri property. // SaveTokens is required so the OIDC sign-out redirect carries // id_token_hint (Keycloak end_session rejects logout without it: // "Missing parameters: id_token_hint", Befund 09.11.2026). options.SaveTokens = true; // Pull the full claim set (incl. realm_access.roles) from the // userinfo endpoint: the realm-roles mapper's "Add to ID token" flag // is not set in this realm, so the ID token alone carried no // realm_access and authorization denied everyone (Befund 09.11.2026). options.GetClaimsFromUserInfoEndpoint = true; // Keycloak realm roles live in the realm_access.roles JSON claim; // KeycloakRealmRolesClaimTransformation maps them onto role claims // (ClaimTypes.Role, the default RoleClaimType — overriding it to // "role" broke IsInRole because inbound claim mapping renames "role" // to ClaimTypes.Role, Befund 09.11.2026). options.Scope.Add("openid"); options.Scope.Add("profile"); // Clean 403 page instead of the default /Account/AccessDenied, which // does not exist in this app and produced a redirect loop in the // browser (Befund 09.11.2026). options.AccessDeniedPath = "/access-denied"; }); builder.Services.AddSingleton(); } builder.Services.AddAuthorization(options => { options.AddPolicy("DashboardAccess", policy => { if (authEnabled) { // Realm roles from Ghost.net (see KeycloakRealmRolesClaimTransformation), // configurable via Auth:AllowedRoles. policy.RequireRole(allowedRoles); } else { // Local/off mode (workstation dev, M5 loopback deployment): // no authentication handler is registered, allow anonymous. policy.RequireAssertion(_ => true); } }); }); builder.Services.AddCascadingAuthenticationState(); var app = builder.Build(); // TLS terminates at NPM (CT-103); trust its forwarded headers so the OIDC // redirect URIs and HTTPS checks see the external scheme/host. Port 8080 is // reachable only from 10.0.0.10 anyway (gnmon_firewall), so clearing the // known-proxy lists is safe here. NOTE: KnownNetworks/KnownProxies must be // .Clear()ed — a `{ }` collection initializer keeps the default loopback // entry, non-loopback proxies are then rejected and the redirect_uri is // computed from the internal 10.0.0.90:8080 host (PAR: "Invalid parameter: // redirect_uri", Befund 09.11.2026). var forwardedHeaders = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost, }; forwardedHeaders.KnownNetworks.Clear(); forwardedHeaders.KnownProxies.Clear(); app.UseForwardedHeaders(forwardedHeaders); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); app.UseHttpsRedirection(); // With auth handlers registered wire the pipeline; disabled (local/off) // there is no scheme provider and the DashboardAccess policy allows // anonymous anyway. if (authEnabled) { app.UseAuthentication(); app.UseAuthorization(); } app.UseAntiforgery(); // Minimal interactive auth endpoints (per-page interactive render mode // keeps this out of the Blazor circuit; AuthorizeRouteView sends // unauthenticated users here via RedirectToLogin). app.MapGet("/login", async (HttpContext context, string? returnUrl) => { if (!authEnabled) { context.Response.Redirect("/"); return; } await context.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = "/" }); }); app.MapGet("/logout", async (HttpContext context) => { if (authEnabled) { await context.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme); await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } else { context.Response.Redirect("/"); } }); app.MapStaticAssets(); // Endpoint-level authorization (AuthorizeRouteView lost its Policy // parameter in .NET 10): unauthenticated requests are challenged by the // OIDC handler and return to the originally requested page after the // Keycloak login; authenticated users without the realm role get 403. app.MapRazorComponents() .AddInteractiveServerRenderMode() .RequireAuthorization("DashboardAccess"); app.Run();