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
fix(ueba): distinguish unscoreable baselines from normal behaviour (#606)
kaaan11ee79c54cf73f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 848bd259e..888d947a1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **UEBA can no longer read an unscoreable baseline as normal behaviour.** A+ feature that had never been observed, had too few samples, or had zero+ variance produced a `0.0` z-score — the same value an observation sitting+ exactly on its own mean produces. Since the composite is a root-sum-of-+ squares, that zero contributed nothing and the entity read as all-clear;+ service accounts, batch jobs and automation users converge on a constant+ stream, so they could not raise an anomaly at all. `compute_z_score` now+ returns `None` for these cases and callers exclude it. Per-feature composites+ are unchanged (`0.0 ** 2` already contributed nothing), but a peer group+ whose features are all degenerate now yields no peer signal instead of a+ `0.0` that halved the caller's personal composite — a `critical` score was+ being reported as `medium`. Affected feature names are logged at `info`.+ A new `MIN_BASELINE_SAMPLES` setting (default 30) gates the sample count.+- **Agent investigations are now persisted to the ledger (issue #601).** Thedemo seed renames the canonical seed tenant's slug from `default` to `demo`,so the agents service's `tenant_ref="default"` fallback matched no tenant anddiff --git a/services/ueba/Dockerfile b/services/ueba/Dockerfileindex d2b8e398c..2ec758035 100644--- a/services/ueba/Dockerfile+++ b/services/ueba/Dockerfile@@ -26,6 +26,7 @@ RUN pip install --no-cache-dir \"numpy>=1.26.0" \"scipy>=1.12.0" \"httpx>=0.27.0" \+ "structlog>=24.1,<27.0" \"opentelemetry-sdk>=1.24.0" \"opentelemetry-exporter-otlp>=1.24.0" \"opentelemetry-instrumentation-fastapi>=0.45b0"diff --git a/services/ueba/app/core/config.py b/services/ueba/app/core/config.pyindex 4482180ac..5f5e1cbf6 100644--- a/services/ueba/app/core/config.py+++ b/services/ueba/app/core/config.py@@ -44,6 +44,10 @@ class Settings(BaseSettings):default=3,validation_alias=AliasChoices("PEER_GROUP_MIN_SIZE", "UEBA_PEER_GROUP_MIN_SIZE"),)+ min_baseline_samples: int = Field(+ default=30,+ validation_alias=AliasChoices("MIN_BASELINE_SAMPLES", "UEBA_MIN_BASELINE_SAMPLES"),+ )scoring_batch_size: int = Field(default=100,validation_alias=AliasChoices("SCORING_BATCH_SIZE", "UEBA_SCORING_BATCH_SIZE"),diff --git a/services/ueba/app/services/baseline.py b/services/ueba/app/services/baseline.pyindex 7325a76fb..a209e4e9f 100644--- a/services/ueba/app/services/baseline.py+++ b/services/ueba/app/services/baseline.py@@ -59,14 +59,43 @@ def compute_z_score(stats: dict[str, dict[str, float]],feature: str,value: float,-) -> float:- """Return the z-score of *value* given the baseline stats for *feature*."""+ *,+ min_samples: int | None = None,+) -> float | None:+ """Return the z-score of *value* given the baseline stats for *feature*.++ Returns ``None`` when the baseline cannot produce a meaningful score: the+ feature has never been observed, fewer than *min_samples* events have been+ recorded, or the observed variance is degenerate. The degenerate case is+ not an edge case in practice — service accounts, batch jobs and automation+ users converge on a constant stream, so their standard deviation collapses+ to zero and every subsequent value, however extreme, sits zero deviations+ from the mean.++ ``None`` means "unknown", not "normal". Returning ``0.0`` for these cases+ made an unscoreable entity indistinguishable from one sitting exactly on+ its own mean, and the RSS composite reads that as all-clear. Callers must+ skip ``None`` rather than coerce it to a number.+ ``peer_group.deviation_score`` already draws this distinction — this brings+ the personal-baseline path in line with it.+ """+ threshold = settings.min_baseline_samples if min_samples is None else min_samples++ # 1. No baseline recorded for this feature at all.if feature not in stats:- return 0.0+ return None+s = stats[feature]++ # 2. Too few observations for the sample variance to carry information.+ if s.get("count", 0) < threshold:+ return None++ # 3. Degenerate distribution — every observation identical.std = s.get("std", 0.0)if std < 1e-9:- return 0.0+ return None+return abs(value - s["mean"]) / std@@ -132,12 +161,17 @@ class BaselineService:entity_type: str,entity_id: str,features: dict[str, float],- ) -> dict[str, dict[str, float]]:- """Return per-feature z-scores (does not mutate the baseline)."""+ ) -> dict[str, dict[str, float | None]]:+ """Return per-feature z-scores (does not mutate the baseline).++ ``z_score`` is ``None`` for features whose baseline cannot be scored;+ ``value``/``mean``/``std`` are still populated so the UI can show what+ little is known about the entity.+ """baseline = await self.get_or_create(tenant_id, entity_type, entity_id)stats = baseline.feature_stats- scored: dict[str, dict[str, float]] = {}+ scored: dict[str, dict[str, float | None]] = {}for feature, value in features.items():z = compute_z_score(stats, feature, value)feat_stats = stats.get(feature, {})diff --git a/services/ueba/app/services/peer_group.py b/services/ueba/app/services/peer_group.pyindex d6baab028..864cd38cd 100644--- a/services/ueba/app/services/peer_group.py+++ b/services/ueba/app/services/peer_group.py@@ -93,11 +93,19 @@ class PeerGroupService:return None# Check minimum sample size- first_feat_count = next(iter(stats.values()), {}).get("count", 0)+ first_feat: dict[str, float] = next(iter(stats.values()), {})+ first_feat_count = first_feat.get("count", 0)if first_feat_count < settings.peer_group_min_size:return None- z_scores = [compute_z_score(stats, f, v) for f, v in features.items() if f in stats]+ # ``None`` marks a feature whose peer baseline cannot be scored; keeping+ # it out means a group of uniformly-degenerate features yields no peer+ # signal at all, rather than a 0.0 that halves the caller's composite.+ z_scores = [+ z+ for z in (compute_z_score(stats, f, v) for f, v in features.items())+ if z is not None+ ]if not z_scores:return Nonediff --git a/services/ueba/app/services/scoring.py b/services/ueba/app/services/scoring.pyindex 2fc53ed58..73c041489 100644--- a/services/ueba/app/services/scoring.py+++ b/services/ueba/app/services/scoring.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport mathimport uuid+import structlogfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.config import settings@@ -16,6 +17,8 @@ from app.models.ueba import UEBAAnomalyfrom app.services.baseline import BaselineServicefrom app.services.peer_group import PeerGroupService+logger = structlog.get_logger(__name__)+def _risk_level(score: float) -> str:if score >= 6.0:@@ -27,11 +30,27 @@ def _risk_level(score: float) -> str:return "low"-def _composite_score(scored_features: dict[str, dict[str, float]]) -> float:- """Root-sum-of-squares of individual z-scores (capped at 10)."""- if not scored_features:+def _unscoreable_features(scored_features: dict[str, dict[str, float | None]]) -> list[str]:+ """Names of features whose baseline could not produce a z-score."""+ return sorted(f for f, s in scored_features.items() if s.get("z_score") is None)+++def _composite_score(scored_features: dict[str, dict[str, float | None]]) -> float:+ """Root-sum-of-squares of individual z-scores (capped at 10).++ Features with a ``None`` z-score are excluded rather than counted as zero.+ RSS has no per-feature denominator and ``0.0 ** 2`` adds nothing, so this+ leaves every existing composite unchanged; it only stops an unscoreable+ feature from being *reported* as a normal one.+ """+ z_scores: list[float] = []+ for stats in scored_features.values():+ z = stats.get("z_score")+ if z is not None:+ z_scores.append(z)+ if not z_scores:return 0.0- rss = math.sqrt(sum(f["z_score"] ** 2 for f in scored_features.values()))+ rss = math.sqrt(sum(z**2 for z in z_scores))return min(rss, 10.0)@@ -57,6 +76,26 @@ class ScoringService:scored = await self._baseline.score_features(tenant_id, entity_type, entity_id, features)composite = _composite_score(scored)+ # An entity whose baseline cannot be scored produces no anomaly and,+ # before this, no record of any kind — it simply never appeared. Say so+ # once per event so the gap is visible to an operator instead of+ # looking like a clean result.+ unscoreable = _unscoreable_features(scored)+ if unscoreable:+ logger.info(+ "ueba.features_unscoreable",+ tenant_id=str(tenant_id),+ entity_type=entity_type,+ entity_id=entity_id,+ features=unscoreable,+ scored_count=len(scored) - len(unscoreable),+ hint=(+ "baseline has zero variance or fewer than "+ f"{settings.min_baseline_samples} samples; automation and service "+ "accounts converge here and cannot be scored by deviation"+ ),+ )+# 2. Update baseline with this eventawait self._baseline.update(tenant_id, entity_type, entity_id, features)diff --git a/services/ueba/pyproject.toml b/services/ueba/pyproject.tomlindex f8f9a4053..d6d28078d 100644--- a/services/ueba/pyproject.toml+++ b/services/ueba/pyproject.toml@@ -19,6 +19,7 @@ dependencies = ["numpy>=1.26.0","scipy>=1.12.0","httpx>=0.27.0",+ "structlog>=24.1,<27.0","opentelemetry-sdk>=1.24.0","opentelemetry-exporter-otlp>=1.24.0","opentelemetry-instrumentation-fastapi>=0.45b0",diff --git a/services/ueba/tests/test_baseline_scoring.py b/services/ueba/tests/test_baseline_scoring.pynew file mode 100644index 000000000..2865bfa48--- /dev/null+++ b/services/ueba/tests/test_baseline_scoring.py@@ -0,0 +1,222 @@+"""Characterisation tests for the UEBA scoring core.++`_welford_update`, `compute_z_score`, `_composite_score` and `_risk_level` are+the whole detection path for personal baselines, and none of them were covered+by a test — CI's own comment claims "config loader + risk scoring core" but all+six existing cases live in `test_config.py`.++A baseline that *cannot* be scored — unknown feature, fewer than+`min_baseline_samples` observations, or zero variance — must return `None`, not+`0.0`. `0.0` is indistinguishable from an observation sitting exactly on its own+mean, so the RSS composite read "no signal" as "all clear"; service accounts,+batch jobs and automation users converge on a constant stream and could never+raise an anomaly.+"""+from __future__ import annotations++import math++import pytest+from app.services.baseline import _welford_update, compute_z_score+from app.services.scoring import (+ _composite_score,+ _risk_level,+ _unscoreable_features,+)+++def _feed(values: list[float], feature: str = "f") -> dict[str, dict[str, float]]:+ """Replay *values* through the online updater, as the service does per event."""+ stats: dict[str, dict[str, float]] = {}+ for v in values:+ stats = _welford_update(stats, feature, v)+ return stats+++def _scored(*z_scores: float) -> dict[str, dict[str, float]]:+ """Build a `score_features`-shaped payload carrying the given z-scores."""+ return {+ f"feature_{i}": {"value": 0.0, "mean": 0.0, "std": 1.0, "z_score": z}+ for i, z in enumerate(z_scores)+ }+++class TestWelfordUpdate:+ """The online mean/variance itself is correct — this must not regress."""++ def test_first_observation_has_no_variance_yet(self):+ # n=1: the n-1 denominator is undefined, so the code yields 0.0.+ stats = _feed([10.0])["f"]+ assert stats["count"] == 1+ assert stats["mean"] == pytest.approx(10.0)+ assert stats["M2"] == pytest.approx(0.0)+ assert stats["std"] == pytest.approx(0.0)++ def test_mean_and_sample_std_match_textbook_values(self):+ # sample std of [2,4,4,4,5,5,7,9] is sqrt(32/7) with the n-1 denominator+ stats = _feed([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0])["f"]+ assert stats["count"] == 8+ assert stats["mean"] == pytest.approx(5.0)+ assert stats["std"] == pytest.approx(math.sqrt(32.0 / 7.0))++ def test_constant_stream_keeps_std_at_zero(self):+ # A service account doing the same thing every day drives std -> 0.+ stats = _feed([100.0] * 200)["f"]+ assert stats["count"] == 200+ assert stats["mean"] == pytest.approx(100.0)+ assert stats["std"] == pytest.approx(0.0)++ def test_features_are_tracked_independently(self):+ stats: dict[str, dict[str, float]] = {}+ stats = _welford_update(stats, "bytes_out", 1.0)+ stats = _welford_update(stats, "hosts_touched", 50.0)+ stats = _welford_update(stats, "bytes_out", 3.0)+ assert stats["bytes_out"]["count"] == 2+ assert stats["hosts_touched"]["count"] == 1+ assert stats["bytes_out"]["mean"] == pytest.approx(2.0)+++class TestComputeZScoreEstablishedBaseline:+ """The healthy path — an established baseline with real variance.++ These fixtures hold five observations and pass ``min_samples=5`` so they+ exercise the scoring arithmetic rather than the sample-count gate, which+ has its own tests below.+ """++ def test_scores_value_against_baseline(self):+ stats = _feed([10.0, 12.0, 14.0, 11.0, 13.0])+ s = stats["f"]+ assert compute_z_score(stats, "f", 20.0, min_samples=5) == pytest.approx(+ abs(20.0 - s["mean"]) / s["std"]+ )++ def test_deviation_is_absolute_in_both_directions(self):+ stats = _feed([10.0, 12.0, 14.0, 11.0, 13.0])+ assert compute_z_score(stats, "f", 0.0, min_samples=5) > 0.0+ assert compute_z_score(stats, "f", 24.0, min_samples=5) > 0.0++ def test_value_at_the_mean_scores_zero(self):+ # A genuinely normal observation still scores 0.0 — this is the value+ # that must stay distinct from the unscoreable None below.+ stats = _feed([10.0, 12.0, 14.0, 11.0, 13.0])+ assert compute_z_score(+ stats, "f", stats["f"]["mean"], min_samples=5+ ) == pytest.approx(0.0)++ def test_defaults_to_the_configured_sample_gate(self):+ # Thirty observations clear settings.min_baseline_samples unaided.+ stats = _feed([10.0, 12.0, 14.0, 11.0, 13.0] * 6)+ assert compute_z_score(stats, "f", 40.0) is not None+++class TestComputeZScoreUnscoreable:+ """Every path that cannot produce a score must return None, not 0.0."""++ def test_never_seen_feature_is_unscoreable(self):+ # No baseline at all for this feature — nothing to deviate from.+ stats = _feed([10.0, 12.0, 14.0] * 10)+ assert compute_z_score(stats, "never_observed", 9999.0) is None++ def test_missing_std_key_is_unscoreable(self):+ # _welford_update seeds {mean, M2, count} and writes "std" at the end,+ # so a partially-initialised entry is reachable.+ stats = {"f": {"mean": 10.0, "M2": 0.0, "count": 100}}+ assert compute_z_score(stats, "f", 9999.0) is None++ def test_too_few_observations_is_unscoreable(self):+ # Cold start: the sample variance carries no information yet.+ stats = _feed([10.0, 12.0, 14.0])+ assert compute_z_score(stats, "f", 9999.0, min_samples=30) is None++ def test_single_observation_is_unscoreable(self):+ # n=1 gives variance 0.0 via the n-1 denominator, so this would have+ # been silently scored as normal even with no sample gate.+ stats = _feed([10.0])+ assert compute_z_score(stats, "f", 9999.0, min_samples=1) is None++ def test_constant_baseline_is_unscoreable_for_extreme_value(self):+ # 50x the established mean over a long, entirely uniform history —+ # the shape a service account produces.+ stats = _feed([100.0] * 200)+ assert compute_z_score(stats, "f", 5000.0) is None++ def test_zero_sample_gate_does_not_make_zero_variance_informative(self):+ # The sample gate and the variance check are independent: disabling the+ # former must not resurrect the degenerate path.+ assert compute_z_score(_feed([7.0]), "f", 8.0, min_samples=0) is None++ def test_unscoreable_is_distinct_from_normal(self):+ """The regression this change exists to prevent."""+ degenerate = _feed([100.0] * 200)+ healthy = _feed([10.0, 12.0, 14.0, 11.0, 13.0] * 6)+ assert compute_z_score(degenerate, "f", 5000.0) is None+ assert compute_z_score(healthy, "f", healthy["f"]["mean"]) == 0.0+++class TestCompositeScore:+ """Root-sum-of-squares, capped at 10, with no per-feature denominator."""++ def test_empty_input_returns_zero(self):+ assert _composite_score({}) == 0.0++ def test_is_root_sum_of_squares(self):+ assert _composite_score(_scored(3.0, 4.0)) == pytest.approx(5.0)++ def test_is_capped_at_ten(self):+ assert _composite_score(_scored(20.0, 20.0)) == 10.0++ def test_zero_scored_features_contribute_nothing(self):+ # Why dropping unscoreable features later is numerically neutral:+ # RSS has no denominator, and 0**2 adds nothing to the sum.+ assert _composite_score(_scored(3.0, 4.0)) == pytest.approx(+ _composite_score(_scored(3.0, 4.0, 0.0, 0.0))+ )++ def test_only_unscoreable_features_score_zero(self):+ assert _composite_score({"a": {"z_score": None}, "b": {"z_score": None}}) == 0.0++ def test_unscoreable_features_are_excluded_not_counted(self):+ mixed = {"a": {"z_score": 3.0}, "b": {"z_score": None}}+ assert _composite_score(mixed) == pytest.approx(3.0)++ def test_is_not_normalised_by_feature_count(self):+ # Ten mild deviations outrank three identical ones.+ assert _composite_score(_scored(*([2.0] * 10))) > _composite_score(+ _scored(2.0, 2.0, 2.0)+ )+++class TestUnscoreableFeatures:+ """The helper that feeds the operator-visible log line."""++ def test_returns_only_unscoreable_names_sorted(self):+ scored = {+ "zeta": {"z_score": None},+ "alpha": {"z_score": 0.0},+ "mu": {"z_score": None},+ }+ assert _unscoreable_features(scored) == ["mu", "zeta"]++ def test_returns_empty_when_every_feature_scored(self):+ assert _unscoreable_features({"a": {"z_score": 1.5}}) == []+++class TestRiskLevel:+ """`critical` and `high` are hard-coded; only `medium` follows settings."""++ @pytest.mark.parametrize(+ "score,expected",+ [+ (9.9, "critical"),+ (6.0, "critical"),+ (5.9, "high"),+ (4.0, "high"),+ (3.9, "medium"),+ (3.0, "medium"),+ (2.9, "low"),+ (0.0, "low"),+ ],+ )+ def test_boundaries(self, score, expected):+ assert _risk_level(score) == expected