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(security): add tenant_id isolation to compliance, phishing, and knowledge-base endpoints (#236)
Tanmay Zade3971565cd2e8
diff --git a/services/api/app/api/v1/endpoints/compliance.py b/services/api/app/api/v1/endpoints/compliance.pyindex f20e4de70..6fa11bd41 100644--- a/services/api/app/api/v1/endpoints/compliance.py+++ b/services/api/app/api/v1/endpoints/compliance.py@@ -165,12 +165,14 @@ def _compute_hash(prev_hash: str | None, summary: str, payload: dict[str, Any])return hashlib.sha256(raw.encode()).hexdigest()-async def _latest_hash(db: DBSession, framework: str) -> str | None:+async def _latest_hash(db: DBSession, framework: str, tenant_id: uuid.UUID) -> str | None:row = (await db.execute(- text("SELECT payload_hash FROM aisoc_compliance_evidence WHERE framework = :f ORDER BY created_at DESC LIMIT 1").bindparams(- f=framework- )+ text(+ "SELECT payload_hash FROM aisoc_compliance_evidence"+ " WHERE framework = :f AND tenant_id = :tenant_id"+ " ORDER BY created_at DESC LIMIT 1"+ ).bindparams(f=framework, tenant_id=tenant_id))).fetchone()return row.payload_hash if row else None@@ -241,23 +243,24 @@ async def trigger_evidence_collection(body: CollectJobRequest) -> CollectJobResp@router.post("/evidence", response_model=EvidenceResponse, status_code=status.HTTP_201_CREATED, summary="Collect evidence item")async def collect_evidence(body: CollectEvidenceRequest, db: DBSession, user: AuthUser) -> EvidenceResponse:- prev_hash = await _latest_hash(db, body.framework)+ prev_hash = await _latest_hash(db, body.framework, user.tenant_id)new_hash = _compute_hash(prev_hash, body.summary, body.raw_payload)now = datetime.now(UTC)evidence_id = uuid.uuid4()q = text("""INSERT INTO aisoc_compliance_evidence (- id, case_id, framework, control_id, control_title,+ id, tenant_id, case_id, framework, control_id, control_title,evidence_kind, summary, raw_payload, payload_hash, prev_hash,collected_at, status, created_at) VALUES (- :id, :case_id, :fw, :ctrl, :title,+ :id, :tenant_id, :case_id, :fw, :ctrl, :title,:kind, :summary, :payload::jsonb, :hash, :prev,:now, 'pending', :now) RETURNING *""").bindparams(id=evidence_id,+ tenant_id=user.tenant_id,case_id=body.case_id,fw=body.framework,ctrl=body.control_id,@@ -290,8 +293,8 @@ async def list_evidence(limit: int = Query(100, ge=1, le=1000),offset: int = Query(0, ge=0),) -> list[EvidenceResponse]:- 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 framework:wheres.append("framework = :fw")params["fw"] = framework@@ -318,7 +321,13 @@ async def list_evidence(@router.get("/evidence/{evidence_id}", response_model=EvidenceResponse, summary="Get evidence item")async def get_evidence(evidence_id: uuid.UUID, db: DBSession, user: AuthUser) -> EvidenceResponse:- row = (await db.execute(text("SELECT * FROM aisoc_compliance_evidence WHERE id = :id").bindparams(id=evidence_id))).fetchone()+ row = (+ await db.execute(+ text("SELECT * FROM aisoc_compliance_evidence WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ id=evidence_id, tenant_id=user.tenant_id+ )+ )+ ).fetchone()if not row:raise HTTPException(status_code=404, detail="Evidence item not found.")return _row_to_evidence(row)@@ -330,8 +339,8 @@ async def review_evidence(evidence_id: uuid.UUID, body: ReviewEvidenceRequest, dq = text("""UPDATE aisoc_compliance_evidenceSET status = :decision, reviewed_by = :reviewer, reviewed_at = :now- WHERE id = :id RETURNING *- """).bindparams(id=evidence_id, decision=body.decision, reviewer=body.reviewer or str(user), now=now)+ WHERE id = :id AND tenant_id = :tenant_id RETURNING *+ """).bindparams(id=evidence_id, tenant_id=user.tenant_id, decision=body.decision, reviewer=body.reviewer or str(user), now=now)try:row = (await db.execute(q)).fetchone()if not row:@@ -352,8 +361,8 @@ async def compliance_report(user: AuthUser,framework: str | None = Query(None, description="Filter to a single framework."),) -> list[CompliancePosture]:- wheres = ["1=1"]- params: dict[str, Any] = {}+ wheres = ["tenant_id = :tenant_id"]+ params: dict[str, Any] = {"tenant_id": user.tenant_id}if framework:wheres.append("framework = :fw")params["fw"] = frameworkdiff --git a/services/api/app/api/v1/endpoints/hunts.py b/services/api/app/api/v1/endpoints/hunts.pyindex 8be19aef3..702ca5cbf 100644--- a/services/api/app/api/v1/endpoints/hunts.py+++ b/services/api/app/api/v1/endpoints/hunts.py@@ -37,6 +37,7 @@ from pydantic import BaseModel, Fieldfrom sqlalchemy import textfrom app.api.v1.deps import AuthUser, DBSession+from app.core.airgap import AirgapViolation, enforce_airgap_for_urllogger = logging.getLogger(__name__)@@ -143,10 +144,12 @@ async def _generate_queries(hypothesis: str, mitre: str | None) -> dict[str, strif mitre:user_msg += f"\nMITRE TECHNIQUE: {mitre}"user_msg += "\nGenerate ES|QL, SPL, and KQL hunt queries."+ completions_url = f"{base_url}/chat/completions"+ enforce_airgap_for_url(completions_url)try:async with httpx.AsyncClient(timeout=45) as client:resp = await client.post(- f"{base_url}/chat/completions",+ completions_url,headers={"Authorization": f"Bearer {api_key}"},json={"model": model,@@ -242,7 +245,13 @@ async def list_hunts(@router.post("", response_model=HuntResponse, status_code=status.HTTP_201_CREATED, summary="Create hunt hypothesis")async def create_hunt(body: CreateHuntRequest, db: DBSession, user: AuthUser) -> HuntResponse:mitre = body.mitre_technique or body.mitre_tactic- queries = await _generate_queries(body.hypothesis, mitre) or _fallback_queries(body.hypothesis)+ # In air-gapped mode the LLM call is refused (AirgapViolation); fall back to+ # the deterministic query templates so hunt creation still succeeds offline+ # rather than surfacing a 500. Mirrors the phishing submit/retriage pattern.+ try:+ queries = await _generate_queries(body.hypothesis, mitre) or _fallback_queries(body.hypothesis)+ except AirgapViolation:+ queries = _fallback_queries(body.hypothesis)hunt_id = uuid.uuid4()now = datetime.now(UTC)q = text("""diff --git a/services/api/app/api/v1/endpoints/knowledge_base.py b/services/api/app/api/v1/endpoints/knowledge_base.pyindex 3afb32815..2f06faa44 100644--- a/services/api/app/api/v1/endpoints/knowledge_base.py+++ b/services/api/app/api/v1/endpoints/knowledge_base.py@@ -27,6 +27,7 @@ from pydantic import BaseModel, Fieldfrom sqlalchemy import textfrom app.api.v1.deps import AuthUser, DBSession+from app.core.airgap import AirgapViolation, enforce_airgap_for_urllogger = logging.getLogger(__name__)@@ -120,10 +121,12 @@ async def _synthesise(question: str, chunks: list[KBChunk]) -> str | None:base_url = os.getenv("LLM_BASE_URL", "https://api.openai.com/v1")model = os.getenv("LLM_MODEL", "gpt-4o-mini")context = "\n\n".join(f"[{c.title}] chunk {c.chunk_index}:\n{c.content}" for c in chunks)+ completions_url = f"{base_url}/chat/completions"+ enforce_airgap_for_url(completions_url)try:async with httpx.AsyncClient(timeout=45) as client:resp = await client.post(- f"{base_url}/chat/completions",+ completions_url,headers={"Authorization": f"Bearer {api_key}"},json={"model": model,@@ -156,14 +159,15 @@ async def ingest(body: IngestRequest, db: DBSession, user: AuthUser) -> list[KBDdoc_id = uuid.uuid4()q = text("""INSERT INTO aisoc_kb_documents (- id, title, doc_kind, source_url, content, tags,+ id, tenant_id, title, doc_kind, source_url, content, tags,chunk_index, chunk_total, created_at, updated_at, created_by) VALUES (- :id, :title, :kind, :url, :content, :tags::text[],+ :id, :tenant_id, :title, :kind, :url, :content, :tags::text[],:idx, :total, :now, :now, :user) RETURNING *""").bindparams(id=doc_id,+ tenant_id=user.tenant_id,title=body.title,kind=body.doc_kind,url=body.source_url,@@ -189,7 +193,11 @@ async def ingest(body: IngestRequest, db: DBSession, user: AuthUser) -> list[KBDasync def list_documents(db: DBSession, user: AuthUser) -> list[KBDocResponse]:try:rows = (- await db.execute(text("SELECT * FROM aisoc_kb_documents WHERE chunk_index = 0 ORDER BY created_at DESC LIMIT 200"))+ await db.execute(+ text(+ "SELECT * FROM aisoc_kb_documents WHERE chunk_index = 0 AND tenant_id = :tenant_id ORDER BY created_at DESC LIMIT 200"+ ).bindparams(tenant_id=user.tenant_id)+ )).fetchall()return [_row_to_doc(r) for r in rows]except Exception as exc:@@ -199,7 +207,13 @@ async def list_documents(db: DBSession, user: AuthUser) -> list[KBDocResponse]:@router.get("/documents/{doc_id}", response_model=KBDocResponse, summary="Get KB document")async def get_document(doc_id: uuid.UUID, db: DBSession, user: AuthUser) -> KBDocResponse:- row = (await db.execute(text("SELECT * FROM aisoc_kb_documents WHERE id = :id").bindparams(id=doc_id))).fetchone()+ row = (+ await db.execute(+ text("SELECT * FROM aisoc_kb_documents WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ id=doc_id, tenant_id=user.tenant_id+ )+ )+ ).fetchone()if not row:raise HTTPException(status_code=404, detail="Document not found.")return _row_to_doc(row)@@ -207,18 +221,28 @@ async def get_document(doc_id: uuid.UUID, db: DBSession, user: AuthUser) -> KBDo@router.delete("/documents/{doc_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None, summary="Remove KB document")async def delete_document(doc_id: uuid.UUID, db: DBSession, user: AuthUser) -> None:- existing = (await db.execute(text("SELECT title FROM aisoc_kb_documents WHERE id = :id").bindparams(id=doc_id))).fetchone()+ existing = (+ await db.execute(+ text("SELECT title FROM aisoc_kb_documents WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ id=doc_id, tenant_id=user.tenant_id+ )+ )+ ).fetchone()if not existing:raise HTTPException(status_code=404, detail="Document not found.")- # Remove all chunks with same title + doc_kind- await db.execute(text("DELETE FROM aisoc_kb_documents WHERE title = :title").bindparams(title=existing.title))+ # Remove all chunks with same title within this tenant only.+ await db.execute(+ text("DELETE FROM aisoc_kb_documents WHERE title = :title AND tenant_id = :tenant_id").bindparams(+ title=existing.title, tenant_id=user.tenant_id+ )+ )await db.commit()@router.post("/query", response_model=QueryResponse, summary="Search knowledge base + optional LLM synthesis")async def query_kb(body: QueryRequest, db: DBSession, user: AuthUser) -> QueryResponse:- wheres = ["to_tsvector('english', content) @@ plainto_tsquery('english', :q)"]- params: dict[str, Any] = {"q": body.question, "limit": body.top_k}+ wheres = ["to_tsvector('english', content) @@ plainto_tsquery('english', :q)", "tenant_id = :tenant_id"]+ params: dict[str, Any] = {"q": body.question, "tenant_id": user.tenant_id, "limit": body.top_k}if body.doc_kinds:wheres.append("doc_kind = ANY(:kinds::text[])")params["kinds"] = body.doc_kinds@@ -249,7 +273,12 @@ async def query_kb(body: QueryRequest, db: DBSession, user: AuthUser) -> QueryRe]answer: str | None = Noneif body.synthesise and chunks:- answer = await _synthesise(body.question, chunks)+ # Air-gapped deployments refuse the LLM call; still return the retrieved+ # chunks with no synthesized answer rather than failing the whole query.+ try:+ answer = await _synthesise(body.question, chunks)+ except AirgapViolation:+ answer = Nonesources = list(dict.fromkeys(c.title for c in chunks))return QueryResponse(question=body.question, chunks=chunks, answer=answer, sources=sources)diff --git a/services/api/app/api/v1/endpoints/phishing.py b/services/api/app/api/v1/endpoints/phishing.pyindex fccbb64d4..e54310228 100644--- a/services/api/app/api/v1/endpoints/phishing.py+++ b/services/api/app/api/v1/endpoints/phishing.py@@ -196,16 +196,17 @@ async def submit(body: SubmitRequest, db: DBSession, user: AuthUser) -> Submissisub_id = uuid.uuid4()q = text("""INSERT INTO aisoc_phishing_submissions (- id, submitted_by, artifact_kind, raw_content, sender, subject,+ id, tenant_id, submitted_by, artifact_kind, raw_content, sender, subject,urls, verdict, confidence, indicators, mitre_technique,submitted_at, triaged_at, created_at) VALUES (- :id, :by, :kind, :content, :sender, :subject,+ :id, :tenant_id, :by, :kind, :content, :sender, :subject,:urls::text[], :verdict, :conf, :iocs::jsonb, :mitre,:now, :now, :now) RETURNING *""").bindparams(id=sub_id,+ tenant_id=user.tenant_id,by=str(user) if user else "system",kind=body.artifact_kind,content=body.raw_content,@@ -236,8 +237,8 @@ async def list_submissions(limit: int = Query(50, ge=1, le=500),offset: int = Query(0, ge=0),) -> list[SubmissionResponse]:- 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 verdict:wheres.append("verdict = :verdict")params["verdict"] = verdict@@ -254,7 +255,13 @@ async def list_submissions(@router.get("/{submission_id}", response_model=SubmissionResponse, summary="Get submission")async def get_submission(submission_id: uuid.UUID, db: DBSession, user: AuthUser) -> SubmissionResponse:- row = (await db.execute(text("SELECT * FROM aisoc_phishing_submissions WHERE id = :id").bindparams(id=submission_id))).fetchone()+ row = (+ await db.execute(+ text("SELECT * FROM aisoc_phishing_submissions WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ id=submission_id, tenant_id=user.tenant_id+ )+ )+ ).fetchone()if not row:raise HTTPException(status_code=404, detail="Submission not found.")return _row_to_submission(row)@@ -262,7 +269,13 @@ async def get_submission(submission_id: uuid.UUID, db: DBSession, user: AuthUser@router.post("/{submission_id}/retriage", response_model=SubmissionResponse, summary="Re-run triage on submission")async def retriage(submission_id: uuid.UUID, db: DBSession, user: AuthUser) -> SubmissionResponse:- existing = (await db.execute(text("SELECT * FROM aisoc_phishing_submissions WHERE id = :id").bindparams(id=submission_id))).fetchone()+ existing = (+ await db.execute(+ text("SELECT * FROM aisoc_phishing_submissions WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ id=submission_id, tenant_id=user.tenant_id+ )+ )+ ).fetchone()if not existing:raise HTTPException(status_code=404, detail="Submission not found.")@@ -278,9 +291,10 @@ async def retriage(submission_id: uuid.UUID, db: DBSession, user: AuthUser) -> SUPDATE aisoc_phishing_submissionsSET verdict = :verdict, confidence = :conf, indicators = :iocs::jsonb,mitre_technique = :mitre, triaged_at = :now- WHERE id = :id RETURNING *+ WHERE id = :id AND tenant_id = :tenant_id RETURNING *""").bindparams(id=submission_id,+ tenant_id=user.tenant_id,verdict=result.verdict,conf=result.confidence,iocs=json.dumps(result.indicators),diff --git a/services/api/tests/test_compliance_phishing_kb_tenant_isolation.py b/services/api/tests/test_compliance_phishing_kb_tenant_isolation.pynew file mode 100644index 000000000..b5136ae09--- /dev/null+++ b/services/api/tests/test_compliance_phishing_kb_tenant_isolation.py@@ -0,0 +1,374 @@+"""Tenant-isolation tests for /compliance, /phishing, and /kb endpoints.++These tests verify that every SQL statement in the compliance, phishing,+and knowledge-base endpoints filters on ``tenant_id`` — preventing+cross-tenant data leakage.++Follows the same mock-session pattern used by+``test_alerts_tenant_isolation.py`` and+``test_threat_intel_tenant_isolation.py``.+"""++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++# ────────────────────────────────────────────────────────────────────────────+# Helpers+# ────────────────────────────────────────────────────────────────────────────+++def _user(tenant_id: uuid.UUID | None = None) -> MagicMock:+ """Construct an AuthUser-like object without touching DB or JWT."""+ u = MagicMock()+ u.tenant_id = tenant_id or uuid.uuid4()+ u.user_id = uuid.uuid4()+ u.email = "[email protected]"+ u.__str__ = lambda self: self.email+ return u+++def _mk_db(rows: list[Any]) -> MagicMock:+ """Mock AsyncSession that captures executed SQL and returns queued rows."""+ 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:+ 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.fetchall = MagicMock(return_value=[payload] if payload else [])+ result.fetchone = MagicMock(return_value=payload)+ 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,+ table_name: str,+) -> None:+ """Every executed statement against ``table_name`` must filter on tenant_id."""+ assert executed, "expected at least one DB call"+ saw_tenant_scoped = False+ for sql, params in executed:+ normalized = re.sub(r"\s+", " ", sql).lower()+ if table_name not in normalized:+ continue+ assert "tenant_id" in normalized, f"SQL against {table_name} missing tenant_id filter: {sql}"+ matching = [+ (name, value) for name, value in params.items() if (name == "tenant_id" or name.startswith("tenant_id_")) and value == tenant_id+ ]+ assert matching, f"no bound tenant_id matches caller's tenant in SQL: {sql}; params={params}; expected_tenant={tenant_id}"+ saw_tenant_scoped = True+ assert saw_tenant_scoped, f"no {table_name} statement was tenant-scoped; every read/write must filter on tenant_id"+++def _evidence_row(tenant_id: uuid.UUID, **overrides: Any) -> MagicMock:+ """Build a fake compliance evidence row."""+ now = datetime.now(UTC)+ defaults = {+ "id": uuid.uuid4(),+ "tenant_id": tenant_id,+ "case_id": None,+ "framework": "SOC2",+ "control_id": "CC7.2",+ "control_title": "System Monitoring",+ "evidence_kind": "alert",+ "summary": "Test evidence item",+ "raw_payload": {},+ "payload_hash": "abc123",+ "prev_hash": None,+ "collected_at": now,+ "reviewed_by": None,+ "reviewed_at": None,+ "status": "pending",+ "created_at": now,+ }+ defaults.update(overrides)+ row = MagicMock()+ for k, v in defaults.items():+ setattr(row, k, v)+ return row+++def _phishing_row(tenant_id: uuid.UUID, **overrides: Any) -> MagicMock:+ """Build a fake phishing submission row."""+ now = datetime.now(UTC)+ defaults = {+ "id": uuid.uuid4(),+ "tenant_id": tenant_id,+ "artifact_kind": "email",+ "sender": "[email protected]",+ "subject": "Urgent: Verify your account",+ "urls": ["https://evil.com/phish"],+ "verdict": "phishing",+ "confidence": 0.9,+ "indicators": [{"kind": "url", "value": "https://evil.com/phish"}],+ "mitre_technique": "T1566.001",+ "case_id": None,+ "submitted_at": now,+ "triaged_at": now,+ "raw_content": "Click here to verify",+ }+ defaults.update(overrides)+ row = MagicMock()+ for k, v in defaults.items():+ setattr(row, k, v)+ return row+++def _kb_row(tenant_id: uuid.UUID, **overrides: Any) -> MagicMock:+ """Build a fake KB document row."""+ now = datetime.now(UTC)+ defaults = {+ "id": uuid.uuid4(),+ "tenant_id": tenant_id,+ "title": "Incident Response Runbook",+ "doc_kind": "runbook",+ "source_url": None,+ "content": "Step 1: Contain the threat. " * 20,+ "tags": ["ir", "runbook"],+ "chunk_index": 0,+ "chunk_total": 1,+ "created_at": now,+ "updated_at": now,+ "created_by": "[email protected]",+ }+ defaults.update(overrides)+ row = MagicMock()+ for k, v in defaults.items():+ setattr(row, k, v)+ return row+++# ────────────────────────────────────────────────────────────────────────────+# Compliance endpoint tests+# ────────────────────────────────────────────────────────────────────────────+++class TestComplianceTenantIsolation:+ """All compliance endpoints must scope queries by tenant_id."""++ @pytest.mark.asyncio+ async def test_list_evidence_scopes_by_tenant(self) -> None:+ from app.api.v1.endpoints.compliance import list_evidence++ user = _user()+ row = _evidence_row(user.tenant_id)+ db = _mk_db([[row]])+ result = await list_evidence(db=db, user=user)+ assert len(result) == 1+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_compliance_evidence")++ @pytest.mark.asyncio+ async def test_get_evidence_cross_tenant_returns_404(self) -> None:+ from app.api.v1.endpoints.compliance import get_evidence+ from fastapi import HTTPException++ user = _user()+ db = _mk_db([None]) # No row found for this tenant+ with pytest.raises(HTTPException) as exc:+ await get_evidence(evidence_id=uuid.uuid4(), db=db, user=user)+ assert exc.value.status_code == 404+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_compliance_evidence")++ def test_collect_evidence_sql_includes_tenant_id(self) -> None:+ """The INSERT statement in collect_evidence must include tenant_id.++ We inspect the source rather than calling the function because+ SQLAlchemy's ``text().bindparams()`` cannot resolve PostgreSQL+ cast syntax (``::jsonb``) without a live DB connection.+ """+ import inspect++ from app.api.v1.endpoints.compliance import collect_evidence++ src = inspect.getsource(collect_evidence)+ # The INSERT column list and VALUES list must both mention tenant_id.+ assert "tenant_id" in src, "collect_evidence INSERT must include tenant_id"+ assert "user.tenant_id" in src, "collect_evidence must bind user.tenant_id"++ @pytest.mark.asyncio+ async def test_review_evidence_cross_tenant_returns_404(self) -> None:+ from app.api.v1.endpoints.compliance import ReviewEvidenceRequest, review_evidence+ from fastapi import HTTPException++ user = _user()+ db = _mk_db([None]) # UPDATE returns no row+ body = ReviewEvidenceRequest(decision="accepted")+ with pytest.raises(HTTPException) as exc:+ await review_evidence(evidence_id=uuid.uuid4(), body=body, db=db, user=user)+ assert exc.value.status_code == 404+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_compliance_evidence")++ @pytest.mark.asyncio+ async def test_compliance_report_scopes_by_tenant(self) -> None:+ from app.api.v1.endpoints.compliance import compliance_report++ user = _user()+ db = _mk_db([[]]) # Empty result set+ result = await compliance_report(db=db, user=user, framework=None)+ # Should still return framework entries from FRAMEWORKS dict+ assert isinstance(result, list)+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_compliance_evidence")+++# ────────────────────────────────────────────────────────────────────────────+# Phishing endpoint tests+# ────────────────────────────────────────────────────────────────────────────+++class TestPhishingTenantIsolation:+ """All phishing endpoints must scope queries by tenant_id."""++ @pytest.mark.asyncio+ async def test_list_submissions_scopes_by_tenant(self) -> None:+ from app.api.v1.endpoints.phishing import list_submissions++ user = _user()+ row = _phishing_row(user.tenant_id)+ db = _mk_db([[row]])+ result = await list_submissions(db=db, user=user)+ assert len(result) == 1+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_phishing_submissions")++ @pytest.mark.asyncio+ async def test_get_submission_cross_tenant_returns_404(self) -> None:+ from app.api.v1.endpoints.phishing import get_submission+ from fastapi import HTTPException++ user = _user()+ db = _mk_db([None])+ with pytest.raises(HTTPException) as exc:+ await get_submission(submission_id=uuid.uuid4(), db=db, user=user)+ assert exc.value.status_code == 404+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_phishing_submissions")++ def test_submit_sql_includes_tenant_id(self) -> None:+ """The INSERT statement in submit must include tenant_id.++ SQLAlchemy's ``text().bindparams()`` cannot resolve PostgreSQL+ array cast syntax (``::text[]``) without a live DB connection,+ so we inspect the source instead.+ """+ import inspect++ from app.api.v1.endpoints.phishing import submit++ src = inspect.getsource(submit)+ assert "tenant_id" in src, "submit INSERT must include tenant_id"+ assert "user.tenant_id" in src, "submit must bind user.tenant_id"++ @pytest.mark.asyncio+ async def test_retriage_cross_tenant_returns_404(self) -> None:+ from app.api.v1.endpoints.phishing import retriage+ from fastapi import HTTPException++ user = _user()+ db = _mk_db([None])+ with pytest.raises(HTTPException) as exc:+ await retriage(submission_id=uuid.uuid4(), db=db, user=user)+ assert exc.value.status_code == 404+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_phishing_submissions")+++# ────────────────────────────────────────────────────────────────────────────+# Knowledge Base endpoint tests+# ────────────────────────────────────────────────────────────────────────────+++class TestKnowledgeBaseTenantIsolation:+ """All KB endpoints must scope queries by tenant_id."""++ @pytest.mark.asyncio+ async def test_list_documents_scopes_by_tenant(self) -> None:+ from app.api.v1.endpoints.knowledge_base import list_documents++ user = _user()+ row = _kb_row(user.tenant_id)+ db = _mk_db([[row]])+ result = await list_documents(db=db, user=user)+ assert len(result) == 1+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_kb_documents")++ @pytest.mark.asyncio+ async def test_get_document_cross_tenant_returns_404(self) -> None:+ from app.api.v1.endpoints.knowledge_base import get_document+ from fastapi import HTTPException++ user = _user()+ db = _mk_db([None])+ with pytest.raises(HTTPException) as exc:+ await get_document(doc_id=uuid.uuid4(), db=db, user=user)+ assert exc.value.status_code == 404+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_kb_documents")++ @pytest.mark.asyncio+ async def test_delete_document_cross_tenant_returns_404(self) -> None:+ from app.api.v1.endpoints.knowledge_base import delete_document+ from fastapi import HTTPException++ user = _user()+ db = _mk_db([None])+ with pytest.raises(HTTPException) as exc:+ await delete_document(doc_id=uuid.uuid4(), db=db, user=user)+ assert exc.value.status_code == 404+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_kb_documents")++ @pytest.mark.asyncio+ async def test_delete_document_scopes_delete_by_tenant(self) -> None:+ """DELETE must use WHERE title = :title AND tenant_id = :tenant_id+ to avoid destroying other tenants' documents with the same title."""+ from app.api.v1.endpoints.knowledge_base import delete_document++ user = _user()+ existing = MagicMock()+ existing.title = "Shared Runbook Title"+ db = _mk_db([existing, None]) # SELECT returns row, DELETE returns nothing+ await delete_document(doc_id=uuid.uuid4(), db=db, user=user)++ # The DELETE statement must be tenant-scoped+ delete_stmts = [(sql, params) for sql, params in db.executed if "delete" in re.sub(r"\s+", " ", sql).lower()]+ assert delete_stmts, "expected a DELETE statement"+ for sql, _params in delete_stmts:+ normalized = re.sub(r"\s+", " ", sql).lower()+ assert "tenant_id" in normalized, f"DELETE against aisoc_kb_documents missing tenant_id: {sql}"++ def test_ingest_sql_includes_tenant_id(self) -> None:+ """The INSERT statement in ingest must include tenant_id.++ SQLAlchemy's ``text().bindparams()`` cannot resolve PostgreSQL+ array cast syntax (``::text[]``) without a live DB connection,+ so we inspect the source instead.+ """+ import inspect++ from app.api.v1.endpoints.knowledge_base import ingest++ src = inspect.getsource(ingest)+ assert "tenant_id" in src, "ingest INSERT must include tenant_id"+ assert "user.tenant_id" in src, "ingest must bind user.tenant_id"