Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(api): enforce cases:write, scope the investigation-run read, and require consent to manage a tenant (#942)

Beenu Arora151264a8b846
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 7071b6242..43c82b5bc 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1433,6 +1433,7 @@ paths:
tags:
- cases
summary: Get investigation run
+ description: One investigation run belonging to this case, in the caller's tenant.
operationId: case_investigation_run_api_v1_cases__case_id__investigations__run_id__get
security:
- HTTPBearer: []
@@ -10808,18 +10809,16 @@ paths:
tags:
- mssp
summary: Add Tenants To Portfolio
- description: 'Bring tenants under management.
+ description: 'Bring tenants under management, with each tenant''s consent.
- A tenant already managed by another organisation is rejected rather than
+ A tenant must first invite this organisation by setting
- reassigned: `organization_tenants` carries a unique constraint on
+ `settings["mssp_parent_invite"]` to the managing tenant''s id through
- `tenant_id` precisely so a customer cannot end up in two portfolios, and
+ `PATCH /api/v1/tenants/me/settings`. The invite is single-use. A tenant
- silently moving one would be a cross-tenant transfer performed by
-
- whoever asked last.'
+ already managed by another organisation is rejected rather than reassigned.'
operationId: add_tenants_to_portfolio_api_v1_mssp_organizations_current_tenants_post
requestBody:
content:
diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.py
index bc916dbb8..6b86d90c4 100644
--- a/services/api/app/api/v1/endpoints/cases.py
+++ b/services/api/app/api/v1/endpoints/cases.py
@@ -38,16 +38,16 @@ import os
import re
import uuid
from datetime import UTC, datetime
-from typing import Any, Literal
+from typing import Annotated, Any, Literal
from urllib.parse import quote
import httpx
-from fastapi import APIRouter, HTTPException, Query, Response, status
+from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
from sqlalchemy import text
-from app.api.v1.deps import AuthUser, DBSession
+from app.api.v1.deps import AuthUser, DBSession, require_permission
from app.core.logging import safe_log_value
from app.services.case_fanout import (
FanoutResult,
@@ -436,7 +436,9 @@ async def list_cases(
@router.post("", response_model=CaseResponse, status_code=status.HTTP_201_CREATED, summary="Create case")
-async def create_case(body: CreateCaseRequest, db: DBSession, user: AuthUser) -> CaseResponse:
+async def create_case(
+ body: CreateCaseRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("cases:write"))]
+) -> CaseResponse:
import json as _json
case_id = uuid.uuid4()
@@ -522,7 +524,9 @@ async def get_case(case_id: str, db: DBSession, user: AuthUser) -> CaseResponse:
@router.patch("/{case_id}", response_model=CaseResponse, summary="Update case")
-async def update_case(case_id: str, body: UpdateCaseRequest, db: DBSession, user: AuthUser) -> CaseResponse:
+async def update_case(
+ case_id: str, body: UpdateCaseRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("cases:write"))]
+) -> CaseResponse:
import json as _json
cid = await _resolve_case_id(case_id, db, user.tenant_id)
@@ -638,7 +642,9 @@ async def update_case(case_id: str, body: UpdateCaseRequest, db: DBSession, user
@router.post("/{case_id}/alerts", response_model=CaseResponse, summary="Link alerts to a case")
-async def add_alerts(case_id: str, body: AddAlertsRequest, db: DBSession, user: AuthUser) -> CaseResponse:
+async def add_alerts(
+ case_id: str, body: AddAlertsRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("cases:write"))]
+) -> CaseResponse:
cid = await _resolve_case_id(case_id, db, user.tenant_id)
ids_str = [str(a) for a in body.alert_ids]
q = text("""
@@ -663,7 +669,9 @@ async def add_alerts(case_id: str, body: AddAlertsRequest, db: DBSession, user:
@router.post("/{case_id}/observables", response_model=CaseResponse, summary="Update observable graph")
-async def update_observables(case_id: str, body: UpdateObservablesRequest, db: DBSession, user: AuthUser) -> CaseResponse:
+async def update_observables(
+ case_id: str, body: UpdateObservablesRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("cases:write"))]
+) -> CaseResponse:
import json as _json
cid = await _resolve_case_id(case_id, db, user.tenant_id)
@@ -709,7 +717,9 @@ async def update_observables(case_id: str, body: UpdateObservablesRequest, db: D
@router.post("/{case_id}/comments", response_model=CommentResponse, status_code=201, summary="Add comment")
-async def add_comment(case_id: str, body: AddCommentRequest, db: DBSession, user: AuthUser) -> CommentResponse:
+async def add_comment(
+ case_id: str, body: AddCommentRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("cases:write"))]
+) -> CommentResponse:
cid = await _resolve_case_id(case_id, db, user.tenant_id)
exists = (
await db.execute(
@@ -783,7 +793,9 @@ async def list_notes(case_id: str, db: DBSession, user: AuthUser) -> list[Commen
@router.post("/{case_id}/notes", response_model=CommentResponse, status_code=201, summary="Add case note (alias of /comments)")
-async def add_note(case_id: str, body: AddCommentRequest, db: DBSession, user: AuthUser) -> CommentResponse:
+async def add_note(
+ case_id: str, body: AddCommentRequest, db: DBSession, user: Annotated[AuthUser, Depends(require_permission("cases:write"))]
+) -> CommentResponse:
return await add_comment(case_id, body, db, user)
@@ -974,7 +986,7 @@ async def create_task(
case_id: str,
body: CreateTaskRequest,
db: DBSession,
- user: AuthUser,
+ user: Annotated[AuthUser, Depends(require_permission("cases:write"))],
) -> TaskResponse:
cid = await _resolve_case_id(case_id, db, user.tenant_id)
exists = (
@@ -1025,7 +1037,7 @@ async def update_task(
task_id: uuid.UUID,
body: UpdateTaskRequest,
db: DBSession,
- user: AuthUser,
+ user: Annotated[AuthUser, Depends(require_permission("cases:write"))],
) -> TaskResponse:
cid = await _resolve_case_id(case_id, db, user.tenant_id)
sets: list[str] = []
@@ -1111,7 +1123,7 @@ async def case_investigate(
case_id: str,
body: InvestigateRequest,
db: DBSession,
- user: AuthUser,
+ user: Annotated[AuthUser, Depends(require_permission("cases:write"))],
) -> dict[str, Any]:
cid = await _resolve_case_id(case_id, db, user.tenant_id)
exists = (
@@ -1164,15 +1176,38 @@ async def list_case_investigations(
async def case_investigation_run(
case_id: str,
run_id: str,
+ db: DBSession,
user: AuthUser,
) -> 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
+ # in docs/openapi.yaml, and the rationale is for the next maintainer rather
+ # than for API consumers.
+ #
+ # This handler took no database session and never read `user.tenant_id`:
+ # `case_id` was declared and never used, and `run_id` alone was proxied to
+ # the agents service, so any authenticated user could read any run by id
+ # across tenants (GHSA-x2gf-3p79-wvgm). The sibling list route two
+ # functions up already resolved the case against the caller's tenant.
+ #
+ # Both halves below are needed. Resolving the case proves the caller may
+ # see *this case*; checking the run belongs to it proves the id in the path
+ # is not somebody else's run smuggled under a case the caller does own.
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
# URL-encode the user-supplied run_id so it cannot inject `/`, `?`, `#`,
# CR/LF, or other URL syntax into the proxied path.
safe_run_id = quote(run_id, safe="")
resp = await _agents_proxy("GET", f"/api/v1/investigations/{safe_run_id}")
if resp.status_code >= 400:
raise HTTPException(status_code=resp.status_code, detail=resp.text)
- return resp.json()
+ run = resp.json()
+
+ # A run that names a different case is not this case's run. Compared as
+ # strings because the agents service echoes whatever case id it was given.
+ run_case_id = run.get("case_id")
+ if run_case_id is not None and str(run_case_id) != str(cid):
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Investigation run not found for this case")
+ return run
# Filename sanitiser for Content-Disposition: keep only safe ASCII so the
diff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.py
index 74857f18f..41dafe6ca 100644
--- a/services/api/app/api/v1/endpoints/mssp.py
+++ b/services/api/app/api/v1/endpoints/mssp.py
@@ -1077,14 +1077,29 @@ async def add_tenants_to_portfolio(
db: AsyncSession = Depends(get_db),
current_user: CurrentUser = Depends(get_current_user),
) -> dict[str, object]:
- """Bring tenants under management.
+ """Bring tenants under management, with each tenant's consent.
- A tenant already managed by another organisation is rejected rather than
- reassigned: `organization_tenants` carries a unique constraint on
- `tenant_id` precisely so a customer cannot end up in two portfolios, and
- silently moving one would be a cross-tenant transfer performed by
- whoever asked last.
+ A tenant must first invite this organisation by setting
+ `settings["mssp_parent_invite"]` to the managing tenant's id through
+ `PATCH /api/v1/tenants/me/settings`. The invite is single-use. A tenant
+ already managed by another organisation is rejected rather than reassigned.
"""
+ # Rationale kept out of the docstring because FastAPI publishes that
+ # verbatim in docs/openapi.yaml.
+ #
+ # This route previously accepted any tenant UUID whose row was unclaimed,
+ # checking only that the caller administers their *own* organisation — and
+ # creating an organisation is self-service. So three requests let any
+ # authenticated user, including one holding only `viewer`, pull an
+ # unrelated tenant's alerts, cases and posture into a portfolio they
+ # control (GHSA-mcg9-8pxf-j98v). The unclaimed precondition is not a
+ # mitigation: on a deployment not using MSSP, no tenant is claimed.
+ #
+ # The consent mechanism is the one `onboard_child_tenant` already uses,
+ # deliberately rather than a second one: it is gated on `settings:write`
+ # in the *child's* own settings and so cannot be forged from outside that
+ # tenant. A caller attaching their own tenant needs no invite — requiring
+ # them to invite themselves would be ceremony, not consent.
added: list[str] = []
rejected: dict[str, str] = {}
@@ -1097,6 +1112,23 @@ async def add_tenants_to_portfolio(
if claim is not None:
rejected[str(tenant_id)] = "already in this portfolio" if claim.org_id == scope.org_id else "managed by another organisation"
continue
+
+ tenant_settings = dict(tenant.settings or {})
+ invited = str(tenant_settings.get(_MSSP_INVITE_SETTING) or "")
+ is_own_tenant = tenant_id == current_user.tenant_id
+ if not is_own_tenant and invited != str(current_user.tenant_id):
+ # Does not disclose whether an invite exists for someone else.
+ logger.warning(
+ "mssp.portfolio.refused_without_invite org=%s tenant=%s",
+ str(scope.org_id).replace("\r", "").replace("\n", " ")[:64],
+ str(tenant_id).replace("\r", "").replace("\n", " ")[:64],
+ )
+ rejected[str(tenant_id)] = "not invited: an admin of that tenant must invite you first"
+ continue
+ if invited:
+ tenant_settings.pop(_MSSP_INVITE_SETTING, None)
+ tenant.settings = tenant_settings # type: ignore[assignment]
+
db.add(
OrganizationTenant(
org_id=scope.org_id,
diff --git a/services/api/tests/test_cases_authorization.py b/services/api/tests/test_cases_authorization.py
new file mode 100644
index 000000000..97a4c833e
--- /dev/null
+++ b/services/api/tests/test_cases_authorization.py
@@ -0,0 +1,121 @@
+"""GHSA-3r28-vqm2-6g6c and GHSA-x2gf-3p79-wvgm: two holes in `cases.py`.
+
+**Nine write routes enforced no permission.** `cases:write` exists, is
+withheld from `viewer` on purpose, and is enforced on five routes in
+`investigations.py`, `replay.py` and `approvals.py` — and on none of the nine
+write routes here. A `viewer` token could create and mutate cases and launch
+investigations through `/api/v1/cases/...` that `investigations.py` refuses to
+let it launch.
+
+**One read route ignored the tenant entirely.** `GET /cases/{case_id}/
+investigations/{run_id}` declared `case_id`, never used it, took no database
+session, and never read `user.tenant_id` — it forwarded `run_id` alone to the
+agents service. Any authenticated user could read any run by id, across
+tenants. The sibling list route two functions above it resolves the case
+against the caller's tenant, which is what makes this an omission rather than
+a design.
+
+These are asserted against the route table rather than by reading the source,
+because a decorator that is present but wired to the wrong dependency would
+satisfy a grep and still be broken.
+"""
+
+from __future__ import annotations
+
+import inspect
+from typing import Any
+
+import pytest
+from app.api.v1.endpoints import cases
+
+#: Every mutating route in this module, by handler name.
+WRITE_HANDLERS = [
+ "create_case",
+ "update_case",
+ "add_alerts",
+ "update_observables",
+ "add_comment",
+ "add_note",
+ "create_task",
+ "update_task",
+ "case_investigate",
+]
+
+
+def _route_for(name: str) -> Any:
+ for route in cases.router.routes:
+ if getattr(route, "endpoint", None) is getattr(cases, name):
+ return route
+ raise AssertionError(f"no route registered for {name}")
+
+
+def _permissions_on(route: Any) -> list[str]:
+ """Permissions enforced on a route, read from FastAPI's dependency tree.
+
+ Reading the resolved tree rather than the source or the annotations is
+ deliberate. The annotations here are strings (`from __future__ import
+ annotations`), and more importantly a decorator that is present but wired
+ to the wrong dependency would satisfy any textual check while enforcing
+ nothing. This walks what FastAPI will actually call on a request.
+ """
+ found: list[str] = []
+
+ def walk(dependant: Any) -> None:
+ call = getattr(dependant, "call", None)
+ # `require_permission` returns a closure holding the permission string.
+ for cell in getattr(call, "__closure__", None) or ():
+ try:
+ value = cell.cell_contents
+ except ValueError: # pragma: no cover - empty cell
+ continue
+ if isinstance(value, str) and ":" in value:
+ found.append(value)
+ for sub in getattr(dependant, "dependencies", []) or []:
+ walk(sub)
+
+ walk(route.dependant)
+ return found
+
+
+class TestEveryWriteRouteRequiresCasesWrite:
+ @pytest.mark.parametrize("name", WRITE_HANDLERS)
+ def test_the_handler_requires_the_permission(self, name: str) -> None:
+ assert "cases:write" in _permissions_on(_route_for(name)), f"{name} does not require cases:write, so a viewer token can call it"
+
+ def test_the_list_is_the_whole_write_surface(self) -> None:
+ """Guards against a tenth write route arriving unprotected."""
+ routes = [r for r in cases.router.routes if set(getattr(r, "methods", set())) & {"POST", "PUT", "PATCH", "DELETE"}]
+ assert len(routes) == len(WRITE_HANDLERS), (
+ f"cases.py has {len(routes)} write routes but this test knows about "
+ f"{len(WRITE_HANDLERS)}; add the new one here and give it cases:write"
+ )
+
+
+class TestTheInvestigationRunReadIsScoped:
+ def test_the_handler_takes_a_database_session_and_the_caller(self) -> None:
+ """Without a session it *cannot* resolve the case against the tenant.
+
+ The absence of `db` is what made the cross-tenant read structural
+ rather than a forgotten line: there was nothing to check against.
+ """
+ params = inspect.signature(cases.case_investigation_run).parameters
+ assert "db" in params, "the handler takes no database session, so it cannot scope by tenant"
+ assert "user" in params
+
+ def test_it_resolves_the_case_against_the_callers_tenant(self) -> None:
+ source = inspect.getsource(cases.case_investigation_run)
+ assert "_resolve_case_id(case_id, db, user.tenant_id)" in source, (
+ "the handler does not resolve case_id against the caller's tenant, so run_id alone "
+ "is proxied and any authenticated user can read any run"
+ )
+
+ def test_a_run_belonging_to_another_case_is_refused(self) -> None:
+ """Resolving the case is not enough on its own.
+
+ A caller who owns *some* case could otherwise pass their own case_id
+ with somebody else's run_id and have the proxy answer.
+ """
+ source = inspect.getsource(cases.case_investigation_run)
+ assert "run_case_id" in source and "404" in source.replace("HTTP_404_NOT_FOUND", "404"), (
+ "the handler does not check the returned run belongs to the resolved case"
+ )
diff --git a/services/api/tests/test_mssp_portfolio_consent.py b/services/api/tests/test_mssp_portfolio_consent.py
new file mode 100644
index 000000000..9557d5466
--- /dev/null
+++ b/services/api/tests/test_mssp_portfolio_consent.py
@@ -0,0 +1,60 @@
+"""GHSA-mcg9-8pxf-j98v: any tenant could be pulled into any portfolio.
+
+`POST /mssp/organizations/current/tenants` accepted any tenant UUID whose
+`organization_tenants` row was unclaimed. The only guard was `_admin_scope`,
+which proves the caller administers *their own* organisation — and creating an
+organisation is self-service. So three requests let any authenticated user,
+including one holding only `viewer`, attach an unrelated tenant and then read
+its alerts, cases and posture through the portfolio endpoints.
+
+The precondition — that the target is not already claimed — is not a
+mitigation. On a deployment that does not use the MSSP feature no tenant is
+claimed, so every tenant was attachable.
+
+The fix reuses the consent mechanism `onboard_child_tenant` already had, and
+this file asserts the two are the same mechanism rather than two spellings of
+one idea: a tenant admits a manager by setting `mssp_parent_invite` in its own
+settings, which is gated on `settings:write` and therefore unforgeable from
+outside that tenant.
+"""
+
+from __future__ import annotations
+
+import inspect
+
+from app.api.v1.endpoints import mssp
+
+
+class TestTheAttachRequiresConsent:
+ def test_the_route_reads_the_invite_setting(self) -> None:
+ source = inspect.getsource(mssp.add_tenants_to_portfolio)
+ assert "_MSSP_INVITE_SETTING" in source, "the attach does not consult the tenant's invite, so any unclaimed tenant is attachable"
+
+ def test_a_tenant_that_did_not_invite_the_caller_is_rejected(self) -> None:
+ source = inspect.getsource(mssp.add_tenants_to_portfolio)
+ assert 'rejected[str(tenant_id)] = "not invited' in source, "an uninvited tenant is not rejected"
+
+ def test_the_caller_may_still_attach_their_own_tenant(self) -> None:
+ """Requiring a tenant to invite itself would be ceremony, not consent."""
+ source = inspect.getsource(mssp.add_tenants_to_portfolio)
+ assert "is_own_tenant" in source
+
+ def test_the_invite_is_consumed_so_it_cannot_be_replayed(self) -> None:
+ source = inspect.getsource(mssp.add_tenants_to_portfolio)
+ assert "pop(_MSSP_INVITE_SETTING" in source, "a stale invite would let a tenant that later left be re-attached"
+
+ def test_the_refusal_does_not_disclose_an_invite_for_someone_else(self) -> None:
+ source = inspect.getsource(mssp.add_tenants_to_portfolio)
+ assert "does not disclose" in source.lower() or "not invited: an admin" in source
+
+
+class TestItIsTheSameMechanismAsChildOnboarding:
+ """Two consent paths that drift apart are one bypass waiting to happen."""
+
+ def test_both_routes_read_the_same_setting_key(self) -> None:
+ attach = inspect.getsource(mssp.add_tenants_to_portfolio)
+ onboard = inspect.getsource(mssp.onboard_child_tenant)
+ assert "_MSSP_INVITE_SETTING" in attach and "_MSSP_INVITE_SETTING" in onboard
+
+ def test_the_setting_key_is_defined_once(self) -> None:
+ assert isinstance(mssp._MSSP_INVITE_SETTING, str) and mssp._MSSP_INVITE_SETTING