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/).
This commit is contained in:
inference-bot committed 2026-11-11 05:24:57 +00:00
1 parent 206c3d5379
commit 23d2fc0eb2
7 files changed
+652 -8

No files matched your search

+109
View File
@@ -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())
+210
View File
@@ -0,0 +1,210 @@
"""OIDC client for Cloudron's OpenID Connect addon — ONE shared module.
This file is the SINGLE SOURCE for the two thin Cloudron apps that implement
the authorization-code flow themselves (admin-panel, member-dashboard). The
copies in those repos' app/oidc.py are byte-identical to this file — verified
by ops-docs/scripts/check-oidc-sync.py and enforced by each repo's
tests/test_oidc_sync.py — so a fix lands here, is synced to both repos, and
can never drift. Do not edit a repo copy directly: sync-oidc-module.sh
overwrites it, and the pin test goes red on any hand edit.
Cloudron exports these env vars (they change on every restart — read per-call,
never cache at import):
CLOUDRON_OIDC_ISSUER e.g. https://my.inference.coop/openid
CLOUDRON_OIDC_AUTH_ENDPOINT authorization endpoint
CLOUDRON_OIDC_TOKEN_ENDPOINT token endpoint
CLOUDRON_OIDC_KEYS_ENDPOINT JWKS endpoint (RS256/EdDSA keys)
CLOUDRON_OIDC_PROFILE_ENDPOINT userinfo endpoint
CLOUDRON_OIDC_CLIENT_ID client id
CLOUDRON_OIDC_CLIENT_SECRET client secret
CLOUDRON_APP_DOMAIN the app's public domain
Identity: Cloudron's `sub` claim is the username (the unique user identifier).
We use `sub` as the identity; each host app decides what it authorizes — the
panel matches it against its ADMIN_USERNAMES allowlist, the dashboard
forwards it to the portal's broker as `X-Member-User` (which resolves
username → email).
Per-app identity: the ONLY differences the two copies used to carry were the
logger name, the session cookie name and the session salt. The host app now
supplies those via configure() at import time (see each app's main.py), which
keeps this file byte-identical everywhere while preserving each app's
existing cookie names and salts (so existing sessions survive a redeploy).
"""
import os
import secrets as _secrets
import logging
import urllib.parse
import httpx
from authlib.jose import JsonWebToken, JsonWebKey
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
# Per-app identity — set by the host app at import time via configure().
# The unset sentinels below are loud on purpose: a copy that reaches a
# request without its host app having configured itself is a sync/setup bug.
APP_NAME = "unset-app"
SESSION_COOKIE = "unset_oidc_session"
_SESSION_SALT = "unset-oidc-session"
SESSION_MAX_AGE = 60 * 60 * 8 # 8 hours, roughly a working day
SCOPES = "openid profile email"
def configure(app_name: str, session_cookie: str, session_salt: str) -> 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
+118
View File
@@ -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)
+108
View File
@@ -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() { # <repo> <cookie-literal-configure-call>
local repo="$1" configure="$2"
local dir="$REPOS/$repo"
mkdir -p "$dir/tests"
cat > "$dir/tests/test_oidc_sync.py" <<EOF
#!/usr/bin/env python3
"""oidc.py sync pin — the repo copy is byte-identical to the canonical module.
WHY THIS EXISTS
app/oidc.py is a byte-identical copy of the canonical module
(co-op/ops-docs repo: scripts/shared/oidc_client.py) — the single source for
the OIDC client the thin apps ship copies of, so their login never depends
on another app being up. This test pins the copy to the canonical revision
recorded below: ANY hand edit to app/oidc.py breaks the pin and goes red.
To change the module, edit the canonical file and run
ops-docs/scripts/sync-oidc-module.sh, which re-copies and re-pins both
repos in one step (check-oidc-sync.py is the pre-deploy gate).
Generated by sync-oidc-module.sh — do not edit by hand.
Run: python3 tests/test_oidc_sync.py
"""
import hashlib
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CANONICAL_SHA256 = "$SHA"
EXPECTED_CONFIGURE = '''$configure'''
failures = []
copy = ROOT / "app" / "oidc.py"
if not copy.exists():
failures.append("app/oidc.py missing")
else:
got = hashlib.sha256(copy.read_bytes()).hexdigest()
if got == CANONICAL_SHA256:
print(f"ok - app/oidc.py matches the pinned canonical revision ({got[:16]}…)")
else:
failures.append(
"app/oidc.py DRIFTED from the pinned canonical revision\\n"
f" pinned {CANONICAL_SHA256}\\n"
f" actual {got}\\n"
" fix: edit the canonical module (ops-docs: scripts/shared/oidc_client.py) "
"and run ops-docs/scripts/sync-oidc-module.sh — never hand-edit the copy.")
main_src = (ROOT / "app" / "main.py")
if not main_src.exists():
failures.append("app/main.py missing")
elif EXPECTED_CONFIGURE not in main_src.read_text():
failures.append(
"app/main.py does not configure this app's oidc identity:\\n"
f" expected literal: {EXPECTED_CONFIGURE}")
if failures:
print()
print("FAILED: " + ", ".join(failures))
sys.exit(1)
print("oidc sync pin: OK")
EOF
echo "regenerated $repo/tests/test_oidc_sync.py"
}
gen_pin_test member-dashboard \
'oidc.configure("member-dashboard", "member_oidc_session", "member-dashboard-oidc-session")'
gen_pin_test admin-panel \
'oidc.configure("admin-panel", "admin_oidc_session", "admin-panel-oidc-session")'
for repo in member-dashboard admin-panel; do
cp "$CANONICAL" "$REPOS/$repo/app/oidc.py"
echo "copied canonical -> $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"