panel: split read from write — any admitted Cloudron account reads, ADMIN_USERNAMES writes
The Cloudron access group alone was not enough: the app's own allowlist still 403'd every non-admin, so a steward with panel access saw nothing. Read is now any authenticated identity Cloudron admitted to the app; write (balances, credits, guest invites) stays with ADMIN_USERNAMES, enforced on every POST. The page says which role you have and hides write controls when read-only.
This commit is contained in:
1 parent
2579e972f9
commit
bd0746d197
1 file changed
+74
-30
+74
-30
@@ -1,19 +1,22 @@
|
||||
"""Admin Panel — co-op-wide member overview, spend, and balance management.
|
||||
|
||||
Security model:
|
||||
- Authentication is done by Cloudron's proxyAuth wall (SSO). Cloudron injects
|
||||
the authenticated user's username via X-Remote-User.
|
||||
- Access is further restricted to a small ADMIN_USERNAMES allowlist (checked
|
||||
against the injected username), so only designated admins see this panel.
|
||||
- This app calls the member portal's /admin/overview and /admin/set-balance
|
||||
endpoints, authenticated with the portal's dedicated ADMIN_TOKEN (the
|
||||
X-Admin-Token header — NOT the webhook's URL token, which cannot unlock
|
||||
/admin/*).
|
||||
Security model — TWO roles, split by the app itself:
|
||||
- Authentication is Cloudron OIDC. Cloudron only completes the login for users
|
||||
the app's access restriction admits (the `managers` and `stewards` groups),
|
||||
so "authenticated here" already means "the operator let this account in".
|
||||
- READ: any authenticated identity may view the panel (overview, spend, dues,
|
||||
guests, money series). The page says so and hides every write control.
|
||||
- WRITE: only the ADMIN_USERNAMES allowlist (Cloudron usernames, comma-
|
||||
separated) may change balances/credits or provision guests. Every POST route
|
||||
re-checks this server-side — hiding a button is not access control.
|
||||
- This app calls the member portal's /admin/* endpoints with the portal's
|
||||
dedicated ADMIN_TOKEN (the X-Admin-Token header — NOT the webhook's URL
|
||||
token, which cannot unlock /admin/*).
|
||||
|
||||
Environment (Cloudron env vars):
|
||||
PORTAL_BASE — base URL of the member portal
|
||||
ADMIN_TOKEN — the portal's admin/webhook token (for /admin/* endpoints)
|
||||
ADMIN_USERNAMES — comma-separated list of allowed Cloudron usernames
|
||||
ADMIN_USERNAMES — comma-separated list of Cloudron usernames with WRITE access
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -63,12 +66,18 @@ def get_identity(request: Request) -> str:
|
||||
|
||||
|
||||
def is_admin(request: Request) -> bool:
|
||||
"""WRITE access: the identity must be in ADMIN_USERNAMES."""
|
||||
identity = get_identity(request)
|
||||
if not identity:
|
||||
return False
|
||||
return identity.lower() in ADMIN_USERNAMES
|
||||
|
||||
|
||||
def is_reader(request: Request) -> bool:
|
||||
"""READ access: any authenticated Cloudron identity Cloudron admitted."""
|
||||
return bool(get_identity(request))
|
||||
|
||||
|
||||
async def portal_get(path: str) -> dict:
|
||||
async with httpx.AsyncClient(timeout=20.0) as client:
|
||||
r = await client.get(f"{PORTAL_BASE}{path}", headers={"X-Admin-Token": ADMIN_TOKEN})
|
||||
@@ -116,28 +125,25 @@ async def index(request: Request):
|
||||
"<h1>Forbidden</h1><p>This panel is restricted to administrators.</p>",
|
||||
status_code=403,
|
||||
)
|
||||
# Authenticated but not an admin → forbid.
|
||||
if identity.lower() not in ADMIN_USERNAMES:
|
||||
return HTMLResponse(
|
||||
"<h1>Forbidden</h1><p>This panel is restricted to administrators.</p>",
|
||||
status_code=403,
|
||||
)
|
||||
# Authenticated → READ is allowed for everyone Cloudron admitted to the app;
|
||||
# WRITE stays with the ADMIN_USERNAMES roster (enforced on every POST).
|
||||
read_only = identity.lower() not in ADMIN_USERNAMES
|
||||
# no-store: the page is one inline script with no validators, so a cached
|
||||
# copy runs the PREVIOUS deploy's JS and makes a working app look broken
|
||||
# (it did, 2026-11-13).
|
||||
return HTMLResponse(render_page(), headers={"Cache-Control": "no-store"})
|
||||
return HTMLResponse(render_page(read_only), headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@app.get("/api/overview")
|
||||
async def api_overview(request: Request):
|
||||
if not is_admin(request):
|
||||
if not is_reader(request):
|
||||
return JSONResponse({"error": "forbidden"}, status_code=403)
|
||||
return await portal_get("/admin/overview")
|
||||
|
||||
|
||||
@app.get("/api/model-usage")
|
||||
async def api_model_usage(request: Request):
|
||||
if not is_admin(request):
|
||||
if not is_reader(request):
|
||||
return JSONResponse({"error": "forbidden"}, status_code=403)
|
||||
try:
|
||||
return await portal_get("/admin/model-usage")
|
||||
@@ -153,7 +159,7 @@ async def api_metrics(request: Request, days: int = 730):
|
||||
only reads it. Fetched once at the widest range and sliced client-side, so
|
||||
the period toggle never refetches.
|
||||
"""
|
||||
if not is_admin(request):
|
||||
if not is_reader(request):
|
||||
return JSONResponse({"error": "forbidden"}, status_code=403)
|
||||
try:
|
||||
return await portal_get(f"/admin/metrics/series?days={max(1, min(int(days), 730))}")
|
||||
@@ -169,7 +175,7 @@ async def api_money_series(request: Request):
|
||||
the panel only reads it. The full history comes back in one payload — the
|
||||
period and spend-mode toggles slice client-side and never refetch.
|
||||
"""
|
||||
if not is_admin(request):
|
||||
if not is_reader(request):
|
||||
return JSONResponse({"error": "forbidden"}, status_code=403)
|
||||
try:
|
||||
return await portal_get("/admin/money-series")
|
||||
@@ -293,7 +299,7 @@ async def api_guest_ledger(request: Request):
|
||||
approval gate, removed 2026-11-08: member invitations provision
|
||||
immediately, so there is nothing to approve.)
|
||||
"""
|
||||
if not is_admin(request):
|
||||
if not is_reader(request):
|
||||
return JSONResponse({"error": "forbidden"}, status_code=403)
|
||||
try:
|
||||
return await portal_get("/admin/guest-ledger")
|
||||
@@ -358,8 +364,18 @@ def _esc(s: str) -> str:
|
||||
return s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
|
||||
|
||||
|
||||
def render_page() -> str:
|
||||
return PAGE_HTML
|
||||
def render_page(read_only: bool) -> str:
|
||||
"""Render the panel for one role.
|
||||
|
||||
The role is injected into the page's JS as one assignment after
|
||||
`let READ_ONLY = false;` — the placeholder stays a JS comment, so the
|
||||
literal is still `node --check`-clean for tests/check-page-js.sh. Hiding
|
||||
the write controls here is UX only; every POST route re-checks the roster.
|
||||
"""
|
||||
html = PAGE_HTML
|
||||
html = html.replace("@@WRITERS@@", ", ".join(sorted(ADMIN_USERNAMES)) or "the operator")
|
||||
html = html.replace("/*@@READ_ONLY@@*/", "READ_ONLY = true;" if read_only else "")
|
||||
return html
|
||||
|
||||
|
||||
# The shared chart module (canonical: ops-docs scripts/shared/coop_chart.js,
|
||||
@@ -450,6 +466,10 @@ PAGE_HTML = """<!DOCTYPE html>
|
||||
.flash.show { display: block; }
|
||||
.flash.ok { background: #eaf3ea; color: #2f5c30; }
|
||||
.flash.err { background: #f6e9e5; color: var(--danger); }
|
||||
/* Role banner: the page states which role you have at the top, where it is
|
||||
unmissable, instead of leaving write controls just absent. */
|
||||
.readonly-banner { background: #eef3ee; border: 1px solid #d7e2d6; border-radius: 10px; padding: 12px 16px; font-size: 13px; color: var(--ink); margin: 0 0 4px; }
|
||||
.readonly-banner strong { color: var(--green-deep); }
|
||||
.adjust { display: inline-flex; gap: 6px; align-items: center; white-space: nowrap; }
|
||||
.adjust input { width: 56px; padding: 4px 6px; border: 1px solid var(--border); border-radius: 6px; font-size: 12px; flex-shrink: 0; }
|
||||
.adjust button { cursor: pointer; border: none; border-radius: 6px; background: var(--green-deep); color: #fff; font-size: 11px; font-weight: 600; padding: 4px 8px; flex-shrink: 0; }
|
||||
@@ -483,6 +503,13 @@ PAGE_HTML = """<!DOCTYPE html>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="readonly-banner" id="readonly-banner" style="display:none;">
|
||||
<strong>Read-only view.</strong> You can see members, spend, dues, guests and money —
|
||||
but only <span id="readonly-writers">@@WRITERS@@</span> can change balances or credits,
|
||||
or invite guests. Buttons that write are hidden, and the server refuses those requests
|
||||
from any other account.
|
||||
</div>
|
||||
|
||||
<div class="totals">
|
||||
<div class="tot"><div class="num" id="tot-members">—</div><div class="lbl">members</div></div>
|
||||
<div class="tot"><div class="num" id="tot-guests">—</div><div class="lbl">guests — guest access</div><div class="sub">excluded from member counts</div></div>
|
||||
@@ -521,7 +548,7 @@ PAGE_HTML = """<!DOCTYPE html>
|
||||
<th class="sortable" onclick="sortMembers('spend')"><span id="spend-mode-label">Spend</span><span class="arrow" id="arrow-members-spend"></span></th>
|
||||
<th class="sortable" onclick="sortMembers('dues_amount')" title="What the member currently pays on Open Collective — their dues level (e.g. $10/mo). Blank when OC shows no live recurring contribution.">Dues<span class="arrow" id="arrow-members-dues_amount"></span></th>
|
||||
<th class="sortable balance-col" onclick="sortMembers('reset_at')">Reset<span class="arrow" id="arrow-members-reset_at"></span></th>
|
||||
<th>Adjust</th>
|
||||
<th id="adjust-th">Adjust</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="rows"><tr><td colspan="10" style="color:var(--muted)">Loading…</td></tr></tbody>
|
||||
@@ -643,6 +670,10 @@ PAGE_HTML = """<!DOCTYPE html>
|
||||
/*@@CHART_MODULE@@*/
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// Role flag, injected per request by render_page() (READ_ONLY = true for an
|
||||
// account outside ADMIN_USERNAMES). UI only — POST routes enforce it.
|
||||
let READ_ONLY = false; /*@@READ_ONLY@@*/
|
||||
|
||||
let flashTimer = null;
|
||||
function flash(msg, ok) {
|
||||
const f = $('flash');
|
||||
@@ -1088,6 +1119,15 @@ function renderMembers() {
|
||||
const org = m.org
|
||||
? ' <span class="pill org" title="Organizational membership: dues paid by OC organization">org: ' + esc(m.org) + '</span>'
|
||||
: '';
|
||||
// Write controls exist only for the writer role. Presentation only — the
|
||||
// POST routes re-check ADMIN_USERNAMES, so a hand-built request still fails.
|
||||
const adjustCell = READ_ONLY
|
||||
? '<td class="balance-col"><span style="color:var(--muted)" title="Read-only view — only the operator accounts can adjust">—</span></td>'
|
||||
: '<td><div class="adjust">' +
|
||||
'<input id="add-' + i(m.email) + '" placeholder="+$" />' +
|
||||
'<button data-email="' + esc(m.email) + '" onclick="addBalance(this.dataset.email)" title="Add monthly allowance">Allow</button>' +
|
||||
'<button data-email="' + esc(m.email) + '" class="credits-btn" onclick="addCredits(this.dataset.email)" title="Add non-expiring credits">Credit</button>' +
|
||||
'</div></td>';
|
||||
return '<tr>' +
|
||||
'<td><strong>' + esc(top) + '</strong>' + emailLine + mxidLine +
|
||||
(org ? '<div style="margin-top:3px">' + org + '</div>' : '') + '</td>' +
|
||||
@@ -1099,11 +1139,7 @@ function renderMembers() {
|
||||
'<td class="num">' + fmt(memberSpend(m)) + '</td>' +
|
||||
'<td class="num">' + duesCell(m) + '</td>' +
|
||||
'<td class="balance-col">' + esc(reset) + '</td>' +
|
||||
'<td><div class="adjust">' +
|
||||
'<input id="add-' + i(m.email) + '" placeholder="+$" />' +
|
||||
'<button data-email="' + esc(m.email) + '" onclick="addBalance(this.dataset.email)" title="Add monthly allowance">Allow</button>' +
|
||||
'<button data-email="' + esc(m.email) + '" class="credits-btn" onclick="addCredits(this.dataset.email)" title="Add non-expiring credits">Credit</button>' +
|
||||
'</div></td>' +
|
||||
adjustCell +
|
||||
'</tr>';
|
||||
}).join('');
|
||||
clearArrows('members', memberSort);
|
||||
@@ -1287,6 +1323,14 @@ async function sendGuestAccess(ev) {
|
||||
// inviter, credits, expiry and status, exactly like admin-created ones.
|
||||
// The portal's /admin/guest-ledger still feeds the duplicate-send guard.
|
||||
|
||||
// Role-dependent chrome: read-only accounts see the banner and no write
|
||||
// controls. Runs before the first load() so no button ever flashes on screen.
|
||||
if (READ_ONLY) {
|
||||
$('readonly-banner').style.display = '';
|
||||
$('guest-invite-section').style.display = 'none';
|
||||
$('adjust-th').style.display = 'none';
|
||||
}
|
||||
|
||||
buildMetricButtons();
|
||||
load();
|
||||
loadModels();
|
||||
|
||||
Reference in new issue
Block a user