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.

wip(2.4): session store, lake columns, graph schema and the one-producer gate

Beenu Arorad0bc894c6ac9
diff --git a/schemas/graph-schema.yaml b/schemas/graph-schema.yaml
index 5a1729726..6ce08fa8a 100644
--- a/schemas/graph-schema.yaml
+++ b/schemas/graph-schema.yaml
@@ -358,6 +358,35 @@ node_labels:
- { name: last_rotated, type: datetime, required: false }
- { name: rotation_days, type: int, required: false }
+ # ── v1.2: session depth (depth plan 2.4) ───────────────────────────────────
+ - label: Session
+ description: >-
+ One session as the vendor understands it, or the closest the vendor lets
+ us get. The node exists so a traversal can ask what else one session
+ touched; the authoritative row is in Postgres, because ADR-0010 measured
+ Neo4j at 42.2% of the CORE profile's remaining memory and kept the graph
+ in `full`. `id` is the same deterministic uuid the Postgres row and the
+ ClickHouse column carry, so the three join without coordinating.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: tenant_id, type: string, required: true }
+ # As the vendor spells it, never a hash: an analyst pastes this into the
+ # vendor's own console, and a value that exists nowhere else cannot be
+ # looked up anywhere.
+ - { name: session_key, type: string, required: true }
+ # vendor_session | vendor_credential | vendor_flow | derived. A property
+ # rather than four labels, because the kinds are a strength ordering and
+ # a query naming each one it wants would silently miss a fifth.
+ - { name: key_kind, type: string, required: true }
+ - { name: key_source, type: string, required: false }
+ - { name: source, type: string, required: true }
+ - { name: principal, type: string, required: false }
+ - { name: originating_human, type: string, required: false }
+ - { name: first_seen_at, type: datetime, required: true }
+ - { name: last_seen_at, type: datetime, required: true }
+ - { name: ended_at, type: datetime, required: false }
+ - { name: event_count, type: int, required: false }
+
# ── v1.1: threat depth ─────────────────────────────────────────────────────
# Malware, Campaign, ThreatActor, Technique and Tactic are *global*
# reference entities: they carry no tenant_id, tenant-scoped reads must
@@ -717,6 +746,46 @@ relationships:
- { name: snapshot_id, type: string, required: true }
- { name: role, type: string, required: false }
+ # ── v1.2: session depth (depth plan 2.4) ───────────────────────────────────
+ - name: OPENED_SESSION
+ source_label: Identity
+ target_label: Session
+ event_edge: true
+ description: >-
+ "What else did this principal do", without scanning every event the
+ principal ever produced.
+ properties:
+ - { name: ts, type: datetime, required: true }
+ - { name: source_event_id, type: string, required: true }
+ - { name: snapshot_id, type: string, required: true }
+
+ - name: ISSUED_SESSION
+ source_label: Session
+ target_label: Session
+ event_edge: true
+ description: >-
+ The assumed-role chain. This edge exists on the issuing STS call and
+ nowhere else: a chained session's own events name only the role it
+ assumed, so without it the person behind the second hop is unrecoverable
+ once the issuing record ages out of the lake. `link_source` records which
+ field established it, because a chain built from a caller-chosen
+ roleSessionName is weaker evidence than one built from sourceIdentity.
+ properties:
+ - { name: ts, type: datetime, required: true }
+ - { name: source_event_id, type: string, required: true }
+ - { name: snapshot_id, type: string, required: true }
+ - { name: link_source, type: string, required: false }
+
+ - name: SESSION_RAISED
+ source_label: Session
+ target_label: Alert
+ event_edge: true
+ description: What the session is accused of.
+ properties:
+ - { name: ts, type: datetime, required: true }
+ - { name: source_event_id, type: string, required: true }
+ - { name: snapshot_id, type: string, required: true }
+
# ── v1.1: threat depth ─────────────────────────────────────────────────────
- name: OBSERVED_IOC
source_label: Alert
diff --git a/scripts/check_session_projection.py b/scripts/check_session_projection.py
new file mode 100644
index 000000000..6b9abda63
--- /dev/null
+++ b/scripts/check_session_projection.py
@@ -0,0 +1,268 @@
+#!/usr/bin/env python3
+"""One producer of a session key, and three consumers that only read it.
+
+ADR-0010 accepted writing sessions to Postgres *and* to the graph, on the
+stated condition that the arrangement is held by a gate rather than by a
+comment. This is that gate.
+
+The hazard it exists for
+------------------------
+`services/ingest/internal/activity/session.go` reads the vendor's own session
+field and labels how strong it is. Three places consume that block: the
+Postgres store (`services/fusion/app/services/sessions.py`), the ClickHouse
+writer (`lake_writer.py`) and the Neo4j writer in Go. The moment one of them
+derives a key itself — reaching for `accessKeyId`, or synthesising a principal
+plus a timestamp because the block was empty — the product has two producers
+that agree today and will not agree after the next vendor-schema change. The
+stores would then disagree about which session an event belongs to, and the
+symptom is a session count that drifts rather than anything failing.
+
+This repository has paid for a second copy of a producer several times, and
+each time the copy was reasonable-looking code in the consumer.
+
+What it checks
+--------------
+1. **One deriver.** Only `session.go` may read a session-identifying vendor
+ field. Any other tracked source file that reads one is a finding.
+2. **The closed set agrees in all three declarations.** The Go constants, the
+ Python tuple and the CHECK constraint in migration `102_sessions.sql` must
+ name exactly the same four kinds. Three hand-maintained copies of one
+ vocabulary is the shape that drifts silently.
+3. **Consumers do not invent a key.** A consumer may read `activity.session`
+ and must not fall back to constructing one when it is absent, because an
+ absent session is a real answer.
+
+Run `--self-test` to see it detect each of those three, performed as the exact
+edit a contributor would make.
+"""
+
+from __future__ import annotations
+
+import argparse
+import re
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+
+#: The one file allowed to read a vendor's session-identifying field.
+PRODUCER = Path("services/ingest/internal/activity/session.go")
+
+#: Where the closed set is declared, three times, by necessity: Go emits it,
+#: Python validates against it, and Postgres constrains on it.
+GO_KINDS = Path("services/ingest/internal/activity/session.go")
+PY_KINDS = Path("services/fusion/app/services/sessions.py")
+SQL_KINDS = Path("services/api/migrations/102_sessions.sql")
+
+#: Vendor fields whose documented meaning is "this session" or "the credential
+#: that is this session". Reading one of these is deriving a session key.
+#:
+#: Written as the field name in the position a lookup would use, so a mention
+#: in prose or a column name does not match. `accessKeyId` is deliberately
+#: scoped to the `userIdentity` and `credentials` objects it appears in,
+#: because an AWS *connector* legitimately handles access keys as credentials
+#: rather than as session identifiers.
+SESSION_FIELD_PATTERNS: tuple[tuple[str, str], ...] = (
+ (r'"externalSessionId"', "Okta session id"),
+ (r'"AADSessionId"', "Entra session id carried on M365 records"),
+ (r'"hashed_token"', "GitHub credential hash"),
+ (r'"subjectFromWebIdentityToken"', "STS web-identity subject"),
+ (r'"userIdentity"\s*,\s*"accessKeyId"', "CloudTrail temporary credential"),
+ (r'"credentials"\s*,\s*"accessKeyId"', "STS issued credential"),
+)
+
+#: Files that read these fields for a reason other than deriving a session.
+#: Each entry needs a reason; an empty allowlist is the goal and the list is
+#: never a convenient place to put a new violation.
+ALLOWED: dict[str, str] = {
+ "scripts/check_session_projection.py": "this gate, which has to name the patterns it looks for",
+ "services/ingest/internal/activity/session_test.go": "the producer's own tests, which assert on these fields by name",
+}
+
+#: A consumer that falls back to building a key when the block is absent.
+#: The shape to catch is a join of identity-ish parts, which is what an
+#: invented key looks like in every language this repo uses.
+INVENTED_KEY = re.compile(
+ r"(session[_a-z]*key\s*=\s*f?[\"'].*\{.*\}.*[\"'])" # f-string assembly
+ r"|(session[_a-z]*key\s*=\s*.*\+\s*.*\+)" # concatenation of three parts
+ r"|(strings\.Join\(\[\]string\{[^}]*\},\s*[\"']\|[\"']\))", # Go pipe-join
+ re.IGNORECASE,
+)
+
+
+def tracked_files() -> list[Path]:
+ out = subprocess.run(
+ ["git", "ls-files", "services", "scripts", "apps", "packages"],
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ check=True,
+ ).stdout
+ keep = {".go", ".py", ".ts", ".tsx"}
+ return [Path(line) for line in out.splitlines() if line and Path(line).suffix in keep]
+
+
+def check_one_deriver(files: list[Path], root: Path) -> list[str]:
+ findings: list[str] = []
+ for rel in files:
+ if rel == PRODUCER or rel.as_posix() in ALLOWED:
+ continue
+ try:
+ text = (root / rel).read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ continue
+ for pattern, what in SESSION_FIELD_PATTERNS:
+ if re.search(pattern, text):
+ findings.append(
+ f"{rel}: reads {what} directly. The session key has exactly one producer "
+ f"({PRODUCER}); read `activity.session` instead, or the two derivations will "
+ f"disagree after the next vendor-schema change and the stores will disagree "
+ f"about which session an event belongs to."
+ )
+ break
+ return findings
+
+
+def _go_kinds(root: Path) -> set[str]:
+ text = (root / GO_KINDS).read_text(encoding="utf-8")
+ return set(re.findall(r'Session\w+\s+SessionKeyKind\s*=\s*"([a-z_]+)"', text))
+
+
+def _py_kinds(root: Path) -> set[str]:
+ text = (root / PY_KINDS).read_text(encoding="utf-8")
+ match = re.search(r"KEY_KINDS:\s*tuple\[str, \.\.\.\]\s*=\s*\(([^)]*)\)", text)
+ if not match:
+ return set()
+ return {value.strip().strip("\"'") for value in match.group(1).split(",") if value.strip()}
+
+
+def _sql_kinds(root: Path) -> set[str]:
+ text = (root / SQL_KINDS).read_text(encoding="utf-8")
+ match = re.search(r"key_kind IN \(([^)]*)\)", text)
+ if not match:
+ return set()
+ return {value.strip().strip("'") for value in match.group(1).split(",") if value.strip()}
+
+
+def check_closed_set(root: Path) -> list[str]:
+ go, py, sql = _go_kinds(root), _py_kinds(root), _sql_kinds(root)
+ if not go:
+ return [f"{GO_KINDS}: no SessionKeyKind constants found; the gate cannot read the closed set"]
+ findings = []
+ if py != go:
+ findings.append(
+ f"{PY_KINDS}: KEY_KINDS is {sorted(py)} but the producer emits {sorted(go)}. "
+ f"A kind the producer emits and this module rejects is silently dropped on the hot path."
+ )
+ if sql != go:
+ findings.append(
+ f"{SQL_KINDS}: the CHECK constraint allows {sorted(sql)} but the producer emits "
+ f"{sorted(go)}. A kind the producer emits and the constraint rejects fails the insert."
+ )
+ return findings
+
+
+def check_no_invented_keys(files: list[Path], root: Path) -> list[str]:
+ findings = []
+ for rel in files:
+ if rel == PRODUCER or rel.as_posix() in ALLOWED:
+ continue
+ try:
+ text = (root / rel).read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ continue
+ if "activity" not in text and "session" not in text.lower():
+ continue
+ for line_no, line in enumerate(text.splitlines(), start=1):
+ if INVENTED_KEY.search(line):
+ findings.append(
+ f"{rel}:{line_no}: builds a session key rather than reading one. An absent "
+ f"session is a real answer; a fabricated grouping makes \"what else did this "
+ f"session do\" answerable with a number that means nothing."
+ )
+ return findings
+
+
+def run(root: Path) -> list[str]:
+ files = tracked_files()
+ return check_one_deriver(files, root) + check_closed_set(root) + check_no_invented_keys(files, root)
+
+
+def self_test() -> int:
+ """Prove the gate detects each violation, as the edit a contributor makes."""
+ failures = []
+
+ with tempfile.TemporaryDirectory() as tmp:
+ work = Path(tmp) / "repo"
+ subprocess.run(["git", "worktree", "add", "--detach", str(work), "HEAD"], cwd=ROOT, capture_output=True, check=True)
+ try:
+ baseline = run(work)
+ if baseline:
+ failures.append(f"the clean tree is not clean: {baseline}")
+
+ # 1. A second deriver, written the way a contributor reasonably would.
+ consumer = work / "services/fusion/app/services/sessions.py"
+ original = consumer.read_text()
+ consumer.write_text(original + '\n\ndef _okta_key(vendor):\n return vendor["authenticationContext"]["externalSessionId"]\n')
+ if not any("one producer" in f for f in run(work)):
+ failures.append("a second deriver of the Okta session id was not detected")
+ consumer.write_text(original)
+
+ # 2. The closed set drifting in one of its three declarations.
+ consumer.write_text(original.replace('("vendor_session", "vendor_credential", "vendor_flow", "derived")', '("vendor_session", "vendor_credential", "derived")'))
+ if not any("KEY_KINDS" in f for f in run(work)):
+ failures.append("a shrunken Python closed set was not detected")
+ consumer.write_text(original)
+
+ migration = work / "services/api/migrations/102_sessions.sql"
+ sql_original = migration.read_text()
+ migration.write_text(sql_original.replace("'vendor_flow', ", ""))
+ if not any("CHECK constraint" in f for f in run(work)):
+ failures.append("a shrunken SQL CHECK constraint was not detected")
+ migration.write_text(sql_original)
+
+ # 3. A consumer inventing a key when the block is absent.
+ consumer.write_text(original + '\n\ndef _fallback(principal, ip, ua):\n session_key = f"{principal}|{ip}|{ua}"\n return session_key\n')
+ if not any("builds a session key" in f for f in run(work)):
+ failures.append("an invented fallback key was not detected")
+ consumer.write_text(original)
+ finally:
+ subprocess.run(["git", "worktree", "remove", "--force", str(work)], cwd=ROOT, capture_output=True)
+
+ if failures:
+ for failure in failures:
+ print(f"SELF-TEST FAILED: {failure}")
+ return 1
+ print("self-test OK: the gate detects a second deriver, a drifted closed set in either "
+ "declaration, and an invented fallback key.")
+ return 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--self-test", action="store_true", help="prove the gate detects each violation")
+ args = parser.parse_args()
+
+ if args.self_test:
+ return self_test()
+
+ findings = run(ROOT)
+ if findings:
+ print("Session projection: the one-producer rule is broken.\n")
+ for finding in findings:
+ print(f" - {finding}")
+ print(
+ "\nADR-0010 accepted two stores for one projection on the condition that this stays "
+ "true. Read `activity.session`; do not re-derive it."
+ )
+ return 1
+
+ kinds = sorted(_go_kinds(ROOT))
+ print(f"OK: one producer ({PRODUCER}), closed set agreed in Go, Python and SQL: {kinds}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/export_graph_schema.py b/scripts/export_graph_schema.py
index e7c5c89a4..106d8acff 100755
--- a/scripts/export_graph_schema.py
+++ b/scripts/export_graph_schema.py
@@ -346,7 +346,7 @@ def compare_against_go(schema: Schema, go_parsed: tuple[set[str], set[str]]) ->
errors.append(
f"node labels declared in Go source but missing from YAML: "
f"{_format_set(missing_in_yaml_labels)} — run "
- f"`python scripts/export_graph_schema.py --write` and update "
+ f"`python scripts/export_graph_schema.py --from-go` and update "
f"apps/docs/docs/architecture/graph-schema.md"
)
@@ -359,7 +359,7 @@ def compare_against_go(schema: Schema, go_parsed: tuple[set[str], set[str]]) ->
errors.append(
f"relationships declared in Go source but missing from YAML: "
f"{_format_set(missing_in_yaml_rels)} — run "
- f"`python scripts/export_graph_schema.py --write` and update "
+ f"`python scripts/export_graph_schema.py --from-go` and update "
f"apps/docs/docs/architecture/graph-schema.md"
)
diff --git a/services/api/app/db/lake_migrations.py b/services/api/app/db/lake_migrations.py
index 6eedaaae8..f508183bc 100644
--- a/services/api/app/db/lake_migrations.py
+++ b/services/api/app/db/lake_migrations.py
@@ -147,6 +147,29 @@ _V2_ACTIVITY_PROJECTION = (
# starts accumulating toward the new ceiling from here.
_V3_RETENTION_CEILING = ("ALTER TABLE aisoc.raw_events MODIFY TTL toDateTime(event_time) + INTERVAL 400 DAY",)
+# ── 004: sessions per principal ────────────────────────────────────────────
+#
+# Depth plan 2.4. The lake is the third store that has to agree on a session,
+# beside the `sessions` table (migration 102) and the Neo4j Session node, and
+# all three carry the same deterministic uuid so a hunt can join them without
+# any of them having coordinated at write time.
+#
+# `session_key_kind` is a column and not a derivable detail: a query counting
+# events per session means something different for a vendor session than for
+# a principal+address+client grouping this product derived, and a hunter who
+# cannot see which they have will mix the two in one result set.
+#
+# A bloom filter on `session_id` rather than on `session_key`: the id is what
+# a join uses, and the key is high-cardinality free text that is read after
+# the id has already narrowed the scan.
+_V4_SESSIONS = (
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS session_id String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS session_key String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS session_key_kind LowCardinality(String) DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN IF NOT EXISTS session_originating_human String DEFAULT ''",
+ "ALTER TABLE aisoc.raw_events ADD INDEX IF NOT EXISTS idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 4",
+)
+
MIGRATIONS: tuple[LakeMigration, ...] = (
LakeMigration(
@@ -179,6 +202,16 @@ MIGRATIONS: tuple[LakeMigration, ...] = (
needs_cluster_ddl=True,
tags=("retention", "depth-4.3"),
),
+ LakeMigration(
+ id="004_sessions",
+ description=(
+ "Adds the session columns (deterministic id shared with Postgres and the graph, the vendor's own "
+ "key, how strong the grouping is, and the originating human) to aisoc.raw_events."
+ ),
+ statements=_V4_SESSIONS,
+ needs_cluster_ddl=True,
+ tags=("sessions", "depth-2.4"),
+ ),
)
diff --git a/services/api/migrations/102_sessions.sql b/services/api/migrations/102_sessions.sql
new file mode 100644
index 000000000..f598784fc
--- /dev/null
+++ b/services/api/migrations/102_sessions.sql
@@ -0,0 +1,157 @@
+-- Depth plan 2.4: sessions per principal.
+--
+-- Why this table is in Postgres and not only in the graph: ADR-0010
+-- (docs/decisions/0010-entity-and-session-context-in-core.md). Neo4j measured
+-- 696.8 MiB resident for 20,000 sessions, which is 42.2% of what the CORE
+-- profile has left at the moment it is triaging an alert; the same rows here
+-- cost +10.9 MiB in a container CORE already runs. The graph still gets the
+-- Session nodes when it is enabled, written from the same ingest-side
+-- projection, so `full` keeps one traversable graph and CORE keeps the
+-- context on the alert.
+--
+-- What a row is
+-- -------------
+-- One session as a *vendor* understands it, or as close as the vendor lets us
+-- get. `services/ingest/internal/activity/session.go` reads the key per event
+-- and labels how strong it is; this table is the stateful half — start, end,
+-- event count, and the walk up an assumed-role chain.
+--
+-- `key_kind` is stored rather than flattened away because the four kinds are
+-- not interchangeable. Okta's externalSessionId is a durable session; Entra's
+-- correlationId groups one sign-in flow and nothing the resulting session went
+-- on to do; a derived key is principal + address + client with an idle gap. A
+-- surface that renders all four as "session" is lying with a precise number,
+-- so the column is NOT NULL and constrained to the producer's closed set.
+--
+-- `id` is deterministic — uuidv5 over (tenant, source, key) — so the lake row,
+-- the graph node and this row agree on one identifier without any of the three
+-- coordinating, and a Kafka replay upserts the same row instead of minting a
+-- second session for events that already have one.
+
+CREATE TABLE IF NOT EXISTS sessions (
+ id uuid PRIMARY KEY,
+ tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+
+ -- As the vendor spells it, never a hash: an analyst pastes this into the
+ -- vendor's own console, and a value that exists nowhere else cannot be
+ -- looked up anywhere.
+ session_key text NOT NULL,
+ key_kind text NOT NULL,
+ -- The vendor field the key was read from, so a reviewer can check the
+ -- derivation against the vendor's documentation without reading Go.
+ key_source text NOT NULL DEFAULT '',
+ source text NOT NULL,
+
+ principal text,
+ -- The person behind the session. On a chained session this is resolved by
+ -- walking `parent_session_id`, because the second hop's own events name
+ -- only the role. NULL is the honest answer when nothing named a person;
+ -- the role name is never read as one.
+ originating_human text,
+ originating_human_source text,
+
+ first_seen_at timestamptz NOT NULL,
+ last_seen_at timestamptz NOT NULL,
+ -- Set when the session is known to have ended: a vendor logout event, or
+ -- the idle gap closing a derived session. NULL means still open *or*
+ -- unknown, which are the same thing from here and are not claimed apart.
+ ended_at timestamptz,
+ ended_reason text,
+
+ event_count bigint NOT NULL DEFAULT 0,
+ -- The strongest actor kind seen on the session's events, from the 2.2
+ -- projection. A session that is sometimes a human and sometimes a token
+ -- is the interesting case, so this is the maximum rather than the first.
+ actor_kinds jsonb NOT NULL DEFAULT '[]'::jsonb,
+ highest_severity text,
+ source_ips jsonb NOT NULL DEFAULT '[]'::jsonb,
+
+ -- The assumed-role chain. ON DELETE SET NULL rather than CASCADE: losing
+ -- the parent must not delete the child's events, it must only make the
+ -- chain unresolvable, which is what actually happened.
+ parent_session_id uuid REFERENCES sessions(id) ON DELETE SET NULL,
+ -- How the parent edge was established, so a chain built from a
+ -- caller-chosen roleSessionName is distinguishable from one built from
+ -- AWS's own sourceIdentity.
+ parent_link_source text,
+
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+
+ CONSTRAINT sessions_key_kind_check CHECK (
+ key_kind IN ('vendor_session', 'vendor_credential', 'vendor_flow', 'derived')
+ )
+);
+
+-- The upsert's conflict target. A key is only unique within its source: an
+-- Okta session id and a GitHub token hash have no shared namespace, and two
+-- tenants may legitimately observe the same vendor identifier.
+CREATE UNIQUE INDEX IF NOT EXISTS sessions_tenant_source_key_idx
+ ON sessions (tenant_id, source, session_key);
+
+-- "What else did this person do" — the question the chain exists to answer.
+CREATE INDEX IF NOT EXISTS sessions_tenant_human_idx
+ ON sessions (tenant_id, originating_human, last_seen_at DESC)
+ WHERE originating_human IS NOT NULL;
+
+-- "What else did this principal do", and the idle sweep's scan.
+CREATE INDEX IF NOT EXISTS sessions_tenant_principal_idx
+ ON sessions (tenant_id, principal, last_seen_at DESC);
+
+CREATE INDEX IF NOT EXISTS sessions_open_idx
+ ON sessions (tenant_id, last_seen_at)
+ WHERE ended_at IS NULL;
+
+CREATE INDEX IF NOT EXISTS sessions_parent_idx
+ ON sessions (parent_session_id)
+ WHERE parent_session_id IS NOT NULL;
+
+COMMENT ON TABLE sessions IS
+ 'One session per principal, keyed by the strongest identifier the source offers. key_kind carries '
+ 'how strong that is and is never flattened away: a vendor session, the credential that is the '
+ 'session, one sign-in flow, or a derived principal+address+client grouping closed on an idle gap.';
+
+COMMENT ON COLUMN sessions.parent_session_id IS
+ 'The session that issued this one, from an STS AssumeRole response. The edge exists only on the '
+ 'issuing call, so it is unrecoverable once that record ages out of the lake.';
+
+-- The alert side. Additive: a stack that rolls the code back keeps running
+-- against this schema, and every existing alert reads NULL, which renders as
+-- "no session context" rather than as a fabricated one.
+ALTER TABLE alerts
+ ADD COLUMN IF NOT EXISTS session_id uuid REFERENCES sessions(id) ON DELETE SET NULL;
+
+-- Denormalized onto the alert deliberately. The queue renders thousands of
+-- rows and the strength of the grouping changes what the row is allowed to
+-- say; a join per row to learn it would make the honest rendering the
+-- expensive one.
+ALTER TABLE alerts
+ ADD COLUMN IF NOT EXISTS session_key_kind text;
+
+ALTER TABLE alerts
+ ADD COLUMN IF NOT EXISTS originating_human text;
+
+CREATE INDEX IF NOT EXISTS alerts_session_idx
+ ON alerts (tenant_id, session_id)
+ WHERE session_id IS NOT NULL;
+
+-- Written out rather than looped with `format()`: the loop was shorter and it
+-- made the policy invisible to `grep` and to
+-- `scripts/check_tenant_query_predicates.py`, which reads migrations to learn
+-- which tables carry one. A control a tool cannot see is a control nobody can
+-- audit.
+DO $$
+BEGIN
+ EXECUTE 'ALTER TABLE sessions ENABLE ROW LEVEL SECURITY';
+ EXECUTE 'ALTER TABLE sessions FORCE ROW LEVEL SECURITY';
+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON sessions';
+ EXECUTE
+ 'CREATE POLICY tenant_isolation ON sessions '
+ 'USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '
+ 'WITH CHECK (tenant_id = current_tenant_id())';
+
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN
+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON sessions TO aisoc_app';
+ END IF;
+END
+$$;
diff --git a/services/fusion/app/main.py b/services/fusion/app/main.py
index 166586976..d8ce126ee 100644
--- a/services/fusion/app/main.py
+++ b/services/fusion/app/main.py
@@ -25,6 +25,7 @@ from app.services.first_seen import FirstSeenStore
from app.services.fusion_engine import FusionEngine
from app.services.ioc_match import TenantIocMatcher
from app.services.lake_writer import LakeWriter
+from app.services.sessions import SessionStore
from app.services.tenant_overlay import OverlayCache
from app.services.ueba_signal import UebaSignalCache
from app.services.windowed_detection import WindowedDetectionEngine
@@ -148,7 +149,12 @@ async def lifespan(app: FastAPI):
# with hot reload. Without it the engine evaluated the shared
# corpus and nothing else, so a tenant who disabled a noisy rule
# in the console kept receiving its alerts.
- overlays=OverlayCache(_overlay_pool()),
+ overlays=OverlayCache(_fusion_pool()),
+ # Depth plan 2.4. Sessions per principal: the stateful half of the
+ # projection `session.go` derives per event. Disabled by the same
+ # switch as the alert sink, because a session row nothing can join
+ # an alert to is a row nobody reads.
+ sessions=SessionStore(_fusion_pool()) if settings.alert_sink_enabled else None,
ueba_cache=ueba_cache,
)
set_worker(worker)
@@ -222,13 +228,21 @@ app.include_router(router)
_OVERLAY_POOL: Any = None
-def _overlay_pool() -> Any:
- """A lazy pool for the tenant-tuning overlay.
+def _fusion_pool() -> Any:
+ """One lazy Postgres pool, shared by the consumer's side readers.
Built on first use rather than at import, because `main` runs before
- an event loop exists and `asyncpg.create_pool` needs one. The cache
- tolerates `None` and returns the empty overlay, so a deployment with
- no database reachable detects exactly as it did before 5.4.
+ an event loop exists and `asyncpg.create_pool` needs one. The overlay
+ cache tolerates `None` and returns the empty overlay, so a deployment
+ with no database reachable detects exactly as it did before 5.4, and
+ the session store logs and returns None for the same reason.
+
+ Shared rather than one pool each: both sit on the consumer's hot path
+ against the same database, and two pools is two connection budgets to
+ size instead of one. Renamed from `_overlay_pool` when the session
+ store (depth plan 2.4) became the second reader, because a name that
+ says "overlay" while two things use it is how the next contributor
+ opens a third.
"""
global _OVERLAY_POOL # noqa: PLW0603
if _OVERLAY_POOL is None:
diff --git a/services/fusion/app/models/alert.py b/services/fusion/app/models/alert.py
index a51c40a80..0b7ffcda6 100644
--- a/services/fusion/app/models/alert.py
+++ b/services/fusion/app/models/alert.py
@@ -197,6 +197,19 @@ class FusedAlert(BaseModel):
# lazily compute it on first read in that case.
narrative: str | None = None
+ # Depth plan 2.4 — which session this alert came out of, and how strongly
+ # that grouping is known. `session_key_kind` travels beside the id rather
+ # than being looked up because it changes what the console is allowed to
+ # say: "17 other events in this session" means the vendor grouped them for
+ # three of the four kinds and means we did for `derived`.
+ #
+ # All three are None on a vendor-asserted finding, which arrives on the
+ # alerts topic rather than as a normalized event and genuinely has no
+ # session. None renders as no session context, never as a session of one.
+ session_id: UUID | None = None
+ session_key_kind: str | None = None
+ originating_human: str | None = None
+
fused_at: datetime = Field(default_factory=datetime.utcnow)
diff --git a/services/fusion/app/services/alert_sink.py b/services/fusion/app/services/alert_sink.py
index 0425ef0d0..a6b260d28 100644
--- a/services/fusion/app/services/alert_sink.py
+++ b/services/fusion/app/services/alert_sink.py
@@ -73,7 +73,8 @@ INSERT INTO alerts (
narrative, anomaly_score, event_time,
connector_id, connector_type, source_event_ids, ocsf_class_uid,
rule_id, rule_name, external_id,
- affected_hosts, affected_users, affected_ips
+ affected_hosts, affected_users, affected_ips,
+ session_id, session_key_kind, originating_human
)
SELECT
$1, $2, $3, $4, $5, 'new',
@@ -82,7 +83,8 @@ SELECT
$15, $16, COALESCE($17, NOW()),
$18, $19, $20::jsonb, $21,
$22, $23, $24,
- $25::jsonb, $26::jsonb, $27::jsonb
+ $25::jsonb, $26::jsonb, $27::jsonb,
+ $28, $29, $30
WHERE NOT EXISTS (
SELECT 1 FROM alerts WHERE tenant_id = $2 AND dedup_hash = $11::text
)
@@ -270,6 +272,9 @@ def _insert_args(fused: FusedAlert) -> tuple[Any, ...]:
json.dumps(hosts),
json.dumps(users),
json.dumps(ips),
+ fused.session_id,
+ fused.session_key_kind,
+ fused.originating_human,
)
diff --git a/services/fusion/app/services/lake_writer.py b/services/fusion/app/services/lake_writer.py
index 6a9a1c564..a7f81e9c4 100644
--- a/services/fusion/app/services/lake_writer.py
+++ b/services/fusion/app/services/lake_writer.py
@@ -96,6 +96,16 @@ _COLUMNS = (
"client_category",
"client_raw",
"outcome",
+ # Sessions per principal (depth plan 2.4). `session_id` is the same
+ # deterministic uuid the Postgres row and the graph node carry, so a hunt
+ # can join the three without any of them having coordinated at write time.
+ # `session_key_kind` rides along because a query that counts events per
+ # session means something different for a vendor session than for a
+ # derived one, and a hunter who cannot see which they have will mix them.
+ "session_id",
+ "session_key",
+ "session_key_kind",
+ "session_originating_human",
)
_INSERT_SQL = f"INSERT INTO aisoc.raw_events ({', '.join(_COLUMNS)}) VALUES"
@@ -270,6 +280,25 @@ def _activity_columns(ocsf: dict[str, Any]) -> dict[str, Any]:
"client_category": _as_str(client.get("category")),
"client_raw": _as_str(client.get("raw"))[:1024],
"outcome": _as_str(act.get("outcome")),
+ **_session_columns(act),
+ }
+
+
+def _session_columns(act: dict[str, Any]) -> dict[str, Any]:
+ """Flatten the session block, defaulting every key for the same reason.
+
+ `session_id` is stamped onto the event by the fusion consumer after the
+ Postgres upsert and before this writer runs. An event that reached the
+ lake without going through that step — a replay, or a deployment with the
+ alert sink off — carries the vendor key and kind but an empty id, which is
+ the honest record: the grouping is known, the row it joins to is not.
+ """
+ session = _as_dict(act.get("session"))
+ return {
+ "session_id": _as_str(session.get("id")),
+ "session_key": _as_str(session.get("key"))[:512],
+ "session_key_kind": _as_str(session.get("key_kind")),
+ "session_originating_human": _as_str(session.get("originating_human")),
}
diff --git a/services/fusion/app/services/sessions.py b/services/fusion/app/services/sessions.py
new file mode 100644
index 000000000..dcba68caf
--- /dev/null
+++ b/services/fusion/app/services/sessions.py
@@ -0,0 +1,388 @@
+"""The stateful half of depth plan 2.4: sessions per principal.
+
+`services/ingest/internal/activity/session.go` is the only producer of a
+session key and its kind. It answers the one question that is answerable from
+a single event and nowhere later: which session does this event belong to, and
+how strongly do we know. Everything that needs more than one event — the
+start, the last sighting, the event count, the walk up an assumed-role chain,
+the idle gap that closes a derived session — is here.
+
+One producer, three consumers
+-----------------------------
+This module, the lake writer and the Go graph writer all read the same
+`activity.session` block and none of them re-derives it. ADR-0010 accepted
+that arrangement on the condition that it is held by a gate rather than by a
+comment, which is `scripts/check_session_projection.py`: it fails if a second
+site in the tree derives a session key, and its self-test performs that exact
+edit.
+
+Why the id is deterministic
+---------------------------
+`uuidv5(namespace, tenant|source|key)` rather than a sequence. Three stores
+have to agree on one identifier — this table, the ClickHouse row and the Neo4j
+node — and the alternative is for two of them to wait on the third. It also
+makes a Kafka replay idempotent: the same event upserts the same row instead
+of minting a second session for events that already have one, which is the
+defect that would show up as a slowly doubling session count and nothing else.
+
+What this module refuses to do
+------------------------------
+It never invents a session. An event whose source names no session and which
+has no principal, address and client to derive one from is recorded as having
+no session, and every surface downstream renders that as "no session context"
+rather than as a session of one event. A fabricated grouping is worse than an
+absent one: it makes "what else did this session do" answerable with a number
+that means nothing.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import uuid
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any
+
+logger = logging.getLogger("aisoc.fusion.sessions")
+
+#: Namespace for the deterministic session id. A fixed, arbitrary UUID — its
+#: only job is to keep session ids from colliding with any other uuidv5 series
+#: in the product. Changing it re-keys every session, so it never changes.
+SESSION_NAMESPACE = uuid.UUID("6f1b0e2a-9a3d-5c7e-8b4f-1d2c3e4f5a6b")
+
+#: The closed set `session.go` emits, in strength order. Mirrored here because
+#: the CHECK constraint in migration 102 and this module must agree; the gate
+#: compares both against the Go constants rather than letting three lists
+#: drift independently.
+KEY_KINDS: tuple[str, ...] = ("vendor_session", "vendor_credential", "vendor_flow", "derived")
+
+#: How long a derived session may be idle before it is considered over.
+#: Derived sessions are the only ones that need this: a vendor session ends
+#: when the vendor says so. Thirty minutes matches the idle timeout Okta and
+#: Entra default to, so a derived session's duration is comparable to a real
+#: one rather than being an arbitrary number of this module's own choosing.
+DERIVED_IDLE_SECONDS = 30 * 60
+
+
+def session_id(tenant_id: str, source: str, key: str) -> uuid.UUID:
+ """The id every store agrees on, without any of them coordinating."""
+ return uuid.uuid5(SESSION_NAMESPACE, f"{tenant_id}|{source}|{key}")
+
+
+@dataclass(frozen=True)
+class SessionRef:
+ """What an alert needs to carry about the session it came from.
+
+ Deliberately not the whole row. The queue renders thousands of alerts and
+ the only things that change what a row is allowed to *say* are the id, how
+ strong the grouping is, and who is behind it.
+ """
+
+ id: uuid.UUID
+ key: str
+ key_kind: str
+ source: str
+ principal: str | None = None
+ originating_human: str | None = None
+ originating_human_source: str | None = None
+
+ @property
+ def is_vendor_grouping(self) -> bool:
+ """True when the vendor grouped these events, rather than we did.
+
+ A surface that says "17 other events in this session" means something
+ different for each answer, and the difference is worth a word in the
+ sentence rather than a footnote nobody reads.
+ """
+ return self.key_kind != "derived"
+
+
+_UPSERT_SQL = """
+INSERT INTO sessions (
+ id, tenant_id, session_key, key_kind, key_source, source,
+ principal, originating_human, originating_human_source,
+ first_seen_at, last_seen_at, event_count, actor_kinds, source_ips
+)
+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10, 1, $11::jsonb, $12::jsonb)
+ON CONFLICT (id) DO UPDATE SET
+ -- least()/greatest() rather than assignment: Kafka delivers out of order
+ -- after a rebalance, so a late event must widen the window and never
+ -- rewind `last_seen_at` to before an event already counted.
+ first_seen_at = least(sessions.first_seen_at, EXCLUDED.first_seen_at),
+ last_seen_at = greatest(sessions.last_seen_at, EXCLUDED.last_seen_at),
+ event_count = sessions.event_count + 1,
+ -- An identity learned later fills a blank; it never overwrites one we
+ -- already have, because the first event to name a person is the one whose
+ -- provenance we recorded alongside it.
+ principal = COALESCE(sessions.principal, EXCLUDED.principal),
+ originating_human = COALESCE(sessions.originating_human, EXCLUDED.originating_human),
+ originating_human_source =
+ CASE WHEN sessions.originating_human IS NULL
+ THEN EXCLUDED.originating_human_source
+ ELSE sessions.originating_human_source END,
+ actor_kinds = (
+ SELECT COALESCE(jsonb_agg(DISTINCT k), '[]'::jsonb)
+ FROM jsonb_array_elements(sessions.actor_kinds || EXCLUDED.actor_kinds) AS k
+ ),
+ source_ips = (
+ SELECT COALESCE(jsonb_agg(DISTINCT ip), '[]'::jsonb)
+ FROM (
+ SELECT ip FROM jsonb_array_elements(sessions.source_ips || EXCLUDED.source_ips) AS ip
+ LIMIT 64
+ ) AS capped
+ ),
+ updated_at = now()
+RETURNING id
+"""
+
+#: Link a child session to the one that issued it.
+#:
+#: The child row may not exist yet — an AssumeRole response names a credential
+#: whose first *use* has not been consumed — so this inserts a placeholder
+#: carrying everything the issuing call knew. `event_count` starts at 0, which
+#: is the honest value: we know this session was created and have seen none of
+#: its events.
+_LINK_ISSUED_SQL = """
+INSERT INTO sessions (
+ id, tenant_id, session_key, key_kind, key_source, source,
+ principal, originating_human, originating_human_source,
+ first_seen_at, last_seen_at, event_count, parent_session_id, parent_link_source
+)
+VALUES ($1, $2, $3, 'vendor_credential', $4, $5, $6, $7, $8, $9, $9, 0, $10, $8)
+ON CONFLICT (id) DO UPDATE SET
+ parent_session_id = COALESCE(sessions.parent_session_id, EXCLUDED.parent_session_id),
+ parent_link_source = COALESCE(sessions.parent_link_source, EXCLUDED.parent_link_source),
+ originating_human = COALESCE(sessions.originating_human, EXCLUDED.originating_human),
+ originating_human_source =
+ CASE WHEN sessions.originating_human IS NULL
+ THEN EXCLUDED.originating_human_source
+ ELSE sessions.originating_human_source END,
+ principal = COALESCE(sessions.principal, EXCLUDED.principal),
+ updated_at = now()
+"""
+
+#: Close derived sessions that have gone quiet. Vendor sessions are left
+#: alone: the vendor says when those end, and guessing on their behalf would
+#: report a session as over while it is still being used.
+_CLOSE_IDLE_SQL = """
+UPDATE sessions
+ SET ended_at = last_seen_at,
+ ended_reason = 'idle',
+ updated_at = now()
+ WHERE ended_at IS NULL
+ AND key_kind = 'derived'
+ AND last_seen_at < now() - make_interval(secs => $1)
+"""
+
+
+class SessionStore:
+ """Upserts one session row per event and resolves the chain.
+
+ Takes an asyncpg pool rather than opening its own, because it runs on the
+ hot path beside the lake writer and a second pool against the same
+ database is two connection budgets to size instead of one.
+ """
+
+ def __init__(self, pool: Any) -> None:
+ self._pool = pool
+
+ async def record_event(self, tenant_id: str, payload: dict[str, Any]) -> SessionRef | None:
+ """Record one event against its session. Returns None when it has none.
+
+ None is a real answer and not a failure: a source that names no
+ session, for an event with no principal, address and client to derive
+ one from, genuinely has no session, and saying so is the point.
+ """
+ block = _session_block(payload)
+ if block is None:
+ return None
+
+ key = str(block.get("key") or "").strip()
+ kind = str(block.get("key_kind") or "").strip()
+ if not key or kind not in KEY_KINDS:
+ # A block with a kind outside the closed set means the producer
+ # and this consumer have drifted. Refuse the row rather than
+ # writing one the CHECK constraint will reject anyway, and say so
+ # loudly: it is a deploy-skew bug, not a data quirk.
+ if kind:
+ logger.warning("fusion.session.unknown_key_kind", extra={"key_kind": kind})
+ return None
+
+ source = _source_of(payload)
+ sid = session_id(tenant_id, source, key)
+ seen_at = _event_time(payload)
+ ref = SessionRef(
+ id=sid,
+ key=key,
+ key_kind=kind,
+ source=source,
+ principal=_clean(block.get("principal")),
+ originating_human=_clean(block.get("originating_human")),
+ originating_human_source=_clean(block.get("originating_human_source")),
+ )
+
+ try:
+ async with self._pool.acquire() as conn:
+ await conn.execute(
+ _UPSERT_SQL,
+ sid,
+ uuid.UUID(tenant_id),
+ key,
+ kind,
+ _clean(block.get("key_source")) or "",
+ source,
+ ref.principal,
+ ref.originating_human,
+ ref.originating_human_source,
+ seen_at,
+ _json_list(_actor_kind(payload)),
+ _json_list(_source_ip(payload)),
+ )
+ issued = block.get("issued")
+ if isinstance(issued, dict):
+ await self._link_issued(conn, tenant_id, source, sid, issued, seen_at)
+ except Exception as exc: # noqa: BLE001 — sessions are context, never the alert path
+ # Deliberately soft. An alert that reaches an analyst without
+ # session context is degraded; an alert that never reaches them
+ # because the session store was unreachable is an outage. Logged
+ # at error with the reason so it is visible rather than absorbed.
+ logger.error("fusion.session.upsert_failed", extra={"error": str(exc)}, exc_info=True)
+ return None
+ return ref
+
+ async def _link_issued(
+ self,
+ conn: Any,
+ tenant_id: str,
+ source: str,
+ parent_id: uuid.UUID,
+ issued: dict[str, Any],
+ seen_at: datetime,
+ ) -> None:
+ """Record the session an STS call created, and the edge back to it.
+
+ This edge exists on the issuing call and nowhere else. The child
+ session's own events name only the role it assumed, so without this
+ the person behind a chained session is unrecoverable — which is the
+ whole reason 2.4 reaches into the AssumeRole response at all.
+ """
+ key = _clean(issued.get("key"))
+ if not key:
+ return
+ child_id = session_id(tenant_id, source, key)
+ if child_id == parent_id:
+ # A call that issued the credential it was made with is not a
+ # chain, and writing the edge would make the row its own parent.
+ return
+ await conn.execute(
+ _LINK_ISSUED_SQL,
+ child_id,
+ uuid.UUID(tenant_id),
+ key,
+ _clean(issued.get("key_source")) or "",
+ source,
+ _clean(issued.get("principal")),
+ _clean(issued.get("originating_human")),
+ _clean(issued.get("originating_human_source")),
+ seen_at,
+ parent_id,
+ )
+
+ async def close_idle(self, idle_seconds: int = DERIVED_IDLE_SECONDS) -> int:
+ """Close derived sessions that have gone quiet. Returns rows closed."""
+ try:
+ async with self._pool.acquire() as conn:
+ result = await conn.execute(_CLOSE_IDLE_SQL, float(idle_seconds))
+ except Exception as exc: # noqa: BLE001 — same reasoning as record_event
+ logger.error("fusion.session.close_idle_failed", extra={"error": str(exc)}, exc_info=True)
+ return 0
+ return _rows_affected(result)
+
+
+def _session_block(payload: dict[str, Any]) -> dict[str, Any] | None:
+ """The `activity.session` block, or None when the event predates 2.4.
+
+ An event from a replayed topic or from before the projection shipped has
+ no block at all and must flow through untouched rather than erroring.
+ """
+ activity = payload.get("activity")
+ if not isinstance(activity, dict):
+ return None
+ block = activity.get("session")
+ return block if isinstance(block, dict) and block else None
+
+
+def _source_of(payload: dict[str, Any]) -> str:
+ for path in (("metadata", "product", "name"), ("connector_type",), ("source",)):
+ node: Any = payload
+ for part in path:
+ node = node.get(part) if isinstance(node, dict) else None
+ if isinstance(node, str) and node.strip():
+ return node.strip()
+ return "unknown"
+
+
+def _event_time(payload: dict[str, Any]) -> datetime:
+ raw = payload.get("time") or payload.get("event_time")
+ if isinstance(raw, datetime):
+ return raw if raw.tzinfo else raw.replace(tzinfo=UTC)
+ if isinstance(raw, int | float):
+ # OCSF `time` is milliseconds since epoch. A value small enough to be
+ # seconds is treated as seconds rather than landing the session in
+ # 1970, which is the shape this mistake takes when it ships.
+ seconds = raw / 1000 if raw > 10_000_000_000 else raw
+ try:
+ return datetime.fromtimestamp(seconds, tz=UTC)
+ except (OverflowError, OSError, ValueError):
+ return datetime.now(UTC)
+ if isinstance(raw, str) and raw:
+ try:
+ parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+ except ValueError:
+ pass
+ return datetime.now(UTC)
+
+
+def _actor_kind(payload: dict[str, Any]) -> str | None:
+ activity = payload.get("activity")
+ if not isinstance(activity, dict):
+ return None
+ actor = activity.get("actor")
+ if not isinstance(actor, dict):
+ return None
+ return _clean(actor.get("kind"))
+
+
+def _source_ip(payload: dict[str, Any]) -> str | None:
+ activity = payload.get("activity")
+ if isinstance(activity, dict):
+ location = activity.get("location")
+ if isinstance(location, dict):
+ if ip := _clean(location.get("ip")):
+ return ip
+ endpoint = payload.get("src_endpoint")
+ if isinstance(endpoint, dict):
+ return _clean(endpoint.get("ip"))
+ return None
+
+
+def _clean(value: Any) -> str | None:
+ if not isinstance(value, str):
+ return None
+ trimmed = value.strip()
+ return trimmed or None
+
+
+def _json_list(value: str | None) -> str:
+ return json.dumps([value] if value else [])
+
+
+def _rows_affected(result: Any) -> int:
+ """asyncpg returns the command tag, e.g. 'UPDATE 7'."""
+ if isinstance(result, str):
+ parts = result.rsplit(" ", 1)
+ if len(parts) == 2 and parts[1].isdigit():
+ return int(parts[1])
+ return 0
diff --git a/services/fusion/app/workers/consumer.py b/services/fusion/app/workers/consumer.py
index 07f60a422..9c6662af7 100644
--- a/services/fusion/app/workers/consumer.py
+++ b/services/fusion/app/workers/consumer.py
@@ -22,6 +22,7 @@ from app.services.event_schema import validate_event
from app.services.fusion_engine import FusionEngine
from app.services.lake_writer import LakeWriter
from app.services.promoter import promote_normalized_event
+from app.services.sessions import SessionRef, SessionStore
from app.services.tenant_overlay import OverlayCache
from app.services.ueba_signal import UebaSignalCache
from app.services.windowed_detection import WindowedDetectionEngine
@@ -39,6 +40,10 @@ _METRICS = {
"persist_unavailable": 0,
"persist_failed": 0,
"laked": 0,
+ # Events recorded against a session (depth plan 2.4). Counted separately
+ # from `laked` so a deployment can see that the session store is working
+ # rather than inferring it from alerts that happen to carry an id.
+ "sessions": 0,
"detected": 0,
"dead_lettered": 0,
"errors": 0,
@@ -59,6 +64,7 @@ class FusionWorker:
first_seen: Any | None = None,
ueba_cache: UebaSignalCache | None = None,
overlays: OverlayCache | None = None,
+ sessions: SessionStore | None = None,
) -> None:
self._engine = engine
self._sink = sink
@@ -70,6 +76,10 @@ class FusionWorker:
#: Per-tenant detection tuning (parity 5.4). Optional, so a
#: deployment that passes nothing behaves exactly as before.
self._overlays = overlays
+ #: Depth plan 2.4. Optional so a deployment without the migration
+ #: behaves exactly as before: alerts carry no session context
+ #: rather than carrying an invented one.
+ self._sessions = sessions
# A poison message must never vanish silently; default to a structured
# logging DLQ so persistence-free deployments still get the signal.
self._dlq: DeadLetterQueue = dlq or LoggingDLQ()
@@ -284,7 +294,30 @@ class FusionWorker:
)
return
+ # Declared ahead of the branch because the tail call below is shared.
+ # A vendor-asserted finding on the alerts topic is not a normalized
+ # event and has no session: None reaches the sink, which renders no
+ # session context rather than attaching the previous event's.
+ session: SessionRef | None = None
+
if topic == settings.kafka_topic_raw_events:
+ # Depth plan 2.4 — record the session this event belongs to before
+ # anything else reads the event, so the lake row, the alert and the
+ # graph node all carry the same session id. `session.go` derived
+ # the key; this is the stateful half that counts the events and
+ # walks the assumed-role chain. It returns None, not an error, for
+ # an event whose source names no session — and that stays None all
+ # the way to the console rather than becoming a session of one.
+ if self._sessions is not None and validation.tenant_id:
+ session = await self._sessions.record_event(str(validation.tenant_id), payload)
+ if session is not None:
+ _METRICS["sessions"] += 1
+ # Stamped onto the event so the lake row carries the same
+ # id as the Postgres row and the graph node, which is what
+ # lets a hunt join the three without any of them having
+ # agreed on anything at write time.
+ payload["activity"]["session"]["id"] = str(session.id)
+
# Phase A1 — archive EVERY normalized event into the ClickHouse lake
# first, independent of the promotion decision below. A non-promoted
# Medium event still has to be queryable via /lake/sql.
@@ -320,7 +353,7 @@ class FusionWorker:
det_alert = self._detector.build_alert(payload, hit)
if det_alert is not None:
_METRICS["detected"] += 1
- await self._fuse_and_persist(det_alert, source_event_id=validation.source_event_id)
+ await self._fuse_and_persist(det_alert, source_event_id=validation.source_event_id, session=session)
# Wave 2 — stateful/windowed detections (brute force, spray, scans)
# count this event into its sliding window and fire once on threshold.
@@ -329,7 +362,7 @@ class FusionWorker:
win_alert = self._windowed.build_alert(payload, hit)
if win_alert is not None:
_METRICS["detected"] += 1
- await self._fuse_and_persist(win_alert, source_event_id=validation.source_event_id)
+ await self._fuse_and_persist(win_alert, source_event_id=validation.source_event_id, session=session)
# Ingest-normalized OCSF event — run the deterministic promotion
# policy (see app/services/promoter.py). Non-promoted events are
@@ -357,9 +390,11 @@ class FusionWorker:
)
return
- await self._fuse_and_persist(alert, source_event_id=validation.source_event_id)
+ await self._fuse_and_persist(alert, source_event_id=validation.source_event_id, session=session)
- async def _fuse_and_persist(self, alert: RawAlert, *, source_event_id: str | None = None) -> None:
+ async def _fuse_and_persist(
+ self, alert: RawAlert, *, source_event_id: str | None = None, session: SessionRef | None = None
+ ) -> None:
"""Run one RawAlert through fusion, persist it, then publish it.
Issue #568: the canonical, replay-stable alert id and source-event
@@ -376,6 +411,15 @@ class FusionWorker:
fused = await self._engine.process(alert)
_METRICS["processed"] += 1
+ # Depth plan 2.4. Attached after fusion rather than before, because
+ # fusion builds the FusedAlert and anything set on the RawAlert first
+ # would have to survive that construction — which is the kind of
+ # assumption that holds until someone adds a field.
+ if session is not None:
+ fused.session_id = session.id
+ fused.session_key_kind = session.key_kind
+ fused.originating_human = session.originating_human
+
if fused.fusion_decision == FusionDecision.DUPLICATE:
_METRICS["duplicates"] += 1
elif fused.fusion_decision == FusionDecision.CORRELATED:
diff --git a/services/fusion/tests/test_alert_sink_batch.py b/services/fusion/tests/test_alert_sink_batch.py
index d68d10939..d49519966 100644
--- a/services/fusion/tests/test_alert_sink_batch.py
+++ b/services/fusion/tests/test_alert_sink_batch.py
@@ -192,4 +192,12 @@ def _fused(index: int): # noqa: ANN202
narrative="",
anomaly_score=0.0,
correlated_events=[],
+ # Depth plan 2.4. Same reason as the alert fields above: a double
+ # more *limited* than the real model raised inside the sink's own
+ # except clause and every row came back FAILED. None is also the
+ # right value here — these rows are not normalized events and
+ # genuinely have no session.
+ session_id=None,
+ session_key_kind=None,
+ originating_human=None,
)
diff --git a/services/fusion/tests/test_sessions.py b/services/fusion/tests/test_sessions.py
new file mode 100644
index 000000000..896c8d913
--- /dev/null
+++ b/services/fusion/tests/test_sessions.py
@@ -0,0 +1,264 @@
+"""Depth plan 2.4 — the stateful half of the session projection.
+
+The fake connection here records the SQL and arguments it was given rather
+than answering whatever it is asked. A double that returns a plausible row for
+any query is how a store that writes to the wrong column passes its tests: the
+assertions below are on what would reach Postgres, and the schema those
+arguments have to satisfy is asserted against the migration itself.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import uuid
+from contextlib import asynccontextmanager
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from app.services.sessions import (
+ KEY_KINDS,
+ SessionStore,
+ session_id,
+)
+
+MIGRATION = Path(__file__).resolve().parents[3] / "services" / "api" / "migrations" / "102_sessions.sql"
+
+TENANT = "11111111-1111-1111-1111-111111111111"
+
+
+class RecordingConn:
+ def __init__(self, fail: Exception | None = None) -> None:
+ self.calls: list[tuple[str, tuple]] = []
+ self._fail = fail
+
+ async def execute(self, sql: str, *args):
+ if self._fail is not None:
+ raise self._fail
+ self.calls.append((sql, args))
+ return "INSERT 0 1"
+
+ def sql_containing(self, needle: str) -> tuple[str, tuple]:
+ for sql, args in self.calls:
+ if needle in sql:
+ return sql, args
+ raise AssertionError(f"no statement containing {needle!r}; saw {[s[:40] for s, _ in self.calls]}")
+
+
+class RecordingPool:
+ def __init__(self, conn: RecordingConn) -> None:
+ self.conn = conn
+
+ @asynccontextmanager
+ async def acquire(self):
+ yield self.conn
+
+
+def event(session: dict | None, *, tenant_source: str = "aws_cloudtrail", actor_kind: str = "human") -> dict:
+ activity: dict = {"actor": {"kind": actor_kind, "id": "arn:aws:iam::1:user/alice"}, "location": {"ip": "203.0.113.10"}}
+ if session is not None:
+ activity["session"] = session
+ return {
+ "metadata": {"product": {"name": tenant_source}},
+ "time": 1_760_000_000_000,
+ "activity": activity,
+ }
+
+
+async def test_a_vendor_session_is_upserted_with_its_kind():
+ conn = RecordingConn()
+ store = SessionStore(RecordingPool(conn))
+
+ ref = await store.record_event(
+ TENANT,
+ event({"key": "ASIAIOSFODNN7EXAMPLE", "key_kind": "vendor_credential", "key_source": "userIdentity.accessKeyId"}),
+ )
+
+ assert ref is not None
+ assert ref.key == "ASIAIOSFODNN7EXAMPLE"
+ assert ref.key_kind == "vendor_credential"
+ assert ref.is_vendor_grouping is True
+
+ _, args = conn.sql_containing("INSERT INTO sessions")
+ assert args[0] == session_id(TENANT, "aws_cloudtrail", "ASIAIOSFODNN7EXAMPLE")
+ assert args[2] == "ASIAIOSFODNN7EXAMPLE"
+ assert args[3] == "vendor_credential"
+ assert json.loads(args[10]) == ["human"]
+ assert json.loads(args[11]) == ["203.0.113.10"]
+
+
+async def test_an_event_with_no_session_writes_nothing():
+ """None is an answer, and it has to stay None all the way to the console.
+
+ A session of one invented for every unattributable event would make "what
+ else did this session do" answerable with a number that means nothing.
+ """
+ conn = RecordingConn()
+ store = SessionStore(RecordingPool(conn))
+
+ assert await store.record_event(TENANT, event(None)) is None
+ assert conn.calls == []
+
+
+async def test_a_kind_outside_the_closed_set_is_refused():
+ """Producer and consumer drift is a deploy-skew bug, not a data quirk.
+
+ Writing the row anyway would fail the CHECK constraint in Postgres and
+ surface as an unexplained insert error on the hot path.
+ """
+ conn = RecordingConn()
+ store = SessionStore(RecordingPool(conn))
+
+ assert await store.record_event(TENANT, event({"key": "s1", "key_kind": "guessed"})) is None
+ assert conn.calls == []
+
+
+async def test_the_derived_kind_is_marked_as_not_the_vendors_grouping():
+ conn = RecordingConn()
+ store = SessionStore(RecordingPool(conn))
+
+ ref = await store.record_event(
+ TENANT, event({"key": "alice|203.0.113.10|curl/8", "key_kind": "derived", "key_source": "principal+ip+user_agent"})
+ )
+
+ assert ref is not None
+ assert ref.is_vendor_grouping is False
+
+
+async def test_the_issued_session_is_written_with_the_edge_back_to_its_parent():
+ """The chain is why 2.4 reaches into the AssumeRole response at all.
+
+ The child session's own events name only the role it assumed, so without
+ this row the person behind it is unrecoverable once the issuing call ages
+ out of the lake.
+ """
+ conn = RecordingConn()
+ store = SessionStore(RecordingPool(conn))
+
+ parent = await store.record_event(
+ TENANT,
+ event(
+ {
+ "key": "AKIAPARENT0000000EXM",
+ "key_kind": "vendor_credential",
+ "key_source": "userIdentity.accessKeyId",
+ "issued": {
+ "key": "ASIACHILD0000000EXMP",
+ "key_source": "responseElements.credentials.accessKeyId",
+ "principal": "arn:aws:sts::1:assumed-role/Deploy/build-471",
+ "originating_human": "[email protected]",
+ "originating_human_source": "requestParameters.sourceIdentity",
+ },
+ }
+ ),
+ )
+
+ assert parent is not None
+ _, args = conn.sql_containing("parent_session_id")
+ assert args[0] == session_id(TENANT, "aws_cloudtrail", "ASIACHILD0000000EXMP")
+ assert args[2] == "ASIACHILD0000000EXMP"
+ assert args[6] == "[email protected]"
+ assert args[7] == "requestParameters.sourceIdentity"
+ assert args[9] == parent.id, "the edge must point at the session that issued the credential"
+
+
+async def test_a_call_that_issued_its_own_credential_is_not_its_own_parent():
+ conn = RecordingConn()
+ store = SessionStore(RecordingPool(conn))
+
+ await store.record_event(
+ TENANT,
+ event(
+ {
+ "key": "ASIASAME00000000EXMP",
+ "key_kind": "vendor_credential",
+ "issued": {"key": "ASIASAME00000000EXMP", "key_source": "responseElements.credentials.accessKeyId"},
+ }
+ ),
+ )
+
+ assert all("parent_session_id" not in sql for sql, _ in conn.calls)
+
+
+async def test_the_id_is_deterministic_across_stores_and_replays():
+ """Three stores have to agree on one id without coordinating, and a Kafka
+ replay must upsert the same row rather than minting a second session."""
+ first = session_id(TENANT, "okta", "102bFs0Aq6VQ1qjqVqk")
+ second = session_id(TENANT, "okta", "102bFs0Aq6VQ1qjqVqk")
+ assert first == second
+ assert isinstance(first, uuid.UUID)
+
+ # Namespaced by tenant and by source: two tenants may legitimately observe
+ # the same vendor identifier, and an Okta session id and a GitHub token
+ # hash share no namespace.
+ assert session_id("22222222-2222-2222-2222-222222222222", "okta", "102bFs0Aq6VQ1qjqVqk") != first
+ assert session_id(TENANT, "github", "102bFs0Aq6VQ1qjqVqk") != first
+
+
+async def test_an_unreachable_store_degrades_the_alert_and_does_not_block_it():
+ """An alert without session context is degraded; an alert that never
+ arrives because the session store was down is an outage."""
+ conn = RecordingConn(fail=RuntimeError("connection refused"))
+ store = SessionStore(RecordingPool(conn))
+
+ assert await store.record_event(TENANT, event({"key": "s1", "key_kind": "vendor_session"})) is None
+
+
+async def test_only_derived_sessions_are_closed_on_an_idle_gap():
+ """A vendor session ends when the vendor says so. Guessing on its behalf
+ would report a session as over while it is still being used."""
+ conn = RecordingConn()
+ store = SessionStore(RecordingPool(conn))
+
+ await store.close_idle(900)
+
+ sql, args = conn.sql_containing("UPDATE sessions")
+ assert "key_kind = 'derived'" in sql
+ assert args[0] == 900.0
+
+
+def test_the_closed_set_matches_the_migrations_check_constraint():
+ """Three declarations of the same vocabulary — Go, this module, and the
+ CHECK constraint — and nothing but a test keeps them equal."""
+ sql = MIGRATION.read_text()
+ match = re.search(r"key_kind IN \(([^)]*)\)", sql)
+ assert match, "migration 102 no longer declares a CHECK on key_kind"
+ in_sql = {value.strip().strip("'") for value in match.group(1).split(",") if value.strip()}
+ assert in_sql == set(KEY_KINDS)
+
+
+def test_the_upsert_widens_the_window_and_never_rewinds_it():
+ """Kafka delivers out of order after a rebalance. A late event must widen
+ the session's window, not move `last_seen_at` back before an event that
+ has already been counted."""
+ from app.services.sessions import _UPSERT_SQL
+
+ assert "least(sessions.first_seen_at" in _UPSERT_SQL
+ assert "greatest(sessions.last_seen_at" in _UPSERT_SQL
+ assert "event_count = sessions.event_count + 1" in _UPSERT_SQL
+
+
+ ("raw", "expect_year"),
+ [
+ (1_760_000_000_000, 2025), # OCSF milliseconds
+ (1_760_000_000, 2025), # seconds, which must not land in 1970
+ ("2026-03-04T05:06:07Z", 2026),
+ (None, datetime.now(UTC).year),
+ ],
+)
+def test_event_time_handles_every_shape_the_spine_delivers(raw, expect_year):
+ from app.services.sessions import _event_time
+
+ payload = {"time": raw} if raw is not None else {}
+ assert _event_time(payload).year == expect_year
diff --git a/services/ingest/internal/graph/schema.go b/services/ingest/internal/graph/schema.go
index ed0b8c436..3d07361ba 100644
--- a/services/ingest/internal/graph/schema.go
+++ b/services/ingest/internal/graph/schema.go
@@ -134,6 +134,19 @@ const (
// These are the global reference labels. They are deliberately not
// tenant-scoped, and tenant_deletion.py exempts them from an
// offboarding purge.
+ // ── v1.2: session depth (depth plan 2.4) ─────────────────────────
+ // One session as the vendor understands it, or the closest the vendor
+ // lets us get. The node exists so a traversal can ask what else one
+ // session touched; the authoritative row is in Postgres, because
+ // ADR-0010 measured Neo4j at 42.2% of the CORE profile's remaining
+ // memory and kept the graph in `full`.
+ //
+ // `key_kind` is a property and not four labels: a query that has to
+ // name every kind it wants would silently miss one when a fifth is
+ // added, and the kinds are a strength ordering rather than four
+ // different things.
+ NodeSession NodeLabel = "Session"
+
NodeIOC NodeLabel = "IOC"
NodeMalware NodeLabel = "Malware"
NodeCampaign NodeLabel = "Campaign"
@@ -169,6 +182,7 @@ var AllNodeLabels = []NodeLabel{
NodeApplication,
NodeCloudAccount,
NodeSecret,
+ NodeSession,
NodeIOC,
NodeMalware,
NodeCampaign,
@@ -240,6 +254,18 @@ const (
RelOwnedBy RelType = "OWNED_BY"
// ── v1.1: threat depth ────────────────────────────────────────────
+ // ── v1.2: session depth (depth plan 2.4) ─────────────────────────
+ // Identity|User -> Session. "What else did this principal do" without
+ // scanning every event the principal ever produced.
+ RelOpenedSession RelType = "OPENED_SESSION"
+ // Session -> Session. The assumed-role chain. This edge exists on the
+ // issuing STS call and nowhere else: a chained session's own events
+ // name only the role, so without it the person behind the second hop
+ // is unrecoverable once the issuing record ages out of the lake.
+ RelIssuedSession RelType = "ISSUED_SESSION"
+ // Session -> Alert. What the session is accused of.
+ RelSessionRaised RelType = "SESSION_RAISED"
+
RelObservedIOC RelType = "OBSERVED_IOC" // Alert -> IOC
RelIndicates RelType = "INDICATES" // IOC -> Malware
RelPartOf RelType = "PART_OF" // Malware -> Campaign
@@ -274,6 +300,9 @@ var AllRelTypes = []RelType{
RelInAccount,
RelStores,
RelOwnedBy,
+ RelOpenedSession,
+ RelIssuedSession,
+ RelSessionRaised,
RelObservedIOC,
RelIndicates,
RelPartOf,