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
"""Ingest checkpoints are a declared contract, not a duck type (10b).
The durable half shipped already: `record_checkpoint` persists a cursor, and
the scheduler advances it only after ingest accepted every submitted event.
What was missing was adoption — `splunk` was the only one of 84 connectors
implementing it, and the scheduler reached it through
`getattr(connector, "set_checkpoint", None)`, which on the other 83 was
simply absent.
That is the shape worth testing against. A duck-typed optional protocol has
no failing state, only a quiet one: the seed no-opped at `logger.debug` and
nothing could report which connectors resumed and which re-read their
overlap window. So these tests hold two things — the machinery is correct,
and the *count* of adopters is visible rather than assumed.
"""
from __future__ import annotations
from typing import Any
import pytest
from app.connectors import CONNECTOR_REGISTRY
from app.connectors.base import BaseConnector, ConnectorSchema
class _Cursored(BaseConnector):
connector_id = "test_cursored"
connector_name = "Cursored"
connector_category = "siem"
checkpoint_time_field: tuple[str, ...] = ("ts",)
checkpoint_id_field: tuple[str, ...] = ("uid",)
@classmethod
def schema(cls) -> ConnectorSchema: # pragma: no cover - not exercised
raise NotImplementedError
async def test_connection(self) -> dict[str, Any]: # pragma: no cover
raise NotImplementedError
async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]: # pragma: no cover
raise NotImplementedError
class _Uncursored(_Cursored):
connector_id = "test_uncursored"
checkpoint_time_field: tuple[str, ...] = ()
checkpoint_id_field: tuple[str, ...] = ()
class _Identified(_Uncursored):
"""A queue-shaped connector: dedups on identity, never on event time."""
connector_id = "test_identified"
dedup_identity_field: tuple[str, ...] = ("rid",)
def _row(ts: str, uid: str) -> dict[str, Any]:
return {"ts": ts, "uid": uid}
class TestTheContractIsAskable:
def test_a_connector_that_declares_both_fields_checkpoints(self) -> None:
assert _Cursored.checkpoints() is True
def test_the_default_is_not_checkpointing_and_says_so(self) -> None:
"""The honest default. A connector whose cursor fields nobody has
identified must not pretend to have one — but it is now *declared*
not-checkpointing, which is the difference from an absent method."""
assert _Uncursored.checkpoints() is False
def test_a_time_field_without_a_tie_breaker_does_not_count(self) -> None:
"""Two events in the same second are ordinary. A cursor on time alone
either loses the second one or replays the first forever."""
class _HalfDeclared(_Cursored):
connector_id = "test_half"
checkpoint_id_field: tuple[str, ...] = ()
assert _HalfDeclared.checkpoints() is False
def test_every_connector_answers_the_question(self) -> None:
"""The property the getattr could not provide: ask any of the 84."""
for connector_id, cls in CONNECTOR_REGISTRY.items():
assert isinstance(cls.checkpoints(), bool), connector_id
assert callable(cls.set_checkpoint)
assert callable(cls.get_checkpoint)
class TestTheMachineryIsCorrect:
def test_rows_are_ordered_by_time_then_id(self) -> None:
c = _Cursored()
rows = [_row("t3", "c"), _row("t1", "b"), _row("t1", "a")]
assert [r["uid"] for r in c.apply_checkpoint(rows)] == ["a", "b", "c"]
def test_anything_at_or_before_the_cursor_is_dropped(self) -> None:
"""This is what suppresses the duplicates an overlapping poll
window produces — the reason the overlap is safe to keep."""
c = _Cursored()
c.set_checkpoint({"time": "t2", "id": "b"})
rows = [_row("t1", "a"), _row("t2", "b"), _row("t2", "c"), _row("t3", "d")]
assert [r["uid"] for r in c.apply_checkpoint(rows)] == ["c", "d"]
def test_the_cursor_advances_to_the_last_fresh_row(self) -> None:
c = _Cursored()
c.apply_checkpoint([_row("t1", "a"), _row("t2", "b")])
assert c.get_checkpoint() == {"time": "t2", "id": "b"}
def test_nothing_new_leaves_the_cursor_unmoved(self) -> None:
"""`None` rather than the old value: the scheduler writes only what
moved, so a poll that found nothing must not rewrite the row."""
c = _Cursored()
c.set_checkpoint({"time": "t9", "id": "z"})
assert c.apply_checkpoint([_row("t1", "a")]) == []
assert c.get_checkpoint() is None
def test_two_rows_sharing_a_timestamp_both_survive(self) -> None:
c = _Cursored()
kept = c.apply_checkpoint([_row("t1", "a"), _row("t1", "b")])
assert {r["uid"] for r in kept} == {"a", "b"}
def test_a_connector_that_does_not_checkpoint_passes_rows_through(self) -> None:
"""Safe to call unconditionally from any `fetch_alerts`."""
c = _Uncursored()
rows = [_row("t3", "c"), _row("t1", "a")]
assert c.apply_checkpoint(rows) == rows
assert c.get_checkpoint() is None
def test_a_malformed_seed_is_treated_as_no_cursor(self) -> None:
c = _Cursored()
for junk in (None, {}, {"time": "", "id": ""}, "not-a-dict"):
c.set_checkpoint(junk) # type: ignore[arg-type]
assert c.apply_checkpoint([_row("t1", "a")]) == [_row("t1", "a")]
class TestAdoptionIsCountedNotAssumed:
#: Every connector that resumes from a persisted cursor, with the fields
#: it resumes on. Shrink-only in the sense that matters: a connector
#: dropping out of this list fails the test rather than going quiet,
#: which is exactly what the `getattr` could not do.
EXPECTED = {
"splunk": (("_time", "event_time"), ("event_id", "_cd")),
"okta": (("published",), ("uuid",)),
"m365_audit": (("CreationTime",), ("Id",)),
"aws_cloudtrail": (("EventTime",), ("EventId",)),
"azure_activity": (("eventTimestamp",), ("eventDataId", "id")),
# Depth plan 4.1. Reads an object store rather than a time-windowed
# API, so the cursor is doing a different job: the store already
# guarantees nothing is lost, and the cursor exists to drop the
# re-read that listing the container from the beginning produces. It
# therefore carries a synthetic `record_id` built from the capture
# path and sequence number, which is what makes it stable.
#
# Phase 3 removed `aws_cloudtrail_s3` and `gcp_pubsub` from this
# table. Both read an *unordered* queue, where a high-water mark
# discards a late arrival the only time it is ever offered; they
# dedup on identity instead and are recorded in
# `TestUnorderedSourcesDoNotCarryAWatermark`. This one stays because
# its container is never drained and is re-listed from the start on
# every poll, which a bounded identity set cannot survive.
"azure_event_hubs": (("event_time",), ("record_id",)),
}
def test_the_adopters_are_exactly_the_ones_recorded(self) -> None:
actual = {cid for cid, cls in CONNECTOR_REGISTRY.items() if cls.checkpoints()}
identity_based = set(TestUnorderedSourcesDoNotCarryAWatermark.UNORDERED)
assert actual == set(self.EXPECTED) | identity_based, (
"the set of checkpointing connectors changed. Adding one is good — record it here. "
"Losing one silently is the defect this replaces."
)
@pytest.mark.parametrize("connector_id", sorted(EXPECTED))
def test_each_adopter_declares_the_fields_recorded_for_it(self, connector_id: str) -> None:
cls = CONNECTOR_REGISTRY[connector_id]
time_fields, id_fields = self.EXPECTED[connector_id]
assert cls.checkpoint_time_field == time_fields
assert cls.checkpoint_id_field == id_fields
def test_the_rest_are_honestly_not_checkpointing(self) -> None:
"""Not a failure. A connector without a declared cursor re-reads its
overlap window after a restart, which is safe and loses events older
than that window. The number is here so the gap is legible."""
without = sorted(cid for cid, cls in CONNECTOR_REGISTRY.items() if not cls.checkpoints())
adopters = len(self.EXPECTED) + len(TestUnorderedSourcesDoNotCarryAWatermark.UNORDERED)
assert len(without) == len(CONNECTOR_REGISTRY) - adopters
assert len(CONNECTOR_REGISTRY) >= 84
class TestUnorderedSourcesDoNotCarryAWatermark:
"""Phase 3, finding 5.
A monotonic ``(event_time, record_id)`` high-water mark is right for an
ordered, time-windowed API poll — that is what the design comment on
``apply_checkpoint`` describes and it is sound. It is wrong for a queue.
Neither Pub/Sub (no ordering key from a Cloud Logging sink) nor an S3
notification over SQS is ordered, so an event older than the last batch's
newest is an ordinary first arrival. A watermark discards it, silently,
and the message that carried it has already been acknowledged.
"""
#: Sources whose arrival order is not their event order. These dedup on a
#: stable identity instead; the queue itself is what guarantees no gap.
UNORDERED = {
"aws_cloudtrail_s3": ("object_key",),
"gcp_pubsub": ("record_id",),
}
@pytest.mark.parametrize("connector_id", sorted(UNORDERED))
def test_it_dedups_on_an_identity_rather_than_a_time(self, connector_id: str) -> None:
cls = CONNECTOR_REGISTRY[connector_id]
assert cls.dedup_identity_field == self.UNORDERED[connector_id]
assert cls.checkpoint_time_field == (), "an event-time watermark over an unordered source drops unseen events"
assert cls.checkpoint_id_field == ()
@pytest.mark.parametrize("connector_id", sorted(UNORDERED))
def test_it_still_resumes_from_a_persisted_cursor(self, connector_id: str) -> None:
"""Identity dedup is a cursor too. Dropping out of the checkpointing
set would mean the scheduler stopped seeding it at all."""
assert CONNECTOR_REGISTRY[connector_id].checkpoints() is True
def test_a_blob_store_that_is_relisted_every_poll_keeps_its_watermark(self) -> None:
"""``azure_event_hubs`` reads Capture files from a container that is
never drained, and lists it from the beginning on every poll. The
watermark is doing load-bearing work there: a bounded identity set
would roll over and re-emit the oldest files for ever. It has the
same out-of-order weakness across partitions, but its source is
re-readable rather than destroyed, so the fix is a different one.
"""
cls = CONNECTOR_REGISTRY["azure_event_hubs"]
assert cls.dedup_identity_field == ()
assert cls.checkpoint_time_field == ("event_time",)
class TestIdentityDedupMachinery:
@pytest.fixture()
def connector(self) -> _Identified:
return _Identified()
def test_an_older_row_never_seen_before_is_kept(self, connector: _Identified) -> None:
"""The whole finding, at the level the logic lives."""
connector.set_checkpoint({"seen": _Identified.seen_tokens(["later"])})
kept = connector.apply_checkpoint([{"rid": "earlier", "ts": "t1"}])
assert [r["rid"] for r in kept] == ["earlier"]
def test_a_row_already_seen_is_dropped(self, connector: _Identified) -> None:
connector.set_checkpoint({"seen": _Identified.seen_tokens(["dupe"])})
assert connector.apply_checkpoint([{"rid": "dupe", "ts": "t1"}]) == []
def test_the_staged_cursor_carries_this_batch(self, connector: _Identified) -> None:
connector.apply_checkpoint([{"rid": "a"}, {"rid": "b"}])
staged = connector.get_checkpoint()
assert staged is not None
assert set(staged["seen"]) == set(_Identified.seen_tokens(["a", "b"]))
def test_rows_are_not_reordered(self, connector: _Identified) -> None:
"""Arrival order is the only order a queue has; imposing an event-time
sort on it implies a guarantee the source does not make."""
kept = connector.apply_checkpoint([{"rid": "c", "ts": "t3"}, {"rid": "a", "ts": "t1"}])
assert [r["rid"] for r in kept] == ["c", "a"]
def test_a_row_with_no_identity_is_kept_rather_than_guessed_at(self, connector: _Identified) -> None:
kept = connector.apply_checkpoint([{"rid": ""}, {"rid": "a"}])
assert len(kept) == 2, "an unidentifiable row cannot be proven a duplicate, so it is not treated as one"
def test_the_set_is_bounded_and_forgets_the_oldest_first(self) -> None:
"""The bound's failure mode is a duplicate, never a drop — the
opposite of the watermark it replaces."""
class _Small(_Identified):
connector_id = "test_small"
max_dedup_identities = 3
connector = _Small()
connector.set_checkpoint({"seen": _Small.seen_tokens(["a", "b", "c"])})
connector.apply_checkpoint([{"rid": "d"}])
staged = connector.get_checkpoint()
assert staged is not None
assert len(staged["seen"]) == 3
assert _Small.seen_tokens(["a"])[0] not in staged["seen"]
assert _Small.seen_tokens(["d"])[0] in staged["seen"]
def test_an_identity_is_scoped_to_its_connector(self) -> None:
"""Two sources can mint the same record id. The token binds the
connector so one cannot suppress the other's event; the tenant scope
comes from the per-instance row the cursor is stored on."""
class _Other(_Identified):
connector_id = "test_other_identified"
assert _Identified.seen_tokens(["same"]) != _Other.seen_tokens(["same"])
def test_a_watermark_cursor_left_by_an_earlier_release_is_ignored(self) -> None:
"""Compatibility. A connector upgraded in place finds a
``{"time", "id"}`` cursor in its config, and must neither crash on it
nor resurrect the behaviour it replaced."""
connector = _Identified()
connector.set_checkpoint({"time": "t9", "id": "z"})
kept = connector.apply_checkpoint([{"rid": "a", "ts": "t1"}])
assert [r["rid"] for r in kept] == ["a"]
def test_declaring_both_schemes_is_refused(self) -> None:
"""They answer the same question two different ways, and a connector
carrying both would silently use one of them.
Refused when the class is defined rather than when it is polled: an
import-time error names the connector on startup, where a poll-time
one would surface as whichever dispatch happened to win.
"""
with pytest.raises(ValueError, match="both an event-time watermark and a dedup identity"):
# Built with `type` rather than a `class` statement so there is no
# name to leave unbound: defining the class *is* the call under
# test, and `__init_subclass__` raises before anything is bound.
type("_Both", (_Cursored,), {"connector_id": "test_both", "dedup_identity_field": ("uid",)})
class TestTheSchedulerNoLongerDuckTypes:
def test_it_calls_the_contract_directly(self) -> None:
"""The getattr is what made 83 silent no-ops invisible."""
from pathlib import Path
source = (Path(__file__).resolve().parents[1] / "app" / "scheduler.py").read_text(encoding="utf-8")
# Comments stripped first: the scheduler's own comment quotes the
# pattern it replaced, and a gate that cannot tell code from prose
# about the code fires on its own explanation.
code = "\n".join(line for line in source.splitlines() if not line.lstrip().startswith("#"))
assert 'getattr(connector, "set_checkpoint"' not in code
assert 'getattr(connector, "get_checkpoint"' not in code
assert "connector.set_checkpoint(" in code
assert "connector.get_checkpoint()" in code
def test_the_advance_still_requires_full_batch_acceptance(self) -> None:
"""The whole safety property of the persisted cursor: a fully or
partially rejected batch must be re-read, not skipped."""
from pathlib import Path
source = (Path(__file__).resolve().parents[1] / "app" / "scheduler.py").read_text(encoding="utf-8")
accept_index = source.index('accepted = int(result.get("accepted", 0) or 0)')
advance_index = source.index("new_checkpoint = connector.get_checkpoint()")
assert accept_index < advance_index
assert '"accepted" in result and "rejected" in result' in source
assert "rejected == 0" in source
assert "accepted == len(kept)" in source
assert "if batch_fully_accepted:" in source