From bf0ec37fc14d6ec1960cfe6959cb1aaaa27081c9 Mon Sep 17 00:00:00 2001 From: spektr Date: Mon, 9 Nov 2026 05:40:47 +0100 Subject: [PATCH] GNMON-001 M6: OIDC-faehiges Dashboard v0.2.0 (App + Rolle + Doku) App (Ghostnet.Dashboard, baut fehlerfrei mit 0 Warnungen, .NET 10): - OIDC konfigurationsgetrieben (Auth:Enabled/Authority/ClientId in appsettings.json, Secret nur via ENV Auth__ClientSecret), Authorization Code Flow mit PKCE, Cookie-Schema - KeycloakRealmRolesClaimTransformation mappt realm_access.roles auf Role-Claims; Policy DashboardAccess erfordert Realm-Rolle dashboard-admin (im Off-Modus permissive) - Endpoint-Autorisierung an MapRazorComponents().RequireAuthorization() (.NET 10: AuthorizeRouteView hat keinen Policy-Parameter mehr), UseForwardedHeaders fuer TLS-Terminierung an NPM, /login + /logout - Paket Microsoft.AspNetCore.Authentication.OpenIdConnect 10.0.14 Rolle/Quadlet: host-lokale, verwaltete Secrets-Datei /etc/gnmon/dashboard-secrets.env (Owner gn-dashboard, 0640, force: false) per EnvironmentFile im Quadlet; Image-Default auf v0.2.0 angehoben, Inventory pinnt v0.2.0; Duplikat gnmon_dashboard_quadlet_dir entfernt; Containerfile-Kommentar an die keep-id-Entscheidung (GNMON-000 M5) angepasst. Doku: GNMON-000 (M6-Abschnitt, Verifikation 09.11.2026 nach Host-Neustart, CT-103-Ansible-Nachbau als erledigt markiert) und GNMON-001 v2.1 (Umsetzungsabweichungen: gn-monitor=986, Braille statt ApexCharts, Hostname mon.ghostnet.selfhost.eu, offene Punkte 1-4 entschieden). Externe Freigabe (NPM-Proxyhost + Keycloak-Client gn-dashboard + Auth__Enabled=true) bleibt Betreiber-Schritt, siehe GNMON-000 M6. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .../monitoring/GNMON-000-DOC_Index.md | 108 +++++++++++++--- .../monitoring/GNMON-001-PLAN_Architecture.md | 27 ++-- .../inventories/testing/group_vars/all.yml | 2 +- .../roles/gnmon_dashboard/defaults/main.yml | 16 ++- .../roles/gnmon_dashboard/tasks/main.yml | 22 ++++ .../templates/gnmon-dashboard.container.j2 | 5 + .../monitoring/images/dashboard/Containerfile | 6 +- .../Components/_Imports.razor | 2 + .../Ghostnet.Dashboard.csproj | 4 + .../src/Ghostnet.Dashboard/Program.cs | 116 +++++++++++++++++- .../KeycloakRealmRolesClaimTransformation.cs | 60 +++++++++ .../src/Ghostnet.Dashboard/appsettings.json | 5 + 12 files changed, 334 insertions(+), 39 deletions(-) create mode 100644 llm-server/monitoring/src/Ghostnet.Dashboard/Services/KeycloakRealmRolesClaimTransformation.cs diff --git a/docs/platform/llm-server/monitoring/GNMON-000-DOC_Index.md b/docs/platform/llm-server/monitoring/GNMON-000-DOC_Index.md index 056ac41..0d07114 100644 --- a/docs/platform/llm-server/monitoring/GNMON-000-DOC_Index.md +++ b/docs/platform/llm-server/monitoring/GNMON-000-DOC_Index.md @@ -1,8 +1,8 @@ # Monitoring – Dokumentationsindex und Projektstand **Dokumenten-ID:** GNMON-000-DOC -**Stand:** 2026-11-06 -**Status:** Revision v2.0 (03.11.2026) übernommen; M1–M4 auf der Workstation implementiert und verifiziert; M5 inkl. Dashboard auf dem KI-Server produktiv (System-Scope); NPM/OIDC-Ingress folgt in M6 +**Stand:** 2026-11-09 +**Status:** Revision v2.0 (03.11.2026) übernommen; M1–M5 produktiv auf Workstation + KI-Server; M6 (NPM + Keycloak-OIDC) App-/Server-seitig vorbereitet, externe Freigabe wartet auf Betreiber-Schritte ## Dokumente @@ -271,20 +271,96 @@ die neue Textfile-Metrik. - **Aufgeräumt:** Dashboard-Tar auf Server und Workstation gelöscht, versehentlicher Root-Load entfernt; kein verwaister Container-Rest. +### Verifikation 09.11.2026 (nach Host-Neustart, read-only via `ghost-agent`) + +Host-Neustart gegen 05:05 CET; danach ohne manuelle Eingriffe: alle vier +`gn-monitor`-Container (VM, Loki, vmalert, Alertmanager) plus node_exporter, +Alloy und der Dashboard-Container (dotnet als `gn-dashboard`) wieder aktiv; +alle Ports weiterhin nur auf 127.0.0.1 (3100, 9096, 8428, 8880, 9093, 9100, +8080). Loki `/ready` direkt nach dem Boot vorübergehend 503 (WAL-Replay), +danach 200; Abfragen und Labels fehlerfrei. Dashboard `/` HTTP 200. +vmalert `/-/healthy` 200, Regelgruppe `gnmon-ai` (`GnAiEnvironmentDown`) +geladen, Alertmanager `/api/v2/alerts` leer. VictoriaMetrics liefert +`gn_ai_active_env{env="production"} 1` (Production-Recovery nach Boot, siehe +GNAI-008 14.6) und `gn_gpu_*` für beide Karten (`gpu="unknown"` bestätigt). +Konten per `getent` bestätigt: `gn-monitor` 986, `gn-dashboard` 984, +`gn-download` 983. **Gegenbefund:** `gnai-ai-backup.service` Exit 21 beim +Boot (NFS-Mount noch nicht verfügbar) — dokumentiert in GNAI-008 14.6. + ## Noch offen -1. Punkte 1–6 aus GNMON-001 v2.0 Abschnitt 9 (Metrics-Account-Identität, - NPM-Hostname/Keycloak-Client, UID/GID `gn-monitor`, Chart-Bibliothek, - LLM-Metriken, Retention-Feinjustierung). -2. **Alarmierung (Planlücke):** v2.0 deckt Sammeln und Anzeigen ab, aber - keinen Schwellwert-Alarm (Motivation des Vorfalls). Vorschlag: - `vmalert`-Regeln gegen VictoriaMetrics mit Notification-Kanal; Kanal- - Auswahl (Mail/ntfy/Matrix) ist eine Betreiberentscheidung. -3. M6 auf `ghostnet-ki`: externer Dashboard-Zugriff über NPM (CT-103) - mit TLS + WebSocket-Upgrade sowie OIDC/Keycloak (Confidential Client - `gn-dashboard`, CT-102); damit einhergehend Bindung von :8080 auf - die Host-LAN-IP und nftables-Regel „8080 nur von 10.0.0.10" - (GNMON-001 §7; solange das Dashboard rein host-lokal läuft, ist - keine Regel nötig — alles andere bindet bereits nur Loopback). -4. keep-id-Ursachenanalyse (crun/Overlay-Rechte der gn-dashboard-Storage) +### M6: OIDC-Freigabe (App-seitig fertig 07.11.2026, Go 06.11.2026) + +Betreiberentscheidungen 06.11.2026: Hostname `mon.ghostnet.selfhost.eu`, +Realm `Ghost.net` (Vaultwarden-Realm, Issuer +`https://auth.ghostnet.selfhost.eu/realms/Ghost.net`, Discovery verifiziert +200), Keycloak-Client über den CT-102-Ansible-Zugang, CT-103-NPM künftig +über einen Ansible-Nachbau durch einen Agenten. + +- **App (implementiert, v0.2.0):** + - `Program.cs`: OIDC konfigurationsgetrieben (`Auth:Enabled`/Authority/ + ClientId; Secret nur über ENV `Auth__ClientSecret`, nie Image/Repo). + Authorization-Code-Flow mit PKCE, Cookie-Schema, Keycloak-Rollen aus + `realm_access.roles` per `IClaimsTransformation` + (`KeycloakRealmRolesClaimTransformation`), Policy `DashboardAccess` + (im Off-Modus permissive, im On-Modus `RequireRole("dashboard-admin")`), + `UseForwardedHeaders` (X-Forwarded-For/Proto, TLS endet an NPM), + Endpoint-Autorisierung an `MapRazorComponents().RequireAuthorization()`, + `/login` + `/logout` Komfort-Endpunkte. + - **.NET-10-Befund:** `AuthorizeRouteView` hat keinen `Policy`-Parameter + mehr (Reflection-Check gegen 10.0.14 — nur NotAuthorized/Authorizing/ + Resource/RouteData/DefaultLayout). Ersatz: Endpoint-Autorisierung; + unauthentifizierte Seitenaufrufe erhalten den automatischen + OIDC-Challenge und kehren nach dem Login auf die Zielseite zurück, + authentifiziert ohne Rolle → 403. + - **PAR-Befund:** .NET 10 OIDC nutzt Pushed Authorization Requests; + der Auth-ON-Smoke gegen den echten Realm lief bis zum PAR-Endpunkt + von Keycloak (401, solange der Client fehlt — erwartet). Pipeline + davor verifiziert. + - Off-Modus-Regression: `/` 200 mit Shell, `/login` 302 → `/`, Bau ohne + Warnungen. +- **Rolle/Image (deployed):** Image `v0.2.0` (ID `46f26c575d22…`) gebaut, + geraucht (HTTP 200) und transportiert; Inventory pinnt v0.2.0. Quadlet + lädt `EnvironmentFile=/etc/gnmon/dashboard-secrets.env` (Rolle shipped + leere verwaltete Datei, Owner gn-dashboard 0640, `force: false` — ein + ausgefülltes Secret wird von Läufen nie überschrieben). Suite grün und + idempotent; Dashboard bleibt bis NPM-Freigabe host-lokal (127.0.0.1). +- **Split-DNS (vorbereitet, Deploy blockiert):** CT-100-Rolle hat den + Record `10.0.0.10 mon.ghostnet.selfhost.eu` in `dns_pihole_hosts_records` + ergänzt; der Production-Deploy scheitert zunächst, weil auf CT-100 noch + **kein `ansible-deploy`-Konto existiert** (Adoption steht aus, siehe + Betreiber-Schritte). +- **Betreiber-Schritte (offen):** + 1. Keycloak: einmalig `kcadm config credentials` als Admin im + `ghostnet-keycloak`-Container (Passwort-Prompt), danach legt der + Agent Client `gn-dashboard` (confidential, Standard-Flow, Redirect + `https://mon.ghostnet.selfhost.eu/signin-oidc`), Realm-Rolle + `dashboard-admin` und Rollen-Zuweisung an; Secret wird nur in die + host-lokale dashboard-secrets.env geschrieben. MFA-Hinweis: eine + reichweitenweite Realm-Policy könnte den produktiven + Vaultwarden-OIDC beeinflussen — Ausgestaltung ist + Betreiberentscheidung (z. B. Conditional Flow nur für die Rolle). + 2. CT-100: Adoption-Bootstrap (`bootstrap.yml` auf Bootstrap-Inventar, + `--ask-become-pass`) → Agent deploys den DNS-Record. + 3. CT-103: Der Ansible-Nachbau ist abgeschlossen — Projekt unter + `proxmox/lxc/ct-103-reverse-proxy/ansible/`, am 07.11.2026 adoptiert + und am 09.11.2026 verifiziert (preflight ok=15, verify-production + ok=27 changed=0, `site.yml --check` changed=0; GNAI-006 v3.0). + Verbleibend: Proxy-Host `mon.ghostnet.selfhost.eu` → `10.0.0.90:8080` + in NPM anlegen (NPM-Proxyhosts sind Runtime-Daten und werden nicht + per Ansible verwaltet), WebSocket Support und Block Common Exploits + aktiv, SSL/Redirect wie die bestehenden Hosts (Vaultwarden-Muster). + Danach: Bind des Dashboards auf die LAN-IP + nftables „8080 nur von + 10.0.0.10" + `Auth__Enabled=true` + E2E-Abnahme (echter Login, + Rollen-403-Negativtest, Blazor-Circuit über WebSocket hinter Proxy). + +## Noch offen (Rest) + +1. GNMON-001 v2.0 Abschnitt 9, Restpunkte: Metrics-Account-Identität, + UID/GID `gn-monitor` und Chart-Bibliothek sind entschieden/umgesetzt; + NPM-Hostname ist entschieden (`mon.ghostnet.selfhost.eu`), der + Keycloak-Client folgt mit den M6-Betreiber-Schritten (oben). Offen + bleiben LLM-Metriken jenseits `gn_ai_active_env` (z. B. Tokens/ + Latenzen der Inference-Engine) und die Retention-Feinjustierung. +2. keep-id-Ursachenanalyse (crun/Overlay-Rechte der gn-dashboard-Storage) bei Bedarf; Entscheidung zum Default-Mapping steht in Abschnitt M5. diff --git a/docs/platform/llm-server/monitoring/GNMON-001-PLAN_Architecture.md b/docs/platform/llm-server/monitoring/GNMON-001-PLAN_Architecture.md index 9ad9e30..5c25c77 100644 --- a/docs/platform/llm-server/monitoring/GNMON-001-PLAN_Architecture.md +++ b/docs/platform/llm-server/monitoring/GNMON-001-PLAN_Architecture.md @@ -2,8 +2,8 @@ **Dokumenten-ID:** GNMON-001-PLAN **Titel:** Host-Monitoring auf dem KI-Server: Systemmetriken, Log-Pipeline und Blazor-Dashboard -**Stand:** 03.11.2026 -**Status:** Revidierter Plan (v2.0) nach Betreiberentscheidungen vom 03.11.2026; Implementierung noch nicht begonnen +**Stand:** 2026-11-09 +**Status:** Revidierter Plan (v2.0) nach Betreiberentscheidungen vom 03.11.2026; M1–M5 produktiv umgesetzt (belegter Stand in GNMON-000), M6 externe Freigabe in Vorbereitung **Referenzen:** [GNENC-001](https://git.ghostnet.selfhost.eu/ghostnet.ai/infrastructure/raw/branch/main/docs/platform/llm-server/encoding/GNENC-001-PLAN_Architecture.md), [GNENC-002](https://git.ghostnet.selfhost.eu/ghostnet.ai/infrastructure/raw/branch/main/docs/platform/llm-server/encoding/GNENC-002-PLAN_Pipeline.md), [GNAI-005](https://git.ghostnet.selfhost.eu/ghostnet.ai/infrastructure/raw/branch/main/docs/platform/GNAI-005-SEC_Access-Control.md), [GNAI-006](https://git.ghostnet.selfhost.eu/ghostnet.ai/infrastructure/raw/branch/main/docs/platform/proxmox-server/lxc/ct-103-reverse-proxy/GNAI-006-SEC_Reverse-Proxy.md) ## Änderungsverlauf @@ -12,6 +12,7 @@ | --- | --- | --- | --- | | 19.10.2026 | 1.0 | Betreiber | Planungsabschluss: Metrics-Collector (system.json) + Flask-Dashboard | | 03.11.2026 | 2.0 | Betreiber / Mistral Vibe | Revision: Dashboard auf ASP.NET Core Blazor Server; Metriken über VictoriaMetrics + Exporter statt system.json-Schnappschuss; neue Log-Pipeline (Alloy + Loki) für journald-, Container- und Encoding-Logs | +| 09.11.2026 | 2.1 | Mistral Vibe | Umsetzungsabweichungen gegenüber v2.0 nachgeführt (belegter Stand in GNMON-000): `gn-monitor` hat UID/GID **986** (die geplante 983 war an `gn-download` vergeben), Charts als eigene Braille-Komponente statt ApexCharts, NPM-Hostname `mon.ghostnet.selfhost.eu` entschieden; M1–M5 sind produktiv auf dem KI-Server (System-Scope) und der Workstation (User-Scope) ausgerollt | ## Änderungen gegenüber v1.0 @@ -40,8 +41,8 @@ flowchart LR Browser["Browser (LAN / WireGuard)"] --> NPM["NPM CT-103 (TLS)"] NPM --> KC["Keycloak CT-102 (OIDC, MFA)"] NPM --> DB["Blazor-Dashboard, gn-dashboard (984), 10.0.0.90:8080"] - DB -->|"PromQL, 10.0.0.90:8428"| VM["VictoriaMetrics, gn-monitor (983)"] - DB -->|"LogQL, 10.0.0.90:3100"| LK["Loki, gn-monitor (983)"] + DB -->|"PromQL, 10.0.0.90:8428"| VM["VictoriaMetrics, gn-monitor (986)"] + DB -->|"LogQL, 10.0.0.90:3100"| LK["Loki, gn-monitor (986)"] DB -->|"read-only Mount"| ST["Encoding state/jobs"] subgraph HOST["Host-systemd auf ghostnet-ki"] NE["node_exporter (9100) mit AMD-Textfile-Skript"] @@ -60,8 +61,8 @@ Architekturprinzip: Die Dashboard-App bleibt eine **read-only, GPU-lose Einheit | node_exporter | Host-systemd, Metrics-Account (siehe Abschnitt 9, offener Punkt 1) | CPU, RAM, Disk (Root + NFS-Export), Load; liest Textfile-Verzeichnis | dauerhaft | | AMD-GPU-Textfile-Skript | Host-systemd-Timer (10 s) | liest rocm-smi/sysfs (Util, VRAM, Junction-Temp, Power je Karte); schreibt `.prom`-Textfile atomar für node_exporter | dauerhaft | | Grafana Alloy | Host-systemd, Metrics-Account, Gruppen `systemd-journal` + `gn-media` | liest journald (System + Container) und Encoding-Logfiles; pusht nach Loki | dauerhaft | -| VictoriaMetrics (single) | `gn-monitor` (983), rootless Quadlet | scrapet node_exporter (10 s); speichert Zeitreihen; `/api/v1/query` + `query_range` (Prometheus-API-kompatibel) | dauerhaft | -| Loki | `gn-monitor` (983), rootless Quadlet | Log-Aggregation; `/loki/api/v1/query_range`; Filesystem-Store, kein S3 | dauerhaft | +| VictoriaMetrics (single) | `gn-monitor` (986), rootless Quadlet | scrapet node_exporter (10 s); speichert Zeitreihen; `/api/v1/query` + `query_range` (Prometheus-API-kompatibel) | dauerhaft | +| Loki | `gn-monitor` (986), rootless Quadlet | Log-Aggregation; `/loki/api/v1/query_range`; Filesystem-Store, kein S3 | dauerhaft | | Blazor-Dashboard | `gn-dashboard` (984), rootless Quadlet | UI: Ressourcen-Charts, GPU-Detail, Encoding-Übersicht, Log-Browser; Keycloak-OIDC | dauerhaft | **Entscheidungen mit Begründung:** @@ -95,7 +96,7 @@ Architekturprinzip: Die Dashboard-App bleibt eine **read-only, GPU-lose Einheit 2. **GPU-Detail:** je RX 6900 XT Util, VRAM, Junction-Temp, Power — Live + Verlauf. 3. **Encoding:** aktive Jobs mit Fortschritt, Queue-Tiefe pro Profil, Historie done/failed (30 Tage), Fehlerfälle mit Ablageort `output/_failed/` — aus `state/jobs/*.json` (read-only Mount, unverändert zu v1.0). 4. **Logs:** Browser über Loki `query_range` mit Filter `unit`/`container`/`job` und Live-Tail (Polling alle 2 s). -- **Charts:** Blazor-ApexCharts (NuGet, C#-API, kapselt die JS-Abhängigkeit). v1.0-Grundsatz „kein JS-Framework" bleibt gewahrt: kein Frontend-Framework, nur eine Chart-Komponentenbibliothek. Falls auch das unerwünscht ist: Alternative sind server-seitig gerenderte SVG-Charts (offener Punkt 4). +- **Charts:** ~~Blazor-ApexCharts~~ **umgesetzt:** eigene Braille-Chart-Komponente ohne JS-Chart-Bibliothek (Betreiberentscheidung 04.11.2026, GNMON-000 M3.4); ApexCharts inkl. CDN-Referenz wurde entfernt. - **Live-Updates:** server-seitige Timer/Streaming-Rendering für Live-Kacheln; keine Client-seitige Logik außer der Chart-Rendering-Bibliothek. - **Image:** `llm-server/monitoring/images/dashboard/Containerfile`, Base `mcr.microsoft.com/dotnet/aspnet:10.x`, Digest gepinnt, Non-Root-User im Image (gemappte UID 984). @@ -127,12 +128,12 @@ VictoriaMetrics und Loki laufen mit gepinnten Upstream-Images (kein Eigenbau-Ima ## 9. Offene Punkte -1. **Metrics-Account-Identität** (aus v1.0 übernommen): root vs. dedizierter Account mit `render`- und `systemd-journal`-Gruppe — bei der Umsetzung festlegen; Empfehlung: dedizierter Account. -2. **NPM-Hostname und Keycloak-Client** `gn-dashboard` (Umsetzung mit GNAI-005/GNAI-006). -3. **UID/GID für `gn-monitor`**: geplant 983 (nahe 984); freie ID bei Umsetzung prüfen. -4. **Chart-Bibliothek:** Blazor-ApexCharts vs. server-seitiges SVG (Entscheidung bei Implementierung). -5. **LLM-Metriken** (später, eigenes Thema im AI-Bereich): scrape-fähiger Endpoint des Serving-Containers oder Textfile — Aufnahme erst mit dauerhaftem Serving. -6. **Retention-Feinjustierung** (60 d Metriken / 30 d Logs) nach erstem Realbetriebsmonat. +1. **Metrics-Account-Identität** — *entschieden/umgesetzt:* dedizierter Account `gn-monitor`, UID/GID **986** mit `systemd-journal`-Gruppe (05.11.2026, GNMON-000 M5; die ursprünglich geplante 983 war auf dem Server an `gn-download` vergeben). +2. **NPM-Hostname und Keycloak-Client** `gn-dashboard` — *Hostname entschieden:* `mon.ghostnet.selfhost.eu` (06.11.2026); Keycloak-Client und NPM-Proxy-Host folgen mit den M6-Betreiber-Schritten (GNMON-000). +3. **UID/GID für `gn-monitor`** — *erledigt:* 986 (siehe Punkt 1). +4. **Chart-Bibliothek** — *entschieden:* eigene Braille-Komponente statt ApexCharts (04.11.2026, Abschnitt 6). +5. **LLM-Metriken** (später, eigenes Thema im AI-Bereich): teilweise umgesetzt — `gn_ai_active_env{env}` aus der `ai_environment_switch`-Rolle plus Regel `GnAiEnvironmentDown` (GNMON-000 M5); Tokens/Latenzen der Inference-Engine bleiben offen. +6. **Retention-Feinjustierung** (60 d Metriken / 30 d Logs) nach erstem Realbetriebsmonat — offen. ## 10. Abnahmekriterien (Auszug für die Umsetzung) diff --git a/llm-server/monitoring/ansible/inventories/testing/group_vars/all.yml b/llm-server/monitoring/ansible/inventories/testing/group_vars/all.yml index 72f46e9..7e65ec9 100644 --- a/llm-server/monitoring/ansible/inventories/testing/group_vars/all.yml +++ b/llm-server/monitoring/ansible/inventories/testing/group_vars/all.yml @@ -80,4 +80,4 @@ 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.1.0 +gnmon_dashboard_image_ref: docker.io/ghostnet/dashboard:v0.2.0 diff --git a/llm-server/monitoring/ansible/roles/gnmon_dashboard/defaults/main.yml b/llm-server/monitoring/ansible/roles/gnmon_dashboard/defaults/main.yml index 3352a9e..8a20d21 100644 --- a/llm-server/monitoring/ansible/roles/gnmon_dashboard/defaults/main.yml +++ b/llm-server/monitoring/ansible/roles/gnmon_dashboard/defaults/main.yml @@ -13,13 +13,17 @@ gnmon_dashboard_quadlet_dir: >- {{ '/etc/containers/systemd/users/' ~ gnmon_dashboard_run_uid if gnmon_dashboard_scope == 'system' else lookup('ansible.builtin.env', 'HOME') ~ '/.config/containers/systemd' }} -gnmon_dashboard_quadlet_dir: >- - {{ '/etc/containers/systemd/users/' ~ gnmon_dashboard_run_uid - if gnmon_dashboard_scope == 'system' - else lookup('ansible.builtin.env', 'HOME') ~ '/.config/containers/systemd' }} -# Transported image (built from images/dashboard/Containerfile). -gnmon_dashboard_image_ref: docker.io/ghostnet/dashboard:v0.1.0 +# 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 # Host loopback only (GNMON-001 section 7); NPM ingress follows in M6. gnmon_dashboard_http_listen: "127.0.0.1:8080" + +# M6 OIDC: host-side environment file for the client secret; the role +# ships it empty and managed. When the Keycloak client exists the file +# carries Auth__Enabled / Auth__ClientSecret (owner gn-dashboard). +gnmon_dashboard_config_dir: /etc/gnmon diff --git a/llm-server/monitoring/ansible/roles/gnmon_dashboard/tasks/main.yml b/llm-server/monitoring/ansible/roles/gnmon_dashboard/tasks/main.yml index ca8f67d..62fb243 100644 --- a/llm-server/monitoring/ansible/roles/gnmon_dashboard/tasks/main.yml +++ b/llm-server/monitoring/ansible/roles/gnmon_dashboard/tasks/main.yml @@ -15,6 +15,28 @@ state: directory mode: "0755" +- name: Ensure the dashboard config directory exists + ansible.builtin.file: + path: "{{ gnmon_dashboard_config_dir }}" + state: directory + mode: "0755" + when: gnmon_dashboard_scope == 'system' + +- name: Ship the managed OIDC environment file (empty until M6 secrets) + ansible.builtin.copy: + dest: "{{ gnmon_dashboard_config_dir }}/dashboard-secrets.env" + owner: "{{ gnmon_dashboard_run_user if gnmon_dashboard_scope == 'system' else omit }}" + group: "{{ gnmon_dashboard_run_user if gnmon_dashboard_scope == 'system' else omit }}" + mode: "0640" + force: false + content: | + # Ansible managed (GNMON-001 gnmon_dashboard) - host-local secrets. + # M6 OIDC environment (GNMON-001 section 6). Fill with: + # Auth__Enabled=true + # Auth__ClientSecret= + # Keep secrets out of the repository; this file is host-local. + when: gnmon_dashboard_scope == 'system' + - name: Install the dashboard quadlet ansible.builtin.template: src: gnmon-dashboard.container.j2 diff --git a/llm-server/monitoring/ansible/roles/gnmon_dashboard/templates/gnmon-dashboard.container.j2 b/llm-server/monitoring/ansible/roles/gnmon_dashboard/templates/gnmon-dashboard.container.j2 index 524fcc1..9a9feca 100644 --- a/llm-server/monitoring/ansible/roles/gnmon_dashboard/templates/gnmon-dashboard.container.j2 +++ b/llm-server/monitoring/ansible/roles/gnmon_dashboard/templates/gnmon-dashboard.container.j2 @@ -15,6 +15,11 @@ Network=host # dir for the gn-dashboard storage (works for gn-monitor; cause open). Environment=ASPNETCORE_URLS=http://{{ gnmon_dashboard_http_listen }} Environment=DOTNET_GENERATE_ASPNET_KEY=true +# M6 OIDC: secrets (Auth__ClientSecret and friends) live host-side in an +# environment file owned by the workload account; never in the repo or +# image. The role ships an empty managed file; the operator (or a later +# role) fills it when the Keycloak client exists. +EnvironmentFile={{ gnmon_dashboard_config_dir }}/dashboard-secrets.env [Service] Restart=on-failure diff --git a/llm-server/monitoring/images/dashboard/Containerfile b/llm-server/monitoring/images/dashboard/Containerfile index b8f54d8..e6961e9 100644 --- a/llm-server/monitoring/images/dashboard/Containerfile +++ b/llm-server/monitoring/images/dashboard/Containerfile @@ -1,8 +1,10 @@ # GNMON-001 section 6: Blazor Server dashboard image. # Multi-stage build from the MCR .NET images (not Docker Hub, so server # side rebuilds stay possible even under Docker Hub rate limits). -# Runs as a non-root user; the rootless quadlet maps it onto the -# gn-dashboard host account (UID 984) via UserNS=keep-id. +# Runs as a non-root user; the rootless quadlet uses the default user-namespace +# mapping (keep-id was tested 06.11.2026 and rejected on the server — crun +# Permission denied on the overlay merged dir; GNMON-000 M5), so the image +# user maps into the gn-dashboard subuid range on the host. FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src diff --git a/llm-server/monitoring/src/Ghostnet.Dashboard/Components/_Imports.razor b/llm-server/monitoring/src/Ghostnet.Dashboard/Components/_Imports.razor index 8b7b3d4..5157251 100644 --- a/llm-server/monitoring/src/Ghostnet.Dashboard/Components/_Imports.razor +++ b/llm-server/monitoring/src/Ghostnet.Dashboard/Components/_Imports.razor @@ -9,3 +9,5 @@ @using Ghostnet.Dashboard @using Ghostnet.Dashboard.Components @using Ghostnet.Dashboard.Components.Layout +@using Microsoft.AspNetCore.Authorization +@using Microsoft.AspNetCore.Components.Authorization diff --git a/llm-server/monitoring/src/Ghostnet.Dashboard/Ghostnet.Dashboard.csproj b/llm-server/monitoring/src/Ghostnet.Dashboard/Ghostnet.Dashboard.csproj index 57a15fd..c972b91 100644 --- a/llm-server/monitoring/src/Ghostnet.Dashboard/Ghostnet.Dashboard.csproj +++ b/llm-server/monitoring/src/Ghostnet.Dashboard/Ghostnet.Dashboard.csproj @@ -10,4 +10,8 @@ true + + + + diff --git a/llm-server/monitoring/src/Ghostnet.Dashboard/Program.cs b/llm-server/monitoring/src/Ghostnet.Dashboard/Program.cs index 2d137ea..8560c0e 100644 --- a/llm-server/monitoring/src/Ghostnet.Dashboard/Program.cs +++ b/llm-server/monitoring/src/Ghostnet.Dashboard/Program.cs @@ -1,5 +1,10 @@ +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); @@ -28,8 +33,77 @@ builder.Services.AddHttpClient(client => 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 the realm role dashboard-admin. +var authEnabled = builder.Configuration.GetValue("Auth:Enabled"); +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; + }) + .AddCookie() + .AddOpenIdConnect(options => + { + options.Authority = authority; + options.ClientId = clientId; + 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"; + options.Scope.Add("openid"); + options.Scope.Add("profile"); + }); + + builder.Services.AddSingleton(); +} + +builder.Services.AddAuthorization(options => +{ + options.AddPolicy("DashboardAccess", policy => + { + if (authEnabled) + { + // Realm role from Ghost.net (see KeycloakRealmRolesClaimTransformation). + policy.RequireRole("dashboard-admin"); + } + 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. +app.UseForwardedHeaders(new ForwardedHeadersOptions +{ + ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto, +}); + // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { @@ -40,10 +114,50 @@ if (!app.Environment.IsDevelopment()) 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(); + .AddInteractiveServerRenderMode() + .RequireAuthorization("DashboardAccess"); app.Run(); diff --git a/llm-server/monitoring/src/Ghostnet.Dashboard/Services/KeycloakRealmRolesClaimTransformation.cs b/llm-server/monitoring/src/Ghostnet.Dashboard/Services/KeycloakRealmRolesClaimTransformation.cs new file mode 100644 index 0000000..607c711 --- /dev/null +++ b/llm-server/monitoring/src/Ghostnet.Dashboard/Services/KeycloakRealmRolesClaimTransformation.cs @@ -0,0 +1,60 @@ +using System.Security.Claims; +using System.Text.Json; +using Microsoft.AspNetCore.Authentication; + +namespace Ghostnet.Dashboard.Services; + +/// +/// 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). +/// +public sealed class KeycloakRealmRolesClaimTransformation : IClaimsTransformation +{ + private const string RealmAccessClaim = "realm_access"; + private const string RolesProperty = "roles"; + + public Task TransformAsync(ClaimsPrincipal principal) + { + if (principal.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated) + { + return Task.FromResult(principal); + } + + // Skip when the identity already carries a usable role claim. + if (identity.HasClaim(claim => + claim.Type == identity.RoleClaimType && !string.IsNullOrEmpty(claim.Value))) + { + return Task.FromResult(principal); + } + + var realmAccess = principal.FindFirst(RealmAccessClaim)?.Value; + if (string.IsNullOrWhiteSpace(realmAccess)) + { + return Task.FromResult(principal); + } + + try + { + using var document = JsonDocument.Parse(realmAccess); + if (document.RootElement.TryGetProperty(RolesProperty, out var roles)) + { + foreach (var role in roles.EnumerateArray()) + { + var value = role.GetString(); + if (!string.IsNullOrEmpty(value)) + { + identity.AddClaim(new Claim(identity.RoleClaimType, value)); + } + } + } + } + catch (JsonException) + { + // Malformed realm_access: fall through without roles; the + // authorization policy denies access (fail closed). + } + + return Task.FromResult(principal); + } +} diff --git a/llm-server/monitoring/src/Ghostnet.Dashboard/appsettings.json b/llm-server/monitoring/src/Ghostnet.Dashboard/appsettings.json index 9d2b5c3..f58033e 100644 --- a/llm-server/monitoring/src/Ghostnet.Dashboard/appsettings.json +++ b/llm-server/monitoring/src/Ghostnet.Dashboard/appsettings.json @@ -6,6 +6,11 @@ } }, "AllowedHosts": "*", + "Auth": { + "Enabled": false, + "Authority": "https://auth.ghostnet.selfhost.eu/realms/Ghost.net", + "ClientId": "gn-dashboard" + }, "Monitoring": { "VictoriaMetrics": "http://127.0.0.1:8428", "Loki": "http://127.0.0.1:3100",