Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(phase-A4): fuse the UEBA behavioral model into alert scoring (#449)
Beenu Arora86a27c893ac1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f817ef55e..122816fac 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 A4 — the behavioral (UEBA) model now feeds alert scoring in production (the three-model story is real).** `services/ueba` continuously scored every entity and emitted `ueba.anomalies`, but fusion never consumed them — so the Semantic-graph / Behavioral-UEBA / Knowledge-LLM story was only two models live. New `services/fusion/app/services/ueba_signal.py`: the fusion consumer subscribes to `ueba.anomalies` and caches the latest per-`(tenant, entity_type, entity_id)` anomaly in Redis with a TTL (behavioral signal is time-decaying); during `FusionEngine.process`, an alert looks up the highest anomaly across its own entities (username→user, hostname→device, src/dst IP→ip) and `apply_ueba_boost` raises the alert's confidence (risk-scaled, label recomputed) and anomaly score, recording an explainable `ueba_anomaly` factor. Fail-soft throughout (Redis miss/outage or malformed message ⇒ no boost, no raise). 10 fusion unit tests; full fusion suite 122 passed at 64% coverage. Claim-to-gate matrix adds a GATED row "Three-model AI: behavioral (UEBA) model feeds alert scoring" (19 GATED / 10 PARTIAL / 1 NO GATE).- **Phase A3 — the default cold-boot stack is complete ("just works").** A plain `docker compose up` previously started the core services but left the connector runtime behind a `connectors` profile and graph-at-ingest OFF, so a fresh install wasn't the full spine. Now `docker-compose.yml` ships the connector runtime in the default profile (it idles harmlessly with no configured instances) and enables graph-at-ingest by default on `ingest-worker` (`AISOC_GRAPH_ENABLED=true` + Neo4j env + `depends_on`; the writer soft-fails if Neo4j is unreachable, so it never blocks ingest). `integration.yml` gains a Phase A3 gate asserting the default boot ships the connectors service **and** ingest enabled the graph writer **and** the Neo4j graph has nodes after the spine flowed — so combined with A1 (lake) and A2 (detection), a cold `up` is proven end-to-end: ingest → OCSF normalize → Kafka → ClickHouse lake + entity graph + detection engine → fused alert row. Claim-to-gate matrix: "`pnpm aisoc:demo` boots the real stack" PARTIAL → GATED (18 GATED / 10 PARTIAL / 1 NO GATE).- **Phase A2 — the executable detection corpus now fires on the live event stream.** The reality audit's second SIEM gap: ~939 executable rules existed but only ran in CI fixture-replay — nothing evaluated them against ingested events, so any telemetry that wasn't a vendor-asserted finding (the promoter's job) never became an alert. New `services/fusion/app/services/detection_engine.py` loads the native corpus exported to `app/data/detection_ruleset.json` (817 rules, by `scripts/export_detection_ruleset.py`) and evaluates each ingested event's connector-normalized fields — recovered from `ocsf_event["raw_data"]`, the shape the specs were authored against — via a **vendored, parity-gated** copy of the canonical `match_when` matcher (`app/services/detection_matcher.py`; `test_detection_matcher_parity.py` asserts byte-for-behaviour agreement with `scripts/generate_detections.py` over every committed fixture). Each firing rule becomes a `RawAlert` routed through the normal fusion dedup/correlate/persist pipeline. Product routing is fuzzy (correctness-first: unknown product ⇒ evaluate all). Gates: `integration.yml` posts an event matching `aws-root-account-login` and asserts the alert appears; `validate-detections.yml` drift-checks the exported ruleset; 16 fusion unit tests. Claim-to-gate matrix adds a GATED row "Detection rules fire on the live event stream" (17 GATED / 11 PARTIAL / 1 NO GATE).- **Phase A1 — the ClickHouse event lake is now populated from the live stream.** The reality audit's central SIEM gap: the `aisoc.raw_events` lake table and its `/api/v1/lake/sql` read API existed with **no writer**, so every hunt/query ran against an empty warehouse. New `services/fusion/app/services/lake_writer.py` (`LakeWriter`) archives every normalized OCSF event from the `aisoc.raw_events` Kafka topic into ClickHouse — mapping the OCSF envelope to the lake columns (IPv4→IPv4-mapped-IPv6 coercion, `DateTime64` binding, MITRE/IOC extraction), batched by size **or** age, and **fail-soft** (a ClickHouse outage drops the batch and logs, never crashes the consumer). Archival is independent of promotion (a non-promoted Medium event is still queryable), and a background periodic-flush ticker guarantees a low-traffic batch is never stranded. Wired into the fusion consumer + lifespan; `docker-compose.yml` fusion service gets ClickHouse env + `depends_on`. `integration.yml` gains a Phase A1 gate asserting `SELECT count() FROM aisoc.raw_events > 0` after the spine ingests, against a live ClickHouse container (verified locally: a real INSERT round-trips). Claim-to-gate matrix adds a GATED row "Ingested events land in the queryable ClickHouse lake" (16 GATED / 11 PARTIAL / 1 NO GATE). At-least-once with a deterministic `event_id` (MergeTree does not dedup; the gate asserts queryability, not exact-once).diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 4092212fe..311160167 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -37,12 +37,13 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| OpenAPI stability for 3 SDKs + MCP | (implied by SDKs) | `check-openapi.yml` (drift) + `openapi-breaking.yml` (`scripts/openapi_diff.py` — PR spec vs base fails on removed endpoint/schema/field, type change, tightened request, or dropped enum value) | GATED | - || Ingested events land in the queryable ClickHouse lake | README (SIEM / lake) | `integration.yml :: spine` (Phase A1 — after the spine ingests, asserts `SELECT count() FROM aisoc.raw_events > 0` against the live ClickHouse container; `services/fusion` `LakeWriter` archives every normalized event) | GATED | - || Detection rules fire on the live event stream (not just CI fixtures) | README L170 (detection engine) | `integration.yml :: spine` (Phase A2 — posts an event matching the native `aws-root-account-login` rule, asserts the fusion `DetectionEngine` produces the alert) + `validate-detections.yml` (exported-ruleset drift `--check`) + fusion `test_detection_engine.py` / `test_detection_matcher_parity.py` | GATED | - |+| Three-model AI: behavioral (UEBA) model feeds alert scoring in production | README (multi-model) | `ci.yml` fusion job (`test_ueba_signal.py` — the `ueba.anomalies` stream warms a per-entity cache that boosts fuse-time confidence + anomaly score; wired in `fusion_engine.process`) | GATED | - |## Summary-- GATED: 17-- PARTIAL: 11-- NO GATE: 1 (Phase 2 moved insecure-defaults-hard-fail to GATED and secret/IaC/container scanning to PARTIAL; the Phase 2 continuation moved signed/attested releases to GATED; Phase 3.4 moved cross-store isolation to GATED; Phase 4 moved the DAC candidate-rule gate and imported-count honesty gate to GATED; Phase 10 moved connector "live Test connection" off NO GATE; Phase 11 moved OpenAPI breaking-change semantics to GATED; Phase A1 gated the ClickHouse lake being populated; Phase A2 gated live-stream detection. The **last** NO GATE row — wet-eval live-agent scoreboard tables — closes in Phase 4c, which needs a budgeted live-agent run)+- GATED: 19+- 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)The ratchet is enforced by `scripts/check_claim_gate_matrix.py` (wired into `security.yml`): the NO GATE count may only decrease.diff --git a/services/fusion/app/core/config.py b/services/fusion/app/core/config.pyindex 309e2a940..bbc0c324f 100644--- a/services/fusion/app/core/config.py+++ b/services/fusion/app/core/config.py@@ -47,6 +47,13 @@ class Settings(BaseSettings):# becomes a RawAlert routed through fusion.detection_engine_enabled: bool = Field(default=True, alias="AISOC_DETECTION_ENGINE_ENABLED")+ # Phase A4 — consume the UEBA behavioral-anomaly stream and fold each+ # entity's latest anomaly into alert confidence + anomaly score at fuse+ # time (app/services/ueba_signal.py). Completes the three-model story.+ ueba_fusion_enabled: bool = Field(default=True, alias="AISOC_UEBA_FUSION_ENABLED")+ 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")+# Redisredis_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.pyindex f80af7422..ed9621209 100644--- a/services/fusion/app/main.py+++ b/services/fusion/app/main.py@@ -16,6 +16,7 @@ from app.services.detection_engine import DetectionEnginefrom app.services.entity_risk import EntityRiskEnginefrom app.services.fusion_engine import FusionEnginefrom app.services.lake_writer import LakeWriter+from app.services.ueba_signal import UebaSignalCachefrom app.workers.consumer import FusionWorker@@ -30,11 +31,17 @@ async def lifespan(app: FastAPI):correlator = Correlator(redis_client)entity_risk = EntityRiskEngine(redis_client)confidence_scorer = ConfidenceScorer(enabled=settings.confidence_enabled)+ # 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+ )engine = FusionEngine(dedup,correlator,entity_risk=entity_risk,confidence_scorer=confidence_scorer,+ ueba_cache=ueba_cache,)# 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@@ -56,7 +63,7 @@ async def lifespan(app: FastAPI):)# Phase A2 — evaluate the executable detection corpus against the stream.detector = DetectionEngine() if settings.detection_engine_enabled else None- worker = FusionWorker(engine, sink=sink, lake=lake, detector=detector)+ worker = FusionWorker(engine, sink=sink, lake=lake, detector=detector, ueba_cache=ueba_cache)set_worker(worker)# Start Kafka worker as a background taskdiff --git a/services/fusion/app/services/fusion_engine.py b/services/fusion/app/services/fusion_engine.pyindex 4447ca511..59802dce0 100644--- a/services/fusion/app/services/fusion_engine.py+++ b/services/fusion/app/services/fusion_engine.py@@ -26,6 +26,7 @@ from app.services.narrative import (NarrativeInputs,build_narrative,)+from app.services.ueba_signal import UebaSignalCache, alert_entities, apply_ueba_boostfrom app.services.vuln_boost import apply_vuln_boostlogger = structlog.get_logger()@@ -118,11 +119,14 @@ class FusionEngine:ml_scorer: MLScorer | None = None,entity_risk: EntityRiskEngine | None = None,confidence_scorer: ConfidenceScorer | None = None,+ ueba_cache: UebaSignalCache | None = None,) -> None:self._dedup = deduplicatorself._correlator = correlatorself._ml_scorer = ml_scorer or MLScorer()self._entity_risk = entity_risk+ # Phase A4 — behavioral-model signal (optional; None = no UEBA fusion).+ self._ueba_cache = ueba_cache# 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.@@ -193,6 +197,16 @@ class FusionEngine:except Exception as exc:logger.warning("vuln_boost_failed", error=str(exc))+ # --- Step 3d: Behavioral-model fusion (Phase A4) ---+ # Fold the alert's entities' latest UEBA anomaly into confidence ++ # anomaly score. Best-effort: a Redis miss/outage is a no-op.+ if self._ueba_cache is not None:+ try:+ signal = await self._ueba_cache.lookup(str(alert.tenant_id), alert_entities(alert))+ fused = apply_ueba_boost(fused, signal)+ except Exception as exc:+ logger.warning("ueba_boost_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 herediff --git a/services/fusion/app/services/ueba_signal.py b/services/fusion/app/services/ueba_signal.pynew file mode 100644index 000000000..7770ad9c5--- /dev/null+++ b/services/fusion/app/services/ueba_signal.py@@ -0,0 +1,178 @@+"""Fuse the UEBA behavioral model into fused-alert scoring (Phase A4).++`services/ueba` continuously scores every entity (user / device / ip) and emits+``ueba.anomalies`` messages, but fusion never consumed them — so the platform's+"three-model" story (Semantic graph / Behavioral UEBA / Knowledge LLM) was only+two models in production. This module closes that: fusion caches the latest+per-entity behavioral anomaly and folds it into an alert's confidence + anomaly+score at fuse time.++Flow:++* The fusion consumer subscribes to ``ueba.anomalies`` and calls+ :meth:`UebaSignalCache.record`, which stores the latest score/risk per+ ``(tenant, entity_type, entity_id)`` in Redis with a TTL (behavioral signal+ is time-decaying — a week-old anomaly shouldn't boost today's alert).+* During ``FusionEngine.process`` an alert looks up the highest behavioral+ anomaly across its own entities (username, hostname, src/dst IP) via+ :meth:`UebaSignalCache.lookup` and :func:`apply_ueba_boost` raises the+ alert's confidence + anomaly score and records an explainable factor.++Everything is fail-soft: a Redis miss/outage or a malformed UEBA message+degrades to "no behavioral boost", never an error into the pipeline.+"""++from __future__ import annotations++import json+from dataclasses import dataclass+from typing import Any++import structlog++from app.models.alert import ConfidenceFactor, ConfidenceLabel, FusedAlert++logger = structlog.get_logger()++# UEBA risk_level -> normalized behavioral weight in [0, 1] and the confidence+# nudge it earns. Kept conservative: even a critical behavioral anomaly is a+# supporting signal, not a verdict on its own.+_RISK_WEIGHT = {"critical": 1.0, "high": 0.75, "medium": 0.45, "low": 0.2}+_RISK_BOOST = {"critical": 0.20, "high": 0.14, "medium": 0.07, "low": 0.0}++_CONF_HIGH = 0.70+_CONF_MEDIUM = 0.40+++def _label_for(score: float) -> ConfidenceLabel:+ if score >= _CONF_HIGH:+ return ConfidenceLabel.HIGH+ if score >= _CONF_MEDIUM:+ return ConfidenceLabel.MEDIUM+ return ConfidenceLabel.LOW+++@dataclass(frozen=True)+class UebaSignal:+ entity_type: str+ entity_id: str+ anomaly_score: float+ risk_level: str++ @property+ def normalized(self) -> float:+ return _RISK_WEIGHT.get(self.risk_level.lower(), 0.0)+++def _key(tenant_id: str, entity_type: str, entity_id: str) -> str:+ return f"ueba:anom:{tenant_id}:{entity_type.lower()}:{entity_id.lower()}"+++def alert_entities(alert: Any) -> list[tuple[str, str]]:+ """(entity_type, entity_id) pairs the UEBA cache is keyed by, for an alert.++ UEBA entity types are user / device / ip (see services/ueba). We map the+ alert's username -> user, hostname -> device, src/dst IP -> ip.+ """+ out: list[tuple[str, str]] = []+ if getattr(alert, "username", None):+ out.append(("user", str(alert.username)))+ if getattr(alert, "hostname", None):+ out.append(("device", str(alert.hostname)))+ for ip in (getattr(alert, "src_ip", None), getattr(alert, "dst_ip", None)):+ if ip:+ out.append(("ip", str(ip)))+ return out+++class UebaSignalCache:+ """Redis-backed latest-anomaly-per-entity cache. Fail-soft on every op."""++ def __init__(self, redis_client: Any, ttl_seconds: int = 86400) -> None:+ self._redis = redis_client+ self._ttl = ttl_seconds++ async def record(self, message: dict[str, Any]) -> bool:+ """Store one ``ueba.anomalies`` message. Returns True if cached."""+ try:+ tenant = str(message.get("tenant_id") or "")+ etype = str(message.get("entity_type") or "")+ eid = str(message.get("entity_id") or "")+ if not (tenant and etype and eid):+ return False+ payload = json.dumps(+ {+ "anomaly_score": float(message.get("anomaly_score") or 0.0),+ "risk_level": str(message.get("risk_level") or "low"),+ "entity_type": etype,+ "entity_id": eid,+ }+ )+ await self._redis.set(_key(tenant, etype, eid), payload.encode("utf-8"), ex=self._ttl)+ return True+ except Exception as exc: # noqa: BLE001 — behavioral cache is best-effort+ logger.debug("ueba_signal.record_failed", error=str(exc))+ return False++ async def lookup(self, tenant_id: str, entities: list[tuple[str, str]]) -> UebaSignal | None:+ """Return the highest-scoring cached behavioral signal for the alert's+ entities, or ``None`` if none is cached."""+ best: UebaSignal | None = None+ for etype, eid in entities:+ try:+ raw = await self._redis.get(_key(tenant_id, etype, eid))+ except Exception as exc: # noqa: BLE001+ logger.debug("ueba_signal.lookup_failed", error=str(exc))+ continue+ if not raw:+ continue+ try:+ data = json.loads(raw.decode("utf-8") if isinstance(raw, bytes) else raw)+ sig = UebaSignal(+ entity_type=data.get("entity_type", etype),+ entity_id=data.get("entity_id", eid),+ anomaly_score=float(data.get("anomaly_score", 0.0)),+ risk_level=str(data.get("risk_level", "low")),+ )+ except (ValueError, TypeError):+ continue+ if best is None or sig.normalized > best.normalized:+ best = sig+ return best+++def apply_ueba_boost(fused: FusedAlert, signal: UebaSignal | None) -> FusedAlert:+ """Fold a behavioral anomaly into the alert's confidence + anomaly score.++ Appends an explainable ``ueba_anomaly`` factor, nudges confidence by the+ risk-scaled amount (and recomputes the label so it stays consistent), and+ raises ``anomaly_score`` to at least the behavioral signal — so a benign-+ looking alert on a wildly anomalous entity is surfaced, not buried.+ """+ if signal is None:+ return fused+ boost = _RISK_BOOST.get(signal.risk_level.lower(), 0.0)+ normalized = signal.normalized++ fused.confidence_rationale.append(+ ConfidenceFactor(+ factor="ueba_anomaly",+ label="Behavioral anomaly (UEBA)",+ value=f"{signal.entity_type}:{signal.entity_id} risk={signal.risk_level} score={signal.anomaly_score:.2f}",+ contribution=+min(0.3, normalized * 0.3),+ weight=0.12,+ )+ )+ if boost > 0.0:+ fused.confidence_score = min(1.0, (fused.confidence_score or 0.0) + boost)+ fused.confidence_label = _label_for(fused.confidence_score)+ if fused.anomaly_score is None or normalized > fused.anomaly_score:+ fused.anomaly_score = normalized++ logger.info(+ "ueba_boost_applied",+ alert_id=str(fused.id),+ entity=f"{signal.entity_type}:{signal.entity_id}",+ risk=signal.risk_level,+ )+ return fuseddiff --git a/services/fusion/app/workers/consumer.py b/services/fusion/app/workers/consumer.pyindex fd887fa9e..739ac9e53 100644--- a/services/fusion/app/workers/consumer.py+++ b/services/fusion/app/workers/consumer.py@@ -20,6 +20,7 @@ from app.services.event_schema import validate_eventfrom app.services.fusion_engine import FusionEnginefrom app.services.lake_writer import LakeWriterfrom app.services.promoter import promote_normalized_event+from app.services.ueba_signal import UebaSignalCachelogger = structlog.get_logger()@@ -48,11 +49,13 @@ class FusionWorker:dlq: DeadLetterQueue | None = None,lake: LakeWriter | None = None,detector: DetectionEngine | None = None,+ ueba_cache: UebaSignalCache | None = None,) -> None:self._engine = engineself._sink = sinkself._lake = lakeself._detector = detector+ self._ueba_cache = ueba_cache# A poison message must never vanish silently; default to a structured# logging DLQ so persistence-free deployments still get the signal.self._dlq: DeadLetterQueue = dlq or LoggingDLQ()@@ -69,8 +72,12 @@ class FusionWorker:topics = [settings.kafka_topic_alerts_raw]# Subscribe to raw_events when EITHER promotion or lake archival needs# it — the lake must fill even if promotion is turned off.- if settings.event_promotion_enabled or self._lake is not None:+ if settings.event_promotion_enabled or self._lake is not None or self._detector is not None:topics.append(settings.kafka_topic_raw_events)+ # Phase A4 — also consume the UEBA behavioral-anomaly stream so the+ # per-entity signal cache stays warm for fuse-time boosting.+ if self._ueba_cache is not None:+ topics.append(settings.kafka_topic_ueba_anomalies)self._consumer = AIOKafkaConsumer(*topics,bootstrap_servers=settings.kafka_bootstrap_servers,@@ -172,6 +179,12 @@ class FusionWorker:async def _process_message(self, payload: dict, topic: str | None = None) -> None:resolved_topic = topic or settings.kafka_topic_alerts_raw+ # Phase A4 — UEBA anomaly stream: warm the per-entity signal cache and+ # return (these are behavioral signals, not alerts).+ if self._ueba_cache is not None and topic == settings.kafka_topic_ueba_anomalies:+ await self._ueba_cache.record(payload)+ return+# Phase 5 — schema-validate the envelope BEFORE the promoter sees it.# A malformed / mis-versioned / mis-tenanted message is dead-lettered# (captured with its reason + lineage), never silently dropped.diff --git a/services/fusion/tests/test_ueba_signal.py b/services/fusion/tests/test_ueba_signal.pynew file mode 100644index 000000000..6d75f81cd--- /dev/null+++ b/services/fusion/tests/test_ueba_signal.py@@ -0,0 +1,172 @@+"""Phase A4 — UEBA behavioral-model fusion tests.++Proves the per-entity anomaly cache round-trips, the alert-entity mapping,+that a cached behavioral anomaly boosts an alert's confidence + anomaly score+(with the label recomputed), and that everything is fail-soft (no signal / bad+message / Redis error => no boost, no raise).+"""++from __future__ import annotations++import json+from uuid import uuid4++import pytest+from app.models.alert import (+ ConfidenceLabel,+ FusedAlert,+ FusionDecision,+ RawAlert,+)+from app.services.ueba_signal import (+ UebaSignal,+ UebaSignalCache,+ alert_entities,+ apply_ueba_boost,+)++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 set(self, key, value, ex=None): # noqa: ANN001, ARG002+ if self.fail:+ raise RuntimeError("redis down")+ self.store[key] = value++ async def get(self, key): # noqa: ANN001+ if self.fail:+ raise RuntimeError("redis down")+ return self.store.get(key)+++def _alert(**kw) -> RawAlert:+ base = {+ "tenant_id": TENANT,+ "source": "test",+ "title": "t",+ "username": "alice",+ "hostname": "HOST-1",+ "src_ip": "10.0.0.9",+ }+ base.update(kw)+ return RawAlert(**base)+++def _fused(alert: RawAlert, *, score: float = 0.5) -> FusedAlert:+ return FusedAlert(+ id=alert.id,+ tenant_id=alert.tenant_id,+ incident_id=uuid4(),+ fusion_decision=FusionDecision.NEW_INCIDENT,+ alert=alert,+ confidence_score=score,+ confidence_label=ConfidenceLabel.MEDIUM,+ anomaly_score=0.1,+ )+++def _ueba_msg(entity_type="user", entity_id="alice", score=4.7, risk="high") -> dict:+ return {+ "anomaly_id": str(uuid4()),+ "tenant_id": TENANT,+ "entity_type": entity_type,+ "entity_id": entity_id,+ "anomaly_score": score,+ "risk_level": risk,+ }+++# ── entity mapping ───────────────────────────────────────────────────────────+++async def test_alert_entities_maps_user_device_ip():+ ents = alert_entities(_alert())+ assert ("user", "alice") in ents+ assert ("device", "HOST-1") in ents+ assert ("ip", "10.0.0.9") in ents+++# ── cache round-trip ─────────────────────────────────────────────────────────+++async def test_record_then_lookup_returns_signal():+ cache = UebaSignalCache(_FakeRedis())+ assert await cache.record(_ueba_msg()) is True+ sig = await cache.lookup(TENANT, [("user", "alice")])+ assert sig is not None+ assert sig.risk_level == "high"+ assert sig.anomaly_score == 4.7+++async def test_lookup_returns_highest_risk_across_entities():+ r = _FakeRedis()+ cache = UebaSignalCache(r)+ await cache.record(_ueba_msg(entity_type="user", entity_id="alice", risk="low"))+ await cache.record(_ueba_msg(entity_type="device", entity_id="HOST-1", risk="critical"))+ sig = await cache.lookup(TENANT, [("user", "alice"), ("device", "HOST-1")])+ assert sig.risk_level == "critical"+++async def test_record_rejects_incomplete_message():+ cache = UebaSignalCache(_FakeRedis())+ assert await cache.record({"tenant_id": TENANT}) is False+++async def test_cache_is_failsoft_on_redis_error():+ r = _FakeRedis()+ r.fail = True+ cache = UebaSignalCache(r)+ assert await cache.record(_ueba_msg()) is False+ assert await cache.lookup(TENANT, [("user", "alice")]) is None+++async def test_lookup_miss_returns_none():+ cache = UebaSignalCache(_FakeRedis())+ assert await cache.lookup(TENANT, [("user", "nobody")]) is None+++# ── boost ────────────────────────────────────────────────────────────────────+++async def test_boost_raises_confidence_and_recomputes_label():+ alert = _alert()+ fused = _fused(alert, score=0.62) # MEDIUM+ sig = UebaSignal(entity_type="user", entity_id="alice", anomaly_score=8.0, risk_level="high")+ apply_ueba_boost(fused, sig)+ assert fused.confidence_score > 0.62+ assert fused.confidence_label == ConfidenceLabel.HIGH # 0.62 + 0.14 = 0.76+ assert any(f.factor == "ueba_anomaly" for f in fused.confidence_rationale)+ assert fused.anomaly_score >= 0.75 # high -> normalized 0.75+++async def test_boost_raises_anomaly_score_even_at_low_risk():+ alert = _alert()+ fused = _fused(alert, score=0.5)+ sig = UebaSignal(entity_type="ip", entity_id="10.0.0.9", anomaly_score=2.0, risk_level="medium")+ apply_ueba_boost(fused, sig)+ assert fused.anomaly_score >= 0.45+++async def test_no_signal_is_noop():+ alert = _alert()+ fused = _fused(alert, score=0.5)+ apply_ueba_boost(fused, None)+ assert fused.confidence_score == 0.5+ assert not any(f.factor == "ueba_anomaly" for f in fused.confidence_rationale)+++async def test_message_shape_round_trips_via_json():+ # The consumer deserialises the ueba.anomalies value as JSON; make sure a+ # realistic serialized message records cleanly.+ cache = UebaSignalCache(_FakeRedis())+ msg = json.loads(json.dumps(_ueba_msg(risk="critical")))+ assert await cache.record(msg) is True+ sig = await cache.lookup(TENANT, [("user", "alice")])+ assert sig.risk_level == "critical"