"""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``). * **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$$$``. 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", # 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 # ── 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$$$``.""" 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" 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=_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 = """ Admin sign-in · OSINT//
OSINT// ADMIN

Sign in

""" _NOT_CONFIGURED = ('
Admin auth is not configured on this server. ' 'Set ADMIN_PASSWORD_HASH and ADMIN_SESSION_SECRET.
') @router.get("/login", response_class=HTMLResponse) async def login_page(): html = _LOGIN_PAGE if not auth_configured(): html = html.replace('', _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 ''") return 2 print(hash_password(argv[1])) return 0 if __name__ == "__main__": import sys raise SystemExit(_main(sys.argv[1:]))