feat(backend): support access by offline challenge codes replaces the master account
Platform v2 step 1.10 (APPS_PLATFORM D-16, section 6.5).
- POST /api/auth/support/challenge (public): an 8-character challenge, stored 15 min
(support_challenges, revision 0009; at most 5 open). POST /api/auth/support/verify
{challenge, code}: code = base32(HMAC(SUPPORT_SECRET, site_id + challenge))[:10];
single use, 5 wrong codes burn the challenge. Opens a 4 h support session
(client=support, synthetic superadmin) with a hard end: sessions.expires_at.
- core/support_codes.py (stdlib only) is the derivation; tools/support_code.py
(--init, --site-secret <SITE_ID>, <SITE_ID> <CHALLENGE>) uses it on the builder's
machine with the master key in %USERPROFILE%/.xenia/support_master_key.txt.
- MASTER_USERNAME/MASTER_PASSWORD removed (config, login, docker-compose.yml,
.env.example); SUPPORT_SECRET added; install.sh asks for it.
- e2e: backends get SUPPORT_SECRET from a test master key and log in with challenge
codes (lib/support.mjs, license_e2e.py); install.mjs expects the new prompt.
- Pack rule CS-15.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -10,7 +10,7 @@ from core.modules.registry import all_permissions
|
||||
|
||||
@dataclass
|
||||
class AccessContext:
|
||||
user: Any = None # User row, or the support ghost (step 1.10); None for device-only calls
|
||||
user: Any = None # User row, or the support account (routers.deps.make_support_user); None for device-only calls
|
||||
session: Any = None # session id (sid) of the user's login
|
||||
device: Any = None # Device row when the call comes from a paired device (D-8)
|
||||
override_token: Optional[str] = None # X-Xenia-Override (D-10); consumed by check() when needed
|
||||
|
||||
@@ -62,6 +62,9 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"auth.username_required": (422, "Enter your username."),
|
||||
"auth.client_not_allowed": (403, "This account can't use the {client} app."),
|
||||
"auth.session_not_found": (404, "Session not found."),
|
||||
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
|
||||
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
|
||||
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
|
||||
"device.revoked": (401, "This device was removed. Pair it again."),
|
||||
"device.not_paired": (401, "This device isn't paired with the venue."),
|
||||
"device.out_of_scope": (403, "A {app} device can't do this ({key})."),
|
||||
|
||||
@@ -44,6 +44,7 @@ class Active(NamedTuple):
|
||||
"""What validate() knows about an active session."""
|
||||
user_id: Optional[int] # None = the support account
|
||||
device_id: Optional[int] # set for terminal sessions: the device they belong to
|
||||
expires_at: Optional[object] = None # hard end (support sessions); None = none
|
||||
|
||||
|
||||
_cache: dict[str, tuple[float, Active]] = {} # sid -> (checked_at monotonic, info) for ACTIVE sessions
|
||||
@@ -61,8 +62,8 @@ def single_session_rule(db, client: str) -> str:
|
||||
|
||||
# ── lifecycle ────────────────────────────────────────────────────────────────
|
||||
|
||||
def start(db, user, client: str, request=None, *, legacy_manager: bool = False, device=None):
|
||||
"""Create a session for user (None user_id for the support ghost). Commits.
|
||||
def start(db, user, client: str, request=None, *, legacy_manager: bool = False, device=None, expires_at=None):
|
||||
"""Create a session for user (None user_id for the support account). Commits.
|
||||
`device`: the paired device of a terminal login; its previous sessions are replaced
|
||||
(a shared screen shows one user at a time)."""
|
||||
from models.session import LoginSession
|
||||
@@ -86,7 +87,7 @@ def start(db, user, client: str, request=None, *, legacy_manager: bool = False,
|
||||
_end_row(s, "replaced")
|
||||
now = utcnow()
|
||||
row = LoginSession(id=uuid.uuid4().hex, user_id=user_id, client=client, created_at=now, last_seen_at=now,
|
||||
device_id=(device.id if device is not None else None),
|
||||
device_id=(device.id if device is not None else None), expires_at=expires_at,
|
||||
ip=(request.client.host if request is not None and request.client else None),
|
||||
user_agent=(request.headers.get("user-agent", "")[:300] if request is not None else None))
|
||||
db.add(row)
|
||||
@@ -138,7 +139,7 @@ def validate(sid: str | None, db=None) -> Active:
|
||||
now_m = time.monotonic()
|
||||
with _lock:
|
||||
hit = _cache.get(sid)
|
||||
if hit and now_m - hit[0] < CACHE_TTL_S:
|
||||
if hit and now_m - hit[0] < CACHE_TTL_S and not (hit[1].expires_at and hit[1].expires_at <= utcnow()):
|
||||
return hit[1]
|
||||
from models.session import LoginSession
|
||||
own = db is None
|
||||
@@ -147,11 +148,14 @@ def validate(sid: str | None, db=None) -> Active:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
row = db.get(LoginSession, sid)
|
||||
if row is not None and row.ended_at is None and row.expires_at is not None and row.expires_at <= utcnow():
|
||||
_end_row(row, "expired")
|
||||
db.commit()
|
||||
if row is None or row.ended_at is not None:
|
||||
with _lock:
|
||||
_cache.pop(sid, None)
|
||||
raise XeniaError("auth.session_ended")
|
||||
info = Active(row.user_id, row.device_id)
|
||||
info = Active(row.user_id, row.device_id, row.expires_at)
|
||||
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
|
||||
finally:
|
||||
if own:
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Support access codes (APPS_PLATFORM D-16, plan step 1.10). Standard library only.
|
||||
|
||||
Used by the backend (routers/auth.py) AND by the builder's tool tools/support_code.py,
|
||||
which loads this file by path, so keep it free of backend imports.
|
||||
|
||||
master key (builder only, %USERPROFILE%\\.xenia\\support_master_key.txt)
|
||||
└─ site secret = HMAC-SHA256(master, "xenia-support-site:" + site_id) -> hex, in the site .env as SUPPORT_SECRET
|
||||
└─ code = base32(HMAC-SHA256(site secret, "xenia-support:" + site_id + ":" + challenge))[:10]
|
||||
|
||||
The site shows a random 8-character challenge (stored server-side for 15 min, single use);
|
||||
the builder runs the tool with the site id and the challenge and reads back the code.
|
||||
Works offline at the site: nothing but the two HMACs is needed. A code made for another
|
||||
site never verifies (different secret, and the site id is in the message).
|
||||
The test suite and tests/e2e (JS) re-implement these two functions; tests/test_support.py
|
||||
pins a known vector so the implementations can't drift apart.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
|
||||
CHALLENGE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # read aloud / typed: no 0/O, 1/I
|
||||
CHALLENGE_LEN = 8
|
||||
CODE_LEN = 10
|
||||
|
||||
|
||||
def site_secret(master_key: str, site_id: str) -> str:
|
||||
return hmac.new(master_key.strip().encode(), f"xenia-support-site:{site_id}".encode(), hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def normalize_challenge(challenge: str) -> str:
|
||||
return "".join(ch for ch in challenge.upper() if ch.isalnum())
|
||||
|
||||
|
||||
def normalize_code(code: str) -> str:
|
||||
# base32 (A-Z, 2-7): people read 0 as O, 1 as I and 8 as B
|
||||
s = "".join(ch for ch in code.upper() if ch.isalnum())
|
||||
return s.translate(str.maketrans({"0": "O", "1": "I", "8": "B"}))
|
||||
|
||||
|
||||
def code_for(secret: str, site_id: str, challenge: str) -> str:
|
||||
msg = f"xenia-support:{site_id}:{normalize_challenge(challenge)}".encode()
|
||||
digest = hmac.new(secret.strip().encode(), msg, hashlib.sha256).digest()
|
||||
return base64.b32encode(digest).decode()[:CODE_LEN]
|
||||
|
||||
|
||||
def new_challenge() -> str:
|
||||
return "".join(secrets.choice(CHALLENGE_ALPHABET) for _ in range(CHALLENGE_LEN))
|
||||
|
||||
|
||||
def group(s: str, size: int) -> str:
|
||||
""""ABCDEFGH" -> "ABCD-EFGH" (for display; input is normalized anyway)."""
|
||||
return "-".join(s[i:i + size] for i in range(0, len(s), size))
|
||||
Reference in New Issue
Block a user