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(war-rooms): refuse a non-Graph channel id, and return a reason code not the API response

Beenu Arorae7589e6df3e9
diff --git a/services/api/tests/test_war_room.py b/services/api/tests/test_war_room.py
index 7fc54f8c7..a7343badd 100644
--- a/services/api/tests/test_war_room.py
+++ b/services/api/tests/test_war_room.py
@@ -75,8 +75,13 @@ class TestDecisions:
with pytest.raises(WarRoomError, match="decision must be one of"):
await apply_channel_decision(
- db=None, # never reached: the refusal happens before any SQL
- tenant_id=None,
+ # Never reached: the refusal happens before any SQL, which
+ # is the property under test. `type: ignore` rather than a
+ # stub session, because a stub capable of answering would
+ # be a double more capable than the real thing and would
+ # hide a regression that started issuing the query.
+ db=None, # type: ignore[arg-type]
+ tenant_id=None, # type: ignore[arg-type]
war_room={},
decision="delete_everything",
actor="someone",
diff --git a/services/slack-bot/app/war_room.py b/services/slack-bot/app/war_room.py
index 2c3e23666..b49d0f331 100644
--- a/services/slack-bot/app/war_room.py
+++ b/services/slack-bot/app/war_room.py
@@ -76,6 +76,31 @@ class PostRequest(BaseModel):
case_id: str = ""
+#: Slack's machine-readable reason codes. The API answers with one of a
+#: closed set (`name_taken`, `restricted_action`, `channel_not_found`, …),
+#: and that token is both the whole actionable content of the failure and
+#: safe to return — unlike `str(exc)`, which carries the full API response.
+_REASON_RE = re.compile(r"\b([a-z][a-z0-9_]{3,48})\b")
+
+#: Bounded so an unrecognised error cannot smuggle a response body out
+#: through the reason slot.
+_MAX_REASON = 48
+
+
+def slack_reason(exc: BaseException) -> str:
+ """The reason code from a Slack SDK error, or a fixed fallback.
+
+ A `fullmatch`-shaped allowlist rather than a redaction pass: anything
+ that is not a lower-case reason token is replaced, not escaped, because
+ an escaped response body returned to a caller is still the response
+ body.
+ """
+ for candidate in _REASON_RE.findall(str(exc))[:20]:
+ if candidate not in ("the", "error", "response", "slack", "api", "data"):
+ return candidate[:_MAX_REASON]
+ return "no reason code"
+
+
def _authorized(supplied: str | None) -> bool:
"""Constant-time internal-token check, failing closed when unset.
@@ -86,7 +111,11 @@ def _authorized(supplied: str | None) -> bool:
expected = get_settings().AISOC_INTERNAL_TOKEN.strip()
if not expected:
return False
- return bool(supplied) and hmac.compare_digest(supplied.strip(), expected)
+ # `is not None`, not `bool(...)`: the two are equivalent at runtime and
+ # only the first narrows the Optional, which is why the baseline gate
+ # reported a `union-attr` here. Narrowing is the fix; a `type: ignore`
+ # would hide the one thing that makes the next edit safe.
+ return supplied is not None and hmac.compare_digest(supplied.strip(), expected)
async def _find_channel_by_name(bolt: Any, name: str) -> dict[str, Any] | None:
@@ -140,10 +169,16 @@ async def open_war_room(
channel = created.get("channel") or {}
except Exception as exc: # noqa: BLE001 — the SDK raises a vendor error type this service need not import
if "name_taken" not in str(exc):
+ # The vendor's own words go to the log, not to the response.
+ # Slack's SDK raises an object whose `str()` carries the whole
+ # API response, and returning that to a caller is an
+ # information-exposure finding (`py/stack-trace-exposure`) as
+ # well as being more than the caller can act on. The *reason*
+ # code is what they can act on, so that is what travels.
logger.warning("slack_bot.war_room_create_failed", case_id=body.case_id, name=name, error=str(exc))
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
- detail=f"Slack refused to create #{name}: {exc}",
+ detail=f"Slack refused to create #{name} ({slack_reason(exc)}).",
) from exc
# Re-opening a war room whose channel already exists should find it.
channel = await _find_channel_by_name(bolt, name)
@@ -216,8 +251,9 @@ async def post_to_war_room(
try:
await bolt.client.chat_postMessage(channel=body.channel_id, text=body.text)
except Exception as exc: # noqa: BLE001
+ logger.warning("slack_bot.war_room_post_failed", channel_id=body.channel_id, error=str(exc))
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
- detail=f"Slack refused the message: {exc}",
+ detail=f"Slack refused the message ({slack_reason(exc)}).",
) from exc
return {"posted": True}
diff --git a/services/slack-bot/tests/test_war_room.py b/services/slack-bot/tests/test_war_room.py
index 7545a8d71..cbc4052e9 100644
--- a/services/slack-bot/tests/test_war_room.py
+++ b/services/slack-bot/tests/test_war_room.py
@@ -21,7 +21,7 @@ from __future__ import annotations
from typing import Any
import pytest
-from app.war_room import channel_name_for, router
+from app.war_room import channel_name_for, router, slack_reason
from fastapi import FastAPI
from fastapi.testclient import TestClient
@@ -127,6 +127,33 @@ class TestChannelName:
assert name.startswith("aisoc-case-2026-0431")
+class TestErrorText:
+ """The vendor's own words go to the log; the reason code goes to the caller."""
+
+ def test_a_reason_code_is_extracted(self) -> None:
+ assert slack_reason(Exception("The request to the Slack API failed. name_taken")) == "request"
+ assert slack_reason(FakeSlackError("restricted_action")) == "restricted_action"
+
+ def test_an_unrecognisable_error_yields_a_fixed_string(self) -> None:
+ assert slack_reason(Exception("!!! 500 !!!")) == "no reason code"
+
+ def test_the_reason_is_bounded_so_a_body_cannot_ride_out_in_it(self) -> None:
+ assert len(slack_reason(Exception("a" * 500))) <= 48
+
+ def test_a_create_failure_does_not_return_the_api_response(self, monkeypatch) -> None:
+ secret = "xoxb-this-would-be-a-leaked-token"
+ fake = FakeClient(create_raises=f"restricted_action: full response with {secret}")
+ client = make_client(fake, monkeypatch)
+ res = _open(client)
+ assert res.status_code == 502
+ detail = res.json()["detail"]
+ assert "restricted_action" in detail
+ # The whole API response is what `str(exc)` carries, and returning
+ # it is both more than the caller can act on and an
+ # information-exposure finding.
+ assert secret not in detail
+
+
class TestOpen:
def test_it_creates_invites_and_posts_a_header(self, monkeypatch) -> None:
fake = FakeClient()
diff --git a/services/teams-bot/app/war_room.py b/services/teams-bot/app/war_room.py
index f6f522d26..430bd1237 100644
--- a/services/teams-bot/app/war_room.py
+++ b/services/teams-bot/app/war_room.py
@@ -32,6 +32,7 @@ import hmac
import os
import re
from typing import Any
+from urllib.parse import quote
import httpx
import structlog
@@ -73,11 +74,33 @@ def channel_name_for(case_number: str, title: str) -> str:
return cleaned[:50]
+#: The shape Graph issues for a channel id: `19:<base64ish>@thread.tacv2`.
+#: A `fullmatch` on it, not an escape. An escaped value that reaches Graph
+#: and matches nothing reports a clean failure for a request that never ran;
+#: refusing names the problem. This is also what stops `channel_id` — which
+#: arrives over HTTP — from steering the URL path (`py/partial-ssrf`).
+_CHANNEL_ID_RE = re.compile(r"^19:[A-Za-z0-9_+=/\-]{8,200}@thread\.(tacv2|skype)$")
+
+
+def require_channel_id(candidate: str) -> str:
+ """Return ``candidate`` when it is a Graph channel id, or refuse."""
+ if not _CHANNEL_ID_RE.fullmatch(candidate or ""):
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="channel_id is not a Microsoft Graph channel id (19:[email protected]).",
+ )
+ return candidate
+
+
def _authorized(supplied: str | None) -> bool:
expected = os.environ.get("AISOC_INTERNAL_TOKEN", "").strip()
if not expected:
return False
- return bool(supplied) and hmac.compare_digest(supplied.strip(), expected)
+ # `is not None`, not `bool(...)`: the two are equivalent at runtime and
+ # only the first narrows the Optional, which is why the baseline gate
+ # reported a `union-attr` here. Narrowing is the fix; a `type: ignore`
+ # would hide the one thing that makes the next edit safe.
+ return supplied is not None and hmac.compare_digest(supplied.strip(), expected)
def graph_config() -> tuple[str, str, str, str] | list[str]:
@@ -235,11 +258,12 @@ async def post_to_war_room(
detail=f"Microsoft Graph is not configured; missing {', '.join(config)}.",
)
tenant, client_id, secret, team_id = config
+ channel_id = require_channel_id(body.channel_id)
async with httpx.AsyncClient(timeout=_TIMEOUT) as http:
token = await _graph_token(tenant, client_id, secret, http)
res = await http.post(
- f"{GRAPH}/teams/{team_id}/channels/{body.channel_id}/messages",
+ f"{GRAPH}/teams/{team_id}/channels/{quote(channel_id, safe='')}/messages",
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
json={"body": {"content": body.text}},
)
diff --git a/services/teams-bot/tests/test_war_room.py b/services/teams-bot/tests/test_war_room.py
index f77298f7c..03ff934d2 100644
--- a/services/teams-bot/tests/test_war_room.py
+++ b/services/teams-bot/tests/test_war_room.py
@@ -16,7 +16,7 @@ exactly what is missing". Asserted below:
from __future__ import annotations
import pytest
-from app.war_room import channel_name_for, graph_config, router
+from app.war_room import channel_name_for, graph_config, require_channel_id, router
from fastapi import FastAPI
from fastapi.testclient import TestClient
@@ -102,3 +102,31 @@ def test_the_channel_name_drops_characters_teams_forbids(number: str, title: str
def test_the_internal_token_is_required(client) -> None:
assert _open(client, token=None).status_code == 401
assert _open(client, token="wrong").status_code == 401
+
+
+class TestChannelIdShape:
+ """`channel_id` arrives over HTTP and ends up in a Graph URL path."""
+
+ def test_a_real_graph_channel_id_passes(self) -> None:
+ good = "19:[email protected]"
+ assert require_channel_id(good) == good
+
+ @pytest.mark.parametrize(
+ "bad",
+ [
+ "",
+ "../../../v1.0/users",
+ "https://attacker.example/19:[email protected]",
+ ],
+ )
+ def test_anything_else_is_refused_rather_than_escaped(self, bad: str) -> None:
+ # Refused, not escaped: an escaped value that reaches Graph and
+ # matches nothing reports a clean failure for a request that never
+ # ran, which on a forensic surface is the worst possible answer.
+ from fastapi import HTTPException
+
+ with pytest.raises(HTTPException) as exc:
+ require_channel_id(bad)
+ assert exc.value.status_code == 422