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:
2026-11-13 10:52:16 +02:00
co-authored by Claude Opus 5.5
parent 650fee7873
commit 3a522e457d
23 changed files with 517 additions and 52 deletions
+3 -3
View File
@@ -26,9 +26,9 @@ class Settings(BaseSettings):
# machines and test suites (docker-compose.dev.yml, tests/e2e). Never on a site.
LICENSE_MODE: str = "enforced"
# Break-glass master account — lives only in env vars, never in the DB
MASTER_USERNAME: str = ""
MASTER_PASSWORD: str = ""
# Support access (APPS_PLATFORM D-16): this site's secret, made by the builder with
# tools/support_code.py --site-secret <SITE_ID>. Empty = no support access.
SUPPORT_SECRET: str = ""
model_config = {"env_file": str(_HERE / ".env"), "env_file_encoding": "utf-8"}
+1 -1
View File
@@ -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
+3
View File
@@ -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})."),
+9 -5
View File
@@ -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:
+55
View File
@@ -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))
@@ -0,0 +1,51 @@
"""support_challenges + sessions.expires_at (support access)
Revision ID: 0009_support_access
Revises: 0008_access_overrides
Create Date: 2026-11-13 10:47:20.516800
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0009_support_access'
down_revision = '0008_access_overrides'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('support_challenges',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('challenge', sa.String(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('expires_at', UTCDateTime(), nullable=False),
sa.Column('attempts', sa.Integer(), nullable=False),
sa.Column('used_at', UTCDateTime(), nullable=True),
sa.Column('session_id', sa.String(), nullable=True),
sa.Column('ip', sa.String(), nullable=True),
sa.Column('user_agent', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('challenge'),
sqlite_autoincrement=True
)
with op.batch_alter_table('support_challenges', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_support_challenges_expires_at'), ['expires_at'], unique=False)
with op.batch_alter_table('sessions', schema=None) as batch_op:
batch_op.add_column(sa.Column('expires_at', UTCDateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('sessions', schema=None) as batch_op:
batch_op.drop_column('expires_at')
with op.batch_alter_table('support_challenges', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_support_challenges_expires_at'))
op.drop_table('support_challenges')
# ### end Alembic commands ###
+1
View File
@@ -32,3 +32,4 @@ import models.user_permission # noqa: F401 UserPermission (permission keys, st
import models.session # noqa: F401 LoginSession (step 1.6)
import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
import models.access_override # noqa: F401 AccessOverride (manager override, step 1.9)
import models.support_challenge # noqa: F401 SupportChallenge (support access, step 1.10)
+2 -1
View File
@@ -22,6 +22,7 @@ class LoginSession(Base):
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
last_seen_at = Column(UTCDateTime, nullable=False, default=utcnow)
ended_at = Column(UTCDateTime, nullable=True, index=True)
end_reason = Column(String, nullable=True) # logout | replaced | ended_by_manager | user_blocked | refreshed | device_revoked | device_reassigned
expires_at = Column(UTCDateTime, nullable=True) # hard end (support sessions: 4 h); NULL = none
end_reason = Column(String, nullable=True) # logout | replaced | ended_by_manager | user_blocked | refreshed | device_revoked | device_reassigned | expired
ip = Column(String, nullable=True)
user_agent = Column(String, nullable=True)
+26
View File
@@ -0,0 +1,26 @@
"""Support access challenges (APPS_PLATFORM D-16, §6.5, plan step 1.10).
One row per challenge shown on a login screen ("Support access"). It is valid for 15 min,
once, with a few wrong tries. A used row is the audit record of a support login: when,
from where and which session it opened. Rows are never deleted.
Written through routers/auth.py (support endpoints) only.
"""
from sqlalchemy import Column, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class SupportChallenge(Base):
__tablename__ = "support_challenges"
__table_args__ = {"sqlite_autoincrement": True}
id = Column(Integer, primary_key=True, autoincrement=True)
challenge = Column(String, nullable=False, unique=True) # normalized, 8 chars
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
expires_at = Column(UTCDateTime, nullable=False, index=True)
attempts = Column(Integer, nullable=False, default=0) # wrong codes entered
used_at = Column(UTCDateTime, nullable=True)
session_id = Column(String, nullable=True) # the support session it opened
ip = Column(String, nullable=True)
user_agent = Column(String, nullable=True)
+79 -9
View File
@@ -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:
+10 -9
View File
@@ -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")
+1 -2
View File
@@ -37,8 +37,7 @@ _TMP = Path(tempfile.mkdtemp(prefix="xenia-tests-"))
os.environ["DATABASE_URL"] = f"sqlite:///{(_TMP / 'test.db').as_posix()}"
os.environ["LOG_DIR"] = str(_TMP / "logs")
os.environ["TLS_DIR"] = str(_TMP / "tls")
os.environ.setdefault("MASTER_USERNAME", "")
os.environ.setdefault("MASTER_PASSWORD", "")
os.environ.setdefault("SUPPORT_SECRET", "")
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+133
View File
@@ -0,0 +1,133 @@
"""Support access (plan step 1.10, APPS_PLATFORM D-16, §6.5)."""
import subprocess
import sys
from datetime import timedelta
from pathlib import Path
import pytest
from core import support_codes as C
MASTER = "test-master-key-0123456789abcdef"
TOOL = Path(__file__).resolve().parents[2] / "tools" / "support_code.py"
def err(r):
return r.json()["error"]["code"]
@pytest.fixture
def site(monkeypatch):
from config import settings
monkeypatch.setattr(settings, "SITE_ID", "site-A")
monkeypatch.setattr(settings, "SUPPORT_SECRET", C.site_secret(MASTER, "site-A"))
return settings
def challenge(client):
r = client.post("/api/auth/support/challenge")
assert r.status_code == 201, r.text
return r.json()["challenge"]
def verify(client, ch, code):
return client.post("/api/auth/support/verify", json={"challenge": ch, "code": code})
# ── the derivation ───────────────────────────────────────────────────────────
def test_known_vector(): # pins the algorithm; tests/e2e/lib (JS) must give the same values
secret = C.site_secret(MASTER, "site-A")
assert secret == "058ec8ca09a653f82d1d4f546fbb2c03ababe6d6830079c75a564675ceb6fcfe"
assert C.code_for(secret, "site-A", "ABCD-EFGH") == "E4MYPVWT3M"
assert C.code_for(secret, "site-A", "abcd efgh") == "E4MYPVWT3M" # challenge typed loosely
assert C.normalize_code("e4myp-vwt3m") == "E4MYPVWT3M"
def test_tool_round_trip(client, site, tmp_path): # "done when": a code made by the tool works, once
key = tmp_path / "master.txt"
env = {"XENIA_SUPPORT_MASTER_KEY_FILE": str(key), "SYSTEMROOT": "C:\\Windows", "PATH": ""}
def tool(*args):
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, text=True, env=env, check=True).stdout.strip()
assert "Created" in tool("--init")
assert "already exists" in tool("--init") # never overwrites
site.SUPPORT_SECRET = tool("--site-secret", "site-A")
ch = challenge(client)
code = tool("site-A", ch)
assert len(code) == 11 and code[5] == "-"
r = verify(client, ch, code)
assert r.status_code == 200, r.text
h = {"Authorization": f"Bearer {r.json()['access_token']}"}
me = client.get("/api/auth/me", headers=h).json()
assert me["role"] == "superadmin" and me["username"] == "support"
assert client.get("/api/settings/", headers=h).status_code == 200 # full access
# single use
assert err(verify(client, ch, code)) == "auth.support_code_invalid"
def test_code_for_another_site_is_refused(client, site):
ch = challenge(client)
other = C.code_for(C.site_secret(MASTER, "site-B"), "site-B", ch)
assert err(verify(client, ch, other)) == "auth.support_code_invalid"
# a different master key doesn't work either
assert err(verify(client, ch, C.code_for(C.site_secret("x" * 32, "site-A"), "site-A", ch))) == "auth.support_code_invalid"
def test_wrong_codes_burn_the_challenge(client, site):
from routers.auth import SUPPORT_MAX_ATTEMPTS
ch = challenge(client)
for _ in range(SUPPORT_MAX_ATTEMPTS):
assert err(verify(client, ch, "AAAAA-AAAAA")) == "auth.support_code_invalid"
right = C.code_for(site.SUPPORT_SECRET, "site-A", ch)
assert err(verify(client, ch, right)) == "auth.support_code_invalid"
def test_challenge_expires(client, db, site):
from models.support_challenge import SupportChallenge
ch = challenge(client)
row = db.query(SupportChallenge).filter(SupportChallenge.challenge == C.normalize_challenge(ch)).one()
row.expires_at = row.created_at - timedelta(seconds=1)
db.commit()
assert err(verify(client, ch, C.code_for(site.SUPPORT_SECRET, "site-A", ch))) == "auth.support_code_invalid"
def test_support_session_has_a_hard_end(client, db, site):
from core import sessions
from models.session import LoginSession
from models.support_challenge import SupportChallenge
ch = challenge(client)
r = verify(client, ch, C.code_for(site.SUPPORT_SECRET, "site-A", ch))
h = {"Authorization": f"Bearer {r.json()['access_token']}"}
audit = db.query(SupportChallenge).filter(SupportChallenge.challenge == C.normalize_challenge(ch)).one()
s = db.get(LoginSession, audit.session_id)
assert s.client == "support" and s.user_id is None
assert timedelta(hours=3, minutes=59) < s.expires_at - s.created_at <= timedelta(hours=4)
s.expires_at = s.created_at
db.commit()
sessions.clear_cache()
assert err(client.get("/api/auth/me", headers=h)) == "auth.session_ended"
db.refresh(s)
assert s.end_reason == "expired"
def test_open_challenges_are_capped(client, site):
from routers.auth import SUPPORT_MAX_OPEN
for _ in range(SUPPORT_MAX_OPEN):
challenge(client)
r = client.post("/api/auth/support/challenge")
assert r.status_code == 429 and err(r) == "auth.support_rate_limited"
def test_not_configured(client, monkeypatch):
from config import settings
monkeypatch.setattr(settings, "SUPPORT_SECRET", "")
r = client.post("/api/auth/support/challenge")
assert r.status_code == 503 and err(r) == "auth.support_not_configured"
def test_master_account_is_gone(): # "done when": the env vars are gone
from config import Settings
assert not {"MASTER_USERNAME", "MASTER_PASSWORD"} & set(Settings.model_fields)