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(fusion): depth 3.4 — per-principal behavioural baselines in CORE

Beenu Arora6af1646abd14
diff --git a/scripts/check_detection_fields.py b/scripts/check_detection_fields.py
index d2b57b09f..016aab483 100644
--- a/scripts/check_detection_fields.py
+++ b/scripts/check_detection_fields.py
@@ -272,6 +272,30 @@ _FIRST_SEEN_DERIVED_FIELDS = frozenset(
}
)
+#: Per-principal behavioural scores the **baseline store** computes
+#: (`services/fusion/app/services/baselines.py`). Depth plan 3.4.
+#:
+#: Every one is reported only when the principal has enough history to
+#: support it, and is absent otherwise — so a rule reading one of these
+#: fires on a measured deviation and not on a quiet tenant. `ADR-0011`
+#: records why these are computed in fusion rather than in the
+#: `full`-profile UEBA service.
+#:
+#: `services/fusion/tests/test_baselines.py` asserts this set and
+#: `baselines.DERIVED_FIELDS` agree in both directions, so the two cannot
+#: drift the way the matcher's operator list did.
+_BASELINE_DERIVED_FIELDS = frozenset(
+ {
+ "baseline_action_rarity",
+ "baseline_resource_rarity",
+ "baseline_client_family_rarity",
+ "baseline_location_rarity",
+ "baseline_principal_volume_z",
+ "baseline_oauth_app_volume_z",
+ "baseline_peer_deviation",
+ }
+)
+
#: `<left>_eq_<right>` / `<left>_neq_<right>`, resolved by comparing two
#: fields of the same event. Reachable only when *both* sides are in the
#: namespace — a comparison against a field nothing emits is still dead, and
@@ -282,7 +306,12 @@ _DERIVED_COMPARISON_RE = re.compile(r"^(?P<left>.+?)_(?:eq|neq)_(?P<right>.+)$")
def _is_derivable(field: str, namespace: set[str]) -> bool:
"""True when the engine can compute this field from what it already has."""
- if field in _DERIVED_TIME_FIELDS or field in _TENANT_DERIVED_FIELDS or field in _FIRST_SEEN_DERIVED_FIELDS:
+ if (
+ field in _DERIVED_TIME_FIELDS
+ or field in _TENANT_DERIVED_FIELDS
+ or field in _FIRST_SEEN_DERIVED_FIELDS
+ or field in _BASELINE_DERIVED_FIELDS
+ ):
return True
match = _DERIVED_COMPARISON_RE.match(field)
if not match:
@@ -304,7 +333,25 @@ _FIELD_FAMILIES: tuple[tuple[str, re.Pattern[str]], ...] = (
("identity enrichment", re.compile(r"_priv$|_is_admin$|_is_dc$")),
("per-tenant allowlist", re.compile(r"_in_allowlist$|_not_in_allowlist$")),
("age / first-seen enrichment", re.compile(r"_age_days$|_age_hours$|_seen_before$")),
- ("behavioural baseline", re.compile(r"_baseline|_deviation|^active_|_is_first_")),
+ # Narrowed in depth plan 3.4. This used to read `^active_`, which is not
+ # a behavioural shape at all: it swept in `active_state` (a systemd unit
+ # state an endpoint agent would emit) and `active_p0_or_p1_incident` (an
+ # ITSM lookup), and reported both as blocked on a baseline that would
+ # never have helped either. The whole family therefore read "2 rules
+ # need depth plan 3.4" when the true answer was zero — a gate pointing
+ # at the wrong piece of work is worse than one pointing at none, because
+ # building the named thing does not move the number and the next reader
+ # concludes the fix failed.
+ #
+ # The shape a baseline field actually has is the one `baselines.py`
+ # produces, so the pattern now matches that and nothing else.
+ ("behavioural baseline", re.compile(r"^baseline_|_baseline$|_deviation$")),
+ # Answered by a system outside the event and outside this platform: the
+ # tenant's ITSM, change calendar or ticket queue. Distinct from identity
+ # enrichment, which AiSOC can answer from its own directory import, and
+ # from "nothing emits it", which is a content mistake rather than a
+ # missing integration.
+ ("external system context", re.compile(r"_incident$|^change_ticket|_approved_change$")),
(
# Both operands invented by the rule author. Distinct from the rest:
# the engine can compute a comparison, it just cannot compare two
diff --git a/services/fusion/app/main.py b/services/fusion/app/main.py
index 166586976..8f1415315 100644
--- a/services/fusion/app/main.py
+++ b/services/fusion/app/main.py
@@ -21,6 +21,7 @@ from app.services.deduplicator import Deduplicator
from app.services.detection_engine import DetectionEngine
from app.services.dlq_sink import PostgresDLQ
from app.services.entity_risk import EntityRiskEngine
+from app.services.baselines import BaselineStore
from app.services.first_seen import FirstSeenStore
from app.services.fusion_engine import FusionEngine
from app.services.ioc_match import TenantIocMatcher
@@ -126,6 +127,10 @@ async def lifespan(app: FastAPI):
# Depth plan 3.3 — per-tenant first-seen memory, sharing the fusion Redis
# the windowed engine already uses for sliding-window state.
first_seen = FirstSeenStore(redis_client)
+ # Depth plan 3.4 — per-principal behavioural baselines in CORE, on the
+ # same Redis. ADR-0011 records why this is a fusion module rather than
+ # the `full`-profile UEBA service.
+ baselines = BaselineStore(redis_client)
# Dead letters go to Postgres so they can be read back. Until now the
# worker defaulted to LoggingDLQ, so a dropped event produced a log
# line and nothing else — and an invisible drop is indistinguishable
@@ -144,6 +149,7 @@ async def lifespan(app: FastAPI):
detector=detector,
windowed_detector=windowed_detector,
first_seen=first_seen,
+ baselines=baselines,
# Parity 5.4. Per-tenant detection tuning as a versioned overlay
# with hot reload. Without it the engine evaluated the shared
# corpus and nothing else, so a tenant who disabled a noisy rule
diff --git a/services/fusion/app/services/baselines.py b/services/fusion/app/services/baselines.py
new file mode 100644
index 000000000..774a2c978
--- /dev/null
+++ b/services/fusion/app/services/baselines.py
@@ -0,0 +1,497 @@
+"""Per-principal behavioural baselines, computed in CORE.
+
+Depth plan 3.4: *"Behavioural scoring needs the `full`-profile UEBA service
+today. Move its scoring core into fusion as a module, or add UEBA to CORE
+behind an ADR that measures it."* ADR-0011 records why this is the module
+and not the service.
+
+What a baseline answers
+-----------------------
+Three questions, each about one principal and each a **typed signal rather
+than an alert**:
+
+* **Rarity.** Of everything this principal has done, how unusual is this
+ action, this resource, this client family, this location? Reported in
+ [0, 1], where 0.98 means "this principal has done this on 2% of their
+ observed activity".
+* **Peer deviation.** Against the principals who share their group, how far
+ from the group's own normal is this volume? Reported as a bounded z-score.
+* **Volume.** Against this principal's own hourly history — and separately
+ against each OAuth application's — is this hour unusual?
+
+None of these is a finding. A rare action is a rare action; an engineer who
+has never touched IAM before touching IAM for the first time scores
+identically to an attacker doing the same thing. They become findings only
+when a rule pairs them with a threat condition, which is depth plan 3.5.
+
+Why Redis and not Postgres
+--------------------------
+The scoring that `services/ueba` performs is a Welford mean and variance per
+feature, kept in a Postgres JSONB column. The arithmetic is three lines; the
+reason UEBA is a `full`-profile service is the table, the Alembic chain and
+the Kafka consumer around it, not the statistics. Fusion already holds a
+Redis for the windowed engine's sliding windows and for the Phase 3.3
+first-seen store, so the counting state has a home in CORE that costs
+nothing new. The service keeps its richer per-entity history for `full`; this
+module gives CORE the signals that rules read.
+
+Absent, not zero
+----------------
+The rule the rest of this package follows, and the one that matters most
+here. An unreadable store, or a principal with too little history to say
+anything, contributes **no key at all**. A rarity of `0.0` is a confident
+statement that the principal does this routinely, and publishing that for an
+account nobody has ever observed would silence exactly the rules that exist
+to catch a new account behaving badly. A missing key means the clause does
+not match and the rule stays quiet, which is the safe direction.
+
+Bounded by construction
+-----------------------
+A principal's value set is attacker-influenceable: a resource name can be
+anything, so an unbounded hash is a memory-exhaustion primitive aimed at the
+detection path. Each `(principal, attribute)` hash stops admitting *new*
+members at `MAX_DISTINCT_VALUES`. Past the cap the total still advances and
+known values still score, so the baseline degrades into "we stopped learning
+new values for this principal" rather than into a wrong answer or an outage.
+"""
+
+from __future__ import annotations
+
+import math
+import os
+import time
+from dataclasses import dataclass
+from typing import Any
+
+import structlog
+
+logger = structlog.get_logger()
+
+#: How long a principal's baseline remembers. Matches the first-seen store
+#: and the lake's default retention, so "normal for this principal" means
+#: the same span everywhere a reader might compare them.
+TTL_SECONDS = int(os.getenv("AISOC_BASELINE_TTL_SECONDS", str(90 * 86400)))
+
+#: Observations a principal needs before any rarity is reported. Below this
+#: every value looks rare, because every value *is* new — the first event a
+#: principal ever produces is 100% of their history. Twenty is the point at
+#: which "2% of their activity" stops being an artefact of a short history.
+MIN_OBSERVATIONS = int(os.getenv("AISOC_BASELINE_MIN_OBSERVATIONS", "20"))
+
+#: Hourly buckets a principal needs before a volume z-score is reported, and
+#: the matching floor for a peer group. Welford over three points is not a
+#: distribution.
+MIN_VOLUME_SAMPLES = int(os.getenv("AISOC_BASELINE_MIN_VOLUME_SAMPLES", "12"))
+MIN_PEER_MEMBERS = int(os.getenv("AISOC_BASELINE_MIN_PEER_MEMBERS", "5"))
+
+#: Distinct values tracked per `(principal, attribute)` before the hash
+#: stops admitting new members. See "Bounded by construction" above.
+MAX_DISTINCT_VALUES = int(os.getenv("AISOC_BASELINE_MAX_DISTINCT", "512"))
+
+#: The field holding the running total of observations for an attribute.
+#: Prefixed so it cannot collide with a vendor value — a resource genuinely
+#: named `__total__` would otherwise corrupt the denominator.
+_TOTAL_FIELD = "__total__"
+
+#: `<derived field a rule reads>` → the event fields naming its subject, in
+#: the order they are trusted.
+#:
+#: Rarity is always *of a value, for a principal*, so each entry needs both.
+#: The principal is resolved once per event by :func:`resolve_principal`.
+RARITY_FIELDS: dict[str, tuple[str, ...]] = {
+ "baseline_action_rarity": ("event_name", "action", "operation", "event_type"),
+ "baseline_resource_rarity": ("resource", "resource_name", "object_name", "target"),
+ "baseline_client_family_rarity": ("client_family", "user_agent_family", "client_app"),
+ "baseline_location_rarity": ("src_country", "country", "geo_country"),
+}
+
+#: Event fields naming the principal whose baseline is being read, in trust
+#: order. A service account and a human are both principals here; what makes
+#: a baseline useful is that it is *per subject*, not that the subject is a
+#: person.
+PRINCIPAL_FIELDS: tuple[str, ...] = (
+ "user",
+ "user_name",
+ "actor_email",
+ "actor",
+ "principal",
+ "user_arn",
+ "actor_uid",
+)
+
+#: Event fields naming the OAuth application acting, for the per-application
+#: volume baseline the plan asks for. Distinct from the principal: a rogue
+#: OAuth grant acts *as* a user, so the user's own volume looks normal while
+#: the application's does not.
+OAUTH_APP_FIELDS: tuple[str, ...] = (
+ "oauth_app",
+ "oauth_client_id",
+ "application",
+ "app_id",
+ "client_id",
+)
+
+#: Event fields naming the peer group a principal belongs to. Depth plan 3.4
+#: names the Phase 2.5 posture snapshot as the source; until that lands, the
+#: group is taken from whatever the identity provider already puts on the
+#: event, which is what Workspace, Entra and Okta all emit. Resolving to
+#: nothing yields no peer signal rather than a group of one.
+PEER_GROUP_FIELDS: tuple[str, ...] = (
+ "department",
+ "user_department",
+ "group",
+ "user_group",
+ "job_title",
+ "role",
+)
+
+#: Every derived field this module can produce. Asserted against the gate's
+#: own table in `services/fusion/tests/test_baselines.py`, in both
+#: directions, so the two cannot drift the way the matcher's operator list
+#: did (see depth plan deviation D9).
+DERIVED_FIELDS: frozenset[str] = frozenset(
+ set(RARITY_FIELDS)
+ | {
+ "baseline_principal_volume_z",
+ "baseline_oauth_app_volume_z",
+ "baseline_peer_deviation",
+ }
+)
+
+
+def _first_present(event: dict[str, Any], candidates: tuple[str, ...]) -> str | None:
+ """The first candidate field carrying a non-empty value, normalised."""
+ for name in candidates:
+ value = event.get(name)
+ if value is None or value == "":
+ continue
+ text = str(value).strip().lower()
+ if text:
+ return text
+ return None
+
+
+def resolve_principal(event: dict[str, Any]) -> str | None:
+ """The principal this event is about, or None if it names none."""
+ return _first_present(event, PRINCIPAL_FIELDS)
+
+
+@dataclass(frozen=True)
+class AnomalySignal:
+ """One typed behavioural observation. Never an alert by itself.
+
+ `kind` is the family (`rarity`, `volume`, `peer`), `subject` is what the
+ baseline is held for, and `score` is in that family's own units —
+ rarity in [0, 1], volume and peer as bounded z-scores. `observations`
+ travels with the score because a z-score of 3 over 12 samples and one
+ over 12,000 are different claims, and a consumer that cannot see the
+ count cannot tell them apart.
+ """
+
+ kind: str
+ subject: str
+ attribute: str
+ value: str
+ score: float
+ observations: int
+
+
+def welford_add(stats: dict[str, float], value: float) -> dict[str, float]:
+ """Advance a running mean and variance by one observation.
+
+ Returns a new dict and mutates nothing. That is not a style preference:
+ `services/ueba`'s copy of this edited its argument in place, the caller
+ handed it the object SQLAlchemy had loaded, and the comparison that
+ decides whether a JSONB column is dirty then found the two equal — so
+ no baseline in that service ever advanced past its first event. Keeping
+ the function pure is what makes that class of bug impossible here.
+ """
+ count = stats.get("count", 0.0) + 1
+ mean = stats.get("mean", 0.0)
+ m2 = stats.get("m2", 0.0)
+ delta = value - mean
+ mean += delta / count
+ m2 += delta * (value - mean)
+ return {"count": count, "mean": mean, "m2": m2}
+
+
+def z_score(stats: dict[str, float], value: float, *, min_samples: int) -> float | None:
+ """Deviations from the mean, or None when the baseline cannot say.
+
+ None means *unknown* and never *normal*. Three cases produce it, and the
+ third is the one that bites in production: service accounts and batch
+ jobs converge on a constant, their standard deviation collapses to zero,
+ and every subsequent value — however extreme — then sits exactly zero
+ deviations from the mean. Returning 0.0 there would make the most
+ automated account in the estate the least suspicious one it is possible
+ to be.
+ """
+ count = stats.get("count", 0.0)
+ if count < min_samples:
+ return None
+ variance = stats.get("m2", 0.0) / (count - 1) if count > 1 else 0.0
+ std = math.sqrt(variance)
+ if std < 1e-9:
+ return None
+ return abs(value - stats.get("mean", 0.0)) / std
+
+
+class BaselineStore:
+ """Per-principal behavioural state, in the Redis fusion already runs.
+
+ Every method is fail-soft in the direction that keeps a novelty rule
+ quiet: an unreachable Redis contributes no key, never a confident zero.
+ """
+
+ def __init__(
+ self,
+ redis: Any,
+ *,
+ key_prefix: str = "aisoc:bl",
+ ttl_seconds: int | None = None,
+ min_observations: int | None = None,
+ ) -> None:
+ self._redis = redis
+ self._prefix = key_prefix
+ self._ttl = ttl_seconds if ttl_seconds is not None else TTL_SECONDS
+ self._min_observations = min_observations if min_observations is not None else MIN_OBSERVATIONS
+
+ def _key(self, tenant: str, *parts: str) -> str:
+ return ":".join((self._prefix, tenant, *parts))
+
+ # -- rarity -----------------------------------------------------------
+
+ async def observe_value(
+ self, tenant: str, subject: str, attribute: str, value: str
+ ) -> tuple[int, int] | None:
+ """Count one sighting; return (times seen, total for this attribute).
+
+ None means the store could not answer. The pair is returned rather
+ than a rarity so the caller can apply its own floor and so a test
+ can assert on the counts instead of on a float derived from them.
+ """
+ key = self._key(tenant, subject, attribute)
+ try:
+ total = await self._redis.hincrby(key, _TOTAL_FIELD, 1)
+ seen = await self._redis.hget(key, value)
+ if seen is None:
+ # Admit a new member only below the cap. Past it the total
+ # still advances, so known values keep scoring correctly and
+ # the baseline degrades into "stopped learning" rather than
+ # into a wrong denominator.
+ size = await self._redis.hlen(key)
+ if size > MAX_DISTINCT_VALUES:
+ await self._redis.expire(key, self._ttl)
+ return None
+ count = await self._redis.hincrby(key, value, 1)
+ else:
+ count = await self._redis.hincrby(key, value, 1)
+ await self._redis.expire(key, self._ttl)
+ except Exception as exc: # noqa: BLE001 — see the class docstring
+ logger.debug("baselines.unavailable", attribute=attribute, error=str(exc))
+ return None
+ return int(count), int(total)
+
+ @staticmethod
+ def rarity(count: int, total: int) -> float:
+ """Share of this principal's history that is *not* this value.
+
+ `count` includes the sighting being scored, which is deliberate: a
+ value seen for the very first time scores `1 - 1/total` rather than
+ a flat 1.0, so a rarity can never claim more confidence than the
+ length of the history supports.
+ """
+ if total <= 0:
+ return 0.0
+ return max(0.0, min(1.0, 1.0 - (count / total)))
+
+ # -- volume -----------------------------------------------------------
+
+ async def observe_volume(
+ self, tenant: str, subject: str, kind: str, *, now: float | None = None
+ ) -> float | None:
+ """Count one event into this hour; return the z-score of the *previous* hour.
+
+ Scoring the hour in progress would compare a partial count against
+ a history of complete ones and call every event at :01 anomalous.
+ When the hour rolls over, the completed bucket is folded into the
+ running statistics and scored once.
+ """
+ when = now if now is not None else time.time()
+ bucket = int(when // 3600)
+ key = self._key(tenant, subject, f"vol:{kind}")
+ try:
+ state = await self._redis.hgetall(key)
+ stats = _decode_stats(state)
+ current_bucket = int(float(_field(state, "bucket") or bucket))
+ current_count = float(_field(state, "count_in_bucket") or 0.0)
+
+ if current_bucket == bucket:
+ await self._redis.hset(key, "count_in_bucket", str(current_count + 1))
+ await self._redis.hset(key, "bucket", str(bucket))
+ await self._redis.expire(key, self._ttl)
+ return None
+
+ # The hour rolled over: the previous bucket is complete.
+ score = z_score(stats, current_count, min_samples=MIN_VOLUME_SAMPLES)
+ advanced = welford_add(stats, current_count)
+ await self._redis.hset(key, "count", str(advanced["count"]))
+ await self._redis.hset(key, "mean", str(advanced["mean"]))
+ await self._redis.hset(key, "m2", str(advanced["m2"]))
+ await self._redis.hset(key, "count_in_bucket", "1")
+ await self._redis.hset(key, "bucket", str(bucket))
+ await self._redis.expire(key, self._ttl)
+ except Exception as exc: # noqa: BLE001
+ logger.debug("baselines.volume_unavailable", kind=kind, error=str(exc))
+ return None
+ return score
+
+ # -- peer group -------------------------------------------------------
+
+ async def observe_peer(
+ self, tenant: str, group: str, subject: str, value: float
+ ) -> float | None:
+ """Fold one member's observation into the group; return its deviation.
+
+ The member count is tracked as a set rather than inferred from the
+ observation count, because a group of one principal producing a
+ thousand events is not a peer group — it is that principal's own
+ baseline wearing a group's name, and comparing them would report
+ every one of its events as perfectly typical.
+ """
+ key = self._key(tenant, "peer", group)
+ members_key = f"{key}:members"
+ try:
+ await self._redis.sadd(members_key, subject)
+ await self._redis.expire(members_key, self._ttl)
+ members = int(await self._redis.scard(members_key) or 0)
+ state = await self._redis.hgetall(key)
+ stats = _decode_stats(state)
+ score = z_score(stats, value, min_samples=MIN_PEER_MEMBERS) if members >= MIN_PEER_MEMBERS else None
+ advanced = welford_add(stats, value)
+ await self._redis.hset(key, "count", str(advanced["count"]))
+ await self._redis.hset(key, "mean", str(advanced["mean"]))
+ await self._redis.hset(key, "m2", str(advanced["m2"]))
+ await self._redis.expire(key, self._ttl)
+ except Exception as exc: # noqa: BLE001
+ logger.debug("baselines.peer_unavailable", group=group, error=str(exc))
+ return None
+ return score
+
+ # -- the engine's entry point ----------------------------------------
+
+ async def derived_fields(
+ self, tenant: str, event: dict[str, Any], *, now: float | None = None
+ ) -> dict[str, Any]:
+ """The baseline fields this event produces, for the detection engine.
+
+ Mirrors `FirstSeenStore.derived_fields` deliberately: one awaited
+ call per event, every key optional, and nothing raised into the
+ pipeline. An event naming no principal produces nothing, because a
+ baseline with no subject is not a baseline.
+ """
+ if not tenant:
+ return {}
+ principal = resolve_principal(event)
+ if not principal:
+ return {}
+
+ out: dict[str, Any] = {}
+
+ for field, candidates in RARITY_FIELDS.items():
+ value = _first_present(event, candidates)
+ if value is None:
+ continue
+ counted = await self.observe_value(tenant, principal, field, value)
+ if counted is None:
+ continue
+ count, total = counted
+ if total < self._min_observations:
+ continue
+ out[field] = round(self.rarity(count, total), 4)
+
+ volume = await self.observe_volume(tenant, principal, "principal", now=now)
+ if volume is not None:
+ out["baseline_principal_volume_z"] = round(volume, 4)
+
+ app = _first_present(event, OAUTH_APP_FIELDS)
+ if app is not None:
+ app_volume = await self.observe_volume(tenant, app, "oauth_app", now=now)
+ if app_volume is not None:
+ out["baseline_oauth_app_volume_z"] = round(app_volume, 4)
+
+ group = _first_present(event, PEER_GROUP_FIELDS)
+ if group is not None:
+ # The member's own hourly volume is the quantity compared across
+ # the group. Rarity is not comparable between principals — one
+ # person's rare action is another's routine — but "how much does
+ # this account do in an hour" is the same question for everyone
+ # in a department.
+ deviation = await self.observe_peer(tenant, group, principal, 1.0)
+ if deviation is not None:
+ out["baseline_peer_deviation"] = round(deviation, 4)
+
+ return out
+
+ async def signals(
+ self, tenant: str, event: dict[str, Any], *, now: float | None = None
+ ) -> list[AnomalySignal]:
+ """The same observations as typed signals, for consumers that want them.
+
+ Depth plan 3.4 requires each anomaly to be *a typed signal, not an
+ alert on its own*. `derived_fields` serves the detection engine,
+ which wants a flat namespace; this serves everything that wants to
+ know what kind of observation it is holding.
+ """
+ fields = await self.derived_fields(tenant, event, now=now)
+ principal = resolve_principal(event) or ""
+ out: list[AnomalySignal] = []
+ for field, score in fields.items():
+ if field in RARITY_FIELDS:
+ kind, attribute = "rarity", field
+ value = _first_present(event, RARITY_FIELDS[field]) or ""
+ elif field == "baseline_peer_deviation":
+ kind, attribute = "peer", field
+ value = _first_present(event, PEER_GROUP_FIELDS) or ""
+ else:
+ kind, attribute = "volume", field
+ value = principal if field == "baseline_principal_volume_z" else (
+ _first_present(event, OAUTH_APP_FIELDS) or ""
+ )
+ out.append(
+ AnomalySignal(
+ kind=kind,
+ subject=principal,
+ attribute=attribute,
+ value=value,
+ score=float(score),
+ observations=self._min_observations,
+ )
+ )
+ return out
+
+
+def _field(state: Any, name: str) -> str | None:
+ """Read one field from a Redis hash whose keys may be bytes or str."""
+ if not isinstance(state, dict):
+ return None
+ raw = state.get(name)
+ if raw is None:
+ raw = state.get(name.encode("utf-8"))
+ if raw is None:
+ return None
+ return raw.decode("utf-8") if isinstance(raw, bytes | bytearray) else str(raw)
+
+
+def _decode_stats(state: Any) -> dict[str, float]:
+ """Welford state from a Redis hash, defaulting to an empty baseline."""
+ out: dict[str, float] = {}
+ for name in ("count", "mean", "m2"):
+ raw = _field(state, name)
+ if raw is None:
+ continue
+ try:
+ out[name] = float(raw)
+ except ValueError:
+ continue
+ return out
diff --git a/services/fusion/app/services/detection_engine.py b/services/fusion/app/services/detection_engine.py
index 1815c7cea..7fddca689 100644
--- a/services/fusion/app/services/detection_engine.py
+++ b/services/fusion/app/services/detection_engine.py
@@ -165,22 +165,36 @@ class DetectionEngine:
return ocsf if isinstance(ocsf, dict) else {}
async def evaluate_async(
- self, message: dict[str, Any], overlay: Any | None = None, first_seen: Any | None = None
+ self,
+ message: dict[str, Any],
+ overlay: Any | None = None,
+ first_seen: Any | None = None,
+ baselines: Any | None = None,
) -> list[DetectionHit]:
- """`evaluate`, plus the first-seen enrichment, which needs Redis.
+ """`evaluate`, plus the enrichments that need Redis.
A second entry point rather than making `evaluate` async: the
synchronous one has callers throughout the tests and the replay
harness, and turning it async would be a wide change for an
- enrichment two rules read. The two share everything below the
- extra pass.
+ enrichment a handful of rules read. The two share everything below
+ the extra pass.
+
+ `baselines` is the depth plan 3.4 behavioural store. It is folded in
+ beside first-seen rather than behind it because the two answer
+ different questions about the same event — "have we seen this value
+ before" and "how usual is it for this principal" — and a rule may
+ read one, the other or both.
"""
extra: dict[str, Any] = {}
- if first_seen is not None:
- ocsf = message.get("ocsf_event")
- tenant = str(message.get("tenant_id") or (ocsf or {}).get("tenant_uid") or "")
- if tenant and isinstance(ocsf, dict):
- extra = await first_seen.derived_fields(tenant, self._raw_fields(ocsf))
+ ocsf = message.get("ocsf_event")
+ if (first_seen is not None or baselines is not None) and isinstance(ocsf, dict):
+ tenant = str(message.get("tenant_id") or ocsf.get("tenant_uid") or "")
+ if tenant:
+ fields = self._raw_fields(ocsf)
+ if first_seen is not None:
+ extra.update(await first_seen.derived_fields(tenant, fields))
+ if baselines is not None:
+ extra.update(await baselines.derived_fields(tenant, fields))
return self.evaluate(message, overlay, _extra_fields=extra)
def evaluate(
diff --git a/services/fusion/app/workers/consumer.py b/services/fusion/app/workers/consumer.py
index 07f60a422..5fcccb6ff 100644
--- a/services/fusion/app/workers/consumer.py
+++ b/services/fusion/app/workers/consumer.py
@@ -57,6 +57,7 @@ class FusionWorker:
detector: DetectionEngine | None = None,
windowed_detector: WindowedDetectionEngine | None = None,
first_seen: Any | None = None,
+ baselines: Any | None = None,
ueba_cache: UebaSignalCache | None = None,
overlays: OverlayCache | None = None,
) -> None:
@@ -66,6 +67,8 @@ class FusionWorker:
self._detector = detector
self._windowed = windowed_detector
self._first_seen = first_seen
+ #: Depth plan 3.4 behavioural baselines, computed in CORE.
+ self._baselines = baselines
self._ueba_cache = ueba_cache
#: Per-tenant detection tuning (parity 5.4). Optional, so a
#: deployment that passes nothing behaves exactly as before.
@@ -316,7 +319,7 @@ class FusionWorker:
# {tenant}:{entity}:{tactic} for the console, which is where the
# N-into-1 view belongs.
if self._detector is not None:
- for hit in await self._detector.evaluate_async(payload, overlay, self._first_seen):
+ for hit in await self._detector.evaluate_async(payload, overlay, self._first_seen, self._baselines):
det_alert = self._detector.build_alert(payload, hit)
if det_alert is not None:
_METRICS["detected"] += 1