fix(openapi): declare the admin session cookie on every guarded operation #71
3 changed files with 214 additions and 1 deletions
51
app/auth.py
51
app/auth.py
|
|
@ -153,6 +153,57 @@ def is_public(path: str, method: str) -> bool:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
# ── OpenAPI security declaration ─────────────────────────────────────────────
|
||||||
|
# The admin check runs in :class:`AdminAuthMiddleware`, not in a route
|
||||||
|
# dependency, so FastAPI cannot infer a scheme from the decorators. The
|
||||||
|
# published spec is derived from :func:`is_public` instead — the same allowlist
|
||||||
|
# the middleware enforces — so the contract and the behaviour cannot drift.
|
||||||
|
# ``tests/test_auth.py`` asserts both halves of that pair for every documented
|
||||||
|
# operation.
|
||||||
|
|
||||||
|
SECURITY_SCHEME_NAME = "adminSession"
|
||||||
|
|
||||||
|
SECURITY_SCHEME: dict = {
|
||||||
|
"type": "apiKey",
|
||||||
|
"in": "cookie",
|
||||||
|
"name": COOKIE_NAME,
|
||||||
|
"description": (
|
||||||
|
"Admin session cookie set by `POST /api/auth/login` (HttpOnly, "
|
||||||
|
"SameSite=Lax, HMAC-SHA256 signed, 7-day lifetime). Every `/api/*` "
|
||||||
|
"operation outside the public read allowlist answers "
|
||||||
|
'`401 {"detail": "admin authentication required"}` without it, and '
|
||||||
|
"`403` while `ADMIN_PASSWORD_HASH`/`ADMIN_SESSION_SECRET` are unset. "
|
||||||
|
"Browser clients sign in at `/login`; other clients POST credentials "
|
||||||
|
"and replay the cookie."
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
_OPENAPI_METHODS = frozenset(
|
||||||
|
{"get", "put", "post", "delete", "options", "head", "patch", "trace"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_openapi_security(spec: dict) -> dict:
|
||||||
|
"""Stamp the admin-cookie requirement onto every guarded operation.
|
||||||
|
|
||||||
|
Protected operations get ``security: [{"adminSession": []}]``. Public ones
|
||||||
|
get ``security: []`` so the document states "no auth" explicitly — an
|
||||||
|
absent field is indistinguishable from an inherited global requirement.
|
||||||
|
"""
|
||||||
|
components = spec.setdefault("components", {})
|
||||||
|
schemes = components.setdefault("securitySchemes", {})
|
||||||
|
schemes[SECURITY_SCHEME_NAME] = dict(SECURITY_SCHEME)
|
||||||
|
for path, item in (spec.get("paths") or {}).items():
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
for method, operation in item.items():
|
||||||
|
if method.lower() not in _OPENAPI_METHODS or not isinstance(operation, dict):
|
||||||
|
continue
|
||||||
|
protected = not is_public(path, method.upper())
|
||||||
|
operation["security"] = [{SECURITY_SCHEME_NAME: []}] if protected else []
|
||||||
|
return spec
|
||||||
|
|
||||||
|
|
||||||
# ── Config (read per call so tests and reloads pick up env changes) ─────────
|
# ── Config (read per call so tests and reloads pick up env changes) ─────────
|
||||||
|
|
||||||
def _env(name: str) -> str:
|
def _env(name: str) -> str:
|
||||||
|
|
|
||||||
26
app/main.py
26
app/main.py
|
|
@ -28,13 +28,14 @@ import httpx
|
||||||
import structlog
|
import structlog
|
||||||
from fastapi import FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect
|
from fastapi import FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||||
from fastapi.middleware.gzip import GZipMiddleware
|
from fastapi.middleware.gzip import GZipMiddleware
|
||||||
|
from fastapi.openapi.utils import get_openapi
|
||||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
from sqlalchemy import and_, func, or_, select, text
|
from sqlalchemy import and_, func, or_, select, text
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from database import async_session, init_extensions
|
from database import async_session, init_extensions
|
||||||
from auth import AdminAuthMiddleware, router as auth_router
|
from auth import AdminAuthMiddleware, apply_openapi_security, router as auth_router
|
||||||
from models import (
|
from models import (
|
||||||
alerts, documents, entities, entity_events, events, feed_sources, fires,
|
alerts, documents, entities, entity_events, events, feed_sources, fires,
|
||||||
articles, article_scores, article_summaries, news_items,
|
articles, article_scores, article_summaries, news_items,
|
||||||
|
|
@ -123,6 +124,29 @@ app.add_middleware(GZipMiddleware, minimum_size=1024)
|
||||||
app.add_middleware(AdminAuthMiddleware)
|
app.add_middleware(AdminAuthMiddleware)
|
||||||
app.include_router(auth_router)
|
app.include_router(auth_router)
|
||||||
|
|
||||||
|
|
||||||
|
def _custom_openapi() -> dict:
|
||||||
|
"""OpenAPI document that declares the admin-cookie requirement.
|
||||||
|
|
||||||
|
The gate lives in ``AdminAuthMiddleware``, so nothing in the route
|
||||||
|
decorators tells FastAPI which operations need a session. Security is
|
||||||
|
stamped from ``auth.is_public`` — the same allowlist the middleware
|
||||||
|
enforces — rather than hand-maintained per route.
|
||||||
|
"""
|
||||||
|
if app.openapi_schema:
|
||||||
|
return app.openapi_schema
|
||||||
|
schema = get_openapi(
|
||||||
|
title=app.title,
|
||||||
|
version=app.version,
|
||||||
|
description=app.description,
|
||||||
|
routes=app.routes,
|
||||||
|
)
|
||||||
|
app.openapi_schema = apply_openapi_security(schema)
|
||||||
|
return app.openapi_schema
|
||||||
|
|
||||||
|
|
||||||
|
app.openapi = _custom_openapi
|
||||||
|
|
||||||
STATIC_DIR = Path(__file__).parent / "static"
|
STATIC_DIR = Path(__file__).parent / "static"
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ checkout.
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import re
|
||||||
import time
|
import time
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
@ -547,3 +548,140 @@ def test_public_allowlist_classification():
|
||||||
assert not auth.is_public("/api/vessels/subscribe", "POST")
|
assert not auth.is_public("/api/vessels/subscribe", "POST")
|
||||||
assert not auth.is_public("/api/geofences", "POST")
|
assert not auth.is_public("/api/geofences", "POST")
|
||||||
assert auth.is_public("/ws/live", "GET")
|
assert auth.is_public("/ws/live", "GET")
|
||||||
|
|
||||||
|
|
||||||
|
# ── 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_every_route_is_in_the_documented_surface():
|
||||||
|
"""No APIRoute may escape the spec — an undocumented route dodges the pair."""
|
||||||
|
from fastapi.routing import APIRoute
|
||||||
|
from main import app as _app
|
||||||
|
|
||||||
|
spec = _spec()
|
||||||
|
missing = []
|
||||||
|
for route in _app.routes:
|
||||||
|
if not isinstance(route, APIRoute): # Mount, WebSocket, included routers
|
||||||
|
continue
|
||||||
|
for method in route.methods:
|
||||||
|
if spec["paths"].get(route.path, {}).get(method.lower()) is None:
|
||||||
|
missing.append(f"{method} {route.path}")
|
||||||
|
assert missing == []
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue