"""Single-admin auth tests: public read-only site, admin-only everything else. Driven in-process through ``httpx.ASGITransport`` exactly like the other API tests. No database is required: the few routes under test that would query Postgres are stubbed with a no-row fake session, so this file runs on a bare checkout. """ from __future__ import annotations import asyncio import time import httpx import pytest from conftest import ADMIN_TEST_PASSWORD, ADMIN_TEST_USER, admin_cookies import auth from main import app BASE = "http://test" NOUS_KEY_PATH = "/api/keys/NOUS_API_KEY" # ── Helpers ───────────────────────────────────────────────────────────────── class _FakeResult: def mappings(self): return self def all(self): return [] def scalar(self): return 0 def scalars(self): return self def unique(self): return self def one_or_none(self): return None def scalar_one_or_none(self): return None def __iter__(self): return iter(()) class _FakeSession: async def __aenter__(self): return self async def __aexit__(self, *exc): return False async def execute(self, *args, **kwargs): return _FakeResult() async def commit(self): return None def _fake_session(*args, **kwargs): return _FakeSession() @pytest.fixture() def no_db(monkeypatch): """Stub the DB session + key/settings stores so reads succeed offline.""" import main monkeypatch.setattr(main, "async_session", _fake_session) async def _empty_keys(): return [] async def _settings(): return {"summary_model": "Hermes-4.3-36B", "nous_base_url": "https://inference-api.nousresearch.com/v1"} async def _set_model(model: str): return {"summary_model": model, "nous_base_url": "https://inference-api.nousresearch.com/v1"} monkeypatch.setattr(main, "list_keys", _empty_keys) monkeypatch.setattr(main, "get_app_settings", _settings) monkeypatch.setattr(main, "set_summary_model", _set_model) def _request(method: str, path: str, *, cookies=None, json=None, headers=None, data=None) -> httpx.Response: async def _run() -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: if cookies: client.cookies.update(cookies) return await client.request( method, path, json=json, headers=headers, data=data, ) return asyncio.run(_run()) def _login(password: str = ADMIN_TEST_PASSWORD, username: str = ADMIN_TEST_USER, headers=None, form: bool = True) -> httpx.Response: if form: return _request( "POST", "/api/auth/login", data={"username": username, "password": password}, headers=headers, ) return _request( "POST", "/api/auth/login", json={"username": username, "password": password}, headers=headers, ) # ── Anonymous: public reads ───────────────────────────────────────────────── def test_anonymous_can_read_news(no_db): resp = _request("GET", "/api/news") assert resp.status_code == 200 assert resp.json() == [] def test_anonymous_can_read_public_allowlist(no_db): # Every documented public read must pass the gate (handler errors from the # stubbed DB are irrelevant here — 401/403/redirects are the failure modes). async def _run() -> dict[str, int]: # raise_app_exceptions=False: handler errors from the stubbed DB are # irrelevant here — 401/403/redirects are the failure modes. transport = httpx.ASGITransport(app=app, raise_app_exceptions=False) out: dict[str, int] = {} async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: for path in ( "/api/health", "/api/map/layers", "/api/map/chokepoints", "/api/news", "/api/news/ticker", "/api/news/map", "/api/news/blips", "/api/geofences", "/api/geofence-alerts", "/api/analytics/summary", "/api/tracks/range", "/api/fire-aircraft", ): out[path] = (await client.get(path)).status_code return out statuses = asyncio.run(_run()) for path, status in statuses.items(): assert status not in (401, 403, 307), f"{path} -> {status}" # DB-free reads answer for real. for path in ("/api/news", "/api/map/layers", "/api/map/chokepoints"): assert _request("GET", path).status_code == 200, path SPEC_PUBLIC_READS = ( "/api/health", "/api/ready", "/api/events", "/api/fires", "/api/sources", "/api/entities", "/api/alerts", "/api/documents", "/api/analytics/summary", "/api/analytics/timeline", "/api/analytics/sentiment/by-source", "/api/cameras", "/api/news", "/api/news/summaries", "/api/news/ticker", "/api/news/map", "/api/news/blips", "/api/map/layers", "/api/map/chokepoints", "/api/map/radar", "/api/map/sentinel1", "/api/aircraft", "/api/aircraft/photo", "/api/trains", "/api/vessels", "/api/tracks/range", "/api/geofences", "/api/geofence-alerts", "/api/fire-aircraft", "/api/events/11111111-1111-1111-1111-111111111111", "/api/entities/11111111-1111-1111-1111-111111111111", "/api/entities/11111111-1111-1111-1111-111111111111/events", "/api/cameras/abc", "/api/cameras/abc/snapshot", "/api/cameras/abc/stream", "/api/cameras/abc/hls.m3u8", "/api/cameras/abc/hlsseg", ) def test_public_allowlist_covers_the_spec(): for path in SPEC_PUBLIC_READS: assert auth.is_public(path, "GET"), path def test_public_post_search_is_read_only(no_db): resp = _request("POST", "/api/search", json={"q": "fire", "limit": 5}) assert resp.status_code not in (401, 403) def test_anonymous_can_load_hud(): resp = _request("GET", "/") assert resp.status_code == 200 assert "text/html" in resp.headers["content-type"] assert "OSINT" in resp.text assert 'id="view-map"' in resp.text def test_login_page_is_public(): resp = _request("GET", "/login") assert resp.status_code == 200 assert "Sign in" in resp.text assert resp.headers.get("cache-control") == "no-store" assert 'name="username"' in resp.text and 'name="password"' in resp.text assert "/api/auth/login" in resp.text def test_hud_gates_admin_chrome_client_side(): """Spec item 5: UX hiding is markup-driven and fails closed.""" html = _request("GET", "/").text # Fails closed without JS: data-admin is hidden unless body.is-admin. assert "body:not(.is-admin) [data-admin]" in html # Admin nav entries (API Keys is the headline requirement) are marked. for view in ("keys", "ingest", "settings"): assert f'data-view="{view}" data-admin' in html, view # Keys view, ingest view and the summarizer panel are gated too. assert 'id="view-keys" aria-label="API keys" data-admin' in html assert 'id="view-ingest" aria-label="Ingest" data-admin' in html # Discreet sign-in link + the /api/auth/me probe that reveals admin chrome. assert 'id="admin-link"' in html and 'href="/login"' in html assert "/api/auth/me" in html def test_static_assets_are_public(): assert _request("GET", "/static/index.html").status_code == 200 # ── Anonymous: admin surface is closed ────────────────────────────────────── def test_anonymous_keys_read_is_401(): resp = _request("GET", "/api/keys") assert resp.status_code == 401 assert resp.headers["content-type"].startswith("application/json") assert "detail" in resp.json() def test_anonymous_keys_write_is_401(): resp = _request("POST", NOUS_KEY_PATH, json={"value": "sk-nope-1234567890"}) assert resp.status_code == 401 def test_anonymous_keys_delete_is_401(): assert _request("DELETE", NOUS_KEY_PATH).status_code == 401 def test_anonymous_settings_write_is_401(): resp = _request("PUT", "/api/settings", json={"summary_model": "x/y-z"}) assert resp.status_code == 401 def test_anonymous_settings_read_is_401(): assert _request("GET", "/api/settings").status_code == 401 def test_anonymous_news_models_is_401(): # /api/news/models spends the stored Nous key — never public. assert _request("GET", "/api/news/models").status_code == 401 def test_anonymous_state_changing_routes_are_401(): cases = [ ("POST", "/api/sources", {"name": "x", "url": "https://example.com/feed", "source_type": "rss"}), ("POST", "/api/events", {"source_type": "rss", "title": "x"}), ("POST", "/api/entities", {"name": "x", "entity_type": "person"}), ("POST", "/api/alerts", {"alert_type": "keyword", "severity": "low", "title": "x"}), ("POST", "/api/geofences", {"name": "x", "geojson": {"type": "Point", "coordinates": [0, 0]}}), ("PATCH", "/api/geofences/abc", {"name": "y"}), ("DELETE", "/api/geofences/abc", None), ("POST", "/api/vessels/subscribe", {"bbox": "-70,40,-60,45"}), ("POST", "/api/ingest/rss", None), ("POST", "/api/ingest/earthquakes", None), ("POST", "/api/ingest/process", None), ] for method, path, body in cases: resp = _request(method, path, json=body) assert resp.status_code == 401, f"{method} {path} -> {resp.status_code}" def test_unknown_api_path_is_denied_anonymously(): assert _request("GET", "/api/does-not-exist").status_code == 401 # ── /api/auth/me ──────────────────────────────────────────────────────────── def test_auth_me_anonymous(): resp = _request("GET", "/api/auth/me") assert resp.status_code == 200 assert resp.json() == {"authenticated": False, "admin": False} def test_auth_me_with_session(): resp = _request("GET", "/api/auth/me", cookies=admin_cookies()) assert resp.status_code == 200 assert resp.json() == {"authenticated": True, "admin": True} # ── Login / logout ────────────────────────────────────────────────────────── def test_login_wrong_password_is_401(): resp = _login(password="wrong-password") assert resp.status_code == 401 assert "invalid credentials" in resp.json()["detail"] assert auth.COOKIE_NAME not in resp.cookies def test_login_wrong_username_is_401(): resp = _login(username="root") assert resp.status_code == 401 # Generic message: never reveal which half was wrong / that the user exists. assert "root" not in resp.text def test_login_missing_fields_is_401_not_500(): resp = _request("POST", "/api/auth/login", data={}) assert resp.status_code == 401 def test_login_success_sets_httponly_cookie(monkeypatch): monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False) resp = _login() assert resp.status_code == 200 assert resp.json() == {"authenticated": True, "admin": True} raw = resp.headers.get("set-cookie", "") assert auth.COOKIE_NAME in raw assert "HttpOnly" in raw assert "SameSite=lax" in raw.replace("samesite=lax", "SameSite=lax") assert "Path=/" in raw assert "Secure" not in raw # plain http in tests assert resp.cookies.get(auth.COOKIE_NAME) def test_login_accepts_json_body(): resp = _login(form=False) assert resp.status_code == 200 assert resp.json()["authenticated"] is True def test_login_cookie_marks_secure_behind_https_proxy(monkeypatch): monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False) resp = _login(headers={"X-Forwarded-Proto": "https"}) assert resp.status_code == 200 assert "Secure" in resp.headers.get("set-cookie", "") def test_login_cookie_secure_via_env_flag_over_http_origin(monkeypatch): """ADMIN_COOKIE_SECURE is what makes the cookie Secure in the cluster: the header arrives as ``http`` from the Cilium Gateway.""" monkeypatch.setenv("ADMIN_COOKIE_SECURE", "1") resp = _login(headers={"X-Forwarded-Proto": "http"}) assert resp.status_code == 200 raw = resp.headers.get("set-cookie", "") assert "Secure" in raw assert "SameSite=lax" in raw.replace("samesite=lax", "SameSite=lax") assert "HttpOnly" in raw @pytest.mark.parametrize("value", ["true", "TRUE", " Yes ", "yes"]) def test_login_cookie_env_flag_accepts_truthy_spellings(monkeypatch, value): monkeypatch.setenv("ADMIN_COOKIE_SECURE", value) resp = _login() assert resp.status_code == 200 assert "Secure" in resp.headers.get("set-cookie", "") @pytest.mark.parametrize("value", ["", "0", "false", "no", "off"]) def test_login_cookie_env_flag_ignores_falsey_spellings(monkeypatch, value): monkeypatch.setenv("ADMIN_COOKIE_SECURE", value) resp = _login(headers={"X-Forwarded-Proto": "http"}) assert resp.status_code == 200 assert "Secure" not in resp.headers.get("set-cookie", "") def test_login_cookie_without_header_or_flag_is_not_secure_locally(monkeypatch): monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False) resp = _login() assert resp.status_code == 200 assert "Secure" not in resp.headers.get("set-cookie", "") def test_session_cookie_unlocks_admin_routes(no_db): login = _login() cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)} assert _request("GET", "/api/keys", cookies=cookie).status_code == 200 assert _request("PUT", "/api/settings", json={"summary_model": "m"}, cookies=cookie).status_code == 200 assert _request("GET", "/api/settings", cookies=cookie).status_code == 200 def test_logout_clears_session(no_db): login = _login() cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)} out = _request("POST", "/api/auth/logout", cookies=cookie) assert out.status_code == 200 assert out.json() == {"authenticated": False, "admin": False} assert "Max-Age=0" in out.headers.get("set-cookie", "") or "expires" in \ out.headers.get("set-cookie", "").lower() # A cleared cookie no longer authenticates (simulate the browser dropping it). assert _request("GET", "/api/keys", cookies={}).status_code == 401 def test_tampered_cookie_is_401(): login = _login() token = login.cookies.get(auth.COOKIE_NAME) body, signature = token.rsplit(".", 1) tampered = f"{body}.{'A' * len(signature)}" assert _request("GET", "/api/keys", cookies={auth.COOKIE_NAME: tampered}).status_code == 401 def test_cookie_for_another_user_is_401(monkeypatch): forged = auth.create_session_token("intruder") assert _request("GET", "/api/keys", cookies={auth.COOKIE_NAME: forged}).status_code == 401 def test_expired_token_is_rejected(): token = auth.create_session_token(ADMIN_TEST_USER, now=time.time() - auth.SESSION_TTL_SECONDS - 5) assert auth.verify_session_token(token) is None # ── Fail closed ───────────────────────────────────────────────────────────── def test_admin_env_unset_fails_closed(monkeypatch, no_db): monkeypatch.delenv("ADMIN_PASSWORD_HASH", raising=False) monkeypatch.delenv("ADMIN_SESSION_SECRET", raising=False) resp = _request("GET", "/api/keys") assert resp.status_code == 403 assert resp.json() == {"detail": "admin auth not configured"} # Public site keeps working, and /login explains the situation. assert _request("GET", "/api/news").status_code == 200 page = _request("GET", "/login") assert page.status_code == 200 assert "not configured" in page.text def test_login_without_password_hash_is_403(monkeypatch): monkeypatch.delenv("ADMIN_PASSWORD_HASH", raising=False) resp = _login() assert resp.status_code == 403 assert resp.json() == {"detail": "admin auth not configured"} def test_session_secret_unset_invalidates_existing_cookie(monkeypatch): cookie = admin_cookies() monkeypatch.delenv("ADMIN_SESSION_SECRET", raising=False) resp = _request("GET", "/api/keys", cookies=cookie) assert resp.status_code == 403 assert resp.json() == {"detail": "admin auth not configured"} # ── Rate limiting ─────────────────────────────────────────────────────────── def test_rate_limit_after_five_failures(): for attempt in range(5): assert _login(password="nope").status_code == 401, f"attempt {attempt}" assert _login(password="nope").status_code == 429 # Correct credentials are refused too while the window is open. assert _login().status_code == 429 def test_rate_limit_is_per_client_ip(): for _ in range(5): _login(password="nope", headers={"X-Forwarded-For": "203.0.113.9"}) assert _login(password="nope", headers={"X-Forwarded-For": "203.0.113.9"}).status_code == 429 # A different client is unaffected. assert _login(password="nope", headers={"X-Forwarded-For": "203.0.113.10"}).status_code == 401 def test_logout_does_not_reset_the_login_limiter(): """Regression: logout is unauthenticated — it must not clear lockouts.""" for _ in range(5): assert _login(password="nope").status_code == 401 assert _request("POST", "/api/auth/logout").status_code == 200 assert _login().status_code == 429 def test_non_ascii_garbage_cookie_is_rejected_not_500(): assert auth.verify_session_token("abc.\u00e9\u00e9\u00e9") is None assert auth.verify_session_token("\u00e9\u00e9\u00e9") is None resp = _request("GET", "/api/keys", cookies={auth.COOKIE_NAME: "garbage"}) assert resp.status_code == 401 # ── CSRF ──────────────────────────────────────────────────────────────────── def test_cross_origin_admin_write_is_403(no_db): cookies = admin_cookies() resp = _request("PUT", "/api/settings", json={"summary_model": "m"}, cookies=cookies, headers={"Origin": "https://evil.example"}) assert resp.status_code == 403 assert "cross-origin" in resp.json()["detail"] def test_same_origin_admin_write_is_allowed(no_db): cookies = admin_cookies() resp = _request("PUT", "/api/settings", json={"summary_model": "m"}, cookies=cookies, headers={"Origin": BASE}) assert resp.status_code == 200 def test_same_host_referer_admin_write_is_allowed(no_db): cookies = admin_cookies() resp = _request("PUT", "/api/settings", json={"summary_model": "m"}, cookies=cookies, headers={"Referer": f"{BASE}/login"}) assert resp.status_code == 200 # ── Unit: hashing + token helpers ─────────────────────────────────────────── def test_password_hash_round_trip(): stored = auth.hash_password("s3cret-pw", iterations=2000) assert stored.startswith("pbkdf2_sha256$") assert auth.verify_password("s3cret-pw", stored) assert not auth.verify_password("s3cret-pW", stored) assert not auth.verify_password("", stored) def test_password_hash_rejects_malformed_values(): for bad in ("", "plain", "pbkdf2_sha256$abc$x$y", "md5$1$a$b", "pbkdf2_sha256$0$AAAA$AAAA"): assert not auth.verify_password("x", bad) def test_session_token_round_trip(): token = auth.create_session_token(ADMIN_TEST_USER) assert auth.verify_session_token(token) == ADMIN_TEST_USER assert auth.verify_session_token(token + "x") is None assert auth.verify_session_token(None) is None def test_public_allowlist_classification(): assert auth.is_public("/api/news", "GET") assert auth.is_public("/api/news/", "GET") assert auth.is_public("/api/events/abc-123", "GET") assert auth.is_public("/api/cameras/abc/hls.m3u8", "GET") assert auth.is_public("/api/search", "POST") assert not auth.is_public("/api/news/models", "GET") assert not auth.is_public("/api/keys", "GET") assert not auth.is_public("/api/settings", "GET") assert not auth.is_public("/api/ingest/rss", "POST") assert not auth.is_public("/api/vessels/subscribe", "POST") assert not auth.is_public("/api/geofences", "POST") assert auth.is_public("/ws/live", "GET")