Kette: Browser -> https://mon.ghostnet.selfhost.eu (NPM CT-103 ID 14, LE-TLS, Force SSL, WS-Support, X-Forwarded-Proto/Host + 32k-Puffer) -> 10.0.0.90:8080 (nftables gnmon_firewall: nur von 10.0.0.10) -> Blazor v0.3.2 -> Keycloak Realm Ghost.net, Client gnai-dashboard, Rollen gnai-dashboard-user/-admin. Neu/geaendert: - Rolle gnmon_firewall (nftables auf ghostnet-ki, Policy ACCEPT, 8080 nur von NPM, Monitoring-Ports non-loopback-drop), Tag firewall in monitor.yml - Dashboard-Bind 10.0.0.90:8080 (Assertion: LAN-Bind nur mit Firewall-Tag); Image v0.3.2; Playbook-Verifikation akzeptiert 200/302 mit Forwarded-Headern - App: ClientId gnai-dashboard, Auth:AllowedRoles konfigurierbar, KnownNetworks/KnownProxies per .Clear() (leere Initializer = Loopback-Default), GetClaimsFromUserInfoEndpoint=true (realm-roles-Mapper-Flags im Realm unset), SaveTokens=true (Logout: id_token_hint), Cookie AccessDeniedPath /access-denied + Page (sonst Redirect-Loop), csproj PrunePackageData=false + Containerfile ohne --no-restore (sonst fehlt blazor.web.js im Image -> Blazor-Circuit startet nicht) - KeycloakRealmRolesClaimTransformation auf ClaimTypes.Role + [gnmon-auth]-Log - CT-100: Adoption 09.11. (pct exec), Split-DNS mon -> 10.0.0.10 live; Befunde gefixt: dns_pihole_hosts_records in allen 3 Inventaren gespiegelt, FTLCONF_dns_hosts als eine ';'-gejointe Environment-Zeile (systemd: letzter Key gewinnt); gnmon_alloy doppelte Key korrigiert - Doku: GNMON-000 M6 abgenommen (alle Befunde), GNMON-001 v2.2, GNAI-000 Monitoring/DNS-Zeilen, GNAI-006 v3.1 (Proxy-Host 14), GNAI-012 Stand E2E 09.11.2026: unauth -> 302 mit PAR request_uri; Direktzugriff 10.0.0.90:8080 gedroppt; blazor.web.js 200 text/javascript; Login ghost -> Dashboard 200 mit Live-Daten, Unterseiten + WebSocket ok; testuser ohne Rollen -> saubere 403; /logout ok; monitor.yml gesamt ok=84 changed=0. Server-Image-Store aufgeraeumt (v0.3.2 + Rollback v0.2.0/v0.1.0). Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
200 lines
8.6 KiB
C#
200 lines
8.6 KiB
C#
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<VictoriaMetricsClient>(client =>
|
|
{
|
|
client.BaseAddress = new Uri(
|
|
builder.Configuration["Monitoring:VictoriaMetrics"] ?? "http://127.0.0.1:8428");
|
|
client.Timeout = TimeSpan.FromSeconds(5);
|
|
});
|
|
builder.Services.AddHttpClient<LokiClient>(client =>
|
|
{
|
|
client.BaseAddress = new Uri(
|
|
builder.Configuration["Monitoring:Loki"] ?? "http://127.0.0.1:3100");
|
|
client.Timeout = TimeSpan.FromSeconds(5);
|
|
});
|
|
builder.Services.AddHttpClient<AlertmanagerClient>(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<bool>("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<IClaimsTransformation, KeycloakRealmRolesClaimTransformation>();
|
|
}
|
|
|
|
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<App>()
|
|
.AddInteractiveServerRenderMode()
|
|
.RequireAuthorization("DashboardAccess");
|
|
|
|
app.Run();
|