From 36571e07bc849b375bc2ab01b39cfb4941fb0fd6 Mon Sep 17 00:00:00 2001 From: Ramon Date: Fri, 30 Oct 2026 20:52:10 +0100 Subject: [PATCH] feat(sso): fase 2, kern voor apps koppelen (nog zonder routes) - core/sso.py: app_spec (metadata.sso gecontroleerd, alleen bekende plaatshouders), app_client_id, app_gegevens, app_env, compose_aanvullen en compose_terugdraaien. Het terugzetten onderscheidt ontbrekend, kaal (KEY / KEY: null) en een waarde, ook een lege string; lijst- en mappingvorm blijven behouden, bestaande regels houden hun plek. - YAML-fouten zonder regelinhoud (kan een geheim bevatten), zoals Codex vroeg. maak_client met PKCE als keuze per app. - metadata.sso voor Grafana, Mealie, Open WebUI en Miniflux, volgens de Pocket ID-voorbeelden; docs/apps-maken.md beschrijft het veld. - tests/test_sso_apps.py (28): specificatie, plaatshouders, heen en terug in alle vormen, keuze van de hoofddienst, YAML-fout, catalogus. - De routes, installatie en het appmenu volgen na Codex' commit van de DB-UI (zelfde bestanden, gedeelde werkmap). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WPhDUEiVvmH9F4uUkPGKsT --- apps/grafana/template.json | 25 ++++- apps/mealie/template.json | 20 +++- apps/miniflux/template.json | 20 +++- apps/open-webui/template.json | 21 ++++- docs/apps-maken.md | 42 +++++++++ server-up/core/sso.py | 172 ++++++++++++++++++++++++++++++++- tests/test_sso_apps.py | 173 ++++++++++++++++++++++++++++++++++ 7 files changed, 466 insertions(+), 7 deletions(-) create mode 100644 tests/test_sso_apps.py diff --git a/apps/grafana/template.json b/apps/grafana/template.json index a870084..6e04e89 100644 --- a/apps/grafana/template.json +++ b/apps/grafana/template.json @@ -19,7 +19,30 @@ "categories": [ "monitoring" ], - "links": {"website": "https://grafana.com/oss/grafana/", "source": "https://github.com/grafana/grafana"} + "links": { + "website": "https://grafana.com/oss/grafana/", + "source": "https://github.com/grafana/grafana" + }, + "sso": { + "callbacks": [ + "/login/generic_oauth" + ], + "pkce": true, + "env": { + "GF_SERVER_ROOT_URL": "{app_url}/", + "GF_AUTH_GENERIC_OAUTH_ENABLED": "true", + "GF_AUTH_GENERIC_OAUTH_NAME": "{naam}", + "GF_AUTH_GENERIC_OAUTH_CLIENT_ID": "{client_id}", + "GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET": "{client_secret}", + "GF_AUTH_GENERIC_OAUTH_SCOPES": "openid email profile groups", + "GF_AUTH_GENERIC_OAUTH_AUTH_URL": "{auth_url}", + "GF_AUTH_GENERIC_OAUTH_TOKEN_URL": "{token_url}", + "GF_AUTH_GENERIC_OAUTH_USE_PKCE": "true", + "GF_AUTH_GENERIC_OAUTH_ALLOW_SIGN_UP": "true", + "GF_AUTH_GENERIC_OAUTH_EMAIL_ATTRIBUTE_NAME": "email:primary", + "GF_AUTH_GENERIC_OAUTH_ROLE_ATTRIBUTE_PATH": "contains(groups[*], '{admin_groep}') && 'Admin' || 'Viewer'" + } + } }, "variables": [ { diff --git a/apps/mealie/template.json b/apps/mealie/template.json index 4971ff4..88727dd 100644 --- a/apps/mealie/template.json +++ b/apps/mealie/template.json @@ -19,7 +19,25 @@ "categories": [ "gezin" ], - "links": {"website": "https://mealie.io", "source": "https://github.com/mealie-recipes/mealie"} + "links": { + "website": "https://mealie.io", + "source": "https://github.com/mealie-recipes/mealie" + }, + "sso": { + "callbacks": [ + "/login" + ], + "env": { + "BASE_URL": "{app_url}", + "OIDC_AUTH_ENABLED": "true", + "OIDC_SIGNUP_ENABLED": "true", + "OIDC_CONFIGURATION_URL": "{discovery_url}", + "OIDC_CLIENT_ID": "{client_id}", + "OIDC_CLIENT_SECRET": "{client_secret}", + "OIDC_PROVIDER_NAME": "{naam}", + "OIDC_ADMIN_GROUP": "{admin_groep}" + } + } }, "variables": [ { diff --git a/apps/miniflux/template.json b/apps/miniflux/template.json index 95c6ad8..5be0cdc 100644 --- a/apps/miniflux/template.json +++ b/apps/miniflux/template.json @@ -19,7 +19,25 @@ "categories": [ "documenten" ], - "links": {"website": "https://miniflux.app", "source": "https://github.com/miniflux/v2"} + "links": { + "website": "https://miniflux.app", + "source": "https://github.com/miniflux/v2" + }, + "sso": { + "callbacks": [ + "/oauth2/oidc/callback" + ], + "env": { + "BASE_URL": "{app_url}", + "OAUTH2_PROVIDER": "oidc", + "OAUTH2_CLIENT_ID": "{client_id}", + "OAUTH2_CLIENT_SECRET": "{client_secret}", + "OAUTH2_REDIRECT_URL": "{app_url}/oauth2/oidc/callback", + "OAUTH2_OIDC_DISCOVERY_ENDPOINT": "{issuer}", + "OAUTH2_OIDC_PROVIDER_NAME": "{naam}", + "OAUTH2_USER_CREATION": "1" + } + } }, "variables": [ { diff --git a/apps/open-webui/template.json b/apps/open-webui/template.json index f765362..2b33957 100644 --- a/apps/open-webui/template.json +++ b/apps/open-webui/template.json @@ -18,7 +18,26 @@ "categories": [ "ai" ], - "links": {"website": "https://openwebui.com", "source": "https://github.com/open-webui/open-webui"} + "links": { + "website": "https://openwebui.com", + "source": "https://github.com/open-webui/open-webui" + }, + "sso": { + "callbacks": [ + "/oauth/oidc/callback" + ], + "env": { + "WEBUI_URL": "{app_url}", + "ENABLE_OAUTH_SIGNUP": "true", + "OAUTH_CLIENT_ID": "{client_id}", + "OAUTH_CLIENT_SECRET": "{client_secret}", + "OAUTH_PROVIDER_NAME": "{naam}", + "OPENID_PROVIDER_URL": "{discovery_url}", + "OAUTH_SCOPES": "openid email profile", + "OAUTH_MERGE_ACCOUNTS_BY_EMAIL": "true", + "DEFAULT_USER_ROLE": "user" + } + } }, "variables": [ { diff --git a/docs/apps-maken.md b/docs/apps-maken.md index b528556..f5c5e77 100644 --- a/docs/apps-maken.md +++ b/docs/apps-maken.md @@ -116,6 +116,7 @@ De testsuite controleert dit voor elke app. | `architecture_note` | Uitleg die bij de platformmelding in de catalogus en het installatieformulier staat | | `links` | `website`, `source` en `docs` voor het infovenster; alleen http(s). `tools/app_links.py` controleert ze | | `maintenance` | Of de app upstream nog onderhouden wordt; zie [Onderhoud](#onderhoud) | +| `sso` | Of en hoe de app met de centrale inlog kan; zie [Centrale inlog](#centrale-inlog) | Laat `architectures` weg als de image-ondersteuning niet is geverifieerd. Een expliciete mismatch blokkeert de installatie zowel in de interface als in de @@ -254,6 +255,47 @@ sjabloon `architectures: ["arm64"]` belooft. Gaat daar iets mis, dan wordt de run rood. Server Up haalt de bronnen van de store elke dag op (instelling `REPO_AUTO_SYNC`), dus de meting staat er vanzelf in. +### Centrale inlog + +Kan een app inloggen via OpenID Connect, dan kan Server Up hem koppelen aan de +centrale inlog (Instellingen → Centrale inlog, eerst Pocket ID). Server Up maakt +dan per app een client aan in de inlogdienst en zet de instellingen in het +compose-bestand, na het renderen, op de hoofddienst. Het sjabloon zelf blijft +zonder voorwaarden: aan of uit regelt Server Up. + +```json +"sso": { + "callbacks": ["/login/generic_oauth"], + "pkce": true, + "env": { + "GF_SERVER_ROOT_URL": "{app_url}/", + "GF_AUTH_GENERIC_OAUTH_CLIENT_ID": "{client_id}", + "GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET": "{client_secret}" + } +} +``` + +| Sleutel | Betekenis | +|---|---| +| `callbacks` | Paden achter het adres van de app waar de inlogdienst naar terugstuurt; beginnen met `/` | +| `env` | Omgevingsvariabelen voor de hoofddienst, met plaatshouders | +| `pkce` | `true` als de app zelf PKCE doet; dan eist de inlogdienst het ook | +| `service` | Optioneel: welke dienst. Anders de eerste die geen database of zoekindex is | + +Plaatshouders: `{issuer}`, `{discovery_url}` (met `/.well-known/openid-configuration`), +`{auth_url}`, `{token_url}`, `{userinfo_url}`, `{client_id}`, `{client_secret}`, +`{app_url}` (zonder slotslash), `{naam}` (van de inlogdienst) en `{admin_groep}` +(de groep die in Server Up beheerder is). Een onbekende plaatshouder maakt de +hele `sso` ongeldig. + +- Het clientgeheim komt in `.env` als `SU_SSO_CLIENT_SECRET`; in het + compose-bestand staat `${SU_SSO_CLIENT_SECRET}`. +- Een variabele die het sjabloon zelf al zet (zoals `BASE_URL`), wordt + overschreven. Wat er stond, bewaart Server Up: uitzetten zet het terug, + inclusief het verschil tussen ontbrekend, leeg en kaal (`KEY` zonder `=`). +- Neem de instellingen over uit de documentatie van de app of van Pocket ID + (`pocket-id.org/docs/client-examples`), niet uit je hoofd. + ### Backupbeleid Server Up's generieke backup pakt de stackmap, de appdata-mappen en een dump diff --git a/server-up/core/sso.py b/server-up/core/sso.py index a67ca52..09ba70f 100644 --- a/server-up/core/sso.py +++ b/server-up/core/sso.py @@ -165,11 +165,12 @@ class PocketId: return False, f"HTTP {code}: {_melding(antwoord)}" return True, "Verbonden met Pocket ID." - def maak_client(self, client_id: str, naam: str, callbacks: list[str]) -> dict: - """Een vertrouwelijke client met PKCE; {client_id, client_secret}.""" + def maak_client(self, client_id: str, naam: str, callbacks: list[str], pkce: bool = True) -> dict: + """Een vertrouwelijke client; {client_id, client_secret}. PKCE verplicht + alleen als de app het ook doet (Server Up zelf wel).""" code, antwoord = self._api("POST", "/oidc/clients", { "id": client_id, "name": naam[:50], "callbackURLs": callbacks, - "isPublic": False, "pkceEnabled": True}) + "isPublic": False, "pkceEnabled": bool(pkce)}) if code >= 400: raise SsoFout(f"Client aanmaken mislukt (HTTP {code}): {_melding(antwoord)}") geheim = ((antwoord or {}).get("createdSecret") or {}).get("secret") if isinstance(antwoord, dict) else "" @@ -357,3 +358,168 @@ def afronden(code: str, state: str, binding: str | None = None) -> dict: "Voeg de gebruiker in de inlogdienst toe aan een van de gekoppelde groepen.") return {"naam": f"sso:{naam}", "rol": rol, "email": str(info.get("email") or ""), "volgende": lopend["volgende"], "epoch": lopend["epoch"]} + + +# ── Apps koppelen ──────────────────────────────────────────────────────────── +# +# Een sjabloon dat OIDC kan, beschrijft in `metadata.sso` welke callback-paden +# de app gebruikt en welke omgevingsvariabelen hij wil (docs/apps-maken.md): +# +# "sso": {"callbacks": ["/login/generic_oauth"], "pkce": true, +# "env": {"GF_AUTH_GENERIC_OAUTH_CLIENT_ID": "{client_id}", ...}} +# +# Server Up maakt per app een client aan en zet die variabelen in het +# compose-bestand, op de hoofddienst. Dat gebeurt na het renderen, net als de +# tijdzone, zodat het sjabloon zelf niets hoeft te weten van aan of uit. Wat er +# stond, wordt bewaard (ontbrekend, kaal of met waarde): uitzetten zet precies +# dat terug. + +APP_PLAATSHOUDERS = ("issuer", "discovery_url", "auth_url", "token_url", "userinfo_url", + "client_id", "client_secret", "app_url", "naam", "admin_groep") +APP_GEHEIM_ENV = "SU_SSO_CLIENT_SECRET" +_PLAATSHOUDER = re.compile(r"\{(\w+)\}") +_ENV_SLEUTEL = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") + + +def app_spec(bron_meta: dict) -> dict | None: + """`metadata.sso` van een sjabloon, gecontroleerd; None als de app het niet kan.""" + s = (bron_meta or {}).get("sso") + if not isinstance(s, dict): + return None + callbacks, env = s.get("callbacks"), s.get("env") + if not (isinstance(callbacks, list) and callbacks + and all(isinstance(c, str) and c.startswith("/") and not c.startswith("//") for c in callbacks)): + return None + if not (isinstance(env, dict) and env + and all(isinstance(k, str) and _ENV_SLEUTEL.fullmatch(k) and isinstance(v, str) + and set(_PLAATSHOUDER.findall(v)) <= set(APP_PLAATSHOUDERS) + for k, v in env.items())): + return None + return {"callbacks": callbacks, "env": env, "pkce": bool(s.get("pkce")), + "service": str(s.get("service") or "")} + + +def app_client_id(stack: str) -> str: + return f"serverup-{stack}"[:128] + + +def app_gegevens(i: dict, client_id: str, app_url: str) -> dict: + """De waarden voor de plaatshouders. Het geheim staat in `.env`.""" + d = discovery(i) + return {"issuer": i["issuer"], "discovery_url": f"{i['issuer']}/.well-known/openid-configuration", + "auth_url": d["authorization_endpoint"], "token_url": d["token_endpoint"], + "userinfo_url": d["userinfo_endpoint"], "client_id": client_id, + "client_secret": "${" + APP_GEHEIM_ENV + "}", "app_url": app_url.rstrip("/"), + "naam": PROVIDERS.get(i["provider"], i["provider"]), + "admin_groep": i["groepen"].get("admin") or ""} + + +def app_env(spec: dict, gegevens: dict) -> dict[str, str]: + """De omgevingsvariabelen met ingevulde plaatshouders.""" + def vul(tekst: str) -> str: + return _PLAATSHOUDER.sub(lambda m: str(gegevens.get(m.group(1), m.group(0))), tekst) + return {k: vul(v) for k, v in spec["env"].items()} + + +def _laad_compose(tekst: str) -> dict: + import yaml + try: + doc = yaml.safe_load(tekst) + except yaml.YAMLError as e: + # Zonder de regel zelf: die kan een wachtwoord bevatten. + mark = getattr(e, "problem_mark", None) + waar = f" (regel {mark.line + 1})" if mark is not None else "" + raise SsoFout(f"Het compose-bestand is geen geldige YAML{waar}.") from None + if not isinstance(doc, dict) or not isinstance(doc.get("services"), dict) or not doc["services"]: + raise SsoFout("Het compose-bestand heeft geen services.") + return doc + + +def _dump(doc: dict) -> str: + import yaml + return yaml.safe_dump(doc, sort_keys=False, default_flow_style=False, allow_unicode=True, width=120) + + +def _hoofddienst(services: dict, voorkeur: str) -> str: + if voorkeur in services: + return voorkeur + from core import compose_transform + for naam, svc in services.items(): + if isinstance(svc, dict) and not compose_transform.is_hulpdienst(str(svc.get("image") or "")): + return naam + return next(iter(services)) + + +# Wat er stond: {"vorm": "ontbreekt"}, {"vorm": "kaal"} (KEY of KEY: null, +# doorgegeven uit de omgeving van compose) of {"vorm": "waarde", "waarde": …}. +# Een lege string is een waarde, geen kaal. + +def _env_toestand(svc: dict, sleutel: str) -> dict: + omgeving = svc.get("environment") + if isinstance(omgeving, dict): + if sleutel not in omgeving: + return {"vorm": "ontbreekt"} + v = omgeving[sleutel] + return {"vorm": "kaal"} if v is None else {"vorm": "waarde", "waarde": str(v)} + toestand = {"vorm": "ontbreekt"} + for regel in omgeving or []: + if isinstance(regel, str) and regel.partition("=")[0].strip() == sleutel: + toestand = ({"vorm": "waarde", "waarde": regel.partition("=")[2]} if "=" in regel + else {"vorm": "kaal"}) + return toestand + + +def _env_zetten(svc: dict, wijzig: dict[str, dict]) -> None: + """Zet elke sleutel in de gevraagde toestand, in de vorm die er al stond + (lijst of mapping). Bestaande regels houden hun plek.""" + omgeving = svc.get("environment") + if isinstance(omgeving, dict): + for k, s in wijzig.items(): + if s["vorm"] == "ontbreekt": + omgeving.pop(k, None) + else: + omgeving[k] = None if s["vorm"] == "kaal" else s["waarde"] + return + + def regel(k, s): + return k if s["vorm"] == "kaal" else f"{k}={s['waarde']}" + + uit, gedaan = [], set() + for r in omgeving or []: + k = r.partition("=")[0].strip() if isinstance(r, str) else None + if k in wijzig: + if k not in gedaan and wijzig[k]["vorm"] != "ontbreekt": + uit.append(regel(k, wijzig[k])) + gedaan.add(k) + else: + uit.append(r) + uit += [regel(k, s) for k, s in wijzig.items() if k not in gedaan and s["vorm"] != "ontbreekt"] + if uit: + svc["environment"] = uit + else: + svc.pop("environment", None) + + +def compose_aanvullen(tekst: str, env: dict[str, str], service: str = "") -> tuple[str, dict, str]: + """(nieuwe tekst, wat er per sleutel stond, de gekozen dienst).""" + doc = _laad_compose(tekst) + naam = _hoofddienst(doc["services"], service) + svc = doc["services"][naam] + if not isinstance(svc, dict): + raise SsoFout(f"Dienst {naam} is leeg.") + vorige = {k: _env_toestand(svc, k) for k in env} + _env_zetten(svc, {k: {"vorm": "waarde", "waarde": v} for k, v in env.items()}) + return _dump(doc), vorige, naam + + +def compose_terugdraaien(tekst: str, vorige: dict, service: str) -> str: + doc = _laad_compose(tekst) + svc = doc["services"].get(service) + if not isinstance(svc, dict): + return tekst + geldig = {k: s for k, s in (vorige or {}).items() + if _ENV_SLEUTEL.fullmatch(str(k)) and isinstance(s, dict) + and s.get("vorm") in ("ontbreekt", "kaal", "waarde") + and (s["vorm"] != "waarde" or isinstance(s.get("waarde"), str))} + _env_zetten(svc, geldig) + return _dump(doc) diff --git a/tests/test_sso_apps.py b/tests/test_sso_apps.py new file mode 100644 index 0000000..f94215d --- /dev/null +++ b/tests/test_sso_apps.py @@ -0,0 +1,173 @@ +"""Centrale inlog, fase 2: apps koppelen (core/sso.py, deel "Apps koppelen"). + +Alleen de pure stukken: de specificatie in het sjabloon, de plaatshouders, en +het compose-bestand aanvullen en precies terugzetten. Codex, 30 oktober: bij +terugzetten onderscheid tussen ontbrekend, kaal/null en een lege string, en een +YAML-fout nooit met de regelinhoud. +""" +import pytest +import yaml + +SPEC = {"sso": {"callbacks": ["/login/generic_oauth"], "pkce": True, + "env": {"GF_AUTH_GENERIC_OAUTH_ENABLED": "true", + "GF_AUTH_GENERIC_OAUTH_CLIENT_ID": "{client_id}", + "GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET": "{client_secret}", + "GF_SERVER_ROOT_URL": "{app_url}/"}}} + + +@pytest.fixture +def sso(env): + from core import sso + return sso + + +# ── Specificatie ───────────────────────────────────────────────────────────── + +def test_geldige_specificatie(sso): + s = sso.app_spec(SPEC) + assert s["pkce"] is True and s["service"] == "" and s["callbacks"] == ["/login/generic_oauth"] + + +@pytest.mark.parametrize("fout", [ + {"callbacks": [], "env": {"A": "x"}}, + {"callbacks": ["login"], "env": {"A": "x"}}, + {"callbacks": ["//kwaad.nl/cb"], "env": {"A": "x"}}, + {"callbacks": ["/cb"], "env": {}}, + {"callbacks": ["/cb"], "env": {"1A": "x"}}, + {"callbacks": ["/cb"], "env": {"A B": "x"}}, + {"callbacks": ["/cb"], "env": {"A": 1}}, + {"callbacks": ["/cb"], "env": {"A": "{onbekend}"}}, + "ja", +]) +def test_ongeldige_specificatie(sso, fout): + assert sso.app_spec({"sso": fout}) is None + + +def test_plaatshouders(sso): + g = {"client_id": "serverup-grafana", "client_secret": "${SU_SSO_CLIENT_SECRET}", + "app_url": "https://grafana.voorbeeld.nl"} + env = sso.app_env(sso.app_spec(SPEC), g) + assert env["GF_AUTH_GENERIC_OAUTH_CLIENT_ID"] == "serverup-grafana" + assert env["GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET"] == "${SU_SSO_CLIENT_SECRET}" + assert env["GF_SERVER_ROOT_URL"] == "https://grafana.voorbeeld.nl/" + assert env["GF_AUTH_GENERIC_OAUTH_ENABLED"] == "true" + + +def test_client_id(sso): + assert sso.app_client_id("grafana") == "serverup-grafana" + + +# ── Aanvullen en terugzetten ───────────────────────────────────────────────── + +LIJST = """services: + grafana: + image: grafana/grafana:12 + environment: + - GF_SECURITY_ADMIN_USER=admin + - GF_SERVER_ROOT_URL=http://localhost:3000/ + - GF_LEEG= + - GF_KAAL + grafana-db: + image: postgres:16-alpine +""" + +MAPPING = """services: + grafana-db: + image: postgres:16-alpine + grafana: + image: grafana/grafana:12 + environment: + GF_SECURITY_ADMIN_USER: admin + GF_SERVER_ROOT_URL: http://localhost:3000/ + GF_LEEG: "" + GF_KAAL: +""" + +NIEUW = {"GF_SERVER_ROOT_URL": "https://g.voorbeeld.nl/", "GF_LEEG": "gevuld", "GF_KAAL": "ook", + "GF_NIEUW": "x"} + + +@pytest.mark.parametrize("tekst", [LIJST, MAPPING]) +def test_heen_en_terug_is_precies_hetzelfde(sso, tekst): + nieuw, vorige, dienst = sso.compose_aanvullen(tekst, NIEUW) + assert dienst == "grafana" # de database niet + assert vorige == {"GF_SERVER_ROOT_URL": {"vorm": "waarde", "waarde": "http://localhost:3000/"}, + "GF_LEEG": {"vorm": "waarde", "waarde": ""}, + "GF_KAAL": {"vorm": "kaal"}, + "GF_NIEUW": {"vorm": "ontbreekt"}} + terug = sso.compose_terugdraaien(nieuw, vorige, dienst) + assert yaml.safe_load(terug) == yaml.safe_load(tekst) + + +def test_lijst_houdt_volgorde_en_vult_aan(sso): + nieuw, _, _ = sso.compose_aanvullen(LIJST, NIEUW) + env = yaml.safe_load(nieuw)["services"]["grafana"]["environment"] + assert env == ["GF_SECURITY_ADMIN_USER=admin", "GF_SERVER_ROOT_URL=https://g.voorbeeld.nl/", + "GF_LEEG=gevuld", "GF_KAAL=ook", "GF_NIEUW=x"] + + +def test_dubbele_regel_wordt_er_een(sso): + tekst = "services:\n a:\n image: x\n environment:\n - K=1\n - K=2\n" + nieuw, vorige, _ = sso.compose_aanvullen(tekst, {"K": "3"}) + assert vorige == {"K": {"vorm": "waarde", "waarde": "2"}} # compose neemt de laatste + assert yaml.safe_load(nieuw)["services"]["a"]["environment"] == ["K=3"] + + +def test_dienst_zonder_environment(sso): + tekst = "services:\n a:\n image: x\n" + nieuw, vorige, dienst = sso.compose_aanvullen(tekst, {"K": "1"}) + assert yaml.safe_load(nieuw)["services"]["a"]["environment"] == ["K=1"] + assert yaml.safe_load(sso.compose_terugdraaien(nieuw, vorige, dienst)) == yaml.safe_load(tekst) + + +def test_gekozen_dienst_uit_het_sjabloon(sso): + _, _, dienst = sso.compose_aanvullen(LIJST, {"K": "1"}, service="grafana-db") + assert dienst == "grafana-db" + _, _, dienst = sso.compose_aanvullen(LIJST, {"K": "1"}, service="bestaat-niet") + assert dienst == "grafana" + + +def test_terugzetten_negeert_rommel(sso): + nieuw, _, dienst = sso.compose_aanvullen(LIJST, {"K": "1"}) + terug = sso.compose_terugdraaien(nieuw, {"K": {"vorm": "raar"}, "1X": {"vorm": "ontbreekt"}, + "J": {"vorm": "waarde", "waarde": 3}}, dienst) + assert "K=1" in yaml.safe_load(terug)["services"]["grafana"]["environment"] + + +def test_yaml_fout_zonder_regelinhoud(sso): + tekst = "services:\n a:\n image: x\n environment:\n - WACHTWOORD=geheim123\n kapot: [\n" + with pytest.raises(sso.SsoFout) as e: + sso.compose_aanvullen(tekst, {"K": "1"}) + assert "geheim123" not in str(e.value) and "regel" in str(e.value) + assert e.value.__cause__ is None and e.value.__suppress_context__ + + +@pytest.mark.parametrize("tekst", ["", "services: {}\n", "- a\n"]) +def test_geen_services(sso, tekst): + with pytest.raises(sso.SsoFout, match="geen services"): + sso.compose_aanvullen(tekst, {"K": "1"}) + + +# ── Catalogus ──────────────────────────────────────────────────────────────── + +def _sjablonen_met_sso(): + import json + from pathlib import Path + wortel = Path(__file__).resolve().parent.parent / "apps" + for f in sorted(wortel.glob("*/template.json")): + meta = json.loads(f.read_text(encoding="utf-8")).get("metadata") or {} + if "sso" in meta: + yield f.parent.name, meta + + +@pytest.mark.parametrize("app, meta", list(_sjablonen_met_sso()), ids=lambda x: x if isinstance(x, str) else "") +def test_elke_sso_in_de_catalogus_is_geldig(sso, app, meta): + spec = sso.app_spec(meta) + assert spec, f"{app}: metadata.sso is ongeldig" + # Zonder client-id en -geheim kan geen enkele app inloggen. + alles = " ".join(spec["env"].values()) + assert "{client_id}" in alles and "{client_secret}" in alles, app + + +def test_eerste_vier_apps_kunnen_het(): + assert {a for a, _ in _sjablonen_met_sso()} >= {"grafana", "mealie", "open-webui", "miniflux"}