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.

One activity projection on every event: actor kind derived from the vendor's own field, never guessed (#1204)

Beenu Arora785280d86dfb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 9524edd38..0cc054fd9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -649,6 +649,17 @@ jobs:
run: python3 scripts/check_connector_profiles.py --self-test
- name: Connector profile drift gate
run: python3 scripts/check_connector_profiles.py
+ # The activity projection lives in five hand-written lists: the Go, the
+ # lake's CREATE TABLE, the lake's migration, the fusion writer's column
+ # tuple and the graph schema. Three of the disagreements between them
+ # are silent, and the one nothing checked is the pair of lake files —
+ # 001_init.sql runs only in the container entrypoint on a fresh volume,
+ # so a column added there alone exists on new installs and on no
+ # upgrade.
+ - name: Activity projection drift gate — self-test
+ run: python3 scripts/check_activity_projection.py --self-test
+ - name: Activity projection drift gate
+ run: python3 scripts/check_activity_projection.py
# The same shape one layer over: an inbox template that ships has to be
# mintable, and a mintable id has to have a template to apply. Both
# directions, because only one of them was ever checked informally and
diff --git a/schemas/graph-schema.yaml b/schemas/graph-schema.yaml
index 0c5f12881..5a1729726 100644
--- a/schemas/graph-schema.yaml
+++ b/schemas/graph-schema.yaml
@@ -20,7 +20,7 @@
# are reconciled from configuration snapshots and carry `snapshot_id` and a
# `valid_from`/`valid_to` window instead.
-version: v1.1
+version: v1.2
# ---------------------------------------------------------------------------
# Node labels
@@ -51,6 +51,12 @@ node_labels:
- { name: department, type: string, required: false }
- { name: manager_id, type: string, required: false }
- { name: status, type: string, required: false }
+ # v1.2 activity projection. actor_kind is written on every event,
+ # including as `unknown`, because the absence of the property and a
+ # source that declined to say are different facts.
+ - { name: actor_kind, type: string, required: false }
+ - { name: actor_kind_source, type: string, required: false }
+ - { name: on_behalf_of, type: string, required: false }
- label: ServiceAccount
description: >-
@@ -62,6 +68,10 @@ node_labels:
- { name: kind, type: string, required: false }
- { name: owner_user_id, type: string, required: false }
- { name: created_at, type: datetime, required: false }
+ # v1.2 activity projection — see the User label for the rule.
+ - { name: actor_kind, type: string, required: false }
+ - { name: actor_kind_source, type: string, required: false }
+ - { name: on_behalf_of, type: string, required: false }
- label: Role
description: >-
@@ -187,6 +197,18 @@ node_labels:
- { name: port, type: int, required: false }
- { name: direction, type: string, required: false }
- { name: observed_at, type: datetime, required: false }
+ # v1.2 activity projection, written on the source side only: the
+ # geography and ASN describe where the action came from, and putting
+ # them on the destination would attribute the caller's country to the
+ # thing they reached. reputation_known separates a clean verdict from
+ # an enrichment service that did not answer.
+ - { name: country_code, type: string, required: false }
+ - { name: asn, type: int, required: false }
+ - { name: as_org, type: string, required: false }
+ - { name: reputation, type: float, required: false }
+ - { name: reputation_known, type: bool, required: false }
+ - { name: client_family, type: string, required: false }
+ - { name: client_category, type: string, required: false }
- label: SaaSApp
description: >-
diff --git a/scripts/check_activity_projection.py b/scripts/check_activity_projection.py
new file mode 100644
index 000000000..fe3b96e2a
--- /dev/null
+++ b/scripts/check_activity_projection.py
@@ -0,0 +1,501 @@
+#!/usr/bin/env python3
+"""The activity projection says the same thing in all five places it lives.
+
+Why this exists
+---------------
+Depth plan 2.2 puts one projection — who acted, what kind of actor they were,
+what they did, to which resource, from where, with what outcome — on every
+normalized event, and then carries it into four more places: the lake's
+``CREATE TABLE``, the lake's migration list, the fusion writer's column
+tuple, and the graph schema. Five hand-written lists of the same thing, which
+is five chances for them to disagree.
+
+Three of those disagreements are silent, and one of them is a trap this
+repository has already documented without closing:
+
+**``001_init.sql`` and ``lake_migrations.py`` are read by different
+deployments.** The SQL file runs only in the ClickHouse container entrypoint,
+on a fresh volume. An existing deployment gets its schema from the migration
+list and never sees the file again. `lake_migrations.py`'s own docstring says
+so — "a new column lands on a fresh deployment and silently does not land on
+an existing one" — and before this gate nothing compared the two. A column
+added to one alone produces a lake where the same query works on a new
+install and fails on every upgrade, discovered whenever somebody selects it.
+
+**The writer's column tuple is positional.** ``_INSERT_SQL`` is built by
+joining ``_COLUMNS``, and the row dict is read in that order. A column in the
+tuple that the table does not have fails the insert; a column the table has
+that the tuple omits is silently always default.
+
+**``actor.kind`` must be a closed set.** It is the field that separates a
+person from the app or token acting for them, and every later surface — a
+privilege decision, a blast radius, an auto-close — treats it as evidence. A
+derivation returning a value outside the set reaches a ``LowCardinality``
+column and a graph property as something nothing queries for.
+
+What it checks
+--------------
+ GO -> SQL every lake column the writer sends exists in the CREATE TABLE
+ GO -> MIGR and in the migration that adds it, so both deployment paths
+ converge on the same schema
+ SQL <-> MIGR in both directions, which is the one nothing checked
+ KIND every ActorKind constant is in ActorKinds, the lake's
+ documented set and nothing else; and every derivation that
+ returns a kind also names the vendor field it read it from,
+ because an unsourced kind is a guess wearing a type
+ GRAPH every property in ActivityNodeProperties is declared on that
+ label in schemas/graph-schema.yaml, in both directions
+
+Usage
+-----
+ python3 scripts/check_activity_projection.py
+ python3 scripts/check_activity_projection.py --json
+ python3 scripts/check_activity_projection.py --self-test
+
+``--repo-root`` overrides the tree. Every input is named before the verdict
+and an empty read is a hard error, never a quiet pass.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from gate_toolkit import repo_root
+
+ACTIVITY_REL = Path("services/ingest/internal/activity/activity.go")
+ACTOR_REL = Path("services/ingest/internal/activity/actor.go")
+GRAPH_SCHEMA_GO_REL = Path("services/ingest/internal/graph/schema.go")
+GRAPH_SCHEMA_YAML_REL = Path("schemas/graph-schema.yaml")
+INIT_SQL_REL = Path("services/api/clickhouse/001_init.sql")
+LAKE_MIGRATIONS_REL = Path("services/api/app/db/lake_migrations.py")
+LAKE_WRITER_REL = Path("services/fusion/app/services/lake_writer.py")
+
+#: Columns the writer sends that 001_init.sql declares but no migration adds,
+#: because they predate the migration mechanism. Everything the projection
+#: adds must appear in both.
+PRE_MIGRATION_COLUMNS = {
+ "event_id",
+ "tenant_id",
+ "event_time",
+ # Declared with a DEFAULT and never sent by the writer, which is why it
+ # is in the table and not in _COLUMNS.
+ "ingest_time",
+ "class_uid",
+ "category_uid",
+ "severity_id",
+ "severity",
+ "activity_id",
+ "source_ip",
+ "dest_ip",
+ "src_port",
+ "dst_port",
+ "protocol",
+ "src_hostname",
+ "dst_hostname",
+ "user_name",
+ "process_name",
+ "file_path",
+ "hash_sha256",
+ "connector_type",
+ "raw_payload",
+ "ocsf_json",
+ "mitre_techniques",
+ "mitre_tactics",
+ "iocs",
+}
+
+
+class GateError(RuntimeError):
+ """An input could not be read. Never downgraded to a passing result."""
+
+
+def parse_actor_kinds(src: str) -> tuple[set[str], set[str]]:
+ """(constants declared, members of the ActorKinds slice)."""
+ declared = set(re.findall(r'^\tActor\w+\s+ActorKind = "([a-z_]+)"$', src, re.MULTILINE))
+ match = re.search(r"var ActorKinds = \[\]ActorKind\{(.*?)\}", src, re.DOTALL)
+ if not match:
+ raise GateError("could not find the ActorKinds slice")
+ names = set(re.findall(r"\bActor(\w+)\b", match.group(1)))
+ by_const = dict(re.findall(r"^\tActor(\w+)\s+ActorKind = \"([a-z_]+)\"$", src, re.MULTILINE))
+ listed = {by_const[n] for n in names if n in by_const}
+ return declared, listed
+
+
+def parse_kind_returns(src: str) -> list[tuple[str, str]]:
+ """Every `return ActorX, "source"` in the derivations, as (kind, source)."""
+ return re.findall(r'return\s+Actor(\w+),\s*"([^"]*)"', src)
+
+
+def parse_sql_columns(src: str) -> set[str]:
+ """Column names declared inside the raw_events CREATE TABLE."""
+ start = src.find("CREATE TABLE IF NOT EXISTS aisoc.raw_events (")
+ if start == -1:
+ raise GateError("could not find the raw_events CREATE TABLE")
+ depth, body_start = 0, src.index("(", start)
+ for i in range(body_start, len(src)):
+ if src[i] == "(":
+ depth += 1
+ elif src[i] == ")":
+ depth -= 1
+ if depth == 0:
+ body = src[body_start + 1 : i]
+ break
+ else:
+ raise GateError("unbalanced parentheses in the raw_events CREATE TABLE")
+
+ columns: set[str] = set()
+ for line in body.splitlines():
+ line = line.strip()
+ if not line or line.startswith("--") or line.startswith("INDEX "):
+ continue
+ name = line.split()[0]
+ if re.fullmatch(r"[a-z_][a-z0-9_]*", name):
+ columns.add(name)
+ return columns
+
+
+def parse_migration_columns(src: str) -> set[str]:
+ """Columns added by an ALTER ... ADD COLUMN in the lake migration list."""
+ return set(re.findall(r"ADD COLUMN IF NOT EXISTS (\w+)", src))
+
+
+def parse_writer_columns(src: str) -> set[str]:
+ match = re.search(r"^_COLUMNS = \((.*?)^\)", src, re.DOTALL | re.MULTILINE)
+ if not match:
+ raise GateError("could not find _COLUMNS in the lake writer")
+ return set(re.findall(r'"(\w+)"', match.group(1)))
+
+
+def parse_graph_go_properties(src: str) -> dict[str, set[str]]:
+ match = re.search(r"var ActivityNodeProperties = map\[NodeLabel\]\[\]string\{(.*?)\n\}", src, re.DOTALL)
+ if not match:
+ raise GateError("could not find ActivityNodeProperties in the graph schema")
+ out: dict[str, set[str]] = {}
+ label_const = dict(re.findall(r'^\tNode(\w+)\s+NodeLabel = "(\w+)"$', src, re.MULTILINE))
+ for const, body in re.findall(r"Node(\w+):\s*\{(.*?)\}", match.group(1), re.DOTALL):
+ label = label_const.get(const, const)
+ out[label] = set(re.findall(r'"(\w+)"', body))
+ return out
+
+
+def parse_graph_yaml_properties(src: str) -> dict[str, set[str]]:
+ """label -> declared property names, from the node_labels block."""
+ out: dict[str, set[str]] = {}
+ label = None
+ for line in src.splitlines():
+ label_match = re.match(r"^\s*-\s*label:\s*(\w+)\s*$", line)
+ if label_match:
+ label = label_match.group(1)
+ out.setdefault(label, set())
+ continue
+ if label and (prop := re.match(r"^\s*-\s*\{\s*name:\s*([a-z_]+)", line)):
+ out[label].add(prop.group(1))
+ # A new top-level key ends the node_labels block.
+ if re.match(r"^[a-z_]+:", line):
+ label = None
+ return out
+
+
+def evaluate(
+ kinds_declared: set[str],
+ kinds_listed: set[str],
+ kind_returns: list[tuple[str, str]],
+ sql_columns: set[str],
+ migration_columns: set[str],
+ writer_columns: set[str],
+ graph_go: dict[str, set[str]],
+ graph_yaml: dict[str, set[str]],
+) -> tuple[list[tuple[str, str]], dict]:
+ failures: list[tuple[str, str]] = []
+
+ # KIND. The closed set has to be closed in both directions, or a
+ # consumer reading ActorKinds sees a different vocabulary from the one
+ # the derivations can produce.
+ for kind in sorted(kinds_declared - kinds_listed):
+ failures.append(
+ (
+ "kind-not-listed",
+ f"ActorKind {kind!r} is declared but is not in ActorKinds, so the lake's enum and the gate "
+ "that reads it do not know about a value the derivations can produce",
+ )
+ )
+ for kind in sorted(kinds_listed - kinds_declared):
+ failures.append(("kind-not-declared", f"ActorKinds lists {kind!r}, which no constant declares"))
+
+ # KIND. An unsourced kind is a guess wearing a type. The one exception
+ # is `unknown`, which is precisely the answer that was read from no
+ # field — and it must carry no source, for the same reason.
+ for const, source in kind_returns:
+ kind = const.lower()
+ if kind == "unknown":
+ if source:
+ failures.append(
+ (
+ "unknown-kind-has-a-source",
+ f"a derivation returns unknown alongside the source {source!r}; unknown means no field "
+ "answered, so naming one would make a reviewer check a derivation that did not happen",
+ )
+ )
+ continue
+ if not source:
+ failures.append(
+ (
+ "kind-without-a-source",
+ f"a derivation returns {kind!r} naming no vendor field. actor.kind is evidence downstream, "
+ "and a kind no field produced is a guess",
+ )
+ )
+
+ # LAKE. Three lists, compared pairwise in both directions.
+ for column in sorted(writer_columns - sql_columns):
+ failures.append(
+ (
+ "writer-column-not-in-table",
+ f"the lake writer sends {column!r}, which the raw_events CREATE TABLE does not declare; "
+ "the insert is positional, so this fails at write time on a fresh deployment",
+ )
+ )
+ for column in sorted(writer_columns - migration_columns - PRE_MIGRATION_COLUMNS):
+ failures.append(
+ (
+ "writer-column-not-migrated",
+ f"the lake writer sends {column!r} and no lake migration adds it. 001_init.sql runs only in "
+ "the container entrypoint on a fresh volume, so an existing deployment never gets this column",
+ )
+ )
+ for column in sorted(migration_columns - sql_columns):
+ failures.append(
+ (
+ "migrated-column-not-in-table",
+ f"a lake migration adds {column!r} but the CREATE TABLE does not declare it, so a fresh "
+ "deployment and an upgraded one end up with different schemas",
+ )
+ )
+ for column in sorted(sql_columns - migration_columns - PRE_MIGRATION_COLUMNS):
+ failures.append(
+ (
+ "table-column-not-migrated",
+ f"the CREATE TABLE declares {column!r} and no migration adds it; it will exist on a fresh "
+ "deployment and be missing on every upgrade",
+ )
+ )
+
+ # GRAPH. Both directions, because the YAML is what the drift gate and
+ # the published schema doc read and the Go is what the writer uses.
+ for label, properties in sorted(graph_go.items()):
+ declared = graph_yaml.get(label)
+ if declared is None:
+ failures.append(("graph-label-missing", f"ActivityNodeProperties names label {label!r}, which the YAML does not declare"))
+ continue
+ for prop in sorted(properties - declared):
+ failures.append(
+ (
+ "graph-property-undeclared",
+ f"the writer puts {prop!r} on {label}, and schemas/graph-schema.yaml does not declare it",
+ )
+ )
+
+ stats = {
+ "actor_kinds": sorted(kinds_listed),
+ "kind_derivations": len([s for _, s in kind_returns if s]),
+ "lake_columns": len(writer_columns),
+ "projection_columns": sorted(writer_columns & migration_columns),
+ "graph_labels": sorted(graph_go),
+ }
+ return failures, stats
+
+
+def load(root: Path) -> dict:
+ paths = {
+ "activity": root / ACTIVITY_REL,
+ "actor": root / ACTOR_REL,
+ "graph_go": root / GRAPH_SCHEMA_GO_REL,
+ "graph_yaml": root / GRAPH_SCHEMA_YAML_REL,
+ "init_sql": root / INIT_SQL_REL,
+ "migrations": root / LAKE_MIGRATIONS_REL,
+ "writer": root / LAKE_WRITER_REL,
+ }
+ for name, path in paths.items():
+ if not path.exists():
+ raise GateError(f"expected input does not exist: {path} ({name})")
+
+ activity_src = paths["activity"].read_text(encoding="utf-8")
+ declared, listed = parse_actor_kinds(activity_src)
+ data = {
+ "kinds_declared": declared,
+ "kinds_listed": listed,
+ "kind_returns": parse_kind_returns(paths["actor"].read_text(encoding="utf-8")),
+ "sql_columns": parse_sql_columns(paths["init_sql"].read_text(encoding="utf-8")),
+ "migration_columns": parse_migration_columns(paths["migrations"].read_text(encoding="utf-8")),
+ "writer_columns": parse_writer_columns(paths["writer"].read_text(encoding="utf-8")),
+ "graph_go": parse_graph_go_properties(paths["graph_go"].read_text(encoding="utf-8")),
+ "graph_yaml": parse_graph_yaml_properties(paths["graph_yaml"].read_text(encoding="utf-8")),
+ }
+ required = (
+ "kinds_declared",
+ "kinds_listed",
+ "kind_returns",
+ "sql_columns",
+ "migration_columns",
+ "writer_columns",
+ "graph_go",
+ "graph_yaml",
+ )
+ for name in required:
+ if not data[name]:
+ raise GateError(f"parsed zero {name} — refusing to report a clean tree from an empty read")
+ return data
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--repo-root", type=Path, default=repo_root())
+ parser.add_argument("--json", action="store_true")
+ parser.add_argument("--self-test", action="store_true", help="prove the gate detects what it claims to")
+ args = parser.parse_args(argv)
+
+ if args.self_test:
+ return self_test(args.repo_root.resolve())
+
+ root = args.repo_root.resolve()
+ try:
+ data = load(root)
+ except GateError as exc:
+ print(f"check_activity_projection: FAILED to read the tree: {exc}", file=sys.stderr)
+ return 2
+
+ failures, stats = evaluate(**data)
+
+ if args.json:
+ report = {"repo_root": str(root), **stats, "failures": [{"code": c, "detail": d} for c, d in failures]}
+ print(json.dumps(report, indent=2, sort_keys=True))
+ return 1 if failures else 0
+
+ print(f"repo root {root}")
+ print(f"projection {ACTIVITY_REL} ({len(stats['actor_kinds'])} actor kinds)")
+ print(f"derivations {ACTOR_REL} ({stats['kind_derivations']} kinds returned, each naming a vendor field)")
+ print(f"lake table {INIT_SQL_REL} ({len(data['sql_columns'])} columns)")
+ print(f"lake migrations {LAKE_MIGRATIONS_REL} ({len(data['migration_columns'])} columns added)")
+ print(f"lake writer {LAKE_WRITER_REL} ({stats['lake_columns']} columns sent)")
+ print(f"graph {GRAPH_SCHEMA_GO_REL} / {GRAPH_SCHEMA_YAML_REL} ({', '.join(stats['graph_labels'])})")
+ print()
+ print(f"actor kinds {', '.join(stats['actor_kinds'])}")
+ print(f"projection cols {len(stats['projection_columns'])} in the table, the migration and the writer")
+ print()
+ if failures:
+ print(f"FAIL — {len(failures)} finding(s):")
+ for code, detail in failures:
+ print(f" [{code}] {detail}")
+ return 1
+ print("OK — the projection says the same thing in the Go, the lake table, the lake")
+ print(" migration, the fusion writer and the graph schema.")
+ return 0
+
+
+def self_test(root: Path) -> int:
+ """Inject each defect the gate claims to catch and require it to bite."""
+ try:
+ base = load(root)
+ except GateError as exc:
+ print(f"self-test: cannot read the tree: {exc}", file=sys.stderr)
+ return 2
+
+ clean, _ = evaluate(**base)
+ if clean:
+ print("self-test: the unmodified tree already fails; fix that first", file=sys.stderr)
+ for code, detail in clean:
+ print(f" [{code}] {detail}", file=sys.stderr)
+ return 1
+
+ def mutate(**overrides) -> dict:
+ data = {k: (v.copy() if hasattr(v, "copy") else v) for k, v in base.items()}
+ for key, fn in overrides.items():
+ fn(data[key])
+ return data
+
+ cases = [
+ (
+ "KIND: a constant missing from the closed-set slice",
+ "kind-not-listed",
+ mutate(kinds_declared=lambda s: s.add("contractor")),
+ ),
+ (
+ "KIND: the slice naming something no constant declares",
+ "kind-not-declared",
+ mutate(kinds_listed=lambda s: s.add("robot")),
+ ),
+ (
+ "KIND: a derivation returning a kind it read from no field",
+ "kind-without-a-source",
+ mutate(kind_returns=lambda lst: lst.append(("Human", ""))),
+ ),
+ (
+ "KIND: an unknown kind claiming a source",
+ "unknown-kind-has-a-source",
+ mutate(kind_returns=lambda lst: lst.append(("Unknown", "a.field"))),
+ ),
+ (
+ "LAKE: the writer sending a column the table does not declare",
+ "writer-column-not-in-table",
+ mutate(writer_columns=lambda s: s.add("actor_shoe_size")),
+ ),
+ (
+ "LAKE: a column in the table that no migration adds, so upgrades never get it",
+ "table-column-not-migrated",
+ mutate(sql_columns=lambda s: s.add("added_to_the_sql_file_only")),
+ ),
+ (
+ "LAKE: a column a migration adds that the table does not declare",
+ "migrated-column-not-in-table",
+ mutate(migration_columns=lambda s: s.add("added_to_the_migration_only")),
+ ),
+ (
+ "GRAPH: a property the writer sets that the YAML does not declare",
+ "graph-property-undeclared",
+ mutate(graph_go=lambda d: d.__setitem__("User", d["User"] | {"undeclared_property"})),
+ ),
+ (
+ "GRAPH: a label in the Go that the YAML does not carry",
+ "graph-label-missing",
+ mutate(graph_go=lambda d: d.__setitem__("Phantom", {"x"})),
+ ),
+ ]
+
+ print(f"self-test against {root}")
+ print("clean tree: 0 failures (the baseline every case below perturbs)\n")
+ ok = True
+ for description, expected_code, data in cases:
+ found, _ = evaluate(**data)
+ codes = {code for code, _ in found}
+ caught = expected_code in codes
+ ok &= caught
+ print(f" {'PASS' if caught else 'FAIL'} {description}")
+ print(f" expected [{expected_code}] got {sorted(codes) or 'nothing'}")
+
+ empty_refused = True
+ try:
+ load(Path("/nonexistent-tree-for-the-self-test"))
+ empty_refused = False
+ except GateError:
+ # Refusing an empty tree is the behaviour under test, so the
+ # exception is the pass and there is nothing to handle.
+ pass
+ ok &= empty_refused
+ print(f" {'PASS' if empty_refused else 'FAIL'} TREE: a tree with no inputs is refused rather than reported clean")
+
+ print()
+ if not ok:
+ print("self-test FAILED: the gate did not catch what it claims to catch")
+ return 1
+ print(f"self-test OK: {len(cases)} injected defects plus the empty-tree case, each caught")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/services/api/app/db/lake_migrations.py b/services/api/app/db/lake_migrations.py
index 3385a2270..69f312e65 100644
--- a/services/api/app/db/lake_migrations.py
+++ b/services/api/app/db/lake_migrations.py
@@ -87,6 +87,47 @@ class LakeMigration:
_V1_BASELINE = ("CREATE DATABASE IF NOT EXISTS aisoc",)
+# ── 002: the activity projection ───────────────────────────────────────────
+#
+# Depth plan 2.2. Ingest now answers five questions on every event — who
+# acted, what kind of actor they were, what they did, to which resource, from
+# where, with what outcome — and the lake has to carry the answers as columns
+# rather than only inside `ocsf_json`, or a hunt for "every action by a
+# non-human actor from a new ASN" is a full scan of a ZSTD blob.
+#
+# `actor_kind` is a LowCardinality(String) and not an Enum: an Enum would
+# make adding a kind a schema migration on a table with months of data, and
+# the closed set lives in Go (`activity.ActorKinds`) where the gate can read
+# it. The bloom filters mirror the ones 001_init.sql already puts on the
+# high-cardinality hunt needles.
+_V2_ACTIVITY_PROJECTION = (
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS actor_kind LowCardinality(String) DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS actor_kind_source String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS actor_id String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS actor_on_behalf_of String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS action String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS resource_type String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS resource_id String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS resource_owner String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS src_country_code LowCardinality(String) DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS src_asn UInt32 DEFAULT 0",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS src_as_org String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS src_reputation Float32 DEFAULT 0",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS src_reputation_known UInt8 DEFAULT 0",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS client_family LowCardinality(String) DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS client_version String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS client_category LowCardinality(String) DEFAULT ''",
+ # The raw string is kept beside the parse because a user agent is
+ # attacker-controlled and every parser is a lossy summary of it. A tool
+ # renamed to "Mozilla/5.0" is itself the finding, and only the raw
+ # column can show it.
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS client_raw String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS outcome LowCardinality(String) DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD INDEX IF NOT EXISTS idx_action action TYPE bloom_filter(0.01) GRANULARITY 4",
+ "ALTER TABLE aisoc.raw_events ADD INDEX IF NOT EXISTS idx_resource_id resource_id TYPE bloom_filter(0.01) GRANULARITY 4",
+)
+
+
MIGRATIONS: tuple[LakeMigration, ...] = (
LakeMigration(
id="001_baseline",
@@ -94,6 +135,20 @@ MIGRATIONS: tuple[LakeMigration, ...] = (
statements=_V1_BASELINE,
tags=("baseline",),
),
+ LakeMigration(
+ id="002_activity_projection",
+ description=(
+ "Adds the activity projection columns (actor kind and identity, normalized action, resource, "
+ "source geography/ASN/reputation, parsed client, outcome) to aisoc.raw_events."
+ ),
+ statements=_V2_ACTIVITY_PROJECTION,
+ # Every statement is an ALTER on an existing table, which is exactly
+ # the case that needs ON CLUSTER on a multi-replica deployment. The
+ # repo names no cluster topology, so this is recorded rather than
+ # guessed, and the runner logs it on the way past.
+ needs_cluster_ddl=True,
+ tags=("activity-projection", "depth-2.2"),
+ ),
)
diff --git a/services/api/clickhouse/001_init.sql b/services/api/clickhouse/001_init.sql
index d054406e8..ec12a8f09 100644
--- a/services/api/clickhouse/001_init.sql
+++ b/services/api/clickhouse/001_init.sql
@@ -34,6 +34,38 @@ CREATE TABLE IF NOT EXISTS aisoc.raw_events (
mitre_techniques Array(String),
mitre_tactics Array(String),
iocs Array(String),
+ -- The activity projection (depth plan 2.2). Ingest answers five
+ -- questions on every event and the lake carries the answers as columns
+ -- rather than only inside ocsf_json, so a hunt for "every action by a
+ -- non-human actor from a new ASN" is not a full scan of a ZSTD blob.
+ --
+ -- Kept in lockstep with lake_migrations.py's 002_activity_projection,
+ -- which is what an *existing* deployment applies: this file only runs in
+ -- the container entrypoint on a fresh volume, so a column added here
+ -- alone would land on new deployments and silently not on old ones.
+ actor_kind LowCardinality(String) DEFAULT '',
+ actor_kind_source String DEFAULT '',
+ actor_id String DEFAULT '',
+ actor_on_behalf_of String DEFAULT '',
+ action String DEFAULT '',
+ resource_type String DEFAULT '',
+ resource_id String DEFAULT '',
+ resource_owner String DEFAULT '',
+ src_country_code LowCardinality(String) DEFAULT '',
+ src_asn UInt32 DEFAULT 0,
+ src_as_org String DEFAULT '',
+ src_reputation Float32 DEFAULT 0,
+ -- Zero and "nobody answered" are different facts: without this flag a
+ -- clean verdict and an unreachable enrichment service are the same row.
+ src_reputation_known UInt8 DEFAULT 0,
+ client_family LowCardinality(String) DEFAULT '',
+ client_version String DEFAULT '',
+ client_category LowCardinality(String) DEFAULT '',
+ -- The raw user agent beside the parse: it is attacker-controlled, every
+ -- parser is a lossy summary, and a tool renamed to "Mozilla/5.0" is
+ -- itself the finding.
+ client_raw String DEFAULT '',
+ outcome LowCardinality(String) DEFAULT '',
-- Data-skipping (bloom-filter) indexes so hunts over high-cardinality
-- needles (file hash, user, host, IOCs) skip granules instead of scanning
-- the whole ZSTD blob. GRANULARITY 4 = one index block per 4 * 8192 rows.
@@ -41,7 +73,9 @@ CREATE TABLE IF NOT EXISTS aisoc.raw_events (
INDEX idx_user user_name TYPE bloom_filter(0.01) GRANULARITY 4,
INDEX idx_src_host src_hostname TYPE bloom_filter(0.01) GRANULARITY 4,
INDEX idx_iocs iocs TYPE bloom_filter(0.01) GRANULARITY 4,
- INDEX idx_techniques mitre_techniques TYPE bloom_filter(0.01) GRANULARITY 4
+ INDEX idx_techniques mitre_techniques TYPE bloom_filter(0.01) GRANULARITY 4,
+ INDEX idx_action action TYPE bloom_filter(0.01) GRANULARITY 4,
+ INDEX idx_resource_id resource_id TYPE bloom_filter(0.01) GRANULARITY 4
)
-- ReplacingMergeTree collapses rows sharing the ORDER BY key, keeping the row
-- with the greatest ingest_time. Ingest now stamps a replay-stable event_id
diff --git a/services/api/tests/test_store_migrations.py b/services/api/tests/test_store_migrations.py
index 292ee700a..8073cc5e8 100644
--- a/services/api/tests/test_store_migrations.py
+++ b/services/api/tests/test_store_migrations.py
@@ -73,15 +73,23 @@ class TestLakeRunner:
return c
async def test_applies_and_records(self, client: AsyncMock) -> None:
+ """A fresh lake applies every declared migration, in declared order.
+
+ Derived from ``MIGRATIONS`` rather than written out, because a list
+ pinned here goes red on the next migration for no reason and teaches
+ whoever is adding one to edit the assertion instead of reading it.
+ """
applied = await lake_migrations.run_migrations(client)
- assert applied == ["001_baseline"]
+ assert applied == [m.id for m in lake_migrations.MIGRATIONS]
statements = [call.args[0] for call in client.execute.await_args_list]
assert any("_migrations" in s for s in statements), "ledger was not created"
assert any("INSERT INTO" in s for s in statements), "nothing was recorded"
async def test_an_applied_migration_is_not_reapplied(self, client: AsyncMock) -> None:
- client.execute = AsyncMock(return_value=[("001_baseline",)])
- assert await lake_migrations.run_migrations(client) == []
+ """A recorded id is skipped and everything after it still runs."""
+ first, *rest = lake_migrations.MIGRATIONS
+ client.execute = AsyncMock(return_value=[(first.id,)])
+ assert await lake_migrations.run_migrations(client) == [m.id for m in rest]
async def test_a_failure_stops_the_run(self, client: AsyncMock) -> None:
"""Migration N+1 is written against the schema N produced."""
diff --git a/services/fusion/app/services/lake_writer.py b/services/fusion/app/services/lake_writer.py
index 030357c66..6a9a1c564 100644
--- a/services/fusion/app/services/lake_writer.py
+++ b/services/fusion/app/services/lake_writer.py
@@ -75,6 +75,27 @@ _COLUMNS = (
"mitre_techniques",
"mitre_tactics",
"iocs",
+ # The activity projection ingest builds on every event (depth plan 2.2).
+ # These are columns and not only `ocsf_json` because a hunt that has to
+ # JSONExtract out of a ZSTD blob cannot use an index.
+ "actor_kind",
+ "actor_kind_source",
+ "actor_id",
+ "actor_on_behalf_of",
+ "action",
+ "resource_type",
+ "resource_id",
+ "resource_owner",
+ "src_country_code",
+ "src_asn",
+ "src_as_org",
+ "src_reputation",
+ "src_reputation_known",
+ "client_family",
+ "client_version",
+ "client_category",
+ "client_raw",
+ "outcome",
)
_INSERT_SQL = f"INSERT INTO aisoc.raw_events ({', '.join(_COLUMNS)}) VALUES"
@@ -103,6 +124,23 @@ def _as_str(value: Any) -> str:
return value if isinstance(value, str) else ("" if value is None else str(value))
+def _as_dict(value: Any) -> dict[str, Any]:
+ """A nested object, or an empty one — never None.
+
+ Sibling of `_as_str` and `_as_int` above, for the same reason: the
+ projection reads an envelope a connector shaped, so any level of it can
+ be missing or be the wrong type.
+ """
+ return value if isinstance(value, dict) else {}
+
+
+def _as_float(value: Any, default: float = 0.0) -> float:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return default
+
+
def _as_ip(value: Any) -> str:
"""Normalise to a valid IP string; '::' when absent/invalid.
@@ -195,6 +233,46 @@ def _iocs(ocsf: dict[str, Any]) -> list[str]:
return out
+def _activity_columns(ocsf: dict[str, Any]) -> dict[str, Any]:
+ """Flatten the activity projection ingest put on the event.
+
+ Every value is defaulted rather than left absent: ClickHouse's column
+ order is positional at insert time, so a row missing one key would shift
+ every column after it. An event from before depth plan 2.2, or from a
+ replayed topic, has no ``activity`` block at all and must still insert.
+
+ ``src_reputation_known`` is carried separately from the score because a
+ clean verdict and an unreachable enrichment service both produce 0.0, and
+ collapsing them would let a broken enrichment path read as a quiet estate.
+ """
+ act = _as_dict(ocsf.get("activity"))
+ actor = _as_dict(act.get("actor"))
+ resource = _as_dict(act.get("resource"))
+ location = _as_dict(act.get("location"))
+ client = _as_dict(location.get("client"))
+
+ return {
+ "actor_kind": _as_str(actor.get("kind")),
+ "actor_kind_source": _as_str(actor.get("kind_source")),
+ "actor_id": _as_str(actor.get("id")),
+ "actor_on_behalf_of": _as_str(actor.get("on_behalf_of")),
+ "action": _as_str(act.get("action")),
+ "resource_type": _as_str(resource.get("type")),
+ "resource_id": _as_str(resource.get("id") or resource.get("name")),
+ "resource_owner": _as_str(resource.get("owner")),
+ "src_country_code": _as_str(location.get("country_code")),
+ "src_asn": _as_int(location.get("asn")),
+ "src_as_org": _as_str(location.get("as_org")),
+ "src_reputation": _as_float(location.get("reputation")),
+ "src_reputation_known": 1 if location.get("reputation_known") else 0,
+ "client_family": _as_str(client.get("family")),
+ "client_version": _as_str(client.get("version")),
+ "client_category": _as_str(client.get("category")),
+ "client_raw": _as_str(client.get("raw"))[:1024],
+ "outcome": _as_str(act.get("outcome")),
+ }
+
+
def event_to_row(message: dict[str, Any]) -> dict[str, Any] | None:
"""Map an ingest NormalizedEvent envelope to a ClickHouse row dict.
@@ -236,6 +314,7 @@ def event_to_row(message: dict[str, Any]) -> dict[str, Any] | None:
"mitre_techniques": techniques,
"mitre_tactics": tactics,
"iocs": _iocs(ocsf),
+ **_activity_columns(ocsf),
}
# Only set a deterministic event_id when the ingest id is a real UUID;
diff --git a/services/fusion/tests/test_lake_writer.py b/services/fusion/tests/test_lake_writer.py
index 4a9d77296..5cad0358e 100644
--- a/services/fusion/tests/test_lake_writer.py
+++ b/services/fusion/tests/test_lake_writer.py
@@ -158,3 +158,103 @@ async def test_disabled_writer_is_noop():
w._disabled = True # noqa: SLF001
assert await w.write_event(_message()) is False
await w.flush() # no raise
+
+
+# ── depth plan 2.2: the activity projection ────────────────────────────────
+
+
+def _with_activity(**activity_overrides) -> dict:
+ activity = {
+ "actor": {
+ "kind": "api_token",
+ "kind_source": "actor.callerType",
+ "id": "arn:aws:iam::123456789012:user/deploy",
+ "on_behalf_of": "[email protected]",
+ },
+ "action": "create.access.key",
+ "resource": {"type": "AWS::IAM::User", "id": "arn:aws:iam::123456789012:user/x", "owner": "123456789012"},
+ "location": {
+ "ip": "8.8.8.8",
+ "country_code": "SE",
+ "asn": 1299,
+ "as_org": "Arelion",
+ "reputation": 72.5,
+ "reputation_known": True,
+ "client": {"raw": "aws-cli/2.15.30", "family": "aws-cli", "version": "2.15.30", "category": "cli"},
+ },
+ "outcome": "failure",
+ }
+ activity.update(activity_overrides)
+ return _message(activity=activity)
+
+
+async def test_activity_projection_lands_in_its_own_columns():
+ """The projection is columns, not only a slice of the ocsf_json blob.
+
+ A hunt for "every action by a non-human actor from a new ASN" has to be
+ an indexed scan; JSONExtract over a ZSTD column cannot use an index.
+ """
+ row = event_to_row(_with_activity())
+ assert row is not None
+ assert row["actor_kind"] == "api_token"
+ assert row["actor_kind_source"] == "actor.callerType"
+ assert row["actor_on_behalf_of"] == "[email protected]"
+ assert row["action"] == "create.access.key"
+ assert row["resource_type"] == "AWS::IAM::User"
+ assert row["resource_owner"] == "123456789012"
+ assert row["src_country_code"] == "SE"
+ assert row["src_asn"] == 1299
+ assert row["src_as_org"] == "Arelion"
+ assert row["src_reputation"] == pytest.approx(72.5)
+ assert row["src_reputation_known"] == 1
+ assert row["client_family"] == "aws-cli"
+ assert row["client_category"] == "cli"
+ assert row["client_raw"] == "aws-cli/2.15.30"
+ assert row["outcome"] == "failure"
+
+
+async def test_an_event_with_no_projection_still_inserts():
+ """The insert is positional, so a missing key would shift every column
+ after it. An event from before the projection, or replayed off an older
+ topic, has no `activity` block and must still land."""
+ row = event_to_row(_message())
+ assert row is not None
+ assert set(row) >= {"actor_kind", "action", "src_asn", "outcome"}
+ assert row["actor_kind"] == ""
+ assert row["src_asn"] == 0
+ assert row["src_reputation_known"] == 0
+
+
+async def test_an_unanswered_reputation_is_not_a_clean_one():
+ """A clean verdict and an unreachable enrichment service both produce
+ 0.0. Only the flag separates them, and a surface rendering 0 as "clean"
+ when nobody answered is a fabricated confidence."""
+ row = event_to_row(_with_activity(location={"ip": "8.8.8.8", "reputation": 0.0, "reputation_known": False}))
+ assert row is not None
+ assert row["src_reputation"] == pytest.approx(0.0)
+ assert row["src_reputation_known"] == 0
+
+ answered = event_to_row(_with_activity(location={"ip": "8.8.8.8", "reputation": 0.0, "reputation_known": True}))
+ assert answered is not None
+ assert answered["src_reputation_known"] == 1
+
+
+async def test_every_declared_column_is_present_in_every_row():
+ """_INSERT_SQL is built by joining _COLUMNS and the driver reads the row
+ positionally, so a row missing one key inserts every later value into the
+ wrong column."""
+ from app.services.lake_writer import _COLUMNS
+
+ for message in (_with_activity(), _message()):
+ row = event_to_row(message)
+ assert row is not None
+ missing = [c for c in _COLUMNS if c not in row]
+ assert not missing, f"row is missing declared columns: {missing}"
+
+
+async def test_an_attacker_chosen_user_agent_is_bounded():
+ """The raw agent is kept deliberately, which means an attacker chooses
+ the length of a string that reaches a lake column."""
+ row = event_to_row(_with_activity(location={"client": {"raw": "x" * 50_000}}))
+ assert row is not None
+ assert len(row["client_raw"]) <= 1024
diff --git a/services/ingest/internal/activity/action.go b/services/ingest/internal/activity/action.go
new file mode 100644
index 000000000..46c5efb69
--- /dev/null
+++ b/services/ingest/internal/activity/action.go
@@ -0,0 +1,302 @@
+package activity
+
+import (
+ "regexp"
+ "strings"
+)
+
+// Action, resource, location and outcome.
+//
+// `action` is a normalized verb: a short, lower-case, dotted string the same
+// across vendors, so a hunt for "somebody created a credential" does not have
+// to enumerate `CreateAccessKey`, `system.api_token.create`,
+// `Add service principal credentials` and `personal_access_token.create`.
+//
+// The normalization here is structural — it folds a vendor's own event
+// identifier into a stable shape and lower-cases it. It deliberately does not
+// try to map vendor verbs onto a semantic taxonomy: that is the event
+// catalogue's job (depth plan 2.3), which is a reviewed data file rather than
+// a regex, and which also carries the sensitivity and ATT&CK hint a verb
+// alone cannot.
+
+// actionSplitter breaks CamelCase at a lower-to-upper boundary so AWS's
+// `CreateAccessKey` becomes `create.access.key` rather than one opaque token.
+var actionSplitter = regexp.MustCompile(`([a-z0-9])([A-Z])`)
+
+// actionCleaner collapses anything that is not alphanumeric into the dotted
+// separator, so a vendor's spaces, slashes, colons and hyphens all land on
+// one spelling.
+var actionCleaner = regexp.MustCompile(`[^a-z0-9]+`)
+
+// deriveAction returns the normalized verb, or "" when the source names no
+// event type. An empty action is honest: several connectors emit only a
+// human-readable title, and inventing a verb from prose would produce a
+// vocabulary nothing else in the platform shares.
+func deriveAction(connectorType string, payload, vendor, ocsf map[string]any) string {
+ raw := vendorActionField(connectorType, payload, vendor, ocsf)
+ return NormalizeAction(raw)
+}
+
+// vendorActionField reads the field whose documented meaning is "what
+// happened", per source. Order within each case is precedence.
+func vendorActionField(connectorType string, payload, vendor, ocsf map[string]any) string {
+ switch connectorType {
+ case "aws_cloudtrail":
+ if v := firstStr(vendor, []string{"eventName"}, []string{"EventName"}); v != "" {
+ return v
+ }
+ case "okta", "okta_system_log":
+ if v := str(vendor, "eventType"); v != "" {
+ return v
+ }
+ case "m365_audit":
+ if v := str(vendor, "Operation"); v != "" {
+ return v
+ }
+ case "google_workspace":
+ if events, ok := nested(vendor, "events").([]any); ok && len(events) > 0 {
+ if first, ok := events[0].(map[string]any); ok {
+ if v := str(first, "name"); v != "" {
+ return v
+ }
+ }
+ }
+ case "gcp_cloud_audit":
+ if v := firstStr(vendor,
+ []string{"protoPayload", "methodName"},
+ []string{"methodName"},
+ ); v != "" {
+ return v
+ }
+ case "azure_activity":
+ if v := firstStr(vendor,
+ []string{"operationName", "value"},
+ []string{"operationName"},
+ ); v != "" {
+ return v
+ }
+ case "azure_entra":
+ if v := str(vendor, "activityDisplayName"); v != "" {
+ return v
+ }
+ case "github", "gitlab":
+ if v := firstStr(vendor, []string{"action"}, []string{"event_type"}); v != "" {
+ return v
+ }
+ case "kubernetes_audit":
+ // verb plus resource is the pair that means something: `create` on
+ // its own says nothing about what was created.
+ verb := str(vendor, "verb")
+ resource := str(vendor, "objectRef", "resource")
+ if verb != "" && resource != "" {
+ return verb + "." + resource
+ }
+ return verb
+ case "windows_event":
+ // The event id *is* the verb on this source, and it is the thing
+ // every Windows detection keys on.
+ if v := firstStr(vendor, []string{"EventID"}, []string{"System", "EventID"}); v != "" {
+ return "windows.event." + v
+ }
+ case "auditd":
+ if v := str(vendor, "syscall"); v != "" {
+ return "auditd." + v
+ }
+ }
+
+ // The connector's own normalized `event_type`, which several emit, then
+ // the OCSF activity name a profile mapped.
+ if v := firstStr(payload, []string{"event_type"}, []string{"action"}); v != "" {
+ return v
+ }
+ return str(ocsf, "activity_name")
+}
+
+// NormalizeAction folds a vendor's event identifier into the dotted
+// lower-case shape. Exported because the event catalogue gate (depth plan
+// 2.3) must normalize the same way this does, and two implementations would
+// drift.
+func NormalizeAction(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return ""
+ }
+ // Bound an attacker-chosen event name the same way the user agent is
+ // bounded; this string reaches a lake column and a graph property.
+ const maxLen = 128
+ if len(raw) > maxLen {
+ raw = raw[:maxLen]
+ }
+ split := actionSplitter.ReplaceAllString(raw, "$1.$2")
+ cleaned := actionCleaner.ReplaceAllString(strings.ToLower(split), ".")
+ return strings.Trim(cleaned, ".")
+}
+
+// deriveResource names what was acted on. Type and id come from the source's
+// own resource fields; owner is filled only where the source says who owns
+// the thing, which most do not.
+func deriveResource(connectorType string, payload, vendor, ocsf map[string]any) Resource {
+ switch connectorType {
+ case "aws_cloudtrail":
+ // `resources` is CloudTrail's own array of {ARN, type, accountId}.
+ if resources, ok := nested(vendor, "resources").([]any); ok && len(resources) > 0 {
+ if first, ok := resources[0].(map[string]any); ok {
+ return Resource{
+ Type: str(first, "type"),
+ ID: str(first, "ARN"),
+ Owner: str(first, "accountId"),
+ }
+ }
+ }
+ return Resource{
+ Type: str(vendor, "eventSource"),
+ Owner: str(vendor, "recipientAccountId"),
+ }
+ case "kubernetes_audit":
+ ref, _ := nested(vendor, "objectRef").(map[string]any)
+ if ref != nil {
+ return Resource{
+ Type: str(ref, "resource"),
+ Name: str(ref, "name"),
+ Owner: str(ref, "namespace"),
+ }
+ }
+ case "gcp_cloud_audit":
+ return Resource{
+ Type: firstStr(vendor, []string{"protoPayload", "serviceName"}, []string{"resource", "type"}),
+ ID: firstStr(vendor, []string{"protoPayload", "resourceName"}, []string{"resourceName"}),
+ }
+ case "github":
+ return Resource{Type: "repository", Name: str(vendor, "repo"), Owner: str(vendor, "org")}
+ case "okta", "okta_system_log":
+ if targets, ok := nested(vendor, "target").([]any); ok && len(targets) > 0 {
+ if first, ok := targets[0].(map[string]any); ok {
+ return Resource{
+ Type: str(first, "type"),
+ ID: str(first, "id"),
+ Name: firstStr(first, []string{"displayName"}, []string{"alternateId"}),
+ }
+ }
+ }
+ }
+
+ // The OCSF resource block, which several profiles already fill.
+ return Resource{
+ Type: str(ocsf, "resource", "type"),
+ ID: str(ocsf, "resource", "uid"),
+ Name: str(ocsf, "resource", "name"),
+ }
+}
+
+// deriveOutcome reads whether the action succeeded.
+//
+// Unknown is a real answer and the default. A source that reports nothing
+// must not be folded into "success", because a detection counting failed
+// attempts would then read a silent source as a clean estate.
+func deriveOutcome(payload, vendor, ocsf map[string]any) Outcome {
+ // Explicit booleans first: a vendor that says `success: false` has said
+ // the most unambiguous thing available.
+ for _, m := range []map[string]any{vendor, payload} {
+ for _, key := range []string{"success", "is_success", "IsSuccess"} {
+ if v, ok := m[key].(bool); ok {
+ if v {
+ return OutcomeSuccess
+ }
+ return OutcomeFailure
+ }
+ }
+ }
+
+ // An error code present and non-empty is a failure on every source that
+ // emits one.
+ for _, m := range []map[string]any{vendor, payload} {
+ if firstStr(m, []string{"errorCode"}, []string{"errorMessage"}, []string{"error"}) != "" {
+ return OutcomeFailure
+ }
+ }
+
+ // Documented string enumerations.
+ candidates := []string{
+ str(vendor, "outcome", "result"), // Okta: SUCCESS / FAILURE / SKIPPED / ALLOW / DENY / CHALLENGE
+ str(vendor, "ResultStatus"), // M365: Succeeded / Success / Failed / Failure / PartiallySucceeded
+ str(vendor, "result"),
+ str(vendor, "status"),
+ str(payload, "outcome"),
+ str(ocsf, "status"),
+ }
+ for _, candidate := range candidates {
+ switch strings.ToUpper(strings.TrimSpace(candidate)) {
+ case "":
+ continue
+ case "SUCCESS", "SUCCEEDED", "ALLOW", "ALLOWED", "OK", "COMPLETED":
+ return OutcomeSuccess
+ case "FAILURE", "FAILED", "DENY", "DENIED", "BLOCK", "BLOCKED", "ERROR":
+ return OutcomeFailure
+ }
+ }
+
+ // Kubernetes and HTTP sources carry the answer as a status code.
+ for _, m := range []map[string]any{vendor, ocsf} {
+ if code, ok := intField(m, "status_code"); ok && code > 0 {
+ return httpOutcome(code)
+ }
+ }
+ if code, ok := nestedInt(vendor, "responseStatus", "code"); ok && code > 0 {
+ return httpOutcome(code)
+ }
+ return OutcomeUnknown
+}
+
+func httpOutcome(code int) Outcome {
+ if code >= 200 && code < 400 {
+ return OutcomeSuccess
+ }
+ return OutcomeFailure
+}
+
+func nestedInt(m map[string]any, path ...string) (int, bool) {
+ switch v := nested(m, path...).(type) {
+ case int:
+ return v, true
+ case int64:
+ return int(v), true
+ case float64:
+ return int(v), true
+ }
+ return 0, false
+}
+
+// deriveLocation fills everything about where the action came from that is
+// available without a network call. Geography, ASN and reputation are added
+// afterwards by the enrichment pass, which needs one.
+func deriveLocation(payload, vendor, ocsf map[string]any) Location {
+ return Location{
+ IP: str(ocsf, "src_endpoint", "ip"),
+ Device: firstStr(ocsf, []string{"device", "name"}, []string{"src_endpoint", "hostname"}),
+ Client: ParseUserAgent(userAgentString(payload, vendor, ocsf)),
+ }
+}
+
+// userAgentString finds the raw agent across the field names these sources
+// actually use. Checked against the vendor records rather than guessed:
+// CloudTrail spells it `userAgent`, Okta nests it under
+// `client.userAgent.rawUserAgent`, Kubernetes uses `userAgent`, Workspace and
+// M365 do not send one at all on most events, and the OCSF mapping puts it at
+// `http_request.user_agent` where a profile named it.
+func userAgentString(payload, vendor, ocsf map[string]any) string {
+ if v := str(ocsf, "http_request", "user_agent"); v != "" {
+ return v
+ }
+ for _, m := range []map[string]any{vendor, payload} {
+ if v := firstStr(m,
+ []string{"userAgent"},
+ []string{"user_agent"},
+ []string{"client", "userAgent", "rawUserAgent"},
+ []string{"context", "ua"},
+ []string{"http_request", "user_agent"},
+ ); v != "" {
+ return v
+ }
+ }
+ return ""
+}
diff --git a/services/ingest/internal/activity/activity.go b/services/ingest/internal/activity/activity.go
new file mode 100644
index 000000000..b776ef752
--- /dev/null
+++ b/services/ingest/internal/activity/activity.go
@@ -0,0 +1,200 @@
+// Package activity builds the canonical activity projection carried on every
+// normalized event: who acted, what kind of actor they were, what they did,
+// to which resource, from where, and with what outcome.
+//
+// Why one projection rather than per-source fields
+// ------------------------------------------------
+// Every consumer downstream of ingest — the detection matcher, the lake, the
+// entity graph, triage, the investigation rail — asks the same five questions
+// of an event, and before this package each answered them from whatever field
+// names the vendor happened to use. The OCSF mapping gets an event's *shape*
+// right; it does not say whether `actor.user.name` is a person, the OAuth app
+// acting for them, or a long-lived token somebody minted two years ago.
+//
+// `actor.kind` is the field that separates those, and it is the one with the
+// strictest rule in this package: it is derived from the vendor's own
+// identity-type, token-type and client fields, and **never guessed**. A
+// source that does not say stays `unknown`. An inferred `human` is worse than
+// no answer, because every later surface — a privilege decision, a blast
+// radius, an auto-close — would treat the guess as evidence.
+//
+// Each derivation below names the vendor field it reads and the documented
+// vocabulary of that field. Where a vendor's enumeration has no member
+// meaning "a person", the result is `unknown` rather than a default.
+package activity
+
+import "strings"
+
+// ActorKind is the closed set the projection may report.
+//
+// The names come from depth plan 2.2 and are deliberately about *what is
+// acting*, not about what it is allowed to do:
+//
+// human a person, interactively or through a client they drive
+// service_account a non-human principal the directory manages as an account
+// oauth_app a third-party application acting with delegated consent
+// api_token a long-lived programmatic credential acting on its own
+// workload compute acting as itself (a cloud service, a node, a pod)
+// ai_agent an autonomous agent acting on a person's behalf
+// unknown the source did not say, and this package does not guess
+type ActorKind string
+
+const (
+ ActorHuman ActorKind = "human"
+ ActorServiceAccount ActorKind = "service_account"
+ ActorOAuthApp ActorKind = "oauth_app"
+ ActorAPIToken ActorKind = "api_token"
+ ActorWorkload ActorKind = "workload"
+ ActorAIAgent ActorKind = "ai_agent"
+ ActorUnknown ActorKind = "unknown"
+)
+
+// ActorKinds is the closed set, in the order the plan names them. The gate
+// and the lake's enum read this rather than a second list.
+var ActorKinds = []ActorKind{
+ ActorHuman, ActorServiceAccount, ActorOAuthApp,
+ ActorAPIToken, ActorWorkload, ActorAIAgent, ActorUnknown,
+}
+
+// Outcome is the result the source reported, normalized to three values.
+//
+// Three and not two: a source that does not report an outcome must be
+// distinguishable from one that reported success, or a detection counting
+// failures would read every silent source as a clean estate.
+type Outcome string
+
+const (
+ OutcomeSuccess Outcome = "success"
+ OutcomeFailure Outcome = "failure"
+ OutcomeUnknown Outcome = "unknown"
+)
+
+// Actor is who acted and what kind of thing they are.
+type Actor struct {
+ // Kind is never guessed. See the package comment.
+ Kind ActorKind `json:"kind"`
+ // KindSource names the vendor field the kind was read from, so a
+ // reviewer can check the derivation against the vendor's documentation
+ // without re-reading this package. Empty when Kind is unknown.
+ KindSource string `json:"kind_source,omitempty"`
+ Name string `json:"name,omitempty"`
+ ID string `json:"id,omitempty"`
+ Email string `json:"email,omitempty"`
+ // OnBehalfOf is the human an agent, app or token is acting for, when
+ // the source says. This is what makes `actor.kind` useful rather than
+ // merely accurate: an OAuth app reading a mailbox is interesting
+ // because of whose mailbox it is.
+ OnBehalfOf string `json:"on_behalf_of,omitempty"`
+}
+
+// Resource is what was acted on.
+type Resource struct {
+ Type string `json:"type,omitempty"`
+ ID string `json:"id,omitempty"`
+ Name string `json:"name,omitempty"`
+ Owner string `json:"owner,omitempty"`
+}
+
+// Location is where the action came from.
+//
+// Geography, ASN and reputation are filled by the enrichment pass, which
+// runs only for public addresses: a private address has no useful answer and
+// sending one to a third party would leak the customer's internal topology.
+type Location struct {
+ IP string `json:"ip,omitempty"`
+ Country string `json:"country,omitempty"`
+ CountryCode string `json:"country_code,omitempty"`
+ City string `json:"city,omitempty"`
+ ASN int64 `json:"asn,omitempty"`
+ ASOrg string `json:"as_org,omitempty"`
+ // Reputation is the enrichment service's 0-100 risk score, and
+ // ReputationKnown says whether anything answered — a score of 0 from a
+ // source that answered "clean" and a score of 0 from no answer at all
+ // are different facts.
+ Reputation float64 `json:"reputation,omitempty"`
+ ReputationKnown bool `json:"reputation_known"`
+ Device string `json:"device,omitempty"`
+ // Client is the parsed user agent. The raw string is kept beside it
+ // because every parser is a lossy summary of a string an attacker can
+ // choose, and a hunt needs the original.
+ Client Client `json:"client,omitempty"`
+}
+
+// Activity is the projection itself.
+type Activity struct {
+ Actor Actor `json:"actor"`
+ Action string `json:"action,omitempty"`
+ Resource Resource `json:"resource,omitempty"`
+ Location Location `json:"location,omitempty"`
+ Outcome Outcome `json:"outcome"`
+}
+
+// Project builds the projection for one normalized event.
+//
+// `payload` is the connector's own output — for a canonical envelope that is
+// the envelope, with the vendor's record under `raw_event`. `ocsf` is the
+// event this normalizer has already built, which is where the identity
+// aliases have resolved a name, a host and a source IP that the vendor's
+// record may spell four different ways.
+//
+// Reading both is deliberate. The vendor record is the only place the
+// identity-type fields live, and the OCSF event is the only place the
+// aliases have already done the cross-vendor work.
+func Project(connectorType string, payload, ocsf map[string]any) Activity {
+ vendor := vendorRecord(payload)
+
+ act := Activity{
+ Actor: deriveActor(connectorType, payload, vendor, ocsf),
+ Action: deriveAction(connectorType, payload, vendor, ocsf),
+ Resource: deriveResource(connectorType, payload, vendor, ocsf),
+ Outcome: deriveOutcome(payload, vendor, ocsf),
+ }
+ act.Location = deriveLocation(payload, vendor, ocsf)
+ return act
+}
+
+// vendorRecord returns the vendor's own record from a canonical envelope, or
+// the payload itself when there is no envelope.
+//
+// The key is `raw_event` and never `raw`: 26 connectors once emitted `raw`,
+// missed the canonical-envelope check in the normalizer and fell through to a
+// borrowed vendor profile. Reading only the one key here keeps this package
+// from re-introducing that fork under a different name.
+func vendorRecord(payload map[string]any) map[string]any {
+ if nested, ok := payload["raw_event"].(map[string]any); ok {
+ return nested
+ }
+ return payload
+}
+
+// nested walks a dotted path through maps and returns the leaf, or nil.
+func nested(m map[string]any, path ...string) any {
+ var cur any = m
+ for _, key := range path {
+ asMap, ok := cur.(map[string]any)
+ if !ok {
+ return nil
+ }
+ cur = asMap[key]
+ }
+ return cur
+}
+
+// str returns a trimmed non-empty string at a dotted path, or "".
+func str(m map[string]any, path ...string) string {
+ if s, ok := nested(m, path...).(string); ok {
+ return strings.TrimSpace(s)
+ }
+ return ""
+}
+
+// firstStr returns the first non-empty value among several dotted paths, in
+// declared order. Order is precedence; a map would randomise it.
+func firstStr(m map[string]any, paths ...[]string) string {
+ for _, path := range paths {
+ if v := str(m, path...); v != "" {
+ return v
+ }
+ }
+ return ""
+}
diff --git a/services/ingest/internal/activity/activity_test.go b/services/ingest/internal/activity/activity_test.go
new file mode 100644
index 000000000..9e48efba8
--- /dev/null
+++ b/services/ingest/internal/activity/activity_test.go
@@ -0,0 +1,571 @@
+package activity
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Each case is a real vendor record shape, trimmed to the fields the
+// derivation reads plus enough context to show where they sit. They are
+// transcriptions of the documented schemas named in actor.go, not inventions:
+// a fixture that puts `userIdentity.type` somewhere AWS does not would make
+// this suite agree with itself forever.
+func canonical(connector string, vendor map[string]any) map[string]any {
+ return map[string]any{"source": connector, "raw_event": vendor}
+}
+
+func TestActorKindComesFromTheVendorsOwnField(t *testing.T) {
+ cases := []struct {
+ name string
+ connector string
+ vendor map[string]any
+ wantKind ActorKind
+ wantSource string
+ }{
+ {
+ name: "CloudTrail AWSService is compute acting as itself",
+ connector: "aws_cloudtrail",
+ vendor: map[string]any{
+ "eventName": "AssumeRole",
+ "userIdentity": map[string]any{"type": "AWSService", "invokedBy": "config.amazonaws.com"},
+ },
+ wantKind: ActorWorkload,
+ wantSource: "userIdentity.invokedBy",
+ },
+ {
+ name: "CloudTrail root is a person",
+ connector: "aws_cloudtrail",
+ vendor: map[string]any{
+ "eventName": "ConsoleLogin",
+ "userIdentity": map[string]any{"type": "Root", "arn": "arn:aws:iam::123456789012:root"},
+ },
+ wantKind: ActorHuman,
+ wantSource: "userIdentity.type",
+ },
+ {
+ name: "CloudTrail IdentityCenterUser is a person",
+ connector: "aws_cloudtrail",
+ vendor: map[string]any{
+ "userIdentity": map[string]any{"type": "IdentityCenterUser"},
+ },
+ wantKind: ActorHuman,
+ wantSource: "userIdentity.type",
+ },
+ {
+ name: "Okta User",
+ connector: "okta",
+ vendor: map[string]any{
+ "eventType": "user.session.start",
+ "actor": map[string]any{"type": "User", "displayName": "Alice"},
+ },
+ wantKind: ActorHuman,
+ wantSource: "actor.type",
+ },
+ {
+ name: "Okta SystemPrincipal",
+ connector: "okta",
+ vendor: map[string]any{
+ "actor": map[string]any{"type": "SystemPrincipal"},
+ },
+ wantKind: ActorServiceAccount,
+ wantSource: "actor.type",
+ },
+ {
+ name: "Okta PublicClientApp is a delegated app",
+ connector: "okta",
+ vendor: map[string]any{
+ "actor": map[string]any{"type": "PublicClientApp"},
+ },
+ wantKind: ActorOAuthApp,
+ wantSource: "actor.type",
+ },
+ {
+ name: "M365 UserType 5 is an application",
+ connector: "m365_audit",
+ vendor: map[string]any{"Operation": "MailItemsAccessed", "UserType": float64(5)},
+ wantKind: ActorOAuthApp,
+ wantSource: "UserType",
+ },
+ {
+ name: "M365 UserType 6 is a service principal",
+ connector: "m365_audit",
+ vendor: map[string]any{"UserType": float64(6)},
+ wantKind: ActorServiceAccount,
+ wantSource: "UserType",
+ },
+ {
+ name: "M365 UserType 2 is an admin, still a person",
+ connector: "m365_audit",
+ vendor: map[string]any{"UserType": float64(2)},
+ wantKind: ActorHuman,
+ wantSource: "UserType",
+ },
+ {
+ name: "Entra initiatedBy.app alone is a service principal",
+ connector: "azure_entra",
+ vendor: map[string]any{
+ "activityDisplayName": "Add member to role",
+ "initiatedBy": map[string]any{"app": map[string]any{"appId": "0000-1111"}},
+ },
+ wantKind: ActorServiceAccount,
+ wantSource: "initiatedBy.app",
+ },
+ {
+ name: "Entra initiatedBy.user is a person",
+ connector: "azure_entra",
+ vendor: map[string]any{
+ "initiatedBy": map[string]any{"user": map[string]any{"userPrincipalName": "[email protected]"}},
+ },
+ wantKind: ActorHuman,
+ wantSource: "initiatedBy.user",
+ },
+ {
+ name: "Workspace callerType KEY is a token",
+ connector: "google_workspace",
+ vendor: map[string]any{
+ "actor": map[string]any{"callerType": "KEY"},
+ "events": []any{map[string]any{"name": "download"}},
+ },
+ wantKind: ActorAPIToken,
+ wantSource: "actor.callerType",
+ },
+ {
+ name: "Workspace callerType APPLICATION is a delegated app",
+ connector: "google_workspace",
+ vendor: map[string]any{
+ "actor": map[string]any{"callerType": "APPLICATION"},
+ },
+ wantKind: ActorOAuthApp,
+ wantSource: "actor.callerType",
+ },
+ {
+ name: "GCP service account by its own namespace",
+ connector: "gcp_cloud_audit",
+ vendor: map[string]any{
+ "protoPayload": map[string]any{
+ "methodName": "storage.objects.list",
+ "authenticationInfo": map[string]any{"principalEmail": "[email protected]"},
+ },
+ },
+ wantKind: ActorServiceAccount,
+ wantSource: "authenticationInfo.principalEmail",
+ },
+ {
+ name: "GCP impersonation is a service account whatever the caller is",
+ connector: "gcp_cloud_audit",
+ vendor: map[string]any{
+ "protoPayload": map[string]any{
+ "authenticationInfo": map[string]any{
+ "principalEmail": "[email protected]",
+ "serviceAccountDelegationInfo": []any{map[string]any{"principalSubject": "svc"}},
+ },
+ },
+ },
+ wantKind: ActorServiceAccount,
+ wantSource: "authenticationInfo.serviceAccountDelegationInfo",
+ },
+ {
+ name: "GitHub personal access token",
+ connector: "github",
+ vendor: map[string]any{"action": "repo.destroy", "programmatic_access_type": "Fine-grained personal access token"},
+ wantKind: ActorAPIToken,
+ wantSource: "programmatic_access_type",
+ },
+ {
+ name: "GitHub bot actor",
+ connector: "github",
+ vendor: map[string]any{"action": "workflow_run", "actor_is_bot": true},
+ wantKind: ActorWorkload,
+ wantSource: "actor_is_bot",
+ },
+ {
+ name: "Kubernetes service account by its reserved username",
+ connector: "kubernetes_audit",
+ vendor: map[string]any{"verb": "list", "user": map[string]any{"username": "system:serviceaccount:kube-system:replicaset-controller"}},
+ wantKind: ActorServiceAccount,
+ wantSource: "user.username",
+ },
+ {
+ name: "Kubernetes node by its reserved username",
+ connector: "kubernetes_audit",
+ vendor: map[string]any{"verb": "get", "user": map[string]any{"username": "system:node:ip-10-0-1-5"}},
+ wantKind: ActorWorkload,
+ wantSource: "user.username",
+ },
+ {
+ name: "an AI agent says so in its own envelope",
+ connector: "ai_gateway",
+ vendor: map[string]any{"agent_id": "agt-7", "tool_name": "search_siem"},
+ wantKind: ActorAIAgent,
+ wantSource: "agent_id",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := Project(tc.connector, canonical(tc.connector, tc.vendor), map[string]any{})
+ if got.Actor.Kind != tc.wantKind {
+ t.Errorf("kind = %q, want %q", got.Actor.Kind, tc.wantKind)
+ }
+ if got.Actor.KindSource != tc.wantSource {
+ t.Errorf("kind_source = %q, want %q", got.Actor.KindSource, tc.wantSource)
+ }
+ })
+ }
+}
+
+// The rule with the sharpest edge: what cannot be derived stays unknown.
+//
+// An inferred `human` is worse than no answer, because a privilege decision,
+// a blast radius and an auto-close would each treat the guess as evidence.
+// Every case below is a shape a plausible heuristic would get wrong.
+func TestWhatCannotBeDerivedStaysUnknown(t *testing.T) {
+ cases := []struct {
+ name string
+ connector string
+ vendor map[string]any
+ }{
+ {
+ // AWS does not say whether an IAM user is a person, and a great
+ // many are long-lived programmatic identities.
+ name: "CloudTrail IAMUser",
+ connector: "aws_cloudtrail",
+ vendor: map[string]any{"userIdentity": map[string]any{"type": "IAMUser", "userName": "deploy-bot"}},
+ },
+ {
+ // An assumed role is whatever assumed it.
+ name: "CloudTrail AssumedRole with no invokedBy",
+ connector: "aws_cloudtrail",
+ vendor: map[string]any{"userIdentity": map[string]any{"type": "AssumedRole"}},
+ },
+ {
+ // A name that looks like a service account is not a vendor
+ // field. "svc-" means nothing.
+ name: "a username that looks automated",
+ connector: "okta",
+ vendor: map[string]any{"actor": map[string]any{"displayName": "svc-backup-runner"}},
+ },
+ {
+ // GitHub documents when programmatic_access_type appears, not
+ // that it appears on every API event, so silence is not a web
+ // session.
+ name: "GitHub with no programmatic access type",
+ connector: "github",
+ vendor: map[string]any{"action": "team.add_member", "actor": "alice"},
+ },
+ {
+ // An email address in a corporate domain says nothing about
+ // whether a person or a job is behind it.
+ name: "GCP principal in a corporate domain",
+ connector: "gcp_cloud_audit",
+ vendor: map[string]any{
+ "protoPayload": map[string]any{"authenticationInfo": map[string]any{"principalEmail": "[email protected]"}},
+ },
+ },
+ {
+ name: "M365 UserType 1, which Microsoft documents as Reserved",
+ connector: "m365_audit",
+ vendor: map[string]any{"UserType": float64(1)},
+ },
+ {
+ name: "a source with no identity-type field at all",
+ connector: "zscaler",
+ vendor: map[string]any{"action": "Allow", "url": "example.com"},
+ },
+ {
+ name: "a connector this package has no derivation for",
+ connector: "tailscale",
+ vendor: map[string]any{"actor": "device-01", "action": "UPDATE"},
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := Project(tc.connector, canonical(tc.connector, tc.vendor), map[string]any{})
+ if got.Actor.Kind != ActorUnknown {
+ t.Errorf("kind = %q, want %q — this source does not say, and a guess here becomes evidence downstream",
+ got.Actor.Kind, ActorUnknown)
+ }
+ if got.Actor.KindSource != "" {
+ t.Errorf("kind_source = %q, want empty: an unknown kind was read from no field", got.Actor.KindSource)
+ }
+ })
+ }
+}
+
+// A kind is only ever one of the closed set. A typo in a derivation would
+// otherwise reach a lake column and a graph property as a value nothing
+// queries for.
+func TestEveryDerivedKindIsInTheClosedSet(t *testing.T) {
+ allowed := map[ActorKind]bool{}
+ for _, k := range ActorKinds {
+ allowed[k] = true
+ }
+ // Drive every connector this package derives for, with a shape that
+ // resolves, and one that does not.
+ for _, connector := range []string{
+ "aws_cloudtrail", "okta", "m365_audit", "azure_entra", "google_workspace",
+ "gcp_cloud_audit", "github", "kubernetes_audit", "ai_gateway", "zscaler",
+ } {
+ for _, vendor := range []map[string]any{
+ {"userIdentity": map[string]any{"type": "Root"}},
+ {"actor": map[string]any{"type": "User", "callerType": "KEY"}},
+ {"UserType": float64(6)},
+ {"agent_id": "a"},
+ {},
+ } {
+ got := Project(connector, canonical(connector, vendor), map[string]any{})
+ if !allowed[got.Actor.Kind] {
+ t.Errorf("%s produced kind %q, which is not in ActorKinds", connector, got.Actor.Kind)
+ }
+ }
+ }
+}
+
+// The envelope key is `raw_event` and never `raw`. 26 connectors once emitted
+// `raw`, missed the normalizer's canonical-envelope check and fell through to
+// a borrowed vendor profile; reading only the one key here keeps this package
+// from re-introducing that fork under a different name.
+func TestOnlyRawEventIsReadAsTheVendorRecord(t *testing.T) {
+ vendor := map[string]any{"userIdentity": map[string]any{"type": "Root"}}
+
+ viaRawEvent := Project("aws_cloudtrail", map[string]any{"source": "aws_cloudtrail", "raw_event": vendor}, map[string]any{})
+ if viaRawEvent.Actor.Kind != ActorHuman {
+ t.Fatalf("raw_event envelope: kind = %q, want human", viaRawEvent.Actor.Kind)
+ }
+
+ viaRaw := Project("aws_cloudtrail", map[string]any{"source": "aws_cloudtrail", "raw": vendor}, map[string]any{})
+ if viaRaw.Actor.Kind != ActorUnknown {
+ t.Errorf("a `raw` key resolved to kind %q; this package must read `raw_event` only, so a connector "+
+ "emitting the wrong key is visibly unclassified rather than quietly working", viaRaw.Actor.Kind)
+ }
+}
+
+func TestOutcomeDistinguishesSilenceFromSuccess(t *testing.T) {
+ cases := []struct {
+ name string
+ vendor map[string]any
+ want Outcome
+ }{
+ {"an explicit false", map[string]any{"success": false}, OutcomeFailure},
+ {"an explicit true", map[string]any{"success": true}, OutcomeSuccess},
+ {"an AWS error code", map[string]any{"errorCode": "AccessDenied"}, OutcomeFailure},
+ {"Okta FAILURE", map[string]any{"outcome": map[string]any{"result": "FAILURE"}}, OutcomeFailure},
+ {"Okta SUCCESS", map[string]any{"outcome": map[string]any{"result": "SUCCESS"}}, OutcomeSuccess},
+ {"M365 Succeeded", map[string]any{"ResultStatus": "Succeeded"}, OutcomeSuccess},
+ {"a Kubernetes 403", map[string]any{"responseStatus": map[string]any{"code": float64(403)}}, OutcomeFailure},
+ {"a Kubernetes 201", map[string]any{"responseStatus": map[string]any{"code": float64(201)}}, OutcomeSuccess},
+ {
+ "a source that says nothing",
+ map[string]any{"url": "example.com"},
+ // The whole point: a detection counting failures would read a
+ // silent source as a clean estate if this folded into success.
+ OutcomeUnknown,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := Project("generic", canonical("generic", tc.vendor), map[string]any{})
+ if got.Outcome != tc.want {
+ t.Errorf("outcome = %q, want %q", got.Outcome, tc.want)
+ }
+ })
+ }
+}
+
+func TestActionNormalizesAcrossVendors(t *testing.T) {
+ cases := []struct {
+ connector string
+ vendor map[string]any
+ want string
+ }{
+ {"aws_cloudtrail", map[string]any{"eventName": "CreateAccessKey"}, "create.access.key"},
+ {"okta", map[string]any{"eventType": "system.api_token.create"}, "system.api.token.create"},
+ {"m365_audit", map[string]any{"Operation": "Add service principal credentials."}, "add.service.principal.credentials"},
+ {"gcp_cloud_audit", map[string]any{"protoPayload": map[string]any{"methodName": "storage.objects.list"}}, "storage.objects.list"},
+ {"github", map[string]any{"action": "repo.destroy"}, "repo.destroy"},
+ {"kubernetes_audit", map[string]any{"verb": "create", "objectRef": map[string]any{"resource": "pods"}}, "create.pods"},
+ {"windows_event", map[string]any{"EventID": "4688"}, "windows.event.4688"},
+ {"auditd", map[string]any{"syscall": "execve"}, "auditd.execve"},
+ // A source naming no event type gets no action, rather than a verb
+ // invented from prose that nothing else in the platform shares.
+ {"zscaler", map[string]any{"url": "example.com"}, ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.connector+"/"+tc.want, func(t *testing.T) {
+ got := Project(tc.connector, canonical(tc.connector, tc.vendor), map[string]any{})
+ if got.Action != tc.want {
+ t.Errorf("action = %q, want %q", got.Action, tc.want)
+ }
+ })
+ }
+}
+
+// An attacker chooses the event name on a pushed payload, and it reaches a
+// lake column and a graph property.
+func TestActionIsBounded(t *testing.T) {
+ got := NormalizeAction(strings.Repeat("A", 4000))
+ if len(got) > 256 {
+ t.Errorf("a 4,000-character event name normalized to %d characters", len(got))
+ }
+}
+
+func TestResourceComesFromTheSourcesOwnResourceFields(t *testing.T) {
+ ct := Project("aws_cloudtrail", canonical("aws_cloudtrail", map[string]any{
+ "eventName": "DeleteBucket",
+ "resources": []any{map[string]any{
+ "ARN": "arn:aws:s3:::finance-exports",
+ "type": "AWS::S3::Bucket",
+ "accountId": "123456789012",
+ }},
+ }), map[string]any{})
+ if ct.Resource.Type != "AWS::S3::Bucket" || ct.Resource.ID != "arn:aws:s3:::finance-exports" || ct.Resource.Owner != "123456789012" {
+ t.Errorf("CloudTrail resource = %+v", ct.Resource)
+ }
+
+ k8s := Project("kubernetes_audit", canonical("kubernetes_audit", map[string]any{
+ "verb": "delete",
+ "objectRef": map[string]any{"resource": "secrets", "name": "db-password", "namespace": "payments"},
+ }), map[string]any{})
+ if k8s.Resource.Type != "secrets" || k8s.Resource.Name != "db-password" || k8s.Resource.Owner != "payments" {
+ t.Errorf("Kubernetes resource = %+v", k8s.Resource)
+ }
+}
+
+// The assumed-role chain back to the originating human is what makes an
+// actor kind actionable rather than merely accurate.
+func TestOnBehalfOfResolvesTheOriginatingPrincipal(t *testing.T) {
+ got := Project("aws_cloudtrail", canonical("aws_cloudtrail", map[string]any{
+ "eventName": "GetObject",
+ "userIdentity": map[string]any{
+ "type": "AssumedRole",
+ "sourceIdentity": "[email protected]",
+ },
+ }), map[string]any{})
+ if got.Actor.OnBehalfOf != "[email protected]" {
+ t.Errorf("on_behalf_of = %q, want the sourceIdentity AWS recorded", got.Actor.OnBehalfOf)
+ }
+}
+
+// ──────────────────────────────────────────────────────────────────────────
+// Enrichment
+// ──────────────────────────────────────────────────────────────────────────
+
+// No private, loopback, link-local, CGNAT, documentation or benchmarking
+// address may leave the process. Sending one costs a round trip to learn
+// nothing and publishes the customer's internal topology to a service that
+// forwards to third-party vendors.
+func TestOnlyPublicAddressesAreEnriched(t *testing.T) {
+ var asked []string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body map[string]string
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ asked = append(asked, body["value"])
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "risk_score": 72.5,
+ "geo_location": map[string]any{"country": "Sweden", "country_code": "SE", "asn": 1299, "as_org": "Arelion"},
+ })
+ }))
+ defer server.Close()
+
+ enricher := NewIPEnricher(server.URL, "token", time.Minute, time.Second)
+ private := []string{
+ "10.0.0.4", "172.16.3.9", "192.168.1.1", "127.0.0.1", "169.254.169.254",
+ "100.64.1.1", "192.0.2.5", "198.51.100.7", "203.0.113.9", "198.18.0.1",
+ "::1", "fe80::1", "fd00::1", "2001:db8::1", "", "not-an-ip",
+ }
+ for _, ip := range private {
+ loc := Location{IP: ip}
+ enricher.Enrich(context.Background(), &loc)
+ if loc.Country != "" || loc.ASN != 0 || loc.ReputationKnown {
+ t.Errorf("%q was enriched: %+v", ip, loc)
+ }
+ }
+ if len(asked) != 0 {
+ t.Errorf("the enrichment service was asked about %v; none of those addresses has a public answer", asked)
+ }
+
+ loc := Location{IP: "8.8.8.8"}
+ enricher.Enrich(context.Background(), &loc)
+ if loc.CountryCode != "SE" || loc.ASN != 1299 || loc.ASOrg != "Arelion" {
+ t.Errorf("a public address was not enriched: %+v", loc)
+ }
+ if !loc.ReputationKnown || loc.Reputation != 72.5 {
+ t.Errorf("reputation = %v known=%v, want 72.5 known", loc.Reputation, loc.ReputationKnown)
+ }
+ if len(asked) != 1 || asked[0] != "8.8.8.8" {
+ t.Errorf("asked = %v, want exactly the one public address", asked)
+ }
+}
+
+// A clean verdict and an unreachable enrichment service both produce a
+// reputation of 0. Only the flag separates them, and a surface that renders
+// 0 as "clean" when nobody answered is the fabricated-confidence shape this
+// repository keeps finding.
+func TestAnUnreachableEnricherLeavesReputationUnknown(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusInternalServerError)
+ }))
+ defer server.Close()
+
+ loc := Location{IP: "8.8.8.8"}
+ NewIPEnricher(server.URL, "token", time.Minute, time.Second).Enrich(context.Background(), &loc)
+ if loc.ReputationKnown {
+ t.Error("reputation_known is true after the service returned 500")
+ }
+}
+
+// An internal call with no credential is answered 401 by our own service and
+// reads to an operator as the vendor rejecting us.
+func TestTheServiceTokenIsSent(t *testing.T) {
+ var auth string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ auth = r.Header.Get("Authorization")
+ _ = json.NewEncoder(w).Encode(map[string]any{"risk_score": 1.0})
+ }))
+ defer server.Close()
+
+ loc := Location{IP: "8.8.8.8"}
+ NewIPEnricher(server.URL, "s3cr3t", time.Minute, time.Second).Enrich(context.Background(), &loc)
+ if auth != "Bearer s3cr3t" {
+ t.Errorf("Authorization = %q, want the service token", auth)
+ }
+}
+
+// A second event from the same address must not be a second round trip.
+func TestTheEnricherCaches(t *testing.T) {
+ calls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls++
+ _ = json.NewEncoder(w).Encode(map[string]any{"risk_score": 5.0})
+ }))
+ defer server.Close()
+
+ enricher := NewIPEnricher(server.URL, "", time.Minute, time.Second)
+ for range 5 {
+ loc := Location{IP: "8.8.8.8"}
+ enricher.Enrich(context.Background(), &loc)
+ }
+ if calls != 1 {
+ t.Errorf("the enrichment service was called %d times for one address", calls)
+ }
+}
+
+// No URL means no enricher, and a nil enricher is usable. A deployment with
+// no enrichment service must get thinner events, not a nil dereference.
+func TestNoURLMeansNoEnricherAndThatIsSafe(t *testing.T) {
+ enricher := NewIPEnricher("", "token", time.Minute, time.Second)
+ if enricher != nil {
+ t.Fatal("an empty URL produced an enricher")
+ }
+ loc := Location{IP: "8.8.8.8"}
+ enricher.Enrich(context.Background(), &loc)
+ if loc.ReputationKnown {
+ t.Error("a nil enricher filled a reputation")
+ }
+}
diff --git a/services/ingest/internal/activity/actor.go b/services/ingest/internal/activity/actor.go
new file mode 100644
index 000000000..f6421f4e5
--- /dev/null
+++ b/services/ingest/internal/activity/actor.go
@@ -0,0 +1,309 @@
+package activity
+
+import "strings"
+
+// Actor-kind derivation, one source at a time.
+//
+// The rule for everything in this file: read a field whose *documented
+// meaning* is the thing being asserted, and return `unknown` otherwise. Each
+// function names the vendor reference it was written against. None of them
+// infers a kind from a name, a domain, a severity or a pattern the vendor
+// does not define — "svc-" in a username means nothing, and a repository that
+// guesses from it will keep guessing wrong on the accounts that matter.
+//
+// References, each read before the derivation below was written:
+//
+// AWS CloudTrail userIdentity.type
+// https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-user-identity.html
+// Okta System Log actor.type
+// https://developer.okta.com/docs/reference/api/system-log/
+// Microsoft 365 Management Activity API UserType
+// https://learn.microsoft.com/en-us/office/office-365-management-api/office-365-management-activity-api-schema
+// Microsoft Entra audit initiatedBy
+// https://learn.microsoft.com/en-us/graph/api/resources/audituserinfo
+// Google Workspace Reports API actor.callerType
+// https://developers.google.com/workspace/admin/reports/reference/rest/v1/activities/list
+// GCP Cloud Audit authenticationInfo
+// https://cloud.google.com/logging/docs/audit
+// GitHub audit log programmatic_access_type
+// https://docs.github.com/en/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/reviewing-the-audit-log-for-your-organization
+// Kubernetes audit user.username and user.groups
+// https://kubernetes.io/docs/reference/access-authn-authz/service-accounts-admin/
+
+// deriveActor fills the actor block. The kind comes from a per-source
+// function; the name, id and email come from the OCSF event, where the
+// normalizer's identity aliases have already reconciled the vendor's spelling.
+func deriveActor(connectorType string, payload, vendor, ocsf map[string]any) Actor {
+ kind, source := actorKind(connectorType, payload, vendor)
+ return Actor{
+ Kind: kind,
+ KindSource: source,
+ Name: str(ocsf, "actor", "user", "name"),
+ ID: str(ocsf, "actor", "user", "uid"),
+ Email: str(ocsf, "actor", "user", "email_addr"),
+ OnBehalfOf: onBehalfOf(connectorType, payload, vendor),
+ }
+}
+
+// actorKind returns the kind and the vendor field it was read from. An empty
+// source string accompanies ActorUnknown and nothing else.
+func actorKind(connectorType string, payload, vendor map[string]any) (ActorKind, string) {
+ // The AI sources are first because they are the only ones that can
+ // report ai_agent, and they say so in their own envelope rather than
+ // in a vendor record.
+ if kind, source := aiActorKind(payload, vendor); kind != ActorUnknown {
+ return kind, source
+ }
+
+ switch connectorType {
+ case "aws_cloudtrail":
+ return cloudTrailActorKind(vendor)
+ case "okta", "okta_system_log":
+ return oktaActorKind(vendor)
+ case "m365_audit":
+ return m365ActorKind(vendor)
+ case "azure_entra":
+ return entraActorKind(vendor)
+ case "google_workspace":
+ return workspaceActorKind(vendor)
+ case "gcp_cloud_audit":
+ return gcpActorKind(vendor)
+ case "github":
+ return githubActorKind(vendor)
+ case "kubernetes_audit":
+ return kubernetesActorKind(vendor)
+ }
+ return ActorUnknown, ""
+}
+
+// aiActorKind reads the AI SDK's own envelope. `agent_id` is set by
+// packages/aisoc-ai-sdk and by the ai-runtime webhook template, and it means
+// exactly one thing: an autonomous agent made this call.
+func aiActorKind(payload, vendor map[string]any) (ActorKind, string) {
+ for _, m := range []map[string]any{payload, vendor} {
+ if str(m, "agent_id") != "" {
+ return ActorAIAgent, "agent_id"
+ }
+ }
+ return ActorUnknown, ""
+}
+
+// cloudTrailActorKind reads `userIdentity.type`, whose documented members are
+// Root, IAMUser, AssumedRole, Role, FederatedUser, Directory, AWSAccount,
+// AWSService, IdentityCenterUser, SAMLUser, WebIdentityUser and Unknown.
+//
+// `IAMUser` and `AssumedRole` deliberately return unknown. AWS does not say
+// whether an IAM user is a person, and in practice a great many are
+// long-lived programmatic identities; an assumed role is whatever assumed it.
+// Returning `human` for either would put a guess in the field whose whole
+// purpose is to be ungessed.
+//
+// `invokedBy` is checked first and overrides the type: AWS sets it when
+// another AWS service made the call, which is compute acting as itself
+// whatever the principal's type says.
+func cloudTrailActorKind(vendor map[string]any) (ActorKind, string) {
+ identity, _ := nested(vendor, "userIdentity").(map[string]any)
+ if identity == nil {
+ return ActorUnknown, ""
+ }
+ if str(identity, "invokedBy") != "" {
+ return ActorWorkload, "userIdentity.invokedBy"
+ }
+ switch str(identity, "type") {
+ case "AWSService":
+ return ActorWorkload, "userIdentity.type"
+ case "Root", "IdentityCenterUser", "SAMLUser", "WebIdentityUser", "FederatedUser":
+ return ActorHuman, "userIdentity.type"
+ }
+ return ActorUnknown, ""
+}
+
+// oktaActorKind reads `actor.type`. Okta's documented members include User,
+// SystemPrincipal, PublicClientApp, AppInstance, AppUser and Client.
+//
+// AppUser is not mapped: Okta uses it for an application's representation of
+// a user, which is a person's account inside an app rather than a statement
+// about who acted.
+func oktaActorKind(vendor map[string]any) (ActorKind, string) {
+ switch str(vendor, "actor", "type") {
+ case "User":
+ return ActorHuman, "actor.type"
+ case "SystemPrincipal":
+ return ActorServiceAccount, "actor.type"
+ case "PublicClientApp", "AppInstance", "Client":
+ return ActorOAuthApp, "actor.type"
+ }
+ return ActorUnknown, ""
+}
+
+// m365ActorKind reads `UserType`, an integer enumeration: 0 Regular,
+// 1 Reserved, 2 Admin, 3 DcAdmin, 4 System, 5 Application,
+// 6 ServicePrincipal, 7 CustomPolicy, 8 SystemPolicy.
+//
+// 1, 7 and 8 are not mapped: Reserved has no documented meaning, and the two
+// policy members describe a policy evaluation rather than a principal.
+func m365ActorKind(vendor map[string]any) (ActorKind, string) {
+ value, ok := intField(vendor, "UserType")
+ if !ok {
+ return ActorUnknown, ""
+ }
+ switch value {
+ case 0, 2, 3:
+ return ActorHuman, "UserType"
+ case 4:
+ return ActorWorkload, "UserType"
+ case 5:
+ return ActorOAuthApp, "UserType"
+ case 6:
+ return ActorServiceAccount, "UserType"
+ }
+ return ActorUnknown, ""
+}
+
+// entraActorKind reads `initiatedBy`, which Graph documents as carrying
+// either a `user` object or an `app` object and never both for one event.
+func entraActorKind(vendor map[string]any) (ActorKind, string) {
+ initiated, _ := nested(vendor, "initiatedBy").(map[string]any)
+ if initiated == nil {
+ return ActorUnknown, ""
+ }
+ if app, ok := initiated["app"].(map[string]any); ok && len(app) > 0 {
+ // A service principal acting with its own credentials is a service
+ // account; one acting with delegated consent is an OAuth app. Graph
+ // distinguishes them by whether a user is also named.
+ if _, hasUser := initiated["user"].(map[string]any); hasUser {
+ return ActorOAuthApp, "initiatedBy.app+user"
+ }
+ return ActorServiceAccount, "initiatedBy.app"
+ }
+ if user, ok := initiated["user"].(map[string]any); ok && len(user) > 0 {
+ return ActorHuman, "initiatedBy.user"
+ }
+ return ActorUnknown, ""
+}
+
+// workspaceActorKind reads `actor.callerType`, documented as USER,
+// APPLICATION, APPLICATION_OWNER or KEY. `KEY` is Google's own name for a
+// request authenticated by a consumer key rather than a signed-in identity.
+func workspaceActorKind(vendor map[string]any) (ActorKind, string) {
+ switch str(vendor, "actor", "callerType") {
+ case "USER":
+ return ActorHuman, "actor.callerType"
+ case "APPLICATION", "APPLICATION_OWNER":
+ return ActorOAuthApp, "actor.callerType"
+ case "KEY":
+ return ActorAPIToken, "actor.callerType"
+ }
+ return ActorUnknown, ""
+}
+
+// gcpActorKind reads `authenticationInfo`. Two documented signals:
+// `serviceAccountDelegationInfo` is present only when a service account was
+// impersonated, and a principal in the `gserviceaccount.com` namespace is a
+// service account by Google's own naming contract rather than by convention.
+func gcpActorKind(vendor map[string]any) (ActorKind, string) {
+ auth, _ := nested(vendor, "protoPayload", "authenticationInfo").(map[string]any)
+ if auth == nil {
+ auth, _ = nested(vendor, "authenticationInfo").(map[string]any)
+ }
+ if auth == nil {
+ return ActorUnknown, ""
+ }
+ if delegation, ok := auth["serviceAccountDelegationInfo"].([]any); ok && len(delegation) > 0 {
+ return ActorServiceAccount, "authenticationInfo.serviceAccountDelegationInfo"
+ }
+ if principal := str(auth, "principalEmail"); strings.HasSuffix(principal, ".gserviceaccount.com") {
+ return ActorServiceAccount, "authenticationInfo.principalEmail"
+ }
+ return ActorUnknown, ""
+}
+
+// githubActorKind reads `programmatic_access_type`, which GitHub sets on
+// audit entries produced through the API, and `actor_is_bot`.
+//
+// The absence of `programmatic_access_type` is not read as "a person": GitHub
+// documents when the field appears, not that it appears on every API event,
+// so treating silence as a web session would be exactly the guess this file
+// refuses.
+func githubActorKind(vendor map[string]any) (ActorKind, string) {
+ if isBot, ok := vendor["actor_is_bot"].(bool); ok && isBot {
+ return ActorWorkload, "actor_is_bot"
+ }
+ access := strings.ToLower(str(vendor, "programmatic_access_type"))
+ switch {
+ case access == "":
+ return ActorUnknown, ""
+ case strings.Contains(access, "personal access token"):
+ return ActorAPIToken, "programmatic_access_type"
+ case strings.Contains(access, "oauth"):
+ return ActorOAuthApp, "programmatic_access_type"
+ case strings.Contains(access, "github app"):
+ return ActorOAuthApp, "programmatic_access_type"
+ case strings.Contains(access, "ssh key") || strings.Contains(access, "deploy key"):
+ return ActorAPIToken, "programmatic_access_type"
+ }
+ return ActorUnknown, ""
+}
+
+// kubernetesActorKind reads `user.username` and `user.groups`. Both prefixes
+// are reserved by Kubernetes itself: `system:serviceaccount:<ns>:<name>` is
+// the only username a service account can have, and `system:node:<name>` the
+// only one a kubelet can.
+func kubernetesActorKind(vendor map[string]any) (ActorKind, string) {
+ username := str(vendor, "user", "username")
+ switch {
+ case strings.HasPrefix(username, "system:serviceaccount:"):
+ return ActorServiceAccount, "user.username"
+ case strings.HasPrefix(username, "system:node:"):
+ return ActorWorkload, "user.username"
+ }
+ if groups, ok := nested(vendor, "user", "groups").([]any); ok {
+ for _, group := range groups {
+ if g, ok := group.(string); ok && g == "system:serviceaccounts" {
+ return ActorServiceAccount, "user.groups"
+ }
+ }
+ }
+ return ActorUnknown, ""
+}
+
+// onBehalfOf is the human an agent, app or token is acting for, where the
+// source names one. Only fields whose documented meaning is "the principal
+// this call is attributed to" qualify.
+func onBehalfOf(connectorType string, payload, vendor map[string]any) string {
+ if v := firstStr(payload, []string{"on_behalf_of"}); v != "" {
+ return v
+ }
+ if v := firstStr(vendor, []string{"on_behalf_of"}); v != "" {
+ return v
+ }
+ switch connectorType {
+ case "aws_cloudtrail":
+ // sourceIdentity is set by AWS when the role was assumed with one,
+ // and it is the documented way an assumed-role chain names the
+ // originating principal.
+ return firstStr(vendor,
+ []string{"userIdentity", "sourceIdentity"},
+ []string{"userIdentity", "sessionContext", "sessionIssuer", "userName"},
+ )
+ case "google_workspace":
+ return str(vendor, "actor", "email")
+ case "m365_audit":
+ return str(vendor, "UserId")
+ }
+ return ""
+}
+
+// intField reads an integer that may have arrived as a float (JSON numbers
+// decode to float64) or as a string.
+func intField(m map[string]any, key string) (int, bool) {
+ switch v := m[key].(type) {
+ case int:
+ return v, true
+ case int64:
+ return int(v), true
+ case float64:
+ return int(v), true
+ }
+ return 0, false
+}
diff --git a/services/ingest/internal/activity/enrich.go b/services/ingest/internal/activity/enrich.go
new file mode 100644
index 000000000..a22b7a3b2
--- /dev/null
+++ b/services/ingest/internal/activity/enrich.go
@@ -0,0 +1,249 @@
+package activity
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "net"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Geography, ASN and reputation for every public IP, at ingest, cached.
+//
+// The data comes from `services/enrichment`, which already merges GreyNoise,
+// VirusTotal, AbuseIPDB and the commercial feeds behind one `POST /enrich`
+// and caches in Redis. Ingest does not reach a vendor directly: a second
+// implementation of the same merge would drift from the one triage reads,
+// and the vendor keys live in one service for a reason.
+//
+// Three constraints this enricher is built around.
+//
+// **Only public addresses are sent.** A private, loopback, link-local or
+// documentation-range address has no geography and no ASN, so a lookup would
+// cost a round trip to learn nothing — and sending one to a service that
+// forwards to third-party vendors would publish the customer's internal
+// topology one address at a time.
+//
+// **It never blocks ingest.** The cache is in-process and the call has a
+// short timeout; a failure leaves the location block without geography and
+// logs, because an event with no ASN is worth far more than no event. This
+// is the same posture the Shodan enricher beside it already takes.
+//
+// **It carries the service token.** An internal call with no credential is
+// answered 401 by our own service and reads to an operator as the vendor
+// rejecting us — the failure shape that cost four separate sites in this
+// tree. When no token is configured the enricher stays off rather than
+// making a call that cannot succeed.
+
+const enrichPath = "/enrich"
+
+// IPEnricher fills geography, ASN and reputation on a Location.
+type IPEnricher struct {
+ baseURL string
+ serviceToken string
+ ttl time.Duration
+ client *http.Client
+ log *slog.Logger
+
+ mu sync.RWMutex
+ cache map[string]ipCacheEntry
+}
+
+type ipCacheEntry struct {
+ value ipFacts
+ expiry time.Time
+}
+
+// ipFacts is what the enrichment service told us about one address.
+// `known` distinguishes "answered, nothing notable" from "nobody answered",
+// which a bare zero score cannot.
+type ipFacts struct {
+ Country string
+ CountryCode string
+ City string
+ ASN int64
+ ASOrg string
+ Reputation float64
+ Known bool
+}
+
+// enrichResponse is the subset of services/enrichment's EnrichmentResult
+// this reads. Kept narrow deliberately: the full result carries dark-web
+// excerpts and vulnerability references that have no column here, and a
+// struct mirroring all of it would need updating every time that one grows.
+type enrichResponse struct {
+ RiskScore float64 `json:"risk_score"`
+ GeoLocation *struct {
+ Country string `json:"country"`
+ CountryCode string `json:"country_code"`
+ City string `json:"city"`
+ ASN int64 `json:"asn"`
+ ASOrg string `json:"as_org"`
+ } `json:"geo_location"`
+}
+
+// NewIPEnricher returns an enricher, or nil when it cannot work.
+//
+// nil is a supported value everywhere it is used: a deployment with no
+// enrichment service configured gets events with an empty geography rather
+// than a constructor that fails or a per-event error log.
+func NewIPEnricher(baseURL, serviceToken string, ttl time.Duration, timeout time.Duration) *IPEnricher {
+ baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
+ if baseURL == "" {
+ return nil
+ }
+ if ttl <= 0 {
+ ttl = time.Hour
+ }
+ if timeout <= 0 {
+ timeout = 2 * time.Second
+ }
+ return &IPEnricher{
+ baseURL: baseURL,
+ serviceToken: strings.TrimSpace(serviceToken),
+ ttl: ttl,
+ client: &http.Client{Timeout: timeout},
+ log: slog.Default().With("component", "ip_enricher"),
+ cache: make(map[string]ipCacheEntry),
+ }
+}
+
+// Enrich fills geography, ASN and reputation on `loc` when its IP is public
+// and something answers. It mutates nothing else and never returns an error:
+// a missed enrichment is a thinner event, not a failed one.
+func (e *IPEnricher) Enrich(ctx context.Context, loc *Location) {
+ if e == nil || loc == nil || !IsPublicIP(loc.IP) {
+ return
+ }
+ facts, ok := e.lookup(ctx, loc.IP)
+ if !ok {
+ return
+ }
+ loc.Country = facts.Country
+ loc.CountryCode = facts.CountryCode
+ loc.City = facts.City
+ loc.ASN = facts.ASN
+ loc.ASOrg = facts.ASOrg
+ loc.Reputation = facts.Reputation
+ loc.ReputationKnown = facts.Known
+}
+
+func (e *IPEnricher) lookup(ctx context.Context, ip string) (ipFacts, bool) {
+ e.mu.RLock()
+ entry, hit := e.cache[ip]
+ e.mu.RUnlock()
+ if hit && time.Now().Before(entry.expiry) {
+ return entry.value, true
+ }
+
+ facts, err := e.fetch(ctx, ip)
+ if err != nil {
+ // Logged as the reparsed canonical address rather than the caller's
+ // string. The value arrives from a connector-supplied event, and
+ // although it has already passed IsPublicIP, that is a predicate a
+ // taint tracker cannot follow across the call -- it read this as
+ // go/log-injection. net.IP.String() reconstructs the address from
+ // parsed octets, so a newline cannot survive it and a reader can see
+ // why without tracing the caller.
+ e.log.Debug("enrichment lookup failed", "ip", net.ParseIP(ip).String(), "error", err)
+ return ipFacts{}, false
+ }
+
+ e.mu.Lock()
+ e.cache[ip] = ipCacheEntry{value: facts, expiry: time.Now().Add(e.ttl)}
+ e.mu.Unlock()
+ return facts, true
+}
+
+func (e *IPEnricher) fetch(ctx context.Context, ip string) (ipFacts, error) {
+ body, err := json.Marshal(map[string]string{"ioc_type": "ip", "value": ip})
+ if err != nil {
+ return ipFacts{}, err
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.baseURL+enrichPath, bytes.NewReader(body))
+ if err != nil {
+ return ipFacts{}, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ if e.serviceToken != "" {
+ req.Header.Set("Authorization", "Bearer "+e.serviceToken)
+ }
+
+ resp, err := e.client.Do(req)
+ if err != nil {
+ return ipFacts{}, err
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode != http.StatusOK {
+ return ipFacts{}, fmt.Errorf("enrichment service returned %d", resp.StatusCode)
+ }
+
+ var parsed enrichResponse
+ if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {
+ return ipFacts{}, err
+ }
+ facts := ipFacts{Reputation: parsed.RiskScore, Known: true}
+ if parsed.GeoLocation != nil {
+ facts.Country = parsed.GeoLocation.Country
+ facts.CountryCode = parsed.GeoLocation.CountryCode
+ facts.City = parsed.GeoLocation.City
+ facts.ASN = parsed.GeoLocation.ASN
+ facts.ASOrg = parsed.GeoLocation.ASOrg
+ }
+ return facts, nil
+}
+
+// IsPublicIP reports whether an address is one a third party could say
+// anything useful about.
+//
+// Exported because the test that proves no private address is ever sent must
+// use the same predicate the enricher does — a second copy would be the
+// gate agreeing with itself.
+//
+// `IsPrivate` alone is not enough: it covers RFC 1918 and unique-local but
+// not loopback, link-local, carrier-grade NAT, the documentation ranges or
+// the unspecified address, and every one of those appears in real telemetry.
+func IsPublicIP(value string) bool {
+ ip := net.ParseIP(strings.TrimSpace(value))
+ if ip == nil {
+ return false
+ }
+ if ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() ||
+ ip.IsLinkLocalMulticast() || ip.IsMulticast() || ip.IsUnspecified() ||
+ ip.IsInterfaceLocalMulticast() {
+ return false
+ }
+ for _, block := range reservedBlocks {
+ if block.Contains(ip) {
+ return false
+ }
+ }
+ return true
+}
+
+// reservedBlocks are the ranges Go's own predicates do not cover but which
+// still have no public answer: carrier-grade NAT, the three IPv4
+// documentation ranges, benchmarking, and the IPv6 documentation range.
+var reservedBlocks = func() []*net.IPNet {
+ cidrs := []string{
+ "100.64.0.0/10", // RFC 6598 carrier-grade NAT
+ "192.0.0.0/24", // RFC 6890 IETF protocol assignments
+ "192.0.2.0/24", // RFC 5737 documentation (TEST-NET-1)
+ "198.51.100.0/24", // RFC 5737 documentation (TEST-NET-2)
+ "203.0.113.0/24", // RFC 5737 documentation (TEST-NET-3)
+ "198.18.0.0/15", // RFC 2544 benchmarking
+ "2001:db8::/32", // RFC 3849 documentation
+ }
+ out := make([]*net.IPNet, 0, len(cidrs))
+ for _, cidr := range cidrs {
+ if _, block, err := net.ParseCIDR(cidr); err == nil {
+ out = append(out, block)
+ }
+ }
+ return out
+}()
diff --git a/services/ingest/internal/activity/useragent.go b/services/ingest/internal/activity/useragent.go
new file mode 100644
index 000000000..09c422e07
--- /dev/null
+++ b/services/ingest/internal/activity/useragent.go
@@ -0,0 +1,188 @@
+package activity
+
+import (
+ "regexp"
+ "strings"
+)
+
+// User-agent parsing, in Go, inside ingest.
+//
+// It belongs here rather than in a downstream service because the string is
+// on the event at normalization time and every consumer wants the same
+// answer. It is deliberately a *classifier* rather than a full UA database:
+// the question a SOC asks of a user agent is not "which Chrome point release"
+// but "was this a browser, a CLI, an SDK, an infrastructure-as-code tool, or
+// something from an offensive toolkit", and a 50 MB regex corpus answers the
+// first question at the cost of a dependency and a monthly update.
+//
+// The raw string is kept beside the parse on every event. A user agent is
+// attacker-controlled, any parser is a lossy summary of it, and a hunt needs
+// the original — a tool renamed to "Mozilla/5.0" is itself the finding.
+
+// ClientCategory is what kind of thing sent the request.
+type ClientCategory string
+
+const (
+ ClientBrowser ClientCategory = "browser"
+ ClientCLI ClientCategory = "cli"
+ ClientSDK ClientCategory = "sdk"
+ ClientIaC ClientCategory = "iac"
+ ClientOffensive ClientCategory = "offensive"
+ // ClientInfrastructure is a monitoring agent, health checker or load
+ // balancer — the traffic that is always there and almost never the
+ // answer, which is worth labelling so it can be excluded on purpose.
+ ClientInfrastructure ClientCategory = "infrastructure"
+ ClientUnknown ClientCategory = "unknown"
+)
+
+// Client is the parsed user agent plus the string it was parsed from.
+type Client struct {
+ Raw string `json:"raw,omitempty"`
+ Family string `json:"family,omitempty"`
+ Version string `json:"version,omitempty"`
+ Category ClientCategory `json:"category,omitempty"`
+}
+
+// signature matches one client family. `pattern` is matched
+// case-insensitively against the raw string; `version` optionally extracts
+// the version that follows.
+type signature struct {
+ family string
+ category ClientCategory
+ pattern *regexp.Regexp
+ version *regexp.Regexp
+}
+
+func sig(family string, category ClientCategory, pattern, version string) signature {
+ s := signature{family: family, category: category, pattern: regexp.MustCompile(`(?i)` + pattern)}
+ if version != "" {
+ s.version = regexp.MustCompile(`(?i)` + version)
+ }
+ return s
+}
+
+// signatures is ordered, most specific first, and the order is load-bearing
+// rather than cosmetic in three places:
+//
+// - every offensive tool is ahead of every browser and SDK, because
+// several of them send a browser-shaped string with their own name
+// appended and the browser pattern would otherwise swallow them;
+// - Edge is ahead of Chrome and Chrome ahead of Safari, because each of
+// those strings contains the next one;
+// - the generic HTTP libraries are last, because an SDK built on one still
+// names itself first.
+var signatures = []signature{
+ // ── offensive tooling ─────────────────────────────────────────────
+ // Cloud and identity attack tools first: these are the ones that show
+ // up in the sources this projection covers.
+ sig("Pacu", ClientOffensive, `\bPacu\b`, ""),
+ sig("ScoutSuite", ClientOffensive, `Scout\s?Suite`, ""),
+ sig("CloudMapper", ClientOffensive, `CloudMapper`, ""),
+ sig("Prowler", ClientOffensive, `\bProwler\b`, ""),
+ sig("ROADtools", ClientOffensive, `ROADtools|roadrecon`, ""),
+ sig("AADInternals", ClientOffensive, `AADInternals`, ""),
+ sig("impacket", ClientOffensive, `impacket`, ""),
+ sig("CobaltStrike", ClientOffensive, `Cobalt\s?Strike`, ""),
+ sig("Metasploit", ClientOffensive, `Metasploit|Meterpreter`, ""),
+ sig("sqlmap", ClientOffensive, `sqlmap`, `sqlmap/([\d.]+)`),
+ sig("Nmap", ClientOffensive, `\bNmap\b|Nmap Scripting Engine`, ""),
+ sig("Nuclei", ClientOffensive, `Nuclei`, ""),
+ sig("Nikto", ClientOffensive, `Nikto`, ""),
+ sig("gobuster", ClientOffensive, `gobuster`, ""),
+ sig("ffuf", ClientOffensive, `\bffuf\b`, ""),
+ sig("Hydra", ClientOffensive, `\bTHC-Hydra\b|\bhydra/`, ""),
+ sig("Burp", ClientOffensive, `Burp\s?Suite|BurpCollaborator`, ""),
+ sig("evil-winrm", ClientOffensive, `evil-winrm`, ""),
+
+ // ── infrastructure-as-code ────────────────────────────────────────
+ sig("Terraform", ClientIaC, `(?:HashiCorp/)?[Tt]erraform`, `[Tt]erraform/([\d.]+)`),
+ sig("OpenTofu", ClientIaC, `OpenTofu`, `OpenTofu/([\d.]+)`),
+ sig("Pulumi", ClientIaC, `[Pp]ulumi`, `pulumi/([\d.]+)`),
+ sig("CloudFormation", ClientIaC, `cloudformation\.amazonaws\.com|CloudFormation`, ""),
+ sig("Ansible", ClientIaC, `ansible-httpget|[Aa]nsible`, `[Aa]nsible/([\d.]+)`),
+ sig("aws-cdk", ClientIaC, `aws-cdk`, `aws-cdk/([\d.]+)`),
+ sig("Crossplane", ClientIaC, `[Cc]rossplane`, ""),
+
+ // ── infrastructure and monitoring ─────────────────────────────────
+ sig("ELB-HealthChecker", ClientInfrastructure, `ELB-HealthChecker`, ""),
+ sig("kube-probe", ClientInfrastructure, `kube-probe`, `kube-probe/([\d.]+)`),
+ sig("Prometheus", ClientInfrastructure, `Prometheus`, `Prometheus/([\d.]+)`),
+ sig("Datadog-Agent", ClientInfrastructure, `Datadog(?:[ -]Agent)?`, ""),
+ sig("Zabbix", ClientInfrastructure, `Zabbix`, ""),
+ sig("GoogleHC", ClientInfrastructure, `GoogleHC`, ""),
+
+ // ── command-line tools ────────────────────────────────────────────
+ // aws-cli is ahead of Boto3: the CLI's own string contains `Botocore`.
+ sig("aws-cli", ClientCLI, `aws-cli`, `aws-cli/([\d.]+)`),
+ sig("gcloud", ClientCLI, `google-cloud-sdk|gcloud`, `(?:google-cloud-sdk|gcloud)/([\d.]+)`),
+ sig("az-cli", ClientCLI, `AZURECLI`, `AZURECLI/([\d.]+)`),
+ sig("kubectl", ClientCLI, `kubectl`, `kubectl/v?([\d.]+)`),
+ sig("gh-cli", ClientCLI, `GitHub CLI`, `GitHub CLI ([\d.]+)`),
+ sig("oci-cli", ClientCLI, `Oracle-PythonCLI`, ""),
+ sig("curl", ClientCLI, `\bcurl/`, `curl/([\d.]+)`),
+ sig("wget", ClientCLI, `\bWget/`, `Wget/([\d.]+)`),
+ sig("HTTPie", ClientCLI, `HTTPie`, `HTTPie/([\d.]+)`),
+ sig("PowerShell", ClientCLI, `WindowsPowerShell|PowerShell`, `PowerShell/([\d.]+)`),
+
+ // ── vendor SDKs ───────────────────────────────────────────────────
+ sig("Boto3", ClientSDK, `Boto3|Botocore`, `Boto3/([\d.]+)`),
+ sig("aws-sdk-go", ClientSDK, `aws-sdk-go`, `aws-sdk-go/([\d.]+)`),
+ sig("aws-sdk-java", ClientSDK, `aws-sdk-java`, `aws-sdk-java/([\d.]+)`),
+ sig("aws-sdk-js", ClientSDK, `aws-sdk-js|aws-sdk-nodejs`, `aws-sdk-(?:js|nodejs)/([\d.]+)`),
+ sig("google-api-client", ClientSDK, `google-api-(?:python|go|java|nodejs)-client`, ""),
+ sig("Azure-SDK", ClientSDK, `azsdk-|Azure-SDK`, ""),
+ sig("okta-sdk", ClientSDK, `okta-sdk`, ""),
+ sig("Octokit", ClientSDK, `octokit`, `octokit[.\w]*/([\d.]+)`),
+
+ // ── browsers ──────────────────────────────────────────────────────
+ // Each of these strings contains the one after it, so the order here
+ // is the whole correctness of the block.
+ sig("Edge", ClientBrowser, `Edg[e]?/`, `Edg[e]?/([\d.]+)`),
+ sig("Opera", ClientBrowser, `OPR/|Opera`, `(?:OPR|Opera)/([\d.]+)`),
+ sig("Firefox", ClientBrowser, `Firefox/`, `Firefox/([\d.]+)`),
+ sig("Chrome", ClientBrowser, `Chrome/|CriOS/`, `(?:Chrome|CriOS)/([\d.]+)`),
+ sig("Safari", ClientBrowser, `Safari/`, `Version/([\d.]+)`),
+ sig("IE", ClientBrowser, `MSIE |Trident/`, `(?:MSIE |rv:)([\d.]+)`),
+
+ // ── generic HTTP libraries, last ──────────────────────────────────
+ sig("python-requests", ClientSDK, `python-requests`, `python-requests/([\d.]+)`),
+ sig("python-urllib", ClientSDK, `[Pp]ython-urllib`, `[Pp]ython-urllib/([\d.]+)`),
+ sig("Go-http-client", ClientSDK, `Go-http-client`, `Go-http-client/([\d.]+)`),
+ sig("okhttp", ClientSDK, `okhttp`, `okhttp/([\d.]+)`),
+ sig("axios", ClientSDK, `axios`, `axios/([\d.]+)`),
+ sig("Java", ClientSDK, `^Java/`, `Java/([\d.]+)`),
+ sig("libcurl", ClientSDK, `libcurl`, `libcurl/([\d.]+)`),
+}
+
+// ParseUserAgent classifies a raw user-agent string.
+//
+// An empty string returns an empty Client rather than one labelled unknown:
+// "no user agent was sent" and "a user agent was sent that we could not
+// place" are different facts, and a source with no UA field at all should
+// not acquire a client block.
+func ParseUserAgent(raw string) Client {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return Client{}
+ }
+ // Bound what a single attacker-chosen header can cost. The longest
+ // legitimate agent seen in these sources is well under this.
+ const maxLen = 512
+ if len(raw) > maxLen {
+ raw = raw[:maxLen]
+ }
+
+ for _, s := range signatures {
+ if !s.pattern.MatchString(raw) {
+ continue
+ }
+ client := Client{Raw: raw, Family: s.family, Category: s.category}
+ if s.version != nil {
+ if m := s.version.FindStringSubmatch(raw); len(m) > 1 {
+ client.Version = m[1]
+ }
+ }
+ return client
+ }
+ return Client{Raw: raw, Category: ClientUnknown}
+}
diff --git a/services/ingest/internal/activity/useragent_test.go b/services/ingest/internal/activity/useragent_test.go
new file mode 100644
index 000000000..ca05ef9d0
--- /dev/null
+++ b/services/ingest/internal/activity/useragent_test.go
@@ -0,0 +1,154 @@
+package activity
+
+import (
+ "strings"
+ "testing"
+)
+
+// Real agent strings, as these sources emit them. Several are the reason the
+// signature order in useragent.go is load-bearing rather than cosmetic.
+func TestParseUserAgentClassifiesRealStrings(t *testing.T) {
+ cases := []struct {
+ raw string
+ wantFamily string
+ wantCategory ClientCategory
+ wantVersion string
+ }{
+ // CloudTrail's own userAgent values.
+ {"aws-cli/2.15.30 Python/3.11.8 Darwin/23.4.0 source/arm64", "aws-cli", ClientCLI, "2.15.30"},
+ {"Boto3/1.34.69 md/Botocore#1.34.69 ua/2.0 os/linux#6.1.0", "Boto3", ClientSDK, "1.34.69"},
+ {"aws-sdk-go/1.50.0 (go1.22; linux; amd64)", "aws-sdk-go", ClientSDK, "1.50.0"},
+ {"cloudformation.amazonaws.com", "CloudFormation", ClientIaC, ""},
+ {"APN/1.0 HashiCorp/1.0 Terraform/1.7.5 (+https://www.terraform.io)", "Terraform", ClientIaC, "1.7.5"},
+ {"OpenTofu/1.6.2", "OpenTofu", ClientIaC, "1.6.2"},
+ // Kubernetes audit.
+ {"kubectl/v1.29.2 (darwin/arm64) kubernetes/4b8e819", "kubectl", ClientCLI, "1.29.2"},
+ {"kube-probe/1.29", "kube-probe", ClientInfrastructure, "1.29"},
+ // Okta and the console.
+ {
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
+ "Chrome", ClientBrowser, "124.0.0.0",
+ },
+ {
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.2478.51",
+ "Edge", ClientBrowser, "124.0.2478.51",
+ },
+ {"Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0", "Firefox", ClientBrowser, "125.0"},
+ // Generic libraries.
+ {"python-requests/2.31.0", "python-requests", ClientSDK, "2.31.0"},
+ {"Go-http-client/2.0", "Go-http-client", ClientSDK, "2.0"},
+ {"curl/8.4.0", "curl", ClientCLI, "8.4.0"},
+ // Offensive tooling, which is the whole reason for the category.
+ {"Pacu/1.5.1 (https://rhinosecuritylabs.com)", "Pacu", ClientOffensive, ""},
+ {"Scout Suite", "ScoutSuite", ClientOffensive, ""},
+ {"sqlmap/1.8.3#stable (https://sqlmap.org)", "sqlmap", ClientOffensive, "1.8.3"},
+ {"Mozilla/5.0 (compatible; Nmap Scripting Engine; https://nmap.org/book/nse.html)", "Nmap", ClientOffensive, ""},
+ // Infrastructure noise, worth labelling so it can be excluded on
+ // purpose rather than by a rule nobody wrote down.
+ {"ELB-HealthChecker/2.0", "ELB-HealthChecker", ClientInfrastructure, ""},
+ {"Prometheus/2.51.1", "Prometheus", ClientInfrastructure, "2.51.1"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.wantFamily, func(t *testing.T) {
+ got := ParseUserAgent(tc.raw)
+ if got.Family != tc.wantFamily {
+ t.Errorf("family = %q, want %q", got.Family, tc.wantFamily)
+ }
+ if got.Category != tc.wantCategory {
+ t.Errorf("category = %q, want %q", got.Category, tc.wantCategory)
+ }
+ if tc.wantVersion != "" && got.Version != tc.wantVersion {
+ t.Errorf("version = %q, want %q", got.Version, tc.wantVersion)
+ }
+ if got.Raw != tc.raw {
+ t.Errorf("the raw string was not kept: %q", got.Raw)
+ }
+ })
+ }
+}
+
+// The order of the browser signatures is the whole correctness of that
+// block: every one of those strings contains the next. An alphabetical
+// reorder would silently reclassify every Edge session as Chrome.
+func TestBrowserSignatureOrderIsNotAccidental(t *testing.T) {
+ edge := "Mozilla/5.0 AppleWebKit/537.36 Chrome/124.0.0.0 Safari/537.36 Edg/124.0.2478.51"
+ if got := ParseUserAgent(edge); got.Family != "Edge" {
+ t.Errorf("an Edge string parsed as %q; Edge must precede Chrome, and Chrome Safari", got.Family)
+ }
+ chrome := "Mozilla/5.0 AppleWebKit/537.36 Chrome/124.0.0.0 Safari/537.36"
+ if got := ParseUserAgent(chrome); got.Family != "Chrome" {
+ t.Errorf("a Chrome string parsed as %q", got.Family)
+ }
+ // aws-cli's own string contains Botocore, so the CLI must win.
+ cli := "aws-cli/2.15.30 md/Botocore#1.34.69 Python/3.11.8"
+ if got := ParseUserAgent(cli); got.Family != "aws-cli" {
+ t.Errorf("an aws-cli string parsed as %q; aws-cli must precede Boto3", got.Family)
+ }
+}
+
+// Offensive tooling that disguises itself as a browser must still be caught,
+// which is why every offensive signature precedes every browser one.
+func TestOffensiveToolingBeatsABrowserDisguise(t *testing.T) {
+ for _, raw := range []string{
+ "Mozilla/5.0 (Windows NT 10.0) Chrome/124.0.0.0 Safari/537.36 sqlmap/1.8",
+ "Mozilla/5.0 (compatible; Nuclei - Open-source project (github.com/projectdiscovery/nuclei))",
+ "Mozilla/5.0 Firefox/125.0 ROADtools",
+ } {
+ got := ParseUserAgent(raw)
+ if got.Category != ClientOffensive {
+ t.Errorf("%q classified as %q; a browser prefix must not hide the tool name", raw, got.Category)
+ }
+ }
+}
+
+// An absent user agent and an unrecognised one are different facts. A source
+// that sends none should not acquire a client block at all.
+func TestAnAbsentAgentIsNotAnUnknownOne(t *testing.T) {
+ if got := ParseUserAgent(""); got != (Client{}) {
+ t.Errorf("an empty string produced %+v, want the zero Client", got)
+ }
+ if got := ParseUserAgent(" "); got != (Client{}) {
+ t.Errorf("whitespace produced %+v, want the zero Client", got)
+ }
+ got := ParseUserAgent("SomeInternalTool/4")
+ if got.Category != ClientUnknown {
+ t.Errorf("an unrecognised agent classified as %q, want unknown", got.Category)
+ }
+ if got.Raw != "SomeInternalTool/4" {
+ t.Errorf("an unrecognised agent lost its raw string: %q", got.Raw)
+ }
+}
+
+// The header is attacker-chosen and reaches a lake column and a graph
+// property.
+func TestTheRawStringIsBounded(t *testing.T) {
+ got := ParseUserAgent(strings.Repeat("x", 100_000))
+ if len(got.Raw) > 512 {
+ t.Errorf("a 100,000-character agent was kept at %d characters", len(got.Raw))
+ }
+}
+
+// A signature that matches nothing is dead weight a reader would still
+// trust, and one whose version regex cannot fire is a column that is always
+// empty for that family.
+func TestEverySignatureIsExercisedByThisSuite(t *testing.T) {
+ // Not a coverage proxy: this asserts the table itself is well formed,
+ // which is the part a reorder or a bad paste breaks.
+ seen := map[string]bool{}
+ for _, s := range signatures {
+ if s.family == "" {
+ t.Error("a signature has no family")
+ }
+ if seen[s.family] {
+ t.Errorf("duplicate signature family %q; the second can never fire", s.family)
+ }
+ seen[s.family] = true
+ if s.pattern == nil {
+ t.Errorf("signature %q has no pattern", s.family)
+ }
+ if s.category == "" || s.category == ClientUnknown {
+ t.Errorf("signature %q declares category %q; a matched signature must name a real category", s.family, s.category)
+ }
+ }
+}
diff --git a/services/ingest/internal/config/config.go b/services/ingest/internal/config/config.go
index d3db832d9..994df4ac4 100644
--- a/services/ingest/internal/config/config.go
+++ b/services/ingest/internal/config/config.go
@@ -45,6 +45,17 @@ type Config struct {
ShodanEnrichEnabled bool
ShodanCacheExpirySecs int
+ // Geography, ASN and reputation on the activity projection's location
+ // block, read from services/enrichment rather than from a vendor
+ // directly: that service already merges the feeds and owns the keys,
+ // and a second merge here would drift from the one triage reads.
+ //
+ // Unset means off, which is why there is no separate enable flag. Only
+ // public addresses are ever sent (see activity.IsPublicIP).
+ EnrichmentServiceURL string
+ EnrichmentCacheTTLSecs int
+ EnrichmentTimeoutSeconds int
+
// CVE / vulnerability correlation.
//
// Off by default. Nothing in the platform consumes VulnKafkaTopic —
@@ -198,6 +209,11 @@ func Load() (*Config, error) {
ShodanEnrichEnabled: getEnv("SHODAN_ENRICH_ENABLED", "false") == "true",
ShodanCacheExpirySecs: mustGetEnvInt("SHODAN_CACHE_EXPIRY_SECS", 3600),
+ // IOC enrichment for the activity projection's location block.
+ EnrichmentServiceURL: getEnv("ENRICHMENT_SERVICE_URL", ""),
+ EnrichmentCacheTTLSecs: mustGetEnvInt("ENRICHMENT_CACHE_TTL_SECS", 3600),
+ EnrichmentTimeoutSeconds: mustGetEnvInt("ENRICHMENT_TIMEOUT_SECS", 2),
+
// CVE correlation
VulnCorrelEnabled: getEnv("VULN_CORREL_ENABLED", "false") == "true",
VulnKafkaTopic: getEnv("VULN_KAFKA_TOPIC", "aisoc.vulnerability_matches"),
diff --git a/services/ingest/internal/graph/extractor.go b/services/ingest/internal/graph/extractor.go
index 607feec4a..29ea51e97 100644
--- a/services/ingest/internal/graph/extractor.go
+++ b/services/ingest/internal/graph/extractor.go
@@ -21,6 +21,7 @@
package graph
import (
+ "encoding/json"
"fmt"
"strings"
"time"
@@ -82,12 +83,132 @@ func ExtractFromOCSF(eventID, tenantID, connectorType string, ocsf map[string]in
// connector since it's pulled from the OCSF mitre_attck enrichment.
extractMITRE(ev, ocsf)
+ // The activity projection, applied to whichever nodes the extractors
+ // above produced. A post-pass rather than a line in each of the five
+ // extractors: the projection is on the event, not on the connector, and
+ // the next extractor somebody adds would otherwise ship without it and
+ // nobody would notice until a traversal came back missing actor_kind
+ // for one source.
+ applyActivityProperties(ev, ocsf)
+
if len(ev.Nodes) == 0 && len(ev.Edges) == 0 {
return nil
}
return ev
}
+// applyActivityProperties copies the projection onto the nodes it describes.
+//
+// Which property lands on which label is declared in schema.go
+// (ActivityNodeProperties) so the schema-drift gate and the writer read one
+// list. Only non-empty values are written, with one deliberate exception:
+// `actor_kind` is written even when it is `unknown`, because "the source
+// declined to say" and "this event predates the projection" are different
+// facts and a Cypher `IS NULL` cannot tell them apart.
+func applyActivityProperties(ev *Event, ocsf map[string]interface{}) {
+ act, ok := ocsf["activity"].(map[string]interface{})
+ if !ok {
+ // The projection is a struct on the normalizer's own path and a map
+ // once it has been through JSON. Both reach this function depending
+ // on whether the graph writer runs in-process or off the topic.
+ act = structToMap(ocsf["activity"])
+ if act == nil {
+ return
+ }
+ }
+ actor := childMap(act, "actor")
+ location := childMap(act, "location")
+ client := childMap(location, "client")
+
+ for i := range ev.Nodes {
+ node := &ev.Nodes[i]
+ if node.Properties == nil {
+ node.Properties = map[string]interface{}{}
+ }
+ switch node.Label {
+ case NodeUser, NodeServiceAccount:
+ node.Properties["actor_kind"] = stringOr(actor["kind"], "unknown")
+ setIfNonEmpty(node.Properties, "actor_kind_source", actor["kind_source"])
+ setIfNonEmpty(node.Properties, "on_behalf_of", actor["on_behalf_of"])
+ case NodeNetworkPath:
+ // Only the source side: the geography and ASN describe where
+ // the action came from, and writing them onto the destination
+ // node would attribute the caller's country to the thing they
+ // reached.
+ if role, _ := node.Properties["role"].(string); role != "src" {
+ continue
+ }
+ setIfNonEmpty(node.Properties, "country_code", location["country_code"])
+ setIfNonEmpty(node.Properties, "as_org", location["as_org"])
+ setIfNonEmpty(node.Properties, "client_family", client["family"])
+ setIfNonEmpty(node.Properties, "client_category", client["category"])
+ if asn := numberOr(location["asn"]); asn != 0 {
+ node.Properties["asn"] = asn
+ }
+ if known, _ := location["reputation_known"].(bool); known {
+ node.Properties["reputation"] = numberOr(location["reputation"])
+ node.Properties["reputation_known"] = true
+ }
+ }
+ }
+}
+
+func childMap(parent map[string]interface{}, key string) map[string]interface{} {
+ if parent == nil {
+ return map[string]interface{}{}
+ }
+ if child, ok := parent[key].(map[string]interface{}); ok {
+ return child
+ }
+ if child := structToMap(parent[key]); child != nil {
+ return child
+ }
+ return map[string]interface{}{}
+}
+
+// structToMap round-trips a value through its JSON form. The projection is a
+// typed struct where the normalizer builds it and a map once it has crossed
+// Kafka; the graph writer runs on both paths and must not see two shapes.
+func structToMap(value interface{}) map[string]interface{} {
+ if value == nil {
+ return nil
+ }
+ encoded, err := json.Marshal(value)
+ if err != nil {
+ return nil
+ }
+ var out map[string]interface{}
+ if err := json.Unmarshal(encoded, &out); err != nil {
+ return nil
+ }
+ return out
+}
+
+func setIfNonEmpty(props map[string]interface{}, key string, value interface{}) {
+ if s, ok := value.(string); ok && strings.TrimSpace(s) != "" {
+ props[key] = s
+ }
+}
+
+func stringOr(value interface{}, fallback string) string {
+ if s, ok := value.(string); ok && strings.TrimSpace(s) != "" {
+ return s
+ }
+ return fallback
+}
+
+func numberOr(value interface{}) float64 {
+ switch v := value.(type) {
+ case float64:
+ return v
+ case int64:
+ return float64(v)
+ case int:
+ return float64(v)
+ }
+ return 0
+}
+
// extractGeneric is the fallback path. Every OCSF event has actor + endpoints
// at known field paths; this pulls those out so we never produce zero-node
// projections for connectors we haven't fully wired yet.
diff --git a/services/ingest/internal/graph/schema.go b/services/ingest/internal/graph/schema.go
index 710caf6bf..ed0b8c436 100644
--- a/services/ingest/internal/graph/schema.go
+++ b/services/ingest/internal/graph/schema.go
@@ -41,7 +41,52 @@ package graph
//
// Every v1.0 label and relationship is unchanged, so a consumer pinned to
// v1.0 keeps working and simply does not see the new vocabulary.
-const SchemaVersion = "v1.1"
+//
+// v1.2 (the activity projection) is strictly additive and adds no label and
+// no relationship. It adds properties, which is why it is a minor bump: the
+// projection ingest now builds on every event (depth plan 2.2) carries onto
+// the nodes it already writes, so a traversal can ask "which of these
+// accounts is a person" without leaving the graph. See ActivityNodeProperties
+// below for exactly which keys land where.
+const SchemaVersion = "v1.2"
+
+// ActivityNodeProperties names the properties the activity projection adds,
+// per label. Declared here rather than only written in the extractor so the
+// schema-drift gate compares the same list the writer uses, and so a reader
+// of the vocabulary sees them without reading the extractor.
+//
+// `actor_kind` is the one that matters: it is the difference between an
+// account and the person, app or token behind it, and a traversal that
+// cannot tell those apart computes a blast radius for the wrong principal.
+// It is written only when ingest derived it from a vendor field — an
+// `unknown` kind is written as `unknown` rather than omitted, because the
+// absence of the property and a source that declined to say are different
+// facts and a Cypher `IS NULL` cannot distinguish them.
+var ActivityNodeProperties = map[NodeLabel][]string{
+ NodeUser: {
+ "actor_kind",
+ // The vendor field the kind was read from, so a reviewer can check
+ // the derivation without re-reading the Go.
+ "actor_kind_source",
+ "on_behalf_of",
+ },
+ NodeServiceAccount: {
+ "actor_kind",
+ "actor_kind_source",
+ "on_behalf_of",
+ },
+ NodeNetworkPath: {
+ "country_code",
+ "asn",
+ "as_org",
+ "reputation",
+ // Whether anything answered. A clean verdict and an unreachable
+ // enrichment service both produce 0.
+ "reputation_known",
+ "client_family",
+ "client_category",
+ },
+}
// NodeLabel is the canonical entity type — matches the Neo4j label.
type NodeLabel string
diff --git a/services/ingest/internal/normalizer/activity_projection_test.go b/services/ingest/internal/normalizer/activity_projection_test.go
new file mode 100644
index 000000000..a94633170
--- /dev/null
+++ b/services/ingest/internal/normalizer/activity_projection_test.go
@@ -0,0 +1,111 @@
+package normalizer
+
+import (
+ "testing"
+
+ "github.com/beenuar/aisoc/services/ingest/internal/activity"
+)
+
+// The projection is on *every* normalized event, not only the ones a
+// derivation recognises. A consumer that has to check whether the block
+// exists before reading it will eventually forget, and the honest answer for
+// a source that says nothing is `unknown` rather than an absent field.
+func TestEveryNormalizedEventCarriesTheProjection(t *testing.T) {
+ n := newLenientNormalizer()
+ for _, connector := range []string{
+ "aws_cloudtrail", "okta", "kubernetes_audit", // have derivations
+ "zscaler", "tailscale", "some_connector_nobody_wrote", // do not
+ } {
+ t.Run(connector, func(t *testing.T) {
+ ev, err := n.Normalize(&RawEvent{
+ ConnectorID: "c-1",
+ ConnectorType: connector,
+ TenantID: "11111111-1111-1111-1111-111111111111",
+ ReceivedAt: "2026-10-07T00:00:00Z",
+ Payload: map[string]interface{}{
+ "source": connector,
+ "raw_event": map[string]interface{}{"id": "1"},
+ "severity": "high",
+ "title": "something happened",
+ },
+ })
+ if err != nil {
+ t.Fatalf("Normalize: %v", err)
+ }
+ act, ok := ev.OcsfEvent["activity"].(activity.Activity)
+ if !ok {
+ t.Fatalf("no activity projection on the event: %T", ev.OcsfEvent["activity"])
+ }
+ if act.Actor.Kind == "" {
+ t.Error("actor.kind is empty; a source that says nothing must report `unknown`, not nothing")
+ }
+ if act.Outcome == "" {
+ t.Error("outcome is empty; a source that says nothing must report `unknown`")
+ }
+ })
+ }
+}
+
+// The projection reads the OCSF event *after* the identity aliases have run,
+// which is the only reason it can name an actor on a connector whose vendor
+// record spells the field something else entirely.
+func TestTheProjectionSeesTheResolvedIdentity(t *testing.T) {
+ ev, err := newLenientNormalizer().Normalize(&RawEvent{
+ ConnectorID: "c-1",
+ ConnectorType: "zscaler",
+ TenantID: "11111111-1111-1111-1111-111111111111",
+ ReceivedAt: "2026-10-07T00:00:00Z",
+ Payload: map[string]interface{}{
+ "source": "zscaler",
+ "raw_event": map[string]interface{}{"userAgent": "aws-cli/2.15.30 Python/3.11.8"},
+ "severity": "medium",
+ "title": "web request",
+ // `actor` is one of the alias sources, not an OCSF field name.
+ "actor": "[email protected]",
+ "src_ip": "203.0.113.9",
+ },
+ })
+ if err != nil {
+ t.Fatalf("Normalize: %v", err)
+ }
+ act := ev.OcsfEvent["activity"].(activity.Activity)
+ if act.Actor.Name != "[email protected]" {
+ t.Errorf("actor.name = %q; the projection must read the alias-resolved OCSF identity", act.Actor.Name)
+ }
+ if act.Location.IP != "203.0.113.9" {
+ t.Errorf("location.ip = %q", act.Location.IP)
+ }
+ if act.Location.Client.Family != "aws-cli" {
+ t.Errorf("client.family = %q, want the parsed user agent", act.Location.Client.Family)
+ }
+ if act.Location.Client.Raw == "" {
+ t.Error("the raw user agent was dropped; it is attacker-controlled and a hunt needs the original")
+ }
+}
+
+// No enrichment service configured means no geography, and that must be a
+// quiet absence rather than a per-event error or a fabricated country.
+func TestWithNoEnricherTheLocationCarriesNoGeography(t *testing.T) {
+ ev, err := newLenientNormalizer().Normalize(&RawEvent{
+ ConnectorID: "c-1",
+ ConnectorType: "zscaler",
+ TenantID: "11111111-1111-1111-1111-111111111111",
+ ReceivedAt: "2026-10-07T00:00:00Z",
+ Payload: map[string]interface{}{
+ "source": "zscaler",
+ "raw_event": map[string]interface{}{},
+ "src_ip": "8.8.8.8",
+ "severity": "low",
+ },
+ })
+ if err != nil {
+ t.Fatalf("Normalize: %v", err)
+ }
+ act := ev.OcsfEvent["activity"].(activity.Activity)
+ if act.Location.Country != "" || act.Location.ASN != 0 {
+ t.Errorf("geography appeared with no enrichment service configured: %+v", act.Location)
+ }
+ if act.Location.ReputationKnown {
+ t.Error("reputation_known is true with no enrichment service configured")
+ }
+}
diff --git a/services/ingest/internal/normalizer/normalizer.go b/services/ingest/internal/normalizer/normalizer.go
index 162f14f0a..1abb04329 100644
--- a/services/ingest/internal/normalizer/normalizer.go
+++ b/services/ingest/internal/normalizer/normalizer.go
@@ -8,6 +8,7 @@ import (
"strings"
"time"
+ "github.com/beenuar/aisoc/services/ingest/internal/activity"
"github.com/beenuar/aisoc/services/ingest/internal/attck"
"github.com/beenuar/aisoc/services/ingest/internal/config"
"github.com/beenuar/aisoc/services/ingest/internal/enrichment"
@@ -77,6 +78,7 @@ type Normalizer struct {
version string
shodan *enrichment.ShodanEnricher
vulnCorrel *enrichment.VulnCorrelator
+ ipEnricher *activity.IPEnricher
// VulnMatches is a channel where VULNERABILITY_MATCH events are published.
// Nil if vuln correlation is disabled.
@@ -410,6 +412,15 @@ func New(cfg *config.Config) (*Normalizer, error) {
n := &Normalizer{
cfg: cfg,
version: "1.1.0",
+ ipEnricher: activity.NewIPEnricher(
+ cfg.EnrichmentServiceURL,
+ cfg.ServiceToken,
+ time.Duration(cfg.EnrichmentCacheTTLSecs)*time.Second,
+ time.Duration(cfg.EnrichmentTimeoutSeconds)*time.Second,
+ ),
+ }
+ if n.ipEnricher != nil {
+ log.Info().Str("url", cfg.EnrichmentServiceURL).Msg("IP geography/ASN/reputation enrichment enabled for the activity projection")
}
// Set up Shodan enrichment if configured
@@ -816,6 +827,22 @@ func (n *Normalizer) Normalize(raw *RawEvent) (*NormalizedEvent, error) {
warnings = append(warnings, w)
}
+ // The activity projection: who acted, what kind of actor they were, what
+ // they did, to which resource, from where, with what outcome.
+ //
+ // Built after the field map and the identity aliases have run, because
+ // it reads the reconciled OCSF identity alongside the vendor's own
+ // record — the vendor record is the only place the identity-type fields
+ // live, and the OCSF event is the only place the cross-vendor aliasing
+ // has already happened.
+ act := activity.Project(connectorType, raw.Payload, ocsf)
+ if n.ipEnricher != nil {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ n.ipEnricher.Enrich(ctx, &act.Location)
+ cancel()
+ }
+ ocsf["activity"] = act
+
// Set metadata
ocsf["metadata"] = map[string]interface{}{
"version": n.version,