"""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)