Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

fix(connectors,threatintel): make seven Okta identity rules reachable, stop reporting a stored batch as zero (#1279, #1278) (#1290)

Beenu Arora67c4f6cbced5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ff0d53cda..8c8c7c8ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -66,6 +66,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **Seven shipped Okta identity rules can fire for the first time** (#1279).
+ Okta carries its result inside an `outcome` *object*, and
+ `OktaConnector.normalize()` read `outcome["result"]` only to pick a
+ severity before discarding it. The detection engine flattens `raw_event`
+ exactly one level, so the matcher saw `outcome` as
+ `{"result": "FAILURE", ...}` and compared a dict to the string
+ `"FAILURE"` — `wd-brute-force-login` and `wd-okta-password-spray` could
+ never match a failed Okta login, and four native identity rules clausing
+ on `SUCCESS` were equally unreachable. That is why a default install
+ reads as having no identity detections rather than unreachable ones.
+ Fixed in the connector, following the Windows `CommandLine`/`Image`
+ precedent: the matcher and both engines are byte-identical, so the blast
+ radius is one connector and is provable by replay. The vendor object is
+ still preserved verbatim under `raw_event`.
+
+- **A threat-intel batch that stored correctly no longer reports zero**
+ (#1278). `ingest_iocs` returned `indexed`, which was the OpenSearch
+ bulk-index count and nothing else. OpenSearch is a `full`-profile store
+ and `threatintel` runs in CORE, so on a stock install the call raises,
+ `indexed` keeps its `0` initialiser, and the Qdrant write on the next
+ line succeeds — printing `indexed: 0` for ~1,700 CISA KEV entries that
+ landed fine. Each sink now reports itself and `None` means "unreachable"
+ rather than "stored nothing". Two false claims in the tree are corrected
+ alongside: `ioc_match.py` asserted CORE's KEV feed fills
+ `threat_intel_iocs` (it has no Postgres leg at all), and
+ `vuln_promotion_sql.py` named a "093 KEV seed worker" that does not
+ exist. `/threat-intel/iocs` and `/feeds` now state which store they read,
+ so an empty response is distinguishable from a broken feed.
- **The autonomy settings page announced an autopilot posture no deployment
has** ([#1243](https://github.com/beenuar/AiSOC/issues/1243)). On a fresh
install, Settings → Autonomy guardrails rendered **"Autopilot · 7 high-blast
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index aaa9c8d41..4b54f5753 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -16066,6 +16066,22 @@ paths:
tags:
- threat-intel
summary: List Iocs
+ description: '**This tenant''s own** IOCs, from Postgres `threat_intel_iocs`.
+
+
+ Not the platform''s feed intelligence, and the distinction is the whole
+
+ content of issue #1278: this route and `/indicators` sit next to each
+
+ other and read different stores. `/indicators` serves the CISA KEV
+
+ catalogue out of Qdrant — about 1,700 entries on a stock CORE install.
+
+ This table is written **only** by `POST /threat-intel/iocs`, so it is
+
+ empty until somebody submits to it, and an empty response here is not
+
+ evidence that the KEV feed failed.'
operationId: list_iocs_api_v1_threat_intel_iocs_get
security:
- HTTPBearer: []
@@ -16285,6 +16301,26 @@ paths:
tags:
- threat-intel
summary: List Feeds
+ description: '**Feeds this tenant has registered**, from Postgres `threat_intel_feeds`.
+
+
+ Written only by `POST /threat-intel/feeds`, so it is empty until an
+
+ operator adds one. It deliberately does **not** list the platform''s
+
+ built-in feeds: the CISA KEV poller is an in-process job in
+
+ `services/threatintel` and owns no row here, which is why a stock CORE
+
+ install sees `[]` here while `/indicators` serves the catalogue that
+
+ poller fetched (issue #1278). Listing the built-in poller here would
+
+ mean synthesising an id and a `tenant_id` for a row that does not
+
+ exist, which is the fabrication pattern this project has paid for
+
+ before; `/indicators` is where its output is observable.'
operationId: list_feeds_api_v1_threat_intel_feeds_get
responses:
'200':
diff --git a/services/api/app/api/v1/endpoints/threat_intel.py b/services/api/app/api/v1/endpoints/threat_intel.py
index 05f299798..93faa81c4 100644
--- a/services/api/app/api/v1/endpoints/threat_intel.py
+++ b/services/api/app/api/v1/endpoints/threat_intel.py
@@ -243,6 +243,16 @@ async def list_iocs(
offset: int = Query(0, ge=0),
db: AsyncSession = Depends(get_db),
) -> list[ThreatIntelIOC]:
+ """**This tenant's own** IOCs, from Postgres `threat_intel_iocs`.
+
+ Not the platform's feed intelligence, and the distinction is the whole
+ content of issue #1278: this route and `/indicators` sit next to each
+ other and read different stores. `/indicators` serves the CISA KEV
+ catalogue out of Qdrant — about 1,700 entries on a stock CORE install.
+ This table is written **only** by `POST /threat-intel/iocs`, so it is
+ empty until somebody submits to it, and an empty response here is not
+ evidence that the KEV feed failed.
+ """
q = select(ThreatIntelIOC).where(ThreatIntelIOC.tenant_id == current_user.tenant_id)
if ioc_type:
q = q.where(ThreatIntelIOC.ioc_type == ioc_type)
@@ -337,6 +347,18 @@ async def list_feeds(
current_user: Annotated[AuthUser, Depends(require_permission("threat_intel:read"))],
db: AsyncSession = Depends(get_db),
) -> list[ThreatIntelFeed]:
+ """**Feeds this tenant has registered**, from Postgres `threat_intel_feeds`.
+
+ Written only by `POST /threat-intel/feeds`, so it is empty until an
+ operator adds one. It deliberately does **not** list the platform's
+ built-in feeds: the CISA KEV poller is an in-process job in
+ `services/threatintel` and owns no row here, which is why a stock CORE
+ install sees `[]` here while `/indicators` serves the catalogue that
+ poller fetched (issue #1278). Listing the built-in poller here would
+ mean synthesising an id and a `tenant_id` for a row that does not
+ exist, which is the fabrication pattern this project has paid for
+ before; `/indicators` is where its output is observable.
+ """
result = await db.execute(
select(ThreatIntelFeed).where(ThreatIntelFeed.tenant_id == current_user.tenant_id).order_by(ThreatIntelFeed.name)
)
diff --git a/services/connectors/app/connectors/okta.py b/services/connectors/app/connectors/okta.py
index 99e35fc0a..182579dca 100644
--- a/services/connectors/app/connectors/okta.py
+++ b/services/connectors/app/connectors/okta.py
@@ -149,6 +149,26 @@ class OktaConnector(BaseConnector):
"actor": actor.get("displayName"),
"actor_email": actor.get("alternateId"),
"event_type": raw.get("eventType"),
+ # Okta carries the result inside an `outcome` *object*. `result`
+ # was read here only to pick a severity and then thrown away,
+ # which made every identity rule that matches on it unreachable
+ # (issue #1279).
+ #
+ # The detection engine flattens `raw_event` one level, so the
+ # matcher saw `outcome` as the dict `{"result": "FAILURE",
+ # "reason": ...}` and compared it to the string `"FAILURE"`.
+ # Seven shipped Okta rules clause on that value — the two
+ # windowed brute-force/password-spray rules on `FAILURE`, four
+ # native identity rules on `SUCCESS` — so none of them could
+ # ever fire, which is why a default install looks as though it
+ # has no identity detections rather than unreachable ones.
+ #
+ # Hoisted here rather than taught to the engine, following the
+ # Windows `CommandLine`/`Image` fix: the matcher and both
+ # engines stay byte-identical, so the blast radius is one
+ # connector and is provable by replay.
+ "outcome": result,
+ "outcome_reason": outcome.get("reason"),
"raw_event": raw,
"created_at": raw.get("published"),
}
diff --git a/services/connectors/app/vuln_promotion_sql.py b/services/connectors/app/vuln_promotion_sql.py
index f286fb766..ffa4a5551 100644
--- a/services/connectors/app/vuln_promotion_sql.py
+++ b/services/connectors/app/vuln_promotion_sql.py
@@ -29,10 +29,16 @@ MARK_OVERDUE_SQL = """
#: aggregates pick the worst-case representation; the per-CVE grouping is
#: why 1 CVE on 4 hosts is one alert instead of four.
#:
-#: KEV join note: ``threat_intel_iocs`` is live-empty on this stack, so
-#: the EXISTS clause contributes nothing today — it is the seam the 093
-#: KEV seed worker feeds when it lands. ``is_exploited`` is the exploited
-#: signal that works right now.
+#: KEV join note: ``threat_intel_iocs`` is empty unless a tenant posts to
+#: it, so the EXISTS clause contributes nothing on a stock install. It is
+#: the seam a tenant's own IOC submissions feed.
+#:
+#: This used to name "the 093 KEV seed worker" as pending. There is no such
+#: worker and migration 093 is `093_role_label_and_repair.sql` — naming a
+#: planned thing as if it were in flight is how a reader concludes the gap
+#: is already owned (issue #1278). CORE's CISA KEV feed writes to Qdrant,
+#: not to this table. ``is_exploited`` is the exploited signal that works
+#: right now.
PROMOTE_CANDIDATES_SQL = """
SELECT v.cve_id,
MAX(v.cvss_score) AS cvss_score,
diff --git a/services/connectors/tests/test_okta_outcome_reaches_detection.py b/services/connectors/tests/test_okta_outcome_reaches_detection.py
new file mode 100644
index 000000000..1575675ec
--- /dev/null
+++ b/services/connectors/tests/test_okta_outcome_reaches_detection.py
@@ -0,0 +1,120 @@
+"""``OktaConnector.normalize()`` emits the result the rules match on.
+
+Issue #1279. Okta carries its result inside an ``outcome`` *object*.
+``normalize()`` read ``outcome["result"]`` to choose a severity and then
+discarded it, so the value never appeared at the top level — and the
+detection engine flattens ``raw_event`` exactly one level, which meant
+the matcher saw the dict and compared it to a string.
+
+Seven shipped Okta rules clause on that value. None could fire on any
+deployment, which is why a default install reads as having no identity
+detections rather than unreachable ones.
+
+This is the connector half of the proof and it drives the real class.
+The engine half lives in
+``services/fusion/tests/test_okta_identity_rules_are_reachable.py``,
+which runs the shipped rules through the real matcher — the two services
+both name their top-level package ``app``, so one interpreter cannot
+import both. The payload asserted here is the payload that file uses.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from app.connectors.okta import OktaConnector
+
+OKTA_FAILED_LOGIN = {
+ "uuid": "f7b1a0de-0000-4000-8000-000000000001",
+ "published": "2026-10-10T09:15:00.000Z",
+ "eventType": "user.session.start",
+ "displayMessage": "User login to Okta",
+ "outcome": {"result": "FAILURE", "reason": "INVALID_CREDENTIALS"},
+ "actor": {"displayName": "Alice Example", "alternateId": "[email protected]"},
+ "client": {"ipAddress": "203.0.113.42"},
+}
+
+
+def _normalize(raw: dict[str, Any]) -> dict[str, Any]:
+ return OktaConnector(domain="example.okta.com", api_token="t").normalize(raw)
+
+
+class TestTheResultIsEmittedWhereTheMatcherLooks:
+ def test_the_outcome_is_a_top_level_scalar(self) -> None:
+ assert _normalize(OKTA_FAILED_LOGIN)["outcome"] == "FAILURE"
+
+ def test_a_successful_login_says_so(self) -> None:
+ """Not a constant. Hoisting `"FAILURE"` unconditionally would pass
+ the test above and alert on every sign-in."""
+ raw = {**OKTA_FAILED_LOGIN, "outcome": {"result": "SUCCESS", "reason": "OK"}}
+ assert _normalize(raw)["outcome"] == "SUCCESS"
+
+ def test_the_reason_travels_too(self) -> None:
+ assert _normalize(OKTA_FAILED_LOGIN)["outcome_reason"] == "INVALID_CREDENTIALS"
+
+ def test_an_event_with_no_outcome_object_defaults_the_same_way_severity_does(self) -> None:
+ """`result` already defaulted to SUCCESS for the severity decision;
+ the hoisted value must not disagree with it."""
+ raw = {k: v for k, v in OKTA_FAILED_LOGIN.items() if k != "outcome"}
+ normalized = _normalize(raw)
+ assert normalized["outcome"] == "SUCCESS"
+ assert normalized["severity"] == "info"
+ assert normalized["outcome_reason"] is None
+
+
+class TestNothingElseChanged:
+ def test_the_vendor_object_is_preserved_verbatim(self) -> None:
+ """An analyst reads `raw_event`, and a future rule may need the
+ nested form. Hoisting a scalar must not cost the original."""
+ assert _normalize(OKTA_FAILED_LOGIN)["raw_event"]["outcome"] == {
+ "result": "FAILURE",
+ "reason": "INVALID_CREDENTIALS",
+ }
+
+ def test_the_envelope_is_still_raw_event_not_raw(self) -> None:
+ """`raw` is the known bug class: it misses the ingest normalizer's
+ canonical-envelope check and the event falls through to the generic
+ profile."""
+ normalized = _normalize(OKTA_FAILED_LOGIN)
+ assert "raw_event" in normalized
+ assert "raw" not in normalized
+
+ def test_severity_is_unchanged_for_both_outcomes(self) -> None:
+ assert _normalize(OKTA_FAILED_LOGIN)["severity"] == "medium"
+ raw = {**OKTA_FAILED_LOGIN, "outcome": {"result": "SUCCESS"}}
+ assert _normalize(raw)["severity"] == "info"
+
+ @pytest.mark.parametrize(
+ ("key", "expected"),
+ [
+ ("source", "okta"),
+ ("event_type", "user.session.start"),
+ ("actor_email", "[email protected]"),
+ ("src_ip", "203.0.113.42"),
+ ("external_id", "f7b1a0de-0000-4000-8000-000000000001"),
+ ],
+ )
+ def test_the_existing_fields_still_carry_what_they_did(self, key: str, expected: str) -> None:
+ assert _normalize(OKTA_FAILED_LOGIN)[key] == expected
+
+ def test_the_payload_matches_what_the_fusion_test_replays(self) -> None:
+ """The two halves of this proof live in different interpreters, so
+ this is the seam. If `normalize()` changes shape, this reds here
+ rather than letting the fusion test replay a payload the connector
+ no longer produces."""
+ assert _normalize(OKTA_FAILED_LOGIN) == {
+ "source": "okta",
+ "external_id": "f7b1a0de-0000-4000-8000-000000000001",
+ "title": "User login to Okta",
+ "description": "user.session.start - INVALID_CREDENTIALS",
+ "severity": "medium",
+ "src_ip": "203.0.113.42",
+ "actor": "Alice Example",
+ "actor_email": "[email protected]",
+ "event_type": "user.session.start",
+ "outcome": "FAILURE",
+ "outcome_reason": "INVALID_CREDENTIALS",
+ "raw_event": OKTA_FAILED_LOGIN,
+ "created_at": "2026-10-10T09:15:00.000Z",
+ }
diff --git a/services/fusion/app/services/ioc_match.py b/services/fusion/app/services/ioc_match.py
index f56020a71..67e6f9ce2 100644
--- a/services/fusion/app/services/ioc_match.py
+++ b/services/fusion/app/services/ioc_match.py
@@ -13,9 +13,17 @@ indicator on every alert, which is the first thing the capability review
found: the default install gives the agent almost nothing to reason with.
The tenant's own IOC store is different. `threat_intel_iocs` lives in the
-same Postgres every CORE service already connects to, and CORE ships a real
-CISA KEV feed, so there is genuinely something to match against on a first
-run. Reading it directly needs no extra service.
+same Postgres every CORE service already connects to, so reading it
+directly needs no extra service.
+
+It is, however, **empty unless a tenant posts to it**. This paragraph used
+to claim CORE's CISA KEV feed fills it, and that was never true (issue
+#1278): the feed writes to OpenSearch, Qdrant and Neo4j and has no
+Postgres leg at all, which is why `/threat-intel/indicators` serves 1,739
+KEV entries from Qdrant while `/threat-intel/iocs` returns `[]` on the
+same stack. The only writer of this table is `POST /threat-intel/iocs`.
+So a first run matches nothing here, and that is an accurate empty rather
+than a broken feed.
Expiry and decay
----------------
diff --git a/services/fusion/tests/test_okta_identity_rules_are_reachable.py b/services/fusion/tests/test_okta_identity_rules_are_reachable.py
new file mode 100644
index 000000000..3e9dc8a2a
--- /dev/null
+++ b/services/fusion/tests/test_okta_identity_rules_are_reachable.py
@@ -0,0 +1,179 @@
+"""Okta identity rules can see the field they match on (issue #1279).
+
+The report was "identity events are invisible in the core profile": an
+Okta ``user.session.start`` FAILURE is accepted and produces no alert.
+Half of that is the promoter working as designed — an authentication
+event normalised to OCSF category 3 at medium severity is archived and
+not promoted, and nobody wants an alert per login.
+
+The other half is a reachability bug one layer below the engine, and it
+is the same shape as the Windows ``CommandLine``/``Image`` fix. Okta
+carries its result inside an ``outcome`` *object*. ``normalize()`` read
+``outcome["result"]`` only to choose a severity and discarded it, and the
+engine flattens ``raw_event`` exactly one level — so the matcher saw
+``outcome`` as ``{"result": "FAILURE", ...}`` and compared a dict against
+the string ``"FAILURE"``.
+
+Seven shipped Okta rules clause on that value. None of them could fire on
+any deployment, which is why a stock install reads as having no identity
+detections rather than unreachable ones.
+
+This test drives the **real** engine field resolution, the **real**
+matcher and the **real** shipped rulesets. It cannot also drive the real
+connector: ``services/connectors`` and ``services/fusion`` both name
+their top-level package ``app``, so importing one inside the other's
+interpreter shadows it. The connector half is pinned separately by
+``services/connectors/tests/test_okta_outcome_reaches_detection.py``,
+which drives ``OktaConnector.normalize()`` itself and asserts exactly the
+payload below — so a connector change that drops the field again reds
+that test rather than silently passing this one.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from app.services.detection_engine import DetectionEngine, _load_ruleset
+from app.services.detection_matcher import matches
+from app.services.windowed_detection import load_window_rules
+
+#: A real Okta System Log row, trimmed. Shape taken from the vendor's
+#: documented payload, not from what the rules want.
+OKTA_FAILED_LOGIN = {
+ "uuid": "f7b1a0de-0000-4000-8000-000000000001",
+ "published": "2026-10-10T09:15:00.000Z",
+ "eventType": "user.session.start",
+ "displayMessage": "User login to Okta",
+ "outcome": {"result": "FAILURE", "reason": "INVALID_CREDENTIALS"},
+ "actor": {"displayName": "Alice Example", "alternateId": "[email protected]"},
+ "client": {"ipAddress": "203.0.113.42"},
+}
+
+OKTA_SUCCESSFUL_LOGIN = {
+ **OKTA_FAILED_LOGIN,
+ "outcome": {"result": "SUCCESS", "reason": "OK"},
+}
+
+
+def _normalised(raw: dict[str, Any]) -> dict[str, Any]:
+ """What ``OktaConnector.normalize()`` emits for ``raw``.
+
+ A transcription, not a reimplementation — the connector's own test
+ asserts this exact mapping against the real class. The alternative was
+ to invent an event in the shape the engine wants, which is how a
+ reachability bug stays invisible: the fixture would pass while the
+ product does not.
+ """
+ outcome = raw.get("outcome", {})
+ result = outcome.get("result", "SUCCESS")
+ actor = raw.get("actor", {})
+ return {
+ "source": "okta",
+ "external_id": raw.get("uuid", ""),
+ "title": raw.get("displayMessage", "Okta Event"),
+ "description": f"{raw.get('eventType')} - {outcome.get('reason', result)}",
+ "severity": "medium" if result in ("FAILURE", "DENY") else "info",
+ "src_ip": raw.get("client", {}).get("ipAddress"),
+ "actor": actor.get("displayName"),
+ "actor_email": actor.get("alternateId"),
+ "event_type": raw.get("eventType"),
+ "outcome": result,
+ "outcome_reason": outcome.get("reason"),
+ "raw_event": raw,
+ "created_at": raw.get("published"),
+ }
+
+
+def _match_namespace(raw: dict[str, Any]) -> dict[str, Any]:
+ """What the engine really gives the matcher for that event."""
+ return DetectionEngine._raw_fields({"raw_data": json.dumps(_normalised(raw))})
+
+
+def _window_rule(rule_id: str) -> Any:
+ for rule in load_window_rules():
+ if rule.id == rule_id:
+ return rule
+ raise AssertionError(f"{rule_id} is not in the shipped windowed ruleset")
+
+
+def _stateless_rule(rule_id: str) -> dict[str, Any]:
+ for rule in _load_ruleset():
+ if rule["id"] == rule_id:
+ return rule
+ raise AssertionError(f"{rule_id} is not in the shipped ruleset")
+
+
+class TestTheFieldReachesTheMatcher:
+ def test_outcome_is_a_comparable_value_not_the_vendor_object(self) -> None:
+ """The defect in one assertion. `_check` does `event.get(field)` and
+ compares — a dict never equals a string."""
+ resolved = _match_namespace(OKTA_FAILED_LOGIN)["outcome"]
+ assert resolved == "FAILURE"
+ assert not isinstance(resolved, dict)
+
+ def test_the_reason_survives_too(self) -> None:
+ assert _match_namespace(OKTA_FAILED_LOGIN)["outcome_reason"] == "INVALID_CREDENTIALS"
+
+ def test_the_vendor_object_is_still_preserved_verbatim(self) -> None:
+ """Hoisting a scalar must not cost the original payload — the raw
+ event is what an analyst reads and what a future rule may need."""
+ assert _normalised(OKTA_FAILED_LOGIN)["raw_event"]["outcome"] == {
+ "result": "FAILURE",
+ "reason": "INVALID_CREDENTIALS",
+ }
+
+ def test_the_grouping_keys_the_windowed_rules_need_are_populated(self) -> None:
+ """A rule that matches but cannot group is still inert."""
+ ns = _match_namespace(OKTA_FAILED_LOGIN)
+ assert ns["actor_email"] == "[email protected]"
+ assert ns["src_ip"] == "203.0.113.42"
+
+
+class TestTheShippedRulesNowFire:
+ """Every one of these is a rule the product ships and that could not
+ fire on any deployment."""
+
+ def test_the_brute_force_rule_matches_a_failed_login(self) -> None:
+ rule = _window_rule("wd-brute-force-login")
+ assert matches(rule.match_when, _match_namespace(OKTA_FAILED_LOGIN))
+
+ def test_the_password_spray_rule_matches_a_failed_login(self) -> None:
+ rule = _window_rule("wd-okta-password-spray")
+ assert matches(rule.match_when, _match_namespace(OKTA_FAILED_LOGIN))
+
+ def test_a_successful_login_does_not_match_the_failure_rules(self) -> None:
+ """The negative control that matters most. Hoisting a constant
+ string would satisfy every assertion above and alert on every
+ sign-in — which is exactly the behaviour the promoter policy exists
+ to avoid."""
+ namespace = _match_namespace(OKTA_SUCCESSFUL_LOGIN)
+ assert namespace["outcome"] == "SUCCESS"
+ for rule_id in ("wd-brute-force-login", "wd-okta-password-spray"):
+ assert not matches(_window_rule(rule_id).match_when, namespace)
+
+ def test_the_success_gated_identity_rules_can_now_see_their_clause(self) -> None:
+ """Four native rules clause on `outcome: SUCCESS` and were equally
+ unreachable. They carry further clauses this one event does not
+ satisfy, so the assertion is on the clause that was broken."""
+ namespace = _match_namespace(OKTA_SUCCESSFUL_LOGIN)
+ for rule_id in ("det-identity-002", "det-identity-005", "det-identity-006", "det-identity-015"):
+ clause = _stateless_rule(rule_id)["match_when"]
+ assert clause.get("outcome") == "SUCCESS"
+ assert matches({"outcome": clause["outcome"]}, namespace), rule_id
+
+
+class TestTheEngineIsUnchanged:
+ def test_only_the_intended_field_is_newly_displaced(self) -> None:
+ """`_raw_fields` lets connector keys win over nested ones, so a new
+ top-level key shadows its nested namesake in the match namespace.
+ Two keys are shadowed here and only one of them is new: `actor` was
+ already a display-name string over Okta's actor *object*, which
+ this change does not touch."""
+ normalised = _normalised(OKTA_FAILED_LOGIN)
+ nested = normalised["raw_event"]
+ shadowed = {k for k in normalised if k in nested and normalised[k] != nested[k]}
+ assert shadowed == {"actor", "outcome"}
+
+ pre_existing = {k: v for k, v in normalised.items() if k not in ("outcome", "outcome_reason")}
+ assert {k for k in pre_existing if k in nested and pre_existing[k] != nested[k]} == {"actor"}
diff --git a/services/threatintel/app/feeds/pipeline.py b/services/threatintel/app/feeds/pipeline.py
index 128aa350b..f54fa2020 100644
--- a/services/threatintel/app/feeds/pipeline.py
+++ b/services/threatintel/app/feeds/pipeline.py
@@ -54,11 +54,14 @@ class ThreatIntelPipeline:
self,
iocs: list[dict[str, Any]],
source: str,
- ) -> dict[str, int]:
+ ) -> dict[str, Any]:
"""
Ingest a batch of normalized IOCs.
- Returns a stats dict with counts for new, duplicate, and indexed items.
+ Returns counts for ``total`` / ``new`` / ``duplicate`` / ``indexed``,
+ plus a ``sinks`` map naming what each store took. A sink reports
+ ``None`` when it could not be reached, which is a different fact
+ from storing nothing — see the comment at the write site.
"""
if not iocs:
return {"total": 0, "new": 0, "duplicate": 0}
@@ -94,22 +97,49 @@ class ThreatIntelPipeline:
# exception from it aborted the batch before Qdrant — the CORE store,
# and the one the console reads through — was written at all. A feed
# that can reach one of its sinks should write to that one.
- indexed = 0
+ # `indexed` was the OpenSearch return value and nothing else, so on
+ # CORE — where OpenSearch is not in the profile — a batch of 1,739
+ # KEV entries that landed correctly in Qdrant reported `indexed: 0`
+ # (issue #1278). A zero beside a successful write is the shape this
+ # project treats as worse than a missing number: it reads as a
+ # measurement, and it is the number an operator checks to decide
+ # whether the feed works.
+ #
+ # Each sink now reports itself, and `None` means "this store was not
+ # reachable" rather than "it stored nothing".
+ sinks: dict[str, int | None] = {}
+
try:
- indexed = await self._os.bulk_index_iocs(new_iocs)
+ sinks["opensearch"] = await self._os.bulk_index_iocs(new_iocs)
except Exception as exc:
+ sinks["opensearch"] = None
logger.warning("OpenSearch IOC index failed", error=str(exc))
try:
await self._qdrant.upsert_iocs(new_iocs)
+ sinks["qdrant"] = len(new_iocs)
except Exception as exc:
+ sinks["qdrant"] = None
logger.warning("Qdrant IOC upsert failed", error=str(exc))
try:
await self._neo4j.upsert_iocs(new_iocs)
+ sinks["neo4j"] = len(new_iocs)
except Exception as exc:
+ sinks["neo4j"] = None
logger.warning("Neo4j IOC upsert failed", error=str(exc))
+ stored = max((count for count in sinks.values() if count is not None), default=0)
+ unavailable = sorted(name for name, count in sinks.items() if count is None)
+ logger.info(
+ "IOC batch stored",
+ source=source,
+ new=len(new_iocs),
+ stored=stored,
+ sinks=dict(sinks),
+ unavailable=unavailable or None,
+ )
+
# --- Emit Kafka events ---
if self._kafka:
await self._emit_kafka_events(new_iocs, event_type="NEW_IOC", source=source)
@@ -118,7 +148,11 @@ class ThreatIntelPipeline:
"total": len(iocs),
"new": len(new_iocs),
"duplicate": duplicates,
- "indexed": indexed,
+ # Kept, but it now means "stored in at least one sink" rather
+ # than "stored in OpenSearch". `sinks` carries the detail, and a
+ # `None` there is an unreachable store, not an empty one.
+ "indexed": stored,
+ "sinks": sinks,
}
async def ingest_actors(
diff --git a/services/threatintel/tests/test_pipeline_sink_reporting.py b/services/threatintel/tests/test_pipeline_sink_reporting.py
new file mode 100644
index 000000000..da3b6452b
--- /dev/null
+++ b/services/threatintel/tests/test_pipeline_sink_reporting.py
@@ -0,0 +1,120 @@
+"""A batch that landed somewhere does not report zero (issue #1278).
+
+`ingest_iocs` returned `indexed`, which was the OpenSearch bulk-index
+count and nothing else. OpenSearch is a `full`-profile store and
+`threatintel` now runs in CORE, so on a stock install the call raises,
+`indexed` keeps its `0` initialiser, and the Qdrant write on the very next
+line succeeds — producing `indexed: 0` in the logs for a batch of ~1,700
+CISA KEV entries that stored correctly.
+
+That is the number an operator checks to decide whether the feed works,
+and a zero beside a successful write reads as a measurement rather than
+as a missing one. It was the single most misleading signal in the report:
+`/threat-intel/feeds` and `/iocs` returning `[]` is correct behaviour for
+two tenant-owned stores nobody has written to, but `indexed: 0` beside
+them made the whole thing look like a broken feed.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from app.feeds.pipeline import ThreatIntelPipeline
+
+IOCS = [{"type": "vulnerability", "value": f"CVE-2026-{n:04d}"} for n in range(3)]
+
+
+class _Bloom:
+ def __init__(self) -> None:
+ self._seen: set[str] = set()
+
+ async def contains(self, key: str) -> bool:
+ return key in self._seen
+
+ async def add(self, key: str) -> None:
+ self._seen.add(key)
+
+
+class _Sink:
+ """A store that either works or is absent. `absent` raises the way an
+ unreachable host does, which is the condition CORE is actually in."""
+
+ def __init__(self, *, absent: bool = False) -> None:
+ self.absent = absent
+
+ async def bulk_index_iocs(self, iocs: list[dict[str, Any]]) -> int:
+ if self.absent:
+ raise ConnectionError("opensearch: name or service not known")
+ return len(iocs)
+
+ async def upsert_iocs(self, iocs: list[dict[str, Any]], **_kw: Any) -> None:
+ if self.absent:
+ raise ConnectionError("store unreachable")
+
+
+def _pipeline(*, opensearch: bool, qdrant: bool, neo4j: bool) -> ThreatIntelPipeline:
+ # The stores are substituted by duck type rather than by subclass: the
+ # real ones each own a live client, and the property under test is which
+ # store answered, not what any of them does internally.
+ return ThreatIntelPipeline(
+ bloom=_Bloom(), # type: ignore[arg-type]
+ os_store=_Sink(absent=not opensearch), # type: ignore[arg-type]
+ qdrant_store=_Sink(absent=not qdrant), # type: ignore[arg-type]
+ neo4j_store=_Sink(absent=not neo4j), # type: ignore[arg-type]
+ kafka_producer=None,
+ kafka_topic="t",
+ )
+
+
+class TestTheCoreProfileReportsWhatItStored:
+ @pytest.mark.asyncio
+ async def test_a_core_install_does_not_report_zero_for_a_stored_batch(self) -> None:
+ """CORE exactly: OpenSearch and Neo4j are `full`-profile and absent,
+ Qdrant is present and is what `/indicators` reads."""
+ stats = await _pipeline(opensearch=False, qdrant=True, neo4j=False).ingest_iocs(IOCS, source="cisa-kev")
+
+ assert stats["new"] == 3
+ assert stats["indexed"] == 3, "a batch that landed in the CORE store reported zero"
+
+ @pytest.mark.asyncio
+ async def test_an_unreachable_store_is_none_not_zero(self) -> None:
+ """The distinction the whole issue turns on: `0` is a count, `None`
+ is 'nobody counted'."""
+ stats = await _pipeline(opensearch=False, qdrant=True, neo4j=False).ingest_iocs(IOCS, source="cisa-kev")
+
+ assert stats["sinks"]["opensearch"] is None
+ assert stats["sinks"]["neo4j"] is None
+ assert stats["sinks"]["qdrant"] == 3
+
+ @pytest.mark.asyncio
+ async def test_a_batch_that_landed_nowhere_really_does_report_zero(self) -> None:
+ """The control. The fix must not make every batch look successful."""
+ stats = await _pipeline(opensearch=False, qdrant=False, neo4j=False).ingest_iocs(IOCS, source="cisa-kev")
+
+ assert stats["indexed"] == 0
+ assert set(stats["sinks"].values()) == {None}
+
+ @pytest.mark.asyncio
+ async def test_the_full_profile_still_reports_every_sink(self) -> None:
+ stats = await _pipeline(opensearch=True, qdrant=True, neo4j=True).ingest_iocs(IOCS, source="cisa-kev")
+
+ assert stats["indexed"] == 3
+ assert stats["sinks"] == {"opensearch": 3, "qdrant": 3, "neo4j": 3}
+
+ @pytest.mark.asyncio
+ async def test_duplicates_are_still_counted_and_not_restored(self) -> None:
+ """The dedup half is untouched; a second pass stores nothing because
+ there is nothing new, which is a real zero."""
+ pipeline = _pipeline(opensearch=False, qdrant=True, neo4j=False)
+ await pipeline.ingest_iocs(IOCS, source="cisa-kev")
+ second = await pipeline.ingest_iocs(IOCS, source="cisa-kev")
+
+ assert second["new"] == 0
+ assert second["duplicate"] == 3
+ assert "indexed" not in second or second.get("indexed", 0) == 0
+
+ @pytest.mark.asyncio
+ async def test_an_empty_batch_is_not_an_error(self) -> None:
+ stats = await _pipeline(opensearch=True, qdrant=True, neo4j=True).ingest_iocs([], source="cisa-kev")
+ assert stats["total"] == 0