diff --git a/.env.example b/.env.example index 7e582dc..7d194f6 100644 --- a/.env.example +++ b/.env.example @@ -69,16 +69,6 @@ VESSELAPI_IN_INGEST=0 # (GET/POST/DELETE /api/keys/{name}) — see app/keystore.py. The FIRMS ingestor # currently reads FIRMS_MAP_KEY from .env (above); wiring the Keys-UI store as # its lookup/fallback is a planned follow-up. -# -# Key management is ADMIN-ONLY (single admin, no user table). Visitors get a -# read-only map + news. Configure the three vars below or admin endpoints -# answer 403 {"detail": "admin auth not configured"} (fail closed — the public -# site keeps working). In the cluster they come from Secret `osint-admin`. -# Generate the hash: python app/auth.py hash 'your password' -# Generate the secret: python -c 'import secrets; print(secrets.token_urlsafe(48))' -ADMIN_USER= -ADMIN_PASSWORD_HASH= -ADMIN_SESSION_SECRET= # ── News pipeline (scraper + summarizer, profile `ingest`) ──────────────── # Scraper crawls urls.txt continuously (default 10s between crawls). diff --git a/app/auth.py b/app/auth.py deleted file mode 100644 index cfdb074..0000000 --- a/app/auth.py +++ /dev/null @@ -1,574 +0,0 @@ -"""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:])) diff --git a/app/main.py b/app/main.py index 2d7a3f6..049d96c 100644 --- a/app/main.py +++ b/app/main.py @@ -34,7 +34,6 @@ from sqlalchemy import and_, func, or_, select, text from sqlalchemy.ext.asyncio import AsyncSession from database import async_session, init_extensions -from auth import AdminAuthMiddleware, router as auth_router from models import ( alerts, documents, entities, entity_events, events, feed_sources, fires, articles, article_summaries, news_items, @@ -117,11 +116,6 @@ app = FastAPI( ) app.add_middleware(GZipMiddleware, minimum_size=1024) -# Single-admin auth: deny-by-default on /api/* with an explicit public read -# allowlist (app/auth.py), plus /login, /api/auth/{login,logout,me}. -app.add_middleware(AdminAuthMiddleware) -app.include_router(auth_router) - STATIC_DIR = Path(__file__).parent / "static" diff --git a/app/static/index.html b/app/static/index.html index acca754..fdc1588 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -157,20 +157,6 @@ .nav-item.primary .ico { color: var(--magenta); } .nav-sep { height: 1px; background: var(--line); margin: 0.35rem 0.3rem; } - /* ═══════════════ ADMIN GATE (UX only — the API is the real gate) ═══ - Elements marked data-admin stay hidden until /api/auth/me reports a - valid admin session (body.is-admin). Fails closed: no JS => hidden. */ - body:not(.is-admin) [data-admin] { display: none !important; } - .admin-link { - font-size: 0.62rem; letter-spacing: 0.16em; text-transform: uppercase; - color: var(--muted); text-decoration: none; border: 1px solid var(--line); - border-radius: 3px; padding: 0.28rem 0.5rem; white-space: nowrap; - transition: color .15s, border-color .15s; - } - .admin-link:hover, .admin-link:focus-visible { color: var(--cyan); border-color: var(--cyan); } - body.is-admin .admin-link { color: var(--magenta); border-color: var(--magenta); } - - /* ═══════════════ STAGE / VIEWS ═══════════════ */ .stage { /* 100vh first for old browsers; 100dvh shrinks with mobile URL chrome */ @@ -889,7 +875,6 @@ - SIGN IN @@ -948,7 +933,7 @@
Opacity 100%
-
+
@@ -1253,7 +1238,7 @@ -
+

⇪ Data Ingestion

Manually trigger feed pulls & NATS processing

@@ -1286,7 +1271,7 @@
-
+

⚿ API Keys

Keys used by ingest services (FIRMS, Nous Portal, Telegram, AIS, …). Stored in Postgres, never shown again — only status + last 4 chars.

@@ -1313,7 +1298,7 @@
-
+

News Summarizer

Takes effect on the next 15-min run. No container restart.

