Add NASA FIRMS active-fire ingest + /api/fires; API keys management page

Coherent merge of two coordinated features on the shared working tree:

FIRMS fire heatmap (backend, t_6e404c14):
- app/fire_sources.py: fetch FIRMS VIIRS area CSV (free MAP_KEY) -> NATS events.fire
- fires hypertable (TimescaleDB, 1-day chunks) with natural-key PK
  (latitude, longitude, acq_time, satellite); idempotent ON CONFLICT DO NOTHING
- alembic/versions/002_fires.py; GET /api/fires?bbox=&since= (JSON only)
- POST /api/ingest/fires; ~15 min poll loop (FIRMS_INTERVAL=900) in ingester
- env-driven config (FIRMS_MAP_KEY/DATASET/BBOX/INTERVAL); docs/firms.md covers
  the zero-cost GIBS VIIRS_SNPP_Thermal_Anomalies_375m_All tile alternative
- 18 tests (parser, mapping, idempotency, API contract) verified vs real
  TimescaleDB+PostGIS (localhost/osint-dashboard-pg image)

API keys page (frontend, t_4433cff2):
- app/keystore.py: api_keys table (self-creating), FIRMS/GEMINI/TELEGRAM
  registry with format validation, ****last4 masking, get_api_key()
- GET/POST/DELETE /api/keys (never returns full values); Keys tab in index.html

DB_NULL_POOL env switch in app/database.py enables a NullPool for tests /
short-lived processes that open a fresh event loop per unit.
This commit is contained in:
Sirius DevOps 2026-08-24 15:37:42 -04:00
commit 627990efde
19 changed files with 1428 additions and 10 deletions

111
tests/conftest.py Normal file
View file

