diff --git a/.gitignore b/.gitignore index de7cda9..5b2cc21 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,7 @@ # .NET build artifacts (Ghostnet.Dashboard). bin/ obj/ + +# Python +__pycache__/ +*.pyc diff --git a/docs/GNAI-000-DOC_Index.md b/docs/GNAI-000-DOC_Index.md index 538fd4d..a44f934 100644 --- a/docs/GNAI-000-DOC_Index.md +++ b/docs/GNAI-000-DOC_Index.md @@ -2,7 +2,7 @@ **Stand:** 2026-11-14 -**Status:** Plattformgrundlage vorhanden; KI-Stack bis M6 produktiv (Testing/Production live auf `10.0.0.90`, Monitoring M1–M6 produktiv, öffentlicher Nutzerpfad `https://chat.ghostnet.selfhost.eu` live seit 11.11.2026 inklusive Websuche 12.11. und Theme 14.11.); Sicherheitsabschluss: Fail2Ban-Abnahme, hostunabhängige Backups/Restore, Keycloak-Stabilisierung, praktischer NPM-Rückfalltest und CT-104-Entfernung am 10.11.2026 geschlossen — WAN/IPv6-Fremdnetz-Rescan vom Hotspot, FRITZ!Box-Abgleich und FRITZ!Box-DNS-Rollback noch offen; M5-Delivery-Kette: statische CI, Runner (CT 116) und Branch-Protection seit 10.11.2026 umgesetzt, privilegierter Deployment-Runner noch offen; Encoding (M7) in Planung, Implementierung noch nicht begonnen +**Status:** Plattformgrundlage vorhanden; KI-Stack bis M6 produktiv (Testing/Production live auf `10.0.0.90`, Monitoring M1–M6 produktiv, öffentlicher Nutzerpfad `https://chat.ghostnet.selfhost.eu` live seit 11.11.2026 inklusive Websuche 12.11. und Theme 14.11.); Sicherheitsabschluss: Fail2Ban-Abnahme, hostunabhängige Backups/Restore, Keycloak-Stabilisierung, praktischer NPM-Rückfalltest und CT-104-Entfernung am 10.11.2026 geschlossen — WAN/IPv6-Fremdnetz-Rescan vom Hotspot, FRITZ!Box-Abgleich und FRITZ!Box-DNS-Rollback noch offen; M5-Delivery-Kette: statische CI, Runner (CT 116) und Branch-Protection seit 10.11.2026 umgesetzt, privilegierter Deployment-Runner noch offen; Encoding (M7) in Planung, Implementierung noch nicht begonnen; Phase 1 M6-R1 (Deep Research in OpenWebUI, GNAI-022) deployt + UI-abgenommen 14.11.; Phase 2 M8 (GPT Researcher hinter oauth2-proxy/IAP, GNAI-023) produktiv live seit 22.11.2026 (`https://research.ghostnet.selfhost.eu`, M8-T5 Härtung/Abnahme offen) Dieses Dokument ist der zentrale Einstieg, nicht das technische Nachweisprotokoll. Details, historische Laufdaten und Bedienverfahren stehen ausschließlich in den @@ -53,6 +53,8 @@ jeweiligen Fachdokumenten. Die priorisierte weitere Umsetzung beschreibt der | [GNAI-010](platform/llm-server/ai/GNAI-010-TECH_Llama-Serving.md) | technische Sollkonfiguration des Testing-Servings | | [GNAI-020](platform/llm-server/ai/GNAI-020-TECH_OpenWebUI-WebSearch.md) | Websuche in OpenWebUI (SearXNG kuratiert + Native/Agentic Mode, UI- und API-Pfade) | | [GNAI-021](platform/llm-server/ai/GNAI-021-TECH_OpenWebUI-Theme.md) | OpenWebUI-Theme „gnai-catppuccin-mocha" (GNMON-Farbschema) als Default, update-persistent via read-only custom.css-Mount | +| [GNAI-022](platform/llm-server/ai/GNAI-022-TECH_OpenWebUI-DeepResearch.md) | Phase 1 (M6-R1): Deep Research im bestehenden OpenWebUI-Harness — Recherche, Pipe-Function `gnai-deep-research`, Betrieb | +| [GNAI-023](platform/llm-server/ai/GNAI-023-PLAN_GPT-Researcher-IAP.md) | Phase 2 (M8): GPT Researcher hinter Identity-Aware Proxy (oauth2-proxy + NPM auth_request + Keycloak-OIDC) — produktiv seit 22.11.2026; Machbarkeit, Sicherheit, Härtung | | [LLM-Server-Host-Ansible](../llm-server/host/ansible/README.md) | ausführbare Host-/ROCm-Playbooks und Rollen für `10.0.0.90` | | [LLM-Stack-Ansible](../llm-server/llm/ansible/README.md) | ausführbares Ansible-Projekt für den LLM-Stack auf `10.0.0.90` (Production/Testing, Umschaltung, Backup) | | [Encoding-Ansible](../llm-server/encoding/ansible/README.md) | ausführbares Ansible-Projekt für den CPU-Encoding-Workload auf `10.0.0.90` | @@ -90,7 +92,7 @@ Hauptverzeichnisse `llm-server/host/` (Grundkonfiguration des Servers), | --- | --- | --- | | KI-Host | Debian 13.6, Deployment-Zugang, Podman 5.4.2, getrennte rootless Konten, Gerätezugriff für beide KI-Konten; IPv4-only (31.10., GNAI-002 6); Lüftersteuerungs-Dienst `gnai-gpu-fan-control` als Dauerlösung (05.11., GNAI-010 10.10); Backup/Restore praktisch belegt (06.11., GNAI-008 14.6) und Backup-Unit per `RequiresMountsFor` boot-sicher (Fix 09.11., GNAI-008 14.6/0.21); Host-Neustart mit automatischem Production-Recovery (06.11. und erneut 09.11.2026, GNAI-008 14.6) | Host-/Treiber-Upgradepfad | | GPU/ROCm | beide RX 6900 XT als `gfx1030`, `ROCm0` und `ROCm1` im gepinnten Testing-Image erkannt; Modellladen, Layer-Verteilung und reale Inferenz auf beiden GPUs; 64k- und 128k-Stabilität in Testing (GNAI-010 10.5–10.9); GPU-Sensoren im Monitoring mit Alarmgrenzen (GNMON-000 M4/M5, verifiziert 09.11.2026) | Hardware-Ursache des thermischen Defekts an Slot `03:00.0` (GNAI-010 10.10) — Lüfterkurven-Service überbrückt als Dauerlösung | -| LLM-Serving | drei gepinnte Profile (Swift 1.0, Swift 1.5, Unsloth); Testing-Abnahme 64k/128k je Profil (GNAI-010 10.5–10.9); Production-Umgebung live mit Swift 1.5 Q6_K seit 06.11.2026 (Betreiberbeschluss 05.11., GNAI-009 10.4) inklusive Health, Alias und Inferenztest; exklusive Umschaltmechanik mit Recovery (GNAI-008 14.6, T1–T7; nach Neustart 09.11.2026 `gn_ai_active_env{env="production"}=1` verifiziert); **OpenWebUI v0.13.3 (digest-gepinnt) intern produktiv seit 10.11.2026** — Health 200, Model-Liste, reale Chat-Completion via OpenWebUI → llama.cpp (Rolle `open_webui`, Playbook `webui.yml`, Ingress `10.0.0.90:8081` nur von NPM, Split-DNS `chat.ghostnet.selfhost.eu` live). **Öffentlicher Nutzerpfad M6 live seit 11.11.2026:** `https://chat.ghostnet.selfhost.eu` (OpenWebUI v0.13.3, NPM → 10.0.0.90:8081, Keycloak-OIDC Client `gnai-openwebui` public+PKCE; Negativtests: 8081/Engine-Ports von außen geblockt, `/admin/` 403, keine AAAA; OIDC-Redirect-Kette verifiziert). **Websuche produktiv seit 12.11.2026 (GNAI-020):** SearXNG mit 43 kuratierten Engines (168 Ergebnisse/1,4 s), OpenWebUI Native/Agentic Mode (`search_web`/`fetch_url`, `ENABLE_WEB_SEARCH=True` + DB-Config-Sync), E2E-Tool-Loop via API mit Quellen verifiziert, NPM-Proxy-Timeouts chat.* 600 s gesetzt (12.11., GNAI-020 Abschnitt 6). **Theme „gnai-catppuccin-mocha" live seit 14.11.2026 (GNAI-021)**, update-persistent via read-only custom.css-Mount | LLM-Metriken jenseits `gn_ai_active_env`, Nutzerakzeptanzprüfung (GNAI-009 5.3), Lizenz-/Nutzungsrahmen-Nachweis vor externer Freigabe (GNAI-009 10.4), Rate-Limit-Doku, Betriebs-SOP, API-Key-Freigabe für Agenten (GNAI-001 M6) | +| LLM-Serving | drei gepinnte Profile (Swift 1.0, Swift 1.5, Unsloth); Testing-Abnahme 64k/128k je Profil (GNAI-010 10.5–10.9); Production-Umgebung live mit Swift 1.5 Q6_K seit 06.11.2026 (Betreiberbeschluss 05.11., GNAI-009 10.4) inklusive Health, Alias und Inferenztest; exklusive Umschaltmechanik mit Recovery (GNAI-008 14.6, T1–T7; nach Neustart 09.11.2026 `gn_ai_active_env{env="production"}=1` verifiziert); **OpenWebUI v0.13.3 (digest-gepinnt) intern produktiv seit 10.11.2026** — Health 200, Model-Liste, reale Chat-Completion via OpenWebUI → llama.cpp (Rolle `open_webui`, Playbook `webui.yml`, Ingress `10.0.0.90:8081` nur von NPM, Split-DNS `chat.ghostnet.selfhost.eu` live). **Öffentlicher Nutzerpfad M6 live seit 11.11.2026:** `https://chat.ghostnet.selfhost.eu` (OpenWebUI v0.13.3, NPM → 10.0.0.90:8081, Keycloak-OIDC Client `gnai-openwebui` public+PKCE; Negativtests: 8081/Engine-Ports von außen geblockt, `/admin/` 403, keine AAAA; OIDC-Redirect-Kette verifiziert). **Websuche produktiv seit 12.11.2026 (GNAI-020):** SearXNG mit 43 kuratierten Engines (168 Ergebnisse/1,4 s), OpenWebUI Native/Agentic Mode (`search_web`/`fetch_url`, `ENABLE_WEB_SEARCH=True` + DB-Config-Sync), E2E-Tool-Loop via API mit Quellen verifiziert, NPM-Proxy-Timeouts chat.* 600 s gesetzt (12.11., GNAI-020 Abschnitt 6). **Theme „gnai-catppuccin-mocha" live seit 14.11.2026 (GNAI-021)**. **Deep Research (Phase 1, GNAI-022) deployt + UI-abgenommen 14.11.2026:** Pipe „Deep Research" (`gnai-deep-research`, sha256-gepinnt, public read grant) im Model-Selector; iterativer plan→SearXNG→fetch→Synthese-Loop direkt auf der Engine (max_tokens-Limit gegen NPM-Read-Timeout), Branding persistent in der Rolle; Playbook verifiziert + idempotent `changed=0`; Default-Modell „Qwen 3.8 27B (Swift 1.5)" | LLM-Metriken jenseits `gn_ai_active_env`, Nutzerakzeptanzprüfung (GNAI-009 5.3), Lizenz-/Nutzungsrahmen-Nachweis vor externer Freigabe (GNAI-009 10.4), Rate-Limit-Doku, Betriebs-SOP, API-Key-Freigabe für Agenten (GNAI-001 M6), formaler E2E-Research-Lauf via API (GNAI-022 Abschnitt 5). **Phase 2 (M8) in Arbeit (GNAI-023):** GPT Researcher hinter oauth2-proxy/IAP + NPM auth_request + Keycloak-OIDC | | Deployment | lokales Ansible-Control-Projekt und idempotente Hostrollen; Production-Inventar mit Referenz- und Rollback-Profil, `ai_environment_switch` und Backup-Timer deployt und abgenommen (GNAI-008 14.6); **M5-Fortschritt 10.11.2026:** statische CI (Gitea Actions, 4 Jobs) + repo-scoped Runner `ci-static-01` auf CT 116 + Branch-Protection `main` (required checks, 1 Approval) eingerichtet und per PR-Durchlauf bewiesen (GNAI-008 Abschnitt 12) | privilegierter Deployment-Runner mit Promotion-Tag-Freigabe, Secret-Store/-Rotation, getrennte Testing-/Production-Rechte, Secret-Scan über die Git-Historie (GNAI-008 Abschnitt 12, Fragen 3–5) | | VPN | wg-easy v15.4.0; einziger Peer `ghost-laptop` als Server Admin; native nftables-Zielpolicy und NAT, Legacy-Bereinigung, Fremdnetz-, Positiv-/Negativ-, Dienst- und LXC-Wiederanlauftests bestanden; CT 104 am 07.10.2026 als zwölftes Ziel praktisch abgenommen; WAN-Exposure-Erfassung 10.11.2026: nur TCP 80/443 offen, keine AAAA (GNAI-007 7); frischer Stop-Mode-vzdump + hostunabhängige Kopie auf `ghostnet-ki` am 10.11.2026 | Fremdnetz-WAN-Rescan vom Hotspot (UDP 51820, TCP-Portmatrix), FRITZ!Box-Forward-/IPv6-Abgleich, wg-easy-GUI-HTTPS und KI-Server-Test bei eingeschaltetem Host | | DNS / Pi-hole | CT 100 unter `10.0.0.14` mit digest-gepinntem Pi-hole 2026.09.0 als Podman-Quadlet; SSH/nftables, UDP/TCP-DNS, Split-DNS, Blocking/Allowlist, FRITZ!Box-Cutover, LXC-Reboot und Stop-Mode-Backup am 01.10.2026 abgenommen; Ansible-Projekt am 09.11.2026 adoptiert (ansible-deploy via pct; `site.yml`/`verify-production` `changed=0`) und Split-DNS-Record `mon.ghostnet.selfhost.eu → 10.0.0.10` live (verifiziert per `dig @10.0.0.14`); frischer Stop-Mode-vzdump + hostunabhängige Kopie auf `ghostnet-ki` + praktischer Restore-Test (CT 150) am 10.11.2026 (GNAI-012 10.2) | vollständige App-/OIDC-Regression, praktischer FRITZ!Box-Rollback, mobile DuckDuckGo-/IPv6-Strategie, WireGuard-Profile | diff --git a/docs/GNAI-001-PLAN_Project-Roadmap.md b/docs/GNAI-001-PLAN_Project-Roadmap.md index b15af5a..fd7d653 100644 --- a/docs/GNAI-001-PLAN_Project-Roadmap.md +++ b/docs/GNAI-001-PLAN_Project-Roadmap.md @@ -6,7 +6,7 @@ **Stand:** 2026-11-14 -**Status:** Arbeitsgrundlage; M1 bis auf Fremdnetz-Rescan/FRITZ!Box-Rollback geschlossen (10.11.), M2–M4 abgenommen, M5 statische CI/Runner/Branch-Protection umgesetzt (10.11.), M6 öffentlich live seit 11.11. (inkl. Websuche 12.11., Theme 14.11.), M7 offen +**Status:** Arbeitsgrundlage; M1 bis auf Fremdnetz-Rescan/FRITZ!Box-Rollback geschlossen (10.11.), M2–M4 abgenommen, M5 statische CI/Runner/Branch-Protection umgesetzt (10.11.), M6 öffentlich live seit 11.11. (inkl. Websuche 12.11., Theme 14.11.) — Phase 1 (M6-R1 Deep Research im bestehenden Harness) abgenommen 14.11.; M7 offen; M8 (Phase 2: GPT Researcher hinter Identity-Aware Proxy, GNAI-023) produktiv live seit 22.11.2026 — M8-T5 Härtung/Abnahme offen **Referenzen:** [Projektstand](GNAI-000-DOC_Index.md), [Zielarchitektur](platform/llm-server/ai/GNAI-004-INFRA_Architecture.md), [Ansible-Plan](platform/llm-server/ai/GNAI-008-PLAN_Ansible-Deployment.md), [Modellbewertung](platform/llm-server/ai/GNAI-009-PLAN_Llama-Model-Evaluation.md), [`llama.cpp`-Sollkonfiguration](platform/llm-server/ai/GNAI-010-TECH_Llama-Serving.md) @@ -216,6 +216,20 @@ Nutzerakzeptanzprüfung auf dem Siegerprofil (GNAI-009 5.3) sowie der Lizenz-/Nutzungsrahmen-Nachweis (GNAI-009 10.4 — vor der externen Freigabe gefordert, als abgeschlossen noch nicht dokumentiert). +**Arbeitspaket M6-R1 — Deep Research im bestehenden Harness (Phase 1, +umgesetzt 14.11.2026, Details GNAI-022):** Recherche vom 14.11.2026 ergab, +dass kein zweiter Harness nötig ist, solange OpenWebUI selbst den +Research-Loop fährt: native agentic Web-Search ist produktiv (GNAI-020), +dazu eine Pipe-Function `gnai-deep-research` (iterativer +plan→search→fetch→synthesize-Loop mit zitiertem Markdown-Report), geseeded +per `open_webui`-Rolle in `webui.db` (sha256-gepinnt, idempotent, public read +grant, Valves `SEARXNG_URL=http://searxng:8080`, Engine direkt via +`http://llama-cpp:8080/v1`). Verifikation 14.11.: `webui.yml` produktiver Lauf +`ok=35 changed=3 failed=0`, DB-Verify PIPE-OK, Health 200, zweiter Lauf +`changed=0`. **Abnahme:** Function aktiv und im Model-Selector sichtbar +(erfüllt); E2E-Research-Lauf via API mit Quellen durch den Betreiber mit +temporärem API-Key noch offen (GNAI-022 Abschnitt 5). + **Ergebnis:** Genau ein klar definierter, authentifizierter Nutzerpfad ist öffentlich nutzbar; Backend- und Managementports bleiben intern. @@ -244,6 +258,42 @@ LLM-Betrieb nicht. und unter gleichzeitiger Inferenzlast testen; - erst danach Zeitplan, Queue, Benachrichtigung und Nutzer-SOP freigeben. +### Meilenstein 8 – Zweiten Research-Harness hinter Identity-Aware Proxy (Phase 2) + +**Status: M8-T1..T4 umgesetzt und produktiv live seit 22.11.2026 (`https://research.ghostnet.selfhost.eu`, stabilisiert nach Live-Tests — Befunde in GNAI-023 Abschnitt 7); offen: M8-T5 (Fail2Ban-Jail + formale Abnahme GNAI-023 Abschnitt 4).** + +**Ergebnis:** GPT Researcher läuft als zweiter Harness auf `ghostnet-ki` im +Production-Netz (Engine via `http://llama-cpp:8080/v1`, LLM-Konfig über +`OPENAI_BASE_URL`), öffentlich nur über NPM hinter einem Identity-Aware +Proxy. + +- Harness-Wahl (Recherche 14.11., GNAI-023): GPT Researcher + (`assafelovic/gpt-researcher`, 30.683 Sterne, v3.8.0 09.11.2026, + Apache-2.0) — reiner Research-Agent, llama.cpp über custom + `OPENAI_BASE_URL` (dokumentiert), Websuche über die bestehende + SearXNG-Instanz (custom retriever, kein externer API-Key). DeerFlow + (85.330 Sterne) bleibt Alternative für Multi-Agent/Sandboxes, ist aber + kein reiner Research-Harness und hat kein natives Keycloak-OIDC-Setup so + direkt wie der IAP-Pfad unten. +- Identity-Aware Proxy: **oauth2-proxy v7.15.5** (provider `oidc` / + `keycloak-oidc` gegen Keycloak Realm Ghost.net) hinter NPM (CT 103) via + nginx `auth_request`-Subrequest (`/oauth2/auth`, 202 = erlaubt); NPM-vHost + `research.ghostnet.selfhost.eu` mit Custom-Config (Advanced) für + `auth_request` + interne `location /oauth2/`. oauth2-proxy selbst ohne + öffentlichen Port (eigenes Podman-Netz auf CT 103 oder eigener LXC). +- Härtung (GNAI-023 Abschnitt 4): cookie-secret 32B random, cookie-secure/ + httponly/samesite, PKCE (v7 default), `--email-domain`/`--whitelist-domain`, + Gruppen/Rollen aus Keycloak-claim (`--allowed-group` + + `--oidc-groups-claim`), skip-auth nur für `/ping`/ACME, internes TLS bzw. + loopback-only, Secrets als Podman-Secrets, Fail2Ban-Jail auf oauth2-proxy- + Logs, Session-Store, Rate-Limits, 2FA-Pflicht im Keycloak-Realm. +- Abnahme: unauth 302→Keycloak, auth 200, Backend-Ports von außen geblockt, + Gruppen-Negativtest, Logout, Idempotenz. + +**Fertig, wenn:** GPT Researcher hinter dem IAP produktiv erreichbar ist, +Keycloak-Gruppen die Nutzung steuern und Negativtests (direkte IP/Port, +Bypass-Header) scheitern. + ### Stand 14.11.2026 - **M1 weitgehend geschlossen (10.11.2026):** Fail2Ban-Funktionsabnahme, @@ -280,6 +330,18 @@ LLM-Betrieb nicht. SMB-Output-Pickup als geschlossener Ablauf, Lasttest unter Inferenzlast (GNENC-000 „Noch offen“). +### Stand 22.11.2026 + +- **M8 Phase 2 produktiv (GNAI-023):** GPT Researcher hinter IAP + (oauth2-proxy + NPM auth_request + Keycloak-OIDC) live auf + `https://research.ghostnet.selfhost.eu`; M8-T1..T4 umgesetzt, nach + Live-Tests stabilisiert (SearXNG-Shim mit `href`, CPU-Embedding-Sidecar + `llama-cpp-embed`, `/outputs/`-Download-Routing, weasyprint-PDF, + `enable_thinking=false` gegen leere Reports). E2E: Research-Lauf mit + Quellen, Report als md/docx/pdf mit Inhalt; alle Playbooks idempotent + (`changed=0`). **Offen M8-T5:** Fail2Ban-Jail auf oauth2-proxy-Logs, + formale Abnahme der Härtungs-Checkliste (GNAI-023 Abschnitt 4). + ## 4. Bewusst nicht Teil der nächsten Ausbaustufe - dynamischer `llama.cpp`-Router; diff --git a/docs/platform/llm-server/ai/GNAI-022-TECH_OpenWebUI-DeepResearch.md b/docs/platform/llm-server/ai/GNAI-022-TECH_OpenWebUI-DeepResearch.md new file mode 100644 index 0000000..751eaef --- /dev/null +++ b/docs/platform/llm-server/ai/GNAI-022-TECH_OpenWebUI-DeepResearch.md @@ -0,0 +1,192 @@ +# Technischer Arbeitsentwurf + +**Dokumenten-ID:** GNAI-022-TECH +**Titel:** Deep Research im bestehenden OpenWebUI-Harness (Roadmap Phase 1, M6-R1) +**Stand:** 2026-11-14 +**Status:** deployt und verifiziert (Playbook ok, Idempotenz `changed=0`, DB-Verify PIPE-OK, Health 200); UI-Abnahme durch den Betreiber 14.11. (Seite lädt, Model-Selector „Deep Research“ + „Qwen 3.8 27B (Swift 1.5)" als Default, Branding/Favicon live); formaler E2E-Research-Lauf via API mit temporärem Key weiterhin als Nachweis offen (Abschnitt 5) +**Referenzen:** [Roadmap M6/M6-R1](../../../GNAI-001-PLAN_Project-Roadmap.md), [DOC-Index](../../../GNAI-000-DOC_Index.md), [GNAI-020](GNAI-020-TECH_OpenWebUI-WebSearch.md) (Websuche/SearXNG), Rolle `llm-server/llm/ansible/roles/open_webui/` (README, `files/gnai-deep-research-pipe.py`), OpenWebUI v0.13.3 (digest-gepinnt), OpenWebUI docs (Pipe Function, Reserved Arguments, Stand 2026-11-14) + +> Dieses Dokument beschreibt, warum Phase 1 **ohne zweiten Harness** +auskommt, wie die Pipe-Function `gnai-deep-research` aufgebaut ist und wie +sie betrieben/verifiziert wird. + +--- + +## Änderungsverlauf + +| Datum | Version | Autor | Beschreibung | +| --- | --- | --- | --- | +| 2026-11-14 | 0.1 | spektr / Mistral Vibe | Erstfassung: Recherche-Ergebnis, Pipe-Implementierung, Deployment, Verifikation, Betriebs-Hinweise | + +--- + +## 1. Entscheidung (Betreiber, 14.11.2026) + +Ein zweiter Harness (DeerFlow, GPT Researcher, Vane) wird für ausführliche +Recherchen **nicht** zusätzlich betrieben, solange OpenWebUI den Research-Loop +selbst fährt. Phase 1 = OpenWebUI-native Agentic Web Search (bereits produktiv, +GNAI-020) plus eine dedizierte Pipe-Function für iterative Deep Research. +Phase 2 (GPT Researcher hinter Identity-Aware Proxy) ist als M8 separat +geplant (GNAI-023). + +## 2. Recherche-Ergebnis (14.11.2026) + +Marktübersicht Deep-Research-Harnesses (GitHub API 14.11.2026, Reddit +r/LocalLLaMA/r/selfhosted, Vergleichsartikel Okt–Nov 2026): + +- **DeerFlow** (bytedance) 85.330 Sterne, #1 GitHub Trending 28.02.2026 — + Super-Agent-Harness (Sub-Agenten, Memory, Sandboxes, Skills); Research nur + ein Skill; empfiehlt Cloud-Frontier-Modelle; OIDC vorhanden, llama.cpp als + custom Provider möglich (dokumentiertes Qwen3.8-27B-llama.cpp-Setup). +- **GPT Researcher** 30.683 Sterne, v3.8.0 (09.11.2026), Apache-2.0 — reiner + Research-Agent, llama.cpp via custom `OPENAI_BASE_URL`; kein natives + Keycloak-OIDC (eigener Login) → IAP nötig (Phase 2, GNAI-023). +- **Vane** (ex-Perplexica, umbenannt 03/2026) ~36.700 Sterne — Answer-Engine, + SearXNG gebundled, aber OSS single-user ohne Keycloak-SSO. +- **AnythingLLM** 67.691 Sterne — Chat/RAG-Workspace, OSS **ohne** echtes OIDC + (nur Simple-SSO-Passthrough; Keycloak nur Enterprise-Lizenz). +- **LibreChat** 45.200 Sterne — Chat-UI, Keycloak-OIDC dokumentiert, aber + kein Research-Harness. +- Archiviert/gefroren: `langchain-ai/open_deep_research` (archiviert + 21.08.2026), STORM (main seit 30.09.2025 gefroren). +- Community-Option in OpenWebUI: Function „Iterative Deep Research" + (openwebui.com, OWUI v0.11+, braucht SearXNG) — openwebui.com war am + 14.11.2026 im System-Upgrade nicht erreichbar und der Code ist nicht auf + GitHub gespiegelt; daher **eigene, auditierbare Pipe** (Abschnitt 3). + +OpenWebUI selbst deckt den Research-Loop bereits ab: v0.13.3 mit Native +Agentic Web Search (`search_web`/`fetch_url`, produktiv seit 12.11.2026, +GNAI-020) und Pipe-Functions als eigene „Modelle" im Selector. + +## 3. Implementierung: Pipe `gnai-deep-research` + +Datei: `llm-server/llm/ansible/roles/open_webui/files/gnai-deep-research-pipe.py`, +Content per sha256 gepinnt (`open_webui_deep_research_pipe_sha256`, nach jeder +Code-Änderung neu berechnen). Die Rolle seedet die Function idempotent per +sqlite in `webui.db` (Tabelle `function`: type `pipe`, `is_active=1`, +`is_global=0`, Valves als JSON) und setzt einen public read `access_grant` +(resource_type `model`, principal `user`/`*`) — dadurch erscheint +`gnai-deep-research` im Model-Selector jedes authentifizierten OIDC-Users. + +Loop (Valves konfigurierbar, Defaults in `defaults/main.yml`): + +1. **Planen:** Engine-Call (direkt `POST {ENGINE_BASE_URL}/chat/completions`, + `ENGINE_BASE_URL=http://llama-cpp:8080/v1`, `ENGINE_MODEL_ID` = + Production-Profil) mit Planner-Prompt → JSON `{"queries": [...]}`. +2. **Suchen:** SearXNG `GET {SEARXNG_URL}/search?q=…&format=json` + (`SEARXNG_URL=http://searxng:8080`, die kuratierte Instanz aus GNAI-020). +3. **Fetchen:** Top-Seiten per httpx, **SSRF-Guard** (nur http(s), DNS + auflösen und private/loopback/link-local/reserved IPs verwerfen), + Redirect-Chain max. 3 Hops mit Re-Validierung, Content-Type-Prüfung, + Content-Cap (`FETCH_MAX_BYTES`), Timeout (`FETCH_TIMEOUT_S`). +4. **Synthetisieren:** Engine bewertet Fundstellen → JSON + `{"status":"continue","next_queries":[…]}` oder + `{"status":"done","report":"…"}`; Zitationen als `[n]`, Quellenliste wird + von der Pipe deterministisch angehängt. Abbruch nach `MAX_ITERATIONS` + mit Best-possible-Report. +5. **Streaming:** `__event_emitter__`-Statusmeldungen pro Runde; bei + `stream:false` eine Gesamtresponse. + +Keine externen API-Keys, keine Secrets im Code; `__user__`/`__metadata__` +nach OWUI-v0.13.3 Reserved-Args (`user_prompt` lesen, History cappen). + +## 4. Deployment-Verifikation (14.11.2026, Production-Inventar) + +- `webui.yml --check --diff`: sauber. +- Produktiver Lauf als `ansible-deploy`: `ok=35 changed=3 failed=0` + (Pipe-Sync `CHANGED`, Unit-Restart, Staging); Health `/health` 200; + Engine-Model-List aus dem Container ok. +- DB-Verify im Playbook: `PIPE-OK` (function row type=pipe active, Valves mit + SEARXNG_URL, public read grant vorhanden); sha256-Verify gegen Pin ok. +- Idempotenz: zweiter Lauf `ok=33 changed=0`. +- Read-only gegen `ghostnet-ki` (ghost-agent): Health über `10.0.0.90:8081` + bestätigt (Playbook-uri), Container/Unit aktiv. + +## 5. Betrieb und E2E-Abnahme + +- **UI (Browser, OIDC):** Model-Selector → `Deep Research (gnai)` + (`gnai-deep-research`) wählen, Frage stellen; Statusmeldungen streamen, + Report mit Quellenliste. **Sichtbarkeit (Befund 14.11.):** Pipe-Functions + ohne eigenen `model`-Tabelleneintrag sind admin-only — die Rolle seedet + daher zusätzlich eine `model`-Row (id = function id, name + „Deep Research (gnai)") + public read grant; ohne beides sieht nur der + Admin die Pipe im Selector. +- **Branding (GNAI-021, persistent nachgezogen 14.11.):** Favicons + + `custom.css`-Theme liegen in `roles/open_webui/files/branding/`, werden + nach `open_webui_favicon_dir` / `open_webui_theme_dir` deployt und per ro-Mount in + `/app/backend/open_webui/static/` **und** `/app/build/favicon.png` + gemountet (v0.13.3: index.html lädt `/static/*` aus dem Backend-static, + die Root-Route `/favicon.png` aus dem Build-Dir). Verifiziert von außen: + `/favicon.png` und `/static/favicon.png` md5 `78966788…` (Geist), + `/static/custom.css` 200 mit 5311 B. +- **API:** `POST /api/chat/completions` mit `"model": "gnai-deep-research"`. +- **E2E-Betreiberschritt (noch offen, analog GNAI-020 Abschnitt 4e/g):** + temporären API-Key im Admin-UI anlegen (`auth.enable_api_keys` temporär + true), dann z. B. + `curl -X POST https://chat.ghostnet.selfhost.eu/api/chat/completions -H "Authorization: Bearer sk-…" -d '{"model":"gnai-deep-research","messages":[{"role":"user","content":"…"}],"stream":false}'`, + Report auf Quellen prüfen; danach Test-Chat löschen, Key entfernen, + `auth.enable_api_keys` wieder false. NPM-Proxy-Timeouts 600 s auf + `chat.*` sind seit 12.11. gesetzt (GNAI-020 Abschnitt 6) — lange + Research-Loops sind damit abgedeckt. +- Rate-Limit-Doku und LLM-Metriken im Monitoring bleiben M6-Restpunkte + (GNAI-001 M6). + +## 5a. Befunde aus dem ersten Live-Test (14.11.2026) + +- **Fehler `"queries"` in der Pipe:** die Prompts enthielten JSON-Beispiele + (`{"queries": …}`) und wurden per `str.format()` gerendert — die Braces + kollidierten mit Format-Feldern (KeyError). Fix: `.replace("{qpr}", …)`; + neuer sha256-Pin `5ddb6191…`. Non-Streaming-Pfad fängt Exceptions jetzt ab + und meldet sie als Text. +- **HTTP 500 `GET /ollama/api/version` beim Öffnen der Modellliste:** v0.13.3 + ruft den Ollama-Endpoint mit `ENABLE_OLLAMA_API=True` (Default) — ohne + Ollama auf dem Host 500. Fix: `ENABLE_OLLAMA_API=False` in `open_webui_env`. +- Verifiziert nach Redeploy: function-Content in DB sha256 `5ddb6191…`, + `ENABLE_OLLAMA_API=False` im Container, Playbook idempotent `changed=0`. +- **„Verbindung zum Server fehlgeschlagen“ nach 2 Research-Runden (14.11.):** + Ursache war **kein** voller Kontext (die Pipe cappt History auf 8 Messages + und Seiten-Texte selbst), sondern unbegrenztes `max_tokens`: das + Production-Profil läuft mit `xhigh` Reasoning und `n_predict=32768` — eine + Synthese-Antwort lief bis zum Server-Cap, der Stream war minutenlang stumm + und der NPM `proxy_read_timeout` (600 s auf `chat.*`, GNAI-020 §6) brach + die Verbindung ab. Fix: `max_tokens` pro Engine-Call in der Pipe + (Valve `MAX_TOKENS`, default 4096; HTTP-Timeout daran gekoppelt), Fetches + parallel via `asyncio.gather`, Status-Heartbeat vor jedem Engine-Call + (hält den SSE-Stream aktiv). Neuer sha256-Pin `45cb3be0…`, Valves + `MAX_TOKENS`/`PAGE_TEXT_CHARS` in DB verifiziert. Hinweis: Im Pipe-Modus + sieht man das Thinking des Modells nicht (by design — die Pipe streamt nur + Status + Report); Token-Usage steht in der API-Response unter `usage`. +- **Ollama-500 trotz `ENABLE_OLLAMA_API=False` (14.11.):** in v0.13.3 schlägt + die persistierte DB-Config (`ollama.enable=true`, beim ersten Start aus dem + Env geseeded) das Env — Fix: DB-Key `ollama.enable=false` im Config-Sync. +- **Model-Namen/Default (14.11.):** `model.name` bzw. `function.name` sind + reine Anzeigenamen (id bleibt stabil für Grants/API): Engine-Modell heißt + „Qwen 3.8 27B (Swift 1.5)", die Pipe „Deep Research"; Default im Picker + über `ui.default_models` (+ `DEFAULT_MODELS`-Env). **Befund:** + `ui.default_models` muss ein **komma-getrennter String** sein — als JSON-Liste + stürzt Chat.svelte mit `default_models.split is not a function` ab + (unendlicher Spinner). Korrekt: `"swift-1.5-qwen3.8-27b-q6k"`. +- Source-Map-Fehler und 403 auf `/api/v1/channels/` in der Konsole sind + kosmetisch/Berechtigungs-Hinweise und blockieren nicht. +- **Console-Warning `svelte.dev/e/derived_inert`:** kosmetisch, kommt aus + OpenWebUI v0.13.3 selbst (Upstream), kein Handlungsbedarf. + +## 6. Sicherheit + +- Pipe-Code läuft serverseitig in OpenWebUI (OWUI-Warnung: Functions sind + arbitrary Python — daher sha256-Pin, Review vor Änderung, nur Admin legt + Functions an). +- SSRF-Guard siehe Abschnitt 3; SearXNG/Engine werden nicht über den Guard + gefiltert (interne Aliase), nur externe Fetches. +- Keine Secrets in Code/Valves/Repo; Ingress unverändert: `10.0.0.90:8081` + nur von NPM, öffentlich nur `chat.ghostnet.selfhost.eu` mit Keycloak-OIDC. + +## 7. Offen + +1. E2E-Research-Lauf durch den Betreiber (Abschnitt 5). +2. Qualität des 27B-Produktionsprofils (Swift 1.5 Q6_K) im langen Research-Loop + gegen Frontier — Nutzerakzeptanz (GNAI-009 5.3) mitnehmen. +3. Option: später Community-Function „Iterative Deep Research" (openwebui.com) + evaluieren, sobald die Community-API wieder erreichbar ist; eigene Pipe + bleibt Referenz. +4. Phase 2 (GPT Researcher + IAP) siehe GNAI-023. diff --git a/docs/platform/llm-server/ai/GNAI-023-PLAN_GPT-Researcher-IAP.md b/docs/platform/llm-server/ai/GNAI-023-PLAN_GPT-Researcher-IAP.md new file mode 100644 index 0000000..b72c459 --- /dev/null +++ b/docs/platform/llm-server/ai/GNAI-023-PLAN_GPT-Researcher-IAP.md @@ -0,0 +1,329 @@ +# Plan + +**Dokumenten-ID:** GNAI-023-PLAN +**Titel:** Phase 2 (M8): GPT Researcher hinter Identity-Aware Proxy — Machbarkeit, Sicherheit, Härtung +**Stand:** 2026-11-22 +**Status:** M8-T1..T4 umgesetzt, produktiv hinter dem IAP erreichbar (`https://research.ghostnet.selfhost.eu`, 22.11.2026) und nach mehreren Live-Läufen stabilisiert (Abschnitt 7); offen: M8-T5 (Fail2Ban-Jail + formale Abnahme-Checkliste Abschnitt 4) +**Referenzen:** [Roadmap M8](../../../GNAI-001-PLAN_Project-Roadmap.md), [DOC-Index](../../../GNAI-000-DOC_Index.md), [GNAI-006](../../proxmox-server/lxc/ct-103-reverse-proxy/GNAI-006-SEC_Reverse-Proxy.md) (NPM CT 103), [GNAI-016](../../proxmox-server/lxc/ct-102-keycloak/GNAI-016-PLAN_Keycloak-Ansible-Rebuild.md) (Keycloak CT 102), [GNAI-022](GNAI-022-TECH_OpenWebUI-DeepResearch.md) (Phase 1), oauth2-proxy docs v7.15.x, NPM docs, GPT Researcher docs (Stand 14.11.2026) + +> Dieses Dokument fasst die Recherche vom 14.11.2026 zusammen und legt die +> geplante Architektur für einen zweiten Research-Harness hinter einem +> Identity-Aware Proxy fest. Es ist Planungsstand, noch keine +> Installationsanleitung. + +--- + +## 1. Zielbild + +``` +Internet → NPM (CT 103, 443) → auth_request-Subrequest an oauth2-proxy + → bei 202: proxy_pass an GPT Researcher (ghostnet-ki, LAN-Port nur von NPM) + → bei 401/403: 302 zu Keycloak-OIDC (Realm Ghost.net, Client gnai-research) +``` + +- Harness: **GPT Researcher** (`assafelovic/gpt-researcher`, 30.683 Sterne, + v3.8.0 vom 09.11.2026, Apache-2.0) auf `ghostnet-ki` im Production-Netz + (neues Quadlet-Set, Rolle `gpt_researcher` unter `llm-server/llm/ansible/`). +- LLM: bestehende Engine via `OPENAI_BASE_URL=http://llama-cpp:8080/v1` + (llama.cpp, kein Auth — Container-intern), `OPENAI_API_KEY` = Placeholder; + `FAST_LLM`/`SMART_LLM` = Production-Profil-Alias. Custom OpenAI-compatible + Endpoints werden von GPT Researcher unterstützt (dokumentiert; externe + Praxistests 2026 bestätigen llama.cpp-Anbindung über `OPENAI_BASE_URL`). +- Websuche: bestehende SearXNG-Instanz (GNAI-020) als custom retriever — + kein externer Search-API-Key; Fallback DuckDuckGo (keyless). +- Ingress: `research.ghostnet.selfhost.eu` (Split-DNS CT 100 → 10.0.0.10, + NPM-vHost → `10.0.0.90:`), abgesichert durch oauth2-proxy. + +## 2. Machbarkeit Identity-Aware Proxy hinter NPM + +**Ja, mit oauth2-proxy v7.15.5 (aktuell 2026) + nginx `auth_request`:** + +- oauth2-proxy stellt `/oauth2/auth` bereit: Subrequest antwortet **202** bei + gültiger Session, **401/403** sonst — genau das nginx-`auth_request`-Modul. +- NPM (2.15.1, OpenResty) erlaubt pro Proxy-Host im **Advanced**-Tab arbitrary + nginx-Snippet; dort wird eingebaut: + ```nginx + location /oauth2/ { internal; proxy_pass http://:4180; ... } + location / { auth_request /oauth2/auth; error_page 401 =302 https://auth…/login…; + proxy_pass http://10.0.0.90:; ... } + location = /oauth2/auth { internal; proxy_pass …; proxy_pass_request_body off; + proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; } + ``` + (exaktes Snippet beim Rollout gegen oauth2-proxy-docs prüfen). +- oauth2-proxy selbst **ohne** öffentlichen Port: eigenes Podman-Netz auf + CT 103 (nur NPM-Container dürfen es erreichen) oder eigener kleiner LXC + (z. B. CT 117) — Entscheidung beim Rollout; Trennung vom NPM-Container ist + die härtere Variante (CT 117 empfohlen). +- Keycloak: oauth2-proxy v7.15 unterstützt Provider `oidc` (issuer discovery) + und `keycloak-oidc`; Issuer + `https://auth.ghostnet.selfhost.eu/realms/Ghost.net`. Keycloak-Client + `gnai-research` (confidential; Secret als Podman-Secret, nie in Git), + Redirect-URI `https://research.ghostnet.selfhost.eu/oauth2/callback`, + Scopes `openid email profile groups`. +- Alternativen geprüft und verworfen: **Authelia** (eigener IdP + 2FA; + überdimensioniert, da Keycloak bereits IdP ist), **Pomerium** (Zero-Trust- + Gateway, eigener IdP-Fokus), AnythingLLM/Vane (kein OSS-Keycloak), DeerFlow + (Harness statt IAP; OIDC vorhanden, aber als zweiter Harness mit eigener + Auth-Domäne ungünstiger als IAP vor einem beliebigen Backend). + +## 3. Sicherheitsmodell + +- **Vertrauensanker ist Keycloak, nicht der Client:** oauth2-proxy validiert + Session serverseitig (signiertes/verschlüsseltes Cookie oder Redis-Session); + `auth_request` prüft serverseitig — ein von außen gefälschter + `X-Forwarded-User`-Header ist wirkungslos, weil oauth2-proxy nur seinem + eigenen Cookie vertraut und `--reverse-proxy=true` nur hinter dem internen + NPM erreichbar ist. +- **Gruppen/Rollen:** Keycloak-Realm-Rollen per Mapper auf den `groups`-Claim + legen; oauth2-proxy `--oidc-groups-claim=groups` + + `--allowed-group=gnai-research-user` (Realm-Rolle anlegen, User zuweisen). + Negativtest: User ohne Rolle → 403. +- **Registrierung/Whitelist:** `--email-domain` (oder `--allowed-email`), + `--whitelist-domain=.ghostnet.selfhost.eu`, `--skip-provider-button`. +- **Session-Härtung:** `--cookie-secret` (32 B random, Podman-Secret), + `--cookie-secure=true`, `--cookie-httponly=true`, `--cookie-samesite=lax` + (auth_request-Flow braucht Lax), Cookie-Name mit `__Host-`-Präfix wo + möglich, `--cookie-expire`/`--cookie-refresh` begrenzen, optional Redis- + Session-Store für Multi-Replica. +- **Flow-Härtung:** PKCE (v7 default), CSRF-State-Cookie, `--skip-auth-regex` + nur für `^/ping$` und ACME-Pfade, kein Open Redirect (redirect-URL strikt + auf die eigene Domain), `--pass-access-token=false` unless GPT Researcher + ihn braucht, `--set-xauthrequest` nur wenn das Backend X-User/X-Email + auswerten soll. +- **Transport:** oauth2-proxy nur auf loopback/internem Netz; NPM→oauth2- + proxy über Podman-Netz Klartext ok (intern), Client→NPM TLS (LE). +- **Logging/Monitoring:** oauth2-proxy-Logs (auth failures) in Loki + (GNMON), Fail2Ban-Jail auf CT 103 für wiederholte 401/403 auf + `/oauth2/start`, Rate-Limit am IAP, Metriken-Endpunkt nur intern. +- **Backend-Härtung:** GPT-Researcher-Port auf `10.0.0.90` per + `gnmon_firewall`-Rolle nur von `10.0.0.10` (NPM) freigeben — direkter + LAN-Zugriff ohne IAP dann unmöglich; WAN-Scan muss den Port geblockt + zeigen. 2FA-Pflicht im Keycloak-Realm (required action) für die + research-Rolle. + +## 4. Härtungs-Checkliste für den Rollout (Abnahme) + +1. unauth Request auf `research.ghostnet.selfhost.eu` → 302 zu Keycloak + (nicht 200/502). +2. auth Request (Keycloak-Login, Rolle `gnai-research-user`) → 200. +3. User ohne Rolle → 403 (Gruppen-Negativtest). +4. Direkter Zugriff auf `10.0.0.90:` vom LAN (ohne NPM) → geblockt + (nftables); vom WAN → geblockt (Port nicht offen). +5. Gefälschte `X-Forwarded-User`/`X-Forwarded-Email`-Header von außen → + keine Auth-Bypass (auth_request gewinnt). +6. `/oauth2/sign_out` → Session invalidiert, erneuter Zugriff → 302. +7. Keycloak-Client-Secret als Podman-Secret; Secret-Scan (CI `secret-scan`) + grün; kein Secret in Git/Logs. +8. Fail2Ban-Jail greift bei wiederholten Fehl-Logins. +9. Idempotenz: Playbook zweiter Lauf `changed=0`; CT-103-Ansible-Drift + `changed=0`. +10. E2E: Research-Auftrag in GPT Researcher läuft gegen llama.cpp + + SearXNG, Report mit Quellen; NPM-Timeouts für lange Läufe gesetzt. + +## 5. Arbeitspakete (Stand 22.11.2026: M8-T1..T4 umgesetzt, produktiv und stabilisiert; M8-T5 Haertung/Abnahme offen) + +| # | Paket | Ziel | Wo | +| --- | --- | --- | --- | +| M8-T1 | Keycloak-Objekte **idempotent per Ansible** (Rolle `keycloak_realm_config` im CT-102-Projekt, Admin-REST-API via Service Account). **Einmaliger Bootstrap (Operator, Admin-UI `https://auth.ghostnet.selfhost.eu`, Realm-Dropdown = `Ghost.net`):** Clients → Create client: ID `ansible-keycloak-admin`, publicClient OFF, **Service accounts roles ON**, Standard flow OFF; Service account roles → **Assign role** → `realm-management`: `manage-realm`, `manage-clients`, `manage-users`, `view-users` (Fallback: Users → `service-account-ansible-keycloak-admin` → Role mapping → Assign role → realm-management); Credentials → Secret kopieren; auf CT 102: `install -d -m 0700 /etc/keycloak-ansible && install -m 0600 /dev/null /etc/keycloak-ansible/client_secret` und Secret eintragen (nie in Git/Chat). **Danach alles per Playbook:** `cd proxmox/lxc/ct-102-keycloak/ansible && ansible-playbook -i inventories/production playbooks/site.yml` — synct Realm-Rolle `gnai-research-user`, Client `gnai-research` (confidential, Standard flow only, Redirect `https://research.ghostnet.selfhost.eu/oauth2/callback`, Web Origin `https://research.ghostnet.selfhost.eu`, post-logout `https://research.ghostnet.selfhost.eu/*`), Mapper `realm-roles-to-groups` (dedicated scope, Claim `groups`, in ID/access token + userinfo) und Role-Mapping für `ghost`; zweiter Lauf `changed=0`. Spec in `roles/keycloak_realm_config/defaults/main.yml`, Doku im Rollen-README. **Test nach M8-T3:** `curl -sI https://research.ghostnet.selfhost.eu/` → 302 zu `auth.ghostnet.selfhost.eu/...login...client_id=gnai-research`. | CT 102 (Bootstrap einmalig UI + Secret-Datei, danach site.yml) | Keycloak | +| M8-T2 | oauth2-proxy v7.15.5 (quay.io, digest-gepinnt) als Quadlet auf CT 103 in eigenem Podman-Netz mit NPM, **kein** publish; Env: provider `oidc`, issuer, client-id/secret + cookie-secret als Podman-Secrets, `--email-domain`, `--whitelist-domain=.ghostnet.selfhost.eu`, `--allowed-group=gnai-research-user`, `--oidc-groups-claim=groups`, `--skip-auth-regex=^/ping$`, `--reverse-proxy=true`, `--set-xauthrequest` | CT 103, Rolle im CT-103-Ansible-Projekt | IAP | +| M8-T3 | NPM-vHost `research.ghostnet.selfhost.eu` (LE-TLS, Force SSL) mit Advanced-Snippet `auth_request /oauth2/auth` + interne `location /oauth2/`; Split-DNS-Record auf CT 100; NPM-API via CT-103-Ansible | CT 103 + CT 100 | Ingress | +| M8-T4 | GPT Researcher (digest-gepinnt) als Quadlet auf `ghostnet-ki` im Production-Netz, Port `10.0.0.90:8085` (Firewall: nur NPM); Env: `OPENAI_BASE_URL=http://llama-cpp:8080/v1`, `OPENAI_API_KEY`=Placeholder-Secret, `FAST_LLM`/`SMART_LLM`=Production-Alias, Search via SearXNG (custom retriever, `SEARXNG_URL=http://searxng:8080`) | `llm-server/llm/ansible` (neue Rolle `gpt_researcher`, Playbook `research.yml`) | Harness | +| M8-T5 | Härtung + Abnahme: Fail2Ban-Jail auf oauth2-proxy-Logs (CT 103), 10-Punkte-Checkliste Abschnitt 4, Idempotenz `changed=0`, WAN-Negativtest (Port nicht offen) | CT 103 / ghostnet-ki | Verifikation | + +## 6. Offene Entscheidungen vor dem Rollout + +- oauth2-proxy-Platzierung: Podman-Netz auf CT 103 vs. eigener LXC CT 117 + (Empfehlung: CT 117, sauberere Fehlerdomäne). +- NPM-vHost + auth_request-Snippet per CT-103-Ansible automatisieren oder + Betreiber-Schritt (Vorschlag: Ansible, damit `verify-production` greift). +- GPT-Researcher-Port und Ressourcen-Limits (CPU/RAM, parallel zur Engine + exklusiv — gleicher Host, Wartungsfenster beachten). +- Ob DeerFlow später als dritter Harness mit Sandboxes ergänzt wird + (Community-Favorit), hängt von den Erfahrungen mit GPT Researcher ab. + +## 7. Belegter Stand 17.11.2026 + +- **M8-T1 (Keycloak, idempotent via Ansible):** Rolle `keycloak_realm_config` im + CT-102-Projekt; `site.yml` ok=103 changed=0 (idempotent). Verifiziert per + Admin-API: Realm-Rolle `gnai-research-user`, Client `gnai-research` + (confidential, standard flow only, direct grants OFF, redirect + `https://research.ghostnet.selfhost.eu/oauth2/callback`, web origin gesetzt), + Mapper `realm-roles-to-groups` auf dem realm-weiten `roles`-Scope + (KC26: `/clients/{id}/client-scopes` ist 404 — Mapper liegt auf `roles`), + Claim `groups` in ID/access token + userinfo; `ghost` hat die Rolle. + Befunde: Keycloak hört auf `10.0.0.4:8080` (nicht loopback); Client-`attributes` + enthalten KC-Defaults (Drift-Vergleich nur eigene Keys). +- **M8-T2 (oauth2-proxy auf CT 103):** Rolle `reverse_proxy_oauth2proxy`, + Image `quay.io/oauth2-proxy/oauth2-proxy@sha256:0d989b27…` (v7.15.5), + `site.yml` idempotent changed=0. Verifiziert: `/ping` 200 auf 127.0.0.1:4180, + `/oauth2/auth` ohne Session 401, LAN 10.0.0.10:4180 geblockt (000), + `/oauth2/start` → 302 zu Keycloak mit `client_id=gnai-research`, + `scope=openid+email+profile+groups`. Befunde: Quadlet-`Environment` mit + Leerzeichen braucht Quotes; cookie-secret als base64(24B)=32 Zeichen + (v7.15 prüft Stringlänge); `systemctl is-active` rc=4 wenn Unit noch nicht + geladen. Client-Secret als Podman-Secret `oauth2-proxy-client-secret` + (aus Keycloak-API via Bootstrap-Token gelesen, nie in Logs/Git). + +- **M8-T3 (NPM vHost, 18.11.):** Rolle `reverse_proxy_research_vhost` (NPM-API + 127.0.0.1:81, idempotent). LE-Cert `npm-22` (Let's Encrypt), Proxy-Host id 16 + `research.ghostnet.selfhost.eu → 10.0.0.90:8085`, ssl_forced/hsts/http2/block_exploits/ws. + Befunde: NPM 2.15.1 cert-`meta` leer lassen (400 bei letsencrypt_email); + PUT proxy-host nur mit Soll-Feldern (400 sonst); **auth_request/error_page + gehören in eine Custom Location `/` (locations-Array mit eigenem + advanced_config), NICHT in den host-level advanced tab** — sonst 401 ohne + Redirect. Split-DNS live (`dig @10.0.0.14` → 10.0.0.10). E2E: `curl -sI + https://research.ghostnet.selfhost.eu/` → 302 zu Keycloak + (`client_id=gnai-research`, scope openid+email+profile+groups). NPM-Admin-Creds + als `/etc/nginx-proxy-manager/api.env` (0600). + +- **M8-T4 (GPT Researcher auf ghostnet-ki, 18.11.):** Rolle `gpt_researcher`, + Playbook `research.yml`. Images `gptresearcher/gpt-researcher` + + `gptresearcher/gptr-nextjs` (nur `latest` publiziert) digest-gepinnt: + backend `sha256:8e0975ec…`, frontend `sha256:69e7e2fa…`. Backend + `10.0.0.90:8086` (FastAPI), Frontend `10.0.0.90:8085` (NextJS), beide nur + von NPM (Firewall `gnmon_firewall_npm_only_ports` += 8085, 8086). LLM via + `OPENAI_BASE_URL=http://llama-cpp:8080/v1`, FAST/SMART/STRATEGIC_LLM = + Production-Alias; Retriever duckduckgo (keyless). Befunde: `User=root` + nötig (sonst PermissionError logs/app.log), Verify ohne curl (python3), + Unit-Start mit is-active-Check (idempotent `changed=0`). NPM-vHost: Location + `/` → 8085, `/api` → 8086 (600 s Timeouts), beide mit auth_request. + E2E: `research/` und `research/api/docs` unauth → 302 Keycloak; Backend + `/docs` 200 via NPM; 8086 von außen geblockt. + +- **Befund 18.11. (invalid_scope):** oauth2-proxy scope darf kein `groups` + enthalten — Keycloak lehnt unbekannte Scopes ab (`invalid_scope`); der + `groups`-Claim kommt über den `roles`-Scope-Mapper ins Token. Scope jetzt + `openid email profile` (Redirect verifiziert: `scope=openid+email+profile`). + +- **Befund 18.11. (502 auf /oauth2/callback):** `upstream sent too big header` + — der IAP-302 trägt ein großes Set-Cookie (Session mit id/access/refresh + token); nginx-Default-Puffer (4k/8k) reichen nicht. Fix: `proxy_buffer_size + 32k; proxy_buffers 8 32k; proxy_busy_buffers_size 64k` in `location /oauth2/` + (derselbe Befund wie GNMON-000 M6 am mon-Host). Nach Fix idempotent deployt. + +- **Befund 18.11. (wss://…/ws schlägt fehl):** NPM-Custom-Locations bekommen + die WebSocket-Upgrade-Header nicht automatisch — `location /ws` braucht + `proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade";` + lange Timeouts (3600 s) im eigenen + advanced_config. Verifiziert via NPM-API: locations `/`→8085, `/api`→8086, + `/ws`→8086 (upgrade: true, auth: true), host ws_upgrade=true, cert=22. + +- **Befund 19.11. (SSL_ERROR_UNRECOGNIZED_NAME_ALERT / 502 callback):** NPM + 2.15.1 generiert `proxy_host/.conf` nur zuverlässig, wenn die Config + komplett im host-level `advanced_config` steht (custom `locations` + + advanced_config zusammen, oder Locations mit eigenem advanced_config, + brechen die Generierung still — DB-Row existiert, conf fehlt → SNI alert). + Lösung: alles in advanced_config inkl. eigener `location /`, `/api/`, `/ws` + (NPM verzichtet dann auf seine generierte location /), `locations: []`; + Drift-Update via DELETE+POST (PUT löscht die conf ohne neu zu schreiben). + Verifiziert: 36.conf generiert, nginx -t ok, TLS CN=research, unauth /, + /api/docs, /ws → 302 Keycloak. + +- **Befund 19.11. (Retriever):** das publizierte gptr-Image lacks `duckduckgo-search` + (lib heißt 2026 `ddgs`) → Fehler beim DuckDuckGo-Retriever. Lösung: + `RETRIEVER=custom` + `RETRIEVER_ENDPOINT=http://gptr-searxng-shim:8099/` + gegen einen kleinen Shim-Container (`python:3.13-alpine`, Tag-Pin wegen + 404-bei-Digest-Pull, `files/searxng_shim.py`), der `?query=` auf SearXNG + `?q=&format=json` mappt und `[{href, url, raw_content}]` zurückgibt + („href“, weil v3.8 genau dieses Feld liest — siehe Befund unten). Shim läuft + ohne publish im LLM-Netz (Alias `gptr-searxng-shim`), ruft SearXNG im + Egress-Netz. Verifiziert: Shim-Query aus dem Backend-Container liefert + echte Ergebnisse; research.yml idempotent. + +- **Befund 20.11. (weiterhin 0 Quellen — Root Cause gefunden):** Retriever + war ok, aber gpt-researcher v3.8 baut die Scrape-Liste in + `skills/researcher.py::_search_relevant_source_urls` über + `url.get("href")` — liest also das Feld **„href“**, nicht „url“. Der Shim + lieferte nur `{"url", "raw_content"}` → alle Einträge `None` → nach + Dedup in `_get_new_urls` genau **1 URL** („Scraping content from 1 URLs“) + → Scraper-Crash `Error processing None: 'NoneType' ... endswith` + (`scraper.py` `link.endswith(".pdf")`) → „Scraped 0 pages“ → „No content + found“. Der Scraper selbst ist nicht kaputt; v3.8 nutzt `raw_content` + aus dem Retriever **nicht** zum Überspringen des Scrapens (nur v3.6 tat + das) — der Backend scrapt jede `href` selbst. +- **Fix 20.11.:** Shim liefert jetzt `{"href", "url", "raw_content"}` pro + Ergebnis und reicht nur selbst erfolgreich gefetchte Seiten (>100 chars + Text, `SHIM_MAX_RESULTS=8`, Cap 200k/Seite, Timeout 10 s) durch — das + Pre-Fetch filtert tote Links, bevor der gptr-Scraper sie abruft. + Zusätzlich `SCRAPER=bs` explizit gepinnt (v3.8-Default ist „bs“ = + requests+bs4, braucht keinen Browser im Image; Default-Pin schützt vor + künftigen Upstream-Wechseln auf browserbasierte Scraper). `RETRIEVERS` + (plural) bleibt zusätzlich gesetzt. Verifiziert im Backend-Container: + CustomRetriever → 8 Ergebnisse mit `href`, `Scraper(..., "bs")` → + **8/8 Seiten mit Inhalt** (1,9k–8k chars), kein None-Crash. + +- **Befund 20.11. (501 „does not support embeddings“ bei der Auswertung):** + gpt-researcher v3.8 rankt gescrapte Inhalte pro Sub-Query über Embeddings + (`ContextCompressor`/`EmbeddingsFilter` → `memory.get_embeddings()`), + default `EMBEDDING=openai:text-embedding-3-small` → POST + `OPENAI_BASE_URL/embeddings` → llama.cpp ohne `--embeddings` → 501. + v3.8 hat eine einzige `OPENAI_BASE_URL` für Chat-LLM UND Embeddings + (`utils/llm.py` und `memory/embeddings.py` lesen beide dieselbe Env) — + kein Env-Split möglich, `embedding_kwargs` ist fest `{}`. +- **Fix 20.11.:** dedizierter CPU-only llama.cpp-Sidecar + (`--embeddings`, Alias `llama-cpp-embed`, nur im Production-Netz, kein + publish) mit **nomic-embed-text-v2-moe Q8_0** (488 MiB, ~305M, SoTA + multilingual ~100 Sprachen — passend zu deutschen Queries; sha256-gepinnt + im `model_store`, Flag `model_store_include_embedding` nur in Production). + Backend-Env `EMBEDDING=custom:nomic-embed-text-v2-moe` + + `GNAI_EMBEDDING_BASE_URL=http://llama-cpp-embed:8080/v1`; ein per Volume + gemountetes `sitecustomize.py` (`files/sitecustomize_gnai.py`, im Image + nicht vorhanden) biegt nur `langchain_openai.OpenAIEmbeddings` auf die + Sidecar-URL um — Chat-Completions laufen unverändert auf `llama-cpp`. + CPU-only vermeidet VRAM-Konkurrenz mit der 27B-Engine. Verifiziert im + Backend-Container: `Memory("custom",…).get_embeddings().embed_query()` → + 768-dim Vektor über `llama-cpp-embed`, `OPENAI_BASE_URL` bleibt + `llama-cpp`. research.yml idempotent (changed=0). + +- **Befund 21.11. (Report-Download: „No pdf path provided“ / docx 404):** + zwei unabhängige Ursachen. (a) PDF: `write_md_to_pdf` nutzt `md2pdf` + (braucht playwright+chromium — im Image beides nicht installiert) → + Exception wird geschluckt, Rückgabe `""` → Frontend loggt „No pdf path + provided“ und rendert `href="#"` (Klick landet auf der Main Page). + (b) docx/md: Backend schreibt die Dateien nach `outputs/` und mountet + `/outputs` via StaticFiles, das gptr-nextjs-Frontend baut aber + same-origin-Links `outputs/` — die NPM-vHost leitete `/outputs/` + bisher an den FRONTEND-Container (location /) → 404. Zusätzlich + verdoppelt das Frontend das Präfix (`"outputs/" + output.pdf`, der + Backend-Pfad enthält `outputs/` bereits) → `outputs/outputs/...`. +- **Fix 21.11.:** (a) `sitecustomize_gnai.py` ersetzt `backend.utils. + write_md_to_pdf` durch eine weasyprint-Implementierung (mistune → HTML → + weasyprint 64.1, im Image vorhanden und funktionsfähig; CSS aus + `frontend/pdf_styles.css`). Verifiziert: `write_md_to_pdf('# Test…')` → + `outputs/verify_pdf.pdf`. (b) NPM-vHost um `location /outputs/` ergänzt + (auth_request + proxy auf Backend :8086 + `rewrite ^/outputs/outputs/ + (.*)$ /outputs/$1 break;` gegen das doppelte Präfix). Verifiziert: + NPM-API host research.* enthält den Block, `nginx -t` ok, unauth + `/outputs/test.md` → 302 Keycloak. research.yml + ct103 site.yml + idempotent (jeweils changed=0). + +- **Befund 22.11. (pdf/docx existieren, sind aber leer — md 0 Bytes):** die + Report-Generierung lieferte einen leeren String. Ursache: die Engine läuft + mit Reasoning (Profil `reasoning_effort xhigh`), und das clientseitige + `max_tokens` begrenzt Reasoning+Inhalt GEMEINSAM — bei großem Report-Prompt + verbrauchte das Denken das gesamte Budget (SMART_TOKEN_LIMIT=4000), der + sichtbare Content blieb leer (keine `report`-Events im JSON-Log, md 0 + Bytes, LLM-Call lief trotzdem 3,5 min). Reproduktion: `POST + /v1/chat/completions` mit `chat_template_kwargs.enable_thinking=false` + → 3 statt 97 Completion-Tokens, kein reasoning_content. +- **Fix 22.11.:** `sitecustomize_gnai.py` wrappt `create_chat_completion` + und injiziert `llm_kwargs.extra_body.chat_template_kwargs.enable_thinking= + false` (llama.cpp --jinja wertet das aus; litellm reicht extra_body durch). + Dazu `FAST_TOKEN_LIMIT=4000`, `SMART/STRATEGIC_TOKEN_LIMIT=16000` (v3.8-Cap) + als Reserve. Verifiziert im Backend: gepatchte Funktion antwortet in 0,4 s + mit Inhalt. Achtung: Single-File-Bind-Mount behält bei `copy` den alten + Inode — deshalb `force_handlers: true` in research.yml, damit der + Backend-Neustart auch bei fehlschlagender Verifikation läuft. + +- **Stand 22.11.2026 (M8-T4 stabil, E2E abgenommen):** GPT Researcher läuft + produktiv hinter dem IAP auf `https://research.ghostnet.selfhost.eu` + (Keycloak-Login, Gruppe `gnai-research-user`). Live-Research-Läufe mit + SearXNG-Retriever liefern Quellen (8/8, 5/5, 7/8 … gescrapte Seiten pro + Sub-Query), der Report wird im UI gestreamt und als **md/docx/pdf mit + Inhalt** ausgeliefert (`/outputs/`-Routing via NPM, PDF via weasyprint). + Alle Fixes oben (href-Shim, Embeddings-Sidecar, /outputs-Routing, + weasyprint-PDF, enable_thinking=false) sind eingerollt; `research.yml`, + `ai.yml` (Production) und ct103 `site.yml` jeweils idempotent + (`changed=0`). **Offen (M8-T5):** Fail2Ban-Jail auf oauth2-proxy-Logs + (CT 103), formale Abnahme der 10-Punkte-Checkliste Abschnitt 4 + (Gruppen-Negativtest, Header-Bypass-Test, Logout, WAN-Negativtest). diff --git a/docs/platform/llm-server/ai/README.md b/docs/platform/llm-server/ai/README.md index b0f0426..792b6aa 100644 --- a/docs/platform/llm-server/ai/README.md +++ b/docs/platform/llm-server/ai/README.md @@ -15,7 +15,9 @@ Video-Encoding-Workload besitzt einen | [GNAI-009](GNAI-009-PLAN_Llama-Model-Evaluation.md) | Modellbewertung für Swift/Unsloth; Betreiberbeschluss 05.11.2026: Swift 1.5 Q6_K als Production-Profil (Abschnitt 10.4) | | [GNAI-010](GNAI-010-TECH_Llama-Serving.md) | technische Sollkonfiguration für die Modellprofile auf rootless `llama.cpp` mit ROCm; Testing abgenommen (10.5–10.10), Production live seit 06.11.2026 | | [GNAI-020](GNAI-020-TECH_OpenWebUI-WebSearch.md) | Websuche in OpenWebUI: SearXNG mit kuratierten Engines + Native/Agentic Mode (`search_web`/`fetch_url`), UI- und API-Betrieb (Path A/B), produktiv verifiziert seit 12.11.2026 | -| [GNAI-021](GNAI-021-TECH_OpenWebUI-Theme.md) | OpenWebUI-Theme „gnai-catppuccin-mocha" (Farbschema des GNMON-Dashboards) als Default für alle Nutzer, update-persistent via read-only `custom.css`-Mount im Quadlet | +| [GNAI-021](GNAI-021-TECH_OpenWebUI-Theme.md) | OpenWebUI-Theme „gnai-catppuccin-mocha" + Favicons, update-persistent via read-only Mounts, live seit 14.11.2026 | +| [GNAI-022](GNAI-022-TECH_OpenWebUI-DeepResearch.md) | Phase 1 (M6-R1): Deep Research im bestehenden OpenWebUI-Harness — Pipe `gnai-deep-research` (sha256-gepinnt), Deployment verifiziert 14.11.2026 | +| [GNAI-023](GNAI-023-PLAN_GPT-Researcher-IAP.md) | Phase 2 (M8): GPT Researcher hinter Identity-Aware Proxy (oauth2-proxy + NPM auth_request + Keycloak-OIDC) — Machbarkeit, Sicherheit, Härtung | Der übergreifende Projektstand steht im [zentralen Dokumentationsindex](../../../GNAI-000-DOC_Index.md). diff --git a/llm-server/llm/ansible/inventories/production/group_vars/llm_servers.yml b/llm-server/llm/ansible/inventories/production/group_vars/llm_servers.yml index 55f7821..03d50b3 100644 --- a/llm-server/llm/ansible/inventories/production/group_vars/llm_servers.yml +++ b/llm-server/llm/ansible/inventories/production/group_vars/llm_servers.yml @@ -64,3 +64,10 @@ inference_engine_ctx_size_override: null # Keycloak OIDC at https://chat.ghostnet.selfhost.eu (NPM proxy host -> # 10.0.0.90:8081; Keycloak client gnai-openwebui, public + PKCE S256). open_webui_oidc_enabled: true + +# M8 (GNAI-023): the Production environment additionally runs gpt-researcher, +# which needs a multilingual embedding model for its context ranking. The +# model is fetched by model_store (ai.yml) and served by a CPU-only +# llama.cpp --embeddings sidecar rendered by the gpt_researcher role +# (research.yml). +model_store_include_embedding: true diff --git a/llm-server/llm/ansible/playbooks/research.yml b/llm-server/llm/ansible/playbooks/research.yml new file mode 100644 index 0000000..56afd2c --- /dev/null +++ b/llm-server/llm/ansible/playbooks/research.yml @@ -0,0 +1,17 @@ +--- +# Deploys the GPT Researcher harness (backend + frontend) for the Production +# environment only (GNAI-023 M8-T4). Requires the Production engine network +# (run ai.yml first). Never changes engine state. +# +# Usage: +# ansible-playbook -i inventories/production playbooks/research.yml --check --diff +# ansible-playbook -i inventories/production playbooks/research.yml +- name: Deploy the GPT Researcher harness for the Production environment + hosts: llm_servers + become: true + # single-file bind mounts (sitecustomize.py) keep the old inode when the + # copy task replaces the file — the restart handler must run even if a + # later verification task fails, else the container serves a stale patch + force_handlers: true + roles: + - role: gpt_researcher diff --git a/llm-server/llm/ansible/roles/gpt_researcher/README.md b/llm-server/llm/ansible/roles/gpt_researcher/README.md new file mode 100644 index 0000000..4c2c60e --- /dev/null +++ b/llm-server/llm/ansible/roles/gpt_researcher/README.md @@ -0,0 +1,28 @@ +# gpt_researcher + +GPT Researcher (assafelovic/gpt-researcher, GNAI-023 M8-T4) als zweiter +Research-Harness auf `ghostnet-ki` im Production-Netz. Deploy via +`playbooks/research.yml` gegen `inventories/production`. + +- Zwei Quadlets als `gnai-production`: Backend (FastAPI :8000, Image + `gptresearcher/gpt-researcher` digest-gepinnt) und Frontend (NextJS :3000, + `gptresearcher/gptr-nextjs` digest-gepinnt). Beide in + `gnai-production-llama` + `gnai-production-egress`. +- Publish LAN-only: Frontend `10.0.0.90:8085`, Backend `10.0.0.90:8086`; + `gnmon_firewall_npm_only_ports` beschränkt beide auf NPM (10.0.0.10). +- LLM: Engine via `http://llama-cpp:8080/v1` (Alias), `OPENAI_API_KEY` als + Podman-Secret (Placeholder; llama.cpp ohne Auth). `FAST_LLM`/`SMART_LLM`/ + `STRATEGIC_LLM` = Production-Profil-Alias. `LLM_TIMEOUT=600`. +- Retriever: `SEARCH_ENGINE`/`RETRIEVER=duckduckgo` (keyless, Egress-Netz). + SearXNG als Custom-Retriever wäre eine Erweiterung (GNAI-023). +- `User=root` im Container nötig (upstream compose läuft als root; rootless + mappt auf gnai-production — sonst PermissionError auf logs/app.log). +- Ingress: NPM-vHost `research.ghostnet.selfhost.eu` (Rolle + `reverse_proxy_research_vhost` auf CT 103): Location `/` → 8085, Location + `/api` → 8086 (mit 600 s Timeouts), beide hinter oauth2-proxy + (`auth_request`, Keycloak-Client `gnai-research`). +- Daten: `/var/lib/ghostnet-ai/production/gptr/{my-docs,outputs,logs}`. + +Verifiziert 18.11.: `research.yml` idempotent (`changed=0`), Backend +`/docs` 200 und Frontend `/` 200 via NPM-Host, `research/` und +`research/api/docs` unauth → 302 zu Keycloak, Port 8086 von außen geblockt. diff --git a/llm-server/llm/ansible/roles/gpt_researcher/defaults/main.yml b/llm-server/llm/ansible/roles/gpt_researcher/defaults/main.yml new file mode 100644 index 0000000..2642c34 --- /dev/null +++ b/llm-server/llm/ansible/roles/gpt_researcher/defaults/main.yml @@ -0,0 +1,108 @@ +--- +# GPT Researcher (assafelovic/gpt-researcher, GNAI-023 M8-T4) as the second +# research harness on ghostnet-ki in the Production environment. +# Backend (FastAPI, :8000) + NextJS frontend (:3000), both in the Production +# engine network (llama.cpp via alias) and the egress network. +# Published on LAN only: frontend 10.0.0.90:8085, backend 10.0.0.90:8086 — +# host firewall restricts both to NPM (CT-103, gnmon_firewall_npm_only_ports). +# +# Images pulled from docker.io/gptresearcher/*:latest on 2026-11-18 and +# pinned by digest (upstream publishes no version tags). +gpt_researcher_backend_image: docker.io/gptresearcher/gpt-researcher +gpt_researcher_backend_image_ref: "{{ gpt_researcher_backend_image }}@sha256:8e0975ec9aaddc49c17c59568a25618c8a5f75b7a5f1fab35bc90e6c6dc950c7" +gpt_researcher_frontend_image: docker.io/gptresearcher/gptr-nextjs +gpt_researcher_frontend_image_ref: "{{ gpt_researcher_frontend_image }}@sha256:69e7e2fa02d23666e7c00774faed154af1684ac06dc97d2c29c8b6e77f98710a" + +gpt_researcher_user: gnai-production +gpt_researcher_uid: 980 +gpt_researcher_home: /var/lib/ghostnet-ai/production +gpt_researcher_quadlet_dir: /etc/containers/systemd/users/980 +gpt_researcher_unit_prefix: gnai-production-gptr +gpt_researcher_network_name: gnai-production-llama +gpt_researcher_egress_network_name: gnai-production-egress + +gpt_researcher_frontend_host_addr: 10.0.0.90 +gpt_researcher_frontend_host_port: 8085 +gpt_researcher_frontend_container_port: 3000 +gpt_researcher_backend_host_addr: 10.0.0.90 +gpt_researcher_backend_host_port: 8086 +gpt_researcher_backend_container_port: 8000 + +gpt_researcher_data_dir: /var/lib/ghostnet-ai/production/gptr + +# Engine via the Production network alias (llama.cpp has no auth; placeholder +# key via Podman secret, never in git). +gpt_researcher_engine_base_url: http://llama-cpp:8080/v1 +gpt_researcher_engine_model_id: swift-1.5-qwen3.8-27b-q6k +gpt_researcher_engine_api_key_secret: gptr-engine-api-key + +# Shim (python:3.13-alpine, tag-gepinnt) maps gpt-researcher's +# RETRIEVER=custom contract (?query= -> [{"href","url","raw_content"}]) +# onto our SearXNG (?q=&format=json). The published gptr image lacks the +# duckduckgo lib (renamed to ddgs in 2026), so SearXNG via shim is the +# retriever. "href" is the key v3.8 actually reads when building the +# scrape list (skills/researcher.py: url.get("href")). +gpt_researcher_shim_image: docker.io/library/python +# Tag-ref (Pull=never + pre-pull by tag in the role): the manifest-list +# digest of 3.13-alpine 404s on direct pull, so we pin the tag and pull it +# explicitly when absent (same pattern as the GNMON image transport). +gpt_researcher_shim_image_ref: "{{ gpt_researcher_shim_image }}:3.13-alpine" +gpt_researcher_shim_script: "{{ gpt_researcher_data_dir }}/searxng_shim.py" + +# Embedding sidecar (GNAI-023 M8-T4, Befund 20.11. "501 embeddings"): +# gpt-researcher v3.8 ranks scraped context via embeddings but reads a single +# OPENAI_BASE_URL for chat AND embeddings, so a dedicated CPU-only llama.cpp +# instance with --embeddings serves /v1/embeddings on the alias +# llama-cpp-embed; the backend's sitecustomize patch redirects only the +# embeddings client there (see files/sitecustomize_gnai.py). +# The image digest is a copy of inference_engine_image_ref (role defaults +# are not visible across plays) — keep in sync with +# roles/inference_engine/defaults/main.yml. +gpt_researcher_embed_engine_image_ref: "ghcr.io/ggml-org/llama.cpp@sha256:4bbbd2e33deb54330fd23edde3a2cdf12b05ce4415139c7e8639a9aebbacdcf2" +gpt_researcher_model_store_root: "{{ model_store_root | default('/var/lib/ghostnet-ai/shared/models') }}" +gpt_researcher_embed_model_directory: nomic-embed-text-v2-moe +gpt_researcher_embed_model_file: nomic-embed-text-v2-moe.Q8_0.gguf +# copy of model_store_embedding_artifact.sha256 (role defaults are not +# visible across plays) — keep in sync with roles/model_store/defaults/main.yml +gpt_researcher_embed_model_sha256: "06e7a7e594a26985523c18383aba4aad39fe6e14f08ffc6ab5b554e1ccdc3cff" +gpt_researcher_embed_model_alias: nomic-embed-text-v2-moe +gpt_researcher_embed_alias: llama-cpp-embed +gpt_researcher_embed_base_url: "http://{{ gpt_researcher_embed_alias }}:8080/v1" +# Mounted over site-packages/sitecustomize.py in the backend container +# (auto-imported at interpreter start; the image ships none). +gpt_researcher_backend_patch_script: "{{ gpt_researcher_data_dir }}/sitecustomize_gnai.py" + +# LLM + retriever config (gpt-researcher v3.8 env; LLM names need the +# ':' form). Token limits stay at upstream defaults +# (FAST=3000/SMART=6000) — fine for a 27B local model. +gpt_researcher_env: + OPENAI_BASE_URL: "{{ gpt_researcher_engine_base_url }}" + FAST_LLM: "openai:{{ gpt_researcher_engine_model_id }}" + SMART_LLM: "openai:{{ gpt_researcher_engine_model_id }}" + STRATEGIC_LLM: "openai:{{ gpt_researcher_engine_model_id }}" + RETRIEVER: custom + RETRIEVERS: custom + RETRIEVER_ENDPOINT: http://gptr-searxng-shim:8099/ + # v3.8 default scraper is "bs" (requests + bs4) — pin it explicitly so a + # future upstream default change cannot require a browser in the image + SCRAPER: bs + # Embeddings: provider "custom" sends /v1/embeddings to OPENAI_BASE_URL by + # default; sitecustomize_gnai.py redirects only that client to + # GNAI_EMBEDDING_BASE_URL (CPU-only llama-cpp sidecar, alias llama-cpp-embed) + EMBEDDING: "custom:{{ gpt_researcher_embed_model_alias }}" + GNAI_EMBEDDING_BASE_URL: "{{ gpt_researcher_embed_base_url }}" + # headroom for report generation (sitecustomize disables thinking, so the + # budget goes to content; 16000 is the v3.8 hard cap) + FAST_TOKEN_LIMIT: "4000" + SMART_TOKEN_LIMIT: "16000" + STRATEGIC_TOKEN_LIMIT: "16000" + LLM_TIMEOUT: "600" + LOGGING_LEVEL: INFO + DOC_PATH: /usr/src/app/my-docs + +gpt_researcher_frontend_env: + # relative API base: the browser calls same-origin /api/... which the NPM + # vHost routes to the backend (10.0.0.90:8086) + NEXT_PUBLIC_GPTR_API_URL: "" + CHOKIDAR_USEPOLLING: "true" + LOGGING_LEVEL: INFO diff --git a/llm-server/llm/ansible/roles/gpt_researcher/files/searxng_shim.py b/llm-server/llm/ansible/roles/gpt_researcher/files/searxng_shim.py new file mode 100644 index 0000000..f08f926 --- /dev/null +++ b/llm-server/llm/ansible/roles/gpt_researcher/files/searxng_shim.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Shim between gpt-researcher's RETRIEVER=custom and SearXNG. + +gpt-researcher v3.8 custom retriever: GET ?query= +(+ extra params), expects a JSON list of result dicts. IMPORTANT: v3.8 +builds the scrape list via `url.get("href")` in +skills/researcher.py::_search_relevant_source_urls — the key must be +"href" (returning only "url" yields None entries and the scraper crashes +with "Error processing None ... endswith"). "url"/"raw_content" are kept +for compatibility; v3.8 does NOT skip its own scraper based on +raw_content — the backend re-fetches every href with the default "bs" +scraper (requests + bs4, no browser needed in the image). + +The pre-fetch here therefore only filters dead/unfetchable result pages +(raw text <= 100 chars are dropped) so the gptr scraper does not waste +workers on them. + +SearXNG side: /search?q=&format=json -> {"results": [...]}. +Listens on :8099, internal networks only (no published port). +""" +import json +import os +import re +import urllib.parse +import urllib.request +from http.server import BaseHTTPRequestHandler, HTTPServer + +SEARXNG = os.environ.get("SHIM_SEARXNG_URL", "http://searxng:8080") +UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36" +MAX_RESULTS = int(os.environ.get("SHIM_MAX_RESULTS", "8")) +FETCH_TIMEOUT = 10 +MAX_BODY = 200_000 + + +def fetch_text(url): + try: + req = urllib.request.Request(url, headers={"User-Agent": UA}) + with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT) as resp: + ctype = resp.headers.get("content-type", "") + if "html" not in ctype and "text" not in ctype: + return "" + raw = resp.read(MAX_BODY).decode("utf-8", errors="replace") + text = re.sub(r"(?is)<(script|style|nav|footer|header|svg)[^>]*>.*?", " ", raw) + text = re.sub(r"(?s)<[^>]+>", " ", text) + text = re.sub(r"\s+", " ", text).strip() + return text[:8000] + except Exception: + return "" + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + qs = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query) + q = (qs.get("query") or qs.get("q") or [""])[0] + if not q: + self.send_response(400) + self.end_headers() + self.wfile.write(b'{"error": "missing query"}') + return + url = f"{SEARXNG}/search?" + urllib.parse.urlencode({"q": q, "format": "json"}) + try: + with urllib.request.urlopen(url, timeout=25) as resp: + data = json.loads(resp.read()) + except Exception as e: + self.send_response(502) + self.end_headers() + self.wfile.write(json.dumps({"error": str(e)}).encode()) + return + out = [] + for r in data.get("results", []): + u = r.get("url", "") + if not u or not isinstance(u, str): + continue + content = fetch_text(u) + # only pass pages we actually fetched (raw text > 100 chars); + # v3.8 reads "href" to build the scrape list, so without it the + # scraper receives None and crashes ("Error processing None") + if len(content) <= 100: + continue + out.append({"href": u, "url": u, "raw_content": content}) + if len(out) >= MAX_RESULTS: + break + body = json.dumps(out).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +if __name__ == "__main__": + HTTPServer(("0.0.0.0", 8099), Handler).serve_forever() diff --git a/llm-server/llm/ansible/roles/gpt_researcher/files/sitecustomize_gnai.py b/llm-server/llm/ansible/roles/gpt_researcher/files/sitecustomize_gnai.py new file mode 100644 index 0000000..e8e848e --- /dev/null +++ b/llm-server/llm/ansible/roles/gpt_researcher/files/sitecustomize_gnai.py @@ -0,0 +1,86 @@ +"""Ghostnet.AI patch for the gpt-researcher backend (GNAI-023 M8-T4). + +Mounted read-only over /usr/local/lib/python3.11/site-packages/sitecustomize.py +in the gptr backend container, so Python imports it automatically at +interpreter start (the published image ships no sitecustomize). + +gpt-researcher v3.8 reads a single OPENAI_BASE_URL for BOTH the chat LLM +(utils/llm.py) and the embeddings client (memory/embeddings.py, "custom" +provider), so chat and embeddings cannot be split via environment variables +alone. This patch redirects ONLY the embeddings client +(langchain_openai.OpenAIEmbeddings, used exclusively for context ranking) to +GNAI_EMBEDDING_BASE_URL — a CPU-only llama.cpp --embeddings sidecar +(alias llama-cpp-embed). Chat completions keep using OPENAI_BASE_URL +(llama-cpp) untouched. +""" +import os + +_base = os.environ.get("GNAI_EMBEDDING_BASE_URL") +if _base: + try: + from langchain_openai import OpenAIEmbeddings as _OE + + _orig_init = _OE.__init__ + + def _patched_init(self, *args, **kwargs): + kwargs["openai_api_base"] = _base + _orig_init(self, *args, **kwargs) + + _OE.__init__ = _patched_init + except Exception: + # never break interpreter startup because of the patch + pass + +# write_md_to_pdf: the published image ships md2pdf (needs playwright + +# chromium, both absent) so every PDF export fails and returns "" — which +# makes the frontend log "No pdf path provided" and render href="#". +# weasyprint 64.1 IS installed and works in the image, so replace the +# function with a mistune -> HTML -> weasyprint implementation. Must run +# before backend.server.server_utils does `from backend.utils import +# write_md_to_pdf`; sitecustomize runs at interpreter start, so importing +# backend.utils here and swapping the attribute is sufficient. +try: + import urllib.parse + + import backend.utils as _bu + + async def _write_md_to_pdf_weasyprint(text: str, filename: str = "") -> str: + import mistune + from weasyprint import CSS, HTML + + file_path = f"outputs/{filename[:60]}.pdf" + css_path = "./frontend/pdf_styles.css" + stylesheets = [CSS(filename=css_path)] if os.path.exists(css_path) else None + HTML(string=mistune.html(text), base_url=".").write_pdf( + file_path, stylesheets=stylesheets + ) + return urllib.parse.quote(file_path) + + _bu.write_md_to_pdf = _write_md_to_pdf_weasyprint +except Exception: + pass + +# gpt-researcher LLM calls: the engine profile runs with reasoning enabled and +# the client-side max_tokens caps reasoning+content TOGETHER. On large report +# prompts the reasoning alone exhausts the budget, so the report comes back +# EMPTY (no streamed chunks, md/pdf/docx 0 bytes). Force enable_thinking=false +# via chat_template_kwargs (llama.cpp --jinja honors it, verified 2026-11-22: +# 3 vs 97 completion tokens) so the budget goes to visible content. +# sitecustomize runs before any gpt_researcher module import, so replacing the +# attribute here covers all `from ...utils.llm import create_chat_completion`. +try: + import gpt_researcher.utils.llm as _gllm + + _orig_ccc = _gllm.create_chat_completion + + async def _ccc_no_thinking(*args, **kwargs): + kw = dict(kwargs.get("llm_kwargs") or {}) + extra = dict(kw.get("extra_body") or {}) + extra["chat_template_kwargs"] = {"enable_thinking": False} + kw["extra_body"] = extra + kwargs["llm_kwargs"] = kw + return await _orig_ccc(*args, **kwargs) + + _gllm.create_chat_completion = _ccc_no_thinking +except Exception: + pass diff --git a/llm-server/llm/ansible/roles/gpt_researcher/handlers/main.yml b/llm-server/llm/ansible/roles/gpt_researcher/handlers/main.yml new file mode 100644 index 0000000..186e9a0 --- /dev/null +++ b/llm-server/llm/ansible/roles/gpt_researcher/handlers/main.yml @@ -0,0 +1,39 @@ +--- +- name: Reload workload user manager + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - "HOME={{ gpt_researcher_home }}" + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/systemctl + - --user + - daemon-reload + chdir: "{{ gpt_researcher_home }}" + changed_when: false + when: not ansible_check_mode + +- name: Restart gptr units + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - "HOME={{ gpt_researcher_home }}" + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/systemctl + - --user + - restart + - "{{ gpt_researcher_unit_prefix }}-{{ item }}.service" + chdir: "{{ gpt_researcher_home }}" + loop: + - backend + - frontend + - searxng-shim + - embed + when: not ansible_check_mode diff --git a/llm-server/llm/ansible/roles/gpt_researcher/tasks/main.yml b/llm-server/llm/ansible/roles/gpt_researcher/tasks/main.yml new file mode 100644 index 0000000..3959545 --- /dev/null +++ b/llm-server/llm/ansible/roles/gpt_researcher/tasks/main.yml @@ -0,0 +1,316 @@ +--- +- name: Verify gpt_researcher role declarations + ansible.builtin.assert: + that: + - gpt_researcher_backend_image_ref is match('^docker\.io/gptresearcher/gpt-researcher@sha256:[0-9a-f]{64}$') + - gpt_researcher_frontend_image_ref is match('^docker\.io/gptresearcher/gptr-nextjs@sha256:[0-9a-f]{64}$') + - gpt_researcher_network_name == 'gnai-production-llama' + fail_msg: "gpt_researcher must use digest-pinned images and the Production network" + +- name: Ensure the gptr data directories exist + ansible.builtin.file: + path: "{{ gpt_researcher_data_dir }}/{{ item }}" + state: directory + owner: "{{ gpt_researcher_user }}" + group: "{{ gpt_researcher_user }}" + mode: "0750" + loop: + - my-docs + - outputs + - logs + +- name: Deploy the searxng shim script + ansible.builtin.copy: + src: files/searxng_shim.py + dest: "{{ gpt_researcher_shim_script }}" + owner: "{{ gpt_researcher_user }}" + group: "{{ gpt_researcher_user }}" + mode: "0644" + notify: + - Reload workload user manager + - Restart gptr units + +- name: Deploy the backend sitecustomize patch (embeddings split) + ansible.builtin.copy: + src: files/sitecustomize_gnai.py + dest: "{{ gpt_researcher_backend_patch_script }}" + owner: "{{ gpt_researcher_user }}" + group: "{{ gpt_researcher_user }}" + mode: "0644" + notify: + - Reload workload user manager + - Restart gptr units + +- name: Ensure the embedding model is present in the shared model store + ansible.builtin.stat: + path: "{{ gpt_researcher_model_store_root }}/{{ gpt_researcher_embed_model_directory }}/{{ gpt_researcher_embed_model_file }}" + checksum_algorithm: sha256 + get_checksum: true + register: gptr_embed_model + changed_when: false + failed_when: >- + not gptr_embed_model.stat.exists + or gptr_embed_model.stat.checksum != gpt_researcher_embed_model_sha256 + check_mode: false + +- name: Explain a missing embedding model + ansible.builtin.assert: + that: + - gptr_embed_model.stat.exists + - gptr_embed_model.stat.checksum == gpt_researcher_embed_model_sha256 + fail_msg: >- + The embedding model {{ gpt_researcher_embed_model_file }} is missing or + its checksum mismatches in {{ gpt_researcher_model_store_root }} — + run playbooks/ai.yml for the production inventory first + (model_store_include_embedding: true fetches it). + +- name: Check whether the engine API key secret exists + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - "HOME={{ gpt_researcher_home }}" + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/podman + - secret + - exists + - "{{ gpt_researcher_engine_api_key_secret }}" + chdir: "{{ gpt_researcher_home }}" + register: gptr_engine_secret_exists + changed_when: false + failed_when: gptr_engine_secret_exists.rc not in [0, 1] + check_mode: false + +- name: Create the engine API key secret (placeholder, llama.cpp has no auth) + ansible.builtin.shell: | + set -euo pipefail + printf 'local-noauth-%s' "$(head -c 16 /dev/urandom | base64)" \ + | /usr/sbin/runuser --user {{ gpt_researcher_user }} -- /usr/bin/env \ + HOME={{ gpt_researcher_home }} XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }} \ + /usr/bin/podman secret create {{ gpt_researcher_engine_api_key_secret }} - + args: + executable: /bin/bash + chdir: "{{ gpt_researcher_home }}" + when: gptr_engine_secret_exists.rc == 1 + no_log: true + +- name: Check whether the pinned images are in the workload store + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - "HOME={{ gpt_researcher_home }}" + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/podman + - image + - exists + - "{{ item }}" + chdir: "{{ gpt_researcher_home }}" + loop: + - "{{ gpt_researcher_backend_image_ref }}" + - "{{ gpt_researcher_frontend_image_ref }}" + - "{{ gpt_researcher_shim_image_ref }}" + - "{{ gpt_researcher_embed_engine_image_ref }}" + register: gptr_images_present + changed_when: false + failed_when: false + check_mode: false + +- name: Pull the pinned images into the workload store + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - "HOME={{ gpt_researcher_home }}" + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/podman + - pull + - "{{ item.item }}" + chdir: "{{ gpt_researcher_home }}" + loop: "{{ gptr_images_present.results }}" + when: + - not ansible_check_mode + - item.rc != 0 + +- name: Render the gptr quadlets + ansible.builtin.template: + src: "{{ item.src }}" + dest: "{{ gpt_researcher_quadlet_dir }}/{{ gpt_researcher_unit_prefix }}-{{ item.name }}.container" + owner: root + group: "{{ gpt_researcher_user }}" + mode: "0640" + loop: + - { src: gptr-backend.container.j2, name: backend } + - { src: gptr-frontend.container.j2, name: frontend } + - { src: gptr-searxng-shim.container.j2, name: searxng-shim } + - { src: gptr-embed.container.j2, name: embed } + notify: + - Reload workload user manager + - Restart gptr units + +- name: Ensure the workload user manager knows the rendered units + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - "HOME={{ gpt_researcher_home }}" + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/systemctl + - --user + - daemon-reload + chdir: "{{ gpt_researcher_home }}" + changed_when: false + when: not ansible_check_mode + +- name: Read the current state of the gptr units + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - "HOME={{ gpt_researcher_home }}" + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/systemctl + - --user + - is-active + - "{{ gpt_researcher_unit_prefix }}-{{ item }}.service" + chdir: "{{ gpt_researcher_home }}" + loop: + - backend + - frontend + - searxng-shim + - embed + register: gptr_unit_states + changed_when: false + failed_when: false + check_mode: false + +- name: Start the gptr units + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - "HOME={{ gpt_researcher_home }}" + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/systemctl + - --user + - start + - "{{ gpt_researcher_unit_prefix }}-{{ item.item }}.service" + chdir: "{{ gpt_researcher_home }}" + loop: "{{ gptr_unit_states.results }}" + when: + - not ansible_check_mode + - item.rc != 0 + +- name: Wait for the backend and frontend health endpoints + ansible.builtin.uri: + url: "http://{{ item.addr }}:{{ item.port }}{{ item.path }}" + status_code: [200, 404] + timeout: 10 + loop: + - { addr: "{{ gpt_researcher_backend_host_addr }}", port: "{{ gpt_researcher_backend_host_port }}", path: /docs } + - { addr: "{{ gpt_researcher_frontend_host_addr }}", port: "{{ gpt_researcher_frontend_host_port }}", path: / } + retries: 30 + delay: 5 + when: not ansible_check_mode + +- name: Verify the searxng shim answers via the backend network + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - "HOME={{ gpt_researcher_home }}" + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/podman + - exec + - "{{ gpt_researcher_unit_prefix }}-backend" + - /bin/sh + - -c + - "python3 -c \"import urllib.request,json; d=json.loads(urllib.request.urlopen('http://gptr-searxng-shim:8099/?query=openwebui', timeout=25).read()); assert isinstance(d, list) and d and d[0]['url'], d[:1]\"" + chdir: "{{ gpt_researcher_home }}" + changed_when: false + when: not ansible_check_mode + +- name: Verify the engine is reachable from the backend container + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - "HOME={{ gpt_researcher_home }}" + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/podman + - exec + - "{{ gpt_researcher_unit_prefix }}-backend" + - /bin/sh + - -c + - "python3 -c \"import urllib.request,sys; sys.exit(0 if b'swift' in urllib.request.urlopen('{{ gpt_researcher_engine_base_url }}/models', timeout=10).read() else 1)\"" + chdir: "{{ gpt_researcher_home }}" + changed_when: false + when: not ansible_check_mode + +- name: Wait for the embedding sidecar (via the backend container) + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - HOME={{ gpt_researcher_home }} + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/podman + - exec + - "{{ gpt_researcher_unit_prefix }}-backend" + - /bin/sh + - -c + - "python3 -c \"import urllib.request; urllib.request.urlopen('{{ gpt_researcher_embed_base_url }}/models', timeout=10)\"" + chdir: "{{ gpt_researcher_home }}" + register: gptr_embed_health + until: gptr_embed_health.rc == 0 + retries: 30 + delay: 5 + changed_when: false + when: not ansible_check_mode + +- name: Verify the embeddings endpoint answers via the sidecar + ansible.builtin.command: + argv: + - /usr/sbin/runuser + - --user + - "{{ gpt_researcher_user }}" + - -- + - /usr/bin/env + - HOME={{ gpt_researcher_home }} + - "XDG_RUNTIME_DIR=/run/user/{{ gpt_researcher_uid }}" + - /usr/bin/podman + - exec + - "{{ gpt_researcher_unit_prefix }}-backend" + - /bin/sh + - -c + - "python3 -c \"import json,urllib.request; req=urllib.request.Request('{{ gpt_researcher_embed_base_url }}/embeddings', data=json.dumps({'model':'{{ gpt_researcher_embed_model_alias }}','input':'Hallo Welt'}).encode(), headers={'Content-Type':'application/json'}); d=json.loads(urllib.request.urlopen(req, timeout=60).read()); assert len(d['data'][0]['embedding']) > 100, list(d.keys())\"" + chdir: "{{ gpt_researcher_home }}" + changed_when: false + when: not ansible_check_mode diff --git a/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-backend.container.j2 b/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-backend.container.j2 new file mode 100644 index 0000000..bd6b4fa --- /dev/null +++ b/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-backend.container.j2 @@ -0,0 +1,32 @@ +[Unit] +Description=GPT Researcher backend (FastAPI :8000, GNAI-023 M8) +Wants={{ gpt_researcher_network_name }}-network.service {{ gpt_researcher_egress_network_name }}-network.service +After={{ gpt_researcher_network_name }}-network.service {{ gpt_researcher_egress_network_name }}-network.service + +[Container] +Image={{ gpt_researcher_backend_image_ref }} +Pull=never +# upstream compose runs as root; rootless maps container root to gnai-production +User=root +ContainerName={{ gpt_researcher_unit_prefix }}-backend +Network={{ gpt_researcher_network_name }} +Network={{ gpt_researcher_egress_network_name }} +PublishPort={{ gpt_researcher_backend_host_addr }}:{{ gpt_researcher_backend_host_port }}:{{ gpt_researcher_backend_container_port }} +Secret={{ gpt_researcher_engine_api_key_secret }},type=env,target=OPENAI_API_KEY +Volume={{ gpt_researcher_data_dir }}/my-docs:/usr/src/app/my-docs:rw +Volume={{ gpt_researcher_data_dir }}/outputs:/usr/src/app/outputs:rw +Volume={{ gpt_researcher_data_dir }}/logs:/usr/src/app/logs:rw +# sitecustomize patch: redirects only the embeddings client to +# GNAI_EMBEDDING_BASE_URL (llama-cpp-embed); image ships no sitecustomize +Volume={{ gpt_researcher_backend_patch_script }}:/usr/local/lib/python3.11/site-packages/sitecustomize.py:ro +{% for key, value in gpt_researcher_env.items() %} +Environment="{{ key }}={{ value }}" +{% endfor %} + +[Service] +Restart=on-failure +RestartSec=10 +TimeoutStartSec=600 + +[Install] +WantedBy=default.target diff --git a/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-embed.container.j2 b/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-embed.container.j2 new file mode 100644 index 0000000..ba1ea35 --- /dev/null +++ b/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-embed.container.j2 @@ -0,0 +1,24 @@ +[Unit] +Description=Embedding sidecar for gpt-researcher (llama.cpp --embeddings, CPU-only, :8080 internal) +Wants={{ gpt_researcher_network_name }}-network.service +After={{ gpt_researcher_network_name }}-network.service + +[Container] +Image={{ gpt_researcher_embed_engine_image_ref }} +Pull=never +ContainerName={{ gpt_researcher_unit_prefix }}-embed +Network={{ gpt_researcher_network_name }} +NetworkAlias={{ gpt_researcher_embed_alias }} +# no PublishPort, no AddDevice: CPU-only (n-gpu-layers 0), reachable only +# inside the workload network as {{ gpt_researcher_embed_alias }} +Volume={{ gpt_researcher_model_store_root }}/{{ gpt_researcher_embed_model_directory }}:/models:ro +# ENTRYPOINT of the pinned image is /app/llama-server, Exec= carries args only +Exec=--host 0.0.0.0 --port 8080 --model /models/{{ gpt_researcher_embed_model_file }} --alias {{ gpt_researcher_embed_model_alias }} --embeddings --n-gpu-layers 0 --ctx-size 8192 --no-webui + +[Service] +Restart=on-failure +RestartSec=10 +TimeoutStartSec=600 + +[Install] +WantedBy=default.target diff --git a/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-frontend.container.j2 b/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-frontend.container.j2 new file mode 100644 index 0000000..2535cf2 --- /dev/null +++ b/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-frontend.container.j2 @@ -0,0 +1,26 @@ +[Unit] +Description=GPT Researcher frontend (NextJS :3000, GNAI-023 M8) +Wants={{ gpt_researcher_network_name }}-network.service {{ gpt_researcher_egress_network_name }}-network.service +After={{ gpt_researcher_network_name }}-network.service {{ gpt_researcher_egress_network_name }}-network.service + +[Container] +Image={{ gpt_researcher_frontend_image_ref }} +Pull=never +# upstream compose runs as root; rootless maps container root to gnai-production +User=root +ContainerName={{ gpt_researcher_unit_prefix }}-frontend +Network={{ gpt_researcher_network_name }} +Network={{ gpt_researcher_egress_network_name }} +PublishPort={{ gpt_researcher_frontend_host_addr }}:{{ gpt_researcher_frontend_host_port }}:{{ gpt_researcher_frontend_container_port }} +Volume={{ gpt_researcher_data_dir }}/outputs:/app/outputs:ro +{% for key, value in gpt_researcher_frontend_env.items() %} +Environment="{{ key }}={{ value }}" +{% endfor %} + +[Service] +Restart=on-failure +RestartSec=10 +TimeoutStartSec=300 + +[Install] +WantedBy=default.target diff --git a/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-searxng-shim.container.j2 b/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-searxng-shim.container.j2 new file mode 100644 index 0000000..0d1fa4b --- /dev/null +++ b/llm-server/llm/ansible/roles/gpt_researcher/templates/gptr-searxng-shim.container.j2 @@ -0,0 +1,24 @@ +[Unit] +Description=SearXNG shim for gpt-researcher custom retriever (:8099, internal only) +Wants={{ gpt_researcher_network_name }}-network.service {{ gpt_researcher_egress_network_name }}-network.service +After={{ gpt_researcher_network_name }}-network.service {{ gpt_researcher_egress_network_name }}-network.service + +[Container] +Image={{ gpt_researcher_shim_image_ref }} +Pull=never +ContainerName={{ gpt_researcher_unit_prefix }}-searxng-shim +Network={{ gpt_researcher_network_name }} +Network={{ gpt_researcher_egress_network_name }} +NetworkAlias=gptr-searxng-shim +# no PublishPort: reachable only inside the workload networks +Volume={{ gpt_researcher_shim_script }}:/shim.py:ro +Exec=python3 /shim.py +Environment=SHIM_SEARXNG_URL=http://searxng:8080 + +[Service] +Restart=on-failure +RestartSec=5 +TimeoutStartSec=60 + +[Install] +WantedBy=default.target diff --git a/llm-server/llm/ansible/roles/model_store/defaults/main.yml b/llm-server/llm/ansible/roles/model_store/defaults/main.yml index 7bb3369..f366a75 100644 --- a/llm-server/llm/ansible/roles/model_store/defaults/main.yml +++ b/llm-server/llm/ansible/roles/model_store/defaults/main.yml @@ -62,5 +62,24 @@ model_store_vision_artifact: license: >- Qwen base model Apache-2.0; Swift changes under Swift Open License 1.0. +# The embedding model is only needed by the Production environment (gpt- +# researcher M8, GNAI-023); Testing does not run a research harness. +model_store_include_embedding: false + +model_store_embedding_artifact: + profile: nomic-embed-text-v2-moe-q8 + directory: nomic-embed-text-v2-moe + file: nomic-embed-text-v2-moe.Q8_0.gguf + sha256: 06e7a7e594a26985523c18383aba4aad39fe6e14f08ffc6ab5b554e1ccdc3cff + url: https://huggingface.co/nomic-ai/nomic-embed-text-v2-moe-GGUF/resolve/ffbcf4c99e5d617dda10ec8c0e9f75754b0cbb80/nomic-embed-text-v2-moe.Q8_0.gguf + repository: nomic-ai/nomic-embed-text-v2-moe-GGUF + revision: ffbcf4c99e5d617dda10ec8c0e9f75754b0cbb80 + origin: >- + Nomic Embed Text v2 MoE, Q8_0 (~488 MiB, ~305M params) — SoTA + multilingual (~100 languages) text embedding model, served by a + CPU-only llama.cpp --embeddings sidecar for gpt-researcher (GNAI-023). + SHA-256 from the Hugging Face LFS blob metadata. + license: Apache-2.0 + model_store_directory_mode: "0755" model_store_file_mode: "0644" diff --git a/llm-server/llm/ansible/roles/model_store/tasks/main.yml b/llm-server/llm/ansible/roles/model_store/tasks/main.yml index c002f98..b239f6d 100644 --- a/llm-server/llm/ansible/roles/model_store/tasks/main.yml +++ b/llm-server/llm/ansible/roles/model_store/tasks/main.yml @@ -6,10 +6,8 @@ ansible.builtin.set_fact: model_store_all_artifacts: >- {{ model_store_artifacts - + (model_store_vision_artifact | ternary( - [model_store_vision_artifact], [])) - if model_store_include_vision - else model_store_artifacts }} + + ([model_store_vision_artifact] if model_store_include_vision else []) + + ([model_store_embedding_artifact] if model_store_include_embedding else []) }} tags: - models - service diff --git a/llm-server/llm/ansible/roles/open_webui/README.md b/llm-server/llm/ansible/roles/open_webui/README.md index 58fe2e3..05af408 100644 --- a/llm-server/llm/ansible/roles/open_webui/README.md +++ b/llm-server/llm/ansible/roles/open_webui/README.md @@ -44,6 +44,29 @@ Lang laufende Research-Loops (mehrere search_web/fetch_url-Runden) brauchen auf dem NPM-Proxy-Host `chat.ghostnet.selfhost.eu` erhöhte Proxy-Timeouts (siehe GNAI-020 Abschnitt NPM). +## Deep Research (GNAI-022, M6-R1 / Phase 1) + +Die Pipe-Function `gnai-deep-research` (`files/gnai-deep-research-pipe.py`, +Content per sha256 gepinnt) wird idempotent in die `function`-Tabelle von +`webui.db` geseeded (type `pipe`, `is_active=1`) und erhält einen public read +`access_grant` (resource_type `model`) — dadurch erscheint sie im +Model-Selector als „gnai-deep-research". Valves (Engine, SearXNG, Iterationen, +Fetch-Limits) liegen in `defaults/main.yml`. Der Loop ruft die Engine direkt +über `http://llama-cpp:8080/v1` (kein OWUI-Auth nötig) und SearXNG über +`http://searxng:8080`; Seiten-Fetch mit SSRF-Guard (keine privaten/loopback/ +link-local IPs), Redirect-Chain mit Re-Validierung, Content-Cap und Timeout. +Nach jeder Code-Änderung `sha256sum` neu berechnen und +`open_webui_deep_research_pipe_sha256` aktualisieren. Sichtbarkeit im +Model-Selector: Pipe braucht zusätzlich eine Zeile in der `model`-Tabelle +(ohne sie sind Pipes admin-only) + public read grant — beides seedet die Rolle. + +## Branding (GNAI-021) + +`files/branding/` (Geist-Favicons + `custom.css` Theme „gnai-catppuccin-mocha") +wird nach `open_webui_branding_dir` deployt und per read-only Mounts in +`/app/backend/open_webui/static/` des Image gemountet — update-persistent, +da OpenWebUIs Start-Wipe von `static/` ro-Mounts nicht anfassen kann. +Datei-Ersetzen erzeugt einen neuen Inode, daher notify Restart. ## Theme (GNAI-021): GNMON Catppuccin Mocha als Default - `files/theme/gnai-catppuccin-mocha.css` wird nach diff --git a/llm-server/llm/ansible/roles/open_webui/defaults/main.yml b/llm-server/llm/ansible/roles/open_webui/defaults/main.yml index 8ecceee..d7a08db 100644 --- a/llm-server/llm/ansible/roles/open_webui/defaults/main.yml +++ b/llm-server/llm/ansible/roles/open_webui/defaults/main.yml @@ -27,12 +27,41 @@ open_webui_egress_network_name: gnai-production-egress # Engine model exposed in the chat UI. The model is synced into the OpenWebUI # DB and granted public read access (access_grant principal user "*"), so # every authenticated OIDC user sees it (GNAI-005: anwendungsbezogene Rechte). +# The id stays stable (grants, API callers); the display name is cosmetic. open_webui_engine_model_id: swift-1.5-qwen3.8-27b-q6k +open_webui_engine_model_name: "Qwen 3.8 27B (Swift 1.5)" +# Default model preselected in the model picker of new chats. v0.13 expects +# ui.default_models as a COMMA-SEPARATED STRING (Chat.svelte calls .split on +# it) — a JSON list crashes the page with "default_models.split is not a +# function". DB config wins over the DEFAULT_MODELS env var. +open_webui_default_models: "{{ open_webui_engine_model_id }}" # Workspace tool (API agents): SearXNG wrapper seeded into the OpenWebUI DB # with a public read grant. API callers pass this id in `tool_ids`. open_webui_web_search_tool_id: gnai-web-search +# Deep-Research pipe (GNAI-022, M6-R1 / Roadmap Phase 1): iterative +# plan->search->fetch->synthesize loop exposed as a pipe "model" in the +# model selector. Seeded idempotently into webui.db; content pinned by +# sha256 (recompute after every edit of files/gnai-deep-research-pipe.py: +# sha256sum files/gnai-deep-research-pipe.py). +open_webui_deep_research_function_id: gnai-deep-research +open_webui_deep_research_display_name: "Deep Research" +open_webui_deep_research_pipe_sha256: "45cb3be0029937fdde7d70018d63191101fba8151dcf55e5566c464584b54c9b" +open_webui_deep_research_valves: + ENGINE_BASE_URL: "{{ open_webui_engine_base_url }}" + ENGINE_MODEL_ID: "{{ open_webui_engine_model_id }}" + SEARXNG_URL: "http://searxng:8080" + MAX_ITERATIONS: 5 + QUERIES_PER_ROUND: 4 + RESULTS_PER_QUERY: 6 + PAGES_PER_ROUND: 5 + FETCH_TIMEOUT_S: 12.0 + FETCH_MAX_BYTES: 200000 + PAGE_TEXT_CHARS: 5000 + MAX_TOKENS: 4096 + TEMPERATURE: 0.3 + # Engine endpoint inside the shared Production network. llama.cpp itself # has no auth; OpenWebUI just needs a non-empty key value, supplied via a # Podman secret (never in git). @@ -115,6 +144,12 @@ open_webui_env: # existed only in legacy versions and is gone in v0.13.3. ENABLE_WEB_SEARCH: "True" WEB_SEARCH_ENGINE: searxng + # No Ollama on this host: without this the UI calls /ollama/api/version on + # every model-list open and surfaces HTTP 500 "could not connect to Ollama". + # NOTE: the persisted DB config (ollama.enable) wins over this env var, so + # the DB sync task below also sets ollama.enable=false. + ENABLE_OLLAMA_API: "False" + DEFAULT_MODELS: "{{ open_webui_engine_model_id }}" # v0.13.3 strips any query string from the URL and sends q/format=json # itself (retrieval/web/searxng.py), so the placeholder form is # correct. diff --git a/llm-server/llm/ansible/roles/open_webui/files/gnai-deep-research-pipe.py b/llm-server/llm/ansible/roles/open_webui/files/gnai-deep-research-pipe.py new file mode 100644 index 0000000..f4fcac4 --- /dev/null +++ b/llm-server/llm/ansible/roles/open_webui/files/gnai-deep-research-pipe.py @@ -0,0 +1,353 @@ +""" +title: gnai-deep-research +author: ghostnet.ai +description: Iterativer Deep-Research-Loop (plan -> SearXNG-Suche -> Seiten-Fetch -> Synthese mit Quellenangaben) als Pipe-Model. Ruft die Production-Engine direkt ueber das interne Netz (llama.cpp, kein Host-Port) und die bestehende SearXNG-Instanz. Läuft serverseitig in OpenWebUI (v0.13.3). +license: MIT +""" + +import asyncio +import ipaddress +import json +import re +import socket +from typing import Any, AsyncIterator +from urllib.parse import urlparse + +import httpx +from pydantic import BaseModel, Field + +try: + from bs4 import BeautifulSoup +except ImportError: # pragma: no cover - bs4 ist im OpenWebUI-Image vorhanden + BeautifulSoup = None + + +# NOTE: no str.format() on these prompts — the JSON braces {"queries": ...} +# would be parsed as format fields (KeyError). Use .replace() for {qpr}. +PLANNER_SYSTEM = ( + "You are a research planner. Given the user's research question and the " + "conversation so far, produce a JSON object with key \"queries\" holding a " + "list of up to {qpr} concrete, diverse web search queries (English and the " + "user's language). Answer with JSON only, no prose." +) + +SYNTH_SYSTEM = ( + "You are a research analyst. You receive search results and fetched page " + "excerpts, each tagged with a citation number [n]. Decide whether the " + "material answers the user's research question.\n" + "If more research is needed, answer JSON only with keys \"status\" = " + "\"continue\" and \"next_queries\" = list of up to {qpr} follow-up queries " + "that close the gaps.\n" + "If done, answer JSON only with keys \"status\" = \"done\" and \"report\" = " + "markdown report in the user's language, citing claims with [n] markers.\n" + "Never invent citations; only use numbers of sources actually provided." +) + + +class Pipe: + class Valves(BaseModel): + ENGINE_BASE_URL: str = Field( + default="http://llama-cpp:8080/v1", + description="OpenAI-kompatibles Engine-Ende im Production-Netz (llama.cpp, ohne Auth).", + ) + ENGINE_MODEL_ID: str = Field( + default="swift-1.5-qwen3.8-27b-q6k", + description="Modell- alias auf der Engine (muss zum Model-Store passen).", + ) + SEARXNG_URL: str = Field( + default="http://searxng:8080", + description="Interne SearXNG-Instanz (Egress-Netz).", + ) + MAX_ITERATIONS: int = Field(default=5, ge=1, le=10) + QUERIES_PER_ROUND: int = Field(default=4, ge=1, le=8) + RESULTS_PER_QUERY: int = Field(default=6, ge=1, le=20) + PAGES_PER_ROUND: int = Field(default=5, ge=1, le=10) + FETCH_TIMEOUT_S: float = Field(default=12.0, gt=0, le=60) + FETCH_MAX_BYTES: int = Field(default=200_000, ge=10_000, le=1_000_000) + PAGE_TEXT_CHARS: int = Field( + default=5000, + ge=1000, + le=20000, + description="Textlaenge pro gefetchter Seite im Synthese-Kontext.", + ) + MAX_TOKENS: int = Field( + default=4096, + ge=512, + le=16384, + description="max_tokens pro Engine-Call. Wichtig: ohne Limit laeuft das " + "xhigh-Profil bis n_predict (32k) und der NPM proxy_read_timeout (600 s) " + "bricht den Stream ab.", + ) + TEMPERATURE: float = Field(default=0.3, ge=0, le=2) + + def __init__(self): + self.valves = self.Valves() + + # ---------- helpers ---------- + + @staticmethod + def _user_text(body: dict, metadata: dict | None) -> str: + md = metadata or {} + prompt = md.get("user_prompt") + if prompt: + return str(prompt) + for msg in reversed(body.get("messages", [])): + if msg.get("role") != "user": + continue + content = msg.get("content") + if isinstance(content, str): + return content + if isinstance(content, list): + return "\n".join( + p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text" + ) + return "" + + @staticmethod + def _history(body: dict) -> list[dict]: + out = [] + for msg in body.get("messages", []): + if msg.get("role") not in ("user", "assistant"): + continue + content = msg.get("content") + if isinstance(content, list): + content = "\n".join( + p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text" + ) + if isinstance(content, str) and content: + out.append({"role": msg["role"], "content": content}) + return out[-8:] + + @staticmethod + def _extract_json(text: str) -> dict: + text = text.strip() + m = re.search(r"\{.*\}", text, re.DOTALL) + if m: + try: + return json.loads(m.group(0)) + except json.JSONDecodeError: + pass + try: + return json.loads(text) + except json.JSONDecodeError: + return {} + + @staticmethod + def _safe_url(url: str) -> bool: + """SSRF-Schutz: nur http(s), keine privaten/loopback/reserved IPs.""" + try: + p = urlparse(url) + if p.scheme not in ("http", "https") or not p.hostname: + return False + if p.hostname.lower() in ("localhost", "127.0.0.1", "::1"): + return False + infos = socket.getaddrinfo(p.hostname, None) + for info in infos: + ip = ipaddress.ip_address(info[4][0]) + if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved: + return False + return True + except Exception: + return False + + async def _engine(self, client: httpx.AsyncClient, messages: list[dict], emitter: Any = None) -> str: + # max_tokens begrenzt JEDEN Engine-Call: das xhigh-Profil denkt sonst + # bis n_predict (32k) und der NPM-Read-Timeout killt den Stream. + if emitter is not None: + await self._emit(emitter, "Engine-Antwort wird erzeugt (max_tokens begrenzt) …") + resp = await client.post( + f"{self.valves.ENGINE_BASE_URL.rstrip('/')}/chat/completions", + json={ + "model": self.valves.ENGINE_MODEL_ID, + "messages": messages, + "temperature": self.valves.TEMPERATURE, + "stream": False, + "max_tokens": self.valves.MAX_TOKENS, + }, + timeout=max(120.0, self.valves.MAX_TOKENS / 5.0), + ) + resp.raise_for_status() + data = resp.json() + return data["choices"][0]["message"]["content"] or "" + + async def _search(self, client: httpx.AsyncClient, query: str) -> list[dict]: + try: + resp = await client.get( + f"{self.valves.SEARXNG_URL.rstrip('/')}/search", + params={"q": query, "format": "json", "safesearch": "1"}, + timeout=20.0, + ) + resp.raise_for_status() + results = resp.json().get("results", []) + return [ + {"url": r.get("url", ""), "title": r.get("title", ""), "snippet": r.get("content", "")} + for r in results + if r.get("url") + ][: self.valves.RESULTS_PER_QUERY] + except Exception: + return [] + + async def _fetch(self, client: httpx.AsyncClient, url: str) -> str: + """holt eine Seite mit Redirect-Chain (jede Hop neu validiert) und Content-Cap.""" + current = url + for _ in range(3): + if not self._safe_url(current): + return "" + try: + resp = await client.get( + current, + follow_redirects=False, + timeout=self.valves.FETCH_TIMEOUT_S, + headers={"User-Agent": "gnai-deep-research/0.1 (+selfhosted research pipe)"}, + ) + except Exception: + return "" + if resp.is_redirect: + location = resp.headers.get("location", "") + if not location: + return "" + from urllib.parse import urljoin + + current = urljoin(current, location) + continue + if resp.status_code != 200: + return "" + ctype = resp.headers.get("content-type", "") + if "html" not in ctype and "text" not in ctype and "json" not in ctype and "xml" not in ctype: + return "" + raw = b"" + async for chunk in resp.aiter_bytes(65536): + raw += chunk + if len(raw) > self.valves.FETCH_MAX_BYTES: + raw = raw[: self.valves.FETCH_MAX_BYTES] + break + text = raw.decode("utf-8", errors="replace") + if "html" in ctype and BeautifulSoup is not None: + text = BeautifulSoup(text, "html.parser").get_text("\n") + text = re.sub(r"\n{3,}", "\n\n", text) + return text[: self.valves.FETCH_MAX_BYTES] + return "" + + async def _emit(self, emitter: Any, text: str) -> None: + if emitter is not None: + try: + await emitter({"type": "status", "data": {"description": text, "done": False}}) + except Exception: + pass + + # ---------- pipe ---------- + + async def pipe( + self, + body: dict, + __metadata__: dict | None = None, + __user__: dict | None = None, + __event_emitter__: Any = None, + ) -> AsyncIterator[str] | str: + v = self.valves + question = self._user_text(body, __metadata__) + if not question: + return "No user question found in the request." + history = self._history(body) + if history and history[-1]["role"] == "user" and history[-1]["content"] == question: + history = history[:-1] + + sources: list[dict] = [] # {n, url, title} + seen_urls: set[str] = set() + + async def run() -> AsyncIterator[str]: + nonlocal sources + async with httpx.AsyncClient(timeout=30.0) as client: + queries: list[str] = [] + for round_no in range(1, v.MAX_ITERATIONS + 1): + # 1) planen (Runde 1) bzw. Luecken schliessen (Folgerunden) + if round_no == 1 or not queries: + plan_msgs = [ + {"role": "system", "content": PLANNER_SYSTEM.replace("{qpr}", str(v.QUERIES_PER_ROUND))}, + *history, + {"role": "user", "content": f"Research question: {question}"}, + ] + await self._emit(__event_emitter__, f"Runde {round_no}: plane Suchanfragen …") + plan = self._extract_json(await self._engine(client, plan_msgs, __event_emitter__)) + queries = [q for q in plan.get("queries", []) if isinstance(q, str)][: v.QUERIES_PER_ROUND] + if not queries: + queries = [question] + + # 2) suchen + await self._emit(__event_emitter__, f"Runde {round_no}: {len(queries)} Suchanfragen …") + found: list[dict] = [] + for q in queries: + for r in await self._search(client, q): + if r["url"] not in seen_urls: + seen_urls.add(r["url"]) + r["query"] = q + found.append(r) + + # 3) Top-Seiten parallel fetchen (mit SSRF-Guard) + targets = found[: v.PAGES_PER_ROUND] + for r in targets: + await self._emit(__event_emitter__, f"Lese {r['url'][:100]} …") + texts = await asyncio.gather(*(self._fetch(client, r["url"]) for r in targets)) + pages: list[dict] = [] + for r, text in zip(targets, texts): + if text: + sources.append({"n": len(sources) + 1, "url": r["url"], "title": r["title"] or r["url"]}) + pages.append({"n": sources[-1]["n"], "url": r["url"], "title": sources[-1]["title"], "text": text[: v.PAGE_TEXT_CHARS]}) + + findings = "\n\n".join( + f"[{p['n']}] {p['title']} ({p['url']})\n{p['text']}" for p in pages + ) or "(keine neuen Seiteninhalte)" + snippets = "\n".join( + f"- {r['title']}: {r['snippet'][:200]} ({r['url']})" for r in found[:10] + ) + + # 4) synthetisieren / Luecken bewerten + synth_msgs = [ + {"role": "system", "content": SYNTH_SYSTEM.replace("{qpr}", str(v.QUERIES_PER_ROUND))}, + *history, + {"role": "user", "content": f"Research question: {question}\n\nSearch-result snippets:\n{snippets}\n\nFetched pages:\n{findings}"}, + ] + await self._emit(__event_emitter__, f"Runde {round_no}: synthetisiere Zwischenergebnis …") + verdict = self._extract_json(await self._engine(client, synth_msgs, __event_emitter__)) + if verdict.get("status") == "done" and verdict.get("report"): + report = str(verdict["report"]) + if sources: + report += "\n\n## Quellen\n" + "\n".join( + f"[{s['n']}] {s['title']} — {s['url']}" for s in sources + ) + yield report + return + queries = [ + q for q in verdict.get("next_queries", []) if isinstance(q, str) + ][: v.QUERIES_PER_ROUND] + if not queries: + break + + # Max-Iterationen erreicht: trotzdem ein Report aus dem akkumulierten Material + if sources: + final_msgs = [ + {"role": "system", "content": SYNTH_SYSTEM.replace("{qpr}", "0")}, + *history, + {"role": "user", "content": f"Research question: {question}\n\nAccumulated sources (iteration limit reached, write the best possible report now):\n" + "\n\n".join( + f"[{s['n']}] {s['title']} ({s['url']})" for s in sources + )}, + ] + verdict = self._extract_json(await self._engine(client, final_msgs, __event_emitter__)) + report = verdict.get("report") or "(kein Report erzeugt)" + report += "\n\n## Quellen\n" + "\n".join( + f"[{s['n']}] {s['title']} — {s['url']}" for s in sources + ) + yield report + return + yield "Recherche ohne brauchbare Quellen. Bitte Frage präzisieren." + + if body.get("stream"): + return run() + # non-streaming: Generator konsumieren und als eine Completion zurückgeben + chunks: list[str] = [] + try: + async for chunk in run(): + chunks.append(chunk) + except Exception as e: + return f"Deep-Research-Fehler: {type(e).__name__}: {e}" + return "".join(chunks) diff --git a/llm-server/llm/ansible/roles/open_webui/tasks/main.yml b/llm-server/llm/ansible/roles/open_webui/tasks/main.yml index 06a9b48..47f6e83 100644 --- a/llm-server/llm/ansible/roles/open_webui/tasks/main.yml +++ b/llm-server/llm/ansible/roles/open_webui/tasks/main.yml @@ -286,23 +286,26 @@ # params stay empty. Idempotent; touches only the app DB, no secrets. ansible.builtin.shell: | set -euo pipefail - python3 - "{{ open_webui_data_dir }}/webui.db" "{{ open_webui_engine_model_id }}" <<'PYEOF' + python3 - "{{ open_webui_data_dir }}/webui.db" "{{ open_webui_engine_model_id }}" "{{ open_webui_engine_model_name }}" <<'PYEOF' import json, sqlite3, sys, time, uuid - db, model_id = sys.argv[1], sys.argv[2] + db, model_id, model_name = sys.argv[1], sys.argv[2], sys.argv[3] con = sqlite3.connect(db) now = int(time.time()) changed = False - row = con.execute("select id, meta from model where id=?", (model_id,)).fetchone() + row = con.execute("select id, name, meta from model where id=?", (model_id,)).fetchone() if not row: con.execute( "insert into model (id, user_id, base_model_id, name, params, meta, is_active, version_id, created_at, updated_at)" " values (?,?,?,?,?,?,?,?,?,?)", - (model_id, "openwebui", None, model_id, "{}", "{}", 1, str(uuid.uuid4()), now, now), + (model_id, "openwebui", None, model_name, "{}", "{}", 1, str(uuid.uuid4()), now, now), ) changed = True meta = {} else: - meta = json.loads(row[1] or "{}") + meta = json.loads(row[2] or "{}") + if row[1] != model_name: + con.execute("update model set name=?, updated_at=? where id=?", (model_name, now, model_id)) + changed = True caps = meta.get("capabilities") or {} builtin = meta.get("builtinTools") or {} meta["capabilities"] = caps @@ -379,6 +382,13 @@ web.search.result_count: "{{ open_webui_env.WEB_SEARCH_RESULT_COUNT | int }}" web.search.concurrent_requests: "{{ open_webui_env.WEB_SEARCH_CONCURRENT_REQUESTS | int }}" web.fetch.max_content_length: "{{ open_webui_env.WEB_FETCH_MAX_CONTENT_LENGTH | int }}" + # DB config wins over env in v0.13: without ollama.enable=false the UI + # still calls /ollama/api/version on every model-list open (HTTP 500, + # no Ollama on this host). ui.default_models preselects the engine model + # in new chats. + ollama.enable: false + # comma-separated string, NOT a JSON list (Chat.svelte does .split(",")) + ui.default_models: "{{ open_webui_default_models }}" when: not ansible_check_mode register: open_webui_web_config_sync changed_when: open_webui_web_config_sync.stdout_lines | first == 'CHANGED' @@ -459,6 +469,142 @@ changed_when: false when: not ansible_check_mode +- name: Stage the deep-research pipe source and verify its pinned sha256 + # GNAI-022 (M6-R1 Phase 1): the pipe content is pinned by sha256 so a + # silent upstream edit can never reach the server; the DB sync task below + # reports the real change. + block: + - name: Stage the pipe source + ansible.builtin.copy: + src: files/gnai-deep-research-pipe.py + dest: /tmp/gnai-deep-research-pipe.py + mode: "0600" + changed_when: false + + - name: Verify the pipe sha256 against the pinned value + ansible.builtin.command: + argv: + - sha256sum + - /tmp/gnai-deep-research-pipe.py + register: open_webui_pipe_hash + changed_when: false + failed_when: >- + open_webui_pipe_hash.stdout.split()[0] != open_webui_deep_research_pipe_sha256 + +- name: Ensure the deep-research pipe exists, is active and publicly readable in OpenWebUI + # Pipe functions (type='pipe') appear in the model selector with + # id=function.id; non-admin users only see them when a row in the `model` + # table exists for that id (plus a public read access_grant on + # resource_type='model'). Both are seeded here. Valves are stored as plain + # JSON (no secret fields). Idempotent; touches only the app DB. + ansible.builtin.shell: | + set -euo pipefail + python3 - "{{ open_webui_data_dir }}/webui.db" \ + /tmp/gnai-deep-research-pipe.py \ + '{{ open_webui_deep_research_valves | to_json }}' \ + "{{ open_webui_deep_research_function_id }}" \ + "{{ open_webui_deep_research_display_name }}" <<'PYEOF' + import json, sqlite3, sys, time, uuid + db, content_path, valves_raw, fn_id, fn_name = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] + content = open(content_path).read() + valves = json.loads(valves_raw) + meta = json.dumps({"description": "Iterativer Deep-Research-Loop (plan -> SearXNG -> fetch -> Synthese) auf der Production-Engine. GNAI-022 / GNAI-001 M6-R1."}) + now = int(time.time()) + con = sqlite3.connect(db) + changed = False + row = con.execute("select content, valves, meta, type, is_active, is_global, name from function where id=?", (fn_id,)).fetchone() + if not row: + con.execute( + "insert into function (id, version_id, user_id, name, type, content, meta, valves, is_active, is_global, updated_at, created_at)" + " values (?,?,?,?,?,?,?,?,?,?,?,?)", + (fn_id, str(uuid.uuid4()), "openwebui", fn_name, "pipe", content, meta, json.dumps(valves), 1, 0, now, now), + ) + changed = True + elif ( + row[0] != content + or json.loads(row[1] or "{}") != valves + or row[2] != meta + or row[3] != "pipe" + or row[4] != 1 + or row[5] != 0 + or row[6] != fn_name + ): + con.execute( + "update function set content=?, valves=?, meta=?, type='pipe', is_active=1, is_global=0, name=?, updated_at=?, version_id=? where id=?", + (content, json.dumps(valves), meta, fn_name, now, str(uuid.uuid4()), fn_id), + ) + changed = True + grant = con.execute( + "select id from access_grant where resource_type='model' and resource_id=? and principal_type='user' and principal_id='*' and permission='read'", + (fn_id,), + ).fetchone() + if not grant: + con.execute( + "insert into access_grant (id, resource_type, resource_id, principal_type, principal_id, permission, created_at)" + " values (?,?,?,?,?,?,?)", + (str(uuid.uuid4()), "model", fn_id, "user", "*", "read", now), + ) + changed = True + # model row: without it, pipe models are visible to admins only + # (open-webui issue: "Pipe models without a model entry are shown to + # admins only"). With row + grant, every OIDC user sees the pipe. + mrow = con.execute("select name, meta, is_active from model where id=?", (fn_id,)).fetchone() + model_meta = json.dumps({"description": "Deep Research: iterativer plan→SearXNG→fetch→Synthese-Loop mit Quellen (GNAI-022). Engine: Production-llama.cpp, SearXNG: kuratiert."}) + if not mrow: + con.execute( + "insert into model (id, user_id, base_model_id, name, params, meta, is_active, version_id, created_at, updated_at)" + " values (?,?,?,?,?,?,?,?,?,?)", + (fn_id, "openwebui", None, fn_name, "{}", model_meta, 1, str(uuid.uuid4()), now, now), + ) + changed = True + elif mrow[0] != fn_name or mrow[1] != model_meta or mrow[2] != 1: + con.execute( + "update model set name=?, meta=?, is_active=1, updated_at=? where id=?", + (fn_name, model_meta, now, fn_id), + ) + changed = True + con.commit() + print("CHANGED" if changed else "UNCHANGED") + PYEOF + args: + executable: /bin/bash + when: not ansible_check_mode + register: open_webui_pipe_sync + changed_when: open_webui_pipe_sync.stdout_lines | first == 'CHANGED' + +- name: Verify the deep-research pipe row and grant in webui.db + ansible.builtin.shell: | + set -euo pipefail + python3 - "{{ open_webui_data_dir }}/webui.db" "{{ open_webui_deep_research_function_id }}" <<'PYEOF' + import json, sqlite3, sys + con = sqlite3.connect(sys.argv[1]) + fn_id = sys.argv[2] + row = con.execute("select type, is_active, valves from function where id=?", (fn_id,)).fetchone() + assert row, "function row missing" + assert row[0] == "pipe" and row[1] == 1, "pipe not active" + valves = json.loads(row[2]) + assert valves.get("SEARXNG_URL"), "SEARXNG_URL valve missing" + grant = con.execute( + "select count(*) from access_grant where resource_type='model' and resource_id=? and principal_type='user' and principal_id='*' and permission='read'", + (fn_id,), + ).fetchone()[0] + assert grant == 1, "public read grant missing" + mrow = con.execute("select is_active from model where id=?", (fn_id,)).fetchone() + assert mrow and mrow[0] == 1, "model row for pipe missing (pipe would be admin-only)" + print("PIPE-OK") + PYEOF + args: + executable: /bin/bash + register: open_webui_pipe_verify + changed_when: false + failed_when: "'PIPE-OK' not in open_webui_pipe_verify.stdout" + when: not ansible_check_mode + +- name: Remove the staged pipe source + ansible.builtin.file: + path: /tmp/gnai-deep-research-pipe.py + state: absent + changed_when: false - name: Flush handlers before the served checks # Content changes to the ro-mounted files notify "Restart OpenWebUI unit"; # the restart must happen BEFORE the served checks, otherwise they test the diff --git a/llm-server/llm/ansible/roles/open_webui/templates/open-webui.container.j2 b/llm-server/llm/ansible/roles/open_webui/templates/open-webui.container.j2 index 27a6f94..e744435 100644 --- a/llm-server/llm/ansible/roles/open_webui/templates/open-webui.container.j2 +++ b/llm-server/llm/ansible/roles/open_webui/templates/open-webui.container.j2 @@ -21,6 +21,9 @@ Volume={{ open_webui_theme_dir }}/{{ open_webui_theme_file }}:{{ open_webui_them {% for m in open_webui_favicon_mounts %} Volume={{ open_webui_favicon_dir }}/{{ m.host_file }}:{{ m.container_path }}:ro {% endfor %} +# v0.13.3 root route /favicon.png is served from the frontend build dir +# (index.html links /static/* from the backend static mounted above). +Volume={{ open_webui_favicon_dir }}/favicon.png:/app/build/favicon.png:ro # Secrets are injected as environment variables, never written to disk or git. Secret={{ open_webui_webui_secret_key_secret }},type=env,target=WEBUI_SECRET_KEY Secret={{ open_webui_engine_api_key_secret }},type=env,target=OPENAI_API_KEY diff --git a/llm-server/monitoring/ansible/roles/gnmon_firewall/defaults/main.yml b/llm-server/monitoring/ansible/roles/gnmon_firewall/defaults/main.yml index fb60ec4..cd89997 100644 --- a/llm-server/monitoring/ansible/roles/gnmon_firewall/defaults/main.yml +++ b/llm-server/monitoring/ansible/roles/gnmon_firewall/defaults/main.yml @@ -24,6 +24,9 @@ gnmon_firewall_dashboard_allowed_ip: 10.0.0.10 gnmon_firewall_npm_only_ports: - 8080 - 8081 + # GNAI-023 M8: GPT Researcher behind NPM + oauth2-proxy (IAP) + - 8085 + - 8086 # 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). diff --git a/proxmox/lxc/ct-100-dns/ansible/inventories/agent/group_vars/dns_hosts.yml b/proxmox/lxc/ct-100-dns/ansible/inventories/agent/group_vars/dns_hosts.yml index 00f3345..cb0310e 100644 --- a/proxmox/lxc/ct-100-dns/ansible/inventories/agent/group_vars/dns_hosts.yml +++ b/proxmox/lxc/ct-100-dns/ansible/inventories/agent/group_vars/dns_hosts.yml @@ -34,6 +34,8 @@ dns_pihole_hosts_records: - "10.0.0.10 mon.ghostnet.selfhost.eu" # GNAI-001 M6: OpenWebUI via NPM (CT-103). - "10.0.0.10 chat.ghostnet.selfhost.eu" + # GNAI-023 M8: GPT Researcher via NPM (CT-103) + oauth2-proxy. + - "10.0.0.10 research.ghostnet.selfhost.eu" dns_pihole_timezone: Europe/Berlin dns_pihole_database_max_db_days: 30 dns_pihole_secret_name: pihole_web_password diff --git a/proxmox/lxc/ct-100-dns/ansible/inventories/bootstrap/group_vars/dns_hosts.yml b/proxmox/lxc/ct-100-dns/ansible/inventories/bootstrap/group_vars/dns_hosts.yml index 00f3345..cb0310e 100644 --- a/proxmox/lxc/ct-100-dns/ansible/inventories/bootstrap/group_vars/dns_hosts.yml +++ b/proxmox/lxc/ct-100-dns/ansible/inventories/bootstrap/group_vars/dns_hosts.yml @@ -34,6 +34,8 @@ dns_pihole_hosts_records: - "10.0.0.10 mon.ghostnet.selfhost.eu" # GNAI-001 M6: OpenWebUI via NPM (CT-103). - "10.0.0.10 chat.ghostnet.selfhost.eu" + # GNAI-023 M8: GPT Researcher via NPM (CT-103) + oauth2-proxy. + - "10.0.0.10 research.ghostnet.selfhost.eu" dns_pihole_timezone: Europe/Berlin dns_pihole_database_max_db_days: 30 dns_pihole_secret_name: pihole_web_password diff --git a/proxmox/lxc/ct-100-dns/ansible/inventories/production/group_vars/dns_hosts.yml b/proxmox/lxc/ct-100-dns/ansible/inventories/production/group_vars/dns_hosts.yml index 00f3345..cb0310e 100644 --- a/proxmox/lxc/ct-100-dns/ansible/inventories/production/group_vars/dns_hosts.yml +++ b/proxmox/lxc/ct-100-dns/ansible/inventories/production/group_vars/dns_hosts.yml @@ -34,6 +34,8 @@ dns_pihole_hosts_records: - "10.0.0.10 mon.ghostnet.selfhost.eu" # GNAI-001 M6: OpenWebUI via NPM (CT-103). - "10.0.0.10 chat.ghostnet.selfhost.eu" + # GNAI-023 M8: GPT Researcher via NPM (CT-103) + oauth2-proxy. + - "10.0.0.10 research.ghostnet.selfhost.eu" dns_pihole_timezone: Europe/Berlin dns_pihole_database_max_db_days: 30 dns_pihole_secret_name: pihole_web_password diff --git a/proxmox/lxc/ct-100-dns/ansible/roles/dns_pihole/defaults/main.yml b/proxmox/lxc/ct-100-dns/ansible/roles/dns_pihole/defaults/main.yml index f638cfd..972ff2f 100644 --- a/proxmox/lxc/ct-100-dns/ansible/roles/dns_pihole/defaults/main.yml +++ b/proxmox/lxc/ct-100-dns/ansible/roles/dns_pihole/defaults/main.yml @@ -15,6 +15,8 @@ dns_pihole_hosts_records: - "10.0.0.10 mon.ghostnet.selfhost.eu" # GNAI-001 M6: OpenWebUI via NPM (CT-103). - "10.0.0.10 chat.ghostnet.selfhost.eu" + # GNAI-023 M8: GPT Researcher via NPM (CT-103) + oauth2-proxy. + - "10.0.0.10 research.ghostnet.selfhost.eu" dns_pihole_database_max_db_days: 30 dns_pihole_service_name: pihole.service dns_pihole_quadlet_path: /etc/containers/systemd/pihole.container diff --git a/proxmox/lxc/ct-102-keycloak/ansible/playbooks/site.yml b/proxmox/lxc/ct-102-keycloak/ansible/playbooks/site.yml index bed42ff..a87f54f 100644 --- a/proxmox/lxc/ct-102-keycloak/ansible/playbooks/site.yml +++ b/proxmox/lxc/ct-102-keycloak/ansible/playbooks/site.yml @@ -26,3 +26,4 @@ - role: keycloak_firewall - role: keycloak_postgres - role: keycloak_service + - role: keycloak_realm_config diff --git a/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/README.md b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/README.md new file mode 100644 index 0000000..4c9fec3 --- /dev/null +++ b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/README.md @@ -0,0 +1,40 @@ +# keycloak_realm_config + +Idempotente Realm-Konfiguration über die Keycloak Admin REST API (GNAI-023 +M8-T1) — ersetzt das manuelle Klicken in der Admin-UI für wiederkehrende +Objekte (Realm-Rolle `gnai-research-user`, Client `gnai-research` mit +Redirect-Uris/Web-Origits, `groups`-Claim-Mapper, Role-Mapping für `ghost`). + +## Einmaliger Bootstrap (Operator, Admin-UI, Realm `Ghost.net`) + +1. **Clients → Create client**: Client ID `ansible-keycloak-admin`, + publicClient **OFF** (confidential), **Service accounts roles ON**, + Standard flow OFF. +2. Tab **Service account roles** → **Assign role** → Client-Rollen + `realm-management` anhaken: `manage-realm`, `manage-clients`, `manage-users`, + `view-users`. (Falls die Liste dort leer bleibt: Users → + `service-account-ansible-keycloak-admin` → Role mapping → Assign role → + Filter `realm-management` → dieselben vier Rollen.) +3. Tab **Credentials** → Client Secret kopieren. +4. Auf CT 102 (als root): + ``` + install -d -m 0700 /etc/keycloak-ansible + install -m 0600 /dev/null /etc/keycloak-ansible/client_secret + # Secret in /etc/keycloak-ansible/client_secret eintragen + ``` + Secret nie in Git/Chat. + +Danach: `ansible-playbook -i inventories/production playbooks/site.yml` — +die Rolle synct Rolle/Client/Mapper/Mapping idempotent (`changed=0` beim +zweiten Lauf). Änderungen am Sollzustand gebeuren nur noch in +`defaults/main.yml`. + +## Technik + +`files/keycloak_realm_sync.py` (stdlib only, kein Extra-Paket auf CT 102): +Token via Client-Credentials-Grant des Bootstrap-Clients gegen +`http://127.0.0.1:8080/realms/Ghost.net/protocol/openid-connect/token`, dann +GET→POST/PUT gegen `/admin/realms/Ghost.net/...` (Rolle, Client inkl. +PUT bei Drift, dedizierter Client-Scope `-dedicated` mit +`oidc-usermodel-realm-role-mapper` auf Claim `groups`, Role-Mapping des +Users). Ausgabe `CHANGED`/`UNCHANGED` für `changed_when`. diff --git a/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/defaults/main.yml b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/defaults/main.yml new file mode 100644 index 0000000..19ff766 --- /dev/null +++ b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/defaults/main.yml @@ -0,0 +1,33 @@ +--- +# Idempotent realm configuration via the Keycloak Admin REST API (GNAI-023 +# M8-T1, replaces manual admin-UI clicking). Runs on CT 102 against the local +# Keycloak (127.0.0.1:8080), authenticating as a service account of the +# bootstrap client below. +# +# One-time bootstrap (operator, admin UI, realm Ghost.net) — see README: +# Clients -> Create client: clientId `ansible-keycloak-admin`, +# publicClient=false, serviceAccountsEnabled=true, standardFlow off; +# Service account roles: realm-management -> manage-realm, manage-clients, +# manage-users, view-users. Copy the secret to CT 102: +# install -m 0600 /dev/null /etc/keycloak-ansible/client_secret (als root) +# und Secret eintragen. +keycloak_realm_internal_url: http://10.0.0.4:8080 # Keycloak listens on the CT IP, not loopback (conmon, 10.0.0.4:8080) +keycloak_realm_name: Ghost.net +keycloak_realm_bootstrap_client_id: ansible-keycloak-admin +keycloak_realm_ansible_secret_file: /etc/keycloak-ansible/client_secret + +# Research-IAP objects (GNAI-023 M8-T1): +keycloak_realm_research_role: gnai-research-user +keycloak_realm_research_user: ghost +keycloak_realm_research_client: + clientId: gnai-research + name: Ghostnet Research (oauth2-proxy) + rootUrl: https://research.ghostnet.selfhost.eu + redirectUris: + - https://research.ghostnet.selfhost.eu/oauth2/callback + webOrigins: + - https://research.ghostnet.selfhost.eu + postLogoutRedirectUris: "https://research.ghostnet.selfhost.eu/*" +keycloak_realm_research_mapper: + name: realm-roles-to-groups + claim_name: groups diff --git a/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/files/keycloak_realm_sync.py b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/files/keycloak_realm_sync.py new file mode 100644 index 0000000..06002fe --- /dev/null +++ b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/files/keycloak_realm_sync.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Idempotent Keycloak realm configuration via the Admin REST API. + +Usage: keycloak_realm_sync.py +Prints CHANGED or UNCHANGED (for ansible changed_when). Exits non-zero on API +errors. Only stdlib (urllib) — no extra packages on the Keycloak host. +""" +import json +import sys +import urllib.error +import urllib.parse +import urllib.request + +base, realm, secret_file, spec_file = sys.argv[1:5] +spec = json.load(open(spec_file)) +secret = open(secret_file).read().strip() + +changed = False + + +def req(method, path, body=None): + url = f"{base}{path}" + data = None + headers = {"Authorization": f"Bearer {token}"} + if body is not None: + data = json.dumps(body).encode() + headers["Content-Type"] = "application/json" + r = urllib.request.Request(url, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(r, timeout=15) as resp: + raw = resp.read() + return resp.status, json.loads(raw) if raw else None + except urllib.error.HTTPError as e: + raw = e.read() + try: + return e.code, json.loads(raw) if raw else None + except json.JSONDecodeError: + return e.code, None + + +# --- token via client credentials (service account of the bootstrap client) --- +tok_data = urllib.parse.urlencode({ + "grant_type": "client_credentials", + "client_id": spec["bootstrap_client_id"], + "client_secret": secret, +}).encode() +tok_req = urllib.request.Request( + f"{base}/realms/{realm}/protocol/openid-connect/token", + data=tok_data, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + method="POST", +) +with urllib.request.urlopen(tok_req, timeout=15) as resp: + token = json.loads(resp.read())["access_token"] + +R = f"/admin/realms/{realm}" + +# --- 1) realm role --- +role_name = spec["research_role"] +st, role = req("GET", f"{R}/roles/{urllib.parse.quote(role_name)}") +if st == 404: + st, _ = req("POST", f"{R}/roles", {"name": role_name, "description": "Access to research.ghostnet.selfhost.eu (oauth2-proxy)"}) + assert st == 201, f"create role failed: {st}" + changed = True + st, role = req("GET", f"{R}/roles/{urllib.parse.quote(role_name)}") +assert st == 200 and role, f"role lookup failed: {st}" + +# --- 2) client --- +c = spec["research_client"] +st, clients = req("GET", f"{R}/clients?clientId={urllib.parse.quote(c['clientId'])}") +assert st == 200, f"client lookup failed: {st}" +client_body = { + "clientId": c["clientId"], + "name": c["name"], + "enabled": True, + "protocol": "openid-connect", + "publicClient": False, + "standardFlowEnabled": True, + "directAccessGrantsEnabled": False, + "implicitFlowEnabled": False, + "serviceAccountsEnabled": False, + "rootUrl": c["rootUrl"], + "redirectUris": c["redirectUris"], + "webOrigins": c["webOrigins"], + "attributes": {"post.logout.redirect.uris": c["postLogoutRedirectUris"]}, +} +if not clients: + st, _ = req("POST", f"{R}/clients", client_body) + assert st == 201, f"create client failed: {st}" + changed = True + st, clients = req("GET", f"{R}/clients?clientId={urllib.parse.quote(c['clientId'])}") +client = clients[0] +cuuid = client["id"] +# idempotent update: PUT the full desired state if any field differs +st, current = req("GET", f"{R}/clients/{cuuid}") +assert st == 200 +drift = False +for k, v in client_body.items(): + if k == "attributes": + # Keycloak stores many default attributes; only compare our own key + cur_attrs = current.get("attributes") or {} + for ak, av in v.items(): + if cur_attrs.get(ak) != av: + drift = True + print(f"DRIFT attributes.{ak}: current={cur_attrs.get(ak)!r} wanted={av!r}", file=sys.stderr) + break + continue + if current.get(k) != v: + drift = True + print(f"DRIFT {k}: current={current.get(k)!r} wanted={v!r}", file=sys.stderr) + break +if drift: + merged = dict(current) + merged.update(client_body) + st, _ = req("PUT", f"{R}/clients/{cuuid}", merged) + assert st == 204, f"update client failed: {st}" + changed = True + +# --- 3) realm-role -> groups claim mapper on the realm-wide "roles" scope --- +# KC26: /clients/{id}/client-scopes is gone (404) and dedicated scopes are not +# listed globally; the "roles" scope is a default client scope of every new +# client, so the mapper lands there and every such client gets the groups claim. +st, scopes = req("GET", f"{R}/client-scopes") +assert st == 200, f"client-scopes lookup failed: {st}" +roles_scope = [s for s in scopes if s.get("name") == "roles"] +assert roles_scope, "realm-wide 'roles' client scope missing" +scope_id = roles_scope[0]["id"] +m = spec["research_mapper"] +mapper_body = { + "name": m["name"], + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-realm-role-mapper", + "config": { + "claim.name": m["claim_name"], + "multivalued": "true", + "id.token.claim": "true", + "access.token.claim": "true", + "userinfo.token.claim": "true", + "jsonType.label": "String", + }, +} +st, mappers = req("GET", f"{R}/client-scopes/{scope_id}/protocol-mappers/models") +assert st == 200, f"mapper lookup failed: {st}" +if not any(x.get("name") == m["name"] for x in mappers): + st, _ = req("POST", f"{R}/client-scopes/{scope_id}/protocol-mappers/models", mapper_body) + assert st == 201, f"create mapper failed: {st}" + changed = True + +# --- 4) assign realm role to the operator user --- +st, users = req("GET", f"{R}/users?username={urllib.parse.quote(spec['research_user'])}&exact=true") +assert st == 200 and users, f"user {spec['research_user']} not found" +uid = users[0]["id"] +st, assigned = req("GET", f"{R}/users/{uid}/role-mappings/realm") +assert st == 200 +if not any(x.get("name") == role_name for x in assigned): + st, _ = req("POST", f"{R}/users/{uid}/role-mappings/realm", [{"id": role["id"], "name": role["name"]}]) + assert st == 204, f"role mapping failed: {st}" + changed = True + +print("CHANGED" if changed else "UNCHANGED") diff --git a/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/tasks/main.yml b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/tasks/main.yml new file mode 100644 index 0000000..8ccfc12 --- /dev/null +++ b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/tasks/main.yml @@ -0,0 +1,67 @@ +--- +- name: Verify the Keycloak realm config role declarations + ansible.builtin.assert: + that: + - keycloak_realm_name == 'Ghost.net' + - keycloak_realm_ansible_secret_file is match('^/etc/') + fail_msg: "realm must be Ghost.net and the bootstrap secret must live under /etc" + +- name: Check the bootstrap client secret file (mode 0600, root-owned) + # Created once by the operator (see README / GNAI-023 M8-T1 bootstrap): + # /etc/keycloak-ansible/client_secret with the secret of client + # `ansible-keycloak-admin` (service account, realm-management). + ansible.builtin.stat: + path: "{{ keycloak_realm_ansible_secret_file }}" + register: keycloak_realm_secret_stat + +- name: Fail with bootstrap instructions when the secret is missing or too open + ansible.builtin.fail: + msg: >- + {{ keycloak_realm_ansible_secret_file }} missing or mode != 0600. + Bootstrap once (GNAI-023 M8-T1 / role README): create client + `ansible-keycloak-admin` (confidential, service account, + realm-management manage-realm/manage-clients/manage-users/view-users), + then: install -d -m 0700 /etc/keycloak-ansible && install -m 0600 /dev/null + {{ keycloak_realm_ansible_secret_file }} and write the client secret into it. + when: >- + not keycloak_realm_secret_stat.stat.exists + or keycloak_realm_secret_stat.stat.mode != '0600' + +- name: Stage the realm sync script + ansible.builtin.copy: + src: files/keycloak_realm_sync.py + dest: /tmp/keycloak_realm_sync.py + mode: "0600" + changed_when: false + when: not ansible_check_mode + +- name: Render the realm spec + ansible.builtin.template: + src: keycloak_realm_spec.json.j2 + dest: /tmp/keycloak_realm_spec.json + mode: "0600" + changed_when: false + when: not ansible_check_mode + +- name: Sync the realm objects idempotently (role, client, mapper, role mapping) + ansible.builtin.command: + argv: + - python3 + - /tmp/keycloak_realm_sync.py + - "{{ keycloak_realm_internal_url }}" + - "{{ keycloak_realm_name }}" + - "{{ keycloak_realm_ansible_secret_file }}" + - /tmp/keycloak_realm_spec.json + register: keycloak_realm_sync + changed_when: keycloak_realm_sync.stdout_lines | first == 'CHANGED' + when: not ansible_check_mode + +- name: Remove the staged script and spec + ansible.builtin.file: + path: "/tmp/{{ item }}" + state: absent + loop: + - keycloak_realm_sync.py + - keycloak_realm_spec.json + changed_when: false + when: not ansible_check_mode diff --git a/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/templates/keycloak_realm_spec.json.j2 b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/templates/keycloak_realm_spec.json.j2 new file mode 100644 index 0000000..d360771 --- /dev/null +++ b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/templates/keycloak_realm_spec.json.j2 @@ -0,0 +1,7 @@ +{ + "bootstrap_client_id": {{ keycloak_realm_bootstrap_client_id | to_json }}, + "research_role": {{ keycloak_realm_research_role | to_json }}, + "research_user": {{ keycloak_realm_research_user | to_json }}, + "research_client": {{ keycloak_realm_research_client | to_json }}, + "research_mapper": {{ keycloak_realm_research_mapper | to_json }} +} diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/playbooks/site.yml b/proxmox/lxc/ct-103-reverse-proxy/ansible/playbooks/site.yml index 268f418..3eb3e18 100644 --- a/proxmox/lxc/ct-103-reverse-proxy/ansible/playbooks/site.yml +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/playbooks/site.yml @@ -23,4 +23,6 @@ - role: podman_runtime - role: reverse_proxy_firewall - role: reverse_proxy_npm + - role: reverse_proxy_oauth2proxy + - role: reverse_proxy_research_vhost - role: reverse_proxy_fail2ban diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/README.md b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/README.md new file mode 100644 index 0000000..f550264 --- /dev/null +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/README.md @@ -0,0 +1,28 @@ +# reverse_proxy_oauth2proxy + +oauth2-proxy v7.15.5 als Identity-Aware Proxy auf CT 103 (GNAI-023, Roadmap +M8). Schützt `research.ghostnet.selfhost.eu` (GPT Researcher) über nginx +`auth_request` gegen Keycloak-OIDC (Realm Ghost.net, Client `gnai-research`). + +- **Netzwerk:** `Network=host`, gebunden auf `127.0.0.1:4180` (kein + `PublishPort`) — von LAN/WAN nicht direkt erreichbar; NPM erreicht den + IAP via `auth_request` auf `http://127.0.0.1:4180/oauth2/auth` (202 = ok, + 401 = an Keycloak weiterleiten). Verifiziert durch Task „LAN blocked". +- **Secrets** als rootful Podman-Secrets, nie in Git: + - `oauth2-proxy-cookie-secret` — random 32 B, wird von der Rolle auto-legt. + - `oauth2-proxy-client-secret` — Secret des Keycloak-Clients `gnai-research` + (Operator legt Client in Keycloak an, dann + `printf '%s' '' | podman secret create oauth2-proxy-client-secret -`). +- **Image** digest-gepinnt; beim ersten Rollout Tag pullen, Digest ermitteln + (`podman image inspect --format '{{.Digest}}'`) und in + `reverse_proxy_oauth2proxy_image_ref` eintragen. +- **Härtung** (Env im Quadlet): cookie secure/httponly/samesite=lax, + 24 h Expiry, Session-Store cookie, `--reverse-proxy` (nur loopback-Vertrauen), + `--set-xauthrequest`, kein Access-Token-Pass-Through, `--skip-provider-button`, + `--whitelist-domain=.ghostnet.selfhost.eu`, `--allowed-group=gnai-research-user` + über `--oidc-groups-claim=groups`, `--skip-auth-regex=^/ping$`. +- **NPM-Seite** (M8-T3): vHost `research.ghostnet.selfhost.eu` mit Advanced-Snippet: + interne `location /oauth2/` → `proxy_pass http://127.0.0.1:4180;`, + `location / { auth_request /oauth2/auth; error_page 401 =302 /oauth2/sign_in?rd=$request_uri; … }`, + `location = /oauth2/auth { internal; proxy_pass …; proxy_pass_request_body off; + proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; }`. diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/defaults/main.yml b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/defaults/main.yml new file mode 100644 index 0000000..177bb54 --- /dev/null +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/defaults/main.yml @@ -0,0 +1,45 @@ +--- +# oauth2-proxy (Identity-Aware Proxy) for the research harness route +# (GNAI-023, Roadmap M8). Runs on CT 103 with Network=host, bound to +# 127.0.0.1 only — NPM's generated nginx reaches it via auth_request on +# http://127.0.0.1:4180/oauth2/auth. No published port: not reachable from +# LAN/WAN directly. +# +# Image: pin by digest after the first pull on CT 103: +# podman pull quay.io/oauth2-proxy/oauth2-proxy:v7.15.5 +# podman image inspect ... --format '{{.Digest}}' +reverse_proxy_oauth2proxy_image: quay.io/oauth2-proxy/oauth2-proxy +reverse_proxy_oauth2proxy_image_tag: v7.15.5 +reverse_proxy_oauth2proxy_image_ref: "{{ reverse_proxy_oauth2proxy_image }}@sha256:0d989b27d90d5e527fb2b045d864c4001c3104bdd763b3211b7e9ba2110380ea" # v7.15.5, digest verifiziert 2026-11-17 + +reverse_proxy_oauth2proxy_container_name: oauth2-proxy +reverse_proxy_oauth2proxy_service_name: oauth2-proxy.service +reverse_proxy_oauth2proxy_quadlet_path: /etc/containers/systemd/oauth2-proxy.container +reverse_proxy_oauth2proxy_quadlet_mode: "0644" + +reverse_proxy_oauth2proxy_http_address: 127.0.0.1:4180 +reverse_proxy_oauth2proxy_metrics_address: 127.0.0.1:4181 + +# Keycloak (CT 102, realm Ghost.net) as OIDC IdP. Client `gnai-research` +# (confidential) must exist first — created by the operator in the Keycloak +# admin UI (GNAI-023 M8-T1); its secret goes into the Podman secret below. +reverse_proxy_oauth2proxy_provider: oidc +reverse_proxy_oauth2proxy_oidc_issuer_url: https://auth.ghostnet.selfhost.eu/realms/Ghost.net +reverse_proxy_oauth2proxy_client_id: gnai-research +reverse_proxy_oauth2proxy_redirect_url: https://research.ghostnet.selfhost.eu/oauth2/callback +reverse_proxy_oauth2proxy_scopes: "openid email profile" # "groups" ist kein Keycloak-Client-Scope (invalid_scope); der groups-Claim kommt ueber den roles-Scope-Mapper + +# Authorization: Keycloak realm role mapped onto the `groups` claim. +reverse_proxy_oauth2proxy_allowed_group: gnai-research-user +reverse_proxy_oauth2proxy_oidc_groups_claim: groups +reverse_proxy_oauth2proxy_email_domains: "*" +reverse_proxy_oauth2proxy_whitelist_domain: .ghostnet.selfhost.eu +reverse_proxy_oauth2proxy_skip_auth_regex: "^/ping$" + +reverse_proxy_oauth2proxy_cookie_expire: 24h + +# Podman secrets (rootful store on CT 103), never in git: +# podman secret create oauth2-proxy-cookie-secret - (random 32 bytes, auto-created by this role) +# podman secret create oauth2-proxy-client-secret - (Keycloak client secret of gnai-research, operator) +reverse_proxy_oauth2proxy_cookie_secret_name: oauth2-proxy-cookie-secret +reverse_proxy_oauth2proxy_client_secret_name: oauth2-proxy-client-secret diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/handlers/main.yml b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/handlers/main.yml new file mode 100644 index 0000000..2d245e5 --- /dev/null +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/handlers/main.yml @@ -0,0 +1,11 @@ +--- +- name: Daemon reload CT 103 + ansible.builtin.command: + argv: [systemctl, daemon-reload] + changed_when: false + when: not ansible_check_mode + +- name: Restart oauth2-proxy unit + ansible.builtin.command: + argv: [systemctl, restart, "{{ reverse_proxy_oauth2proxy_service_name }}"] + when: not ansible_check_mode diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/tasks/main.yml b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/tasks/main.yml new file mode 100644 index 0000000..ce09c1f --- /dev/null +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/tasks/main.yml @@ -0,0 +1,107 @@ +--- +- name: Verify oauth2-proxy role declarations + ansible.builtin.assert: + that: + - reverse_proxy_oauth2proxy_image_ref is match('^quay\.io/oauth2-proxy/oauth2-proxy@sha256:[0-9a-f]{64}$') + - reverse_proxy_oauth2proxy_http_address is match('^127\.0\.0\.1:') + fail_msg: >- + oauth2-proxy must be digest-pinned and bound to loopback only. + Pin: podman pull quay.io/oauth2-proxy/oauth2-proxy:v7.15.5, then + podman image inspect --format '{{ '{{' }}.Digest{{ '}}' }}' . + +- name: Check whether the oauth2-proxy cookie secret exists + ansible.builtin.command: + argv: [podman, secret, exists, "{{ reverse_proxy_oauth2proxy_cookie_secret_name }}"] + register: oauth2proxy_cookie_secret_exists + changed_when: false + failed_when: oauth2proxy_cookie_secret_exists.rc not in [0, 1] + check_mode: false + +- name: Create the cookie secret (random 32 bytes, host-local only) + ansible.builtin.shell: | + set -euo pipefail + # base64 of 24 raw bytes = exactly 32 chars: v7.15 validates the string + # length ("must be 16, 24, or 32 bytes"); 32 raw or 44-char base64 fail + head -c 24 /dev/urandom | base64 -w0 | podman secret create {{ reverse_proxy_oauth2proxy_cookie_secret_name }} - + args: + executable: /bin/bash + when: oauth2proxy_cookie_secret_exists.rc == 1 + no_log: true + +- name: Check whether the Keycloak client secret exists + # Created by the operator from the Keycloak client `gnai-research` + # (GNAI-023 M8-T1): podman secret create oauth2-proxy-client-secret - + ansible.builtin.command: + argv: [podman, secret, exists, "{{ reverse_proxy_oauth2proxy_client_secret_name }}"] + register: oauth2proxy_client_secret_exists + changed_when: false + failed_when: false + check_mode: false + +- name: Fail with instructions when the Keycloak client secret is missing + ansible.builtin.fail: + msg: >- + Podman secret {{ reverse_proxy_oauth2proxy_client_secret_name }} missing. + Create the Keycloak client `gnai-research` first (GNAI-023 M8-T1), then: + printf '%s' '' | podman secret create {{ reverse_proxy_oauth2proxy_client_secret_name }} - + when: oauth2proxy_client_secret_exists.rc != 0 + +- name: Check whether the pinned oauth2-proxy image is in the store + ansible.builtin.command: + argv: [podman, image, exists, "{{ reverse_proxy_oauth2proxy_image_ref }}"] + register: oauth2proxy_image_present + changed_when: false + failed_when: oauth2proxy_image_present.rc not in [0, 1] + check_mode: false + +- name: Pull the pinned oauth2-proxy image + ansible.builtin.command: + argv: [podman, pull, "{{ reverse_proxy_oauth2proxy_image_ref }}"] + when: + - not ansible_check_mode + - oauth2proxy_image_present.rc != 0 + +- name: Render the oauth2-proxy quadlet + ansible.builtin.template: + src: oauth2-proxy.container.j2 + dest: "{{ reverse_proxy_oauth2proxy_quadlet_path }}" + mode: "{{ reverse_proxy_oauth2proxy_quadlet_mode }}" + notify: + - Daemon reload CT 103 + - Restart oauth2-proxy unit + +- name: Read the current state of the oauth2-proxy unit + ansible.builtin.command: + argv: [systemctl, is-active, "{{ reverse_proxy_oauth2proxy_service_name }}"] + register: oauth2proxy_unit_state + changed_when: false + # rc 3 = inactive, rc 4 = unit not loaded yet (check mode skips daemon-reload) + failed_when: oauth2proxy_unit_state.rc not in [0, 3, 4] + check_mode: false + +- name: Start the oauth2-proxy unit + ansible.builtin.command: + argv: [systemctl, start, "{{ reverse_proxy_oauth2proxy_service_name }}"] + when: + - not ansible_check_mode + - oauth2proxy_unit_state.rc != 0 + +- name: Wait for the oauth2-proxy ping endpoint (loopback only) + ansible.builtin.uri: + url: "http://{{ reverse_proxy_oauth2proxy_http_address }}/ping" + status_code: 200 + timeout: 5 + register: oauth2proxy_ping + retries: 12 + delay: 5 + until: oauth2proxy_ping.status == 200 + when: not ansible_check_mode + +- name: Verify the IAP is NOT reachable from the LAN address + # The quadlet binds 127.0.0.1 only; a connect to 10.0.0.10:4180 must fail. + ansible.builtin.command: + argv: [sh, -c, "curl -s -o /dev/null --max-time 3 http://10.0.0.10:4180/ping && exit 1 || exit 0"] + register: oauth2proxy_lan_blocked + changed_when: false + failed_when: oauth2proxy_lan_blocked.rc != 0 + when: not ansible_check_mode diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/templates/oauth2-proxy.container.j2 b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/templates/oauth2-proxy.container.j2 new file mode 100644 index 0000000..62045ef --- /dev/null +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_oauth2proxy/templates/oauth2-proxy.container.j2 @@ -0,0 +1,50 @@ +[Unit] +Description=oauth2-proxy identity-aware proxy (GNAI-023 M8, Keycloak OIDC) +After=network-online.target +Wants=network-online.target + +[Container] +Image={{ reverse_proxy_oauth2proxy_image_ref }} +Pull=never +ContainerName={{ reverse_proxy_oauth2proxy_container_name }} +# host network, but bound to loopback only (see OAUTH2_PROXY_HTTP_ADDRESS): +# no PublishPort, so the IAP is unreachable from LAN/WAN; NPM reaches it via +# auth_request on 127.0.0.1:4180. +Network=host +Secret={{ reverse_proxy_oauth2proxy_client_secret_name }},type=env,target=OAUTH2_PROXY_CLIENT_SECRET +Secret={{ reverse_proxy_oauth2proxy_cookie_secret_name }},type=env,target=OAUTH2_PROXY_COOKIE_SECRET +Environment=OAUTH2_PROXY_PROVIDER={{ reverse_proxy_oauth2proxy_provider }} +Environment=OAUTH2_PROXY_OIDC_ISSUER_URL={{ reverse_proxy_oauth2proxy_oidc_issuer_url }} +Environment=OAUTH2_PROXY_CLIENT_ID={{ reverse_proxy_oauth2proxy_client_id }} +Environment=OAUTH2_PROXY_REDIRECT_URL={{ reverse_proxy_oauth2proxy_redirect_url }} +Environment="OAUTH2_PROXY_SCOPE={{ reverse_proxy_oauth2proxy_scopes }}" +Environment=OAUTH2_PROXY_HTTP_ADDRESS={{ reverse_proxy_oauth2proxy_http_address }} +Environment=OAUTH2_PROXY_METRICS_ADDRESS={{ reverse_proxy_oauth2proxy_metrics_address }} +# upstream is never used directly; nginx auth_request only asks /oauth2/auth +Environment=OAUTH2_PROXY_UPSTREAM=static://200 +# behind NPM: trust X-Forwarded-* from loopback only (reverse-proxy mode) +Environment=OAUTH2_PROXY_REVERSE_PROXY=true +Environment=OAUTH2_PROXY_SET_XAUTHREQUEST=true +Environment=OAUTH2_PROXY_PASS_ACCESS_TOKEN=false +Environment=OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER=false +Environment=OAUTH2_PROXY_SET_AUTHORIZATION_HEADER=false +# hardening +Environment=OAUTH2_PROXY_COOKIE_SECURE=true +Environment=OAUTH2_PROXY_COOKIE_HTTPONLY=true +Environment=OAUTH2_PROXY_COOKIE_SAMESITE=lax +Environment=OAUTH2_PROXY_COOKIE_EXPIRE={{ reverse_proxy_oauth2proxy_cookie_expire }} +Environment=OAUTH2_PROXY_SESSION_STORE_TYPE=cookie +Environment=OAUTH2_PROXY_SKIP_PROVIDER_BUTTON=true +Environment=OAUTH2_PROXY_EMAIL_DOMAINS={{ reverse_proxy_oauth2proxy_email_domains }} +Environment=OAUTH2_PROXY_WHITELIST_DOMAIN={{ reverse_proxy_oauth2proxy_whitelist_domain }} +Environment=OAUTH2_PROXY_ALLOWED_GROUP={{ reverse_proxy_oauth2proxy_allowed_group }} +Environment=OAUTH2_PROXY_OIDC_GROUPS_CLAIM={{ reverse_proxy_oauth2proxy_oidc_groups_claim }} +Environment="OAUTH2_PROXY_SKIP_AUTH_REGEX={{ reverse_proxy_oauth2proxy_skip_auth_regex }}" + +[Service] +Restart=on-failure +RestartSec=5 +TimeoutStartSec=120 + +[Install] +WantedBy=multi-user.target diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/README.md b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/README.md new file mode 100644 index 0000000..01b886d --- /dev/null +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/README.md @@ -0,0 +1,33 @@ +# reverse_proxy_research_vhost + +NPM-Proxy-Host `research.ghostnet.selfhost.eu` → `10.0.0.90:8085` (GPT +Researcher, M8-T4), geschützt durch oauth2-proxy via `auth_request` +(GNAI-023 M8-T3). Idempotent über die NPM-API (127.0.0.1:81), inkl. LE-Cert. + +## Einmalig durch den Operator auf CT 103 + +NPM-Admin-Zugang als Datei (nie in Git): + +``` +install -d -m 0700 /etc/nginx-proxy-manager +install -m 0600 /dev/null /etc/nginx-proxy-manager/api.env +# eintragen: +# NPM_API_EMAIL= +# NPM_API_PASSWORD= +``` + +## Danach + +`site.yml` deployt/aktualisiert Cert + Proxy-Host idempotent (`changed=0` beim +zweiten Lauf; der Verify-Task erwartet `UNCHANGED`). Split-DNS-Record +`research.ghostnet.selfhost.eu → 10.0.0.10` kommt aus dem CT-100-Projekt +(`dns_pihole_hosts_records`). + +## auth_request-Muster (advanced_config) + +`auth_request`, `error_page 401` und `auth_request_set` liegen auf **server**- +Ebene (nginx erlaubt das und vererbt es an die generierte `location /`). +Nur `location = /oauth2/auth` ist `internal`; der Rest von `/oauth2/` +(sign_in/start/callback) bleibt extern erreichbar. Identität-Header +(X-Auth-Request-*) werden aktuell nicht an den Upstream durchgereicht — +GPT Researcher braucht sie nicht. diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/defaults/main.yml b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/defaults/main.yml new file mode 100644 index 0000000..db132bc --- /dev/null +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/defaults/main.yml @@ -0,0 +1,88 @@ +--- +# NPM proxy host for the GPT Researcher harness behind the IAP +# (GNAI-023 M8-T3). Managed idempotently via the NPM API (127.0.0.1:81). +# +# NPM admin credentials are read from this root-only file on CT 103 +# (created once by the operator, never in git): +# /etc/nginx-proxy-manager/api.env mode 0600, content: +# NPM_API_EMAIL=admin@example.com +# NPM_API_PASSWORD=... +reverse_proxy_research_npm_api: http://127.0.0.1:81/api +reverse_proxy_research_api_env_file: /etc/nginx-proxy-manager/api.env + +reverse_proxy_research_domain: research.ghostnet.selfhost.eu +reverse_proxy_research_upstream_host: 10.0.0.90 +reverse_proxy_research_upstream_port: 8085 +reverse_proxy_research_api_port: 8086 +reverse_proxy_research_upstream_scheme: http +reverse_proxy_research_letsencrypt_email: ma-koenig@gmx.net +# oauth2-proxy on this host, loopback only (role reverse_proxy_oauth2proxy) +reverse_proxy_research_iap_upstream: http://127.0.0.1:4180 + +# Host-level advanced config ONLY (NPM 2.15.1 quirk: host-level advanced_config +# AND custom locations together silently break conf generation; a location / +# inside advanced_config makes NPM skip its own generated location /). +# - /oauth2/* -> IAP (loopback), /oauth2/auth internal for auth_request +# - /, /api/, /ws each carry auth_request + error_page redirect (per-location, +# server-level inheritance did NOT redirect in practice) +# - big proxy buffers on /oauth2/ (IAP callback Set-Cookie, else 502) +# - /ws websocket upgrade headers + long timeouts; /api 600 s +reverse_proxy_research_advanced_config: | + location /oauth2/ { + proxy_pass {{ reverse_proxy_research_iap_upstream }}; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffer_size 64k; + proxy_buffers 16 64k; + proxy_busy_buffers_size 128k; + } + location = /oauth2/auth { + internal; + proxy_pass {{ reverse_proxy_research_iap_upstream }}/oauth2/auth; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header X-Original-URI $request_uri; + proxy_set_header X-Original-URL $scheme://$host$request_uri; + } + location / { + auth_request /oauth2/auth; + error_page 401 =302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + auth_request_set $auth_user $upstream_http_x_auth_request_user; + auth_request_set $auth_email $upstream_http_x_auth_request_email; + proxy_pass http://{{ reverse_proxy_research_upstream_host }}:{{ reverse_proxy_research_upstream_port }}; + proxy_set_header Host $host; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $http_connection; + } + location /api/ { + auth_request /oauth2/auth; + error_page 401 =302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + proxy_pass http://{{ reverse_proxy_research_upstream_host }}:{{ reverse_proxy_research_api_port }}; + proxy_set_header Host $host; + proxy_read_timeout 600s; + proxy_send_timeout 600s; + } + # report downloads (pdf/docx/md/json): the backend serves /outputs via + # StaticFiles; gptr-nextjs prepends "outputs/" to the backend path which + # already contains it -> collapse the doubled prefix before proxying + location /outputs/ { + auth_request /oauth2/auth; + error_page 401 =302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + rewrite ^/outputs/outputs/(.*)$ /outputs/$1 break; + proxy_pass http://{{ reverse_proxy_research_upstream_host }}:{{ reverse_proxy_research_api_port }}; + proxy_set_header Host $host; + } + location /ws { + auth_request /oauth2/auth; + error_page 401 =302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + proxy_pass http://{{ reverse_proxy_research_upstream_host }}:{{ reverse_proxy_research_api_port }}; + proxy_set_header Host $host; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $http_connection; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + } diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/files/npm_research_vhost.py b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/files/npm_research_vhost.py new file mode 100644 index 0000000..407ab88 --- /dev/null +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/files/npm_research_vhost.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Idempotent NPM proxy-host + LE certificate for research.ghostnet.selfhost.eu +behind the oauth2-proxy IAP. Usage: + + npm_research_vhost.py + +Prints CHANGED/UNCHANGED. stdlib only. +""" +import json +import sys +import urllib.error +import urllib.parse +import urllib.request + +api, env_file, spec_file = sys.argv[1:4] +spec = json.load(open(spec_file)) + +env = {} +for line in open(env_file): + line = line.strip() + if line and not line.startswith("#") and "=" in line: + k, v = line.split("=", 1) + env[k.strip()] = v.strip() +email = env["NPM_API_EMAIL"] +password = env["NPM_API_PASSWORD"] + +changed = False + + +def req(method, path, body=None, token=None): + url = f"{api}{path}" + data = None + headers = {} + if token: + headers["Authorization"] = f"Bearer {token}" + if body is not None: + data = json.dumps(body).encode() + headers["Content-Type"] = "application/json" + r = urllib.request.Request(url, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(r, timeout=30) as resp: + raw = resp.read() + return resp.status, json.loads(raw) if raw else None + except urllib.error.HTTPError as e: + raw = e.read() + try: + return e.code, json.loads(raw) if raw else None + except json.JSONDecodeError: + return e.code, raw[:300] + + +st, tok = req("POST", "/tokens", {"identity": email, "secret": password}) +assert st == 200 and tok and tok.get("token"), f"npm token failed: {st} {tok}" +token = tok["token"] + +domain = spec["domain"] + +# --- 1) letsencrypt certificate --- +st, certs = req("GET", "/nginx/certificates", token=token) +assert st == 200, f"cert list failed: {st}" +cert = next((c for c in certs if domain in (c.get("domain_names") or [])), None) +if not cert: + # NPM 2.15.1 rejects letsencrypt_email/agree in meta ("additional + # properties" 400) — empty meta works, LE account email is used. + st, cert = req("POST", "/nginx/certificates", { + "provider": "letsencrypt", + "domain_names": [domain], + "meta": {}, + }, token=token) + assert st == 201, f"cert create failed: {st} {cert}" + changed = True + cert_id = cert["id"] +else: + cert_id = cert["id"] + +# --- 2) proxy host --- +st, hosts = req("GET", "/nginx/proxy-hosts", token=token) +assert st == 200, f"proxy-host list failed: {st}" +host = next((h for h in hosts if domain in (h.get("domain_names") or [])), None) + +host_body = { + "domain_names": [domain], + "forward_scheme": spec["upstream_scheme"], + "forward_host": spec["upstream_host"], + "forward_port": spec["upstream_port"], + "access_list_id": 0, + "certificate_id": cert_id, + "ssl_forced": True, + "hsts_enabled": True, + "http2_support": True, + "block_exploits": True, + "allow_websocket_upgrade": True, + "advanced_config": spec["advanced_config"], + "locations": [], +} + +if not host: + st, host = req("POST", "/nginx/proxy-hosts", host_body, token=token) + assert st == 201, f"proxy-host create failed: {st} {host}" + changed = True +else: + # NPM 2.15.1 quirk: PUT does NOT regenerate the nginx conf (it even + # deletes it) — only POST/create writes proxy_host/.conf. So on drift + # we delete and re-create the host (cert id stays). + drift = any(host.get(k) != v for k, v in host_body.items()) + if drift: + for k, v in host_body.items(): + if host.get(k) != v: + print(f"DRIFT {k}: current={str(host.get(k))[:120]!r} wanted={str(v)[:120]!r}", file=sys.stderr) + if drift: + st, _ = req("DELETE", f"/nginx/proxy-hosts/{host['id']}", token=token) + assert st == 200, f"proxy-host delete failed: {st}" + st, host = req("POST", "/nginx/proxy-hosts", host_body, token=token) + assert st == 201, f"proxy-host recreate failed: {st} {host}" + changed = True + +print("CHANGED" if changed else "UNCHANGED") diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/tasks/main.yml b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/tasks/main.yml new file mode 100644 index 0000000..be467b6 --- /dev/null +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/tasks/main.yml @@ -0,0 +1,70 @@ +--- +- name: Check the NPM API credentials file (mode 0600) + ansible.builtin.stat: + path: "{{ reverse_proxy_research_api_env_file }}" + register: research_npm_api_env + +- name: Fail with instructions when NPM API credentials are missing + ansible.builtin.fail: + msg: >- + {{ reverse_proxy_research_api_env_file }} missing or mode != 0600. + Create it once on CT 103 (root) with NPM_API_EMAIL / NPM_API_PASSWORD + of the NPM admin user; never in git. + when: >- + not research_npm_api_env.stat.exists + or research_npm_api_env.stat.mode != '0600' + +- name: Stage the NPM vhost sync script + ansible.builtin.copy: + src: files/npm_research_vhost.py + dest: /tmp/npm_research_vhost.py + mode: "0600" + changed_when: false + when: not ansible_check_mode + +- name: Render the vhost spec + ansible.builtin.template: + src: spec.json.j2 + dest: /tmp/research_vhost_spec.json + mode: "0600" + changed_when: false + when: not ansible_check_mode + +- name: Sync the research proxy host + LE cert idempotently via the NPM API + ansible.builtin.command: + argv: + - python3 + - /tmp/npm_research_vhost.py + - "{{ reverse_proxy_research_npm_api }}" + - "{{ reverse_proxy_research_api_env_file }}" + - /tmp/research_vhost_spec.json + register: research_vhost_sync + changed_when: research_vhost_sync.stdout_lines | first == 'CHANGED' + when: not ansible_check_mode + no_log: true + +- name: Verify the sync reports UNCHANGED on a second run (idempotence) + ansible.builtin.command: + argv: + - python3 + - /tmp/npm_research_vhost.py + - "{{ reverse_proxy_research_npm_api }}" + - "{{ reverse_proxy_research_api_env_file }}" + - /tmp/research_vhost_spec.json + register: research_vhost_verify + changed_when: false + failed_when: >- + research_vhost_verify.rc != 0 + or (research_vhost_verify.stdout_lines | first) != 'UNCHANGED' + when: not ansible_check_mode + no_log: true + +- name: Remove the staged script and spec + ansible.builtin.file: + path: "/tmp/{{ item }}" + state: absent + loop: + - npm_research_vhost.py + - research_vhost_spec.json + changed_when: false + when: not ansible_check_mode diff --git a/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/templates/spec.json.j2 b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/templates/spec.json.j2 new file mode 100644 index 0000000..393cee5 --- /dev/null +++ b/proxmox/lxc/ct-103-reverse-proxy/ansible/roles/reverse_proxy_research_vhost/templates/spec.json.j2 @@ -0,0 +1,9 @@ +{ + "domain": {{ reverse_proxy_research_domain | to_json }}, + "upstream_scheme": {{ reverse_proxy_research_upstream_scheme | to_json }}, + "upstream_host": {{ reverse_proxy_research_upstream_host | to_json }}, + "upstream_port": {{ reverse_proxy_research_upstream_port | int }}, + "api_port": {{ reverse_proxy_research_api_port | int }}, + "letsencrypt_email": {{ reverse_proxy_research_letsencrypt_email | to_json }}, + "advanced_config": {{ reverse_proxy_research_advanced_config | to_json }} +}