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(api): cases read-scope, system-note spoofing, webhook RLS+SSRF, and two live RLS-session siblings (#1421)
Beenu Aroraa57ab3afdc3e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ac78f0a36..a7b4a3fe9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### BREAKING++- `POST /api/v1/cases/{case_id}/comments` no longer accepts `is_system` in the+ request body (GHSA-9mc5-hqgh-j6wf). The field let any `cases:write` holder+ author rows the case summary renders as an unattributed "System note" and the+ post-mortem drops from the analyst record, so it could not be preserved —+ system notes are written by the server itself. A client that still sends the+ field is ignored rather than refused, so existing requests keep succeeding;+ only generated SDK request types lose the property.++### Security++- Every GET route in `cases.py` now requires `cases:read`, so an API key minted+ with only `alerts:read` can no longer list cases or read their comments,+ timeline and evidence chain (GHSA-wwq7-2xvh-qgq6). Role users are unaffected.+- Outbound webhooks work and are SSRF-hardened (GHSA-898c-wxrw-hx6c): all eight+ routes open tenant-scoped sessions (registration previously 500ed against the+ table's row-level security for every tenant), and destinations are validated+ through the platform SSRF guard at create, update and delivery time.+- The kill switch can actually be engaged and TAXII collections actually be+ created: both wrote strict-RLS tables through sessions that never set the+ tenant, and 500ed on every deployment (siblings of GHSA-898c, found by sweep).+## [19.0.0] - 2026-10-12### BREAKINGdiff --git a/docs/openapi.yaml b/docs/openapi.yamlindex f80d922e9..e872c797d 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -22248,10 +22248,6 @@ components:type: stringminLength: 1title: Body- is_system:- type: boolean- title: Is System- default: falsetype: objectrequired:- bodydiff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.pyindex 0ed024a78..7ae8c043e 100644--- a/services/api/app/api/v1/endpoints/cases.py+++ b/services/api/app/api/v1/endpoints/cases.py@@ -68,6 +68,13 @@ logger = logging.getLogger(__name__)router = APIRouter(prefix="/cases", tags=["cases"])+# Every read route here took a bare AuthUser: authenticated, never authorized+# (GHSA-wwq7-2xvh-qgq6). Role users all hold `cases:read`, so nothing changes+# for them, but an API key's scopes are enforced only through+# `require_permission`, so a key minted with nothing but `alerts:read` could+# list cases and read their comments, timeline and evidence chain.+CaseReader = Annotated[AuthUser, Depends(require_permission("cases:read"))]+# The agents service owns the actual investigation orchestrator (Pillar-1).# We keep the route surface on `/cases/{id}/investigate` and# `/cases/{id}/investigations/{run_id}` for the web console and proxy through@@ -240,7 +247,13 @@ class UpdateObservablesRequest(BaseModel):class AddCommentRequest(BaseModel):body: str = Field(..., min_length=1)- is_system: bool = False+ # `is_system` is no longer accepted from callers (GHSA-9mc5-hqgh-j6wf).+ # It was, and `case_summary` renders such a row as an unattributed+ # "System note" while the post-mortem drops it from the analyst record,+ # so any `cases:write` holder could author text the incident report+ # presents as the platform's own. System notes are written by the server+ # itself (author "aisoc"); a client still sending the field is ignored,+ # not refused.class CaseResponse(BaseModel):@@ -487,7 +500,7 @@ async def _resolve_case_id(case_id: str, db: Any, tenant_id: uuid.UUID) -> uuid.@router.get("", response_model=list[CaseResponse], summary="List cases")async def list_cases(db: DBSession,- user: AuthUser,+ user: CaseReader,status_filter: str | None = Query(None, alias="status"),severity: str | None = Query(None),assignee: str | None = Query(None),@@ -605,7 +618,7 @@ async def create_case(@router.get("/{case_id}", response_model=CaseResponse, summary="Get case")-async def get_case(case_id: str, db: DBSession, user: AuthUser) -> CaseResponse:+async def get_case(case_id: str, db: DBSession, user: CaseReader) -> CaseResponse:cid = await _resolve_case_id(case_id, db, user.tenant_id)row = (await db.execute(@@ -1092,7 +1105,7 @@ async def add_comment(tenant_id=user.tenant_id,author=getattr(user, "email", None) or "system",body=body.body,- sys=body.is_system,+ sys=False,now=now,)try:@@ -1115,7 +1128,7 @@ async def add_comment(@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]:+async def list_comments(case_id: str, db: DBSession, user: CaseReader) -> list[CommentResponse]:cid = await _resolve_case_id(case_id, db, user.tenant_id)rows = (await db.execute(@@ -1135,7 +1148,7 @@ async def list_comments(case_id: str, db: DBSession, user: AuthUser) -> list[Com# avoids a behavior change for any existing integration that already speaks# `/comments`.@router.get("/{case_id}/notes", response_model=list[CommentResponse], summary="List case notes (alias of /comments)")-async def list_notes(case_id: str, db: DBSession, user: AuthUser) -> list[CommentResponse]:+async def list_notes(case_id: str, db: DBSession, user: CaseReader) -> list[CommentResponse]:return await list_comments(case_id, db, user)@@ -1147,7 +1160,7 @@ async def add_note(@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:+async def evidence_report(case_id: str, db: DBSession, user: CaseReader) -> EvidenceReport:cid = await _resolve_case_id(case_id, db, user.tenant_id)row = (await db.execute(@@ -1180,7 +1193,7 @@ 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:+async def case_timeline(case_id: str, db: DBSession, user: CaseReader) -> TimelineResponse:cid = await _resolve_case_id(case_id, db, user.tenant_id)case_row = (await db.execute(@@ -1308,7 +1321,7 @@ 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]:+async def list_tasks(case_id: str, db: DBSession, user: CaseReader) -> list[TaskResponse]:cid = await _resolve_case_id(case_id, db, user.tenant_id)exists = (await db.execute(@@ -1723,7 +1736,7 @@ async def case_investigate(async def list_case_investigations(case_id: str,db: DBSession,- user: AuthUser,+ user: CaseReader,) -> dict[str, Any]:"""List all investigation runs for a case.@@ -1781,7 +1794,7 @@ async def case_investigation_run(case_id: str,run_id: str,db: DBSession,- user: AuthUser,+ user: CaseReader,) -> dict[str, Any]:"""One investigation run belonging to this case, in the caller's tenant."""# Scoping kept out of the docstring because FastAPI publishes that verbatim@@ -1823,7 +1836,7 @@ async def case_investigation_report_md(case_id: str,run_id: str,db: DBSession,- user: AuthUser,+ user: CaseReader,) -> PlainTextResponse:"""The Markdown report the case workspace renders."""# `CaseWorkspace.tsx` fetched this from two places and the route did not@@ -1924,7 +1937,7 @@ async def _emit_summary_breadcrumb(async def case_auto_summary(case_id: str,db: DBSession,- user: AuthUser,+ user: CaseReader,format: Literal["json", "html"] = Query("json",description=(@@ -1963,7 +1976,7 @@ async def case_auto_summary(async def case_auto_postmortem(case_id: str,db: DBSession,- user: AuthUser,+ user: CaseReader,format: Literal["json", "html"] = Query("json",description=(@@ -2004,7 +2017,7 @@ async def case_auto_postmortem(async def case_investigation_pdf(case_id: str,run_id: str,- user: AuthUser,+ user: CaseReader,) -> Response:safe_run_id = quote(run_id, safe="")resp = await _agents_proxy(@@ -2032,7 +2045,7 @@ async def case_investigation_pdf(async def list_related_cases(case_id: str,db: DBSession,- user: AuthUser,+ user: CaseReader,) -> dict[str, Any]:"""Return other cases that share alerts or observables with this case.diff --git a/services/api/app/api/v1/endpoints/kill_switch.py b/services/api/app/api/v1/endpoints/kill_switch.pyindex 159fcb8c0..441ae40d0 100644--- a/services/api/app/api/v1/endpoints/kill_switch.py+++ b/services/api/app/api/v1/endpoints/kill_switch.py@@ -38,6 +38,7 @@ from pydantic import BaseModel, Fieldfrom sqlalchemy import textfrom app.api.v1.deps import AuthUser, DBSession, require_permission+from app.db.rls import TenantDBSessionlogger = logging.getLogger(__name__)@@ -111,7 +112,13 @@ async def read_kill_switch(db: DBSession, user: AuthUser) -> KillSwitchState:)async def engage(body: EngageRequest,- db: DBSession,+ # Tenant-scoped on purpose: aisoc_kill_switch and aisoc_kill_switch_audit+ # carry the strict RLS policy `WITH CHECK (tenant_id = current_tenant_id())`,+ # so these INSERTs through a session that never sets app.current_tenant_id+ # were refused for every tenant — the emergency stop answered HTTP 500 on+ # every deployment (same defect class as GHSA-898c-wxrw-hx6c, reproduced+ # live against real Postgres as the aisoc_app runtime role).+ db: TenantDBSession,user: Annotated[AuthUser, Depends(require_permission("settings:write"))],) -> KillSwitchState:actor = getattr(user, "email", None) or str(getattr(user, "user_id", "unknown"))@@ -156,7 +163,11 @@ async def engage()async def release(body: ReleaseRequest,- db: DBSession,+ # Tenant-scoped for the same reason as engage: the UPDATE's new row and+ # the audit INSERT are judged by the strict WITH CHECK. The global-switch+ # read below still works — the table's USING clause admits tenant_id IS+ # NULL rows to every session.+ db: TenantDBSession,user: Annotated[AuthUser, Depends(require_permission("settings:write"))],) -> KillSwitchState:actor = getattr(user, "email", None) or str(getattr(user, "user_id", "unknown"))diff --git a/services/api/app/api/v1/endpoints/outbound_webhooks.py b/services/api/app/api/v1/endpoints/outbound_webhooks.pyindex 6e01a1d7d..e50892b3b 100644--- a/services/api/app/api/v1/endpoints/outbound_webhooks.py+++ b/services/api/app/api/v1/endpoints/outbound_webhooks.py@@ -19,8 +19,9 @@ from pydantic import BaseModel, Field, field_validatorfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app._vendor.ssrf_guard import SSRFError, validate_outbound_urlfrom app.api.v1.deps import CurrentUser, require_permission-from app.db.database import get_db+from app.db.rls import TenantDBSessionfrom app.models.outbound_webhook import OutboundDelivery, OutboundWebhookfrom app.security.credential_vault import get_vaultfrom app.services.outbound_webhooks import attempt_delivery@@ -30,6 +31,22 @@ logger = structlog.get_logger(__name__)router = APIRouter(prefix="/outbound-webhooks", tags=["integrations"])+def _refuse_internal(url: str) -> str:+ """Refuse destinations inside the deployment, as ``destinations.py`` does.++ The delivery worker POSTs the alert payload to this URL and records the+ status code and error text, so an internal URL (169.254.169.254, the+ compose service names, loopback, RFC 1918) made the API a request proxy+ into its own network with a response oracle (GHSA-898c-wxrw-hx6c).+ Private ranges stay refused unless ``AISOC_SSRF_ALLOW_PRIVATE`` says+ otherwise, for an on-prem receiver.+ """+ try:+ return validate_outbound_url(url)+ except SSRFError as exc:+ raise ValueError(f"destination refused: {exc}") from exc++class WebhookCreate(BaseModel):name: str = Field(max_length=255)url: str = Field(max_length=2048)@@ -43,7 +60,7 @@ class WebhookCreate(BaseModel):def _http_only(cls, value: str) -> str:if not value.startswith(("http://", "https://")):raise ValueError("url must be http or https")- return value+ return _refuse_internal(value)class WebhookUpdate(BaseModel):@@ -52,6 +69,18 @@ class WebhookUpdate(BaseModel):event_types: list[str] | None = Field(default=None, max_length=64)enabled: bool | None = None+ # The create model checked the scheme and nothing else, and this one+ # checked nothing at all, so a destination saved as https://partner could+ # be edited to file:// or to 169.254.169.254 afterwards.+ @field_validator("url")+ @classmethod+ def _http_only(cls, value: str | None) -> str | None:+ if value is None:+ return value+ if not value.startswith(("http://", "https://")):+ raise ValueError("url must be http or https")+ return _refuse_internal(value)+class WebhookOut(BaseModel):"""The public projection. ``secret`` is never in it.@@ -107,7 +136,7 @@ async def _owned(db: AsyncSession, webhook_id: uuid.UUID, tenant_id: uuid.UUID)@router.get("", response_model=list[WebhookOut])async def list_webhooks(user: Annotated[CurrentUser, Depends(require_permission("integrations:read"))],- db: Annotated[AsyncSession, Depends(get_db)],+ db: TenantDBSession,) -> list[WebhookOut]:rows = ((await db.execute(select(OutboundWebhook).where(OutboundWebhook.tenant_id == user.tenant_id).order_by(OutboundWebhook.name)))@@ -121,7 +150,7 @@ async def list_webhooks(async def create_webhook(body: WebhookCreate,user: Annotated[CurrentUser, Depends(require_permission("integrations:write"))],- db: Annotated[AsyncSession, Depends(get_db)],+ db: TenantDBSession,) -> dict[str, Any]:"""Create a destination and mint its signing secret.@@ -157,7 +186,7 @@ async def update_webhook(webhook_id: uuid.UUID,body: WebhookUpdate,user: Annotated[CurrentUser, Depends(require_permission("integrations:write"))],- db: Annotated[AsyncSession, Depends(get_db)],+ db: TenantDBSession,) -> WebhookOut:row = await _owned(db, webhook_id, user.tenant_id)for field_name in ("name", "url", "event_types", "enabled"):@@ -174,7 +203,7 @@ async def update_webhook(async def delete_webhook(webhook_id: uuid.UUID,user: Annotated[CurrentUser, Depends(require_permission("integrations:write"))],- db: Annotated[AsyncSession, Depends(get_db)],+ db: TenantDBSession,) -> None:row = await _owned(db, webhook_id, user.tenant_id)await db.delete(row)@@ -185,7 +214,7 @@ async def delete_webhook(async def rotate_secret(webhook_id: uuid.UUID,user: Annotated[CurrentUser, Depends(require_permission("integrations:write"))],- db: Annotated[AsyncSession, Depends(get_db)],+ db: TenantDBSession,) -> dict[str, Any]:row = await _owned(db, webhook_id, user.tenant_id)plaintext = secrets.token_urlsafe(32)@@ -198,7 +227,7 @@ async def rotate_secret(@router.get("/deliveries", response_model=list[DeliveryOut])async def list_deliveries(user: Annotated[CurrentUser, Depends(require_permission("integrations:read"))],- db: Annotated[AsyncSession, Depends(get_db)],+ db: TenantDBSession,status_filter: Annotated[str | None, Query(alias="status", pattern="^(pending|delivered|failed|dead)$")] = None,limit: Annotated[int, Query(ge=1, le=500)] = 100,) -> list[DeliveryOut]:@@ -212,7 +241,7 @@ async def list_deliveries(@router.get("/dead-letters", response_model=list[DeliveryOut])async def list_dead_letters(user: Annotated[CurrentUser, Depends(require_permission("integrations:read"))],- db: Annotated[AsyncSession, Depends(get_db)],+ db: TenantDBSession,limit: Annotated[int, Query(ge=1, le=500)] = 100,) -> list[DeliveryOut]:"""Deliveries that exhausted their retries or were refused outright.@@ -241,7 +270,7 @@ async def list_dead_letters(async def replay_delivery(delivery_id: uuid.UUID,user: Annotated[CurrentUser, Depends(require_permission("integrations:write"))],- db: Annotated[AsyncSession, Depends(get_db)],+ db: TenantDBSession,) -> DeliveryOut:"""Send a dead letter again, with the body the first attempt sent.diff --git a/services/api/app/api/v1/endpoints/taxii.py b/services/api/app/api/v1/endpoints/taxii.pyindex 13494529a..a7d63df19 100644--- a/services/api/app/api/v1/endpoints/taxii.py+++ b/services/api/app/api/v1/endpoints/taxii.py@@ -40,6 +40,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.api.v1.deps import AuthUser, require_permissionfrom app.db.database import get_db+from app.db.rls import TenantDBSessionfrom app.models.taxii import TaxiiCollectionfrom app.models.threat_intel import ThreatIntelIOCfrom app.services.taxii import (@@ -528,7 +529,12 @@ async def list_managed_collections(async def create_managed_collection(payload: CollectionCreate,current_user: AuthUser,- db: Annotated[AsyncSession, Depends(get_db)],+ # Tenant-scoped on purpose: taxii_collections carries the strict RLS+ # policy `WITH CHECK (tenant_id = current_tenant_id())`, so an INSERT+ # through a session that never sets app.current_tenant_id is refused for+ # every tenant (HTTP 500) — the same defect GHSA-898c-wxrw-hx6c reported+ # on outbound webhooks, reproduced live here too.+ db: TenantDBSession,_: Annotated[None, Depends(require_permission("threat_intel:write"))] = None,) -> CollectionOut:try:diff --git a/services/api/app/services/outbound_webhooks.py b/services/api/app/services/outbound_webhooks.pyindex 081ec2551..662a348bf 100644--- a/services/api/app/services/outbound_webhooks.py+++ b/services/api/app/services/outbound_webhooks.py@@ -41,6 +41,7 @@ from __future__ import annotationsimport hashlibimport hmacimport json+import socketimport timeimport uuidfrom datetime import UTC, datetime, timedelta@@ -51,6 +52,7 @@ import structlogfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app._vendor.ssrf_guard import SSRFError, validate_outbound_urlfrom app.models.outbound_webhook import OutboundDelivery, OutboundWebhookfrom app.security.credential_vault import CredentialVaultError, get_vault@@ -209,6 +211,26 @@ async def attempt_delivery(if secret:headers[_SIGNATURE_HEADER] = sign(body, secret=secret)+ # Checked again at send time, not only at registration: a hostname that+ # resolved to a public address when the destination was saved can resolve+ # to an internal one now (DNS rebinding), and rows written before the+ # registration check existed were never validated at all+ # (GHSA-898c-wxrw-hx6c). Two classes, deliberately: a *policy* refusal+ # (metadata, loopback, private range, bad scheme) is permanent and kills+ # the delivery, while a hostname that merely failed to resolve is the+ # same transient condition as a connection failure — the HTTP attempt+ # below will fail through the existing retry ladder rather than a DNS+ # blip permanently deadening a valid destination. A host the guard cannot+ # resolve is one the client cannot connect to either.+ try:+ validate_outbound_url(webhook.url)+ except SSRFError as exc:+ if not isinstance(exc.__cause__, socket.gaierror):+ delivery.status = "dead"+ delivery.next_attempt_at = None+ delivery.last_error = f"destination refused: {exc}"[:500]+ return delivery+owns_client = client is Noneclient = client or httpx.AsyncClient(timeout=_TIMEOUT_SECONDS)try:diff --git a/services/api/tests/test_cases_authorization.py b/services/api/tests/test_cases_authorization.pyindex b716da4e0..8d39a2819 100644--- a/services/api/tests/test_cases_authorization.py+++ b/services/api/tests/test_cases_authorization.py@@ -183,3 +183,48 @@ class TestTheInvestigationRunReadIsScoped:assert proxy.await_args is not None, "the handler never reached the proxy"path = proxy.await_args.args[1]assert "../" not in path and "?" not in path, path+++class TestEveryReadRouteRequiresCasesRead:+ """GHSA-wwq7-2xvh-qgq6: every GET here took a bare AuthUser.++ Role users all hold `cases:read`, but an API key's scopes are enforced+ only through `require_permission`, so a key minted with nothing but+ `alerts:read` listed cases and read their comments, timeline and evidence+ chain (reproduced live: 200 on all three against real Postgres, while+ `GET /api/v1/investigations` — which does enforce — answered 403 to the+ same key).+ """++ def _read_routes(self) -> list[Any]:+ return [r for r in cases.router.routes if "GET" in set(getattr(r, "methods", set()))]++ def test_there_are_read_routes_to_check(self) -> None:+ assert len(self._read_routes()) >= 14++ def test_every_read_route_requires_cases_read(self) -> None:+ missing = [r.path for r in self._read_routes() if "cases:read" not in _permissions_on(r)]+ assert not missing, f"read routes without cases:read (a narrow API key reads them): {missing}"+++class TestCallersCannotAuthorSystemNotes:+ """GHSA-9mc5-hqgh-j6wf: `AddCommentRequest.is_system` was client-settable.++ `case_summary.py` renders an `is_system` row as an unattributed "System+ note" and `case_postmortem.py` drops it from the analyst record, so any+ `cases:write` holder could author text the incident report presents as+ the platform's own (reproduced live: the flag round-tripped to storage).+ Server-written system notes use author "aisoc"; no legitimate caller sets+ the flag through this endpoint.+ """++ def test_the_request_model_does_not_carry_the_flag(self) -> None:+ assert "is_system" not in cases.AddCommentRequest.model_fields, (+ "AddCommentRequest accepts is_system from callers again; any cases:write "+ "holder can author unattributed 'System note' rows the post-mortem omits"+ )++ def test_a_client_still_sending_it_is_ignored_not_refused(self) -> None:+ body = cases.AddCommentRequest.model_validate({"body": "[AUTOMATION] Containment verified.", "is_system": True})+ assert not hasattr(body, "is_system")+ assert body.body.startswith("[AUTOMATION]")diff --git a/services/api/tests/test_outbound_webhooks_ssrf.py b/services/api/tests/test_outbound_webhooks_ssrf.pynew file mode 100644index 000000000..cd9419209--- /dev/null+++ b/services/api/tests/test_outbound_webhooks_ssrf.py@@ -0,0 +1,91 @@+"""Outbound webhook destinations may not point inside the deployment.++GHSA-898c-wxrw-hx6c (part 2). The delivery worker POSTs the alert payload to+the stored URL and records ``last_status_code`` / ``last_error``, so an+internal destination (cloud metadata, loopback, the compose service names,+RFC 1918) makes the API a request proxy into its own network with a response+oracle. The create model checked only the scheme, the update model checked+nothing at all (a destination saved as ``https://partner`` could be edited to+``file://`` or to 169.254.169.254 afterwards), and delivery never re-checked —+so a hostname that resolved publicly at registration could rebind to an+internal address at send time.++The API already vendors ``app._vendor.ssrf_guard.validate_outbound_url``; this+suite pins that both request models and the delivery path use it. Private+ranges stay refused unless ``AISOC_SSRF_ALLOW_PRIVATE`` says otherwise, for an+on-prem receiver — the same posture ``destinations.py`` already takes.+"""++from __future__ import annotations++import uuid+from types import SimpleNamespace++import pytest+from app.api.v1.endpoints.outbound_webhooks import WebhookCreate, WebhookUpdate+from app.services import outbound_webhooks as svc+from pydantic import ValidationError++INTERNAL = [+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/",+ "http://127.0.0.1:5432/",+ "http://localhost:8000/api/v1/admin/users",+ "http://[::1]:8000/",+ "http://0.0.0.0:8000/",+ "http://2130706433/",+ "http://10.0.0.5/",+]++[email protected]("url", INTERNAL)+def test_create_refuses_internal_destinations(url: str) -> None:+ with pytest.raises(ValidationError):+ WebhookCreate(name="x", url=url, event_types=["alert.created"])++[email protected]("url", [*INTERNAL, "file:///etc/passwd"])+def test_update_refuses_what_create_refuses(url: str) -> None:+ with pytest.raises(ValidationError):+ WebhookUpdate(url=url)+++def test_update_without_a_url_is_fine() -> None:+ assert WebhookUpdate(name="renamed").url is None+++def test_a_public_destination_is_still_accepted() -> None:+ """The guard must not refuse the legitimate case, or the feature is dead."""+ created = WebhookCreate(name="partner", url="https://example.com/hook", event_types=["alert.created"])+ assert created.url == "https://example.com/hook"+++async def test_delivery_refuses_an_internal_destination_without_sending(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Checked again at send time, not only at registration: DNS rebinding,+ and rows written before the registration check existed."""+ sent: list[str] = []++ class _Client:+ async def post(self, url: str, **_: object) -> None:+ sent.append(url)+ raise AssertionError("must not send")++ delivery = SimpleNamespace(+ id=uuid.uuid4(),+ attempts=0,+ status="pending",+ next_attempt_at=None,+ last_error="",+ last_status_code=None,+ event_type="alert.created",+ payload={},+ )+ webhook = SimpleNamespace(url="http://169.254.169.254/latest/meta-data/", secret=None)+ monkeypatch.setattr(svc, "_secret_for", lambda _w: "")+ monkeypatch.setattr(svc, "_body", lambda _d: b"{}")+ out = await svc.attempt_delivery(delivery, webhook, client=_Client()) # type: ignore[arg-type]+ assert sent == [], "the internal destination was contacted"+ assert out.status == "dead"+ assert "refused" in (out.last_error or "")diff --git a/services/api/tests/test_outbound_webhooks_tenant_session.py b/services/api/tests/test_outbound_webhooks_tenant_session.pynew file mode 100644index 000000000..b872354e0--- /dev/null+++ b/services/api/tests/test_outbound_webhooks_tenant_session.py@@ -0,0 +1,57 @@+"""Every outbound-webhook route must open a tenant-scoped session.++GHSA-898c-wxrw-hx6c (part 1). ``aisoc_outbound_webhooks`` and+``aisoc_outbound_deliveries`` carry the RLS policy+``WITH CHECK (tenant_id = current_tenant_id())`` (migration 097, ENABLE ++FORCE). Every route here took a plain ``get_db`` session, which never sets+``app.current_tenant_id``, so registering a destination failed for **every**+tenant with::++ asyncpg.exceptions.InsufficientPrivilegeError: new row violates+ row-level security policy for table "aisoc_outbound_webhooks"++and the API answered 500 (reproduced live against real Postgres with the app+connected as the NOSUPERUSER runtime role). Reads still worked — the USING+clause also admits a NULL tenant setting — which is why the list looked+healthy while nothing could ever be created. ``deps.py`` documents+``TenantDBSession`` for exactly this; all eight routes must use it.++Asserted on FastAPI's resolved dependency tree, the way+``test_cases_authorization`` reads permissions: a session dependency that is+present but wired to the wrong callable would satisfy a grep and still 500.+"""++from __future__ import annotations++from typing import Any++import pytest+from app.api.v1.endpoints import outbound_webhooks+from app.db.rls import get_tenant_db+++def _db_dependency(route: Any) -> Any:+ """The callable behind the route's own ``db`` parameter.++ ``get_db`` appears elsewhere in every tree (``get_current_user`` loads the+ user with it), so the question is what the *handler's* session comes from.+ """+ for dep in route.dependant.dependencies:+ if dep.name == "db":+ return dep.call+ return None+++ROUTES = [r for r in outbound_webhooks.router.routes if getattr(r, "dependant", None)]+++def test_there_are_routes_to_check() -> None:+ assert len(ROUTES) >= 8++[email protected]("route", ROUTES, ids=lambda r: f"{sorted(r.methods)[0]} {r.path}")+def test_route_uses_the_tenant_scoped_session(route: Any) -> None:+ assert _db_dependency(route) is get_tenant_db, (+ f"{route.path} opens its session through a dependency that never sets "+ "app.current_tenant_id, so every write violates the table's RLS policy (HTTP 500)"+ )diff --git a/services/api/tests/test_rls_write_sessions.py b/services/api/tests/test_rls_write_sessions.pynew file mode 100644index 000000000..87c619b24--- /dev/null+++ b/services/api/tests/test_rls_write_sessions.py@@ -0,0 +1,61 @@+"""Writes against strict-WITH-CHECK tables must open tenant-scoped sessions.++Siblings of GHSA-898c-wxrw-hx6c, found by sweeping every endpoint module that+opens its own plain ``get_db`` session against the tables whose RLS policy+carries the strict ``WITH CHECK (tenant_id = current_tenant_id())`` (no NULL+branch). Both were reproduced live against real Postgres with the app+connected as the NOSUPERUSER ``aisoc_app`` runtime role:++* ``POST /api/v1/kill-switch/engage`` answered **500** — the emergency stop+ for autonomous closure and action dispatch could not be engaged on any+ deployment. ``/release`` shared the defect through its audit INSERT and the+ UPDATE's new-row check.+* ``POST /api/v1/taxii/collections`` answered **500** — no tenant could ever+ create a TAXII collection.++``mfa.py`` writes the same class of table and is correct — it calls+``set_rls_context`` on every write path — and ``war_rooms.py`` documents its+one deliberate ``DBSession`` route. These two were the ones missed.++Asserted on FastAPI's resolved dependency tree, as+``test_outbound_webhooks_tenant_session`` does.+"""++from __future__ import annotations++from typing import Any++import pytest+from app.api.v1.endpoints import kill_switch, taxii+from app.db.rls import get_tenant_db+++def _db_dependency(route: Any) -> Any:+ for dep in route.dependant.dependencies:+ if dep.name == "db":+ return dep.call+ return None+++def _route(router: Any, method: str, path: str) -> Any:+ for r in router.routes:+ if path == r.path and method in set(getattr(r, "methods", set())):+ return r+ raise AssertionError(f"no route {method} {path}")++[email protected]("path", ["/kill-switch/engage", "/kill-switch/release"])+def test_kill_switch_writes_are_tenant_scoped(path: str) -> None:+ route = _route(kill_switch.router, "POST", path)+ assert _db_dependency(route) is get_tenant_db, (+ f"POST {path} writes aisoc_kill_switch/_audit (strict WITH CHECK) through a "+ "session without app.current_tenant_id, so the emergency stop 500s for every tenant"+ )+++def test_taxii_collection_create_is_tenant_scoped() -> None:+ route = _route(taxii.admin_router, "POST", "/taxii/collections")+ assert _db_dependency(route) is get_tenant_db, (+ "POST /taxii/collections inserts into taxii_collections (strict WITH CHECK) "+ "through a session without app.current_tenant_id, so it 500s for every tenant"+ )