GNMON-001 M6 abgenommen: Dashboard oeffentlich via mon.ghostnet.selfhost.eu (Keycloak-OIDC)

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>
This commit is contained in:
2026-11-09 19:34:50 +01:00
parent 148104de4e
commit fd8e1a5559
25 changed files with 383 additions and 90 deletions
@@ -73,11 +73,17 @@ gnmon_loki_image_ref: docker.io/grafana/loki:3.6.19
gnmon_alertmanager_image_ref: docker.io/prom/alertmanager:v0.34.2
gnmon_vmalert_image_ref: docker.io/victoriametrics/vmalert:v1.154.1
# --- Firewall (M6, nur System-Scope auf ghostnet-ki) -------------------------
gnmon_firewall_scope: system
# 8080 nur von NPM (CT-103) erreichbar (gnmon_firewall); Default-Werte siehe Rolle.
# --- Dashboard ---------------------------------------------------------------
gnmon_dashboard_scope: system
gnmon_dashboard_systemd_scope: system
gnmon_dashboard_quadlet_dir: /etc/containers/systemd/users/984
# Transportiertes Image (Workstation-Build, podman save/load am 06.11.2026:
# docker.io/ghostnet/dashboard:v0.1.0, ID 1b71e6d35069 — identisch zur
# Workstation, Build aus images/dashboard/Containerfile).
gnmon_dashboard_image_ref: docker.io/ghostnet/dashboard:v0.2.0
# M6: Bind auf die LAN-IP; nftables (gnmon_firewall) lässt nur 10.0.0.10 (NPM) zu.
gnmon_dashboard_http_listen: "10.0.0.90:8080"
# Transportiertes Image (Workstation-Build, podman save/load am 09.11.2026).
# v0.2.1: konfigurierbare Auth:AllowedRoles; v0.2.2 (ID 518f88349c6c): ClientId
# an den Keycloak-Client "gnai-dashboard" angepasst. Build aus images/dashboard/Containerfile.
gnmon_dashboard_image_ref: docker.io/ghostnet/dashboard:v0.3.2
@@ -7,6 +7,8 @@
roles:
- role: gnmon_accounts
tags: [accounts, never]
- role: gnmon_firewall
tags: [firewall]
- role: gnmon_collector
tags: [collector]
- role: gnmon_victoria_metrics
@@ -120,23 +122,33 @@
when: gnmon_vmalert_selftest_rule | bool
tags: [alerting]
- name: Wait for the dashboard to answer on the host loopback
# M6: with Auth enabled, "/" answers 302 (OIDC challenge via PAR toward
# Keycloak) instead of 200; without auth it serves the Blazor shell (200).
# The forwarded headers simulate the NPM ingress so the OIDC redirect
# URI resolves to the external host registered in Keycloak.
- name: Wait for the dashboard to answer
ansible.builtin.uri:
url: "http://{{ gnmon_dashboard_http_listen }}/"
status_code: 200
status_code: [200, 302]
headers:
X-Forwarded-Proto: https
X-Forwarded-Host: mon.ghostnet.selfhost.eu
register: gnmon_dashboard_ready
retries: 20
delay: 3
until: gnmon_dashboard_ready.status == 200
until: gnmon_dashboard_ready.status in [200, 302]
tags: [dashboard]
- name: Verify the dashboard serves the Blazor shell
- name: Verify the dashboard answers (200 shell or 302 OIDC challenge)
ansible.builtin.uri:
url: "http://{{ gnmon_dashboard_http_listen }}/"
status_code: 200
status_code: [200, 302]
headers:
X-Forwarded-Proto: https
X-Forwarded-Host: mon.ghostnet.selfhost.eu
return_content: false
register: gnmon_dashboard_shell
until: gnmon_dashboard_shell.status == 200
until: gnmon_dashboard_shell.status in [200, 302]
retries: 3
delay: 2
tags: [dashboard]
@@ -24,11 +24,9 @@ gnmon_alloy_loki_push_url: "http://127.0.0.1:3100/loki/api/v1/push"
# journald source. In user-scope operation the sd-journal auto-discovery
# only opens the user journal; the workstation inventory therefore sets
# an explicit journal path. Empty string = auto-discovery.
# an explicit journal path. Empty string = auto-discovery. Needs the
# systemd-journal group membership of the run user in system scope.
gnmon_alloy_journal_path: ""
gnmon_alloy_journal_max_age: "12h"
# journald source (needs systemd-journal group membership).
gnmon_alloy_journal_enabled: true
gnmon_alloy_journal_max_age: "12h"
@@ -14,11 +14,11 @@ gnmon_dashboard_quadlet_dir: >-
if gnmon_dashboard_scope == 'system'
else lookup('ansible.builtin.env', 'HOME') ~ '/.config/containers/systemd' }}
# Transported image (built from images/dashboard/Containerfile); v0.2.0
# adds the configuration-driven OIDC layer (M6, GNMON-000). The image is
# transported (podman save/load), so the inventory pins the tag ref either
# way.
gnmon_dashboard_image_ref: docker.io/ghostnet/dashboard:v0.2.0
# Transported image (built from images/dashboard/Containerfile); v0.2.1
# adds the configuration-driven OIDC layer with configurable Auth:AllowedRoles
# (M6, GNMON-000). The image is transported (podman save/load), so the
# inventory pins the tag ref either way.
gnmon_dashboard_image_ref: docker.io/ghostnet/dashboard:v0.3.2
# Host loopback only (GNMON-001 section 7); NPM ingress follows in M6.
gnmon_dashboard_http_listen: "127.0.0.1:8080"
@@ -4,10 +4,17 @@
that:
- gnmon_dashboard_scope in ['user', 'system']
- gnmon_dashboard_image_ref is match('^[a-z0-9./:-]+$')
- gnmon_dashboard_http_listen is match('^127\.0\.0\.1:[0-9]+$')
# M5 default: host loopback. M6: a LAN bind is allowed only in system
# scope together with the gnmon_firewall role (8080 restricted to NPM).
- >-
gnmon_dashboard_http_listen is match('^127\.0\.0\.1:[0-9]+$')
or (gnmon_dashboard_scope == 'system'
and gnmon_firewall_scope | default('user') == 'system'
and gnmon_dashboard_http_listen is match('^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+$'))
fail_msg: >-
gnmon_dashboard requires scope user|system, an image ref and a
host-loopback listen address.
gnmon_dashboard requires scope user|system, an image ref and either a
host-loopback listen address or — in system scope with gnmon_firewall
active — a LAN listen address (M6 ingress via NPM only).
- name: Create the dashboard quadlet directory
ansible.builtin.file:
@@ -0,0 +1,32 @@
# gnmon_firewall
Host-nftables on `ghostnet-ki` (GNMON-001 section 7), system scope only. The
workstation inventory (user scope) is a no-op.
## What it enforces
- Dashboard port 8080 (M6): reachable **only from NPM** (CT-103,
`gnmon_firewall_dashboard_allowed_ip` = 10.0.0.10). NPM terminates TLS and
the OIDC redirect; the dashboard itself binds to the LAN address
`10.0.0.90:8080` (`gnmon_dashboard_http_listen`).
- Monitoring APIs (Loki 3100/9096, VictoriaMetrics 8428, vmalert 8880,
Alertmanager 9093, node_exporter 9100): bound to 127.0.0.1 by the services
and additionally dropped for non-loopback traffic (defense in depth).
## What it deliberately does NOT do
The input policy stays **ACCEPT**: the KI host has no other firewall, and a
default-drop policy introduced from the monitoring project could lock out SSH
management. A full host firewall is a separate sprint (GNAI-001 M1).
`flush ruleset` in the managed `/etc/nftables.conf` removes every other
table — do not maintain foreign nftables content on this host.
## Operations
- Preview: `ansible-playbook -i inventories/testing/hosts.yml playbooks/monitor.yml --tags firewall --check --diff`
- Deploy: same without `--check`.
- Verify live: `nft list ruleset` (root), e.g. on the host
`sudo nft list table inet gnmon_filter`.
- Negative test from the workstation while the dashboard is LAN-bound:
`curl -k --max-time 5 https://10.0.0.90:8080/` must time out (dropped),
while `https://mon.ghostnet.selfhost.eu/` via NPM answers.
@@ -0,0 +1,29 @@
# GNMON-001 section 7: host nftables on ghostnet-ki (M6 ingress control).
#
# System scope only (ghostnet-ki). The workstation (user scope) needs no
# host firewall: everything binds to 127.0.0.1 there as well.
#
# Safety: the input policy stays ACCEPT. This role only adds GNMON-specific
# restrictions (dashboard ingress from NPM only, monitoring ports loopback
# only). A default-drop host firewall is a separate sprint (GNAI-001 M1)
# and must never be introduced from here.
gnmon_firewall_scope: user
gnmon_firewall_config_path: /etc/nftables.conf
gnmon_firewall_service_name: nftables.service
# Dashboard ingress (M6): the Blazor dashboard binds to the LAN address,
# but only NPM (CT-103) may reach it; NPM terminates TLS and OIDC.
gnmon_firewall_dashboard_port: 8080
gnmon_firewall_dashboard_allowed_ip: 10.0.0.10
# Monitoring APIs bind to 127.0.0.1 (GNMON-000 M5); deny non-loopback
# access to them anyway (defense in depth, GNMON-001 section 7).
gnmon_firewall_loopback_only_ports:
- 3100 # Loki HTTP
- 9096 # Loki gRPC
- 8428 # VictoriaMetrics
- 8880 # vmalert
- 9093 # Alertmanager
- 9100 # node_exporter
@@ -0,0 +1,8 @@
---
# GNMON-001 section 7: nftables reload handler (system scope).
- name: Restart nftables
ansible.builtin.systemd_service:
name: "{{ gnmon_firewall_service_name }}"
state: restarted
daemon_reload: true
when: gnmon_firewall_scope == 'system'
@@ -0,0 +1,68 @@
---
# GNMON-001 section 7: host nftables on ghostnet-ki. System scope only;
# the role is a no-op for the workstation (user scope) inventory.
- name: Validate firewall declarations
ansible.builtin.assert:
that:
- gnmon_firewall_scope in ['user', 'system']
- gnmon_firewall_config_path is match('^/etc/')
- gnmon_firewall_dashboard_port | int >= 1024
- gnmon_firewall_dashboard_allowed_ip is match('^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$')
- gnmon_firewall_loopback_only_ports | length > 0
fail_msg: >-
gnmon_firewall requires scope user|system, an /etc config path, a
dashboard port >= 1024 and a valid NPM ingress IPv4.
when: gnmon_firewall_scope == 'system'
- name: Install nftables (system scope only)
ansible.builtin.apt:
name: nftables
state: present
when: gnmon_firewall_scope == 'system'
- name: Install the managed nftables configuration
ansible.builtin.template:
src: nftables.conf.j2
dest: "{{ gnmon_firewall_config_path }}"
owner: root
group: root
mode: "0644"
validate: "/usr/sbin/nft --check --file %s"
notify: Restart nftables
when: gnmon_firewall_scope == 'system'
- name: Enable and start the nftables service
ansible.builtin.systemd_service:
name: "{{ gnmon_firewall_service_name }}"
enabled: true
state: started
daemon_reload: true
when:
- gnmon_firewall_scope == 'system'
- not ansible_check_mode
- name: Verify the GNMON ruleset is loaded
ansible.builtin.command:
argv:
- /usr/sbin/nft
- list
- ruleset
register: gnmon_firewall_ruleset
changed_when: false
check_mode: false
when:
- gnmon_firewall_scope == 'system'
- not ansible_check_mode
- name: Require the dashboard ingress restriction
ansible.builtin.assert:
that:
- "'gnmon_filter' in gnmon_firewall_ruleset.stdout"
- "('tcp dport ' ~ (gnmon_firewall_dashboard_port | string)) in gnmon_firewall_ruleset.stdout"
fail_msg: >-
The gnmon_filter table or the dashboard port restriction is missing
from the live ruleset.
when:
- gnmon_firewall_scope == 'system'
- not ansible_check_mode
@@ -0,0 +1,26 @@
#!/usr/sbin/nft -f
# {{ ansible_managed }}
# GNMON-001 section 7: host nftables on ghostnet-ki, managed by the
# gnmon_firewall role (llm-server/monitoring/ansible).
#
# The input policy deliberately stays ACCEPT: this host has no other
# firewall and a default-drop here could lock out SSH management.
# This table only enforces the GNMON ingress rules. `flush ruleset`
# removes every other table — do not add foreign nftables content to
# this host without moving the firewall into its own role/sprint.
flush ruleset
table inet gnmon_filter {
chain input {
type filter hook input priority filter; policy accept;
iifname "lo" accept
# M6: dashboard ingress only from NPM (CT-103, {{ gnmon_firewall_dashboard_allowed_ip }}).
ip saddr != {{ gnmon_firewall_dashboard_allowed_ip }} tcp dport {{ gnmon_firewall_dashboard_port }} drop
# Monitoring APIs are bound to 127.0.0.1; deny non-loopback anyway.
iifname != "lo" tcp dport { {{ gnmon_firewall_loopback_only_ports | join(', ') }} } drop
}
}
@@ -13,7 +13,10 @@ COPY Ghostnet.Dashboard.csproj .
RUN dotnet restore Ghostnet.Dashboard.csproj
COPY . .
RUN dotnet publish Ghostnet.Dashboard.csproj -c Release -o /app --no-restore
# No --no-restore: with the cached restore the publish could run with stale
# package data and drop wwwroot/_framework/blazor.web.js (404 in the
# container, Befund 09.11.2026); a full restore+publish keeps it.
RUN dotnet publish Ghostnet.Dashboard.csproj -c Release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
@@ -0,0 +1,9 @@
@page "/access-denied"
@attribute [AllowAnonymous]
@layout MainLayout
<h3>Zugriff verweigert (403)</h3>
<p>Dein Keycloak-Account (Realm <code>Ghost.net</code>) hat keine der Realm-Rollen
<code>gnai-dashboard-user</code> oder <code>gnai-dashboard-admin</code>.</p>
<p>Bitte wende dich an den Betreiber, um eine der Rollen zugewiesen zu bekommen,
oder melde dich mit einem anderen Account an: <a href="/login">Login</a></p>
@@ -5,8 +5,13 @@
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<BlazorDisableThrowNavigationException>true</BlazorDisableThrowNavigationException>
<!-- SDK 10 prune package data is unavailable for the system-installed
runtime pack; irrelevant for framework-dependent builds. -->
<!-- .NET 10 package pruning dropped wwwroot/_framework/blazor.web.js from
the published output (it lives in the prunable Internal.Assets
package), so the container served 404 for blazor.web.js and the
Blazor circuit never started (Befund 09.11.2026). Disable pruning;
AllowMissingPrunePackageData is required because the system-installed
runtime pack ships no prune data (NETSDK1226 otherwise). -->
<PrunePackageData>false</PrunePackageData>
<AllowMissingPrunePackageData>true</AllowMissingPrunePackageData>
</PropertyGroup>
@@ -36,8 +36,14 @@ builder.Services.AddHttpClient<AlertmanagerClient>(client =>
// --- 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 the realm role dashboard-admin.
// 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"]
@@ -49,13 +55,16 @@ if (authEnabled)
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;
})
.AddCookie()
// 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;
@@ -63,14 +72,31 @@ if (authEnabled)
options.ClientSecret = clientSecret;
options.ResponseType = "code"; // authorization code flow + PKCE
options.UsePkce = true;
options.SaveTokens = false;
options.GetClaimsFromUserInfoEndpoint = false;
// Keycloak realm roles live in realm_access.roles; map them onto
// role claims in addition to the claims transformation (the
// transformation also covers identities without a role claim).
options.TokenValidationParameters.RoleClaimType = "role";
// 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>();
@@ -82,8 +108,9 @@ builder.Services.AddAuthorization(options =>
{
if (authEnabled)
{
// Realm role from Ghost.net (see KeycloakRealmRolesClaimTransformation).
policy.RequireRole("dashboard-admin");
// Realm roles from Ghost.net (see KeycloakRealmRolesClaimTransformation),
// configurable via Auth:AllowedRoles.
policy.RequireRole(allowedRoles);
}
else
{
@@ -97,12 +124,21 @@ 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.
app.UseForwardedHeaders(new ForwardedHeadersOptions
// 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 = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost,
};
forwardedHeaders.KnownNetworks.Clear();
forwardedHeaders.KnownProxies.Clear();
app.UseForwardedHeaders(forwardedHeaders);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
@@ -6,8 +6,10 @@ namespace Ghostnet.Dashboard.Services;
/// <summary>
/// Maps Keycloak realm roles (the realm_access.roles JSON claim) onto
/// role claims so [Authorize]/RequireRole work with the standard OIDC
/// handler (GNMON-001 section 6: realm role dashboard-admin).
/// ClaimTypes.Role claims so [Authorize]/RequireRole work with the standard
/// OIDC handler (GNMON-001 section 6: realm roles gnai-dashboard-user /
/// gnai-dashboard-admin in realm Ghost.net). Fail closed: a malformed
/// realm_access claim adds no roles and authorization denies access.
/// </summary>
public sealed class KeycloakRealmRolesClaimTransformation : IClaimsTransformation
{
@@ -16,14 +18,12 @@ public sealed class KeycloakRealmRolesClaimTransformation : IClaimsTransformatio
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (principal.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
{
return Task.FromResult(principal);
}
// M6 diagnostic: always log invocation + claim inventory (claim types
// only, no values) so a missing realm_access becomes visible.
var types = principal.Claims.Select(c => c.Type).Distinct().OrderBy(t => t).ToList();
Console.WriteLine($"[gnmon-auth] transform called; authenticated={principal.Identity?.IsAuthenticated}; claim_types={string.Join(",", types)}");
// Skip when the identity already carries a usable role claim.
if (identity.HasClaim(claim =>
claim.Type == identity.RoleClaimType && !string.IsNullOrEmpty(claim.Value)))
if (principal.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
{
return Task.FromResult(principal);
}
@@ -31,9 +31,11 @@ public sealed class KeycloakRealmRolesClaimTransformation : IClaimsTransformatio
var realmAccess = principal.FindFirst(RealmAccessClaim)?.Value;
if (string.IsNullOrWhiteSpace(realmAccess))
{
Console.WriteLine("[gnmon-auth] realm_access claim MISSING");
return Task.FromResult(principal);
}
var mapped = new List<string>();
try
{
using var document = JsonDocument.Parse(realmAccess);
@@ -44,17 +46,23 @@ public sealed class KeycloakRealmRolesClaimTransformation : IClaimsTransformatio
var value = role.GetString();
if (!string.IsNullOrEmpty(value))
{
identity.AddClaim(new Claim(identity.RoleClaimType, value));
// Always ClaimTypes.Role: that is the identity's
// RoleClaimType under the default token validation
// parameters, so IsInRole finds these claims.
identity.AddClaim(new Claim(ClaimTypes.Role, value));
mapped.Add(value);
}
}
}
}
catch (JsonException)
{
// Malformed realm_access: fall through without roles; the
// authorization policy denies access (fail closed).
// Malformed realm_access: no roles added; the authorization
// policy denies access (fail closed).
}
// Role names are not secret; log them for M6 acceptance evidence.
Console.WriteLine($"[gnmon-auth] user={identity.Name} realm_roles={string.Join(",", mapped)}");
return Task.FromResult(principal);
}
}
@@ -9,7 +9,7 @@
"Auth": {
"Enabled": false,
"Authority": "https://auth.ghostnet.selfhost.eu/realms/Ghost.net",
"ClientId": "gn-dashboard"
"ClientId": "gnai-dashboard"
},
"Monitoring": {
"VictoriaMetrics": "http://127.0.0.1:8428",