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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(agents): give copilot conversations and saved hunts a tenant (#1079)
Beenu Arora3c04a21bb3b2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8221c7b26..04d906475 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Security++- **Copilot conversations and saved hunt searches were readable by every tenant.** Both lived in a module-level dict — `_CONVERSATIONS` in `services/agents/app/api/copilot.py` and `_SAVED_SEARCHES` in `hunt_search.py` — with no tenant column anywhere, and the list handlers took no principal at all. `GET /api/v1/copilot/conversations` returned every tenant's conversations to whoever asked, `GET /api/v1/copilot/conversations/{id}` returned any conversation to anyone holding its id, and `GET /api/v1/hunt/saved` did the same for saved searches.++ This is not chat history. A copilot conversation carries the analyst's question, which names hosts and users, and the model's answer, which quotes the alert evidence it was grounded on. A saved hunt search is the query an analyst wrote against their own telemetry.++ **Both routers already authenticated every request** — each declared `dependencies=[Depends(require_console_or_service_auth)]` — and that is the detail worth keeping. Authenticated and scoped are different properties, and the gap between them is where this lived: the principal was verified and then discarded, because no handler took it as a parameter. A module global has no tenant, so the moment a handler writes to one the read can no longer be scoped; the information needed to scope it was never stored. That is why these moved to tables rather than gaining a filter.++ Migration `076` adds `aisoc_copilot_conversations` and `aisoc_saved_hunt_searches`, both with `tenant_id NOT NULL` so a row cannot exist outside a tenant, RLS enabled and forced, and an explicit grant to `aisoc_app` (`ALTER DEFAULT PRIVILEGES` only covers tables created by the role that ran it). Every statement in `conversation_store.py` carries the predicate as well as the policy, because a policy is only as good as the `set_config` that precedes it.++ Three smaller corrections came with it. `GET /conversations/{id}` answered **200** with `{"title": "Not found", "messages": []}`, a shape no client can branch on and one that made a missing id, somebody else's id and a real empty conversation identical; it is a 404 now. The chat handlers did a read-modify-write on the message list, so two tabs on one conversation each dropped the other's turn; both turns now append in a single statement. And the streaming handler persisted the assistant's reply **inside the generator**, so a client disconnecting mid-stream left the user's question stored with no answer and the next request fed the model a conversation ending in an unanswered question — the reply is fully computed before the stream opens, so it is written there instead.++### Security- **Both SSO handlers minted a signed session for an identity nobody authenticated.** `app/auth/saml.py` issued a token for `stub-saml-user` whenever `python3-saml` failed to import, and `python3-saml` was declared in **no install path at all** — so the `ImportError` branch was not a fallback, it was the only reachable path through the assertion consumer on every deployment. `app/auth/oidc.py` did the same for `oidc-stub-user` whenever `OIDC_ISSUER` or `OIDC_CLIENT_ID` was unset, which is the default. Both set `aisoc_token` as a cookie from inside an exception handler that had verified nothing.diff --git a/ROADMAP.md b/ROADMAP.mdindex 5d252d632..a6bbfca62 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **246 rows — 246 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **247 rows — 247 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 12eee1213..73e7afdac 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 246 rows+The last row is the one worth reading first. It is the honest index: 247 rows`GATED`, 0 `PARTIAL`, and a ratchet that refuses to let a row sit at`NO GATE`. Re-read the figure from the table rather than from here — a countcopied into prose goes stale in silence, which is whydiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 4628b871f..881941ced 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -254,10 +254,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Every documented way to start AiSOC produces a production-class posture | `README.md` (quick start); `apps/docs/docs/deployment/single-host.md`; `apps/docs/docs/deployment/walkthrough.mdx` | `ci.yml :: Python — Lint & Type-check` (`check_deployment_auth_posture.py` — resolves `${VAR:-default}` against the env file each documented path uses, for every service in the compose file, with no Docker, and fails on a development-class `ENV`/`ENVIRONMENT`, a truthy `AISOC_DEV_MODE`, `AISOC_DEV_AUTH_BYPASS` outside the overlay, a service that reads the flags without being told its published addresses, or an entry point that exports any of them. 13 self-test cases, three of them controls) + `ci.yml :: Python — Tests` (`tests/test_compose_environment_gate.py`, `tests/test_production_compose_gate.py`) + `make smoke`, which answers 401 to an anonymous write on the API port and through the console proxy | GATED | **Proven against the pre-fix tree**: 28 findings at `03e923f3`, across every service that reads the bypass flags; 0 after. **And verified live on a rebuilt image**, three postures on a real container: `make up` answers 401 with no bypass variable set; `make up-dev` on loopback answers 200 and logs the activation warning naming the demo tenant; `make up-dev` with the console on `0.0.0.0` answers 401 and logs the refusal naming the address. The first probe run graded a cached pre-fix image and was discarded, which is why the claim says rebuilt. One limit stated rather than implied: the gate reads declarations, so it proves the *shipped* default is production-class, not that a particular operator's `.env` is — an operator who writes `ENVIRONMENT=development` and `AISOC_DEV_AUTH_BYPASS=1` by hand has asked for it, and the loopback refusal is what still stands between that and a reachable host || Repeated credential failures are throttled and eventually locked out | `SECURITY.md` (what to review) | `ci.yml :: Python — Tests` (`services/api/tests/test_login_throttle.py`, 18 cases, and `services/api/tests/test_login_route_throttled.py`, 4 that drive the real route — because a gate on the limiter alone passes over a route that never calls it, and that was the defect: three limiters existed in this service and login consulted none of them. Asserted in both directions: a success clears the account counter and not the source counter; password spraying trips the source counter without ever tripping an account counter; an address that does not exist is refused identically to one that does; and Redis being down degrades to per-replica counting rather than locking everyone out) | GATED | **Proven against the pre-fix tree**: the four route cases fail at `4f4ba326` as `assert 429 in [401, 401, 401, ...]`, and the control — the first two attempts still answering 401 — passes on both trees, so the suite cannot be satisfied by a route that refuses everyone. Two limits stated rather than implied. The source counter is evadable where `X-Forwarded-For` is not stripped by a trusted proxy, since an attacker can rotate it for a fresh bucket per request; that is why the account counter is the primary control, and why the source counter is aimed at spraying, where per-request rotation is not something an attacker expects to need. And the fallback is per-replica, so an attacker spread across replicas gets one budget per replica — weaker than shared counting, and recorded as weaker || No SSO path mints an identity that no identity provider authenticated | `apps/docs/docs/operations/security.md` (SSO); `SECURITY.md` | `ci.yml :: Python — Tests` (`services/api/tests/test_sso_mints_no_stub_identity.py`, 8 cases: neither `stub-saml-user` nor `oidc-stub-user` is constructible in any auth module, both handlers answer 501 when unconfigured, no `set_cookie` sits inside an exception handler, and `python3-saml` is declared so the 501 is clearable. The glob is asserted non-empty, because a pattern that matches nothing makes every other case vacuous) | GATED | **Proven against the pre-fix tree**: 6 of 8 fail at `48234dc5`. **And verified by building the image**, not by reading the manifest: `onelogin.saml2` imports inside it, so the `ImportError` branch that minted the stub is unreachable rather than merely deleted. One cost stated rather than hidden: the image grows 1.36 GB to 1.42 GB, which is the three wheels. The first attempt also added four `-dev` packages on the assumption that `xmlsec` compiles from source; it does not, a `manylinux` wheel exists, and removing them kept the import working and saved 110 MB. Measured, not assumed, in both directions. One limit: this proves no *stub* identity can be minted, not that a real SAML assertion is correctly verified — the containerised test IdP that would prove that is parity 4.1 |+| Copilot conversations and saved hunts are visible only to the tenant that created them | `apps/docs/docs/console/copilot.md`; `apps/docs/docs/concepts/multi-tenancy.md` | `ci.yml :: Python — Tests` (`services/agents/tests/test_copilot_and_hunts_are_tenant_scoped.py`, 21 cases: neither module global survives, all seven handlers take a principal **and** resolve a tenant from it, every SQL statement in the store carries the predicate (parsed from the AST, not eyeballed), the RLS context variable is spelled `app.current_tenant_id`, an unavailable store raises rather than returning empty, and the migration creates both tables with `tenant_id NOT NULL`, forced RLS and the `aisoc_app` grant) | GATED | **Proven against the pre-fix tree**: all 21 fail at `e7f4d2b3`. The instructive part is that both routers *already* authenticated every request — the principal was verified and then discarded, because no handler took it as a parameter, so a gate checking only for an auth dependency would have passed this. Hence two cases per handler: binds a principal, and resolves a tenant from it. One limit: these assert the predicate exists, not that Postgres enforces it — the two-tenant replay that proves the policy lives in `tests/isolation/` and runs only where containers are available |## Summary-- GATED: 246+- GATED: 247- PARTIAL: 0- NO GATE: 0 (**every claim is backed by a failing test, and none is now a named deferral either.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The last two PARTIAL rows closed with `scripts/check_live_agent_floor.py` and a floor derived from ten runs across two environments, not by relabelling. Recount with `scripts/check_claim_gate_matrix.py` rather than trusting these three numbers: they move weekly, and a count copied into prose goes stale in silence.)diff --git a/services/agents/app/api/conversation_store.py b/services/agents/app/api/conversation_store.pynew file mode 100644index 000000000..457227bda--- /dev/null+++ b/services/agents/app/api/conversation_store.py@@ -0,0 +1,313 @@+"""Tenant-scoped persistence for copilot conversations and saved hunt searches.++Both used to be module-level dicts — `_CONVERSATIONS` in `copilot.py` and+`_SAVED_SEARCHES` in `hunt_search.py`. A module global has no tenant, so the+read could not be scoped: the information needed to scope it was never+stored. The list handlers bound no principal at all, so one tenant's+conversations were returned to whoever asked.++Follows `app/hunt/store.py` and `app/investigator/ledger.py`: raw asyncpg, a+lazily-created pool, and `app.current_tenant_id` set on every connection.++One deliberate difference from those two. They are best-effort — a database+outage must not take the hunt scheduler offline, so their writes are wrapped+and a failure is logged. These are not. A read that fails must raise, because+the alternative is returning an empty list, and an empty list is+indistinguishable from "this tenant has no conversations". A write that fails+must raise, because the alternative is telling an analyst their search was+saved when it was not.+"""++from __future__ import annotations++import json+import os+import uuid+from dataclasses import dataclass+from datetime import UTC, datetime+from typing import Any++import asyncpg+import structlog++logger = structlog.get_logger()++_POOL: asyncpg.Pool | None = None+++class ConversationStoreUnavailable(RuntimeError):+ """The store cannot answer. Raised rather than returning an empty result.++ Distinguished from "no rows" on purpose: a caller that cannot tell them+ apart renders an empty conversation list over a database outage, and the+ analyst concludes their history is gone.+ """+++def _normalise_dsn(url: str) -> str:+ return url.replace("postgresql+asyncpg://", "postgresql://").replace("postgres+asyncpg://", "postgresql://")+++async def _pool() -> asyncpg.Pool:+ global _POOL+ if _POOL is not None:+ return _POOL+ dsn = os.environ.get("DATABASE_URL", "").strip()+ if not dsn:+ raise ConversationStoreUnavailable(+ "DATABASE_URL is not set, so copilot conversations cannot be stored. They used "+ "to live in a process-local dict shared by every tenant; refusing is the "+ "correct behaviour now."+ )+ _POOL = await asyncpg.create_pool(dsn=_normalise_dsn(dsn), min_size=1, max_size=4, command_timeout=10)+ return _POOL+++async def _scoped(conn: asyncpg.Connection, tenant_id: uuid.UUID) -> None:+ """Bind the connection to one tenant for the enclosing transaction.++ `app.current_tenant_id` is the variable every policy in this schema+ reads. It said `app.tenant_id` in two modules until 2026-09, and the+ scope was silently never applied — the same spelling mistake is the+ reason the query layer filters as well.+ """+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, true)", str(tenant_id))+++@dataclass(frozen=True)+class Conversation:+ id: str+ title: str+ messages: list[dict[str, Any]]+ updated_at: str++ def summary(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "title": self.title,+ "updatedAt": self.updated_at,+ "messageCount": len(self.messages),+ }++ def full(self) -> dict[str, Any]:+ return {"id": self.id, "title": self.title, "messages": self.messages}+++def _row_to_conversation(row: asyncpg.Record) -> Conversation:+ raw = row["messages"]+ return Conversation(+ id=str(row["id"]),+ title=row["title"],+ messages=json.loads(raw) if isinstance(raw, str) else list(raw or []),+ updated_at=row["updated_at"].astimezone(UTC).isoformat(),+ )+++# ── Conversations ───────────────────────────────────────────────────────────+++async def list_conversations(*, tenant_id: uuid.UUID, limit: int = 20) -> list[Conversation]:+ pool = await _pool()+ async with pool.acquire() as conn, conn.transaction():+ await _scoped(conn, tenant_id)+ rows = await conn.fetch(+ """+ SELECT id, title, messages, updated_at+ FROM aisoc_copilot_conversations+ WHERE tenant_id = $1+ ORDER BY updated_at DESC+ LIMIT $2+ """,+ tenant_id,+ max(1, min(limit, 200)),+ )+ return [_row_to_conversation(row) for row in rows]+++async def get_conversation(*, tenant_id: uuid.UUID, conversation_id: str) -> Conversation | None:+ """Return the conversation, or None if this tenant does not have it.++ The `tenant_id` predicate is what makes "does not exist" and "belongs to+ somebody else" the same answer. Before this, an id was enough.+ """+ try:+ parsed = uuid.UUID(conversation_id)+ except ValueError:+ return None+ pool = await _pool()+ async with pool.acquire() as conn, conn.transaction():+ await _scoped(conn, tenant_id)+ row = await conn.fetchrow(+ """+ SELECT id, title, messages, updated_at+ FROM aisoc_copilot_conversations+ WHERE tenant_id = $1 AND id = $2+ """,+ tenant_id,+ parsed,+ )+ return _row_to_conversation(row) if row else None+++async def append_messages(+ *,+ tenant_id: uuid.UUID,+ conversation_id: str | None,+ user_id: uuid.UUID | None,+ title: str,+ new_messages: list[dict[str, Any]],+) -> Conversation:+ """Create or extend a conversation, and return it as stored.++ One statement rather than read-modify-write. Two browser tabs on the same+ conversation would otherwise each read the message list, append locally,+ and write back — and the second write would silently drop the first one's+ turn.+ """+ pool = await _pool()+ payload = json.dumps(new_messages)+ now = datetime.now(UTC)++ async with pool.acquire() as conn, conn.transaction():+ await _scoped(conn, tenant_id)+ parsed: uuid.UUID | None = None+ if conversation_id:+ try:+ parsed = uuid.UUID(conversation_id)+ except ValueError:+ parsed = None++ if parsed is not None:+ row = await conn.fetchrow(+ """+ UPDATE aisoc_copilot_conversations+ SET messages = messages || $3::jsonb,+ updated_at = $4+ WHERE tenant_id = $1 AND id = $2+ RETURNING id, title, messages, updated_at+ """,+ tenant_id,+ parsed,+ payload,+ now,+ )+ if row is not None:+ return _row_to_conversation(row)+ # Falls through to an insert. A caller naming an id that belongs+ # to another tenant gets a new conversation of their own rather+ # than an error that would confirm the id exists.++ row = await conn.fetchrow(+ """+ INSERT INTO aisoc_copilot_conversations+ (tenant_id, user_id, title, messages, updated_at)+ VALUES ($1, $2, $3, $4::jsonb, $5)+ RETURNING id, title, messages, updated_at+ """,+ tenant_id,+ user_id,+ title,+ payload,+ now,+ )+ return _row_to_conversation(row)+++# ── Saved hunt searches ─────────────────────────────────────────────────────+++@dataclass(frozen=True)+class SavedSearch:+ id: str+ name: str+ query: str+ backend: str+ updated_at: str++ def as_dict(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "name": self.name,+ "query": self.query,+ "backend": self.backend,+ "updatedAt": self.updated_at,+ }+++def _row_to_search(row: asyncpg.Record) -> SavedSearch:+ return SavedSearch(+ id=str(row["id"]),+ name=row["name"],+ query=row["query"],+ backend=row["backend"],+ updated_at=row["updated_at"].astimezone(UTC).isoformat(),+ )+++async def list_saved_searches(*, tenant_id: uuid.UUID, limit: int = 50) -> list[SavedSearch]:+ pool = await _pool()+ async with pool.acquire() as conn, conn.transaction():+ await _scoped(conn, tenant_id)+ rows = await conn.fetch(+ """+ SELECT id, name, query, backend, updated_at+ FROM aisoc_saved_hunt_searches+ WHERE tenant_id = $1+ ORDER BY updated_at DESC+ LIMIT $2+ """,+ tenant_id,+ max(1, min(limit, 200)),+ )+ return [_row_to_search(row) for row in rows]+++async def save_search(+ *,+ tenant_id: uuid.UUID,+ user_id: uuid.UUID | None,+ name: str,+ query: str,+ backend: str = "",+) -> SavedSearch:+ pool = await _pool()+ async with pool.acquire() as conn, conn.transaction():+ await _scoped(conn, tenant_id)+ row = await conn.fetchrow(+ """+ INSERT INTO aisoc_saved_hunt_searches+ (tenant_id, user_id, name, query, backend)+ VALUES ($1, $2, $3, $4, $5)+ RETURNING id, name, query, backend, updated_at+ """,+ tenant_id,+ user_id,+ name,+ query,+ backend,+ )+ return _row_to_search(row)+++async def delete_saved_search(*, tenant_id: uuid.UUID, search_id: str) -> bool:+ try:+ parsed = uuid.UUID(search_id)+ except ValueError:+ return False+ pool = await _pool()+ async with pool.acquire() as conn, conn.transaction():+ await _scoped(conn, tenant_id)+ result = await conn.execute(+ "DELETE FROM aisoc_saved_hunt_searches WHERE tenant_id = $1 AND id = $2",+ tenant_id,+ parsed,+ )+ return result.endswith(" 1")+++async def reset_pool_for_tests() -> None:+ """Drop the cached pool. Only the suite calls this."""+ global _POOL+ if _POOL is not None:+ await _POOL.close()+ _POOL = Nonediff --git a/services/agents/app/api/copilot.py b/services/agents/app/api/copilot.pyindex ec325b501..c176a2731 100644--- a/services/agents/app/api/copilot.py+++ b/services/agents/app/api/copilot.py@@ -14,6 +14,7 @@ unset so the demo path never breaks.from __future__ import annotations+import asyncioimport itertoolsimport jsonimport uuid@@ -22,11 +23,17 @@ from datetime import UTC, datetimefrom typing import Any, Literalimport structlog-from fastapi import APIRouter, Depends+from fastapi import APIRouter, Depends, HTTPException, statusfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel, Field-from app.security.tenant_scope import require_console_or_service_auth+from app.api import conversation_store+from app.security.tenant_scope import (+ TenantPrincipal,+ TenantScopeError,+ require_console_or_service_auth,+ resolve_scoped_tenant,+)logger = structlog.get_logger()@@ -77,7 +84,23 @@ class CopilotConversation(BaseModel):# In-memory store (demo: resets on restart; production would use Postgres)# ----------------------------------------------------------------------------_CONVERSATIONS: dict[str, dict[str, Any]] = {}++def _tenant_of(principal: TenantPrincipal) -> uuid.UUID:+ """The one tenant this request may read and write.++ Conversations lived in a module-level dict keyed by conversation id with+ no tenant anywhere, and the list and fetch handlers bound no principal at+ all — so `GET /conversations` returned every tenant's conversations to+ whoever asked, and `GET /conversations/{id}` returned any conversation to+ anyone holding its id. A copilot conversation carries the analyst's+ question, which names hosts and users, and the model's answer, which+ quotes the evidence it was grounded on.+ """+ try:+ return resolve_scoped_tenant(principal)+ except TenantScopeError as exc:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc+_SYNTHETIC_REPLIES = [(@@ -182,51 +205,47 @@ async def _get_openai_reply(@router.get("/conversations")-async def list_conversations(limit: int = 20) -> dict[str, Any]:- convs = sorted(- _CONVERSATIONS.values(),- key=lambda c: c["updatedAt"],- reverse=True,- )[:limit]- return {- "conversations": [- {- "id": c["id"],- "title": c["title"],- "updatedAt": c["updatedAt"],- "messageCount": len(c["messages"]),- }- for c in convs- ]- }+async def list_conversations(+ limit: int = 20,+ principal: TenantPrincipal = Depends(require_console_or_service_auth),+) -> dict[str, Any]:+ """This tenant's conversations, newest first."""+ conversations = await conversation_store.list_conversations(tenant_id=_tenant_of(principal), limit=limit)+ return {"conversations": [c.summary() for c in conversations]}@router.get("/conversations/{conversation_id}")-async def get_conversation(conversation_id: str) -> dict[str, Any]:- conv = _CONVERSATIONS.get(conversation_id)- if conv is None:- return {"id": conversation_id, "title": "Not found", "messages": []}- return {- "id": conv["id"],- "title": conv["title"],- "messages": conv["messages"],- }+async def get_conversation(+ conversation_id: str,+ principal: TenantPrincipal = Depends(require_console_or_service_auth),+) -> dict[str, Any]:+ """One conversation, if it belongs to this tenant.++ 404 rather than the previous `{"title": "Not found", "messages": []}`+ body with a 200. A 200 saying "not found" is a shape no client can+ branch on, and it made "this id does not exist" and "this id is+ somebody else's" look the same as a real empty conversation.+ """+ conversation = await conversation_store.get_conversation(tenant_id=_tenant_of(principal), conversation_id=conversation_id)+ if conversation is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such conversation.")+ return conversation.full()@router.post("/chat", response_model=CopilotChatResponse)-async def chat(req: CopilotChatRequest) -> CopilotChatResponse:- conv_id = req.conversationId or str(uuid.uuid4())+async def chat(+ req: CopilotChatRequest,+ principal: TenantPrincipal = Depends(require_console_or_service_auth),+) -> CopilotChatResponse:+ tenant_id = _tenant_of(principal)now = datetime.now(UTC).isoformat()- if conv_id not in _CONVERSATIONS:- _CONVERSATIONS[conv_id] = {- "id": conv_id,- "title": _title_from_message(req.message),- "messages": [],- "updatedAt": now,- }-- conv = _CONVERSATIONS[conv_id]+ # Read the existing turns under the tenant predicate, so a caller naming+ # another tenant's conversation id gets a new conversation of their own+ # rather than that one's history as model context.+ existing = (+ await conversation_store.get_conversation(tenant_id=tenant_id, conversation_id=req.conversationId) if req.conversationId else None+ )user_msg: dict[str, Any] = {"id": str(uuid.uuid4()),@@ -234,9 +253,9 @@ async def chat(req: CopilotChatRequest) -> CopilotChatResponse:"content": req.message,"timestamp": now,}- conv["messages"].append(user_msg)- reply_text, reply_source = await _get_openai_reply(conv, req.message)+ history = {"messages": [*(existing.messages if existing else []), user_msg]}+ reply_text, reply_source = await _get_openai_reply(history, req.message)assistant_msg: dict[str, Any] = {"id": str(uuid.uuid4()),@@ -244,11 +263,19 @@ async def chat(req: CopilotChatRequest) -> CopilotChatResponse:"content": reply_text,"timestamp": datetime.now(UTC).isoformat(),}- conv["messages"].append(assistant_msg)- conv["updatedAt"] = assistant_msg["timestamp"]++ # Both turns in one append, so two tabs on the same conversation cannot+ # drop each other's messages the way a read-modify-write would.+ stored = await conversation_store.append_messages(+ tenant_id=tenant_id,+ conversation_id=existing.id if existing else None,+ user_id=None,+ title=existing.title if existing else _title_from_message(req.message),+ new_messages=[user_msg, assistant_msg],+ )return CopilotChatResponse(- conversationId=conv_id,+ conversationId=stored.id,reply=CopilotMessage(**assistant_msg),source=reply_source,notice=(@@ -262,31 +289,49 @@ async def chat(req: CopilotChatRequest) -> CopilotChatResponse:@router.post("/chat/stream")-async def chat_stream(req: CopilotChatRequest) -> StreamingResponse:+async def chat_stream(+ req: CopilotChatRequest,+ principal: TenantPrincipal = Depends(require_console_or_service_auth),+) -> StreamingResponse:"""Stream a chat reply as NDJSON deltas."""- conv_id = req.conversationId or str(uuid.uuid4())+ tenant_id = _tenant_of(principal)now = datetime.now(UTC).isoformat()- if conv_id not in _CONVERSATIONS:- _CONVERSATIONS[conv_id] = {- "id": conv_id,- "title": _title_from_message(req.message),- "messages": [],- "updatedAt": now,- }+ existing = (+ await conversation_store.get_conversation(tenant_id=tenant_id, conversation_id=req.conversationId) if req.conversationId else None+ )- conv = _CONVERSATIONS[conv_id]user_msg: dict[str, Any] = {"id": str(uuid.uuid4()),"role": "user","content": req.message,"timestamp": now,}- conv["messages"].append(user_msg)+ history = {"messages": [*(existing.messages if existing else []), user_msg]}- reply_text, reply_source = await _get_openai_reply(conv, req.message)+ reply_text, reply_source = await _get_openai_reply(history, req.message)msg_id = str(uuid.uuid4())+ assistant_msg: dict[str, Any] = {+ "id": msg_id,+ "role": "assistant",+ "content": reply_text,+ "timestamp": datetime.now(UTC).isoformat(),+ }++ # Persisted before the stream opens, not inside the generator. A client+ # that disconnects mid-stream used to leave the assistant turn unwritten+ # while the user's question had already been appended, so the next+ # request fed the model a conversation ending in an unanswered question.+ # The reply is fully computed by this point, so there is nothing to wait+ # for.+ stored = await conversation_store.append_messages(+ tenant_id=tenant_id,+ conversation_id=existing.id if existing else None,+ user_id=None,+ title=existing.title if existing else _title_from_message(req.message),+ new_messages=[user_msg, assistant_msg],+ )async def _stream() -> AsyncIterator[bytes]:# Provenance first: a consumer must be able to label the answer before@@ -296,25 +341,13 @@ async def chat_stream(req: CopilotChatRequest) -> StreamingResponse:for i, word in enumerate(words):chunk = word + (" " if i < len(words) - 1 else "")yield (json.dumps({"delta": chunk, "done": False}) + "\n").encode()- # tiny delay to simulate streaming- import asyncio-await asyncio.sleep(0.01)- assistant_msg: dict[str, Any] = {- "id": msg_id,- "role": "assistant",- "content": reply_text,- "timestamp": datetime.now(UTC).isoformat(),- }- conv["messages"].append(assistant_msg)- conv["updatedAt"] = assistant_msg["timestamp"]-yield (json.dumps({"done": True,- "conversationId": conv_id,+ "conversationId": stored.id,"messageId": msg_id,})diff --git a/services/agents/app/api/hunt_search.py b/services/agents/app/api/hunt_search.pyindex db3c961f0..bdc4d1cb5 100644--- a/services/agents/app/api/hunt_search.py+++ b/services/agents/app/api/hunt_search.py@@ -23,7 +23,13 @@ import structlogfrom fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import BaseModel-from app.security.tenant_scope import require_console_or_service_auth+from app.api import conversation_store+from app.security.tenant_scope import (+ TenantPrincipal,+ TenantScopeError,+ require_console_or_service_auth,+ resolve_scoped_tenant,+)logger = structlog.get_logger()@@ -91,10 +97,21 @@ class SavedSearch(BaseModel):# ----------------------------------------------------------------------------# In-memory store (demo; production would persist to Postgres)+# Tenant-scoped persistence# ---------------------------------------------------------------------------+#+# This was a module-level dict with no tenant, listed by a handler that bound+# no principal, so one analyst's saved searches were returned to every other+# tenant and a restart lost all of them. A saved hunt search is the query an+# analyst wrote against their own telemetry, which names their hosts, their+# users and what they were looking for.-_SAVED_SEARCHES: dict[str, SavedSearch] = {}++def _tenant_of(principal: TenantPrincipal) -> uuid.UUID:+ try:+ return resolve_scoped_tenant(principal)+ except TenantScopeError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from excdef _synthetic_hits(query: str, limit: int) -> list[dict[str, Any]]:@@ -180,28 +197,60 @@ async def hunt_search(query: HuntQuery) -> HuntResponse:@router.get("/saved")-async def list_saved_searches() -> dict[str, list[dict[str, Any]]]:- """Return all saved searches."""- return {"searches": [s.model_dump() for s in _SAVED_SEARCHES.values()]}+async def list_saved_searches(+ principal: TenantPrincipal = Depends(require_console_or_service_auth),+) -> dict[str, list[dict[str, Any]]]:+ """This tenant's saved searches, newest first."""+ rows = await conversation_store.list_saved_searches(tenant_id=_tenant_of(principal))+ return {+ "searches": [+ {+ "id": row.id,+ "name": row.name,+ "query": row.query,+ "language": row.backend,+ "createdAt": row.updated_at,+ "pinned": False,+ }+ for row in rows+ ]+ }@router.post("/saved", response_model=SavedSearch, status_code=201)-async def save_search(data: SavedSearchCreate) -> SavedSearch:- """Persist a new saved search."""- ss = SavedSearch(- id=str(uuid.uuid4()),+async def save_search(+ data: SavedSearchCreate,+ principal: TenantPrincipal = Depends(require_console_or_service_auth),+) -> SavedSearch:+ """Persist a new saved search against the caller's tenant."""+ row = await conversation_store.save_search(+ tenant_id=_tenant_of(principal),+ user_id=None,name=data.name,query=data.query,- language=data.language,- createdAt=datetime.now(UTC).isoformat(),+ backend=data.language,+ )+ return SavedSearch(+ id=row.id,+ name=row.name,+ query=row.query,+ language=row.backend,+ createdAt=row.updated_at,)- _SAVED_SEARCHES[ss.id] = ss- return ss@router.delete("/saved/{search_id}", status_code=204, response_model=None)-async def delete_saved_search(search_id: str) -> None:- """Delete a saved search by ID."""- if search_id not in _SAVED_SEARCHES:+async def delete_saved_search(+ search_id: str,+ principal: TenantPrincipal = Depends(require_console_or_service_auth),+) -> None:+ """Delete one of this tenant's saved searches.++ The delete carries the tenant predicate, so an id belonging to another+ tenant removes nothing and answers 404 — the same answer as an id that+ does not exist, which is what stops the route being a probe for whether+ one does.+ """+ deleted = await conversation_store.delete_saved_search(tenant_id=_tenant_of(principal), search_id=search_id)+ if not deleted:raise HTTPException(status_code=404, detail="saved search not found")- del _SAVED_SEARCHES[search_id]diff --git a/services/agents/tests/test_copilot_and_hunts_are_tenant_scoped.py b/services/agents/tests/test_copilot_and_hunts_are_tenant_scoped.pynew file mode 100644index 000000000..9b24e2709--- /dev/null+++ b/services/agents/tests/test_copilot_and_hunts_are_tenant_scoped.py@@ -0,0 +1,172 @@+"""Copilot conversations and saved hunt searches belong to one tenant.++Both lived in a module-level dict — `_CONVERSATIONS` and `_SAVED_SEARCHES` —+with no tenant column anywhere, and the list handlers took no principal at+all. So `GET /copilot/conversations` returned every tenant's conversations+to whoever asked, `GET /copilot/conversations/{id}` returned any+conversation to anyone holding its id, and `GET /hunt/saved` did the same+for saved searches.++This is not chat history. A copilot conversation carries the analyst's+question, which names hosts and users, and the model's answer, which quotes+the alert evidence it was grounded on. A saved hunt search is the query an+analyst wrote against their own telemetry.++The durable point is that **a module global has no tenant**, so the moment a+handler writes to one the read can no longer be scoped: the information+needed to scope it was never stored. That is why these moved to tables+rather than gaining a filter.++Checked without a database, by reading the handlers' signatures and the+store's SQL. A live two-tenant replay belongs in `tests/isolation/`, which+runs against containers; these cases must hold in the unit suite so a+regression is caught on every pull request rather than only where containers+are available.+"""++from __future__ import annotations++import ast+import inspect+import pathlib++import pytest++SERVICE_ROOT = pathlib.Path(__file__).resolve().parents[1]++#: Every handler that reads or writes one of the two stores.+SCOPED_HANDLERS = (+ ("copilot", "list_conversations"),+ ("copilot", "get_conversation"),+ ("copilot", "chat"),+ ("copilot", "chat_stream"),+ ("hunt_search", "list_saved_searches"),+ ("hunt_search", "save_search"),+ ("hunt_search", "delete_saved_search"),+)+++def _module(name: str):+ import importlib++ return importlib.import_module(f"app.api.{name}")+++class TestTheDictsAreGone:+ @pytest.mark.parametrize(+ ("module", "name"),+ [("copilot", "_CONVERSATIONS"), ("hunt_search", "_SAVED_SEARCHES")],+ )+ def test_no_module_global_holds_the_data(self, module: str, name: str) -> None:+ source = (SERVICE_ROOT / "app" / "api" / f"{module}.py").read_text(encoding="utf-8")+ code = "\n".join(line for line in source.splitlines() if not line.lstrip().startswith("#"))+ assert name not in code, (+ f"{name} is back in {module}.py. It is one object for the whole process with no tenant, so the read cannot be scoped"+ )+++class TestEveryHandlerResolvesATenant:+ @pytest.mark.parametrize(("module", "handler"), SCOPED_HANDLERS)+ def test_the_handler_binds_a_principal(self, module: str, handler: str) -> None:+ """Binding it at router level is not enough.++ Both routers already declared `dependencies=[Depends(...)]`, so every+ request *was* authenticated — and the handlers still could not scope,+ because none of them received the principal. Authenticated and+ scoped are different properties, and the gap between them is where+ this defect lived.+ """+ fn = getattr(_module(module), handler)+ params = inspect.signature(fn).parameters+ assert "principal" in params, (+ f"{module}.{handler} takes no principal, so it cannot name a tenant even though the router authenticates the request"+ )++ @pytest.mark.parametrize(("module", "handler"), SCOPED_HANDLERS)+ def test_the_handler_resolves_the_tenant_before_touching_the_store(self, module: str, handler: str) -> None:+ source = inspect.getsource(getattr(_module(module), handler))+ assert "_tenant_of(principal)" in source, f"{module}.{handler} never resolves a tenant from its principal"+++class TestEveryStatementCarriesThePredicate:+ """The store's SQL, parsed rather than eyeballed.++ `resolve_scoped_tenant` returning the right id means nothing if a+ statement then forgets to use it, and that is the half a signature check+ cannot see.+ """++ def test_every_statement_filters_on_tenant_id(self) -> None:+ source = (SERVICE_ROOT / "app" / "api" / "conversation_store.py").read_text(encoding="utf-8")+ tree = ast.parse(source)+ statements: list[str] = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Constant) or not isinstance(node.value, str):+ continue+ text = " ".join(node.value.split())+ upper = text.upper()+ # The verb must be followed by whitespace. Matching a bare prefix+ # caught the dict keys `updatedAt` and `updated_at`, which+ # uppercase to something starting with UPDATE — four string+ # literals reported as unscoped SQL.+ if any(upper.startswith(verb + " ") for verb in ("SELECT", "INSERT", "UPDATE", "DELETE")):+ statements.append(text)++ assert len(statements) >= 6, f"expected the store's statements, found {len(statements)}"++ offenders = [+ s+ for s in statements+ if "tenant_id" not in s+ # An INSERT names the column in its column list instead of a+ # WHERE clause, which is the same property expressed differently.+ ]+ assert not offenders, f"statements with no tenant predicate: {offenders}"++ def test_the_rls_context_variable_is_spelled_correctly(self) -> None:+ """`app.current_tenant_id`, not `app.tenant_id`.++ Two modules in this tree used the wrong name until 2026-09 and the+ scope was silently never applied — every policy reads the first+ spelling, so the second sets a variable nothing consults and the+ query runs unscoped while looking correct.+ """+ source = (SERVICE_ROOT / "app" / "api" / "conversation_store.py").read_text(encoding="utf-8")+ assert "app.current_tenant_id" in source+ assert "'app.tenant_id'" not in source++ def test_an_unavailable_store_raises_rather_than_returning_empty(self) -> None:+ """Because an empty list is a claim about the tenant's data.++ The sibling stores in this service are deliberately best-effort — a+ database outage must not take the hunt scheduler offline. These are+ not, and the difference is that a scheduler losing a write retries,+ while an analyst shown an empty conversation list concludes their+ history is gone.+ """+ from app.api.conversation_store import ConversationStoreUnavailable++ assert issubclass(ConversationStoreUnavailable, RuntimeError)+ source = (SERVICE_ROOT / "app" / "api" / "conversation_store.py").read_text(encoding="utf-8")+ assert "raise ConversationStoreUnavailable" in source+++class TestTheMigrationCreatesWhatTheStoreReads:+ def test_both_tables_exist_with_a_not_null_tenant(self) -> None:+ migration = (SERVICE_ROOT.parents[0] / "api" / "migrations" / "076_copilot_and_hunt_search_tenancy.sql").read_text(encoding="utf-8")+ for table in ("aisoc_copilot_conversations", "aisoc_saved_hunt_searches"):+ assert f"CREATE TABLE IF NOT EXISTS {table}" in migration+ assert "tenant_id UUID NOT NULL" in migration, (+ f"{table} must make a row outside a tenant impossible, which is the property the dict could not have"+ )+ assert f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY" in migration+ assert f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY" in migration++ def test_the_dml_role_is_granted(self) -> None:+ """Or every write fails as a permission error on a real deployment.++ `ALTER DEFAULT PRIVILEGES` only covers tables created by the role+ that ran it, and the services connect as the DML-only `aisoc_app`.+ """+ migration = (SERVICE_ROOT.parents[0] / "api" / "migrations" / "076_copilot_and_hunt_search_tenancy.sql").read_text(encoding="utf-8")+ assert "TO aisoc_app" in migrationdiff --git a/services/api/migrations/076_copilot_and_hunt_search_tenancy.sql b/services/api/migrations/076_copilot_and_hunt_search_tenancy.sqlnew file mode 100644index 000000000..2cf16105f--- /dev/null+++ b/services/api/migrations/076_copilot_and_hunt_search_tenancy.sql@@ -0,0 +1,88 @@+-- Copilot conversations and saved hunt searches become tenant-scoped rows.+--+-- Both lived in a module-level dict: `_CONVERSATIONS` in+-- `services/agents/app/api/copilot.py` and `_SAVED_SEARCHES` in+-- `services/agents/app/api/hunt_search.py`. Neither carried a tenant, and+-- the list handlers bound no principal at all, so `GET /copilot/conversations`+-- returned every tenant's conversations to whoever asked and+-- `GET /copilot/conversations/{id}` returned any conversation by id.+--+-- A copilot conversation is not chat history. It contains the analyst's+-- question, which names hosts and users, and the model's answer, which+-- quotes the alert evidence it was grounded on. A saved hunt search is the+-- query body an analyst wrote against their own telemetry.+--+-- These are not caching bugs with a privacy side effect. A module global has+-- no tenant, so the moment a handler writes to one the read can no longer be+-- scoped — the information needed to scope it was never stored.+--+-- Both tables carry `tenant_id NOT NULL` so a row cannot exist outside a+-- tenant, which is the property the dict could not have.++BEGIN;++CREATE TABLE IF NOT EXISTS aisoc_copilot_conversations (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ -- The author. Nullable because the agents service reaches some callers+ -- through a service principal that has a tenant but no user, and a+ -- conversation owned by the tenant is still correctly scoped.+ user_id UUID REFERENCES users(id) ON DELETE SET NULL,+ title TEXT NOT NULL DEFAULT '',+ messages JSONB NOT NULL DEFAULT '[]'::jsonb,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- The list query is "this tenant's conversations, newest first", so the+-- index carries the sort column rather than leaving it to a sort node.+CREATE INDEX IF NOT EXISTS idx_copilot_conversations_tenant_updated+ ON aisoc_copilot_conversations (tenant_id, updated_at DESC);++CREATE TABLE IF NOT EXISTS aisoc_saved_hunt_searches (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ user_id UUID REFERENCES users(id) ON DELETE SET NULL,+ name TEXT NOT NULL,+ query TEXT NOT NULL,+ backend TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_saved_hunt_searches_tenant_updated+ ON aisoc_saved_hunt_searches (tenant_id, updated_at DESC);++-- RLS as defence in depth. The query layer filters by `tenant_id` as well,+-- because the services connect as `aisoc_app` and a policy is only as good+-- as the `set_config` that precedes it — a connection that forgets the+-- context would otherwise read nothing, which is safe, or everything, which+-- is not, depending on the policy's null handling.+ALTER TABLE aisoc_copilot_conversations ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_copilot_conversations FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_copilot_conversations_tenant ON aisoc_copilot_conversations;+CREATE POLICY aisoc_copilot_conversations_tenant ON aisoc_copilot_conversations+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++ALTER TABLE aisoc_saved_hunt_searches ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_saved_hunt_searches FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS aisoc_saved_hunt_searches_tenant ON aisoc_saved_hunt_searches;+CREATE POLICY aisoc_saved_hunt_searches_tenant ON aisoc_saved_hunt_searches+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++-- `ALTER DEFAULT PRIVILEGES` from 061 only covers tables created by the role+-- that ran it, so a new table needs its grant stated. Without this the+-- DML-only `aisoc_app` role gets a permission error that+-- `CREATE TABLE IF NOT EXISTS` callers have historically swallowed into a+-- debug log.+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ GRANT SELECT, INSERT, UPDATE, DELETE+ ON aisoc_copilot_conversations, aisoc_saved_hunt_searches+ TO aisoc_app;+ END IF;+END+$$;++COMMIT;