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.

Five dead spines, and one that was never dead (#730)

Beenu Aroraa122c502b59e
diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.md
index 282dc4359..d33ad89f9 100644
--- a/apps/docs/docs/deployment/env-vars.md
+++ b/apps/docs/docs/deployment/env-vars.md
@@ -139,7 +139,7 @@ Source: [`services/api/app/auth/saml.py`](https://github.com/beenuar/AiSOC/blob/
| `AISOC_DEMO_MODE` | `false` | When `true`, mutating requests outside the demo tenant return 403 |
| `AISOC_DEMO_TENANT` | `demo` | Tenant slug allowed to write in demo mode |
| `AISOC_DEMO_BANNER` | `Demo data resets daily at 00:00 UTC. All write actions are disabled.` | Banner text rendered by the web app |
-| `AISOC_DISABLE_KAFKA` / `AISOC_DISABLE_CLICKHOUSE` / `AISOC_DISABLE_OPENSEARCH` / `AISOC_DISABLE_NEO4J` / `AISOC_DISABLE_QDRANT` | `false` | Skip the corresponding subsystem at boot — endpoints that need it return 503 |
+| `AISOC_DISABLE_KAFKA` / `AISOC_DISABLE_CLICKHOUSE` / `AISOC_DISABLE_NEO4J` / `AISOC_DISABLE_QDRANT` | `false` | Skip the corresponding subsystem at boot — endpoints that need it return 503. There is no OpenSearch equivalent: the API service holds no OpenSearch client. OpenSearch belongs to `services/threatintel`, configured with `OPENSEARCH_HOST` / `OPENSEARCH_PORT`. |
---
diff --git a/docker-compose.yml b/docker-compose.yml
index 644fbabd0..50b386c34 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -258,7 +258,9 @@ services:
LLM_GATEWAY_URL: http://litellm:4000/v1
# Phase 2.6 — use /readyz, not /health, so the orchestrator
# only routes traffic once the lifespan has finished wiring
- # Postgres, Redis, Kafka, OpenSearch, Qdrant, and Neo4j.
+ # Postgres, Redis, Kafka, Qdrant, and Neo4j. (Not OpenSearch: this
+ # service constructs no OpenSearch client. `services/threatintel` is
+ # the only consumer of that store.)
# /livez is what the restart policy looks at via `pgrep`-style
# checks; we don't need a separate compose healthcheck for it
# because the process being up implies it's alive.
@@ -284,6 +286,8 @@ services:
depends_on:
kafka:
condition: service_healthy
+ postgres:
+ condition: service_healthy
ports:
- "127.0.0.1:8081:8080"
- "127.0.0.1:9090:9090"
@@ -293,6 +297,12 @@ services:
METRICS_PORT: 9090
KAFKA_BOOTSTRAP_SERVERS: kafka:29092
REDIS_URL: redis://:redis_dev_secret@redis:6379/1
+ # The inbox webhook routes (/v1/inbox/*) mount only when this is set,
+ # and no compose file set it, so the documented "push events straight
+ # from your SIEM" path was unreachable on every local and CI stack.
+ # This is a pgx DSN and is deliberately distinct from the SQLAlchemy
+ # DATABASE_URL the Python services use.
+ DATABASE_DSN: postgres://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisoc?sslmode=disable
LOG_LEVEL: info
JWT_SECRET: dev_secret_key_change_in_production
ATTCK_DATA_PATH: /app/data/enterprise-attack.json
@@ -561,12 +571,23 @@ services:
condition: service_healthy
kafka:
condition: service_healthy
+ # OpenSearch is a hard dependency, not an optional one: the lifespan
+ # calls os_store.initialize() without a try/except, so starting before
+ # it is up kills the container and leaves `restart: unless-stopped` to
+ # paper over the race.
+ opensearch:
+ condition: service_started
ports:
- "127.0.0.1:8005:8005"
environment:
KAFKA_BOOTSTRAP_SERVERS: kafka:29092
REDIS_URL: redis://:redis_dev_secret@redis:6379/7
- OPENSEARCH_URL: http://opensearch:9200
+ # This service reads OPENSEARCH_HOST/PORT. It was given OPENSEARCH_URL,
+ # which its Settings has no field for and `extra="ignore"` discards, so
+ # the connection worked only because the defaults happened to match the
+ # compose service name. Set what is actually read.
+ OPENSEARCH_HOST: opensearch
+ OPENSEARCH_PORT: 9200
QDRANT_URL: http://qdrant:6333
NEO4J_URI: bolt://neo4j:7687
NEO4J_USER: neo4j
diff --git a/docs/architecture/README.md b/docs/architecture/README.md
index f916a4dd0..4ffb7fbfc 100644
--- a/docs/architecture/README.md
+++ b/docs/architecture/README.md
@@ -161,10 +161,13 @@ flowchart TB
| **ClickHouse** | Columnar scans over hundreds of millions of events. Postgres cannot do this at cost. | No event lake, no hunting over raw telemetry. **Alerting is unaffected.** |
| **Neo4j** | Multi-hop traversal ("what else did this identity touch") is a join explosion in SQL. | No graph context or blast radius. Alerting unaffected. |
| **Qdrant** | Vector similarity for IOC and actor matching. | No semantic threat-intel matching. |
+| **OpenSearch** | Full-text and structured search over the threat-intel corpus — `threatintel-iocs` and `threatintel-actors`. | `services/threatintel` cannot start: it indexes into OpenSearch in its lifespan, without a fallback. |
-**OpenSearch is started by the `full` profile and nothing reads from it.**
-It is recorded in [the reality audit](../audit/REPOSITORY_REALITY.md) as
-unused rather than drawn here as though it were part of the design.
+**Who reads OpenSearch, precisely:** only `services/threatintel`. This page
+previously said nothing read it at all, which came from checking
+`services/api` — which genuinely holds no OpenSearch client — and stopping
+there. See the correction in
+[the reality audit](../audit/REPOSITORY_REALITY.md).
---
diff --git a/docs/audit/REPOSITORY_REALITY.md b/docs/audit/REPOSITORY_REALITY.md
index b5100ef01..cae0e6317 100644
--- a/docs/audit/REPOSITORY_REALITY.md
+++ b/docs/audit/REPOSITORY_REALITY.md
@@ -82,22 +82,40 @@ mismatch is invisible until nothing arrives.
| ClickHouse | full | the event lake (`aisoc.raw_events` table) behind `/lake/sql` and hunt | **WORKING** when enabled |
| Neo4j | full | entity graph, blast radius | **WORKING** when enabled |
| Qdrant | full | IOC/actor embeddings for `services/threatintel` | **WORKING** when enabled |
-| OpenSearch | full | declared for archived-event search | **DEAD CODE** — no CORE or FULL code path queries it |
-
-OpenSearch is the honest casualty of this audit: it is started by the compose
-file and nothing reads from it. It stays in the `full` profile rather than
-being silently removed, and is recorded here as unused.
+| OpenSearch | full | IOC + threat-actor indices for `services/threatintel` | **WORKING** when enabled |
+
+**Correction (v9.0).** This audit originally recorded OpenSearch as dead code
+on the grounds that nothing read it. That was wrong, and wrong in the way this
+document exists to prevent: the check was made against `services/api`, which
+holds no OpenSearch client, and never against `services/threatintel`, which
+holds one and uses it unconditionally. `OpenSearchStore.initialize()` runs in
+the threatintel lifespan with no feature flag and no `try`, and every CISA KEV
+poll bulk-indexes into `threatintel-iocs`.
+
+Two real defects sat underneath the wrong verdict, both now fixed: compose set
+`OPENSEARCH_URL` on the threatintel service, which its settings class has no
+field for and `extra="ignore"` silently discards, so the connection worked
+only because the defaults happened to match the compose service name; and
+threatintel declared no `depends_on` for OpenSearch, so it could boot first,
+die in the lifespan, and be restarted until the race resolved.
+
+What *is* vestigial is on the API side. `AISOC_DISABLE_OPENSEARCH` had zero
+readers while three deploy configs set it and the env-var reference documented
+it — an operator could disable a subsystem this service never had — so the
+setting is removed rather than left as a switch wired to nothing.
+`OPENSEARCH_URL` stays in the API config because `esql_runner` reads it as an
+SSRF allow-list entry, and is commented as such.
### Broken or disconnected
| Component | Status | What is wrong |
|---|---|---|
-| `services/ueba` | **BROKEN** | Consumes the topic `security.events`. Nothing in the repository produces that topic — ingest writes `aisoc.raw_events`. So UEBA never scores, never emits `ueba.anomalies`, and fusion's UEBA confidence boost is permanently inert despite defaulting on. |
-| Ingest inbox webhooks | **BROKEN** | Routes mount only when `DATABASE_DSN` is set; compose never sets it. The templates directory is also not copied into the image, so even with a DSN every template resolves 503. |
-| Fuse-time enrichment | **FIXED in this audit** | Defaulted to `http://localhost:8082`, which inside the fusion container is fusion itself. Every enrichment call failed and the failure was swallowed at `DEBUG`. Now points at the `enrichment` service and is a declared `full`-profile capability. |
+| `services/ueba` | **FIXED in v9.0** | Consumed the topic `security.events`, which nothing in the repository produces — ingest writes `aisoc.raw_events`. So UEBA never scored, never emitted `ueba.anomalies`, and fusion's UEBA confidence boost was permanently inert despite defaulting on. The default topic is now `aisoc.raw_events` and `app/services/feature_extraction.py` recovers the entity and features the scorer needs from the OCSF envelope. |
+| Ingest inbox webhooks | **FIXED in v9.0** | Routes mounted only when `DATABASE_DSN` was set and compose never set it; the templates were also not copied into the runtime image, so even with a DSN every template resolved 503. Templates are now `go:embed`-ed into the binary — a directory cannot be missing from an image — and compose sets the DSN. The on-disk path remains as an operator override. |
+| Fuse-time enrichment | **FIXED in v8.1.1** | Defaulted to `http://localhost:8082`, which inside the fusion container is fusion itself. Every enrichment call failed and the failure was swallowed at `DEBUG`. Now points at the `enrichment` service and is a declared `full`-profile capability. |
| Investigation → response | **PARTIAL, by design** | Nothing automatically dispatches to `services/actions`. Response is copilot-default and human-initiated. This is intentional, but it means the pipeline terminates at triage. |
-| `aisoc.alerts.raw` | **DEAD** | Fusion subscribes to it; no producer exists anywhere. |
-| `aisoc.vulnerability_matches` | **DEAD** | Ingest produces it; no consumer exists. |
+| `aisoc.alerts.raw` | **EXTERNAL ENTRYPOINT** | Previously recorded as dead because no in-repo producer exists. That is what an entrypoint is: fusion subscribes, schema-validates against the pinned `v1` RawAlert envelope, and dead-letters poison, so an external system can push a vendor alert straight into fusion. Covered by `test_event_schema.py` and `test_consumer_dlq.py`, and documented in `docs/runbooks/kafka-consumer-lag.md`. |
+| `aisoc.vulnerability_matches` | **OPT-IN EXPORT** | Ingest produced it by default and nothing consumed it — fusion gets vulnerability context by calling the enrichment service at fuse time. `VULN_CORREL_ENABLED` now defaults to `false`, so a stock deployment no longer downloads the CISA KEV catalogue at boot to publish into a topic with no reader. It stays available for an external consumer. |
### Detection
@@ -124,9 +142,20 @@ These were not visible from the code alone:
every request, and compose still reported it `healthy`. `make doctor`
checks disk before anything else and probes the broker with an admin call
rather than trusting the healthcheck.
-4. **CrowdStrike has no normalizer profile** and falls through to the generic
- one. Events still promote, but entity extraction is weak — the correlation
- key came back `tenant:unknown:unknown`.
+4. **CrowdStrike alerts reached fusion with no actor.** Recorded here first as
+ "has no normalizer profile", which was the wrong diagnosis: the connector
+ emits a canonical envelope, so it takes the canonical path and gets OCSF
+ 2001 correctly. The actual faults were two, and both are fixed in v9.0.
+ The connector never read `behaviors[].user_name`, where Falcon puts the
+ acting identity, so the envelope carried none. And the canonical field map
+ recognised only `actor` — of the 68 canonical-envelope connectors, 40 use
+ that spelling and 11 use `username` or `user`, which mapped nowhere.
+ Because the fusion correlation key is `{tenant}:{entity}:{tactic}`, a
+ missing actor did not merely blank a column: every affected alert
+ correlated into the same `unknown` bucket. Aliases now resolve in declared
+ order rather than as extra map entries, because Go randomises map
+ iteration and three entries pointing at one destination would pick a
+ different winner per process.
---
diff --git a/infra/fly/api/fly.toml b/infra/fly/api/fly.toml
index 3a5b4014b..f1b4e9594 100644
--- a/infra/fly/api/fly.toml
+++ b/infra/fly/api/fly.toml
@@ -67,10 +67,11 @@ kill_timeout = "5s"
# "MIGRATION SKIPPED" line in the deploy log to investigate. Flip this
# back to "1" if you want demo deploys to fail-closed on DB outages.
AISOC_MIGRATIONS_REQUIRED = "0"
- # Disable optional integrations (no Kafka/ClickHouse/OpenSearch on demo)
+ # Disable optional integrations (no Kafka/ClickHouse/graph/vector on demo).
+ # There is no AISOC_DISABLE_OPENSEARCH: this service holds no OpenSearch
+ # client, so the flag disabled nothing and only implied it did.
AISOC_DISABLE_KAFKA = "true"
AISOC_DISABLE_CLICKHOUSE = "true"
- AISOC_DISABLE_OPENSEARCH = "true"
AISOC_DISABLE_NEO4J = "true"
AISOC_DISABLE_QDRANT = "true"
# Seeding runs automatically on deploy via [deploy].release_command above.
diff --git a/infra/railway/railway.toml b/infra/railway/railway.toml
index b5c9ee961..06ffdd61e 100644
--- a/infra/railway/railway.toml
+++ b/infra/railway/railway.toml
@@ -88,6 +88,5 @@ AISOC_DEMO_TENANT = "demo"
# off, so the demo profile works fine without them.
AISOC_DISABLE_KAFKA = "true"
AISOC_DISABLE_CLICKHOUSE = "true"
-AISOC_DISABLE_OPENSEARCH = "true"
AISOC_DISABLE_NEO4J = "true"
AISOC_DISABLE_QDRANT = "true"
diff --git a/infra/render/README.md b/infra/render/README.md
index 6efcd8d7a..322fc98d2 100644
--- a/infra/render/README.md
+++ b/infra/render/README.md
@@ -30,7 +30,6 @@ The Blueprint sets these flags on the api and agents services:
```yaml
AISOC_DISABLE_KAFKA: "true"
AISOC_DISABLE_CLICKHOUSE: "true"
-AISOC_DISABLE_OPENSEARCH: "true"
AISOC_DISABLE_NEO4J: "true"
AISOC_DISABLE_QDRANT: "true"
```
diff --git a/render.yaml b/render.yaml
index 6c373623e..3dca9c4c4 100644
--- a/render.yaml
+++ b/render.yaml
@@ -75,8 +75,6 @@ services:
value: "true"
- key: AISOC_DISABLE_CLICKHOUSE
value: "true"
- - key: AISOC_DISABLE_OPENSEARCH
- value: "true"
- key: AISOC_DISABLE_NEO4J
value: "true"
- key: AISOC_DISABLE_QDRANT
diff --git a/services/api/app/core/config.py b/services/api/app/core/config.py
index c92640b50..54fca4a48 100644
--- a/services/api/app/core/config.py
+++ b/services/api/app/core/config.py
@@ -338,7 +338,10 @@ class Settings(BaseSettings):
KAFKA_TOPIC_EVENTS: str = "aisoc.normalized_events"
KAFKA_TOPIC_ALERTS: str = "aisoc.alerts"
- # OpenSearch
+ # OpenSearch. This service constructs no OpenSearch client; the value is
+ # read only by esql_runner's SSRF allow-list, as the host an operator is
+ # permitted to point ES|QL at. `services/threatintel` is the only service
+ # that actually stores anything in OpenSearch.
OPENSEARCH_URL: str = "http://localhost:9200"
# Neo4j
@@ -467,9 +470,12 @@ class Settings(BaseSettings):
# and the API returns 503 for endpoints that require it.
AISOC_DISABLE_KAFKA: bool = False
AISOC_DISABLE_CLICKHOUSE: bool = False
- AISOC_DISABLE_OPENSEARCH: bool = False
AISOC_DISABLE_NEO4J: bool = False
AISOC_DISABLE_QDRANT: bool = False
+ # AISOC_DISABLE_OPENSEARCH is deliberately absent. It sat here with zero
+ # readers while three deploy configs set it and the env-var reference
+ # documented it, so an operator could switch off a subsystem this service
+ # never had. A flag that disables nothing is worse than no flag.
# ------------------------------------------------------------------
# v6 capability flags (AiSOC v6 capability roadmap).
diff --git a/services/connectors/app/connectors/crowdstrike.py b/services/connectors/app/connectors/crowdstrike.py
index 7f1d84db3..0124fb217 100644
--- a/services/connectors/app/connectors/crowdstrike.py
+++ b/services/connectors/app/connectors/crowdstrike.py
@@ -166,6 +166,19 @@ class CrowdStrikeConnector(BaseConnector):
behaviors = raw.get("behaviors") or [{}]
title = behaviors[0].get("display_name", "CrowdStrike Detection")
+ # Falcon carries the acting identity per behavior, not on the
+ # detection. The envelope omitted it entirely, so every CrowdStrike
+ # alert reached fusion with no actor — and fusion's correlation key is
+ # {tenant}:{entity}:{tactic}, so an EDR detection on a named user
+ # correlated under "unknown" alongside every other one.
+ actor = ""
+ for behavior in behaviors:
+ candidate = (behavior.get("user_name") or "").strip()
+ if candidate:
+ domain = (behavior.get("user_id") or "").strip()
+ actor = f"{candidate}@{domain}" if "@" not in candidate and "@" in domain else candidate
+ break
+
return {
"source": self.connector_id,
"external_id": raw.get("detection_id", ""),
@@ -174,6 +187,7 @@ class CrowdStrikeConnector(BaseConnector):
"severity": severity,
"src_ip": raw.get("device", {}).get("external_ip"),
"hostname": raw.get("device", {}).get("hostname"),
+ "actor": actor or None,
"mitre_techniques": [b.get("technique_id", "") for b in raw.get("behaviors", []) if b.get("technique_id")],
"raw_event": raw,
"created_at": raw.get("created_timestamp"),
diff --git a/services/connectors/tests/test_crowdstrike_normalize.py b/services/connectors/tests/test_crowdstrike_normalize.py
new file mode 100644
index 000000000..0a3c8b70b
--- /dev/null
+++ b/services/connectors/tests/test_crowdstrike_normalize.py
@@ -0,0 +1,81 @@
+"""CrowdStrike detections must carry the acting identity through to fusion.
+
+Falcon puts the user on each behavior, not on the detection, and the envelope
+omitted it entirely. That is not a cosmetic gap: fusion's correlation key is
+``{tenant}:{entity}:{tactic}``, so an EDR detection against a named user
+arrived with the entity segment blank and correlated into the same bucket as
+every other CrowdStrike alert in the tenant.
+"""
+
+from __future__ import annotations
+
+from app.connectors.crowdstrike import CrowdStrikeConnector
+
+
+def _connector() -> CrowdStrikeConnector:
+ return CrowdStrikeConnector(client_id="id", client_secret="secret")
+
+
+def _detection(**overrides) -> dict:
+ detection = {
+ "detection_id": "ldt:abc:123",
+ "max_severity_displayname": "High",
+ "created_timestamp": "2026-09-23T10:00:00Z",
+ "device": {"hostname": "WKSTN-01", "external_ip": "203.0.113.7"},
+ "behaviors": [
+ {
+ "display_name": "Suspicious PowerShell",
+ "technique_id": "T1059.001",
+ "user_name": "alice",
+ "user_id": "S-1-5-21-1",
+ }
+ ],
+ }
+ detection.update(overrides)
+ return detection
+
+
+class TestActor:
+ def test_actor_comes_from_the_behavior(self):
+ event = _connector().normalize(_detection())
+ assert event["actor"] == "alice"
+
+ def test_first_behavior_with_a_user_wins(self):
+ event = _connector().normalize(
+ _detection(
+ behaviors=[
+ {"display_name": "Stage one", "user_name": ""},
+ {"display_name": "Stage two", "user_name": "bob"},
+ ]
+ )
+ )
+ assert event["actor"] == "bob"
+
+ def test_missing_actor_is_none_not_an_empty_string(self):
+ # An empty string is a value the normalizer would map onto
+ # actor.user.name, producing an alert that claims to name a user and
+ # names nobody. None is absent, which is the truth.
+ event = _connector().normalize(_detection(behaviors=[{"display_name": "No user"}]))
+ assert event["actor"] is None
+
+ def test_no_behaviors_at_all_is_handled(self):
+ event = _connector().normalize(_detection(behaviors=[]))
+ assert event["actor"] is None
+ assert event["title"] == "CrowdStrike Detection"
+
+
+class TestEnvelope:
+ def test_still_emits_the_canonical_envelope(self):
+ # `source` + `raw_event` is what makes the normalizer take the
+ # canonical path, which is what gives the event OCSF class 2001 and
+ # therefore makes it promotable to an alert at all.
+ event = _connector().normalize(_detection())
+ assert event["source"] == "crowdstrike"
+ assert isinstance(event["raw_event"], dict)
+
+ def test_severity_and_host_survive(self):
+ event = _connector().normalize(_detection())
+ assert event["severity"] == "high"
+ assert event["hostname"] == "WKSTN-01"
+ assert event["src_ip"] == "203.0.113.7"
+ assert event["mitre_techniques"] == ["T1059.001"]
diff --git a/services/ingest/internal/config/config.go b/services/ingest/internal/config/config.go
index 9c499880f..d308534c1 100644
--- a/services/ingest/internal/config/config.go
+++ b/services/ingest/internal/config/config.go
@@ -29,7 +29,15 @@ type Config struct {
ShodanEnrichEnabled bool
ShodanCacheExpirySecs int
- // CVE / vulnerability correlation
+ // CVE / vulnerability correlation.
+ //
+ // Off by default. Nothing in the platform consumes VulnKafkaTopic —
+ // fusion gets its vulnerability context by calling the enrichment service
+ // at fuse time, not from this stream — so with it on, every deployment
+ // downloaded the CISA KEV catalogue at boot and published matches into a
+ // topic with no reader. It remains available as an opt-in export for an
+ // external consumer; the messages carry an `event_type:
+ // VULNERABILITY_MATCH` header for exactly that.
VulnCorrelEnabled bool
VulnKafkaTopic string // topic for VULNERABILITY_MATCH events
NvdAPIKey string // optional NVD API key for higher rate limits
@@ -169,7 +177,7 @@ func Load() (*Config, error) {
ShodanCacheExpirySecs: mustGetEnvInt("SHODAN_CACHE_EXPIRY_SECS", 3600),
// CVE correlation
- VulnCorrelEnabled: getEnv("VULN_CORREL_ENABLED", "true") == "true",
+ VulnCorrelEnabled: getEnv("VULN_CORREL_ENABLED", "false") == "true",
VulnKafkaTopic: getEnv("VULN_KAFKA_TOPIC", "aisoc.vulnerability_matches"),
NvdAPIKey: getEnv("NVD_API_KEY", ""),
diff --git a/services/ingest/internal/inbox/template.go b/services/ingest/internal/inbox/template.go
index 2eccde55b..93bf02f78 100644
--- a/services/ingest/internal/inbox/template.go
+++ b/services/ingest/internal/inbox/template.go
@@ -4,12 +4,15 @@ import (
"errors"
"fmt"
"os"
+ "path"
"path/filepath"
"strings"
"sync"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v3"
+
+ "github.com/beenuar/aisoc/services/ingest/internal/normalizer"
)
// ErrTemplateNotFound is returned when a token resolves to a template_id
@@ -90,56 +93,106 @@ func NewRegistry() *Registry {
return &Registry{templates: make(map[string]*Template)}
}
-// Load reads every *.yaml file in dir and registers it as a template.
-// Files with malformed YAML are logged and skipped so a typo in one
-// template doesn't take down the whole ingest service.
+// parse turns one template file's bytes into a registered Template.
+// Returns false when the YAML is malformed, so one typo cannot take down
+// the whole ingest service.
+func (r *Registry) parse(name string, raw []byte) bool {
+ t := &Template{}
+ if err := yaml.Unmarshal(raw, t); err != nil {
+ log.Warn().Err(err).Str("template", name).Msg("inbox: malformed template YAML")
+ return false
+ }
+ // Default the ID to the filename stem — operators usually leave
+ // the explicit `id:` blank and rely on the convention.
+ if t.ID == "" {
+ t.ID = strings.TrimSuffix(strings.TrimSuffix(name, ".yaml"), ".yml")
+ }
+ // Normalise severity keys.
+ if len(t.SeverityMap) > 0 {
+ normalised := make(map[string]int, len(t.SeverityMap))
+ for k, v := range t.SeverityMap {
+ normalised[strings.ToLower(strings.TrimSpace(k))] = v
+ }
+ t.SeverityMap = normalised
+ }
+
+ r.mu.Lock()
+ r.templates[t.ID] = t
+ r.mu.Unlock()
+ return true
+}
+
+func isTemplateFile(name string) bool {
+ return strings.HasSuffix(name, ".yaml") || strings.HasSuffix(name, ".yml")
+}
+
+// LoadEmbedded registers the templates compiled into the binary.
//
-// dir is typically baked into the container image at
-// /app/templates, but tests override to use a tmpdir.
-func (r *Registry) Load(dir string) error {
- entries, err := os.ReadDir(dir)
+// This is the load that must always succeed: the on-disk path below is an
+// operator override, and for most of this service's life it pointed at a
+// directory the container image never contained, so /v1/inbox/* answered 503
+// for every template on every deployment.
+func (r *Registry) LoadEmbedded() error {
+ entries, err := normalizer.InboxTemplates.ReadDir(normalizer.InboxTemplateDir)
if err != nil {
- return fmt.Errorf("inbox: read template dir %s: %w", dir, err)
+ return fmt.Errorf("inbox: read embedded templates: %w", err)
}
loaded := 0
for _, e := range entries {
- if e.IsDir() {
+ if e.IsDir() || !isTemplateFile(e.Name()) {
continue
}
- name := e.Name()
- if !strings.HasSuffix(name, ".yaml") && !strings.HasSuffix(name, ".yml") {
- continue
- }
- path := filepath.Join(dir, name)
- raw, err := os.ReadFile(path)
+ raw, err := normalizer.InboxTemplates.ReadFile(path.Join(normalizer.InboxTemplateDir, e.Name()))
if err != nil {
- log.Warn().Err(err).Str("path", path).Msg("inbox: skipping unreadable template")
+ log.Warn().Err(err).Str("template", e.Name()).Msg("inbox: skipping unreadable embedded template")
continue
}
- t := &Template{}
- if err := yaml.Unmarshal(raw, t); err != nil {
- log.Warn().Err(err).Str("path", path).Msg("inbox: malformed template YAML")
+ if r.parse(e.Name(), raw) {
+ loaded++
+ }
+ }
+ log.Info().Int("count", loaded).Msg("inbox: embedded templates loaded")
+ if loaded == 0 {
+ // The embed directive matched nothing, which means the binary shipped
+ // without the templates it is supposed to carry. Saying so loudly is
+ // the whole point of this change.
+ return errors.New("inbox: no embedded templates found in the binary")
+ }
+ return nil
+}
+
+// Load reads every *.yaml file in dir and registers it as a template,
+// overriding any embedded template of the same ID.
+//
+// Files with malformed YAML are logged and skipped so a typo in one
+// template doesn't take down the whole ingest service. A missing directory
+// is not an error: the embedded set is the baseline and this is the operator
+// override on top of it.
+func (r *Registry) Load(dir string) error {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ if os.IsNotExist(err) {
+ log.Debug().Str("dir", dir).Msg("inbox: no on-disk template overrides")
+ return nil
+ }
+ return fmt.Errorf("inbox: read template dir %s: %w", dir, err)
+ }
+
+ loaded := 0
+ for _, e := range entries {
+ if e.IsDir() || !isTemplateFile(e.Name()) {
continue
}
- // Default the ID to the filename stem — operators usually leave
- // the explicit `id:` blank and rely on the convention.
- if t.ID == "" {
- t.ID = strings.TrimSuffix(strings.TrimSuffix(name, ".yaml"), ".yml")
+ p := filepath.Join(dir, e.Name())
+ raw, err := os.ReadFile(p)
+ if err != nil {
+ log.Warn().Err(err).Str("path", p).Msg("inbox: skipping unreadable template")
+ continue
}
- // Normalise severity keys.
- if len(t.SeverityMap) > 0 {
- normalised := make(map[string]int, len(t.SeverityMap))
- for k, v := range t.SeverityMap {
- normalised[strings.ToLower(strings.TrimSpace(k))] = v
- }
- t.SeverityMap = normalised
+ if r.parse(e.Name(), raw) {
+ loaded++
}
-
- r.mu.Lock()
- r.templates[t.ID] = t
- r.mu.Unlock()
- loaded++
}
log.Info().Int("count", loaded).Str("dir", dir).Msg("inbox: templates loaded")
return nil
diff --git a/services/ingest/internal/inbox/template_test.go b/services/ingest/internal/inbox/template_test.go
index 9997a269f..2dbcb4e46 100644
--- a/services/ingest/internal/inbox/template_test.go
+++ b/services/ingest/internal/inbox/template_test.go
@@ -168,11 +168,85 @@ field_map: {}
}
}
-func TestRegistry_Load_ErrorsOnMissingDir(t *testing.T) {
+func TestRegistry_Load_MissingDirIsNotAnError(t *testing.T) {
+ // Load is now the operator override on top of LoadEmbedded, so an absent
+ // directory is the normal case rather than a failure. It used to be an
+ // error, and the default it was pointed at — /app/templates — was a path
+ // the container image never contained, so the "error" was logged as a
+ // warning on every boot and the inbox 503'd regardless.
r := NewRegistry()
- err := r.Load("/nonexistent/template/dir/" + strings.Repeat("x", 10))
- if err == nil {
- t.Fatalf("expected error for missing dir")
+ if err := r.Load("/nonexistent/template/dir/" + strings.Repeat("x", 10)); err != nil {
+ t.Fatalf("missing override dir should not error: %v", err)
+ }
+}
+
+func TestRegistry_LoadEmbedded_ShipsTemplatesInTheBinary(t *testing.T) {
+ // The regression this pins: the runtime image copies only the compiled
+ // binary, so a disk-only template path meant every /v1/inbox/* request
+ // answered 503 on every deployment.
+ r := NewRegistry()
+ if err := r.LoadEmbedded(); err != nil {
+ t.Fatalf("LoadEmbedded failed: %v", err)
+ }
+ ids := r.IDs()
+ if len(ids) == 0 {
+ t.Fatalf("no embedded templates registered")
+ }
+ // generic-json is the template the documented inbox quickstart uses.
+ if _, err := r.Get("generic-json"); err != nil {
+ t.Errorf("generic-json not embedded; got IDs %v", ids)
+ }
+}
+
+func TestRegistry_LoadEmbedded_CoversEveryTemplateOnDisk(t *testing.T) {
+ // A new template added to the directory but not reachable through the
+ // embed would be invisible at runtime while looking present in the repo.
+ entries, err := os.ReadDir("../normalizer/templates")
+ if err != nil {
+ t.Fatalf("read template source dir: %v", err)
+ }
+ r := NewRegistry()
+ if err := r.LoadEmbedded(); err != nil {
+ t.Fatalf("LoadEmbedded failed: %v", err)
+ }
+ for _, e := range entries {
+ if e.IsDir() || !isTemplateFile(e.Name()) {
+ continue
+ }
+ id := strings.TrimSuffix(strings.TrimSuffix(e.Name(), ".yaml"), ".yml")
+ if _, err := r.Get(id); err != nil {
+ t.Errorf("template %s exists on disk but is not embedded", e.Name())
+ }
+ }
+}
+
+func TestRegistry_Load_OverridesAnEmbeddedTemplate(t *testing.T) {
+ r := NewRegistry()
+ if err := r.LoadEmbedded(); err != nil {
+ t.Fatalf("LoadEmbedded failed: %v", err)
+ }
+ before, err := r.Get("generic-json")
+ if err != nil {
+ t.Fatalf("generic-json not embedded: %v", err)
+ }
+
+ dir := t.TempDir()
+ writeTemplate(t, dir, "generic-json.yaml", `
+vendor_name: Operator
+product_name: Override
+class_uid: 2001
+field_map: {}
+`)
+ if err := r.Load(dir); err != nil {
+ t.Fatalf("Load failed: %v", err)
+ }
+ after, err := r.Get("generic-json")
+ if err != nil {
+ t.Fatalf("generic-json vanished after override: %v", err)
+ }
+ if after.VendorName != "Operator" {
+ t.Errorf("on-disk template did not override embedded one: vendor = %q (was %q)",
+ after.VendorName, before.VendorName)
}
}
diff --git a/services/ingest/internal/normalizer/normalizer.go b/services/ingest/internal/normalizer/normalizer.go
index 26af98c63..b8b4ab2d6 100644
--- a/services/ingest/internal/normalizer/normalizer.go
+++ b/services/ingest/internal/normalizer/normalizer.go
@@ -336,9 +336,30 @@ var _canonicalSeverityMap = map[string]int{
var _canonicalFieldMap = map[string]string{
"title": "message",
"external_id": "finding.uid",
- "src_ip": "src_endpoint.ip",
- "hostname": "device.name",
- "actor": "actor.user.name",
+}
+
+// _canonicalAliases fills one OCSF destination from the first connector field
+// that carries a value, in declared order.
+//
+// This is a slice and not more fieldMap entries because Go randomises map
+// iteration: three entries pointing at actor.user.name would resolve to a
+// different one of them per process, which is a correctness bug that only
+// shows up as flakiness. Declared order is the precedence.
+//
+// The aliases exist because the canonical map recognised only `actor`, and a
+// count across the 68 canonical-envelope connectors found 40 using `actor`
+// but 11 using `username` or `user`. Those eleven lost their identity on the
+// way through, and the fusion correlation key is {tenant}:{entity}:{tactic},
+// so a missing actor does not merely blank a column — it collapses the
+// entity segment to "unknown" and every one of that connector's alerts
+// correlates into the same bucket.
+var _canonicalAliases = []struct {
+ dst string
+ sources []string
+}{
+ {"actor.user.name", []string{"actor", "username", "user", "user_name"}},
+ {"device.name", []string{"hostname", "host", "device_name"}},
+ {"src_endpoint.ip", []string{"src_ip", "source_ip", "client_ip"}},
}
// canonicalClassByConnector overrides the default Security Finding class for
@@ -425,7 +446,8 @@ func (n *Normalizer) Normalize(raw *RawEvent) (*NormalizedEvent, error) {
}
var profile connectorProfile
- if isCanonicalEnvelope(raw.Payload) {
+ isCanonical := isCanonicalEnvelope(raw.Payload)
+ if isCanonical {
// Connector-normalized envelope: map its canonical fields directly.
profile = canonicalProfile(raw.ConnectorType)
} else {
@@ -473,6 +495,24 @@ func (n *Normalizer) Normalize(raw *RawEvent) (*NormalizedEvent, error) {
}
}
+ // Canonical envelopes additionally resolve identity aliases in declared
+ // order, so a connector that spells the actor `username` is not silently
+ // anonymised. Only applies where the profile uses the canonical map;
+ // hand-written vendor profiles already name their own fields.
+ if isCanonical {
+ for _, alias := range _canonicalAliases {
+ if getNestedField(ocsf, alias.dst) != nil {
+ continue
+ }
+ for _, src := range alias.sources {
+ if val := getNestedField(raw.Payload, src); val != nil {
+ setNestedField(ocsf, alias.dst, val)
+ break
+ }
+ }
+ }
+ }
+
// Map severity
if sevField, ok := raw.Payload["severity"].(string); ok {
if sevID, found := profile.severityMap[sevField]; found {
diff --git a/services/ingest/internal/normalizer/normalizer_test.go b/services/ingest/internal/normalizer/normalizer_test.go
index dedac3378..a8e4be18c 100644
--- a/services/ingest/internal/normalizer/normalizer_test.go
+++ b/services/ingest/internal/normalizer/normalizer_test.go
@@ -305,3 +305,123 @@ func TestAiGuardrailFindingIsAlwaysPromotable(t *testing.T) {
t.Errorf("activity_name = %v, want the finding type detections match on", ocsf["activity_name"])
}
}
+
+// getNestedField on the produced OCSF event, for assertions that need to
+// reach actor.user.name / device.name without re-implementing the walk.
+func nested(t *testing.T, ocsf map[string]interface{}, path string) interface{} {
+ t.Helper()
+ return getNestedField(ocsf, path)
+}
+
+func canonicalEvent(payload map[string]interface{}) *RawEvent {
+ return &RawEvent{
+ ConnectorID: "conn-1",
+ ConnectorType: "crowdstrike",
+ TenantID: "11111111-1111-1111-1111-111111111111",
+ ReceivedAt: "2026-09-23T00:00:00Z",
+ Payload: payload,
+ }
+}
+
+// The canonical field map recognised only `actor`. Eleven of the 68
+// canonical-envelope connectors spell it `username` or `user`, and their
+// alerts reached fusion anonymous — which matters beyond a blank column,
+// because the correlation key is {tenant}:{entity}:{tactic} and every one of
+// those alerts collapsed into the same "unknown" bucket.
+func TestCanonicalEnvelopeResolvesActorAliases(t *testing.T) {
+ for _, tc := range []struct {
+ field string
+ value string
+ }{
+ {"actor", "alice"},
+ {"username", "bob"},
+ {"user", "carol"},
+ {"user_name", "dave"},
+ } {
+ t.Run(tc.field, func(t *testing.T) {
+ n := newLenientNormalizer()
+ ev, err := n.Normalize(canonicalEvent(map[string]interface{}{
+ "source": "crowdstrike",
+ "title": "Detection",
+ "severity": "high",
+ tc.field: tc.value,
+ "raw_event": map[string]interface{}{},
+ }))
+ if err != nil {
+ t.Fatalf("Normalize returned error: %v", err)
+ }
+ if got := nested(t, ev.OcsfEvent, "actor.user.name"); got != tc.value {
+ t.Errorf("actor.user.name = %v, want %q from field %q", got, tc.value, tc.field)
+ }
+ })
+ }
+}
+
+// Precedence must be the declared order, not Go's randomised map iteration.
+// Expressing the aliases as extra fieldMap entries would pick a different
+// winner per process, which surfaces as flake rather than as a bug.
+func TestCanonicalActorPrecedenceIsDeterministic(t *testing.T) {
+ for i := 0; i < 50; i++ {
+ n := newLenientNormalizer()
+ ev, err := n.Normalize(canonicalEvent(map[string]interface{}{
+ "source": "crowdstrike",
+ "title": "Detection",
+ "severity": "high",
+ "actor": "primary",
+ "username": "secondary",
+ "user": "tertiary",
+ "raw_event": map[string]interface{}{},
+ }))
+ if err != nil {
+ t.Fatalf("Normalize returned error: %v", err)
+ }
+ if got := nested(t, ev.OcsfEvent, "actor.user.name"); got != "primary" {
+ t.Fatalf("iteration %d: actor.user.name = %v, want the declared-first source", i, got)
+ }
+ }
+}
+
+func TestCanonicalEnvelopeResolvesHostAndIPAliases(t *testing.T) {
+ n := newLenientNormalizer()
+ ev, err := n.Normalize(canonicalEvent(map[string]interface{}{
+ "source": "crowdstrike",
+ "title": "Detection",
+ "severity": "high",
+ "host": "web-01",
+ "client_ip": "203.0.113.7",
+ "raw_event": map[string]interface{}{},
+ }))
+ if err != nil {
+ t.Fatalf("Normalize returned error: %v", err)
+ }
+ if got := nested(t, ev.OcsfEvent, "device.name"); got != "web-01" {
+ t.Errorf("device.name = %v, want web-01 resolved from `host`", got)
+ }
+ if got := nested(t, ev.OcsfEvent, "src_endpoint.ip"); got != "203.0.113.7" {
+ t.Errorf("src_endpoint.ip = %v, want the value resolved from `client_ip`", got)
+ }
+}
+
+// Hand-written vendor profiles name their own fields and must not have the
+// canonical aliases applied on top of them.
+func TestAliasesDoNotApplyToRawVendorProfiles(t *testing.T) {
+ n := newTestNormalizer()
+ ev, err := n.Normalize(&RawEvent{
+ ConnectorID: "conn-1",
+ ConnectorType: "crowdstrike_falcon",
+ TenantID: "11111111-1111-1111-1111-111111111111",
+ ReceivedAt: "2026-09-23T00:00:00Z",
+ Payload: map[string]interface{}{
+ "UserName": "falcon-user",
+ "ComputerName": "falcon-host",
+ // A stray `username` must not override the profile's own mapping.
+ "username": "should-not-win",
+ },
+ })
+ if err != nil {
+ t.Fatalf("Normalize returned error: %v", err)
+ }
+ if got := nested(t, ev.OcsfEvent, "actor.user.name"); got != "falcon-user" {
+ t.Errorf("actor.user.name = %v, want the vendor profile's own mapping", got)
+ }
+}
diff --git a/services/ingest/internal/normalizer/templates.go b/services/ingest/internal/normalizer/templates.go
new file mode 100644
index 000000000..9dc23549f
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates.go
@@ -0,0 +1,23 @@
+package normalizer
+
+import "embed"
+
+// InboxTemplates carries the vendor webhook templates into the binary.
+//
+// They used to be read from disk at INBOX_TEMPLATES_DIR, defaulting to
+// /app/templates — a path the Dockerfile never populated, because the runtime
+// stage copies only the compiled binary. So every deployment that got as far
+// as configuring DATABASE_DSN still answered 503 for every template, and the
+// failure surfaced as a warning at startup that nothing was watching.
+//
+// Embedding removes the class of bug rather than the instance: the templates
+// are version-controlled beside the code that parses them, so they cannot be
+// absent from an image, out of step with the binary, or pointed at the wrong
+// directory. An operator can still add templates on disk — the registry loads
+// these first and lets a same-named file on disk override one.
+//
+//go:embed templates/*.yaml
+var InboxTemplates embed.FS
+
+// InboxTemplateDir is the path prefix inside InboxTemplates.
+const InboxTemplateDir = "templates"
diff --git a/services/ingest/main.go b/services/ingest/main.go
index 3d99204d0..61a0d33ac 100644
--- a/services/ingest/main.go
+++ b/services/ingest/main.go
@@ -174,9 +174,16 @@ func main() {
defer pool.Close()
store := inbox.NewStore(pool)
registry := inbox.NewRegistry()
+ // Embedded first — these ship in the binary and are the set the
+ // service is tested against. The on-disk directory is an operator
+ // override layered on top, and is allowed to be absent.
+ if err := registry.LoadEmbedded(); err != nil {
+ log.Error().Err(err).
+ Msg("Failed to load embedded inbox templates; /v1/inbox/* will return 503 for every template")
+ }
if err := registry.Load(cfg.InboxTemplatesDir); err != nil {
log.Warn().Err(err).Str("dir", cfg.InboxTemplatesDir).
- Msg("Failed to load inbox templates; /v1/inbox/* will return 503 for unknown templates")
+ Msg("Failed to load inbox template overrides from disk")
}
log.Info().
Strs("templates", registry.IDs()).
diff --git a/services/ueba/app/core/config.py b/services/ueba/app/core/config.py
index 5f5e1cbf6..a741fc16a 100644
--- a/services/ueba/app/core/config.py
+++ b/services/ueba/app/core/config.py
@@ -19,8 +19,12 @@ class Settings(BaseSettings):
default="localhost:9092",
validation_alias=AliasChoices("KAFKA_BOOTSTRAP_SERVERS", "UEBA_KAFKA_BOOTSTRAP_SERVERS"),
)
+ # The topic ingest actually publishes normalized events to. This used to
+ # default to ``security.events``, which no service in the platform writes,
+ # so the scorer consumed an empty topic forever and fusion's UEBA
+ # confidence boost — on by default — was permanently inert.
kafka_input_topic: str = Field(
- default="security.events",
+ default="aisoc.raw_events",
validation_alias=AliasChoices("KAFKA_INPUT_TOPIC", "UEBA_KAFKA_INPUT_TOPIC"),
)
kafka_output_topic: str = Field(
diff --git a/services/ueba/app/services/feature_extraction.py b/services/ueba/app/services/feature_extraction.py
new file mode 100644
index 000000000..0bea45723
--- /dev/null
+++ b/services/ueba/app/services/feature_extraction.py
@@ -0,0 +1,292 @@
+"""Turn an ingest-normalized OCSF event into something the scorer can score.
+
+UEBA's scorer wants ``(entity_type, entity_id, event_type, features)`` where
+``features`` is a flat map of numbers. Nothing in the platform produced that
+shape. The consumer's default topic was ``security.events``, which no service
+in this repository writes to, so the scorer never ran, ``ueba.anomalies``
+never carried a message, and fusion's UEBA confidence boost — enabled by
+default — could only ever be inert. This module is the missing translation
+between the envelope ingest actually publishes on ``aisoc.raw_events`` and the
+shape the scorer already knew how to consume.
+
+Two rules govern what becomes a feature.
+
+**It has to vary.** A z-score against a zero-variance baseline is undefined,
+and the scorer reports those as ``features_unscoreable`` rather than as normal
+behaviour. So a field that is constant for an entity is not a feature, however
+numeric it looks. ``hour_of_day`` earns its place because when someone works
+is genuinely characteristic of them; a per-event ``count`` of 1 does not.
+
+**It has to be readable from one event.** Volumetric behaviour — *how many*
+logins in ten minutes — is not visible here and is not faked: that is the
+windowed detection engine's job, and inventing a per-event approximation of it
+would produce a number that looks like a rate and is not one.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from typing import Any
+
+#: Vendor payload fields that are behavioural when present. Each is a genuine
+#: magnitude whose distribution per entity carries signal — transfer sizes,
+#: session durations, response sizes. Keys are matched case-insensitively
+#: against the recovered flat namespace.
+_NUMERIC_FIELDS: tuple[str, ...] = (
+ "bytes_in",
+ "bytes_out",
+ "bytes_sent",
+ "bytes_received",
+ "duration",
+ "duration_ms",
+ "file_size",
+ "request_size",
+ "response_size",
+ "packets_in",
+ "packets_out",
+)
+
+#: Outcome spellings that mean "this did not succeed". Failure rate per entity
+#: is one of the strongest behavioural signals there is.
+_FAILURE_VALUES = frozenset({"failure", "failed", "fail", "denied", "deny", "blocked", "error", "unsuccessful"})
+
+#: Fields carrying the acting identity, most specific first.
+_USER_FIELDS: tuple[str, ...] = ("user", "username", "user_name", "actor", "principal", "account")
+_HOST_FIELDS: tuple[str, ...] = ("hostname", "host", "device", "device_name", "computer")
+_IP_FIELDS: tuple[str, ...] = ("src_ip", "source_ip", "src_endpoint_ip", "client_ip")
+
+
+@dataclass(frozen=True)
+class ExtractedEvent:
+ """What the scorer needs, recovered from an ingest envelope."""
+
+ tenant_id: str
+ entity_type: str
+ entity_id: str
+ event_type: str
+ features: dict[str, float]
+ source_event_id: str | None = None
+ peer_group_id: str | None = None
+ #: Present only on pre-extracted messages; the OCSF path never sets it.
+ raw_features: dict[str, Any] = field(default_factory=dict)
+
+
+def flat_fields(message: dict[str, Any]) -> dict[str, Any]:
+ """Recover the flat field namespace from an ingest envelope.
+
+ This mirrors ``WindowedDetectionEngine._fields`` and the stateless
+ detection engine deliberately, and must keep mirroring them. Connectors
+ nest the untouched vendor payload one level down under ``raw_event``, so a
+ consumer reading the OCSF envelope flat sees ``None`` for every vendor
+ field. Connector-normalized keys win on collision, because a connector
+ that mapped a vendor's severity ladder onto AiSOC's five tiers must not
+ have that undone by the raw vendor value underneath.
+ """
+ ocsf = message.get("ocsf_event")
+ if not isinstance(ocsf, dict):
+ return {}
+ fields: dict[str, Any] = ocsf
+ raw = ocsf.get("raw_data")
+ if isinstance(raw, str) and raw.strip():
+ try:
+ parsed = json.loads(raw)
+ if isinstance(parsed, dict):
+ fields = parsed
+ except (ValueError, TypeError):
+ pass
+ elif isinstance(raw, dict):
+ fields = raw
+ nested = fields.get("raw_event")
+ if isinstance(nested, dict):
+ merged = {k: v for k, v in nested.items() if isinstance(k, str)}
+ merged.update(fields)
+ return merged
+ return fields
+
+
+def _first_str(fields: dict[str, Any], names: tuple[str, ...]) -> str | None:
+ for name in names:
+ value = fields.get(name)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ if isinstance(value, dict):
+ # OCSF nests identity as ``{"name": ...}`` / ``{"ip": ...}``.
+ for key in ("name", "uid", "ip", "hostname"):
+ inner = value.get(key)
+ if isinstance(inner, str) and inner.strip():
+ return inner.strip()
+ return None
+
+
+def _coerce_float(value: Any) -> float | None:
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int | float):
+ return float(value)
+ if isinstance(value, str):
+ try:
+ return float(value.strip())
+ except ValueError:
+ return None
+ return None
+
+
+def _parse_time(fields: dict[str, Any], message: dict[str, Any]) -> datetime | None:
+ for source in (fields, message):
+ for name in ("time", "timestamp", "ts", "event_time", "@timestamp"):
+ value = source.get(name)
+ if isinstance(value, int | float) and value > 0:
+ # OCSF publishes epoch milliseconds; anything past year 2286 in
+ # seconds is really milliseconds.
+ seconds = value / 1000.0 if value > 10_000_000_000 else float(value)
+ try:
+ return datetime.fromtimestamp(seconds, tz=UTC)
+ except (OverflowError, OSError, ValueError):
+ continue
+ if isinstance(value, str) and value.strip():
+ try:
+ return datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
+ except ValueError:
+ continue
+ return None
+
+
+def _entity(fields: dict[str, Any]) -> tuple[str, str] | None:
+ """Pick the entity this event is about, most specific identity first.
+
+ A user is preferred over a host and a host over an address because a
+ behavioural baseline is only meaningful for something that behaves. An IP
+ is the last resort, and the least stable: DHCP and NAT both make it a
+ different subject over time.
+ """
+ user = _first_str(fields, _USER_FIELDS)
+ if user:
+ return "user", user
+ host = _first_str(fields, _HOST_FIELDS)
+ if host:
+ return "device", host
+ ip = _first_str(fields, _IP_FIELDS)
+ if ip:
+ return "ip", ip
+ return None
+
+
+def _event_type(fields: dict[str, Any], ocsf: dict[str, Any]) -> str:
+ for name in ("event_type", "activity_name", "class_name", "category_name"):
+ value = fields.get(name) or ocsf.get(name)
+ if isinstance(value, str) and value.strip():
+ return value.strip().lower()
+ class_uid = ocsf.get("class_uid")
+ if isinstance(class_uid, int):
+ return f"class_{class_uid}"
+ return "unknown"
+
+
+def _features(fields: dict[str, Any], message: dict[str, Any]) -> dict[str, float]:
+ features: dict[str, float] = {}
+
+ when = _parse_time(fields, message)
+ if when is not None:
+ features["hour_of_day"] = float(when.hour)
+ features["day_of_week"] = float(when.weekday())
+
+ outcome = fields.get("outcome") or fields.get("status") or fields.get("result")
+ if isinstance(outcome, str) and outcome.strip():
+ features["is_failure"] = 1.0 if outcome.strip().lower() in _FAILURE_VALUES else 0.0
+
+ severity = _coerce_float(fields.get("severity_id"))
+ if severity is not None:
+ features["severity_id"] = severity
+
+ lowered = {k.lower(): v for k, v in fields.items() if isinstance(k, str)}
+ for name in _NUMERIC_FIELDS:
+ number = _coerce_float(lowered.get(name))
+ if number is not None:
+ features[name] = number
+
+ return features
+
+
+def _from_preextracted(message: dict[str, Any]) -> ExtractedEvent | None:
+ """Accept the original ``security.events`` shape unchanged.
+
+ Kept because it is a documented contract and an operator may already be
+ producing it from their own pipeline. Nothing in this repository does, but
+ silently rejecting a shape the module docstring advertises would replace
+ one invisible failure with another.
+ """
+ tenant_id = message.get("tenant_id")
+ entity_id = message.get("entity_id")
+ raw_features = message.get("features")
+ if not isinstance(tenant_id, str) or not isinstance(entity_id, str):
+ return None
+ if not entity_id.strip() or not isinstance(raw_features, dict):
+ return None
+
+ features: dict[str, float] = {}
+ for key, value in raw_features.items():
+ number = _coerce_float(value)
+ if number is not None:
+ features[str(key)] = number
+ if not features:
+ return None
+
+ peer = message.get("peer_group_id")
+ source_id = message.get("event_id")
+ return ExtractedEvent(
+ tenant_id=tenant_id,
+ entity_type=str(message.get("entity_type") or "user"),
+ entity_id=entity_id.strip(),
+ event_type=str(message.get("event_type") or "unknown"),
+ features=features,
+ source_event_id=str(source_id) if isinstance(source_id, str) else None,
+ peer_group_id=str(peer) if isinstance(peer, str) and peer.strip() else None,
+ raw_features=dict(raw_features),
+ )
+
+
+def extract(message: dict[str, Any]) -> ExtractedEvent | None:
+ """Recover a scoreable event, or ``None`` if this message carries none.
+
+ ``None`` is a normal outcome, not an error: most telemetry names no
+ identity, and an event with no entity has no baseline to deviate from.
+ """
+ if not isinstance(message, dict):
+ return None
+
+ # A pre-extracted message is recognised by carrying its own feature map.
+ if isinstance(message.get("features"), dict):
+ return _from_preextracted(message)
+
+ ocsf = message.get("ocsf_event")
+ if not isinstance(ocsf, dict):
+ return None
+
+ tenant_id = message.get("tenant_id") or ocsf.get("tenant_uid")
+ if not isinstance(tenant_id, str) or not tenant_id.strip():
+ return None
+
+ fields = flat_fields(message)
+ if not fields:
+ return None
+
+ entity = _entity(fields)
+ if entity is None:
+ return None
+ entity_type, entity_id = entity
+
+ features = _features(fields, message)
+ if not features:
+ return None
+
+ source_id = message.get("event_id") or ocsf.get("uid") or fields.get("event_id")
+ return ExtractedEvent(
+ tenant_id=tenant_id.strip(),
+ entity_type=entity_type,
+ entity_id=entity_id,
+ event_type=_event_type(fields, ocsf),
+ features=features,
+ source_event_id=str(source_id) if source_id else None,
+ )
diff --git a/services/ueba/app/services/kafka_consumer.py b/services/ueba/app/services/kafka_consumer.py
index 088a2ab4c..609b6c9cd 100644
--- a/services/ueba/app/services/kafka_consumer.py
+++ b/services/ueba/app/services/kafka_consumer.py
@@ -1,6 +1,11 @@
"""Kafka consumer — reads security events, scores them, emits anomalies.
-Message schema (JSON, ``security.events`` topic):
+The consumer reads ``aisoc.raw_events``: the ingest-normalized OCSF envelope
+that every connector and webhook already produces. Entity and features are
+recovered by :mod:`app.services.feature_extraction`, which also still accepts
+the pre-extracted shape below for operators feeding UEBA from their own
+pipeline:
+
{
"event_id": "uuid-string",
"tenant_id": "uuid-string",
@@ -41,6 +46,7 @@ from typing import Any
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.core.config import settings
+from app.services.feature_extraction import extract
from app.services.peer_group import PeerGroupService
from app.services.scoring import ScoringService
@@ -60,32 +66,24 @@ class UEBAKafkaConsumer:
LOG.warning("Invalid JSON message; skipping.")
return
- tenant_id_raw = msg.get("tenant_id")
- entity_type = msg.get("entity_type", "user")
- entity_id = msg.get("entity_id", "")
- event_type = msg.get("event_type", "unknown")
- peer_group_id = msg.get("peer_group_id")
- features_raw = msg.get("features", {})
- source_event_id = msg.get("event_id")
-
- if not tenant_id_raw or not entity_id:
- LOG.debug("Skipping message: missing tenant_id or entity_id")
+ # An event with no recoverable entity or no numeric feature is a
+ # normal outcome, not an error — most telemetry names no identity, and
+ # something with no baseline cannot deviate from one.
+ event = extract(msg)
+ if event is None:
return
+ entity_type = event.entity_type
+ entity_id = event.entity_id
+ event_type = event.event_type
+ peer_group_id = event.peer_group_id
+ features = event.features
+ source_event_id = event.source_event_id
+
try:
- tenant_id = uuid.UUID(tenant_id_raw)
+ tenant_id = uuid.UUID(event.tenant_id)
except ValueError:
- LOG.warning("Invalid tenant_id: %s", tenant_id_raw)
- return
-
- features: dict[str, float] = {}
- for k, v in features_raw.items():
- try:
- features[k] = float(v)
- except (TypeError, ValueError):
- pass # non-numeric feature value; skip
-
- if not features:
+ LOG.warning("Invalid tenant_id: %s", event.tenant_id)
return
async with self._session_factory() as session:
diff --git a/services/ueba/tests/test_feature_extraction.py b/services/ueba/tests/test_feature_extraction.py
new file mode 100644
index 000000000..26366bde5
--- /dev/null
+++ b/services/ueba/tests/test_feature_extraction.py
@@ -0,0 +1,171 @@
+"""UEBA must be able to score the events the platform actually publishes.
+
+The consumer's input topic used to default to ``security.events``, which no
+service writes, so every test of the scorer passed while the scorer never ran
+on a real message. These tests are written against the envelope
+``services/ingest`` publishes on ``aisoc.raw_events`` — the same shape the
+fusion detection engines consume — so a change to that envelope breaks them
+here rather than silently in production.
+"""
+
+from __future__ import annotations
+
+import json
+
+from app.services.feature_extraction import extract, flat_fields
+
+TENANT = "11111111-1111-1111-1111-111111111111"
+
+
+def _envelope(raw_event: dict | None = None, **ocsf) -> dict:
+ """An ingest envelope, with the vendor payload nested where connectors put it."""
+ event: dict = {"class_uid": 3002, "severity_id": 3, **ocsf}
+ if raw_event is not None:
+ event["raw_event"] = raw_event
+ return {"tenant_id": TENANT, "ocsf_event": event}
+
+
+class TestFlatFields:
+ def test_recovers_vendor_fields_nested_under_raw_event(self):
+ # The bug this guards: connectors nest the untouched vendor payload one
+ # level down, so a consumer reading the envelope flat sees None for
+ # every vendor field.
+ msg = _envelope(raw_event={"user": "alice", "src_ip": "10.0.0.5"})
+ assert flat_fields(msg)["user"] == "alice"
+ assert flat_fields(msg)["src_ip"] == "10.0.0.5"
+
+ def test_connector_normalized_keys_win_over_raw_vendor_values(self):
+ # A connector that mapped a vendor ladder onto AiSOC's five tiers must
+ # not have that undone by the raw value underneath.
+ msg = _envelope(raw_event={"severity_id": 99}, severity_id=4)
+ assert flat_fields(msg)["severity_id"] == 4
+
+ def test_parses_raw_data_when_it_is_a_json_string(self):
+ msg = {
+ "tenant_id": TENANT,
+ "ocsf_event": {"raw_data": json.dumps({"user": "bob", "outcome": "failure"})},
+ }
+ assert flat_fields(msg)["user"] == "bob"
+
+ def test_non_dict_envelope_yields_nothing(self):
+ assert flat_fields({"ocsf_event": "not-a-dict"}) == {}
+ assert flat_fields({}) == {}
+
+
+class TestEntitySelection:
+ def test_prefers_user_over_host_and_ip(self):
+ msg = _envelope(raw_event={"user": "alice", "hostname": "web-1", "src_ip": "10.0.0.5", "time": 0})
+ event = extract(msg)
+ assert event is not None
+ assert (event.entity_type, event.entity_id) == ("user", "alice")
+
+ def test_falls_back_to_host_then_ip(self):
+ host = extract(_envelope(raw_event={"hostname": "web-1", "time": 0}))
+ assert host is not None and (host.entity_type, host.entity_id) == ("device", "web-1")
+
+ ip = extract(_envelope(raw_event={"src_ip": "10.0.0.5", "time": 0}))
+ assert ip is not None and (ip.entity_type, ip.entity_id) == ("ip", "10.0.0.5")
+
+ def test_unwraps_ocsf_nested_identity(self):
+ msg = _envelope(raw_event={"actor": {"name": "svc-deploy"}, "time": 0})
+ event = extract(msg)
+ assert event is not None
+ assert event.entity_id == "svc-deploy"
+
+ def test_event_with_no_identity_is_skipped(self):
+ # Not an error. Most telemetry names nobody, and something with no
+ # baseline cannot deviate from one.
+ assert extract(_envelope(raw_event={"message": "disk usage 61%"})) is None
+
+
+class TestFeatures:
+ def test_derives_hour_and_weekday_from_epoch_millis(self):
+ # 2026-09-23T18:30:00Z is a Wednesday (weekday 2).
+ msg = _envelope(raw_event={"user": "alice", "time": 1790188200000})
+ event = extract(msg)
+ assert event is not None
+ assert event.features["hour_of_day"] == 18.0
+ assert event.features["day_of_week"] == 2.0
+
+ def test_accepts_iso8601_timestamps(self):
+ msg = _envelope(raw_event={"user": "alice", "time": "2026-09-23T06:15:00Z"})
+ event = extract(msg)
+ assert event is not None
+ assert event.features["hour_of_day"] == 6.0
+
+ def test_outcome_becomes_a_failure_indicator(self):
+ failed = extract(_envelope(raw_event={"user": "alice", "outcome": "Denied", "time": 0}))
+ assert failed is not None and failed.features["is_failure"] == 1.0
+
+ ok = extract(_envelope(raw_event={"user": "alice", "outcome": "success", "time": 0}))
+ assert ok is not None and ok.features["is_failure"] == 0.0
+
+ def test_numeric_vendor_magnitudes_are_carried_through(self):
+ msg = _envelope(raw_event={"user": "alice", "bytes_out": "1048576", "duration_ms": 250, "time": 0})
+ event = extract(msg)
+ assert event is not None
+ assert event.features["bytes_out"] == 1048576.0
+ assert event.features["duration_ms"] == 250.0
+
+ def test_booleans_are_not_treated_as_numbers(self):
+ # bool is a subclass of int in Python, so an unguarded float() turns
+ # True into a 1.0 magnitude that means nothing.
+ msg = _envelope(raw_event={"user": "alice", "bytes_out": True, "time": 0})
+ event = extract(msg)
+ assert event is not None
+ assert "bytes_out" not in event.features
+
+ def test_no_scoreable_feature_means_no_event(self):
+ # An entity with nothing measurable about it must not reach the scorer,
+ # which would log it as unscoreable on every single message. Built by
+ # hand rather than via _envelope, which always stamps a severity.
+ msg = {"tenant_id": TENANT, "ocsf_event": {"raw_event": {"user": "alice", "note": "hello"}}}
+ assert extract(msg) is None
+
+
+class TestEventType:
+ def test_uses_the_vendor_event_type_when_present(self):
+ msg = _envelope(raw_event={"user": "a", "event_type": "Authentication", "time": 0})
+ event = extract(msg)
+ assert event is not None and event.event_type == "authentication"
+
+ def test_falls_back_to_the_ocsf_class(self):
+ msg = _envelope(raw_event={"user": "a", "time": 0}, class_uid=3002)
+ event = extract(msg)
+ assert event is not None and event.event_type == "class_3002"
+
+
+class TestPreExtractedShape:
+ def test_the_documented_security_events_shape_still_works(self):
+ event = extract(
+ {
+ "event_id": "evt-1",
+ "tenant_id": TENANT,
+ "entity_type": "user",
+ "entity_id": "[email protected]",
+ "event_type": "login",
+ "peer_group_id": "dept:engineering",
+ "features": {"hour_of_day": 3, "login_count": "7", "label": "ignored"},
+ }
+ )
+ assert event is not None
+ assert event.entity_id == "[email protected]"
+ assert event.peer_group_id == "dept:engineering"
+ assert event.source_event_id == "evt-1"
+ # Non-numeric values are dropped rather than failing the whole message.
+ assert event.features == {"hour_of_day": 3.0, "login_count": 7.0}
+
+ def test_missing_tenant_is_rejected(self):
+ assert extract({"entity_id": "alice", "features": {"hour_of_day": 3}}) is None
+
+
+class TestTenantScoping:
+ def test_tenant_comes_from_the_envelope(self):
+ event = extract(_envelope(raw_event={"user": "alice", "time": 0}))
+ assert event is not None and event.tenant_id == TENANT
+
+ def test_untenanted_event_is_refused(self):
+ # Scoring an event into no tenant's baseline, or every tenant's, are
+ # both wrong. Refusing is the only safe option.
+ msg = {"ocsf_event": {"raw_event": {"user": "alice", "time": 0}}}
+ assert extract(msg) is None