osint-dashboard/app/auth.py
Sirius DevOps 5a39404384 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:27:50 -05:00

640 lines
24 KiB
Python

"""Single-admin authentication for the OSINT dashboard.
The public site stays read-only for anonymous visitors; the one admin (the
operator) unlocks API-key management, settings and every state-changing route.
Design notes
------------
* **Deny by default.** :class:`AdminAuthMiddleware` inspects every ``/api/*``
request. Only the explicit read allowlist below is reachable without a
session; everything else needs a valid signed cookie. ``/api/auth/*`` is the
bootstrap surface and handles its own checks.
* **Fail closed.** With ``ADMIN_PASSWORD_HASH`` or ``ADMIN_SESSION_SECRET``
unset/empty, admin endpoints answer ``403 {"detail": "admin auth not
configured"}``. There is no default password and no bypass; public reads and
the HUD keep working.
* **No new dependencies.** Password hashing is stdlib ``hashlib.pbkdf2_hmac``
and the session token is an HMAC-SHA256 signature over a base64url JSON
payload. Cookies are HttpOnly, SameSite=Lax, Path=/, 7-day lifetime, and
``Secure`` when the request arrived over https (``X-Forwarded-Proto``) or
when ``ADMIN_COOKIE_SECURE`` is truthy (TLS-only deployments behind an
HTTP origin listener, where Envoy normalizes the header to ``http``).
* **CSRF.** State-changing admin requests that carry an ``Origin``/``Referer``
are rejected when the origin host differs from the request host. Requests
without either header (curl, server-to-server) are allowed — the signed,
SameSite=Lax session cookie is what authenticates them.
Environment (exact names, supplied by the ``osint-admin`` Secret):
``ADMIN_USER``
Admin username.
``ADMIN_PASSWORD_HASH``
``pbkdf2_sha256$<iterations>$<salt_b64>$<hash_b64>``. Generate with::
python app/auth.py hash 'your password'
``ADMIN_SESSION_SECRET``
HMAC key for session tokens. Generate with::
python -c 'import secrets; print(secrets.token_urlsafe(48))'
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import os
import re
import secrets
import time
from collections import deque
from urllib.parse import parse_qs, urlparse
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, JSONResponse
# ── Constants ────────────────────────────────────────────────────────────────
COOKIE_NAME = "osint_session"
SESSION_TTL_SECONDS = 7 * 24 * 60 * 60
PBKDF2_ALGORITHM = "pbkdf2_sha256"
PBKDF2_ITERATIONS = 260_000
_ITERATIONS_FLOOR, _ITERATIONS_CEIL = 1_000, 5_000_000
LOGIN_WINDOW_SECONDS = 15 * 60
LOGIN_MAX_FAILURES = 5
_STATE_CHANGING = frozenset({"POST", "PUT", "PATCH", "DELETE"})
# ── Public read allowlist ────────────────────────────────────────────────────
# Anonymous visitors get the map + news HUD. Every path here was audited as a
# pure read (no writes, no spend of a stored API key). Anything absent requires
# the admin session.
PUBLIC_GET_EXACT = frozenset({
# core
"/api/health",
"/api/ready",
"/api/stats",
# events / sources / entities / alerts / documents
"/api/sources",
"/api/events",
"/api/fires",
"/api/entities",
"/api/alerts",
"/api/documents",
# analytics
"/api/analytics/summary",
"/api/analytics/timeline",
"/api/analytics/sentiment/by-source",
# cameras
"/api/cameras",
# news
"/api/news",
"/api/news/summaries",
"/api/news/ticker",
"/api/news/map",
"/api/news/blips",
# map / live layers
"/api/map/layers",
"/api/map/chokepoints",
"/api/map/radar",
"/api/map/sentinel1",
"/api/map/gpsjam",
"/api/map/times",
"/api/conflicts",
"/api/aircraft",
"/api/aircraft/photo",
"/api/trains",
"/api/vessels",
"/api/tracks/range",
"/api/satellites",
"/api/infrastructure",
"/api/place",
# geofences (reads only — create/patch/delete stay admin)
"/api/geofences",
"/api/geofence-alerts",
# fire / weather overlays
"/api/fire-aircraft",
"/api/fire-incidents",
"/api/fire-perimeters",
"/api/weather-alerts",
"/api/storms",
})
PUBLIC_GET_PATTERNS = tuple(re.compile(p) for p in (
r"^/api/events/[^/]+$",
r"^/api/entities/[^/]+$",
r"^/api/entities/[^/]+/events$",
r"^/api/cameras/[^/]+$",
r"^/api/cameras/[^/]+/(?:snapshot|stream|hls\.m3u8|hlsseg)$",
r"^/api/geofences/[^/]+/at$",
))
# POST is only public for the read-only query endpoint.
PUBLIC_POST_EXACT = frozenset({"/api/search"})
def is_public(path: str, method: str) -> bool:
"""True when ``method path`` may be served without an admin session."""
if not path.startswith("/api/"):
return True
if path.startswith("/api/auth/"):
return True
norm = path.rstrip("/") or "/"
if method in ("GET", "HEAD"):
if norm in PUBLIC_GET_EXACT:
return True
return any(p.match(norm) for p in PUBLIC_GET_PATTERNS)
if method == "POST":
return norm in PUBLIC_POST_EXACT
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) ─────────
def _env(name: str) -> str:
return (os.environ.get(name) or "").strip()
def admin_user() -> str:
return _env("ADMIN_USER")
def admin_password_hash() -> str:
return _env("ADMIN_PASSWORD_HASH")
def session_secret() -> str:
return _env("ADMIN_SESSION_SECRET")
def auth_configured() -> bool:
"""Fail closed: both the password hash and the signing key must be set."""
return bool(admin_password_hash() and session_secret())
# ── Password hashing (stdlib PBKDF2-SHA256) ─────────────────────────────────
def _b64e(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def _b64d(text: str) -> bytes:
pad = "=" * (-len(text) % 4)
return base64.urlsafe_b64decode(text + pad)
def hash_password(password: str, *, iterations: int = PBKDF2_ITERATIONS,
salt: bytes | None = None) -> str:
"""Return ``pbkdf2_sha256$<iters>$<salt_b64>$<hash_b64>``."""
salt = salt if salt is not None else secrets.token_bytes(16)
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
return f"{PBKDF2_ALGORITHM}${iterations}${_b64e(salt)}${_b64e(dk)}"
def verify_password(password: str, stored: str) -> bool:
"""Constant-time check of ``password`` against a stored PBKDF2 string."""
if not stored:
return False
try:
algorithm, iterations_s, salt_b64, hash_b64 = stored.split("$", 3)
iterations = int(iterations_s)
salt = _b64d(salt_b64)
expected = _b64d(hash_b64)
except (ValueError, TypeError):
return False
if algorithm != PBKDF2_ALGORITHM:
return False
if not (_ITERATIONS_FLOOR <= iterations <= _ITERATIONS_CEIL):
return False
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
return hmac.compare_digest(dk, expected)
def _const_eq(a: str, b: str) -> bool:
return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))
# ── Session tokens ───────────────────────────────────────────────────────────
def _sign(body: str, secret: str) -> str:
digest = hmac.new(secret.encode("utf-8"), body.encode("ascii"), hashlib.sha256).digest()
return _b64e(digest)
def create_session_token(user: str, *, now: float | None = None) -> str:
secret = session_secret()
if not secret:
raise RuntimeError("ADMIN_SESSION_SECRET is not configured")
issued = int(now if now is not None else time.time())
payload = {"v": 1, "sub": user, "iat": issued, "exp": issued + SESSION_TTL_SECONDS}
body = _b64e(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8"))
return f"{body}.{_sign(body, secret)}"
def verify_session_token(token: str | None, *, now: float | None = None) -> str | None:
"""Return the username for a valid token, else ``None``. Never raises."""
if not token or "." not in token:
return None
secret = session_secret()
if not secret:
return None
body, signature = token.rsplit(".", 1)
try:
expected = _sign(body, secret)
if not hmac.compare_digest(signature.encode("utf-8"), expected.encode("utf-8")):
return None
except (UnicodeEncodeError, ValueError, TypeError):
return None
try:
payload = json.loads(_b64d(body))
version = payload["v"]
subject = str(payload["sub"])
issued = int(payload["iat"])
expires = int(payload["exp"])
except (ValueError, KeyError, TypeError):
return None
now_s = int(now if now is not None else time.time())
if version != 1:
return None
if expires <= now_s or issued > now_s + 300:
return None
expected = admin_user()
if not expected or not _const_eq(subject, expected):
return None
return subject
def current_user(request: Request) -> str | None:
"""The authenticated admin username for this request, else ``None``."""
if not auth_configured():
return None
return verify_session_token(request.cookies.get(COOKIE_NAME))
# ── Cookie helpers ───────────────────────────────────────────────────────────
def _is_https(request: Request) -> bool:
proto = (request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower()
if proto:
return proto == "https"
return request.url.scheme == "https"
_TRUTHY = {"1", "true", "yes"}
def cookie_secure_forced() -> bool:
"""``ADMIN_COOKIE_SECURE`` marks the deployment TLS-only.
Read on every call so tests and restarts pick up env changes; the header
inference in :func:`_is_https` stays as the fallback.
"""
return (os.getenv("ADMIN_COOKIE_SECURE") or "").strip().lower() in _TRUTHY
def set_session_cookie(response, request: Request, token: str) -> None:
response.set_cookie(
COOKIE_NAME,
token,
max_age=SESSION_TTL_SECONDS,
httponly=True,
samesite="lax",
secure=cookie_secure_forced() or _is_https(request),
path="/",
)
def clear_session_cookie(response) -> None:
response.delete_cookie(COOKIE_NAME, path="/", httponly=True, samesite="lax")
# ── Login rate limiting (in-memory; single replica) ─────────────────────────
_failures: dict[str, deque[float]] = {}
def client_ip(request: Request) -> str:
forwarded = request.headers.get("x-forwarded-for") or ""
first = forwarded.split(",")[0].strip()
if first:
return first
return request.client.host if request.client else "unknown"
def _prune(bucket: deque[float], now: float) -> None:
while bucket and now - bucket[0] > LOGIN_WINDOW_SECONDS:
bucket.popleft()
def rate_limited(ip: str, *, now: float | None = None) -> bool:
now_s = time.time() if now is None else now
bucket = _failures.get(ip)
if not bucket:
return False
_prune(bucket, now_s)
return len(bucket) >= LOGIN_MAX_FAILURES
def record_failure(ip: str, *, now: float | None = None) -> None:
now_s = time.time() if now is None else now
if len(_failures) > 10_000: # bound memory against IP spraying
for key in [k for k, v in _failures.items() if not v or now_s - v[-1] > LOGIN_WINDOW_SECONDS]:
_failures.pop(key, None)
bucket = _failures.setdefault(ip, deque())
_prune(bucket, now_s)
bucket.append(now_s)
def reset_failures(ip: str | None = None) -> None:
"""Clear the limiter (used by logout success and tests)."""
if ip is None:
_failures.clear()
else:
_failures.pop(ip, None)
# ── CSRF (origin host must match the request host when supplied) ────────────
def origin_allowed(request: Request) -> bool:
if request.method.upper() not in _STATE_CHANGING:
return True
origin = request.headers.get("origin") or request.headers.get("referer")
if not origin:
return True # no browser context: session cookie is the credential
host = (request.headers.get("x-forwarded-host") or request.headers.get("host") or "")
host = host.split(",")[0].strip().lower()
try:
origin_host = urlparse(origin).netloc.strip().lower()
except ValueError:
return False
if not host or not origin_host:
return False
return origin_host == host
# ── Middleware ───────────────────────────────────────────────────────────────
def _json_response(status: int, detail: str) -> JSONResponse:
return JSONResponse({"detail": detail}, status_code=status)
class AdminAuthMiddleware:
"""Deny-by-default gate for ``/api/*`` (pure ASGI; keeps streaming intact)."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope.get("type") != "http":
return await self.app(scope, receive, send)
path = scope.get("path") or ""
method = (scope.get("method") or "GET").upper()
if not path.startswith("/api/") or is_public(path, method):
return await self.app(scope, receive, send)
request = Request(scope)
if not auth_configured():
return await _json_response(403, "admin auth not configured")(scope, receive, send)
if current_user(request) is None:
return await _json_response(401, "admin authentication required")(scope, receive, send)
if not origin_allowed(request):
return await _json_response(403, "cross-origin admin request blocked")(scope, receive, send)
return await self.app(scope, receive, send)
# ── Auth routes ─────────────────────────────────────────────────────────────
router = APIRouter()
@router.get("/api/auth/me")
async def auth_me(request: Request):
"""Always 200 — the HUD uses this to show/hide admin UI."""
user = current_user(request)
return {"authenticated": user is not None, "admin": user is not None}
async def _read_credentials(request: Request) -> dict:
"""Accept form-encoded or JSON bodies (never trust the claimed type)."""
raw = await request.body()
if not raw:
return {}
ctype = (request.headers.get("content-type") or "").lower()
if "json" in ctype:
try:
payload = json.loads(raw)
except (ValueError, TypeError):
return {}
return payload if isinstance(payload, dict) else {}
if "form" in ctype or "urlencoded" in ctype:
try:
parsed = parse_qs(raw.decode("utf-8", "replace"))
except (ValueError, TypeError):
return {}
return {k: v[0] for k, v in parsed.items() if v}
# Unknown content type: try JSON, then form.
try:
payload = json.loads(raw)
if isinstance(payload, dict):
return payload
except (ValueError, TypeError):
pass
try:
parsed = parse_qs(raw.decode("utf-8", "replace"))
except (ValueError, TypeError):
return {}
return {k: v[0] for k, v in parsed.items() if v}
@router.post("/api/auth/login")
async def auth_login(request: Request):
ip = client_ip(request)
if not auth_configured():
return _json_response(403, "admin auth not configured")
if rate_limited(ip):
return _json_response(429, "too many failed login attempts")
data = await _read_credentials(request)
username = str(data.get("username") or data.get("user") or "")
password = str(data.get("password") or "")
user_ok = bool(username) and bool(admin_user()) and _const_eq(username, admin_user())
pass_ok = verify_password(password, admin_password_hash())
if not (user_ok and pass_ok):
record_failure(ip)
return _json_response(401, "invalid credentials")
reset_failures(ip)
response = JSONResponse({"authenticated": True, "admin": True})
set_session_cookie(response, request, create_session_token(admin_user()))
return response
@router.post("/api/auth/logout")
async def auth_logout(request: Request):
# NOTE: never clear the login limiter here — logout is unauthenticated and
# would otherwise let an attacker reset the rate limit between guesses.
response = JSONResponse({"authenticated": False, "admin": False})
clear_session_cookie(response)
return response
_LOGIN_PAGE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Admin sign-in · OSINT//</title>
<style>
:root { --bg:#05070c; --panel:#0b1018; --line:#1c2735; --cyan:#35e0ff; --magenta:#ff2e97; --text:#d7e3f2; --dim:#7d8ea3; }
* { box-sizing:border-box; }
body { margin:0; min-height:100vh; display:grid; place-items:center; background:
radial-gradient(1000px 500px at 50% -10%, rgba(53,224,255,.10), transparent 60%),
radial-gradient(700px 400px at 90% 110%, rgba(255,46,151,.08), transparent 60%), var(--bg);
color:var(--text); font:15px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
.box { width:100%; max-width:360px; padding:2rem 1.6rem; border:1px solid var(--line);
border-radius:8px; background:linear-gradient(180deg, var(--panel), #070b12);
box-shadow:0 0 0 1px rgba(53,224,255,.06), 0 24px 60px rgba(0,0,0,.6); }
.brand { letter-spacing:.24em; font-size:.8rem; color:var(--dim); margin-bottom:1.4rem; }
.brand b { color:var(--cyan); }
h1 { font-size:1rem; letter-spacing:.12em; margin:0 0 1.2rem; text-transform:uppercase; }
label { display:block; font-size:.68rem; letter-spacing:.16em; color:var(--dim);
text-transform:uppercase; margin:.9rem 0 .35rem; }
input { width:100%; padding:.6rem .7rem; background:#04070d; color:var(--text);
border:1px solid var(--line); border-radius:4px; font:inherit; }
input:focus { outline:none; border-color:var(--cyan); box-shadow:0 0 0 2px rgba(53,224,255,.14); }
button { width:100%; margin-top:1.4rem; padding:.65rem; background:var(--cyan); color:#02121a;
border:0; border-radius:4px; font:inherit; font-weight:700; letter-spacing:.12em; cursor:pointer; }
button:hover { background:#6becff; }
button:disabled { opacity:.5; cursor:default; }
.msg { min-height:1.2rem; margin-top:.9rem; font-size:.8rem; color:var(--magenta); }
.note { margin-top:1.1rem; font-size:.74rem; color:var(--dim); }
a { color:var(--cyan); text-decoration:none; }
</style>
</head>
<body>
<form class="box" id="login-form">
<div class="brand">OSINT<b>//</b> ADMIN</div>
<h1>Sign in</h1>
<label for="username">Username</label>
<input id="username" name="username" type="text" autocomplete="username" required autofocus>
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" required>
<button id="submit" type="submit">AUTHENTICATE</button>
<div class="msg" id="msg" role="alert"></div>
<div class="note"><a href="/">← Back to dashboard</a></div>
</form>
<script>
const form = document.getElementById('login-form');
const msg = document.getElementById('msg');
const submit = document.getElementById('submit');
form.addEventListener('submit', async (ev) => {
ev.preventDefault();
msg.textContent = '';
submit.disabled = true;
try {
const r = await fetch('/api/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams(new FormData(form)),
});
const data = await r.json().catch(() => ({}));
if (r.ok) { window.location.replace('/'); return; }
msg.textContent = r.status === 429 ? 'Too many attempts. Try again later.'
: (data && data.detail ? String(data.detail) : 'Sign-in failed.');
} catch (e) {
msg.textContent = 'Network error.';
} finally {
submit.disabled = false;
}
});
</script>
</body>
</html>
"""
_NOT_CONFIGURED = ('<div class="msg">Admin auth is not configured on this server. '
'Set ADMIN_PASSWORD_HASH and ADMIN_SESSION_SECRET.</div>')
@router.get("/login", response_class=HTMLResponse)
async def login_page():
html = _LOGIN_PAGE
if not auth_configured():
html = html.replace('<div class="msg" id="msg" role="alert"></div>',
_NOT_CONFIGURED.replace('class="msg"', 'class="msg" id="msg" role="alert"'))
response = HTMLResponse(html)
response.headers["Cache-Control"] = "no-store"
return response
# ── CLI: generate a password hash ────────────────────────────────────────────
def _main(argv: list[str]) -> int:
if len(argv) != 2 or argv[0] != "hash":
print("usage: python app/auth.py hash '<password>'")
return 2
print(hash_password(argv[1]))
return 0
if __name__ == "__main__":
import sys
raise SystemExit(_main(sys.argv[1:]))