feat(auth): public read-only HUD, admin-only API keys and mutations
Adds single-admin authentication to the dashboard. Anonymous visitors get a
read-only site (map + news); the one admin unlocks everything else.
- app/auth.py: deny-by-default ASGI middleware on /api/* with an explicit
public read allowlist; /login page; /api/auth/{login,logout,me}; PBKDF2
password hashing; HMAC-signed HttpOnly SameSite=Lax session cookie (7d,
Secure behind X-Forwarded-Proto: https); 5-fail/15-min per-IP login limit;
Origin/Referer host check on state-changing admin requests.
- Fails closed: missing ADMIN_PASSWORD_HASH or ADMIN_SESSION_SECRET -> admin
routes 403 'admin auth not configured', public site unaffected.
- app/main.py: mounts the middleware + router (6 lines, no per-route decorators).
- app/static/index.html: hides Ingest/API Keys/Settings, the summarizer panel
and geofence write controls until /api/auth/me says admin; adds a discreet
SIGN IN link to /login. CSS gates fail closed without JS.
- tests/test_auth.py: 42 tests (anonymous 401s, login/logout, tampered and
expired cookies, fail-closed, rate limit, CSRF, HUD markup).
- Existing API tests now send an admin session cookie for admin routes.
Public allowlist extends the spec's list with the remaining read-only GETs the
HUD calls (/api/stats, /api/conflicts, /api/place, /api/satellites,
/api/infrastructure, /api/map/gpsjam, /api/map/times, /api/fire-incidents,
/api/fire-perimeters, /api/weather-alerts, /api/storms, /api/geofences/{id}/at)
so an anonymous HUD is not half-broken.
This commit is contained in:
parent
38eb4fe4d6
commit
c0a2454fdd
11 changed files with 1283 additions and 14 deletions
574
app/auth.py
Normal file
574
app/auth.py
Normal file
|
|
@ -0,0 +1,574 @@
|
|||
"""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$<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",
|
||||
# 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$<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"
|
||||
|
||||
|
||||
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 = """<!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:]))
|
||||
|
|
@ -34,6 +34,7 @@ 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,
|
||||
|
|
@ -116,6 +117,11 @@ 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"
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -157,6 +157,20 @@
|
|||
.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 */
|
||||
|
|
@ -875,6 +889,7 @@
|
|||
<span class="sep hide-sm" id="swpc-sep" hidden>|</span>
|
||||
<span class="hide-sm" id="swpc-chip" hidden title="NOAA SWPC planetary K-index">Kp —</span>
|
||||
</div>
|
||||
<a class="admin-link" id="admin-link" href="/login" data-anon-label="SIGN IN">SIGN IN</a>
|
||||
<div class="nav">
|
||||
<button id="nav-btn" class="nav-btn" aria-haspopup="true" aria-expanded="false">
|
||||
MENU <span class="nav-caret">▾</span>
|
||||
|
|
@ -886,10 +901,10 @@
|
|||
<button class="nav-item" role="menuitem" data-view="events"><span class="ico">≣</span>Events</button>
|
||||
<button class="nav-item" role="menuitem" data-view="alerts"><span class="ico">⚠</span>Alerts</button>
|
||||
<button class="nav-item" role="menuitem" data-view="entities"><span class="ico">◎</span>Entities</button>
|
||||
<button class="nav-item" role="menuitem" data-view="ingest"><span class="ico">⇪</span>Ingest</button>
|
||||
<button class="nav-item" role="menuitem" data-view="keys"><span class="ico">⚿</span>API Keys</button>
|
||||
<div class="nav-sep" role="separator"></div>
|
||||
<button class="nav-item" role="menuitem" data-view="settings"><span class="ico">⚙</span>Settings</button>
|
||||
<button class="nav-item" role="menuitem" data-view="ingest" data-admin><span class="ico">⇪</span>Ingest</button>
|
||||
<button class="nav-item" role="menuitem" data-view="keys" data-admin><span class="ico">⚿</span>API Keys</button>
|
||||
<div class="nav-sep" role="separator" data-admin></div>
|
||||
<button class="nav-item" role="menuitem" data-view="settings" data-admin><span class="ico">⚙</span>Settings</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -933,7 +948,7 @@
|
|||
<div class="lp-opacity">Opacity <input type="range" id="lp-base-opacity" min="5" max="100" value="100" oninput="setBaseOpacity(this.value)"><b id="lp-base-val">100%</b></div>
|
||||
</div>
|
||||
<div class="lp-layer">
|
||||
<div class="lp-row gf-draw-row">
|
||||
<div class="lp-row gf-draw-row" data-admin>
|
||||
<button class="btn" id="gf-draw" type="button" onclick="toggleGeofenceDraw()" title="Tap vertices, then Finish">Draw geofence</button>
|
||||
<button class="btn" id="gf-finish" type="button" hidden onclick="onGfClose(event)">Finish</button>
|
||||
<button class="btn" id="gf-cancel" type="button" hidden onclick="cancelGeofenceDraw()">Cancel</button>
|
||||
|
|
@ -1238,7 +1253,7 @@
|
|||
</section>
|
||||
|
||||
<!-- ───────────── VIEW: INGEST ───────────── -->
|
||||
<section class="view" id="view-ingest" aria-label="Ingest">
|
||||
<section class="view" id="view-ingest" aria-label="Ingest" data-admin>
|
||||
<div class="subview">
|
||||
<h2><span class="tick">⇪</span> Data Ingestion</h2>
|
||||
<p class="sub">Manually trigger feed pulls & NATS processing</p>
|
||||
|
|
@ -1271,7 +1286,7 @@
|
|||
</section>
|
||||
|
||||
<!-- ───────────── VIEW: API KEYS ───────────── -->
|
||||
<section class="view" id="view-keys" aria-label="API keys">
|
||||
<section class="view" id="view-keys" aria-label="API keys" data-admin>
|
||||
<div class="subview">
|
||||
<h2><span class="tick">⚿</span> API Keys</h2>
|
||||
<p class="sub">Keys used by ingest services (FIRMS, Nous Portal, Telegram, AIS, …). Stored in Postgres, never shown again — only status + last 4 chars.</p>
|
||||
|
|
@ -1298,7 +1313,7 @@
|
|||
</div>
|
||||
<div class="set-saved" id="mkt-saved"></div>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<div class="panel" data-admin>
|
||||
<h3>News Summarizer</h3>
|
||||
<p class="set-note" style="margin-bottom:0.9rem">Takes effect on the next 15-min run. No container restart.</p>
|
||||
<div class="set-row">
|
||||
|
|
@ -1626,6 +1641,40 @@ 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'];
|
||||
|
||||
|
|
@ -1672,6 +1721,7 @@ 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);
|
||||
});
|
||||
|
|
@ -4154,6 +4204,8 @@ async function loadConflicts(paint) {
|
|||
}
|
||||
|
||||
/* ═══════════════ INITIAL LOAD ═══════════════ */
|
||||
document.getElementById('admin-link').addEventListener('click', onAdminLink);
|
||||
initAuth();
|
||||
initNav();
|
||||
initHudKeys();
|
||||
initSettings();
|
||||
|
|
@ -4493,13 +4545,13 @@ async function loadGeofences() {
|
|||
const on = f.active === false ? '' : ' checked';
|
||||
const sel = f.id === gfSelectedId ? ' selected' : '';
|
||||
return `<div class="gf-item${sel}" data-id="${id}">` +
|
||||
`<input class="gf-active" type="checkbox"${on} aria-label="Active" ` +
|
||||
`<input class="gf-active" type="checkbox"${on} aria-label="Active" data-admin ` +
|
||||
`onchange="patchGfActive('${id}', this.checked)">` +
|
||||
`<button type="button" class="gf-name" title="${name}" onclick="onGfNameClick('${id}')">${name}</button>` +
|
||||
`<span class="gf-actions">` +
|
||||
`<button class="gf-go" type="button" onclick="goGeofence('${id}')">Go</button>` +
|
||||
`<button class="gf-ren" type="button" aria-label="Rename" onclick="renameGeofence('${id}')">Aa</button>` +
|
||||
`<button class="gf-del" type="button" onclick="deleteGeofence('${id}')">Delete</button>` +
|
||||
`<button class="gf-ren" type="button" aria-label="Rename" data-admin onclick="renameGeofence('${id}')">Aa</button>` +
|
||||
`<button class="gf-del" type="button" data-admin onclick="deleteGeofence('${id}')">Delete</button>` +
|
||||
`</span></div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
|
@ -4524,8 +4576,8 @@ async function loadGeofences() {
|
|||
const chk = active ? ' checked' : '';
|
||||
layer.bindPopup(
|
||||
`<div class="gf-pop"><b>${name}</b><br>` +
|
||||
`<label><input type="checkbox"${chk} onchange="patchGfActive('${newsEsc(id)}', this.checked)"> active</label><br>` +
|
||||
`<button class="gf-del" type="button" onclick="deleteGeofence('${newsEsc(id)}')">Delete</button></div>`
|
||||
`<label data-admin><input type="checkbox"${chk} onchange="patchGfActive('${newsEsc(id)}', this.checked)"> active</label><br>` +
|
||||
`<button class="gf-del" type="button" data-admin onclick="deleteGeofence('${newsEsc(id)}')">Delete</button></div>`
|
||||
);
|
||||
},
|
||||
}).addTo(map);
|
||||
|
|
|
|||
Loading…
Reference in a new issue