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 index fb423b9..f9b2bd9 100644 --- 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 @@ -124,7 +124,7 @@ Internet → NPM (CT 103, 443) → auth_request-Subrequest an oauth2-proxy | # | Paket | Ziel | Wo | | --- | --- | --- | --- | -| M8-T1 | Keycloak-Client `gnai-research` + Realm-Rolle + Claim-Mapper; Secret als Podman-Secret. **Detaillierte Betreiberschritte (Keycloak 26.2.4, Admin-UI `https://auth.ghostnet.selfhost.eu`, oben links Realm-Dropdown = `Ghost.net`):** **A) Realm-Rolle:** Menü „Realm roles" → „Create role" → Name `gnai-research-user` → Save. **B) Client:** Menü „Clients" → „Create client": Client ID `gnai-research`, Name „Ghostnet Research (oauth2-proxy)" → Next; Capability config: **Client authentication ON** (confidential), Authorization OFF, Standard flow ON, Direct access grants / Implicit / Service accounts / Device / CIBA **OFF** → Next; Login settings: Root URL `https://research.ghostnet.selfhost.eu`, Valid redirect URIs `https://research.ghostnet.selfhost.eu/oauth2/callback`, Valid post logout redirect URIs `https://research.ghostnet.selfhost.eu/*`, Web origins `https://research.ghostnet.selfhost.eu` → Save. **C) groups-Claim-Mapper** (damit `--oidc-groups-claim=groups` greift): Clients → `gnai-research` → „Client scopes" → `gnai-research-dedicated` → „Mappers" → „Add mapper" → „By configuration" → „User Realm Role": Mapper name `realm-roles-to-groups`, Multivalued ON, **Token Claim Name `groups`**, Claim JSON Type String, Add to ID token ON, Add to access token ON, Add to userinfo ON → Save. **D) Secret auf CT 103:** `ssh ansible-deploy@10.0.0.10` → `podman secret rm oauth2-proxy-client-secret 2>/dev/null; printf '%s' '' | podman secret create oauth2-proxy-client-secret -` (Secret nie in Chat/Repo). **E) Rolle zuweisen:** Users → `ghost` → „Role mapping" → „Assign role" → `gnai-research-user` → Assign. **F) Nach dem Deploy testen:** `curl -sI https://research.ghostnet.selfhost.eu/` → 302 zu `auth.ghostnet.selfhost.eu/.../login`. Hinweis: Redirect-URI jetzt schon registrieren, auch wenn `research.ghostnet.selfhost.eu` per DNS/vHost erst in M8-T3 live wird. | CT 102 (Admin-UI) + CT 103 (Secret) | Keycloak | +| 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 → `realm-management`: `manage-realm`, `manage-clients`, `manage-users`, `view-users`; 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 | 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..9abb2b7 --- /dev/null +++ b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/README.md @@ -0,0 +1,37 @@ +# 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** → Client role `realm-management` → + anhaken: `manage-realm`, `manage-clients`, `manage-users`, `view-users`. +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..a030ebb --- /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://127.0.0.1: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..21f1aaf --- /dev/null +++ b/proxmox/lxc/ct-102-keycloak/ansible/roles/keycloak_realm_config/files/keycloak_realm_sync.py @@ -0,0 +1,147 @@ +#!/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 current.get(k) != v: + drift = True + 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) dedicated client scope + realm-role -> groups claim mapper --- +st, scopes = req("GET", f"{R}/clients/{cuuid}/client-scopes") +assert st == 200 +dedicated = [s for s in scopes if s.get("name") == f"{c['clientId']}-dedicated"] +assert dedicated, "dedicated client scope missing after client create" +scope_id = dedicated[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 }} +}