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.

fix(api): close two cross-tenant leaks in the entity graph (#667)

Beenu Arora996f4990f231
diff --git a/services/api/app/services/graph_service.py b/services/api/app/services/graph_service.py
index dba2c067b..a52c3b68e 100644
--- a/services/api/app/services/graph_service.py
+++ b/services/api/app/services/graph_service.py
@@ -279,12 +279,17 @@ async def _attack_path_fallback(case_id: str, tenant_id: str) -> dict[str, Any]:
nodes.append({"id": case_id, "label": "Case", "properties": dict(rec["c"])})
# Alerts
+ # Defence in depth: the Case anchor above is already tenant-verified,
+ # so these alerts are the tenant's own. Scoping anyway means a
+ # mis-tagged CONTAINS_ALERT edge cannot pull in a foreign alert.
r2 = await s.run(
"""
MATCH (c:Case {id: $id})-[:CONTAINS_ALERT]->(a:Alert)
+ WHERE a.tenant_id = $tid
RETURN a
""",
id=case_id,
+ tid=tenant_id,
)
alert_ids = []
async for record in r2:
@@ -326,6 +331,30 @@ async def _attack_path_fallback(case_id: str, tenant_id: str) -> dict[str, Any]:
}
+#: Labels that are global reference data rather than tenant-owned estate.
+#: MITRE techniques are shared by every tenant, so requiring a tenant_id on
+#: them would make technique nodes unreachable for everyone.
+_GLOBAL_LABELS = ("Technique", "Tactic", "Mitigation")
+
+#: Cypher predicate asserting a node belongs to the querying tenant.
+#:
+#: `tenant_id IS NULL` is deliberately NOT accepted. An untagged node would
+#: otherwise act as a bridge between tenants: a traversal could enter it from
+#: tenant A and leave it into tenant B's estate.
+#:
+#: The Go graph writer MERGEs on `natural_key` alone with `tenant_id` as a
+#: property, so shared entities such as a public IP are last-writer-wins. A
+#: strict read filter therefore fails closed — safe, never leaking, at the cost
+#: of some completeness on shared infrastructure nodes. Re-keying those nodes
+#: on `(tenant_id, natural_key)` is the proper fix and needs a migration.
+_TENANT_SCOPED = "({var}.tenant_id = $tenant_id OR any(l IN labels({var}) WHERE l IN $global_labels))"
+
+
+def _scoped(var: str) -> str:
+ """Tenant-scoping predicate for one Cypher variable."""
+ return _TENANT_SCOPED.format(var=var)
+
+
async def get_blast_radius(entity_id: str, entity_type: str, tenant_id: str, hops: int = 3) -> dict[str, Any]:
"""
Compute blast radius: all entities reachable from an IOC/Host/User within N hops.
@@ -340,15 +369,21 @@ async def get_blast_radius(entity_id: str, entity_type: str, tenant_id: str, hop
label = label_map.get(entity_type.lower(), "Host")
id_prop = "value" if label == "IOC" else "id"
+ # Every node of every path is scoped, not just the start node. Filtering
+ # only `start` let the APOC expansion walk out through a shared entity —
+ # a public IP seen by two tenants, for instance — and enumerate the other
+ # tenant's hosts and users, returning their full properties. Blast radius
+ # is exactly the query an attacker would want for reconnaissance.
cypher = f"""
MATCH (start:{label} {{{id_prop}: $entity_id}})
- WHERE start.tenant_id = $tenant_id OR start.tenant_id IS NULL
+ WHERE {_scoped("start")}
CALL apoc.path.expandConfig(start, {{
maxLevel: $hops,
bfs: true,
uniqueness: 'NODE_GLOBAL'
}})
YIELD path
+ WHERE all(pn IN nodes(path) WHERE {_scoped("pn")})
WITH nodes(path) AS path_nodes, relationships(path) AS path_rels
UNWIND path_nodes AS n
WITH COLLECT(DISTINCT {{
@@ -360,7 +395,13 @@ async def get_blast_radius(entity_id: str, entity_type: str, tenant_id: str, hop
"""
async with get_session() as s:
- result = await s.run(cypher, entity_id=entity_id, tenant_id=tenant_id, hops=hops)
+ result = await s.run(
+ cypher,
+ entity_id=entity_id,
+ tenant_id=tenant_id,
+ hops=hops,
+ global_labels=list(_GLOBAL_LABELS),
+ )
record = await result.single()
if not record:
@@ -389,10 +430,16 @@ async def _blast_radius_fallback(entity_id: str, entity_type: str, tenant_id: st
label = label_map.get(entity_type.lower(), "Host")
id_prop = "value" if label == "IOC" else "id"
+ # Scoped the same way as the APOC path above. Previously `start` had no
+ # tenant predicate at all, the intermediate nodes of the variable-length
+ # path were unchecked, and `tenant_id IS NULL` was accepted on the
+ # endpoint — so an untagged node bridged straight into another tenant's
+ # estate. Binding the path lets us assert every node on it.
cypher = f"""
MATCH (start:{label} {{{id_prop}: $entity_id}})
- MATCH (start)-[*1..{hops}]-(n)
- WHERE n.tenant_id = $tenant_id OR n.tenant_id IS NULL
+ WHERE {_scoped("start")}
+ MATCH path = (start)-[*1..{hops}]-(n)
+ WHERE all(pn IN nodes(path) WHERE {_scoped("pn")})
RETURN COLLECT(DISTINCT {{
id: coalesce(n.id, n.value, n.technique_id),
label: labels(n)[0],
@@ -400,7 +447,12 @@ async def _blast_radius_fallback(entity_id: str, entity_type: str, tenant_id: st
}}) AS affected
"""
async with get_session() as s:
- result = await s.run(cypher, entity_id=entity_id, tenant_id=tenant_id)
+ result = await s.run(
+ cypher,
+ entity_id=entity_id,
+ tenant_id=tenant_id,
+ global_labels=list(_GLOBAL_LABELS),
+ )
record = await result.single()
affected = record["affected"] if record else []
@@ -440,9 +492,16 @@ async def get_entity_neighbors(
label = label_map.get(entity_type.lower(), "Host")
id_prop = "value" if label == "IOC" else "id"
+ # This function accepted `tenant_id` and never bound or used it: the query
+ # had no tenant predicate and the parameter was not even passed to
+ # `s.run`. Any authenticated user could read any other tenant's host, user
+ # or IOC node and all of its neighbours, with full node properties, just by
+ # naming the id. Both the anchor node and each neighbour are now scoped.
cypher = f"""
MATCH (n:{label} {{{id_prop}: $entity_id}})
+ WHERE {_scoped("n")}
MATCH (n)-[r]-(neighbor)
+ WHERE {_scoped("neighbor")}
RETURN
{{id: coalesce(n.id, n.value), label: labels(n)[0], properties: properties(n)}} AS source,
COLLECT(DISTINCT {{
@@ -453,7 +512,12 @@ async def get_entity_neighbors(
}}) AS neighbors
"""
async with get_session() as s:
- result = await s.run(cypher, entity_id=entity_id)
+ result = await s.run(
+ cypher,
+ entity_id=entity_id,
+ tenant_id=tenant_id,
+ global_labels=list(_GLOBAL_LABELS),
+ )
record = await result.single()
if not record:
diff --git a/services/api/tests/test_graph_tenant_isolation.py b/services/api/tests/test_graph_tenant_isolation.py
new file mode 100644
index 000000000..472ceda04
--- /dev/null
+++ b/services/api/tests/test_graph_tenant_isolation.py
@@ -0,0 +1,150 @@
+"""Graph reads must be scoped to the querying tenant.
+
+Two real cross-tenant leaks lived here.
+
+`get_entity_neighbors` accepted a `tenant_id` argument and never used it. The
+Cypher had no tenant predicate and the parameter was not even passed to the
+driver, so any authenticated user could read any other tenant's host, user or
+IOC node plus all of its neighbours — with full node properties — just by
+naming the id.
+
+`get_blast_radius` filtered only the traversal's *start* node, and accepted
+`tenant_id IS NULL`. The APOC expansion could therefore leave the tenant's
+estate through a shared entity such as a public IP and enumerate another
+tenant's hosts and users. Blast radius is exactly the query an attacker would
+want for reconnaissance.
+
+These tests assert the shape of the query and, critically, that `tenant_id` is
+bound at all. The original bug was not a subtly wrong predicate; it was a
+parameter that never reached the database, which is why a review reading the
+function signature saw a tenant-scoped API.
+"""
+
+from __future__ import annotations
+
+import contextlib
+from typing import Any
+
+import pytest
+
+graph_service = pytest.importorskip(
+ "app.services.graph_service",
+ reason="neo4j driver not installed",
+)
+
+
+class _FakeResult:
+ def __init__(self, record: Any) -> None:
+ self._record = record
+
+ async def single(self) -> Any:
+ return self._record
+
+ def __aiter__(self):
+ async def _gen():
+ if False: # pragma: no cover — empty async iterator
+ yield None
+
+ return _gen()
+
+
+class _FakeSession:
+ """Captures every Cypher statement and its bound parameters."""
+
+ def __init__(self, record: Any = None) -> None:
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+ self._record = record
+
+ async def run(self, cypher: str, **params: Any) -> _FakeResult:
+ self.calls.append((cypher, params))
+ return _FakeResult(self._record)
+
+
+def session(monkeypatch: pytest.MonkeyPatch) -> _FakeSession:
+ fake = _FakeSession(record={"source": None, "neighbors": [], "all_nodes": [], "affected": []})
+
+ @contextlib.asynccontextmanager
+ async def _get_session():
+ yield fake
+
+ monkeypatch.setattr(graph_service, "get_session", _get_session)
+ return fake
+
+
+TENANT = "tenant-a"
+
+
+def _assert_scoped(cypher: str, params: dict[str, Any], variables: list[str]) -> None:
+ """Every named variable is tenant-scoped, and tenant_id is really bound."""
+ assert params.get("tenant_id") == TENANT, "tenant_id was not bound to the query"
+ assert params.get("global_labels"), "global reference labels were not bound"
+ for var in variables:
+ assert f"{var}.tenant_id = $tenant_id" in cypher, f"{var} is not tenant-scoped"
+
+
+# ── neighbours ────────────────────────────────────────────────────────────
+
+
+async def test_neighbours_binds_the_tenant_and_scopes_both_ends(session: _FakeSession):
+ """The regression: tenant_id was accepted and then dropped entirely."""
+ await graph_service.get_entity_neighbors(entity_id="host-1", entity_type="host", tenant_id=TENANT)
+ cypher, params = session.calls[0]
+ _assert_scoped(cypher, params, ["n", "neighbor"])
+
+
+async def test_neighbours_does_not_accept_an_untagged_node(session: _FakeSession):
+ """An untagged node would bridge tenant A into tenant B's estate."""
+ await graph_service.get_entity_neighbors(entity_id="host-1", entity_type="host", tenant_id=TENANT)
+ cypher, _ = session.calls[0]
+ assert "tenant_id IS NULL" not in cypher
+
+
+# ── blast radius ──────────────────────────────────────────────────────────
+
+
+async def test_blast_radius_scopes_every_node_of_every_path(session: _FakeSession):
+ """Filtering only the start node let the expansion walk out of the tenant."""
+ await graph_service.get_blast_radius(entity_id="1.2.3.4", entity_type="ioc", tenant_id=TENANT)
+ cypher, params = session.calls[0]
+ _assert_scoped(cypher, params, ["start", "pn"])
+ assert "all(pn IN nodes(path)" in cypher, "path nodes are not checked collectively"
+
+
+async def test_blast_radius_no_longer_accepts_untagged_nodes(session: _FakeSession):
+ await graph_service.get_blast_radius(entity_id="1.2.3.4", entity_type="ioc", tenant_id=TENANT)
+ cypher, _ = session.calls[0]
+ assert "tenant_id IS NULL" not in cypher
+
+
+async def test_the_apoc_free_fallback_is_scoped_too(session: _FakeSession):
+ """The fallback runs whenever APOC is absent, so it is not a lesser path.
+
+ It previously had no predicate on `start`, left the intermediate nodes of
+ the variable-length path unchecked, and accepted `tenant_id IS NULL` on
+ the endpoint.
+ """
+ await graph_service._blast_radius_fallback("1.2.3.4", "ioc", TENANT, hops=2)
+ cypher, params = session.calls[0]
+ _assert_scoped(cypher, params, ["start", "pn"])
+ assert "tenant_id IS NULL" not in cypher
+
+
+# ── global reference data ─────────────────────────────────────────────────
+
+
+def test_mitre_techniques_stay_readable_by_every_tenant():
+ """Techniques are shared reference data, not tenant estate.
+
+ Requiring a tenant_id on them would make every technique node unreachable,
+ so the scoping predicate carries a narrow exemption for these labels.
+ """
+ assert "Technique" in graph_service._GLOBAL_LABELS
+ predicate = graph_service._scoped("n")
+ assert "labels(n)" in predicate
+ assert "$global_labels" in predicate