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(pillar-2): playbook API, schema, CI lint (p2-api, p2-schema)

Beenu Arora2e0d8773ac19
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1df0cabb9..928c76486 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -156,6 +156,23 @@ jobs:
name: mitre-accuracy-report
path: eval_report.json
+ # ──────────────────────────────────────────────
+ # Pillar-2: Playbook JSON Schema lint
+ # Validates all playbook JSON files against schemas/playbook.schema.json
+ # ──────────────────────────────────────────────
+ p2-playbook-schema-lint:
+ name: P2 — Playbook Schema Lint
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ - name: Install jsonschema
+ run: pip install jsonschema
+ - name: Lint playbook files
+ run: python3 scripts/lint_playbooks.py
+
# ──────────────────────────────────────────────
# Docker Compose smoke test
# ──────────────────────────────────────────────
diff --git a/schemas/playbook.schema.json b/schemas/playbook.schema.json
new file mode 100644
index 000000000..b0e652f89
--- /dev/null
+++ b/schemas/playbook.schema.json
@@ -0,0 +1,166 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "https://github.com/cyble-dev/aisoc/schemas/playbook.schema.json",
+ "title": "AiSOC Playbook",
+ "description": "Schema for AiSOC v4 Pillar-2 playbook definitions.",
+ "type": "object",
+ "required": ["name", "steps"],
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "Unique playbook identifier (UUID or slug)."
+ },
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 120,
+ "description": "Human-readable playbook name."
+ },
+ "description": {
+ "type": "string",
+ "maxLength": 1000
+ },
+ "version": {
+ "type": "string",
+ "pattern": "^\\d+\\.\\d+\\.\\d+$",
+ "description": "Semantic version string, e.g. '1.0.0'."
+ },
+ "tags": {
+ "type": "array",
+ "items": { "type": "string" },
+ "uniqueItems": true
+ },
+ "trigger": {
+ "type": "object",
+ "required": ["on"],
+ "properties": {
+ "on": {
+ "type": "string",
+ "enum": ["alert", "case", "manual", "schedule"],
+ "description": "Event type that fires this playbook."
+ },
+ "severity": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "enum": ["info", "low", "medium", "high", "critical"]
+ },
+ "description": "Optional severity filter."
+ },
+ "tags": {
+ "type": "array",
+ "items": { "type": "string" },
+ "description": "Alert/case must carry at least one of these tags."
+ },
+ "cron": {
+ "type": "string",
+ "description": "Cron expression for schedule trigger."
+ }
+ },
+ "additionalProperties": true
+ },
+ "steps": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "#/definitions/PlaybookStep" }
+ },
+ "author": {
+ "type": "string"
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": true
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time"
+ }
+ },
+ "definitions": {
+ "StepCondition": {
+ "type": "object",
+ "required": ["field", "operator"],
+ "additionalProperties": false,
+ "properties": {
+ "field": {
+ "type": "string",
+ "description": "Dot-path into run context, e.g. 'alert.severity'."
+ },
+ "operator": {
+ "type": "string",
+ "enum": ["eq", "ne", "gt", "lt", "contains", "exists"]
+ },
+ "value": {
+ "description": "Expected value (not required for 'exists' operator)."
+ }
+ }
+ },
+ "PlaybookStep": {
+ "type": "object",
+ "required": ["name", "type"],
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "Short unique identifier within the playbook (used for branching)."
+ },
+ "name": {
+ "type": "string",
+ "minLength": 1
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "enrich",
+ "investigate",
+ "notify",
+ "block_ip",
+ "isolate_host",
+ "create_ticket",
+ "close_case",
+ "http",
+ "condition"
+ ]
+ },
+ "params": {
+ "type": "object",
+ "description": "Step-specific parameters. Keys depend on the step type.",
+ "additionalProperties": true
+ },
+ "condition": {
+ "$ref": "#/definitions/StepCondition"
+ },
+ "on_failure": {
+ "type": "string",
+ "enum": ["abort", "continue", "retry"],
+ "default": "abort"
+ },
+ "retry_max": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 5,
+ "default": 0
+ },
+ "timeout_seconds": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 600,
+ "default": 30
+ },
+ "next_true": {
+ "type": "string",
+ "description": "Step ID to jump to when condition is true (branching)."
+ },
+ "next_false": {
+ "type": "string",
+ "description": "Step ID to jump to when condition is false (branching)."
+ }
+ }
+ }
+ }
+}
diff --git a/scripts/lint_playbooks.py b/scripts/lint_playbooks.py
new file mode 100755
index 000000000..856a4c9c8
--- /dev/null
+++ b/scripts/lint_playbooks.py
@@ -0,0 +1,101 @@
+#!/usr/bin/env python3
+"""
+Lint all playbook JSON files in services/agents/data/playbooks/ (and any
+*.playbook.json files anywhere in the repo) against the JSON Schema at
+schemas/playbook.schema.json.
+
+Exit code:
+ 0 all files pass
+ 1 one or more files fail validation
+ 2 no files found (treated as a warning, exits 0)
+
+Usage:
+ python3 scripts/lint_playbooks.py
+ python3 scripts/lint_playbooks.py path/to/my-playbook.json
+"""
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+try:
+ import jsonschema
+except ImportError:
+ print("ERROR: jsonschema not installed. Run: pip install jsonschema", file=sys.stderr)
+ sys.exit(1)
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+SCHEMA_PATH = REPO_ROOT / "schemas" / "playbook.schema.json"
+
+# Directories / glob patterns to scan automatically
+SCAN_DIRS = [
+ REPO_ROOT / "services" / "agents" / "data" / "playbooks",
+]
+SCAN_GLOB = "*.json"
+
+
+def load_schema() -> dict:
+ if not SCHEMA_PATH.exists():
+ print(f"ERROR: Schema not found at {SCHEMA_PATH}", file=sys.stderr)
+ sys.exit(1)
+ return json.loads(SCHEMA_PATH.read_text())
+
+
+def collect_files(extra: list[str]) -> list[Path]:
+ files: list[Path] = []
+ for d in SCAN_DIRS:
+ if d.is_dir():
+ files.extend(sorted(d.glob(SCAN_GLOB)))
+ for p in extra:
+ files.append(Path(p))
+ return files
+
+
+def validate_file(path: Path, schema: dict, validator_cls) -> list[str]:
+ try:
+ data = json.loads(path.read_text())
+ except json.JSONDecodeError as exc:
+ return [f"JSON parse error: {exc}"]
+
+ # If the file is a list (e.g. index.json with multiple playbooks), validate each item
+ items = data if isinstance(data, list) else [data]
+ errors: list[str] = []
+ for i, item in enumerate(items):
+ for err in sorted(validator_cls.iter_errors(item), key=lambda e: list(e.path)):
+ loc = ".".join(str(p) for p in err.path) or "(root)"
+ errors.append(f" [item {i}] {loc}: {err.message}")
+ return errors
+
+
+def main() -> None:
+ extra_args = sys.argv[1:]
+ schema = load_schema()
+ validator_cls = jsonschema.Draft7Validator(schema)
+
+ files = collect_files(extra_args)
+
+ if not files:
+ print("No playbook files found — skipping lint (exit 0).")
+ sys.exit(0)
+
+ fail_count = 0
+ for path in files:
+ errs = validate_file(path, schema, validator_cls)
+ if errs:
+ print(f"FAIL {path.relative_to(REPO_ROOT)}")
+ for e in errs:
+ print(e)
+ fail_count += 1
+ else:
+ print(f"OK {path.relative_to(REPO_ROOT)}")
+
+ total = len(files)
+ print(f"\n{total - fail_count}/{total} playbook files passed schema validation.")
+
+ if fail_count:
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/services/agents/app/api/playbooks.py b/services/agents/app/api/playbooks.py
new file mode 100644
index 000000000..443c82bbf
--- /dev/null
+++ b/services/agents/app/api/playbooks.py
@@ -0,0 +1,158 @@
+"""
+Pillar-2 Playbook REST API
+===========================
+Endpoints:
+ GET /api/v1/playbooks → list all playbooks
+ POST /api/v1/playbooks → create a playbook
+ GET /api/v1/playbooks/{id} → get a playbook
+ PUT /api/v1/playbooks/{id} → update a playbook
+ DELETE /api/v1/playbooks/{id} → delete a playbook
+ POST /api/v1/playbooks/{id}/run → execute a playbook against a context
+ GET /api/v1/playbooks/runs/{run_id} → get a run result
+"""
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from fastapi import APIRouter, BackgroundTasks, HTTPException
+from pydantic import BaseModel
+
+from app.playbook import (
+ Playbook,
+ PlaybookEngine,
+ PlaybookRun,
+ PlaybookStore,
+ RunStatus,
+)
+
+logger = logging.getLogger("aisoc.api.playbooks")
+router = APIRouter(prefix="/api/v1/playbooks", tags=["playbooks"])
+
+# In-memory run store for Pillar-2 (swap for Redis/DB in production)
+_runs: dict[str, PlaybookRun] = {}
+
+
+# ---------------------------------------------------------------------------
+# Request / Response helpers
+# ---------------------------------------------------------------------------
+
+class RunRequest(BaseModel):
+ context: dict[str, Any] = {}
+ dry_run: bool = False
+
+
+# ---------------------------------------------------------------------------
+# CRUD
+# ---------------------------------------------------------------------------
+
[email protected]("", summary="List all playbooks")
+async def list_playbooks(enabled_only: bool = False) -> list[dict]:
+ store = PlaybookStore.default()
+ return [pb.model_dump() for pb in store.list(enabled_only=enabled_only)]
+
+
[email protected]("", summary="Create a playbook", status_code=201)
+async def create_playbook(playbook: Playbook) -> dict:
+ store = PlaybookStore.default()
+ created = store.create(playbook)
+ return created.model_dump()
+
+
[email protected]("/{playbook_id}", summary="Get a playbook")
+async def get_playbook(playbook_id: str) -> dict:
+ store = PlaybookStore.default()
+ pb = store.get(playbook_id)
+ if not pb:
+ raise HTTPException(status_code=404, detail="Playbook not found")
+ return pb.model_dump()
+
+
[email protected]("/{playbook_id}", summary="Update a playbook")
+async def update_playbook(playbook_id: str, data: dict[str, Any]) -> dict:
+ store = PlaybookStore.default()
+ updated = store.update(playbook_id, data)
+ if not updated:
+ raise HTTPException(status_code=404, detail="Playbook not found")
+ return updated.model_dump()
+
+
[email protected]("/{playbook_id}", summary="Delete a playbook", status_code=204)
+async def delete_playbook(playbook_id: str) -> None:
+ store = PlaybookStore.default()
+ if not store.delete(playbook_id):
+ raise HTTPException(status_code=404, detail="Playbook not found")
+
+
+# ---------------------------------------------------------------------------
+# Execution
+# ---------------------------------------------------------------------------
+
+async def _execute(playbook: Playbook, context: dict[str, Any], dry_run: bool, run_holder: list) -> None:
+ """Background task: run the playbook and store the result."""
+ engine = PlaybookEngine()
+ pr = await engine.run(playbook, context, dry_run=dry_run)
+ _runs[pr.run_id] = pr
+ run_holder.append(pr.run_id)
+
+
[email protected]("/{playbook_id}/run", summary="Execute a playbook", status_code=202)
+async def run_playbook(
+ playbook_id: str,
+ body: RunRequest,
+ background_tasks: BackgroundTasks,
+) -> dict:
+ store = PlaybookStore.default()
+ pb = store.get(playbook_id)
+ if not pb:
+ raise HTTPException(status_code=404, detail="Playbook not found")
+
+ # We need a run_id before background task completes; pre-register it
+ import uuid
+ run_id_holder: list[str] = []
+
+ # Create a placeholder run immediately so the caller can poll it
+ from app.playbook.engine import PlaybookRun as _PR, RunStatus as _RS
+ placeholder = _PR(pb, body.context)
+ placeholder.status = _RS.PENDING
+ _runs[placeholder.run_id] = placeholder
+
+ background_tasks.add_task(
+ _execute_and_update, pb, body.context, body.dry_run, placeholder.run_id
+ )
+
+ return {
+ "run_id": placeholder.run_id,
+ "playbook_id": playbook_id,
+ "status": "pending",
+ "message": f"Playbook execution started. Poll GET /api/v1/playbooks/runs/{placeholder.run_id}",
+ }
+
+
+async def _execute_and_update(
+ playbook: Playbook, context: dict[str, Any], dry_run: bool, run_id: str
+) -> None:
+ """Background task: overwrite placeholder with real run."""
+ engine = PlaybookEngine()
+ pr = await engine.run(playbook, context, dry_run=dry_run)
+ # Preserve the pre-allocated run_id
+ pr.run_id = run_id
+ _runs[run_id] = pr
+
+
[email protected]("/runs/{run_id}", summary="Get a playbook run result")
+async def get_run(run_id: str) -> dict:
+ pr = _runs.get(run_id)
+ if not pr:
+ raise HTTPException(status_code=404, detail="Playbook run not found")
+ return pr.to_dict()
+
+
[email protected]("/runs", summary="List recent playbook runs")
+async def list_runs(limit: int = 50) -> list[dict]:
+ recent = sorted(
+ _runs.values(),
+ key=lambda r: r.started_at or "",
+ reverse=True,
+ )[:limit]
+ return [r.to_dict() for r in recent]
diff --git a/services/agents/app/main.py b/services/agents/app/main.py
index 8ffea3f27..755192f48 100644
--- a/services/agents/app/main.py
+++ b/services/agents/app/main.py
@@ -7,6 +7,8 @@ from fastapi import FastAPI
from app.api.router import router
from app.api.investigate import router as investigate_router
+from app.api.playbooks import router as playbook_router
+from app.playbook import PlaybookStore
from app.tools.mitre_full import load_attck_corpus, embed_techniques_into_qdrant
logger = structlog.get_logger()
@@ -15,6 +17,15 @@ logger = structlog.get_logger()
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""Load resources on startup."""
+ # Seed playbook store with default templates
+ try:
+ store = PlaybookStore.default()
+ n = store.seed_defaults()
+ if n:
+ logger.info("playbook_store.seeded", count=n)
+ except Exception as exc:
+ logger.warning("Playbook store seed failed", error=str(exc))
+
# Load full MITRE ATT&CK corpus
try:
await load_attck_corpus()
@@ -45,6 +56,7 @@ app = FastAPI(
app.include_router(router, prefix="/api/v1")
app.include_router(investigate_router) # prefix already set in investigate.py
+app.include_router(playbook_router) # prefix: /api/v1/playbooks
@app.get("/health")
diff --git a/services/agents/app/playbook/__init__.py b/services/agents/app/playbook/__init__.py
new file mode 100644
index 000000000..fb6ef9203
--- /dev/null
+++ b/services/agents/app/playbook/__init__.py
@@ -0,0 +1,20 @@
+"""AiSOC Playbook Engine — Pillar 2."""
+from .engine import PlaybookEngine, PlaybookRun, RunStatus
+from .models import (
+ Playbook,
+ PlaybookStep,
+ StepCondition,
+ StepType,
+)
+from .store import PlaybookStore
+
+__all__ = [
+ "Playbook",
+ "PlaybookStep",
+ "PlaybookEngine",
+ "PlaybookRun",
+ "PlaybookStore",
+ "RunStatus",
+ "StepCondition",
+ "StepType",
+]
diff --git a/services/agents/app/playbook/engine.py b/services/agents/app/playbook/engine.py
new file mode 100644
index 000000000..7ad1b1850
--- /dev/null
+++ b/services/agents/app/playbook/engine.py
@@ -0,0 +1,363 @@
+"""
+Playbook Engine — Pillar 2
+==========================
+Executes an AiSOC Playbook against a trigger context (alert/case dict).
+
+Design goals:
+- Async, step-by-step execution with per-step structured logging.
+- Supports condition gates, on_failure policies, and basic retries.
+- Emits events to the realtime service so the UI can stream progress.
+- Zero external dependencies beyond httpx + stdlib.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+import time
+import uuid
+from datetime import UTC, datetime
+from enum import Enum
+from typing import Any
+
+import httpx
+
+from .models import Playbook, PlaybookStep, StepCondition, StepType
+
+logger = logging.getLogger("aisoc.playbook.engine")
+
+_REALTIME_URL = os.getenv("REALTIME_URL", "http://realtime:3001")
+_INTERNAL_TOKEN = os.getenv("REALTIME_INTERNAL_TOKEN", "changeme")
+_API_URL = os.getenv("API_URL", "http://api:8000")
+
+
+# ---------------------------------------------------------------------------
+# Run status
+# ---------------------------------------------------------------------------
+
+class RunStatus(str, Enum):
+ PENDING = "pending"
+ RUNNING = "running"
+ COMPLETED = "completed"
+ FAILED = "failed"
+ CANCELLED = "cancelled"
+
+
+class StepStatus(str, Enum):
+ PENDING = "pending"
+ SKIPPED = "skipped"
+ RUNNING = "running"
+ SUCCESS = "success"
+ FAILED = "failed"
+
+
+# ---------------------------------------------------------------------------
+# Run record
+# ---------------------------------------------------------------------------
+
+class StepResult(dict): # thin dict subclass for JSON serialisation
+ pass
+
+
+class PlaybookRun:
+ """Mutable run state threaded through the engine."""
+
+ def __init__(self, playbook: Playbook, trigger_context: dict[str, Any]) -> None:
+ self.run_id: str = str(uuid.uuid4())
+ self.playbook_id: str = playbook.id
+ self.playbook_name: str = playbook.name
+ self.status: RunStatus = RunStatus.PENDING
+ self.trigger_context: dict[str, Any] = trigger_context
+ # Accumulated output from previous steps — available to later steps as {{prev.*}}
+ self.context: dict[str, Any] = dict(trigger_context)
+ self.step_results: list[dict[str, Any]] = []
+ self.started_at: str = ""
+ self.finished_at: str = ""
+ self.error: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "run_id": self.run_id,
+ "playbook_id": self.playbook_id,
+ "playbook_name": self.playbook_name,
+ "status": self.status.value,
+ "context": self.context,
+ "step_results": self.step_results,
+ "started_at": self.started_at,
+ "finished_at": self.finished_at,
+ "error": self.error,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Condition evaluation
+# ---------------------------------------------------------------------------
+
+def _resolve_field(context: dict[str, Any], field: str) -> Any:
+ """Resolve a dot-path field from context, e.g. 'alert.severity'."""
+ parts = field.split(".")
+ cur: Any = context
+ for p in parts:
+ if isinstance(cur, dict):
+ cur = cur.get(p)
+ else:
+ return None
+ return cur
+
+
+def _evaluate_condition(condition: StepCondition, context: dict[str, Any]) -> bool:
+ """Return True if the condition passes."""
+ value = _resolve_field(context, condition.field)
+ op = condition.operator
+ expected = condition.value
+
+ if op == "exists":
+ return value is not None
+ if op == "eq":
+ return value == expected
+ if op == "ne":
+ return value != expected
+ if op == "contains":
+ return expected in str(value) if value is not None else False
+ if op == "gt":
+ return float(value or 0) > float(expected or 0)
+ if op == "lt":
+ return float(value or 0) < float(expected or 0)
+ return False
+
+
+# ---------------------------------------------------------------------------
+# Step handlers
+# ---------------------------------------------------------------------------
+
+async def _handle_enrich(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:
+ ioc = step.params.get("ioc") or context.get("ioc") or context.get("src_ip", "")
+ ioc_type = step.params.get("ioc_type", "ip")
+ r = await http.post(
+ f"{_API_URL}/api/v1/enrichment/lookup",
+ json={"ioc": ioc, "ioc_type": ioc_type},
+ timeout=step.timeout_seconds,
+ )
+ r.raise_for_status()
+ return r.json()
+
+
+async def _handle_investigate(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:
+ case_id = step.params.get("case_id") or context.get("case_id") or context.get("id")
+ if not case_id:
+ return {"skipped": True, "reason": "no case_id in context"}
+ r = await http.post(
+ f"{_API_URL}/api/v1/cases/{case_id}/investigate",
+ json={"dry_run": step.params.get("dry_run", False)},
+ timeout=step.timeout_seconds,
+ )
+ r.raise_for_status()
+ return r.json()
+
+
+async def _handle_notify(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:
+ channel = step.params.get("channel", "webhook")
+ url = step.params.get("url", "")
+ message = step.params.get("message", "AiSOC playbook notification")
+ # Simple template substitution
+ for k, v in context.items():
+ message = message.replace(f"{{{{{k}}}}}", str(v))
+
+ if channel == "webhook" and url:
+ r = await http.post(url, json={"text": message}, timeout=step.timeout_seconds)
+ return {"status": r.status_code}
+ return {"channel": channel, "message": message, "delivered": False, "reason": "no url"}
+
+
+async def _handle_http(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:
+ method = step.params.get("method", "POST").upper()
+ url = step.params.get("url", "")
+ body = step.params.get("body", {})
+ headers = step.params.get("headers", {})
+ r = await http.request(method, url, json=body, headers=headers, timeout=step.timeout_seconds)
+ return {"status": r.status_code, "body": r.text[:500]}
+
+
+async def _handle_block_ip(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:
+ ip = step.params.get("ip") or context.get("src_ip", "")
+ return {"action": "block_ip", "ip": ip, "simulated": True}
+
+
+async def _handle_isolate_host(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:
+ host = step.params.get("host") or context.get("host", "")
+ return {"action": "isolate_host", "host": host, "simulated": True}
+
+
+async def _handle_create_ticket(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:
+ return {"action": "create_ticket", "params": step.params, "simulated": True}
+
+
+async def _handle_close_case(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:
+ case_id = step.params.get("case_id") or context.get("case_id") or context.get("id")
+ if not case_id:
+ return {"skipped": True, "reason": "no case_id"}
+ r = await http.patch(
+ f"{_API_URL}/api/v1/cases/{case_id}",
+ json={"status": "closed"},
+ timeout=step.timeout_seconds,
+ )
+ r.raise_for_status()
+ return {"case_id": case_id, "status": "closed"}
+
+
+_HANDLERS = {
+ StepType.ENRICH: _handle_enrich,
+ StepType.INVESTIGATE: _handle_investigate,
+ StepType.NOTIFY: _handle_notify,
+ StepType.HTTP: _handle_http,
+ StepType.BLOCK_IP: _handle_block_ip,
+ StepType.ISOLATE_HOST: _handle_isolate_host,
+ StepType.CREATE_TICKET: _handle_create_ticket,
+ StepType.CLOSE_CASE: _handle_close_case,
+}
+
+
+# ---------------------------------------------------------------------------
+# Realtime event helper
+# ---------------------------------------------------------------------------
+
+async def _emit(run_id: str, event_type: str, payload: dict, http: httpx.AsyncClient) -> None:
+ try:
+ await http.post(
+ f"{_REALTIME_URL}/internal/agent-event",
+ json={"channel": f"playbook:{run_id}", "type": event_type, "data": payload},
+ headers={"x-internal-token": _INTERNAL_TOKEN},
+ timeout=3,
+ )
+ except Exception:
+ pass # non-critical
+
+
+# ---------------------------------------------------------------------------
+# Engine
+# ---------------------------------------------------------------------------
+
+class PlaybookEngine:
+ """Executes playbooks step-by-step, emitting realtime events."""
+
+ async def run(
+ self,
+ playbook: Playbook,
+ trigger_context: dict[str, Any],
+ *,
+ dry_run: bool = False,
+ ) -> PlaybookRun:
+ pr = PlaybookRun(playbook, trigger_context)
+ pr.started_at = datetime.now(UTC).isoformat()
+ pr.status = RunStatus.RUNNING
+
+ async with httpx.AsyncClient() as http:
+ await _emit(pr.run_id, "run.started", {"playbook": playbook.name, "dry_run": dry_run}, http)
+
+ # Build a step index for branching
+ step_index = {s.id: i for i, s in enumerate(playbook.steps)}
+ visited: set[str] = set()
+ current_idx = 0
+
+ while current_idx < len(playbook.steps):
+ step = playbook.steps[current_idx]
+
+ if step.id in visited:
+ logger.warning("Cycle detected at step %s, aborting", step.id)
+ pr.status = RunStatus.FAILED
+ pr.error = f"cycle at step {step.id}"
+ break
+ visited.add(step.id)
+
+ # Condition gate
+ condition_passed = True
+ if step.condition:
+ condition_passed = _evaluate_condition(step.condition, pr.context)
+
+ if not condition_passed:
+ pr.step_results.append(
+ {"step_id": step.id, "name": step.name, "status": StepStatus.SKIPPED}
+ )
+ # Branching: use next_false if set
+ if step.next_false and step.next_false in step_index:
+ current_idx = step_index[step.next_false]
+ else:
+ current_idx += 1
+ continue
+
+ # CONDITION type — just branch, no external action
+ if step.type == StepType.CONDITION:
+ branch_id = step.next_true if condition_passed else step.next_false
+ if branch_id and branch_id in step_index:
+ current_idx = step_index[branch_id]
+ else:
+ current_idx += 1
+ pr.step_results.append(
+ {"step_id": step.id, "name": step.name, "status": StepStatus.SUCCESS, "branch": branch_id}
+ )
+ continue
+
+ await _emit(pr.run_id, "step.started", {"step": step.name, "type": step.type}, http)
+
+ result: dict = {}
+ step_status = StepStatus.SUCCESS
+ attempt = 0
+ handler = _HANDLERS.get(step.type)
+
+ while True:
+ attempt += 1
+ t0 = time.perf_counter()
+ try:
+ if dry_run:
+ result = {"dry_run": True, "step": step.name}
+ elif handler:
+ result = await handler(step, pr.context, http)
+ else:
+ result = {"skipped": True, "reason": f"no handler for {step.type}"}
+ elapsed = time.perf_counter() - t0
+ result["_elapsed_ms"] = round(elapsed * 1000)
+ break # success
+ except Exception as exc: # noqa: BLE001
+ elapsed = time.perf_counter() - t0
+ logger.error("Step %s attempt %d failed: %s", step.name, attempt, exc)
+ if attempt <= step.retry_max:
+ await asyncio.sleep(min(2 ** attempt, 30))
+ else:
+ step_status = StepStatus.FAILED
+ result = {"error": str(exc), "_elapsed_ms": round(elapsed * 1000)}
+ break
+
+ pr.step_results.append(
+ {"step_id": step.id, "name": step.name, "status": step_status, "result": result}
+ )
+ # Merge result into context for downstream steps
+ pr.context.update({f"_step_{step.id}": result})
+ # Also flatten top-level keys without underscore prefix for convenience
+ for k, v in result.items():
+ if not k.startswith("_"):
+ pr.context.setdefault(k, v)
+
+ await _emit(pr.run_id, "step.done", {
+ "step": step.name,
+ "status": step_status,
+ "result_keys": list(result.keys()),
+ }, http)
+
+ if step_status == StepStatus.FAILED and step.on_failure == "abort":
+ pr.status = RunStatus.FAILED
+ pr.error = f"step '{step.name}' failed"
+ break
+
+ # Advance: branching on success
+ if step_status == StepStatus.SUCCESS and step.next_true and step.next_true in step_index:
+ current_idx = step_index[step.next_true]
+ else:
+ current_idx += 1
+
+ if pr.status == RunStatus.RUNNING:
+ pr.status = RunStatus.COMPLETED
+
+ pr.finished_at = datetime.now(UTC).isoformat()
+ await _emit(pr.run_id, "run.done", pr.to_dict(), http)
+
+ return pr
diff --git a/services/agents/app/playbook/models.py b/services/agents/app/playbook/models.py
new file mode 100644
index 000000000..24e867028
--- /dev/null
+++ b/services/agents/app/playbook/models.py
@@ -0,0 +1,63 @@
+"""Playbook data models — Pydantic v2."""
+from __future__ import annotations
+
+import uuid
+from enum import Enum
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+
+class StepType(str, Enum):
+ """Supported step action types."""
+ ENRICH = "enrich" # Call enrichment service
+ INVESTIGATE = "investigate" # Trigger AI investigator
+ NOTIFY = "notify" # Send notification (Slack, email, webhook)
+ BLOCK_IP = "block_ip" # Call firewall/EDR action
+ ISOLATE_HOST = "isolate_host"
+ CREATE_TICKET = "create_ticket"
+ CLOSE_CASE = "close_case"
+ HTTP = "http" # Generic outbound HTTP call
+ CONDITION = "condition" # Branching / gate
+
+
+class StepCondition(BaseModel):
+ """Optional condition guard that must be true before this step runs."""
+ field: str = Field(..., description="JSONPath into run context, e.g. 'verdict'")
+ operator: Literal["eq", "ne", "gt", "lt", "contains", "exists"] = "eq"
+ value: Any = None
+
+
+class PlaybookStep(BaseModel):
+ """A single step in a playbook."""
+ id: str = Field(default_factory=lambda: str(uuid.uuid4())[:8])
+ name: str
+ type: StepType
+ params: dict[str, Any] = Field(default_factory=dict)
+ condition: StepCondition | None = None
+ on_failure: Literal["abort", "continue", "retry"] = "abort"
+ retry_max: int = 0
+ timeout_seconds: int = 30
+ # For branching: step IDs to jump to on true / false
+ next_true: str | None = None
+ next_false: str | None = None
+
+
+class Playbook(BaseModel):
+ """A complete playbook definition."""
+ id: str = Field(default_factory=lambda: str(uuid.uuid4()))
+ name: str
+ description: str = ""
+ version: str = "1.0.0"
+ tags: list[str] = Field(default_factory=list)
+ # Trigger configuration
+ trigger: dict[str, Any] = Field(
+ default_factory=dict,
+ description="e.g. {'on': 'alert', 'severity': ['high','critical']}",
+ )
+ steps: list[PlaybookStep] = Field(default_factory=list)
+ # Metadata
+ author: str = "AiSOC"
+ enabled: bool = True
+ created_at: str = ""
+ updated_at: str = ""
diff --git a/services/agents/app/playbook/store.py b/services/agents/app/playbook/store.py
new file mode 100644
index 000000000..9a3c4c15d
--- /dev/null
+++ b/services/agents/app/playbook/store.py
@@ -0,0 +1,169 @@
+"""
+Playbook Store
+==============
+Simple in-process store backed by a JSON file (``playbooks.json``).
+In production this would be replaced with a Postgres-backed store, but
+the file-based approach lets us ship playbooks as part of the repo and
+have zero DB migrations for Pillar-2.
+
+The store is a singleton; mount it at app startup:
+
+ store = PlaybookStore.default() # loads from data/playbooks/
+"""
+from __future__ import annotations
+
+import json
+import logging
+import os
+import uuid
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from .models import Playbook, PlaybookStep, StepType
+
+logger = logging.getLogger("aisoc.playbook.store")
+
+_DEFAULT_STORE_DIR = Path(__file__).parent.parent.parent / "data" / "playbooks"
+
+
+class PlaybookStore:
+ """CRUD store for Playbook objects, backed by a JSON manifest file."""
+
+ def __init__(self, store_dir: Path | None = None) -> None:
+ self._dir = store_dir or Path(
+ os.getenv("PLAYBOOK_STORE_DIR", str(_DEFAULT_STORE_DIR))
+ )
+ self._dir.mkdir(parents=True, exist_ok=True)
+ self._manifest_path = self._dir / "index.json"
+ self._playbooks: dict[str, Playbook] = {}
+ self._load()
+
+ # ------------------------------------------------------------------
+ # Singleton
+ # ------------------------------------------------------------------
+
+ _instance: PlaybookStore | None = None
+
+ @classmethod
+ def default(cls) -> "PlaybookStore":
+ if cls._instance is None:
+ cls._instance = cls()
+ return cls._instance
+
+ # ------------------------------------------------------------------
+ # Persistence
+ # ------------------------------------------------------------------
+
+ def _load(self) -> None:
+ # 1) Load individual *.playbook.json fixture files shipped with the repo
+ for fixture in sorted(self._dir.glob("*.playbook.json")):
+ try:
+ data = json.loads(fixture.read_text())
+ pb = Playbook.model_validate(data)
+ if pb.id not in self._playbooks:
+ self._playbooks[pb.id] = pb
+ except Exception as exc:
+ logger.warning("Skipping invalid fixture %s: %s", fixture.name, exc)
+
+ # 2) Load/merge from the mutable index.json (user-created / API-created playbooks)
+ if not self._manifest_path.exists():
+ if self._playbooks:
+ logger.info("Loaded %d fixture playbooks from %s", len(self._playbooks), self._dir)
+ return
+ try:
+ raw: list[dict] = json.loads(self._manifest_path.read_text())
+ for entry in raw:
+ pb = Playbook.model_validate(entry)
+ self._playbooks[pb.id] = pb # index.json wins over fixtures
+ logger.info("Loaded %d playbooks from %s", len(self._playbooks), self._manifest_path)
+ except Exception as exc:
+ logger.error("Failed to load playbooks: %s", exc)
+
+ def _save(self) -> None:
+ data = [pb.model_dump() for pb in self._playbooks.values()]
+ self._manifest_path.write_text(json.dumps(data, indent=2))
+
+ # ------------------------------------------------------------------
+ # CRUD
+ # ------------------------------------------------------------------
+
+ def list(self, *, enabled_only: bool = False) -> list[Playbook]:
+ pbs = list(self._playbooks.values())
+ if enabled_only:
+ pbs = [p for p in pbs if p.enabled]
+ return pbs
+
+ def get(self, playbook_id: str) -> Playbook | None:
+ return self._playbooks.get(playbook_id)
+
+ def create(self, playbook: Playbook) -> Playbook:
+ now = datetime.now(UTC).isoformat()
+ if not playbook.id:
+ playbook = playbook.model_copy(update={"id": str(uuid.uuid4())})
+ playbook = playbook.model_copy(update={"created_at": now, "updated_at": now})
+ self._playbooks[playbook.id] = playbook
+ self._save()
+ return playbook
+
+ def update(self, playbook_id: str, data: dict[str, Any]) -> Playbook | None:
+ pb = self._playbooks.get(playbook_id)
+ if pb is None:
+ return None
+ now = datetime.now(UTC).isoformat()
+ data["updated_at"] = now
+ updated = pb.model_copy(update=data)
+ self._playbooks[playbook_id] = updated
+ self._save()
+ return updated
+
+ def delete(self, playbook_id: str) -> bool:
+ if playbook_id not in self._playbooks:
+ return False
+ del self._playbooks[playbook_id]
+ self._save()
+ return True
+
+ # ------------------------------------------------------------------
+ # Trigger matching
+ # ------------------------------------------------------------------
+
+ def find_matching(self, event: str, context: dict[str, Any]) -> list[Playbook]:
+ """Return all enabled playbooks whose trigger matches this event/context."""
+ matches: list[Playbook] = []
+ for pb in self._playbooks.values():
+ if not pb.enabled:
+ continue
+ trigger = pb.trigger
+ if trigger.get("on") != event:
+ continue
+ # Optional severity filter
+ if "severity" in trigger:
+ allowed = trigger["severity"]
+ if context.get("severity") not in allowed:
+ continue
+ # Optional tag filter
+ if "tags" in trigger:
+ required_tags = set(trigger["tags"])
+ ctx_tags = set(context.get("tags", []))
+ if not required_tags.intersection(ctx_tags):
+ continue
+ matches.append(pb)
+ return matches
+
+ # ------------------------------------------------------------------
+ # Seed helpers (used by seed_demo.py)
+ # ------------------------------------------------------------------
+
+ def seed_defaults(self) -> int:
+ """Seed the store with built-in starter playbooks if store is empty."""
+ if self._playbooks:
+ return 0
+ from .templates import STARTER_PLAYBOOKS
+ count = 0
+ for pb_dict in STARTER_PLAYBOOKS:
+ pb = Playbook.model_validate(pb_dict)
+ self.create(pb)
+ count += 1
+ logger.info("Seeded %d default playbooks", count)
+ return count
diff --git a/services/agents/app/playbook/templates.py b/services/agents/app/playbook/templates.py
new file mode 100644
index 000000000..adc27a314
--- /dev/null
+++ b/services/agents/app/playbook/templates.py
@@ -0,0 +1,425 @@
+"""
+12 Starter Playbook Templates — Pillar 2 (p2-templates)
+========================================================
+These are imported by PlaybookStore.seed_defaults() and can also be
+referenced from the marketplace/index.json.
+"""
+from __future__ import annotations
+
+STARTER_PLAYBOOKS: list[dict] = [
+ # 1 ─ Phishing Triage
+ {
+ "id": "tpl-phishing-triage",
+ "name": "Phishing Email Triage",
+ "description": "Enrich sender IP and URLs, notify SOC channel, auto-close low-risk cases.",
+ "version": "1.0.0",
+ "tags": ["phishing", "email", "triage"],
+ "trigger": {"on": "alert", "severity": ["low", "medium"]},
+ "steps": [
+ {
+ "id": "step-enrich-ip",
+ "name": "Enrich sender IP",
+ "type": "enrich",
+ "params": {"ioc_type": "ip"},
+ },
+ {
+ "id": "step-notify",
+ "name": "Notify SOC channel",
+ "type": "notify",
+ "params": {
+ "channel": "webhook",
+ "url": "{{SLACK_WEBHOOK_URL}}",
+ "message": "Phishing alert: {{title}} — sender IP enriched.",
+ },
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 2 ─ Ransomware Response
+ {
+ "id": "tpl-ransomware-response",
+ "name": "Ransomware Rapid Response",
+ "description": "Isolate affected host, block C2 IP, trigger AI investigation, notify leadership.",
+ "version": "1.0.0",
+ "tags": ["ransomware", "containment", "critical"],
+ "trigger": {"on": "alert", "severity": ["critical"]},
+ "steps": [
+ {
+ "id": "step-isolate",
+ "name": "Isolate host",
+ "type": "isolate_host",
+ "params": {},
+ },
+ {
+ "id": "step-block",
+ "name": "Block C2 IP",
+ "type": "block_ip",
+ "params": {},
+ },
+ {
+ "id": "step-investigate",
+ "name": "Trigger AI investigation",
+ "type": "investigate",
+ "params": {"dry_run": False},
+ },
+ {
+ "id": "step-notify-lead",
+ "name": "Notify leadership",
+ "type": "notify",
+ "params": {
+ "channel": "webhook",
+ "url": "{{SLACK_WEBHOOK_URL}}",
+ "message": "CRITICAL: Ransomware response initiated for {{host}}.",
+ },
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 3 ─ Credential Stuffing
+ {
+ "id": "tpl-cred-stuffing",
+ "name": "Credential Stuffing Detection",
+ "description": "Enrich source IPs, block top offenders, create a ticket.",
+ "version": "1.0.0",
+ "tags": ["credential", "brute-force", "identity"],
+ "trigger": {"on": "alert", "severity": ["high", "critical"]},
+ "steps": [
+ {
+ "id": "step-enrich",
+ "name": "Enrich source IP",
+ "type": "enrich",
+ "params": {"ioc_type": "ip"},
+ },
+ {
+ "id": "step-block",
+ "name": "Block IP",
+ "type": "block_ip",
+ "params": {},
+ },
+ {
+ "id": "step-ticket",
+ "name": "Create JIRA ticket",
+ "type": "create_ticket",
+ "params": {"project": "SOC", "type": "Incident"},
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 4 ─ Insider Threat Investigation
+ {
+ "id": "tpl-insider-threat",
+ "name": "Insider Threat Investigation",
+ "description": "Automatically investigate bulk-download alerts and escalate to HR/Legal.",
+ "version": "1.0.0",
+ "tags": ["insider", "data-loss", "dlp"],
+ "trigger": {"on": "alert", "severity": ["medium", "high"]},
+ "steps": [
+ {
+ "id": "step-investigate",
+ "name": "AI investigation",
+ "type": "investigate",
+ "params": {},
+ },
+ {
+ "id": "step-ticket",
+ "name": "Escalate to HR",
+ "type": "create_ticket",
+ "params": {"project": "HR", "type": "Investigation"},
+ },
+ {
+ "id": "step-notify",
+ "name": "Notify Legal",
+ "type": "notify",
+ "params": {
+ "channel": "webhook",
+ "message": "Insider threat case opened: {{title}}",
+ },
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 5 ─ Malware IOC Enrichment
+ {
+ "id": "tpl-malware-ioc-enrich",
+ "name": "Malware IOC Enrichment",
+ "description": "Enrich all IOCs attached to a case and update threat intel.",
+ "version": "1.0.0",
+ "tags": ["malware", "ioc", "enrichment"],
+ "trigger": {"on": "case", "severity": ["medium", "high", "critical"]},
+ "steps": [
+ {
+ "id": "step-enrich-ip",
+ "name": "Enrich IP IOC",
+ "type": "enrich",
+ "params": {"ioc_type": "ip"},
+ },
+ {
+ "id": "step-enrich-hash",
+ "name": "Enrich hash IOC",
+ "type": "enrich",
+ "params": {"ioc_type": "hash"},
+ },
+ {
+ "id": "step-enrich-domain",
+ "name": "Enrich domain IOC",
+ "type": "enrich",
+ "params": {"ioc_type": "domain"},
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 6 ─ Cloud Misconfiguration Alert
+ {
+ "id": "tpl-cloud-misconfig",
+ "name": "Cloud Misconfiguration Response",
+ "description": "Enrich exposed resource, notify cloud team, create remediation ticket.",
+ "version": "1.0.0",
+ "tags": ["cloud", "misconfiguration", "aws", "azure"],
+ "trigger": {"on": "alert", "severity": ["high", "critical"]},
+ "steps": [
+ {
+ "id": "step-enrich",
+ "name": "Enrich resource",
+ "type": "enrich",
+ "params": {},
+ },
+ {
+ "id": "step-notify-cloud",
+ "name": "Notify cloud-ops",
+ "type": "notify",
+ "params": {
+ "channel": "webhook",
+ "message": "Cloud misconfiguration: {{title}}",
+ },
+ },
+ {
+ "id": "step-ticket",
+ "name": "Create remediation ticket",
+ "type": "create_ticket",
+ "params": {"project": "CLOUD", "type": "Remediation"},
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 7 ─ Lateral Movement Detection
+ {
+ "id": "tpl-lateral-movement",
+ "name": "Lateral Movement Containment",
+ "description": "Block pivot IPs, isolate source host, trigger investigation.",
+ "version": "1.0.0",
+ "tags": ["lateral-movement", "containment"],
+ "trigger": {"on": "alert", "severity": ["high", "critical"]},
+ "steps": [
+ {
+ "id": "step-block",
+ "name": "Block lateral IP",
+ "type": "block_ip",
+ "params": {},
+ },
+ {
+ "id": "step-isolate",
+ "name": "Isolate source host",
+ "type": "isolate_host",
+ "params": {},
+ },
+ {
+ "id": "step-investigate",
+ "name": "AI investigation",
+ "type": "investigate",
+ "params": {},
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 8 ─ Data Exfiltration Alert
+ {
+ "id": "tpl-data-exfil",
+ "name": "Data Exfiltration Response",
+ "description": "Block exfil destination, isolate host, notify DLP team, create ticket.",
+ "version": "1.0.0",
+ "tags": ["exfiltration", "dlp", "containment"],
+ "trigger": {"on": "alert", "severity": ["high", "critical"]},
+ "steps": [
+ {
+ "id": "step-block",
+ "name": "Block destination IP",
+ "type": "block_ip",
+ "params": {},
+ },
+ {
+ "id": "step-isolate",
+ "name": "Isolate exfil host",
+ "type": "isolate_host",
+ "params": {},
+ },
+ {
+ "id": "step-notify",
+ "name": "Notify DLP team",
+ "type": "notify",
+ "params": {
+ "channel": "webhook",
+ "message": "Data exfiltration blocked: {{title}}",
+ },
+ },
+ {
+ "id": "step-ticket",
+ "name": "Create DLP ticket",
+ "type": "create_ticket",
+ "params": {"project": "DLP"},
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 9 ─ Zero-Day Exploit
+ {
+ "id": "tpl-zero-day",
+ "name": "Zero-Day Exploit Response",
+ "description": "Immediate isolation, war-room notification, AI investigation, executive escalation.",
+ "version": "1.0.0",
+ "tags": ["zero-day", "exploit", "critical"],
+ "trigger": {"on": "alert", "severity": ["critical"]},
+ "steps": [
+ {
+ "id": "step-isolate",
+ "name": "Isolate affected host",
+ "type": "isolate_host",
+ "params": {},
+ },
+ {
+ "id": "step-investigate",
+ "name": "AI investigation",
+ "type": "investigate",
+ "params": {},
+ },
+ {
+ "id": "step-notify-war-room",
+ "name": "Notify war-room",
+ "type": "notify",
+ "params": {
+ "channel": "webhook",
+ "message": "ZERO-DAY: War-room activated for {{title}}",
+ },
+ },
+ {
+ "id": "step-ticket",
+ "name": "P0 incident ticket",
+ "type": "create_ticket",
+ "params": {"project": "SEC", "type": "P0-Incident"},
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 10 ─ BEC (Business Email Compromise)
+ {
+ "id": "tpl-bec",
+ "name": "Business Email Compromise Response",
+ "description": "Freeze transfers, notify finance, open HR/Legal investigation.",
+ "version": "1.0.0",
+ "tags": ["bec", "fraud", "email"],
+ "trigger": {"on": "alert", "severity": ["high", "critical"]},
+ "steps": [
+ {
+ "id": "step-notify-finance",
+ "name": "Notify finance team",
+ "type": "notify",
+ "params": {
+ "channel": "webhook",
+ "message": "BEC alert: Potential wire fraud — {{title}}. Freeze pending transfers.",
+ },
+ },
+ {
+ "id": "step-investigate",
+ "name": "AI investigation",
+ "type": "investigate",
+ "params": {},
+ },
+ {
+ "id": "step-ticket",
+ "name": "Open fraud investigation ticket",
+ "type": "create_ticket",
+ "params": {"project": "FRAUD"},
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 11 ─ Supply Chain Alert
+ {
+ "id": "tpl-supply-chain",
+ "name": "Supply Chain Compromise Response",
+ "description": "Quarantine affected package/build, notify DevSecOps, trigger investigation.",
+ "version": "1.0.0",
+ "tags": ["supply-chain", "ci-cd", "sca"],
+ "trigger": {"on": "alert", "severity": ["high", "critical"]},
+ "steps": [
+ {
+ "id": "step-enrich",
+ "name": "Enrich malicious package IOC",
+ "type": "enrich",
+ "params": {"ioc_type": "hash"},
+ },
+ {
+ "id": "step-notify-devsec",
+ "name": "Notify DevSecOps",
+ "type": "notify",
+ "params": {
+ "channel": "webhook",
+ "message": "Supply chain alert: {{title}}. Quarantine build pipeline.",
+ },
+ },
+ {
+ "id": "step-investigate",
+ "name": "AI investigation",
+ "type": "investigate",
+ "params": {},
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+
+ # 12 ─ Auto-close Informational
+ {
+ "id": "tpl-auto-close-info",
+ "name": "Auto-close Informational Alerts",
+ "description": "Automatically close low-risk informational alerts after enrichment.",
+ "version": "1.0.0",
+ "tags": ["triage", "automation", "low-risk"],
+ "trigger": {"on": "alert", "severity": ["low"]},
+ "steps": [
+ {
+ "id": "step-enrich",
+ "name": "Enrich IP",
+ "type": "enrich",
+ "params": {"ioc_type": "ip"},
+ },
+ {
+ "id": "step-close",
+ "name": "Auto-close case",
+ "type": "close_case",
+ "params": {},
+ },
+ ],
+ "author": "AiSOC",
+ "enabled": True,
+ },
+]
diff --git a/services/agents/data/playbooks/phishing-triage.playbook.json b/services/agents/data/playbooks/phishing-triage.playbook.json
new file mode 100644
index 000000000..9fc9b992d
--- /dev/null
+++ b/services/agents/data/playbooks/phishing-triage.playbook.json
@@ -0,0 +1,63 @@
+{
+ "id": "phishing-triage-v1",
+ "name": "Phishing Triage",
+ "description": "Automated phishing alert triage: enrich sender/URL, notify SOC, and close low-confidence cases.",
+ "version": "1.0.0",
+ "tags": ["phishing", "email", "triage"],
+ "trigger": {
+ "on": "alert",
+ "severity": ["medium", "high", "critical"],
+ "tags": ["phishing"]
+ },
+ "author": "AiSOC",
+ "enabled": true,
+ "steps": [
+ {
+ "id": "enrich-sender",
+ "name": "Enrich sender IP/domain",
+ "type": "enrich",
+ "params": {
+ "indicator_field": "alert.source_ip"
+ },
+ "on_failure": "continue",
+ "timeout_seconds": 30
+ },
+ {
+ "id": "investigate",
+ "name": "Run AI Investigator",
+ "type": "investigate",
+ "params": {
+ "case_id_field": "alert.case_id"
+ },
+ "on_failure": "abort",
+ "timeout_seconds": 120
+ },
+ {
+ "id": "notify-soc",
+ "name": "Notify SOC channel",
+ "type": "notify",
+ "params": {
+ "channel": "slack",
+ "webhook_env": "SLACK_SOC_WEBHOOK",
+ "message_template": "Phishing alert {{alert.id}} investigated. Verdict: {{verdict}}"
+ },
+ "on_failure": "continue",
+ "timeout_seconds": 10
+ },
+ {
+ "id": "close-if-fp",
+ "name": "Close if false-positive",
+ "type": "close_case",
+ "condition": {
+ "field": "verdict",
+ "operator": "eq",
+ "value": "false_positive"
+ },
+ "params": {
+ "resolution": "false_positive"
+ },
+ "on_failure": "continue",
+ "timeout_seconds": 10
+ }
+ ]
+}
diff --git a/services/agents/data/playbooks/ransomware-response.playbook.json b/services/agents/data/playbooks/ransomware-response.playbook.json
new file mode 100644
index 000000000..c1b659630
--- /dev/null
+++ b/services/agents/data/playbooks/ransomware-response.playbook.json
@@ -0,0 +1,70 @@
+{
+ "id": "ransomware-response-v1",
+ "name": "Ransomware Response",
+ "description": "Immediate containment and investigation workflow for ransomware detections.",
+ "version": "1.0.0",
+ "tags": ["ransomware", "malware", "critical"],
+ "trigger": {
+ "on": "alert",
+ "severity": ["critical"],
+ "tags": ["ransomware"]
+ },
+ "author": "AiSOC",
+ "enabled": true,
+ "steps": [
+ {
+ "id": "isolate",
+ "name": "Isolate affected host",
+ "type": "isolate_host",
+ "params": {
+ "host_field": "alert.host"
+ },
+ "on_failure": "abort",
+ "timeout_seconds": 30
+ },
+ {
+ "id": "enrich-ioc",
+ "name": "Enrich malware IOCs",
+ "type": "enrich",
+ "params": {
+ "indicator_field": "alert.file_hash"
+ },
+ "on_failure": "continue",
+ "timeout_seconds": 30
+ },
+ {
+ "id": "investigate",
+ "name": "Run AI Forensic Investigation",
+ "type": "investigate",
+ "params": {
+ "case_id_field": "alert.case_id",
+ "focus": "forensics"
+ },
+ "on_failure": "continue",
+ "timeout_seconds": 180
+ },
+ {
+ "id": "create-ticket",
+ "name": "Create P1 incident ticket",
+ "type": "create_ticket",
+ "params": {
+ "priority": "P1",
+ "title_template": "RANSOMWARE DETECTED: {{alert.host}}"
+ },
+ "on_failure": "continue",
+ "timeout_seconds": 20
+ },
+ {
+ "id": "notify-oncall",
+ "name": "Page on-call team",
+ "type": "notify",
+ "params": {
+ "channel": "pagerduty",
+ "service_key_env": "PD_RANSOMWARE_KEY",
+ "message_template": "Ransomware detected on {{alert.host}}. Host isolated. Ticket created."
+ },
+ "on_failure": "continue",
+ "timeout_seconds": 10
+ }
+ ]
+}
diff --git a/services/api/app/api/v1/endpoints/playbooks.py b/services/api/app/api/v1/endpoints/playbooks.py
new file mode 100644
index 000000000..6992d43b0
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/playbooks.py
@@ -0,0 +1,81 @@
+"""
+Pillar-2 Playbook proxy endpoints.
+
+The api service acts as a gateway that forwards playbook CRUD and run
+requests to the agents service. This keeps the public API contract in
+one place while the engine lives in services/agents.
+"""
+from __future__ import annotations
+
+import os
+from typing import Any
+
+import httpx
+from fastapi import APIRouter, HTTPException, Request
+from fastapi.responses import JSONResponse
+
+_AGENTS_URL = os.getenv("AGENTS_SERVICE_URL", "http://agents:8000")
+
+router = APIRouter(prefix="/playbooks", tags=["playbooks"])
+
+
+async def _proxy(method: str, path: str, **kwargs) -> Any:
+ """Forward a request to the agents service and return the JSON body."""
+ url = f"{_AGENTS_URL}/api/v1/playbooks{path}"
+ try:
+ async with httpx.AsyncClient(timeout=60) as client:
+ r = await client.request(method, url, **kwargs)
+ if r.status_code >= 400:
+ raise HTTPException(status_code=r.status_code, detail=r.text)
+ if r.status_code == 204:
+ return None
+ return r.json()
+ except httpx.RequestError as exc:
+ raise HTTPException(status_code=503, detail=f"Agents service unavailable: {exc}") from exc
+
+
+# ---------------------------------------------------------------------------
+# CRUD
+# ---------------------------------------------------------------------------
+
[email protected]("", summary="List playbooks")
+async def list_playbooks(enabled_only: bool = False):
+ return await _proxy("GET", "", params={"enabled_only": enabled_only})
+
+
[email protected]("", summary="Create playbook", status_code=201)
+async def create_playbook(request: Request):
+ body = await request.json()
+ return await _proxy("POST", "", json=body)
+
+
[email protected]("/runs", summary="List playbook runs")
+async def list_runs(limit: int = 50):
+ return await _proxy("GET", "/runs", params={"limit": limit})
+
+
[email protected]("/runs/{run_id}", summary="Get a playbook run")
+async def get_run(run_id: str):
+ return await _proxy("GET", f"/runs/{run_id}")
+
+
[email protected]("/{playbook_id}", summary="Get a playbook")
+async def get_playbook(playbook_id: str):
+ return await _proxy("GET", f"/{playbook_id}")
+
+
[email protected]("/{playbook_id}", summary="Update a playbook")
+async def update_playbook(playbook_id: str, request: Request):
+ body = await request.json()
+ return await _proxy("PUT", f"/{playbook_id}", json=body)
+
+
[email protected]("/{playbook_id}", summary="Delete a playbook", status_code=204)
+async def delete_playbook(playbook_id: str):
+ await _proxy("DELETE", f"/{playbook_id}")
+
+
[email protected]("/{playbook_id}/run", summary="Execute a playbook", status_code=202)
+async def run_playbook(playbook_id: str, request: Request):
+ body = await request.json()
+ return await _proxy("POST", f"/{playbook_id}/run", json=body)
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index 83853c56b..884c16e70 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -1,7 +1,7 @@
"""API v1 router aggregating all endpoint modules."""
from fastapi import APIRouter
-from app.api.v1.endpoints import alerts, auth, cases, connectors, detection_rules, graph, tenants
+from app.api.v1.endpoints import alerts, auth, cases, connectors, detection_rules, graph, playbooks, tenants
api_router = APIRouter(prefix="/api/v1")
@@ -12,3 +12,4 @@ api_router.include_router(connectors.router)
api_router.include_router(tenants.router)
api_router.include_router(detection_rules.router)
api_router.include_router(graph.router)
+api_router.include_router(playbooks.router)