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.

feat(phase-C4): form/extend attack chains at fuse time (#456)

Beenu Arora2c217c17f4af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 631212712..36faa6855 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Phase C4 — related alerts now auto-collapse into one ordered attack chain at fuse time.** Correlation grouped alerts into incidents by shared entity and the API could compute a chain per case on demand, but nothing formed/extended a chain **as alerts arrived** — so an analyst saw N separate alerts instead of "step 3 of an intrusion on host X that began 20m ago". New `services/fusion/app/services/attack_chain_grouper.py`: for each entity an alert touches (host/user/ip) it looks up (or mints) a stable `chain_id` in Redis with a rolling window, so a follow-on alert on the same entity — or a *different* entity sharing an IP — joins the same chain. Members are ordered by MITRE kill-chain stage (initial-access → … → impact), so the assignment's `position`/`stage` reflect where in the intrusion this alert sits, not its arrival order. The fusion engine attaches the assignment to `FusedAlert.enrichments["attack_chain"]` (chain_id, position, stage, prior_alert_ids, member_count) for the UI + triage agent. Fail-soft (Redis miss/outage ⇒ no assignment). 8 unit tests; full fusion suite 130 passed at 65% coverage. Claim-to-gate matrix +1 GATED (24 GATED / 10 PARTIAL / 1 NO GATE).
- **Phase B4 — Business Context Rules now run on the live path (environment-specific noise reduction).** A leading AI-SOC differentiator — suppress alerts during a maintenance window, bump severity for production assets, route cloud alerts to the cloud team — existed as an engine + authoring UI in `services/api` but only ran in a dry-run preview; it never touched a live alert. New `services/agents/app/workers/business_context.py` applies the same `when`/`then` semantics (dotted-path fields + `eq/ne/lt/gt/contains/in/exists/...` comparators + `all/any/not`; effects `set_severity` / `route_to` / `tag` / `suppress`) in the auto-triage worker's post-fusion → pre-triage seam. A **suppress** rule drops the alert **before any triage spend**; severity/route/tag mutations flow into the alert the agent reasons over. Rules load from `AISOC_BUSINESS_CONTEXT_RULES_FILE` (mtime-reloaded), gated by `AISOC_BUSINESS_CONTEXT_ENABLED` (default on), fail-soft (bad/missing file ⇒ no rules applied, never an error into triage). The agents image can't import `services/api`, so the evaluator is a faithful, independently-tested re-implementation of the same documented semantics (unifying both call sites is a follow-up). 15 unit tests (`test_business_context_hotpath.py`, added to the CI agents gate). Claim-to-gate matrix +1 GATED (23 GATED / 10 PARTIAL / 1 NO GATE).
- **Phase B3 — rollback is real, actions are post-verified, and approval SLA timers survive restarts.** Three "honest response" gaps closed. (1) **Real rollback:** every executor's `rollback()` previously returned a bare `True` — logging "rolling back" without calling the vendor. New `services/actions/app/services/rollback.py` performs the **real** reverse via the same clients (isolate→`lift_containment`/`unisolate_machine`, block_ip→`unblock_ip`/`unblock_ip_zone`, disable_user→`enable_user`/`unsuspend_user`, suspend_session→`unsuspend_user`) and returns an honest `RollbackResult` (`reversed_` / `simulated` / `supported`) — never a fake success; a failed reverse is reported, not hidden. `autonomy_safety.REVERSIBLE_ACTIONS` now imports from this module (single source of truth) and `test_rollback.py` gates the two sets so an action can't be declared reversible without a real reverse. (2) **Post-action verification:** new `services/actions/app/services/verification.py` re-queries the vendor to confirm the effect is actually present (`VERIFIED` / `FAILED` / honest `UNVERIFIED` when no probe or no creds) — a probe error is never a false `VERIFIED`. (3) **Durable approvals:** `services/slack-bot/app/services/timer_store.py` adds a Postgres-backed `TimerStore`; the `ApprovalTimeoutScheduler` persists pending SLA timers and `recover()` re-arms them on startup (firing overdue ones promptly), so a bot restart can no longer strand a forgotten approval forever. Fail-soft to in-memory when no DB. 25 new tests across actions + slack-bot. Claim-to-gate matrix +1 GATED (22 GATED / 10 PARTIAL / 1 NO GATE).
- **Phase B2 — connector credentials now reach the SOAR executors, and the autonomy policy governs every real execution.** Two wiring gaps closed. (1) Executors read vendor-prefixed parameter keys (`cs_client_id`, `okta_domain`, `splunk_url` …) but connectors store schema field names (`client_id`, `domain`, `base_url` …) — nothing translated, so even fully-configured credentials never reached an executor and every action fell back to simulation. New `services/actions/app/services/credential_resolver.py` pins the per-vendor translation (15 vendors, connector-id aliases like `aws_security_hub`→`aws_security_groups`, `azure_defender`→`defender`; unknown fields dropped, never blindly forwarded), and `LiveActionRequest.auth_config` lets callers pass connector-style creds that the dispatcher resolves at the boundary. (2) The Phase 9a `autonomy_safety.decide()` policy existed but was never called on the live path (the 9b gap) — now every dispatch whose capability maps to an `ActionType` is governed **before** the executor is invoked: above-tier ⇒ downgraded to a dry-run preview; with dry-run disabled ⇒ `PENDING_APPROVAL` (executor never invoked); tier L0 ⇒ `BLOCKED`; explicit dry-run honoured unchanged; governance verdict attached to the result for the audit trail. Deployment tier via `AISOC_MATURITY_TIER` (default L1 — copilot). Also registers ten previously-missing vendor adapters (SentinelOne isolate, Entra/GWS disable-user, PAN-OS/FortiGate/Cloudflare block-ip, Jira/ServiceNow/PagerDuty create-ticket, Slack notify) so the agent can plan against them (19→29 builtins). 29 new/updated tests; full actions suite 224 passed at 64% coverage. Claim-to-gate matrix +1 GATED (21 GATED / 10 PARTIAL / 1 NO GATE).
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index d7e02ffbe..8a14d540d 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -42,10 +42,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Connector credentials reach the SOAR executors (not simulation-only) + autonomy policy governs every real execution | README (SOAR / response) | `ci.yml` actions job (`test_credential_resolver.py` — per-vendor auth_config→executor-param translation pinned; `test_governed_dispatch.py` — Phase 9a `decide()` wired into live dispatch: above-tier ⇒ dry-run preview, dry-run-disabled ⇒ queued approval, L0 ⇒ blocked, executor never invoked when queued/blocked) | GATED | - |
| Rollback is real (not "return True"), post-action verified, and approvals are restart-durable | README (response / rollback) | `ci.yml` actions job (`test_rollback.py` — real vendor reverse calls, honest simulated/failed states, REVERSIBLE_ACTIONS gated against the actual reverse impls; `test_verification.py` — re-queries vendor, never a false VERIFIED) + slack-bot job (`test_timer_store.py` — pending SLA timers persist + recover across restart) | GATED | - |
| Environment-specific noise reduction (business context) applied post-fusion → pre-triage | README (noise reduction) | `ci.yml` agents job (`test_business_context_hotpath.py` — YAML when/then rules mutate severity/route/tags and suppress before any triage spend, wired into `FusedAlertTriageWorker.triage`; `AISOC_BUSINESS_CONTEXT_ENABLED` gate) | GATED | - |
+| Related alerts auto-collapse into one ordered attack chain at fuse time | README (attack chains) | `ci.yml` fusion job (`test_attack_chain_grouper.py` — shared-entity alerts join one chain within the window, members ordered by MITRE kill-chain stage, cross-entity link via shared IP; wired into `fusion_engine.process` → `enrichments.attack_chain`) | GATED | - |
## Summary
-- GATED: 23
+- GATED: 24
- PARTIAL: 10
- NO GATE: 1 (progressively closed through Phases 2–11 and A1–A4: insecure-defaults, secret/IaC scanning, signed releases, cross-store isolation, DAC candidate-rule + imported-count honesty, connector live-test, OpenAPI breaking-change, ClickHouse lake population (A1), live-stream detection (A2), default cold-boot stack (A3), and the behavioral-model fusion (A4). The **last** NO GATE row — wet-eval live-agent scoreboard tables — closes in Phase 4c/E1, which needs a budgeted live-agent run)
diff --git a/services/fusion/app/core/config.py b/services/fusion/app/core/config.py
index bbc0c324f..948d2e7b6 100644
--- a/services/fusion/app/core/config.py
+++ b/services/fusion/app/core/config.py
@@ -54,6 +54,11 @@ class Settings(BaseSettings):
kafka_topic_ueba_anomalies: str = Field(default="ueba.anomalies", alias="KAFKA_TOPIC_UEBA_ANOMALIES")
ueba_signal_ttl_seconds: int = Field(default=86400, alias="AISOC_UEBA_SIGNAL_TTL_SECONDS")
+ # Phase C4 — form/extend attack chains at fuse time so related alerts
+ # auto-collapse into one ordered incident (app/services/attack_chain_grouper.py).
+ attack_chain_grouping_enabled: bool = Field(default=True, alias="AISOC_ATTACK_CHAIN_GROUPING_ENABLED")
+ attack_chain_window_seconds: int = Field(default=3600, alias="AISOC_ATTACK_CHAIN_WINDOW_SECONDS")
+
# Redis
redis_url: str = Field(default="redis://localhost:6379/2", alias="REDIS_URL")
dedup_window_seconds: int = Field(default=300, alias="DEDUP_WINDOW_SECONDS")
diff --git a/services/fusion/app/main.py b/services/fusion/app/main.py
index 5f63d5160..af444ec90 100644
--- a/services/fusion/app/main.py
+++ b/services/fusion/app/main.py
@@ -9,6 +9,7 @@ from app.api.router import router, set_worker
from app.core.config import settings
from app.core.logging import configure_logging, logger
from app.services.alert_sink import AlertSink
+from app.services.attack_chain_grouper import AttackChainGrouper
from app.services.confidence import ConfidenceScorer
from app.services.correlator import Correlator
from app.services.deduplicator import Deduplicator
@@ -34,12 +35,19 @@ async def lifespan(app: FastAPI):
# Phase A4 — behavioral-model fusion: one cache shared by the engine
# (fuse-time lookup) and the worker (records the ueba.anomalies stream).
ueba_cache = UebaSignalCache(redis_client, ttl_seconds=settings.ueba_signal_ttl_seconds) if settings.ueba_fusion_enabled else None
+ # Phase C4 — fuse-time attack-chain grouping (shares the fusion Redis).
+ chain_grouper = (
+ AttackChainGrouper(redis_client, window_seconds=settings.attack_chain_window_seconds)
+ if settings.attack_chain_grouping_enabled
+ else None
+ )
engine = FusionEngine(
dedup,
correlator,
entity_risk=entity_risk,
confidence_scorer=confidence_scorer,
ueba_cache=ueba_cache,
+ chain_grouper=chain_grouper,
)
# Phase 3.1 — fused alerts land in the Postgres alert store so the spine
# is continuous (raw event → alert row). Fail-soft: a missing/unreachable
diff --git a/services/fusion/app/services/attack_chain_grouper.py b/services/fusion/app/services/attack_chain_grouper.py
new file mode 100644
index 000000000..b34916529
--- /dev/null
+++ b/services/fusion/app/services/attack_chain_grouper.py
@@ -0,0 +1,193 @@
+"""Attack-chain auto-grouping at fuse time (Phase C4).
+
+Correlation groups alerts into incidents by shared entity, and the API can
+compute an attack chain *per case* on demand. But nothing formed or extended a
+chain **at fuse time**, so related alerts didn't auto-collapse into one ordered
+incident narrative as they arrived — the analyst saw N separate alerts instead
+of "stage 3 of an intrusion on host X that began with initial-access 20m ago".
+
+This grouper closes that. For each entity an alert touches (host / user / ip),
+it looks up (or mints) a stable ``chain_id`` in Redis with a rolling TTL, so a
+follow-on alert on the same entity within the window joins the same chain. It
+appends a compact member record, orders members by MITRE kill-chain stage, and
+returns a :class:`ChainAssignment` the fusion engine attaches to the fused
+alert (``enrichments["attack_chain"]``) — giving the UI and the triage agent an
+at-a-glance "this is step K of an unfolding attack" view.
+
+Fail-soft: a Redis miss/outage degrades to "no chain assignment", never an
+error into the fusion pipeline.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+import uuid
+from dataclasses import asdict, dataclass
+from typing import Any
+
+import structlog
+
+logger = structlog.get_logger()
+
+# MITRE ATT&CK tactic → kill-chain ordinal. Lower = earlier in an intrusion.
+# Names are matched case-insensitively against both dashed and spaced forms.
+_TACTIC_ORDER = {
+ "reconnaissance": 0,
+ "resource-development": 1,
+ "initial-access": 2,
+ "execution": 3,
+ "persistence": 4,
+ "privilege-escalation": 5,
+ "defense-evasion": 6,
+ "credential-access": 7,
+ "discovery": 8,
+ "lateral-movement": 9,
+ "collection": 10,
+ "command-and-control": 11,
+ "exfiltration": 12,
+ "impact": 13,
+}
+_MAX_MEMBERS = 50
+
+
+def _stage_ordinal(tactics: list[str]) -> int:
+ best = -1
+ for t in tactics or []:
+ key = str(t).strip().lower().replace(" ", "-")
+ if key in _TACTIC_ORDER and _TACTIC_ORDER[key] > best:
+ best = _TACTIC_ORDER[key]
+ return best
+
+
+def _stage_name(ordinal: int) -> str:
+ if ordinal < 0:
+ return "unknown"
+ for name, ord_ in _TACTIC_ORDER.items():
+ if ord_ == ordinal:
+ return name
+ return "unknown"
+
+
+@dataclass
+class ChainMember:
+ alert_id: str
+ title: str
+ severity: str
+ stage_ordinal: int
+ stage: str
+ ts: float
+
+
+@dataclass
+class ChainAssignment:
+ chain_id: str
+ is_new_chain: bool
+ position: int # 1-based position of this alert in the chain
+ stage: str # this alert's kill-chain stage
+ entity: str # the entity the chain is keyed on ("host:WIN-DC01")
+ prior_alert_ids: list[str]
+ member_count: int
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+def _entities(alert: Any) -> list[tuple[str, str]]:
+ out: list[tuple[str, str]] = []
+ if getattr(alert, "hostname", None):
+ out.append(("host", str(alert.hostname)))
+ if getattr(alert, "username", None):
+ out.append(("user", str(alert.username)))
+ if getattr(alert, "src_ip", None):
+ out.append(("ip", str(alert.src_ip)))
+ return out
+
+
+class AttackChainGrouper:
+ """Redis-backed fuse-time chain former/extender. Fail-soft on every op."""
+
+ def __init__(self, redis_client: Any, *, window_seconds: int = 3600) -> None:
+ self._redis = redis_client
+ self._window = window_seconds
+
+ def _chain_key(self, tenant_id: str, entity_type: str, entity_id: str) -> str:
+ return f"chain:idx:{tenant_id}:{entity_type.lower()}:{entity_id.lower()}"
+
+ def _members_key(self, chain_id: str) -> str:
+ return f"chain:members:{chain_id}"
+
+ async def assign(self, alert: Any) -> ChainAssignment | None:
+ """Form or extend the attack chain for ``alert``. Returns the
+ assignment, or ``None`` when the alert has no entity or Redis is down."""
+ entities = _entities(alert)
+ if not entities:
+ return None
+ tenant_id = str(getattr(alert, "tenant_id", ""))
+ try:
+ # Reuse the first entity that already has an active chain; otherwise
+ # start a new chain keyed on the alert's primary entity.
+ chain_id: str | None = None
+ chosen_entity = entities[0]
+ for etype, eid in entities:
+ existing = await self._redis.get(self._chain_key(tenant_id, etype, eid))
+ if existing:
+ chain_id = existing.decode() if isinstance(existing, bytes) else str(existing)
+ chosen_entity = (etype, eid)
+ break
+
+ is_new = chain_id is None
+ if chain_id is None:
+ chain_id = str(uuid.uuid4())
+
+ # Point every entity of this alert at the chain (rolling TTL) so a
+ # later alert on any of them joins the same chain.
+ for etype, eid in entities:
+ await self._redis.set(self._chain_key(tenant_id, etype, eid), chain_id, ex=self._window)
+
+ stage_ord = _stage_ordinal(list(getattr(alert, "mitre_tactics", []) or []))
+ member = ChainMember(
+ alert_id=str(getattr(alert, "id", "")),
+ title=str(getattr(alert, "title", ""))[:200],
+ severity=str(getattr(getattr(alert, "severity", None), "value", getattr(alert, "severity", ""))),
+ stage_ordinal=stage_ord,
+ stage=_stage_name(stage_ord),
+ ts=time.time(),
+ )
+
+ members = await self._load_members(chain_id)
+ prior_ids = [m.alert_id for m in members]
+ members.append(member)
+ members = members[-_MAX_MEMBERS:]
+ await self._save_members(chain_id, members)
+
+ # Position = kill-chain-ordered rank of this alert among members.
+ ordered = sorted(members, key=lambda m: (m.stage_ordinal, m.ts))
+ position = next((i + 1 for i, m in enumerate(ordered) if m.alert_id == member.alert_id), len(members))
+
+ return ChainAssignment(
+ chain_id=chain_id,
+ is_new_chain=is_new,
+ position=position,
+ stage=member.stage,
+ entity=f"{chosen_entity[0]}:{chosen_entity[1]}",
+ prior_alert_ids=prior_ids,
+ member_count=len(members),
+ )
+ except Exception as exc: # noqa: BLE001 — chaining is additive; never break fusion
+ logger.warning("attack_chain.assign_failed", error=str(exc))
+ return None
+
+ async def _load_members(self, chain_id: str) -> list[ChainMember]:
+ raw = await self._redis.get(self._members_key(chain_id))
+ if not raw:
+ return []
+ try:
+ data = json.loads(raw.decode() if isinstance(raw, bytes) else raw)
+ return [ChainMember(**m) for m in data]
+ except (ValueError, TypeError):
+ return []
+
+ async def _save_members(self, chain_id: str, members: list[ChainMember]) -> None:
+ payload = json.dumps([asdict(m) for m in members])
+ await self._redis.set(self._members_key(chain_id), payload.encode("utf-8"), ex=self._window)
diff --git a/services/fusion/app/services/fusion_engine.py b/services/fusion/app/services/fusion_engine.py
index 59802dce0..d87af845e 100644
--- a/services/fusion/app/services/fusion_engine.py
+++ b/services/fusion/app/services/fusion_engine.py
@@ -16,6 +16,7 @@ from app.models.alert import (
IncidentSummary,
RawAlert,
)
+from app.services.attack_chain_grouper import AttackChainGrouper
from app.services.confidence import ConfidenceScorer
from app.services.correlator import Correlator
from app.services.deduplicator import Deduplicator
@@ -120,6 +121,7 @@ class FusionEngine:
entity_risk: EntityRiskEngine | None = None,
confidence_scorer: ConfidenceScorer | None = None,
ueba_cache: UebaSignalCache | None = None,
+ chain_grouper: AttackChainGrouper | None = None,
) -> None:
self._dedup = deduplicator
self._correlator = correlator
@@ -127,6 +129,8 @@ class FusionEngine:
self._entity_risk = entity_risk
# Phase A4 — behavioral-model signal (optional; None = no UEBA fusion).
self._ueba_cache = ueba_cache
+ # Phase C4 — fuse-time attack-chain former/extender (optional).
+ self._chain_grouper = chain_grouper
# Confidence + explainability is intrinsic to a fused alert — every
# alert leaves the engine with a high/med/low label and an evidence
# chain. The scorer is pure / stateless so we instantiate a default.
@@ -207,6 +211,18 @@ class FusionEngine:
except Exception as exc:
logger.warning("ueba_boost_failed", error=str(exc))
+ # --- Step 3e: Attack-chain auto-grouping at fuse time (Phase C4) ---
+ # Form/extend the entity's attack chain so related alerts collapse into
+ # one ordered incident narrative as they arrive. Additive: a failure
+ # never blocks the alert.
+ if self._chain_grouper is not None:
+ try:
+ assignment = await self._chain_grouper.assign(alert)
+ if assignment is not None:
+ fused.enrichments["attack_chain"] = assignment.to_dict()
+ except Exception as exc:
+ logger.warning("attack_chain_grouping_failed", error=str(exc))
+
# --- Step 4: Risk-Based Alerting (entity rollup) ---
# RBA accumulates points on the entities this alert touches and may
# promote one or more of them to an entity-incident. Failures here
diff --git a/services/fusion/tests/test_attack_chain_grouper.py b/services/fusion/tests/test_attack_chain_grouper.py
new file mode 100644
index 000000000..2410f6569
--- /dev/null
+++ b/services/fusion/tests/test_attack_chain_grouper.py
@@ -0,0 +1,125 @@
+"""Phase C4 — fuse-time attack-chain auto-grouping tests.
+
+Proves related alerts on a shared entity join one chain within the window,
+that members are ordered by MITRE kill-chain stage (so "position" reflects the
+intrusion stage, not arrival order), that a new entity starts a new chain, and
+that everything is fail-soft.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from app.models.alert import AlertSeverity, RawAlert
+from app.services.attack_chain_grouper import AttackChainGrouper
+
+pytestmark = pytest.mark.asyncio
+
+TENANT = "11111111-1111-1111-1111-111111111111"
+
+
+class _FakeRedis:
+ def __init__(self) -> None:
+ self.store: dict[str, bytes] = {}
+ self.fail = False
+
+ async def get(self, key): # noqa: ANN001
+ if self.fail:
+ raise RuntimeError("redis down")
+ return self.store.get(key)
+
+ async def set(self, key, value, ex=None): # noqa: ANN001, ARG002
+ if self.fail:
+ raise RuntimeError("redis down")
+ self.store[key] = value if isinstance(value, bytes) else str(value).encode()
+
+
+def _alert(*, hostname=None, username=None, src_ip=None, tactics=None, title="t") -> RawAlert:
+ return RawAlert(
+ tenant_id=TENANT,
+ source="test",
+ title=title,
+ severity=AlertSeverity.HIGH,
+ hostname=hostname,
+ username=username,
+ src_ip=src_ip,
+ mitre_tactics=tactics or [],
+ )
+
+
+async def test_first_alert_starts_new_chain():
+ g = AttackChainGrouper(_FakeRedis())
+ a = await g.assign(_alert(hostname="WIN-DC01", tactics=["initial-access"]))
+ assert a is not None
+ assert a.is_new_chain is True
+ assert a.member_count == 1
+ assert a.position == 1
+ assert a.entity == "host:WIN-DC01"
+
+
+async def test_second_alert_same_host_joins_chain():
+ r = _FakeRedis()
+ g = AttackChainGrouper(r)
+ a1 = await g.assign(_alert(hostname="WIN-DC01", tactics=["initial-access"], title="phish"))
+ a2 = await g.assign(_alert(hostname="WIN-DC01", tactics=["lateral-movement"], title="psexec"))
+ assert a2.is_new_chain is False
+ assert a2.chain_id == a1.chain_id
+ assert a2.member_count == 2
+ assert a1.member_count == 1
+
+
+async def test_members_ordered_by_kill_chain_stage():
+ r = _FakeRedis()
+ g = AttackChainGrouper(r)
+ # Arrive out of order: exfiltration first, then initial-access.
+ await g.assign(_alert(hostname="H1", tactics=["exfiltration"], title="exfil"))
+ early = await g.assign(_alert(hostname="H1", tactics=["initial-access"], title="access"))
+ # The initial-access alert should rank position 1 (earliest stage) even
+ # though it arrived second.
+ assert early.position == 1
+ assert early.stage == "initial-access"
+
+
+async def test_cross_entity_link_via_shared_ip():
+ r = _FakeRedis()
+ g = AttackChainGrouper(r)
+ a1 = await g.assign(_alert(hostname="H1", src_ip="10.0.0.9", tactics=["execution"]))
+ # New host but same IP → joins the existing chain.
+ a2 = await g.assign(_alert(hostname="H2", src_ip="10.0.0.9", tactics=["persistence"]))
+ assert a2.chain_id == a1.chain_id
+
+
+async def test_different_entity_starts_separate_chain():
+ r = _FakeRedis()
+ g = AttackChainGrouper(r)
+ a1 = await g.assign(_alert(hostname="H1", tactics=["execution"]))
+ a2 = await g.assign(_alert(hostname="H2", tactics=["execution"]))
+ assert a1.chain_id != a2.chain_id
+
+
+async def test_no_entity_returns_none():
+ g = AttackChainGrouper(_FakeRedis())
+ assert await g.assign(_alert(tactics=["impact"])) is None
+
+
+async def test_failsoft_on_redis_error():
+ r = _FakeRedis()
+ r.fail = True
+ g = AttackChainGrouper(r)
+ assert await g.assign(_alert(hostname="H1")) is None
+
+
+async def test_prior_alert_ids_populated():
+ r = _FakeRedis()
+ g = AttackChainGrouper(r)
+ a1 = await g.assign(_alert(hostname="H1", tactics=["initial-access"]))
+ a2 = await g.assign(_alert(hostname="H1", tactics=["discovery"]))
+ # The second alert's prior_alert_ids is exactly the first alert's id.
+ assert a2.prior_alert_ids == [_first_member_id(r, a1.chain_id)]
+ assert len(a2.prior_alert_ids) == 1
+
+
+def _first_member_id(redis: _FakeRedis, chain_id: str) -> str:
+ raw = redis.store[f"chain:members:{chain_id}"]
+ return json.loads(raw.decode())[0]["alert_id"]