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:
@@ -23,7 +23,7 @@ class LoginByIdRequest(_PydanticBase):
|
||||
pin: str
|
||||
from schemas.user import UserOut
|
||||
from core.i18n import normalize_language
|
||||
from routers.deps import bearer, get_current_user, make_token, decode_token, _make_ghost_superadmin
|
||||
from routers.deps import bearer, get_current_user, make_token, decode_token, make_support_user
|
||||
from core import sessions
|
||||
from core.access.deps import require
|
||||
from core.errors import XeniaError
|
||||
@@ -54,14 +54,6 @@ def do_login(db: Session, request: Request, *, client: str, username: str | None
|
||||
if client == "terminal":
|
||||
return _terminal_login(db, request, username=username, user_id=user_id, pin=pin, password=password)
|
||||
|
||||
# Support access (synthetic superadmin). >>> replaced by challenge codes in step 1.10
|
||||
if (client == "manager" and settings.MASTER_USERNAME and settings.MASTER_PASSWORD
|
||||
and username == settings.MASTER_USERNAME and password == settings.MASTER_PASSWORD):
|
||||
_logger.warning("MASTER LOGIN USED from username=%s", username)
|
||||
ghost = _make_ghost_superadmin()
|
||||
row = sessions.start(db, ghost, "support", request)
|
||||
return TokenResponse(access_token=make_token(ghost, row.id), user=UserOut.model_validate(ghost))
|
||||
|
||||
if client == "manager":
|
||||
mode = sessions.manager_login_mode(db)
|
||||
if not legacy: # the current manager UI (no `client`) keeps v1 behaviour: pin or password
|
||||
@@ -165,6 +157,84 @@ def logout(credentials: Optional[HTTPAuthorizationCredentials] = Depends(_option
|
||||
return {"status": "logged out"}
|
||||
|
||||
|
||||
# ── Support access (D-16, §6.5) ─────────────────────────────────────────────
|
||||
# The login screen's "Support access" asks for a challenge, the builder answers with
|
||||
# tools/support_code.py <SITE_ID> <challenge>, and verify opens a 4 h support session
|
||||
# (synthetic superadmin). Works offline. Replaces the MASTER_USERNAME/PASSWORD account.
|
||||
|
||||
SUPPORT_CHALLENGE_TTL_MIN = 15
|
||||
SUPPORT_SESSION_HOURS = 4
|
||||
SUPPORT_MAX_ATTEMPTS = 5 # wrong codes per challenge
|
||||
SUPPORT_MAX_OPEN = 5 # unexpired, unused challenges at once
|
||||
|
||||
|
||||
class SupportVerifyRequest(_PydanticBase):
|
||||
challenge: str
|
||||
code: str
|
||||
|
||||
|
||||
def _support_configured() -> None:
|
||||
if not (settings.SUPPORT_SECRET and settings.SITE_ID):
|
||||
raise XeniaError("auth.support_not_configured")
|
||||
|
||||
|
||||
@router.post("/support/challenge", status_code=201, dependencies=[Depends(public())])
|
||||
def support_challenge(request: Request, db: Session = Depends(get_db)):
|
||||
"""A new challenge to read to the builder: {challenge: "ABCD-EFGH", site_id, expires_at}."""
|
||||
from datetime import timedelta
|
||||
from core import support_codes
|
||||
from core.timeutil import utcnow
|
||||
from models.support_challenge import SupportChallenge
|
||||
_support_configured()
|
||||
now = utcnow()
|
||||
open_now = db.query(SupportChallenge).filter(SupportChallenge.used_at.is_(None), SupportChallenge.expires_at > now,
|
||||
SupportChallenge.attempts < SUPPORT_MAX_ATTEMPTS).count()
|
||||
if open_now >= SUPPORT_MAX_OPEN:
|
||||
raise XeniaError("auth.support_rate_limited")
|
||||
while True:
|
||||
ch = support_codes.new_challenge()
|
||||
if not db.query(SupportChallenge).filter(SupportChallenge.challenge == ch).first():
|
||||
break
|
||||
row = SupportChallenge(challenge=ch, created_at=now, expires_at=now + timedelta(minutes=SUPPORT_CHALLENGE_TTL_MIN),
|
||||
ip=request.headers.get("x-real-ip") or (request.client.host if request.client else None),
|
||||
user_agent=request.headers.get("user-agent", "")[:300])
|
||||
db.add(row)
|
||||
db.commit()
|
||||
_logger.info("support.challenge id=%s", row.id)
|
||||
return {"challenge": support_codes.group(ch, 4), "site_id": settings.SITE_ID, "expires_at": iso_z(row.expires_at)}
|
||||
|
||||
|
||||
@router.post("/support/verify", response_model=TokenResponse, dependencies=[Depends(public())])
|
||||
def support_verify(body: SupportVerifyRequest, request: Request, db: Session = Depends(get_db)):
|
||||
"""The builder's code for a challenge -> a support session (4 h, single use per challenge)."""
|
||||
import hmac as _hmac
|
||||
from datetime import timedelta
|
||||
from core import support_codes
|
||||
from core.timeutil import utcnow
|
||||
from models.support_challenge import SupportChallenge
|
||||
_support_configured()
|
||||
now = utcnow()
|
||||
row = db.query(SupportChallenge).filter(
|
||||
SupportChallenge.challenge == support_codes.normalize_challenge(body.challenge)).first()
|
||||
if row is None or row.used_at is not None or row.expires_at <= now or row.attempts >= SUPPORT_MAX_ATTEMPTS:
|
||||
raise XeniaError("auth.support_code_invalid")
|
||||
expected = support_codes.code_for(settings.SUPPORT_SECRET, settings.SITE_ID, row.challenge)
|
||||
if not _hmac.compare_digest(expected, support_codes.normalize_code(body.code)):
|
||||
row.attempts += 1
|
||||
db.commit()
|
||||
_logger.warning("support.code_wrong challenge=%s attempts=%s", row.id, row.attempts)
|
||||
raise XeniaError("auth.support_code_invalid")
|
||||
support = make_support_user()
|
||||
session = sessions.start(db, support, "support", request, expires_at=now + timedelta(hours=SUPPORT_SESSION_HOURS))
|
||||
row.used_at = now
|
||||
row.session_id = session.id
|
||||
db.commit()
|
||||
_logger.warning("support.access_used challenge=%s sid=%s ip=%s", row.id, session.id[:8], session.ip)
|
||||
# >>> step 1.11: notify owners (support.access_used)
|
||||
return TokenResponse(access_token=make_token(support, session.id, hours=SUPPORT_SESSION_HOURS),
|
||||
user=UserOut.model_validate(support))
|
||||
|
||||
|
||||
# ── Sessions (D-9): who is logged in where ─────────────────────────────────
|
||||
|
||||
def _session_out(s, users: dict) -> dict:
|
||||
|
||||
@@ -17,15 +17,16 @@ bearer = HTTPBearer()
|
||||
TOKEN_EXPIRY_HOURS = 8
|
||||
|
||||
|
||||
MASTER_USER_ID = 0 # sentinel — never a real DB row
|
||||
SUPPORT_USER_ID = 0 # sentinel — never a real DB row
|
||||
|
||||
|
||||
def _make_ghost_superadmin():
|
||||
"""Synthetic in-memory superadmin — plain namespace, never touches SQLAlchemy."""
|
||||
def make_support_user():
|
||||
"""The support account (D-16): a synthetic superadmin, never a DB row. Its sessions have
|
||||
client="support" and user_id NULL; it only exists through POST /api/auth/support/verify."""
|
||||
from types import SimpleNamespace
|
||||
return SimpleNamespace(
|
||||
id=MASTER_USER_ID,
|
||||
username=settings.MASTER_USERNAME,
|
||||
id=SUPPORT_USER_ID,
|
||||
username="support",
|
||||
full_name="Xenia Support",
|
||||
role="superadmin",
|
||||
is_active=True,
|
||||
@@ -44,14 +45,14 @@ def _make_ghost_superadmin():
|
||||
)
|
||||
|
||||
|
||||
def make_token(user: User, sid: str) -> str:
|
||||
def make_token(user: User, sid: str, hours: float = TOKEN_EXPIRY_HOURS) -> str:
|
||||
"""JWT for an existing session row (core.sessions.start). `sid` is what makes it revocable."""
|
||||
payload = {
|
||||
"sub": str(user.id),
|
||||
"sid": sid,
|
||||
"username": user.username,
|
||||
"role": user.role,
|
||||
"exp": utcnow() + timedelta(hours=TOKEN_EXPIRY_HOURS),
|
||||
"exp": utcnow() + timedelta(hours=hours),
|
||||
}
|
||||
return jwt.encode(payload, settings.SECRET_KEY, algorithm="HS256")
|
||||
|
||||
@@ -87,9 +88,9 @@ def user_from_token(token: str, request: Request, db: Session):
|
||||
dev = current_device(request, db)
|
||||
if dev is None or dev.id != info.device_id:
|
||||
raise XeniaError("device.required")
|
||||
if int(payload["sub"]) == MASTER_USER_ID and payload.get("role") == "superadmin":
|
||||
if info.user_id is None: # only support sessions have no user (core/sessions.py)
|
||||
set_log_context(user="support")
|
||||
return _make_ghost_superadmin(), payload.get("sid")
|
||||
return make_support_user(), payload.get("sid")
|
||||
user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
||||
|
||||
Reference in New Issue
Block a user