"""P2.2: /admin/v2 отдаёт оболочку, strict CSP; API v2 — admin only; legacy CSP не сломан.""" import importlib import os import sys import pytest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if ROOT not in sys.path: sys.path.insert(0, ROOT) @pytest.fixture() def env(tmp_path, monkeypatch): monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db")) monkeypatch.setenv("SESSION_SECRET", "test-secret") monkeypatch.setenv("AI_BACKEND", "claude") monkeypatch.chdir(ROOT) import auth import db import main for m in (db, auth, main): importlib.reload(m) db.init_db() db.create_user("boss@x", auth.hash_password("Passw0rd!ok"), role="admin") db.admin_verify_user("boss@x") db.create_user("joe@x", auth.hash_password("Passw0rd!ok")) db.admin_verify_user("joe@x") from fastapi.testclient import TestClient return TestClient(main.app), auth def test_v2_page_deep_link_and_strict_csp(env): client, auth = env for path in ("/admin/v2", "/admin/v2/customers", "/admin/v2/money"): r = client.get(path) assert r.status_code == 200, path assert 'id="app"' in r.text csp = r.headers["Content-Security-Policy"] assert "unsafe-inline" not in csp, csp assert "script-src 'self'" in csp def test_legacy_csp_still_works(env): client, auth = env r = client.get("/admin") assert r.status_code == 200 assert "unsafe-inline" in r.headers["Content-Security-Policy"] def test_audit_action_keeps_v2_subpath(env): client, auth = env import main assert main._resolve_action("GET", "/api/admin/v2/ping") == "admin.v2.ping" def test_v2_api_is_admin_only(env): client, auth = env h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")} r = client.get("/api/admin/v2/ping", headers=h) assert r.status_code == 200 assert r.json()["user"] == "boss@x" user = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")} assert client.get("/api/admin/v2/ping", headers=user).status_code == 403 assert client.get("/api/admin/v2/ping").status_code in (401, 403)