forked from code/member-dashboard
oidc.py: single-sourced shared module; guest trail consumes the portal's state
- app/oidc.py is now a byte-identical copy of the canonical module (ops-docs: scripts/shared/oidc_client.py); this app's identity (logger name, session cookie, session salt) is set via oidc.configure() in main.py with the app's historical values, so existing sessions survive. tests/test_oidc_sync.py pins the copy to the canonical revision — a hand edit goes red; changes go through the canonical + sync-oidc-module.sh. - The guest trail pill consumes the portal-served `state` (the single invited-vs-active derivation, tested in the portal) with the old status-only payload fallback kept; dashboard-guests-harness.js asserts both shapes through the real page JS.
This commit is contained in:
1 parent
1e6e9e481c
commit
622982a371
4 files changed
+184
-13
No files matched your search
+12
-3
@@ -26,6 +26,13 @@ from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
|
||||
|
||||
from app import oidc
|
||||
|
||||
# The oidc module is SHARED (byte-identical copy of the canonical
|
||||
# ops-docs: scripts/shared/oidc_client.py — see tests/test_oidc_sync.py);
|
||||
# this app's identity (logger name, session cookie, session salt) is set
|
||||
# here. The cookie name and salt are the app's historical values, so
|
||||
# existing sessions survive the consolidation.
|
||||
oidc.configure("member-dashboard", "member_oidc_session", "member-dashboard-oidc-session")
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger("member-dashboard")
|
||||
|
||||
@@ -1035,9 +1042,11 @@ function renderGuests(d) {
|
||||
$('guest-trail').innerHTML = trail.map(t => {
|
||||
const who = t.name ? escapeHtml(t.name) + ' · ' + escapeHtml(t.recipient) : escapeHtml(t.recipient);
|
||||
const when = t.decided_at ? 'Decided ' + fmtDay(t.decided_at) : 'Sent ' + fmtDay(t.created_at);
|
||||
// `state` carries the portal's derived display state — 'invited' while the
|
||||
// guest has not accepted their setup invite (never 'active' before that).
|
||||
// Older payloads carry status only; fall back to it.
|
||||
// `state` carries the portal's derived display state — the SINGLE
|
||||
// derivation lives in the portal (tested there) and this page derives
|
||||
// nothing: 'invited' while the guest has not accepted their setup invite
|
||||
// (never 'active' before that), else the ledger status. Older payloads
|
||||
// carry status only; fall back to it.
|
||||
return '<div class="guest-row">' +
|
||||
'<div><div class="guest-who">' + who + '</div>' +
|
||||
'<div class="guest-meta">' + when + '</div></div>' +
|
||||
|
||||
+52
-10
@@ -1,7 +1,12 @@
|
||||
"""OIDC client for Cloudron's OpenID Connect addon.
|
||||
"""OIDC client for Cloudron's OpenID Connect addon — ONE shared module.
|
||||
|
||||
Implements the authorization-code flow against Cloudron's built-in OIDC
|
||||
provider, so the app no longer depends on the proxyAuth header wall.
|
||||
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):
|
||||
@@ -16,8 +21,16 @@ never cache at import):
|
||||
CLOUDRON_APP_DOMAIN the app's public domain
|
||||
|
||||
Identity: Cloudron's `sub` claim is the username (the unique user identifier).
|
||||
We use `sub` (username) as the identity — the portal's broker accepts it as
|
||||
`X-Member-User` and resolves username → email.
|
||||
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
|
||||
@@ -29,15 +42,44 @@ import httpx
|
||||
from authlib.jose import JsonWebToken, JsonWebKey
|
||||
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
|
||||
|
||||
logger = logging.getLogger("member-dashboard")
|
||||
# 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 cookie name + max age (8 hours, roughly a working day).
|
||||
SESSION_COOKIE = "member_oidc_session"
|
||||
SESSION_MAX_AGE = 60 * 60 * 8
|
||||
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()
|
||||
|
||||
@@ -55,7 +97,7 @@ 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="member-dashboard-oidc-session")
|
||||
return URLSafeTimedSerializer(secret, salt=_SESSION_SALT)
|
||||
|
||||
|
||||
def _redirect_uri(request_host: str) -> str:
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// Harness for the member dashboard's GUEST TRAIL (the member's own invite
|
||||
// history), run through the panel's vendored checker:
|
||||
// bash ../admin-panel/tests/check-page-js.sh app/main.py dashboard-guests-harness.js
|
||||
//
|
||||
// The portal derives the trail's display state (the SINGLE derivation, tested
|
||||
// in the portal's tests/test_guest_invited_state.py); this page CONSUMES it:
|
||||
// * state='invited' wins even though the ledger status underneath is still
|
||||
// 'active' — a provisioned-but-not-set-up guest is never 'active';
|
||||
// * state carries the ledger status once accepted/ended (expired ...);
|
||||
// * an older payload with status only falls back to it (the thin shim).
|
||||
// The checker evals in CommonJS (no top-level await), so the body is wrapped.
|
||||
const assert = (cond, msg) => { if (!cond) { console.error("FAIL: " + msg); process.exit(1); } };
|
||||
const count = (s, re) => (String(s).match(re) || []).length;
|
||||
|
||||
async function runRender(payload) {
|
||||
globalThis.fetch = async () => ({ status: 200, json: async () => payload });
|
||||
await loadGuests();
|
||||
}
|
||||
|
||||
(async () => {
|
||||
// New payload: the portal serves `state` on every trail entry.
|
||||
await runRender({
|
||||
eligible: false,
|
||||
next_eligible_at: "2026-12-15T00:00:00Z",
|
||||
trail: [
|
||||
{ kind: "guest", recipient: "pending@example.com", created_at: "2026-11-10 10:00:00",
|
||||
status: "active", state: "invited" },
|
||||
{ kind: "guest", recipient: "lapsed@example.com", created_at: "2026-09-01 10:00:00",
|
||||
decided_at: "2026-10-30 10:00:00", status: "expired", state: "expired" },
|
||||
],
|
||||
});
|
||||
{
|
||||
const t = document.getElementById("guest-trail").innerHTML;
|
||||
assert(/gpill invited[^>]*>Invited — awaiting setup</.test(t),
|
||||
"portal-served state='invited' renders the awaiting-setup pill even though the ledger says active");
|
||||
assert(!/>active guest</.test(t),
|
||||
"a pending guest is never rendered as an active guest");
|
||||
assert(/gpill done[^>]*>ended — time ran out</.test(t),
|
||||
"state='expired' renders the ended pill");
|
||||
assert(t.indexOf("pending@example.com") !== -1 && t.indexOf("lapsed@example.com") !== -1,
|
||||
"both trail rows render");
|
||||
assert(document.getElementById("guest-invite-wrap").style.display === "none",
|
||||
"used invite: the form is hidden (next-date hint takes its place)");
|
||||
assert(document.getElementById("guest-allowance").textContent.indexOf("next invite is available") !== -1,
|
||||
"the next-open date is surfaced");
|
||||
}
|
||||
|
||||
// Old payload shape: status only, no state — the shim falls back to it.
|
||||
await runRender({
|
||||
eligible: true,
|
||||
trail: [
|
||||
{ kind: "guest", recipient: "friend@example.com", created_at: "2026-11-09 10:00:00",
|
||||
status: "active" },
|
||||
],
|
||||
});
|
||||
{
|
||||
const t = document.getElementById("guest-trail").innerHTML;
|
||||
assert(/gpill ok[^>]*>active guest</.test(t),
|
||||
"old payload (status only) falls back to the ledger status");
|
||||
assert(document.getElementById("guest-invite-wrap").style.display === "",
|
||||
"eligible: the invite form is shown");
|
||||
}
|
||||
|
||||
console.log("DASHBOARD GUESTS HARNESS OK: consumes the portal's state, old-shape fallback intact");
|
||||
})().catch((e) => { console.error("FAIL: " + (e && e.stack || e)); process.exit(1); });
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/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 = "0b17a491b26bceab42fc95f1a091cee50b7ab298096e99ac7b09c771ce99cd55"
|
||||
EXPECTED_CONFIGURE = '''oidc.configure("member-dashboard", "member_oidc_session", "member-dashboard-oidc-session")'''
|
||||
|
||||
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")
|
||||
Reference in new issue
Block a user