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(splunk): saved-search dispatch, normalize-once, checkpointed pagination (#525 #528 #529) (#532)

Beenu Arora06a8ce58846c
diff --git a/docs/connectors/conformance-matrix.md b/docs/connectors/conformance-matrix.md
index 2d93cdf75..4ac43864e 100644
--- a/docs/connectors/conformance-matrix.md
+++ b/docs/connectors/conformance-matrix.md
@@ -71,7 +71,7 @@
| slack_audit | saas | 1 | 1 | 3 | ✅ | ✅ | ✅ |
| snowflake | saas | 5 | 1 | 4 | ✅ | ✅ | ✅ |
| snyk | vcs | 3 | 1 | 1 | ✅ | ✅ | ✅ |
-| splunk | siem | 4 | 1 | 4 | ✅ | ✅ | ✅ |
+| splunk | siem | 5 | 1 | 4 | ✅ | ✅ | ✅ |
| sublime_security | saas | 2 | 1 | 3 | ✅ | ✅ | ✅ |
| sumo_logic | siem | 3 | 1 | 4 | ✅ | ✅ | ✅ |
| sysdig | siem | 2 | 1 | 4 | ✅ | ✅ | ✅ |
diff --git a/services/connectors/app/connectors/splunk.py b/services/connectors/app/connectors/splunk.py
index 23e49a4c0..cbc5bf070 100644
--- a/services/connectors/app/connectors/splunk.py
+++ b/services/connectors/app/connectors/splunk.py
@@ -5,7 +5,10 @@ Runs saved searches and fetches notable events from Splunk SIEM.
from __future__ import annotations
+import asyncio
+import re
from typing import Any
+from urllib.parse import quote
import httpx
import structlog
@@ -16,6 +19,23 @@ from app.federated.translators import to_spl
logger = structlog.get_logger()
+# Page size for the results endpoint. ``head 100`` / ``count=100`` used to cap a
+# poll at 100 notables and silently drop the rest (#529); we now page through
+# every result. _MAX_PAGES bounds a single poll so a misconfigured saved search
+# can't spin forever.
+_DEFAULT_PAGE_SIZE = 500
+_MAX_PAGES = 200
+_JOB_POLL_ATTEMPTS = 30
+_JOB_POLL_INTERVAL_S = 2.0
+_SEVERITY_BY_URGENCY = {
+ "critical": "critical",
+ "high": "high",
+ "medium": "medium",
+ "low": "low",
+ "informational": "info",
+ "info": "info",
+}
+
class SplunkConnector(BaseConnector):
connector_id = "splunk"
@@ -46,6 +66,15 @@ class SplunkConnector(BaseConnector):
"Saved Search Name",
required=False,
default="AiSOC_Alerts",
+ help_text="Dispatched via the saved-search endpoint. Leave blank to search index=notable.",
+ ),
+ Field(
+ "page_size",
+ "number",
+ "Results page size",
+ required=False,
+ default=_DEFAULT_PAGE_SIZE,
+ help_text="Number of results fetched per page. Polling pages through all results — there is no 100-event cap.",
),
Field(
"ssl_verify",
@@ -77,11 +106,37 @@ class SplunkConnector(BaseConnector):
token: str,
saved_search: str = "AiSOC_Alerts",
ssl_verify: bool = True,
+ page_size: int = _DEFAULT_PAGE_SIZE,
):
self._base_url = base_url.rstrip("/")
self._token = token
self._saved_search = saved_search
self._ssl_verify = ssl_verify
+ try:
+ self._page_size = max(1, int(page_size))
+ except (TypeError, ValueError):
+ self._page_size = _DEFAULT_PAGE_SIZE
+ # Checkpoint plumbing (#529). ``_checkpoint`` is the last-accepted
+ # (event_time, tie-breaker id) fed in by the scheduler before a poll;
+ # ``_next_checkpoint`` is the advanced value the scheduler persists
+ # *after* ingest accepts the batch. Both are ``{"time","id"}`` dicts.
+ self._checkpoint: dict[str, str] | None = None
+ self._next_checkpoint: dict[str, str] | None = None
+
+ def set_checkpoint(self, checkpoint: dict[str, Any] | None) -> None:
+ """Seed the poll with the last-accepted checkpoint (scheduler-owned)."""
+ if isinstance(checkpoint, dict) and (checkpoint.get("time") or checkpoint.get("id")):
+ self._checkpoint = {"time": str(checkpoint.get("time") or ""), "id": str(checkpoint.get("id") or "")}
+ else:
+ self._checkpoint = None
+
+ def get_checkpoint(self) -> dict[str, str] | None:
+ """Return the advanced checkpoint after a fetch, or None if unchanged.
+
+ The scheduler persists this only once ingest has accepted the batch, so
+ a failed ingest never advances the checkpoint (#529).
+ """
+ return self._next_checkpoint
def _headers(self) -> dict[str, str]:
return {
@@ -105,45 +160,122 @@ class SplunkConnector(BaseConnector):
return {"success": False, "connector": self.connector_id, "error": "Connection failed"}
async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
- search_query = f"search index=notable earliest=-{since_seconds}s | head 100"
-
+ earliest = f"-{max(1, int(since_seconds))}s"
async with httpx.AsyncClient(timeout=60.0, verify=self._ssl_verify) as client:
- # Create search job
+ sid = await self._dispatch(client, earliest)
+ if not sid:
+ return []
+ await self._await_job(client, sid)
+ rows = await self._collect_results(client, sid)
+
+ ordered = self._order_and_checkpoint(rows)
+ return [self.normalize(r) for r in ordered]
+
+ async def _dispatch(self, client: httpx.AsyncClient, earliest: str) -> str | None:
+ """Kick off the search job and return its SID.
+
+ Honors the configured saved search (#525): when ``saved_search`` names
+ a real saved search we dispatch it via the dedicated endpoint with a
+ URL-encoded name (never injecting the untrusted name into SPL) and
+ override its time window. When it is empty or an ``index=`` expression
+ we fall back to the original ad-hoc notable-index search.
+ """
+ ss = (self._saved_search or "").strip()
+ if ss and not ss.startswith("index="):
resp = await client.post(
- f"{self._base_url}/services/search/jobs",
+ f"{self._base_url}/services/saved/searches/{quote(ss, safe='')}/dispatch",
headers=self._headers(),
- data={"search": search_query, "output_mode": "json"},
+ data={
+ "output_mode": "json",
+ "dispatch.earliest_time": earliest,
+ "dispatch.latest_time": "now",
+ "trigger_actions": "0",
+ },
)
resp.raise_for_status()
- sid = resp.json().get("sid")
+ return self._extract_sid(resp)
- if not sid:
- return []
+ index = ss[len("index=") :] if ss.startswith("index=") else "notable"
+ resp = await client.post(
+ f"{self._base_url}/services/search/jobs",
+ headers=self._headers(),
+ data={"search": f"search index={index} earliest={earliest}", "output_mode": "json"},
+ )
+ resp.raise_for_status()
+ return self._extract_sid(resp)
- # Wait for completion (simple polling)
- import asyncio
+ @staticmethod
+ def _extract_sid(resp: httpx.Response) -> str | None:
+ try:
+ data = resp.json()
+ if isinstance(data, dict) and data.get("sid"):
+ return str(data["sid"])
+ except (ValueError, KeyError):
+ pass
+ # The dispatch endpoint may answer with XML (<sid>…</sid>) despite
+ # output_mode=json depending on Splunk version.
+ match = re.search(r"<sid>([^<]+)</sid>", resp.text)
+ return match.group(1) if match else None
- for _ in range(10):
- status_resp = await client.get(
- f"{self._base_url}/services/search/jobs/{sid}",
- headers=self._headers(),
- params={"output_mode": "json"},
- )
- dispatch_state = status_resp.json().get("entry", [{}])[0].get("content", {}).get("dispatchState", "")
- if dispatch_state == "DONE":
- break
- await asyncio.sleep(2)
+ async def _await_job(self, client: httpx.AsyncClient, sid: str) -> str:
+ for _ in range(_JOB_POLL_ATTEMPTS):
+ resp = await client.get(
+ f"{self._base_url}/services/search/jobs/{sid}",
+ headers=self._headers(),
+ params={"output_mode": "json"},
+ )
+ state = resp.json().get("entry", [{}])[0].get("content", {}).get("dispatchState", "")
+ if state in ("DONE", "FAILED", "PAUSED"):
+ return state
+ await asyncio.sleep(_JOB_POLL_INTERVAL_S)
+ return "TIMED_OUT"
- # Fetch results
- results_resp = await client.get(
+ async def _collect_results(self, client: httpx.AsyncClient, sid: str) -> list[dict[str, Any]]:
+ """Page through every result (#529) — no more silent ``head 100`` cap."""
+ rows: list[dict[str, Any]] = []
+ offset = 0
+ for _ in range(_MAX_PAGES):
+ resp = await client.get(
f"{self._base_url}/services/search/jobs/{sid}/results",
headers=self._headers(),
- params={"output_mode": "json", "count": 100},
+ params={"output_mode": "json", "count": self._page_size, "offset": offset},
)
- results_resp.raise_for_status()
- results = results_resp.json().get("results", [])
+ resp.raise_for_status()
+ page = resp.json().get("results", [])
+ if not page:
+ break
+ rows.extend(page)
+ if len(page) < self._page_size:
+ break
+ offset += len(page)
+ return rows
- return [self.normalize(r) for r in results]
+ @staticmethod
+ def _event_time(row: dict[str, Any]) -> str:
+ return str(row.get("_time") or row.get("event_time") or "")
+
+ @staticmethod
+ def _event_tiebreak(row: dict[str, Any]) -> str:
+ return str(row.get("event_id") or row.get("_cd") or "")
+
+ def _order_and_checkpoint(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Sort by a stable (event_time, tie-breaker) tuple, drop anything at or
+ before the incoming checkpoint (suppresses overlapping-window
+ duplicates), and stage the advanced checkpoint for the scheduler."""
+ ordered = sorted(rows, key=lambda r: (self._event_time(r), self._event_tiebreak(r)))
+ cp = self._checkpoint or {}
+ cp_key = (str(cp.get("time") or ""), str(cp.get("id") or ""))
+ fresh: list[dict[str, Any]] = []
+ for row in ordered:
+ if cp_key[0] and (self._event_time(row), self._event_tiebreak(row)) <= cp_key:
+ continue
+ fresh.append(row)
+ if fresh:
+ last = fresh[-1]
+ self._next_checkpoint = {"time": self._event_time(last), "id": self._event_tiebreak(last)}
+ else:
+ self._next_checkpoint = None
+ return fresh
async def query(self, unified: UnifiedQuery) -> list[dict[str, Any]]:
"""Run a translated SPL search and return raw rows.
@@ -165,13 +297,27 @@ class SplunkConnector(BaseConnector):
return list(resp.json().get("results", []))
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
- urgency_map = {"critical": "critical", "high": "high", "medium": "medium", "low": "low", "informational": "info"}
+ # Idempotency guard (#528): ``fetch_alerts`` already returns canonical
+ # events, and the scheduler historically re-ran ``normalize`` on every
+ # event. Re-normalizing a canonical envelope treated it as a raw Splunk
+ # row (external_id -> "", title -> "splunk", severity -> medium,
+ # nested raw_event). Detect the envelope and pass it straight through.
+ if isinstance(raw, dict) and "raw_event" in raw and raw.get("source") == self.connector_id:
+ return raw
+
+ # Prefer a stable vendor identifier so replays map to the same canonical
+ # event ID downstream (#529). Emit it under both keys the ingest
+ # normalizer understands.
+ external_id = str(raw.get("event_id") or raw.get("_cd") or "")
return {
"source": self.connector_id,
- "external_id": raw.get("event_id", raw.get("_cd", "")),
- "title": raw.get("source", "Splunk Notable Event"),
+ "external_id": external_id,
+ "event_id": external_id,
+ # The correlation-search name is the notable's rule title; fall back
+ # to source, then a generic label.
+ "title": raw.get("search_name") or raw.get("source") or "Splunk Notable Event",
"description": raw.get("description", ""),
- "severity": urgency_map.get(raw.get("urgency", "medium"), "medium"),
+ "severity": _SEVERITY_BY_URGENCY.get(str(raw.get("urgency", "medium")).lower(), "medium"),
"src_ip": raw.get("src", raw.get("src_ip")),
"hostname": raw.get("host"),
"raw_event": raw,
diff --git a/services/connectors/app/db/connector_repo.py b/services/connectors/app/db/connector_repo.py
index c288512a9..3c6a5ef58 100644
--- a/services/connectors/app/db/connector_repo.py
+++ b/services/connectors/app/db/connector_repo.py
@@ -15,6 +15,7 @@ worst possible failure mode.
from __future__ import annotations
+import json
import uuid
from dataclasses import dataclass
from datetime import UTC, datetime
@@ -30,6 +31,7 @@ from sqlalchemy import (
String,
Table,
Text,
+ cast,
func,
select,
update,
@@ -244,6 +246,26 @@ async def record_poll_failure(
await connection.execute(stmt)
+async def record_checkpoint(
+ connection: Any,
+ connector_id: uuid.UUID,
+ checkpoint: dict[str, Any],
+) -> None:
+ """Persist a connector's ingest checkpoint under ``connector_config.checkpoint``.
+
+ Used by connectors that resume from a per-source cursor (e.g. Splunk, #529).
+ Merged into the existing JSONB with the ``||`` operator so the rest of the
+ config is preserved. Written only after ingest accepts the batch, so a
+ crash mid-poll leaves the previous checkpoint intact and the next poll
+ re-scans a bounded overlap rather than skipping events.
+ """
+ now = datetime.now(UTC)
+ patch = cast(json.dumps({"checkpoint": checkpoint}), JSONB)
+ merged = func.coalesce(connectors_table.c.connector_config, cast("{}", JSONB)).op("||")(patch)
+ stmt = update(connectors_table).where(connectors_table.c.id == connector_id).values(connector_config=merged, updated_at=now)
+ await connection.execute(stmt)
+
+
async def record_backfill_run(
connection: Any,
connector_id: uuid.UUID,
diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.py
index 20d00b7f9..e1511c7c4 100644
--- a/services/connectors/app/scheduler.py
+++ b/services/connectors/app/scheduler.py
@@ -63,6 +63,7 @@ from app.db.connector_repo import (
ConnectorInstance,
fetch_enabled_connectors,
record_backfill_run,
+ record_checkpoint,
record_poll_failure,
record_poll_success,
record_schema_drift,
@@ -424,8 +425,8 @@ class ConnectorScheduler:
# Filter out the scheduler-only knobs from connector_config before
# passing to the constructor — connectors don't accept
- # ``poll_interval_seconds`` as a kwarg.
- runtime_config = {k: v for k, v in (target.connector_config or {}).items() if k not in {"poll_interval_seconds"}}
+ # ``poll_interval_seconds`` (or the ingest ``checkpoint``) as a kwarg.
+ runtime_config = {k: v for k, v in (target.connector_config or {}).items() if k not in {"poll_interval_seconds", "checkpoint"}}
kwargs = {**auth, **runtime_config}
started = datetime.now(UTC)
@@ -441,6 +442,15 @@ class ConnectorScheduler:
await self._record_failure(target.id)
return
+ # Seed the connector's ingest checkpoint (#529) if it supports one, so a
+ # restart resumes from the last-accepted event instead of re-scanning.
+ setter = getattr(connector, "set_checkpoint", None)
+ if callable(setter):
+ try:
+ setter((target.connector_config or {}).get("checkpoint"))
+ except Exception: # never let checkpoint seeding break a poll
+ logger.debug("connector.scheduler.checkpoint_seed_failed id=%s", connector_id)
+
# The schema lives in connector_config; use it for fetch lookback.
# We deliberately default to the same poll interval, so a 5-min
# poll fetches the last 5 min of events. This keeps the source
@@ -560,6 +570,18 @@ class ConnectorScheduler:
accepted = int(result.get("accepted", 0) or 0)
elapsed_ms = int((datetime.now(UTC) - started).total_seconds() * 1000)
+ # Advance the persisted checkpoint only now that ingest has accepted the
+ # batch (#529). A failed push returned earlier, so reaching here means
+ # the page was accepted — this is the "advance only after accept" rule.
+ getter = getattr(connector, "get_checkpoint", None)
+ if callable(getter):
+ try:
+ new_checkpoint = getter()
+ except Exception: # never let checkpoint bookkeeping break a poll
+ new_checkpoint = None
+ if isinstance(new_checkpoint, dict) and new_checkpoint:
+ await self._record_checkpoint(target.id, new_checkpoint)
+
# If drift was detected, persist that fact *before* marking the
# poll successful so the UI reflects "drifted" status alongside
# "healthy". Both writes are independent transactions; the order
@@ -734,6 +756,25 @@ class ConnectorScheduler:
connector_id,
)
+ async def _record_checkpoint(self, connector_id: uuid.UUID, checkpoint: dict[str, Any]) -> None:
+ """Persist an advanced ingest checkpoint into ``connector_config`` (#529).
+
+ Best-effort: a failed write leaves the previous checkpoint in place, so
+ the next poll simply re-scans a small overlap rather than skipping
+ events. One job per instance (``max_instances=1``) means no concurrent
+ writer races here.
+ """
+ if self._engine is None: # pragma: no cover
+ return
+ try:
+ async with self._engine.begin() as conn:
+ await record_checkpoint(conn, connector_id, checkpoint)
+ except Exception: # pragma: no cover
+ logger.debug(
+ "connector.scheduler.record_checkpoint_failed id=%s",
+ connector_id,
+ )
+
async def _record_failure(self, connector_id: uuid.UUID) -> None:
if self._engine is None: # pragma: no cover
return
@@ -747,8 +788,27 @@ class ConnectorScheduler:
)
+def _is_canonical_event(event: Any) -> bool:
+ """True if ``event`` is already a normalized connector envelope.
+
+ Connectors normalize inside ``fetch_alerts`` and return this shape; the
+ scheduler must NOT re-normalize it (#528). A second ``normalize`` pass
+ treats the envelope as a raw vendor row and corrupts it (blanks the
+ external_id, resets severity, double-nests ``raw_event``). We detect the
+ envelope structurally — a canonical event carries the original vendor row
+ under ``raw_event`` plus a ``source`` label — which no raw vendor row has.
+ """
+ return isinstance(event, dict) and "raw_event" in event and "source" in event
+
+
def _safe_normalize(connector: Any, event: dict[str, Any]) -> dict[str, Any]:
- """Run ``connector.normalize`` but never raise out of the loop."""
+ """Normalize an event once, never raising out of the loop.
+
+ Idempotent: an already-canonical event is passed through untouched so
+ self-normalizing connectors aren't double-normalized (#528).
+ """
+ if _is_canonical_event(event):
+ return event
try:
out = connector.normalize(event)
except Exception:
diff --git a/services/connectors/tests/test_scheduler.py b/services/connectors/tests/test_scheduler.py
index 05f745888..f8722c45e 100644
--- a/services/connectors/tests/test_scheduler.py
+++ b/services/connectors/tests/test_scheduler.py
@@ -1000,3 +1000,46 @@ async def test_scheduled_job_executes_without_manual_resume():
aps.shutdown(wait=False)
assert ran.is_set(), "scheduled polling job did not execute on its own"
+
+
+# ---------------------------------------------------------------------------
+# #528 — the scheduler must normalize each event exactly once.
+# ---------------------------------------------------------------------------
+
+
+def test_safe_normalize_passes_through_canonical_event():
+ """A self-normalized (canonical) event must NOT be re-normalized (#528)."""
+ from app.scheduler import _is_canonical_event, _safe_normalize
+
+ canonical = {
+ "source": "splunk",
+ "external_id": "NOTABLE-1",
+ "title": "Brute Force Detected",
+ "severity": "high",
+ "raw_event": {"event_id": "NOTABLE-1", "urgency": "high"},
+ }
+ assert _is_canonical_event(canonical) is True
+
+ class _BrokenReNormalizer:
+ connector_id = "splunk"
+
+ def normalize(self, _raw): # would corrupt a canonical event if called
+ raise AssertionError("normalize must not run on an already-canonical event")
+
+ # Passed straight through, unchanged — the double-normalize is skipped.
+ assert _safe_normalize(_BrokenReNormalizer(), canonical) is canonical
+
+
+def test_safe_normalize_still_normalizes_raw_event():
+ """A genuinely raw vendor row is still normalized exactly once."""
+ from app.scheduler import _safe_normalize
+
+ class _Normalizer:
+ connector_id = "x"
+
+ def normalize(self, raw):
+ return {"source": "x", "raw_event": raw, "external_id": raw["id"]}
+
+ out = _safe_normalize(_Normalizer(), {"id": "abc", "foo": "bar"})
+ assert out["external_id"] == "abc"
+ assert out["raw_event"] == {"id": "abc", "foo": "bar"}
diff --git a/services/connectors/tests/test_splunk_connector.py b/services/connectors/tests/test_splunk_connector.py
new file mode 100644
index 000000000..ba49cd683
--- /dev/null
+++ b/services/connectors/tests/test_splunk_connector.py
@@ -0,0 +1,153 @@
+"""Splunk connector: saved-search dispatch (#525), normalize-once (#528), and
+checkpointed pagination + deterministic identity (#529)."""
+
+from __future__ import annotations
+
+from urllib.parse import parse_qs, urlparse
+
+import httpx
+import pytest
+import respx
+from app.connectors.splunk import SplunkConnector
+
+BASE = "https://splunk.test:8089"
+
+
+def _conn(**kw) -> SplunkConnector:
+ return SplunkConnector(base_url=BASE, token="tok", **kw)
+
+
+# --------------------------------------------------------------------------
+# normalize: idempotent + deterministic identity (#528 / #529)
+# --------------------------------------------------------------------------
+
+
+def test_normalize_is_idempotent():
+ c = _conn()
+ row = {
+ "event_id": "E1",
+ "search_name": "Brute Force Detected",
+ "urgency": "high",
+ "_time": "2026-08-01T00:00:00Z",
+ "src": "1.2.3.4",
+ "host": "h1",
+ }
+ once = c.normalize(row)
+ twice = c.normalize(once)
+ # Re-normalizing a canonical envelope must be a no-op (no blanked
+ # external_id, no title -> "splunk", no severity reset, no double nesting).
+ assert twice == once
+ assert once["external_id"] == "E1"
+ assert once["title"] == "Brute Force Detected"
+ assert once["severity"] == "high"
+ assert once["hostname"] == "h1"
+ assert once["raw_event"] == row
+
+
+def test_normalize_deterministic_external_id():
+ c = _conn()
+ assert c.normalize({"_cd": "1:99", "urgency": "low"})["external_id"] == "1:99"
+ assert c.normalize({"event_id": "E7"})["external_id"] == c.normalize({"event_id": "E7"})["external_id"]
+
+
+# --------------------------------------------------------------------------
+# ordering + checkpoint (#529)
+# --------------------------------------------------------------------------
+
+
+def test_order_and_checkpoint_filters_seen_and_advances():
+ c = _conn()
+ c.set_checkpoint({"time": "2026-08-01T00:00:10Z", "id": "E10"})
+ rows = [
+ {"event_id": "E09", "_time": "2026-08-01T00:00:09Z"}, # before checkpoint -> dropped
+ {"event_id": "E10", "_time": "2026-08-01T00:00:10Z"}, # == checkpoint -> dropped
+ {"event_id": "E12", "_time": "2026-08-01T00:00:12Z"},
+ {"event_id": "E11", "_time": "2026-08-01T00:00:11Z"},
+ ]
+ fresh = c._order_and_checkpoint(rows)
+ assert [r["event_id"] for r in fresh] == ["E11", "E12"] # stable order restored
+ assert c.get_checkpoint() == {"time": "2026-08-01T00:00:12Z", "id": "E12"}
+
+
+def test_checkpoint_not_advanced_when_nothing_new():
+ c = _conn()
+ c.set_checkpoint({"time": "2026-08-01T00:00:99Z", "id": "Z"})
+ assert c._order_and_checkpoint([{"event_id": "E1", "_time": "2026-08-01T00:00:01Z"}]) == []
+ assert c.get_checkpoint() is None
+
+
+def test_same_timestamp_distinct_ids_both_kept():
+ c = _conn()
+ rows = [
+ {"event_id": "A", "_time": "2026-08-01T00:00:10Z"},
+ {"event_id": "B", "_time": "2026-08-01T00:00:10Z"},
+ ]
+ assert {r["event_id"] for r in c._order_and_checkpoint(rows)} == {"A", "B"}
+
+
+# --------------------------------------------------------------------------
+# saved-search dispatch vs notable fallback (#525) + pagination (#529)
+# --------------------------------------------------------------------------
+
+
+def _done_status() -> httpx.Response:
+ return httpx.Response(200, json={"entry": [{"content": {"dispatchState": "DONE"}}]})
+
+
+async def test_fetch_alerts_dispatches_configured_saved_search():
+ c = _conn(saved_search="My Search")
+ # Name is URL-encoded into the dispatch path, never injected into SPL.
+ dispatch = respx.post(url__regex=r".+/services/saved/searches/My%20Search/dispatch").mock(
+ return_value=httpx.Response(201, json={"sid": "SID1"})
+ )
+ respx.get(url__regex=r".+/services/search/jobs/SID1/results").mock(
+ return_value=httpx.Response(200, json={"results": [{"event_id": "E1", "urgency": "high", "_time": "2026-08-01T00:00:00Z"}]})
+ )
+ respx.get(url__regex=r".+/services/search/jobs/SID1(\?.*)?$").mock(return_value=_done_status())
+
+ out = await c.fetch_alerts(since_seconds=300)
+ assert dispatch.called, "configured saved_search was not dispatched (#525)"
+ assert len(out) == 1
+ assert out[0]["external_id"] == "E1"
+ assert out[0]["severity"] == "high"
+
+
+async def test_fetch_alerts_falls_back_to_notable_index_when_unset():
+ c = _conn(saved_search="")
+ jobs = respx.post(url__regex=r".+/services/search/jobs$").mock(return_value=httpx.Response(201, json={"sid": "SID2"}))
+ respx.get(url__regex=r".+/services/search/jobs/SID2/results").mock(return_value=httpx.Response(200, json={"results": []}))
+ respx.get(url__regex=r".+/services/search/jobs/SID2(\?.*)?$").mock(return_value=_done_status())
+
+ await c.fetch_alerts()
+ assert jobs.called
+ assert "notable" in jobs.calls[0].request.content.decode()
+
+
+async def test_pagination_collects_all_results_no_head_cap():
+ c = _conn(saved_search="", page_size=100)
+ total = 250
+ respx.post(url__regex=r".+/services/search/jobs$").mock(return_value=httpx.Response(201, json={"sid": "S"}))
+ respx.get(url__regex=r".+/services/search/jobs/S(\?.*)?$").mock(return_value=_done_status())
+
+ def _results(request: httpx.Request) -> httpx.Response:
+ qs = parse_qs(urlparse(str(request.url)).query)
+ offset = int(qs.get("offset", ["0"])[0])
+ count = int(qs.get("count", ["100"])[0])
+ page = [
+ {"event_id": f"E{i}", "_time": f"2026-08-01T00:{(i // 60) % 60:02d}:{i % 60:02d}Z"}
+ for i in range(offset, min(offset + count, total))
+ ]
+ return httpx.Response(200, json={"results": page})
+
+ respx.get(url__regex=r".+/services/search/jobs/S/results").mock(side_effect=_results)
+
+ out = await c.fetch_alerts()
+ # All 250 survive — the old `head 100` / count=100 cap silently dropped 150.
+ assert len(out) == total
+ assert len({e["external_id"] for e in out}) == total
diff --git a/services/ingest/internal/normalizer/normalizer.go b/services/ingest/internal/normalizer/normalizer.go
index b0205489c..e9422f360 100644
--- a/services/ingest/internal/normalizer/normalizer.go
+++ b/services/ingest/internal/normalizer/normalizer.go
@@ -134,6 +134,27 @@ var connectorProfiles = map[string]connectorProfile{
},
severityMap: map[string]int{},
},
+ // splunk — connector type emitted by SplunkConnector (#528). Its
+ // fetch_alerts already returns a canonical envelope (external_id / title /
+ // severity / src_ip / hostname / created_at + the original row under
+ // raw_event), so the field map reads those lowercase canonical keys, NOT
+ // raw Splunk fields. Class 2001 (Security Finding, category 2) means the
+ // fusion promoter promotes a notable as a vendor-asserted finding
+ // regardless of severity, so a Medium notable is never silently dropped.
+ "splunk": {
+ product: OcsfProduct{Name: "Splunk", VendorName: "Splunk"},
+ classUID: 2001,
+ className: "Security Finding",
+ fieldMap: map[string]string{
+ "title": "message",
+ "external_id": "finding.uid",
+ "src_ip": "src_endpoint.ip",
+ "hostname": "device.name",
+ },
+ severityMap: map[string]int{
+ "critical": 5, "high": 4, "medium": 3, "low": 2, "info": 1, "informational": 1,
+ },
+ },
"okta_system_log": {
product: OcsfProduct{Name: "Okta System Log", VendorName: "Okta"},
classUID: 3002,
@@ -268,6 +289,10 @@ func (n *Normalizer) Normalize(raw *RawEvent) (*NormalizedEvent, error) {
eventTime = t
} else if t, ok := raw.Payload["timestamp"].(string); ok && t != "" {
eventTime = t
+ } else if t, ok := raw.Payload["created_at"].(string); ok && t != "" {
+ // Canonical connector envelopes (e.g. Splunk, #528) carry the event
+ // time under created_at; honor it so the notable's event time survives.
+ eventTime = t
}
ocsf["time"] = normalizeTime(eventTime)
ocsf["ingest_time"] = time.Now().UTC().Format(time.RFC3339Nano)
@@ -475,11 +500,45 @@ func setNestedField(m map[string]interface{}, path string, val interface{}) {
setNestedField(nested, parts[1], val)
}
-// generateEventID creates a deterministic event ID for deduplication
+// firstString returns the first non-empty string value among the given payload
+// keys, or "" if none are present.
+func firstString(payload map[string]interface{}, keys ...string) string {
+ for _, k := range keys {
+ if v, ok := payload[k].(string); ok && v != "" {
+ return v
+ }
+ }
+ return ""
+}
+
+// generateEventID creates a deterministic, replay-stable event ID for
+// deduplication (#529).
+//
+// It is derived from the connector instance + tenant + a STABLE vendor
+// identifier (external_id / event_id / id / _cd, in priority order) so
+// re-ingesting the same event — overlapping poll windows, backfills, restarts —
+// always yields the same canonical ID. ReceivedAt is deliberately excluded from
+// this path; it is set per poll and previously made the ID change on every
+// poll. When no stable vendor ID exists we fall back to the event time plus a
+// content hash of the payload, so a byte-identical replay still collapses to
+// one ID while two same-timestamp events with different content stay distinct.
func generateEventID(raw *RawEvent) string {
- key := fmt.Sprintf("%s:%s:%s", raw.ConnectorID, raw.TenantID, raw.ReceivedAt)
- if id, ok := raw.Payload["id"].(string); ok && id != "" {
- key += ":" + id
+ base := fmt.Sprintf("%s:%s", raw.ConnectorID, raw.TenantID)
+ for _, field := range []string{"external_id", "event_id", "id", "_cd"} {
+ if v, ok := raw.Payload[field].(string); ok && v != "" {
+ return uuid.NewSHA1(uuid.NameSpaceOID, []byte(base+":"+field+"="+v)).String()
+ }
+ }
+ key := base
+ if t := firstString(raw.Payload, "time", "created_at", "timestamp"); t != "" {
+ key += ":t=" + t
+ } else {
+ key += ":r=" + raw.ReceivedAt
+ }
+ // json.Marshal sorts map keys, so the same payload always hashes to the
+ // same content string — the hash is deterministic across replays.
+ if rawBytes, err := json.Marshal(raw.Payload); err == nil {
+ key += ":c=" + string(rawBytes)
}
return uuid.NewSHA1(uuid.NameSpaceOID, []byte(key)).String()
}
diff --git a/services/ingest/internal/normalizer/normalizer_test.go b/services/ingest/internal/normalizer/normalizer_test.go
new file mode 100644
index 000000000..358f82693
--- /dev/null
+++ b/services/ingest/internal/normalizer/normalizer_test.go
@@ -0,0 +1,104 @@
+package normalizer
+
+import (
+ "testing"
+
+ "github.com/beenuar/aisoc/services/ingest/internal/config"
+)
+
+func newTestNormalizer() *Normalizer {
+ return &Normalizer{cfg: &config.Config{NormalizerMode: "strict"}, version: "test"}
+}
+
+// A canonical Splunk envelope (what SplunkConnector.fetch_alerts emits) must
+// normalize as an OCSF Security Finding with its fields preserved, so the
+// fusion promoter promotes it regardless of severity (#528).
+func TestSplunkProfileNormalizesNotableAsFinding(t *testing.T) {
+ n := newTestNormalizer()
+ raw := &RawEvent{
+ ConnectorID: "conn-1",
+ ConnectorType: "splunk",
+ TenantID: "11111111-1111-1111-1111-111111111111",
+ ReceivedAt: "2026-08-02T00:00:00Z",
+ Payload: map[string]interface{}{
+ "source": "splunk",
+ "external_id": "NOTABLE-42",
+ "event_id": "NOTABLE-42",
+ "title": "Brute Force Access Behavior Detected",
+ "severity": "medium",
+ "src_ip": "10.0.0.9",
+ "hostname": "web-01",
+ "created_at": "2026-08-01T23:59:00Z",
+ "raw_event": map[string]interface{}{"_time": "2026-08-01T23:59:00Z"},
+ },
+ }
+
+ ev, err := n.Normalize(raw)
+ if err != nil {
+ t.Fatalf("Normalize returned error: %v", err)
+ }
+ ocsf := ev.OcsfEvent
+
+ if got := ocsf["class_uid"]; got != 2001 {
+ t.Errorf("class_uid = %v, want 2001 (Security Finding)", got)
+ }
+ if got := ocsf["category_uid"]; got != 2 {
+ t.Errorf("category_uid = %v, want 2 (Findings) so the promoter promotes it", got)
+ }
+ if got := ocsf["severity_id"]; got != 3 {
+ t.Errorf("severity_id = %v, want 3 (medium preserved)", got)
+ }
+ if got := ocsf["message"]; got != "Brute Force Access Behavior Detected" {
+ t.Errorf("message = %v, want the rule title", got)
+ }
+ // hostname -> device.name (nested)
+ if dev, ok := ocsf["device"].(map[string]interface{}); !ok || dev["name"] != "web-01" {
+ t.Errorf("device.name not preserved: %v", ocsf["device"])
+ }
+ // external_id must not become empty (the double-normalize regression, #528)
+ if finding, ok := ocsf["finding"].(map[string]interface{}); !ok || finding["uid"] != "NOTABLE-42" {
+ t.Errorf("finding.uid not preserved: %v", ocsf["finding"])
+ }
+}
+
+// The canonical event ID must be stable across polls: same vendor id + tenant +
+// connector => same ID even though ReceivedAt changes every poll (#529).
+func TestGenerateEventIDStableAcrossPolls(t *testing.T) {
+ poll1 := &RawEvent{
+ ConnectorID: "conn-1", TenantID: "t1", ReceivedAt: "2026-08-02T00:00:00Z",
+ Payload: map[string]interface{}{"external_id": "NOTABLE-42"},
+ }
+ poll2 := &RawEvent{
+ ConnectorID: "conn-1", TenantID: "t1", ReceivedAt: "2026-08-02T00:05:00Z", // later poll
+ Payload: map[string]interface{}{"external_id": "NOTABLE-42"},
+ }
+ if generateEventID(poll1) != generateEventID(poll2) {
+ t.Error("event ID changed across polls despite identical vendor id (#529)")
+ }
+}
+
+func TestGenerateEventIDDistinctForDifferentEvents(t *testing.T) {
+ a := &RawEvent{ConnectorID: "c", TenantID: "t", Payload: map[string]interface{}{"external_id": "A"}}
+ b := &RawEvent{ConnectorID: "c", TenantID: "t", Payload: map[string]interface{}{"external_id": "B"}}
+ if generateEventID(a) == generateEventID(b) {
+ t.Error("distinct vendor ids collided to the same event ID")
+ }
+}
+
+// Two events with the same timestamp but different content and no stable vendor
+// id must both be ingestible (distinct IDs), while a byte-identical replay
+// collapses to one (#529).
+func TestGenerateEventIDContentFallback(t *testing.T) {
+ mk := func(msg string) *RawEvent {
+ return &RawEvent{
+ ConnectorID: "c", TenantID: "t", ReceivedAt: "2026-08-02T00:00:00Z",
+ Payload: map[string]interface{}{"time": "2026-08-01T00:00:00Z", "message": msg},
+ }
+ }
+ if generateEventID(mk("one")) == generateEventID(mk("two")) {
+ t.Error("same-timestamp events with different content collided")
+ }
+ if generateEventID(mk("one")) != generateEventID(mk("one")) {
+ t.Error("identical replay produced different IDs")
+ }
+}