"""Data source ingestors — fetch from external APIs and push to NATS.""" from __future__ import annotations import html import io import json import logging import os import re import time import zipfile from datetime import datetime, timedelta, timezone from email.utils import parsedate_to_datetime import httpx import feedparser import nats from config import NATS_URL, OSINT_USER_AGENT from upstream_cache import rss_cache logger = logging.getLogger("osint.sources") def _parse_rfc822(date_str: object) -> str | None: """Parse RFC-822 date string from feedparser entries.""" if not isinstance(date_str, str): return None try: return parsedate_to_datetime(date_str).astimezone(timezone.utc).isoformat() except (ValueError, TypeError): return None NATS_URLS = NATS_URL _nc = None async def _jetstream(): """Reuse one NATS connection across publishes (no connect/close per event).""" global _nc if _nc is None or _nc.is_closed: _nc = await nats.connect(NATS_URLS) return _nc.jetstream() async def publish_event(subject: str, event: dict): """Publish an event to NATS JetStream.""" js = await _jetstream() await js.publish(subject, json.dumps(event).encode()) logger.debug("Published event to %s", subject) def event_dedup_key(msg: dict) -> str | None: """Natural key for generic events. URL when present; else None (always insert).""" url = msg.get("url") if not isinstance(url, str): return None url = url.strip() return url or None async def existing_event_urls(urls: list[str]) -> set[str]: """URLs already claimed in event_dedup. Empty input -> empty set.""" if not urls: return set() from sqlalchemy import select from database import async_session from models import event_dedup as event_dedup_table async with async_session() as session: result = await session.execute( select(event_dedup_table.c.url).where(event_dedup_table.c.url.in_(urls)) ) return {row[0] for row in result} async def _publish_unknown(subject: str, events: list[dict]) -> int: """Publish only events whose URL is not already in event_dedup.""" keys = [event_dedup_key(e) for e in events] known = await existing_event_urls([k for k in keys if k]) published = 0 for event, key in zip(events, keys): if key and key in known: continue await publish_event(subject, event) published += 1 return published def _ua_headers() -> dict[str, str]: return {"User-Agent": OSINT_USER_AGENT} # ─── RSS Feed Ingestor ────────────────────────────────────────────────── async def ingest_rss_feed(feed_url: str, source_id: str | None = None): """Fetch and parse an RSS feed, publish items to NATS.""" text = rss_cache.get(feed_url) if text is None: async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client: resp = await client.get(feed_url) resp.raise_for_status() text = resp.text rss_cache[feed_url] = text feed = feedparser.parse(text) count = 0 for entry in feed.entries[:100]: # max 100 per run event = { "source_type": "rss", "title": entry.get("title"), "body": entry.get("summary") or entry.get("description"), "url": entry.get("link"), "source_timestamp": _parse_rfc822(entry.get("published")) or datetime.now(timezone.utc).isoformat(), "tags": [t.get("term") for t in entry.get("tags", []) if t.get("term")], "raw": { "feed_url": feed_url, "feed_title": feed.feed.get("title"), "author": entry.get("author"), "categories": [c.get("term") for c in entry.get("categories", [])], }, } await publish_event("events.rss", event) count += 1 logger.info("Ingested %d items from RSS feed %s", count, feed_url) return count # ─── GDELT 2.0 DOC API ────────────────────────────────────────────────── GDELT_API = "https://api.gdeltproject.org/api/v2/doc/doc" GDELT_DEFAULT_QUERY = '(unrest OR protest OR outage OR cyber OR "power outage")' def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]: """DOC 2.0 query string (not the retired gdeltv2 ``search`` param).""" q = (query or "").strip() or GDELT_DEFAULT_QUERY return { "query": q, "mode": "ArtList", "format": "json", "maxrecords": str(int(max_articles)), "timespan": "1d", } # GDELT 429 backoff state. GDELT sends no Retry-After, and its block window # grows with request volume, so the only useful reaction to a 429 is to stop # asking: skip whole producer cycles, doubling the wait from BASE to MAX. GDELT_BACKOFF_BASE = int(os.getenv("GDELT_BACKOFF_BASE", "300")) GDELT_BACKOFF_MAX = int(os.getenv("GDELT_BACKOFF_MAX", "1800")) _gdelt_backoff_secs = 0 _gdelt_backoff_until = 0.0 # time.monotonic() def gdelt_backoff_remaining() -> float: """Seconds left in the GDELT cooldown window (0 = ready to call).""" return max(0.0, _gdelt_backoff_until - time.monotonic()) def _gdelt_backoff_until_iso() -> str: return ( datetime.now(timezone.utc).replace(microsecond=0) + timedelta(seconds=gdelt_backoff_remaining()) ).strftime("%Y-%m-%dT%H:%M:%SZ") def _gdelt_start_backoff(retry_after: float | None = None) -> None: global _gdelt_backoff_secs, _gdelt_backoff_until wait = retry_after or min( GDELT_BACKOFF_MAX, max(GDELT_BACKOFF_BASE, _gdelt_backoff_secs * 2) ) _gdelt_backoff_secs = int(wait) _gdelt_backoff_until = time.monotonic() + wait def _gdelt_clear_backoff() -> None: global _gdelt_backoff_secs, _gdelt_backoff_until _gdelt_backoff_secs = 0 _gdelt_backoff_until = 0.0 def _gdelt_retry_after(resp: httpx.Response) -> float | None: """Retry-After as seconds (delta-seconds or HTTP-date); GDELT sends neither.""" raw = resp.headers.get("retry-after") if not raw: return None raw = raw.strip() try: return max(1.0, float(raw)) except ValueError: pass try: return max( 1.0, (parsedate_to_datetime(raw) - datetime.now(timezone.utc)).total_seconds(), ) except (TypeError, ValueError): return None def _parse_gdelt_seendate(value: object) -> str: if isinstance(value, str) and len(value) >= 15: try: return datetime.strptime(value[:15], "%Y%m%dT%H%M%S").replace( tzinfo=timezone.utc ).isoformat() except ValueError: pass return datetime.now(timezone.utc).isoformat() def parse_gdelt_articles(data: dict) -> list[dict]: events = [] for article in data.get("articles") or []: if not isinstance(article, dict): continue url = article.get("url") if not url: continue events.append({ "source_type": "gdel-t2", "title": article.get("title"), "body": article.get("domain") or article.get("language"), "url": url, "location_name": article.get("sourcecountry"), "source_timestamp": _parse_gdelt_seendate(article.get("seendate")), "tags": [t for t in (article.get("language"), article.get("sourcecountry")) if t], "raw": article, }) return events async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50): """Fetch articles from the GDELT DOC 2.0 API. GDELT enforces a per-IP quota that answers ``429`` with a plain-text body ("Please limit requests to one every 5 seconds"), sends **no** Retry-After, and widens the block window as request volume accumulates. So a 429 is not retried: the ingester stops calling until a backoff window expires, and the cycle is skipped with a single log line. See ``gdelt_backoff_remaining``. """ remaining = gdelt_backoff_remaining() if remaining > 0: logger.info( "GDELT: cooling down (%ds left after 429); skipping this cycle", int(remaining) ) return 0 params = gdelt_params(query=query, max_articles=max_articles) async with httpx.AsyncClient( timeout=60, headers=_ua_headers(), follow_redirects=True, ) as client: try: resp = await client.get(GDELT_API, params=params) except httpx.TransportError as exc: # gdeltproject.org certs have expired in the wild; HTTP fallback. # Only transport failures (TLS/connect) get the fallback — an HTTP # error status is a quota answer and retrying it just burns the # same per-IP budget a second time. logger.warning("GDELT HTTPS transport error (%s); retrying HTTP", exc) http_url = GDELT_API.replace("https://", "http://", 1) resp = await client.get(http_url, params=params) if resp.status_code == 429: _gdelt_start_backoff(_gdelt_retry_after(resp)) logger.warning( "GDELT 429 (rate limited) -> backing off until %s", _gdelt_backoff_until_iso(), ) return 0 try: resp.raise_for_status() data = resp.json() except (httpx.HTTPStatusError, ValueError) as exc: # GDELT also signals errors/throttling as HTTP 200 + prose, so a # JSON decode failure is "busy", not "no results". _gdelt_start_backoff(_gdelt_retry_after(resp)) logger.warning( "GDELT unusable response (HTTP %s: %s) -> backing off until %s", resp.status_code, str(exc).splitlines()[0][:120], _gdelt_backoff_until_iso(), ) return 0 _gdelt_clear_backoff() events = parse_gdelt_articles(data if isinstance(data, dict) else {}) for event in events: await publish_event("events.gdelt", event) logger.info("Ingested %d articles from GDELT", len(events)) return len(events) # ─── GDELT 2.0 15-minute bulk files (throttle-free) ───────────────────── # # The DOC 2.0 API is per-IP quota'd (429, no Retry-After). The same coverage is # published every 15 minutes as static files under /gdeltv2/ with no key and no # quota, indexed by ``lastupdate.txt``: # *.export.CSV.zip events (CAMEO codes) # *.mentions.CSV.zip event->article mentions (URL + confidence, no title) # *.gkg.csv.zip Global Knowledge Graph, one row per article: URL, source # domain, themes, locations with lat/lon, tone, and the # page title in the V2ExtrasXML column # GKG is the one that carries title + geo, so map a filtered row into the same # event shape ``parse_gdelt_articles`` produces and let the existing # ``events.gdelt`` NATS consumer + ``event_dedup`` (URL) keep working. GDELT_BULK_ENABLED = os.getenv("GDELT_BULK_ENABLED", "1").lower() in ("1", "true", "yes") GDELT_BULK_LASTUPDATE = os.getenv( "GDELT_BULK_LASTUPDATE", "https://data.gdeltproject.org/gdeltv2/lastupdate.txt" ) GDELT_BULK_MAX_EVENTS = int(os.getenv("GDELT_BULK_MAX_EVENTS", "100")) # Newest bulk file already parsed; lastupdate.txt is re-read every cycle but the # 15-minute file behind it only changes 4x/hour. _gdelt_bulk_last_file: str | None = None _PAGE_TITLE_RE = re.compile(r"(.*?)", re.DOTALL) _PAGE_PUB_TS_RE = re.compile(r"(\d{14})<") def gdelt_query_terms(query: str = "") -> list[str]: """CONFIG GDELT query (``(unrest OR protest OR ...)``) -> plain terms. Used to filter bulk rows against their GKG theme tokens instead of publishing every article in the 15-minute window. """ q = (query or "").strip() or GDELT_DEFAULT_QUERY terms: list[str] = [] for part in re.split(r"\s+OR\s+", q.strip().strip("()"), flags=re.IGNORECASE): term = part.strip().strip('"').strip("'").strip().lower() if term and term not in terms: terms.append(term) return terms def _term_hits_themes(term: str, themes: str) -> bool: """Term matches when every word of it appears in the theme token list.""" words = [w for w in re.split(r"[\s_\-]+", term) if w] return bool(words) and all(w in themes for w in words) def select_gdelt_bulk_url(lastupdate_text: str) -> tuple[str, str] | None: """``(filename, https_url)`` of the newest GKG file in lastupdate.txt. lastupdate.txt lists plain ``http://`` URLs, which 301 to https; normalise so the fetch never follows a redirect into a stale mirror. """ for line in (lastupdate_text or "").splitlines(): parts = line.split() if len(parts) < 3 or not parts[2].endswith(".gkg.csv.zip"): continue url = parts[2] if url.startswith("http://"): url = "https://" + url[len("http://"):] return url.rsplit("/", 1)[-1], url return None def _gkg_location(field: str) -> tuple[float | None, float | None, str | None]: """First location in a V2Locations field -> (lat, lon, name). V2Locations is ``type#fullname#cc#adm1[#adm2]#lat#lon#featureid``; the adm2 slot is sometimes dropped, so read the triple from the end. """ segment = (field or "").split(";", 1)[0] parts = segment.split("#") if len(parts) < 5: return None, None, None name = parts[1].strip() or None try: lat = float(parts[-3]) lon = float(parts[-2]) except (TypeError, ValueError): return None, None, name if not (-90 <= lat <= 90 and -180 <= lon <= 180): return None, None, name return lat, lon, name def _gkg_tone(field: str) -> float | None: try: return _parse_gdelt_tone(field.split(",", 1)[0]) except (AttributeError, IndexError): return None def _gkg_timestamp(row: list[str], extras: str) -> str: """Article publish time: PAGE_PRECISEPUBTIMESTAMP, else the GKG window stamp.""" stamps = [] pub = _PAGE_PUB_TS_RE.search(extras) if pub is not None: stamps.append(pub.group(1)) if len(row) > 1 and isinstance(row[1], str): stamps.append(row[1][:14]) for stamp in stamps: try: return datetime.strptime(stamp, "%Y%m%d%H%M%S").replace( tzinfo=timezone.utc ).isoformat() except ValueError: continue return datetime.now(timezone.utc).isoformat() def parse_gkg_row(row: list[str], terms: list[str], bulk_file: str = "") -> dict | None: """Map one GKG CSV row into the ``events.gdelt`` event shape. Returns None when the row has no usable URL or matches none of ``terms``. """ if len(row) < 8: return None url = (row[4] or "").strip() if not url.startswith(("http://", "https://")): return None raw_themes = row[7] or "" themes = raw_themes.lower() matched = [t for t in terms if _term_hits_themes(t, themes)] if not matched: return None extras = row[-1] if isinstance(row[-1], str) else "" title_match = _PAGE_TITLE_RE.search(extras) title = html.unescape(title_match.group(1)).strip() if title_match else None lat = lon = loc_name = None for idx in (9, 10): if idx < len(row): lat, lon, loc_name = _gkg_location(row[idx]) if lat is not None: break theme_tokens = [t for t in raw_themes.split(";") if t] tags = matched + [ t for t in theme_tokens if any(w in t.lower() for w in matched) ] tags = list(dict.fromkeys(tags))[:10] return { "source_type": "gdel-t2", "title": title, "body": (row[3] or "").strip() or None, "url": url, "location_lat": lat, "location_lon": lon, "location_name": loc_name, "source_timestamp": _gkg_timestamp(row, extras), "tags": tags, "raw": { "gkg_record_id": row[0], "source_common_name": row[3], "source_collection": row[2], "themes": theme_tokens[:12], "tone": _gkg_tone(row[15]) if len(row) > 15 else None, "bulk_file": bulk_file, }, } async def ingest_gdelt_bulk(query: str = "", max_events: int | None = None) -> int: """Publish new articles from the newest 15-minute GKG bulk file. No API key, no per-IP quota, and the existing URL dedupe means re-reading the same file after a restart publishes nothing new. """ global _gdelt_bulk_last_file cap = GDELT_BULK_MAX_EVENTS if max_events is None else max_events async with httpx.AsyncClient( timeout=120, headers=_ua_headers(), follow_redirects=True, ) as client: index = await client.get(GDELT_BULK_LASTUPDATE) index.raise_for_status() picked = select_gdelt_bulk_url(index.text) if picked is None: logger.warning("GDELT bulk: no .gkg file listed in lastupdate.txt") return 0 filename, url = picked if filename == _gdelt_bulk_last_file: logger.debug("GDELT bulk: %s already ingested; nothing new", filename) return 0 archive = await client.get(url) archive.raise_for_status() terms = gdelt_query_terms(query) events: list[dict] = [] scanned = 0 with zipfile.ZipFile(io.BytesIO(archive.content)) as zf: member = zf.namelist()[0] with zf.open(member) as fh: for line in io.TextIOWrapper(fh, encoding="utf-8", errors="replace"): if not line.strip(): continue scanned += 1 event = parse_gkg_row(line.rstrip("\r\n").split("\t"), terms, filename) if event is not None and len(events) < cap: events.append(event) published = await _publish_unknown("events.gdelt", events) _gdelt_bulk_last_file = filename logger.info( "GDELT bulk %s: %d/%d rows matched %s, %d new articles published", filename, len(events), scanned, "/".join(terms), published, ) return published async def ingest_gdelt(query: str = "", max_articles: int = 50): """GDELT articles: throttle-free 15-minute bulk file first, DOC API fallback. The bulk path carries the coverage; the DOC 2.0 call (with its 429 backoff) only runs when the bulk fetch itself fails, so the per-IP quota is no longer on the hot path. """ if GDELT_BULK_ENABLED: try: return await ingest_gdelt_bulk(query=query) except Exception as exc: # noqa: BLE001 — any bulk failure falls back logger.warning( "GDELT bulk fetch failed (%s: %s); falling back to DOC API", type(exc).__name__, str(exc)[:160], ) return await _ingest_gdelt_doc(query=query, max_articles=max_articles) def _parse_gdelt_tone(tone: str) -> float | None: """Parse GDELT tone string to a -1..1 sentiment score.""" try: tone_float = float(tone) return max(-1.0, min(1.0, tone_float / 4249.0)) # GDELT tone range except (ValueError, TypeError): return None # ─── Earthquake Ingestor (USGS) ───────────────────────────────────────── USGS_API = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson" def parse_usgs_feature(feature: dict) -> dict: """Map one USGS GeoJSON feature, keeping the stable event id.""" props = feature.get("properties") or {} geometry = (feature.get("geometry") or {}).get("coordinates") or [] usgs_id = feature.get("id") url = props.get("url") or ( f"https://earthquake.usgs.gov/earthquakes/eventpage/{usgs_id}" if usgs_id else None ) raw = dict(props) raw["usgs_id"] = usgs_id return { "source_type": "earthquake", "title": props.get("title"), "body": props.get("description"), "url": url, "location_lat": geometry[1] if len(geometry) > 1 else None, "location_lon": geometry[0] if len(geometry) > 0 else None, "location_name": props.get("place"), "sentiment_label": "neutral", "tags": [f"magnitude:{props.get('mag')}"] if props.get("mag") else [], "source_timestamp": ( datetime.utcfromtimestamp(props.get("time", 0) / 1000) .replace(tzinfo=timezone.utc) .isoformat() ), "raw": raw, } async def ingest_earthquakes(): """Fetch recent earthquakes from USGS.""" async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client: resp = await client.get(USGS_API) resp.raise_for_status() data = resp.json() count = 0 for feature in data.get("features", []): event = parse_usgs_feature(feature) await publish_event("events.earthquake", event) count += 1 logger.info("Ingested %d earthquake events", count) return count # ─── NASA EONET v3 ────────────────────────────────────────────────────── EONET_API = "https://eonet.gsfc.nasa.gov/api/v3/events" def parse_eonet_events(payload: dict) -> list[dict]: events = [] for item in payload.get("events") or []: if not isinstance(item, dict): continue eid = item.get("id") geoms = item.get("geometry") or [] point = None for g in geoms: if isinstance(g, dict) and g.get("type") == "Point": point = g if point is None: continue coords = point.get("coordinates") or [] if len(coords) < 2: continue lon, lat = float(coords[0]), float(coords[1]) cats = item.get("categories") or [] tags = [] for c in cats: if isinstance(c, dict) and c.get("id"): tags.append(str(c["id"])) url = item.get("link") or (f"https://eonet.gsfc.nasa.gov/api/v3/events/{eid}" if eid else None) ts = point.get("date") or datetime.now(timezone.utc).isoformat() events.append({ "source_type": "disaster", "title": item.get("title"), "body": ", ".join(tags) if tags else None, "url": url, "location_lat": lat, "location_lon": lon, "location_name": item.get("title"), "tags": tags, "source_timestamp": ts, "raw": {**item, "eonet_id": eid}, }) return events async def ingest_eonet(): """Volcanoes, storms, floods, drought — gaps USGS/FIRMS don't cover.""" async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client: resp = await client.get(EONET_API, params={"status": "open", "limit": 100}) resp.raise_for_status() data = resp.json() events = parse_eonet_events(data if isinstance(data, dict) else {}) published = await _publish_unknown("events.disaster", events) logger.info("Ingested %d EONET events (%d already known)", published, len(events) - published) return published # ─── CISA KEV ─────────────────────────────────────────────────────────── CISA_KEV_API = ( "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json" ) def parse_cisa_kev(payload: dict) -> list[dict]: events = [] for row in payload.get("vulnerabilities") or []: if not isinstance(row, dict): continue cve = row.get("cveID") if not cve: continue title = row.get("vulnerabilityName") or cve vendor = row.get("vendorProject") or "" product = row.get("product") or "" events.append({ "source_type": "disaster", "title": f"{cve}: {title}", "body": row.get("shortDescription") or f"{vendor} {product}".strip(), "url": f"https://nvd.nist.gov/vuln/detail/{cve}", "location_lat": None, "location_lon": None, "location_name": None, "tags": ["cisa-kev", cve, "ransomware" if row.get("knownRansomwareCampaignUse") == "Known" else None], "source_timestamp": row.get("dateAdded") or datetime.now(timezone.utc).isoformat(), "raw": {**row, "cveID": cve}, }) events[-1]["tags"] = [t for t in events[-1]["tags"] if t] return events async def ingest_cisa_kev(): """Exploited-in-the-wild CVEs. No fake map coords — ticker/events only.""" async with httpx.AsyncClient(timeout=30, headers=_ua_headers(), follow_redirects=True) as client: resp = await client.get(CISA_KEV_API) resp.raise_for_status() data = resp.json() events = parse_cisa_kev(data if isinstance(data, dict) else {}) published = await _publish_unknown("events.disaster", events) logger.info("Ingested %d CISA KEV rows (%d already known)", published, len(events) - published) return published # ─── Social Signals (Twitter/X-like placeholder) ──────────────────────── async def ingest_social_signals(query: str = "", max_items: int = 50): """Placeholder for social media signal ingestion. In production, this would connect to Twitter API, Reddit, NewsAPI, etc. For now, it publishes a heartbeat to signal the pipeline is active. """ event = { "source_type": "social", "title": f"Social signal scan: {query}", "body": f"Scanned for '{query}' — placeholder connector", "source_timestamp": datetime.now(timezone.utc).isoformat(), "tags": [query] if query else [], "raw": {"query": query, "max_items": max_items, "connector": "placeholder"}, } await publish_event("events.social", event) logger.info("Social signal scan complete for '%s'", query) return 1