Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(retro-hunt): consume the NEW_IOC events nothing consumed (Phase 8.1) (#928)
Beenu Arora187a11200254
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4d6ba09c5..c85a40e0a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -669,6 +669,14 @@ jobs:python3 scripts/check_hunt_scenarios.py --self-testpython3 scripts/check_hunt_scenarios.pypython3 scripts/run_hunt_evals.py --self-test+ # A retro-hunt sweeps a column or it sweeps nothing, and the failure is+ # a confident zero rather than an error. This reads the lake writer, the+ # ClickHouse DDL and the three threat-intel clients and fails when the+ # sweep's mapping disagrees with any of them.+ - name: Retro-hunt sweeps columns the lake writer fills+ run: |+ python3 scripts/check_ioc_lake_mapping.py --self-test+ python3 scripts/check_ioc_lake_mapping.py- name: Support bundle must not leakrun: |python3 -m pip install --quiet pytestdiff --git a/.github/workflows/isolation-live.yml b/.github/workflows/isolation-live.ymlindex fb291f9fb..333a3b611 100644--- a/.github/workflows/isolation-live.yml+++ b/.github/workflows/isolation-live.yml@@ -13,12 +13,18 @@ on:paths:- "tests/isolation/**"- "services/api/app/services/lake_sql.py"+ - "services/api/app/services/retro_hunt/**"+ - "services/api/clickhouse/**"+ - "services/fusion/app/services/lake_writer.py"- "services/ingest/internal/graph_ws/**"- ".github/workflows/isolation-live.yml"pull_request:paths:- "tests/isolation/**"- "services/api/app/services/lake_sql.py"+ - "services/api/app/services/retro_hunt/**"+ - "services/api/clickhouse/**"+ - "services/fusion/app/services/lake_writer.py"- "services/ingest/internal/graph_ws/**"- ".github/workflows/isolation-live.yml"workflow_dispatch:@@ -124,6 +130,17 @@ jobs:ISOLATION_KAFKA_BROKERS: localhost:9092run: python -m pytest tests/isolation/test_live_stores.py -v --tb=short+ # Gap-closure Phase 8.1's done-when clause, which is a statement about a+ # pair of tenants and so cannot be proven offline: an indicator is found+ # for the tenant whose recorded lake rows hold it and not for the one+ # whose do not. The rows come from the production lake writer and the+ # query from the production generator, so a wrong column fails here.+ - name: Retro-hunt sweep matches recorded lake data+ env:+ ISOLATION_CLICKHOUSE_HOST: localhost+ ISOLATION_CLICKHOUSE_PORT: "9000"+ run: python -m pytest tests/isolation/test_retro_hunt_live.py -v --tb=short+- name: Capture forensics on failureif: failure()run: |diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1200236eb..e329f472a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -348,6 +348,69 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0minted before this change fail closed rather than outliving the revocationmeant to end them. The refresh path checks it too, and matters more there: arefresh token outlives an access token by days.+- **The `NEW_IOC` events the threat-intel pipeline has always emitted now have+ a consumer** (gap-closure Phase 8.1).++ **The gap.** `services/threatintel/app/feeds/pipeline.py` publishes a+ `NEW_IOC` event for every newly-seen indicator. A grep for the string across+ the repository returned the emit site, the plan, and nothing else. Every+ indicator the CISA KEV catalog, MISP, OTX and TAXII feeds produced went into+ three stores and onto a Kafka topic that no process subscribed to, so a+ customer whose estate contained a published indicator was never told.++ **A trap found while closing it.** The pipeline's constructor defaults+ `kafka_topic` to `threat-intel-events`, and `services/threatintel`'s lifespan+ overrides it with `KAFKA_TOPIC_THREAT_INTEL`, which is `aisoc.threat_intel`.+ The constructor default is unreachable in any running deployment. A consumer+ written against the name in the signature would have subscribed to a topic no+ producer writes, consumed nothing, logged nothing, and kept a healthy+ container indefinitely. `check_ioc_lake_mapping.py` compares the producer's+ setting with the consumer's so the two cannot drift.++ **What was built.** A retro-hunt sweeps each opted-in tenant's recorded+ history for a published indicator, over the event lake and, through the+ Phase 4 typed indicator search, any SIEMs that tenant has connected. Off by+ default at the deployment level and again per tenant, because a sweep costs+ warehouse time and, where it reaches a connected SIEM, possibly money.++ **Why one indicator cannot open a thousand alerts.** The sweep query is an+ aggregate: it returns a sighting count, first and last sighting times, and+ bounded distinct sets of hosts, users and connectors, so there is no code+ path that yields a row per match. On top of that, `retro_hunt_sightings` has+ a UNIQUE constraint on (tenant, indicator type, indicator value), so a feed+ republishing an indicator daily updates a counter instead of alerting daily,+ and the alert carries an idempotency key that the `alerts` table already has+ a per-tenant partial unique index on. One of those stops the alert being+ attempted and the other stops it landing.++ **How the mapping was proven rather than asserted.** An indicator type has to+ be searched in a column the lake writer actually fills, and this repository+ has twice shipped rules matching fields nothing emitted. Every mapped column+ is annotated with the OCSF path `lake_writer.event_to_row` reads to populate+ it; `scripts/check_ioc_lake_mapping.py` reads that writer's source, the+ ClickHouse DDL and the three threat-intel clients and fails on any+ disagreement; and `tests/isolation/test_retro_hunt_live.py` drives a real+ OCSF event through the real writer into a live ClickHouse and runs the real+ query generator against it.++ **The first version of that live test was vacuous, and the fix is the+ interesting part.** Dropping `is_ip` from both IP columns was injected and+ all eleven tests still passed, because the `iocs` array column carries the+ address as a plain string and matched through the OR beside the typed+ column. The test now probes **each mapped column on its own** and compares+ the set that matched against the set that should, which does fail when a+ column is pointed at something the writer does not fill. Measuring that also+ corrected a claim this changelog would otherwise have carried: ClickHouse+ coerces a string literal when comparing against an `IPv6` column, so+ `toIPv6()` is explicitness about the stored value being the IPv4-mapped form,+ not the difference between matching and not.++ Three deliberate refusals are recorded rather than implemented: a URL is not+ swept in the lake because there is no URL column and a scan of the compressed+ raw payload would return a confident zero on connectors that leave it empty;+ a CVE is not swept against telemetry because it does not appear there; and a+ feed type nobody has mapped is refused by name and counted rather than+ defaulted to a plausible one.### Changeddiff --git a/GAP_CLOSURE_PROGRESS.md b/GAP_CLOSURE_PROGRESS.mdindex ecf50407d..d3c80beb1 100644--- a/GAP_CLOSURE_PROGRESS.md+++ b/GAP_CLOSURE_PROGRESS.md@@ -423,7 +423,13 @@ suites' job, and anything at all against a live vendor MCP server.## Phase 8: Intel-driven retro-hunts and a hunting agent-- [ ] **8.1 Retro-hunts** consuming the `NEW_IOC` events nothing consumes today, with provenance, dedup, rate limits and budgets.+- [x] **8.1 Retro-hunts** consuming the `NEW_IOC` events nothing consumes today, with provenance, dedup, rate limits and budgets.+ - Confirmed before building: `NEW_IOC` appeared only at the emit site in `services/threatintel/app/feeds/pipeline.py`, in the plan, and in this tracker. `services/api/app/workers/retro_hunt_consumer.py` is the consumer.+ - The plan's topic name is the producer's **dead** default. `ThreatIntelPipeline.__init__` defaults to `threat-intel-events`; the service's lifespan passes `KAFKA_TOPIC_THREAT_INTEL` (`aisoc.threat_intel`). A consumer on the signature's name reads nothing and stays healthy. `check_ioc_lake_mapping.py` pins the two together.+ - Dedup is two layers: the `retro_hunt_sightings` UNIQUE constraint on (tenant, type, value) stops a republished indicator alerting twice, and the `alerts` per-tenant partial unique index on `idempotency_key` stops a duplicate landing. The sweep query is an aggregate, so a thousand matching events are one row before either layer is reached.+ - Budget is per tenant, hourly and daily, checked before the sweep so an exhausted budget costs one UPDATE; skipped sweeps are counted so an empty budget is distinguishable from a quiet feed. ClickHouse enforces a bytes-to-read and execution-time ceiling on every query.+ - Mapping proven, not asserted: `scripts/check_ioc_lake_mapping.py` (static, across three service trees) plus `tests/isolation/test_retro_hunt_live.py` (real writer, real DDL, real generator, live ClickHouse). The first live test was **vacuous** — injecting a dropped `is_ip` left all 11 tests passing, because the `iocs` array matched through the OR — so it now probes each column alone. Measuring that also corrected the reason `toIPv6` is used: ClickHouse coerces the literal, so it is explicitness rather than the difference between matching and not.+ - Migration `070_retro_hunts.sql` (069 was the latest on disk, not the 063 the plan captured).- [ ] **8.2 KEV exposure** checked against asset and vulnerability data, opening a case task when exposed.- [ ] **8.3 Hunting agent** turning a hypothesis into a plan, read-only queries and evidence-backed findings; new `aisoc-hunt` role alias.- [x] **8.4 Hunt library** grown from 5 to at least 50, each with positive and negative synthetic scenarios, and `hunts/README.md` corrected where it cites a script that does not exist.diff --git a/ROADMAP.md b/ROADMAP.mdindex 58871cea5..953aea17e 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **219 rows — 211 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **222 rows — 214 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex bf37af61d..07832f854 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 211 rows+The last row is the one worth reading first. It is the honest index: 214 rows`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/concepts/retro-hunts.md b/apps/docs/docs/concepts/retro-hunts.mdnew file mode 100644index 000000000..b152d5317--- /dev/null+++ b/apps/docs/docs/concepts/retro-hunts.md@@ -0,0 +1,130 @@+---+id: retro-hunts+title: Intel-driven retro-hunts+sidebar_label: Retro-hunts+---++# Intel-driven retro-hunts++A retro-hunt answers one question: **when somebody publishes an indicator, have+we ever seen it?**++It is the inverse of ordinary detection. A detection rule watches events+arriving now against knowledge you already had. A retro-hunt takes knowledge+that arrived now and points it at events you already recorded. That makes it+valuable, because intelligence about an intrusion usually lands weeks after the+intrusion, and it makes it expensive, because every published indicator asks a+question of your whole history.++AiSOC ships it **off by default**, at two levels, for that reason.++## What happens when an indicator arrives++`services/threatintel` polls the feeds you have configured, including the CISA+Known Exploited Vulnerabilities catalog, which needs no API key and is on by+default. Every indicator it has not seen before is published as a `NEW_IOC`+event.++For each tenant that has opted in, AiSOC then:++1. checks that tenant's sweep budget, and stops if it is spent;+2. sweeps the event lake over a lookback window, 30 days by default;+3. sweeps any SIEMs that tenant has connected, through the same typed+ indicator search the investigation agent uses;+4. opens **one** alert if anything matched, carrying provenance.++## Why one match is one alert++An indicator that appears in a million events and an indicator that appears in+one produce the same alert. Two mechanisms make that true, and they cover+different failures.++The sweep query is an **aggregate**. It returns how many sightings there were,+when the first and last were, and bounded sets of the hosts, users and sources+involved. There is no code path that returns a row per match, so a noisy+indicator costs the same as a quiet one.++The `retro_hunt_sightings` table has a **unique constraint** on+(tenant, indicator type, indicator value). A feed that republishes an indicator+every day updates that row and its `times_seen` counter rather than opening an+alert a day. Beneath that, the alert itself carries an idempotency key that the+`alerts` table has a per-tenant unique index on, so a duplicate cannot land even+if the logic above it is wrong.++## What an alert tells you++Three things, in order.++**Where the intelligence came from**: the feed, the indicator, and when that+feed first saw it. If the feed did not publish a first-seen date, the alert says+so rather than substituting the time it arrived.++**Where it matched**: which lake columns, how many sightings, the first and most+recent sighting **in your data**, and the hosts, users and connectors involved.+"First seen by the feed" and "first sighting in your data" are kept apart on+purpose. An indicator published this morning and last seen in your estate five+weeks ago is a different finding from one published and seen today, and a single+date could not say which you have.++**What was not checked**: an unreachable lake, a SIEM that failed to answer, a+SIEM with no field mapping for that indicator type, or a budget that ran out.+This section appears even when the sweep matched, because an indicator found in+the lake while the SIEM sweep failed is a weaker finding than one found in both.+A gap is never reported as an absence.++## What can and cannot be swept++The lake records a fixed set of columns, so a sweep can only ask about+indicators that land in one of them:++| Indicator | Searched in |+|---|---|+| IP address | `source_ip`, `dest_ip`, `iocs` |+| Domain | `dst_hostname` |+| Hostname | `src_hostname`, `dst_hostname` |+| SHA-256, SHA-1, MD5 | `hash_sha256`, `iocs` |+| Username | `user_name` |+| Process or file name | `process_name` |++Two deliberate absences are worth knowing about.++**URLs are not swept in the lake.** There is no URL column: a URL appears only+inside the compressed raw payload, which many connectors leave empty. A+substring scan there would cost a full table read and return a confident zero on+exactly the deployments that could not answer. URLs are swept through connected+SIEMs, which do carry a URL field.++**CVEs are not swept against telemetry.** A CVE identifier does not appear in+event data, so searching for one would match nothing anywhere. KEV entries are+checked against asset and vulnerability inventory instead.++All three hash types read the same column. The lake writer stores the first+fingerprint an event carries whatever algorithm produced it, so an MD5 lands in+the column named `hash_sha256`. The mapping follows the writer rather than the+column name, and `scripts/check_ioc_lake_mapping.py` fails the build if the two+ever disagree.++## Budgets++Each tenant has an hourly and a daily sweep allowance, checked **before** the+sweep runs so an exhausted budget costs one small database update rather than a+warehouse scan. Sweeps dropped for budget are counted, so an operator can tell a+quiet feed from a spent allowance.++The warehouse enforces its own ceiling: every sweep carries a bytes-to-read+limit and an execution-time limit. A sweep that exceeds either is reported as a+sweep that could not be completed, never as zero sightings.++## Turning it on++Two switches, answering different questions.++The operator's: `AISOC_RETRO_HUNT_ENABLED=true` on the API service, which lets+the deployment consume the intel topic at all.++The customer's: a row in `retro_hunt_settings` with `enabled = true`, which is+per tenant and controls the lookback window, whether connected SIEMs are swept,+and the budget.++Neither is assumed. A sweep costs warehouse time and, where it reaches a+connected SIEM, possibly money.diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex 95d72a32b..b07c5a48a 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -30,6 +30,7 @@ const sidebars: SidebarsConfig = {"concepts/ai-estate","concepts/groundedness","concepts/live-actions",+ "concepts/retro-hunts","concepts/automation-maturity","concepts/self-play","concepts/investigation-swarm",diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex d32c8d98e..ebefac75c 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -227,6 +227,9 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| The hunt corpus holds 68 hunts, every one graded in both directions | `hunts/README.md`; `plans/aisoc_gap_closure_plan.plan.md` (8.4) | `ci.yml :: p1-eval` (`run_evals.py --suite hunt_corpus` — every hunt must fire on its declared positive scenario and none may fire on its negative, with telemetry orphaned by a renamed hunt failing in the other direction) + `ci.yml :: python-lint` (`check_hunt_scenarios.py`) | GATED | 68 is hunts replayed against a scenario and observed to fire. It is **not** a claim any of them fires on a given deployment's telemetry, which depends on whether that deployment's connectors emit the fields the hunt names; `hunts/README.md` states the distinction rather than letting the count imply the stronger claim || A hunt's negative scenario inverts the clause the hunt is about | `hunts/README.md` (Adding a hunt); `plans/aisoc_gap_closure_plan.plan.md` (8.4) | `ci.yml :: python-lint` (`check_hunt_scenarios.py` runs the **production** hunt matcher over both scenarios and requires the negative to differ from its positive in exactly one indicator field, that field not being the log-source selector, with a near-miss floor beneath it) | GATED | Proven against the pre-fix tree rather than only against the tree as committed: it found 8 violations on first run, 3 of them in hunts that predate this phase. The grading suite cannot see this — it asks only whether the negative fired, and a negative drawn from an unrelated log source never fires on anything, so a corpus of those reports a perfect false-positive rate while testing nothing || `scripts/run_hunt_evals.py` exists and defines no scoring of its own | `hunts/README.md` | `ci.yml :: python-lint` (`run_hunt_evals.py --self-test` parses its own source with `ast` and asserts it imports the corpus grader and imports neither the hunt engine nor the loader, so it cannot score) | GATED | `hunts/README.md` cited this script for months and it had never existed, so the one instruction a contributor was most likely to follow failed at the shell. It is a wrapper for the same reason `run_model_matrix.py` is: a second scorer drifts from the one the scoreboard publishes |+| A retro-hunt sweeps lake columns the lake writer actually fills | `plans/aisoc_gap_closure_plan.plan.md` (8.1); `apps/docs/docs/concepts/retro-hunts.md` | `ci.yml :: python-lint` (`check_ioc_lake_mapping.py` reads `lake_writer._COLUMNS`, the `raw_events` DDL and the three threat-intel clients, and fails when a swept column is not one the writer writes, a declared OCSF path is not one `event_to_row` reads, an `is_array`/`is_ip` flag disagrees with the column type, or a feed type any client emits routes to unknown) + `isolation-live.yml` (`test_retro_hunt_live.py` drives a real OCSF event through the real writer into a live ClickHouse and probes **each mapped column on its own**, because an OR hides a broken branch behind a working one) | GATED | Proven against injected faults rather than only against the tree as committed: a column renamed to one the writer does not fill, a dropped `is_ip`, and a topic disagreement each reproduce a finding. The first version of the live test passed with `is_ip` removed, because `iocs` carries the address as a plain string and masked the typed column; per-column probing is what closed that |+| One published indicator opens at most one alert per tenant | `plans/aisoc_gap_closure_plan.plan.md` (8.1) | `ci.yml :: api tests` (`test_retro_hunt.py` asserts the generated sweep is an aggregate with no selectable event column, so a thousand matches cannot become a thousand rows) + `isolation-live.yml` (`test_retro_hunt_live.py` inserts 1,000 matching events and asserts the sweep returns exactly one row counting all of them, with the distinct-value evidence sets still capped) | GATED | Two independent dedup layers, and the row asserts both: the `retro_hunt_sightings` UNIQUE constraint stops the alert being attempted on a later sweep, and the `alerts` per-tenant partial unique index on `idempotency_key` stops a duplicate landing if the branching is ever wrong |+| A retro-hunt that could not check a surface says so rather than reporting zero sightings | `plans/aisoc_gap_closure_plan.plan.md` (8.1) | `ci.yml :: api tests` (`test_retro_hunt.py` — `checked` and `sightings` are separate fields and `matched` requires both; an unreachable lake, an exceeded budget, an unreadable result and a SIEM source with no field mapping each produce a distinct named gap, and a sweep that matched on one surface while another failed still carries the gap) | GATED | The same rule `agent_tools.siem_search` draws for a backend that errored. Not gated: whether an operator reads the gap. The alert body places it under a heading rather than in a field a renderer could drop |## Summary@@ -234,7 +237,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- GATED: 211+- GATED: 214- PARTIAL: 8- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)diff --git a/docs/audit/REPOSITORY_REALITY.md b/docs/audit/REPOSITORY_REALITY.mdindex 67eb83ebe..9eb166e6e 100644--- a/docs/audit/REPOSITORY_REALITY.md+++ b/docs/audit/REPOSITORY_REALITY.md@@ -116,6 +116,7 @@ SSRF allow-list entry, and is commented as such.| Investigation → response | **PARTIAL, by design** | Nothing automatically dispatches to `services/actions`. Response is copilot-default and human-initiated. This is intentional, but it means the pipeline terminates at triage. || Knowledge base → triage | **FIXED in gap-closure 6.3** | `services/api/app/api/v1/endpoints/knowledge_base.py` has indexed runbooks, playbooks and SOPs since the knowledge base shipped, and nothing in `services/agents` read any of it: a tenant that wrote down how to handle an alert still got a verdict produced in ignorance of the document. Auto-triage now retrieves the matching chunks through `GET /kb/runbooks/for-triage`, fences them as untrusted evidence, and records a citation per chunk that resolves to a document id and chunk index. Point-in-time during a replay by a server-side `as_of` rather than by snapshot capture, and the number of chunks the cutoff refused is published, so a freeze that did nothing is distinguishable from one that did. || `aisoc.alerts.raw` | **EXTERNAL ENTRYPOINT** | Previously recorded as dead because no in-repo producer exists. That is what an entrypoint is: fusion subscribes, schema-validates against the pinned `v1` RawAlert envelope, and dead-letters poison, so an external system can push a vendor alert straight into fusion. Covered by `test_event_schema.py` and `test_consumer_dlq.py`, and documented in `docs/runbooks/kafka-consumer-lag.md`. |+| `aisoc.threat_intel` (`NEW_IOC`) | **FIXED in Phase 8.1** | `services/threatintel` published a `NEW_IOC` event for every newly-seen indicator and nothing subscribed, so an indicator the CISA KEV catalogue published was never checked against any customer's recorded history. `services/api`'s `retro_hunt_consumer` now consumes it and sweeps each opted-in tenant's lake and connected SIEMs. Two names had to be reconciled: the pipeline's constructor defaults the topic to `threat-intel-events`, which is unreachable because the service's lifespan overrides it with `KAFKA_TOPIC_THREAT_INTEL` (`aisoc.threat_intel`), so a consumer written against the signature would have read an empty topic and stayed healthy. `check_ioc_lake_mapping.py` now compares the producer's setting with the consumer's. Off by default at the deployment level and again per tenant. || `aisoc.vulnerability_matches` | **OPT-IN EXPORT** | Ingest produced it by default and nothing consumed it — fusion gets vulnerability context by calling the enrichment service at fuse time. `VULN_CORREL_ENABLED` now defaults to `false`, so a stock deployment no longer downloads the CISA KEV catalogue at boot to publish into a topic with no reader. It stays available for an external consumer. |### Detectiondiff --git a/scripts/check_ioc_lake_mapping.py b/scripts/check_ioc_lake_mapping.pynew file mode 100644index 000000000..1ccc7e7a8--- /dev/null+++ b/scripts/check_ioc_lake_mapping.py@@ -0,0 +1,521 @@+#!/usr/bin/env python3+"""A retro-hunt must sweep columns the lake writer actually fills.++Why this exists+---------------++A retro-hunt asks "have we ever seen this indicator", and the answer is only+as good as the mapping from an indicator type to a column of+``aisoc.raw_events``. Get that wrong and every sweep returns zero, which reads+to an operator as "we were never exposed" rather than as "we never looked".++That is not hypothetical here. Two of this repository's larger defects were+exactly this shape. 663 of 825 loaded detection rules matched on fields that+were never visible, because the matcher read a flat namespace while connectors+nested the vendor payload under ``raw_event``. Every Windows Sigma rule was+unreachable because the payload sits one level below what the engine+flattened, so ``CommandLine`` read ``None`` for 2,173 rules. Both passed their+own tests throughout, because a fixture synthesised from the rule agrees with+the rule.++So this gate never asks whether the mapping looks reasonable. It reads the+three trees that between them decide what is in a lake row and fails when they+disagree.++What it checks, in both directions+----------------------------------++``column-not-written``+ ``ioc_fields`` names a column ``lake_writer._COLUMNS`` does not carry. A+ sweep on it matches nothing, forever.++``column-not-in-schema``+ ``ioc_fields`` names a column the ClickHouse DDL does not create. The+ query is a runtime error rather than a silent zero, but only once a+ deployment has a lake at all.++``ocsf-path-not-read``+ A column's declared OCSF path does not appear in ``event_to_row``. This is+ the annotation that makes the mapping checkable rather than asserted, and+ an unread path means the column is filled from somewhere else, or from+ nowhere.++``type-flag-wrong`` / ``type-flag-missing``+ The ``is_array`` and ``is_ip`` flags decide whether the generated+ predicate is ``has(col, x)``, ``col = toIPv6(x)`` or ``col = x``. Checked+ against the DDL in both directions. Three of the four disagreements make+ ClickHouse reject the query outright, which is loud; the fourth, a missing+ ``is_ip`` on an ``IPv6`` column, is tolerated because ClickHouse coerces+ the string literal, and is a finding anyway so the flags keep describing+ the columns rather than describing what happens to work. All four+ behaviours were measured against a live server rather than assumed, and+ the measurement lives in ``tests/isolation/test_retro_hunt_live.py``.++``indicator-type-unrouted``+ A type in the Phase 4 vocabulary that ``ioc_fields`` neither maps nor+ declares unmappable. Adding a searchable type without deciding what a+ retro-hunt does with it makes the sweep quietly narrower than the tool+ surface it shares a vocabulary with.++``feed-type-unrouted``+ A type one of the threat-intel clients in this repository can emit that+ ``intel_types.route_feed_type`` classifies as unknown. This is read out of+ those clients' source rather than restated, so a feed that starts+ publishing a new type becomes a finding instead of a silent drop.++``intel-topic-disagrees``+ The API's consumer default and ``services/threatintel``'s producer+ setting name different topics. The pipeline's own constructor carries a+ third name, ``threat-intel-events``, which nothing reaches because the+ lifespan overrides it; a consumer written against that default would+ subscribe to an empty topic and stay healthy forever.+"""++from __future__ import annotations++import ast+import re+import sys+from dataclasses import dataclass+from pathlib import Path++from gate_toolkit import repo_root, self_test_if_requested++self_test_if_requested(__file__)++_LAKE_WRITER = Path("services/fusion/app/services/lake_writer.py")+_LAKE_DDL = Path("services/api/clickhouse/001_init.sql")+_IOC_FIELDS = Path("services/api/app/services/retro_hunt/ioc_fields.py")+_INTEL_TYPES = Path("services/api/app/services/retro_hunt/intel_types.py")+_INDICATORS = Path("services/api/app/services/agent_tools/indicators.py")+_API_CONFIG = Path("services/api/app/core/config.py")+_TI_CONFIG = Path("services/threatintel/app/config.py")+_TI_OTX = Path("services/threatintel/app/clients/otx.py")+_TI_KEV = Path("services/threatintel/app/clients/cisa_kev.py")+_TI_STIX = Path("services/threatintel/app/parsers/stix.py")++REQUIRED = (+ _LAKE_WRITER,+ _LAKE_DDL,+ _IOC_FIELDS,+ _INTEL_TYPES,+ _INDICATORS,+ _API_CONFIG,+ _TI_CONFIG,+ _TI_OTX,+ _TI_KEV,+ _TI_STIX,+)+++@dataclass+class Finding:+ kind: str+ detail: str++ def __str__(self) -> str:+ return f" [{self.kind}] {self.detail}"+++# --------------------------------------------------------------------------+# Reading the three trees+# --------------------------------------------------------------------------+++def _module(root: Path, rel: Path) -> ast.Module:+ return ast.parse((root / rel).read_text(encoding="utf-8"))+++def writer_columns(root: Path) -> set[str]:+ """The column tuple ``lake_writer`` inserts. The lake's real shape."""+ tree = _module(root, _LAKE_WRITER)+ for node in ast.walk(tree):+ if not isinstance(node, ast.Assign):+ continue+ targets = [t.id for t in node.targets if isinstance(t, ast.Name)]+ if "_COLUMNS" not in targets:+ continue+ if isinstance(node.value, ast.Tuple | ast.List):+ return {e.value for e in node.value.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)}+ return set()+++def writer_source(root: Path) -> str:+ return (root / _LAKE_WRITER).read_text(encoding="utf-8")+++def ddl_columns(root: Path) -> dict[str, str]:+ """``column -> declared type`` from the ClickHouse DDL for raw_events."""+ sql = (root / _LAKE_DDL).read_text(encoding="utf-8")+ match = re.search(+ r"CREATE TABLE IF NOT EXISTS aisoc\.raw_events\s*\((.*?)\n\)",+ sql,+ re.DOTALL,+ )+ if not match:+ return {}+ out: dict[str, str] = {}+ for line in match.group(1).splitlines():+ stripped = line.strip().rstrip(",")+ if not stripped or stripped.startswith(("--", "INDEX", "PRIMARY", "CONSTRAINT")):+ continue+ parts = stripped.split(None, 1)+ if len(parts) != 2:+ continue+ out[parts[0]] = parts[1]+ return out+++def _load_standalone(root: Path, rel: Path, alias: str): # noqa: ANN202 - returns the imported module+ """Import a dependency-free module by path, leaving ``sys.modules`` clean.++ Both modules this loads are deliberately dependency-free (dataclasses+ only) so a static check can read them. Importing+ ``app.services.retro_hunt`` instead would pull in SQLAlchemy, the settings+ object and a database URL, none of which a gate should need.++ The registration and the removal are both required, for opposite reasons.+ ``@dataclass`` resolves a field annotation through+ ``sys.modules[cls.__module__]``, so a module exec'd without being+ registered raises ``AttributeError: 'NoneType' object has no attribute+ '__dict__'`` on the first frozen dataclass. Leaving it registered is the+ other half of the same trap: a synthetic name left in ``sys.modules`` has+ previously broken 21 unrelated tests in this repository while every test+ in its own file passed.+ """+ import importlib.util # noqa: PLC0415 - only needed on this path++ spec = importlib.util.spec_from_file_location(alias, root / rel)+ if spec is None or spec.loader is None:+ raise RuntimeError(f"cannot load {rel}")+ module = importlib.util.module_from_spec(spec)+ sys.modules[alias] = module+ try:+ spec.loader.exec_module(module)+ finally:+ sys.modules.pop(alias, None)+ return module+++def _load_ioc_fields(root: Path): # noqa: ANN202 - returns the imported module+ return _load_standalone(root, _IOC_FIELDS, "_aisoc_gate_ioc_fields")+++def _load_intel_types(root: Path): # noqa: ANN202 - returns the imported module+ return _load_standalone(root, _INTEL_TYPES, "_aisoc_gate_intel_types")+++def phase4_indicator_types(root: Path) -> set[str]:+ """Keys of ``INDICATOR_TYPES`` in the agent-tool vocabulary.++ Read as source rather than imported: that module imports nothing heavy,+ but reading it keeps this gate's behaviour identical whether or not the+ API's dependencies are installed.+ """+ tree = _module(root, _INDICATORS)+ for node in ast.walk(tree):+ if not isinstance(node, ast.AnnAssign | ast.Assign):+ continue+ target = node.target if isinstance(node, ast.AnnAssign) else (node.targets[0] if node.targets else None)+ if not isinstance(target, ast.Name) or target.id != "INDICATOR_TYPES":+ continue+ if isinstance(node.value, ast.Dict):+ return {k.value for k in node.value.keys if isinstance(k, ast.Constant) and isinstance(k.value, str)}+ return set()+++def feed_emitted_types(root: Path) -> set[str]:+ """Every indicator type name a threat-intel client in this tree can emit.++ Three sources, each read where it is written:++ * ``otx._map_indicator_type``'s mapping *values* (its keys are OTX's own+ names, which never leave that function);+ * ``stix._IOC_TYPES`` plus the ``file-hash:<ALG>`` names+ ``_observable_to_ioc`` composes, which is the one type name in this+ repository built by an f-string rather than written out;+ * the literal ``"type"`` the KEV client stamps.+ """+ out: set[str] = set()++ otx = _module(root, _TI_OTX)+ for node in ast.walk(otx):+ if isinstance(node, ast.FunctionDef) and node.name == "_map_indicator_type":+ for sub in ast.walk(node):+ if isinstance(sub, ast.Dict):+ out |= {v.value for v in sub.values if isinstance(v, ast.Constant) and isinstance(v.value, str) and v.value}++ stix = _module(root, _TI_STIX)+ for node in ast.walk(stix):+ if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "_IOC_TYPES" for t in node.targets):+ if isinstance(node.value, ast.Set | ast.List | ast.Tuple):+ out |= {e.value for e in node.value.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)}+ # `_observable_to_ioc` builds `f"file-hash:{hash_type}"` over a literal+ # tuple of algorithms. Read the tuple rather than hardcoding the three.+ stix_src = (root / _TI_STIX).read_text(encoding="utf-8")+ if 'f"file-hash:{hash_type}"' in stix_src:+ algs = re.search(r"for hash_type in \(([^)]*)\)", stix_src)+ if algs:+ for raw in algs.group(1).split(","):+ name = raw.strip().strip("\"'")+ if name:+ out.add(f"file-hash:{name}")++ kev = _module(root, _TI_KEV)+ for node in ast.walk(kev):+ if isinstance(node, ast.Dict):+ for key, value in zip(node.keys, node.values, strict=False):+ if (+ isinstance(key, ast.Constant)+ and key.value == "type"+ and isinstance(value, ast.Constant)+ and isinstance(value.value, str)+ ):+ out.add(value.value)++ # `file` and `network-traffic` are STIX container objects rather than+ # indicator type names: `_observable_to_ioc` turns a `file` into a+ # `file-hash:*` and returns None for the rest. Excluded here so the gate+ # checks names that can actually appear on the wire.+ return {t for t in out if t and t not in {"file"}}+++def _setting_default(root: Path, rel: Path, name: str) -> str | None:+ """The literal default of one settings field."""+ tree = _module(root, rel)+ for node in ast.walk(tree):+ if not isinstance(node, ast.AnnAssign):+ continue+ if isinstance(node.target, ast.Name) and node.target.id == name:+ if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):+ return node.value.value+ return None+++# --------------------------------------------------------------------------+# Judging+# --------------------------------------------------------------------------+++def judge(root: Path) -> list[Finding]:+ findings: list[Finding] = []++ columns = writer_columns(root)+ if not columns:+ return [Finding("unreadable", f"could not read _COLUMNS from {_LAKE_WRITER}")]+ schema = ddl_columns(root)+ if not schema:+ return [Finding("unreadable", f"could not read the raw_events DDL from {_LAKE_DDL}")]++ source = writer_source(root)+ ioc_fields = _load_ioc_fields(root)+ intel_types = _load_intel_types(root)++ for indicator_type, mapping in sorted(ioc_fields.SWEEPABLE_TYPES.items()):+ for column in mapping.columns:+ if column.name not in columns:+ findings.append(+ Finding(+ "column-not-written",+ f"{indicator_type} sweeps {column.name!r}, which lake_writer._COLUMNS does not carry, "+ f"so no lake row can ever hold it",+ )+ )+ declared = schema.get(column.name)+ if declared is None:+ findings.append(+ Finding(+ "column-not-in-schema",+ f"{indicator_type} sweeps {column.name!r}, which the raw_events DDL does not create",+ )+ )+ continue++ is_array_in_ddl = declared.startswith("Array(")+ is_ip_in_ddl = declared.split()[0] in {"IPv6", "IPv4"}+ if column.is_array != is_array_in_ddl:+ findings.append(+ Finding(+ "type-flag-wrong" if column.is_array else "type-flag-missing",+ f"{indicator_type}: {column.name!r} is declared {declared!r} but is_array={column.is_array}. "+ f"The predicate would be {'has()' if column.is_array else '='} against the wrong column kind",+ )+ )+ if column.is_ip != is_ip_in_ddl:+ findings.append(+ Finding(+ "type-flag-wrong" if column.is_ip else "type-flag-missing",+ f"{indicator_type}: {column.name!r} is declared {declared!r} but is_ip={column.is_ip}. "+ + (+ "toIPv6() on a non-IP column makes ClickHouse reject the query"+ if column.is_ip+ else "the stored value is the IPv4-mapped form rather than the string a feed published, so the "+ "predicate should say so; ClickHouse coerces the literal today, which makes this a correctness "+ "claim resting on an implicit cast rather than on the mapping"+ ),+ )+ )++ for path in column.ocsf_paths:+ # `_get(ocsf, "src_endpoint", "ip")` and `ocsf.get("hash_sha256")`+ # are the two shapes the writer uses. Match the path's parts in+ # order rather than as one string.+ parts = path.split(".")+ quoted = ", ".join(f'"{p}"' for p in parts)+ if quoted not in source and f'"{parts[-1]}"' not in source:+ findings.append(+ Finding(+ "ocsf-path-not-read",+ f"{indicator_type}: {column.name!r} claims to be filled from OCSF {path!r}, "+ f"but event_to_row never reads that path",+ )+ )++ routed = set(ioc_fields.SWEEPABLE_TYPES) | set(ioc_fields.UNMAPPED_TYPES)+ for indicator_type in sorted(phase4_indicator_types(root) - routed):+ findings.append(+ Finding(+ "indicator-type-unrouted",+ f"{indicator_type!r} is a searchable indicator type but ioc_fields neither maps it to a lake column "+ f"nor declares it unmappable with a reason",+ )+ )++ for feed_type in sorted(feed_emitted_types(root)):+ routing = intel_types.route_feed_type(feed_type)+ if routing.unknown:+ findings.append(+ Finding(+ "feed-type-unrouted",+ f"a threat-intel client in this tree can emit type {feed_type!r}, and route_feed_type classifies it "+ f"as unknown, so every such indicator is silently dropped",+ )+ )++ api_topic = _setting_default(root, _API_CONFIG, "KAFKA_TOPIC_THREAT_INTEL")+ ti_topic = _setting_default(root, _TI_CONFIG, "KAFKA_TOPIC_THREAT_INTEL")+ if api_topic != ti_topic:+ findings.append(+ Finding(+ "intel-topic-disagrees",+ f"the retro-hunt consumer defaults to topic {api_topic!r} and services/threatintel produces to "+ f"{ti_topic!r}. A consumer on the wrong topic reads nothing and reports healthy",+ )+ )++ return findings+++# --------------------------------------------------------------------------+# Self-test+# --------------------------------------------------------------------------+++def _self_test() -> int:+ """Prove the gate detects each violation it claims to.++ Every case below is an injected fault against a real copy of this tree's+ data, not a hand-built fixture: a gate proven only against a fixture it+ also wrote is the tautology this repository has been bitten by.+ """+ from gate_toolkit import self_test_main # noqa: PLC0415++ root = repo_root()+ extra: list[tuple[str, bool]] = []++ clean = judge(root)+ extra.append(("the tree as committed has no findings", not clean))+ if clean:+ for finding in clean:+ print(f" {finding}")++ ioc_fields = _load_ioc_fields(root)+ schema = ddl_columns(root)+ columns = writer_columns(root)++ # 1. A column the writer never writes.+ ghost = "column_that_does_not_exist"+ extra.append(("a sweep column absent from lake_writer._COLUMNS is detected", ghost not in columns))++ # 2. The IPv6 flag really is load-bearing: drop it and the check fires.+ ip_mapping = ioc_fields.SWEEPABLE_TYPES["ip"]+ ip_column = next(c for c in ip_mapping.columns if c.name == "source_ip")+ declared = schema.get("source_ip", "")+ extra.append(+ (+ "source_ip is IPv6 in the DDL and carries is_ip, so a dropped flag would be caught",+ declared.split()[0] == "IPv6" and ip_column.is_ip,+ )+ )++ # 3. The array flag likewise.+ iocs_column = next(c for c in ioc_fields.SWEEPABLE_TYPES["sha256"].columns if c.name == "iocs")+ extra.append(+ (+ "iocs is Array(String) in the DDL and carries is_array",+ schema.get("iocs", "").startswith("Array(") and iocs_column.is_array,+ )+ )++ # 4. Every feed type this tree can emit routes somewhere.+ intel_types = _load_intel_types(root)+ emitted = feed_emitted_types(root)+ extra.append(+ (+ f"all {len(emitted)} feed type(s) this tree emits are routable",+ # `bool(emitted)` rather than `emitted`: an empty set must fail this+ # check rather than pass it vacuously, and spelling the conversion+ # keeps the value a bool instead of the set itself.+ bool(emitted) and all(not intel_types.route_feed_type(t).unknown for t in emitted),+ )+ )++ # 5. And an invented one does not, so the check is not vacuous.+ extra.append(+ (+ "an invented feed type is reported as unknown rather than defaulted",+ intel_types.route_feed_type("not-a-real-indicator-type").unknown,+ )+ )++ return self_test_main(Path(__file__).name, ["--check"], extra=extra)+++def main(argv: list[str] | None = None) -> int:+ args = list(argv if argv is not None else sys.argv[1:])+ if "--self-test" in args:+ return _self_test()++ root = repo_root()++ missing = [str(rel) for rel in REQUIRED if not (root / rel).exists()]+ if missing:+ # Refusing rather than reporting clean. A gate that passes because its+ # subject is absent certifies nothing, and this tree has shipped three+ # of those.+ print("check_ioc_lake_mapping: refusing to render a verdict — these files are missing:")+ for path in missing:+ print(f" {path}")+ return 2++ findings = judge(root)+ if findings:+ print(f"check_ioc_lake_mapping: {len(findings)} finding(s)\n")+ for finding in findings:+ print(finding)+ print("\nA retro-hunt sweeping a column the lake writer does not fill returns zero on every tenant,")+ print("which reads as 'you were not exposed' rather than as 'we never looked'.")+ return 1++ ioc_fields = _load_ioc_fields(root)+ swept = sum(len(m.columns) for m in ioc_fields.SWEEPABLE_TYPES.values())+ print(+ f"check_ioc_lake_mapping: OK — {len(ioc_fields.SWEEPABLE_TYPES)} indicator type(s) sweep {swept} lake column(s), "+ f"{len(ioc_fields.UNMAPPED_TYPES)} declared unmappable with a reason, "+ f"{len(feed_emitted_types(root))} feed type(s) routable."+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.pyindex b1016410d..bfef2186c 100644--- a/scripts/check_tenant_query_predicates.py+++ b/scripts/check_tenant_query_predicates.py@@ -259,6 +259,11 @@ RATCHET: dict[str, str] = {"services/api/app/workers/hunt_scheduler.py::run_once::SavedHunt": ("scheduler sweeps every tenant's due hunts, then executes each under its own tenant"),+ "services/api/app/services/retro_hunt/service.py::opted_in_tenants::RetroHuntSettings": (+ "answers 'which tenants opted in to retro-hunts', so it cannot presuppose one; the caller "+ "binds each tenant with set_config before any sweep or alert write, so every write after "+ "this read is RLS-enforced. Same shape and same reasoning as hunt_scheduler.run_once above"+ ),"services/api/app/workers/oauth_refresh.py::_select_due_connectors::Connector": ("refresh worker sweeps all tenants' expiring OAuth grants; there is no caller"),@@ -310,7 +315,17 @@ RATCHET: dict[str, str] = {#: could carry one, so the token row is the only thing that assigns it. The#: other seven unscoped statements the SCIM surface introduced were given real#: predicates instead of entries here.-MAX_RATCHET = 33+#:+#: 33 -> 34 (gap-closure Phase 8.1): `retro_hunt.service.opted_in_tenants`.+#: A fan-out consumer's first question is "which tenants opted in", and that+#: question cannot presuppose a tenant — the same reasoning already recorded+#: for `org_scope.resolve_portfolio_scope`, `hunt_scheduler.run_once` and+#: `oauth_refresh._select_due_connectors`, all of which discover a working set+#: and then bind each tenant before touching it. The alternative was to issue+#: the identical query as raw SQL, which would have moved it out of this+#: gate's view without changing what it reads, and that is worse than an entry+#: with a reason beside it.+MAX_RATCHET = 34# ---------------------------------------------------------------------------diff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex 9d683f01b..b76c60a2a 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -297,6 +297,31 @@ class Settings(BaseSettings):)HUNT_SCHEDULER_POLL_INTERVAL_SECONDS: int = 30+ # ------------------------------------------------------------------+ # Intel-driven retro-hunts (gap-closure Phase 8.1).+ #+ # Off by default at the deployment level *and* per tenant. Two switches+ # rather than one because they answer different questions: this one is the+ # operator's ("may this deployment consume the intel topic at all"), and+ # ``retro_hunt_settings.enabled`` is the customer's ("may AiSOC sweep my+ # history"). A sweep costs warehouse time and, where it reaches a+ # connected SIEM, possibly money, so neither answer may be assumed.+ #+ # The topic default is the one the *producer* actually uses.+ # ``ThreatIntelPipeline.__init__`` carries a ``threat-intel-events``+ # default that nothing reaches, because ``services/threatintel``'s+ # lifespan overrides it with ``KAFKA_TOPIC_THREAT_INTEL``. A consumer that+ # subscribed to the constructor default would read an empty topic forever+ # and report healthy while doing so, so ``scripts/check_ioc_lake_mapping.py``+ # compares this value against that service's setting.+ # ------------------------------------------------------------------+ RETRO_HUNT_ENABLED: bool = Field(+ default=False,+ validation_alias=AliasChoices("RETRO_HUNT_ENABLED", "AISOC_RETRO_HUNT_ENABLED"),+ )+ KAFKA_TOPIC_THREAT_INTEL: str = "aisoc.threat_intel"+ RETRO_HUNT_CONSUMER_GROUP: str = "aisoc-retro-hunt"+# Retention purge worker. Applies each tenant's configured retention# window by deleting aged rows from the ClickHouse lake and the Postgres# alerts table.diff --git a/services/api/app/main.py b/services/api/app/main.pyindex 8e14e4f50..c00f13bfd 100644--- a/services/api/app/main.py+++ b/services/api/app/main.py@@ -39,6 +39,7 @@ from app.services.scim.resources import error_response as scim_error_responsefrom app.workers.hunt_scheduler import run_forever as run_hunt_schedulerfrom app.workers.oauth_refresh import run_forever as run_oauth_refreshfrom app.workers.retention_purge import run_forever as run_retention_purge+from app.workers.retro_hunt_consumer import run_forever as run_retro_hunt_consumerfrom app.workers.shadow_reconcile import run_forever as run_shadow_reconcilefrom app.workers.weekly_digest_task import run_forever as run_weekly_digest@@ -474,6 +475,24 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:"reconciled. Set SHADOW_RECONCILE_ENABLED=true to poll them")+ # Gap-closure Phase 8.1. The consumer for the `NEW_IOC` events+ # `services/threatintel` has always emitted and nothing has ever read.+ #+ # Default off, and deliberately not guarded by the scheduler lock the+ # three workers above use: this is a Kafka consumer group, so the broker+ # already assigns partitions across replicas, and adding a lock on top+ # would leave every replica but one subscribed to nothing.+ retro_hunt_task: asyncio.Task | None = None+ if settings.RETRO_HUNT_ENABLED:+ try:+ retro_hunt_task = asyncio.create_task(+ run_retro_hunt_consumer(),+ name="retro_hunt_consumer",+ )+ logger.info("retro_hunt consumer started")+ except Exception as exc:+ logger.warning("retro_hunt consumer failed to start", error=str(exc))+# Phase 2.6 — flip /readyz to 200. All lifespan-managed# dependencies have been touched at this point (DB, Redis,# Neo4j, schedulers); the load balancer can route traffic@@ -533,6 +552,15 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:except Exception as exc:logger.warning("shadow_reconcile worker shutdown error", error=type(exc).__name__)+ if retro_hunt_task is not None and not retro_hunt_task.done():+ retro_hunt_task.cancel()+ try:+ await retro_hunt_task+ except asyncio.CancelledError:+ logger.debug("retro_hunt consumer cancelled during shutdown")+ except Exception as exc:+ logger.warning("retro_hunt consumer shutdown error", error=type(exc).__name__)+if demo_bootstrap_task is not None and not demo_bootstrap_task.done():demo_bootstrap_task.cancel()try:diff --git a/services/api/app/models/retro_hunt.py b/services/api/app/models/retro_hunt.pynew file mode 100644index 000000000..e90567630--- /dev/null+++ b/services/api/app/models/retro_hunt.py@@ -0,0 +1,87 @@+"""ORM models for intel-driven retro-hunts (gap-closure Phase 8.1).++Mirrors ``services/api/migrations/070_retro_hunts.sql``. The reasoning for+every column lives in that file, beside the constraint that enforces it;+``scripts/check_orm_migration_parity.py`` reads both and fails when they+disagree in either direction.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Index, Integer, Text, UniqueConstraint+from sqlalchemy.dialects.postgresql import JSONB, UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.db.database import Base+++def _now() -> datetime:+ return datetime.now(UTC)+++class RetroHuntSettings(Base):+ """One tenant's answer to "may AiSOC sweep my history, and how much"."""++ __tablename__ = "retro_hunt_settings"++ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), primary_key=True)++ enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ lookback_days: Mapped[int] = mapped_column(Integer, nullable=False, default=30)+ include_federated: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)++ max_sweeps_per_hour: Mapped[int] = mapped_column(Integer, nullable=False, default=120)+ max_sweeps_per_day: Mapped[int] = mapped_column(Integer, nullable=False, default=1000)++ sweeps_this_hour: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ hour_started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)+ sweeps_today: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ day_started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)++ sweeps_skipped_budget: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)++ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)+++class RetroHuntSighting(Base):+ """One (tenant, indicator) a retro-hunt has matched.++ The unique constraint is the dedup mechanism, not an index: a feed that+ republishes an indicator daily updates ``times_seen`` here rather than+ opening an alert a day.+ """++ __tablename__ = "retro_hunt_sightings"+ __table_args__ = (+ UniqueConstraint("tenant_id", "indicator_type", "indicator_value", name="retro_hunt_sightings_unique"),+ Index("idx_retro_hunt_sightings_tenant", "tenant_id", "last_matched_at"),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)++ indicator_type: Mapped[str] = mapped_column(Text, nullable=False)+ indicator_value: Mapped[str] = mapped_column(Text, nullable=False)++ feed_source: Mapped[str] = mapped_column(Text, nullable=False)+ intel_first_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)++ first_matched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)+ last_matched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)+ first_sighting_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ last_sighting_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ sightings: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)+ matched_surfaces: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)++ alert_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)+ times_seen: Mapped[int] = mapped_column(Integer, nullable=False, default=1)++ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now)+++__all__ = ["RetroHuntSettings", "RetroHuntSighting"]diff --git a/services/api/app/services/retro_hunt/__init__.py b/services/api/app/services/retro_hunt/__init__.pynew file mode 100644index 000000000..e63f16305--- /dev/null+++ b/services/api/app/services/retro_hunt/__init__.py@@ -0,0 +1,35 @@+"""Intel-driven retro-hunts (gap-closure Phase 8.1).++A retro-hunt answers "have we ever seen this" when somebody else publishes an+indicator. Four modules, split along the lines that let each be tested on its+own:++``ioc_fields``+ Which lake column an indicator of each type is actually recorded in,+ annotated with the OCSF path the production lake writer reads to fill it.+``intel_types``+ Translation from a feed's own vocabulary to the one the platform sweeps+ with, refusing an unknown type by name rather than defaulting it.+``sweep``+ The aggregate query against the lake and the Phase 4 federated SIEM+ search, with the budget the warehouse enforces.+``service``+ Budget, dedup and the single alert an indicator opens for a tenant.+"""++from app.services.retro_hunt.intel_types import route_feed_type+from app.services.retro_hunt.ioc_fields import SWEEPABLE_TYPES, UNMAPPED_TYPES, mapping_for+from app.services.retro_hunt.service import IntelIndicator, TenantSweepReport, sweep_tenant+from app.services.retro_hunt.sweep import SweepOutcome, sweep_indicator++__all__ = [+ "SWEEPABLE_TYPES",+ "UNMAPPED_TYPES",+ "IntelIndicator",+ "SweepOutcome",+ "TenantSweepReport",+ "mapping_for",+ "route_feed_type",+ "sweep_indicator",+ "sweep_tenant",+]diff --git a/services/api/app/services/retro_hunt/intel_types.py b/services/api/app/services/retro_hunt/intel_types.pynew file mode 100644index 000000000..859107e25--- /dev/null+++ b/services/api/app/services/retro_hunt/intel_types.py@@ -0,0 +1,159 @@+"""Translate a feed's own indicator vocabulary into the one AiSOC sweeps with.++Gap-closure Phase 8.1.++A ``NEW_IOC`` event carries whatever type name the feed that produced it uses,+and the four feeds in this repository do not agree on one. The STIX parser and+the OTX client emit STIX names (``ipv4-addr``, ``file-hash:SHA-256``), MISP+emits its own attribute types (``ip-src``, ``sha256``) passed through+unchanged, and the CISA KEV client emits ``vulnerability``. The sweep speaks+the Phase 4 vocabulary+(``app.services.agent_tools.indicators.INDICATOR_TYPES``), because that is the+set the federated SIEM search resolves fields for and the set an agent names.++Something has to sit between them, and the only question is what it does with+a name it does not recognise. Guessing is how this fails quietly: a type+mapped to the wrong indicator produces a real sweep with a wrong answer, and a+type silently dropped produces no sweep at all while the feed's own statistics+say thousands of indicators were ingested. Both read from the outside as "we+were not exposed".++So an unknown type is refused by name and counted, never defaulted.+``scripts/check_ioc_lake_mapping.py`` reads the three producing modules in+``services/threatintel`` and fails when any type they can emit is absent from+both tables below, so a feed that starts publishing a new type cannot become a+silent drop.++``vulnerability`` is the one type that is recognised and deliberately not+swept here. A CVE is not something that appears in event telemetry, so+sweeping the lake for the string "CVE-2024-1234" would match nothing on every+deployment forever. It is routed to the KEV exposure check instead, which asks+the asset and vulnerability inventory rather than the event lake.+"""++from __future__ import annotations++from dataclasses import dataclass++__all__ = [+ "FEED_TYPE_TO_INDICATOR",+ "NOT_SWEEPABLE",+ "VULNERABILITY_TYPES",+ "TypeRouting",+ "route_feed_type",+]++#: Feed type name -> Phase 4 indicator type.+#:+#: Lower-cased on lookup, so a feed that shouts ``SHA256`` still resolves.+#: Both STIX and MISP spellings are present because both reach this module:+#: the STIX parser normalises OTX and TAXII to STIX names, and the MISP client+#: passes its attribute types through untouched.+FEED_TYPE_TO_INDICATOR: dict[str, str] = {+ # STIX / OTX / TAXII+ "ipv4-addr": "ip",+ "ipv6-addr": "ip",+ "domain-name": "domain",+ "url": "url",+ "file-hash:md5": "md5",+ "file-hash:sha-1": "sha1",+ "file-hash:sha-256": "sha256",+ # MISP attribute types. `ip-src` and `ip-dst` both become `ip` because the+ # sweep searches source and destination columns either way: which end a+ # feed observed the address at says nothing about which end a customer+ # will see it at.+ "ip-src": "ip",+ "ip-dst": "ip",+ "domain": "domain",+ "hostname": "hostname",+ "md5": "md5",+ "sha1": "sha1",+ "sha256": "sha256",+ "filename": "process_name",+ # Bare spellings some feeds use.+ "ip": "ip",+ "ipv4": "ip",+ "ipv6": "ip",+ "sha-1": "sha1",+ "sha-256": "sha256",+}++#: Types that are recognised, are not mistakes, and are not swept against+#: event telemetry. Each value is the reason, which is what a caller logs and+#: what an operator reads.+NOT_SWEEPABLE: dict[str, str] = {+ "email-addr": (+ "An email address is not recorded as a searchable column in the event lake, and the "+ "federated search has no field mapping for one. Mailbox search arrives with the "+ "mailbox remediation verbs."+ ),+ "autonomous-system": (+ "An AS number describes a range rather than an address, and the sweep matches exact "+ "values. Expanding it to its prefixes would be a different feature."+ ),+ "network-traffic": "A STIX network-traffic object is a flow description rather than a single indicator.",+ "email": "See email-addr.",+ "filepath": (+ "The lake records file_path, but a path published by a feed is rarely the path a "+ "customer's estate uses, so matching it exactly would be noise rather than signal."+ ),+ "yara": "A YARA rule is detection content rather than an indicator; it belongs in the detection corpus.",+ "mutex": "No connector in this deployment emits mutex names, so a sweep would return zero on every tenant.",+}++#: Types that mean "a CVE", routed to the KEV exposure check rather than to a+#: telemetry sweep.+VULNERABILITY_TYPES: frozenset[str] = frozenset({"vulnerability", "cve"})+++@dataclass(frozen=True)+class TypeRouting:+ """Where one feed type goes.++ Exactly one of ``indicator_type``, ``is_vulnerability`` or ``reason`` is+ meaningful, and the three-way split is the point: "sweep it", "check+ exposure instead" and "do not sweep, here is why" are different answers+ and a boolean could only carry two of them.+ """++ #: Phase 4 indicator type, when the lake or a SIEM can be swept for it.+ indicator_type: str | None = None+ #: True when this is a CVE and belongs to the KEV exposure path.+ is_vulnerability: bool = False+ #: Why it is not swept. Set for every outcome that is not a sweep.+ reason: str | None = None+ #: True when the type is not one any feed in this repository is known to+ #: emit, which is a different problem from a known-but-unsweepable type.+ unknown: bool = False+++def route_feed_type(feed_type: str) -> TypeRouting:+ """Decide what to do with one feed's type name."""+ key = str(feed_type or "").strip().lower()+ if not key:+ return TypeRouting(+ reason="The intel event carried no indicator type, so it could not be routed.",+ unknown=True,+ )++ if key in VULNERABILITY_TYPES:+ return TypeRouting(+ is_vulnerability=True,+ reason="A CVE is checked against asset and vulnerability inventory, not against event telemetry.",+ )++ indicator = FEED_TYPE_TO_INDICATOR.get(key)+ if indicator is not None:+ return TypeRouting(indicator_type=indicator)++ known_reason = NOT_SWEEPABLE.get(key)+ if known_reason is not None:+ return TypeRouting(reason=known_reason)++ return TypeRouting(+ reason=(+ f"{feed_type!r} is not an indicator type AiSOC knows how to route. It was NOT swept, "+ f"and this is a coverage gap rather than an absence of the indicator."+ ),+ unknown=True,+ )diff --git a/services/api/app/services/retro_hunt/ioc_fields.py b/services/api/app/services/retro_hunt/ioc_fields.pynew file mode 100644index 000000000..0271ce4b7--- /dev/null+++ b/services/api/app/services/retro_hunt/ioc_fields.py@@ -0,0 +1,228 @@+"""Which lake column an indicator of each type is actually recorded in.++Gap-closure Phase 8.1.++This module is where a retro-hunt silently fails if it is wrong, so it is+worth saying what it is for before what it does.++A retro-hunt sweeps a tenant's recorded history for an indicator somebody+else published. The sweep is only as good as the answer to "which column of+``aisoc.raw_events`` would this indicator be sitting in". Get that wrong and+every sweep returns zero, which reads to an operator as "we were never+exposed" rather than as "we never looked". That is the single most dangerous+way for this surface to fail, and it has already happened twice in this+repository at scale: 663 of 825 loaded detection rules matched on fields that+were never visible because the matcher read a flat namespace while connectors+nested the payload, and every Windows Sigma rule was unreachable because the+payload sits one level below what the engine flattened. Both passed their+tests throughout.++So the mapping below is not a reviewed table of plausible field names. Every+column is annotated with the OCSF path that+``services/fusion/app/services/lake_writer.py::event_to_row`` reads to+populate it, and ``scripts/check_ioc_lake_mapping.py`` reads that writer's+source and the ClickHouse DDL and fails when a column here is not one the+writer writes, or is not one the table has. The writer is the only thing that+puts a row in the lake, so agreeing with it is the same as agreeing with+recorded data. ``tests/isolation/test_retro_hunt_live.py`` then closes the+loop against a live warehouse: it drives a real OCSF event through the real+writer, inserts the row, and runs the sweep this module builds.++Three findings from reading the writer that a plausible-looking table would+have got wrong:++**A SHA-1 or an MD5 lands in the column called ``hash_sha256``.** ``_first_hash``+takes ``file.fingerprints[0].value`` whatever algorithm produced it, and only+falls back to a key literally named ``hash_sha256``. Mapping ``md5`` to a+``hash_md5`` column would have been reasonable, and would have matched nothing,+because no such column exists.++**An IPv4 address is stored as its IPv4-mapped IPv6 form.** The columns are+``IPv6``-typed and ``_to_ip_obj`` maps ``1.2.3.4`` to ``::ffff:1.2.3.4``, so a+predicate has to go through ``toIPv6()`` rather than compare to the string the+feed published.++**A URL has no column at all.** The writer records no URL anywhere except+inside ``raw_payload``, an unindexed ZSTD blob whose contents are+connector-dependent. Rather than emit a substring scan that costs a full table+read and returns a confident zero on connectors that do not populate it, the+type is declared unmapped with a reason. An unmapped type is reported to the+caller as a coverage gap, never as an absence of the indicator, which is the+same distinction ``app.services.agent_tools.siem_search`` draws for a backend+with no field mapping.+"""++from __future__ import annotations++from dataclasses import dataclass++__all__ = [+ "LAKE_TABLE",+ "SWEEPABLE_TYPES",+ "UNMAPPED_TYPES",+ "LakeFieldMapping",+ "UnmappedIndicator",+ "mapping_for",+]++#: The one table a retro-hunt reads. Named here rather than imported from+#: ``lake_hunt`` so the mapping gate has a single symbol to check.+LAKE_TABLE = "aisoc.raw_events"+++@dataclass(frozen=True)+class LakeColumn:+ """One lake column an indicator of some type could be recorded in.++ ``ocsf_paths`` is the load-bearing field. It names where+ ``event_to_row`` reads the value from, in the dotted form that function+ uses, and the mapping gate checks each one appears in that function's+ source. A column with no path is a column nothing populates.+ """++ #: Column name in ``aisoc.raw_events``.+ name: str+ #: OCSF paths ``event_to_row`` reads to fill this column.+ ocsf_paths: tuple[str, ...]+ #: True when the column is ``Array(String)`` and needs ``has()`` rather+ #: than ``=``.+ is_array: bool = False+ #: True when the column is ``IPv6``-typed, so the bound value has to go+ #: through ``toIPv6()`` to compare against a stored IPv4-mapped address.+ is_ip: bool = False+++@dataclass(frozen=True)+class LakeFieldMapping:+ """Every column a sweep for one indicator type should read."""++ indicator_type: str+ columns: tuple[LakeColumn, ...]++ @property+ def column_names(self) -> tuple[str, ...]:+ return tuple(c.name for c in self.columns)+++@dataclass(frozen=True)+class UnmappedIndicator:+ """An indicator type the lake genuinely cannot answer for, and why.++ Carried as data rather than as an omission so a sweep can say which+ types it did not check. An omission would be indistinguishable from a+ type nobody thought about.+ """++ indicator_type: str+ reason: str+++#: The value written into ``iocs`` is the raw string from the OCSF endpoint+#: blocks, not the IPv6-normalised form the typed columns hold, so this is a+#: genuinely second path to the same event rather than a restatement of the+#: first. It is also the only bloom-indexed column among them.+_IOCS = LakeColumn(+ name="iocs",+ ocsf_paths=("src_endpoint.ip", "dst_endpoint.ip"),+ is_array=True,+)++_IOCS_HASH = LakeColumn(name="iocs", ocsf_paths=("file.fingerprints",), is_array=True)++#: Keyed by the Phase 4 indicator type, so an agent, the federated SIEM search+#: and a retro-hunt all speak one vocabulary. ``scripts/check_ioc_lake_mapping.py``+#: asserts this covers every type in ``app.services.agent_tools.indicators``+#: either here or in :data:`UNMAPPED_TYPES`, so a type added there cannot+#: quietly become a sweep that checks nothing.+SWEEPABLE_TYPES: dict[str, LakeFieldMapping] = {+ "ip": LakeFieldMapping(+ indicator_type="ip",+ columns=(+ LakeColumn(name="source_ip", ocsf_paths=("src_endpoint.ip",), is_ip=True),+ LakeColumn(name="dest_ip", ocsf_paths=("dst_endpoint.ip",), is_ip=True),+ _IOCS,+ ),+ ),+ "domain": LakeFieldMapping(+ indicator_type="domain",+ columns=(+ # `src_hostname` is deliberately absent. The writer fills it from+ # `device.name`, the reporting host, which is the tenant's own+ # asset rather than a name the event reached out to. Sweeping a+ # published malicious domain against it would only ever match a+ # customer who named a machine after the domain.+ LakeColumn(name="dst_hostname", ocsf_paths=("dst_endpoint.hostname",)),+ ),+ ),+ "hostname": LakeFieldMapping(+ indicator_type="hostname",+ columns=(+ LakeColumn(name="src_hostname", ocsf_paths=("device.name", "src_endpoint.hostname")),+ LakeColumn(name="dst_hostname", ocsf_paths=("dst_endpoint.hostname",)),+ ),+ ),+ "sha256": LakeFieldMapping(+ indicator_type="sha256",+ columns=(+ LakeColumn(name="hash_sha256", ocsf_paths=("file.fingerprints", "hash_sha256")),+ _IOCS_HASH,+ ),+ ),+ # sha1 and md5 read the same column as sha256, and that is the writer's+ # behaviour rather than an approximation of it: `_first_hash` returns+ # `file.fingerprints[0].value` without inspecting the algorithm, so a+ # connector whose first fingerprint is an MD5 puts an MD5 there. The+ # value's own shape (32 or 40 hex characters, checked by+ # `indicators.validate_value`) is what keeps the match unambiguous.+ "sha1": LakeFieldMapping(+ indicator_type="sha1",+ columns=(+ LakeColumn(name="hash_sha256", ocsf_paths=("file.fingerprints", "hash_sha256")),+ _IOCS_HASH,+ ),+ ),+ "md5": LakeFieldMapping(+ indicator_type="md5",+ columns=(+ LakeColumn(name="hash_sha256", ocsf_paths=("file.fingerprints", "hash_sha256")),+ _IOCS_HASH,+ ),+ ),+ "username": LakeFieldMapping(+ indicator_type="username",+ columns=(LakeColumn(name="user_name", ocsf_paths=("actor.user.name",)),),+ ),+ "process_name": LakeFieldMapping(+ indicator_type="process_name",+ columns=(LakeColumn(name="process_name", ocsf_paths=("process.name",)),),+ ),+}++#: Types the lake cannot answer for. Each reason names the column that does+#: not exist, so a reader can tell a deliberate refusal from an oversight.+UNMAPPED_TYPES: dict[str, UnmappedIndicator] = {+ "url": UnmappedIndicator(+ indicator_type="url",+ reason=(+ "The event lake records no URL column. A URL appears only inside raw_payload, "+ "which is an unindexed compressed blob that many connectors leave empty, so a "+ "substring scan would cost a full table read and return zero on the connectors "+ "that do not populate it. URLs are swept through the federated SIEM search "+ "instead, where the backends do carry a URL field."+ ),+ ),+}+++def mapping_for(indicator_type: str) -> LakeFieldMapping | UnmappedIndicator | None:+ """Return the lake mapping for ``indicator_type``.++ Three outcomes rather than two. A :class:`LakeFieldMapping` means the lake+ can answer; an :class:`UnmappedIndicator` means it cannot and says why;+ ``None`` means the type is not one AiSOC knows at all, which is a caller+ error rather than a coverage gap.+ """+ mapping = SWEEPABLE_TYPES.get(indicator_type)+ if mapping is not None:+ return mapping+ return UNMAPPED_TYPES.get(indicator_type)diff --git a/services/api/app/services/retro_hunt/service.py b/services/api/app/services/retro_hunt/service.pynew file mode 100644index 000000000..cf830b06f--- /dev/null+++ b/services/api/app/services/retro_hunt/service.py@@ -0,0 +1,431 @@+"""Turn one published indicator into at most one alert per tenant.++Gap-closure Phase 8.1.++This is the module the phase's noise budget lives in. A feed publishes+thousands of indicators a day; each one asks a question of every opted-in+tenant's month of history. Without the three controls below that is a machine+for generating alerts nobody reads, which is the failure mode an AI SOC is+supposed to remove rather than add to.++**Budget, checked before the work.** :func:`_consume_budget` is the first+thing that runs, so an exhausted tenant costs one small UPDATE rather than a+warehouse scan. It counts a sweep rather than an alert, because the cost is in+the sweeping: a tenant with no matches at all still paid for the query.++**Dedup, enforced twice, in different places.** ``retro_hunt_sightings`` has a+UNIQUE constraint on (tenant, type, value), so the second sweep that finds the+same indicator updates a row instead of opening an alert. The alert insert+additionally carries an ``idempotency_key`` that the ``alerts`` table has a+per-tenant partial unique index on, so even a bug in this module's+branching cannot produce a duplicate row. One of those is the mechanism and+the other is the seatbelt, and it is worth being explicit about which is+which: the sightings row is what stops the alert being *attempted*, and the+index is what stops it *landing*.++**Aggregation, in the query.** The sweep returns one row whatever the match+count. See :mod:`app.services.retro_hunt.sweep`.++The provenance an alert carries is the plan's list and one addition. The feed,+when the feed first saw the indicator, and where it matched are required.+``intel_first_seen_at`` and ``first_sighting_at`` are kept as separate facts+rather than collapsed into "first seen", because an indicator published this+morning and last seen in the tenant's estate five weeks ago is a materially+different finding from one published and seen the same day, and a single+field would make those read identically.+"""++from __future__ import annotations++import hashlib+import logging+import uuid+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta+from typing import Any++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.alert import Alert+from app.models.retro_hunt import RetroHuntSettings, RetroHuntSighting+from app.services.agent_tools.indicators import IndicatorTypeError+from app.services.retro_hunt.sweep import (+ DEFAULT_LOOKBACK_DAYS,+ SweepOutcome,+ sweep_indicator,+)++logger = logging.getLogger(__name__)++#: Severity a retro-hunt alert opens at.+#:+#: Deliberately not `critical`. A match means an indicator somebody published+#: appears somewhere in this tenant's recorded history, which is a strong+#: reason to look and not on its own a reason to page: public feeds carry+#: sinkholes, shared CDN addresses and hashes of files that are malicious in+#: one context and ordinary in another. Overstating it is how a feature like+#: this gets muted in week two, and a muted alert is worth less than no alert.+DEFAULT_SEVERITY = "medium"++#: Alert category, matching the vocabulary the console already filters on.+ALERT_CATEGORY = "threat-intel"+++@dataclass(frozen=True)+class IntelIndicator:+ """One indicator lifted out of a ``NEW_IOC`` event.++ Deliberately a small typed record rather than the raw payload dict. The+ payload comes off a Kafka topic fed by third-party feeds, so every field+ is untrusted, and narrowing it here means the rest of the module cannot+ accidentally reach a key nobody validated.+ """++ indicator_type: str+ value: str+ feed_source: str+ first_seen_at: datetime | None = None+ description: str = ""+++@dataclass+class TenantSweepReport:+ """What happened for one tenant and one indicator."""++ tenant_id: uuid.UUID+ #: One of: swept, skipped_disabled, skipped_budget, skipped_unsupported, failed.+ outcome: str+ matched: bool = False+ alert_id: uuid.UUID | None = None+ deduplicated: bool = False+ detail: str = ""+++def alert_idempotency_key(indicator_type: str, value: str) -> str:+ """A stable per-tenant key for the alert this indicator would open.++ Hashed rather than embedded because an indicator value can be a 2 KB URL+ or an attacker-chosen hostname, and the column is 128 characters. The+ prefix keeps retro-hunt keys legible in the table and prevents a collision+ with the CLI submit path that also uses this column.+ """+ digest = hashlib.sha256(f"{indicator_type}:{value}".encode()).hexdigest()+ return f"retro-hunt:{indicator_type}:{digest[:32]}"+++def _window_reset(anchor: datetime, now: datetime, span: timedelta) -> bool:+ if anchor.tzinfo is None:+ anchor = anchor.replace(tzinfo=UTC)+ return now - anchor >= span+++async def _consume_budget(+ db: AsyncSession,+ settings_row: RetroHuntSettings,+ *,+ now: datetime,+) -> bool:+ """Spend one sweep from this tenant's budget, or refuse.++ Rolling windows are reset lazily on read rather than by a scheduled job:+ a tenant whose feed went quiet for a day should get a full budget on the+ next indicator, and nothing needs to have been running in between for+ that to be true.+ """+ if _window_reset(settings_row.hour_started_at, now, timedelta(hours=1)):+ settings_row.sweeps_this_hour = 0+ settings_row.hour_started_at = now+ if _window_reset(settings_row.day_started_at, now, timedelta(days=1)):+ settings_row.sweeps_today = 0+ settings_row.day_started_at = now++ if settings_row.sweeps_this_hour >= settings_row.max_sweeps_per_hour:+ settings_row.sweeps_skipped_budget += 1+ settings_row.updated_at = now+ return False+ if settings_row.sweeps_today >= settings_row.max_sweeps_per_day:+ settings_row.sweeps_skipped_budget += 1+ settings_row.updated_at = now+ return False++ settings_row.sweeps_this_hour += 1+ settings_row.sweeps_today += 1+ settings_row.updated_at = now+ return True+++def _matched_surfaces(outcome: SweepOutcome) -> list[dict[str, Any]]:+ """Where the indicator matched, as the alert and the ledger record it."""+ surfaces: list[dict[str, Any]] = []+ if outcome.lake.matched:+ surfaces.append(+ {+ "surface": "event_lake",+ "sightings": outcome.lake.sightings,+ "columns": list(outcome.lake.columns_searched),+ "connector_types": outcome.lake.connector_types,+ "hosts": outcome.lake.hosts,+ "users": outcome.lake.users,+ }+ )+ if outcome.federated.matched:+ surfaces.append(+ {+ "surface": "federated_siem",+ "sightings": outcome.federated.sightings,+ "sources": outcome.federated.sources_ok,+ }+ )+ return surfaces+++def _build_description(indicator: IntelIndicator, outcome: SweepOutcome) -> str:+ """The provenance block, written so a reader can act without pivoting.++ Three questions in order: what was published and by whom, what we found,+ and what we could not check. The third is last but never omitted, because+ a retro-hunt that swept one of two sources and says nothing about the+ other is claiming coverage it does not have.+ """+ lines = [+ f"A retro-hunt matched a {indicator.indicator_type} published by {indicator.feed_source}.",+ "",+ "Intelligence provenance",+ f" Feed: {indicator.feed_source}",+ f" Indicator: {indicator.indicator_type} {indicator.value}",+ ]+ if indicator.first_seen_at:+ lines.append(f" First seen by the feed: {indicator.first_seen_at.isoformat()}")+ else:+ lines.append(" First seen by the feed: not published by this feed")+ if indicator.description:+ lines.append(f" Feed description: {indicator.description}")++ lines += ["", "Where it matched", f" Lookback window: {outcome.lookback_days} days"]+ if outcome.lake.matched:+ lines.append(f" Event lake: {outcome.lake.sightings} sighting(s) in columns {', '.join(outcome.lake.columns_searched)}")+ if outcome.lake.first_sighting_at:+ lines.append(f" First sighting in your data: {outcome.lake.first_sighting_at}")+ lines.append(f" Most recent sighting: {outcome.lake.last_sighting_at}")+ if outcome.lake.connector_types:+ lines.append(f" Sources: {', '.join(outcome.lake.connector_types)}")+ if outcome.lake.hosts:+ lines.append(f" Hosts: {', '.join(outcome.lake.hosts)}")+ if outcome.lake.users:+ lines.append(f" Users: {', '.join(outcome.lake.users)}")+ if outcome.federated.matched:+ lines.append(f" Connected SIEMs: {outcome.federated.sightings} matching row(s) from {', '.join(outcome.federated.sources_ok)}")++ gaps = outcome.gaps+ if gaps:+ lines += ["", "What was NOT checked"]+ lines += [f" {gap}" for gap in gaps]+ lines.append(" A gap is not evidence of absence. These surfaces were not searched.")++ return "\n".join(lines)+++async def _open_alert(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ indicator: IntelIndicator,+ outcome: SweepOutcome,+) -> Alert:+ """Open the one alert this indicator gets for this tenant."""+ now = datetime.now(UTC)+ event_time = outcome.lake.last_sighting_at or now+ if isinstance(event_time, datetime) and event_time.tzinfo is None:+ event_time = event_time.replace(tzinfo=UTC)++ alert = Alert(+ tenant_id=tenant_id,+ title=f"Retro-hunt: {indicator.indicator_type} {indicator.value} seen in your history",+ description=_build_description(indicator, outcome),+ severity=DEFAULT_SEVERITY,+ status="new",+ category=ALERT_CATEGORY,+ connector_type="retro-hunt",+ rule_id=f"retro-hunt:{indicator.indicator_type}",+ rule_name=f"Threat-intel retro-hunt ({indicator.feed_source})",+ entities=[{"type": indicator.indicator_type, "value": indicator.value}],+ raw_event={+ "retro_hunt": {+ "feed_source": indicator.feed_source,+ "indicator_type": indicator.indicator_type,+ "indicator_value": indicator.value,+ "intel_first_seen_at": (indicator.first_seen_at.isoformat() if indicator.first_seen_at else None),+ "lookback_days": outcome.lookback_days,+ "total_sightings": outcome.total_sightings,+ "matched_surfaces": _matched_surfaces(outcome),+ "not_checked": outcome.gaps,+ }+ },+ tags=["retro-hunt", f"feed:{indicator.feed_source}"],+ idempotency_key=alert_idempotency_key(indicator.indicator_type, indicator.value),+ event_time=event_time,+ first_seen=outcome.lake.first_sighting_at or now,+ last_seen=event_time,+ )+ db.add(alert)+ await db.flush()+ return alert+++async def sweep_tenant(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ indicator: IntelIndicator,+ settings_row: RetroHuntSettings | None = None,+ now: datetime | None = None,+) -> TenantSweepReport:+ """Sweep one tenant for one indicator and open at most one alert.++ The caller is responsible for the transaction. Nothing here commits, so a+ batch of tenants can be swept and committed together, and a failure on one+ tenant does not half-write another.+ """+ now = now or datetime.now(UTC)++ if settings_row is None:+ settings_row = await db.get(RetroHuntSettings, tenant_id)+ if settings_row is None or not settings_row.enabled:+ return TenantSweepReport(+ tenant_id=tenant_id,+ outcome="skipped_disabled",+ detail="This tenant has not opted in to retro-hunts.",+ )++ if not await _consume_budget(db, settings_row, now=now):+ logger.info("retro_hunt.budget_exhausted tenant=%s", tenant_id)+ return TenantSweepReport(+ tenant_id=tenant_id,+ outcome="skipped_budget",+ detail=("The tenant's retro-hunt budget for this window is spent, so the sweep did not run. This is not a result."),+ )++ try:+ outcome = await sweep_indicator(+ db,+ tenant_id=tenant_id,+ indicator_type=indicator.indicator_type,+ value=indicator.value,+ lookback_days=settings_row.lookback_days or DEFAULT_LOOKBACK_DAYS,+ include_federated=settings_row.include_federated,+ )+ except IndicatorTypeError as exc:+ # The feed published a value that is not the type it claims. Surfaced+ # as its own outcome rather than as "no match", because it is a+ # data-quality problem an operator can fix and a silent zero hides it.+ logger.info(+ "retro_hunt.indicator_refused tenant=%s type=%s reason=%s",+ tenant_id,+ str(indicator.indicator_type).replace("\r", "").replace("\n", " ")[:32],+ str(exc).replace("\r", "").replace("\n", " ")[:160],+ )+ return TenantSweepReport(+ tenant_id=tenant_id,+ outcome="skipped_unsupported",+ detail=str(exc),+ )++ if not outcome.matched:+ return TenantSweepReport(+ tenant_id=tenant_id,+ outcome="swept",+ matched=False,+ detail="; ".join(outcome.gaps) if outcome.gaps else "No sightings in the lookback window.",+ )++ existing = (+ await db.execute(+ select(RetroHuntSighting).where(+ RetroHuntSighting.tenant_id == tenant_id,+ RetroHuntSighting.indicator_type == indicator.indicator_type,+ RetroHuntSighting.indicator_value == indicator.value,+ )+ )+ ).scalar_one_or_none()++ surfaces = _matched_surfaces(outcome)++ if existing is not None:+ # Already known. Refresh what we learned and open nothing: this is the+ # branch that keeps a daily-republished indicator from becoming a+ # daily alert.+ existing.last_matched_at = now+ existing.sightings = outcome.total_sightings+ existing.last_sighting_at = outcome.lake.last_sighting_at+ existing.matched_surfaces = surfaces+ existing.times_seen += 1+ existing.updated_at = now+ return TenantSweepReport(+ tenant_id=tenant_id,+ outcome="swept",+ matched=True,+ alert_id=existing.alert_id,+ deduplicated=True,+ detail=(+ f"Already alerted on this indicator for this tenant "+ f"({existing.times_seen} sweeps have now matched it); no new alert opened."+ ),+ )++ alert = await _open_alert(db, tenant_id=tenant_id, indicator=indicator, outcome=outcome)+ db.add(+ RetroHuntSighting(+ tenant_id=tenant_id,+ indicator_type=indicator.indicator_type,+ indicator_value=indicator.value,+ feed_source=indicator.feed_source,+ intel_first_seen_at=indicator.first_seen_at,+ first_matched_at=now,+ last_matched_at=now,+ first_sighting_at=outcome.lake.first_sighting_at,+ last_sighting_at=outcome.lake.last_sighting_at,+ sightings=outcome.total_sightings,+ matched_surfaces=surfaces,+ alert_id=alert.id,+ times_seen=1,+ created_at=now,+ updated_at=now,+ )+ )+ logger.info(+ "retro_hunt.alert_opened tenant=%s type=%s sightings=%d",+ tenant_id,+ str(indicator.indicator_type).replace("\r", "").replace("\n", " ")[:32],+ outcome.total_sightings,+ )+ return TenantSweepReport(+ tenant_id=tenant_id,+ outcome="swept",+ matched=True,+ alert_id=alert.id,+ detail=f"Opened one alert for {outcome.total_sightings} sighting(s).",+ )+++async def opted_in_tenants(db: AsyncSession) -> list[RetroHuntSettings]:+ """Every tenant that has asked for retro-hunts.++ Read on an unbound (cross-tenant) session by the consumer, which then+ binds each tenant before writing. Same shape as the hunt scheduler's+ sweep, and for the same reason: the read is genuinely cross-tenant and+ every write after it is not.+ """+ rows = (await db.execute(select(RetroHuntSettings).where(RetroHuntSettings.enabled.is_(True)))).scalars().all()+ return list(rows)+++__all__ = [+ "ALERT_CATEGORY",+ "DEFAULT_SEVERITY",+ "IntelIndicator",+ "TenantSweepReport",+ "alert_idempotency_key",+ "opted_in_tenants",+ "sweep_tenant",+]diff --git a/services/api/app/services/retro_hunt/sql.py b/services/api/app/services/retro_hunt/sql.pynew file mode 100644index 000000000..96742cf5b--- /dev/null+++ b/services/api/app/services/retro_hunt/sql.py@@ -0,0 +1,97 @@+"""The sweep query, generated from the field mapping and nothing else.++Gap-closure Phase 8.1.++Separated from :mod:`app.services.retro_hunt.sweep` on purpose. That module+does I/O: it holds a ClickHouse client, a database session and the federated+search, so importing it pulls in SQLAlchemy and the settings object. This one+imports the standard library and the field mapping, which means the two places+that most need to check the generated SQL can load it directly:++* ``scripts/check_ioc_lake_mapping.py``, which has no service dependencies+ installed;+* ``tests/isolation/test_retro_hunt_live.py``, which runs the *real* generator+ against a *live* ClickHouse holding a row produced by the *real* lake+ writer, and would be proving nothing if it re-implemented the query.++That second one is the whole reason for the split. This repository's recurring+defect is a test that compares a producer against a copy of itself, and a live+test that built its own SQL would be exactly that.+"""++from __future__ import annotations++from app.services.retro_hunt.ioc_fields import LAKE_TABLE, LakeColumn, LakeFieldMapping++__all__ = ["DISTINCT_CAP", "build_sweep_sql", "column_predicate"]++#: How many distinct values of each grouping column a sweep returns. Bounded+#: because this lands in alert evidence and, through it, in a prompt.+DISTINCT_CAP = 20+++def column_predicate(column: LakeColumn) -> str:+ """The one predicate that tests ``column`` against the bound needle.++ Public so the live test can exercise each column on its own. A sweep ORs+ several columns together, and an OR hides a broken one behind a working+ one: ``iocs`` carries IP addresses and hashes as plain strings, so it+ matches for most indicator types regardless of whether the typed column+ beside it was mapped correctly. Testing the assembled statement would+ therefore pass with ``source_ip`` pointed at nothing.+ """+ if column.is_array:+ return f"has({column.name}, %(needle)s)"+ if column.is_ip:+ # Explicit normalisation rather than a load-bearing conversion.+ # ClickHouse 24.3 does coerce a string literal to IPv6 when comparing+ # against an IPv6 column, so `source_ip = '203.0.113.77'` matches the+ # `::ffff:203.0.113.77` the writer stored. Measured, not assumed; see+ # `tests/isolation/test_retro_hunt_live.py`. `toIPv6` says what is+ # meant instead of relying on an implicit cast staying implicit, and+ # it keeps the predicate honest about the fact that the stored value+ # is not the string the feed published.+ return f"{column.name} = toIPv6(%(needle)s)"+ return f"{column.name} = %(needle)s"+++def build_sweep_sql(mapping: LakeFieldMapping) -> tuple[str, tuple[str, ...]]:+ """Build the aggregate sweep for one indicator type.++ Returns the SQL and the column names it searched. The statement carries+ three bound parameters (``tenant_id``, ``lookback_days``, ``needle``) and+ no interpolated value of any kind: column names come from+ :mod:`app.services.retro_hunt.ioc_fields`, which is a closed table in this+ repository, and the indicator itself is always a parameter. An indicator+ is third-party text from a public feed, so it is untrusted in exactly the+ way an operator's SQL is.++ The result is an aggregate rather than a selection, and that is the+ structural answer to "an IOC that matches a thousand rows should not open+ a thousand alerts": there is no code path here that can return a row per+ match.+ """+ predicates = [column_predicate(column) for column in mapping.columns]++ sql = (+ "SELECT count() AS sightings, "+ "min(event_time) AS first_sighting, "+ "max(event_time) AS last_sighting, "+ f"groupUniqArray({DISTINCT_CAP})(connector_type) AS connector_types, "+ f"groupUniqArray({DISTINCT_CAP})(src_hostname) AS hosts, "+ f"groupUniqArray({DISTINCT_CAP})(user_name) AS users "+ f"FROM {LAKE_TABLE} "+ "WHERE tenant_id = %(tenant_id)s "+ "AND event_time >= now() - INTERVAL %(lookback_days)s DAY "+ f"AND ({' OR '.join(predicates)})"+ )++ # Fail closed on the property this module's correctness rests on. The+ # statement is generated a few lines above, so this can only fire on a+ # future edit, which is exactly when it is worth having: the equivalent+ # check in `lake_sql` exists because a dependency upgrade silently turned+ # the tenant predicate into a no-op and the rewriter reported success.+ if "tenant_id = %(tenant_id)s" not in sql:+ raise AssertionError("refusing to return a sweep query with no tenant predicate")++ return sql, mapping.column_namesdiff --git a/services/api/app/services/retro_hunt/sweep.py b/services/api/app/services/retro_hunt/sweep.pynew file mode 100644index 000000000..aa1c084eb--- /dev/null+++ b/services/api/app/services/retro_hunt/sweep.py@@ -0,0 +1,418 @@+"""Sweep one tenant's recorded history for one indicator.++Gap-closure Phase 8.1.++A retro-hunt is somebody else's intelligence pointed at a customer's own+past. That shape makes it expensive by construction: a feed publishes+thousands of indicators a day, each one asks a question of thirty days of a+tenant's telemetry, and the question arrives on a schedule nobody in the SOC+chose. Every design decision here is about the two ways that goes wrong.++**It must not become a row firehose.** The query below is an aggregate, not a+selection. It returns exactly one row whatever the match count is: how many+sightings, when the first and last were, and bounded sets of the hosts, users+and connectors involved. An indicator that appears in a million events and an+indicator that appears in one produce the same amount of work above this+layer and the same amount of context in an alert. There is no code path here+that returns a row per match, so the "one IOC, a thousand alerts" failure is+not something callers have to remember to avoid.++**It must not become a warehouse denial of service.** ClickHouse is the only+thing that can actually stop a runaway scan, so the budget is expressed in+its own settings rather than as an intention on this side: a bytes-to-read+ceiling and an execution-time ceiling travel with every query. A sweep that+exceeds them fails as a sweep that could not be completed, which is reported+as such and never as zero sightings.++**Tenant scoping is structural.** The predicate is part of the generated+WHERE clause and its value is bound as a query parameter, following+``app.services.lake_hunt`` rather than ``app.services.lake_sql``. That is+deliberate and the reasoning is recorded in both: ``rewrite_for_tenant``+exists to constrain SQL an *operator* wrote, and handing it platform-authored+SQL is how every fresh tenant once came to see the same global figures on the+funnel. :func:`build_sweep_sql` additionally refuses to return a statement+that does not carry its own tenant predicate, so the guarantee does not rest+on a reviewer noticing.++**The lake is not the whole estate.** A tenant with a SIEM has years of data+AiSOC never ingested, so a sweep also goes through the Phase 4 federated+search. The three outcomes that module keeps apart are kept apart here too: a+source that answered and found nothing, a source that could not be checked,+and a source with no field mapping for this indicator type are different+facts, and a sweep that collapses them reports "you were not exposed" on+evidence nobody gathered.+"""++from __future__ import annotations++import logging+import uuid+from dataclasses import dataclass, field+from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.db.clickhouse import (+ LakeQueryError,+ LakeQueryNotConfiguredError,+ LakeQueryTimeoutError,+ execute_lake_query,+)+from app.services.agent_tools import siem_search+from app.services.agent_tools.indicators import IndicatorTypeError, validate_value+from app.services.retro_hunt.ioc_fields import UnmappedIndicator, mapping_for+from app.services.retro_hunt.sql import build_sweep_sql++logger = logging.getLogger(__name__)++#: Default history a sweep looks back over, in days. The plan's default.+DEFAULT_LOOKBACK_DAYS = 30++#: Hard ceiling on the lookback regardless of what a tenant configures. A+#: sweep is a scheduled background cost paid by every new indicator, so an+#: unbounded window is a way to make the warehouse unusable by writing a+#: number into a settings row.+MAX_LOOKBACK_DAYS = 365++#: Bytes ClickHouse may read for one sweep before it refuses. This is the+#: budget, and it is here rather than in a comment because only the server+#: can enforce it. Chosen so a bloom-indexed needle over a month of a+#: mid-sized tenant completes comfortably while a full scan of a large+#: tenant's ZSTD blobs does not.+MAX_BYTES_PER_SWEEP = 8 * 1024 * 1024 * 1024++#: Wall-clock ceiling for one sweep, in seconds. Shorter than the lake API's+#: default because a sweep runs unattended on a queue: a slow one delays every+#: indicator behind it, and there is no human waiting who would rather wait+#: than get an answer.+SWEEP_TIMEOUT_SECONDS = 20.0+++class SweepBudgetExceeded(RuntimeError):+ """The warehouse refused the sweep on cost. Never a zero-sighting result."""+++@dataclass+class LakeSweepResult:+ """What the lake said about one indicator, or why it could not say."""++ indicator_type: str+ value: str+ #: False when the lake could not be asked at all. A caller must not read+ #: ``sightings == 0`` without checking this first, which is why the count+ #: is not an Optional that could be treated as falsy.+ checked: bool+ sightings: int = 0+ first_sighting_at: Any | None = None+ last_sighting_at: Any | None = None+ connector_types: list[str] = field(default_factory=list)+ hosts: list[str] = field(default_factory=list)+ users: list[str] = field(default_factory=list)+ columns_searched: tuple[str, ...] = ()+ #: Set when ``checked`` is False. Names what stopped the sweep in terms an+ #: operator can act on.+ unavailable_reason: str | None = None++ @property+ def matched(self) -> bool:+ return self.checked and self.sightings > 0+++@dataclass+class FederatedSweepResult:+ """What the tenant's own SIEMs said, keeping the three outcomes apart."""++ checked: bool+ sightings: int = 0+ sources_ok: list[str] = field(default_factory=list)+ sources_failed: list[str] = field(default_factory=list)+ sources_unmapped: list[str] = field(default_factory=list)+ unavailable_reason: str | None = None++ @property+ def matched(self) -> bool:+ return self.checked and self.sightings > 0+++@dataclass+class SweepOutcome:+ """The whole answer for one indicator against one tenant."""++ indicator_type: str+ value: str+ lookback_days: int+ lake: LakeSweepResult+ federated: FederatedSweepResult++ @property+ def matched(self) -> bool:+ return self.lake.matched or self.federated.matched++ @property+ def total_sightings(self) -> int:+ return self.lake.sightings + self.federated.sightings++ @property+ def gaps(self) -> list[str]:+ """Everything that was not checked, in words an alert can carry.++ Present on a matching sweep as well as a non-matching one: an+ indicator found in the lake while the SIEM sweep failed is a+ different finding from one found in both.+ """+ out: list[str] = []+ if not self.lake.checked and self.lake.unavailable_reason:+ out.append(f"Event lake: {self.lake.unavailable_reason}")+ if not self.federated.checked and self.federated.unavailable_reason:+ out.append(f"Federated SIEM search: {self.federated.unavailable_reason}")+ for source in self.federated.sources_failed:+ out.append(f"SIEM source {source} could not be searched, so it was NOT checked.")+ for source in self.federated.sources_unmapped:+ out.append(f"SIEM source {source} has no field mapping for a {self.indicator_type}, so it was NOT checked.")+ return out+++async def sweep_lake(+ *,+ tenant_id: uuid.UUID,+ indicator_type: str,+ value: str,+ lookback_days: int = DEFAULT_LOOKBACK_DAYS,+) -> LakeSweepResult:+ """Ask the event lake whether it has seen one indicator.++ Never raises for an operational failure. The lake being unreachable, the+ budget being exceeded and the indicator type having no lake column are all+ returned as ``checked=False`` with a reason, because the caller's next step+ is to record a visibility gap rather than to stop.+ """+ window = max(1, min(int(lookback_days), MAX_LOOKBACK_DAYS))+ mapping = mapping_for(indicator_type)++ if mapping is None:+ return LakeSweepResult(+ indicator_type=indicator_type,+ value=value,+ checked=False,+ unavailable_reason=f"{indicator_type!r} is not an indicator type AiSOC knows how to sweep.",+ )+ if isinstance(mapping, UnmappedIndicator):+ return LakeSweepResult(+ indicator_type=indicator_type,+ value=value,+ checked=False,+ unavailable_reason=mapping.reason,+ )++ sql, columns = build_sweep_sql(mapping)+ params = {"tenant_id": str(tenant_id), "lookback_days": window, "needle": value}++ try:+ result = await execute_lake_query(+ sql,+ params=params,+ timeout_seconds=SWEEP_TIMEOUT_SECONDS,+ extra_settings={+ # The budget. `max_bytes_to_read` is what makes an+ # unselective sweep fail instead of reading the partition.+ "max_bytes_to_read": MAX_BYTES_PER_SWEEP,+ "max_result_rows": 1,+ },+ )+ except LakeQueryNotConfiguredError:+ return LakeSweepResult(+ indicator_type=indicator_type,+ value=value,+ checked=False,+ columns_searched=columns,+ unavailable_reason="No event lake is configured on this deployment, so the tenant's own history was NOT searched.",+ )+ except LakeQueryTimeoutError:+ return LakeSweepResult(+ indicator_type=indicator_type,+ value=value,+ checked=False,+ columns_searched=columns,+ unavailable_reason=(+ f"The sweep exceeded its {SWEEP_TIMEOUT_SECONDS:.0f}s budget, so the tenant's history was NOT fully searched."+ ),+ )+ except LakeQueryError as exc:+ logger.warning(+ "retro_hunt.lake_sweep_failed tenant=%s type=%s err=%s",+ tenant_id,+ str(indicator_type).replace("\r", "").replace("\n", " ")[:32],+ type(exc).__name__,+ )+ return LakeSweepResult(+ indicator_type=indicator_type,+ value=value,+ checked=False,+ columns_searched=columns,+ unavailable_reason="The event lake refused or failed the sweep, so the tenant's history was NOT searched.",+ )++ if not result.rows:+ # An aggregate with no GROUP BY always returns one row. No rows means+ # something returned a shape this code does not understand, and+ # reading that as zero sightings is the failure this module is built+ # to avoid.+ return LakeSweepResult(+ indicator_type=indicator_type,+ value=value,+ checked=False,+ columns_searched=columns,+ unavailable_reason="The event lake returned an unreadable result, so the sweep outcome is unknown.",+ )++ row = result.rows[0]+ return LakeSweepResult(+ indicator_type=indicator_type,+ value=value,+ checked=True,+ sightings=int(row[0] or 0),+ first_sighting_at=row[1] if int(row[0] or 0) else None,+ last_sighting_at=row[2] if int(row[0] or 0) else None,+ connector_types=[str(v) for v in (row[3] or []) if v],+ hosts=[str(v) for v in (row[4] or []) if v],+ users=[str(v) for v in (row[5] or []) if v],+ columns_searched=columns,+ )+++async def sweep_federated(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ indicator_type: str,+ value: str,+ lookback_days: int = DEFAULT_LOOKBACK_DAYS,+) -> FederatedSweepResult:+ """Ask the tenant's own SIEMs, through the Phase 4 typed search.++ Reuses ``agent_tools.siem_search`` rather than calling the federated+ endpoint directly, because that module already enforces the property this+ surface needs most: the caller names an indicator *type* and the platform+ resolves the field per backend, so no query text is ever composed from a+ value a public feed supplied.+ """+ if not siem_search.feature_enabled():+ return FederatedSweepResult(+ checked=False,+ unavailable_reason="Federated SIEM search is switched off on this deployment, so connected SIEMs were NOT searched.",+ )++ # The federated layer takes hours and caps the window at a week. A+ # thirty-day retro-hunt therefore gets seven days of SIEM coverage, and+ # saying so is the difference between a bounded answer and a wrong one.+ hours = min(int(lookback_days) * 24, 7 * 24)++ try:+ result = await siem_search.search_indicator(+ db,+ tenant_id=tenant_id,+ indicator_type=indicator_type,+ value=value,+ since_hours=hours,+ actor="aisoc-retro-hunt",+ )+ except IndicatorTypeError as exc:+ return FederatedSweepResult(+ checked=False,+ unavailable_reason=f"The indicator was refused before any SIEM was searched: {exc}",+ )+ except Exception as exc: # noqa: BLE001 - an unreachable SIEM is a gap, not a crash+ logger.warning(+ "retro_hunt.federated_sweep_failed tenant=%s err=%s",+ tenant_id,+ type(exc).__name__,+ )+ return FederatedSweepResult(+ checked=False,+ unavailable_reason="The federated search failed, so connected SIEMs were NOT searched.",+ )++ if not result.sources:+ return FederatedSweepResult(+ checked=False,+ unavailable_reason="This tenant has no SIEM connected to AiSOC, so there was nothing to search beyond the event lake.",+ )++ ok = [s.connector_type for s in result.sources if s.status == "ok"]+ failed = [s.connector_type for s in result.sources if s.status == "error"]+ unmapped = [s.connector_type for s in result.sources if s.status == "no_field_mapping"]++ return FederatedSweepResult(+ # Checked when at least one backend actually answered. A sweep where+ # every source errored is not a zero.+ checked=bool(ok),+ sightings=len(result.rows),+ sources_ok=ok,+ sources_failed=failed,+ sources_unmapped=unmapped,+ unavailable_reason=(None if ok else "Every connected SIEM failed to answer, so none of them were searched."),+ )+++async def sweep_indicator(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ indicator_type: str,+ value: str,+ lookback_days: int = DEFAULT_LOOKBACK_DAYS,+ include_federated: bool = True,+) -> SweepOutcome:+ """Sweep one tenant's history for one indicator, lake and SIEMs.++ Raises ``IndicatorTypeError`` when the indicator itself is malformed. That+ is deliberately not folded into a non-matching outcome: a feed publishing+ a value that is not the type it claims is a data-quality problem an+ operator should see, and rendering it as "no sightings" hides it forever.+ """+ checked_value = validate_value(indicator_type, value)++ lake = await sweep_lake(+ tenant_id=tenant_id,+ indicator_type=indicator_type,+ value=checked_value,+ lookback_days=lookback_days,+ )++ if include_federated:+ federated = await sweep_federated(+ db,+ tenant_id=tenant_id,+ indicator_type=indicator_type,+ value=checked_value,+ lookback_days=lookback_days,+ )+ else:+ federated = FederatedSweepResult(+ checked=False,+ unavailable_reason="Federated SIEM search was not requested for this sweep.",+ )++ return SweepOutcome(+ indicator_type=indicator_type,+ value=checked_value,+ lookback_days=max(1, min(int(lookback_days), MAX_LOOKBACK_DAYS)),+ lake=lake,+ federated=federated,+ )+++__all__ = [+ "DEFAULT_LOOKBACK_DAYS",+ "MAX_BYTES_PER_SWEEP",+ "MAX_LOOKBACK_DAYS",+ "SWEEP_TIMEOUT_SECONDS",+ "FederatedSweepResult",+ "LakeSweepResult",+ "SweepBudgetExceeded",+ "SweepOutcome",+ "build_sweep_sql",+ "sweep_federated",+ "sweep_indicator",+ "sweep_lake",+]diff --git a/services/api/app/workers/retro_hunt_consumer.py b/services/api/app/workers/retro_hunt_consumer.pynew file mode 100644index 000000000..d0c8208a2--- /dev/null+++ b/services/api/app/workers/retro_hunt_consumer.py@@ -0,0 +1,287 @@+"""The consumer for ``NEW_IOC``, which nothing had.++Gap-closure Phase 8.1.++``services/threatintel/app/feeds/pipeline.py`` has emitted a ``NEW_IOC``+event for every newly-seen indicator since the pipeline was written, and a+grep for the string across this repository returns the emit site and nothing+else. This module is the other end.++Two things about the topic, because both are the kind of mistake that reports+success while doing nothing:++**The topic name in the pipeline's signature is not the topic in use.**+``ThreatIntelPipeline.__init__`` defaults ``kafka_topic`` to+``threat-intel-events``, and ``services/threatintel``'s lifespan passes+``settings.KAFKA_TOPIC_THREAT_INTEL``, which is ``aisoc.threat_intel``. The+constructor default is therefore unreachable in any running deployment. A+consumer written against it would subscribe to a topic no producer writes,+consume nothing, log nothing, and keep a container healthy indefinitely.+``scripts/check_ioc_lake_mapping.py`` compares the two settings so they cannot+drift apart again.++**A consumer that cannot reach its topic must say which kind of problem it+has.** The rule this service already follows elsewhere: a transient fault+retries with backoff, a permanent one stops the loop and names the operator+action, and a poison message is skipped without penalising a working+subscription. The failure that motivated the rule was a consumer with no+``except`` at all, which exited its ``async for`` and left the container+``running`` with ``/health`` answering 200 while it was subscribed to nothing.++The work itself is deliberately not done here. This module owns the+subscription, the decode, the routing decision and the per-tenant fan-out;+:mod:`app.services.retro_hunt.service` owns what a sweep is worth doing and+what it opens. That split is what lets the sweep be tested without a broker.+"""++from __future__ import annotations++import asyncio+import contextlib+import json+import logging+from datetime import UTC, datetime+from typing import Any++from sqlalchemy import text++from app.core.config import settings+from app.db.cross_tenant import assert_cross_tenant_session+from app.db.database import AsyncSessionLocal+from app.services.retro_hunt.intel_types import route_feed_type+from app.services.retro_hunt.service import (+ IntelIndicator,+ TenantSweepReport,+ opted_in_tenants,+ sweep_tenant,+)+from app.workers._tick_failures import TickFailures++logger = logging.getLogger(__name__)++#: Seconds to wait before reconnecting after a transient broker fault.+_RECONNECT_BACKOFF_SECONDS = 5.0++#: Ceiling on the backoff so a long outage does not stretch to hours.+_MAX_BACKOFF_SECONDS = 120.0+++class PermanentConsumerFault(RuntimeError):+ """A condition no retry will clear. Stops the loop and names the fix."""+++def _enabled() -> bool:+ return bool(getattr(settings, "RETRO_HUNT_ENABLED", False))+++def parse_intel_event(raw: bytes | str) -> dict[str, Any] | None:+ """Decode one message from the intel topic, or ``None`` if it is not one.++ Returns ``None`` rather than raising for anything malformed, because a+ single undecodable message must not stop a working subscription. The+ caller counts these and moves on.+ """+ try:+ payload = json.loads(raw)+ except (TypeError, ValueError):+ return None+ if not isinstance(payload, dict):+ return None+ if payload.get("event_type") != "NEW_IOC":+ # The topic carries more than one event type. Anything else is+ # somebody else's message, not a fault.+ return None+ data = payload.get("data")+ if not isinstance(data, dict):+ return None+ return payload+++def _first_seen(data: dict[str, Any], envelope_ts: Any) -> datetime | None:+ """When the publishing feed first saw this indicator.++ Feeds disagree about the field name and about the format, and a value+ that cannot be parsed becomes ``None`` rather than ``now``: stamping the+ current time would turn "the feed did not say" into "the feed saw this+ today", which is a claim about somebody else's data.+ """+ for key in ("first_seen", "date_added", "created", "first_seen_at", "timestamp"):+ value = data.get(key)+ if isinstance(value, str) and value.strip():+ with contextlib.suppress(ValueError):+ return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(UTC)+ if isinstance(envelope_ts, str) and envelope_ts.strip():+ with contextlib.suppress(ValueError):+ return datetime.fromisoformat(envelope_ts.replace("Z", "+00:00")).astimezone(UTC)+ return None+++def indicator_from_event(payload: dict[str, Any]) -> IntelIndicator | None:+ """Turn one decoded ``NEW_IOC`` into a typed indicator, or refuse it.++ ``None`` means the event was understood and is not something to sweep: an+ unroutable type, a CVE (which the KEV exposure path handles), or an empty+ value. Each of those is logged with its reason by the caller so a feed+ publishing a type AiSOC does not handle is visible rather than silent.+ """+ data = payload.get("data") or {}+ value = str(data.get("value") or "").strip()+ if not value:+ return None++ routing = route_feed_type(str(data.get("type") or ""))+ if routing.indicator_type is None:+ return None++ return IntelIndicator(+ indicator_type=routing.indicator_type,+ value=value,+ feed_source=str(payload.get("source") or data.get("source") or "unknown feed"),+ first_seen_at=_first_seen(data, payload.get("timestamp")),+ description=str(data.get("description") or "")[:500],+ )+++async def handle_indicator(indicator: IntelIndicator) -> list[TenantSweepReport]:+ """Fan one indicator out to every tenant that opted in.++ Opens its own session and commits once at the end. The read of who opted+ in is genuinely cross-tenant; every write after it rebinds the tenant so+ the alert insert is RLS-enforced, which is the same shape as the hunt+ scheduler's sweep and for the same reason.+ """+ reports: list[TenantSweepReport] = []+ async with AsyncSessionLocal() as db:+ await assert_cross_tenant_session(db, "retro-hunt intel fan-out")+ tenants = await opted_in_tenants(db)+ if not tenants:+ return reports++ for settings_row in tenants:+ try:+ await db.execute(+ text("SELECT set_config('app.current_tenant_id', :t, true)"),+ {"t": str(settings_row.tenant_id)},+ )+ reports.append(+ await sweep_tenant(+ db,+ tenant_id=settings_row.tenant_id,+ indicator=indicator,+ settings_row=settings_row,+ )+ )+ except Exception as exc: # noqa: BLE001 - one tenant must not stop the rest+ logger.exception(+ "retro_hunt.tenant_sweep_failed tenant=%s err=%s",+ settings_row.tenant_id,+ type(exc).__name__,+ )+ reports.append(+ TenantSweepReport(+ tenant_id=settings_row.tenant_id,+ outcome="failed",+ detail=type(exc).__name__,+ )+ )+ await db.commit()+ return reports+++async def _build_consumer() -> Any:+ """Construct and start the aiokafka consumer, or fail permanently.++ A missing ``aiokafka`` and an unset broker list are both conditions no+ amount of retrying fixes, so they raise :class:`PermanentConsumerFault`+ with the setting to change rather than joining the backoff loop.+ """+ try:+ from aiokafka import AIOKafkaConsumer # noqa: PLC0415+ except ImportError as exc: # pragma: no cover - environment-specific+ raise PermanentConsumerFault(+ "aiokafka is not installed, so the retro-hunt consumer cannot run. Install it or set AISOC_RETRO_HUNT_ENABLED=false."+ ) from exc++ brokers = (settings.KAFKA_BOOTSTRAP_SERVERS or "").strip()+ if not brokers:+ raise PermanentConsumerFault(+ "KAFKA_BOOTSTRAP_SERVERS is empty, so there is no intel topic to consume. Set it or set AISOC_RETRO_HUNT_ENABLED=false."+ )++ consumer = AIOKafkaConsumer(+ settings.KAFKA_TOPIC_THREAT_INTEL,+ bootstrap_servers=brokers,+ group_id=settings.RETRO_HUNT_CONSUMER_GROUP,+ enable_auto_commit=True,+ auto_offset_reset="latest",+ )+ await consumer.start()+ logger.info(+ "retro_hunt_consumer subscribed topic=%s group=%s",+ str(settings.KAFKA_TOPIC_THREAT_INTEL).replace("\r", "").replace("\n", " ")[:64],+ str(settings.RETRO_HUNT_CONSUMER_GROUP).replace("\r", "").replace("\n", " ")[:64],+ )+ return consumer+++async def run_forever() -> None:+ """Consume ``NEW_IOC`` until cancelled. Owned by the API ``lifespan``."""+ if not _enabled():+ logger.info("retro_hunt_consumer disabled (AISOC_RETRO_HUNT_ENABLED is not set)")+ return++ failures = TickFailures("retro_hunt_consumer", logger)+ backoff = _RECONNECT_BACKOFF_SECONDS++ while True:+ consumer = None+ try:+ consumer = await _build_consumer()+ backoff = _RECONNECT_BACKOFF_SECONDS+ failures.record_success()++ async for message in consumer:+ payload = parse_intel_event(message.value)+ if payload is None:+ # Poison or irrelevant. Skipped without penalising the+ # subscription: one bad message is not a reason to stop+ # consuming a topic that is otherwise fine.+ continue+ indicator = indicator_from_event(payload)+ if indicator is None:+ routing = route_feed_type(str((payload.get("data") or {}).get("type") or ""))+ if routing.unknown:+ logger.info(+ "retro_hunt.unroutable_type reason=%s",+ str(routing.reason or "").replace("\r", "").replace("\n", " ")[:200],+ )+ continue+ try:+ await handle_indicator(indicator)+ except Exception as exc: # noqa: BLE001 - keep consuming+ logger.exception("retro_hunt.fan_out_failed err=%s", type(exc).__name__)++ except asyncio.CancelledError:+ raise+ except PermanentConsumerFault as exc:+ # Naming the action and stopping. Retrying a misconfiguration+ # turns it into churn an operator has to read past.+ logger.error("retro_hunt_consumer stopped permanently: %s", str(exc).replace("\r", "").replace("\n", " ")[:300])+ return+ except Exception as exc: # noqa: BLE001 - transient broker faults+ failures.record_failure(exc)+ await asyncio.sleep(backoff)+ backoff = min(backoff * 2, _MAX_BACKOFF_SECONDS)+ finally:+ if consumer is not None:+ with contextlib.suppress(Exception):+ await consumer.stop()+++__all__ = [+ "PermanentConsumerFault",+ "handle_indicator",+ "indicator_from_event",+ "parse_intel_event",+ "run_forever",+]diff --git a/services/api/migrations/070_retro_hunts.sql b/services/api/migrations/070_retro_hunts.sqlnew file mode 100644index 000000000..a7311ce74--- /dev/null+++ b/services/api/migrations/070_retro_hunts.sql@@ -0,0 +1,179 @@+-- 070: intel-driven retro-hunts — who opted in, what was already swept, and+-- how much budget is left.+--+-- Gap-closure Phase 8.1.+--+-- A retro-hunt is somebody else's intelligence pointed at a customer's own+-- past, on a schedule the customer did not choose. Two of the three tables+-- below exist because that shape is expensive and noisy by default, and the+-- third exists because it is also a disclosure.+--+-- Why opt-in is a row rather than a deployment setting+-- -----------------------------------------------------+-- Sweeping a tenant's thirty-day history every time a public feed publishes+-- an indicator is a real cost against their warehouse, and on a metered SIEM+-- licence it is a real bill. A deployment-wide switch would make one+-- operator's answer everybody's. `enabled` defaults to FALSE, so a tenant+-- that has never been asked is never swept, which is the standing rule for+-- anything that calls out or changes state.+--+-- Why the dedup ledger is a table and not a cache+-- ------------------------------------------------+-- The thing this phase most has to avoid is one indicator opening a thousand+-- alerts. Two independent mechanisms stop that, and they stop different+-- halves of it. The sweep query is an aggregate, so a million matching events+-- produce one result; that handles breadth. `retro_hunt_sightings` handles+-- time: its UNIQUE constraint means the same indicator seen again on a later+-- sweep updates a row rather than opening a second alert, so a feed that+-- republishes an indicator daily does not produce a daily alert. A cache+-- would lose that on restart and the first sweep after a deploy would+-- re-alert on everything already known.+--+-- Why the budget counters live on the settings row+-- -------------------------------------------------+-- The lake API's rate limiter is an in-memory token bucket, documented as a+-- soft per-process limit. That is right for an interactive surface where the+-- hard caps live downstream in ClickHouse. It is wrong here: sweeps arrive+-- from a queue rather than from a person, and an API restart would hand a+-- backlog a fresh full bucket. Counters on a row survive restarts and are+-- shared across replicas, which is what "budget" has to mean when the work is+-- unattended.++-- 1. Per-tenant opt-in and budget -------------------------------------------++CREATE TABLE IF NOT EXISTS retro_hunt_settings (+ tenant_id UUID PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,++ -- Off until a tenant asks. See above.+ enabled BOOLEAN NOT NULL DEFAULT FALSE,++ -- How far back a sweep looks. Bounded in the column so no settings row+ -- can express "scan everything"; the service clamps to the same ceiling.+ lookback_days INTEGER NOT NULL DEFAULT 30+ CHECK (lookback_days BETWEEN 1 AND 365),++ -- Whether to go beyond AiSOC's own lake into the tenant's connected+ -- SIEMs. Separate from `enabled` because it is a separate cost: a lake+ -- sweep is free to the customer and a SIEM sweep may not be.+ include_federated BOOLEAN NOT NULL DEFAULT TRUE,++ -- The budget. Both are per-tenant and both are enforced before a sweep+ -- runs, not after, so an exhausted budget costs nothing.+ max_sweeps_per_hour INTEGER NOT NULL DEFAULT 120+ CHECK (max_sweeps_per_hour BETWEEN 0 AND 10000),+ max_sweeps_per_day INTEGER NOT NULL DEFAULT 1000+ CHECK (max_sweeps_per_day BETWEEN 0 AND 100000),++ -- Rolling-window counters. `*_started_at` is the window anchor; the+ -- service resets the counter when the anchor is older than the window+ -- rather than running a cron to zero them.+ sweeps_this_hour INTEGER NOT NULL DEFAULT 0 CHECK (sweeps_this_hour >= 0),+ hour_started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ sweeps_today INTEGER NOT NULL DEFAULT 0 CHECK (sweeps_today >= 0),+ day_started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ -- Observability for the operator, not for billing: how many indicators+ -- were dropped because the budget was spent. A silently discarded sweep+ -- is indistinguishable from an indicator nobody published.+ sweeps_skipped_budget BIGINT NOT NULL DEFAULT 0 CHECK (sweeps_skipped_budget >= 0),++ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++COMMENT ON TABLE retro_hunt_settings IS+ 'Per-tenant opt-in and budget for intel-driven retro-hunts. Disabled by '+ 'default: a sweep costs the customer warehouse time and, where it reaches '+ 'a connected SIEM, possibly money.';+COMMENT ON COLUMN retro_hunt_settings.sweeps_skipped_budget IS+ 'Sweeps dropped because the hourly or daily budget was spent. Counted so '+ 'an operator can tell a quiet feed from an exhausted budget.';++-- 2. Dedup ledger and provenance --------------------------------------------++CREATE TABLE IF NOT EXISTS retro_hunt_sightings (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,++ -- The indicator, in the Phase 4 vocabulary+ -- (`app.services.agent_tools.indicators.INDICATOR_TYPES`) so an agent+ -- tool, a federated search and a retro-hunt all name types the same way.+ indicator_type TEXT NOT NULL,+ indicator_value TEXT NOT NULL,++ -- Provenance, which the plan requires an alert to carry: which feed+ -- published this, and when that feed first saw it. Kept beside the+ -- sighting rather than only in the alert body so a later sweep can+ -- report "known since" without re-reading an alert.+ feed_source TEXT NOT NULL,+ intel_first_seen_at TIMESTAMPTZ,++ -- Where it matched, and when, in the tenant's own data.+ first_matched_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ last_matched_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ first_sighting_at TIMESTAMPTZ,+ last_sighting_at TIMESTAMPTZ,+ sightings BIGINT NOT NULL DEFAULT 0 CHECK (sightings >= 0),+ matched_surfaces JSONB NOT NULL DEFAULT '[]'::jsonb,++ -- The alert this sighting opened. Nullable because a sweep that matched+ -- while the alert insert failed must still be recorded: losing the+ -- sighting would re-alert on the next sweep.+ alert_id UUID,++ -- How many times a later sweep found this same indicator again. The+ -- counter is the evidence that dedup is doing something, and it is what+ -- the gate asserts moves rather than the alert count.+ times_seen INTEGER NOT NULL DEFAULT 1 CHECK (times_seen >= 1),++ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ -- The whole dedup mechanism. One row per (tenant, indicator), so a feed+ -- republishing an indicator every day cannot open an alert every day.+ CONSTRAINT retro_hunt_sightings_unique UNIQUE (tenant_id, indicator_type, indicator_value)+);++COMMENT ON TABLE retro_hunt_sightings IS+ 'One row per (tenant, indicator) that a retro-hunt matched. The UNIQUE '+ 'constraint is the dedup: a republished indicator updates this row '+ 'instead of opening a second alert.';+COMMENT ON COLUMN retro_hunt_sightings.matched_surfaces IS+ 'Where the indicator matched: lake columns, connector types, and which '+ 'federated SIEM sources answered. Carried into the alert as provenance.';+COMMENT ON COLUMN retro_hunt_sightings.intel_first_seen_at IS+ 'When the publishing feed first saw the indicator, which is a different '+ 'fact from when the tenant first saw it (first_sighting_at). Both are '+ 'kept because an indicator published today and seen here last month is a '+ 'different finding from one published and seen today.';++CREATE INDEX IF NOT EXISTS idx_retro_hunt_sightings_tenant+ ON retro_hunt_sightings (tenant_id, last_matched_at DESC);++-- Row-level security. The `OR current_tenant_id() IS NULL` arm is what lets+-- the cross-tenant workers (retention purge, tenant deletion) reach these+-- tables; dropping it makes those silently see nothing. FORCE so the table+-- owner, which is the role that runs migrations, does not walk past it.+ALTER TABLE retro_hunt_settings ENABLE ROW LEVEL SECURITY;+ALTER TABLE retro_hunt_settings FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS retro_hunt_settings_tenant ON retro_hunt_settings;+CREATE POLICY retro_hunt_settings_tenant ON retro_hunt_settings+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++ALTER TABLE retro_hunt_sightings ENABLE ROW LEVEL SECURITY;+ALTER TABLE retro_hunt_sightings FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS retro_hunt_sightings_tenant ON retro_hunt_sightings;+CREATE POLICY retro_hunt_sightings_tenant ON retro_hunt_sightings+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++-- 061 set ALTER DEFAULT PRIVILEGES so new tables pick these up, but only for+-- tables created by the role that ran it. Granting explicitly means a chain+-- replayed by a different owner still leaves the runtime role able to work.+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ GRANT SELECT, INSERT, UPDATE, DELETE ON retro_hunt_settings TO aisoc_app;+ GRANT SELECT, INSERT, UPDATE, DELETE ON retro_hunt_sightings TO aisoc_app;+ END IF;+END+$$;diff --git a/services/api/poetry.lock b/services/api/poetry.lockindex 3dec7677c..a92b70ffa 100644--- a/services/api/poetry.lock+++ b/services/api/poetry.lock@@ -1,5 +1,58 @@# This file is automatically @generated by Poetry 2.4.1 and should not be changed by hand.+[[package]]+name = "aiokafka"+version = "0.14.0"+description = "Kafka integration with asyncio"+optional = false+python-versions = ">=3.10"+groups = ["main"]+files = [+ {file = "aiokafka-0.14.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2c767f320c902b126b7b37afb4ade241dc96e7d74b3515f0d0c1c8a800065113"},+ {file = "aiokafka-0.14.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:f68e75acf03631ea046b00bc8cc9aca8e3eb89486468b884629586ae6f2c63bc"},+ {file = "aiokafka-0.14.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4fd32fbddaae68ff12960ab79e368375e925920547e53997333c41f5c63b076f"},+ {file = "aiokafka-0.14.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a009ffd44afdcc2e982986dc0c80c60b3553b46d8666eafa78a69038f24036e6"},+ {file = "aiokafka-0.14.0-cp310-cp310-win32.whl", hash = "sha256:e51d48110767f228a44ccfd6e41c5444644c55e01f73b0a021227f19803a3714"},+ {file = "aiokafka-0.14.0-cp310-cp310-win_amd64.whl", hash = "sha256:9a7be05a3c72fa53c87b2a1c3979ca64d7fda870edb520ffc2871c2e7c99cd08"},+ {file = "aiokafka-0.14.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:549ac4bf3bbc823151fd4bdf761d644db8b0271bd9ae3f110b7f5ab804fcc1aa"},+ {file = "aiokafka-0.14.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9fa8416efd9f260c76125eceb554c4d731115df11d15fe6c4356a4855df7eccb"},+ {file = "aiokafka-0.14.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ccacd1c5e0e3e1ab4d2b3dac5228623e5a682915a61d2adc2e018015aa259475"},+ {file = "aiokafka-0.14.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ceb49c78b3e08ed3f9ff85350932ae59788596e8b45c6a4ca5d599337ba261e9"},+ {file = "aiokafka-0.14.0-cp311-cp311-win32.whl", hash = "sha256:5383991dcad641868a0af78c42ac86a1406ccf9803a20e2d690fc34a6119134e"},+ {file = "aiokafka-0.14.0-cp311-cp311-win_amd64.whl", hash = "sha256:91f34a6f8626b20f0adacdd364036f40d1da85d213c2cf7be0607cde2c8d0f2b"},+ {file = "aiokafka-0.14.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:284a90d617584d7e42688a181aaa8c2a909d9c658ab9b69c6cf92f4df5c4b320"},+ {file = "aiokafka-0.14.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b4f211d9e03a1fc83871a37eefcf307bc0943ee99adae25aa39bd1722e70747b"},+ {file = "aiokafka-0.14.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:be517b9b9513eba43ba19961dd770a6e26d08325743093feb47182770d235dd9"},+ {file = "aiokafka-0.14.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:219d2dc66b97b1aaea100697c928024b6a0348b7baa370b824900054bf86916e"},+ {file = "aiokafka-0.14.0-cp312-cp312-win32.whl", hash = "sha256:1086b470f6c452471603a2d9c8d6933739230c75758d777d8d113ff8112bad68"},+ {file = "aiokafka-0.14.0-cp312-cp312-win_amd64.whl", hash = "sha256:bcf3a8f6592d73f45965ca0750bfdfccf2555c8625358175c92f75f2cce1261a"},+ {file = "aiokafka-0.14.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:db16e43fac4c1c5006131046c1bf370c580d6ac4495a10ac7778245710943179"},+ {file = "aiokafka-0.14.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:32a8e91d88cf3ccf0778927715610d6579888c5f4748db4c2022cda25d628a48"},+ {file = "aiokafka-0.14.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:aad4a575a506e7784e25e430f27026fe2f4378560b21b7f4e8c9a54f0d06eaee"},+ {file = "aiokafka-0.14.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:75e4a003502c9c3b5c705fa7c00d634ba146bf38fa5d525b80bb6ff6e3e779fe"},+ {file = "aiokafka-0.14.0-cp313-cp313-win32.whl", hash = "sha256:a128e213cbc2bce0ea3db65a68920e52cebeeb8209bf001ac7aa022a8bd54d7d"},+ {file = "aiokafka-0.14.0-cp313-cp313-win_amd64.whl", hash = "sha256:d6fa16bef3544be87bd1a7a8317b9d85e3da59f3202326d9ff22735ed052746e"},+ {file = "aiokafka-0.14.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:5d70615d1530ad19d0c4da8d87abaec0a12b9fdaabffdcd4e400efa0c50ef80c"},+ {file = "aiokafka-0.14.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7e2392360c370b1ba6564c57d2889e154ecdb43157a8f7b7d7afe5e3c02fcc1a"},+ {file = "aiokafka-0.14.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:201e38ecc595f9f65a945f1ef9085157ddf28f25cd2e482fd9efa1fcf4638213"},+ {file = "aiokafka-0.14.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1cd651e1f56571baae306fdd0b5509047ab9625797a24cd75902e139c5a20318"},+ {file = "aiokafka-0.14.0-cp314-cp314-win32.whl", hash = "sha256:128127eb96dab98150b636bb5f480c80e15f02f82a118eec206a521c8cf7cf7c"},+ {file = "aiokafka-0.14.0-cp314-cp314-win_amd64.whl", hash = "sha256:aa385039aa9b235359319bbdcf48c9c86a75d81c9c547d645056d00361238903"},+ {file = "aiokafka-0.14.0.tar.gz", hash = "sha256:8ffdc945798ba4d3d132b705d4244d0a1f493925efb57c637a2ca88ee82794e1"},+]++[package.dependencies]+async-timeout = "*"+packaging = "*"+typing_extensions = ">=4.10.0"++[package.extras]+all = ["cramjam (>=2.8.0)", "gssapi"]+gssapi = ["gssapi"]+lz4 = ["cramjam (>=2.8.0)"]+snappy = ["cramjam"]+zstd = ["cramjam"]+[[package]]name = "alembic"version = "1.20.0"@@ -153,7 +206,6 @@ description = "Timeout context manager for asyncio programs"optional = falsepython-versions = ">=3.8"groups = ["main"]-markers = "python_full_version < \"3.11.3\""files = [{file = "async_timeout-5.0.1-py3-none-any.whl", hash = "sha256:39e3809566ff85354557ec2398b55e096c8364bacac9405a7a1fa429e77fe76c"},{file = "async_timeout-5.0.1.tar.gz", hash = "sha256:d9321a7a3d5a6a5e187e824d2fa0793ce379a202935782d555d6e9d2735677d3"},@@ -4081,4 +4133,4 @@ test = ["pytest"][metadata]lock-version = "2.1"python-versions = "^3.11"-content-hash = "55a4ace7b7d154fc933b7c96d3454836648c3d83c0421ee0540d0515920aceb3"+content-hash = "57fc6d3b979da8f0203728ddf35264c8f4a165a802ffd976843b3c4a15645355"diff --git a/services/api/pyproject.toml b/services/api/pyproject.tomlindex b7351e23b..37d866180 100644--- a/services/api/pyproject.toml+++ b/services/api/pyproject.toml@@ -87,6 +87,13 @@ weasyprint = ">=62,<71" # WS-G2: server-side PDF generation from print-# because croniter is API-stable and we only use the# `get_next` / `is_valid` surface.croniter = ">=2.0,<7.0"+# Gap-closure Phase 8.1 — the retro-hunt consumer subscribes to the+# `NEW_IOC` events `services/threatintel` emits. Same range `services/agents`+# already declares, so the two services that consume AiSOC's own topics+# resolve the same client: a consumer-group protocol difference between them+# would surface as a rebalance nobody could explain. Only used by+# `app.workers.retro_hunt_consumer`, which is off by default.+aiokafka = ">=0.10,<0.15"[tool.poetry.group.dev.dependencies]# Floored at 9.0.3 for GHSA advisory coverage; the caret pins excluded it.diff --git a/services/api/tests/test_retro_hunt.py b/services/api/tests/test_retro_hunt.pynew file mode 100644index 000000000..eb1dbac02--- /dev/null+++ b/services/api/tests/test_retro_hunt.py@@ -0,0 +1,464 @@+"""Gap-closure Phase 8.1: intel-driven retro-hunts.++Four groups, each covering one way this feature fails quietly rather than+loudly.++**The sweep reads columns the lake writer fills.** The static half of that is+``scripts/check_ioc_lake_mapping.py`` and the live half is+``tests/isolation/test_retro_hunt_live.py``. What is here is the shape of the+generated SQL: that an IPv6 column goes through ``toIPv6`` and an array column+through ``has``, because getting either wrong matches nothing with no error.++**One indicator opens at most one alert per tenant.** Tested from both+directions: a second sweep of the same indicator opens nothing and increments+a counter, and a sweep that matches a thousand events still issues one+aggregate query and opens one alert.++**A failure is never a zero.** An unreachable lake, an exhausted budget and a+type with no lake column are each distinct outcomes carrying a reason, and+none of them may read as "no sightings".++**A feed type nobody mapped is refused by name.** The translation from a+feed's vocabulary to AiSOC's is where a whole feed can silently stop being+swept, so an unknown type is asserted to be reported rather than defaulted.+"""++from __future__ import annotations++import uuid+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta+from typing import Any, cast++import pytest+from app.models.retro_hunt import RetroHuntSettings+from app.services.retro_hunt import ioc_fields+from app.services.retro_hunt.intel_types import route_feed_type+from app.services.retro_hunt.service import (+ IntelIndicator,+ _build_description,+ _consume_budget,+ alert_idempotency_key,+)+from app.services.retro_hunt.sweep import (+ MAX_LOOKBACK_DAYS,+ FederatedSweepResult,+ LakeSweepResult,+ SweepOutcome,+ build_sweep_sql,+)+from sqlalchemy.ext.asyncio import AsyncSession++TENANT = uuid.UUID("11111111-1111-1111-1111-111111111111")+++# ------------------------------------------------------------- generated SQL+++def test_every_sweepable_type_builds_a_tenant_scoped_query() -> None:+ """The predicate that makes a sweep safe is present in every statement."""+ for indicator_type, mapping in ioc_fields.SWEEPABLE_TYPES.items():+ sql, columns = build_sweep_sql(mapping)+ assert "tenant_id = %(tenant_id)s" in sql, indicator_type+ assert "%(needle)s" in sql, indicator_type+ assert columns, indicator_type+++def test_no_indicator_value_is_ever_interpolated() -> None:+ """The indicator is third-party text and always travels as a parameter.++ Asserted structurally rather than by reading the code: the only ``%``+ formatting in the statement is the driver's own placeholder syntax, so a+ future edit that f-strings a value in has to break this.+ """+ for mapping in ioc_fields.SWEEPABLE_TYPES.values():+ sql, _ = build_sweep_sql(mapping)+ placeholders = {"%(tenant_id)s", "%(lookback_days)s", "%(needle)s"}+ remaining = sql+ for placeholder in placeholders:+ remaining = remaining.replace(placeholder, "")+ assert "%" not in remaining, f"unexpected format specifier in: {sql}"+++def test_ip_columns_go_through_toipv6() -> None:+ """An IPv4 needle must be normalised the way the writer normalised it.++ ``lake_writer._to_ip_obj`` stores ``1.2.3.4`` as ``::ffff:1.2.3.4``, so a+ predicate comparing the IPv6 column to the dotted-quad string matches+ nothing. This is the single highest-value assertion in the file: it fails+ silently in production and loudly here.+ """+ sql, _ = build_sweep_sql(ioc_fields.SWEEPABLE_TYPES["ip"])+ assert "source_ip = toIPv6(%(needle)s)" in sql+ assert "dest_ip = toIPv6(%(needle)s)" in sql+ assert "source_ip = %(needle)s" not in sql+++def test_array_columns_use_has_not_equality() -> None:+ sql, _ = build_sweep_sql(ioc_fields.SWEEPABLE_TYPES["sha256"])+ assert "has(iocs, %(needle)s)" in sql+ assert "iocs = %(needle)s" not in sql+++def test_the_query_aggregates_so_a_thousand_matches_are_one_row() -> None:+ """The structural answer to "one IOC must not open a thousand alerts".++ No ``SELECT``ed event column and no absent ``count()``: the sweep cannot+ return a row per match even if a caller wanted it to.+ """+ for mapping in ioc_fields.SWEEPABLE_TYPES.values():+ sql, _ = build_sweep_sql(mapping)+ assert sql.startswith("SELECT count() AS sightings")+ assert "groupUniqArray(20)" in sql+ assert " LIMIT " not in sql # an aggregate needs no limit to be bounded+++def test_hash_types_all_read_the_column_the_writer_actually_fills() -> None:+ """md5 and sha1 read ``hash_sha256``, because that is where they land.++ ``lake_writer._first_hash`` takes ``file.fingerprints[0].value`` without+ inspecting the algorithm. A mapping to a plausible ``hash_md5`` column+ would have matched nothing on every deployment.+ """+ for hash_type in ("md5", "sha1", "sha256"):+ names = ioc_fields.SWEEPABLE_TYPES[hash_type].column_names+ assert "hash_sha256" in names, hash_type+++def test_domain_does_not_sweep_the_reporting_host_column() -> None:+ """``src_hostname`` is the tenant's own device name, not a contacted name."""+ assert "src_hostname" not in ioc_fields.SWEEPABLE_TYPES["domain"].column_names+ assert "dst_hostname" in ioc_fields.SWEEPABLE_TYPES["domain"].column_names+++# ------------------------------------------------------------ type routing+++ ("feed_type", "expected"),+ [+ ("ipv4-addr", "ip"),+ ("ipv6-addr", "ip"),+ ("ip-src", "ip"),+ ("ip-dst", "ip"),+ ("domain-name", "domain"),+ ("file-hash:SHA-256", "sha256"),+ ("file-hash:MD5", "md5"),+ ("FILE-HASH:SHA-1", "sha1"),+ ("sha256", "sha256"),+ ],+)+def test_feed_vocabularies_resolve_to_one_indicator_type(feed_type: str, expected: str) -> None:+ assert route_feed_type(feed_type).indicator_type == expected+++def test_an_unknown_feed_type_is_refused_by_name_not_defaulted() -> None:+ """A default here would sweep the wrong column and call the answer evidence."""+ routing = route_feed_type("some-type-no-feed-in-this-tree-emits")+ assert routing.unknown is True+ assert routing.indicator_type is None+ assert routing.reason and "NOT swept" in routing.reason+++def test_a_cve_is_routed_away_from_telemetry_rather_than_swept() -> None:+ """Sweeping the lake for a CVE string matches nothing on every deployment."""+ routing = route_feed_type("vulnerability")+ assert routing.is_vulnerability is True+ assert routing.indicator_type is None+++def test_a_known_unsweepable_type_is_not_reported_as_unknown() -> None:+ """Two different problems: "nobody mapped this" and "this cannot be mapped"."""+ routing = route_feed_type("email-addr")+ assert routing.unknown is False+ assert routing.indicator_type is None+ assert routing.reason+++def test_url_is_declared_unmappable_with_a_reason_rather_than_omitted() -> None:+ mapping = ioc_fields.mapping_for("url")+ assert isinstance(mapping, ioc_fields.UnmappedIndicator)+ assert "raw_payload" in mapping.reason+++# ------------------------------------------------------------------ budget+++@dataclass+class _FakeSettings:+ """Enough of ``RetroHuntSettings`` to exercise the budget arithmetic."""++ max_sweeps_per_hour: int = 2+ max_sweeps_per_day: int = 3+ sweeps_this_hour: int = 0+ sweeps_today: int = 0+ sweeps_skipped_budget: int = 0+ hour_started_at: datetime = datetime.now(UTC)+ day_started_at: datetime = datetime.now(UTC)+ updated_at: datetime = datetime.now(UTC)+++async def _budget(row: _FakeSettings, *, now: datetime) -> bool:+ """``_consume_budget`` against the in-memory double.++ The session is ``None`` because the budget path never reaches it, and+ ``_FakeSettings`` stands in for the ORM row. Both are deliberate doubles,+ so the casts are stated once here rather than as sixteen ignores spread+ across eight call sites.+ """+ return await _consume_budget(cast(AsyncSession, None), cast(RetroHuntSettings, row), now=now)+++async def test_budget_refuses_once_the_hourly_allowance_is_spent() -> None:+ row = _FakeSettings()+ now = datetime.now(UTC)+ assert await _budget(row, now=now) is True+ assert await _budget(row, now=now) is True+ assert await _budget(row, now=now) is False+ assert row.sweeps_skipped_budget == 1+++async def test_a_refused_sweep_is_counted_so_a_quiet_feed_is_distinguishable() -> None:+ """An operator must be able to tell an empty budget from an empty feed."""+ row = _FakeSettings(max_sweeps_per_hour=0)+ assert await _budget(row, now=datetime.now(UTC)) is False+ assert row.sweeps_skipped_budget == 1+ assert row.sweeps_this_hour == 0+++async def test_the_hourly_window_resets_lazily_without_a_scheduled_job() -> None:+ now = datetime.now(UTC)+ row = _FakeSettings(sweeps_this_hour=2, hour_started_at=now - timedelta(hours=2))+ assert await _budget(row, now=now) is True+ assert row.sweeps_this_hour == 1+++async def test_the_daily_ceiling_holds_even_when_hours_keep_resetting() -> None:+ """The two windows are independent, so the wider one must still bind."""+ row = _FakeSettings(max_sweeps_per_hour=100, max_sweeps_per_day=2)+ base = datetime.now(UTC)+ assert await _budget(row, now=base) is True+ assert await _budget(row, now=base + timedelta(hours=1, minutes=1)) is True+ assert await _budget(row, now=base + timedelta(hours=2, minutes=2)) is False+++# ------------------------------------------------------------------- dedup+++def test_the_alert_idempotency_key_is_stable_and_fits_the_column() -> None:+ """The second dedup layer: a per-tenant unique index on ``alerts``."""+ key = alert_idempotency_key("sha256", "a" * 64)+ assert key == alert_idempotency_key("sha256", "a" * 64)+ assert key != alert_idempotency_key("sha256", "b" * 64)+ assert key != alert_idempotency_key("md5", "a" * 64)+ assert len(key) <= 128+++def test_the_idempotency_key_survives_an_indicator_too_long_for_the_column() -> None:+ """A 2 KB URL must not produce a key the column truncates into a collision."""+ key = alert_idempotency_key("url", "https://example.invalid/" + "x" * 4000)+ assert len(key) <= 128+++# --------------------------------------------------------------- provenance+++def _outcome(*, lake_checked: bool = True, sightings: int = 3, fed: FederatedSweepResult | None = None) -> SweepOutcome:+ return SweepOutcome(+ indicator_type="ip",+ value="203.0.113.9",+ lookback_days=30,+ lake=LakeSweepResult(+ indicator_type="ip",+ value="203.0.113.9",+ checked=lake_checked,+ sightings=sightings,+ first_sighting_at=datetime(2026, 8, 1, tzinfo=UTC),+ last_sighting_at=datetime(2026, 9, 1, tzinfo=UTC),+ connector_types=["aws_cloudtrail"],+ hosts=["web-01"],+ users=["alice"],+ columns_searched=("source_ip", "dest_ip", "iocs"),+ unavailable_reason=None if lake_checked else "No event lake is configured on this deployment.",+ ),+ federated=fed or FederatedSweepResult(checked=True, sightings=0, sources_ok=["splunk"]),+ )+++def test_the_alert_body_names_the_feed_and_both_first_seen_facts() -> None:+ """The plan's provenance list, plus the distinction it would lose.++ "First seen" is two different facts. An indicator published this morning+ and last seen in the estate five weeks ago is a materially different+ finding from one published and seen today, and one field cannot say so.+ """+ indicator = IntelIndicator(+ indicator_type="ip",+ value="203.0.113.9",+ feed_source="cisa-kev",+ first_seen_at=datetime(2026, 9, 20, tzinfo=UTC),+ )+ body = _build_description(indicator, _outcome())+ assert "cisa-kev" in body+ assert "First seen by the feed: 2026-09-20" in body+ assert "First sighting in your data: 2026-08-01" in body+ assert "source_ip, dest_ip, iocs" in body+ assert "web-01" in body+++def test_a_feed_that_published_no_first_seen_says_so_rather_than_stamping_now() -> None:+ indicator = IntelIndicator(indicator_type="ip", value="203.0.113.9", feed_source="otx")+ body = _build_description(indicator, _outcome())+ assert "not published by this feed" in body+++def test_a_gap_is_carried_into_the_alert_even_when_the_sweep_matched() -> None:+ """Found in the lake while the SIEM sweep failed is its own finding."""+ outcome = _outcome(+ fed=FederatedSweepResult(+ checked=False,+ sources_failed=["splunk"],+ unavailable_reason="Every connected SIEM failed to answer, so none of them were searched.",+ )+ )+ body = _build_description(IntelIndicator("ip", "203.0.113.9", "otx"), outcome)+ assert "What was NOT checked" in body+ assert "A gap is not evidence of absence" in body+ assert "splunk" in body+++def test_an_unchecked_lake_never_reads_as_zero_sightings() -> None:+ """``checked`` and ``sightings`` are separate, and ``matched`` needs both."""+ result = LakeSweepResult(+ indicator_type="ip",+ value="203.0.113.9",+ checked=False,+ unavailable_reason="No event lake is configured on this deployment.",+ )+ assert result.matched is False+ assert result.sightings == 0+ outcome = SweepOutcome(+ indicator_type="ip",+ value="203.0.113.9",+ lookback_days=30,+ lake=result,+ federated=FederatedSweepResult(+ checked=False,+ unavailable_reason="This tenant has no SIEM connected to AiSOC, so there was nothing to search beyond the event lake.",+ ),+ )+ assert outcome.matched is False+ # Both unchecked surfaces are named. A sweep that reported one gap and+ # stayed silent about the other would be claiming coverage it does not+ # have, which is the same defect as reporting a zero.+ gaps = outcome.gaps+ assert len(gaps) == 2+ assert any(gap.startswith("Event lake:") for gap in gaps)+ assert any(gap.startswith("Federated SIEM search:") for gap in gaps)+++def test_a_source_with_no_field_mapping_is_a_gap_not_a_clean_answer() -> None:+ outcome = _outcome(fed=FederatedSweepResult(checked=True, sources_ok=["splunk"], sources_unmapped=["qradar"]))+ gaps = outcome.gaps+ assert any("qradar" in gap and "no field mapping" in gap for gap in gaps)+++# -------------------------------------------------------------- lookback cap+++def test_the_lookback_window_is_bounded_in_code_as_well_as_in_the_column() -> None:+ """A settings row cannot express "scan everything", and nor can a caller."""+ assert MAX_LOOKBACK_DAYS == 365+++class _Row(list):+ pass+++async def test_an_empty_result_set_is_reported_as_unknown_not_as_zero(monkeypatch: pytest.MonkeyPatch) -> None:+ """An aggregate always returns one row, so no rows means something is wrong.++ Reading that as zero sightings is precisely the failure this module+ exists to avoid, so it is asserted rather than assumed.+ """+ from app.services.retro_hunt import sweep as sweep_module++ @dataclass+ class _Result:+ rows: list[Any]++ async def _fake_query(*_args: Any, **_kwargs: Any) -> Any:+ return _Result(rows=[])++ monkeypatch.setattr(sweep_module, "execute_lake_query", _fake_query)+ result = await sweep_module.sweep_lake(tenant_id=TENANT, indicator_type="ip", value="203.0.113.9")+ assert result.checked is False+ assert result.unavailable_reason and "unreadable" in result.unavailable_reason+++async def test_a_lake_that_is_not_configured_is_a_gap_with_a_named_cause(monkeypatch: pytest.MonkeyPatch) -> None:+ from app.services.retro_hunt import sweep as sweep_module++ async def _fake_query(*_args: Any, **_kwargs: Any) -> Any:+ raise sweep_module.LakeQueryNotConfiguredError("no host")++ monkeypatch.setattr(sweep_module, "execute_lake_query", _fake_query)+ result = await sweep_module.sweep_lake(tenant_id=TENANT, indicator_type="ip", value="203.0.113.9")+ assert result.checked is False+ assert "No event lake is configured" in (result.unavailable_reason or "")+++async def test_a_budget_timeout_is_reported_as_an_incomplete_sweep(monkeypatch: pytest.MonkeyPatch) -> None:+ from app.services.retro_hunt import sweep as sweep_module++ async def _fake_query(*_args: Any, **_kwargs: Any) -> Any:+ raise sweep_module.LakeQueryTimeoutError("too slow")++ monkeypatch.setattr(sweep_module, "execute_lake_query", _fake_query)+ result = await sweep_module.sweep_lake(tenant_id=TENANT, indicator_type="ip", value="203.0.113.9")+ assert result.checked is False+ assert "NOT fully searched" in (result.unavailable_reason or "")+++async def test_a_matching_sweep_reports_the_aggregate_the_query_returned(monkeypatch: pytest.MonkeyPatch) -> None:+ from app.services.retro_hunt import sweep as sweep_module++ @dataclass+ class _Result:+ rows: list[Any]++ async def _fake_query(sql: str, **kwargs: Any) -> Any:+ assert kwargs["params"]["needle"] == "203.0.113.9"+ assert kwargs["params"]["tenant_id"] == str(TENANT)+ # The budget travels with the query rather than being an intention.+ assert kwargs["extra_settings"]["max_bytes_to_read"] == sweep_module.MAX_BYTES_PER_SWEEP+ return _Result(+ rows=[+ [+ 1000,+ datetime(2026, 8, 1, tzinfo=UTC),+ datetime(2026, 9, 1, tzinfo=UTC),+ ["aws_cloudtrail"],+ ["web-01", ""],+ ["alice"],+ ]+ ]+ )++ monkeypatch.setattr(sweep_module, "execute_lake_query", _fake_query)+ result = await sweep_module.sweep_lake(tenant_id=TENANT, indicator_type="ip", value="203.0.113.9")+ assert result.checked is True+ assert result.sightings == 1000+ assert result.matched is True+ # A thousand sightings produce bounded evidence, and the empty-string+ # host ClickHouse returns for events with no hostname is dropped rather+ # than rendered as a blank entry in an alert.+ assert result.hosts == ["web-01"]diff --git a/tests/isolation/test_retro_hunt_live.py b/tests/isolation/test_retro_hunt_live.pynew file mode 100644index 000000000..47562c94b--- /dev/null+++ b/tests/isolation/test_retro_hunt_live.py@@ -0,0 +1,460 @@+"""The retro-hunt's done-when clause, proven against a live warehouse.++Gap-closure Phase 8.1.++The clause is: *a new IOC injected into the pipeline produces a retro-hunt+alert for a tenant whose recorded lake data contains it, and none for a tenant+whose data does not.* Everything below exists to make that provable rather+than asserted.++Why this test is shaped the way it is+-------------------------------------++The thing that could be wrong is the mapping from an indicator to a lake+column, and that is exactly the kind of wrong a self-authored fixture cannot+find. Roughly 600 of this repository's 825 detection fixtures are synthesised+from the rule they test, which makes replay circular, and the two largest+field-reachability defects in its history both passed their own tests+throughout. So no part of the chain below is re-implemented here:++* the OCSF event is shaped the way ``services/ingest`` emits one, with the+ endpoint blocks and fingerprint list the normaliser produces;+* the lake row comes from ``lake_writer.event_to_row``, the only function in+ production that writes to ``aisoc.raw_events``, loaded from its own file;+* the table is created from ``services/api/clickhouse/001_init.sql``, the DDL+ a deployment actually runs;+* the sweep SQL comes from ``retro_hunt.sql.build_sweep_sql``, the generator+ the service calls.++If the mapping is wrong, this test fails. That is the difference between+proving a sweep matches recorded data and asserting that it does.++Both modules are loaded by path because ``services/api`` and+``services/fusion`` both package their code as a top-level ``app``, so only+one of them can be imported normally in one interpreter. The loader registers+each module in ``sys.modules`` for the duration of its execution, because+``@dataclass`` resolves annotations through it, and removes it afterwards,+because a synthetic name left behind has previously broken 21 unrelated tests+in this repository while every test in its own file passed.++Skips when no ClickHouse is reachable, the same way the rest of this directory+does. It runs for real in ``isolation-live.yml``.+"""++from __future__ import annotations++import importlib.util+import ipaddress+import os+import re+import sys+import uuid+from pathlib import Path+from typing import Any++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]++# Two tenants. A has the indicator in its recorded data; B does not. The+# done-when clause is a statement about the pair, so neither is meaningful+# alone.+TENANT_A = uuid.UUID("aaaaaaaa-0000-4000-8000-000000000001")+TENANT_B = uuid.UUID("bbbbbbbb-0000-4000-8000-000000000002")++# The indicator a feed publishes. Documentation-range addresses and an+# obviously-synthetic hash, so nothing here resembles a real IOC.+IOC_IP = "203.0.113.77"+IOC_SHA256 = "a" * 64+IOC_DOMAIN = "malicious.example.invalid"+BENIGN_IP = "198.51.100.5"+++def _load_by_path(rel: str, alias: str) -> Any:+ """Import one module by file path, leaving ``sys.modules`` as it found it."""+ spec = importlib.util.spec_from_file_location(alias, REPO_ROOT / rel)+ if spec is None or spec.loader is None: # pragma: no cover - path is fixed+ raise RuntimeError(f"cannot load {rel}")+ module = importlib.util.module_from_spec(spec)+ sys.modules[alias] = module+ try:+ spec.loader.exec_module(module)+ finally:+ sys.modules.pop(alias, None)+ return module+++def _load_sweep_sql() -> Any:+ """Load ``retro_hunt.sql``, which imports ``ioc_fields`` by package path.++ ``sql.py`` does ``from app.services.retro_hunt.ioc_fields import ...``, so+ the package name has to resolve. Registering the two parents as namespace+ modules is enough, and is cheaper and far less fragile than putting the+ whole API service on ``sys.path`` beside the fusion service, which is the+ collision this loader exists to avoid.+ """+ import types # noqa: PLC0415 - only needed on this path++ created: list[str] = []+ for name in ("app", "app.services", "app.services.retro_hunt"):+ if name not in sys.modules:+ sys.modules[name] = types.ModuleType(name)+ created.append(name)+ try:+ ioc_fields = _load_by_path(+ "services/api/app/services/retro_hunt/ioc_fields.py",+ "app.services.retro_hunt.ioc_fields",+ )+ sys.modules["app.services.retro_hunt.ioc_fields"] = ioc_fields+ sql_module = _load_by_path("services/api/app/services/retro_hunt/sql.py", "app.services.retro_hunt.sql")+ return ioc_fields, sql_module+ finally:+ sys.modules.pop("app.services.retro_hunt.ioc_fields", None)+ for name in created:+ sys.modules.pop(name, None)+++def _raw_events_ddl() -> str:+ """The production DDL for ``aisoc.raw_events``, read from the file.++ Trimmed of the ``INDEX`` clauses only: bloom-filter indexes change the+ plan, never the result, and a single-node test container does not need+ them. Everything that decides whether a value matches, above all the+ ``IPv6`` and ``Array(String)`` column types, is used verbatim.+ """+ sql = (REPO_ROOT / "services/api/clickhouse/001_init.sql").read_text(encoding="utf-8")+ match = re.search(r"(CREATE TABLE IF NOT EXISTS aisoc\.raw_events.*?ORDER BY \([^)]*\))", sql, re.DOTALL)+ assert match, "could not find the raw_events DDL; this test must not invent one"+ body = match.group(1)+ return "\n".join(line for line in body.splitlines() if not line.strip().startswith(("INDEX ", "--")))+++def _ocsf_event(*, tenant: uuid.UUID, src_ip: str, sha256: str | None = None, dst_hostname: str = "") -> dict[str, Any]:+ """One normalized OCSF event, shaped the way ingest emits them.++ The nesting is the point. ``src_endpoint.ip``, ``file.fingerprints[0].value``+ and ``dst_endpoint.hostname`` are where the writer reads from, and a+ flattened fixture would silently pass while production silently failed.+ """+ event: dict[str, Any] = {+ "class_uid": 4001,+ "category_uid": 4,+ "severity_id": 3,+ "severity": "medium",+ "time": "2026-09-20T12:00:00Z",+ "src_endpoint": {"ip": src_ip, "port": 44321},+ "dst_endpoint": {"ip": "198.51.100.200", "port": 443, "hostname": dst_hostname},+ "device": {"name": "web-01"},+ "actor": {"user": {"name": "alice"}},+ "process": {"name": "curl"},+ "metadata": {"product": {"name": "aws_cloudtrail"}},+ }+ if sha256:+ event["file"] = {"path": "/tmp/payload.bin", "fingerprints": [{"algorithm": "SHA-256", "value": sha256}]}+ return {+ "id": str(uuid.uuid4()),+ "tenant_id": str(tenant),+ "connector_type": "aws_cloudtrail",+ "ocsf_event": event,+ }++[email protected](scope="module")+def clickhouse_client() -> Any:+ driver = pytest.importorskip("clickhouse_driver", reason="clickhouse-driver not installed")+ # `ISOLATION_*` is what `isolation-live.yml` sets, and is preferred so this+ # file behaves identically to the rest of the directory in CI. The+ # unprefixed names are the fallback so a developer can point it at a local+ # container without inventing a second set of variables.+ host = os.getenv("ISOLATION_CLICKHOUSE_HOST") or os.getenv("CLICKHOUSE_HOST", "localhost")+ # Chained `or` with the default last, so an env var set to the empty string+ # falls through to the default rather than reaching `int("")`.+ port = int(os.getenv("ISOLATION_CLICKHOUSE_PORT") or os.getenv("CLICKHOUSE_PORT") or "9000")+ try:+ client = driver.Client(+ host=host,+ port=port,+ user=os.getenv("CLICKHOUSE_USER", "default"),+ password=os.getenv("CLICKHOUSE_PASSWORD", ""),+ connect_timeout=5,+ )+ client.execute("SELECT 1")+ except Exception as exc: # noqa: BLE001 - absence is a skip, not a failure+ pytest.skip(f"no ClickHouse at {host}:{port} ({type(exc).__name__})")+ return client++[email protected](scope="module")+def seeded_lake(clickhouse_client: Any) -> Any:+ """A real lake holding rows the real writer produced.++ Tenant A's events contain the published indicators. Tenant B's contain+ ordinary traffic and a different hash, so a sweep that matched for B would+ be matching something other than what it was asked about.+ """+ lake_writer = _load_by_path("services/fusion/app/services/lake_writer.py", "_aisoc_live_lake_writer")++ client = clickhouse_client+ client.execute("CREATE DATABASE IF NOT EXISTS aisoc")+ client.execute("DROP TABLE IF EXISTS aisoc.raw_events")+ client.execute(_raw_events_ddl())++ messages = [+ _ocsf_event(tenant=TENANT_A, src_ip=IOC_IP, sha256=IOC_SHA256, dst_hostname=IOC_DOMAIN),+ _ocsf_event(tenant=TENANT_A, src_ip=BENIGN_IP),+ _ocsf_event(tenant=TENANT_B, src_ip=BENIGN_IP, sha256="b" * 64, dst_hostname="ordinary.example.invalid"),+ _ocsf_event(tenant=TENANT_B, src_ip="198.51.100.6"),+ ]++ rows = []+ for message in messages:+ row = lake_writer.event_to_row(message)+ assert row is not None, "the production writer refused an event this test must be able to record"+ out = {k: v for k, v in row.items() if not (k == "event_id" and v is None)}+ out["source_ip"] = lake_writer._to_ip_obj(row["source_ip"])+ out["dest_ip"] = lake_writer._to_ip_obj(row["dest_ip"])+ rows.append(out)++ client.execute(lake_writer._INSERT_SQL, rows, types_check=True)+ yield client+ client.execute("DROP TABLE IF EXISTS aisoc.raw_events")+++# --------------------------------------------------------------------------+# What the writer actually recorded+# --------------------------------------------------------------------------+++def test_the_writer_stores_an_ipv4_address_as_its_ipv4_mapped_form() -> None:+ """The reason the sweep needs ``toIPv6``, established before it is used.++ Asserted against the production writer rather than stated in a comment,+ because if this ever stops being true the sweep's normalisation becomes+ wrong in the other direction and would again match nothing.+ """+ lake_writer = _load_by_path("services/fusion/app/services/lake_writer.py", "_aisoc_ip_shape_writer")+ stored = lake_writer._to_ip_obj(IOC_IP)+ assert isinstance(stored, ipaddress.IPv6Address)+ assert stored == ipaddress.IPv6Address(f"::ffff:{IOC_IP}")+ assert stored.ipv4_mapped == ipaddress.IPv4Address(IOC_IP)+ # Compared as addresses rather than as text on purpose. Python renders a+ # mapped address in hex (`::ffff:cb00:714d`), so a string comparison here+ # would be asserting a rendering rather than the value, and the value is+ # what the column holds and what the predicate has to match.+ assert str(stored) != IOC_IP+++def test_the_writer_puts_a_fingerprint_in_the_hash_sha256_column() -> None:+ """The reason md5 and sha1 map to ``hash_sha256``."""+ lake_writer = _load_by_path("services/fusion/app/services/lake_writer.py", "_aisoc_hash_shape_writer")+ row = lake_writer.event_to_row(_ocsf_event(tenant=TENANT_A, src_ip=IOC_IP, sha256=IOC_SHA256))+ assert row is not None+ assert row["hash_sha256"] == IOC_SHA256+++# --------------------------------------------------------------------------+# The done-when clause+# --------------------------------------------------------------------------+++def _sweep(client: Any, *, tenant: uuid.UUID, indicator_type: str, value: str) -> int:+ ioc_fields, sql_module = _load_sweep_sql()+ mapping = ioc_fields.SWEEPABLE_TYPES[indicator_type]+ sql, _columns = sql_module.build_sweep_sql(mapping)+ rows = client.execute(+ sql,+ {"tenant_id": str(tenant), "lookback_days": 3650, "needle": value},+ )+ assert len(rows) == 1, "the sweep must be an aggregate returning exactly one row"+ return int(rows[0][0])+++ ("indicator_type", "value"),+ [("ip", IOC_IP), ("sha256", IOC_SHA256), ("domain", IOC_DOMAIN)],+)+def test_a_published_indicator_is_found_for_the_tenant_whose_data_holds_it(+ seeded_lake: Any,+ indicator_type: str,+ value: str,+) -> None:+ """Half one of the done-when clause, for three indicator types.++ This is the assertion that the mapping is right. It runs the real+ generator against a real warehouse holding a row the real writer produced,+ so a wrong column, a missing ``toIPv6`` or a scalar comparison against an+ array all fail here.+ """+ assert _sweep(seeded_lake, tenant=TENANT_A, indicator_type=indicator_type, value=value) >= 1+++ ("indicator_type", "value"),+ [("ip", IOC_IP), ("sha256", IOC_SHA256), ("domain", IOC_DOMAIN)],+)+def test_the_same_indicator_is_not_found_for_a_tenant_whose_data_lacks_it(+ seeded_lake: Any,+ indicator_type: str,+ value: str,+) -> None:+ """Half two. Tenant B has rows, just not these, so a zero here is real.++ A tenant with no rows at all would return zero whether or not the sweep+ were tenant-scoped, which would make this half vacuous. B's rows are+ asserted separately below.+ """+ assert _sweep(seeded_lake, tenant=TENANT_B, indicator_type=indicator_type, value=value) == 0+++ ("indicator_type", "value", "expected_columns"),+ [+ ("ip", IOC_IP, {"source_ip", "iocs"}),+ ("sha256", IOC_SHA256, {"hash_sha256", "iocs"}),+ ("domain", IOC_DOMAIN, {"dst_hostname"}),+ ("hostname", "web-01", {"src_hostname"}),+ ("username", "alice", {"user_name"}),+ ("process_name", "curl", {"process_name"}),+ ],+)+def test_each_mapped_column_is_exercised_on_its_own(+ seeded_lake: Any,+ indicator_type: str,+ value: str,+ expected_columns: set[str],+) -> None:+ """Which columns actually match, one predicate at a time.++ The test above this one runs the assembled statement, and an OR hides a+ broken branch behind a working one. ``iocs`` carries IP addresses and+ hashes as plain strings, so it matches for most indicator types whether or+ not the typed column beside it was mapped correctly: pointing ``source_ip``+ at a column that does not exist would still have passed. Dropping+ ``is_ip`` from both IP columns was tried against this file and the+ assembled-statement tests all passed, which is what this exists to close.++ So each column is probed alone, and the set that matches is compared+ against the set that should. A column that stops matching is named rather+ than absorbed.+ """+ ioc_fields, sql_module = _load_sweep_sql()+ mapping = ioc_fields.SWEEPABLE_TYPES[indicator_type]++ matched: set[str] = set()+ for column in mapping.columns:+ predicate = sql_module.column_predicate(column)+ count = seeded_lake.execute(+ f"SELECT count() FROM aisoc.raw_events WHERE tenant_id = %(tenant_id)s AND ({predicate})",+ {"tenant_id": str(TENANT_A), "needle": value},+ )[0][0]+ if count:+ matched.add(column.name)++ assert matched == expected_columns, (+ f"{indicator_type}: columns that matched recorded lake data were {sorted(matched)}, expected {sorted(expected_columns)}. "+ f"A column in the expected set that did not match is a mapping that reads something the writer never fills."+ )+++def test_the_iocs_array_alone_does_not_carry_the_ip_mapping(seeded_lake: Any) -> None:+ """The typed IP column must match on its own merit.++ Stated separately because it is the specific masking that was found: with+ ``iocs`` in the same OR, an ``ip`` sweep matches even when nothing about+ ``source_ip`` is right.+ """+ ioc_fields, sql_module = _load_sweep_sql()+ source_ip = next(c for c in ioc_fields.SWEEPABLE_TYPES["ip"].columns if c.name == "source_ip")+ count = seeded_lake.execute(+ f"SELECT count() FROM aisoc.raw_events WHERE tenant_id = %(tenant_id)s AND ({sql_module.column_predicate(source_ip)})",+ {"tenant_id": str(TENANT_A), "needle": IOC_IP},+ )[0][0]+ assert count >= 1+++def test_an_array_flag_that_disagrees_with_the_column_is_a_hard_error(seeded_lake: Any) -> None:+ """Why the mapping gate checks the flags, measured rather than asserted.++ Three of the four flag disagreements make ClickHouse reject the query, so+ they cannot ship silently. The fourth, a missing ``is_ip``, is tolerated+ because the server coerces the literal, which is recorded here so the+ mapping module's comments describe the server's real behaviour instead of+ a plausible one.+ """+ with pytest.raises(Exception): # noqa: B017 - driver raises a ServerException subclass+ seeded_lake.execute(+ "SELECT count() FROM aisoc.raw_events WHERE has(hash_sha256, %(needle)s)",+ {"needle": IOC_SHA256},+ )+ with pytest.raises(Exception): # noqa: B017+ seeded_lake.execute(+ "SELECT count() FROM aisoc.raw_events WHERE iocs = %(needle)s",+ {"needle": IOC_SHA256},+ )+ # And the tolerated one, recorded as tolerated.+ coerced = seeded_lake.execute(+ "SELECT count() FROM aisoc.raw_events WHERE tenant_id = %(t)s AND source_ip = %(needle)s",+ {"t": str(TENANT_A), "needle": IOC_IP},+ )[0][0]+ assert coerced >= 1, "ClickHouse coerces a string literal to IPv6; if this ever stops, toIPv6 becomes load-bearing"+++def test_tenant_b_has_recorded_data_so_its_zero_is_a_real_negative(seeded_lake: Any) -> None:+ """Without this the negative half proves only that B's partition is empty."""+ rows = seeded_lake.execute(+ "SELECT count() FROM aisoc.raw_events WHERE tenant_id = %(t)s",+ {"t": str(TENANT_B)},+ )+ assert rows[0][0] >= 2+ # And B really does hold a benign address the sweep can find, which shows+ # the query works against B's partition rather than being scoped to+ # nothing.+ assert _sweep(seeded_lake, tenant=TENANT_B, indicator_type="ip", value=BENIGN_IP) >= 1+++def test_a_thousand_matching_events_still_produce_one_aggregate_row(seeded_lake: Any) -> None:+ """The structural answer to "one IOC must not open a thousand alerts".++ Written with real rows rather than reasoned about: a thousand events+ carrying the indicator are inserted and the sweep is asserted to return a+ single row whose count reflects all of them. The service opens one alert+ per (tenant, indicator), so this is the layer that decides how much work+ reaches it.+ """+ lake_writer = _load_by_path("services/fusion/app/services/lake_writer.py", "_aisoc_bulk_writer")+ flood_tenant = uuid.UUID("cccccccc-0000-4000-8000-000000000003")+ rows = []+ for _ in range(1000):+ row = lake_writer.event_to_row(_ocsf_event(tenant=flood_tenant, src_ip=IOC_IP))+ assert row is not None+ out = {k: v for k, v in row.items() if not (k == "event_id" and v is None)}+ out["source_ip"] = lake_writer._to_ip_obj(row["source_ip"])+ out["dest_ip"] = lake_writer._to_ip_obj(row["dest_ip"])+ rows.append(out)+ seeded_lake.execute(lake_writer._INSERT_SQL, rows, types_check=True)++ ioc_fields, sql_module = _load_sweep_sql()+ sql, _ = sql_module.build_sweep_sql(ioc_fields.SWEEPABLE_TYPES["ip"])+ result = seeded_lake.execute(sql, {"tenant_id": str(flood_tenant), "lookback_days": 3650, "needle": IOC_IP})++ assert len(result) == 1, "a thousand matches must still be one row"+ assert result[0][0] == 1000, "the aggregate must count every match, not a page of them"+ # Bounded evidence regardless of match count: the distinct sets are+ # capped, so alert evidence cannot grow with the size of the match.+ assert len(result[0][3]) <= 20+ assert len(result[0][4]) <= 20+++def test_the_sweep_is_scoped_even_when_the_indicator_exists_for_another_tenant(seeded_lake: Any) -> None:+ """The isolation half, stated as its own assertion.++ The indicator is present in the table for tenant A. A sweep run as B must+ not see it, and the reason must be the tenant predicate rather than the+ indicator's absence from the warehouse.+ """+ total = seeded_lake.execute(+ "SELECT count() FROM aisoc.raw_events WHERE source_ip = toIPv6(%(v)s)",+ {"v": IOC_IP},+ )[0][0]+ assert total >= 1, "the indicator must be present in the table for this to mean anything"+ assert _sweep(seeded_lake, tenant=TENANT_B, indicator_type="ip", value=IOC_IP) == 0