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
feat(war-rooms): open a Slack channel for a case, sync its timeline, take decisions back
Beenu Arora6f6bafcf519f
diff --git a/services/api/app/api/v1/endpoints/war_rooms.py b/services/api/app/api/v1/endpoints/war_rooms.pynew file mode 100644index 000000000..68795f38d--- /dev/null+++ b/services/api/app/api/v1/endpoints/war_rooms.py@@ -0,0 +1,292 @@+"""War-room routes: one action opens a channel, a sweep keeps it current.++Depth plan 9.4.++* ``POST /war-rooms/cases/{case_id}`` open a channel for this case+* ``GET /war-rooms/cases/{case_id}`` what rooms this case has, and their health+* ``POST /war-rooms/{id}/sync`` post whatever the room has not been told+* ``POST /war-rooms/{id}/close`` stop mirroring; the channel is left alone+* ``POST /war-rooms/{id}/decision`` **bot only** — a decision taken in chat++Why the decision route is service-token only, with no session fallback+----------------------------------------------------------------------+It is reached by the chat bot, which has already verified the vendor's+signature on the interaction. This service cannot re-verify it: it holds no+workspace secret. So the bot is trusted exactly as far as the shared+internal token, and the blast radius of that trust is the four verbs in+``CHANNEL_DECISIONS`` — none of which closes a case. A console session has+no business on this route, and accepting one would mean two paths to the+same write with different evidence behind them.+"""++from __future__ import annotations++import uuid+from typing import Annotated, Any++import structlog+from fastapi import APIRouter, Depends, Header, HTTPException, Request, status+from pydantic import BaseModel, Field+from sqlalchemy import text++from app.api.v1.deps import AuthUser, DBSession, require_permission+from app.api.v1.endpoints.alert_writeback import service_token_valid+from app.db.rls import TenantDBSession, set_rls_context+from app.services.audit import emit_audit+from app.services.war_room import (+ PROVIDERS,+ WarRoomError,+ apply_channel_decision,+ open_war_room,+ sync_war_room,+)++logger = structlog.get_logger()++router = APIRouter(prefix="/war-rooms", tags=["war-rooms"])+++class OpenWarRoomRequest(BaseModel):+ provider: str = Field(default="slack", description="slack | teams")+ #: Vendor user ids to invite. The caller supplies them because only the+ #: console knows which AiSOC user maps to which workspace member, and+ #: guessing from an email address is how a bot invites the wrong person.+ invite: list[str] = Field(default_factory=list, max_length=100)+++class WarRoomModel(BaseModel):+ id: str+ case_id: str+ provider: str+ channel_id: str+ channel_name: str+ channel_url: str+ state: str+ opened_by: str+ #: ``None`` means the sweep has never run for this room, which is a+ #: different fact from "ran and had nothing to say". The console renders+ #: them differently.+ last_synced_at: str | None+ #: Empty on success. A war room that has silently stopped mirroring is+ #: worse than one that was never opened, so the reason is surfaced.+ last_error: str+++class SyncResult(BaseModel):+ posted: int+ error: str | None+++class ChannelDecisionRequest(BaseModel):+ decision: str+ actor: str = Field(default="", max_length=200)+ note: str = Field(default="", max_length=1_000)+++def _model(row: Any) -> WarRoomModel:+ return WarRoomModel(+ id=str(row["id"]),+ case_id=str(row["case_id"]),+ provider=row["provider"],+ channel_id=row["channel_id"],+ channel_name=row["channel_name"],+ channel_url=row["channel_url"],+ state=row["state"],+ opened_by=row["opened_by"],+ last_synced_at=row["last_synced_at"].isoformat() if row["last_synced_at"] else None,+ last_error=row["last_error"],+ )++[email protected]("/cases/{case_id}", response_model=WarRoomModel, status_code=status.HTTP_201_CREATED)+async def open_for_case(+ case_id: uuid.UUID,+ body: OpenWarRoomRequest,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("cases:write"))],+) -> WarRoomModel:+ """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.+ """+ if body.provider not in PROVIDERS:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"provider must be one of {list(PROVIDERS)}",+ )+ actor = current_user.api_key_prefix or current_user.email+ try:+ result = await open_war_room(+ db,+ tenant_id=current_user.tenant_id,+ case_id=case_id,+ provider=body.provider,+ opened_by=actor,+ invite=body.invite,+ )+ except WarRoomError as exc:+ # 502 rather than 500: the failure is a downstream one and the text+ # names which downstream. An operator reading "the slack bot is not+ # configured" knows what to do; "internal server error" does not.+ raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc++ if result["created"]:+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="war_room:open",+ resource="case",+ resource_id=str(case_id),+ changes={"provider": body.provider, "channel_id": result["war_room"]["channel_id"]},+ request=request,+ )+ await db.commit()+ return _model(result["war_room"])++[email protected]("/cases/{case_id}", response_model=list[WarRoomModel])+async def list_for_case(+ case_id: uuid.UUID,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("cases:read"))],+) -> list[WarRoomModel]:+ rows = (+ (+ await db.execute(+ text(+ "SELECT * FROM aisoc_case_war_rooms WHERE tenant_id = :tenant_id AND case_id = :case_id ORDER BY created_at DESC"+ ).bindparams(tenant_id=current_user.tenant_id, case_id=case_id)+ )+ )+ .mappings()+ .all()+ )+ return [_model(row) for row in rows]++[email protected]("/{war_room_id}/sync", response_model=SyncResult)+async def sync(+ war_room_id: uuid.UUID,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("cases:write"))],+) -> SyncResult:+ row = (+ (+ await db.execute(+ text("SELECT * FROM aisoc_case_war_rooms WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ id=war_room_id, tenant_id=current_user.tenant_id+ )+ )+ )+ .mappings()+ .one_or_none()+ )+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such war room")+ result = await sync_war_room(db, tenant_id=current_user.tenant_id, war_room=dict(row))+ await db.commit()+ return SyncResult(posted=result["posted"], error=result["error"])++[email protected]("/{war_room_id}/close", response_model=WarRoomModel)+async def close(+ war_room_id: uuid.UUID,+ request: Request,+ db: TenantDBSession,+ current_user: AuthUser,+ _: Annotated[None, Depends(require_permission("cases:write"))],+) -> WarRoomModel:+ """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.+ """+ row = (+ (+ await db.execute(+ text("UPDATE aisoc_case_war_rooms SET state = 'closed' WHERE id = :id AND tenant_id = :tenant_id RETURNING *").bindparams(+ id=war_room_id, tenant_id=current_user.tenant_id+ )+ )+ )+ .mappings()+ .one_or_none()+ )+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such war room")+ await emit_audit(+ db=db,+ tenant_id=current_user.tenant_id,+ actor_id=current_user.user_id,+ actor_email=current_user.email,+ api_key_prefix=getattr(current_user, "api_key_prefix", None),+ action="war_room:close",+ resource="case",+ resource_id=str(row["case_id"]),+ changes={"channel_id": row["channel_id"]},+ request=request,+ )+ await db.commit()+ return _model(row)++[email protected]("/{war_room_id}/decision")+async def channel_decision(+ war_room_id: uuid.UUID,+ body: ChannelDecisionRequest,+ # `DBSession`, not `TenantDBSession`: the latter depends on+ # `get_current_user`, and there is no user here. The tenant is read off+ # the war-room row and bound to the session below, which is also why the+ # request body has no tenant field to get wrong.+ db: DBSession,+ x_service_token: str | None = Header(default=None, alias="X-AiSOC-Service-Token"),+) -> dict[str, Any]:+ """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.+ """+ if not service_token_valid(x_service_token):+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="service token required")++ row = (await db.execute(text("SELECT * FROM aisoc_case_war_rooms WHERE id = :id").bindparams(id=war_room_id))).mappings().one_or_none()+ if row is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such war room")++ # The tenant comes from the row the bot named, never from the request.+ # There is no tenant field in `ChannelDecisionRequest` to get wrong.+ await set_rls_context(db, row["tenant_id"])+ try:+ result = await apply_channel_decision(+ db,+ tenant_id=row["tenant_id"],+ war_room=dict(row),+ decision=body.decision,+ actor=body.actor or "a war-room participant",+ note=body.note,+ )+ except WarRoomError as exc:+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc++ await emit_audit(+ db=db,+ tenant_id=row["tenant_id"],+ actor_email=body.actor or None,+ action="war_room:decision",+ resource="case",+ resource_id=str(row["case_id"]),+ changes=result,+ )+ await db.commit()+ return resultdiff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex 5cadb3d76..2b083c328 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -96,6 +96,7 @@ from app.api.v1.endpoints import (translation,usage,waitlist,+ war_rooms,workload_identities,)@@ -117,6 +118,10 @@ api_router.include_router(alert_explain.router)# Dry-run by default; AISOC_SIEM_WRITEBACK_EXECUTE opts in to the vendor call.api_router.include_router(alert_writeback.router)api_router.include_router(cases.router)+# Depth 9.4: one action opens a Slack or Teams channel for a case, the+# sweep posts the timeline and verdicts as they change, and a decision+# taken in the channel comes back onto the case.+api_router.include_router(war_rooms.router)# Attack-chain timeline (T3.3 — v8.0 parallel team plan).# Backs the attack-chain view in apps/web/src/components/cases/CaseWorkspace.tsx with a# ranked timeline (graph-distance + temporal proximity + risk overlap)diff --git a/services/api/app/services/war_room.py b/services/api/app/services/war_room.pynew file mode 100644index 000000000..95011ee2e--- /dev/null+++ b/services/api/app/services/war_room.py@@ -0,0 +1,426 @@+"""A case's chat channel: open it, keep it current, take decisions back.++Depth plan 9.4. Nothing in the tree opened a channel. Both bots could only+answer: ``services/slack-bot`` had exactly one outbound route (an approval+card) and ``services/teams-bot`` posts to a webhook somebody configured by+hand. The four grep hits for "war room" on ``main`` were all prose.++Where each half lives, and why+------------------------------+The vendor call belongs in the bot — it holds the workspace token, the Bolt+client and the signature verification, and this service holds neither. The+*decision* about what to say, and the record of what has already been said,+belong here, because this service holds the case, the tenant session and the+audit chain. So the shape is the one ``siem_writeback`` already uses in+reverse: this service posts to the bot's internal route over HTTP with the+shared internal token.++Idempotency is the design, not a refinement+-------------------------------------------+"Post the timeline and verdicts as they change" is a sweep. A sweep with no+record of what it has already sent re-posts the whole case history every+tick, which in a channel people are reading during an incident is not a+cosmetic problem. Every post is keyed by a fingerprint of the *event* and+the key is unique per room, so a retry after a timeout is a no-op and two+replicas running the sweep cannot double-post.++Failure posture+---------------+Opening a war room **fails loudly**: the analyst clicked a button and is+entitled to know it did not work. Syncing one **fails soft** and records+``last_error`` on the room, because a chat outage must not take down the+case surface — but the error is stored and rendered, because a war room that+has silently stopped mirroring is worse than one that was never opened.+"""++from __future__ import annotations++import logging+import os+import uuid+from dataclasses import dataclass+from datetime import UTC, datetime+from typing import Any++import httpx+from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession++logger = logging.getLogger("aisoc.war_room")++PROVIDERS: tuple[str, ...] = ("slack", "teams")++_TIMEOUT = httpx.Timeout(15.0, connect=5.0)+++class WarRoomError(RuntimeError):+ """A refusal or a vendor failure the caller should see, with the reason."""+++@dataclass(frozen=True)+class BotTarget:+ base_url: str+ token: str+++def bot_target(provider: str) -> BotTarget | None:+ """Where to reach the bot for ``provider``, or ``None`` when unconfigured.++ ``None`` rather than a guessed default. A guessed URL produces a+ connection error at click time, which reads to an operator as "the+ feature is broken" rather than "the chat bot is not deployed" — and the+ bots are in the ``chatops`` compose profile, so not running one is an+ ordinary, supported state rather than a misconfiguration.+ """+ env = {+ "slack": ("AISOC_SLACK_BOT_URL", "AISOC_INTERNAL_TOKEN"),+ "teams": ("AISOC_TEAMS_BOT_URL", "AISOC_INTERNAL_TOKEN"),+ }.get(provider)+ if env is None:+ return None+ url = os.environ.get(env[0], "").strip()+ token = os.environ.get(env[1], "").strip()+ if not url or not token:+ return None+ return BotTarget(base_url=url.rstrip("/"), token=token)+++async def _call_bot(+ provider: str,+ path: str,+ payload: dict[str, Any],+ *,+ client: httpx.AsyncClient | None = None,+) -> dict[str, Any]:+ target = bot_target(provider)+ if target is None:+ raise WarRoomError(+ f"The {provider} bot is not configured. Set AISOC_{provider.upper()}_BOT_URL and "+ "AISOC_INTERNAL_TOKEN, and start the service — both bots are in the `chatops` "+ "compose profile and are not running by default."+ )+ owns = client is None+ http = client or httpx.AsyncClient(timeout=_TIMEOUT)+ try:+ res = await http.post(+ f"{target.base_url}{path}",+ json=payload,+ headers={"X-AiSOC-Internal-Token": target.token, "Content-Type": "application/json"},+ )+ except httpx.HTTPError as exc:+ raise WarRoomError(f"The {provider} bot was unreachable: {exc}") from exc+ finally:+ if owns:+ await http.aclose()+ if res.status_code >= 400:+ raise WarRoomError(f"The {provider} bot answered HTTP {res.status_code}: {res.text[:300]}")+ body = res.json() if res.content else {}+ if not isinstance(body, dict):+ raise WarRoomError(f"The {provider} bot returned {type(body).__name__}, not an object.")+ return body+++# ---------------------------------------------------------------------------+# What the channel should be told+# ---------------------------------------------------------------------------+++def case_events(case: dict[str, Any]) -> list[tuple[str, str]]:+ """``(event_key, text)`` for everything about this case worth saying.++ Derived from the case row rather than from a feed, so the sweep is a pure+ function of state and a missed tick cannot lose an event — the next tick+ still sees the same row and the key is still absent from the posts table.+ A feed-based sweep would have to track a cursor, and a cursor that+ advances past an unposted event loses it permanently.++ The keys embed the *value*, not just the field, so a status that goes+ `open → closed → open` posts three times rather than once. That matters:+ a re-opened case is news.+ """+ out: list[tuple[str, str]] = []+ status = (case.get("status") or "").strip()+ if status:+ out.append((f"status:{status}", f"*Status* is now `{status}`."))+ severity = (case.get("severity") or "").strip()+ if severity:+ out.append((f"severity:{severity}", f"*Severity* is `{severity}`."))+ assignee = (case.get("assignee") or "").strip()+ if assignee:+ out.append((f"assignee:{assignee}", f"*Assigned* to {assignee}."))+ resolution = (case.get("resolution") or "").strip()+ if resolution:+ # Bounded: a resolution can be an essay and a chat message should not+ # be. The case link in the channel header is where the full text is.+ out.append((f"resolution:{resolution[:64]}", f"*Resolution*: {resolution[:400]}"))+ verdict = (case.get("verdict") or "").strip()+ if verdict:+ confidence = case.get("confidence")+ suffix = f" (confidence {confidence})" if confidence is not None else ""+ out.append((f"verdict:{verdict}:{confidence}", f"*Verdict*: `{verdict}`{suffix}."))+ return out+++# ---------------------------------------------------------------------------+# Open+# ---------------------------------------------------------------------------+++async def open_war_room(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ case_id: uuid.UUID,+ provider: str,+ opened_by: str,+ invite: list[str],+ client: httpx.AsyncClient | None = None,+) -> dict[str, Any]:+ """Create the channel, invite the assignees, post the case header.++ Fails loudly: the analyst pressed a button and is entitled to know when+ it did not work.+ """+ if provider not in PROVIDERS:+ raise WarRoomError(f"provider must be one of {list(PROVIDERS)}")++ case = (+ (+ await db.execute(+ text(+ "SELECT id, case_number, title, status, severity, assignee, resolution "+ "FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id"+ ).bindparams(id=case_id, tenant_id=tenant_id)+ )+ )+ .mappings()+ .one_or_none()+ )+ if case is None:+ raise WarRoomError("No such case in this tenant.")++ existing = (+ (+ await db.execute(+ text(+ "SELECT * FROM aisoc_case_war_rooms "+ "WHERE tenant_id = :tenant_id AND case_id = :case_id AND provider = :provider AND state = 'open'"+ ).bindparams(tenant_id=tenant_id, case_id=case_id, provider=provider)+ )+ )+ .mappings()+ .one_or_none()+ )+ if existing is not None:+ # Idempotent. Opening twice must not produce a second channel for one+ # case, which is the failure an analyst notices at the worst moment.+ return {"war_room": dict(existing), "created": False}++ number = case["case_number"] or str(case_id)[:8]+ reply = await _call_bot(+ provider,+ "/internal/war-room",+ {+ "case_id": str(case_id),+ "case_number": str(number),+ "title": case["title"],+ "severity": case["severity"],+ "status": case["status"],+ "invite": invite,+ },+ client=client,+ )+ channel_id = str(reply.get("channel_id") or "").strip()+ if not channel_id:+ raise WarRoomError(+ f"The {provider} bot reported success but returned no channel id ({reply!r}). Refusing to record a war room with no channel."+ )++ row = (+ (+ await db.execute(+ text(+ "INSERT INTO aisoc_case_war_rooms "+ "(tenant_id, case_id, provider, channel_id, channel_name, channel_url, opened_by) "+ "VALUES (:tenant_id, :case_id, :provider, :channel_id, :channel_name, :channel_url, :opened_by) "+ "RETURNING *"+ ).bindparams(+ tenant_id=tenant_id,+ case_id=case_id,+ provider=provider,+ channel_id=channel_id,+ channel_name=str(reply.get("channel_name") or ""),+ channel_url=str(reply.get("channel_url") or ""),+ opened_by=opened_by,+ )+ )+ )+ .mappings()+ .one()+ )+ return {"war_room": dict(row), "created": True, "invited": reply.get("invited", [])}+++# ---------------------------------------------------------------------------+# Sync+# ---------------------------------------------------------------------------+++async def sync_war_room(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ war_room: dict[str, Any],+ client: httpx.AsyncClient | None = None,+) -> dict[str, Any]:+ """Post whatever this room has not been told. Fails soft, records why.++ Returns ``{"posted": n, "error": str | None}``. The caller commits.+ """+ case = (+ (+ await db.execute(+ text(+ "SELECT id, status, severity, assignee, resolution FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id"+ ).bindparams(id=war_room["case_id"], tenant_id=tenant_id)+ )+ )+ .mappings()+ .one_or_none()+ )+ if case is None:+ return {"posted": 0, "error": "the case no longer exists"}++ known = {+ row+ for row in (+ await db.execute(text("SELECT event_key FROM aisoc_war_room_posts WHERE war_room_id = :id").bindparams(id=war_room["id"]))+ )+ .scalars()+ .all()+ }+ pending = [(key, body) for key, body in case_events(dict(case)) if key not in known]+ if not pending:+ await db.execute(+ text("UPDATE aisoc_case_war_rooms SET last_synced_at = :now, last_error = '' WHERE id = :id").bindparams(+ now=datetime.now(UTC), id=war_room["id"]+ )+ )+ return {"posted": 0, "error": None}++ posted = 0+ error: str | None = None+ for key, body in pending:+ try:+ await _call_bot(+ war_room["provider"],+ "/internal/war-room/post",+ {"channel_id": war_room["channel_id"], "text": body, "case_id": str(war_room["case_id"])},+ client=client,+ )+ except WarRoomError as exc:+ # Stop at the first failure rather than pressing on: the rest of+ # the batch would almost certainly fail too, and the unposted+ # keys stay absent from the table so the next tick retries them+ # in order.+ error = str(exc)+ break+ await db.execute(+ text(+ "INSERT INTO aisoc_war_room_posts (tenant_id, war_room_id, event_key, summary) "+ "VALUES (:tenant_id, :room, :key, :summary) ON CONFLICT (war_room_id, event_key) DO NOTHING"+ ).bindparams(tenant_id=tenant_id, room=war_room["id"], key=key, summary=body[:400])+ )+ posted += 1++ await db.execute(+ text("UPDATE aisoc_case_war_rooms SET last_synced_at = :now, last_error = :err WHERE id = :id").bindparams(+ now=datetime.now(UTC), err=error or "", id=war_room["id"]+ )+ )+ return {"posted": posted, "error": error}+++# ---------------------------------------------------------------------------+# Decisions coming back from the channel+# ---------------------------------------------------------------------------++#: What a channel may do to a case. Deliberately narrow: a chat message is+#: not an authenticated console session, and the set of verbs reachable from+#: one should be the set somebody has thought about. Anything else is refused+#: by name rather than ignored, so a user who tries gets told.+CHANNEL_DECISIONS: frozenset[str] = frozenset({"acknowledge", "escalate", "resolve", "note"})+++async def apply_channel_decision(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ war_room: dict[str, Any],+ decision: str,+ actor: str,+ note: str,+) -> dict[str, Any]:+ """Write a decision taken in the channel back onto the case.++ The decision arrives from the bot, which has verified the vendor's+ signature on the interaction. This service does not re-verify it — it+ cannot, it has no workspace secret — so the bot is trusted exactly as far+ as the shared internal token, and the verb set above is the blast radius+ of that trust.+ """+ if decision not in CHANNEL_DECISIONS:+ raise WarRoomError(f"decision must be one of {sorted(CHANNEL_DECISIONS)}")++ now = datetime.now(UTC)+ case_id = war_room["case_id"]+ changed: dict[str, Any] = {}++ if decision == "acknowledge":+ await db.execute(+ text(+ "UPDATE aisoc_cases SET acknowledged_at = COALESCE(acknowledged_at, :now), updated_at = :now "+ "WHERE id = :id AND tenant_id = :tenant_id"+ ).bindparams(now=now, id=case_id, tenant_id=tenant_id)+ )+ changed["acknowledged_at"] = now.isoformat()+ elif decision == "escalate":+ await db.execute(+ text(+ "UPDATE aisoc_cases SET severity = 'critical', escalation_level = "+ "COALESCE(escalation_level, 0) + 1, updated_at = :now "+ "WHERE id = :id AND tenant_id = :tenant_id"+ ).bindparams(now=now, id=case_id, tenant_id=tenant_id)+ )+ changed["severity"] = "critical"+ elif decision == "resolve":+ # `resolved`, not `closed`. Closing is a terminal decision with SLA+ # and reporting consequences and belongs on an authenticated console+ # session; a chat button moves the case to the state a human then+ # confirms.+ await db.execute(+ text(+ "UPDATE aisoc_cases SET status = 'resolved', resolved_at = COALESCE(resolved_at, :now), "+ "resolution = COALESCE(NULLIF(resolution, ''), :note), updated_at = :now "+ "WHERE id = :id AND tenant_id = :tenant_id"+ ).bindparams(now=now, note=note or f"resolved from the war room by {actor}", id=case_id, tenant_id=tenant_id)+ )+ changed["status"] = "resolved"+ else: # note+ changed["note"] = note[:400]++ # Recorded as a post so the channel's own history and the case's agree+ # about what happened, and so the sweep does not immediately echo the+ # change back into the channel that caused it.+ await db.execute(+ text(+ "INSERT INTO aisoc_war_room_posts (tenant_id, war_room_id, event_key, summary) "+ "VALUES (:tenant_id, :room, :key, :summary) ON CONFLICT (war_room_id, event_key) DO NOTHING"+ ).bindparams(+ tenant_id=tenant_id,+ room=war_room["id"],+ key=f"decision:{decision}:{now.isoformat()}",+ summary=f"{actor} chose {decision} in the channel: {note[:200]}",+ )+ )+ return {"decision": decision, "changed": changed}diff --git a/services/slack-bot/app/main.py b/services/slack-bot/app/main.pyindex c1b3f4b9b..d52c2eeba 100644--- a/services/slack-bot/app/main.py+++ b/services/slack-bot/app/main.py@@ -62,6 +62,7 @@ from app.interactions import (handle_action_decision,)from app.notify import router as notify_router+from app.war_room import router as war_room_routerfrom app.services.aisoc_clients import AisocActionsClient, AisocApiClientfrom app.services.approval_audit import StructlogAuditSinkfrom app.services.approval_timeout import ApprovalTimeoutScheduler@@ -330,6 +331,11 @@ app = FastAPI(# Bolt's respond() only works inside an inbound interaction — which is why an# agent could not ask for approval until a human asked first.app.include_router(notify_router)+# Depth 9.4. Before this the only outbound thing this service could do was+# post one approval card into one pre-configured channel; it could not+# create anything, so "open a war room" existed in the tree only as a+# sentence in a playbook template.+app.include_router(war_room_router)# Phase 2.6 — k8s liveness + readiness probes (see app/_health.py)._mark_ready, _mark_not_ready = install_health_routes(app, service_name="aisoc-slack-bot")diff --git a/services/slack-bot/app/war_room.py b/services/slack-bot/app/war_room.pynew file mode 100644index 000000000..2c3e23666--- /dev/null+++ b/services/slack-bot/app/war_room.py@@ -0,0 +1,223 @@+"""Open a Slack channel for a case, invite the people on it, keep it fed.++Depth plan 9.4. Before this, every outbound thing this service could do was+post one approval card into one pre-configured channel. It could not create+anything, so "open a war room" was a sentence in a playbook template and+nowhere else in the tree.++Why the channel call lives here and the decision lives in the API+-----------------------------------------------------------------+This service holds the workspace token, the Bolt client and the signature+verification; the API holds the case, the tenant session and the audit+chain. Neither can import the other. So the API posts here with the shared+internal token to create and to speak, and this service posts back to the+API when somebody presses a button — the same split ``siem_writeback`` uses,+with the direction reversed per call.++Three Slack facts this encodes, each of which is a failure if ignored+---------------------------------------------------------------------+* **Channel names are constrained**: lower case, no spaces, no dots, 80+ characters. ``conversations.create`` rejects anything else, and a case+ title is exactly the kind of string that violates all four.+* **`name_taken` is not an error here.** Re-opening a war room for a case+ whose channel already exists should find it, not fail. The handler looks+ the name up and returns the existing channel.+* **An invite failure is not a create failure.** A user id that is wrong, or+ a person who has left, must not undo a channel that now exists. Invites+ are attempted individually and the ones that failed are named in the+ reply, so the console can say "the room is open, these three were not+ added" instead of "something went wrong".+"""++from __future__ import annotations++import hmac+import re+from typing import Any++import structlog+from fastapi import APIRouter, Header, HTTPException, Request, status+from pydantic import BaseModel, Field++from app.core.config import get_settings++logger = structlog.get_logger(__name__)++router = APIRouter(prefix="/internal", tags=["internal"])++#: Slack's own rule, encoded rather than discovered at runtime: lower case,+#: no spaces or periods, at most 80 characters.+_ILLEGAL = re.compile(r"[^a-z0-9_-]+")+++def channel_name_for(case_number: str, title: str) -> str:+ """A legal Slack channel name that still says which case it is.++ The case number leads, because that is the thing an analyst searches+ for and it survives the truncation that a long title does not.+ """+ slug = _ILLEGAL.sub("-", f"{case_number}-{title}".lower()).strip("-")+ slug = re.sub(r"-{2,}", "-", slug)+ return f"aisoc-{slug}"[:80].rstrip("-")+++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 _authorized(supplied: str | None) -> bool:+ """Constant-time internal-token check, failing closed when unset.++ Same posture as ``notify.py``: an unset token refuses every internal+ call, with no dev-mode exemption, because a route that creates channels+ in somebody's workspace must not be open to whatever can reach the pod.+ """+ expected = get_settings().AISOC_INTERNAL_TOKEN.strip()+ if not expected:+ return False+ return bool(supplied) and hmac.compare_digest(supplied.strip(), expected)+++async def _find_channel_by_name(bolt: Any, name: str) -> dict[str, Any] | None:+ """Look a channel up by name, paging until it is found or the list ends.++ Only used on `name_taken`, so the cost is paid once per re-open rather+ than on every create.+ """+ cursor: str | None = None+ for _ in range(20): # bounded: a workspace with 20k channels is not a loop we own+ page = await bolt.client.conversations_list(+ exclude_archived=True,+ limit=1000,+ types="public_channel,private_channel",+ **({"cursor": cursor} if cursor else {}),+ )+ for channel in page.get("channels", []):+ if channel.get("name") == name:+ return channel+ cursor = (page.get("response_metadata") or {}).get("next_cursor") or ""+ if not cursor:+ return None+ return None++[email protected]("/war-room", status_code=status.HTTP_201_CREATED)+async def open_war_room(+ body: OpenWarRoomRequest,+ request: Request,+ x_internal_token: str | None = Header(default=None, alias="X-AiSOC-Internal-Token"),+) -> dict[str, Any]:+ """Create the channel, invite, post the header. Returns the channel id."""+ if not _authorized(x_internal_token):+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="internal token required")++ bolt = getattr(request.app.state, "bolt_app", None)+ if bolt is None:+ # 503 rather than a success with a flag: the caller is a button an+ # analyst pressed, and it needs to fail loudly.+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail="no Slack client; SLACK_BOT_TOKEN is unset on the slack-bot service",+ )++ settings = get_settings()+ name = channel_name_for(body.case_number or body.case_id[:8], body.title)++ channel: dict[str, Any] | None = None+ try:+ created = await bolt.client.conversations_create(name=name, is_private=False)+ 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):+ 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}",+ ) from exc+ # Re-opening a war room whose channel already exists should find it.+ channel = await _find_channel_by_name(bolt, name)+ if channel is None:+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail=f"Slack says #{name} is taken but it is not in the channel list; it may be archived or private to another user.",+ ) from exc++ channel_id = str(channel.get("id") or "")+ if not channel_id:+ raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="Slack returned a channel with no id")++ # Invites are per-user and a failure does not undo the channel.+ invited: list[str] = []+ not_invited: list[dict[str, str]] = []+ for user in body.invite:+ try:+ await bolt.client.conversations_invite(channel=channel_id, users=user)+ invited.append(user)+ except Exception as exc: # noqa: BLE001+ # `already_in_channel` is a success from the caller's point of view.+ if "already_in_channel" in str(exc):+ invited.append(user)+ continue+ not_invited.append({"user": user, "reason": str(exc)[:200]})++ header = (+ f"*AiSOC case {body.case_number or body.case_id[:8]}* — {body.title or 'untitled'}\n"+ f"Severity `{body.severity or 'unknown'}` · status `{body.status or 'unknown'}`\n"+ f"{settings.AISOC_WEB_BASE_URL.rstrip('/')}/cases/{body.case_id}"+ )+ try:+ await bolt.client.chat_postMessage(channel=channel_id, text=header)+ except Exception as exc: # noqa: BLE001+ # The channel exists and is recorded; a failed header is a degraded+ # room, not a failed open, and the reply says so.+ logger.warning("slack_bot.war_room_header_failed", channel_id=channel_id, error=str(exc))++ logger.info("slack_bot.war_room_opened", case_id=body.case_id, channel_id=channel_id, name=name)+ return {+ "channel_id": channel_id,+ "channel_name": channel.get("name") or name,+ "channel_url": f"slack://channel?id={channel_id}",+ "invited": invited,+ "not_invited": not_invited,+ }++[email protected]("/war-room/post", status_code=status.HTTP_202_ACCEPTED)+async def post_to_war_room(+ body: PostRequest,+ request: Request,+ x_internal_token: str | None = Header(default=None, alias="X-AiSOC-Internal-Token"),+) -> dict[str, Any]:+ """Say one thing in a war room.++ Fails with a status the caller can act on rather than a flag: the API's+ sweep records `last_error` on the room from this, and an operator reading+ "channel_not_found" knows the channel was archived.+ """+ if not _authorized(x_internal_token):+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="internal token required")+ bolt = getattr(request.app.state, "bolt_app", None)+ if bolt is None:+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail="no Slack client; SLACK_BOT_TOKEN is unset on the slack-bot service",+ )+ try:+ await bolt.client.chat_postMessage(channel=body.channel_id, text=body.text)+ except Exception as exc: # noqa: BLE001+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail=f"Slack refused the message: {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.pynew file mode 100644index 000000000..7545a8d71--- /dev/null+++ b/services/slack-bot/tests/test_war_room.py@@ -0,0 +1,258 @@+"""Opening a war room: legal names, an existing channel, a bad invite.++Depth plan 9.4.++Asserted by name below:++* a case title becomes a channel name Slack will actually accept — the four+ rules it enforces are encoded rather than discovered at runtime;+* `name_taken` resolves to the existing channel rather than failing, because+ re-opening a war room for a case that already has one should find it;+* an invite that fails does **not** undo a channel that now exists, and the+ reply names who was not added, so the console can say "the room is open,+ these were not added" instead of "something went wrong";+* a failed header message is a degraded room, not a failed open;+* the internal token is required, and an unset token refuses rather than+ opening the route to anything that can reach the pod.+"""++from __future__ import annotations++from typing import Any++import pytest+from app.war_room import channel_name_for, router+from fastapi import FastAPI+from fastapi.testclient import TestClient++TOKEN = "internal-token-for-the-war-room-tests"+++class FakeSlackError(Exception):+ """Stands in for the SDK's error type, which this service need not import."""+++class FakeClient:+ def __init__(+ self,+ *,+ create_raises: str | None = None,+ invite_fails: set[str] | None = None,+ post_raises: bool = False,+ existing: list[dict[str, Any]] | None = None,+ ) -> None:+ self.create_raises = create_raises+ self.invite_fails = invite_fails or set()+ self.post_raises = post_raises+ self.existing = existing or []+ self.created: list[str] = []+ self.invited: list[str] = []+ self.messages: list[dict[str, Any]] = []++ async def conversations_create(self, name: str, is_private: bool = False) -> dict[str, Any]:+ if self.create_raises:+ raise FakeSlackError(self.create_raises)+ self.created.append(name)+ return {"channel": {"id": "C0WARROOM1", "name": name}}++ async def conversations_list(self, **_kwargs: Any) -> dict[str, Any]:+ return {"channels": self.existing, "response_metadata": {"next_cursor": ""}}++ async def conversations_invite(self, channel: str, users: str) -> dict[str, Any]:+ if users in self.invite_fails:+ raise FakeSlackError(self.invite_fails_reason(users))+ self.invited.append(users)+ return {"ok": True}++ def invite_fails_reason(self, user: str) -> str:+ return "already_in_channel" if user.startswith("UALREADY") else "user_not_found"++ async def chat_postMessage(self, **kwargs: Any) -> dict[str, Any]: # noqa: N802 - Slack's own name+ if self.post_raises:+ raise FakeSlackError("channel_not_found")+ self.messages.append(kwargs)+ return {"ok": True}+++class FakeBolt:+ def __init__(self, client: FakeClient) -> None:+ self.client = client+++def make_client(fake: FakeClient | None, monkeypatch) -> TestClient:+ from app.core import config as config_module++ monkeypatch.setenv("AISOC_INTERNAL_TOKEN", TOKEN)+ config_module.get_settings.cache_clear()++ app = FastAPI()+ app.include_router(router)+ if fake is not None:+ app.state.bolt_app = FakeBolt(fake)+ return TestClient(app)+++def _open(client: TestClient, token: str | None = TOKEN, **body: Any):+ headers = {"X-AiSOC-Internal-Token": token} if token else {}+ payload = {+ "case_id": "11111111-1111-1111-1111-111111111111",+ "case_number": "CASE-2026-0431",+ "title": "File server encrypted overnight!!",+ "severity": "critical",+ "status": "investigating",+ "invite": [],+ }+ payload.update(body)+ return client.post("/internal/war-room", json=payload, headers=headers)+++class TestChannelName:+ """Slack's four rules, encoded rather than discovered at runtime."""++ def test_a_case_title_becomes_a_name_slack_accepts(self) -> None:+ name = channel_name_for("CASE-2026-0431", "File server encrypted overnight!!")+ assert name == "aisoc-case-2026-0431-file-server-encrypted-overnight"+ assert name == name.lower()+ assert " " not in name and "." not in name+ assert len(name) <= 80++ def test_a_very_long_title_is_truncated_without_a_trailing_hyphen(self) -> None:+ name = channel_name_for("CASE-1", "x" * 200)+ assert len(name) <= 80+ assert not name.endswith("-")++ def test_the_case_number_leads_so_it_survives_truncation(self) -> None:+ """It is what an analyst searches for; a long title is not."""+ name = channel_name_for("CASE-2026-0431", "y" * 200)+ assert name.startswith("aisoc-case-2026-0431")+++class TestOpen:+ def test_it_creates_invites_and_posts_a_header(self, monkeypatch) -> None:+ fake = FakeClient()+ client = make_client(fake, monkeypatch)+ res = _open(client, invite=["U111", "U222"])+ assert res.status_code == 201, res.text+ body = res.json()+ assert body["channel_id"] == "C0WARROOM1"+ assert body["invited"] == ["U111", "U222"]+ assert body["not_invited"] == []+ assert fake.created == ["aisoc-case-2026-0431-file-server-encrypted-overnight"]+ assert "CASE-2026-0431" in fake.messages[0]["text"]++ def test_name_taken_resolves_to_the_existing_channel(self, monkeypatch) -> None:+ name = "aisoc-case-2026-0431-file-server-encrypted-overnight"+ fake = FakeClient(create_raises="name_taken", existing=[{"id": "C0EXISTING", "name": name}])+ client = make_client(fake, monkeypatch)+ res = _open(client)+ assert res.status_code == 201, res.text+ # Re-opening finds the room rather than failing. The alternative is a+ # console button that works once per case and errors forever after.+ assert res.json()["channel_id"] == "C0EXISTING"++ def test_name_taken_with_no_matching_channel_is_a_readable_failure(self, monkeypatch) -> None:+ fake = FakeClient(create_raises="name_taken", existing=[])+ client = make_client(fake, monkeypatch)+ res = _open(client)+ assert res.status_code == 502+ assert "archived or private" in res.json()["detail"]++ def test_a_bad_invite_does_not_undo_a_channel_that_exists(self, monkeypatch) -> None:+ fake = FakeClient(invite_fails={"UGONE"})+ client = make_client(fake, monkeypatch)+ res = _open(client, invite=["U111", "UGONE"])+ assert res.status_code == 201, res.text+ body = res.json()+ assert body["channel_id"] == "C0WARROOM1"+ assert body["invited"] == ["U111"]+ # Named, so the console can say which people were not added rather+ # than reporting a generic failure for a room that is open.+ assert [row["user"] for row in body["not_invited"]] == ["UGONE"]++ def test_someone_already_in_the_channel_counts_as_invited(self, monkeypatch) -> None:+ fake = FakeClient(invite_fails={"UALREADY1"})+ client = make_client(fake, monkeypatch)+ res = _open(client, invite=["UALREADY1"])+ assert res.json()["invited"] == ["UALREADY1"]+ assert res.json()["not_invited"] == []++ def test_a_failed_header_is_a_degraded_room_not_a_failed_open(self, monkeypatch) -> None:+ fake = FakeClient(post_raises=True)+ client = make_client(fake, monkeypatch)+ res = _open(client)+ assert res.status_code == 201+ assert res.json()["channel_id"] == "C0WARROOM1"++ def test_a_create_failure_that_is_not_name_taken_fails_loudly(self, monkeypatch) -> None:+ fake = FakeClient(create_raises="restricted_action")+ client = make_client(fake, monkeypatch)+ res = _open(client)+ # The analyst pressed a button. A 202 "we'll try" here would be the+ # toast-only control the console is not allowed to ship.+ assert res.status_code == 502+ assert "restricted_action" in res.json()["detail"]++ def test_no_slack_client_is_503_not_a_quiet_success(self, monkeypatch) -> None:+ client = make_client(None, monkeypatch)+ res = _open(client)+ assert res.status_code == 503+ assert "SLACK_BOT_TOKEN" in res.json()["detail"]+++class TestAuthorization:+ def test_the_internal_token_is_required(self, monkeypatch) -> None:+ client = make_client(FakeClient(), monkeypatch)+ assert _open(client, token=None).status_code == 401+ assert _open(client, token="wrong").status_code == 401++ def test_an_unset_token_refuses_rather_than_opening_the_route(self, monkeypatch) -> None:+ from app.core import config as config_module++ monkeypatch.setenv("AISOC_INTERNAL_TOKEN", "")+ config_module.get_settings.cache_clear()+ app = FastAPI()+ app.include_router(router)+ app.state.bolt_app = FakeBolt(FakeClient())+ with TestClient(app) as client:+ res = client.post(+ "/internal/war-room",+ json={"case_id": "x"},+ headers={"X-AiSOC-Internal-Token": ""},+ )+ # A route that creates channels in somebody's workspace must not be+ # open to whatever can reach the pod.+ assert res.status_code == 401+++class TestPost:+ def test_it_says_one_thing(self, monkeypatch) -> None:+ fake = FakeClient()+ client = make_client(fake, monkeypatch)+ res = client.post(+ "/internal/war-room/post",+ json={"channel_id": "C0WARROOM1", "text": "*Status* is now `resolved`."},+ headers={"X-AiSOC-Internal-Token": TOKEN},+ )+ assert res.status_code == 202+ assert fake.messages[-1]["channel"] == "C0WARROOM1"++ def test_a_vendor_refusal_is_a_status_the_caller_can_act_on(self, monkeypatch) -> None:+ fake = FakeClient(post_raises=True)+ client = make_client(fake, monkeypatch)+ res = client.post(+ "/internal/war-room/post",+ json={"channel_id": "C0GONE", "text": "anything"},+ headers={"X-AiSOC-Internal-Token": TOKEN},+ )+ assert res.status_code == 502+ # The API records this verbatim as the room's `last_error`, and an+ # operator reading "channel_not_found" knows it was archived.+ assert "channel_not_found" in res.json()["detail"]++[email protected]("token", ["", None])+def test_post_also_requires_the_token(monkeypatch, token: str | None) -> None:+ client = make_client(FakeClient(), monkeypatch)+ headers = {"X-AiSOC-Internal-Token": token} if token is not None else {}+ res = client.post("/internal/war-room/post", json={"channel_id": "C", "text": "t"}, headers=headers)+ assert res.status_code == 401