From 23d2fc0eb2e915909f6f7eea3bd7744e642811b2 Mon Sep 17 00:00:00 2001 From: Inferencebot Date: Wed, 11 Nov 2026 05:24:57 +0000 Subject: [PATCH] Shared code: single-source the OIDC client; record the guest-state consolidation - scripts/shared/oidc_client.py is the canonical OIDC client module; the dashboard and panel ship byte-identical copies (pinned by tests/test_oidc_sync.py in each repo). sync-oidc-module.sh re-copies + re-pins; check-oidc-sync.py is the pre-deploy gate; scripts/shared/test_oidc_client.py is the behaviour harness. - maintenance/shared-code-and-guest-state.md records the guest-state single-derivation design (portal serves state; panel/dashboard are pure shims), the deploy record with rollback tags, and the CI follow-up. - app-inventory.md: the three apps' tags refreshed to the 20261111 deploys; the stale 'admin panel = local/coop...' registry-path note corrected against the live API (all three live under code/). --- app-inventory.md | 19 +- maintenance/shared-code-and-guest-state.md | 96 ++++++++ scripts/check-oidc-sync.py | 109 +++++++++ .../__pycache__/oidc_client.cpython-314.pyc | Bin 0 -> 12150 bytes scripts/shared/oidc_client.py | 210 ++++++++++++++++++ scripts/shared/test_oidc_client.py | 118 ++++++++++ scripts/sync-oidc-module.sh | 108 +++++++++ 7 files changed, 652 insertions(+), 8 deletions(-) create mode 100644 maintenance/shared-code-and-guest-state.md create mode 100755 scripts/check-oidc-sync.py create mode 100644 scripts/shared/__pycache__/oidc_client.cpython-314.pyc create mode 100644 scripts/shared/oidc_client.py create mode 100644 scripts/shared/test_oidc_client.py create mode 100755 scripts/sync-oidc-module.sh diff --git a/app-inventory.md b/app-inventory.md index 140b7ba..7f06e54 100644 --- a/app-inventory.md +++ b/app-inventory.md @@ -22,9 +22,9 @@ does not hold it. | `inference.coop` | `55f5f904-3233-44de-ad7b-5dc7c8533b75` | — | `cloudron/io.cloudron.surfer:202611021342220000` | store (Surfer — marketing site) | | `chat.inference.coop` | `4023ccbf-d57a-4500-97df-14de9cf3516e` | AI Chat | `registry.inference.coop/co-op/librechat-custom:20261106-c2aec74` | **custom** (LibreChat overlay) | | `chat-legacy.inference.coop` | `50ae6c97-e851-4d17-b013-51ca7a4e5be0` | Legacy AI Chat | `cloudron/com.openwebui.cloudronapp:202611040420410000` | store (Open WebUI) | -| `portal.inference.coop` | `d4f05e4b-75c6-492e-9faf-7afb0712fc94` | — | `registry.inference.coop/code/member-portal:20261108-2954fe60` | **custom** | -| `dashboard.inference.coop` | `daf8750e-2683-4104-83ea-f77d1b4601e8` | Dashboard | `registry.inference.coop/code/member-dashboard:20261108-1e6e9e48` | **custom** | -| `panel.inference.coop` | `ae187071-7a43-4a6e-8a02-986609a66a1a` | Admin Panel | `registry.inference.coop/code/admin-panel:20261108-b23cc67` | **custom** | +| `portal.inference.coop` | `d4f05e4b-75c6-492e-9faf-7afb0712fc94` | — | `registry.inference.coop/code/member-portal:20261111-58214be0` | **custom** | +| `dashboard.inference.coop` | `daf8750e-2683-4104-83ea-f77d1b4601e8` | Dashboard | `registry.inference.coop/code/member-dashboard:20261111-622982a3` | **custom** | +| `panel.inference.coop` | `ae187071-7a43-4a6e-8a02-986609a66a1a` | Admin Panel | `registry.inference.coop/code/admin-panel:20261111-80acfaed` | **custom** | | `gateway.inference.coop` | `adababd4-2427-4bdd-9bf7-6bdad0302610` | LiteLLM | `registry.inference.coop/local/ai.coop.litellm:20261109-c43d45c` | **custom** | | `matrix.inference.coop` | `aa6f4597-6206-4509-b32e-c89750b2c1d8` | Matrix Chat | `cloudron/org.matrix.synapse:202611030719520000` | store (Synapse) | | `git.inference.coop` | `c91c13aa-30ed-4af9-9599-7a87ab4f221d` | Code | `cloudron/io.gitea.cloudronapp:202611011719500000` | store (Gitea) | @@ -54,12 +54,15 @@ another app's pattern deploys the wrong (or a missing) image: | member portal | `registry.inference.coop/code/member-portal` | | member dashboard | `registry.inference.coop/code/member-dashboard` | | gateway (LiteLLM) | `registry.inference.coop/local/ai.coop.litellm` | -| admin panel | `local/coop.inference.admin-panel` | +| admin panel | `registry.inference.coop/code/admin-panel` | -**Correcting a stale memory:** the portal is `code/member-portal` (not -`co-op/member-portal`), and the admin panel is `local/coop.inference.admin-panel` -(not `code/admin-panel`). Both were cited wrongly in earlier notes; the values -above are read from the running apps. +**Correcting a stale memory (re-verified against the live system 2026-11-11):** +the portal, dashboard and panel ALL live under the `code/` namespace +(`code/member-portal`, `code/member-dashboard`, `code/admin-panel`) — read from +each running app's `manifest.dockerImage` via the API and confirmed by +successful builds and pulls. An earlier note claimed the panel was +`local/coop.inference.admin-panel`; that path does not match the running +system and is superseded by the verified values above. ## Store vs custom, and what that decides diff --git a/maintenance/shared-code-and-guest-state.md b/maintenance/shared-code-and-guest-state.md new file mode 100644 index 0000000..29432d0 --- /dev/null +++ b/maintenance/shared-code-and-guest-state.md @@ -0,0 +1,96 @@ +# Shared code: guest state and the OIDC client (2026-11-11 consolidation) + +The fragile-framework audit found the guest invited/active state logic +triplicated (portal `app/main.py` admin_overview, dashboard page JS, panel page +JS) and `app/oidc.py` near-duplicated between the dashboard and the panel +(21-line diff: logger name, session cookie, session salt, docstring, one dead +line). This note records how both were consolidated and how to change them +safely from here. + +## Guest state — the portal is the single derivation point + +`member-portal` computes a guest's display state ONCE, in the `/admin/overview` +row (and the same semantics ride the `/broker/guests` trail): + +1. invite not yet accepted (Cloudron `inviteAccepted` false AND no username, + from a SEEN user record) → `state: "invited"` — never "active"; +2. otherwise → the guests-ledger status (active / converted / expired / + depleted / cancelled by recipient) — the record of record; +3. no ledger row → the membership state (active/inactive) as fallback. + +Tested once, in `member-portal/tests/test_guest_invited_state.py`. + +The consumers are pure shims — first served field wins, NO derivation from +flags anywhere: + +- **admin panel** (`admin-panel-guests-harness.js` asserts this): `state` → + `guest_status` → nothing (an empty pill; a payload with neither field no + longer exists and must not be re-derived). `guest_status` first keeps the + previous payload shape rendering identically during a portal rollback. +- **member dashboard** (`dashboard-guests-harness.js`): trail pill reads + `state || status` (unchanged behaviour; comment updated). + +Changing the derivation means changing the PORTAL + its test, then syncing the +consumer comments/harnesses if the vocabulary changes. Never re-add a +derivation to a consumer. + +## OIDC client — one canonical module, byte-identical copies + +- **Canonical:** `scripts/shared/oidc_client.py` (this repo). +- **Copies:** `member-dashboard/app/oidc.py`, `admin-panel/app/oidc.py` — + byte-identical to the canonical by sha256. Each app calls + `oidc.configure("", "", "")` in `main.py` at import time + with its HISTORICAL cookie name and salt, so existing sessions survive. +- **Why copies, not a portal-served config:** OIDC is each app's LOGIN path; + making it depend on the portal being up would trade a small duplication for + a cross-app outage coupling. Copies keep every app self-contained; the sync + tooling keeps them identical. +- **Change procedure:** edit the canonical → run + `scripts/sync-oidc-module.sh` (re-copies both, re-pins, py_compiles, runs + the check) → commit all three repos. NEVER hand-edit a repo copy: + - each repo's `tests/test_oidc_sync.py` pins the copy to the canonical + revision's sha256 and goes red on any hand edit; + - `scripts/check-oidc-sync.py` is the pre-deploy gate (run before building + either thin app) and verifies copies, pins and configured identities; + - `scripts/shared/test_oidc_client.py` is the steward-host behaviour harness + (stubs authlib/httpx; needs `pip install itsdangerous`): configure(), + lazy-logger attribution, session roundtrip, cross-app salt isolation. + +Woodpecker CI currently runs the panel's guard+harnesses and the portal's 12 +suites but does NOT run the new pin tests (CI was out of scope for the +consolidation). Adding `python3 tests/test_oidc_sync.py` to both thin apps' +pipelines is a one-line follow-up; until then the pre-deploy +`check-oidc-sync.py` run is the drift gate. + +## Deploy record 2026-11-11 (zero downtime) + +Order: portal first (source of truth), then dashboard, then panel; each built +from its own repo dir, verified by running image tag + container md5 + code +marker + health + real payload fetch. Chat/gateway untouched throughout. + +| App | New tag (deployed) | Rollback tag (previous) | +|---|---|---| +| member-portal | `code/member-portal:20261111-58214be0` | `code/member-portal:20261108-2954fe60` | +| member-dashboard | `code/member-dashboard:20261111-622982a3` | `code/member-dashboard:20261108-1e6e9e48` | +| admin-panel | `code/admin-panel:20261111-80acfaed` | `code/admin-panel:20261108-b23cc67` | + +One-command reverts (run from the app's OWN repo dir; verify by container md5 ++ marker afterwards, never by exit code): + +- portal / panel (pinned manifests): `git revert --no-edit ` then + `cloudron update --app --force`. +- dashboard (no pin): `cloudron update --app daf8750e-2683-4104-83ea-f77d1b4601e8 + --image registry.inference.coop/code/member-dashboard:20261108-1e6e9e48 --force`. + +Rollback compatibility: any single-app rollback renders correctly — the shims +consume whichever fields the other payload shape serves. The only known nuance +(portal rolled back alone while the new panel stays deployed): an ENDED guest +would pill as `inactive` instead of its ledger status until the portal is +restored; no ended guests existed at consolidation time. + +Verification evidence 2026-11-11: all 4 live guest rows byte-identical +pre/post (2 invited, 2 active); member stable-field hash identical across +no-deploy fetches (112 active, 1 in_grace, 2 invited); both apps' +`/auth/openid/login` → 302 to the Cloudron provider with correct +client_id/redirect_uri/scope; dashboard + panel `/` → 302 to the login route; +container `oidc.py` md5 identical in both thin apps (`df23e7a8…`). diff --git a/scripts/check-oidc-sync.py b/scripts/check-oidc-sync.py new file mode 100755 index 0000000..536a432 --- /dev/null +++ b/scripts/check-oidc-sync.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Verify the OIDC client module is single-sourced and byte-identical. + +Checks, in order, and exits non-zero naming every failure: + + 1. canonical ops-docs/scripts/shared/oidc_client.py + == member-dashboard/app/oidc.py (byte-identical, sha256) + == admin-panel/app/oidc.py (byte-identical, sha256) + 2. each repo's tests/test_oidc_sync.py pins the CANONICAL revision + (so CI — which has no ops-docs checkout — still goes red when a repo + copy is hand-edited). + 3. each repo's app/main.py calls oidc.configure(...) with THAT repo's + identity literal (cookie name + salt preserved from the pre-consolidation + apps, so existing sessions survive). + +Run from anywhere: python3 ops-docs/scripts/check-oidc-sync.py +This is the pre-deploy gate for either thin app; sync-oidc-module.sh runs it +at the end of every sync. +""" +import hashlib +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent # ops-docs/scripts +REPOS = HERE.parent.parent # ~/repos + +CANONICAL = HERE / "shared" / "oidc_client.py" + +# repo name -> (copy path, pin-test path, main path, expected configure call) +APPS = { + "member-dashboard": ( + "app/oidc.py", + "tests/test_oidc_sync.py", + "app/main.py", + 'oidc.configure("member-dashboard", "member_oidc_session", ' + '"member-dashboard-oidc-session")', + ), + "admin-panel": ( + "app/oidc.py", + "tests/test_oidc_sync.py", + "app/main.py", + 'oidc.configure("admin-panel", "admin_oidc_session", ' + '"admin-panel-oidc-session")', + ), +} + + +def sha256_file(p: Path) -> str: + return hashlib.sha256(p.read_bytes()).hexdigest() + + +def main() -> int: + failures = [] + + if not CANONICAL.exists(): + print(f"FAIL canonical module missing: {CANONICAL}") + return 1 + canon_sha = sha256_file(CANONICAL) + print(f"canonical {CANONICAL.relative_to(REPOS)} sha256={canon_sha[:16]}…") + + for repo, (copy_rel, pin_rel, main_rel, expected_configure) in APPS.items(): + repo_dir = REPOS / repo + copy = repo_dir / copy_rel + pin = repo_dir / pin_rel + app_main = repo_dir / main_rel + + if not copy.exists(): + failures.append(f"{repo}: copy missing: {copy}") + continue + copy_sha = sha256_file(copy) + if copy_sha == canon_sha: + print(f"ok - {repo}: {copy_rel} byte-identical to canonical " + f"(sha256={copy_sha[:16]}…)") + else: + failures.append( + f"{repo}: {copy_rel} DRIFTED from canonical\n" + f" canonical sha256={canon_sha}\n" + f" copy sha256={copy_sha}\n" + f" fix: edit the canonical file and run " + f"ops-docs/scripts/sync-oidc-module.sh — never hand-edit the copy.") + + if pin.exists() and canon_sha in pin.read_text(): + print(f"ok - {repo}: pin test records this canonical revision") + else: + failures.append( + f"{repo}: {pin_rel} does not pin canonical revision {canon_sha[:16]}… " + f"(run sync-oidc-module.sh to re-pin)") + + if app_main.exists() and expected_configure in app_main.read_text(): + print(f"ok - {repo}: main.py configures the app identity") + else: + failures.append( + f"{repo}: {main_rel} does not call the expected identity literal:\n" + f" {expected_configure}") + + if failures: + print() + print(f"FAILED: {len(failures)} problem(s)") + for f in failures: + print(" - " + f) + return 1 + print() + print("oidc module sync: all copies byte-identical, pins current, identities wired") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/shared/__pycache__/oidc_client.cpython-314.pyc b/scripts/shared/__pycache__/oidc_client.cpython-314.pyc new file m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n_ynQ1KlH#&p>3e8dHH zANwJnd|Y$i7Ns|4QW0y~v?AkG?xljvT5) zUby91JNU#q```7f96a^O!Be;NS8m?Ec}J*3y378v?+qgR(^_!Xa@(PD;PB@Nn>QJl z&W-P%HF6UCGLOm(%@XkiB;bj|BmrO+}h({?IddiAtADS7oa?r!xJE$!*2e}N?*C@M8 z8G&g&3DBv;e8CimWXHiYJm$4kNo!$jtr8Bmhco@pm@gVmtFNP#h+O*)GN6Lz@4LEq z&&KmS#|yvV+J3`@f5SEYjthRuJ@F|wagUo=7r0<+$-i3vSSh?(x4#tntf8Y6`K-3H z None: + """Set this app's identity. The host app MUST call this at import time.""" + global APP_NAME, SESSION_COOKIE, _SESSION_SALT + APP_NAME = app_name + SESSION_COOKIE = session_cookie + _SESSION_SALT = session_salt + + +class _LazyLogger: + """Resolves at CALL time, not import time. + + The host app calls configure() AFTER this module is imported (from its + main.py), so an eagerly-created module-level logger would bind the + 'unset-app' sentinel name and every OIDC log line would carry the wrong + attribution. Logging through this proxy reads the configured APP_NAME + when the line is actually emitted; logging.getLogger caches by name, so + the per-call lookup is free. + """ + + def __getattr__(self, name): + return getattr(logging.getLogger(APP_NAME), name) + + +logger = _LazyLogger() + + +def _oidc_env(name: str) -> str: + return os.environ.get(name, "").strip() + + +def is_oidc_configured() -> bool: + """True when Cloudron has injected the OIDC addon env vars.""" + return bool( + _oidc_env("CLOUDRON_OIDC_CLIENT_ID") + and _oidc_env("CLOUDRON_OIDC_CLIENT_SECRET") + and _oidc_env("CLOUDRON_OIDC_AUTH_ENDPOINT") + ) + + +def _session_serializer() -> URLSafeTimedSerializer: + # Derive a stable, secret signing key from the OIDC client secret (already + # a secret the app holds, and stable across restarts). + secret = _oidc_env("CLOUDRON_OIDC_CLIENT_SECRET") or _secrets.token_urlsafe(32) + return URLSafeTimedSerializer(secret, salt=_SESSION_SALT) + + +def _redirect_uri(request_host: str) -> str: + domain = _oidc_env("CLOUDRON_APP_DOMAIN") + host = domain or request_host + scheme = "https" + return f"{scheme}://{host}/auth/openid/callback" + + +def build_login_url(request_host: str) -> tuple[str, str, str]: + """Return (login_url, state, nonce). Caller stores state+nonce in cookies.""" + state = _secrets.token_urlsafe(24) + nonce = _secrets.token_urlsafe(24) + params = { + "response_type": "code", + "client_id": _oidc_env("CLOUDRON_OIDC_CLIENT_ID"), + "redirect_uri": _redirect_uri(request_host), + "scope": SCOPES, + "state": state, + "nonce": nonce, + } + url = f"{_oidc_env('CLOUDRON_OIDC_AUTH_ENDPOINT')}?{urllib.parse.urlencode(params)}" + return url, state, nonce + + +async def exchange_code(code: str, request_host: str, nonce: str) -> str: + """Exchange an authorization code for an ID token, returning the username. + + Validates the ID token signature (JWKS), issuer, audience, nonce, and + expiry. Returns the `sub` claim (Cloudron = username) on success. + Raises ValueError on any failure. + """ + issuer = _oidc_env("CLOUDRON_OIDC_ISSUER") + client_id = _oidc_env("CLOUDRON_OIDC_CLIENT_ID") + client_secret = _oidc_env("CLOUDRON_OIDC_CLIENT_SECRET") + token_endpoint = _oidc_env("CLOUDRON_OIDC_TOKEN_ENDPOINT") + keys_endpoint = _oidc_env("CLOUDRON_OIDC_KEYS_ENDPOINT") + + id_token = None + async with httpx.AsyncClient(timeout=20.0) as client: + # Token exchange (client_secret_post). + token_resp = await client.post( + token_endpoint, + data={ + "grant_type": "authorization_code", + "code": code, + "redirect_uri": _redirect_uri(request_host), + "client_id": client_id, + "client_secret": client_secret, + }, + ) + if token_resp.status_code != 200: + logger.warning("OIDC token exchange failed: %s %s", token_resp.status_code, token_resp.text[:200]) + raise ValueError("token exchange failed") + id_token = token_resp.json().get("id_token") + if not id_token: + logger.warning("OIDC token response missing id_token") + raise ValueError("missing id_token") + + # Fetch JWKS. + keys_resp = await client.get(keys_endpoint) + if keys_resp.status_code != 200: + logger.warning("OIDC JWKS fetch failed: %s", keys_resp.status_code) + raise ValueError("jwks fetch failed") + jwks = keys_resp.json() + + # Validate signature + standard claims (exp/nbf) via claims.validate(), + # and check iss/aud/nonce manually (authlib's JWTClaims.validate() only + # handles exp/nbf; issuer/audience/nonce are checked explicitly). + try: + jwk_set = JsonWebKey.import_key_set(jwks) + jwt = JsonWebToken(["RS256", "EdDSA"]) + claims = jwt.decode(id_token, jwk_set) + claims.validate() # validates exp + nbf + # Issuer + audience + nonce (replay protection). + if claims.get("iss") != issuer: + logger.warning("OIDC id_token issuer mismatch: %s", claims.get("iss")) + raise ValueError("issuer mismatch") + if claims.get("aud") != client_id: + logger.warning("OIDC id_token audience mismatch: %s", claims.get("aud")) + raise ValueError("audience mismatch") + if claims.get("nonce") != nonce: + logger.warning("OIDC id_token nonce mismatch") + raise ValueError("nonce mismatch") + except Exception as e: + logger.warning("OIDC id_token validation failed: %s", e) + raise ValueError("id_token validation failed") from e + + username = claims.get("sub") + if not username: + logger.warning("OIDC id_token missing sub claim") + raise ValueError("missing sub claim") + + return str(username) + + +def write_session(identity: str) -> str: + """Create a signed session token for the given identity (username).""" + return _session_serializer().dumps({"identity": identity}) + + +def read_session(token: str) -> str | None: + """Return the identity from a signed session token, or None if invalid.""" + if not token: + return None + try: + data = _session_serializer().loads(token, max_age=SESSION_MAX_AGE) + return data.get("identity") if isinstance(data, dict) else None + except (BadSignature, SignatureExpired): + return None diff --git a/scripts/shared/test_oidc_client.py b/scripts/shared/test_oidc_client.py new file mode 100644 index 0000000..b563c3d --- /dev/null +++ b/scripts/shared/test_oidc_client.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Behaviour harness for the shared OIDC client module (steward-host only). + +The module's real imports (authlib, itsdangerous, httpx) are not installed on +the steward host, so authlib/httpx are STUBBED and itsdangerous is expected +(pip install itsdangerous). Exercises the parts a copy-edit could break: + + 1. configure() sets the identity; the lazy logger attributes lines to the + CONFIGURED name even though it was created before configure() ran. + 2. write_session/read_session roundtrip on the configured salt, with the + session secret taken from the env (the real derive-from-client-secret + path) — and a DIFFERENT salt cannot read the other app's token. + 3. tampered/expired tokens read as None (no exception leaks). + 4. the pin check: this file's sibling oidc_client.py must be byte-identical + to both repos' copies (same guarantee as check-oidc-sync.py, so the + harness never validates a drifted copy). + +Run: python3 scripts/shared/test_oidc_client.py (from the ops-docs repo) +""" +import hashlib +import logging +import os +import sys +import tempfile +from pathlib import Path +from types import ModuleType + +HERE = Path(__file__).resolve().parent +REPOS = HERE.parent.parent.parent + +# --- stub authlib + httpx BEFORE importing the module ----------------------- +for name in ("authlib", "authlib.jose"): + m = ModuleType(name) + sys.modules.setdefault(name, m) +sys.modules["authlib.jose"].JsonWebToken = object +sys.modules["authlib.jose"].JsonWebKey = object +httpx = ModuleType("httpx") +httpx.AsyncClient = object +sys.modules["httpx"] = httpx + +try: + import itsdangerous # noqa: F401 +except ImportError: + sys.exit("itsdangerous is required: pip install itsdangerous") + +sys.path.insert(0, str(HERE)) +oidc = __import__("oidc_client") + +failures = [] + + +def check(name, ok, detail=""): + print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else "")) + if not ok: + failures.append(name) + + +# --- 0. the copies this harness validates are the byte-identical ones ------- +canon = hashlib.sha256((HERE / "oidc_client.py").read_bytes()).hexdigest() +for repo in ("member-dashboard", "admin-panel"): + copy = REPOS / repo / "app" / "oidc.py" + check(f"sync: {repo}/app/oidc.py byte-identical to canonical", + hashlib.sha256(copy.read_bytes()).hexdigest() == canon, str(copy)) + +# --- 1. configure() + lazy logger ------------------------------------------- +pre = oidc.logger.name # read BEFORE configure: sentinel, not a crash +oidc.configure("admin-panel", "admin_oidc_session", "admin-panel-oidc-session") +records = [] + + +class _Capture(logging.Handler): + def emit(self, record): + records.append(record) + + +h = _Capture() +oidc.logger.addHandler(h) # the proxy resolves the configured logger +oidc.logger.setLevel(logging.WARNING) +oidc.logger.warning("probe line") +check("configure: identity is the app's", oidc.APP_NAME == "admin-panel" + and oidc.SESSION_COOKIE == "admin_oidc_session") +check("lazy logger: pre-configure name is the loud sentinel", + pre == "unset-app", pre) +check("lazy logger: lines attribute to the CONFIGURED app", + bool(records) and records[-1].name == "admin-panel", + records[-1].name if records else "no record") + +# --- 2/3. session tokens on the configured salt ------------------------------ +with tempfile.TemporaryDirectory() as td: + os.environ["CLOUDRON_OIDC_CLIENT_SECRET"] = "unit-test-secret" + token = oidc.write_session("nathan") + check("session: roundtrip returns the identity", + oidc.read_session(token) == "nathan") + check("session: cookie name survived configure", + oidc.SESSION_COOKIE == "admin_oidc_session") + tampered = token[:-3] + ("aaa" if token[-3:] != "aaa" else "bbb") + check("session: tampered token reads None (no exception)", + oidc.read_session(tampered) is None) + check("session: empty token reads None", oidc.read_session("") is None) + + # A different salt (the other app's) must NOT read this token. + oidc.configure("member-dashboard", "member_oidc_session", + "member-dashboard-oidc-session") + check("session: the other app's salt cannot read this app's token", + oidc.read_session(token) is None) + d_tok = oidc.write_session("someuser") + check("session: dashboard roundtrip on its own salt", + oidc.read_session(d_tok) == "someuser") + check("session: APP_NAME switched with configure", + oidc.APP_NAME == "member-dashboard") + os.environ.pop("CLOUDRON_OIDC_CLIENT_SECRET") + +# back to the panel identity, as the panel's main.py leaves it +oidc.configure("admin-panel", "admin_oidc_session", "admin-panel-oidc-session") + +print() +print(f"{len(failures)} failure(s)" + (": " + ", ".join(failures) if failures else "")) +sys.exit(1 if failures else 0) diff --git a/scripts/sync-oidc-module.sh b/scripts/sync-oidc-module.sh new file mode 100755 index 0000000..ceeba4c --- /dev/null +++ b/scripts/sync-oidc-module.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# Sync the shared OIDC client module to both thin apps, and re-pin them. +# +# ops-docs/scripts/sync-oidc-module.sh +# +# The canonical module is scripts/shared/oidc_client.py in THIS repo. The two +# consumer repos (member-dashboard, admin-panel) ship BYTE-IDENTICAL copies at +# app/oidc.py so their login never depends on another app being up. Editing a +# copy by hand is a dead end: this script overwrites it, and the repo's +# tests/test_oidc_sync.py goes red on any drift from the pinned revision. +# +# What this does: +# 1. copies the canonical module over both repos' app/oidc.py +# 2. regenerates each repo's tests/test_oidc_sync.py with the CURRENT +# canonical sha256 (the pin CI checks, since CI has no ops-docs checkout) +# 3. py_compiles every touched file +# 4. runs check-oidc-sync.py as the gate — a red check leaves the working +# tree dirty so nothing can be silently committed half-synced +# +# After it passes: commit all three repos (ops-docs + both apps). +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPOS="$(dirname "$(dirname "$HERE")")" # ops-docs/scripts -> ops-docs -> ~/repos +CANONICAL="$HERE/shared/oidc_client.py" + +[ -f "$CANONICAL" ] || { echo "canonical module missing: $CANONICAL" >&2; exit 1; } + +SHA="$(sha256sum "$CANONICAL" | cut -d' ' -f1)" +echo "canonical sha256: $SHA" + +gen_pin_test() { # + local repo="$1" configure="$2" + local dir="$REPOS/$repo" + mkdir -p "$dir/tests" + cat > "$dir/tests/test_oidc_sync.py" < $repo/app/oidc.py" + python3 -m py_compile "$REPOS/$repo/app/oidc.py" "$REPOS/$repo/tests/test_oidc_sync.py" +done +echo "py_compile: OK (both copies + both pin tests)" + +python3 "$HERE/check-oidc-sync.py"