feat(auth): public read-only HUD, admin-only API keys and mutations #50

Merged
sirius merged 1 commit from feat/public-hud-admin-auth into master 2026-11-14 02:05:20 +00:00
Owner

What this does

Implements the spec public read-only HUD, admin-only API keys (single admin).

  • Anonymous visitors get the map and the news brief, read-only.
  • The one admin (you) additionally gets API Keys, Settings, Ingest, the summarizer model control, geofence draw/edit/delete and every state-changing route.

Enforcement is deny-by-default on /api/* with an explicit public read allowlist in one place — app/auth.py (AdminAuthMiddleware + PUBLIC_GET_EXACT / PUBLIC_GET_PATTERNS / PUBLIC_POST_EXACT). app/main.py gains exactly 6 lines (middleware + router); no per-route decorators, no CSS-only hiding.

Auth surface

Route Anonymous Admin
GET /, GET /login, GET /static/*, WS /ws/live ✅ ✅
Read allowlist (/api/news*, /api/map/*, /api/events, /api/entities, /api/alerts, /api/analytics/*, /api/cameras*, /api/vessels, /api/tracks/range, /api/geofences* reads, POST /api/search, …) ✅ ✅
GET/POST/DELETE /api/keys*, GET/PUT /api/settings, GET /api/news/models 401 JSON ✅
Every other POST/PATCH/PUT/DELETE (sources, events, entities, alerts, geofences, /api/vessels/subscribe, all /api/ingest/*) 401 JSON ✅
  • GET /login — server-rendered form (no build step, no framework), posts to /api/auth/login, dark HUD styling.
  • POST /api/auth/login — form-encoded or JSON; success → {"authenticated": true, "admin": true} + Set-Cookie; failure → 401 {"detail": "invalid credentials"} (generic: never reveals which half was wrong).
  • POST /api/auth/logout — clears the cookie.
  • GET /api/auth/me — always 200, {"authenticated": bool, "admin": bool}.

Credentials, exact env names (cluster Secret osint-admin):

  • ADMIN_USER
  • ADMIN_PASSWORD_HASH — stdlib hashlib.pbkdf2_hmac, format pbkdf2_sha256$<iters>$<salt_b64>$<hash_b64>, constant-time compare. No new dependency. Generate: python app/auth.py hash 'your password'.
  • ADMIN_SESSION_SECRET — HMAC-SHA256 key. Generate: python -c 'import secrets; print(secrets.token_urlsafe(48))'.

Cookie osint_session: HttpOnly, SameSite=Lax, Path=/, 7-day expiry carrying iat/exp, Secure when X-Forwarded-Proto: https (Cloudflare). Signature verified with hmac.compare_digest; a token for a different username or signed with another secret is rejected.

Hard requirements implemented:

  1. Fail closed — missing/empty ADMIN_PASSWORD_HASH or ADMIN_SESSION_SECRET ⇒ admin routes 403 {"detail": "admin auth not configured"}, /login says so, login POST 403, public site untouched. No default password, no bypass.
  2. Login rate limit — 5 failures per client IP (X-Forwarded-For first hop, else peer) per 15 min → 429. In-memory (single replica). POST /api/auth/logout deliberately does not clear the limiter (regression-tested — it is unauthenticated).
  3. CSRF — state-changing admin requests carrying Origin/Referer must match the request host (X-Forwarded-Host aware), else 403. Header-less clients (curl, service-to-service) rely on the signed SameSite=Lax cookie; documented in docs/auth.md.
  4. GET /api/keys untouched — still set/missing + last-4 only.
  5. HUD — body:not(.is-admin) [data-admin] hides the Ingest / API Keys / Settings nav entries, the Keys view, the Ingest view, the summarizer panel and the geofence draw/rename/delete controls. initAuth() adds .is-admin only when /api/auth/me says admin; anonymous visitors get a discreet SIGN IN link to /login. CSS gates fail closed with JS disabled. UX only — the API is the real gate.

Verification (actually run)

Suite with no database (bare checkout): 333 passed, 17 skipped — the 17 are exactly the integration-marked tests auto-skipping with test database unreachable (set DB_* env or start the PG container):

tests/test_api_fires.py: 5   tests/test_api_news.py: 9
tests/test_fire_ingest.py: 2 tests/test_api_settings.py: 1

Suite against a live TimescaleDB+PostGIS (started osint-dashboard-pg on 127.0.0.1:55432, alembic upgrade head): 350 passed, 0 skipped — all integration tests included.

tests/test_auth.py (43 tests) covers the whole matrix via httpx.ASGITransport: anonymous GET /api/news 200 / GET /api/keys 401 / POST /api/keys/NOUS_API_KEY 401 / PUT /api/settings 401; anonymous GET / 200 containing the HUD; /api/auth/me false; wrong password 401; correct password 200 + Set-Cookie (HttpOnly/SameSite/Path asserted, Secure under X-Forwarded-Proto: https); cookie unlocks GET /api/keys + PUT /api/settings; logout ⇒ 401; tampered, foreign-user, expired and non-ASCII cookies rejected; env unset ⇒ keys 403 while news stays 200; 6 rapid failures ⇒ 429; CSRF cross-origin 403 vs same-origin 200; public allowlist classification; HUD data-admin markup.

Manual proof — real uvicorn main:app --port 8099 with the three env vars and a live DB (actual status codes):

anon GET  /api/news          -> 200
anon GET  /api/keys          -> 401
anon GET  /                  -> 200
anon GET  /api/auth/me       -> {"authenticated":false,"admin":false}
anon POST /api/ingest/earthquakes -> 401
POST /api/auth/login (form)  -> 200, Set-Cookie: osint_session=...; HttpOnly; Max-Age=604800; Path=/; SameSite=lax
GET  /api/keys   (cookie)    -> 200
GET  /api/settings (cookie)  -> 200
POST /api/auth/logout        -> 200
GET  /api/keys after logout  -> 401
tampered cookie              -> 401
wrong password               -> 401
5 failed logins then correct -> 429
PUT /api/settings, Origin: https://evil.example (cookie) -> 403
PUT /api/settings, same-origin (cookie)                 -> 200

Anonymous sweep of every public read (37 GETs + POST /api/search) returned 200 or a handler-level 422 for missing params — never 401/403. Fail-closed verified live on a second instance started without ADMIN_*: /api/keys → 403 {"detail":"admin auth not configured"}, /api/news → 200, /login renders the "not configured" notice.

Premise flags (code disagreed with the card)

  • The card's public list omits read-only endpoints the HUD itself calls. Denying them would ship a half-broken anonymous map, so these reads are also public: GET /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. All were audited as pure reads (no writes, no stored-key spend).
  • POST /api/search is a read-only tsvector query → public, as the card assumed.
  • Nothing in the card's public list mutates state.
  • HUD is a single file (app/static/index.html) — gated in place.
  • Existing API tests that hit admin routes (test_api_settings, test_api_live_layers, test_ingest_ssrf_and_sources, test_phase2_api) now send an admin session cookie from a shared conftest.admin_cookies() helper; a session-scoped test credential pair is seeded in conftest.py.

Non-goals respected

No user table/RBAC/OAuth/Cloudflare Access, no alembic migration, no changes to news/*, Dockerfile*, docker-compose.yml, .forgejo/workflows/*, ingester/camera/summarizer processes, no account seeder, no cluster credentials.

docs/auth.md documents the surface, env vars and controls; .env.example gains the three ADMIN_* placeholders.

Operator follow-up (after merge — this PR is not merged here)

  1. Create Secret osint-admin in namespace osint with ADMIN_USER, ADMIN_PASSWORD_HASH, ADMIN_SESSION_SECRET.
  2. Rebuild the amd64 image and bump the pin in sirius/homek8s apps/base/osint/ (add the Secret as envFrom). Merge here does not deploy — and the push to master will fire the legacy compose workflow on the Pi, which is why the operator merges, not CI.
## What this does Implements the spec **public read-only HUD, admin-only API keys (single admin)**. * **Anonymous visitors** get the map and the news brief, read-only. * **The one admin** (you) additionally gets API Keys, Settings, Ingest, the summarizer model control, geofence draw/edit/delete and every state-changing route. Enforcement is **deny-by-default on `/api/*`** with an explicit public read allowlist in one place — `app/auth.py` (`AdminAuthMiddleware` + `PUBLIC_GET_EXACT` / `PUBLIC_GET_PATTERNS` / `PUBLIC_POST_EXACT`). `app/main.py` gains exactly 6 lines (middleware + router); no per-route decorators, no CSS-only hiding. ## Auth surface | Route | Anonymous | Admin | | --- | --- | --- | | `GET /`, `GET /login`, `GET /static/*`, `WS /ws/live` | ✅ | ✅ | | Read allowlist (`/api/news*`, `/api/map/*`, `/api/events`, `/api/entities`, `/api/alerts`, `/api/analytics/*`, `/api/cameras*`, `/api/vessels`, `/api/tracks/range`, `/api/geofences*` reads, `POST /api/search`, …) | ✅ | ✅ | | `GET/POST/DELETE /api/keys*`, `GET/PUT /api/settings`, `GET /api/news/models` | `401` JSON | ✅ | | Every other `POST/PATCH/PUT/DELETE` (sources, events, entities, alerts, geofences, `/api/vessels/subscribe`, all `/api/ingest/*`) | `401` JSON | ✅ | * `GET /login` — server-rendered form (no build step, no framework), posts to `/api/auth/login`, dark HUD styling. * `POST /api/auth/login` — form-encoded **or** JSON; success → `{"authenticated": true, "admin": true}` + `Set-Cookie`; failure → `401 {"detail": "invalid credentials"}` (generic: never reveals which half was wrong). * `POST /api/auth/logout` — clears the cookie. * `GET /api/auth/me` — always `200`, `{"authenticated": bool, "admin": bool}`. Credentials, exact env names (cluster Secret `osint-admin`): * `ADMIN_USER` * `ADMIN_PASSWORD_HASH` — stdlib `hashlib.pbkdf2_hmac`, format `pbkdf2_sha256$<iters>$<salt_b64>$<hash_b64>`, constant-time compare. **No new dependency.** Generate: `python app/auth.py hash 'your password'`. * `ADMIN_SESSION_SECRET` — HMAC-SHA256 key. Generate: `python -c 'import secrets; print(secrets.token_urlsafe(48))'`. Cookie `osint_session`: `HttpOnly`, `SameSite=Lax`, `Path=/`, 7-day expiry carrying `iat`/`exp`, `Secure` when `X-Forwarded-Proto: https` (Cloudflare). Signature verified with `hmac.compare_digest`; a token for a different username or signed with another secret is rejected. Hard requirements implemented: 1. **Fail closed** — missing/empty `ADMIN_PASSWORD_HASH` *or* `ADMIN_SESSION_SECRET` ⇒ admin routes `403 {"detail": "admin auth not configured"}`, `/login` says so, login POST 403, public site untouched. No default password, no bypass. 2. **Login rate limit** — 5 failures per client IP (`X-Forwarded-For` first hop, else peer) per 15 min → `429`. In-memory (single replica). `POST /api/auth/logout` deliberately does **not** clear the limiter (regression-tested — it is unauthenticated). 3. **CSRF** — state-changing admin requests carrying `Origin`/`Referer` must match the request host (`X-Forwarded-Host` aware), else `403`. Header-less clients (curl, service-to-service) rely on the signed SameSite=Lax cookie; documented in `docs/auth.md`. 4. `GET /api/keys` untouched — still set/missing + last-4 only. 5. **HUD** — `body:not(.is-admin) [data-admin]` hides the Ingest / **API Keys** / Settings nav entries, the Keys view, the Ingest view, the summarizer panel and the geofence draw/rename/delete controls. `initAuth()` adds `.is-admin` only when `/api/auth/me` says admin; anonymous visitors get a discreet `SIGN IN` link to `/login`. CSS gates fail closed with JS disabled. UX only — the API is the real gate. ## Verification (actually run) **Suite with no database** (bare checkout): `333 passed, 17 skipped` — the 17 are exactly the `integration`-marked tests auto-skipping with `test database unreachable (set DB_* env or start the PG container)`: ``` tests/test_api_fires.py: 5 tests/test_api_news.py: 9 tests/test_fire_ingest.py: 2 tests/test_api_settings.py: 1 ``` **Suite against a live TimescaleDB+PostGIS** (started `osint-dashboard-pg` on `127.0.0.1:55432`, `alembic upgrade head`): `350 passed, 0 skipped` — all integration tests included. `tests/test_auth.py` (43 tests) covers the whole matrix via `httpx.ASGITransport`: anonymous `GET /api/news` 200 / `GET /api/keys` 401 / `POST /api/keys/NOUS_API_KEY` 401 / `PUT /api/settings` 401; anonymous `GET /` 200 containing the HUD; `/api/auth/me` false; wrong password 401; correct password 200 + `Set-Cookie` (HttpOnly/SameSite/Path asserted, `Secure` under `X-Forwarded-Proto: https`); cookie unlocks `GET /api/keys` + `PUT /api/settings`; logout ⇒ 401; tampered, foreign-user, expired and non-ASCII cookies rejected; env unset ⇒ keys 403 while news stays 200; 6 rapid failures ⇒ 429; CSRF cross-origin 403 vs same-origin 200; public allowlist classification; HUD `data-admin` markup. **Manual proof — real `uvicorn main:app --port 8099` with the three env vars and a live DB** (actual status codes): ``` anon GET /api/news -> 200 anon GET /api/keys -> 401 anon GET / -> 200 anon GET /api/auth/me -> {"authenticated":false,"admin":false} anon POST /api/ingest/earthquakes -> 401 POST /api/auth/login (form) -> 200, Set-Cookie: osint_session=...; HttpOnly; Max-Age=604800; Path=/; SameSite=lax GET /api/keys (cookie) -> 200 GET /api/settings (cookie) -> 200 POST /api/auth/logout -> 200 GET /api/keys after logout -> 401 tampered cookie -> 401 wrong password -> 401 5 failed logins then correct -> 429 PUT /api/settings, Origin: https://evil.example (cookie) -> 403 PUT /api/settings, same-origin (cookie) -> 200 ``` Anonymous sweep of every public read (37 GETs + `POST /api/search`) returned `200` or a handler-level `422` for missing params — never `401`/`403`. Fail-closed verified live on a second instance started **without** `ADMIN_*`: `/api/keys` → `403 {"detail":"admin auth not configured"}`, `/api/news` → `200`, `/login` renders the "not configured" notice. ## Premise flags (code disagreed with the card) * The card's public list omits read-only endpoints the HUD itself calls. Denying them would ship a half-broken anonymous map, so these **reads** are also public: `GET /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`. All were audited as pure reads (no writes, no stored-key spend). * `POST /api/search` is a read-only tsvector query → public, as the card assumed. * Nothing in the card's public list mutates state. * HUD is a single file (`app/static/index.html`) — gated in place. * Existing API tests that hit admin routes (`test_api_settings`, `test_api_live_layers`, `test_ingest_ssrf_and_sources`, `test_phase2_api`) now send an admin session cookie from a shared `conftest.admin_cookies()` helper; a session-scoped test credential pair is seeded in `conftest.py`. ## Non-goals respected No user table/RBAC/OAuth/Cloudflare Access, no alembic migration, no changes to `news/*`, `Dockerfile*`, `docker-compose.yml`, `.forgejo/workflows/*`, ingester/camera/summarizer processes, no account seeder, no cluster credentials. `docs/auth.md` documents the surface, env vars and controls; `.env.example` gains the three `ADMIN_*` placeholders. ## Operator follow-up (after merge — this PR is **not** merged here) 1. Create Secret `osint-admin` in namespace `osint` with `ADMIN_USER`, `ADMIN_PASSWORD_HASH`, `ADMIN_SESSION_SECRET`. 2. Rebuild the amd64 image and bump the pin in `sirius/homek8s` `apps/base/osint/` (add the Secret as envFrom). Merge here does **not** deploy — and the push to `master` will fire the legacy compose workflow on the Pi, which is why the operator merges, not CI.
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.
sirius merged commit d8113b37b8 into master 2026-11-14 02:05:20 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
sirius/osint-dashboard!50
No description provided.