@ -0,0 +1,111 @@
"""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")
import asyncpg # noqa: E402
pytestmark = []
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

91
tests/test_api_fires.py Normal file
View file

@ -0,0 +1,91 @@
"""Integration tests for GET /api/fires (bbox + since filters, JSON contract)."""
import asyncio
import httpx
from conftest import make_fire_msg, requires_db
from ingestor import ingest_fire_row
from main import app
BASE = "http://test"
def _seed(*msgs) -> None:
"""Insert fire rows through the real ingestor path (idempotent)."""
async def run():
for m in msgs:
await ingest_fire_row(m)
asyncio.run(run())
def _get(path: str) -> httpx.Response:
return asyncio.run(_get_async(path))
async def _get_async(path: str) -> httpx.Response:
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
return await client.get(path)
@requires_db
def test_api_fires_bbox_filter(clean_fires):
_seed(
make_fire_msg(latitude=39.45678, longitude=-121.12345, satellite="N"),
make_fire_msg(latitude=34.00000, longitude=-118.20000, satellite="N20"),
make_fire_msg(latitude=10.00000, longitude=20.00000, satellite="N"),
)
# bbox covering only the California-ish points
resp = _get("/api/fires?bbox=-125,30,-115,42")
assert resp.status_code == 200
body = resp.json()
assert isinstance(body, list)
assert len(body) == 2
lats = sorted(p["latitude"] for p in body)
assert lats == [34.0, 39.45678]
@requires_db
def test_api_fires_since_filter(clean_fires):
_seed(
make_fire_msg(acq_time="2026-08-24T18:10:00+00:00"),
make_fire_msg(acq_time="2026-08-24T19:10:00+00:00"),
)
resp = _get("/api/fires?since=2026-08-24T18:30:00Z")
assert resp.status_code == 200
body = resp.json()
assert len(body) == 1
assert body[0]["acq_time"].startswith("2026-08-24T19:10")
@requires_db
def test_api_fires_json_contract(clean_fires):
_seed(make_fire_msg())
body = _get("/api/fires").json()
assert len(body) == 1
point = body[0]
# The exact fields the frontend heatmap needs — nothing more, nothing less.
assert set(point.keys()) == {
"latitude", "longitude", "brightness", "confidence", "acq_time",
"satellite", "instrument", "bright_ti5", "frp", "daynight",
}
assert point["latitude"] == 39.45678
assert point["confidence"] == "h"
assert point["satellite"] == "N"
@requires_db
def test_api_fires_invalid_bbox_422(clean_fires):
assert _get("/api/fires?bbox=-125,30").status_code == 422
assert _get("/api/fires?bbox=-125,abc,-115,42").status_code == 422
@requires_db
def test_api_fires_empty(clean_fires):
resp = _get("/api/fires")
assert resp.status_code == 200
assert resp.json() == []

87
tests/test_fire_ingest.py Normal file
View file

@ -0,0 +1,87 @@
"""Unit + integration tests for fire message routing and idempotent storage.
The row-mapping logic (_fire_row_from_msg) is pure and tested everywhere; the
DB-backed idempotency tests are `integration` and auto-skip without a live DB.
"""
import asyncio
from datetime import datetime, timezone
from conftest import make_fire_msg, requires_db
from ingestor import _fire_row_from_msg, ingest_fire_row, ingest_event
# ── Row mapping (pure, no DB) ────────────────────────────────────────────
def test_fire_row_from_msg_maps_fields():
row = _fire_row_from_msg(make_fire_msg())
assert row is not None
assert row["latitude"] == 39.45678
assert row["longitude"] == -121.12345
assert row["brightness"] == 341.40
assert row["confidence"] == "h"
assert row["satellite"] == "N"
assert row["acq_time"] == datetime(2026, 8, 24, 18, 10, tzinfo=timezone.utc)
assert row["frp"] == 12.4
assert row["daynight"] == "D"
def test_fire_row_from_msg_rejects_missing_natural_key():
for key in ("latitude", "longitude", "acq_time", "satellite"):
msg = make_fire_msg(**{key: None})
assert _fire_row_from_msg(msg) is None, f"{key}=None should be dropped"
def test_fire_row_from_msg_rejects_bad_timestamp():
msg = make_fire_msg(acq_time="not-a-timestamp")
assert _fire_row_from_msg(msg) is None
def test_ingest_event_routes_fire_away_from_events(monkeypatch):
"""source_type='fire' must hit the fire path, never the generic events insert."""
calls = {"fire": 0, "events": 0}
async def fake_fire_row(msg):
calls["fire"] += 1
return True
async def boom(*a, **k): # the generic events insert must not be reached
calls["events"] += 1
raise AssertionError("fire message leaked into the events insert path")
import ingestor
monkeypatch.setattr(ingestor, "ingest_fire_row", fake_fire_row)
monkeypatch.setattr(ingestor.events_table, "insert", boom)
asyncio.run(ingest_event(make_fire_msg()))
assert calls["fire"] == 1
assert calls["events"] == 0
# ── Idempotent storage against a live database ───────────────────────────
@requires_db
def test_ingest_fire_row_idempotent(clean_fires):
async def run():
# First insert persists.
assert await ingest_fire_row(make_fire_msg()) is True
# Same natural key on a later 15-min poll -> silently ignored.
assert await ingest_fire_row(make_fire_msg(brightness=999.0)) is False
# Same point/time but a different satellite is a distinct detection.
assert await ingest_fire_row(make_fire_msg(satellite="N20")) is True
# Same point but a different acquisition time is a distinct detection.
assert await ingest_fire_row(
make_fire_msg(acq_time="2026-08-24T19:10:00+00:00")
) is True
asyncio.run(run())
@requires_db
def test_ingest_fire_row_drops_malformed(clean_fires):
async def run():
assert await ingest_fire_row(make_fire_msg(latitude=None)) is False
assert await ingest_fire_row(make_fire_msg(acq_time="garbage")) is False
asyncio.run(run())

View file

@ -0,0 +1,78 @@
"""Unit tests for the NASA FIRMS CSV parser / timestamp normalization."""
import asyncio
from datetime import datetime, timezone
from fire_sources import normalize_acq_time, parse_firms_csv, ingest_fires
# Grounded against real FIRMS VIIRS area-CSV output.
SAMPLE_CSV = """latitude,longitude,bright_ti4,scan,track,acq_date,acq_time,satellite,instrument,confidence,version,bright_ti5,frp,daynight
-16.28359,29.40531,295.78,0.50,0.66,2025-06-06,1,N20,VIIRS,n,2.0NRT,284.11,1.17,N
-16.28190,29.40279,303.31,0.50,0.66,2025-06-06,1,N20,VIIRS,n,2.0NRT,284.43,0.67,N
-14.98900,28.36286,341.04,0.41,0.60,2025-06-06,1,N20,VIIRS,n,2.0NRT,279.77,4.59,N
15.17397,-11.28343,341.40,0.45,0.47,2025-06-06,1425,N20,VIIRS,l,2.0NRT,315.18,7.91,D
15.45870,-11.13616,339.25,0.46,0.47,2025-06-06,1425,N20,VIIRS,l,2.0NRT,312.05,9.24,D
"""
def test_normalize_acq_time_single_digit_hour():
# acq_time "1" (HHMM int) -> 00:01 UTC
dt = normalize_acq_time("2025-06-06", "1")
assert dt == datetime(2025, 6, 6, 0, 1, tzinfo=timezone.utc)
def test_normalize_acq_time_four_digit():
dt = normalize_acq_time("2025-06-06", 1425)
assert dt == datetime(2025, 6, 6, 14, 25, tzinfo=timezone.utc)
def test_normalize_acq_time_bad_values():
assert normalize_acq_time(None, 100) is None
assert normalize_acq_time("2025-06-06", None) is None
assert normalize_acq_time("2025-06-06", "") is None
assert normalize_acq_time("not-a-date", 100) is None
def test_parse_firms_csv_happy_path():
points = parse_firms_csv(SAMPLE_CSV)
assert len(points) == 5
first = points[0]
assert first["latitude"] == -16.28359
assert first["longitude"] == 29.40531
assert first["brightness"] == 295.78
assert first["confidence"] == "n"
assert first["satellite"] == "N20"
assert first["instrument"] == "VIIRS"
assert first["frp"] == 1.17
assert first["daynight"] == "N"
assert first["acq_time"] == "2025-06-06T00:01:00+00:00"
# late-day acquisition (acq_time 1425) parses to 14:25 UTC
assert points[3]["acq_time"] == "2025-06-06T14:25:00+00:00"
assert points[3]["confidence"] == "l"
def test_parse_firms_csv_skips_legend_line():
# FIRMS occasionally prepends a legend/info line before the real header.
with_legend = (
"Active Fire Data from VIIRS (S-NPP) — near real time\n"
+ SAMPLE_CSV
)
points = parse_firms_csv(with_legend)
assert len(points) == 5
assert points[0]["latitude"] == -16.28359
def test_parse_firms_csv_empty_and_garbage():
assert parse_firms_csv("") == []
assert parse_firms_csv("not a csv at all\njust text\n") == []
# Header present but a data row that is too short / has junk lat-lon
junk = SAMPLE_CSV.splitlines()[0] + "\n1,2\n"
assert parse_firms_csv(junk) == []
def test_ingest_fires_idles_without_map_key(monkeypatch):
# No key -> returns 0 without attempting a network call.
monkeypatch.setattr("fire_sources.FIRMS_MAP_KEY", "")
assert asyncio.run(ingest_fires()) == 0