oidc.py: single-sourced shared module; guest pill 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. - Guests list: the pill CONSUMES the portal-served `state` (the single invited-vs-active derivation now lives in the portal and is tested there). The local active-flag re-derivation is deleted — the shim is first-served-field-wins (state → guest_status), so the previous payload shape renders identically during a portal rollback. Guests harness extended: invited-wins-over-ledger-active, served expired, and a payload with neither field renders NO derived pill text.
This commit is contained in:
1 parent
267a573eda
commit
80acfaed3b
4 files changed
+160
-16
No files matched your search
@@ -116,6 +116,43 @@ await runLoad({
|
||||
assert(g.indexOf("2026-12-01") !== -1, "expired guest keeps its expiry date");
|
||||
}
|
||||
|
||||
// ---- The consolidation: the panel CONSUMES the portal's `state` ----
|
||||
// The portal is the single derivation point (tested there); the panel derives
|
||||
// nothing from flags. state='invited' wins even though the ledger underneath
|
||||
// still says active — a provisioned-but-not-set-up guest is never 'active'.
|
||||
await runLoad({
|
||||
members: [memberRow("alice@example.com", 2)],
|
||||
guests: [
|
||||
{ email: "pending@example.com", username: null, active: true, account_type: "guest",
|
||||
guest_inviter: "alice@example.com", credit_balance: 2, credits_remaining: 2,
|
||||
guest_expires_at: "2027-02-01T00:00:00", guest_status: "active", state: "invited",
|
||||
state_reason: "awaiting setup — invite sent 2026-11-10, not yet accepted",
|
||||
spend: 0, all_time_spend: 0 },
|
||||
{ email: "served-expired@example.com", username: null, active: true, account_type: "guest",
|
||||
guest_inviter: "alice@example.com", credit_balance: 2, credits_remaining: 2,
|
||||
guest_expires_at: "2026-12-01T00:00:00", state: "expired",
|
||||
spend: 0, all_time_spend: 0 },
|
||||
{ email: "flagonly@example.com", username: null, active: true, account_type: "guest",
|
||||
guest_inviter: "alice@example.com", credit_balance: 2, credits_remaining: 2,
|
||||
guest_expires_at: "2027-02-01T00:00:00",
|
||||
spend: 0, all_time_spend: 0 },
|
||||
],
|
||||
totals: { members: 1, total_spend: 2, total_all_time_spend: 20,
|
||||
operator_spend: 0, operator_all_time_spend: 0 },
|
||||
});
|
||||
{
|
||||
const g = document.getElementById("guest-rows").innerHTML;
|
||||
assert(/pill invited[^>]*>invited</.test(g),
|
||||
"portal-served state='invited' wins over the ledger's active (never 'active' before setup)");
|
||||
assert(g.indexOf("awaiting setup") !== -1,
|
||||
"invited tooltip names the awaiting-setup reason");
|
||||
assert(/pill inactive[^>]*>expired</.test(g),
|
||||
"portal-served state='expired' renders without any local derivation");
|
||||
const flagRow = g.slice(g.indexOf("flagonly@example.com"));
|
||||
assert(!/>active</.test(flagRow),
|
||||
"no active flag, no served state: NO pill text is derived from the flag (derivation deleted)");
|
||||
}
|
||||
|
||||
// ---- Empty list: the section disappears entirely ----
|
||||
await runLoad({
|
||||
members: [memberRow("alice@example.com", 2)],
|
||||
|
||||
+16
-4
@@ -25,6 +25,13 @@ from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||
|
||||
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("admin-panel", "admin_oidc_session", "admin-panel-oidc-session")
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger("admin-panel")
|
||||
|
||||
@@ -1347,11 +1354,16 @@ function renderMembers() {
|
||||
const emailLine = g.username ? '<div style="color:var(--muted);font-size:11px">' + esc(g.email) + '</div>' : '';
|
||||
const credits = Number(g.credits_remaining ?? g.credit_balance ?? 0);
|
||||
const exp = g.guest_expires_at ? String(g.guest_expires_at).slice(0, 10) : '—';
|
||||
// The portal derives the display state: 'invited' while the guest has
|
||||
// not accepted their setup invite (provisioned but cannot log in yet —
|
||||
// never 'active' before that), else the ledger status.
|
||||
// The portal derives the display state — the SINGLE derivation, tested
|
||||
// once in the portal (tests/test_guest_invited_state.py): 'invited'
|
||||
// while the guest has not accepted their setup invite, else the
|
||||
// guests-ledger status. This row is a pure consumer: first served field
|
||||
// wins, nothing is derived here from flags. (guest_status first keeps
|
||||
// the previous payload shape rendering identically during a portal
|
||||
// rollback; a payload with neither field renders an empty pill — that
|
||||
// shape no longer exists and must not be re-derived.)
|
||||
const st = g.state === 'invited' ? 'invited'
|
||||
: String(g.guest_status || (g.active ? 'active' : 'inactive'));
|
||||
: String(g.guest_status || g.state || '');
|
||||
const stClass = { invited: 'invited', active: 'active', converted: 'org' }[st] || 'inactive';
|
||||
const stTitle = {
|
||||
invited: 'Invited — awaiting setup (the guest has not accepted their invite yet)',
|
||||
|
||||
+52
-12
@@ -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,9 +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).
|
||||
The `email` scope adds `email`/`email_verified`; `profile` adds `name`,
|
||||
`preferred_username`, etc. We use `sub` (username) as the identity, matching
|
||||
the app's ADMIN_USERNAMES allowlist.
|
||||
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
|
||||
@@ -30,15 +42,44 @@ import httpx
|
||||
from authlib.jose import JsonWebToken, JsonWebKey
|
||||
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
|
||||
|
||||
logger = logging.getLogger("admin-panel")
|
||||
# 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 = "admin_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()
|
||||
|
||||
@@ -56,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="admin-panel-oidc-session")
|
||||
return URLSafeTimedSerializer(secret, salt=_SESSION_SALT)
|
||||
|
||||
|
||||
def _redirect_uri(request_host: str) -> str:
|
||||
@@ -95,7 +136,6 @@ async def exchange_code(code: str, request_host: str, nonce: str) -> str:
|
||||
token_endpoint = _oidc_env("CLOUDRON_OIDC_TOKEN_ENDPOINT")
|
||||
keys_endpoint = _oidc_env("CLOUDRON_OIDC_KEYS_ENDPOINT")
|
||||
|
||||
token_resp = None
|
||||
id_token = None
|
||||
async with httpx.AsyncClient(timeout=20.0) as client:
|
||||
# Token exchange (client_secret_post).
|
||||
|
||||
@@ -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("admin-panel", "admin_oidc_session", "admin-panel-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