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.

feat(war-rooms): Teams via Graph with a named refusal, and 37 tests across three services

Beenu Arora93c19779029e
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 36056e700..d6cfe688c 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -2070,6 +2070,199 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/war-rooms/cases/{case_id}:
+ post:
+ tags:
+ - war-rooms
+ summary: Open For Case
+ description: 'One action: create the channel, invite, post the header, record
+ it.
+
+
+ Fails loudly. The analyst pressed a button and is entitled to know when
+
+ it did not work — a 202 "we''ll try" here would be the toast-only control
+
+ this console is not allowed to ship.'
+ operationId: open_for_case_api_v1_war_rooms_cases__case_id__post
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: case_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: Case Id
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OpenWarRoomRequest'
+ responses:
+ '201':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/WarRoomModel'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ get:
+ tags:
+ - war-rooms
+ summary: List For Case
+ operationId: list_for_case_api_v1_war_rooms_cases__case_id__get
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: case_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: Case Id
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/WarRoomModel'
+ title: Response List For Case Api V1 War Rooms Cases Case Id Get
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/war-rooms/{war_room_id}/sync:
+ post:
+ tags:
+ - war-rooms
+ summary: Sync
+ operationId: sync_api_v1_war_rooms__war_room_id__sync_post
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: war_room_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: War Room Id
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SyncResult'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/war-rooms/{war_room_id}/close:
+ post:
+ tags:
+ - war-rooms
+ summary: Close
+ description: 'Stop mirroring. The channel itself is left alone, deliberately.
+
+
+ Archiving somebody''s channel from a console button is a bigger action
+
+ than it looks: the transcript is often the incident''s own record and the
+
+ people in it did not press anything.'
+ operationId: close_api_v1_war_rooms__war_room_id__close_post
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: war_room_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: War Room Id
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/WarRoomModel'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/war-rooms/{war_room_id}/decision:
+ post:
+ tags:
+ - war-rooms
+ summary: Channel Decision
+ description: 'A decision taken in the channel, delivered by the bot.
+
+
+ Service-token only. See the module header: the bot has verified the
+
+ vendor''s signature and this service cannot, so the token is the whole
+
+ trust relationship and ``CHANNEL_DECISIONS`` is its blast radius.'
+ operationId: channel_decision_api_v1_war_rooms__war_room_id__decision_post
+ parameters:
+ - name: war_room_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: War Room Id
+ - name: X-AiSOC-Service-Token
+ in: header
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: X-Aisoc-Service-Token
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ChannelDecisionRequest'
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+ title: Response Channel Decision Api V1 War Rooms War Room Id Decision
+ Post
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
/api/v1/cases/{case_id}/attack-chain:
get:
tags:
@@ -22871,6 +23064,25 @@ components:
- tags
- sla_due_at
title: CaseResponse
+ ChannelDecisionRequest:
+ properties:
+ decision:
+ type: string
+ title: Decision
+ actor:
+ type: string
+ maxLength: 200
+ title: Actor
+ default: ''
+ note:
+ type: string
+ maxLength: 1000
+ title: Note
+ default: ''
+ type: object
+ required:
+ - decision
+ title: ChannelDecisionRequest
ChildTenantOut:
properties:
id:
@@ -30957,6 +31169,21 @@ components:
- alerts
- sample_data_loaded
title: OnboardingStatus
+ OpenWarRoomRequest:
+ properties:
+ provider:
+ type: string
+ title: Provider
+ description: slack | teams
+ default: slack
+ invite:
+ items:
+ type: string
+ type: array
+ maxItems: 100
+ title: Invite
+ type: object
+ title: OpenWarRoomRequest
OrganizationCreate:
properties:
slug:
@@ -35928,6 +36155,21 @@ components:
required:
- reason
title: SuppressRequest
+ SyncResult:
+ properties:
+ posted:
+ type: integer
+ title: Posted
+ error:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Error
+ type: object
+ required:
+ - posted
+ - error
+ title: SyncResult
TAXIICollection:
properties:
id:
@@ -38388,6 +38630,53 @@ components:
Same shape whether the email was net-new or already on the list —
the prospect should not be able to enumerate existing signups.'
+ WarRoomModel:
+ properties:
+ id:
+ type: string
+ title: Id
+ case_id:
+ type: string
+ title: Case Id
+ provider:
+ type: string
+ title: Provider
+ channel_id:
+ type: string
+ title: Channel Id
+ channel_name:
+ type: string
+ title: Channel Name
+ channel_url:
+ type: string
+ title: Channel Url
+ state:
+ type: string
+ title: State
+ opened_by:
+ type: string
+ title: Opened By
+ last_synced_at:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Last Synced At
+ last_error:
+ type: string
+ title: Last Error
+ type: object
+ required:
+ - id
+ - case_id
+ - provider
+ - channel_id
+ - channel_name
+ - channel_url
+ - state
+ - opened_by
+ - last_synced_at
+ - last_error
+ title: WarRoomModel
WatchlistUpdate:
properties:
is_watchlisted:
diff --git a/services/api/tests/test_war_room.py b/services/api/tests/test_war_room.py
new file mode 100644
index 000000000..7fc54f8c7
--- /dev/null
+++ b/services/api/tests/test_war_room.py
@@ -0,0 +1,113 @@
+"""War rooms: what the channel is told, once, and what it may decide.
+
+Depth plan 9.4.
+
+These are the parts that need no vendor: the event derivation that decides
+what the sweep says, the idempotency key that stops it saying it twice, and
+the closed verb set a chat button may reach. The vendor halves are covered
+by ``services/slack-bot/tests/test_war_room.py`` and
+``services/teams-bot/tests/test_war_room.py``; the end-to-end path through a
+real Postgres is recorded in the pull request.
+
+Asserted by name below:
+
+* an event key embeds the **value**, not just the field, so a case that goes
+ `open → closed → open` posts three times rather than once — a re-opened
+ case is news;
+* the sweep is a pure function of the case row, so a missed tick cannot lose
+ an event the way a cursor-based feed would;
+* a decision outside the closed set is refused by name rather than ignored;
+* ``resolve`` moves a case to `resolved` and never to `closed`, because
+ closing has SLA and reporting consequences and belongs on an authenticated
+ console session.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.services.war_room import CHANNEL_DECISIONS, PROVIDERS, WarRoomError, bot_target, case_events
+
+
+class TestCaseEvents:
+ def test_an_event_key_embeds_the_value_so_a_reopen_is_news(self) -> None:
+ opened = dict(case_events({"status": "open"}))
+ closed = dict(case_events({"status": "closed"}))
+ assert set(opened) == {"status:open"}
+ assert set(closed) == {"status:closed"}
+ # Keyed on the field alone, a case that goes open -> closed -> open
+ # would post once and then go quiet on the thing people care about.
+ assert set(opened) != set(closed)
+
+ def test_it_is_a_pure_function_of_the_case_row(self) -> None:
+ """A missed tick cannot lose an event, which a cursor-based feed can."""
+ case = {"status": "investigating", "severity": "high", "assignee": "[email protected]"}
+ assert case_events(case) == case_events(case)
+ assert len(case_events(case)) == 3
+
+ def test_empty_fields_say_nothing(self) -> None:
+ assert case_events({"status": "", "severity": None, "assignee": " "}) == []
+
+ def test_a_verdict_carries_its_confidence_into_the_key(self) -> None:
+ keys = dict(case_events({"verdict": "true_positive", "confidence": 0.91}))
+ assert "verdict:true_positive:0.91" in keys
+ assert "confidence 0.91" in keys["verdict:true_positive:0.91"]
+ # A verdict that firms up from 0.6 to 0.91 is a second thing worth saying.
+ assert set(case_events({"verdict": "true_positive", "confidence": 0.6})) != set(keys)
+
+ def test_a_long_resolution_is_bounded_in_both_the_key_and_the_message(self) -> None:
+ key, body = case_events({"resolution": "x" * 5_000})[0]
+ assert len(key) <= 80
+ # A chat message should not be an essay; the case link in the channel
+ # header is where the full text lives.
+ assert len(body) <= 420
+
+
+class TestDecisions:
+ def test_the_verb_set_is_closed_and_excludes_closing_a_case(self) -> None:
+ assert CHANNEL_DECISIONS == {"acknowledge", "escalate", "resolve", "note"}
+ # A chat button is not an authenticated console session, and closing
+ # has SLA and reporting consequences.
+ assert "close" not in CHANNEL_DECISIONS
+
+ @pytest.mark.asyncio
+ async def test_a_decision_outside_the_set_is_refused_by_name(self) -> None:
+ from app.services.war_room import apply_channel_decision
+
+ 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,
+ war_room={},
+ decision="delete_everything",
+ actor="someone",
+ note="",
+ )
+
+
+class TestBotTarget:
+ def test_an_unconfigured_bot_resolves_to_none_rather_than_a_guess(self, monkeypatch) -> None:
+ monkeypatch.delenv("AISOC_SLACK_BOT_URL", raising=False)
+ monkeypatch.delenv("AISOC_INTERNAL_TOKEN", raising=False)
+ # A guessed URL produces a connection error at click time, which
+ # reads as "the feature is broken" rather than "the bot is not
+ # deployed" — and both bots are in the `chatops` profile, so not
+ # running one is an ordinary supported state.
+ assert bot_target("slack") is None
+
+ def test_a_url_without_a_token_is_still_unconfigured(self, monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_SLACK_BOT_URL", "http://slack-bot:8089")
+ monkeypatch.delenv("AISOC_INTERNAL_TOKEN", raising=False)
+ assert bot_target("slack") is None
+
+ def test_both_providers_resolve_when_configured(self, monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_INTERNAL_TOKEN", "t")
+ monkeypatch.setenv("AISOC_SLACK_BOT_URL", "http://slack-bot:8089/")
+ monkeypatch.setenv("AISOC_TEAMS_BOT_URL", "http://teams-bot:8090")
+ slack = bot_target("slack")
+ teams = bot_target("teams")
+ assert slack is not None and slack.base_url == "http://slack-bot:8089"
+ assert teams is not None and teams.base_url == "http://teams-bot:8090"
+
+ def test_an_unknown_provider_is_none(self) -> None:
+ assert bot_target("irc") is None
+ assert "irc" not in PROVIDERS
diff --git a/services/teams-bot/app/main.py b/services/teams-bot/app/main.py
index e5da9981c..d2b8b7c69 100644
--- a/services/teams-bot/app/main.py
+++ b/services/teams-bot/app/main.py
@@ -30,6 +30,7 @@ from fastapi import FastAPI, Request
from app._health import install_health_routes
from app.callbacks import callback_max_age_seconds, handle_card_action
from app.notify import router as notify_router
+from app.war_room import router as war_room_router
app = FastAPI(
title="AiSOC Teams Bot",
@@ -39,6 +40,12 @@ app = FastAPI(
# Phase 2.6 — k8s liveness + readiness probes (see app/_health.py).
app.include_router(notify_router)
+# Depth 9.4. Creating a Teams channel needs Microsoft Graph, not the
+# incoming webhook this service posts cards through — so the route
+# refuses with the specific missing settings named rather than falling
+# back to one shared channel, which would put the next incident's
+# traffic in the last one's thread.
+app.include_router(war_room_router)
_mark_ready, _mark_not_ready = install_health_routes(app, service_name="aisoc-teams-bot")
app.state.mark_ready = _mark_ready
diff --git a/services/teams-bot/app/war_room.py b/services/teams-bot/app/war_room.py
new file mode 100644
index 000000000..f6f522d26
--- /dev/null
+++ b/services/teams-bot/app/war_room.py
@@ -0,0 +1,251 @@
+"""Open a Teams channel for a case — and say plainly when it cannot.
+
+Depth plan 9.4.
+
+Teams is not Slack, and the difference is not cosmetic
+------------------------------------------------------
+Slack's ``conversations.create`` needs one bot token, which this project
+already asks an operator for. Creating a Teams channel needs **Microsoft
+Graph** with an Entra application registration holding
+``Channel.Create.Group`` or ``Group.ReadWrite.All``, admin consent, and the
+object id of the team to create it in. None of that is a token somebody
+pastes into a box, and the incoming webhook this service already uses
+cannot create anything at all — a webhook posts into one channel somebody
+chose by hand.
+
+So this route does the Graph call when an operator has done that work, and
+**refuses with the specific missing piece named** when they have not. It
+does not fall back to the webhook and report success: a war room that is
+really one pre-existing channel shared by every case is worse than no war
+room, because the next incident's traffic lands in the last one's thread.
+
+That refusal is the honest state and it is the state a stock install is in.
+``services/api``'s ``WarRoomError`` carries this sentence to the console
+verbatim, so an analyst who presses "Open in Teams" on an unconfigured
+deployment is told which three settings are missing rather than seeing
+"something went wrong".
+"""
+
+from __future__ import annotations
+
+import hmac
+import os
+import re
+from typing import Any
+
+import httpx
+import structlog
+from fastapi import APIRouter, Header, HTTPException, status
+from pydantic import BaseModel, Field
+
+logger = structlog.get_logger(__name__)
+
+router = APIRouter(prefix="/internal", tags=["internal"])
+
+GRAPH = "https://graph.microsoft.com/v1.0"
+LOGIN = "https://login.microsoftonline.com"
+
+_TIMEOUT = httpx.Timeout(20.0, connect=5.0)
+
+#: Teams channel names forbid these characters outright.
+_ILLEGAL = re.compile(r'[~#%&*{}+/\\:<>?|\'"]')
+
+
+class OpenWarRoomRequest(BaseModel):
+ case_id: str
+ case_number: str = ""
+ title: str = ""
+ severity: str = ""
+ status: str = ""
+ invite: list[str] = Field(default_factory=list)
+
+
+class PostRequest(BaseModel):
+ channel_id: str
+ text: str
+ case_id: str = ""
+
+
+def channel_name_for(case_number: str, title: str) -> str:
+ """A Teams-legal display name that still says which case it is."""
+ cleaned = _ILLEGAL.sub("-", f"AiSOC {case_number} {title}".strip())
+ cleaned = re.sub(r"\s{2,}", " ", cleaned).strip(" .-")
+ return cleaned[:50]
+
+
+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)
+
+
+def graph_config() -> tuple[str, str, str, str] | list[str]:
+ """``(tenant, client_id, secret, team_id)`` or the list of what is missing.
+
+ Returns the missing names rather than ``None`` so the refusal can say
+ which three settings an operator has to supply. "Not configured" without
+ naming the gap is a message that sends somebody to the documentation to
+ guess.
+ """
+ values = {
+ "MS_GRAPH_TENANT_ID": os.environ.get("MS_GRAPH_TENANT_ID", "").strip(),
+ "MS_GRAPH_CLIENT_ID": os.environ.get("MS_GRAPH_CLIENT_ID", "").strip(),
+ "MS_GRAPH_CLIENT_SECRET": os.environ.get("MS_GRAPH_CLIENT_SECRET", "").strip(),
+ "MS_TEAMS_TEAM_ID": os.environ.get("MS_TEAMS_TEAM_ID", "").strip(),
+ }
+ missing = [name for name, value in values.items() if not value]
+ if missing:
+ return missing
+ return (
+ values["MS_GRAPH_TENANT_ID"],
+ values["MS_GRAPH_CLIENT_ID"],
+ values["MS_GRAPH_CLIENT_SECRET"],
+ values["MS_TEAMS_TEAM_ID"],
+ )
+
+
+async def _graph_token(tenant: str, client_id: str, secret: str, http: httpx.AsyncClient) -> str:
+ res = await http.post(
+ f"{LOGIN}/{tenant}/oauth2/v2.0/token",
+ data={
+ "grant_type": "client_credentials",
+ "client_id": client_id,
+ "client_secret": secret,
+ "scope": "https://graph.microsoft.com/.default",
+ },
+ )
+ if res.status_code >= 400:
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"Entra refused the client credentials ({res.status_code}). "
+ "Check the application registration and that admin consent has been granted.",
+ )
+ token = res.json().get("access_token")
+ if not token:
+ raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="Entra returned no access token")
+ return str(token)
+
+
[email protected]("/war-room", status_code=status.HTTP_201_CREATED)
+async def open_war_room(
+ body: OpenWarRoomRequest,
+ x_internal_token: str | None = Header(default=None, alias="X-AiSOC-Internal-Token"),
+) -> dict[str, Any]:
+ if not _authorized(x_internal_token):
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="internal token required")
+
+ config = graph_config()
+ if isinstance(config, list):
+ # Named, specific, and deliberately a failure rather than a webhook
+ # fallback. See the module header: one shared channel per deployment
+ # is worse than none.
+ raise HTTPException(
+ status_code=status.HTTP_501_NOT_IMPLEMENTED,
+ detail=(
+ "Creating a Teams channel needs Microsoft Graph, which is not configured here. "
+ f"Missing: {', '.join(config)}. The incoming webhook this service posts cards "
+ "through cannot create a channel, and reusing one channel for every case would "
+ "put the next incident's traffic in the last one's thread."
+ ),
+ )
+
+ tenant, client_id, secret, team_id = config
+ name = channel_name_for(body.case_number or body.case_id[:8], body.title)
+
+ async with httpx.AsyncClient(timeout=_TIMEOUT) as http:
+ token = await _graph_token(tenant, client_id, secret, http)
+ headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
+ res = await http.post(
+ f"{GRAPH}/teams/{team_id}/channels",
+ headers=headers,
+ json={
+ "displayName": name,
+ "description": f"AiSOC case {body.case_number or body.case_id} — {body.title}"[:1024],
+ "membershipType": "standard",
+ },
+ )
+ if res.status_code == 409:
+ # A channel with this display name already exists. Find it rather
+ # than failing: re-opening a war room for a case that already has
+ # one should hand back the same channel.
+ listing = await http.get(f"{GRAPH}/teams/{team_id}/channels", headers=headers)
+ existing = next(
+ (c for c in listing.json().get("value", []) if c.get("displayName") == name),
+ None,
+ )
+ if existing is None:
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"Graph says a channel named {name!r} exists but it is not in the team's channel list.",
+ )
+ channel = existing
+ elif res.status_code >= 400:
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"Graph refused to create the channel ({res.status_code}): {res.text[:300]}",
+ )
+ else:
+ channel = res.json()
+
+ channel_id = str(channel.get("id") or "")
+ if not channel_id:
+ raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="Graph returned a channel with no id")
+
+ header_text = (
+ f"AiSOC case {body.case_number or body.case_id[:8]} — {body.title or 'untitled'}. "
+ f"Severity {body.severity or 'unknown'}, status {body.status or 'unknown'}."
+ )
+ post = await http.post(
+ f"{GRAPH}/teams/{team_id}/channels/{channel_id}/messages",
+ headers=headers,
+ json={"body": {"content": header_text}},
+ )
+ if post.status_code >= 400:
+ # Degraded room, not a failed open — the channel exists and the
+ # API is about to record it.
+ logger.warning("teams_bot.war_room_header_failed", channel_id=channel_id, status=post.status_code)
+
+ logger.info("teams_bot.war_room_opened", case_id=body.case_id, channel_id=channel_id)
+ return {
+ "channel_id": channel_id,
+ "channel_name": channel.get("displayName") or name,
+ "channel_url": channel.get("webUrl") or "",
+ # Graph adds members to a *standard* channel from the team's own
+ # membership, so there is nobody to invite and claiming otherwise
+ # would be a reply the console renders as a list of people who were
+ # never added.
+ "invited": [],
+ "not_invited": [],
+ }
+
+
[email protected]("/war-room/post", status_code=status.HTTP_202_ACCEPTED)
+async def post_to_war_room(
+ body: PostRequest,
+ x_internal_token: str | None = Header(default=None, alias="X-AiSOC-Internal-Token"),
+) -> dict[str, Any]:
+ if not _authorized(x_internal_token):
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="internal token required")
+
+ config = graph_config()
+ if isinstance(config, list):
+ raise HTTPException(
+ status_code=status.HTTP_501_NOT_IMPLEMENTED,
+ detail=f"Microsoft Graph is not configured; missing {', '.join(config)}.",
+ )
+ tenant, client_id, secret, team_id = config
+
+ 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",
+ headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
+ json={"body": {"content": body.text}},
+ )
+ if res.status_code >= 400:
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"Graph refused the message ({res.status_code}): {res.text[:300]}",
+ )
+ return {"posted": True}
diff --git a/services/teams-bot/tests/test_war_room.py b/services/teams-bot/tests/test_war_room.py
new file mode 100644
index 000000000..f77298f7c
--- /dev/null
+++ b/services/teams-bot/tests/test_war_room.py
@@ -0,0 +1,104 @@
+"""Teams war rooms: a named refusal when Graph is not configured.
+
+Depth plan 9.4.
+
+The honest state for a stock install is "this cannot work yet, and here is
+exactly what is missing". Asserted below:
+
+* the refusal is a 501 that **names the missing settings**, not a generic
+ error and not a silent fallback to the incoming webhook — one shared
+ channel for every case would put the next incident's traffic in the last
+ one's thread;
+* a display name Teams will accept, with the forbidden characters removed;
+* the internal token is required on both routes.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.war_room import channel_name_for, graph_config, router
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+TOKEN = "internal-token-for-the-teams-war-room-tests"
+
+GRAPH_VARS = ("MS_GRAPH_TENANT_ID", "MS_GRAPH_CLIENT_ID", "MS_GRAPH_CLIENT_SECRET", "MS_TEAMS_TEAM_ID")
+
+
+def client(monkeypatch):
+ monkeypatch.setenv("AISOC_INTERNAL_TOKEN", TOKEN)
+ for name in GRAPH_VARS:
+ monkeypatch.delenv(name, raising=False)
+ app = FastAPI()
+ app.include_router(router)
+ return TestClient(app)
+
+
+def _open(client, token=TOKEN):
+ headers = {"X-AiSOC-Internal-Token": token} if token else {}
+ return client.post(
+ "/internal/war-room",
+ json={"case_id": "11111111-1111-1111-1111-111111111111", "case_number": "CASE-1", "title": "Intrusion"},
+ headers=headers,
+ )
+
+
+def test_an_unconfigured_deployment_refuses_and_names_what_is_missing(client) -> None:
+ res = _open(client)
+ assert res.status_code == 501
+ detail = res.json()["detail"]
+ # Every one of the four, by name. "Not configured" alone sends an
+ # operator to the documentation to guess.
+ for name in GRAPH_VARS:
+ assert name in detail
+ # And it says why there is no fallback.
+ assert "last one's thread" in detail
+
+
+def test_it_does_not_quietly_succeed_through_the_webhook(client) -> None:
+ res = _open(client)
+ assert res.status_code != 201
+ assert "channel_id" not in res.json()
+
+
+def test_the_post_route_refuses_the_same_way(client) -> None:
+ res = client.post(
+ "/internal/war-room/post",
+ json={"channel_id": "19:abc", "text": "anything"},
+ headers={"X-AiSOC-Internal-Token": TOKEN},
+ )
+ assert res.status_code == 501
+ assert "Microsoft Graph is not configured" in res.json()["detail"]
+
+
+def test_graph_config_reports_every_missing_name(monkeypatch) -> None:
+ for name in GRAPH_VARS:
+ monkeypatch.delenv(name, raising=False)
+ assert graph_config() == list(GRAPH_VARS)
+ monkeypatch.setenv("MS_GRAPH_TENANT_ID", "t")
+ assert graph_config() == list(GRAPH_VARS[1:])
+
+
+def test_graph_config_returns_the_four_values_when_all_are_present(monkeypatch) -> None:
+ for name in GRAPH_VARS:
+ monkeypatch.setenv(name, f"value-for-{name}")
+ config = graph_config()
+ assert isinstance(config, tuple)
+ assert len(config) == 4
+
+
+ ("number", "title", "forbidden"),
+ [("CASE-1", "Exfil via <share>?", "<"), ("CASE-2", 'A "quoted" lure', '"'), ("CASE-3", "a/b\\c", "/")],
+)
+def test_the_channel_name_drops_characters_teams_forbids(number: str, title: str, forbidden: str) -> None:
+ name = channel_name_for(number, title)
+ assert forbidden not in name
+ assert len(name) <= 50
+ assert number in name
+
+
+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