feat(auth): public read-only HUD, admin-only API keys and mutations
Adds single-admin authentication to the dashboard. Anonymous visitors get a
read-only site (map + news); the one admin unlocks everything else.
- app/auth.py: deny-by-default ASGI middleware on /api/* with an explicit
public read allowlist; /login page; /api/auth/{login,logout,me}; PBKDF2
password hashing; HMAC-signed HttpOnly SameSite=Lax session cookie (7d,
Secure behind X-Forwarded-Proto: https); 5-fail/15-min per-IP login limit;
Origin/Referer host check on state-changing admin requests.
- Fails closed: missing ADMIN_PASSWORD_HASH or ADMIN_SESSION_SECRET -> admin
routes 403 'admin auth not configured', public site unaffected.
- app/main.py: mounts the middleware + router (6 lines, no per-route decorators).
- app/static/index.html: hides Ingest/API Keys/Settings, the summarizer panel
and geofence write controls until /api/auth/me says admin; adds a discreet
SIGN IN link to /login. CSS gates fail closed without JS.
- tests/test_auth.py: 42 tests (anonymous 401s, login/logout, tampered and
expired cookies, fail-closed, rate limit, CSRF, HUD markup).
- Existing API tests now send an admin session cookie for admin routes.
Public allowlist extends the spec's list with the remaining read-only GETs the
HUD calls (/api/stats, /api/conflicts, /api/place, /api/satellites,
/api/infrastructure, /api/map/gpsjam, /api/map/times, /api/fire-incidents,
/api/fire-perimeters, /api/weather-alerts, /api/storms, /api/geofences/{id}/at)
so an anonymous HUD is not half-broken.
2026-11-13 20:56:07 -05:00
|
|
|
"""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
|
fix(openapi): declare the admin session cookie on every guarded operation
/openapi.json is served to the internet and declared no securitySchemes at
all, so every one of the 22 mutating operations read as unauthenticated while
the middleware answers 401 on them. The enforcement lives in
AdminAuthMiddleware, not in a route dependency, so FastAPI had nothing to
infer a scheme from.
The spec is now stamped from auth.is_public() — the same allowlist the
middleware enforces — instead of a hand-maintained per-route list:
- components.securitySchemes.adminSession: apiKey in cookie, name
osint_session (the cookie the middleware actually reads), with the 401/403
behaviour documented.
- protected operations: security: [{"adminSession": []}] — 19 of the 22
mutating operations plus GET /api/keys, GET /api/settings, /api/news/models.
- public operations: security: [] (explicit "no auth"; not omitted).
POST /api/search, POST /api/auth/login and POST /api/auth/logout stay
public, and the read-only HUD surface is untouched.
Tests pin the pair per documented operation: the real app must answer 401 on
every operation that declares security, and the middleware must admit every
operation that declares []. Verified red on the untouched base (9 failures)
and green after the change.
2026-11-27 00:26:31 -05:00
|
|
|
import re
|
feat(auth): public read-only HUD, admin-only API keys and mutations
Adds single-admin authentication to the dashboard. Anonymous visitors get a
read-only site (map + news); the one admin unlocks everything else.
- app/auth.py: deny-by-default ASGI middleware on /api/* with an explicit
public read allowlist; /login page; /api/auth/{login,logout,me}; PBKDF2
password hashing; HMAC-signed HttpOnly SameSite=Lax session cookie (7d,
Secure behind X-Forwarded-Proto: https); 5-fail/15-min per-IP login limit;
Origin/Referer host check on state-changing admin requests.
- Fails closed: missing ADMIN_PASSWORD_HASH or ADMIN_SESSION_SECRET -> admin
routes 403 'admin auth not configured', public site unaffected.
- app/main.py: mounts the middleware + router (6 lines, no per-route decorators).
- app/static/index.html: hides Ingest/API Keys/Settings, the summarizer panel
and geofence write controls until /api/auth/me says admin; adds a discreet
SIGN IN link to /login. CSS gates fail closed without JS.
- tests/test_auth.py: 42 tests (anonymous 401s, login/logout, tampered and
expired cookies, fail-closed, rate limit, CSRF, HUD markup).
- Existing API tests now send an admin session cookie for admin routes.
Public allowlist extends the spec's list with the remaining read-only GETs the
HUD calls (/api/stats, /api/conflicts, /api/place, /api/satellites,
/api/infrastructure, /api/map/gpsjam, /api/map/times, /api/fire-incidents,
/api/fire-perimeters, /api/weather-alerts, /api/storms, /api/geofences/{id}/at)
so an anonymous HUD is not half-broken.
2026-11-13 20:56:07 -05:00
|
|
|
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",
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
"/api/news/blips",
|
feat(auth): public read-only HUD, admin-only API keys and mutations
Adds single-admin authentication to the dashboard. Anonymous visitors get a
read-only site (map + news); the one admin unlocks everything else.
- app/auth.py: deny-by-default ASGI middleware on /api/* with an explicit
public read allowlist; /login page; /api/auth/{login,logout,me}; PBKDF2
password hashing; HMAC-signed HttpOnly SameSite=Lax session cookie (7d,
Secure behind X-Forwarded-Proto: https); 5-fail/15-min per-IP login limit;
Origin/Referer host check on state-changing admin requests.
- Fails closed: missing ADMIN_PASSWORD_HASH or ADMIN_SESSION_SECRET -> admin
routes 403 'admin auth not configured', public site unaffected.
- app/main.py: mounts the middleware + router (6 lines, no per-route decorators).
- app/static/index.html: hides Ingest/API Keys/Settings, the summarizer panel
and geofence write controls until /api/auth/me says admin; adds a discreet
SIGN IN link to /login. CSS gates fail closed without JS.
- tests/test_auth.py: 42 tests (anonymous 401s, login/logout, tampered and
expired cookies, fail-closed, rate limit, CSRF, HUD markup).
- Existing API tests now send an admin session cookie for admin routes.
Public allowlist extends the spec's list with the remaining read-only GETs the
HUD calls (/api/stats, /api/conflicts, /api/place, /api/satellites,
/api/infrastructure, /api/map/gpsjam, /api/map/times, /api/fire-incidents,
/api/fire-perimeters, /api/weather-alerts, /api/storms, /api/geofences/{id}/at)
so an anonymous HUD is not half-broken.
2026-11-13 20:56:07 -05:00
|
|
|
"/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",
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
"/api/news/blips",
|
feat(auth): public read-only HUD, admin-only API keys and mutations
Adds single-admin authentication to the dashboard. Anonymous visitors get a
read-only site (map + news); the one admin unlocks everything else.
- app/auth.py: deny-by-default ASGI middleware on /api/* with an explicit
public read allowlist; /login page; /api/auth/{login,logout,me}; PBKDF2
password hashing; HMAC-signed HttpOnly SameSite=Lax session cookie (7d,
Secure behind X-Forwarded-Proto: https); 5-fail/15-min per-IP login limit;
Origin/Referer host check on state-changing admin requests.
- Fails closed: missing ADMIN_PASSWORD_HASH or ADMIN_SESSION_SECRET -> admin
routes 403 'admin auth not configured', public site unaffected.
- app/main.py: mounts the middleware + router (6 lines, no per-route decorators).
- app/static/index.html: hides Ingest/API Keys/Settings, the summarizer panel
and geofence write controls until /api/auth/me says admin; adds a discreet
SIGN IN link to /login. CSS gates fail closed without JS.
- tests/test_auth.py: 42 tests (anonymous 401s, login/logout, tampered and
expired cookies, fail-closed, rate limit, CSRF, HUD markup).
- Existing API tests now send an admin session cookie for admin routes.
Public allowlist extends the spec's list with the remaining read-only GETs the
HUD calls (/api/stats, /api/conflicts, /api/place, /api/satellites,
/api/infrastructure, /api/map/gpsjam, /api/map/times, /api/fire-incidents,
/api/fire-perimeters, /api/weather-alerts, /api/storms, /api/geofences/{id}/at)
so an anonymous HUD is not half-broken.
2026-11-13 20:56:07 -05:00
|
|
|
"/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
|
|
|
|
|
|
|
|
|
|
|
2026-11-13 21:15:05 -05:00
|
|
|
def test_login_success_sets_httponly_cookie(monkeypatch):
|
|
|
|
|
monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False)
|
feat(auth): public read-only HUD, admin-only API keys and mutations
Adds single-admin authentication to the dashboard. Anonymous visitors get a
read-only site (map + news); the one admin unlocks everything else.
- app/auth.py: deny-by-default ASGI middleware on /api/* with an explicit
public read allowlist; /login page; /api/auth/{login,logout,me}; PBKDF2
password hashing; HMAC-signed HttpOnly SameSite=Lax session cookie (7d,
Secure behind X-Forwarded-Proto: https); 5-fail/15-min per-IP login limit;
Origin/Referer host check on state-changing admin requests.
- Fails closed: missing ADMIN_PASSWORD_HASH or ADMIN_SESSION_SECRET -> admin
routes 403 'admin auth not configured', public site unaffected.
- app/main.py: mounts the middleware + router (6 lines, no per-route decorators).
- app/static/index.html: hides Ingest/API Keys/Settings, the summarizer panel
and geofence write controls until /api/auth/me says admin; adds a discreet
SIGN IN link to /login. CSS gates fail closed without JS.
- tests/test_auth.py: 42 tests (anonymous 401s, login/logout, tampered and
expired cookies, fail-closed, rate limit, CSRF, HUD markup).
- Existing API tests now send an admin session cookie for admin routes.
Public allowlist extends the spec's list with the remaining read-only GETs the
HUD calls (/api/stats, /api/conflicts, /api/place, /api/satellites,
/api/infrastructure, /api/map/gpsjam, /api/map/times, /api/fire-incidents,
/api/fire-perimeters, /api/weather-alerts, /api/storms, /api/geofences/{id}/at)
so an anonymous HUD is not half-broken.
2026-11-13 20:56:07 -05:00
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
2026-11-13 21:15:05 -05:00
|
|
|
def test_login_cookie_marks_secure_behind_https_proxy(monkeypatch):
|
|
|
|
|
monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False)
|
feat(auth): public read-only HUD, admin-only API keys and mutations
Adds single-admin authentication to the dashboard. Anonymous visitors get a
read-only site (map + news); the one admin unlocks everything else.
- app/auth.py: deny-by-default ASGI middleware on /api/* with an explicit
public read allowlist; /login page; /api/auth/{login,logout,me}; PBKDF2
password hashing; HMAC-signed HttpOnly SameSite=Lax session cookie (7d,
Secure behind X-Forwarded-Proto: https); 5-fail/15-min per-IP login limit;
Origin/Referer host check on state-changing admin requests.
- Fails closed: missing ADMIN_PASSWORD_HASH or ADMIN_SESSION_SECRET -> admin
routes 403 'admin auth not configured', public site unaffected.
- app/main.py: mounts the middleware + router (6 lines, no per-route decorators).
- app/static/index.html: hides Ingest/API Keys/Settings, the summarizer panel
and geofence write controls until /api/auth/me says admin; adds a discreet
SIGN IN link to /login. CSS gates fail closed without JS.
- tests/test_auth.py: 42 tests (anonymous 401s, login/logout, tampered and
expired cookies, fail-closed, rate limit, CSRF, HUD markup).
- Existing API tests now send an admin session cookie for admin routes.
Public allowlist extends the spec's list with the remaining read-only GETs the
HUD calls (/api/stats, /api/conflicts, /api/place, /api/satellites,
/api/infrastructure, /api/map/gpsjam, /api/map/times, /api/fire-incidents,
/api/fire-perimeters, /api/weather-alerts, /api/storms, /api/geofences/{id}/at)
so an anonymous HUD is not half-broken.
2026-11-13 20:56:07 -05:00
|
|
|
resp = _login(headers={"X-Forwarded-Proto": "https"})
|
|
|
|
|
assert resp.status_code == 200
|
|
|
|
|
assert "Secure" in resp.headers.get("set-cookie", "")
|
|
|
|
|
|
|
|
|
|
|
2026-11-13 21:15:05 -05:00
|
|
|
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", "")
|
|
|
|
|
|
|
|
|
|
|
feat(auth): public read-only HUD, admin-only API keys and mutations
Adds single-admin authentication to the dashboard. Anonymous visitors get a
read-only site (map + news); the one admin unlocks everything else.
- app/auth.py: deny-by-default ASGI middleware on /api/* with an explicit
public read allowlist; /login page; /api/auth/{login,logout,me}; PBKDF2
password hashing; HMAC-signed HttpOnly SameSite=Lax session cookie (7d,
Secure behind X-Forwarded-Proto: https); 5-fail/15-min per-IP login limit;
Origin/Referer host check on state-changing admin requests.
- Fails closed: missing ADMIN_PASSWORD_HASH or ADMIN_SESSION_SECRET -> admin
routes 403 'admin auth not configured', public site unaffected.
- app/main.py: mounts the middleware + router (6 lines, no per-route decorators).
- app/static/index.html: hides Ingest/API Keys/Settings, the summarizer panel
and geofence write controls until /api/auth/me says admin; adds a discreet
SIGN IN link to /login. CSS gates fail closed without JS.
- tests/test_auth.py: 42 tests (anonymous 401s, login/logout, tampered and
expired cookies, fail-closed, rate limit, CSRF, HUD markup).
- Existing API tests now send an admin session cookie for admin routes.
Public allowlist extends the spec's list with the remaining read-only GETs the
HUD calls (/api/stats, /api/conflicts, /api/place, /api/satellites,
/api/infrastructure, /api/map/gpsjam, /api/map/times, /api/fire-incidents,
/api/fire-perimeters, /api/weather-alerts, /api/storms, /api/geofences/{id}/at)
so an anonymous HUD is not half-broken.
2026-11-13 20:56:07 -05:00
|
|
|
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")
|
fix(openapi): declare the admin session cookie on every guarded operation
/openapi.json is served to the internet and declared no securitySchemes at
all, so every one of the 22 mutating operations read as unauthenticated while
the middleware answers 401 on them. The enforcement lives in
AdminAuthMiddleware, not in a route dependency, so FastAPI had nothing to
infer a scheme from.
The spec is now stamped from auth.is_public() — the same allowlist the
middleware enforces — instead of a hand-maintained per-route list:
- components.securitySchemes.adminSession: apiKey in cookie, name
osint_session (the cookie the middleware actually reads), with the 401/403
behaviour documented.
- protected operations: security: [{"adminSession": []}] — 19 of the 22
mutating operations plus GET /api/keys, GET /api/settings, /api/news/models.
- public operations: security: [] (explicit "no auth"; not omitted).
POST /api/search, POST /api/auth/login and POST /api/auth/logout stay
public, and the read-only HUD surface is untouched.
Tests pin the pair per documented operation: the real app must answer 401 on
every operation that declares security, and the middleware must admit every
operation that declares []. Verified red on the untouched base (9 failures)
and green after the change.
2026-11-27 00:26:31 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# ── The published contract matches the enforced behaviour ───────────────────
|
|
|
|
|
# The admin gate lives in middleware, so FastAPI cannot infer a security
|
|
|
|
|
# requirement from the route decorators: the spec must be told. These tests pin
|
|
|
|
|
# the *pair* — for every documented operation, "the middleware answers 401" and
|
|
|
|
|
# "the OpenAPI operation declares security" must agree — so the two cannot
|
|
|
|
|
# drift apart again.
|
|
|
|
|
|
|
|
|
|
_MUTATING = frozenset({"POST", "PUT", "PATCH", "DELETE"})
|
|
|
|
|
_OPENAPI_METHODS = frozenset({"get", "put", "post", "delete", "options", "head",
|
|
|
|
|
"patch", "trace"})
|
|
|
|
|
_ADMIN = [{auth.SECURITY_SCHEME_NAME: []}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _spec() -> dict:
|
|
|
|
|
"""A freshly generated spec (also exercises the generator, not the cache)."""
|
|
|
|
|
from main import app as _app
|
|
|
|
|
|
|
|
|
|
_app.openapi_schema = None
|
|
|
|
|
return _app.openapi()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _operations(spec: dict):
|
|
|
|
|
for path, item in spec["paths"].items():
|
|
|
|
|
for method, operation in item.items():
|
|
|
|
|
if method.lower() in _OPENAPI_METHODS and isinstance(operation, dict):
|
|
|
|
|
yield path, method.upper(), operation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _concrete(path: str) -> str:
|
|
|
|
|
"""Substitute path params with an arbitrary segment (the gate runs first)."""
|
|
|
|
|
return re.sub(r"\{[^}]+\}", "probe", path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def _passthrough(scope, receive, send):
|
|
|
|
|
"""Downstream app that answers 200 to anything — proves the gate opened."""
|
|
|
|
|
await send({"type": "http.response.start", "status": 200, "headers": []})
|
|
|
|
|
await send({"type": "http.response.body", "body": b"ok"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _gate_decision(method: str, path: str) -> int:
|
|
|
|
|
guarded = auth.AdminAuthMiddleware(_passthrough)
|
|
|
|
|
|
|
|
|
|
async def _run() -> int:
|
|
|
|
|
transport = httpx.ASGITransport(app=guarded)
|
|
|
|
|
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
|
|
|
|
return (await client.request(method, path)).status_code
|
|
|
|
|
|
|
|
|
|
return asyncio.run(_run())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_openapi_publishes_the_admin_session_cookie_scheme():
|
|
|
|
|
schemes = _spec()["components"]["securitySchemes"]
|
|
|
|
|
assert list(schemes) == [auth.SECURITY_SCHEME_NAME]
|
|
|
|
|
scheme = schemes[auth.SECURITY_SCHEME_NAME]
|
|
|
|
|
# Truthful, not invented: the middleware authenticates exactly this cookie.
|
|
|
|
|
assert scheme["type"] == "apiKey"
|
|
|
|
|
assert scheme["in"] == "cookie"
|
|
|
|
|
assert scheme["name"] == auth.COOKIE_NAME
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_openapi_json_endpoint_serves_the_scheme():
|
|
|
|
|
from main import app as _app
|
|
|
|
|
|
|
|
|
|
_app.openapi_schema = None
|
|
|
|
|
resp = _request("GET", "/openapi.json")
|
|
|
|
|
assert resp.status_code == 200
|
|
|
|
|
assert auth.SECURITY_SCHEME_NAME in resp.json()["components"]["securitySchemes"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_every_documented_operation_pairs_with_the_middleware():
|
|
|
|
|
"""401 ⇔ security declared, for all documented operations, in both ways."""
|
|
|
|
|
spec = _spec()
|
|
|
|
|
protected, public = [], []
|
|
|
|
|
for path, method, operation in _operations(spec):
|
|
|
|
|
assert "security" in operation, f"{method} {path} declares no security"
|
|
|
|
|
(protected if operation["security"] else public).append((method, path))
|
|
|
|
|
|
|
|
|
|
assert protected, "no protected operation documented"
|
|
|
|
|
assert public, "no public operation documented"
|
|
|
|
|
|
|
|
|
|
# Protected: the real app must refuse an anonymous request before any
|
|
|
|
|
# handler runs (a handler that ran and failed would answer 5xx, not 401).
|
|
|
|
|
for method, path in protected:
|
|
|
|
|
resp = _request(method, _concrete(path))
|
|
|
|
|
assert resp.status_code == 401, f"{method} {path} -> {resp.status_code}"
|
|
|
|
|
assert resp.json() == {"detail": "admin authentication required"}
|
|
|
|
|
|
|
|
|
|
# Public: the same middleware instance must let the request through.
|
|
|
|
|
for method, path in public:
|
|
|
|
|
assert _gate_decision(method, _concrete(path)) == 200, f"{method} {path}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("path", ["/api/keys", "/api/settings"])
|
|
|
|
|
def test_admin_reads_are_documented_as_protected(path):
|
|
|
|
|
operation = _spec()["paths"][path]["get"]
|
|
|
|
|
assert operation["security"] == _ADMIN
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("path", ["/api/aircraft", "/api/stats", "/api/health"])
|
|
|
|
|
def test_public_reads_are_documented_as_unauthenticated(path):
|
|
|
|
|
operation = _spec()["paths"][path]["get"]
|
|
|
|
|
# Explicit [] — an absent field would read as "inherit global security".
|
|
|
|
|
assert operation["security"] == []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_mutating_surface_is_admin_only_except_the_public_three():
|
|
|
|
|
"""22 mutating operations are published; 19 need the admin session."""
|
|
|
|
|
mutating = [(method, path, operation["security"])
|
|
|
|
|
for path, method, operation in _operations(_spec())
|
|
|
|
|
if method in _MUTATING]
|
|
|
|
|
assert len(mutating) >= 22, "mutating surface unexpectedly shrank"
|
|
|
|
|
public = {(method, path) for method, path, security in mutating if not security}
|
|
|
|
|
assert public == {
|
|
|
|
|
("POST", "/api/auth/login"), # bootstrap surface
|
|
|
|
|
("POST", "/api/auth/logout"), # unauthenticated by design
|
|
|
|
|
("POST", "/api/search"), # read-only query endpoint
|
|
|
|
|
}
|
|
|
|
|
assert all(not security or security == _ADMIN for _, _, security in mutating)
|
|
|
|
|
|