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(agents): persist investigations by resolving the 'default' tenant (#601) (#602)

Beenu Arora8dddf962ac96
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 81f1ad5cc..848bd259e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **Agent investigations are now persisted to the ledger (issue #601).** The
+ demo seed renames the canonical seed tenant's slug from `default` to `demo`,
+ so the agents service's `tenant_ref="default"` fallback matched no tenant and
+ every investigation was silently skipped (`ledger.skip_run
+ reason=unknown_tenant` at `debug`) after already spending compute. Two fixes:
+ the API now forwards the authenticated `tenant_id` to the agents service on
+ `/cases/{id}/investigate` (the run is attributed to the real tenant), and the
+ ledger resolver maps the `"default"` placeholder to the canonical seed tenant
+ (stable UUID, regardless of its current slug) or the sole tenant in a
+ single-tenant install. A genuinely unresolvable tenant now logs at `warning`
+ with the run/case id, not `debug`.
+
## [7.7.0] — 2026-08-04
### Added
diff --git a/services/agents/app/investigator/ledger.py b/services/agents/app/investigator/ledger.py
index 99900b985..97e7b342c 100644
--- a/services/agents/app/investigator/ledger.py
+++ b/services/agents/app/investigator/ledger.py
@@ -84,27 +84,50 @@ async def close_pool() -> None:
_POOL = None
+# The canonical seed tenant (migration 001). Its slug/name can be renamed by the
+# demo seed (slug 'default' → 'demo'), but this UUID is stable — so the 'default'
+# placeholder ref resolves here regardless of the current slug. See issue #601.
+_CANONICAL_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")
+_PLACEHOLDER_TENANT_REFS = frozenset({"", "default"})
+
+
async def _resolve_tenant_id(conn: asyncpg.Connection, tenant_ref: str) -> uuid.UUID | None:
"""Look up the canonical tenant UUID. Accepts a UUID string, slug, or name.
- Returns None if no matching tenant exists. Callers should fall back to
- skipping the write rather than violating the FK.
+ The ``"default"`` placeholder — the agents service's fallback when a caller
+ doesn't pass an explicit tenant — resolves to the canonical seed tenant, or,
+ in a single-tenant install, to the sole tenant. This fixes issue #601: the
+ demo seed renames the seed tenant's slug from ``default`` to ``demo``, so
+ ``"default"`` matched nothing and every investigation was silently skipped.
+
+ Returns None only when the ref is genuinely ambiguous (an unknown ref, or
+ ``"default"`` with several tenants and no canonical one). Callers skip the
+ write rather than violate the FK — but should log loudly, not at debug.
"""
- # If already a UUID, trust it
+ ref = (tenant_ref or "").strip()
+
+ # 1. An explicit UUID is trusted as-is.
try:
- return uuid.UUID(tenant_ref)
+ return uuid.UUID(ref)
except (ValueError, TypeError):
pass
- row = await conn.fetchrow(
- """
- SELECT id FROM tenants
- WHERE slug = $1 OR name = $1
- LIMIT 1
- """,
- tenant_ref,
- )
- return row["id"] if row else None
+ # 2. Exact slug / name match.
+ row = await conn.fetchrow("SELECT id FROM tenants WHERE slug = $1 OR name = $1 LIMIT 1", ref)
+ if row:
+ return row["id"]
+
+ # 3. Placeholder ref → the canonical seed tenant (stable UUID, ignoring its
+ # current slug/name), else the sole tenant in a single-tenant install.
+ if ref.lower() in _PLACEHOLDER_TENANT_REFS:
+ canonical = await conn.fetchrow("SELECT id FROM tenants WHERE id = $1", _CANONICAL_TENANT_ID)
+ if canonical:
+ return canonical["id"]
+ only = await conn.fetch("SELECT id FROM tenants LIMIT 2")
+ if len(only) == 1:
+ return only[0]["id"]
+
+ return None
async def resolve_tenant(tenant_ref: str) -> uuid.UUID | None:
@@ -149,10 +172,16 @@ async def start_run(
async with pool.acquire() as conn:
tenant_id = await _resolve_tenant_id(conn, tenant_ref)
if tenant_id is None:
- logger.debug(
+ # Loud, not debug (issue #601): the Investigation Ledger is a
+ # headline capability — a silent skip leaves it off with no
+ # operator signal after the run has already spent compute.
+ logger.warning(
"ledger.skip_run",
reason="unknown_tenant",
tenant_ref=tenant_ref,
+ run_id=str(run_id),
+ case_id=case_id,
+ hint="pass an explicit tenant_id (UUID/slug); 'default' resolves only when a canonical or single tenant exists",
)
return None
await _set_rls_context(conn, tenant_id)
diff --git a/services/agents/tests/test_ledger_tenant.py b/services/agents/tests/test_ledger_tenant.py
new file mode 100644
index 000000000..ee479afc9
--- /dev/null
+++ b/services/agents/tests/test_ledger_tenant.py
@@ -0,0 +1,84 @@
+"""Ledger tenant resolution (issue #601).
+
+`_resolve_tenant_id` must map the "default" placeholder — the agents service's
+fallback when a caller doesn't pass a tenant — to the canonical seed tenant (or
+the sole tenant in a single-tenant install), so investigations are actually
+persisted instead of silently skipped as `reason=unknown_tenant`.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from app.investigator.ledger import _CANONICAL_TENANT_ID, _resolve_tenant_id
+
+
+class _FakeConn:
+ """Minimal asyncpg-connection stub for the resolver's three queries."""
+
+ def __init__(self, *, by_slug=None, canonical_exists=False, all_ids=None):
+ self._by_slug = by_slug or {}
+ self._canonical_exists = canonical_exists
+ self._all_ids = all_ids or []
+
+ async def fetchrow(self, sql: str, *args):
+ if "slug = $1 OR name = $1" in sql:
+ tid = self._by_slug.get(args[0])
+ return {"id": tid} if tid is not None else None
+ if "WHERE id = $1" in sql:
+ return {"id": _CANONICAL_TENANT_ID} if self._canonical_exists else None
+ return None
+
+ async def fetch(self, sql: str, *args):
+ if "LIMIT 2" in sql:
+ return [{"id": i} for i in self._all_ids[:2]]
+ return []
+
+
+async def test_explicit_uuid_is_trusted():
+ tid = uuid.uuid4()
+ assert await _resolve_tenant_id(_FakeConn(), str(tid)) == tid
+
+
+async def test_slug_match_resolves():
+ demo = uuid.uuid4()
+ conn = _FakeConn(by_slug={"demo": demo})
+ assert await _resolve_tenant_id(conn, "demo") == demo
+
+
+async def test_default_resolves_to_canonical_seed_tenant():
+ # The demo seed renamed slug default -> demo, so slug lookup misses; the
+ # canonical UUID still exists and 'default' must resolve to it.
+ conn = _FakeConn(by_slug={"demo": _CANONICAL_TENANT_ID}, canonical_exists=True)
+ assert await _resolve_tenant_id(conn, "default") == _CANONICAL_TENANT_ID
+
+
+async def test_default_falls_back_to_sole_tenant():
+ only = uuid.uuid4()
+ conn = _FakeConn(canonical_exists=False, all_ids=[only])
+ assert await _resolve_tenant_id(conn, "default") == only
+
+
+async def test_empty_ref_is_treated_as_default():
+ conn = _FakeConn(canonical_exists=True)
+ assert await _resolve_tenant_id(conn, "") == _CANONICAL_TENANT_ID
+
+
+async def test_default_is_ambiguous_with_multiple_tenants_and_no_canonical():
+ conn = _FakeConn(canonical_exists=False, all_ids=[uuid.uuid4(), uuid.uuid4()])
+ assert await _resolve_tenant_id(conn, "default") is None
+
+
+async def test_unknown_ref_returns_none():
+ conn = _FakeConn(by_slug={"demo": uuid.uuid4()}, canonical_exists=True, all_ids=[uuid.uuid4()])
+ # A genuinely unknown, non-placeholder ref must NOT borrow the canonical
+ # tenant — that would cross tenants.
+ assert await _resolve_tenant_id(conn, "acme-corp") is None
diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.py
index 28d0f4ca9..7d5bdda6c 100644
--- a/services/api/app/api/v1/endpoints/cases.py
+++ b/services/api/app/api/v1/endpoints/cases.py
@@ -1113,10 +1113,14 @@ async def case_investigate(
if not exists:
raise HTTPException(status_code=404, detail="Case not found.")
+ # Forward the authenticated tenant so the agents service attributes the run
+ # to the real tenant instead of falling back to the "default" placeholder,
+ # which the demo seed no longer maps to any tenant (issue #601). The ledger
+ # is scoped by tenant_id, so without this the whole run is never persisted.
resp = await _agents_proxy(
"POST",
f"/api/v1/cases/{cid}/investigate",
- json={"alert_summary": body.alert_summary or ""},
+ json={"alert_summary": body.alert_summary or "", "tenant_id": str(user.tenant_id)},
)
if resp.status_code >= 400:
raise HTTPException(status_code=resp.status_code, detail=resp.text)