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.

security(F013): cross-tenant isolation tests + nightly RBAC regression gate (#197)

Beenu Aroraa99ff4155dee
diff --git a/.github/workflows/cross-tenant-rbac.yml b/.github/workflows/cross-tenant-rbac.yml
new file mode 100644
index 000000000..5e1f34094
--- /dev/null
+++ b/.github/workflows/cross-tenant-rbac.yml
@@ -0,0 +1,188 @@
+name: Cross-tenant RBAC regression (nightly)
+
+# Nightly, isolation-only regression suite for tenant boundary enforcement.
+#
+# Why a dedicated workflow and not just ci.yml?
+#
+# * Tenant isolation bugs are silently catastrophic — one missing
+# ``.where(Model.tenant_id == current_user.tenant_id)`` clause leaks
+# every other tenant's rows under exactly the SQL that "looks normal"
+# to a reviewer. We want a focused, named gate that we can point at
+# when triaging a regression instead of fishing through the 400-line
+# general-purpose Python test job.
+# * The suites are pinned to the endpoint functions directly (no
+# FastAPI request cycle, no live DB) so they're deterministic and
+# cheap. They are safe to re-run on a tight cron without burning
+# significant runner minutes.
+# * `workflow_dispatch` is exposed so a reviewer can trigger the gate
+# before merging a security-sensitive change to RBAC, audit, or any
+# ``app/api/v1/endpoints/*.py`` module.
+#
+# What it gates
+#
+# The three isolation suites verify that, for every read/write/delete
+# endpoint they cover:
+#
+# 1. The SQL issued against the tenant-scoped table includes a
+# ``WHERE tenant_id = :tenant_id`` clause bound to the caller's
+# tenant id (catches "I forgot the .where()" regressions).
+# 2. Writes attach the caller's tenant_id to new rows and ignore any
+# ``tenant_id`` smuggled in via the request payload (catches
+# "trust the JSON" regressions).
+# 3. Cross-tenant reads of a known-other-tenant id resolve to 404,
+# not 200 with another tenant's row (catches forgotten predicate
+# regressions even when the row physically exists in shared
+# storage).
+#
+# The suites are intentionally light on the wire (mocked AsyncSession)
+# so they hold up against ORM churn — the contract is "every endpoint
+# that touches tenant-scoped state must bind tenant_id", and the
+# assertions read the *compiled* SQL bind parameters rather than the
+# shape of any single query.
+
+on:
+ schedule:
+ # 06:30 UTC — runs before compose-smoke-nightly (09:00 UTC) so any
+ # tenant boundary failure shows up as the *first* nightly signal,
+ # not buried under a downstream compose-smoke failure.
+ - cron: '30 6 * * *'
+ workflow_dispatch:
+ inputs:
+ open_issue_on_failure:
+ description: 'Open a tracking issue if the regression suite fails'
+ type: boolean
+ default: true
+
+concurrency:
+ # One nightly run at a time. If a manual dispatch lands on top of a
+ # scheduled one, queue rather than cancel — a security gate failing
+ # silently because it was cancelled is worse than running twice.
+ group: ${{ github.workflow }}
+ cancel-in-progress: false
+
+jobs:
+ cross-tenant-isolation:
+ name: pytest — tenant isolation suites
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+
+ permissions:
+ # Read source. Write issues so we can open a tracking issue on
+ # failure. No package or deployment scopes — this gate must not
+ # be able to write any artifact that ships.
+ contents: read
+ issues: write
+
+ env:
+ # Mirror the dependency set used by `python-test` in ci.yml so the
+ # suites can import the real endpoint modules (which transitively
+ # pull in pydantic, sqlalchemy, structlog, jose, …) without us
+ # having to maintain a parallel pin list here.
+ API_DEPS: >-
+ fastapi "pydantic[email]" pydantic-settings "sqlalchemy[asyncio]" asyncpg
+ structlog "python-jose[cryptography]" "passlib[bcrypt]" tenacity pyyaml
+ prometheus-client "opentelemetry-sdk" "opentelemetry-api"
+ "opentelemetry-exporter-otlp-proto-grpc"
+ "opentelemetry-instrumentation-fastapi"
+ "strawberry-graphql[fastapi]"
+ neo4j redis celery httpx aiofiles email-validator PyJWT
+ "sqlglot>=23,<27" aiosqlite
+ pytest pytest-asyncio
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+
+ - uses: actions/setup-python@v6
+ with:
+ python-version: '3.12'
+ cache: pip
+
+ - name: Install API dependencies
+ run: pip install --quiet ${{ env.API_DEPS }}
+
+ # Mirror the ci.yml env contract: the FastAPI app reads SECRET_KEY
+ # at import time, and the isolation suites import endpoint modules
+ # transitively. These dummy values keep import-time validators
+ # happy on a fresh runner.
+ - name: Run cross-tenant isolation suites
+ id: pytest
+ working-directory: services/api
+ env:
+ ENVIRONMENT: development
+ SECRET_KEY: ci-dummy-secret-key-at-least-32bytes!
+ DATABASE_URL: postgresql+asyncpg://x:x@localhost/x
+ run: |
+ python -m pytest \
+ tests/test_threat_intel_tenant_isolation.py \
+ tests/test_alerts_tenant_isolation.py \
+ tests/test_llm_credentials_tenant_isolation.py \
+ -v --tb=short --maxfail=1 \
+ --junitxml=tenant-isolation.junit.xml
+
+ - name: Upload junit report
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: tenant-isolation-junit-${{ github.run_id }}
+ path: services/api/tenant-isolation.junit.xml
+ retention-days: 30
+ # Don't fail the workflow if pytest failed before the file was
+ # written — the test-run step is the gate, not the artifact.
+ if-no-files-found: ignore
+
+ - name: Record success summary
+ if: success()
+ run: |
+ {
+ echo "## Cross-tenant RBAC regression — green"
+ echo ""
+ echo "All three tenant-isolation suites passed against \`${{ github.sha }}\`."
+ echo ""
+ echo "| suite | role |"
+ echo "|-------|------|"
+ echo "| tests/test_threat_intel_tenant_isolation.py | IOC / actor / feed scoping + write tenant binding |"
+ echo "| tests/test_alerts_tenant_isolation.py | alert list/stats/get/update/escalate/snooze/queue/claim scoping |"
+ echo "| tests/test_llm_credentials_tenant_isolation.py | BYOK credential get/put/delete scoping + audit propagation |"
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Open tracking issue on failure
+ if: failure() && (github.event_name == 'schedule' || github.event.inputs.open_issue_on_failure == 'true')
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ run: |
+ title="Cross-tenant RBAC regression (nightly) failed ($(date -u +%Y-%m-%d))"
+ body=$(cat <<EOF
+ The nightly cross-tenant RBAC regression suite failed on \`main\`.
+
+ **Run:** ${RUN_URL}
+ **Commit:** \`${{ github.sha }}\`
+
+ This gate covers tenant-id binding on every read/write/delete
+ endpoint that touches tenant-scoped state in the API service.
+ A failure here means one of the following — in *descending*
+ order of severity — has regressed:
+
+ * A SELECT lost its \`WHERE tenant_id = :tenant_id\` clause.
+ * A write endpoint started honouring \`tenant_id\` from a
+ client-supplied payload instead of \`current_user.tenant_id\`.
+ * A cross-tenant lookup resolved a row instead of returning 404.
+
+ **Triage:**
+ 1. Open the run, expand the failing test name.
+ 2. Read the assertion message — every isolation assertion
+ quotes the compiled SQL and bound parameters.
+ 3. The endpoint module to inspect is named in the test file
+ (\`app/api/v1/endpoints/{threat_intel,alerts,llm_credentials}.py\`).
+
+ Artifact: \`tenant-isolation-junit-${{ github.run_id }}\` (under
+ the run's Artifacts tab) has the machine-readable JUnit report.
+ EOF
+ )
+ gh issue create \
+ --title "${title}" \
+ --body "${body}" \
+ --label "security" \
+ --label "ci" \
+ || echo "::warning::Failed to open tracking issue"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 12d7bf9f0..37b6adbb4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Cross-tenant RBAC regression suite (F013, security)
+
+Closes [#159](https://github.com/beenuar/AiSOC/issues/159).
+
+Pure-unit isolation suites that exercise the tenant boundary at the
+endpoint-function level (no live DB, no FastAPI request cycle) so the
+contract is testable in milliseconds and survives ORM churn:
+
+- `services/api/tests/test_threat_intel_tenant_isolation.py` — IOC,
+ actor, and feed list/get/create/delete are scoped by `tenant_id`,
+ cross-tenant lookups resolve to 404, and writes attach
+ `current_user.tenant_id` even when the payload smuggles a different
+ one.
+- `services/api/tests/test_alerts_tenant_isolation.py` — every
+ read/write/queue/claim path on `/alerts` binds `tenant_id` into the
+ compiled SQL or forwards it to the service layer
+ (`build_queue` / `claim_alert`).
+- `services/api/tests/test_llm_credentials_tenant_isolation.py` — BYOK
+ credential GET/PUT/DELETE scope by `tenant_id`, new rows bind the
+ caller's tenant, and `emit_audit` is invoked with the caller's
+ tenant + actor (`CredentialVault` is stubbed so the assertions are
+ on the persistence boundary, not crypto).
+
+Assertions read the *compiled* SQL bind parameters rather than the
+shape of any single query so they don't break on benign rewrites. All
+three suites were mutation-tested by temporarily dropping the
+`tenant_id` predicate in the corresponding endpoint — every dropped
+predicate produced at least one failing test, confirming the suites
+are wired to the right surface.
+
+`.github/workflows/cross-tenant-rbac.yml` runs the three suites
+nightly on `main` (06:30 UTC, ahead of `compose-smoke-nightly` so a
+tenant boundary regression shows up as the first nightly signal) and
+on-demand via `workflow_dispatch`. On failure it uploads a JUnit
+report and opens a `security`-labelled tracking issue.
+
### Fix MCP tool count in docs and landing copy (Issue #36)
Closes the documentation-vs-reality drift on the MCP server's tool surface.
diff --git a/services/api/tests/test_alerts_tenant_isolation.py b/services/api/tests/test_alerts_tenant_isolation.py
new file mode 100644
index 000000000..406a83b5f
--- /dev/null
+++ b/services/api/tests/test_alerts_tenant_isolation.py
@@ -0,0 +1,609 @@
+"""Tenant-isolation tests for the /alerts API (Issue #159 / F013).
+
+Sibling of ``test_threat_intel_tenant_isolation.py``,
+``test_cases_tenant_isolation.py`` and ``test_hunts_tenant_isolation.py``:
+call the endpoint functions directly with a mocked
+:class:`AsyncSession` and assert that **every** SQL statement touching
+the ``alerts`` table filters on ``tenant_id`` *and* binds the caller's
+tenant id, and that cross-tenant reads/writes 404 instead of silently
+hitting the wrong row.
+
+These endpoints use the SQLAlchemy ORM (``select(Alert).where(...)``,
+``update(Alert).where(...)``) rather than raw SQL text — that means
+SQLAlchemy generates bound parameter names like ``tenant_id_1`` instead
+of ``tenant_id``. The ``_assert_tenant_scoped`` helper below accepts
+both shapes so the test is robust across the project's mixed ORM/text-
+SQL endpoints.
+
+The contract being protected
+----------------------------
+* No authenticated caller should be able to read another tenant's
+ alert.
+* No authenticated caller should be able to mutate another tenant's
+ alert (cross-tenant PATCH / escalate / snooze must 404, never write
+ through to the wrong row).
+* Service-layer helpers (``build_queue``, ``claim_alert``) must be
+ invoked with the caller's ``tenant_id`` — not anything derived from
+ the request body or URL.
+
+RBAC coverage for these endpoints lives in :mod:`tests.test_alert_queue`
+and :mod:`tests.test_alert_explain`; this file focuses purely on *data
+isolation* once the RBAC gate has passed.
+"""
+
+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 import alerts as alerts_module
+from app.api.v1.endpoints.alerts import (
+ AlertSnoozeRequest,
+ AlertUpdateRequest,
+ escalate_alert,
+ get_alert,
+ get_alert_queue,
+ get_alert_stats,
+ list_alerts,
+ snooze_alert,
+ update_alert,
+)
+from app.api.v1.endpoints.alerts import (
+ claim_alert_endpoint as claim_alert_route,
+)
+from app.models.alert import Alert
+from fastapi import HTTPException
+
+# ────────────────────────────────────────────────────────────────────────────
+# Fixtures / helpers
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def _user(tenant_id: uuid.UUID | None = None) -> CurrentUser:
+ """Construct a CurrentUser without touching the DB or JWT plumbing."""
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=tenant_id or uuid.uuid4(),
+ role="soc_analyst",
+ )
+
+
+def _alert(tenant_id: uuid.UUID, **overrides: Any) -> Alert:
+ """Build an Alert ORM row in memory (no DB) with all required fields.
+
+ Pydantic's ``AlertResponse.model_validate(...)`` walks attributes via
+ ``from_attributes=True``, so the in-memory row must expose every
+ non-Optional field the schema lists. Anything not set explicitly
+ here falls back to a sane default so individual tests stay short.
+ """
+ now = datetime.now(UTC)
+ defaults: dict[str, Any] = {
+ "id": uuid.uuid4(),
+ "tenant_id": tenant_id,
+ "title": "Suspicious login",
+ "description": None,
+ "severity": "high",
+ "status": "new",
+ "priority": 50,
+ "category": None,
+ "mitre_tactics": [],
+ "mitre_techniques": [],
+ "connector_id": None,
+ "connector_type": None,
+ "source_event_ids": [],
+ "ocsf_class_uid": None,
+ "disposition": None,
+ "first_seen_at": None,
+ "ai_score": None,
+ "ai_summary": None,
+ "ai_recommendations": [],
+ "false_positive_score": None,
+ "confidence": None,
+ "confidence_label": None,
+ "confidence_rationale": None,
+ "narrative": None,
+ "affected_ips": [],
+ "affected_hosts": [],
+ "affected_users": [],
+ "affected_assets": [],
+ "case_id": None,
+ "parent_alert_id": None,
+ "child_alert_ids": [],
+ "is_merged": False,
+ "assigned_to_id": None,
+ "assigned_at": None,
+ "snoozed_until": None,
+ "snoozed_by_id": None,
+ "raw_event": {},
+ "enrichment_data": {},
+ "tags": [],
+ "idempotency_key": None,
+ "event_time": now,
+ "first_seen": now,
+ "last_seen": now,
+ "resolved_at": None,
+ "created_at": now,
+ "updated_at": now,
+ }
+ defaults.update(overrides)
+ alert = Alert()
+ for k, v in defaults.items():
+ setattr(alert, k, v)
+ return alert
+
+
+def _mk_db(rows: list[Any]) -> MagicMock:
+ """Mock AsyncSession that returns queued rows one execute() at a time.
+
+ Captures every executed SQL statement and its compiled bind
+ parameters so the assertion helper can verify tenant scoping. ``rows``
+ is the queue of results returned by ``execute()``:
+
+ * a ``list`` payload is served as ``scalars().all()`` (for list
+ endpoints) and also unwraps the first element for ``scalar_one()``
+ / ``scalar_one_or_none()`` callers — needed for the count queries
+ in :func:`list_alerts` and :func:`get_alert_stats`.
+ * an ``int`` payload is served as ``scalar_one()`` — the count
+ queries in :func:`get_alert_stats` use this.
+ * a tuple-list payload (``list[tuple]``) is served as ``result.all()``
+ — the GROUP BY queries in :func:`get_alert_stats` use this.
+ * anything else is served as ``scalar_one_or_none()`` — the
+ single-row reads in :func:`get_alert`, :func:`update_alert`,
+ :func:`escalate_alert`, :func:`snooze_alert` use this.
+ * ``None`` represents "no row" (the cross-tenant 404 path).
+ """
+ db = MagicMock()
+ db.executed: list[tuple[str, dict[str, Any]]] = []
+ db.added: list[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()
+ scalars = MagicMock()
+ if isinstance(payload, list):
+ # Could be a list of ORM rows (list endpoint) OR a list of
+ # tuples (GROUP BY result). Both shapes round-trip cleanly
+ # via the right accessor.
+ scalars.all = MagicMock(return_value=payload)
+ scalars.first = MagicMock(return_value=payload[0] if payload else None)
+ # ``select(func.count())`` returns an int via .scalar_one();
+ # a list[ORM] hands the first row back instead which is fine
+ # for the existence/null checks our list-shape tests run.
+ result.scalar_one = MagicMock(return_value=len(payload))
+ result.scalar_one_or_none = MagicMock(return_value=payload[0] if payload else None)
+ result.all = MagicMock(return_value=payload)
+ elif isinstance(payload, int):
+ result.scalar_one = MagicMock(return_value=payload)
+ result.scalar_one_or_none = MagicMock(return_value=payload)
+ scalars.all = MagicMock(return_value=[])
+ scalars.first = MagicMock(return_value=None)
+ result.all = MagicMock(return_value=[])
+ else:
+ scalars.all = MagicMock(return_value=[payload] if payload else [])
+ scalars.first = MagicMock(return_value=payload)
+ result.scalar_one = MagicMock(return_value=payload)
+ result.scalar_one_or_none = MagicMock(return_value=payload)
+ result.all = MagicMock(return_value=[payload] if payload else [])
+ result.scalars = MagicMock(return_value=scalars)
+ return result
+
+ def _add(obj: Any) -> None:
+ db.added.append(obj)
+
+ db.execute = AsyncMock(side_effect=_execute)
+ db.add = MagicMock(side_effect=_add)
+ db.commit = AsyncMock()
+ db.refresh = 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 against the ``alerts`` table must filter on tenant_id.
+
+ ORM ``select(Alert).where(Alert.tenant_id == ...)`` produces a bound
+ parameter named ``tenant_id_1`` (or ``tenant_id_N``); raw text SQL
+ keeps the literal ``tenant_id`` name. This helper accepts both
+ shapes — what matters is that *some* bound parameter equal to the
+ caller's tenant id appears, and that the SQL string references
+ ``tenant_id``.
+
+ ``UPDATE alerts SET ... WHERE id = :id`` statements that follow a
+ tenant-scoped read are explicitly *allowed* to drop the tenant_id
+ clause from the WHERE — the prior SELECT has already enforced the
+ scope. This mirrors the actual endpoint code in
+ :mod:`app.api.v1.endpoints.alerts`.
+ """
+ assert executed, "expected at least one DB call"
+ saw_tenant_scoped_read = False
+ for sql, params in executed:
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ if "alerts" not in normalized:
+ continue
+ if "tenant_id" in normalized:
+ # A statement that mentions tenant_id must bind the caller's id.
+ 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 parameter matches caller's tenant in SQL: {sql}; " f"params={params}; expected_tenant={tenant_id}"
+ )
+ saw_tenant_scoped_read = True
+ assert saw_tenant_scoped_read, "no alerts statement was tenant-scoped; " "every alerts read/write must mention tenant_id"
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# list_alerts
+# ────────────────────────────────────────────────────────────────────────────
+
+
+# When we call the endpoint functions directly (no FastAPI request cycle),
+# the ``Query(default=...)`` sentinels are not resolved into their plain
+# defaults — so we must pass every query-string argument explicitly. The
+# helper below builds the kwargs the request layer would normally
+# materialise. Tests then override only what they're exercising.
+_LIST_ALERTS_DEFAULTS: dict[str, Any] = {
+ "page": 1,
+ "page_size": 25,
+ "severity": None,
+ "status": None,
+ "category": None,
+ "assigned_to_me": False,
+ "search": None,
+ "min_confidence": None,
+ "confidence_label": None,
+}
+
+
+async def test_list_alerts_scopes_by_tenant() -> None:
+ """Both the count and the SELECT for /alerts must filter on tenant_id."""
+ user = _user()
+ # ``list_alerts`` runs two queries: count (scalar_one int) + select.
+ db = _mk_db([3, [_alert(user.tenant_id), _alert(user.tenant_id), _alert(user.tenant_id)]])
+ response = await list_alerts(current_user=user, db=db, **_LIST_ALERTS_DEFAULTS)
+ assert response.total == 3
+ assert len(response.items) == 3
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_list_alerts_with_filters_keeps_tenant_scope() -> None:
+ """Severity/status/category/min_confidence filters must not relax tenant scope."""
+ user = _user()
+ db = _mk_db([0, []])
+ kwargs = {
+ **_LIST_ALERTS_DEFAULTS,
+ "severity": "critical",
+ "status": "new",
+ "category": "identity",
+ "assigned_to_me": True,
+ "min_confidence": 70,
+ "confidence_label": "high",
+ }
+ await list_alerts(current_user=user, db=db, **kwargs)
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ # Every alerts statement should mention tenant_id (count + select).
+ alerts_stmts = [(sql, params) for sql, params in db.executed if "alerts" in re.sub(r"\s+", " ", sql).lower()]
+ assert len(alerts_stmts) >= 2, "expected count + select to both hit alerts"
+ for sql, _params in alerts_stmts:
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ assert "tenant_id" in normalized, f"alerts statement missing tenant_id: {sql}"
+
+
+async def test_list_alerts_rejects_invalid_confidence_label() -> None:
+ """The 400 for confidence_label must fire before any DB call (cheap input gate)."""
+ user = _user()
+ db = _mk_db([])
+ kwargs = {**_LIST_ALERTS_DEFAULTS, "confidence_label": "urgent"}
+ with pytest.raises(HTTPException) as exc:
+ await list_alerts(current_user=user, db=db, **kwargs)
+ assert exc.value.status_code == 400
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# get_alert_stats
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_get_alert_stats_scopes_every_query_by_tenant() -> None:
+ """All five aggregations in /alerts/stats must filter on tenant_id."""
+ user = _user()
+ # Five queries: total, by_severity (group_by), by_status (group_by),
+ # new_24h (count), critical_open (count). The grouped queries are
+ # served as list[tuple] via result.all(); the count queries via
+ # result.scalar_one().
+ db = _mk_db(
+ [
+ 7, # total
+ [("critical", 3), ("high", 4)], # by_severity
+ [("new", 5), ("triaging", 2)], # by_status
+ 2, # new_last_24h
+ 3, # critical_open
+ ]
+ )
+ resp = await get_alert_stats(current_user=user, db=db)
+ assert resp.total == 7
+ assert resp.by_severity == {"critical": 3, "high": 4}
+ assert resp.by_status == {"new": 5, "triaging": 2}
+ assert resp.new_last_24h == 2
+ assert resp.critical_open == 3
+ # The 5 SQL statements all touch ``alerts`` and must bind tenant_id.
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ assert len(db.executed) == 5
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# get_alert (single)
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_get_alert_cross_tenant_returns_404() -> None:
+ """An alert owned by tenant B must 404 for tenant A even when the UUID matches.
+
+ The endpoint runs a *single* ``SELECT alert WHERE id = ? AND tenant_id = ?``;
+ if the row exists in tenant B but not in tenant A, the SELECT returns
+ ``None`` and the 404 fires before the rail envelope is ever built.
+ """
+ tenant_a = _user()
+ tenant_b_alert = _alert(uuid.uuid4())
+ # SELECT scoped by (id, tenant=A) returns nothing.
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await get_alert(alert_id=tenant_b_alert.id, current_user=tenant_a, db=db)
+ assert exc.value.status_code == 404
+ _assert_tenant_scoped(db.executed, tenant_a.tenant_id)
+
+
+async def test_get_alert_missing_returns_404() -> None:
+ """A non-existent alert returns 404 (not 500)."""
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await get_alert(alert_id=uuid.uuid4(), current_user=user, db=db)
+ assert exc.value.status_code == 404
+
+
+async def test_get_alert_same_tenant_returns_row(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Same-tenant read returns the alert (positive control with rail mocked)."""
+ user = _user()
+ alert = _alert(user.tenant_id, narrative="already filled") # skip lazy-fill branch.
+ db = _mk_db([alert])
+
+ # The rail envelope hits the audit log; stub it for this isolation
+ # test — the rail's own DB scope is covered by its dedicated tests.
+ fake_envelope = MagicMock(related_entities=[], mini_timeline=[], recommended_actions=[])
+ monkeypatch.setattr(alerts_module, "build_rail_envelope", AsyncMock(return_value=fake_envelope))
+
+ result = await get_alert(alert_id=alert.id, current_user=user, db=db)
+ assert result.id == alert.id
+ assert result.tenant_id == user.tenant_id
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# update_alert
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_update_alert_cross_tenant_returns_404() -> None:
+ """PATCH against an alert in another tenant must 404 and write nothing."""
+ tenant_a = _user()
+ tenant_b_alert = _alert(uuid.uuid4())
+ db = _mk_db([None]) # SELECT scoped to tenant A returns no row.
+ with pytest.raises(HTTPException) as exc:
+ await update_alert(
+ alert_id=tenant_b_alert.id,
+ request=AlertUpdateRequest(status="closed"),
+ current_user=tenant_a,
+ db=db,
+ )
+ assert exc.value.status_code == 404
+ # Critical: no UPDATE statement should have run.
+ update_stmts = [sql for sql, _params in db.executed if "update " in re.sub(r"\s+", " ", sql).lower()]
+ assert not update_stmts, "cross-tenant PATCH leaked an UPDATE through"
+
+
+async def test_update_alert_same_tenant_scopes_select() -> None:
+ """PATCH against your own alert: SELECT must scope by tenant before UPDATE."""
+ user = _user()
+ alert = _alert(user.tenant_id)
+ db = _mk_db([alert, None]) # SELECT returns row, UPDATE returns nothing.
+ resp = await update_alert(
+ alert_id=alert.id,
+ request=AlertUpdateRequest(status="resolved", tags=["triaged"]),
+ current_user=user,
+ db=db,
+ )
+ assert resp.id == alert.id
+ # The SELECT must be tenant-scoped. The UPDATE-by-id WHERE clause
+ # is allowed to drop the tenant filter because the prior SELECT
+ # enforced it.
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# escalate_alert
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_escalate_alert_cross_tenant_returns_404() -> None:
+ """Escalating another tenant's alert must 404 and never raise severity."""
+ tenant_a = _user()
+ tenant_b_alert = _alert(uuid.uuid4(), severity="medium")
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await escalate_alert(alert_id=tenant_b_alert.id, current_user=tenant_a, db=db)
+ assert exc.value.status_code == 404
+ update_stmts = [sql for sql, _params in db.executed if "update " in re.sub(r"\s+", " ", sql).lower()]
+ assert not update_stmts, "cross-tenant escalate leaked an UPDATE through"
+
+
+async def test_escalate_alert_same_tenant_scopes_select() -> None:
+ """Same-tenant escalate: the bounding SELECT must include tenant_id."""
+ user = _user()
+ alert = _alert(user.tenant_id, severity="medium")
+ db = _mk_db([alert, None])
+ resp = await escalate_alert(alert_id=alert.id, current_user=user, db=db)
+ assert resp.id == alert.id
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# snooze_alert
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_snooze_alert_cross_tenant_returns_404() -> None:
+ """Snoozing another tenant's alert must 404 and never write snoozed_until."""
+ tenant_a = _user()
+ tenant_b_alert = _alert(uuid.uuid4())
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await snooze_alert(
+ alert_id=tenant_b_alert.id,
+ body=AlertSnoozeRequest(duration_minutes=60),
+ current_user=tenant_a,
+ db=db,
+ )
+ assert exc.value.status_code == 404
+ update_stmts = [sql for sql, _params in db.executed if "update " in re.sub(r"\s+", " ", sql).lower()]
+ assert not update_stmts, "cross-tenant snooze leaked an UPDATE through"
+
+
+async def test_snooze_alert_requires_duration_or_until() -> None:
+ """The 400 for "no window supplied" must fire before any DB call."""
+ user = _user()
+ db = _mk_db([])
+ with pytest.raises(HTTPException) as exc:
+ await snooze_alert(
+ alert_id=uuid.uuid4(),
+ body=AlertSnoozeRequest(),
+ current_user=user,
+ db=db,
+ )
+ assert exc.value.status_code == 400
+
+
+async def test_snooze_alert_same_tenant_scopes_select() -> None:
+ """Same-tenant snooze: the bounding SELECT must include tenant_id."""
+ user = _user()
+ alert = _alert(user.tenant_id)
+ db = _mk_db([alert, None])
+ resp = await snooze_alert(
+ alert_id=alert.id,
+ body=AlertSnoozeRequest(duration_minutes=30),
+ current_user=user,
+ db=db,
+ )
+ assert resp.id == alert.id
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# /alerts/queue and /alerts/{id}/claim — delegate to service helpers
+# ────────────────────────────────────────────────────────────────────────────
+#
+# These endpoints don't issue tenant-scoped SQL themselves; they pass
+# ``current_user.tenant_id`` into service helpers (``build_queue``,
+# ``claim_alert``) which do. The contract we lock down here is that
+# **the endpoint passes the caller's tenant id, not anything else**.
+# The helpers themselves are tested in :mod:`tests.test_alert_queue`.
+
+
+async def test_get_alert_queue_passes_caller_tenant_id(monkeypatch: pytest.MonkeyPatch) -> None:
+ user = _user()
+ db = _mk_db([])
+ captured: dict[str, Any] = {}
+
+ async def _fake_build_queue(db_arg: Any, *, tenant_id: uuid.UUID, user_id: uuid.UUID, **kwargs: Any) -> Any:
+ captured["tenant_id"] = tenant_id
+ captured["user_id"] = user_id
+ captured["kwargs"] = kwargs
+ return MagicMock(items=[], counts=MagicMock(), page=1, page_size=50)
+
+ monkeypatch.setattr(alerts_module, "build_queue", _fake_build_queue)
+
+ # As with list_alerts, the Query(default=...) sentinels don't resolve
+ # when we call the endpoint function directly — pass the defaults
+ # explicitly to mirror what FastAPI would inject.
+ await get_alert_queue(
+ current_user=user,
+ db=db,
+ owner="all",
+ period="all",
+ page=1,
+ page_size=50,
+ )
+ assert captured["tenant_id"] == user.tenant_id, "queue endpoint forwarded the wrong tenant_id to the service helper"
+ assert captured["user_id"] == user.user_id
+
+
+async def test_claim_alert_passes_caller_tenant_id(monkeypatch: pytest.MonkeyPatch) -> None:
+ user = _user()
+ db = _mk_db([])
+ alert = _alert(user.tenant_id)
+ captured: dict[str, Any] = {}
+
+ async def _fake_claim_alert(db_arg: Any, *, alert_id: uuid.UUID, tenant_id: uuid.UUID, user_id: uuid.UUID) -> Any:
+ captured["alert_id"] = alert_id
+ captured["tenant_id"] = tenant_id
+ captured["user_id"] = user_id
+ return alert
+
+ monkeypatch.setattr(alerts_module, "claim_alert", _fake_claim_alert)
+
+ resp = await claim_alert_route(alert_id=alert.id, current_user=user, db=db)
+ assert resp.id == alert.id
+ assert captured["tenant_id"] == user.tenant_id, "claim endpoint forwarded the wrong tenant_id to the service helper"
+ assert captured["user_id"] == user.user_id
+ assert captured["alert_id"] == alert.id
+
+
+async def test_claim_alert_propagates_not_found_as_404(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Service-layer AlertNotFoundError (incl. cross-tenant lookups) → 404."""
+ user = _user()
+ db = _mk_db([])
+ target_id = uuid.uuid4()
+
+ async def _raises_not_found(*args: Any, **kwargs: Any) -> Any:
+ raise alerts_module.AlertNotFoundError(str(target_id))
+
+ monkeypatch.setattr(alerts_module, "claim_alert", _raises_not_found)
+
+ with pytest.raises(HTTPException) as exc:
+ await claim_alert_route(alert_id=target_id, current_user=user, db=db)
+ assert exc.value.status_code == 404
diff --git a/services/api/tests/test_llm_credentials_tenant_isolation.py b/services/api/tests/test_llm_credentials_tenant_isolation.py
new file mode 100644
index 000000000..9fe4989f1
--- /dev/null
+++ b/services/api/tests/test_llm_credentials_tenant_isolation.py
@@ -0,0 +1,351 @@
+"""Tenant-isolation tests for /api/v1/llm/credentials (Issue #159 / F013).
+
+Sibling of ``test_threat_intel_tenant_isolation.py`` and
+``test_alerts_tenant_isolation.py``: call the endpoint functions directly
+with a mocked :class:`AsyncSession` and assert that every SQL statement
+touching ``tenant_llm_credentials`` filters on ``tenant_id`` *and* binds
+the caller's tenant id, and that writes always carry the caller's
+tenant id (never allow caller-supplied ``tenant_id`` to override).
+
+This endpoint is unusual in that ``tenant_id`` is the *primary key* of
+``tenant_llm_credentials`` — there is one row per tenant. That makes
+tenant isolation an even tighter contract: a cross-tenant read must
+never resolve the other tenant's row even if no other rows exist, and a
+PUT must never overwrite the other tenant's ciphertext.
+
+The vault (``get_vault().encrypt(...)``) and the audit emitter
+(``emit_audit(...)``) are dependencies we mock out so the test stays
+focused on the SQL boundary — exhaustive vault / audit tests live
+elsewhere.
+
+The contract being protected
+----------------------------
+* GET resolves only the caller's row (returns ``None`` rather than
+ leaking another tenant's record).
+* PUT (upsert) issues a tenant-scoped SELECT, and any new row attached
+ to the session carries the caller's ``tenant_id`` (never one taken
+ from a payload or query string).
+* DELETE issues a tenant-scoped SELECT + DELETE so a hostile or buggy
+ caller cannot delete another tenant's credential.
+* The audit row recorded for PUT / DELETE carries the caller's
+ ``tenant_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 import deps as deps_module
+from app.api.v1.deps import CurrentUser
+from app.api.v1.endpoints import llm_credentials as llm_credentials_module
+from app.api.v1.endpoints.llm_credentials import (
+ LlmCredentialUpsert,
+ delete_llm_credential,
+ get_llm_credential,
+ upsert_llm_credential,
+)
+from app.models.llm_credential import TenantLlmCredential
+from pytest import MonkeyPatch
+
+# ────────────────────────────────────────────────────────────────────────────
+# Fixtures / helpers
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def _user(tenant_id: uuid.UUID | None = None) -> CurrentUser:
+ """Construct a CurrentUser without touching DB / JWT plumbing."""
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=tenant_id or uuid.uuid4(),
+ role="tenant_admin",
+ )
+
+
+def _credential(tenant_id: uuid.UUID, **overrides: Any) -> TenantLlmCredential:
+ """Build a TenantLlmCredential ORM row in memory (no DB)."""
+ now = datetime.now(UTC)
+ defaults: dict[str, Any] = {
+ "tenant_id": tenant_id,
+ "provider": "openai",
+ "base_url": None,
+ "model": "gpt-4o-mini",
+ "api_key_vault": "vault:v1:cGxhY2Vob2xkZXI=",
+ "settings": {},
+ "enabled": True,
+ "created_at": now,
+ "updated_at": now,
+ "last_rotated_at": now,
+ }
+ defaults.update(overrides)
+ row = TenantLlmCredential()
+ for k, v in defaults.items():
+ setattr(row, k, v)
+ return row
+
+
+def _mk_db(rows: list[Any]) -> MagicMock:
+ """Mock AsyncSession that captures SQL + binds and replays queued rows.
+
+ Mirrors the helper used by the threat-intel + alerts isolation tests.
+ """
+ db = MagicMock()
+ db.executed: list[tuple[str, dict[str, Any]]] = []
+ db.added: list[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()
+ scalars = MagicMock()
+ if isinstance(payload, list):
+ scalars.all = MagicMock(return_value=payload)
+ scalars.first = MagicMock(return_value=payload[0] if payload else None)
+ result.scalar_one_or_none = MagicMock(return_value=payload[0] if payload else None)
+ else:
+ scalars.all = MagicMock(return_value=[payload] if payload else [])
+ scalars.first = MagicMock(return_value=payload)
+ result.scalar_one_or_none = MagicMock(return_value=payload)
+ result.scalars = MagicMock(return_value=scalars)
+ return result
+
+ def _add(obj: Any) -> None:
+ db.added.append(obj)
+
+ db.execute = AsyncMock(side_effect=_execute)
+ db.add = MagicMock(side_effect=_add)
+ db.commit = AsyncMock()
+ db.refresh = AsyncMock()
+ db.rollback = AsyncMock()
+ return db
+
+
+def _assert_tenant_scoped(executed: list[tuple[str, dict[str, Any]]], tenant_id: uuid.UUID) -> None:
+ """Every SQL statement against ``tenant_llm_credentials`` must bind caller's tenant_id."""
+ assert executed, "expected at least one DB call"
+ saw_credentials_query = False
+ for sql, params in executed:
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ if "tenant_llm_credentials" not in normalized:
+ continue
+ saw_credentials_query = True
+ assert "tenant_id" in normalized, f"tenant_id missing from SQL: {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 parameter matches caller's tenant in SQL: {sql}; " f"params={params}; expected_tenant={tenant_id}"
+ )
+ assert saw_credentials_query, "expected at least one query against tenant_llm_credentials"
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Shared monkey-patches: vault + audit are noise for isolation tests
+# ────────────────────────────────────────────────────────────────────────────
+
+
[email protected](autouse=True)
+def _stub_vault_and_audit(monkeypatch: MonkeyPatch) -> None:
+ """Replace the vault + audit emitter with deterministic stubs.
+
+ The vault stub returns a fixed ciphertext so we can assert the row
+ attached to the session carries the encrypted value (rather than
+ plaintext) without depending on the real CredentialVault config /
+ env vars. The audit stub captures the kwargs it was called with so
+ individual tests can assert ``tenant_id`` propagation.
+ """
+
+ fake_vault = MagicMock()
+ fake_vault.encrypt = MagicMock(return_value="vault:v1:ZmFrZQ==")
+ monkeypatch.setattr(llm_credentials_module, "get_vault", lambda: fake_vault)
+
+ async def _fake_emit_audit(**kwargs: Any) -> None:
+ # Record into module-level list so tests can inspect.
+ _AUDIT_CAPTURE.append(kwargs)
+
+ monkeypatch.setattr(llm_credentials_module, "emit_audit", _fake_emit_audit)
+ _AUDIT_CAPTURE.clear()
+
+
+_AUDIT_CAPTURE: list[dict[str, Any]] = []
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# GET /llm/credentials
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_get_credential_scopes_by_tenant() -> None:
+ """The SELECT for GET must bind current_user.tenant_id."""
+ user = _user()
+ db = _mk_db([_credential(user.tenant_id)])
+ result = await get_llm_credential(current_user=user, db=db)
+ assert result is not None
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_get_credential_returns_none_when_caller_has_no_row() -> None:
+ """GET returns None (not 404) when no credential exists for the caller."""
+ user = _user()
+ db = _mk_db([None])
+ result = await get_llm_credential(current_user=user, db=db)
+ assert result is None
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_get_credential_does_not_leak_another_tenants_row() -> None:
+ """If the DB only has tenant B's row, tenant A's GET must resolve None.
+
+ We model this by having the mock return ``None`` for the caller's
+ scoped query — what we're actually verifying is that the endpoint
+ *issues the scoped query* (so a real DB would return None on its
+ own), rather than blindly returning whatever ``scalar_one_or_none``
+ surfaces.
+ """
+ tenant_a = _user()
+ db = _mk_db([None]) # scoped query for tenant A finds nothing
+ result = await get_llm_credential(current_user=tenant_a, db=db)
+ assert result is None
+ _assert_tenant_scoped(db.executed, tenant_a.tenant_id)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# PUT /llm/credentials (upsert)
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def _request_stub() -> Any:
+ """A minimal Request stand-in for emit_audit (we've stubbed it anyway)."""
+ req = MagicMock()
+ req.client = MagicMock()
+ req.client.host = "127.0.0.1"
+ req.headers = {}
+ return req
+
+
+async def test_upsert_credential_scopes_existing_lookup_by_tenant() -> None:
+ """The initial SELECT-for-existing must bind current_user.tenant_id."""
+ user = _user()
+ # ``None`` -> no existing row, so the upsert branch creates a new row.
+ db = _mk_db([None])
+ payload = LlmCredentialUpsert(provider="openai", api_key="sk-secret-test")
+ result = await upsert_llm_credential(payload=payload, request=_request_stub(), current_user=user, db=db)
+ assert result.provider == "openai"
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_upsert_credential_create_attaches_caller_tenant() -> None:
+ """The newly-created row attached to the session must carry caller's tenant_id."""
+ user = _user()
+ db = _mk_db([None])
+ payload = LlmCredentialUpsert(provider="openai", api_key="sk-secret-test")
+ await upsert_llm_credential(payload=payload, request=_request_stub(), current_user=user, db=db)
+ assert len(db.added) == 1, "exactly one new row should have been attached"
+ new_row = db.added[0]
+ assert isinstance(new_row, TenantLlmCredential)
+ assert new_row.tenant_id == user.tenant_id, "new TenantLlmCredential row must carry caller's tenant_id, not a payload-supplied one"
+ # Confirm we stored the ciphertext from the vault, not the plaintext.
+ assert new_row.api_key_vault == "vault:v1:ZmFrZQ=="
+ assert new_row.api_key_vault != "sk-secret-test"
+
+
+async def test_upsert_credential_update_preserves_caller_tenant() -> None:
+ """Updating an existing row must never mutate ``tenant_id`` to anything else."""
+ user = _user()
+ existing = _credential(user.tenant_id, provider="anthropic")
+ db = _mk_db([existing]) # SELECT returns caller's existing row.
+ payload = LlmCredentialUpsert(provider="openai", api_key="sk-rotation-test")
+ await upsert_llm_credential(payload=payload, request=_request_stub(), current_user=user, db=db)
+ # The endpoint mutates the existing row in place; tenant_id must not move.
+ assert existing.tenant_id == user.tenant_id, "update path must not rebind tenant_id"
+ # And it should not have added a brand-new row.
+ assert db.added == [], "update path must not insert a duplicate"
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_upsert_credential_audit_carries_caller_tenant() -> None:
+ """The audit row emitted on PUT must use current_user.tenant_id."""
+ user = _user()
+ db = _mk_db([None])
+ payload = LlmCredentialUpsert(provider="openai", api_key="sk-secret-test")
+ await upsert_llm_credential(payload=payload, request=_request_stub(), current_user=user, db=db)
+ assert _AUDIT_CAPTURE, "expected emit_audit to be called on PUT"
+ last = _AUDIT_CAPTURE[-1]
+ assert last["tenant_id"] == user.tenant_id
+ assert last["actor_id"] == user.user_id
+ assert last["action"] == "settings.llm.upsert"
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# DELETE /llm/credentials
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_delete_credential_scopes_select_and_delete_by_tenant() -> None:
+ """Both the existence SELECT and the DELETE statement must bind tenant_id."""
+ user = _user()
+ db = _mk_db([_credential(user.tenant_id)])
+ await delete_llm_credential(request=_request_stub(), current_user=user, db=db)
+ # Two statements: SELECT + DELETE, both tenant-scoped.
+ assert len(db.executed) == 2, f"expected SELECT + DELETE, got {len(db.executed)}: {db.executed}"
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+ # Belt-and-braces: confirm the second statement is a DELETE.
+ delete_sql, _ = db.executed[1]
+ normalized = re.sub(r"\s+", " ", delete_sql).lower()
+ assert normalized.startswith(
+ "delete from tenant_llm_credentials"
+ ), f"second statement must be a DELETE FROM tenant_llm_credentials: {delete_sql}"
+
+
+async def test_delete_credential_idempotent_when_row_missing() -> None:
+ """DELETE is a no-op when no row exists; still scoped by tenant_id, still does not audit."""
+ user = _user()
+ db = _mk_db([None]) # SELECT finds nothing
+ result = await delete_llm_credential(request=_request_stub(), current_user=user, db=db)
+ assert result is None
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ # No audit row for a missing-row DELETE — by design.
+ assert _AUDIT_CAPTURE == []
+
+
+async def test_delete_credential_audit_carries_caller_tenant() -> None:
+ """The audit row emitted on a real DELETE must use current_user.tenant_id."""
+ user = _user()
+ existing = _credential(user.tenant_id)
+ db = _mk_db([existing])
+ await delete_llm_credential(request=_request_stub(), current_user=user, db=db)
+ assert _AUDIT_CAPTURE, "expected emit_audit to be called for a real DELETE"
+ last = _AUDIT_CAPTURE[-1]
+ assert last["tenant_id"] == user.tenant_id
+ assert last["actor_id"] == user.user_id
+ assert last["action"] == "settings.llm.delete"
+
+
+# Defensive: keep ``deps_module`` import live so static checkers don't drop it
+# if we later need to inject ``require_permission`` overrides here.
+assert deps_module is not None
diff --git a/services/api/tests/test_threat_intel_tenant_isolation.py b/services/api/tests/test_threat_intel_tenant_isolation.py
new file mode 100644
index 000000000..bf35beca4
--- /dev/null
+++ b/services/api/tests/test_threat_intel_tenant_isolation.py
@@ -0,0 +1,466 @@
+"""Tenant-isolation tests for the /threat-intel API (Issue #159 / F013).
+
+Sibling of ``test_cases_tenant_isolation.py`` and
+``test_hunts_tenant_isolation.py``: call the endpoint functions directly
+with a mocked :class:`AsyncSession` and assert that **every** SQL
+statement touching ``threat_intel_iocs``, ``threat_actors`` or
+``threat_intel_feeds`` filters on ``tenant_id`` *and* binds the caller's
+tenant id, and that cross-tenant reads/writes either 404 or write under
+the caller's tenant id (never the other tenant's).
+
+These endpoints use the SQLAlchemy ORM (``select(Model).where(...)``)
+rather than raw SQL text — that means SQLAlchemy generates bound
+parameter names like ``tenant_id_1`` instead of ``tenant_id``. The
+``_assert_tenant_scoped`` helper below accepts both shapes so the test
+is robust across the project's mixed ORM/text-SQL endpoints.
+
+The contract being protected
+----------------------------
+* No authenticated caller should be able to read another tenant's
+ IOC / actor / feed.
+* No authenticated caller should be able to delete another tenant's
+ IOC / actor / feed (cross-tenant DELETE must 404, not silently
+ succeed against the wrong row).
+* Writes (POST) must always carry the caller's tenant id — never
+ allow caller-supplied ``tenant_id`` to override.
+
+RBAC coverage lives in :mod:`tests.test_threat_intel_rbac`; this file
+focuses purely on *data isolation* once the RBAC gate has passed.
+"""
+
+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.threat_intel import (
+ FeedCreate,
+ IOCCreate,
+ ThreatActorCreate,
+ create_actor,
+ create_feed,
+ create_ioc,
+ delete_feed,
+ delete_ioc,
+ get_ioc,
+ list_actors,
+ list_feeds,
+ list_iocs,
+)
+from app.models.threat_intel import ThreatActor, ThreatIntelFeed, ThreatIntelIOC
+from fastapi import HTTPException
+
+# ────────────────────────────────────────────────────────────────────────────
+# Fixtures / helpers
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def _user(tenant_id: uuid.UUID | None = None) -> CurrentUser:
+ """Construct a CurrentUser without touching the DB or JWT plumbing."""
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=tenant_id or uuid.uuid4(),
+ role="threat_hunter",
+ )
+
+
+def _ioc(tenant_id: uuid.UUID, **overrides: Any) -> ThreatIntelIOC:
+ """Build a ThreatIntelIOC ORM row in memory (no DB)."""
+ defaults: dict[str, Any] = {
+ "id": uuid.uuid4(),
+ "tenant_id": tenant_id,
+ "ioc_type": "domain",
+ "value": "evil.example.com",
+ "confidence": 80,
+ "severity": "high",
+ "tlp": "amber",
+ "source": "internal",
+ "is_active": True,
+ "false_positive": False,
+ "context": {},
+ "first_seen": datetime.now(UTC),
+ "last_seen": datetime.now(UTC),
+ "created_at": datetime.now(UTC),
+ "updated_at": datetime.now(UTC),
+ }
+ defaults.update(overrides)
+ ioc = ThreatIntelIOC()
+ for k, v in defaults.items():
+ setattr(ioc, k, v)
+ return ioc
+
+
+def _actor(tenant_id: uuid.UUID, **overrides: Any) -> ThreatActor:
+ defaults: dict[str, Any] = {
+ "id": uuid.uuid4(),
+ "tenant_id": tenant_id,
+ "name": "APT-Example",
+ "is_active": True,
+ "context": {},
+ "created_at": datetime.now(UTC),
+ "updated_at": datetime.now(UTC),
+ }
+ defaults.update(overrides)
+ actor = ThreatActor()
+ for k, v in defaults.items():
+ setattr(actor, k, v)
+ return actor
+
+
+def _feed(tenant_id: uuid.UUID, **overrides: Any) -> ThreatIntelFeed:
+ defaults: dict[str, Any] = {
+ "id": uuid.uuid4(),
+ "tenant_id": tenant_id,
+ "name": "internal-feed",
+ "feed_type": "stix",
+ "poll_interval": 3600,
+ "is_enabled": True,
+ "config": {},
+ "created_at": datetime.now(UTC),
+ }
+ defaults.update(overrides)
+ feed = ThreatIntelFeed()
+ for k, v in defaults.items():
+ setattr(feed, k, v)
+ return feed
+
+
+def _mk_db(rows: list[Any]) -> MagicMock:
+ """Mock AsyncSession that returns queued rows one execute() at a time.
+
+ Captures every executed SQL statement and its compiled bind
+ parameters so the assertion helper can verify tenant scoping. ``rows``
+ is the queue of results returned by ``execute()`` — list values are
+ treated as ``scalars().all()`` payloads, scalar values as
+ ``scalar_one_or_none()`` payloads, and ``None`` as "no row".
+
+ Also tracks every object passed to ``db.add()`` so we can assert
+ INSERTs carry the caller's tenant_id (ORM ``db.add(...)`` doesn't
+ issue SQL until flush, so we can't capture it from ``execute()``).
+ """
+ db = MagicMock()
+ db.executed: list[tuple[str, dict[str, Any]]] = []
+ db.added: list[Any] = []
+ db.deleted: list[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()
+ scalars = MagicMock()
+ if isinstance(payload, list):
+ scalars.all = MagicMock(return_value=payload)
+ scalars.first = MagicMock(return_value=payload[0] if payload else None)
+ result.scalar_one_or_none = MagicMock(return_value=payload[0] if payload else None)
+ else:
+ scalars.all = MagicMock(return_value=[payload] if payload else [])
+ scalars.first = MagicMock(return_value=payload)
+ result.scalar_one_or_none = MagicMock(return_value=payload)
+ result.scalars = MagicMock(return_value=scalars)
+ return result
+
+ async def _get(model: Any, pk: Any) -> Any:
+ # Used by GET/DELETE endpoints that call ``await db.get(Model, id)``.
+ # We capture the lookup so the assertion helper can confirm it
+ # happened, and pop the next queued row.
+ try:
+ payload = next(iterator)
+ except StopIteration:
+ payload = None
+ db.executed.append((f"GET {model.__tablename__} id={pk}", {"pk": pk}))
+ return payload
+
+ def _add(obj: Any) -> None:
+ db.added.append(obj)
+
+ async def _delete(obj: Any) -> None:
+ db.deleted.append(obj)
+
+ db.execute = AsyncMock(side_effect=_execute)
+ db.get = AsyncMock(side_effect=_get)
+ db.add = MagicMock(side_effect=_add)
+ db.delete = AsyncMock(side_effect=_delete)
+ db.commit = AsyncMock()
+ db.refresh = AsyncMock()
+ db.rollback = AsyncMock()
+ return db
+
+
+_TENANT_TABLES = ("threat_intel_iocs", "threat_actors", "threat_intel_feeds")
+
+
+def _assert_tenant_scoped(executed: list[tuple[str, dict[str, Any]]], tenant_id: uuid.UUID) -> None:
+ """Every executed SELECT against a tenant-owned table must filter on tenant_id.
+
+ ORM ``select(Model).where(Model.tenant_id == ...)`` produces a bound
+ parameter that SQLAlchemy names ``tenant_id_1`` (or
+ ``tenant_id_N`` if there are multiple). Raw text SQL with
+ ``:tenant_id`` keeps that literal name. This helper accepts both
+ shapes — what matters is that *some* bound parameter equal to the
+ caller's tenant id appears, and that the SQL string references
+ ``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}"
+ # Find any bound parameter whose value matches the caller's
+ # tenant_id. ORM uses tenant_id_1, text SQL uses tenant_id.
+ 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 parameter matches caller's tenant in SQL: {sql}; " f"params={params}; expected_tenant={tenant_id}"
+ )
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# IOC endpoints — list / get / create / delete
+# ────────────────────────────────────────────────────────────────────────────
+
+
+# NOTE on signatures: ``list_iocs`` and friends declare ``limit``/``offset``
+# with ``fastapi.Query(...)`` defaults. Those defaults only resolve to real
+# ints inside a real FastAPI request; called directly from a test, they're
+# ``Query`` objects which trip SQLAlchemy's ``int()`` coercion in
+# ``.limit(...)``. So we always pass explicit ``limit`` / ``offset`` ints.
+
+
+async def test_list_iocs_scopes_by_tenant() -> None:
+ """SELECT for /iocs must include tenant_id = current_user.tenant_id."""
+ user = _user()
+ db = _mk_db([[_ioc(user.tenant_id), _ioc(user.tenant_id)]])
+ result = await list_iocs(current_user=user, db=db, limit=50, offset=0)
+ assert len(result) == 2
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_list_iocs_with_filters_keeps_tenant_scope() -> None:
+ """Adding ioc_type/severity filters does not relax the tenant filter."""
+ user = _user()
+ db = _mk_db([[]])
+ await list_iocs(
+ current_user=user,
+ db=db,
+ ioc_type="domain",
+ severity="high",
+ is_active=True,
+ limit=50,
+ offset=0,
+ )
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+ sql, _params = db.executed[0]
+ normalized = re.sub(r"\s+", " ", sql).lower()
+ assert "threat_intel_iocs" in normalized
+ assert "ioc_type" in normalized
+ assert "severity" in normalized
+
+
+async def test_get_ioc_cross_tenant_returns_404() -> None:
+ """An IOC owned by tenant B must 404 for tenant A even when the UUID matches."""
+ tenant_a = _user()
+ tenant_b_id = uuid.uuid4()
+ other_tenant_ioc = _ioc(tenant_b_id)
+ db = _mk_db([other_tenant_ioc]) # ``db.get`` will return tenant B's row.
+ with pytest.raises(HTTPException) as exc:
+ await get_ioc(ioc_id=other_tenant_ioc.id, current_user=tenant_a, db=db)
+ assert exc.value.status_code == 404
+ # Sanity: the db.get call was issued (so the tenant-id post-check
+ # is the only thing preventing the cross-tenant read).
+ assert db.executed and db.executed[0][0].startswith("GET threat_intel_iocs")
+
+
+async def test_get_ioc_missing_returns_404() -> None:
+ """A non-existent IOC also 404s (not 500)."""
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await get_ioc(ioc_id=uuid.uuid4(), current_user=user, db=db)
+ assert exc.value.status_code == 404
+
+
+async def test_get_ioc_same_tenant_returns_row() -> None:
+ """Same-tenant read returns the row (positive control)."""
+ user = _user()
+ ioc = _ioc(user.tenant_id)
+ db = _mk_db([ioc])
+ result = await get_ioc(ioc_id=ioc.id, current_user=user, db=db)
+ assert result is ioc
+
+
+async def test_create_ioc_binds_caller_tenant_id() -> None:
+ """Newly-created IOCs carry the *caller's* tenant_id, not body-supplied."""
+ user = _user()
+ db = _mk_db([])
+ body = IOCCreate(ioc_type="ip", value="1.2.3.4", severity="critical")
+ await create_ioc(body=body, current_user=user, db=db)
+ assert len(db.added) == 1
+ created = db.added[0]
+ assert isinstance(created, ThreatIntelIOC)
+ assert created.tenant_id == user.tenant_id
+ assert created.ioc_type == "ip"
+ assert created.value == "1.2.3.4"
+
+
+async def test_create_ioc_ignores_extra_tenant_id_in_payload() -> None:
+ """Even if some future bug let tenant_id sneak into the payload, the
+ endpoint must use the caller's tenant_id. Pydantic strips unknown
+ fields by default, so this primarily pins the **behavioural** contract:
+ the IOC ORM object's tenant_id is set from ``current_user.tenant_id``,
+ not from body data.
+ """
+ user = _user()
+ db = _mk_db([])
+ body = IOCCreate(ioc_type="hash", value="deadbeef")
+ await create_ioc(body=body, current_user=user, db=db)
+ assert db.added[0].tenant_id == user.tenant_id
+
+
+async def test_delete_ioc_cross_tenant_returns_404() -> None:
+ """Cross-tenant DELETE must 404; the wrong row must NEVER be removed."""
+ tenant_a = _user()
+ tenant_b_ioc = _ioc(uuid.uuid4())
+ db = _mk_db([tenant_b_ioc]) # db.get returns the other tenant's row
+ with pytest.raises(HTTPException) as exc:
+ await delete_ioc(ioc_id=tenant_b_ioc.id, current_user=tenant_a, db=db)
+ assert exc.value.status_code == 404
+ # Critical: db.delete must NOT have been called for the other tenant's row.
+ assert db.deleted == [], "cross-tenant DELETE leaked: row was actually deleted"
+
+
+async def test_delete_ioc_same_tenant_succeeds() -> None:
+ """Same-tenant DELETE actually removes the row (positive control)."""
+ user = _user()
+ ioc = _ioc(user.tenant_id)
+ db = _mk_db([ioc])
+ await delete_ioc(ioc_id=ioc.id, current_user=user, db=db)
+ assert db.deleted == [ioc]
+
+
+async def test_delete_ioc_missing_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await delete_ioc(ioc_id=uuid.uuid4(), current_user=user, db=db)
+ assert exc.value.status_code == 404
+ assert db.deleted == []
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Threat actor endpoints — list / create
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_list_actors_scopes_by_tenant() -> None:
+ user = _user()
+ db = _mk_db([[_actor(user.tenant_id)]])
+ result = await list_actors(current_user=user, db=db, limit=50, offset=0)
+ assert len(result) == 1
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_list_actors_with_is_active_filter_keeps_tenant_scope() -> None:
+ user = _user()
+ db = _mk_db([[]])
+ await list_actors(current_user=user, db=db, is_active=True, limit=50, offset=0)
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_create_actor_binds_caller_tenant_id() -> None:
+ user = _user()
+ db = _mk_db([])
+ body = ThreatActorCreate(name="APT-Test", motivation="financial")
+ await create_actor(body=body, current_user=user, db=db)
+ assert len(db.added) == 1
+ created = db.added[0]
+ assert isinstance(created, ThreatActor)
+ assert created.tenant_id == user.tenant_id
+ assert created.name == "APT-Test"
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Feed endpoints — list / create / delete
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_list_feeds_scopes_by_tenant() -> None:
+ user = _user()
+ db = _mk_db([[_feed(user.tenant_id)]])
+ result = await list_feeds(current_user=user, db=db)
+ assert len(result) == 1
+ _assert_tenant_scoped(db.executed, user.tenant_id)
+
+
+async def test_create_feed_binds_caller_tenant_id() -> None:
+ user = _user()
+ db = _mk_db([])
+ body = FeedCreate(name="otx", feed_type="stix")
+ await create_feed(body=body, current_user=user, db=db)
+ assert len(db.added) == 1
+ created = db.added[0]
+ assert isinstance(created, ThreatIntelFeed)
+ assert created.tenant_id == user.tenant_id
+
+
+async def test_delete_feed_cross_tenant_returns_404() -> None:
+ """Cross-tenant DELETE on /feeds must 404 without removing the row."""
+ tenant_a = _user()
+ other_tenant_feed = _feed(uuid.uuid4())
+ db = _mk_db([other_tenant_feed])
+ with pytest.raises(HTTPException) as exc:
+ await delete_feed(feed_id=other_tenant_feed.id, current_user=tenant_a, db=db)
+ assert exc.value.status_code == 404
+ assert db.deleted == [], "cross-tenant DELETE leaked: feed was actually deleted"
+
+
+async def test_delete_feed_same_tenant_succeeds() -> None:
+ user = _user()
+ feed = _feed(user.tenant_id)
+ db = _mk_db([feed])
+ await delete_feed(feed_id=feed.id, current_user=user, db=db)
+ assert db.deleted == [feed]
+
+
+async def test_delete_feed_missing_returns_404() -> None:
+ user = _user()
+ db = _mk_db([None])
+ with pytest.raises(HTTPException) as exc:
+ await delete_feed(feed_id=uuid.uuid4(), current_user=user, db=db)
+ assert exc.value.status_code == 404
+ assert db.deleted == []