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

View file

@ -26,18 +26,21 @@ from sqlalchemy.ext.asyncio import AsyncSession
from database import async_session, init_extensions
from models import (
alerts, documents, entities, entity_events, events, feed_sources
alerts, documents, entities, entity_events, events, feed_sources, fires
)
from schemas import (
AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate,
DashboardSummary, EntityCreate, EntityKind, EntityOut,
EventCreate, EventOut,
EventCreate, EventOut, FireOut,
FeedSourceCreate, FeedSourceOut,
KeyOut, KeyValueIn,
SearchResult, SentimentSummary, SourceType,
SearchQuery, TimelinePoint,
)
from ingestor import ingest_event, fetch_and_process
from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals
from fire_sources import ingest_fires
from keystore import KeyFormatError, delete_key, list_keys, set_key
logging.basicConfig(level=logging.INFO)
logger = structlog.get_logger("osint.dashboard")
@ -218,6 +221,64 @@ async def create_event(payload: EventCreate):
return {"id": str(event_id)}
# ── Active Fires / Hotspots (NASA FIRMS) ─────────────────────────────────
@app.get("/api/fires", response_model=list[FireOut])
async def list_fires(
bbox: str | None = Query(
None,
description="Comma-separated 'minlon,minlat,maxlon,maxlat' to bound the "
"result set (e.g. '-125,24,-66,50'). Omit for all stored "
"detections (most recent first).",
),
since: datetime | None = Query(
None,
description="Only hotspots acquired at/after this UTC instant "
"(ISO 8601, e.g. '2026-08-24T12:00:00Z').",
),
limit: int = Query(2000, ge=1, le=10000),
):
"""List stored FIRMS active fire/hotspot detections as JSON.
This is the data contract for the map's fire heatmap overlay: the frontend
calls `GET /api/fires?bbox=...&since=...` and renders the returned points.
"""
async with async_session() as session:
stmt = select(fires).order_by(fires.c.acq_time.desc())
if since:
stmt = stmt.where(fires.c.acq_time >= since)
if bbox:
parts = [p.strip() for p in bbox.split(",")]
if len(parts) != 4:
raise HTTPException(
422, "bbox must be 'minlon,minlat,maxlon,maxlat' (4 comma-separated values)"
)
try:
minlon, minlat, maxlon, maxlat = (float(p) for p in parts)
except ValueError:
raise HTTPException(
422, "bbox values must be floats: 'minlon,minlat,maxlon,maxlat'"
)
stmt = stmt.where(
and_(
fires.c.longitude >= minlon, fires.c.longitude <= maxlon,
fires.c.latitude >= minlat, fires.c.latitude <= maxlat,
)
)
stmt = stmt.limit(limit)
rows = (await session.execute(stmt)).mappings().all()
return [
FireOut(
latitude=r["latitude"], longitude=r["longitude"],
brightness=r["brightness"], confidence=r["confidence"],
acq_time=r["acq_time"], satellite=r["satellite"],
instrument=r["instrument"], bright_ti5=r["bright_ti5"],
frp=r["frp"], daynight=r["daynight"],
)
for r in rows
]
# ── Search ────────────────────────────────────────────────────────────────
@app.post("/api/search", response_model=SearchResult)
@ -432,6 +493,43 @@ async def list_documents(
}
# ── API Keys ────────────────────────────────────────────────────────────
@app.get("/api/keys", response_model=list[KeyOut])
async def list_api_keys():
"""List known API keys with set/missing status — masked, never raw.
Registered keys (FIRMS_MAP_KEY, GEMINI_API_KEY, TELEGRAM_TOKEN)
are always included. Any extra stored keys are appended.
"""
return await list_keys()
@app.post("/api/keys/{name}", status_code=200)
async def save_api_key(name: str, payload: KeyValueIn):
"""Save (upsert) an API key value.
Registered key formats are validated (e.g. FIRMS_MAP_KEY must be a
32-char hex string). Unregistered names are accepted as long as they
use UPPER_SNAKE_CASE. The raw value is stored in Postgres and never
returned by any API endpoint — only the masked status is exposed.
"""
try:
result = await set_key(name, payload.value)
except KeyFormatError as exc:
raise HTTPException(status_code=422, detail=str(exc))
return result
@app.delete("/api/keys/{name}")
async def remove_api_key(name: str):
"""Delete a stored API key (unsets it)."""
removed = await delete_key(name)
if not removed:
raise HTTPException(status_code=404, detail="Key not found")
return {"ok": True}
# ── Ingestion Triggers ───────────────────────────────────────────────────
@app.post("/api/ingest/rss")
@ -455,6 +553,13 @@ async def trigger_earthquake_ingest():
return {"status": "ok", "events_ingested": count}
@app.post("/api/ingest/fires")
async def trigger_fire_ingest(bbox: str | None = None):
"""Trigger a NASA FIRMS active-fire poll (uses FIRMS_BBOX if bbox omitted)."""
count = await ingest_fires(bbox)
return {"status": "ok", "hotspots_published": count}
@app.post("/api/ingest/social")
async def trigger_social_ingest(query: str = "", max_items: int = 50):
"""Trigger social signals ingestion."""