Add an admin page for managing collector API keys
Admins (Microsoft 365 sign-in names in BACKUP_DASH_ADMINS) get an Admin link to /admin.html, where they can create, list and revoke the API keys collectors use, instead of running manage.py on the server. Backend - /api/v1/admin/keys (list, create, revoke), admins only (403 otherwise); the user comes from the headers nginx sets after sign-in - Changes need an X-Requested-By header, which another site's page can't add, so a signed-in admin's browser can't be used to forge them - A new key is returned once; only its hash is stored. Names are unique for good, so revoked keys' history stays unambiguous - Keys record who created/revoked them and the company they last reported for (schema v2; databases migrate automatically on start) - /api/v1/me reports is_admin; manage.py shares the key code and records itself as creator/revoker Frontend - admin.html / admin.js: name validation shown after interaction (:user-invalid, aria-invalid kept in sync), the one-time key with a copy button (falls back to selecting it if clipboard access is refused), a key table flagging keys quiet for over 24 hours, and revoking confirmed in a <dialog>; results announced in a status region - Shared el() and signed-in helpers moved to dom.js / signed-in.js - Mock mode (?mock=1) includes sample keys Tested: 15 new backend tests (access, forged requests, names, duplicates, revoking, last-used company, v1 -> v2 upgrade); in the browser, every admin flow in mock mode and at phone width; end to end through the nginx config with the real API (a key created on the API works for ingest; revoking it makes ingest 401; non-admins see an explanation and no Admin link). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+24
-17
@@ -15,41 +15,48 @@ Run it as the service user so files it creates stay writable by the API:
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
import random
|
||||
import sys
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from app import db, repo
|
||||
from app.auth import generate_key, hash_key
|
||||
from app import db, keys, repo
|
||||
from app.models import IngestIn
|
||||
from app.settings import DEFAULT_ENV_FILE, load_settings
|
||||
from app.timeutil import to_db, utcnow
|
||||
from app.timeutil import utcnow
|
||||
|
||||
|
||||
def cli_user() -> str:
|
||||
# Recorded as who created/revoked a key; the admin page records the signed-in user instead
|
||||
try:
|
||||
return f"manage.py ({getpass.getuser()})"
|
||||
except Exception:
|
||||
return "manage.py"
|
||||
|
||||
|
||||
def create_key(conn, args):
|
||||
key = generate_key()
|
||||
if not keys.valid_name(args.name):
|
||||
sys.exit("Key names use letters, digits, '.', '_' and '-', starting with a letter or digit")
|
||||
try:
|
||||
conn.execute(
|
||||
"INSERT INTO api_keys (name, key_hash, created_at) VALUES (?, ?, ?)",
|
||||
(args.name, hash_key(key), to_db(utcnow())),
|
||||
)
|
||||
except db.sqlite3.IntegrityError:
|
||||
_, secret = keys.create_key(conn, args.name, created_by=cli_user())
|
||||
except keys.KeyNameTaken:
|
||||
sys.exit(f"A key named {args.name!r} already exists")
|
||||
print(f"API key for {args.name!r} (shown once, store it in the collector's config):\n{key}")
|
||||
print(f"API key for {args.name!r} (shown once, store it in the collector's config):\n{secret}")
|
||||
|
||||
|
||||
def list_keys(conn, args):
|
||||
for r in conn.execute("SELECT name, created_at, last_used_at, revoked_at FROM api_keys ORDER BY name"):
|
||||
state = f"revoked {r['revoked_at']}" if r["revoked_at"] else "active"
|
||||
print(f"{r['name']:<30} {state:<30} created {r['created_at']} last used {r['last_used_at'] or 'never'}")
|
||||
for k in keys.list_keys(conn):
|
||||
state = f"revoked {k['revoked_at']}" if k["revoked_at"] else "active"
|
||||
tenant = f" ({k['last_used_tenant']})" if k["last_used_tenant"] else ""
|
||||
print(f"{k['name']:<30} {state:<30} created {k['created_at']} last used {k['last_used_at'] or 'never'}{tenant}")
|
||||
|
||||
|
||||
def revoke_key(conn, args):
|
||||
cur = conn.execute(
|
||||
"UPDATE api_keys SET revoked_at = ? WHERE name = ? AND revoked_at IS NULL", (to_db(utcnow()), args.name)
|
||||
)
|
||||
sys.exit(0 if cur.rowcount else f"No active key named {args.name!r}")
|
||||
row = conn.execute("SELECT id FROM api_keys WHERE name = ? AND revoked_at IS NULL", (args.name,)).fetchone()
|
||||
if row is None:
|
||||
sys.exit(f"No active key named {args.name!r}")
|
||||
keys.revoke_key(conn, row["id"], revoked_by=cli_user())
|
||||
|
||||
|
||||
def list_jobs(conn, args):
|
||||
|
||||
Reference in New Issue
Block a user