@@ -1641,40 +1626,6 @@ function initHudKeys() { }); } -/* ═══════════════ ADMIN SESSION (UX gate — the API is the real gate) ═══════ - Anonymous visitors get the read-only map + news. Admin-only chrome is - marked data-admin and revealed only when /api/auth/me reports a session. */ -let IS_ADMIN = false; -let AUTH_READY = false; -const ADMIN_VIEWS = ['keys', 'ingest', 'settings']; - -async function initAuth() { - try { - const r = await fetch(`${API}/api/auth/me`, {cache: 'no-store', credentials: 'same-origin'}); - const d = r.ok ? await r.json() : {}; - IS_ADMIN = !!(d && d.admin); - } catch (e) { - IS_ADMIN = false; - } - AUTH_READY = true; - document.body.classList.toggle('is-admin', IS_ADMIN); - const link = document.getElementById('admin-link'); - if (link) { - link.textContent = IS_ADMIN ? 'SIGN OUT' : (link.dataset.anonLabel || 'SIGN IN'); - link.title = IS_ADMIN ? 'End admin session' : 'Admin sign-in'; - link.setAttribute('aria-label', IS_ADMIN ? 'Sign out of admin session' : 'Admin sign-in'); - } -} - -async function onAdminLink(ev) { - if (!IS_ADMIN) return; // anonymous: plain link to /login - ev.preventDefault(); - try { - await fetch(`${API}/api/auth/logout`, {method: 'POST', credentials: 'same-origin'}); - } catch (e) { /* cookie expires anyway */ } - window.location.reload(); -} - /* ═══════════════ NAV (dropdown) ═══════════════ */ const VIEWS = ['map', 'news', 'events', 'alerts', 'entities', 'ingest', 'keys', 'settings']; @@ -1721,7 +1672,6 @@ function initNav() { function showView(name) { if (!VIEWS.includes(name)) name = 'map'; - if (AUTH_READY && !IS_ADMIN && ADMIN_VIEWS.includes(name)) name = 'map'; VIEWS.forEach(v => { document.getElementById('view-' + v).classList.toggle('active', v === name); }); @@ -4204,8 +4154,6 @@ async function loadConflicts(paint) { } /* ═══════════════ INITIAL LOAD ═══════════════ */ -document.getElementById('admin-link').addEventListener('click', onAdminLink); -initAuth(); initNav(); initHudKeys(); initSettings(); @@ -4545,13 +4493,13 @@ async function loadGeofences() { const on = f.active === false ? '' : ' checked'; const sel = f.id === gfSelectedId ? ' selected' : ''; return `
` + - `` + `` + `` + `` + - `` + - `` + + `` + + `` + `
`; }).join(''); } @@ -4576,8 +4524,8 @@ async function loadGeofences() { const chk = active ? ' checked' : ''; layer.bindPopup( `
${name}
` + - `
` + - `
` + `
` + + `
` ); }, }).addTo(map); diff --git a/docs/auth.md b/docs/auth.md deleted file mode 100644 index 8a7bef9..0000000 --- a/docs/auth.md +++ /dev/null @@ -1,79 +0,0 @@ -# Admin authentication - -The dashboard is **public read-only**: anyone can open the map and the news -brief. One admin (the operator) additionally gets API-key management, settings -and every state-changing route. There is no user table, no RBAC and no OAuth — -one admin, one signed cookie (`app/auth.py`). - -## Surface - -| Route | Anonymous | Admin | -| --- | --- | --- | -| `GET /`, `GET /login`, `GET /static/*`, `WS /ws/live` | ✅ | ✅ | -| Read allowlist (`GET /api/news`, `/api/map/*`, feeds, analytics, cameras, `POST /api/search`, …) | ✅ | ✅ | -| `GET/POST/DELETE /api/keys*` | 401 | ✅ | -| `GET/PUT /api/settings`, `GET /api/news/models` | 401 | ✅ | -| Every other `POST/PUT/PATCH/DELETE` (`/api/ingest/*`, `/api/sources`, events, entities, alerts, geofences, `/api/vessels/subscribe`) | 401 | ✅ | -| `GET /api/auth/me` | 200 `{"authenticated": false, "admin": false}` | 200, both `true` | -| `POST /api/auth/login` | — | 200 + `Set-Cookie` | -| `POST /api/auth/logout` | 200 (clears cookie) | 200 | - -Enforcement is **deny-by-default on `/api/*`** in `AdminAuthMiddleware` -(`app/auth.py`); the public list is an explicit allowlist (`PUBLIC_GET_EXACT`, -`PUBLIC_GET_PATTERNS`, `PUBLIC_POST_EXACT`). Naming a path there is the only way -to make it public — never a per-route decorator in `app/main.py`. - -## Configuration - -Three environment variables (cluster: Secret `osint-admin`): - -| Variable | Meaning | -| --- | --- | -| `ADMIN_USER` | Admin username. | -| `ADMIN_PASSWORD_HASH` | `pbkdf2_sha256$$$`. | -| `ADMIN_SESSION_SECRET` | HMAC-SHA256 key for the session token. | - -```bash -python app/auth.py hash 'your password' # password hash -python -c 'import secrets; print(secrets.token_urlsafe(48))' # session secret -``` - -Put the values into a Secret and reference them from the deployment; never -commit them. - -### Fail closed - -If `ADMIN_PASSWORD_HASH` **or** `ADMIN_SESSION_SECRET` is unset/empty: - -* every admin endpoint answers `403 {"detail": "admin auth not configured"}`, -* `/login` renders that message instead of the form, -* `/api/auth/login` also answers 403, -* public pages and the read allowlist still work. - -There is no default password and no bypass. - -## Session cookie - -`osint_session`, HMAC-SHA256 signed base64url JSON payload `{v,sub,iat,exp}`, -`HttpOnly`, `SameSite=Lax`, `Path=/`, 7-day lifetime, `Secure` when the request -arrived over https (`X-Forwarded-Proto`, i.e. behind Cloudflare). Signature and -expiry are checked with `hmac.compare_digest`; a token for another username, or -one signed with a different secret, is rejected. - -## Abuse controls - -* **Login rate limit:** 5 failed attempts per client IP (first hop of - `X-Forwarded-For`, else the socket peer) per 15 minutes, then `429`. - In-memory — fine for the single replica. -* **CSRF:** state-changing admin requests that carry `Origin`/`Referer` must - match the request host, else `403`. Header-less clients (curl, - service-to-service) rely on the signed SameSite=Lax cookie. - -## HUD - -`app/static/index.html` hides admin chrome with `body:not(.is-admin) -[data-admin]` and adds the class only when `GET /api/auth/me` reports -`admin: true`. The menu's Ingest / API Keys / Settings entries, the summarizer -panel and the geofence draw/rename/delete controls are admin-only; anonymous -visitors see a discreet `SIGN IN` link to `/login`. This is UX only — the API -gate is what actually protects the data. diff --git a/tests/conftest.py b/tests/conftest.py index 770107b..74a1d9c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -30,38 +30,11 @@ os.environ.setdefault("DB_NAME", "osint_data") # reused across loops, so force a NullPool (new connection per session). os.environ.setdefault("DB_NULL_POOL", "1") -# ── Single-admin auth test configuration ──────────────────────────────────── -# Admin routes are denied unless a signed session cookie is present, so the -# suite needs known credentials + a signing key. Tests that exercise the -# "auth not configured" path monkeypatch these away. -ADMIN_TEST_USER = "admin" -ADMIN_TEST_PASSWORD = "test-admin-password" -ADMIN_TEST_SECRET = "test-admin-session-secret-not-for-production" - -from auth import COOKIE_NAME, create_session_token, hash_password, reset_failures # noqa: E402 - -os.environ.setdefault("ADMIN_USER", ADMIN_TEST_USER) -os.environ.setdefault("ADMIN_PASSWORD_HASH", hash_password(ADMIN_TEST_PASSWORD)) -os.environ.setdefault("ADMIN_SESSION_SECRET", ADMIN_TEST_SECRET) - import asyncpg # noqa: E402 pytestmark = [] -def admin_cookies() -> dict[str, str]: - """A valid admin session cookie value for in-process API calls.""" - return {COOKIE_NAME: create_session_token(os.environ["ADMIN_USER"])} - - -@pytest.fixture(autouse=True) -def _clear_login_limiter(): - """The login limiter is process-global; never leak failures between tests.""" - reset_failures() - yield - reset_failures() - - def _db_reachable() -> bool: try: import asyncio diff --git a/tests/test_api_live_layers.py b/tests/test_api_live_layers.py index 2efe445..7349fd8 100644 --- a/tests/test_api_live_layers.py +++ b/tests/test_api_live_layers.py @@ -7,22 +7,18 @@ import httpx from live_layers import overlay_catalog from main import app -from conftest import admin_cookies - BASE = "http://test" async def _get(path: str) -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: - client.cookies.update(admin_cookies()) return await client.get(path) async def _post(path: str, payload: dict | None) -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: - client.cookies.update(admin_cookies()) return await client.post(path, json=payload) diff --git a/tests/test_api_settings.py b/tests/test_api_settings.py index 05a5b1d..6dad2f5 100644 --- a/tests/test_api_settings.py +++ b/tests/test_api_settings.py @@ -9,7 +9,7 @@ import asyncpg import httpx import pytest -from conftest import admin_cookies, requires_db +from conftest import requires_db from main import app @@ -51,7 +51,6 @@ def _request(method: str, path: str, json: dict | None = None) -> httpx.Response async def _run() -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: - client.cookies.update(admin_cookies()) return await client.request(method, path, json=json) return asyncio.run(_run()) diff --git a/tests/test_auth.py b/tests/test_auth.py deleted file mode 100644 index 54d00bb..0000000 --- a/tests/test_auth.py +++ /dev/null @@ -1,510 +0,0 @@ -"""Single-admin auth tests: public read-only site, admin-only everything else. - -Driven in-process through ``httpx.ASGITransport`` exactly like the other API -tests. No database is required: the few routes under test that would query -Postgres are stubbed with a no-row fake session, so this file runs on a bare -checkout. -""" - -from __future__ import annotations - -import asyncio -import time - -import httpx -import pytest - -from conftest import ADMIN_TEST_PASSWORD, ADMIN_TEST_USER, admin_cookies - -import auth -from main import app - -BASE = "http://test" -NOUS_KEY_PATH = "/api/keys/NOUS_API_KEY" - - -# ── Helpers ───────────────────────────────────────────────────────────────── - -class _FakeResult: - def mappings(self): - return self - - def all(self): - return [] - - def scalar(self): - return 0 - - def scalars(self): - return self - - def unique(self): - return self - - def one_or_none(self): - return None - - def scalar_one_or_none(self): - return None - - def __iter__(self): - return iter(()) - - -class _FakeSession: - async def __aenter__(self): - return self - - async def __aexit__(self, *exc): - return False - - async def execute(self, *args, **kwargs): - return _FakeResult() - - async def commit(self): - return None - - -def _fake_session(*args, **kwargs): - return _FakeSession() - - -@pytest.fixture() -def no_db(monkeypatch): - """Stub the DB session + key/settings stores so reads succeed offline.""" - import main - - monkeypatch.setattr(main, "async_session", _fake_session) - - async def _empty_keys(): - return [] - - async def _settings(): - return {"summary_model": "Hermes-4.3-36B", - "nous_base_url": "https://inference-api.nousresearch.com/v1"} - - async def _set_model(model: str): - return {"summary_model": model, - "nous_base_url": "https://inference-api.nousresearch.com/v1"} - - monkeypatch.setattr(main, "list_keys", _empty_keys) - monkeypatch.setattr(main, "get_app_settings", _settings) - monkeypatch.setattr(main, "set_summary_model", _set_model) - - -def _request(method: str, path: str, *, cookies=None, json=None, headers=None, - data=None) -> httpx.Response: - async def _run() -> httpx.Response: - transport = httpx.ASGITransport(app=app) - async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: - if cookies: - client.cookies.update(cookies) - return await client.request( - method, path, json=json, headers=headers, data=data, - ) - - return asyncio.run(_run()) - - -def _login(password: str = ADMIN_TEST_PASSWORD, username: str = ADMIN_TEST_USER, - headers=None, form: bool = True) -> httpx.Response: - if form: - return _request( - "POST", "/api/auth/login", - data={"username": username, "password": password}, headers=headers, - ) - return _request( - "POST", "/api/auth/login", json={"username": username, "password": password}, - headers=headers, - ) - - -# ── Anonymous: public reads ───────────────────────────────────────────────── - -def test_anonymous_can_read_news(no_db): - resp = _request("GET", "/api/news") - assert resp.status_code == 200 - assert resp.json() == [] - - -def test_anonymous_can_read_public_allowlist(no_db): - # Every documented public read must pass the gate (handler errors from the - # stubbed DB are irrelevant here — 401/403/redirects are the failure modes). - async def _run() -> dict[str, int]: - # raise_app_exceptions=False: handler errors from the stubbed DB are - # irrelevant here — 401/403/redirects are the failure modes. - transport = httpx.ASGITransport(app=app, raise_app_exceptions=False) - - out: dict[str, int] = {} - async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: - for path in ( - "/api/health", - "/api/map/layers", - "/api/map/chokepoints", - "/api/news", - "/api/news/ticker", - "/api/news/map", - "/api/geofences", - "/api/geofence-alerts", - "/api/analytics/summary", - "/api/tracks/range", - "/api/fire-aircraft", - ): - out[path] = (await client.get(path)).status_code - return out - - statuses = asyncio.run(_run()) - for path, status in statuses.items(): - assert status not in (401, 403, 307), f"{path} -> {status}" - - # DB-free reads answer for real. - for path in ("/api/news", "/api/map/layers", "/api/map/chokepoints"): - assert _request("GET", path).status_code == 200, path - - -SPEC_PUBLIC_READS = ( - "/api/health", "/api/ready", "/api/events", "/api/fires", "/api/sources", - "/api/entities", "/api/alerts", "/api/documents", - "/api/analytics/summary", "/api/analytics/timeline", - "/api/analytics/sentiment/by-source", "/api/cameras", - "/api/news", "/api/news/summaries", "/api/news/ticker", "/api/news/map", - "/api/map/layers", "/api/map/chokepoints", "/api/map/radar", - "/api/map/sentinel1", "/api/aircraft", "/api/aircraft/photo", - "/api/trains", "/api/vessels", "/api/tracks/range", "/api/geofences", - "/api/geofence-alerts", "/api/fire-aircraft", - "/api/events/11111111-1111-1111-1111-111111111111", - "/api/entities/11111111-1111-1111-1111-111111111111", - "/api/entities/11111111-1111-1111-1111-111111111111/events", - "/api/cameras/abc", "/api/cameras/abc/snapshot", - "/api/cameras/abc/stream", "/api/cameras/abc/hls.m3u8", - "/api/cameras/abc/hlsseg", -) - - -def test_public_allowlist_covers_the_spec(): - for path in SPEC_PUBLIC_READS: - assert auth.is_public(path, "GET"), path - - -def test_public_post_search_is_read_only(no_db): - resp = _request("POST", "/api/search", json={"q": "fire", "limit": 5}) - assert resp.status_code not in (401, 403) - - -def test_anonymous_can_load_hud(): - resp = _request("GET", "/") - assert resp.status_code == 200 - assert "text/html" in resp.headers["content-type"] - assert "OSINT" in resp.text - assert 'id="view-map"' in resp.text - - -def test_login_page_is_public(): - resp = _request("GET", "/login") - assert resp.status_code == 200 - assert "Sign in" in resp.text - assert resp.headers.get("cache-control") == "no-store" - assert 'name="username"' in resp.text and 'name="password"' in resp.text - assert "/api/auth/login" in resp.text - - -def test_hud_gates_admin_chrome_client_side(): - """Spec item 5: UX hiding is markup-driven and fails closed.""" - html = _request("GET", "/").text - # Fails closed without JS: data-admin is hidden unless body.is-admin. - assert "body:not(.is-admin) [data-admin]" in html - # Admin nav entries (API Keys is the headline requirement) are marked. - for view in ("keys", "ingest", "settings"): - assert f'data-view="{view}" data-admin' in html, view - # Keys view, ingest view and the summarizer panel are gated too. - assert 'id="view-keys" aria-label="API keys" data-admin' in html - assert 'id="view-ingest" aria-label="Ingest" data-admin' in html - # Discreet sign-in link + the /api/auth/me probe that reveals admin chrome. - assert 'id="admin-link"' in html and 'href="/login"' in html - assert "/api/auth/me" in html - - -def test_static_assets_are_public(): - assert _request("GET", "/static/index.html").status_code == 200 - - -# ── Anonymous: admin surface is closed ────────────────────────────────────── - -def test_anonymous_keys_read_is_401(): - resp = _request("GET", "/api/keys") - assert resp.status_code == 401 - assert resp.headers["content-type"].startswith("application/json") - assert "detail" in resp.json() - - -def test_anonymous_keys_write_is_401(): - resp = _request("POST", NOUS_KEY_PATH, json={"value": "sk-nope-1234567890"}) - assert resp.status_code == 401 - - -def test_anonymous_keys_delete_is_401(): - assert _request("DELETE", NOUS_KEY_PATH).status_code == 401 - - -def test_anonymous_settings_write_is_401(): - resp = _request("PUT", "/api/settings", json={"summary_model": "x/y-z"}) - assert resp.status_code == 401 - - -def test_anonymous_settings_read_is_401(): - assert _request("GET", "/api/settings").status_code == 401 - - -def test_anonymous_news_models_is_401(): - # /api/news/models spends the stored Nous key — never public. - assert _request("GET", "/api/news/models").status_code == 401 - - -def test_anonymous_state_changing_routes_are_401(): - cases = [ - ("POST", "/api/sources", {"name": "x", "url": "https://example.com/feed", "source_type": "rss"}), - ("POST", "/api/events", {"source_type": "rss", "title": "x"}), - ("POST", "/api/entities", {"name": "x", "entity_type": "person"}), - ("POST", "/api/alerts", {"alert_type": "keyword", "severity": "low", "title": "x"}), - ("POST", "/api/geofences", {"name": "x", "geojson": {"type": "Point", "coordinates": [0, 0]}}), - ("PATCH", "/api/geofences/abc", {"name": "y"}), - ("DELETE", "/api/geofences/abc", None), - ("POST", "/api/vessels/subscribe", {"bbox": "-70,40,-60,45"}), - ("POST", "/api/ingest/rss", None), - ("POST", "/api/ingest/earthquakes", None), - ("POST", "/api/ingest/process", None), - ] - for method, path, body in cases: - resp = _request(method, path, json=body) - assert resp.status_code == 401, f"{method} {path} -> {resp.status_code}" - - -def test_unknown_api_path_is_denied_anonymously(): - assert _request("GET", "/api/does-not-exist").status_code == 401 - - -# ── /api/auth/me ──────────────────────────────────────────────────────────── - -def test_auth_me_anonymous(): - resp = _request("GET", "/api/auth/me") - assert resp.status_code == 200 - assert resp.json() == {"authenticated": False, "admin": False} - - -def test_auth_me_with_session(): - resp = _request("GET", "/api/auth/me", cookies=admin_cookies()) - assert resp.status_code == 200 - assert resp.json() == {"authenticated": True, "admin": True} - - -# ── Login / logout ────────────────────────────────────────────────────────── - -def test_login_wrong_password_is_401(): - resp = _login(password="wrong-password") - assert resp.status_code == 401 - assert "invalid credentials" in resp.json()["detail"] - assert auth.COOKIE_NAME not in resp.cookies - - -def test_login_wrong_username_is_401(): - resp = _login(username="root") - assert resp.status_code == 401 - # Generic message: never reveal which half was wrong / that the user exists. - assert "root" not in resp.text - - -def test_login_missing_fields_is_401_not_500(): - resp = _request("POST", "/api/auth/login", data={}) - assert resp.status_code == 401 - - -def test_login_success_sets_httponly_cookie(): - resp = _login() - assert resp.status_code == 200 - assert resp.json() == {"authenticated": True, "admin": True} - raw = resp.headers.get("set-cookie", "") - assert auth.COOKIE_NAME in raw - assert "HttpOnly" in raw - assert "SameSite=lax" in raw.replace("samesite=lax", "SameSite=lax") - assert "Path=/" in raw - assert "Secure" not in raw # plain http in tests - assert resp.cookies.get(auth.COOKIE_NAME) - - -def test_login_accepts_json_body(): - resp = _login(form=False) - assert resp.status_code == 200 - assert resp.json()["authenticated"] is True - - -def test_login_cookie_marks_secure_behind_https_proxy(): - resp = _login(headers={"X-Forwarded-Proto": "https"}) - assert resp.status_code == 200 - assert "Secure" in resp.headers.get("set-cookie", "") - - -def test_session_cookie_unlocks_admin_routes(no_db): - login = _login() - cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)} - assert _request("GET", "/api/keys", cookies=cookie).status_code == 200 - assert _request("PUT", "/api/settings", - json={"summary_model": "m"}, cookies=cookie).status_code == 200 - assert _request("GET", "/api/settings", cookies=cookie).status_code == 200 - - -def test_logout_clears_session(no_db): - login = _login() - cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)} - out = _request("POST", "/api/auth/logout", cookies=cookie) - assert out.status_code == 200 - assert out.json() == {"authenticated": False, "admin": False} - assert "Max-Age=0" in out.headers.get("set-cookie", "") or "expires" in \ - out.headers.get("set-cookie", "").lower() - # A cleared cookie no longer authenticates (simulate the browser dropping it). - assert _request("GET", "/api/keys", cookies={}).status_code == 401 - - -def test_tampered_cookie_is_401(): - login = _login() - token = login.cookies.get(auth.COOKIE_NAME) - body, signature = token.rsplit(".", 1) - tampered = f"{body}.{'A' * len(signature)}" - assert _request("GET", "/api/keys", cookies={auth.COOKIE_NAME: tampered}).status_code == 401 - - -def test_cookie_for_another_user_is_401(monkeypatch): - forged = auth.create_session_token("intruder") - assert _request("GET", "/api/keys", - cookies={auth.COOKIE_NAME: forged}).status_code == 401 - - -def test_expired_token_is_rejected(): - token = auth.create_session_token(ADMIN_TEST_USER, now=time.time() - auth.SESSION_TTL_SECONDS - 5) - assert auth.verify_session_token(token) is None - - -# ── Fail closed ───────────────────────────────────────────────────────────── - -def test_admin_env_unset_fails_closed(monkeypatch, no_db): - monkeypatch.delenv("ADMIN_PASSWORD_HASH", raising=False) - monkeypatch.delenv("ADMIN_SESSION_SECRET", raising=False) - - resp = _request("GET", "/api/keys") - assert resp.status_code == 403 - assert resp.json() == {"detail": "admin auth not configured"} - - # Public site keeps working, and /login explains the situation. - assert _request("GET", "/api/news").status_code == 200 - page = _request("GET", "/login") - assert page.status_code == 200 - assert "not configured" in page.text - - -def test_login_without_password_hash_is_403(monkeypatch): - monkeypatch.delenv("ADMIN_PASSWORD_HASH", raising=False) - resp = _login() - assert resp.status_code == 403 - assert resp.json() == {"detail": "admin auth not configured"} - - -def test_session_secret_unset_invalidates_existing_cookie(monkeypatch): - cookie = admin_cookies() - monkeypatch.delenv("ADMIN_SESSION_SECRET", raising=False) - resp = _request("GET", "/api/keys", cookies=cookie) - assert resp.status_code == 403 - assert resp.json() == {"detail": "admin auth not configured"} - - -# ── Rate limiting ─────────────────────────────────────────────────────────── - -def test_rate_limit_after_five_failures(): - for attempt in range(5): - assert _login(password="nope").status_code == 401, f"attempt {attempt}" - assert _login(password="nope").status_code == 429 - # Correct credentials are refused too while the window is open. - assert _login().status_code == 429 - - -def test_rate_limit_is_per_client_ip(): - for _ in range(5): - _login(password="nope", headers={"X-Forwarded-For": "203.0.113.9"}) - assert _login(password="nope", headers={"X-Forwarded-For": "203.0.113.9"}).status_code == 429 - # A different client is unaffected. - assert _login(password="nope", headers={"X-Forwarded-For": "203.0.113.10"}).status_code == 401 - - -def test_logout_does_not_reset_the_login_limiter(): - """Regression: logout is unauthenticated — it must not clear lockouts.""" - for _ in range(5): - assert _login(password="nope").status_code == 401 - assert _request("POST", "/api/auth/logout").status_code == 200 - assert _login().status_code == 429 - - -def test_non_ascii_garbage_cookie_is_rejected_not_500(): - assert auth.verify_session_token("abc.\u00e9\u00e9\u00e9") is None - assert auth.verify_session_token("\u00e9\u00e9\u00e9") is None - resp = _request("GET", "/api/keys", cookies={auth.COOKIE_NAME: "garbage"}) - assert resp.status_code == 401 - - -# ── CSRF ──────────────────────────────────────────────────────────────────── - -def test_cross_origin_admin_write_is_403(no_db): - cookies = admin_cookies() - resp = _request("PUT", "/api/settings", json={"summary_model": "m"}, - cookies=cookies, headers={"Origin": "https://evil.example"}) - assert resp.status_code == 403 - assert "cross-origin" in resp.json()["detail"] - - -def test_same_origin_admin_write_is_allowed(no_db): - cookies = admin_cookies() - resp = _request("PUT", "/api/settings", json={"summary_model": "m"}, - cookies=cookies, headers={"Origin": BASE}) - assert resp.status_code == 200 - - -def test_same_host_referer_admin_write_is_allowed(no_db): - cookies = admin_cookies() - resp = _request("PUT", "/api/settings", json={"summary_model": "m"}, - cookies=cookies, headers={"Referer": f"{BASE}/login"}) - assert resp.status_code == 200 - - -# ── Unit: hashing + token helpers ─────────────────────────────────────────── - -def test_password_hash_round_trip(): - stored = auth.hash_password("s3cret-pw", iterations=2000) - assert stored.startswith("pbkdf2_sha256$") - assert auth.verify_password("s3cret-pw", stored) - assert not auth.verify_password("s3cret-pW", stored) - assert not auth.verify_password("", stored) - - -def test_password_hash_rejects_malformed_values(): - for bad in ("", "plain", "pbkdf2_sha256$abc$x$y", "md5$1$a$b", - "pbkdf2_sha256$0$AAAA$AAAA"): - assert not auth.verify_password("x", bad) - - -def test_session_token_round_trip(): - token = auth.create_session_token(ADMIN_TEST_USER) - assert auth.verify_session_token(token) == ADMIN_TEST_USER - assert auth.verify_session_token(token + "x") is None - assert auth.verify_session_token(None) is None - - -def test_public_allowlist_classification(): - assert auth.is_public("/api/news", "GET") - assert auth.is_public("/api/news/", "GET") - assert auth.is_public("/api/events/abc-123", "GET") - assert auth.is_public("/api/cameras/abc/hls.m3u8", "GET") - assert auth.is_public("/api/search", "POST") - assert not auth.is_public("/api/news/models", "GET") - assert not auth.is_public("/api/keys", "GET") - assert not auth.is_public("/api/settings", "GET") - assert not auth.is_public("/api/ingest/rss", "POST") - assert not auth.is_public("/api/vessels/subscribe", "POST") - assert not auth.is_public("/api/geofences", "POST") - assert auth.is_public("/ws/live", "GET") diff --git a/tests/test_ingest_ssrf_and_sources.py b/tests/test_ingest_ssrf_and_sources.py index 16683a1..21c85b2 100644 --- a/tests/test_ingest_ssrf_and_sources.py +++ b/tests/test_ingest_ssrf_and_sources.py @@ -10,8 +10,6 @@ from pydantic import ValidationError from main import app -from conftest import admin_cookies - BASE = "http://test" LINK_LOCAL_META = "http://169.254.169.254/latest/meta-data/" LOOPBACK = "http://127.0.0.1/secret" @@ -20,7 +18,6 @@ LOOPBACK = "http://127.0.0.1/secret" async def _req(method: str, path: str, **kw) -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: - client.cookies.update(admin_cookies()) return await client.request(method, path, **kw) diff --git a/tests/test_phase2_api.py b/tests/test_phase2_api.py index b7e7157..2afead2 100644 --- a/tests/test_phase2_api.py +++ b/tests/test_phase2_api.py @@ -8,15 +8,12 @@ import httpx from main import app -from conftest import admin_cookies - BASE = "http://test" async def _req(method: str, path: str, **kw) -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: - client.cookies.update(admin_cookies()) return await client.request(method, path, **kw)