osint-dashboard/tests/conftest.py
Sirius DevOps c0a2454fdd 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.
2026-11-13 20:56:07 -05:00

138 lines
4.3 KiB
Python

"""Shared test fixtures.
Unit tests (parsing/mapping) run anywhere. DB-backed tests (idempotency, API)
are marked `integration` and auto-skip when the test database is unreachable —
set DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_NAME to point at a TimescaleDB+PostGIS
instance (e.g. the `localhost/osint-dashboard-pg:test` image) to run them.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
import pytest
# Make the app package importable from tests (repo root/app).
APP_DIR = Path(__file__).resolve().parent.parent / "app"
if str(APP_DIR) not in sys.path:
sys.path.insert(0, str(APP_DIR))
# Point the app's config at the test database BEFORE any app module is imported
# (database.py builds DATABASE_URL from env at import time).
os.environ.setdefault("DB_HOST", "127.0.0.1")
os.environ.setdefault("DB_PORT", "55432")
os.environ.setdefault("DB_USER", "osint")
os.environ.setdefault("DB_PASSWORD", "osint")
os.environ.setdefault("DB_NAME", "osint_data")
# Each test opens a fresh event loop (asyncio.run); a pooled connection can't be
# 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
async def _ping() -> bool:
try:
conn = await asyncpg.connect(
host=os.environ["DB_HOST"],
port=int(os.environ["DB_PORT"]),
user=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
database=os.environ["DB_NAME"],
timeout=3,
)
await conn.close()
return True
except Exception:
return False
return asyncio.run(_ping())
except Exception:
return False
requires_db = pytest.mark.skipif(
not _db_reachable(),
reason="test database unreachable (set DB_* env or start the PG container)",
)
@pytest.fixture()
def clean_fires():
"""Truncate the fires table before and after a DB-backed test."""
import asyncio
async def _truncate():
conn = await asyncpg.connect(
host=os.environ["DB_HOST"],
port=int(os.environ["DB_PORT"]),
user=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
database=os.environ["DB_NAME"],
)
try:
await conn.execute("TRUNCATE fires")
finally:
await conn.close()
asyncio.run(_truncate())
yield
asyncio.run(_truncate())
def make_fire_msg(**overrides) -> dict:
"""A realistic VIIRS hotspot NATS message (as fire_sources publishes it)."""
msg = {
"source_type": "fire",
"latitude": 39.45678,
"longitude": -121.12345,
"brightness": 341.40,
"confidence": "h",
"acq_time": "2026-08-24T18:10:00+00:00",
"satellite": "N",
"instrument": "VIIRS",
"bright_ti5": 310.20,
"frp": 12.4,
"daynight": "D",
"scan": 0.45,
"track": 0.47,
"version": "2.0NRT",
"raw": None,
}
msg.update(overrides)
return msg