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(slack-bot): WS-G1 — Slack Bolt service for /aisoc ChatOps

Beenu Arora4c5de65abd82
diff --git a/docker-compose.yml b/docker-compose.yml
index 4c6be8571..95bcc6a29 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -498,6 +498,37 @@ services:
- aisoc
restart: unless-stopped
+ # ChatOps adapter. Holds no state — forwards `/aisoc …` slash commands and
+ # approval-card button clicks to services/api and services/actions. Runs
+ # under the `chatops` profile so a default `docker compose up` doesn't fail
+ # when the operator has not yet provisioned a Slack app or service tokens.
+ slack-bot:
+ build:
+ context: ./services/slack-bot
+ dockerfile: Dockerfile
+ container_name: aisoc-slack-bot
+ depends_on:
+ - api
+ - actions
+ ports:
+ - "127.0.0.1:8009:8089"
+ profiles:
+ - chatops
+ environment:
+ SLACK_BOT_TOKEN: ${SLACK_BOT_TOKEN:-}
+ SLACK_SIGNING_SECRET: ${SLACK_SIGNING_SECRET:-}
+ AISOC_API_BASE_URL: http://api:8000
+ AISOC_ACTIONS_BASE_URL: http://actions:8085
+ AISOC_API_SERVICE_TOKEN: ${AISOC_SLACK_API_TOKEN:-}
+ AISOC_ACTIONS_SERVICE_TOKEN: ${AISOC_SLACK_ACTIONS_TOKEN:-}
+ AISOC_DEFAULT_TENANT_ID: ${AISOC_DEFAULT_TENANT_ID:-00000000-0000-0000-0000-000000000000}
+ AISOC_WEB_BASE_URL: ${AISOC_WEB_BASE_URL:-http://localhost:3000}
+ AISOC_SLACK_BOT_PORT: 8089
+ AISOC_HTTP_TIMEOUT_SECONDS: 10
+ networks:
+ - aisoc
+ restart: unless-stopped
+
web:
build:
context: .
diff --git a/services/slack-bot/Dockerfile b/services/slack-bot/Dockerfile
new file mode 100644
index 000000000..46861cb84
--- /dev/null
+++ b/services/slack-bot/Dockerfile
@@ -0,0 +1,25 @@
+FROM python:3.11-slim
+
+WORKDIR /app
+
+RUN pip install --no-cache-dir poetry==1.7.1 && \
+ poetry config virtualenvs.create false
+
+COPY pyproject.toml poetry.lock* ./
+RUN poetry install --no-interaction --no-ansi --no-dev 2>/dev/null || \
+ pip install --no-cache-dir \
+ fastapi \
+ "uvicorn[standard]" \
+ pydantic \
+ pydantic-settings \
+ slack-bolt \
+ slack-sdk \
+ "aiohttp>=3.9,<4.0" \
+ httpx \
+ structlog
+
+COPY app/ ./app/
+
+EXPOSE 8089
+
+CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8089"]
diff --git a/services/slack-bot/README.md b/services/slack-bot/README.md
new file mode 100644
index 000000000..02df96387
--- /dev/null
+++ b/services/slack-bot/README.md
@@ -0,0 +1,159 @@
+# AiSOC Slack Bot
+
+ChatOps surface for AiSOC: slash commands and interactive approval flows that
+let an L1/L2 analyst run the SOC without leaving Slack.
+
+This service is a thin **adapter** — it owns no security state. Every request
+is forwarded to `services/api` (cases, alerts, investigations) or
+`services/actions` (response actions, approvals) using a service-scoped
+`aisoc_*` API key. The bot itself just translates Slack events ↔ AiSOC HTTP
+calls and renders the result as Block Kit messages.
+
+## Slash commands
+
+All commands live under a single `/aisoc` slash command (Slack only allows
+verb-based parsing inside the command text).
+
+| Command | Behaviour |
+| ------------------------------- | ---------------------------------------------------------------------- |
+| `/aisoc list` | Open cases (top 10), severity-coloured cards, links into the web UI. |
+| `/aisoc investigate <case>` | Kick off an investigation run for the case (no LLM cost in air-gap). |
+| `/aisoc explain <case>` | Pull the per-case auto-summary (`GET /cases/{id}/summary`). |
+| `/aisoc isolate <host>` | Submit `isolate_host` action — gated, posts an approval card. |
+| `/aisoc block <ip>` | Submit `block_ip` action — gated, posts an approval card. |
+| `/aisoc help` | Inline command reference. |
+
+`isolate` and `block` always require explicit human approval; the bot posts a
+"Approve / Deny" card and forwards the analyst's choice back to
+`services/actions`.
+
+## Configuration
+
+Configured entirely via environment variables (Pydantic settings):
+
+| Variable | Required | Description |
+| ------------------------------------- | -------- | ------------------------------------------------------------ |
+| `SLACK_BOT_TOKEN` | yes | `xoxb-…` — bot user OAuth token. |
+| `SLACK_SIGNING_SECRET` | yes | Used by Bolt to verify incoming Slack request signatures. |
+| `AISOC_API_BASE_URL` | yes | e.g. `http://aisoc-api:8000` (in-cluster). |
+| `AISOC_ACTIONS_BASE_URL` | yes | e.g. `http://aisoc-actions:8085` (in-cluster). |
+| `AISOC_API_SERVICE_TOKEN` | yes | `aisoc_…` API key with `cases:read,cases:write,alerts:read`. |
+| `AISOC_ACTIONS_SERVICE_TOKEN` | yes | `aisoc_…` API key with `actions:write` (or shared key). |
+| `AISOC_WEB_BASE_URL` | no | Public web URL used to deep-link case cards. Default `https://app.tryaisoc.com`. |
+| `AISOC_DEFAULT_TENANT_ID` | yes | UUID of the tenant Slack actions belong to (single-tenant Slack workspace assumption). |
+| `AISOC_SLACK_BOT_PORT` | no | Bolt FastAPI port. Default `8089`. |
+
+Secrets must be mounted via your secret store (Doppler / Vault / k8s Secret) —
+do **not** check them into the repo. `pnpm preflight` will fail if it detects
+a Slack token in tracked files.
+
+## Local dev
+
+### Standalone (poetry)
+
+```bash
+poetry install
+export SLACK_BOT_TOKEN=xoxb-…
+export SLACK_SIGNING_SECRET=…
+export AISOC_API_BASE_URL=http://localhost:8000
+export AISOC_ACTIONS_BASE_URL=http://localhost:8002
+export AISOC_API_SERVICE_TOKEN=aisoc_…
+export AISOC_ACTIONS_SERVICE_TOKEN=aisoc_…
+export AISOC_DEFAULT_TENANT_ID=00000000-0000-0000-0000-000000000000
+poetry run uvicorn app.main:app --reload --port 8089
+```
+
+Then expose `http://localhost:8089/slack/events` to Slack via `ngrok`/`cloudflared`.
+
+### Inside docker-compose
+
+The service is gated behind the `chatops` profile so a default
+`docker compose up` doesn't fail when no Slack app is configured. To bring
+it up alongside the rest of the stack:
+
+```bash
+# in repo root .env (do not commit)
+SLACK_BOT_TOKEN=xoxb-…
+SLACK_SIGNING_SECRET=…
+AISOC_SLACK_API_TOKEN=aisoc_… # cases:read, cases:write, alerts:read
+AISOC_SLACK_ACTIONS_TOKEN=aisoc_… # actions:write
+AISOC_DEFAULT_TENANT_ID=00000000-0000-0000-0000-000000000000
+
+docker compose --profile chatops up slack-bot
+```
+
+The bot listens on `127.0.0.1:8009` on the host (mapped to `8089` inside the
+container). Point Slack's request URL at
+`https://<your-tunnel>/slack/events`.
+
+## Slack app review checklist
+
+Before submitting to the Slack app directory (target: end of week 12 in the
+buyer-value plan), confirm every box below. The manifest under
+`marketplace/slack-app/manifest.json` should match this configuration
+verbatim.
+
+### App configuration
+
+- [ ] **OAuth scopes (bot)**: `chat:write`, `commands`, `users:read`,
+ `users:read.email`, `im:write`. We do not need `channels:history` —
+ v1 only reacts to slash commands and interactive payloads.
+- [ ] **Slash command**: `/aisoc` registered with request URL
+ `https://<deployment>/slack/events`. *(Bolt's FastAPI adapter routes
+ slash commands, interactive payloads, and the URL-verification
+ handshake through a single endpoint — there are no separate
+ `/slack/commands` or `/slack/interactive` URLs.)*
+- [ ] **Interactivity & shortcuts**: enabled, request URL
+ `https://<deployment>/slack/events`.
+- [ ] **Event subscriptions**: enabled, request URL
+ `https://<deployment>/slack/events`. No bot events are subscribed to
+ for v1; the endpoint only needs to respond to `url_verification`.
+- [ ] **Tokens**: bot token rotated for production; signing secret deployed
+ via your secret store, not committed.
+
+### Listing
+
+- [ ] **Privacy policy URL** + **support contact email** populated and
+ reachable.
+- [ ] **App icon (512×512)** and **app description** match the marketplace
+ listing copy.
+- [ ] **Long description** explains the data Slack ↔ AiSOC exchanges (case
+ titles, severity, host/IP identifiers in approval prompts) and that
+ AiSOC stores no Slack message content beyond the audit-trail event
+ noting which user approved or denied an action.
+
+### End-to-end verification
+
+- [ ] **Beta workspace** has run end-to-end through every slash command:
+ `list`, `investigate`, `explain`, `isolate`, `block`, `help`.
+- [ ] **Approval flow** validated by a real analyst: both *Approve* and
+ *Deny* paths produce the expected audit-trail entry on the underlying
+ case in `services/actions`.
+- [ ] **Failure modes** verified — invalid case ID, missing argument,
+ backend timeout — all produce ephemeral error responses with no stack
+ traces leaked to Slack.
+- [ ] **Test note** in the review submission documents the demo workspace
+ credentials and a reproducible scenario reviewers can run.
+
+### Infra
+
+- [ ] Public Slack request URL terminates TLS at the edge (`tryaisoc.com`
+ ingress / Cloudflare) before reaching the bot.
+- [ ] Health check at `/health` is wired into the deployment platform's
+ probe (Fly.io / k8s) — review will not block on this, but production
+ alerting depends on it.
+- [ ] `SLACK_SIGNING_SECRET` is **set** in the deployed environment. The
+ bot intentionally allows an empty secret in tests; a missing secret
+ in prod logs a `slack_signing_secret_missing` warning at boot but
+ does not crash, so deployment dashboards must surface that warning
+ explicitly.
+
+## Tests
+
+```bash
+poetry run pytest
+```
+
+Unit tests cover Block Kit builders, the AiSOC HTTP clients (with `respx`
+mocks), command parsing, and approve/deny action handlers. They do not call
+the real Slack API.
diff --git a/services/slack-bot/app/__init__.py b/services/slack-bot/app/__init__.py
new file mode 100644
index 000000000..45ab23405
--- /dev/null
+++ b/services/slack-bot/app/__init__.py
@@ -0,0 +1 @@
+"""AiSOC Slack bot service."""
diff --git a/services/slack-bot/app/blocks.py b/services/slack-bot/app/blocks.py
new file mode 100644
index 000000000..9915da9df
--- /dev/null
+++ b/services/slack-bot/app/blocks.py
@@ -0,0 +1,434 @@
+"""
+Slack Block Kit builders for the AiSOC bot.
+
+Every Slack response in the bot — slash command output, approval prompts,
+post-decision confirmations — flows through one of these helpers. Centralising
+them here means:
+
+* the layout is unit-testable (we just compare dicts)
+* the command handlers stay small and focused on orchestration
+* visual consistency stays high (severity emoji, deep-link URLs, action ids)
+
+Block Kit reference: https://api.slack.com/block-kit
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from urllib.parse import urljoin
+
+# --- Severity / status presentation -----------------------------------------
+
+# Severity → emoji used at the start of every case headline. Slack-friendly
+# unicode so we don't depend on a custom emoji pack being installed in the
+# workspace.
+_SEVERITY_EMOJI = {
+ "critical": "🚨",
+ "high": "🔴",
+ "medium": "🟠",
+ "low": "🟡",
+ "info": "🔵",
+}
+
+# Status → label. We capitalise + de-snake-case so the audit trail in Slack
+# matches what an analyst sees in the web UI.
+_STATUS_LABEL = {
+ "new": "New",
+ "triaged": "Triaged",
+ "investigating": "Investigating",
+ "containment": "Containment",
+ "remediated": "Remediated",
+ "closed": "Closed",
+ "false_positive": "False positive",
+}
+
+
+def _sev_label(severity: str | None) -> str:
+ if not severity:
+ return "🔵 Info"
+ key = severity.lower()
+ return f"{_SEVERITY_EMOJI.get(key, '⚪')} {key.title()}"
+
+
+def _status_label(status: str | None) -> str:
+ if not status:
+ return "Unknown"
+ return _STATUS_LABEL.get(status.lower(), status.replace("_", " ").title())
+
+
+def _case_url(web_base: str, case_id: str) -> str:
+ """
+ Build a deep-link to the case in the web app. Slack requires absolute URLs
+ in link buttons, so we always emit a fully-qualified ``https://`` URL even
+ if the bot is configured with a base ending in ``/``.
+ """
+ return urljoin(web_base.rstrip("/") + "/", f"cases/{case_id}")
+
+
+def _truncate(text: str, *, limit: int = 240) -> str:
+ """
+ Slack section text caps at 3000 chars. We keep things much shorter so
+ cards stay readable in a busy SOC channel.
+ """
+ text = (text or "").strip()
+ if len(text) <= limit:
+ return text
+ return text[: limit - 1].rstrip() + "…"
+
+
+# --- Public builders --------------------------------------------------------
+
+
+def case_list_blocks(
+ cases: list[dict[str, Any]],
+ *,
+ web_base: str,
+ title: str = "Open cases",
+) -> list[dict[str, Any]]:
+ """
+ Render the response to ``/aisoc list``.
+
+ We render at most ten cases (Slack performance + screen-real-estate) and
+ add a footer that prompts the analyst to filter further if the result was
+ truncated.
+ """
+ if not cases:
+ return [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": f"*{title}* — nothing to triage right now. ✅",
+ },
+ }
+ ]
+
+ blocks: list[dict[str, Any]] = [
+ {
+ "type": "header",
+ "text": {"type": "plain_text", "text": title, "emoji": True},
+ }
+ ]
+
+ visible = cases[:10]
+ for case in visible:
+ case_id = str(case.get("id") or "")
+ case_number = case.get("case_number") or case_id[:8]
+ title_text = case.get("title") or "(untitled case)"
+ severity = _sev_label(case.get("severity"))
+ status = _status_label(case.get("status"))
+ url = _case_url(web_base, case_id) if case_id else web_base
+ line = f"*<{url}|{case_number}>* — {_truncate(title_text, limit=120)}\n{severity} · _{status}_"
+ blocks.append(
+ {
+ "type": "section",
+ "text": {"type": "mrkdwn", "text": line},
+ }
+ )
+
+ if len(cases) > len(visible):
+ blocks.append(
+ {
+ "type": "context",
+ "elements": [
+ {
+ "type": "mrkdwn",
+ "text": (f"Showing {len(visible)} of {len(cases)} open cases — use `/aisoc list <severity>` to narrow."),
+ }
+ ],
+ }
+ )
+
+ return blocks
+
+
+def case_card_blocks(
+ case: dict[str, Any],
+ *,
+ web_base: str,
+) -> list[dict[str, Any]]:
+ """
+ Render a single-case detail card used as the parent message for
+ ``/aisoc investigate`` and ``/aisoc explain``.
+ """
+ case_id = str(case.get("id") or "")
+ case_number = case.get("case_number") or case_id[:8]
+ title = case.get("title") or "(untitled case)"
+ severity = _sev_label(case.get("severity"))
+ status = _status_label(case.get("status"))
+ description = _truncate(case.get("description") or "")
+ url = _case_url(web_base, case_id) if case_id else web_base
+
+ fields = [
+ {"type": "mrkdwn", "text": f"*Severity*\n{severity}"},
+ {"type": "mrkdwn", "text": f"*Status*\n{status}"},
+ ]
+ alert_count = case.get("alert_count")
+ if alert_count is not None:
+ fields.append({"type": "mrkdwn", "text": f"*Alerts*\n{alert_count}"})
+ if case.get("priority"):
+ fields.append({"type": "mrkdwn", "text": f"*Priority*\n{case['priority']}"})
+
+ blocks: list[dict[str, Any]] = [
+ {
+ "type": "header",
+ "text": {
+ "type": "plain_text",
+ "text": f"Case {case_number}",
+ "emoji": True,
+ },
+ },
+ {
+ "type": "section",
+ "text": {"type": "mrkdwn", "text": f"*{title}*"},
+ "accessory": {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Open in AiSOC"},
+ "url": url,
+ "action_id": "case_open_link",
+ },
+ },
+ {"type": "section", "fields": fields},
+ ]
+ if description:
+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": description}})
+
+ return blocks
+
+
+def investigation_started_blocks(
+ case: dict[str, Any],
+ investigation: dict[str, Any],
+ *,
+ web_base: str,
+) -> list[dict[str, Any]]:
+ """
+ Confirmation message after ``/aisoc investigate`` succeeds.
+
+ We include the run id and a deep-link so the analyst can hop straight to
+ the live timeline in the web app.
+ """
+ case_id = str(case.get("id") or "")
+ case_number = case.get("case_number") or case_id[:8]
+ run_id = investigation.get("run_id") or investigation.get("id") or "(pending)"
+ deep_link = _case_url(web_base, case_id) if case_id else web_base
+
+ return [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": (f"🛰️ *Investigation launched* for <{deep_link}|{case_number}>\nRun id: `{run_id}`"),
+ },
+ },
+ {
+ "type": "context",
+ "elements": [
+ {
+ "type": "mrkdwn",
+ "text": "Live timeline updates will appear in the case channel.",
+ }
+ ],
+ },
+ ]
+
+
+def case_explanation_blocks(
+ case: dict[str, Any],
+ summary: dict[str, Any],
+ *,
+ web_base: str,
+) -> list[dict[str, Any]]:
+ """
+ Render a case auto-summary as Slack blocks (``/aisoc explain``).
+
+ The summary endpoint returns a JSON payload with at minimum a ``summary``
+ or ``narrative`` field; we surface both that and any structured
+ ``recommendations`` / ``next_steps`` lists when present.
+ """
+ blocks = case_card_blocks(case, web_base=web_base)
+
+ narrative = summary.get("summary") or summary.get("narrative") or summary.get("explanation") or ""
+ if narrative:
+ blocks.append(
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": f"*AI summary*\n{_truncate(narrative, limit=2500)}",
+ },
+ }
+ )
+
+ recommendations = summary.get("recommendations") or summary.get("next_steps") or []
+ if isinstance(recommendations, list) and recommendations:
+ bullets = "\n".join(f"• {_truncate(str(r), limit=300)}" for r in recommendations[:6])
+ blocks.append(
+ {
+ "type": "section",
+ "text": {"type": "mrkdwn", "text": f"*Recommended next steps*\n{bullets}"},
+ }
+ )
+
+ return blocks
+
+
+def approval_card_blocks(
+ *,
+ action: dict[str, Any],
+ case: dict[str, Any],
+ requested_by_slack_id: str,
+ web_base: str,
+) -> list[dict[str, Any]]:
+ """
+ Render an approval prompt for an awaiting-approval response action.
+
+ The ``action_id`` and ``case_id`` are stuffed into the button's ``value``
+ field so the interactive handler can route the approval without a
+ round-trip to the database.
+ """
+ action_id = str(action.get("id") or action.get("action_id") or "")
+ action_type = action.get("action_type") or "unknown"
+ target = action.get("target") or "unknown"
+ blast = action.get("blast_radius") or "unknown"
+ case_id = str(case.get("id") or "")
+ case_number = case.get("case_number") or case_id[:8]
+ rationale = _truncate(action.get("rationale") or "", limit=400)
+ case_url = _case_url(web_base, case_id) if case_id else web_base
+
+ button_value = f"{action_id}|{case_id}"
+
+ headline = (
+ f"⚠️ *Approval required* — `{action_type}` on `{target}`\nCase: <{case_url}|{case_number}> · Requested by <@{requested_by_slack_id}>"
+ )
+
+ return [
+ {"type": "section", "text": {"type": "mrkdwn", "text": headline}},
+ {
+ "type": "section",
+ "fields": [
+ {"type": "mrkdwn", "text": f"*Action*\n`{action_type}`"},
+ {"type": "mrkdwn", "text": f"*Target*\n`{target}`"},
+ {"type": "mrkdwn", "text": f"*Blast radius*\n{blast}"},
+ {"type": "mrkdwn", "text": f"*Action id*\n`{action_id}`"},
+ ],
+ },
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": f"*Rationale*\n{rationale or '_(none provided)_'}",
+ },
+ },
+ {
+ "type": "actions",
+ "block_id": "aisoc_action_decision",
+ "elements": [
+ {
+ "type": "button",
+ "style": "primary",
+ "text": {"type": "plain_text", "text": "Approve"},
+ "action_id": "aisoc_action_approve",
+ "value": button_value,
+ "confirm": {
+ "title": {"type": "plain_text", "text": "Approve action?"},
+ "text": {
+ "type": "mrkdwn",
+ "text": (f"This will execute `{action_type}` on `{target}` and is logged to the case timeline."),
+ },
+ "confirm": {"type": "plain_text", "text": "Approve"},
+ "deny": {"type": "plain_text", "text": "Cancel"},
+ },
+ },
+ {
+ "type": "button",
+ "style": "danger",
+ "text": {"type": "plain_text", "text": "Deny"},
+ "action_id": "aisoc_action_deny",
+ "value": button_value,
+ },
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Open case"},
+ "url": case_url,
+ "action_id": "aisoc_action_open_case",
+ },
+ ],
+ },
+ ]
+
+
+def action_decision_blocks(
+ *,
+ decision: str,
+ action: dict[str, Any],
+ decided_by_slack_id: str,
+) -> list[dict[str, Any]]:
+ """
+ Render the post-decision message that replaces the approval card.
+
+ We deliberately strip the buttons so an action can't be approved twice;
+ the audit trail is preserved in services/actions and surfaced on the case
+ timeline. ``decision`` is ``"approved"`` or ``"rejected"`` (caller is
+ responsible for normalising).
+ """
+ decision = decision.lower()
+ icon = {"approved": "✅", "rejected": "🛑"}.get(decision, "ℹ️")
+ verb = {"approved": "approved", "rejected": "denied"}.get(decision, decision)
+ action_id = str(action.get("id") or action.get("action_id") or "")
+ action_type = action.get("action_type") or "unknown"
+ target = action.get("target") or "unknown"
+
+ return [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": (f"{icon} <@{decided_by_slack_id}> *{verb}* `{action_type}` on `{target}` · action `{action_id}`"),
+ },
+ },
+ ]
+
+
+def error_blocks(message: str) -> list[dict[str, Any]]:
+ """
+ Render a one-line error response. Used when the backend call fails or the
+ user's slash command syntax is wrong; never include a stack trace because
+ Slack messages can leak into customer screen-shares.
+ """
+ return [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": f"❌ {_truncate(message, limit=400)}",
+ },
+ }
+ ]
+
+
+def help_blocks() -> list[dict[str, Any]]:
+ """
+ Static help text rendered for ``/aisoc help`` and as a fallback for
+ unknown subcommands.
+ """
+ return [
+ {
+ "type": "header",
+ "text": {"type": "plain_text", "text": "AiSOC Slack commands"},
+ },
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": (
+ "*`/aisoc list [severity]`* — list open cases\n"
+ "*`/aisoc investigate <case_id>`* — launch an investigation\n"
+ "*`/aisoc explain <case_id>`* — show the AI auto-summary\n"
+ "*`/aisoc isolate <host> <case_id> [reason]`* — request host isolation (approval required)\n"
+ "*`/aisoc block <ip|domain> <case_id> [reason]`* — request a network block (approval required)\n"
+ "*`/aisoc help`* — show this message"
+ ),
+ },
+ },
+ ]
diff --git a/services/slack-bot/app/commands.py b/services/slack-bot/app/commands.py
new file mode 100644
index 000000000..21ae58870
--- /dev/null
+++ b/services/slack-bot/app/commands.py
@@ -0,0 +1,289 @@
+"""
+Pure-Python slash-command dispatcher for ``/aisoc``.
+
+We deliberately keep the dispatcher independent of Slack Bolt: it consumes
+plain values (text, user id) and returns a Slack response payload as a dict.
+This means:
+
+* every subcommand is unit-testable without starting an ASGI app
+* the Bolt wrapper in :mod:`app.main` becomes a 5-line shim around this
+* failures uniformly translate to ephemeral error blocks (private to the
+ user) so we never accidentally leak a stack trace into a public channel
+
+Supported subcommands
+---------------------
+
+``list [severity]``
+ List open cases. Severity is an optional filter (``low``/``medium``/
+ ``high``/``critical``).
+
+``investigate <case>``
+ Kick off an investigation run for the given case id or case number.
+
+``explain <case>``
+ Render the latest AI summary for the case.
+
+``isolate <host> <case> [reason…]``
+ Request host isolation (approval required for non-low blast radius).
+
+``block <ip|domain> <case> [reason…]``
+ Request a network block.
+
+``help``
+ Render the supported subcommands.
+"""
+
+from __future__ import annotations
+
+import shlex
+from typing import Any
+
+from app.blocks import (
+ approval_card_blocks,
+ case_explanation_blocks,
+ case_list_blocks,
+ error_blocks,
+ help_blocks,
+ investigation_started_blocks,
+)
+from app.services.aisoc_clients import (
+ AisocActionsClient,
+ AisocApiClient,
+ AisocClientError,
+)
+
+# ────────────────────────────────────────────────────────────────────────────
+# Response helpers
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def _ephemeral(blocks: list[dict[str, Any]], *, fallback: str) -> dict[str, Any]:
+ """Private response visible only to the invoking user."""
+ return {"response_type": "ephemeral", "text": fallback, "blocks": blocks}
+
+
+def _in_channel(blocks: list[dict[str, Any]], *, fallback: str) -> dict[str, Any]:
+ """Public response visible to everyone in the channel."""
+ return {"response_type": "in_channel", "text": fallback, "blocks": blocks}
+
+
+def _error(message: str) -> dict[str, Any]:
+ return _ephemeral(error_blocks(message), fallback=message)
+
+
+def _parse_tokens(text: str) -> list[str]:
+ """
+ Split a slash-command argument string. We use ``shlex`` so analysts can
+ pass quoted reasons that include spaces, e.g. ``isolate host-1 c-7
+ "confirmed beacon to known-bad C2"``.
+ """
+ text = (text or "").strip()
+ if not text:
+ return []
+ try:
+ return shlex.split(text, posix=True)
+ except ValueError:
+ # shlex chokes on unbalanced quotes — fall back to whitespace split.
+ return text.split()
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Subcommand implementations
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def _cmd_list(
+ args: list[str],
+ *,
+ api_client: AisocApiClient,
+ web_base: str,
+) -> dict[str, Any]:
+ severity = args[0].lower() if args else None
+ if severity and severity not in {"low", "medium", "high", "critical"}:
+ return _error(f"Unknown severity `{severity}`. Use low|medium|high|critical.")
+ try:
+ cases = await api_client.list_open_cases(limit=10, severity=severity)
+ except AisocClientError as exc:
+ return _error(f"Could not load cases: {exc}")
+
+ title = "Open cases" if not severity else f"Open cases · {severity.title()}"
+ blocks = case_list_blocks(cases, web_base=web_base, title=title)
+ return _ephemeral(blocks, fallback=title)
+
+
+async def _cmd_investigate(
+ args: list[str],
+ *,
+ api_client: AisocApiClient,
+ web_base: str,
+ user_id: str,
+) -> dict[str, Any]:
+ if not args:
+ return _error("Usage: `/aisoc investigate <case_id>`")
+ case_id = args[0]
+ try:
+ case = await api_client.get_case(case_id)
+ # Use the requesting Slack user id as a lightweight rationale source so
+ # the case timeline records who fired the run from chat.
+ investigation = await api_client.launch_investigation(case_id, alert_summary=f"investigation requested by Slack user {user_id}")
+ except AisocClientError as exc:
+ return _error(f"Investigation failed: {exc}")
+
+ blocks = investigation_started_blocks(case, investigation, web_base=web_base)
+ return _in_channel(blocks, fallback=f"Investigation launched for case {case_id}")
+
+
+async def _cmd_explain(
+ args: list[str],
+ *,
+ api_client: AisocApiClient,
+ web_base: str,
+) -> dict[str, Any]:
+ if not args:
+ return _error("Usage: `/aisoc explain <case_id>`")
+ case_id = args[0]
+ try:
+ case = await api_client.get_case(case_id)
+ summary = await api_client.get_case_summary(case_id)
+ except AisocClientError as exc:
+ return _error(f"Could not summarise case: {exc}")
+
+ blocks = case_explanation_blocks(case, summary, web_base=web_base)
+ return _in_channel(blocks, fallback=f"Case {case_id} summary")
+
+
+async def _cmd_action(
+ args: list[str],
+ *,
+ api_client: AisocApiClient,
+ actions_client: AisocActionsClient,
+ web_base: str,
+ user_id: str,
+ action_type: str,
+ usage: str,
+) -> dict[str, Any]:
+ """
+ Shared implementation for ``isolate`` and ``block``.
+
+ Both commands have the same shape (``<target> <case> [reason…]``) and
+ differ only in ``action_type``, so we centralise the parsing + submission
+ here to keep the surface tiny.
+ """
+ if len(args) < 2:
+ return _error(f"Usage: `{usage}`")
+
+ target, case_ref, *reason_parts = args
+ rationale = " ".join(reason_parts) if reason_parts else "Submitted via Slack"
+
+ try:
+ case = await api_client.get_case(case_ref)
+ case_id = str(case.get("id") or case_ref)
+ action = await actions_client.submit_action(
+ action_type=action_type,
+ target=target,
+ case_id=case_id,
+ rationale=rationale,
+ requested_by=user_id,
+ )
+ except AisocClientError as exc:
+ return _error(f"Action submission failed: {exc}")
+
+ status = (action.get("status") or "").lower()
+ if status in {"awaiting_approval", "pending_approval", "pending"}:
+ blocks = approval_card_blocks(
+ action=action,
+ case=case,
+ requested_by_slack_id=user_id,
+ web_base=web_base,
+ )
+ return _in_channel(
+ blocks,
+ fallback=f"Approval required: {action_type} {target}",
+ )
+
+ # Auto-approved (low-blast actions): emit a confirmation rather than a
+ # button card.
+ fallback = f"{action_type} on {target} submitted (status: {status or 'unknown'})"
+ return _in_channel(
+ [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": (
+ f"✅ <@{user_id}> submitted `{action_type}` on `{target}` "
+ f"for case <{web_base.rstrip('/')}/cases/{case.get('id', '')}|"
+ f"{case.get('case_number') or case.get('id', '')}> · "
+ f"status `{status or 'unknown'}`"
+ ),
+ },
+ }
+ ],
+ fallback=fallback,
+ )
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Top-level dispatcher
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def handle_aisoc_command(
+ *,
+ text: str,
+ user_id: str,
+ api_client: AisocApiClient,
+ actions_client: AisocActionsClient,
+ web_base: str,
+) -> dict[str, Any]:
+ """
+ Dispatch a parsed ``/aisoc`` command to the right subcommand.
+
+ The function never raises — every exception path is converted to an
+ ephemeral error block so the user always gets useful feedback in Slack.
+ """
+ tokens = _parse_tokens(text)
+ if not tokens:
+ return _ephemeral(help_blocks(), fallback="AiSOC Slack help")
+
+ sub, *rest = tokens
+ sub = sub.lower()
+
+ if sub in {"help", "?", "-h", "--help"}:
+ return _ephemeral(help_blocks(), fallback="AiSOC Slack help")
+
+ if sub == "list":
+ return await _cmd_list(rest, api_client=api_client, web_base=web_base)
+
+ if sub == "investigate":
+ return await _cmd_investigate(rest, api_client=api_client, web_base=web_base, user_id=user_id)
+
+ if sub == "explain":
+ return await _cmd_explain(rest, api_client=api_client, web_base=web_base)
+
+ if sub == "isolate":
+ return await _cmd_action(
+ rest,
+ api_client=api_client,
+ actions_client=actions_client,
+ web_base=web_base,
+ user_id=user_id,
+ action_type="isolate_host",
+ usage="/aisoc isolate <host> <case_id> [reason]",
+ )
+
+ if sub == "block":
+ return await _cmd_action(
+ rest,
+ api_client=api_client,
+ actions_client=actions_client,
+ web_base=web_base,
+ user_id=user_id,
+ action_type="block_ip",
+ usage="/aisoc block <ip|domain> <case_id> [reason]",
+ )
+
+ return _ephemeral(
+ help_blocks(),
+ fallback=f"Unknown subcommand `{sub}`. See `/aisoc help`.",
+ )
diff --git a/services/slack-bot/app/core/__init__.py b/services/slack-bot/app/core/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/services/slack-bot/app/core/config.py b/services/slack-bot/app/core/config.py
new file mode 100644
index 000000000..df93a0160
--- /dev/null
+++ b/services/slack-bot/app/core/config.py
@@ -0,0 +1,106 @@
+"""
+Application configuration for the AiSOC Slack bot.
+
+All secrets (Slack tokens, AiSOC API keys) come from environment variables /
+mounted secret files. The bot itself stores nothing — it only forwards
+requests to ``services/api`` and ``services/actions``.
+"""
+
+from __future__ import annotations
+
+from functools import lru_cache
+
+from pydantic import Field
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+
+class SlackBotSettings(BaseSettings):
+ """
+ Runtime configuration for the Slack bot.
+
+ Loaded from process environment (``.env`` is honoured for local dev).
+ Field names match the env var names exactly so deployment manifests can
+ map secrets directly without a translation table.
+ """
+
+ model_config = SettingsConfigDict(
+ env_file=".env",
+ env_file_encoding="utf-8",
+ case_sensitive=True,
+ extra="ignore",
+ )
+
+ # --- Slack -------------------------------------------------------------
+
+ SLACK_BOT_TOKEN: str = Field(
+ default="",
+ description="Slack bot user OAuth token (xoxb-…).",
+ )
+ SLACK_SIGNING_SECRET: str = Field(
+ default="",
+ description=(
+ "Slack signing secret used by Bolt to verify request signatures. "
+ "Required in production; an empty value disables signature checks "
+ "and is only acceptable for local pytest runs."
+ ),
+ )
+
+ # --- AiSOC backend -----------------------------------------------------
+
+ AISOC_API_BASE_URL: str = Field(
+ default="http://aisoc-api:8000",
+ description="Base URL for the services/api FastAPI app.",
+ )
+ AISOC_ACTIONS_BASE_URL: str = Field(
+ default="http://aisoc-actions:8085",
+ description="Base URL for the services/actions FastAPI app.",
+ )
+ AISOC_API_SERVICE_TOKEN: str = Field(
+ default="",
+ description=("aisoc_… API key the bot uses to call services/api. Must hold at least cases:read, cases:write, alerts:read."),
+ )
+ AISOC_ACTIONS_SERVICE_TOKEN: str = Field(
+ default="",
+ description=("aisoc_… API key for services/actions. May reuse the API service token if the same principal has actions:write."),
+ )
+
+ # --- Tenant + UX -------------------------------------------------------
+
+ AISOC_DEFAULT_TENANT_ID: str = Field(
+ default="00000000-0000-0000-0000-000000000000",
+ description=(
+ "Tenant UUID associated with this Slack workspace. v1 assumes a "
+ "single Slack workspace ↔ single AiSOC tenant mapping; multi-"
+ "tenant workspaces will be addressed in a later workstream."
+ ),
+ )
+ AISOC_WEB_BASE_URL: str = Field(
+ default="https://app.tryaisoc.com",
+ description="Public web app URL used to deep-link case cards.",
+ )
+
+ # --- Service plumbing --------------------------------------------------
+
+ AISOC_SLACK_BOT_PORT: int = Field(
+ default=8089,
+ description="Port the FastAPI app should listen on.",
+ )
+ AISOC_HTTP_TIMEOUT_SECONDS: float = Field(
+ default=10.0,
+ description="Default timeout for outbound HTTP calls to AiSOC services.",
+ )
+
+ # --- Helpers -----------------------------------------------------------
+
+ @property
+ def signature_verification_enabled(self) -> bool:
+ """
+ Bolt's signature verification is mandatory in production. Tests run
+ without a signing secret, so we let them opt out explicitly.
+ """
+ return bool(self.SLACK_SIGNING_SECRET)
+
+
+@lru_cache(maxsize=1)
+def get_settings() -> SlackBotSettings:
+ return SlackBotSettings()
diff --git a/services/slack-bot/app/core/logging.py b/services/slack-bot/app/core/logging.py
new file mode 100644
index 000000000..eca19ef2c
--- /dev/null
+++ b/services/slack-bot/app/core/logging.py
@@ -0,0 +1,34 @@
+"""Structured logging setup for the Slack bot."""
+
+from __future__ import annotations
+
+import logging
+
+import structlog
+
+
+def configure_logging(level: str = "INFO") -> None:
+ """
+ Configure structlog with JSON output. Idempotent — safe to call multiple
+ times (Bolt + FastAPI may both initialise logging).
+ """
+ logging.basicConfig(
+ format="%(message)s",
+ level=getattr(logging, level.upper(), logging.INFO),
+ )
+ structlog.configure(
+ processors=[
+ structlog.contextvars.merge_contextvars,
+ structlog.processors.add_log_level,
+ structlog.processors.TimeStamper(fmt="iso"),
+ structlog.processors.StackInfoRenderer(),
+ structlog.processors.format_exc_info,
+ structlog.processors.JSONRenderer(),
+ ],
+ wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
+ cache_logger_on_first_use=True,
+ )
+
+
+def get_logger(name: str) -> structlog.stdlib.BoundLogger:
+ return structlog.get_logger(name)
diff --git a/services/slack-bot/app/interactions.py b/services/slack-bot/app/interactions.py
new file mode 100644
index 000000000..d4f528e67
--- /dev/null
+++ b/services/slack-bot/app/interactions.py
@@ -0,0 +1,186 @@
+"""
+Interactive component handlers for the AiSOC Slack bot.
+
+Slack delivers a single ``block_actions`` payload whenever the analyst
+clicks a button on a message we sent. This module isolates the *logic*
+side of those events — the decoding of the routing token, the call into
+``services/actions``, and the construction of the reply blocks — from
+the Bolt transport layer in :mod:`app.main`.
+
+Why a pure-Python module again
+==============================
+
+Same reasoning as :mod:`app.commands`:
+
+* the Bolt wrapper stays a 5-line shim (``ack`` → ``handle_action_decision``
+ → ``respond``)
+* every branch — happy path, malformed value, upstream failure — is
+ covered by a fast hermetic unit test
+* error messages never leak a stack trace into a public Slack channel
+
+Action ids
+----------
+
+The approval card emits two button ids that this module knows how to
+handle:
+
+* ``aisoc_action_approve``
+* ``aisoc_action_deny``
+
+The button ``value`` is encoded by :func:`app.blocks.approval_card_blocks`
+as ``"<action_id>|<case_id>"``. We decode that here so the dispatcher
+can avoid a database lookup just to know which case the button belonged
+to (handy for the audit-trail message we post after the decision).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from app.blocks import action_decision_blocks, error_blocks
+from app.services.aisoc_clients import AisocActionsClient, AisocClientError
+
+#: Action id emitted by the *Approve* button on the approval card.
+APPROVE_ACTION_ID = "aisoc_action_approve"
+
+#: Action id emitted by the *Deny* button on the approval card.
+DENY_ACTION_ID = "aisoc_action_deny"
+
+#: Decision strings we send back to ``services/actions``. Kept in a constant
+#: so a typo can't slip into the network payload.
+_DECISION_APPROVE = "approved"
+_DECISION_REJECT = "rejected"
+
+
+def _decode_routing_value(value: str) -> tuple[str, str]:
+ """
+ Pull ``action_id`` and ``case_id`` out of the button ``value``.
+
+ The encoder is :func:`app.blocks.approval_card_blocks`, which uses the
+ format ``"<action_id>|<case_id>"``. We accept a missing case id (the
+ case id is informational on the audit-trail line and not strictly
+ required to call ``services/actions``), but a missing action id is
+ fatal — the upstream call is meaningless without it.
+
+ Raises
+ ------
+ ValueError
+ If ``value`` is empty or does not contain a non-empty action id.
+ """
+ if not value:
+ raise ValueError("missing routing value on action button")
+ parts = value.split("|", 1)
+ action_id = parts[0].strip()
+ case_id = parts[1].strip() if len(parts) > 1 else ""
+ if not action_id:
+ raise ValueError("routing value is missing the action id")
+ return action_id, case_id
+
+
+def _ephemeral(blocks: list[dict[str, Any]], *, fallback: str) -> dict[str, Any]:
+ """
+ Private follow-up message visible only to the analyst who clicked.
+
+ Used for parser/upstream errors so we don't pollute the channel with
+ failure noise.
+ """
+ return {"response_type": "ephemeral", "text": fallback, "blocks": blocks}
+
+
+def _replace_card(blocks: list[dict[str, Any]], *, fallback: str) -> dict[str, Any]:
+ """
+ Replace the original approval card in-place with the post-decision
+ audit-trail line.
+
+ ``replace_original=True`` tells Slack to swap the message we sent
+ earlier rather than append a new one — that way the buttons can't be
+ clicked twice (defence in depth on top of the idempotency guarantees
+ in ``services/actions``).
+ """
+ return {
+ "replace_original": True,
+ "response_type": "in_channel",
+ "text": fallback,
+ "blocks": blocks,
+ }
+
+
+async def handle_action_decision(
+ *,
+ action_id_event: str,
+ button_value: str,
+ user_id: str,
+ actions_client: AisocActionsClient,
+) -> dict[str, Any]:
+ """
+ Resolve an approve/deny click into a Slack response payload.
+
+ Parameters
+ ----------
+ action_id_event
+ The Slack ``action_id`` of the button — one of
+ :data:`APPROVE_ACTION_ID` or :data:`DENY_ACTION_ID`.
+ button_value
+ The button's ``value`` field, encoded by
+ :func:`app.blocks.approval_card_blocks` as
+ ``"<action_id>|<case_id>"``.
+ user_id
+ The Slack user id of the analyst who clicked. Recorded on the
+ post-decision message so the audit trail in chat matches the
+ case timeline.
+ actions_client
+ Client for ``services/actions``.
+
+ Returns
+ -------
+ dict
+ A Slack response payload. Successful decisions use
+ ``replace_original=True`` to swap the approval card with an
+ audit-trail line so the buttons can't be clicked again.
+
+ Notes
+ -----
+ The function never raises — every failure path is converted into an
+ ephemeral error block so the analyst always gets actionable feedback
+ in Slack and we never leak a stack trace.
+ """
+ if action_id_event not in {APPROVE_ACTION_ID, DENY_ACTION_ID}:
+ # Defensive: Bolt should never route an unrelated action here, but
+ # keep the surface honest if a future refactor changes the wiring.
+ return _ephemeral(
+ error_blocks(f"Unknown interactive action `{action_id_event}`"),
+ fallback="Unknown interactive action",
+ )
+
+ try:
+ action_id, _case_id = _decode_routing_value(button_value)
+ except ValueError as exc:
+ return _ephemeral(
+ error_blocks(f"Couldn't decode the approval button: {exc}"),
+ fallback="Bad approval payload",
+ )
+
+ is_approve = action_id_event == APPROVE_ACTION_ID
+ decision_label = _DECISION_APPROVE if is_approve else _DECISION_REJECT
+
+ try:
+ action = await actions_client.approve_action(action_id) if is_approve else await actions_client.reject_action(action_id)
+ except AisocClientError as exc:
+ return _ephemeral(
+ error_blocks(f"Could not record decision for action `{action_id}`: {exc}"),
+ fallback="Decision failed",
+ )
+
+ # Make sure the audit-trail line shows the action context even if the
+ # backend response is sparse. Falling back to the routing-decoded id
+ # guarantees we always show *something* useful.
+ if not action.get("id") and not action.get("action_id"):
+ action = {**action, "id": action_id}
+
+ blocks = action_decision_blocks(
+ decision=decision_label,
+ action=action,
+ decided_by_slack_id=user_id,
+ )
+ fallback = f"Action {action_id} {decision_label} by <@{user_id}>"
+ return _replace_card(blocks, fallback=fallback)
diff --git a/services/slack-bot/app/main.py b/services/slack-bot/app/main.py
new file mode 100644
index 000000000..bbae40734
--- /dev/null
+++ b/services/slack-bot/app/main.py
@@ -0,0 +1,283 @@
+"""
+FastAPI + Slack Bolt entrypoint for the AiSOC Slack bot.
+
+Architecture (one diagram, then code)::
+
+ Slack ──HTTP──► FastAPI ──► SlackRequestHandler ──► Bolt AsyncApp ──► Python handlers
+ │
+ ▼
+ app.commands.handle_aisoc_command
+ app.interactions.handle_action_decision
+ │
+ ▼
+ services/api · services/actions
+
+Design choices
+--------------
+
+* **Bolt is mounted under FastAPI** rather than running standalone so we
+ keep one ASGI app per service (matches every other AiSOC service) and
+ one health-check endpoint for compose / Fly.io.
+* **All Slack-side logic lives behind an async-friendly Bolt app**; the
+ actual command/interaction logic stays in :mod:`app.commands` and
+ :mod:`app.interactions` so it can be tested without touching Bolt.
+* **Per-process singleton clients** (`AisocApiClient`,
+ `AisocActionsClient`). Each holds an ``httpx.AsyncClient`` with
+ connection pooling — building one per request would defeat the pool.
+* **Signing-secret-aware bootstrap**: Bolt requires a signing secret in
+ production. For local pytest / docker-without-secrets we set the Bolt
+ request-verification flag off and log a loud warning so we can never
+ ship a misconfigured production build by accident.
+* **No state on disk**: every command result is rendered into Slack
+ blocks and discarded. The case timeline in ``services/api`` is the
+ source of truth for audit.
+
+Endpoints
+---------
+
+* ``GET /health`` — liveness probe used by docker-compose / Fly.io.
+* ``POST /slack/events`` — single Slack request endpoint. Slack posts
+ slash commands and interactive payloads here; Bolt routes internally.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+
+import structlog
+from fastapi import FastAPI, Request
+from slack_bolt.adapter.fastapi.async_handler import AsyncSlackRequestHandler
+from slack_bolt.async_app import AsyncApp
+
+from app.commands import handle_aisoc_command
+from app.core.config import get_settings
+from app.core.logging import configure_logging
+from app.interactions import (
+ APPROVE_ACTION_ID,
+ DENY_ACTION_ID,
+ handle_action_decision,
+)
+from app.services.aisoc_clients import AisocActionsClient, AisocApiClient
+
+# Configure structlog before anything else so module-level loggers
+# (httpx, slack_bolt, …) inherit the JSON renderer.
+configure_logging()
+logger = structlog.get_logger("aisoc.slack_bot")
+
+
+def _build_bolt_app(api_client: AisocApiClient, actions_client: AisocActionsClient) -> AsyncApp:
+ """
+ Construct the Bolt :class:`AsyncApp` and register every Slack handler.
+
+ The clients are injected so the same builder can be reused from tests
+ with mock clients (or with respx-routed real clients) without
+ spinning up the FastAPI app.
+ """
+ settings = get_settings()
+
+ # ``request_verification_enabled`` defaults to True; we explicitly
+ # disable it when no signing secret is set so docker-without-secrets
+ # bring-up doesn't 401 every Slack request. Production manifests must
+ # supply ``SLACK_SIGNING_SECRET``.
+ #
+ # ``token`` defaults to a placeholder when missing so Bolt doesn't
+ # reject the constructor; outbound API calls obviously won't succeed
+ # without a real token, but startup still works for local dev / tests.
+ bolt = AsyncApp(
+ signing_secret=settings.SLACK_SIGNING_SECRET or None,
+ token=settings.SLACK_BOT_TOKEN or "xoxb-not-configured",
+ request_verification_enabled=settings.signature_verification_enabled,
+ ignoring_self_events_enabled=True,
+ )
+
+ if not settings.signature_verification_enabled:
+ logger.warning(
+ "slack_signing_secret_missing",
+ note=(
+ "Bolt request-signature verification disabled — acceptable for local dev only. Set SLACK_SIGNING_SECRET before shipping."
+ ),
+ )
+ if not settings.SLACK_BOT_TOKEN:
+ logger.warning(
+ "slack_bot_token_missing",
+ note=("SLACK_BOT_TOKEN is empty — outbound Slack API calls will fail. Required before submitting the Slack app for review."),
+ )
+
+ web_base = settings.AISOC_WEB_BASE_URL
+
+ # ── Slash command: /aisoc -------------------------------------------------
+ @bolt.command("/aisoc")
+ async def _on_slash_aisoc(ack, command, respond):
+ # Slack requires an ack within 3 seconds. We ack immediately so
+ # the slow path (HTTP calls into AiSOC services) doesn't blow the
+ # 3s budget on a cold cache.
+ await ack()
+ text = command.get("text") or ""
+ user_id = command.get("user_id") or "unknown"
+ try:
+ payload = await handle_aisoc_command(
+ text=text,
+ user_id=user_id,
+ api_client=api_client,
+ actions_client=actions_client,
+ web_base=web_base,
+ )
+ except Exception as exc: # noqa: BLE001 — last-resort guard
+ # Defensive: handle_aisoc_command swallows AisocClientError but a
+ # programming bug could still raise. We never want a stack
+ # trace to land in Slack.
+ logger.error("slash_command_unhandled_exception", error=str(exc))
+ payload = {
+ "response_type": "ephemeral",
+ "text": f"⚠️ Internal error: {exc}",
+ }
+ await respond(payload)
+
+ # ── Interactive: approve --------------------------------------------------
+ @bolt.action(APPROVE_ACTION_ID)
+ async def _on_approve(ack, body, respond):
+ await ack()
+ await _route_action_decision(
+ event_action_id=APPROVE_ACTION_ID,
+ body=body,
+ respond=respond,
+ actions_client=actions_client,
+ )
+
+ # ── Interactive: deny -----------------------------------------------------
+ @bolt.action(DENY_ACTION_ID)
+ async def _on_deny(ack, body, respond):
+ await ack()
+ await _route_action_decision(
+ event_action_id=DENY_ACTION_ID,
+ body=body,
+ respond=respond,
+ actions_client=actions_client,
+ )
+
+ # ── Interactive: open-case link ------------------------------------------
+ # Pure URL buttons still emit a block_actions payload that Bolt would
+ # otherwise log a "no listener" warning for. Acking quietly keeps
+ # logs clean without coupling the URL button to any business logic.
+ @bolt.action("aisoc_action_open_case")
+ async def _on_open_case(ack):
+ await ack()
+
+ @bolt.action("case_open_link")
+ async def _on_case_open_link(ack):
+ await ack()
+
+ return bolt
+
+
+async def _route_action_decision(
+ *,
+ event_action_id: str,
+ body: dict,
+ respond,
+ actions_client: AisocActionsClient,
+) -> None:
+ """
+ Pull the routing value out of the Slack ``block_actions`` payload and
+ delegate to :func:`app.interactions.handle_action_decision`.
+
+ Slack's payload shape for buttons is:
+
+ body["user"]["id"] -> str
+ body["actions"][0]["value"] -> str ("<action_id>|<case_id>")
+
+ We tolerate missing fields gracefully (eg. a malformed test
+ payload) so handlers can never raise back into Bolt.
+ """
+ user_id = (body.get("user") or {}).get("id") or "unknown"
+ actions = body.get("actions") or []
+ button_value = ""
+ if actions and isinstance(actions, list):
+ first = actions[0] or {}
+ button_value = first.get("value") or ""
+
+ try:
+ payload = await handle_action_decision(
+ action_id_event=event_action_id,
+ button_value=button_value,
+ user_id=user_id,
+ actions_client=actions_client,
+ )
+ except Exception as exc: # noqa: BLE001 — last-resort guard
+ logger.error("action_decision_unhandled_exception", error=str(exc))
+ payload = {
+ "response_type": "ephemeral",
+ "text": f"⚠️ Internal error: {exc}",
+ }
+ await respond(payload)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# FastAPI wiring
+# ────────────────────────────────────────────────────────────────────────────
+
+
+@asynccontextmanager
+async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
+ """
+ Build the AiSOC HTTP clients on startup, tear them down on shutdown.
+
+ The clients each own an ``httpx.AsyncClient`` with a connection pool
+ — sharing them across requests is a 10× win versus building a fresh
+ client per Slack event.
+ """
+ api_client = AisocApiClient.from_settings()
+ actions_client = AisocActionsClient.from_settings()
+ bolt_app = _build_bolt_app(api_client, actions_client)
+
+ app.state.api_client = api_client
+ app.state.actions_client = actions_client
+ app.state.bolt_app = bolt_app
+ app.state.bolt_handler = AsyncSlackRequestHandler(bolt_app)
+
+ logger.info(
+ "slack_bot_started",
+ api_base=api_client.base_url,
+ actions_base=actions_client.base_url,
+ )
+ try:
+ yield
+ finally:
+ await api_client.aclose()
+ await actions_client.aclose()
+ logger.info("slack_bot_stopped")
+
+
+app = FastAPI(
+ title="AiSOC Slack Bot",
+ description=(
+ "ChatOps adapter for AiSOC. Forwards `/aisoc …` slash commands and "
+ "approval-card button clicks to services/api and services/actions. "
+ "Holds no state of its own."
+ ),
+ version="0.1.0",
+ lifespan=_lifespan,
+)
+
+
+async def health() -> dict[str, str]:
+ """
+ Liveness probe used by docker-compose and Fly.io.
+
+ Intentionally does NOT exercise the upstream services — that would
+ couple liveness to an availability concern that is better tracked
+ via a separate readiness probe.
+ """
+ return {"status": "healthy", "service": "aisoc-slack-bot"}
+
+
[email protected]("/slack/events")
+async def slack_events(req: Request):
+ """
+ Single endpoint Slack posts to for slash commands and interactive
+ payloads. Bolt routes internally based on the payload shape.
+ """
+ handler: AsyncSlackRequestHandler = req.app.state.bolt_handler
+ return await handler.handle(req)
diff --git a/services/slack-bot/app/services/__init__.py b/services/slack-bot/app/services/__init__.py
new file mode 100644
index 000000000..09d5ffdda
--- /dev/null
+++ b/services/slack-bot/app/services/__init__.py
@@ -0,0 +1 @@
+"""Service-layer adapters used by the Slack bot."""
diff --git a/services/slack-bot/app/services/aisoc_clients.py b/services/slack-bot/app/services/aisoc_clients.py
new file mode 100644
index 000000000..dd56089bd
--- /dev/null
+++ b/services/slack-bot/app/services/aisoc_clients.py
@@ -0,0 +1,354 @@
+"""
+HTTP clients for the AiSOC backend services.
+
+The Slack bot is a thin adapter — it never touches Postgres or Redis directly.
+Every Slack interaction is translated into one or more HTTP calls against
+``services/api`` (cases, investigations) and ``services/actions`` (response
+actions, approval flows).
+
+We expose two narrow clients:
+
+* :class:`AisocApiClient` — proxies ``/api/v1/cases/*`` endpoints used by the
+ ``/aisoc list``, ``/aisoc investigate`` and ``/aisoc explain`` commands.
+* :class:`AisocActionsClient` — submits and approves response actions used by
+ ``/aisoc isolate`` and ``/aisoc block``.
+
+Both clients:
+
+* Authenticate as a service principal using an ``aisoc_*`` API key (see
+ ``services/api/app/api/v1/deps.py``).
+* Set ``X-Tenant-Id`` so the API can scope queries even when the token's own
+ tenant is wildcarded.
+* Surface failures as :class:`AisocClientError` so command handlers can render
+ a friendly Slack message instead of leaking a traceback.
+
+The HTTP transport (``httpx.AsyncClient``) is injectable so unit tests can swap
+in ``respx`` mocks without monkey-patching the module-level client.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+import structlog
+
+from app.core.config import SlackBotSettings, get_settings
+
+log = structlog.get_logger(__name__)
+
+
+class AisocClientError(RuntimeError):
+ """
+ Raised when an AiSOC backend call fails for any reason — non-2xx, network
+ error, or malformed JSON. ``status_code`` is ``None`` for transport errors.
+
+ Command handlers should catch this and render a short Block Kit error
+ message; never re-raise it inside a Bolt handler because Slack times out
+ interactive responses at 3 seconds.
+ """
+
+ def __init__(self, message: str, *, status_code: int | None = None) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+
+
+def _service_headers(token: str, tenant_id: str) -> dict[str, str]:
+ headers: dict[str, str] = {
+ "Accept": "application/json",
+ "X-Tenant-Id": tenant_id,
+ }
+ if token:
+ # The API resolves ``aisoc_*`` keys via the api_keys table and assigns
+ # the service principal's permissions. An empty token is allowed only
+ # in tests where the dependency override bypasses auth entirely.
+ headers["Authorization"] = f"Bearer {token}"
+ return headers
+
+
+async def _raise_for_response(response: httpx.Response, *, context: str) -> None:
+ """
+ Convert an HTTP error response into :class:`AisocClientError` with a
+ human-readable message. Truncates the upstream body so we never leak a
+ stack trace into Slack.
+ """
+ if response.is_success:
+ return
+ body = response.text or ""
+ snippet = body.strip().splitlines()[0] if body.strip() else response.reason_phrase
+ log.warning(
+ "aisoc_client.upstream_error",
+ context=context,
+ status_code=response.status_code,
+ body=body[:500],
+ )
+ raise AisocClientError(
+ f"{context} failed ({response.status_code}): {snippet[:160]}",
+ status_code=response.status_code,
+ )
+
+
+class _BaseClient:
+ """Shared transport plumbing — base URL, headers, ``httpx.AsyncClient``."""
+
+ def __init__(
+ self,
+ *,
+ base_url: str,
+ token: str,
+ tenant_id: str,
+ timeout_seconds: float,
+ transport: httpx.AsyncBaseTransport | None = None,
+ ) -> None:
+ self._base_url = base_url.rstrip("/")
+ self._token = token
+ self._tenant_id = tenant_id
+ self._client = httpx.AsyncClient(
+ base_url=self._base_url,
+ headers=_service_headers(token, tenant_id),
+ timeout=timeout_seconds,
+ transport=transport,
+ )
+
+ @property
+ def base_url(self) -> str:
+ return self._base_url
+
+ async def aclose(self) -> None:
+ await self._client.aclose()
+
+ async def __aenter__(self) -> _BaseClient:
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb) -> None:
+ await self.aclose()
+
+ async def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ context: str,
+ params: dict[str, Any] | None = None,
+ json: dict[str, Any] | None = None,
+ ) -> httpx.Response:
+ try:
+ response = await self._client.request(method, path, params=params, json=json)
+ except httpx.HTTPError as exc:
+ log.warning(
+ "aisoc_client.transport_error",
+ context=context,
+ error=str(exc),
+ base_url=self._base_url,
+ )
+ raise AisocClientError(f"{context} failed: {exc.__class__.__name__}", status_code=None) from exc
+ await _raise_for_response(response, context=context)
+ return response
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# services/api client
+# ────────────────────────────────────────────────────────────────────────────
+
+
+class AisocApiClient(_BaseClient):
+ """
+ Narrow client for the ``services/api`` endpoints the Slack bot needs.
+
+ Only exposes the verbs we actually use; every other endpoint stays out of
+ the Slack surface for blast-radius reasons. Adding a new command means
+ explicitly adding a new method here.
+ """
+
+ @classmethod
+ def from_settings(
+ cls,
+ settings: SlackBotSettings | None = None,
+ *,
+ transport: httpx.AsyncBaseTransport | None = None,
+ ) -> AisocApiClient:
+ s = settings or get_settings()
+ return cls(
+ base_url=s.AISOC_API_BASE_URL,
+ token=s.AISOC_API_SERVICE_TOKEN,
+ tenant_id=s.AISOC_DEFAULT_TENANT_ID,
+ timeout_seconds=s.AISOC_HTTP_TIMEOUT_SECONDS,
+ transport=transport,
+ )
+
+ async def list_open_cases(
+ self,
+ *,
+ limit: int = 10,
+ severity: str | None = None,
+ ) -> list[dict[str, Any]]:
+ """
+ Return the most recently created cases that are not yet ``closed``.
+
+ services/api supports filtering by ``status``/``severity`` separately.
+ Slack callers want "active work" by default so we fetch the latest
+ ``limit`` rows and filter terminal states client-side; this keeps a
+ single round-trip and stays correct if new transitional statuses are
+ added to the API later.
+ """
+ params: dict[str, Any] = {"limit": max(1, min(limit * 3, 200))}
+ if severity:
+ params["severity"] = severity
+
+ response = await self._request("GET", "/api/v1/cases", context="list cases", params=params)
+ try:
+ rows = response.json()
+ except ValueError as exc:
+ raise AisocClientError("list cases failed: invalid JSON") from exc
+ if not isinstance(rows, list):
+ raise AisocClientError("list cases failed: unexpected response shape")
+ active = [r for r in rows if isinstance(r, dict) and r.get("status") != "closed"]
+ return active[:limit]
+
+ async def get_case(self, case_id: str) -> dict[str, Any]:
+ """
+ Fetch a single case by id or case-number.
+
+ services/api accepts both forms on this route — we URL-encode the
+ identifier so a stray ``/`` in user input cannot escape the path.
+ """
+ safe_id = quote(case_id, safe="")
+ response = await self._request("GET", f"/api/v1/cases/{safe_id}", context="get case")
+ try:
+ return response.json()
+ except ValueError as exc:
+ raise AisocClientError("get case failed: invalid JSON") from exc
+
+ async def launch_investigation(
+ self,
+ case_id: str,
+ *,
+ alert_summary: str = "",
+ ) -> dict[str, Any]:
+ """
+ Kick off a new investigation run for a case.
+
+ services/api proxies to the agents service; the response carries the
+ ``run_id`` we link back into Slack so the analyst can follow it in the
+ web console.
+ """
+ safe_id = quote(case_id, safe="")
+ response = await self._request(
+ "POST",
+ f"/api/v1/cases/{safe_id}/investigate",
+ context="launch investigation",
+ json={"alert_summary": alert_summary},
+ )
+ try:
+ return response.json()
+ except ValueError as exc:
+ raise AisocClientError("launch investigation failed: invalid JSON") from exc
+
+ async def get_case_summary(self, case_id: str) -> dict[str, Any]:
+ """
+ Fetch the structured per-case auto-summary used by ``/aisoc explain``.
+ """
+ safe_id = quote(case_id, safe="")
+ response = await self._request(
+ "GET",
+ f"/api/v1/cases/{safe_id}/summary",
+ context="case summary",
+ params={"format": "json"},
+ )
+ try:
+ return response.json()
+ except ValueError as exc:
+ raise AisocClientError("case summary failed: invalid JSON") from exc
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# services/actions client
+# ────────────────────────────────────────────────────────────────────────────
+
+
+class AisocActionsClient(_BaseClient):
+ """
+ Narrow client for the ``services/actions`` endpoints.
+
+ Only the ``isolate`` and ``block`` commands hit this client today. Both
+ actions are in :data:`APPROVAL_REQUIRED_ACTIONS`, so ``submit_action``
+ will return ``status="awaiting_approval"`` and the bot must then post a
+ Block Kit approval card. The action_id from the response feeds the
+ approve/reject buttons.
+ """
+
+ @classmethod
+ def from_settings(
+ cls,
+ settings: SlackBotSettings | None = None,
+ *,
+ transport: httpx.AsyncBaseTransport | None = None,
+ ) -> AisocActionsClient:
+ s = settings or get_settings()
+ # The actions service is happy to fall back to the API service token
+ # when a dedicated actions key isn't provisioned (single-secret rollout).
+ token = s.AISOC_ACTIONS_SERVICE_TOKEN or s.AISOC_API_SERVICE_TOKEN
+ return cls(
+ base_url=s.AISOC_ACTIONS_BASE_URL,
+ token=token,
+ tenant_id=s.AISOC_DEFAULT_TENANT_ID,
+ timeout_seconds=s.AISOC_HTTP_TIMEOUT_SECONDS,
+ transport=transport,
+ )
+
+ async def submit_action(
+ self,
+ *,
+ action_type: str,
+ target: str,
+ case_id: str,
+ rationale: str,
+ requested_by: str,
+ parameters: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """
+ Submit a response action. For approval-required actions the response
+ contains ``status="awaiting_approval"`` and ``id`` (action_id); the bot
+ is then responsible for surfacing an approval card to a human.
+ """
+ payload: dict[str, Any] = {
+ "incident_id": case_id,
+ "tenant_id": self._tenant_id,
+ "action_type": action_type,
+ "target": target,
+ "rationale": rationale,
+ "requested_by": requested_by,
+ "parameters": parameters or {},
+ }
+ response = await self._request("POST", "/api/v1/actions", context="submit action", json=payload)
+ try:
+ return response.json()
+ except ValueError as exc:
+ raise AisocClientError("submit action failed: invalid JSON") from exc
+
+ async def approve_action(self, action_id: str) -> dict[str, Any]:
+ """Approve a pending action (called from the Slack approve button)."""
+ safe_id = quote(action_id, safe="")
+ response = await self._request(
+ "POST",
+ f"/api/v1/actions/{safe_id}/approve",
+ context="approve action",
+ )
+ try:
+ return response.json()
+ except ValueError as exc:
+ raise AisocClientError("approve action failed: invalid JSON") from exc
+
+ async def reject_action(self, action_id: str) -> dict[str, Any]:
+ """Reject a pending action (called from the Slack deny button)."""
+ safe_id = quote(action_id, safe="")
+ response = await self._request(
+ "POST",
+ f"/api/v1/actions/{safe_id}/reject",
+ context="reject action",
+ )
+ try:
+ return response.json()
+ except ValueError as exc:
+ raise AisocClientError("reject action failed: invalid JSON") from exc
diff --git a/services/slack-bot/pyproject.toml b/services/slack-bot/pyproject.toml
new file mode 100644
index 000000000..aa58bf49b
--- /dev/null
+++ b/services/slack-bot/pyproject.toml
@@ -0,0 +1,33 @@
+[tool.poetry]
+name = "aisoc-slack-bot"
+version = "0.1.0"
+description = "AiSOC Slack bot — slash commands and approval flows for ChatOps-driven SOC operations"
+authors = ["Beenu Arora <[email protected]>"]
+license = "MIT"
+
+[tool.poetry.dependencies]
+python = "^3.11"
+fastapi = ">=0.109,<0.137"
+uvicorn = {extras = ["standard"], version = "^0.27.0"}
+pydantic = "^2.5.0"
+pydantic-settings = "^2.1.0"
+slack-bolt = "^1.18.1"
+slack-sdk = "^3.27.0"
+# Required transitively by slack_bolt.async_app — declared explicitly so a
+# resolver pruning unused deps doesn't break the FastAPI/Bolt adapter.
+aiohttp = ">=3.9,<4.0"
+httpx = ">=0.27,<0.29"
+structlog = ">=24.1,<26.0"
+
+[tool.poetry.group.dev.dependencies]
+pytest = "^7.4.0"
+pytest-asyncio = "^0.23.0"
+respx = "^0.20.2"
+
+[build-system]
+requires = ["poetry-core"]
+build-backend = "poetry.core.masonry.api"
+
+[tool.pytest.ini_options]
+asyncio_mode = "auto"
+testpaths = ["tests"]
diff --git a/services/slack-bot/tests/__init__.py b/services/slack-bot/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/services/slack-bot/tests/test_aisoc_clients.py b/services/slack-bot/tests/test_aisoc_clients.py
new file mode 100644
index 000000000..2cc5e3d17
--- /dev/null
+++ b/services/slack-bot/tests/test_aisoc_clients.py
@@ -0,0 +1,310 @@
+"""
+Tests for ``app.services.aisoc_clients``.
+
+We use ``respx`` to mock the HTTP transport so the tests stay hermetic — no
+live FastAPI app needed. The goal is to lock in:
+
+* request shape (headers, JSON body, URL path)
+* response parsing for happy-path payloads
+* AisocClientError translation for non-2xx responses and transport errors
+* the open-cases filter excludes ``closed`` rows even when the API returns them
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+import respx
+from app.core.config import SlackBotSettings
+from app.services.aisoc_clients import (
+ AisocActionsClient,
+ AisocApiClient,
+ AisocClientError,
+)
+
+API_BASE = "http://api.test"
+ACTIONS_BASE = "http://actions.test"
+TENANT = "11111111-2222-3333-4444-555555555555"
+TOKEN = "aisoc_test_key"
+
+
+def _settings() -> SlackBotSettings:
+ return SlackBotSettings(
+ SLACK_BOT_TOKEN="xoxb-test",
+ SLACK_SIGNING_SECRET="shhh",
+ AISOC_API_BASE_URL=API_BASE,
+ AISOC_ACTIONS_BASE_URL=ACTIONS_BASE,
+ AISOC_API_SERVICE_TOKEN=TOKEN,
+ AISOC_ACTIONS_SERVICE_TOKEN=TOKEN,
+ AISOC_DEFAULT_TENANT_ID=TENANT,
+ )
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# AisocApiClient
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_list_open_cases_filters_closed_and_caps_to_limit():
+ settings = _settings()
+
+ sample = [
+ {"id": "c1", "title": "Active", "status": "investigating", "severity": "high"},
+ {"id": "c2", "title": "Done", "status": "closed", "severity": "low"},
+ {"id": "c3", "title": "New", "status": "new", "severity": "medium"},
+ {"id": "c4", "title": "Triaged", "status": "triaged", "severity": "high"},
+ ]
+
+ with respx.mock(base_url=API_BASE) as router:
+ route = router.get("/api/v1/cases").mock(return_value=httpx.Response(200, json=sample))
+ client = AisocApiClient.from_settings(settings)
+ try:
+ cases = await client.list_open_cases(limit=2)
+ finally:
+ await client.aclose()
+
+ assert route.called
+ request = route.calls.last.request
+ assert request.headers["Authorization"] == f"Bearer {TOKEN}"
+ assert request.headers["X-Tenant-Id"] == TENANT
+ # Query expansion: limit=2 should request more rows so post-filter we still
+ # have 2 active cases even when ``closed`` rows are interleaved.
+ assert request.url.params["limit"] == "6"
+ assert [c["id"] for c in cases] == ["c1", "c3"]
+
+
+async def test_list_open_cases_propagates_severity_filter():
+ settings = _settings()
+ with respx.mock(base_url=API_BASE) as router:
+ route = router.get("/api/v1/cases").mock(return_value=httpx.Response(200, json=[]))
+ client = AisocApiClient.from_settings(settings)
+ try:
+ await client.list_open_cases(limit=5, severity="high")
+ finally:
+ await client.aclose()
+
+ assert route.calls.last.request.url.params["severity"] == "high"
+
+
+async def test_get_case_url_encodes_identifier():
+ settings = _settings()
+ with respx.mock(base_url=API_BASE) as router:
+ # User passes a case-number that contains a slash; the client must
+ # quote it so the path stays inside ``/api/v1/cases/…``.
+ route = router.get("/api/v1/cases/CASE%2F1").mock(return_value=httpx.Response(200, json={"id": "abc", "title": "ok"}))
+ client = AisocApiClient.from_settings(settings)
+ try:
+ case = await client.get_case("CASE/1")
+ finally:
+ await client.aclose()
+
+ assert route.called
+ assert case["title"] == "ok"
+
+
+async def test_launch_investigation_posts_alert_summary():
+ settings = _settings()
+ with respx.mock(base_url=API_BASE) as router:
+ route = router.post("/api/v1/cases/abc/investigate").mock(return_value=httpx.Response(202, json={"run_id": "run-1"}))
+ client = AisocApiClient.from_settings(settings)
+ try:
+ result = await client.launch_investigation("abc", alert_summary="ransomware?")
+ finally:
+ await client.aclose()
+
+ assert route.called
+ sent = route.calls.last.request
+ import json
+
+ body = json.loads(sent.content)
+ assert body == {"alert_summary": "ransomware?"}
+ assert result == {"run_id": "run-1"}
+
+
+async def test_get_case_summary_requests_json_format():
+ settings = _settings()
+ with respx.mock(base_url=API_BASE) as router:
+ route = router.get("/api/v1/cases/abc/summary").mock(return_value=httpx.Response(200, json={"summary": "..."}))
+ client = AisocApiClient.from_settings(settings)
+ try:
+ await client.get_case_summary("abc")
+ finally:
+ await client.aclose()
+
+ assert route.calls.last.request.url.params["format"] == "json"
+
+
+async def test_non_2xx_raises_aisoc_client_error_with_status():
+ settings = _settings()
+ with respx.mock(base_url=API_BASE) as router:
+ router.get("/api/v1/cases").mock(return_value=httpx.Response(503, text="upstream down"))
+ client = AisocApiClient.from_settings(settings)
+ try:
+ with pytest.raises(AisocClientError) as exc:
+ await client.list_open_cases()
+ finally:
+ await client.aclose()
+
+ assert exc.value.status_code == 503
+ assert "list cases failed" in str(exc.value)
+
+
+async def test_transport_error_raises_without_status():
+ settings = _settings()
+ with respx.mock(base_url=API_BASE) as router:
+ router.get("/api/v1/cases").mock(side_effect=httpx.ConnectError("nope"))
+ client = AisocApiClient.from_settings(settings)
+ try:
+ with pytest.raises(AisocClientError) as exc:
+ await client.list_open_cases()
+ finally:
+ await client.aclose()
+
+ assert exc.value.status_code is None
+
+
+async def test_invalid_json_raises_client_error():
+ settings = _settings()
+ with respx.mock(base_url=API_BASE) as router:
+ router.get("/api/v1/cases/abc").mock(return_value=httpx.Response(200, text="not json", headers={"content-type": "text/plain"}))
+ client = AisocApiClient.from_settings(settings)
+ try:
+ with pytest.raises(AisocClientError):
+ await client.get_case("abc")
+ finally:
+ await client.aclose()
+
+
+async def test_list_open_cases_rejects_non_list_response():
+ settings = _settings()
+ with respx.mock(base_url=API_BASE) as router:
+ router.get("/api/v1/cases").mock(return_value=httpx.Response(200, json={"oops": "object"}))
+ client = AisocApiClient.from_settings(settings)
+ try:
+ with pytest.raises(AisocClientError):
+ await client.list_open_cases()
+ finally:
+ await client.aclose()
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# AisocActionsClient
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_submit_action_posts_full_payload_with_tenant():
+ settings = _settings()
+ with respx.mock(base_url=ACTIONS_BASE) as router:
+ route = router.post("/api/v1/actions").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "id": "a1",
+ "status": "awaiting_approval",
+ "blast_radius": "high",
+ "action_type": "isolate_host",
+ },
+ )
+ )
+ client = AisocActionsClient.from_settings(settings)
+ try:
+ result = await client.submit_action(
+ action_type="isolate_host",
+ target="host-42",
+ case_id="case-7",
+ rationale="confirmed beacon",
+ requested_by="U_SLACK_USER",
+ )
+ finally:
+ await client.aclose()
+
+ assert route.called
+ request = route.calls.last.request
+ import json
+
+ body = json.loads(request.content)
+ assert body == {
+ "incident_id": "case-7",
+ "tenant_id": TENANT,
+ "action_type": "isolate_host",
+ "target": "host-42",
+ "rationale": "confirmed beacon",
+ "requested_by": "U_SLACK_USER",
+ "parameters": {},
+ }
+ assert request.headers["Authorization"] == f"Bearer {TOKEN}"
+ assert result["status"] == "awaiting_approval"
+
+
+async def test_actions_client_falls_back_to_api_token_when_actions_token_missing():
+ settings = SlackBotSettings(
+ AISOC_API_BASE_URL=API_BASE,
+ AISOC_ACTIONS_BASE_URL=ACTIONS_BASE,
+ AISOC_API_SERVICE_TOKEN="aisoc_api_only",
+ AISOC_ACTIONS_SERVICE_TOKEN="",
+ AISOC_DEFAULT_TENANT_ID=TENANT,
+ )
+ with respx.mock(base_url=ACTIONS_BASE) as router:
+ route = router.post("/api/v1/actions/aaa/approve").mock(return_value=httpx.Response(200, json={"id": "aaa", "status": "completed"}))
+ client = AisocActionsClient.from_settings(settings)
+ try:
+ await client.approve_action("aaa")
+ finally:
+ await client.aclose()
+
+ assert route.calls.last.request.headers["Authorization"] == "Bearer aisoc_api_only"
+
+
+async def test_approve_and_reject_url_encode_action_id():
+ settings = _settings()
+ with respx.mock(base_url=ACTIONS_BASE) as router:
+ approve = router.post("/api/v1/actions/a%2F1/approve").mock(
+ return_value=httpx.Response(200, json={"id": "a/1", "status": "approved"})
+ )
+ reject = router.post("/api/v1/actions/a%2F1/reject").mock(
+ return_value=httpx.Response(200, json={"id": "a/1", "status": "rejected"})
+ )
+ client = AisocActionsClient.from_settings(settings)
+ try:
+ await client.approve_action("a/1")
+ await client.reject_action("a/1")
+ finally:
+ await client.aclose()
+
+ assert approve.called and reject.called
+
+
+async def test_actions_client_propagates_4xx_with_message_snippet():
+ settings = _settings()
+ with respx.mock(base_url=ACTIONS_BASE) as router:
+ router.post("/api/v1/actions").mock(
+ return_value=httpx.Response(400, text="invalid action_type"),
+ )
+ client = AisocActionsClient.from_settings(settings)
+ try:
+ with pytest.raises(AisocClientError) as exc:
+ await client.submit_action(
+ action_type="not_a_real_action",
+ target="host-1",
+ case_id="c1",
+ rationale="x",
+ requested_by="u1",
+ )
+ finally:
+ await client.aclose()
+
+ assert exc.value.status_code == 400
+ assert "invalid action_type" in str(exc.value)
diff --git a/services/slack-bot/tests/test_blocks.py b/services/slack-bot/tests/test_blocks.py
new file mode 100644
index 000000000..09acc3fef
--- /dev/null
+++ b/services/slack-bot/tests/test_blocks.py
@@ -0,0 +1,260 @@
+"""
+Tests for ``app.blocks``.
+
+The goals here are deliberately structural rather than visual:
+
+* every builder must always return a non-empty list of dicts (Slack rejects
+ empty ``blocks`` arrays)
+* every block must declare a ``type`` (Block Kit hard requirement)
+* deep-link URLs are absolute (Slack rejects relative URLs in buttons)
+* the approval card carries the action and case ids inside button ``value``
+ fields so the interactive handler can decode them without a DB lookup
+* truncation kicks in for long titles and rationale strings (defence in
+ depth — we never want to ship a 4kB Slack message)
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from app.blocks import (
+ action_decision_blocks,
+ approval_card_blocks,
+ case_card_blocks,
+ case_explanation_blocks,
+ case_list_blocks,
+ error_blocks,
+ help_blocks,
+ investigation_started_blocks,
+)
+
+WEB_BASE = "https://app.aisoc.test"
+
+
+def _all_have_type(blocks: list[dict[str, Any]]) -> bool:
+ return bool(blocks) and all(isinstance(b, dict) and "type" in b for b in blocks)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# case_list_blocks
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def test_case_list_blocks_empty_renders_friendly_message():
+ blocks = case_list_blocks([], web_base=WEB_BASE)
+ assert _all_have_type(blocks)
+ text = blocks[0]["text"]["text"]
+ assert "nothing to triage" in text.lower()
+
+
+def test_case_list_blocks_renders_each_case_with_deep_link():
+ cases = [
+ {
+ "id": "c-1",
+ "case_number": "AISOC-1",
+ "title": "Suspicious login burst",
+ "severity": "high",
+ "status": "investigating",
+ },
+ {
+ "id": "c-2",
+ "case_number": "AISOC-2",
+ "title": "Phish mail flagged",
+ "severity": "medium",
+ "status": "new",
+ },
+ ]
+ blocks = case_list_blocks(cases, web_base=WEB_BASE)
+ assert _all_have_type(blocks)
+ rendered = "\n".join(b["text"]["text"] for b in blocks if b["type"] == "section" and isinstance(b.get("text"), dict))
+ assert "AISOC-1" in rendered and "Suspicious login burst" in rendered
+ assert "AISOC-2" in rendered
+ assert f"{WEB_BASE}/cases/c-1" in rendered
+ assert f"{WEB_BASE}/cases/c-2" in rendered
+
+
+def test_case_list_blocks_caps_at_ten_and_shows_overflow_hint():
+ cases = [
+ {
+ "id": f"c-{i}",
+ "case_number": f"AISOC-{i}",
+ "title": f"Case {i}",
+ "severity": "low",
+ "status": "new",
+ }
+ for i in range(15)
+ ]
+ blocks = case_list_blocks(cases, web_base=WEB_BASE)
+ section_blocks = [b for b in blocks if b["type"] == "section"]
+ assert len(section_blocks) == 10
+ context_blocks = [b for b in blocks if b["type"] == "context"]
+ assert context_blocks, "expected an overflow context block"
+ assert "15" in context_blocks[-1]["elements"][0]["text"]
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# case_card_blocks
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def test_case_card_blocks_includes_open_in_aisoc_button():
+ case = {
+ "id": "abc",
+ "case_number": "AISOC-42",
+ "title": "Possible ransomware",
+ "severity": "critical",
+ "status": "containment",
+ "alert_count": 7,
+ }
+ blocks = case_card_blocks(case, web_base=WEB_BASE)
+ assert _all_have_type(blocks)
+ button_section = next(b for b in blocks if b.get("type") == "section" and "accessory" in b)
+ assert button_section["accessory"]["type"] == "button"
+ assert button_section["accessory"]["url"] == f"{WEB_BASE}/cases/abc"
+
+
+def test_case_card_blocks_truncates_long_titles_and_descriptions():
+ case = {
+ "id": "abc",
+ "case_number": "AISOC-99",
+ "title": "x" * 200,
+ "description": "y" * 1000,
+ "severity": "low",
+ "status": "new",
+ }
+ blocks = case_card_blocks(case, web_base=WEB_BASE)
+ serialized = str(blocks)
+ # truncation marker present, no 1000-char y-string
+ assert "…" in serialized
+ assert "y" * 500 not in serialized
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# investigation_started_blocks / case_explanation_blocks
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def test_investigation_started_blocks_surfaces_run_id():
+ case = {"id": "c-1", "case_number": "AISOC-1"}
+ investigation = {"run_id": "run-abcdef"}
+ blocks = investigation_started_blocks(case, investigation, web_base=WEB_BASE)
+ assert _all_have_type(blocks)
+ assert "run-abcdef" in str(blocks)
+ assert f"{WEB_BASE}/cases/c-1" in str(blocks)
+
+
+def test_case_explanation_blocks_renders_summary_and_recommendations():
+ case = {
+ "id": "c-1",
+ "case_number": "AISOC-1",
+ "title": "Outbound DNS spike",
+ "severity": "high",
+ "status": "investigating",
+ }
+ summary = {
+ "summary": "Likely DNS tunnelling from host h-12.",
+ "recommendations": ["Isolate h-12", "Block 1.2.3.4"],
+ }
+ blocks = case_explanation_blocks(case, summary, web_base=WEB_BASE)
+ assert _all_have_type(blocks)
+ rendered = str(blocks)
+ assert "Likely DNS tunnelling" in rendered
+ assert "Isolate h-12" in rendered
+ assert "Block 1.2.3.4" in rendered
+
+
+def test_case_explanation_blocks_handles_empty_summary_gracefully():
+ case = {"id": "c-1", "case_number": "AISOC-1", "title": "t", "severity": "low", "status": "new"}
+ blocks = case_explanation_blocks(case, {}, web_base=WEB_BASE)
+ assert _all_have_type(blocks)
+ # No "AI summary" header should be added when the model returned nothing.
+ assert "AI summary" not in str(blocks)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# approval_card_blocks
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def test_approval_card_includes_approve_and_deny_buttons_with_routing_value():
+ action = {
+ "id": "act-1",
+ "action_type": "isolate_host",
+ "target": "host-42",
+ "blast_radius": "high",
+ "rationale": "confirmed beacon",
+ }
+ case = {"id": "case-7", "case_number": "AISOC-7"}
+ blocks = approval_card_blocks(
+ action=action,
+ case=case,
+ requested_by_slack_id="U123",
+ web_base=WEB_BASE,
+ )
+ assert _all_have_type(blocks)
+
+ actions_block = next(b for b in blocks if b["type"] == "actions")
+ action_ids = [el["action_id"] for el in actions_block["elements"]]
+ assert "aisoc_action_approve" in action_ids
+ assert "aisoc_action_deny" in action_ids
+
+ # routing tokens carry both ids so the handler can avoid a DB hit
+ approve = next(el for el in actions_block["elements"] if el["action_id"] == "aisoc_action_approve")
+ assert approve["value"] == "act-1|case-7"
+ assert approve.get("confirm"), "approve must always show a confirm dialog"
+
+
+def test_approval_card_uses_action_id_fallback_when_id_missing():
+ action = {
+ "action_id": "act-2",
+ "action_type": "block_ip",
+ "target": "1.2.3.4",
+ "blast_radius": "medium",
+ }
+ case = {"id": "case-9"}
+ blocks = approval_card_blocks(
+ action=action,
+ case=case,
+ requested_by_slack_id="U999",
+ web_base=WEB_BASE,
+ )
+ actions_block = next(b for b in blocks if b["type"] == "actions")
+ deny = next(el for el in actions_block["elements"] if el["action_id"] == "aisoc_action_deny")
+ assert deny["value"].startswith("act-2|case-9")
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# action_decision_blocks / help / error
+# ────────────────────────────────────────────────────────────────────────────
+
+
+ "decision, expected_emoji",
+ [("approved", "✅"), ("rejected", "🛑")],
+)
+def test_action_decision_blocks_render_correct_emoji(decision: str, expected_emoji: str):
+ action = {"id": "act-1", "action_type": "isolate_host", "target": "h-1"}
+ blocks = action_decision_blocks(decision=decision, action=action, decided_by_slack_id="U777")
+ assert _all_have_type(blocks)
+ assert expected_emoji in blocks[0]["text"]["text"]
+ assert "<@U777>" in blocks[0]["text"]["text"]
+ # No interactive elements in post-decision state
+ assert all(b["type"] != "actions" for b in blocks)
+
+
+def test_help_blocks_lists_every_supported_subcommand():
+ blocks = help_blocks()
+ assert _all_have_type(blocks)
+ rendered = str(blocks)
+ for cmd in ("list", "investigate", "explain", "isolate", "block", "help"):
+ assert f"`/aisoc {cmd}" in rendered or f"/aisoc {cmd}" in rendered
+
+
+def test_error_blocks_truncate_and_carry_x_emoji():
+ blocks = error_blocks("z" * 1000)
+ assert _all_have_type(blocks)
+ text = blocks[0]["text"]["text"]
+ assert text.startswith("❌")
+ # ensure truncation happened
+ assert text.count("z") < 1000
diff --git a/services/slack-bot/tests/test_commands.py b/services/slack-bot/tests/test_commands.py
new file mode 100644
index 000000000..761894d13
--- /dev/null
+++ b/services/slack-bot/tests/test_commands.py
@@ -0,0 +1,395 @@
+"""
+Tests for ``app.commands``.
+
+We unit-test the dispatcher by stubbing out :class:`AisocApiClient` and
+:class:`AisocActionsClient` with simple async fakes that record the calls
+they received. This keeps the suite hermetic and fast — no respx, no Bolt.
+
+The contract the dispatcher must hold is small but important:
+
+* unknown / empty input → ephemeral help block (private to the user)
+* upstream client errors → ephemeral error block (no traceback leaks)
+* successful list/explain/investigate → ``in_channel`` (visible to the team)
+ except for ``list`` which we keep ephemeral by design
+* approval-required actions → in_channel approval card with action+case
+ routing tokens encoded in the button values
+* auto-approved actions → in_channel confirmation, no buttons
+
+We also check the parser handles quoted reasons correctly so analysts can
+include free-text rationale without breaking the command.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from app.commands import handle_aisoc_command
+from app.services.aisoc_clients import AisocClientError
+
+WEB_BASE = "https://app.aisoc.test"
+
+
+class FakeApiClient:
+ """In-memory stand-in for :class:`AisocApiClient`."""
+
+ def __init__(
+ self,
+ *,
+ cases: list[dict[str, Any]] | None = None,
+ case: dict[str, Any] | None = None,
+ investigation: dict[str, Any] | None = None,
+ summary: dict[str, Any] | None = None,
+ raise_on: str | None = None,
+ ) -> None:
+ self._cases = cases or []
+ self._case = case or {"id": "c-1", "case_number": "AISOC-1", "title": "x"}
+ self._investigation = investigation or {"run_id": "run-xyz"}
+ self._summary = summary or {"summary": "ok"}
+ self._raise_on = raise_on
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+
+ def _maybe_raise(self, name: str) -> None:
+ if self._raise_on == name:
+ raise AisocClientError("upstream boom", status_code=502)
+
+ async def list_open_cases(self, *, limit: int = 10, severity: str | None = None) -> list[dict[str, Any]]:
+ self._maybe_raise("list_open_cases")
+ self.calls.append(("list_open_cases", {"limit": limit, "severity": severity}))
+ return self._cases
+
+ async def get_case(self, case_id: str) -> dict[str, Any]:
+ self._maybe_raise("get_case")
+ self.calls.append(("get_case", {"case_id": case_id}))
+ return self._case
+
+ async def launch_investigation(self, case_id: str, *, alert_summary: str = "") -> dict[str, Any]:
+ self._maybe_raise("launch_investigation")
+ self.calls.append(("launch_investigation", {"case_id": case_id, "alert_summary": alert_summary}))
+ return self._investigation
+
+ async def get_case_summary(self, case_id: str) -> dict[str, Any]:
+ self._maybe_raise("get_case_summary")
+ self.calls.append(("get_case_summary", {"case_id": case_id}))
+ return self._summary
+
+
+class FakeActionsClient:
+ """In-memory stand-in for :class:`AisocActionsClient`."""
+
+ def __init__(
+ self,
+ *,
+ action: dict[str, Any] | None = None,
+ raise_on: str | None = None,
+ ) -> None:
+ self._action = action or {
+ "id": "act-1",
+ "status": "awaiting_approval",
+ "action_type": "isolate_host",
+ "target": "host-1",
+ "blast_radius": "high",
+ }
+ self._raise_on = raise_on
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+
+ def _maybe_raise(self, name: str) -> None:
+ if self._raise_on == name:
+ raise AisocClientError("actions boom", status_code=500)
+
+ async def submit_action(self, **kwargs: Any) -> dict[str, Any]:
+ self._maybe_raise("submit_action")
+ self.calls.append(("submit_action", kwargs))
+ return self._action
+
+
+def _flatten(blocks: list[dict[str, Any]]) -> str:
+ return str(blocks)
+
+
+def _has_action_buttons(blocks: list[dict[str, Any]]) -> bool:
+ return any(b.get("type") == "actions" for b in blocks)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# help / unknown
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_empty_text_returns_help_ephemeral():
+ api = FakeApiClient()
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(text="", user_id="U1", api_client=api, actions_client=actions, web_base=WEB_BASE)
+ assert res["response_type"] == "ephemeral"
+ assert "AiSOC Slack commands" in _flatten(res["blocks"])
+
+
+async def test_unknown_subcommand_returns_help_with_ephemeral_visibility():
+ api = FakeApiClient()
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(text="frobnicate", user_id="U1", api_client=api, actions_client=actions, web_base=WEB_BASE)
+ assert res["response_type"] == "ephemeral"
+ assert "AiSOC Slack commands" in _flatten(res["blocks"])
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# list
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_list_passes_severity_filter_and_uses_titled_header():
+ api = FakeApiClient(cases=[{"id": "c-1", "case_number": "AISOC-1", "title": "t", "severity": "high", "status": "investigating"}])
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(
+ text="list high",
+ user_id="U1",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "ephemeral"
+ assert ("list_open_cases", {"limit": 10, "severity": "high"}) in api.calls
+ assert "High" in _flatten(res["blocks"])
+
+
+async def test_list_rejects_unknown_severity_with_ephemeral_error():
+ api = FakeApiClient()
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(
+ text="list bogus",
+ user_id="U1",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "ephemeral"
+ assert "Unknown severity" in _flatten(res["blocks"])
+ # The bad severity must short-circuit before calling the API.
+ assert api.calls == []
+
+
+async def test_list_translates_upstream_error_to_ephemeral_error():
+ api = FakeApiClient(raise_on="list_open_cases")
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(text="list", user_id="U1", api_client=api, actions_client=actions, web_base=WEB_BASE)
+ assert res["response_type"] == "ephemeral"
+ assert "Could not load cases" in _flatten(res["blocks"])
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# investigate
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_investigate_requires_case_id():
+ api = FakeApiClient()
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(
+ text="investigate",
+ user_id="U1",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "ephemeral"
+ assert "Usage" in _flatten(res["blocks"])
+
+
+async def test_investigate_calls_get_case_then_launch_and_returns_in_channel():
+ api = FakeApiClient(
+ case={"id": "c-9", "case_number": "AISOC-9"},
+ investigation={"run_id": "run-42"},
+ )
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(
+ text="investigate AISOC-9",
+ user_id="U777",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "in_channel"
+ assert ("get_case", {"case_id": "AISOC-9"}) in api.calls
+ # alert_summary mentions the requesting Slack user so the case timeline
+ # records who fired the run.
+ launch_call = next(c for c in api.calls if c[0] == "launch_investigation")
+ assert "U777" in launch_call[1]["alert_summary"]
+ assert "run-42" in _flatten(res["blocks"])
+
+
+async def test_investigate_translates_upstream_error_to_ephemeral_error():
+ api = FakeApiClient(raise_on="launch_investigation")
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(
+ text="investigate AISOC-9",
+ user_id="U1",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "ephemeral"
+ assert "Investigation failed" in _flatten(res["blocks"])
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# explain
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_explain_returns_in_channel_with_summary_and_recommendations():
+ api = FakeApiClient(
+ case={"id": "c-1", "case_number": "AISOC-1", "title": "t", "severity": "high", "status": "investigating"},
+ summary={"summary": "DNS tunnelling suspected.", "recommendations": ["Isolate"]},
+ )
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(
+ text="explain AISOC-1",
+ user_id="U1",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "in_channel"
+ rendered = _flatten(res["blocks"])
+ assert "DNS tunnelling suspected." in rendered
+ assert "Isolate" in rendered
+
+
+async def test_explain_requires_case_id():
+ api = FakeApiClient()
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(
+ text="explain",
+ user_id="U1",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "ephemeral"
+ assert "Usage" in _flatten(res["blocks"])
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# isolate / block — shared "approval required" path
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_isolate_with_quoted_reason_parses_target_and_rationale():
+ api = FakeApiClient(case={"id": "case-7", "case_number": "AISOC-7"})
+ actions = FakeActionsClient(
+ action={
+ "id": "act-1",
+ "status": "awaiting_approval",
+ "action_type": "isolate_host",
+ "target": "host-42",
+ "blast_radius": "high",
+ }
+ )
+ res = await handle_aisoc_command(
+ text='isolate host-42 AISOC-7 "confirmed beacon to known bad C2"',
+ user_id="U1",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "in_channel"
+ # approval card emits an actions block with approve/deny buttons
+ assert _has_action_buttons(res["blocks"])
+ submitted = next(c for c in actions.calls if c[0] == "submit_action")[1]
+ assert submitted["action_type"] == "isolate_host"
+ assert submitted["target"] == "host-42"
+ assert submitted["case_id"] == "case-7"
+ assert submitted["rationale"] == "confirmed beacon to known bad C2"
+ assert submitted["requested_by"] == "U1"
+
+
+async def test_block_dispatches_block_ip_action_type():
+ api = FakeApiClient(case={"id": "case-7", "case_number": "AISOC-7"})
+ actions = FakeActionsClient(
+ action={
+ "id": "act-2",
+ "status": "awaiting_approval",
+ "action_type": "block_ip",
+ "target": "1.2.3.4",
+ "blast_radius": "medium",
+ }
+ )
+ res = await handle_aisoc_command(
+ text="block 1.2.3.4 AISOC-7",
+ user_id="U99",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "in_channel"
+ assert _has_action_buttons(res["blocks"])
+ submitted = next(c for c in actions.calls if c[0] == "submit_action")[1]
+ assert submitted["action_type"] == "block_ip"
+ assert submitted["target"] == "1.2.3.4"
+
+
+async def test_isolate_requires_target_and_case():
+ api = FakeApiClient()
+ actions = FakeActionsClient()
+ res = await handle_aisoc_command(
+ text="isolate host-only",
+ user_id="U1",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "ephemeral"
+ assert "Usage" in _flatten(res["blocks"])
+ assert actions.calls == [] # never submitted to actions service
+
+
+async def test_auto_approved_action_renders_confirmation_without_buttons():
+ api = FakeApiClient(case={"id": "case-7", "case_number": "AISOC-7"})
+ actions = FakeActionsClient(
+ action={
+ "id": "act-3",
+ "status": "approved", # low-blast, no approval needed
+ "action_type": "isolate_host",
+ "target": "host-low",
+ "blast_radius": "low",
+ }
+ )
+ res = await handle_aisoc_command(
+ text="isolate host-low AISOC-7 routine",
+ user_id="U1",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "in_channel"
+ assert not _has_action_buttons(res["blocks"])
+ assert "submitted" in _flatten(res["blocks"]).lower()
+
+
+async def test_isolate_translates_upstream_error_to_ephemeral_error():
+ api = FakeApiClient(case={"id": "case-7"})
+ actions = FakeActionsClient(raise_on="submit_action")
+ res = await handle_aisoc_command(
+ text="isolate host-1 AISOC-7",
+ user_id="U1",
+ api_client=api,
+ actions_client=actions,
+ web_base=WEB_BASE,
+ )
+ assert res["response_type"] == "ephemeral"
+ assert "Action submission failed" in _flatten(res["blocks"])
diff --git a/services/slack-bot/tests/test_config.py b/services/slack-bot/tests/test_config.py
new file mode 100644
index 000000000..75baf987b
--- /dev/null
+++ b/services/slack-bot/tests/test_config.py
@@ -0,0 +1,71 @@
+"""Tests for ``app.core.config``."""
+
+from __future__ import annotations
+
+import importlib
+
+import pytest
+
+
[email protected](autouse=True)
+def _reset_settings_cache(monkeypatch: pytest.MonkeyPatch):
+ """
+ ``get_settings`` is cached; each test needs a fresh import so the env
+ overrides actually take effect.
+ """
+ from app.core import config as config_module
+
+ config_module.get_settings.cache_clear()
+ yield
+ config_module.get_settings.cache_clear()
+
+
+def test_defaults_are_safe_for_local_dev(monkeypatch: pytest.MonkeyPatch):
+ """
+ With no env vars set, the bot must still import — but signature
+ verification must be disabled so we never accept unsigned Slack requests
+ in production by accident.
+ """
+ for var in (
+ "SLACK_BOT_TOKEN",
+ "SLACK_SIGNING_SECRET",
+ "AISOC_API_SERVICE_TOKEN",
+ "AISOC_ACTIONS_SERVICE_TOKEN",
+ ):
+ monkeypatch.delenv(var, raising=False)
+
+ from app.core.config import get_settings
+
+ settings = get_settings()
+ assert settings.SLACK_BOT_TOKEN == ""
+ assert settings.SLACK_SIGNING_SECRET == ""
+ assert settings.signature_verification_enabled is False
+ assert settings.AISOC_API_BASE_URL.startswith("http")
+ assert settings.AISOC_ACTIONS_BASE_URL.startswith("http")
+ assert settings.AISOC_SLACK_BOT_PORT == 8089
+
+
+def test_env_overrides_take_effect(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("SLACK_BOT_TOKEN", "xoxb-test-1234")
+ monkeypatch.setenv("SLACK_SIGNING_SECRET", "shhh")
+ monkeypatch.setenv("AISOC_API_BASE_URL", "http://api.local:9000")
+ monkeypatch.setenv("AISOC_ACTIONS_BASE_URL", "http://actions.local:9001")
+ monkeypatch.setenv("AISOC_API_SERVICE_TOKEN", "aisoc_api_key")
+ monkeypatch.setenv("AISOC_ACTIONS_SERVICE_TOKEN", "aisoc_actions_key")
+ monkeypatch.setenv("AISOC_DEFAULT_TENANT_ID", "11111111-2222-3333-4444-555555555555")
+ monkeypatch.setenv("AISOC_SLACK_BOT_PORT", "9090")
+
+ from app.core import config as config_module
+
+ importlib.reload(config_module)
+
+ settings = config_module.get_settings()
+ assert settings.SLACK_BOT_TOKEN == "xoxb-test-1234"
+ assert settings.SLACK_SIGNING_SECRET == "shhh"
+ assert settings.signature_verification_enabled is True
+ assert settings.AISOC_API_BASE_URL == "http://api.local:9000"
+ assert settings.AISOC_ACTIONS_BASE_URL == "http://actions.local:9001"
+ assert settings.AISOC_API_SERVICE_TOKEN == "aisoc_api_key"
+ assert settings.AISOC_ACTIONS_SERVICE_TOKEN == "aisoc_actions_key"
+ assert settings.AISOC_DEFAULT_TENANT_ID == "11111111-2222-3333-4444-555555555555"
+ assert settings.AISOC_SLACK_BOT_PORT == 9090
diff --git a/services/slack-bot/tests/test_interactions.py b/services/slack-bot/tests/test_interactions.py
new file mode 100644
index 000000000..24db59f0e
--- /dev/null
+++ b/services/slack-bot/tests/test_interactions.py
@@ -0,0 +1,215 @@
+"""
+Tests for ``app.interactions``.
+
+Covered branches
+----------------
+
+* approve / deny route to the matching client method
+* upstream errors translate to ephemeral error blocks (no traceback leaks)
+* malformed button values translate to ephemeral error blocks
+* unknown action ids translate to ephemeral error blocks
+* successful decisions emit ``replace_original=True`` so the approval card
+ can't be clicked twice
+* the post-decision message records the deciding user (audit trail)
+* the post-decision message survives a sparse upstream response (we
+ fall back to the routing-decoded action id)
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from app.interactions import (
+ APPROVE_ACTION_ID,
+ DENY_ACTION_ID,
+ handle_action_decision,
+)
+from app.services.aisoc_clients import AisocClientError
+
+
+class FakeActionsClient:
+ """Minimal stand-in for :class:`AisocActionsClient` for interaction tests."""
+
+ def __init__(
+ self,
+ *,
+ approve_response: dict[str, Any] | None = None,
+ reject_response: dict[str, Any] | None = None,
+ raise_on: str | None = None,
+ ) -> None:
+ self._approve_response = approve_response or {
+ "id": "act-1",
+ "status": "approved",
+ "action_type": "isolate_host",
+ "target": "host-1",
+ }
+ self._reject_response = reject_response or {
+ "id": "act-1",
+ "status": "rejected",
+ "action_type": "isolate_host",
+ "target": "host-1",
+ }
+ self._raise_on = raise_on
+ self.approve_calls: list[str] = []
+ self.reject_calls: list[str] = []
+
+ async def approve_action(self, action_id: str) -> dict[str, Any]:
+ if self._raise_on == "approve":
+ raise AisocClientError("upstream approve boom", status_code=502)
+ self.approve_calls.append(action_id)
+ return self._approve_response
+
+ async def reject_action(self, action_id: str) -> dict[str, Any]:
+ if self._raise_on == "reject":
+ raise AisocClientError("upstream reject boom", status_code=502)
+ self.reject_calls.append(action_id)
+ return self._reject_response
+
+
+def _flatten(blocks: list[dict[str, Any]]) -> str:
+ return str(blocks)
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Happy paths
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_approve_replaces_card_and_records_decider():
+ actions = FakeActionsClient()
+ res = await handle_action_decision(
+ action_id_event=APPROVE_ACTION_ID,
+ button_value="act-7|case-3",
+ user_id="U42",
+ actions_client=actions,
+ )
+ assert actions.approve_calls == ["act-7"]
+ assert actions.reject_calls == []
+ # Replace original guarantees the buttons can't be clicked twice.
+ assert res["replace_original"] is True
+ assert res["response_type"] == "in_channel"
+ rendered = _flatten(res["blocks"])
+ assert "U42" in rendered
+ assert "approved" in rendered.lower()
+
+
+async def test_deny_replaces_card_and_calls_reject_client():
+ actions = FakeActionsClient()
+ res = await handle_action_decision(
+ action_id_event=DENY_ACTION_ID,
+ button_value="act-9|case-3",
+ user_id="U42",
+ actions_client=actions,
+ )
+ assert actions.reject_calls == ["act-9"]
+ assert actions.approve_calls == []
+ assert res["replace_original"] is True
+ rendered = _flatten(res["blocks"])
+ assert "denied" in rendered.lower() or "rejected" in rendered.lower()
+
+
+async def test_value_without_case_id_is_accepted():
+ """
+ The case id in the routing value is informational only — we still want to
+ let the analyst's decision land if Slack ever truncates or reformats the
+ value. The action id is the only required field.
+ """
+ actions = FakeActionsClient()
+ res = await handle_action_decision(
+ action_id_event=APPROVE_ACTION_ID,
+ button_value="act-only",
+ user_id="U1",
+ actions_client=actions,
+ )
+ assert actions.approve_calls == ["act-only"]
+ assert res.get("replace_original") is True
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Defensive / error paths
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_unknown_action_id_returns_ephemeral_error_without_calling_client():
+ actions = FakeActionsClient()
+ res = await handle_action_decision(
+ action_id_event="aisoc_action_open_case", # not approve/deny
+ button_value="act-7|case-3",
+ user_id="U42",
+ actions_client=actions,
+ )
+ assert res["response_type"] == "ephemeral"
+ assert "Unknown interactive action" in _flatten(res["blocks"])
+ assert actions.approve_calls == []
+ assert actions.reject_calls == []
+
+
+async def test_empty_button_value_returns_ephemeral_error():
+ actions = FakeActionsClient()
+ res = await handle_action_decision(
+ action_id_event=APPROVE_ACTION_ID,
+ button_value="",
+ user_id="U42",
+ actions_client=actions,
+ )
+ assert res["response_type"] == "ephemeral"
+ assert "approval button" in _flatten(res["blocks"])
+ assert actions.approve_calls == []
+
+
+async def test_button_value_with_no_action_id_returns_ephemeral_error():
+ actions = FakeActionsClient()
+ res = await handle_action_decision(
+ action_id_event=APPROVE_ACTION_ID,
+ button_value="|case-3", # action_id half is empty
+ user_id="U42",
+ actions_client=actions,
+ )
+ assert res["response_type"] == "ephemeral"
+ assert "approval button" in _flatten(res["blocks"])
+ assert actions.approve_calls == []
+
+
+async def test_upstream_failure_translates_to_ephemeral_error():
+ actions = FakeActionsClient(raise_on="approve")
+ res = await handle_action_decision(
+ action_id_event=APPROVE_ACTION_ID,
+ button_value="act-7|case-3",
+ user_id="U42",
+ actions_client=actions,
+ )
+ assert res["response_type"] == "ephemeral"
+ rendered = _flatten(res["blocks"])
+ assert "act-7" in rendered
+ assert "Could not record decision" in rendered
+ # The original approval card must NOT be replaced when the call fails —
+ # otherwise the analyst loses the buttons and can't retry.
+ assert "replace_original" not in res
+
+
+async def test_sparse_upstream_response_falls_back_to_routing_action_id():
+ """
+ If services/actions returns a payload missing ``id``/``action_id``, we
+ must still surface a useful audit-trail line. We fall back to the id
+ decoded from the routing value.
+ """
+ actions = FakeActionsClient(
+ approve_response={"status": "approved"} # no id/action_id/target
+ )
+ res = await handle_action_decision(
+ action_id_event=APPROVE_ACTION_ID,
+ button_value="act-fallback|case-3",
+ user_id="U42",
+ actions_client=actions,
+ )
+ assert res.get("replace_original") is True
+ assert "act-fallback" in _flatten(res["blocks"])
diff --git a/services/slack-bot/tests/test_main.py b/services/slack-bot/tests/test_main.py
new file mode 100644
index 000000000..0694d9c8b
--- /dev/null
+++ b/services/slack-bot/tests/test_main.py
@@ -0,0 +1,277 @@
+"""
+Tests for ``app.main`` — the FastAPI + Bolt entrypoint.
+
+What we cover here
+==================
+
+* ``GET /health`` returns 200 and the expected service identifier so
+ docker-compose / Fly.io can rely on it for liveness.
+* The FastAPI app exposes the single Slack webhook endpoint
+ (``POST /slack/events``).
+* The lifespan hook builds and tears down the upstream HTTP clients —
+ if it didn't, every Slack request would leak a connection.
+* :func:`app.main._route_action_decision` correctly extracts the
+ ``user.id`` and ``actions[0].value`` shape Slack actually delivers
+ and converts last-resort exceptions into ephemeral errors instead of
+ raising back into Bolt.
+
+What we deliberately don't cover
+================================
+
+We don't fire real Slack-shaped slash command requests through Bolt's
+verifier (that would force us to mint signed payloads with a fake
+secret). The slash command logic is already fully tested in
+``tests/test_commands.py``; here we just verify the Bolt → handler
+wiring (decorator registration, request unpacking).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from app import main as main_module
+from app.interactions import APPROVE_ACTION_ID, DENY_ACTION_ID
+from app.services.aisoc_clients import AisocClientError
+from fastapi.testclient import TestClient
+
+
+class _StubActionsClient:
+ """Mock for :class:`AisocActionsClient` — only methods used by interactions."""
+
+ def __init__(self, *, raise_on: str | None = None) -> None:
+ self._raise_on = raise_on
+ self.approve_calls: list[str] = []
+ self.reject_calls: list[str] = []
+
+ async def approve_action(self, action_id: str) -> dict[str, Any]:
+ if self._raise_on == "approve":
+ raise AisocClientError("upstream boom", status_code=502)
+ self.approve_calls.append(action_id)
+ return {"id": action_id, "status": "approved", "action_type": "isolate_host"}
+
+ async def reject_action(self, action_id: str) -> dict[str, Any]:
+ if self._raise_on == "reject":
+ raise AisocClientError("upstream boom", status_code=502)
+ self.reject_calls.append(action_id)
+ return {"id": action_id, "status": "rejected", "action_type": "isolate_host"}
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Health + route registration
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def test_health_endpoint_returns_expected_payload():
+ """
+ ``/health`` is the contract docker-compose and Fly.io check. If the
+ JSON shape changes, both deployments need to update simultaneously
+ — keep this assertion strict so we don't drift accidentally.
+ """
+ with TestClient(main_module.app) as client:
+ res = client.get("/health")
+ assert res.status_code == 200
+ assert res.json() == {"status": "healthy", "service": "aisoc-slack-bot"}
+
+
+def test_slack_events_route_is_registered():
+ """The single Slack webhook endpoint must exist at ``/slack/events``."""
+ paths = {getattr(route, "path", None) for route in main_module.app.routes}
+ assert "/slack/events" in paths
+
+
+def test_health_route_is_registered():
+ paths = {getattr(route, "path", None) for route in main_module.app.routes}
+ assert "/health" in paths
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Lifespan: clients are built on startup and closed on shutdown
+# ────────────────────────────────────────────────────────────────────────────
+
+
+def test_lifespan_builds_and_closes_clients(monkeypatch):
+ """
+ The lifespan must build singleton AisocApiClient + AisocActionsClient on
+ startup and call ``aclose()`` on both during shutdown. Without this we'd
+ leak an httpx pool on every reload.
+ """
+ closed: list[str] = []
+ built: list[str] = []
+
+ class _RecordingApiClient:
+ base_url = "http://test-api"
+
+ @classmethod
+ def from_settings(cls):
+ built.append("api")
+ return cls()
+
+ async def aclose(self) -> None:
+ closed.append("api")
+
+ class _RecordingActionsClient:
+ base_url = "http://test-actions"
+
+ @classmethod
+ def from_settings(cls):
+ built.append("actions")
+ return cls()
+
+ async def aclose(self) -> None:
+ closed.append("actions")
+
+ monkeypatch.setattr(main_module, "AisocApiClient", _RecordingApiClient)
+ monkeypatch.setattr(main_module, "AisocActionsClient", _RecordingActionsClient)
+
+ with TestClient(main_module.app) as client:
+ # Trigger startup.
+ client.get("/health")
+ assert built == ["api", "actions"]
+ # The bolt app + handler are stashed on app.state for /slack/events.
+ assert client.app.state.api_client is not None
+ assert client.app.state.actions_client is not None
+ assert client.app.state.bolt_app is not None
+ assert client.app.state.bolt_handler is not None
+
+ # Both clients must be closed on shutdown.
+ assert sorted(closed) == ["actions", "api"]
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# _route_action_decision: payload extraction + exception containment
+# ────────────────────────────────────────────────────────────────────────────
+
+
+async def test_route_action_decision_extracts_user_and_value_and_calls_approve():
+ """
+ Verify the Slack ``block_actions`` payload shape is parsed into the
+ fields :func:`handle_action_decision` expects, and that approve
+ routing reaches the actions client.
+ """
+ actions = _StubActionsClient()
+ captured: list[dict] = []
+
+ async def respond(payload: dict) -> None:
+ captured.append(payload)
+
+ body = {
+ "user": {"id": "U99", "username": "soc-analyst"},
+ "actions": [{"action_id": APPROVE_ACTION_ID, "value": "act-7|case-3"}],
+ }
+ await main_module._route_action_decision(
+ event_action_id=APPROVE_ACTION_ID,
+ body=body,
+ respond=respond,
+ actions_client=actions,
+ )
+ assert actions.approve_calls == ["act-7"]
+ assert len(captured) == 1
+ # On a successful decision we replace the original card so analysts
+ # can't double-click.
+ assert captured[0].get("replace_original") is True
+
+
+async def test_route_action_decision_routes_deny_branch():
+ actions = _StubActionsClient()
+ captured: list[dict] = []
+
+ async def respond(payload: dict) -> None:
+ captured.append(payload)
+
+ body = {
+ "user": {"id": "U99"},
+ "actions": [{"action_id": DENY_ACTION_ID, "value": "act-9|case-3"}],
+ }
+ await main_module._route_action_decision(
+ event_action_id=DENY_ACTION_ID,
+ body=body,
+ respond=respond,
+ actions_client=actions,
+ )
+ assert actions.reject_calls == ["act-9"]
+ assert actions.approve_calls == []
+ assert captured[0].get("replace_original") is True
+
+
+async def test_route_action_decision_handles_missing_user_field_gracefully():
+ """A malformed payload missing ``user`` should not raise back into Bolt."""
+ actions = _StubActionsClient()
+ captured: list[dict] = []
+
+ async def respond(payload: dict) -> None:
+ captured.append(payload)
+
+ body = {"actions": [{"value": "act-1|case-1"}]} # no user
+ await main_module._route_action_decision(
+ event_action_id=APPROVE_ACTION_ID,
+ body=body,
+ respond=respond,
+ actions_client=actions,
+ )
+ # We default user_id to "unknown" so the audit-trail line still
+ # renders something deterministic.
+ assert actions.approve_calls == ["act-1"]
+ assert captured[0].get("replace_original") is True
+
+
+async def test_route_action_decision_handles_empty_actions_list():
+ """
+ No actions at all should produce an ephemeral error, not a crash.
+ The interactions module returns the error block; we just verify the
+ main wrapper doesn't lose it.
+ """
+ actions = _StubActionsClient()
+ captured: list[dict] = []
+
+ async def respond(payload: dict) -> None:
+ captured.append(payload)
+
+ body = {"user": {"id": "U99"}, "actions": []}
+ await main_module._route_action_decision(
+ event_action_id=APPROVE_ACTION_ID,
+ body=body,
+ respond=respond,
+ actions_client=actions,
+ )
+ assert actions.approve_calls == []
+ assert captured[0]["response_type"] == "ephemeral"
+
+
+async def test_route_action_decision_converts_unhandled_exception_to_ephemeral(
+ monkeypatch,
+):
+ """
+ The wrapper has a last-resort ``except Exception`` so an unforeseen
+ bug in :func:`handle_action_decision` lands in Slack as an
+ ephemeral error rather than as a 500 to Slack (which would then
+ retry the click and double-fire the approval).
+ """
+
+ async def boom(**kwargs):
+ raise RuntimeError("kaboom")
+
+ monkeypatch.setattr(main_module, "handle_action_decision", boom)
+
+ captured: list[dict] = []
+
+ async def respond(payload: dict) -> None:
+ captured.append(payload)
+
+ body = {
+ "user": {"id": "U99"},
+ "actions": [{"value": "act-1|case-1"}],
+ }
+ await main_module._route_action_decision(
+ event_action_id=APPROVE_ACTION_ID,
+ body=body,
+ respond=respond,
+ actions_client=_StubActionsClient(),
+ )
+ assert captured[0]["response_type"] == "ephemeral"
+ assert "Internal error" in captured[0]["text"]