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): playbook proxy must declare the tenant to the agents service (#1256)

antigravitysoham-eng0ae8a9107ce7
diff --git a/services/api/app/api/v1/endpoints/playbooks.py b/services/api/app/api/v1/endpoints/playbooks.py
index 8d1ecc17e..925b0c385 100644
--- a/services/api/app/api/v1/endpoints/playbooks.py
+++ b/services/api/app/api/v1/endpoints/playbooks.py
@@ -29,7 +29,7 @@ from typing import Annotated, Any
import httpx
from fastapi import APIRouter, Depends, HTTPException, Request, status
-from app.api.v1.deps import AuthUser, require_permission
+from app.api.v1.deps import SERVICE_TENANT_HEADER, AuthUser, require_permission
_AGENTS_URL = os.getenv("AGENTS_SERVICE_URL") or os.getenv("AGENTS_API_URL", "http://agents:8084")
# See cases.py: the agents router fails closed without a bearer credential.
@@ -62,12 +62,22 @@ def _validate_path_id(value: str, name: str = "id") -> str:
return _SAFE_ID_RE.match(value).group(0) # type: ignore[union-attr]
-async def _proxy(method: str, path: str, **kwargs) -> Any:
- """Forward a request to the agents service and return the JSON body."""
+async def _proxy(method: str, path: str, *, tenant_id: Any, **kwargs) -> Any:
+ """Forward a request to the agents service and return the JSON body.
+
+ The agents service accepts a service token only together with the tenant
+ it acts for (``require_console_or_service_auth``), and fails closed with
+ 403 otherwise. This proxy sent the token alone, so every /api/v1/playbooks
+ route answered "403 Upstream service error" for every caller, admins
+ included; the console only worked because it calls the agents service
+ directly. ``tenant_id`` is keyword-only and required so a new route cannot
+ forget it. Same header the cases proxy already sends.
+ """
url = f"{_AGENTS_URL}/api/v1/playbooks{path}"
headers = dict(kwargs.pop("headers", None) or {})
if _AGENTS_SERVICE_TOKEN:
headers.setdefault("Authorization", f"Bearer {_AGENTS_SERVICE_TOKEN}")
+ headers[SERVICE_TENANT_HEADER] = str(tenant_id)
try:
async with httpx.AsyncClient(timeout=60) as client:
r = await client.request(method, url, headers=headers, **kwargs)
@@ -87,47 +97,47 @@ async def _proxy(method: str, path: str, **kwargs) -> Any:
@router.get("", summary="List playbooks")
async def list_playbooks(user: ReadUser, enabled_only: bool = False):
- return await _proxy("GET", "", params={"enabled_only": enabled_only})
+ return await _proxy("GET", "", params={"enabled_only": enabled_only}, tenant_id=user.tenant_id)
@router.post("", summary="Create playbook", status_code=201)
async def create_playbook(request: Request, user: WriteUser):
body = await request.json()
- return await _proxy("POST", "", json=body)
+ return await _proxy("POST", "", json=body, tenant_id=user.tenant_id)
@router.get("/runs", summary="List playbook runs")
async def list_runs(user: ReadUser, limit: int = 50):
- return await _proxy("GET", "/runs", params={"limit": limit})
+ return await _proxy("GET", "/runs", params={"limit": limit}, tenant_id=user.tenant_id)
@router.get("/runs/{run_id}", summary="Get a playbook run")
async def get_run(run_id: str, user: ReadUser):
safe_run_id = _validate_path_id(run_id, "run_id")
- return await _proxy("GET", f"/runs/{safe_run_id}")
+ return await _proxy("GET", f"/runs/{safe_run_id}", tenant_id=user.tenant_id)
@router.get("/{playbook_id}", summary="Get a playbook")
async def get_playbook(playbook_id: str, user: ReadUser):
safe_id = _validate_path_id(playbook_id, "playbook_id")
- return await _proxy("GET", f"/{safe_id}")
+ return await _proxy("GET", f"/{safe_id}", tenant_id=user.tenant_id)
@router.put("/{playbook_id}", summary="Update a playbook")
async def update_playbook(playbook_id: str, request: Request, user: WriteUser):
safe_id = _validate_path_id(playbook_id, "playbook_id")
body = await request.json()
- return await _proxy("PUT", f"/{safe_id}", json=body)
+ return await _proxy("PUT", f"/{safe_id}", json=body, tenant_id=user.tenant_id)
@router.delete("/{playbook_id}", summary="Delete a playbook", status_code=204, response_model=None)
async def delete_playbook(playbook_id: str, user: WriteUser):
safe_id = _validate_path_id(playbook_id, "playbook_id")
- await _proxy("DELETE", f"/{safe_id}")
+ await _proxy("DELETE", f"/{safe_id}", tenant_id=user.tenant_id)
@router.post("/{playbook_id}/run", summary="Execute a playbook", status_code=202)
async def run_playbook(playbook_id: str, request: Request, user: ExecuteUser):
safe_id = _validate_path_id(playbook_id, "playbook_id")
body = await request.json()
- return await _proxy("POST", f"/{safe_id}/run", json=body)
+ return await _proxy("POST", f"/{safe_id}/run", json=body, tenant_id=user.tenant_id)
diff --git a/services/api/tests/test_playbooks_proxy_tenant.py b/services/api/tests/test_playbooks_proxy_tenant.py
new file mode 100644
index 000000000..5095ae46d
--- /dev/null
+++ b/services/api/tests/test_playbooks_proxy_tenant.py
@@ -0,0 +1,63 @@
+"""The playbook proxy must tell the agents service which tenant it acts for."""
+
+import uuid
+from types import SimpleNamespace
+
+import pytest
+from app.api.v1.endpoints import playbooks as pb
+
+TENANT = uuid.UUID("00000000-0000-0000-0000-0000000000aa")
+
+
+class _Resp:
+ status_code = 200
+
+ def json(self):
+ return []
+
+
+class _Client:
+ seen: list = []
+
+ def __init__(self, *a, **k):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *a):
+ return False
+
+ async def request(self, method, url, headers=None, **kwargs):
+ _Client.seen.append({"method": method, "url": url, "headers": dict(headers or {})})
+ return _Resp()
+
+
[email protected](autouse=True)
+def _fake_httpx(monkeypatch):
+ _Client.seen = []
+ monkeypatch.setattr(pb.httpx, "AsyncClient", _Client)
+
+
+def _user():
+ return SimpleNamespace(tenant_id=TENANT)
+
+
+async def test_list_playbooks_declares_the_tenant():
+ await pb.list_playbooks(user=_user())
+ assert _Client.seen[-1]["headers"][pb.SERVICE_TENANT_HEADER] == str(TENANT)
+
+
+async def test_list_runs_declares_the_tenant():
+ await pb.list_runs(user=_user(), limit=5)
+ assert _Client.seen[-1]["headers"][pb.SERVICE_TENANT_HEADER] == str(TENANT)
+
+
+async def test_get_playbook_declares_the_tenant():
+ await pb.get_playbook("tpl-credential-access", user=_user())
+ assert _Client.seen[-1]["headers"][pb.SERVICE_TENANT_HEADER] == str(TENANT)
+
+
+async def test_proxy_refuses_to_forward_without_a_tenant():
+ with pytest.raises(TypeError):
+ await pb._proxy("GET", "")