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): scope /hunts queries by tenant_id (C-2) (#117)

Beenu Arora6377aba82e3c
diff --git a/services/api/app/api/v1/endpoints/hunts.py b/services/api/app/api/v1/endpoints/hunts.py
index ee5916bb6..b18cc4390 100644
--- a/services/api/app/api/v1/endpoints/hunts.py
+++ b/services/api/app/api/v1/endpoints/hunts.py
@@ -12,6 +12,14 @@ Endpoints
* ``POST /hunts/{id}/run`` Execute a hunt query (ES|QL live; SPL/KQL templated).
* ``GET /hunts/{id}/runs`` List run history for a hunt.
* ``POST /hunts/{id}/findings`` Append finding entries to a hunt.
+
+Tenant isolation
+----------------
+Every query is scoped to ``user.tenant_id``. Rows whose ``tenant_id`` is NULL
+remain visible only to the tenant that created them once they are owned.
+Legacy rows created before migration 043 with ``tenant_id IS NULL`` are
+silently treated as orphans — they are *not* returned to anyone, ensuring no
+cross-tenant data leakage during the rollout window.
"""
from __future__ import annotations
@@ -204,8 +212,12 @@ async def list_hunts(
limit: int = Query(50, ge=1, le=500),
offset: int = Query(0, ge=0),
) -> list[HuntResponse]:
- wheres = ["1=1"]
- params: dict[str, Any] = {"limit": limit, "offset": offset}
+ wheres = ["tenant_id = :tenant_id"]
+ params: dict[str, Any] = {
+ "tenant_id": user.tenant_id,
+ "limit": limit,
+ "offset": offset,
+ }
if hunt_status:
wheres.append("status = :status")
params["status"] = hunt_status
@@ -231,16 +243,17 @@ async def create_hunt(body: CreateHuntRequest, db: DBSession, user: AuthUser) ->
now = datetime.now(UTC)
q = text("""
INSERT INTO aisoc_hunts (
- id, title, hypothesis, mitre_tactic, mitre_technique,
+ id, tenant_id, title, hypothesis, mitre_tactic, mitre_technique,
priority, assigned_to, tags, query_esql, query_spl, query_kql,
created_at, updated_at, created_by
) VALUES (
- :id, :title, :hypothesis, :tactic, :technique,
- :priority, :assigned, :tags::text[], :esql, :spl, :kql,
+ :id, :tenant_id, :title, :hypothesis, :tactic, :technique,
+ :priority, :assigned, CAST(:tags AS TEXT[]), :esql, :spl, :kql,
:now, :now, :user
) RETURNING *
""").bindparams(
id=hunt_id,
+ tenant_id=user.tenant_id,
title=body.title,
hypothesis=body.hypothesis,
tactic=body.mitre_tactic,
@@ -252,7 +265,7 @@ async def create_hunt(body: CreateHuntRequest, db: DBSession, user: AuthUser) ->
spl=queries.get("spl"),
kql=queries.get("kql"),
now=now,
- user=str(user) if user else "system",
+ user=user.email or "system",
)
try:
row = (await db.execute(q)).fetchone()
@@ -265,7 +278,11 @@ async def create_hunt(body: CreateHuntRequest, db: DBSession, user: AuthUser) ->
@router.get("/{hunt_id}", response_model=HuntResponse, summary="Get hunt")
async def get_hunt(hunt_id: uuid.UUID, db: DBSession, user: AuthUser) -> HuntResponse:
- row = (await db.execute(text("SELECT * FROM aisoc_hunts WHERE id = :id").bindparams(id=hunt_id))).fetchone()
+ row = (
+ await db.execute(
+ text("SELECT * FROM aisoc_hunts WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=hunt_id, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Hunt not found.")
return _row_to_hunt(row)
@@ -274,7 +291,11 @@ async def get_hunt(hunt_id: uuid.UUID, db: DBSession, user: AuthUser) -> HuntRes
@router.patch("/{hunt_id}", response_model=HuntResponse, summary="Update hunt")
async def update_hunt(hunt_id: uuid.UUID, body: UpdateHuntRequest, db: DBSession, user: AuthUser) -> HuntResponse:
sets = ["updated_at = :now"]
- params: dict[str, Any] = {"id": hunt_id, "now": datetime.now(UTC)}
+ params: dict[str, Any] = {
+ "id": hunt_id,
+ "tenant_id": user.tenant_id,
+ "now": datetime.now(UTC),
+ }
if body.title is not None:
sets.append("title = :title")
@@ -309,10 +330,10 @@ async def update_hunt(hunt_id: uuid.UUID, body: UpdateHuntRequest, db: DBSession
sets.append("query_kql = :kql")
params["kql"] = body.query_kql
if body.tags is not None:
- sets.append("tags = :tags::text[]")
+ sets.append("tags = CAST(:tags AS TEXT[])")
params["tags"] = body.tags
- q = text(f"UPDATE aisoc_hunts SET {', '.join(sets)} WHERE id = :id RETURNING *").bindparams(**params)
+ q = text(f"UPDATE aisoc_hunts SET {', '.join(sets)} WHERE id = :id AND tenant_id = :tenant_id RETURNING *").bindparams(**params)
try:
row = (await db.execute(q)).fetchone()
if not row:
@@ -328,7 +349,11 @@ async def update_hunt(hunt_id: uuid.UUID, body: UpdateHuntRequest, db: DBSession
@router.post("/{hunt_id}/run", response_model=HuntRunResponse, status_code=status.HTTP_200_OK, summary="Execute hunt query")
async def run_hunt(hunt_id: uuid.UUID, body: RunHuntRequest, db: DBSession, user: AuthUser) -> HuntRunResponse:
- hunt_row = (await db.execute(text("SELECT * FROM aisoc_hunts WHERE id = :id").bindparams(id=hunt_id))).fetchone()
+ hunt_row = (
+ await db.execute(
+ text("SELECT * FROM aisoc_hunts WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=hunt_id, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if not hunt_row:
raise HTTPException(status_code=404, detail="Hunt not found.")
@@ -370,10 +395,17 @@ async def run_hunt(hunt_id: uuid.UUID, body: RunHuntRequest, db: DBSession, user
duration_ms = int((datetime.now(UTC) - start).total_seconds() * 1000)
run_id = uuid.uuid4()
q = text("""
- INSERT INTO aisoc_hunt_runs (id, hunt_id, platform, query_used, hit_count, result_sample, duration_ms, error)
- VALUES (:id, :hunt_id, :platform, :query, :hits, :sample::jsonb, :dur, :err) RETURNING *
+ INSERT INTO aisoc_hunt_runs (
+ id, tenant_id, hunt_id, platform, query_used, hit_count,
+ result_sample, duration_ms, error
+ )
+ VALUES (
+ :id, :tenant_id, :hunt_id, :platform, :query, :hits,
+ CAST(:sample AS JSONB), :dur, :err
+ ) RETURNING *
""").bindparams(
id=run_id,
+ tenant_id=user.tenant_id,
hunt_id=hunt_id,
platform=body.platform,
query=query,
@@ -403,8 +435,22 @@ async def run_hunt(hunt_id: uuid.UUID, body: RunHuntRequest, db: DBSession, user
@router.get("/{hunt_id}/runs", response_model=list[HuntRunResponse], summary="List hunt runs")
async def list_runs(hunt_id: uuid.UUID, db: DBSession, user: AuthUser) -> list[HuntRunResponse]:
+ # Authorize: ensure the parent hunt belongs to the caller's tenant before
+ # listing runs (covers historical runs whose own tenant_id might be NULL).
+ parent = (
+ await db.execute(
+ text("SELECT 1 FROM aisoc_hunts WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=hunt_id, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
+ if not parent:
+ raise HTTPException(status_code=404, detail="Hunt not found.")
+
rows = (
- await db.execute(text("SELECT * FROM aisoc_hunt_runs WHERE hunt_id = :id ORDER BY run_at DESC LIMIT 100").bindparams(id=hunt_id))
+ await db.execute(
+ text("SELECT * FROM aisoc_hunt_runs WHERE hunt_id = :id AND tenant_id = :tenant_id ORDER BY run_at DESC LIMIT 100").bindparams(
+ id=hunt_id, tenant_id=user.tenant_id
+ )
+ )
).fetchall()
return [
HuntRunResponse(
@@ -424,13 +470,20 @@ async def list_runs(hunt_id: uuid.UUID, db: DBSession, user: AuthUser) -> list[H
@router.post("/{hunt_id}/findings", response_model=HuntResponse, summary="Append findings")
async def add_findings(hunt_id: uuid.UUID, body: AddFindingsRequest, db: DBSession, user: AuthUser) -> HuntResponse:
- existing = (await db.execute(text("SELECT findings FROM aisoc_hunts WHERE id = :id").bindparams(id=hunt_id))).fetchone()
+ existing = (
+ await db.execute(
+ text("SELECT findings FROM aisoc_hunts WHERE id = :id AND tenant_id = :tenant_id").bindparams(
+ id=hunt_id, tenant_id=user.tenant_id
+ )
+ )
+ ).fetchone()
if not existing:
raise HTTPException(status_code=404, detail="Hunt not found.")
merged = list(existing.findings or []) + body.findings
params: dict[str, Any] = {
"id": hunt_id,
+ "tenant_id": user.tenant_id,
"findings": json.dumps(merged),
"now": datetime.now(UTC),
}
@@ -439,13 +492,18 @@ async def add_findings(hunt_id: uuid.UUID, body: AddFindingsRequest, db: DBSessi
extra_set = ", false_positive_rate = :fpr"
params["fpr"] = body.false_positive_rate
- q = text(f"UPDATE aisoc_hunts SET findings = :findings::jsonb, updated_at = :now{extra_set} WHERE id = :id RETURNING *").bindparams(
- **params
- )
+ q = text(
+ f"UPDATE aisoc_hunts SET findings = CAST(:findings AS JSONB), updated_at = :now{extra_set} "
+ "WHERE id = :id AND tenant_id = :tenant_id RETURNING *"
+ ).bindparams(**params)
try:
row = (await db.execute(q)).fetchone()
+ if not row:
+ raise HTTPException(status_code=404, detail="Hunt not found.")
await db.commit()
return _row_to_hunt(row)
+ except HTTPException:
+ raise
except Exception as exc:
await db.rollback()
raise HTTPException(status_code=503, detail=f"Database error: {exc}") from exc
diff --git a/services/api/migrations/043_hunts_tenant_isolation.sql b/services/api/migrations/043_hunts_tenant_isolation.sql
new file mode 100644
index 000000000..5363ff783
--- /dev/null
+++ b/services/api/migrations/043_hunts_tenant_isolation.sql
@@ -0,0 +1,34 @@
+-- Migration 043: Tenant isolation for aisoc_hunts / aisoc_hunt_runs (C-2)
+--
+-- The legacy aisoc_hunts table (created in migration 014) had a `tenant_id`
+-- column but the /hunts API never scoped queries by it, so any authenticated
+-- caller could read and mutate any tenant's hunt hypotheses, runs, and
+-- findings. The companion aisoc_hunt_runs table didn't even have a tenant_id
+-- column. This migration:
+-- 1. Adds tenant_id to aisoc_hunt_runs and backfills it from aisoc_hunts.
+-- 2. Adds covering indexes so /hunts can filter by (tenant_id, …) efficiently.
+--
+-- The API layer (services/api/app/api/v1/endpoints/hunts.py) is updated in the
+-- same change to add `WHERE tenant_id = :tenant_id` to every query.
+
+-- ------------------------------------------------------------------
+-- 1. aisoc_hunt_runs.tenant_id
+-- ------------------------------------------------------------------
+ALTER TABLE aisoc_hunt_runs
+ ADD COLUMN IF NOT EXISTS tenant_id UUID;
+
+-- Backfill from the parent hunt row.
+UPDATE aisoc_hunt_runs r
+ SET tenant_id = h.tenant_id
+ FROM aisoc_hunts h
+ WHERE r.hunt_id = h.id
+ AND r.tenant_id IS NULL;
+
+-- ------------------------------------------------------------------
+-- 2. Indexes
+-- ------------------------------------------------------------------
+CREATE INDEX IF NOT EXISTS idx_aisoc_hunts_tenant_created
+ ON aisoc_hunts (tenant_id, created_at DESC);
+
+CREATE INDEX IF NOT EXISTS idx_aisoc_hunt_runs_tenant_hunt
+ ON aisoc_hunt_runs (tenant_id, hunt_id, run_at DESC);
diff --git a/services/api/tests/test_hunts_tenant_isolation.py b/services/api/tests/test_hunts_tenant_isolation.py
new file mode 100644
index 000000000..06e8d66d2
--- /dev/null
+++ b/services/api/tests/test_hunts_tenant_isolation.py
@@ -0,0 +1,267 @@
+"""Tenant-isolation tests for the /hunts API (regression: C-2).
+
+These tests don't boot the FastAPI app — they call the endpoint functions
+directly with a mocked :class:`DBSession` and assert that **every** SQL
+statement executed contains ``tenant_id = :tenant_id`` in its WHERE clause and
+that the bound parameter set carries the calling user's tenant id.
+
+The contract being protected: under no circumstances should an authenticated
+caller be able to read or mutate a hunt belonging to a different tenant.
+"""
+
+from __future__ import annotations
+
+import re
+import uuid
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.api.v1.deps import CurrentUser
+from app.api.v1.endpoints import hunts as hunts_module
+from app.api.v1.endpoints.hunts import (
+ AddFindingsRequest,
+ CreateHuntRequest,
+ RunHuntRequest,
+ UpdateHuntRequest,
+ add_findings,
+ create_hunt,
+ get_hunt,
+ list_hunts,
+ list_runs,
+ run_hunt,
+ update_hunt,
+)
+from fastapi import HTTPException
+
+
+def _user(tenant_id: uuid.UUID | None = None) -> CurrentUser:
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=tenant_id or uuid.uuid4(),
+ role="analyst",
+ )
+
+
+def _row(**overrides: Any) -> MagicMock:
+ row = MagicMock()
+ row.id = overrides.get("id", uuid.uuid4())
+ row.hunt_id = overrides.get("hunt_id", uuid.uuid4())
+ row.title = overrides.get("title", "Hunt")
+ row.hypothesis = overrides.get("hypothesis", "Beacons every 60s.")
+ row.mitre_tactic = overrides.get("mitre_tactic")
+ row.mitre_technique = overrides.get("mitre_technique")
+ row.status = overrides.get("status", "draft")
+ row.priority = overrides.get("priority", "medium")
+ row.query_esql = overrides.get("query_esql")
+ row.query_spl = overrides.get("query_spl")
+ row.query_kql = overrides.get("query_kql")
+ row.findings = overrides.get("findings", [])
+ row.false_positive_rate = overrides.get("false_positive_rate")
+ row.assigned_to = overrides.get("assigned_to")
+ row.tags = overrides.get("tags", [])
+ from datetime import UTC, datetime
+
+ now = datetime.now(UTC)
+ row.created_at = overrides.get("created_at", now)
+ row.updated_at = overrides.get("updated_at", now)
+ row.completed_at = overrides.get("completed_at")
+ row.created_by = overrides.get("created_by", "[email protected]")
+ row.run_at = overrides.get("run_at", now)
+ row.platform = overrides.get("platform", "esql")
+ row.query_used = overrides.get("query_used")
+ row.hit_count = overrides.get("hit_count", 0)
+ row.result_sample = overrides.get("result_sample", [])
+ row.duration_ms = overrides.get("duration_ms")
+ row.error = overrides.get("error")
+ return row
+
+
+def _mk_db(rows: list[Any]) -> MagicMock:
+ """Create a mock DBSession that returns the queued rows one execute() at a time."""
+ db = MagicMock()
+ db.executed: list[tuple[str, dict[str, Any]]] = []
+ iterator = iter(rows)
+
+ async def _execute(clause: Any, *args: Any, **kwargs: Any) -> MagicMock:
+ # Capture the SQL string and bound params for assertion.
+ sql = str(clause)
+ params = dict(clause.compile().params) if hasattr(clause, "compile") else {}
+ db.executed.append((sql, params))
+ try:
+ payload = next(iterator)
+ except StopIteration:
+ payload = None
+ result = MagicMock()
+ if isinstance(payload, list):
+ result.fetchall = MagicMock(return_value=payload)
+ result.fetchone = MagicMock(return_value=payload[0] if payload else None)
+ else:
+ result.fetchone = MagicMock(return_value=payload)
+ result.fetchall = MagicMock(return_value=[payload] if payload else [])
+ return result
+
+ db.execute = AsyncMock(side_effect=_execute)
+ db.commit = AsyncMock()
+ db.rollback = AsyncMock()
+ return db
+
+
+def _assert_tenant_scoped(executed: list[tuple[str, dict[str, Any]]], tenant_id: uuid.UUID) -> None:
+ """Every executed statement must filter by tenant_id and bind it."""
+ assert executed, "expected at least one DB call"
+ for sql, params in executed:
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ # Statements touching aisoc_hunts/aisoc_hunt_runs must scope on tenant_id.
+ if "aisoc_hunts" in normalized or "aisoc_hunt_runs" in normalized:
+ assert "tenant_id" in normalized, f"tenant_id missing from SQL: {sql}"
+ assert "tenant_id" in params, f"tenant_id not bound for SQL: {sql}"
+ assert params["tenant_id"] == tenant_id, f"wrong tenant bound: {params['tenant_id']} != {tenant_id}"
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# list_hunts
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_list_hunts_scopes_by_tenant() -> None:
+ user = _user()
+ db = _mk_db([[_row(title="A"), _row(title="B")]])
+ result = await list_hunts(db=db, user=user)
+ assert len(result) == 2
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_list_hunts_with_filters_keeps_tenant_scope() -> None:
+ user = _user()
+ db = _mk_db([[]])
+ await list_hunts(db=db, user=user, hunt_status="active", priority="high")
+ sql, params = db.executed[0]
+ assert "tenant_id = :tenant_id" in sql.replace("\n", " ")
+ assert params["tenant_id"] == user.tenant_id
+ assert params["status"] == "active"
+ assert params["priority"] == "high"
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# get / update / findings — must 404 cross-tenant
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_get_hunt_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await get_hunt(hunt_id=uuid.uuid4(), db=db, user=user)
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_update_hunt_cross_tenant_returns_404() -> None:
+ user = _user()
+ # RETURNING * yields nothing → endpoint must 404 rather than silently succeed.
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await update_hunt(
+ hunt_id=uuid.uuid4(),
+ body=UpdateHuntRequest(title="rename"),
+ db=db,
+ user=user,
+ )
+ assert exc.value.status_code == 404
+ sql, params = db.executed[0]
+ assert "tenant_id = :tenant_id" in sql.replace("\n", " ")
+ assert params["tenant_id"] == user.tenant_id
+
+
+async def test_add_findings_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await add_findings(
+ hunt_id=uuid.uuid4(),
+ body=AddFindingsRequest(findings=[{"k": "v"}]),
+ db=db,
+ user=user,
+ )
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# runs — list & execute
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_list_runs_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None]) # parent check returns no row.
+ with pytest.raises(HTTPException) as exc:
+ await list_runs(hunt_id=uuid.uuid4(), db=db, user=user)
+ assert exc.value.status_code == 404
+ # The single executed query is the parent check; it must be scoped.
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_list_runs_returns_results_scoped() -> None:
+ user = _user()
+ hunt_id = uuid.uuid4()
+ parent = _row(id=hunt_id)
+ runs = [_row(hunt_id=hunt_id), _row(hunt_id=hunt_id)]
+ db = _mk_db([parent, runs])
+ result = await list_runs(hunt_id=hunt_id, db=db, user=user)
+ assert len(result) == 2
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ # Both statements must reference tenant_id.
+ parent_sql, _ = db.executed[0]
+ runs_sql, _ = db.executed[1]
+ assert "tenant_id" in parent_sql
+ assert "tenant_id" in runs_sql
+
+
+async def test_run_hunt_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await run_hunt(
+ hunt_id=uuid.uuid4(),
+ body=RunHuntRequest(platform="esql"),
+ db=db,
+ user=user,
+ )
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# create — both rows must carry tenant_id
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_create_hunt_binds_tenant_id(monkeypatch: pytest.MonkeyPatch) -> None:
+ user = _user()
+ db = _mk_db([_row(title="phish recon")])
+
+ async def _no_llm(*_a: Any, **_kw: Any) -> None:
+ return None
+
+ monkeypatch.setattr(hunts_module, "_generate_queries", _no_llm)
+ result = await create_hunt(
+ body=CreateHuntRequest(title="phish", hypothesis="suspicious DNS spikes"),
+ db=db,
+ user=user,
+ )
+ assert result.title == "phish recon"
+ sql, params = db.executed[0]
+ assert "tenant_id" in sql
+ assert params["tenant_id"] == user.tenant_id