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): tenant-isolate every /cases query and case_number resolver (P2-W1) (#118)

Beenu Arora3c26594458ae
diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.py
index 4013338f6..25319d595 100644
--- a/services/api/app/api/v1/endpoints/cases.py
+++ b/services/api/app/api/v1/endpoints/cases.py
@@ -4,6 +4,20 @@ Implements the full case lifecycle: new → triaged → investigating → contai
resolved → closed. Each case aggregates multiple alerts, maintains an observable
graph, evidence chain, and MITRE ATT&CK coverage map.
+Tenant isolation
+----------------
+Every query in this module is scoped by ``tenant_id = user.tenant_id``. The
+``aisoc_cases`` table has carried a ``tenant_id`` column since migration 012
+but the API historically did not filter by it, allowing any authenticated
+caller to read or mutate another tenant's cases just by guessing a UUID (or
+by guessing the short ``INC-001`` form). Companion tables
+(``aisoc_case_comments``, ``aisoc_case_tasks``) gained a ``tenant_id``
+column in migration 044 and are backfilled from their parent case so the
+same RLS predicate applies uniformly.
+
+The ``_resolve_case_id`` helper is also tenant-scoped — looking up
+``INC-001`` for tenant A must never return tenant B's INC-001.
+
Endpoints
---------
* ``GET /cases`` List cases (filterable by status/severity/assignee).
@@ -323,32 +337,47 @@ def _row_to_case(row: Any) -> CaseResponse:
)
-async def _resolve_case_id(case_id: str, db: Any) -> uuid.UUID:
- """Resolve a case identifier (UUID **or** human-readable case_number) to a UUID.
+async def _resolve_case_id(case_id: str, db: Any, tenant_id: uuid.UUID) -> uuid.UUID:
+ """Resolve a case identifier (UUID **or** human-readable case_number) to a UUID
+ scoped to the caller's tenant.
The web console and demo deeplinks use short identifiers like ``INC-001``,
while the database primary key is a UUID. Accepting both forms here keeps
the API ergonomic without forcing the front end to do a separate lookup.
- Raises ``404`` if the identifier doesn't match either form.
+ Tenant scoping is enforced in both branches:
+
+ * For the UUID branch we return the parsed UUID without touching the DB;
+ callers must still apply ``WHERE tenant_id = :tenant_id`` in their own
+ query, which they all do. (We don't probe existence here because every
+ caller does its own SELECT and would issue a redundant round-trip.)
+ * For the ``case_number`` branch we look up the row with
+ ``WHERE tenant_id = :tenant_id AND case_number = :case_number`` so an
+ attacker can't enumerate another tenant's INC-NNN identifiers.
+
+ Raises ``404`` if the identifier doesn't match either form within the
+ caller's tenant.
"""
case_id = (case_id or "").strip()
if not case_id:
raise HTTPException(status_code=404, detail="Case not found.")
- # Try UUID first — that's the canonical form.
+ # Try UUID first — that's the canonical form. Tenant scoping is enforced
+ # by the per-endpoint queries that consume the returned UUID, so we
+ # don't need a DB round-trip just to validate the format.
try:
return uuid.UUID(case_id)
except (ValueError, AttributeError):
pass
# Fall back to case_number lookup. Use a parameterized query — never
- # interpolate the raw string into SQL.
+ # interpolate the raw string into SQL — and scope by tenant so the
+ # short-id form can't be used as a cross-tenant oracle.
row = (
await db.execute(
- text("SELECT id FROM aisoc_cases WHERE case_number = :case_number ORDER BY created_at DESC LIMIT 1").bindparams(
- case_number=case_id
- )
+ text(
+ "SELECT id FROM aisoc_cases WHERE tenant_id = :tenant_id AND case_number = :case_number ORDER BY created_at DESC LIMIT 1"
+ ).bindparams(tenant_id=tenant_id, case_number=case_id)
)
).fetchone()
if not row:
@@ -371,8 +400,17 @@ async def list_cases(
limit: int = Query(50, ge=1, le=500),
offset: int = Query(0, ge=0),
) -> list[CaseResponse]:
- where_clauses = ["1=1"]
- params: dict[str, Any] = {"limit": limit, "offset": offset}
+ # Tenant scoping is non-optional. The aisoc_cases table has carried a
+ # tenant_id column since migration 012; until P2-W1 the API simply
+ # ignored it, exposing every tenant's caseload to every authenticated
+ # caller. Anchor the WHERE clause on tenant_id so the filter is always
+ # present even when the operator passes no other filters.
+ where_clauses = ["tenant_id = :tenant_id"]
+ params: dict[str, Any] = {
+ "limit": limit,
+ "offset": offset,
+ "tenant_id": user.tenant_id,
+ }
if status_filter:
where_clauses.append("status = :status")
params["status"] = status_filter
@@ -402,18 +440,23 @@ async def create_case(body: CreateCaseRequest, db: DBSession, user: AuthUser) ->
case_id = uuid.uuid4()
now = datetime.now(UTC)
+ # Note: PostgreSQL ``::type`` casts inside text() confuse SQLAlchemy's
+ # bind-parameter parser; use ``CAST(:param AS TYPE)`` so the bind survives
+ # the round-trip (see also Batch 2 / hunts.py for the same gotcha).
q = text("""
INSERT INTO aisoc_cases (
- id, title, description, severity, status, assignee,
+ id, tenant_id, title, description, severity, status, assignee,
mitre_techniques, alert_ids, compliance_frameworks, tags,
sla_due_at, opened_at, created_at, updated_at, created_by
) VALUES (
- :id, :title, :description, :severity, 'new', :assignee,
- :mitre::jsonb, :alert_ids::uuid[], :frameworks::text[], :tags::jsonb,
+ :id, :tenant_id, :title, :description, :severity, 'new', :assignee,
+ CAST(:mitre AS JSONB), CAST(:alert_ids AS UUID[]),
+ CAST(:frameworks AS TEXT[]), CAST(:tags AS JSONB),
:sla, :now, :now, :now, :user
) RETURNING *
""").bindparams(
id=case_id,
+ tenant_id=user.tenant_id,
title=body.title,
description=body.description,
severity=body.severity,
@@ -424,7 +467,7 @@ async def create_case(body: CreateCaseRequest, db: DBSession, user: AuthUser) ->
tags=_json.dumps(body.tags),
sla=body.sla_due_at,
now=now,
- user=str(user) if user else "system",
+ user=getattr(user, "email", None) or "system",
)
try:
row = (await db.execute(q)).fetchone()
@@ -465,8 +508,12 @@ async def create_case(body: CreateCaseRequest, db: DBSession, user: AuthUser) ->
@router.get("/{case_id}", response_model=CaseResponse, summary="Get case")
async def get_case(case_id: str, db: DBSession, user: AuthUser) -> CaseResponse:
- cid = await _resolve_case_id(case_id, db)
- row = (await db.execute(text("SELECT * FROM aisoc_cases WHERE id = :id").bindparams(id=cid))).fetchone()
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ row = (
+ await db.execute(
+ text("SELECT * FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=cid, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Case not found.")
return _row_to_case(row)
@@ -476,8 +523,12 @@ async def get_case(case_id: str, db: DBSession, user: AuthUser) -> CaseResponse:
async def update_case(case_id: str, body: UpdateCaseRequest, db: DBSession, user: AuthUser) -> CaseResponse:
import json as _json
- cid = await _resolve_case_id(case_id, db)
- existing = (await db.execute(text("SELECT status FROM aisoc_cases WHERE id = :id").bindparams(id=cid))).fetchone()
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ existing = (
+ await db.execute(
+ text("SELECT status FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=cid, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if not existing:
raise HTTPException(status_code=404, detail="Case not found.")
@@ -491,7 +542,11 @@ async def update_case(case_id: str, body: UpdateCaseRequest, db: DBSession, user
now = datetime.now(UTC)
sets = ["updated_at = :now"]
- params: dict[str, Any] = {"id": cid, "now": now}
+ params: dict[str, Any] = {
+ "id": cid,
+ "now": now,
+ "tenant_id": user.tenant_id,
+ }
if body.title is not None:
sets.append("title = :title")
@@ -509,13 +564,13 @@ async def update_case(case_id: str, body: UpdateCaseRequest, db: DBSession, user
sets.append("sla_due_at = :sla")
params["sla"] = body.sla_due_at
if body.mitre_techniques is not None:
- sets.append("mitre_techniques = :mitre::jsonb")
+ sets.append("mitre_techniques = CAST(:mitre AS JSONB)")
params["mitre"] = _json.dumps(body.mitre_techniques)
if body.compliance_frameworks is not None:
- sets.append("compliance_frameworks = :frameworks::text[]")
+ sets.append("compliance_frameworks = CAST(:frameworks AS TEXT[])")
params["frameworks"] = body.compliance_frameworks
if body.tags is not None:
- sets.append("tags = :tags::jsonb")
+ sets.append("tags = CAST(:tags AS JSONB)")
params["tags"] = _json.dumps(body.tags)
if body.status:
@@ -525,7 +580,7 @@ async def update_case(case_id: str, body: UpdateCaseRequest, db: DBSession, user
if ts_col:
sets.append(f"{ts_col} = :now")
- q = text(f"UPDATE aisoc_cases SET {', '.join(sets)} WHERE id = :id RETURNING *").bindparams(**params)
+ q = text(f"UPDATE aisoc_cases SET {', '.join(sets)} WHERE id = :id AND tenant_id = :tenant_id RETURNING *").bindparams(**params)
try:
row = (await db.execute(q)).fetchone()
if row is None:
@@ -566,7 +621,12 @@ async def update_case(case_id: str, body: UpdateCaseRequest, db: DBSession, user
# is a cheap, idempotent breadcrumb rather than a heavy precompute.
if body.status in {"resolved", "closed"}:
try:
- await _emit_summary_breadcrumb(db, case_id=row.id, status=body.status)
+ await _emit_summary_breadcrumb(
+ db,
+ case_id=row.id,
+ tenant_id=user.tenant_id,
+ status=body.status,
+ )
except Exception: # pragma: no cover — defensive: never block status change.
logger.exception("cases.update.summary_breadcrumb_failed case=%s", row.id)
await db.rollback()
@@ -576,15 +636,15 @@ async def update_case(case_id: str, body: UpdateCaseRequest, db: DBSession, user
@router.post("/{case_id}/alerts", response_model=CaseResponse, summary="Link alerts to a case")
async def add_alerts(case_id: str, body: AddAlertsRequest, db: DBSession, user: AuthUser) -> CaseResponse:
- cid = await _resolve_case_id(case_id, db)
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
ids_str = [str(a) for a in body.alert_ids]
q = text("""
UPDATE aisoc_cases
- SET alert_ids = array(SELECT DISTINCT unnest(alert_ids || :new_ids::uuid[])),
+ SET alert_ids = array(SELECT DISTINCT unnest(alert_ids || CAST(:new_ids AS UUID[]))),
updated_at = now()
- WHERE id = :id
+ WHERE id = :id AND tenant_id = :tenant_id
RETURNING *
- """).bindparams(id=cid, new_ids=ids_str)
+ """).bindparams(id=cid, new_ids=ids_str, tenant_id=user.tenant_id)
try:
row = (await db.execute(q)).fetchone()
if not row:
@@ -602,8 +662,14 @@ async def add_alerts(case_id: str, body: AddAlertsRequest, db: DBSession, user:
async def update_observables(case_id: str, body: UpdateObservablesRequest, db: DBSession, user: AuthUser) -> CaseResponse:
import json as _json
- cid = await _resolve_case_id(case_id, db)
- existing = (await db.execute(text("SELECT observable_graph FROM aisoc_cases WHERE id = :id").bindparams(id=cid))).fetchone()
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ existing = (
+ await db.execute(
+ text("SELECT observable_graph FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(
+ id=cid, tenant_id=user.tenant_id
+ )
+ )
+ ).fetchone()
if not existing:
raise HTTPException(status_code=404, detail="Case not found.")
@@ -624,9 +690,10 @@ async def update_observables(case_id: str, body: UpdateObservablesRequest, db: D
edges.append(e.model_dump())
graph = {"nodes": nodes, "edges": edges}
- q = text("""
- UPDATE aisoc_cases SET observable_graph = :g::jsonb, updated_at = now() WHERE id = :id RETURNING *
- """).bindparams(id=cid, g=_json.dumps(graph))
+ q = text(
+ "UPDATE aisoc_cases SET observable_graph = CAST(:g AS JSONB), updated_at = now() "
+ "WHERE id = :id AND tenant_id = :tenant_id RETURNING *"
+ ).bindparams(id=cid, g=_json.dumps(graph), tenant_id=user.tenant_id)
try:
row = (await db.execute(q)).fetchone()
await db.commit()
@@ -638,17 +705,34 @@ async def update_observables(case_id: str, body: UpdateObservablesRequest, db: D
@router.post("/{case_id}/comments", response_model=CommentResponse, status_code=201, summary="Add comment")
async def add_comment(case_id: str, body: AddCommentRequest, db: DBSession, user: AuthUser) -> CommentResponse:
- cid = await _resolve_case_id(case_id, db)
- exists = (await db.execute(text("SELECT 1 FROM aisoc_cases WHERE id = :id").bindparams(id=cid))).fetchone()
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ exists = (
+ await db.execute(
+ text("SELECT 1 FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=cid, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if not exists:
raise HTTPException(status_code=404, detail="Case not found.")
comment_id = uuid.uuid4()
now = datetime.now(UTC)
+ # Stamp the row with tenant_id so the comment table is independently
+ # tenant-scoped — see migration 044.
q = text("""
- INSERT INTO aisoc_case_comments (id, case_id, author, body, is_system, created_at)
- VALUES (:id, :case_id, :author, :body, :sys, :now) RETURNING *
- """).bindparams(id=comment_id, case_id=cid, author=str(user) if user else "system", body=body.body, sys=body.is_system, now=now)
+ INSERT INTO aisoc_case_comments
+ (id, case_id, tenant_id, author, body, is_system, created_at)
+ VALUES
+ (:id, :case_id, :tenant_id, :author, :body, :sys, :now)
+ RETURNING *
+ """).bindparams(
+ id=comment_id,
+ case_id=cid,
+ tenant_id=user.tenant_id,
+ author=getattr(user, "email", None) or "system",
+ body=body.body,
+ sys=body.is_system,
+ now=now,
+ )
try:
row = (await db.execute(q)).fetchone()
if row is None:
@@ -669,9 +753,13 @@ async def add_comment(case_id: str, body: AddCommentRequest, db: DBSession, user
@router.get("/{case_id}/comments", response_model=list[CommentResponse], summary="List case comments")
async def list_comments(case_id: str, db: DBSession, user: AuthUser) -> list[CommentResponse]:
- cid = await _resolve_case_id(case_id, db)
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
rows = (
- await db.execute(text("SELECT * FROM aisoc_case_comments WHERE case_id = :id ORDER BY created_at").bindparams(id=cid))
+ await db.execute(
+ text("SELECT * FROM aisoc_case_comments WHERE case_id = :id AND tenant_id = :tenant_id ORDER BY created_at").bindparams(
+ id=cid, tenant_id=user.tenant_id
+ )
+ )
).fetchall()
return [
CommentResponse(id=r.id, case_id=r.case_id, author=r.author, body=r.body, is_system=r.is_system, created_at=r.created_at)
@@ -695,8 +783,12 @@ async def add_note(case_id: str, body: AddCommentRequest, db: DBSession, user: A
@router.get("/{case_id}/evidence", response_model=EvidenceReport, summary="Export evidence chain report")
async def evidence_report(case_id: str, db: DBSession, user: AuthUser) -> EvidenceReport:
- cid = await _resolve_case_id(case_id, db)
- row = (await db.execute(text("SELECT * FROM aisoc_cases WHERE id = :id").bindparams(id=cid))).fetchone()
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ row = (
+ await db.execute(
+ text("SELECT * FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=cid, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Case not found.")
return EvidenceReport(
@@ -724,8 +816,12 @@ async def evidence_report(case_id: str, db: DBSession, user: AuthUser) -> Eviden
@router.get("/{case_id}/timeline", response_model=TimelineResponse, summary="Case activity timeline")
async def case_timeline(case_id: str, db: DBSession, user: AuthUser) -> TimelineResponse:
- cid = await _resolve_case_id(case_id, db)
- case_row = (await db.execute(text("SELECT * FROM aisoc_cases WHERE id = :id").bindparams(id=cid))).fetchone()
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ case_row = (
+ await db.execute(
+ text("SELECT * FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=cid, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if not case_row:
raise HTTPException(status_code=404, detail="Case not found.")
@@ -761,8 +857,11 @@ async def case_timeline(case_id: str, db: DBSession, user: AuthUser) -> Timeline
comment_rows = (
await db.execute(
text(
- "SELECT id, author, body, is_system, created_at FROM aisoc_case_comments WHERE case_id = :id ORDER BY created_at"
- ).bindparams(id=cid)
+ "SELECT id, author, body, is_system, created_at "
+ "FROM aisoc_case_comments "
+ "WHERE case_id = :id AND tenant_id = :tenant_id "
+ "ORDER BY created_at"
+ ).bindparams(id=cid, tenant_id=user.tenant_id)
)
).fetchall()
for c in comment_rows:
@@ -802,8 +901,11 @@ async def case_timeline(case_id: str, db: DBSession, user: AuthUser) -> Timeline
task_rows = (
await db.execute(
text(
- "SELECT id, title, status, assignee, created_at FROM aisoc_case_tasks WHERE case_id = :id ORDER BY created_at"
- ).bindparams(id=cid)
+ "SELECT id, title, status, assignee, created_at "
+ "FROM aisoc_case_tasks "
+ "WHERE case_id = :id AND tenant_id = :tenant_id "
+ "ORDER BY created_at"
+ ).bindparams(id=cid, tenant_id=user.tenant_id)
)
).fetchall()
for t in task_rows:
@@ -831,15 +933,22 @@ async def case_timeline(case_id: str, db: DBSession, user: AuthUser) -> Timeline
@router.get("/{case_id}/tasks", response_model=list[TaskResponse], summary="List case tasks")
async def list_tasks(case_id: str, db: DBSession, user: AuthUser) -> list[TaskResponse]:
- cid = await _resolve_case_id(case_id, db)
- exists = (await db.execute(text("SELECT 1 FROM aisoc_cases WHERE id = :id").bindparams(id=cid))).fetchone()
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ exists = (
+ await db.execute(
+ text("SELECT 1 FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=cid, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if not exists:
raise HTTPException(status_code=404, detail="Case not found.")
rows = (
await db.execute(
text(
- "SELECT id, title, status, assignee, due_at, created_at FROM aisoc_case_tasks WHERE case_id = :id ORDER BY created_at"
- ).bindparams(id=cid)
+ "SELECT id, title, status, assignee, due_at, created_at "
+ "FROM aisoc_case_tasks "
+ "WHERE case_id = :id AND tenant_id = :tenant_id "
+ "ORDER BY created_at"
+ ).bindparams(id=cid, tenant_id=user.tenant_id)
)
).fetchall()
return [_row_to_task(r) for r in rows]
@@ -852,8 +961,12 @@ async def create_task(
db: DBSession,
user: AuthUser,
) -> TaskResponse:
- cid = await _resolve_case_id(case_id, db)
- exists = (await db.execute(text("SELECT 1 FROM aisoc_cases WHERE id = :id").bindparams(id=cid))).fetchone()
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ exists = (
+ await db.execute(
+ text("SELECT 1 FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=cid, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if not exists:
raise HTTPException(status_code=404, detail="Case not found.")
@@ -865,20 +978,21 @@ async def create_task(
text(
"""
INSERT INTO aisoc_case_tasks
- (id, case_id, title, status, assignee, due_at, created_at, updated_at, created_by)
+ (id, case_id, tenant_id, title, status, assignee, due_at, created_at, updated_at, created_by)
VALUES
- (:id, :case_id, :title, :status, :assignee, :due_at, :now, :now, :created_by)
+ (:id, :case_id, :tenant_id, :title, :status, :assignee, :due_at, :now, :now, :created_by)
RETURNING id, title, status, assignee, due_at, created_at
"""
).bindparams(
id=task_id,
case_id=cid,
+ tenant_id=user.tenant_id,
title=body.title,
status=body.status,
assignee=body.assignee,
due_at=body.due_at,
now=now,
- created_by=str(user) if user else None,
+ created_by=getattr(user, "email", None) or "system",
)
)
).fetchone()
@@ -897,9 +1011,14 @@ async def update_task(
db: DBSession,
user: AuthUser,
) -> TaskResponse:
- cid = await _resolve_case_id(case_id, db)
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
sets: list[str] = []
- params: dict[str, Any] = {"id": task_id, "case_id": cid, "now": datetime.now(UTC)}
+ params: dict[str, Any] = {
+ "id": task_id,
+ "case_id": cid,
+ "tenant_id": user.tenant_id,
+ "now": datetime.now(UTC),
+ }
if body.title is not None:
sets.append("title = :title")
params["title"] = body.title
@@ -923,7 +1042,7 @@ async def update_task(
f"""
UPDATE aisoc_case_tasks
SET {", ".join(sets)}
- WHERE id = :id AND case_id = :case_id
+ WHERE id = :id AND case_id = :case_id AND tenant_id = :tenant_id
RETURNING id, title, status, assignee, due_at, created_at
"""
).bindparams(**params)
@@ -977,8 +1096,12 @@ async def case_investigate(
db: DBSession,
user: AuthUser,
) -> dict[str, Any]:
- cid = await _resolve_case_id(case_id, db)
- exists = (await db.execute(text("SELECT 1 FROM aisoc_cases WHERE id = :id").bindparams(id=cid))).fetchone()
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ exists = (
+ await db.execute(
+ text("SELECT 1 FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=cid, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if not exists:
raise HTTPException(status_code=404, detail="Case not found.")
@@ -1003,7 +1126,7 @@ async def list_case_investigations(
The agents service is the source of truth. When it's unreachable we return
an empty list rather than 503 so the case detail page still renders.
"""
- cid = await _resolve_case_id(case_id, db)
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
try:
resp = await _agents_proxy("GET", f"/api/v1/cases/{cid}/investigations")
if resp.status_code == 404:
@@ -1057,7 +1180,13 @@ _SUMMARY_BREADCRUMB_BODY = (
)
-async def _emit_summary_breadcrumb(db: Any, *, case_id: uuid.UUID, status: str) -> None:
+async def _emit_summary_breadcrumb(
+ db: Any,
+ *,
+ case_id: uuid.UUID,
+ tenant_id: uuid.UUID | str,
+ status: str,
+) -> None:
"""Drop a system comment pointing to the on-demand summary endpoint.
Idempotent on repeated status changes — we re-emit only when transitioning
@@ -1070,12 +1199,13 @@ async def _emit_summary_breadcrumb(db: Any, *, case_id: uuid.UUID, status: str)
text(
"""
INSERT INTO aisoc_case_comments
- (id, case_id, author, body, is_system, created_at)
- VALUES (:id, :case_id, :author, :body, true, :now)
+ (id, case_id, tenant_id, author, body, is_system, created_at)
+ VALUES (:id, :case_id, :tenant_id, :author, :body, true, :now)
"""
).bindparams(
id=uuid.uuid4(),
case_id=case_id,
+ tenant_id=tenant_id,
author="aisoc",
body=body,
now=datetime.now(UTC),
@@ -1102,7 +1232,7 @@ async def case_auto_summary(
),
),
) -> Any:
- cid = await _resolve_case_id(case_id, db)
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
summary = await build_case_summary(db, cid)
if summary is None:
raise HTTPException(status_code=404, detail="Case not found.")
@@ -1144,7 +1274,7 @@ async def case_auto_postmortem(
*what happened, when did we find out, what did we do, and what should we
change*. Both are deterministic — same case state in, same artefact out.
"""
- cid = await _resolve_case_id(case_id, db)
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
postmortem = await build_case_postmortem(db, cid)
if postmortem is None:
raise HTTPException(status_code=404, detail="Case not found.")
@@ -1200,8 +1330,14 @@ async def list_related_cases(
overlap on `alert_ids` or share an observable IP/host. It's the smallest
thing the case detail page needs to stop 404'ing.
"""
- cid = await _resolve_case_id(case_id, db)
- row = (await db.execute(text("SELECT alert_ids, observable_graph FROM aisoc_cases WHERE id = :id").bindparams(id=cid))).fetchone()
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ row = (
+ await db.execute(
+ text("SELECT alert_ids, observable_graph FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(
+ id=cid, tenant_id=user.tenant_id
+ )
+ )
+ ).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Case not found.")
@@ -1216,11 +1352,16 @@ async def list_related_cases(
SELECT id, case_number, title, severity, status, created_at
FROM aisoc_cases
WHERE id <> :id
+ AND tenant_id = :tenant_id
AND alert_ids && CAST(:alerts AS UUID[])
ORDER BY created_at DESC
LIMIT 20
"""
- ).bindparams(id=cid, alerts=[str(a) for a in alert_ids])
+ ).bindparams(
+ id=cid,
+ tenant_id=user.tenant_id,
+ alerts=[str(a) for a in alert_ids],
+ )
)
).fetchall()
for r in rows:
diff --git a/services/api/migrations/044_cases_tenant_isolation.sql b/services/api/migrations/044_cases_tenant_isolation.sql
new file mode 100644
index 000000000..1c94e3028
--- /dev/null
+++ b/services/api/migrations/044_cases_tenant_isolation.sql
@@ -0,0 +1,72 @@
+-- Migration 044: Tenant isolation for aisoc_cases / aisoc_case_comments /
+-- aisoc_case_tasks (P2-W1).
+--
+-- aisoc_cases already has a tenant_id column (migration 012) but the /cases API
+-- never scoped queries by it, so any authenticated caller could read or mutate
+-- another tenant's cases just by guessing UUIDs (or by guessing the short
+-- case_number form like INC-001). The companion comments/tasks tables don't
+-- have tenant_id at all, so even with /cases fixed an attacker could still
+-- enumerate comments and tasks for foreign cases.
+--
+-- This migration:
+-- 1. Adds tenant_id to aisoc_case_comments and aisoc_case_tasks and
+-- backfills from the parent aisoc_cases row.
+-- 2. Adds covering indexes so /cases can filter by
+-- (tenant_id, …) efficiently.
+-- 3. Replaces the globally-unique idx_aisoc_cases_case_number with a
+-- (tenant_id, case_number) unique index so two tenants can independently
+-- mint INC-001 without collisions.
+--
+-- The API layer (services/api/app/api/v1/endpoints/cases.py) is updated in
+-- the same change to add `WHERE tenant_id = :tenant_id` to every query and
+-- to scope the case_number resolver by tenant.
+
+-- ------------------------------------------------------------------
+-- 1. aisoc_case_comments.tenant_id
+-- ------------------------------------------------------------------
+ALTER TABLE aisoc_case_comments
+ ADD COLUMN IF NOT EXISTS tenant_id UUID;
+
+UPDATE aisoc_case_comments c
+ SET tenant_id = p.tenant_id
+ FROM aisoc_cases p
+ WHERE c.case_id = p.id
+ AND c.tenant_id IS NULL;
+
+-- ------------------------------------------------------------------
+-- 2. aisoc_case_tasks.tenant_id
+-- ------------------------------------------------------------------
+ALTER TABLE aisoc_case_tasks
+ ADD COLUMN IF NOT EXISTS tenant_id UUID;
+
+UPDATE aisoc_case_tasks t
+ SET tenant_id = p.tenant_id
+ FROM aisoc_cases p
+ WHERE t.case_id = p.id
+ AND t.tenant_id IS NULL;
+
+-- ------------------------------------------------------------------
+-- 3. Indexes
+-- ------------------------------------------------------------------
+CREATE INDEX IF NOT EXISTS idx_aisoc_cases_tenant_created
+ ON aisoc_cases (tenant_id, created_at DESC);
+
+CREATE INDEX IF NOT EXISTS idx_aisoc_case_comments_tenant_case
+ ON aisoc_case_comments (tenant_id, case_id, created_at);
+
+CREATE INDEX IF NOT EXISTS idx_aisoc_case_tasks_tenant_case
+ ON aisoc_case_tasks (tenant_id, case_id, created_at);
+
+-- ------------------------------------------------------------------
+-- 4. Per-tenant uniqueness on case_number
+--
+-- Replace the global unique index from migration 028 with a (tenant_id,
+-- case_number) one so the human-readable identifier ("INC-001") is unique
+-- *within* a tenant but two tenants can share the same value. The legacy
+-- index is only dropped if it exists so this migration is idempotent on
+-- partially-migrated databases.
+-- ------------------------------------------------------------------
+DROP INDEX IF EXISTS idx_aisoc_cases_case_number;
+
+CREATE UNIQUE INDEX IF NOT EXISTS idx_aisoc_cases_tenant_case_number
+ ON aisoc_cases (tenant_id, case_number);
diff --git a/services/api/tests/test_cases_tenant_isolation.py b/services/api/tests/test_cases_tenant_isolation.py
new file mode 100644
index 000000000..621d34991
--- /dev/null
+++ b/services/api/tests/test_cases_tenant_isolation.py
@@ -0,0 +1,564 @@
+"""Tenant-isolation tests for the /cases API (regression: P2-W1).
+
+Mirrors ``test_hunts_tenant_isolation.py`` (Batch 2 / C-2): call the endpoint
+functions directly with a mocked :class:`DBSession` and assert that **every**
+SQL statement touching ``aisoc_cases``, ``aisoc_case_comments`` or
+``aisoc_case_tasks`` filters on ``tenant_id = :tenant_id`` *and* binds the
+caller's tenant id.
+
+The contract being protected: under no circumstances should an authenticated
+caller be able to read or mutate a case, comment, or task belonging to a
+different tenant — including via the human-readable ``INC-NNN`` short id.
+"""
+
+from __future__ import annotations
+
+import re
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.api.v1.deps import CurrentUser
+from app.api.v1.endpoints.cases import (
+ AddAlertsRequest,
+ AddCommentRequest,
+ CreateCaseRequest,
+ CreateTaskRequest,
+ UpdateCaseRequest,
+ UpdateObservablesRequest,
+ UpdateTaskRequest,
+ _resolve_case_id,
+ add_alerts,
+ add_comment,
+ case_timeline,
+ create_case,
+ create_task,
+ evidence_report,
+ get_case,
+ list_cases,
+ list_comments,
+ list_tasks,
+ update_case,
+ update_observables,
+ update_task,
+)
+from fastapi import HTTPException
+
+# ────────────────────────────────────────────────────────────────────────────
+# Fixtures / helpers
+# ────────────────────────────────────────────────────────────────────────────
+
+
+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 _case_row(**overrides: Any) -> MagicMock:
+ """A row object shaped like a SQLAlchemy ``aisoc_cases`` result."""
+ row = MagicMock()
+ now = datetime.now(UTC)
+ defaults = {
+ "id": uuid.uuid4(),
+ "case_number": "INC-001",
+ "title": "Phish wave",
+ "description": "Phishing detected",
+ "severity": "high",
+ "status": "new",
+ "assignee": "[email protected]",
+ "mitre_techniques": [],
+ "alert_ids": [],
+ "observable_graph": {},
+ "evidence_chain": [],
+ "compliance_frameworks": [],
+ "opened_at": now,
+ "triaged_at": None,
+ "resolved_at": None,
+ "closed_at": None,
+ "created_at": now,
+ "updated_at": now,
+ "created_by": "[email protected]",
+ "tags": {},
+ "sla_due_at": None,
+ }
+ defaults.update(overrides)
+ for k, v in defaults.items():
+ setattr(row, k, v)
+ return row
+
+
+def _task_row(**overrides: Any) -> MagicMock:
+ row = MagicMock()
+ now = datetime.now(UTC)
+ defaults = {
+ "id": uuid.uuid4(),
+ "title": "Investigate sender",
+ "status": "todo",
+ "assignee": None,
+ "due_at": None,
+ "created_at": now,
+ }
+ defaults.update(overrides)
+ for k, v in defaults.items():
+ setattr(row, k, v)
+ return row
+
+
+def _comment_row(**overrides: Any) -> MagicMock:
+ row = MagicMock()
+ now = datetime.now(UTC)
+ defaults = {
+ "id": uuid.uuid4(),
+ "case_id": uuid.uuid4(),
+ "author": "[email protected]",
+ "body": "note body",
+ "is_system": False,
+ "created_at": now,
+ }
+ defaults.update(overrides)
+ for k, v in defaults.items():
+ setattr(row, k, v)
+ return row
+
+
+def _mk_db(rows: list[Any]) -> MagicMock:
+ """Mock DBSession that returns 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:
+ sql = str(clause)
+ try:
+ params = dict(clause.compile().params) if hasattr(clause, "compile") else {}
+ except Exception: # pragma: no cover — defensive: never crash the mock.
+ params = {}
+ 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
+
+
+_TENANT_TABLES = ("aisoc_cases", "aisoc_case_comments", "aisoc_case_tasks")
+
+
+def _assert_tenant_scoped(executed: list[tuple[str, dict[str, Any]]], tenant_id: uuid.UUID) -> None:
+ """Every executed statement against a tenant-owned table must scope on tenant_id."""
+ assert executed, "expected at least one DB call"
+ for sql, params in executed:
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ if any(table in normalized for table in _TENANT_TABLES):
+ 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}"
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# _resolve_case_id — the human-readable INC-NNN form must be tenant-scoped
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_resolve_case_id_uuid_does_not_hit_db() -> None:
+ """UUID identifiers are returned as-is; per-endpoint queries enforce tenant."""
+ user = _user()
+ db = _mk_db([]) # no rows; if a query fires, fetch will return None.
+ target = uuid.uuid4()
+ result = await _resolve_case_id(str(target), db, user.tenant_id)
+ assert result == target
+ # No DB round-trip needed for the UUID branch.
+ assert db.executed == []
+
+
+async def test_resolve_case_id_case_number_scopes_by_tenant() -> None:
+ user = _user()
+ expected_id = uuid.uuid4()
+ row = MagicMock()
+ row.id = expected_id
+ db = _mk_db([row])
+ result = await _resolve_case_id("INC-001", db, user.tenant_id)
+ assert result == expected_id
+ sql, params = db.executed[0]
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ assert "tenant_id = :tenant_id" in normalized
+ assert params["tenant_id"] == user.tenant_id
+ assert params["case_number"] == "INC-001"
+
+
+async def test_resolve_case_id_cross_tenant_returns_404() -> None:
+ """Tenant B's INC-001 must 404 for tenant A even if it exists somewhere."""
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await _resolve_case_id("INC-001", db, user.tenant_id)
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# list_cases / get_case
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_list_cases_scopes_by_tenant() -> None:
+ user = _user()
+ db = _mk_db([[_case_row(title="A"), _case_row(title="B")]])
+ result = await list_cases(db=db, user=user)
+ assert len(result) == 2
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_list_cases_with_filters_keeps_tenant_scope() -> None:
+ user = _user()
+ db = _mk_db([[]])
+ await list_cases(
+ db=db,
+ user=user,
+ status_filter="investigating",
+ severity="high",
+ assignee="[email protected]",
+ )
+ sql, params = db.executed[0]
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ assert "tenant_id = :tenant_id" in normalized
+ assert params["tenant_id"] == user.tenant_id
+ assert params["status"] == "investigating"
+ assert params["severity"] == "high"
+
+
+async def test_get_case_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await get_case(case_id=str(uuid.uuid4()), db=db, user=user)
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_get_case_returns_row_when_tenant_matches() -> None:
+ user = _user()
+ cid = uuid.uuid4()
+ db = _mk_db([_case_row(id=cid)])
+ result = await get_case(case_id=str(cid), db=db, user=user)
+ assert result.id == cid
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# create_case — INSERT must carry tenant_id
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_create_case_binds_tenant_id() -> None:
+ user = _user()
+ db = _mk_db([_case_row(title="phish")])
+ result = await create_case(
+ body=CreateCaseRequest(title="phish wave", severity="high"),
+ db=db,
+ user=user,
+ )
+ assert result.title == "phish"
+ sql, params = db.executed[0]
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ assert "insert into aisoc_cases" in normalized
+ assert "tenant_id" in normalized
+ assert params["tenant_id"] == user.tenant_id
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# update_case / add_alerts / update_observables — cross-tenant must 404
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_update_case_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None]) # SELECT existing returns no row.
+ with pytest.raises(HTTPException) as exc:
+ await update_case(
+ case_id=str(uuid.uuid4()),
+ body=UpdateCaseRequest(title="rename"),
+ db=db,
+ user=user,
+ )
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_update_case_scopes_update_statement() -> None:
+ user = _user()
+ cid = uuid.uuid4()
+ existing = MagicMock()
+ existing.status = "new"
+ db = _mk_db([existing, _case_row(id=cid, title="renamed")])
+ await update_case(
+ case_id=str(cid),
+ body=UpdateCaseRequest(title="renamed"),
+ db=db,
+ user=user,
+ )
+ # Two statements: SELECT then UPDATE. Both must scope by tenant_id.
+ assert len(db.executed) >= 2
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ upd_sql, upd_params = db.executed[1]
+ assert "update aisoc_cases" in re.sub(r"\s+", " ", upd_sql).lower()
+ assert upd_params["tenant_id"] == user.tenant_id
+
+
+async def test_add_alerts_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None]) # UPDATE ... RETURNING * yields nothing.
+ with pytest.raises(HTTPException) as exc:
+ await add_alerts(
+ case_id=str(uuid.uuid4()),
+ body=AddAlertsRequest(alert_ids=[uuid.uuid4()]),
+ db=db,
+ user=user,
+ )
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_update_observables_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await update_observables(
+ case_id=str(uuid.uuid4()),
+ body=UpdateObservablesRequest(nodes=[], edges=[]),
+ db=db,
+ user=user,
+ )
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Comments — INSERT and SELECT must both carry tenant_id
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_add_comment_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None]) # parent case check returns no row.
+ with pytest.raises(HTTPException) as exc:
+ await add_comment(
+ case_id=str(uuid.uuid4()),
+ body=AddCommentRequest(body="hi"),
+ db=db,
+ user=user,
+ )
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_add_comment_inserts_with_tenant_id() -> None:
+ user = _user()
+ cid = uuid.uuid4()
+ db = _mk_db([_case_row(id=cid), _comment_row(case_id=cid)])
+ await add_comment(
+ case_id=str(cid),
+ body=AddCommentRequest(body="manual note"),
+ db=db,
+ user=user,
+ )
+ # Two statements: parent SELECT then INSERT. Both must scope by tenant_id.
+ assert len(db.executed) == 2
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ ins_sql, ins_params = db.executed[1]
+ normalized = re.sub(r"\s+", " ", ins_sql).lower()
+ assert "insert into aisoc_case_comments" in normalized
+ assert ins_params["tenant_id"] == user.tenant_id
+
+
+async def test_list_comments_scopes_by_tenant() -> None:
+ user = _user()
+ cid = uuid.uuid4()
+ db = _mk_db([[_comment_row(case_id=cid)]])
+ result = await list_comments(case_id=str(cid), db=db, user=user)
+ assert len(result) == 1
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ sql, params = db.executed[0]
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ assert "from aisoc_case_comments" in normalized
+ assert "tenant_id = :tenant_id" in normalized
+ assert params["tenant_id"] == user.tenant_id
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Evidence / timeline
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_evidence_report_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await evidence_report(case_id=str(uuid.uuid4()), db=db, user=user)
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_case_timeline_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await case_timeline(case_id=str(uuid.uuid4()), db=db, user=user)
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_case_timeline_scopes_comments_and_tasks() -> None:
+ user = _user()
+ cid = uuid.uuid4()
+ # Sequence: case row → comments → (no alerts loop) → tasks
+ db = _mk_db(
+ [
+ _case_row(id=cid),
+ [_comment_row(case_id=cid)],
+ [_task_row()],
+ ]
+ )
+ await case_timeline(case_id=str(cid), db=db, user=user)
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ # Verify both the comments and tasks queries reference their tenant column.
+ joined = " | ".join(re.sub(r"\s+", " ", s).lower() for s, _ in db.executed)
+ assert "from aisoc_case_comments" in joined
+ assert "from aisoc_case_tasks" in joined
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Tasks
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_list_tasks_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None]) # parent check returns no row.
+ with pytest.raises(HTTPException) as exc:
+ await list_tasks(case_id=str(uuid.uuid4()), db=db, user=user)
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_list_tasks_scopes_by_tenant() -> None:
+ user = _user()
+ cid = uuid.uuid4()
+ db = _mk_db([_case_row(id=cid), [_task_row(), _task_row()]])
+ result = await list_tasks(case_id=str(cid), db=db, user=user)
+ assert len(result) == 2
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ # Second statement is the tasks SELECT; check it filters by tenant_id.
+ sql, params = db.executed[1]
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ assert "from aisoc_case_tasks" in normalized
+ assert "tenant_id = :tenant_id" in normalized
+ assert params["tenant_id"] == user.tenant_id
+
+
+async def test_create_task_cross_tenant_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await create_task(
+ case_id=str(uuid.uuid4()),
+ body=CreateTaskRequest(title="Investigate"),
+ db=db,
+ user=user,
+ )
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_create_task_inserts_with_tenant_id() -> None:
+ user = _user()
+ cid = uuid.uuid4()
+ db = _mk_db([_case_row(id=cid), _task_row()])
+ await create_task(
+ case_id=str(cid),
+ body=CreateTaskRequest(title="Investigate"),
+ db=db,
+ user=user,
+ )
+ assert len(db.executed) == 2
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ ins_sql, ins_params = db.executed[1]
+ normalized = re.sub(r"\s+", " ", ins_sql).lower()
+ assert "insert into aisoc_case_tasks" in normalized
+ assert ins_params["tenant_id"] == user.tenant_id
+
+
+async def test_update_task_cross_tenant_returns_404() -> None:
+ user = _user()
+ cid = uuid.uuid4()
+ db = _mk_db([None]) # UPDATE ... RETURNING yields nothing.
+ with pytest.raises(HTTPException) as exc:
+ await update_task(
+ case_id=str(cid),
+ task_id=uuid.uuid4(),
+ body=UpdateTaskRequest(status="in_progress"),
+ db=db,
+ user=user,
+ )
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_update_task_scopes_update_statement() -> None:
+ user = _user()
+ cid = uuid.uuid4()
+ db = _mk_db([_task_row()])
+ await update_task(
+ case_id=str(cid),
+ task_id=uuid.uuid4(),
+ body=UpdateTaskRequest(status="done"),
+ db=db,
+ user=user,
+ )
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ upd_sql, upd_params = db.executed[0]
+ normalized = re.sub(r"\s+", " ", upd_sql).lower()
+ assert "update aisoc_case_tasks" in normalized
+ assert upd_params["tenant_id"] == user.tenant_id