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: secure the customer's AI estate, and make the detection accounting honest (#676)
Beenu Aroraf1dc02d47028
diff --git a/.github/workflows/ai-sdk.yml b/.github/workflows/ai-sdk.ymlnew file mode 100644index 000000000..0577b0ee5--- /dev/null+++ b/.github/workflows/ai-sdk.yml@@ -0,0 +1,68 @@+name: AI SDK++# `packages/aisoc-ai-sdk` runs inside somebody else's agent process, which+# makes two of its properties load-bearing enough to gate on every change:+#+# 1. Prompt and response content does not leave that process by default. A+# SOC needs to detect abuse of the AI without becoming the largest single+# collection of user and retrieval text in the organisation.+# 2. Instrumentation never breaks the host application. A network failure, a+# bad token or an unreachable AiSOC degrades to a dropped span, never to+# an exception escaping into the caller's request path.+#+# Both are the kind of property that is easy to regress with a well-meant+# change, and expensive to discover in production.++on:+ pull_request:+ paths:+ - "packages/aisoc-ai-sdk/**"+ - ".github/workflows/ai-sdk.yml"+ push:+ branches: [main]+ paths:+ - "packages/aisoc-ai-sdk/**"+ - ".github/workflows/ai-sdk.yml"++permissions:+ contents: read++jobs:+ test:+ name: AI SDK — redaction + fail-soft gates+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"+ cache: pip+ - name: Install test deps+ # The SDK itself has zero dependencies on purpose — it must not drag a+ # transport library into a customer's dependency resolution — so only+ # the test tooling is installed here.+ run: pip install --quiet pytest "ruff>=0.4.4,<0.5"+ - name: Verify the package declares no runtime dependencies+ working-directory: packages/aisoc-ai-sdk+ run: |+ python - <<'PY'+ import re, pathlib+ text = pathlib.Path("pyproject.toml").read_text()+ match = re.search(r"^dependencies = \[(.*?)\]", text, re.S | re.M)+ assert match, "dependencies key missing from pyproject.toml"+ body = match.group(1).strip()+ assert not body, (+ "aisoc-ai-sdk declares runtime dependencies: "+ f"{body!r}. This package is imported into a customer's agent "+ "process, so it must stay dependency-free."+ )+ print("no runtime dependencies")+ PY+ - name: Run the test suite+ working-directory: packages/aisoc-ai-sdk+ run: PYTHONPATH=. python -m pytest tests/ -v --tb=short+ - name: Lint+ working-directory: packages/aisoc-ai-sdk+ run: |+ ruff check aisoc_ai tests+ ruff format --check aisoc_ai testsdiff --git a/.github/workflows/validate-detections.yml b/.github/workflows/validate-detections.ymlindex 8c6dd7380..4f3dc419d 100644--- a/.github/workflows/validate-detections.yml+++ b/.github/workflows/validate-detections.yml@@ -47,6 +47,16 @@ jobs:# worker can't silently drift from the committed corpus.run: python3 scripts/export_detection_ruleset.py --check+ # A rule can be loaded by the engine, pass fixture replay, count toward+ # the published executable total, and still never fire — because the+ # matcher does a flat `event.get(field)` and nothing ever computes the+ # field. Fixture replay cannot catch this: fixtures are synthesized from+ # the rule they test, so replaying them is a tautology. Ratcheted rather+ # than clean, because the corpus already contains such rules and blocking+ # every unrelated PR on them would only invite weakening the gate.+ - name: Verify detection rules match on fields that exist+ run: python3 scripts/check_detection_fields.py+- name: Count rules by severityif: always()run: |diff --git a/README.md b/README.mdindex aa3dba7b4..e6d8ce9b4 100644--- a/README.md+++ b/README.md@@ -174,7 +174,7 @@ A handful of headline capabilities — the rest are catalogued in [`apps/docs/do> **Maturity (v8.0.0 — Close the loop).** The end-to-end spine is wired and CI-gated: ingest → ClickHouse lake → live detection → fused alert → auto-triage → governed response. v8.0 connected capabilities the codebase already contained but never called. Response actions are now **verified against the vendor** rather than assumed from a 200 — an action that reports success while the effect is absent is reported as failed, because that gap is how a SOC comes to believe a host is contained when it is not. Autonomy is governed by **each tenant's own** L0–L4 policy instead of one deployment-wide environment variable. Repeat-alert suppression, shipped in v7.7, **could never fire** — the evidence fingerprint included the alert id, so no repeat ever matched; it now does. Analysts can **hunt the events AiSOC itself ingested** instead of needing an external SIEM. A verdict citing indicators the evidence never contained is demoted to human review rather than auto-closed. Autonomous *response* still defaults to copilot/dry-run: an autonomy policy governs every real execution. The live-agent LLM benchmark is preview (the deterministic-tier scoreboard is CI-gated per PR); substrate eval suites are GA. Every product claim is backed by a failing test — [claim-to-gate matrix](docs/audit/CLAIM_TO_GATE_MATRIX.md): 62 GATED / 11 PARTIAL / 0 NO GATE. Full per-claim status: [`docs/audit/REALITY_REPORT.md`](docs/audit/REALITY_REPORT.md).-- **83 click-and-connect data connectors** (EDR/XDR, SIEM, NDR, cloud, CNAPP, identity, SaaS, VCS, K8s audit, network) with schema-driven config, live `Test connection`, and vault-encrypted secrets — recently adding Qualys, GreyNoise, JumpCloud, Darktrace, and Imperva alongside IBM QRadar, Netskope, Zeek/Suricata NDR, and more. One query runs SIEM-agnostic **federated search** across Splunk SPL / Sentinel KQL / Elastic ES|QL / **QRadar AQL**. Walkthrough: [`apps/docs/docs/connectors/index.md`](apps/docs/docs/connectors/index.md).+- **84 click-and-connect data connectors** (EDR/XDR, SIEM, NDR, cloud, CNAPP, identity, SaaS, VCS, K8s audit, network) with schema-driven config, live `Test connection`, and vault-encrypted secrets — recently adding Qualys, GreyNoise, JumpCloud, Darktrace, and Imperva alongside IBM QRadar, Netskope, Zeek/Suricata NDR, and more. One query runs SIEM-agnostic **federated search** across Splunk SPL / Sentinel KQL / Elastic ES|QL / **QRadar AQL**. Walkthrough: [`apps/docs/docs/connectors/index.md`](apps/docs/docs/connectors/index.md).- **End-to-end SIEM spine** — a cold `docker compose up` ingests connector data → lands it in the ClickHouse event lake → the executable detection corpus (947 rules) fires on the live stream → a fused alert is created, all asserted by an extended integration gate. Fuse-time threat-intel + CISA-KEV enrichment now feeds the confidence score and exploit-in-wild boost, and **stateful/windowed detections** (brute-force, password-spray, port-scan) run alongside the corpus. [`apps/docs/docs/architecture.md`](apps/docs/docs/architecture.md).- **Autonomous triage + governed response** — every fused alert is auto-triaged by the agent (copilot/read-only by default) with a prompt-injection guard that demotes tampered evidence to manual review; a unified **confidence × blast-radius × reversibility** policy authorizes auto-execution only for reversible, low-blast actions at high confidence (everything else stays gated to a human), with real rollback + post-action verification. [`apps/docs/docs/concepts/automation-maturity.md`](apps/docs/docs/concepts/automation-maturity.md).- **Advanced Data Explorer** — one investigation surface (NL + SQL over the lake, plus pivots to identity/graph/intel), replacing the SIEM context-switch. `/explore`.diff --git a/RELEASES.md b/RELEASES.mdindex 7de112b8b..ca6dda67e 100644--- a/RELEASES.md+++ b/RELEASES.md@@ -82,7 +82,7 @@ The full inventory (every file, env-var, and test count) lives under `[7.6.0]` i- First community contribution merged: [#135](https://github.com/beenuar/AiSOC/pull/135) (UEBA env-var alignment, closes [#134](https://github.com/beenuar/AiSOC/issues/134)). Every UEBA variable accepts both unprefixed (`DATABASE_URL`) and legacy (`UEBA_DATABASE_URL`) forms; unprefixed wins.**Stage 2 / Stage 3 platform additions** — landed alongside the architectural foundation above.-- **Wazuh Indexer ingest connector** — polls `wazuh-alerts-*` over HTTPX, paginates time-windowed queries, retries on 5xx; collapses Wazuh severity into the AiSOC ladder. Docs: [`apps/docs/docs/connectors/wazuh.md`](apps/docs/docs/connectors/wazuh.md). The connector registry now declares **83 first-party connectors**.+- **Wazuh Indexer ingest connector** — polls `wazuh-alerts-*` over HTTPX, paginates time-windowed queries, retries on 5xx; collapses Wazuh severity into the AiSOC ladder. Docs: [`apps/docs/docs/connectors/wazuh.md`](apps/docs/docs/connectors/wazuh.md). The connector registry now declares **84 first-party connectors**.- **auditd `file_tail` connector + `aisoc.rules` profile** — replaces the host-agent dependency for Linux endpoint visibility; 4 new detections pivot on the bundled `aisoc_*` audit keys. Docs: [`apps/docs/docs/connectors/auditd.md`](apps/docs/docs/connectors/auditd.md).- **Live Actions dispatcher** — generic vendor/capability surface so plugins can register executors against the in-tree taxonomy (`isolate_host`, `disable_user`, `block_ip`, …) without forking. Unknown pairs return a typed `LiveActionResult(FAILED, "executor_not_found")` — never a 500. Docs: [`apps/docs/docs/concepts/live-actions.md`](apps/docs/docs/concepts/live-actions.md).- **Deterministic NL → ES|QL / KQL / SPL translator** — replaces the template fallback in `/nl_query` with an IR + grammar validator; 50-pair gold eval set scores 100% syntactic, 100% semantic. Air-gapped by default; optional `gpt-4o-mini` enhancement falls back deterministically.@@ -91,7 +91,7 @@ The full inventory (every file, env-var, and test count) lives under `[7.6.0]` i- **Azure Container Apps + Postgres Flexible Server Terraform skeleton** — file-for-file mirror of the GCP skeleton for teams standardised on Azure. Container Apps for the three customer-visible services, VNet-integrated Postgres 16 + Azure Cache for Redis on private endpoints, Key Vault for secrets, ACR for images, and per-service user-assigned managed identities so each app pulls its own image and reads only its own secrets. Docs: [`apps/docs/docs/deployment/azure.md`](apps/docs/docs/deployment/azure.md).- **Blameless case post-mortem endpoint** — `GET /api/v1/cases/{case_id}/postmortem?format=json|html` produces a deterministic retrospective covering contributing factors, detection timing/gaps, response phases, blast radius, and action items. Analyst handles are explicitly redacted from the narrative. Docs: [`apps/docs/docs/operations/case-reports.md`](apps/docs/docs/operations/case-reports.md).- **Per-rule cross-fire FP gate** — `services/agents/tests/test_detection_fp_rate.py` replays every rule's `match_when` against every *other* rule's positive fixture; current corpus 816 native rules, worst FPR 0.49% (5% ceiling). Wired into `scripts/run_evals.py` as `suites.detection_fp_rate`.-- **Operator-facing documentation refresh** — new pages for [notifications](apps/docs/docs/operations/notifications.md), [plugin lifecycle](apps/docs/docs/plugins/lifecycle.md), and [credentials / vault rotation](apps/docs/docs/operations/credentials.md); v2.2 architecture diagram and the corrected **83-connector count** (now including Wazuh Indexer + auditd `file_tail`) rolled through every surface.+- **Operator-facing documentation refresh** — new pages for [notifications](apps/docs/docs/operations/notifications.md), [plugin lifecycle](apps/docs/docs/plugins/lifecycle.md), and [credentials / vault rotation](apps/docs/docs/operations/credentials.md); v2.2 architecture diagram and the corrected **84-connector count** (now including Wazuh Indexer + auditd `file_tail`) rolled through every surface.The full inventory (with file paths, env-var changes, and test counts) lives in the `[7.4.0]` section of [`CHANGELOG.md`](CHANGELOG.md).diff --git a/ROADMAP.md b/ROADMAP.mdindex 0cc54b728..661b1ebe2 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -445,7 +445,7 @@ Terraform skeleton equivalent to the existing AWS module.off `auditd_key` for sudoers / SSH / kernel-module / systemdtampering. 444-test full connectors suite green (excluding`test_scheduler.py` which needs the `apscheduler` dev dep).-- [x] Connector registry now declares **83 first-party connectors**;+- [x] Connector registry now declares **84 first-party connectors**;`pnpm marketplace:sync` rebuilt `marketplace/index.json` +`apps/web/public/marketplace/index.json`.diff --git a/apps/docs/docs/architecture.md b/apps/docs/docs/architecture.mdindex 76f6db3c2..5ff8adb6d 100644--- a/apps/docs/docs/architecture.md+++ b/apps/docs/docs/architecture.md@@ -81,7 +81,7 @@ The v1.5 release ships from a review of G2, Gartner Peer Insights, and customer- **Automated compliance evidence** — `services/api/app/api/v1/endpoints/compliance.py` collects point-in-time evidence for SOC 2 / ISO 27001 / NIST CSF / PCI-DSS / HIPAA / DORA.- **AI-generated incident reports** — one-click "Export Report" on every case generates a PDF incident report from the Investigation Ledger.- **Air-gap deployment configuration** — `services/api/app/api/v1/endpoints/deployment.py` exposes air-gap mode toggles for tenants that disallow external feeds.-- **Connector catalog growth** — SentinelOne, Cortex XDR / XSIAM, Wiz, Snyk, Zscaler, Proofpoint, ServiceNow, Jira, 1Password, Duo Security, Carbon Black, Chronicle, Cisco Umbrella, CrowdStrike, Datadog Cloud SIEM, Elastic, Mimecast, Okta, Rapid7 InsightIDR, Salesforce, Microsoft Sentinel, Splunk, Sumo Logic, Tenable, Trellix Helix, Trend Vision One, and more. **The catalog is now 83 connectors** across EDR, SIEM, cloud, identity, SaaS, network, and email categories. See [Connectors](./connectors/).+- **Connector catalog growth** — SentinelOne, Cortex XDR / XSIAM, Wiz, Snyk, Zscaler, Proofpoint, ServiceNow, Jira, 1Password, Duo Security, Carbon Black, Chronicle, Cisco Umbrella, CrowdStrike, Datadog Cloud SIEM, Elastic, Mimecast, Okta, Rapid7 InsightIDR, Salesforce, Microsoft Sentinel, Splunk, Sumo Logic, Tenable, Trellix Helix, Trend Vision One, and more. **The catalog is now 84 connectors** across EDR, SIEM, cloud, identity, SaaS, network, and email categories. See [Connectors](./connectors/).## Connector polling and credential vaultdiff --git a/apps/docs/docs/connectors/api-coverage.md b/apps/docs/docs/connectors/api-coverage.mdindex 92ace7b8f..4560028a8 100644--- a/apps/docs/docs/connectors/api-coverage.md+++ b/apps/docs/docs/connectors/api-coverage.md@@ -27,7 +27,7 @@ This page is the canonical "what works where" reference. It is generated from thWhen a capability is not listed for a connector, the connector simply does not support it today — it is **not** a misconfiguration to surface. Adding a capability requires an explicit code change in that connector's `capabilities()` classmethod and matching method implementation.-## Coverage table — 83 connectors+## Coverage table — 84 connectorsThe matrix below is grouped by category. `OAuth (hosted)` indicates the connector is wired into the hosted OAuth marketplace flow (no client secret in tenant config). `Federated search` means the connector participates in the federated-query planner.diff --git a/apps/docs/docs/connectors/endpoint-decision-matrix.md b/apps/docs/docs/connectors/endpoint-decision-matrix.mdindex 1bb58e21d..b574e38f7 100644--- a/apps/docs/docs/connectors/endpoint-decision-matrix.md+++ b/apps/docs/docs/connectors/endpoint-decision-matrix.md@@ -189,7 +189,7 @@ can ingest today.## Related-- [Connectors overview](/docs/connectors) — the full 83-connector catalog.+- [Connectors overview](/docs/connectors) — the full 84-connector catalog.- [Hello, connector tutorial](/docs/connectors/hello-connector) — write yourown if none of these fit.- [Detection coverage](/docs/detections/coverage) — which endpoint detectionsdiff --git a/apps/docs/docs/connectors/index.md b/apps/docs/docs/connectors/index.mdindex 24092da6a..fae3f3466 100644--- a/apps/docs/docs/connectors/index.md+++ b/apps/docs/docs/connectors/index.md@@ -18,7 +18,7 @@ If your tool isn't in the catalog, see [Universal capture](/docs/connectors/univ## Catalog-The catalog ships with **83 connectors** out of the box, registered in [`services/connectors/app/connectors/__init__.py`](https://github.com/beenuar/AiSOC/blob/main/services/connectors/app/connectors/__init__.py). The list below is grouped by category; only a subset has dedicated walkthrough pages today (linked entries) — the rest follow the same schema-driven wizard described under [Adding a connector](#adding-a-connector).+The catalog ships with **84 connectors** out of the box, registered in [`services/connectors/app/connectors/__init__.py`](https://github.com/beenuar/AiSOC/blob/main/services/connectors/app/connectors/__init__.py). The list below is grouped by category; only a subset has dedicated walkthrough pages today (linked entries) — the rest follow the same schema-driven wizard described under [Adding a connector](#adding-a-connector).### Identitydiff --git a/apps/docs/docs/detections/coverage.md b/apps/docs/docs/detections/coverage.mdindex 0ad7c0c6d..38e6cee17 100644--- a/apps/docs/docs/detections/coverage.md+++ b/apps/docs/docs/detections/coverage.md@@ -11,22 +11,22 @@ sidebar_position: 2# Detection Coverage-Generated: `2026-07-13T06:40:32Z`+Generated: `2026-09-22T15:54:13Z`## Headline numbers-- **Curated v1.0 detections**: `417` (target: ≥ 300)-- **Total rules considered**: `1062` (quality floor: 0.55)+- **Curated v1.0 detections**: `418` (target: ≥ 300)+- **Total rules considered**: `1054` (quality floor: 0.55)- **Unique MITRE techniques covered**: `117`## Coverage by buyer family| Family | Count | Target | Covered ||---|---|---|---|-| **Ransomware** | 49 | ≥ 25 | ✅ |-| **Credential Access** | 85 | ≥ 25 | ✅ |+| **Ransomware** | 48 | ≥ 25 | ✅ |+| **Credential Access** | 86 | ≥ 25 | ✅ || **Lateral Movement** | 33 | ≥ 25 | ✅ |-| **Data Exfiltration** | 41 | ≥ 25 | ✅ |+| **Data Exfiltration** | 42 | ≥ 25 | ✅ || **Cloud** | 100 | ≥ 25 | ✅ || **Identity** | 100 | ≥ 25 | ✅ || **Supply Chain** | 36 | ≥ 25 | ✅ |@@ -36,24 +36,23 @@ Generated: `2026-07-13T06:40:32Z`### By tier-- `imported`: 42-- `native`: 375+- `imported`: 41+- `native`: 377### By severity-- `critical`: 99-- `high`: 208+- `critical`: 100+- `high`: 209- `low`: 6-- `medium`: 104+- `medium`: 103### By category-- `_migrated`: 1-- `application`: 33+- `application`: 36- `cloud`: 164- `data-exfil`: 20- `endpoint`: 117-- `identity`: 70+- `identity`: 69- `network`: 12## How to auditdiff --git a/apps/docs/docs/intro.md b/apps/docs/docs/intro.mdindex 36fb22875..58b18bf57 100644--- a/apps/docs/docs/intro.md+++ b/apps/docs/docs/intro.md@@ -47,7 +47,7 @@ for the full list.## Capabilities-- **Click-and-connect cloud connectors** — pick from a **83-connector** catalog spanning EDR, SIEM, cloud, IAM, SaaS, VCS, network, ITSM, vuln, and email-security sources (CrowdStrike, SentinelOne, Cortex XDR, Splunk, Microsoft Sentinel, AWS Security Hub, Defender XDR, GCP Cloud Audit, GCP SCC, M365, Entra ID, Azure Activity, Google Workspace, Okta, Duo Security, Cloudflare, Tailscale, GitHub, Wiz, Snyk, Zscaler, Proofpoint, ServiceNow, Jira, 1Password, **Wazuh Indexer**, **auditd `file_tail`**, and 25 more — see [Architecture](./architecture)). Fill a schema-driven form, click `Test connection` for a live auth round-trip, and `Save & enable`. Secrets are encrypted at the application layer with a Fernet [`CredentialVault`](./operations/credentials) before they hit Postgres; an in-process APScheduler polls each enabled instance and pushes normalized OCSF events through to the ingest spine. Setup walkthroughs: [docs/connectors](./connectors).+- **Click-and-connect cloud connectors** — pick from a **84-connector** catalog spanning EDR, SIEM, cloud, IAM, SaaS, VCS, network, ITSM, vuln, and email-security sources (CrowdStrike, SentinelOne, Cortex XDR, Splunk, Microsoft Sentinel, AWS Security Hub, Defender XDR, GCP Cloud Audit, GCP SCC, M365, Entra ID, Azure Activity, Google Workspace, Okta, Duo Security, Cloudflare, Tailscale, GitHub, Wiz, Snyk, Zscaler, Proofpoint, ServiceNow, Jira, 1Password, **Wazuh Indexer**, **auditd `file_tail`**, and 25 more — see [Architecture](./architecture)). Fill a schema-driven form, click `Test connection` for a live auth round-trip, and `Save & enable`. Secrets are encrypted at the application layer with a Fernet [`CredentialVault`](./operations/credentials) before they hit Postgres; an in-process APScheduler polls each enabled instance and pushes normalized OCSF events through to the ingest spine. Setup walkthroughs: [docs/connectors](./connectors).- **Investigation Ledger** — every prompt, response, evidence citation, and tool call the agent emits is logged step-by-step and replayable on each case.- **Public eval harness** — alert reduction (a real measurement on a fixed noisy stream) plus MITRE-tactic, investigation-completeness, and response-quality substrate self-consistency gates. Reproducible with one command and run in CI on every PR. The [eval harness page](./benchmark) documents what each suite does and does not measure.- **Ambient Copilot** — context-aware next-action suggestions on every alert, case, rule, and playbook page; one click runs the right agent tool with the right payload.diff --git a/apps/web/public/marketplace/curated.json b/apps/web/public/marketplace/curated.jsonindex 5aabe750a..f3368bd94 100644--- a/apps/web/public/marketplace/curated.json+++ b/apps/web/public/marketplace/curated.json@@ -1,39 +1,38 @@{"$schema": "https://aisoc.example.com/schemas/curated/v1.json","version": "1.0.0",- "generated": "2026-07-13T06:40:32Z",+ "generated": "2026-09-22T15:54:13Z","stats": {- "considered": 1062,- "eligible": 1058,- "selected": 417,+ "considered": 1054,+ "eligible": 1051,+ "selected": 418,"min_per_family": 25,"min_total": 300,"quality_floor": 0.55,"unique_techniques": 117,"selected_by_tier": {- "imported": 42,- "native": 375+ "imported": 41,+ "native": 377},"selected_by_severity": {- "critical": 99,- "high": 208,+ "critical": 100,+ "high": 209,"low": 6,- "medium": 104+ "medium": 103},"selected_by_category": {- "_migrated": 1,- "application": 33,+ "application": 36,"cloud": 164,"data-exfil": 20,"endpoint": 117,- "identity": 70,+ "identity": 69,"network": 12}},"families": {"ransomware": {"label": "Ransomware",- "count": 49,+ "count": 48,"rule_ids": ["det-application-050","det-application-078",@@ -82,21 +81,21 @@"sigmahq-sigma-37222991-11e9-4b6d-8bdf-60fbe48f753e","sigmahq-sigma-87df9ee1-5416-453a-8a08-e8d4a51e9ce1","sigmahq-sigma-add64136-62e5-48ea-807e-88638d02df1e",- "sigmahq-sigma-c947b146-0abc-4c87-9c64-b17e9d7274a2",- "splunk-security-content-0c320fea-6e87-4b99-a884-74d09d4b655d"+ "sigmahq-sigma-c947b146-0abc-4c87-9c64-b17e9d7274a2"],"min_target": 25,"covered": true},"credential-access": {"label": "Credential Access",- "count": 85,+ "count": 86,"rule_ids": ["det-application-004","det-application-008","det-application-020","det-application-040","det-application-075",+ "det-application-085","det-cloud-047","det-cloud-074","det-cloud-101",@@ -224,8 +223,9 @@},"exfil": {"label": "Data Exfiltration",- "count": 41,+ "count": 42,"rule_ids": [+ "det-application-081","det-cloud-058","det-cloud-062","det-cloud-063",@@ -391,6 +391,7 @@"det-application-072","det-application-073","det-application-075",+ "det-application-080","det-cloud-001","det-cloud-007","det-cloud-014",@@ -459,7 +460,6 @@"det-endpoint-301","det-endpoint-302","det-identity-001",- "det-identity-002","det-identity-009","det-identity-020","det-identity-021",@@ -683,7 +683,7 @@"T1484.002": 1,"T1485": 31,"T1486": 5,- "T1489": 3,+ "T1489": 2,"T1490": 11,"T1496": 6,"T1505.003": 2,@@ -698,7 +698,7 @@"T1548.003": 1,"T1550": 4,"T1550.003": 1,- "T1552": 2,+ "T1552": 3,"T1552.001": 5,"T1552.005": 1,"T1552.007": 1,@@ -720,7 +720,7 @@"T1562.008": 8,"T1565": 1,"T1565.001": 1,- "T1567": 10,+ "T1567": 11,"T1567.002": 2,"T1569": 1,"T1570": 6,@@ -1568,6 +1568,81 @@"log_source_product": "openai","has_executable_body": true},+ {+ "id": "det-application-080",+ "name": "AI Agent Took Action Beyond Its Granted Scope",+ "path": "detections/application/ai-agent-excessive-agency.yaml",+ "tier": "native",+ "source": "core",+ "category": "application",+ "severity": "high",+ "mitre_techniques": [+ "T1078"+ ],+ "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": "ai_guardrail",+ "has_executable_body": true+ },+ {+ "id": "det-application-081",+ "name": "Sensitive Data Left via an AI Agent",+ "path": "detections/application/ai-sensitive-data-egress.yaml",+ "tier": "native",+ "source": "core",+ "category": "application",+ "severity": "critical",+ "mitre_techniques": [+ "T1567"+ ],+ "mitre_tactics": [],+ "families": [+ "exfil"+ ],+ "quality_score": 1.0,+ "quality_notes": [+ "tier:native(+0.5)",+ "mitre_techniques:1(+0.2)",+ "severity:critical(+0.150)",+ "executable(+0.15)"+ ],+ "log_source_product": "ai_guardrail",+ "has_executable_body": true+ },+ {+ "id": "det-application-085",+ "name": "Credential Material Present in an AI Prompt",+ "path": "detections/application/ai-prompt-contained-credential.yaml",+ "tier": "native",+ "source": "core",+ "category": "application",+ "severity": "high",+ "mitre_techniques": [+ "T1552"+ ],+ "mitre_tactics": [],+ "families": [+ "credential-access"+ ],+ "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": "ai_runtime",+ "has_executable_body": true+ },{"id": "det-cloud-001","name": "AWS Root Account Console Login",@@ -8331,32 +8406,6 @@"log_source_product": "okta","has_executable_body": true},- {- "id": "det-identity-002",- "name": "Impossible Travel Between Two Authentications",- "path": "detections/identity/impossible-travel.yaml",- "tier": "native",- "source": "core",- "category": "identity",- "severity": "high",- "mitre_techniques": [- "T1078"- ],- "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-003","name": "Password Spray Across Many Users from Single IP",@@ -11482,31 +11531,6 @@],"log_source_product": "windows","has_executable_body": true- },- {- "id": "splunk-security-content-0c320fea-6e87-4b99-a884-74d09d4b655d",- "name": "Linux Auditd Osquery Service Stop",- "path": "detections/splunk-imports/_migrated/linux-auditd-osquery-service-stop.yaml",- "tier": "imported",- "source": "splunk-security-content",- "category": "_migrated",- "severity": "medium",- "mitre_techniques": [- "T1489"- ],- "mitre_tactics": [],- "families": [- "ransomware"- ],- "quality_score": 0.605,- "quality_notes": [- "tier:imported(+0.3)",- "mitre_techniques:1(+0.2)",- "severity:medium(+0.105)",- "no_executable_body(0)"- ],- "log_source_product": "splunk",- "has_executable_body": false}]}diff --git a/apps/web/public/marketplace/index.json b/apps/web/public/marketplace/index.jsonindex ab81c855e..c5834bd98 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-07-13T06:13:47Z",+ "generated": "2026-09-22T15:54:12Z","categories": [{"id": "playbooks",@@ -20,24 +20,24 @@}],"stats": {- "total": 7146,+ "total": 7155,"playbooks": 62,- "detections": 7008,- "plugins": 76,- "verified": 1025,+ "detections": 7016,+ "plugins": 77,+ "verified": 1034,"community": 1,"by_tier": {"beta": 7,"community": 1,"imported": 6113,- "stable": 1025+ "stable": 1034},"detections_by_tier": {"community": 1,"imported": 6113,- "stable": 894+ "stable": 902},- "quarantined": 5921+ "quarantined": 5937},"mitre_coverage": {"techniques": {@@ -130,7 +130,7 @@"T1056.001": 4,"T1056.002": 4,"T1057": 8,- "T1059": 121,+ "T1059": 122,"T1059.001": 243,"T1059.002": 11,"T1059.003": 41,@@ -162,7 +162,7 @@"T1072": 9,"T1074": 3,"T1074.001": 6,- "T1078": 128,+ "T1078": 132,"T1078.001": 10,"T1078.002": 14,"T1078.003": 11,@@ -360,7 +360,7 @@"T1547.012": 7,"T1547.014": 3,"T1547.015": 3,- "T1548": 34,+ "T1548": 35,"T1548.001": 12,"T1548.002": 76,"T1548.003": 39,@@ -370,7 +370,7 @@"T1550.002": 7,"T1550.003": 9,"T1550.004": 2,- "T1552": 21,+ "T1552": 22,"T1552.001": 38,"T1552.002": 7,"T1552.003": 3,@@ -437,7 +437,7 @@"T1566.001": 52,"T1566.002": 14,"T1566.003": 1,- "T1567": 33,+ "T1567": 34,"T1567.001": 2,"T1567.002": 23,"T1568": 1,@@ -536,7 +536,7 @@"T1690": 1},"unique_techniques": 493,- "total_with_mitre": 5792,+ "total_with_mitre": 5800,"by_tier": {"community": {"T1078.004": 1@@ -580,7 +580,7 @@"T1055.001": 1,"T1055.012": 1,"T1056.001": 1,- "T1059": 8,+ "T1059": 9,"T1059.001": 5,"T1059.002": 3,"T1059.004": 8,@@ -595,7 +595,7 @@"T1071.001": 10,"T1071.004": 6,"T1074.001": 1,- "T1078": 37,+ "T1078": 41,"T1078.001": 4,"T1078.002": 3,"T1078.003": 1,@@ -693,7 +693,7 @@"T1547.006": 6,"T1547.010": 1,"T1547.015": 2,- "T1548": 1,+ "T1548": 2,"T1548.001": 6,"T1548.002": 4,"T1548.003": 3,@@ -702,7 +702,7 @@"T1550.002": 2,"T1550.003": 1,"T1550.004": 1,- "T1552": 1,+ "T1552": 2,"T1552.001": 12,"T1552.004": 2,"T1552.005": 2,@@ -747,7 +747,7 @@"T1566.001": 2,"T1566.002": 2,"T1566.003": 1,- "T1567": 12,+ "T1567": 13,"T1567.002": 7,"T1568.001": 2,"T1568.002": 2,@@ -30429,6 +30429,190 @@"enabled": true,"path": "detections/application/llm-project-deleted.yaml"},+ {+ "id": "det-application-079",+ "type": "detection",+ "name": "Prompt Injection Detected in AI Agent Context",+ "description": "A guardrail flagged instruction-override content reaching an agent's context. Injection is the delivery mechanism for every other agent abuse, so this is the earliest point at which the chain is visible.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "application",+ "mitre_techniques": [+ "T1059"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-triage",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-prompt-injection-detected.yaml"+ },+ {+ "id": "det-application-080",+ "type": "detection",+ "name": "AI Agent Took Action Beyond Its Granted Scope",+ "description": "The agent invoked a capability outside the scope it was granted. Unlike a compromised user, an agent has no intent to infer \u2014 a call outside its declared tool set is either a policy gap or someone steering it.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "application",+ "mitre_techniques": [+ "T1078"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-privilege-escalation",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-agent-excessive-agency.yaml"+ },+ {+ "id": "det-application-081",+ "type": "detection",+ "name": "Sensitive Data Left via an AI Agent",+ "description": "A guardrail matched sensitive content on its way out through an agent. An agent with retrieval access is an exfiltration path that authenticates as itself and looks like normal application traffic.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "critical",+ "category": "application",+ "mitre_techniques": [+ "T1567"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-data-exfil",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-sensitive-data-egress.yaml"+ },+ {+ "id": "det-application-082",+ "type": "detection",+ "name": "AI Agent Used an Unapproved Model",+ "description": "An agent called a model outside the approved set. Often benign drift, but it is also how data leaves a reviewed provider for an unreviewed one.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "medium",+ "category": "application",+ "mitre_techniques": [+ "T1078"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-triage",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-unapproved-model.yaml"+ },+ {+ "id": "det-application-083",+ "type": "detection",+ "name": "AI Agent Escalated to a Higher-Privilege Tool",+ "description": "AiSOC v1 curated detection. Triggers on the application signal described by 'AI Agent Escalated to a Higher-Privilege Tool'. Watch the 1 documented false-positive case before tuning.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "application",+ "mitre_techniques": [+ "T1548"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-privilege-escalation",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-tool-escalation.yaml"+ },+ {+ "id": "det-application-084",+ "type": "detection",+ "name": "Undeclared AI Agent Observed",+ "description": "Telemetry arrived from an agent absent from the inventory. Shadow AI is the AI-estate equivalent of an unmanaged endpoint: it cannot be governed, and its access is unreviewed.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "medium",+ "category": "application",+ "mitre_techniques": [+ "T1078"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-triage",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-shadow-agent-discovered.yaml"+ },+ {+ "id": "det-application-085",+ "type": "detection",+ "name": "Credential Material Present in an AI Prompt",+ "description": "A secret shape appeared in a prompt. Detected without the prompt content ever being transmitted: the SDK reports which patterns matched while sending only a digest, so this fires even under the default hashed capture mode.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "application",+ "mitre_techniques": [+ "T1552"+ ],+ "log_source": "ai_runtime",+ "playbook": "tpl-account-compromise",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-prompt-contained-credential.yaml"+ },+ {+ "id": "det-application-086",+ "type": "detection",+ "name": "AI Agent Tool Call Denied",+ "description": "A tool call was refused. Low on its own, and deliberately so \u2014 the value is as a building block once the windowed engine can express 'N denials in M minutes', which is the shape that distinguishes a probing agent from a misconfigured one.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "low",+ "category": "application",+ "mitre_techniques": [+ "T1078"+ ],+ "log_source": "ai_runtime",+ "playbook": "tpl-triage",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-agent-tool-call-failed-repeatedly.yaml"+ },{"id": "det-cloud-001","type": "detection",@@ -158845,7 +159029,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1489"],@@ -158855,7 +159039,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/linux-auditd-osquery-service-stop.yaml",+ "path": "detections/splunk-imports/_quarantine/linux-auditd-osquery-service-stop.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "0c320fea-6e87-4b99-a884-74d09d4b655d",@@ -163991,7 +164176,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1068"],@@ -164001,7 +164186,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/detect-baron-samedit-cve-2021-3156-via-osquery.yaml",+ "path": "detections/splunk-imports/_quarantine/detect-baron-samedit-cve-2021-3156-via-osquery.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "1de31d5d-8fa6-4ee0-af89-17069134118a",@@ -164825,7 +165011,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1543.001"],@@ -164835,7 +165021,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/suspicious-plistbuddy-usage-via-osquery.yaml",+ "path": "detections/splunk-imports/_quarantine/suspicious-plistbuddy-usage-via-osquery.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "20ba6c32-c733-4a32-b64e-2688cf231399",@@ -167124,7 +167311,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": [],"log_source": null,"playbook": null,@@ -167132,7 +167319,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/processes-tapping-keyboard-events.yaml",+ "path": "detections/splunk-imports/_quarantine/processes-tapping-keyboard-events.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "2a371608-331d-4034-ae2c-21dda8f1d0ec",@@ -167780,7 +167968,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1553.001"],@@ -167790,7 +167978,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-gatekeeper-bypass.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-gatekeeper-bypass.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "2c9346f3-bbeb-48ce-8411-fc13d09d83a5",@@ -174408,7 +174597,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1136"],@@ -174418,7 +174607,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-account-created.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-account-created.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "491004ae-694f-453e-b1e0-fc1e65daeea1",@@ -175772,7 +175962,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1059.002"],@@ -175782,7 +175972,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-amos-stealer-virtual-machine-check-activity.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-amos-stealer-virtual-machine-check-activity.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "4e41ad21-9761-426d-8aa1-083712ff9f30",@@ -176535,7 +176726,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1564.001"],@@ -176545,7 +176736,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-hidden-files-and-directories.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-hidden-files-and-directories.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "51c43b7b-e406-45d2-9bad-5c67f07e6528",@@ -178362,7 +178554,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1059.004"],@@ -178372,7 +178564,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-lolbin.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-lolbin.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "58d270fb-5b39-418e-a855-4b8ac046805e",@@ -187489,7 +187682,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1030"],@@ -187499,7 +187692,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-data-chunking.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-data-chunking.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "7f1c8bed-9bd4-40b0-a1df-c262cbade0fc",@@ -195857,7 +196051,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1543"],@@ -195867,7 +196061,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-kextload-usage.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-kextload-usage.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "9d680775-84a6-4625-a8ea-8182b9427ce4",@@ -196591,7 +196786,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1037.002"],@@ -196601,7 +196796,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-loginhook-persistence.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-loginhook-persistence.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "a04832e7-9d1d-49b1-a684-e31bcd775c77",@@ -198420,7 +198616,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1135"],@@ -198430,7 +198626,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-network-share-discovery.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-network-share-discovery.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "a5f5fe52-8e50-4fb0-ad1b-780be6c0d857",@@ -198785,7 +198982,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1070"],@@ -198795,7 +198992,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-log-removal.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-log-removal.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "a7f2e891-3c4d-4a1b-9e6f-2b8d0c5a1f3e",@@ -205687,7 +205885,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1647"],@@ -205697,7 +205895,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-plutil.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-plutil.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "c11f2b57-92c1-4cd2-b46c-064eafb833ac",@@ -213404,7 +213603,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1555.001"],@@ -213414,7 +213613,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-keychains-dumped.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-keychains-dumped.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "dcb45a09-5e6f-441e-b2f8-cbbf923e36d9",@@ -224227,6 +224427,34 @@"tier": "stable","path": "plugins/abnormal_security/plugin.yaml"},+ {+ "id": "ai-gateway",+ "type": "plugin",+ "name": "AI Gateway / MCP Runtime",+ "description": "Pulls request logs from an LLM gateway or MCP server (LiteLLM, Portkey, Helicone, or an in-house proxy) so a SOC can see which agents call which tools and models, on whose behalf. One connector covers every application behind the gateway, which matters because the apps most in need of visibility are the ones nobody will retrofit an SDK into. For applications you do control, packages/aisoc-ai-sdk is the lower-friction push path. Routine activity is archived to the event lake and hunted; a guardrail violation becomes an alert.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "ai",+ "ai-spm",+ "llm",+ "agents",+ "mcp",+ "guardrails",+ "runtime",+ "connector"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/ai_gateway.py",+ "min_aisoc_version": "8.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/ai-gateway/plugin.yaml"+ },{"id": "aisoc-direct","type": "plugin",diff --git a/apps/web/src/data/connector-count.json b/apps/web/src/data/connector-count.jsonindex 00213c881..b3c1579ac 100644--- a/apps/web/src/data/connector-count.json+++ b/apps/web/src/data/connector-count.json@@ -1,6 +1,7 @@{- "count": 83,+ "count": 84,"categories": {+ "ai": 1,"cloud": 15,"edr": 10,"iam": 7,diff --git a/detections/application/ai-agent-excessive-agency.yaml b/detections/application/ai-agent-excessive-agency.yamlnew file mode 100644index 000000000..3b4e66870--- /dev/null+++ b/detections/application/ai-agent-excessive-agency.yaml@@ -0,0 +1,24 @@+id: det-application-080+name: AI Agent Took Action Beyond Its Granted Scope+description: The agent invoked a capability outside the scope it was granted. Unlike a compromised user,+ an agent has no intent to infer — a call outside its declared tool set is either a policy gap or someone+ steering it.+version: 1.0.0+severity: high+tags:+- mitre.attack.t1078+- tlp.white+category: application+log_source:+ product: ai_guardrail+ service: runtime+detection:+ condition: |+ finding_type == "excessive_agency"+false_positives:+- Agent scope widened without the policy being updated to match+playbook: tpl-privilege-escalation+enabled: true+author: AiSOC+created: '2026-05-03'+modified: '2026-05-03'diff --git a/detections/application/ai-agent-tool-call-failed-repeatedly.yaml b/detections/application/ai-agent-tool-call-failed-repeatedly.yamlnew file mode 100644index 000000000..0403b5640--- /dev/null+++ b/detections/application/ai-agent-tool-call-failed-repeatedly.yaml@@ -0,0 +1,24 @@+id: det-application-086+name: AI Agent Tool Call Denied+description: A tool call was refused. Low on its own, and deliberately so — the value is as a building+ block once the windowed engine can express 'N denials in M minutes', which is the shape that distinguishes+ a probing agent from a misconfigured one.+version: 1.0.0+severity: low+tags:+- mitre.attack.t1078+- tlp.white+category: application+log_source:+ product: ai_runtime+ service: runtime+detection:+ condition: |+ outcome == "denied"+false_positives:+- Agent retry logic against a transiently unavailable tool+playbook: tpl-triage+enabled: true+author: AiSOC+created: '2026-05-03'+modified: '2026-05-03'diff --git a/detections/application/ai-prompt-contained-credential.yaml b/detections/application/ai-prompt-contained-credential.yamlnew file mode 100644index 000000000..4278258a1--- /dev/null+++ b/detections/application/ai-prompt-contained-credential.yaml@@ -0,0 +1,25 @@+id: det-application-085+name: Credential Material Present in an AI Prompt+description: 'A secret shape appeared in a prompt. Detected without the prompt content ever being transmitted:+ the SDK reports which patterns matched while sending only a digest, so this fires even under the default+ hashed capture mode.'+version: 1.0.0+severity: high+tags:+- mitre.attack.t1552+- tlp.white+category: application+log_source:+ product: ai_runtime+ service: runtime+detection:+ condition: |+ prompt_secret_kinds HAS_ANY ["aws_access_key", "github_token", "openai_key", "private_key", "slack_token"]+false_positives:+- Security testing with a revoked key+- Developer pasting a sample key from documentation+playbook: tpl-account-compromise+enabled: true+author: AiSOC+created: '2026-05-03'+modified: '2026-05-03'diff --git a/detections/application/ai-prompt-injection-detected.yaml b/detections/application/ai-prompt-injection-detected.yamlnew file mode 100644index 000000000..d7057985a--- /dev/null+++ b/detections/application/ai-prompt-injection-detected.yaml@@ -0,0 +1,25 @@+id: det-application-079+name: Prompt Injection Detected in AI Agent Context+description: A guardrail flagged instruction-override content reaching an agent's context. Injection is+ the delivery mechanism for every other agent abuse, so this is the earliest point at which the chain+ is visible.+version: 1.0.0+severity: high+tags:+- mitre.attack.t1059+- tlp.white+category: application+log_source:+ product: ai_guardrail+ service: runtime+detection:+ condition: |+ finding_type == "prompt_injection"+false_positives:+- Security team testing the guardrail with a known payload+- A document legitimately quoting injection text, e.g. an awareness training page+playbook: tpl-triage+enabled: true+author: AiSOC+created: '2026-05-03'+modified: '2026-05-03'diff --git a/detections/application/ai-sensitive-data-egress.yaml b/detections/application/ai-sensitive-data-egress.yamlnew file mode 100644index 000000000..cf906838c--- /dev/null+++ b/detections/application/ai-sensitive-data-egress.yaml@@ -0,0 +1,23 @@+id: det-application-081+name: Sensitive Data Left via an AI Agent+description: A guardrail matched sensitive content on its way out through an agent. An agent with retrieval+ access is an exfiltration path that authenticates as itself and looks like normal application traffic.+version: 1.0.0+severity: critical+tags:+- mitre.attack.t1567+- tlp.white+category: application+log_source:+ product: ai_guardrail+ service: runtime+detection:+ condition: |+ finding_type == "sensitive_data_egress"+false_positives:+- Approved data-processing workflow not yet added to the allowlist+playbook: tpl-data-exfil+enabled: true+author: AiSOC+created: '2026-05-03'+modified: '2026-05-03'diff --git a/detections/application/ai-shadow-agent-discovered.yaml b/detections/application/ai-shadow-agent-discovered.yamlnew file mode 100644index 000000000..4057eba07--- /dev/null+++ b/detections/application/ai-shadow-agent-discovered.yaml@@ -0,0 +1,23 @@+id: det-application-084+name: Undeclared AI Agent Observed+description: 'Telemetry arrived from an agent absent from the inventory. Shadow AI is the AI-estate equivalent+ of an unmanaged endpoint: it cannot be governed, and its access is unreviewed.'+version: 1.0.0+severity: medium+tags:+- mitre.attack.t1078+- tlp.white+category: application+log_source:+ product: ai_guardrail+ service: runtime+detection:+ condition: |+ finding_type == "shadow_ai"+false_positives:+- A newly deployed agent that has not been registered yet+playbook: tpl-triage+enabled: true+author: AiSOC+created: '2026-05-03'+modified: '2026-05-03'diff --git a/detections/application/ai-tool-escalation.yaml b/detections/application/ai-tool-escalation.yamlnew file mode 100644index 000000000..ff92ca8a1--- /dev/null+++ b/detections/application/ai-tool-escalation.yaml@@ -0,0 +1,23 @@+id: det-application-083+name: AI Agent Escalated to a Higher-Privilege Tool+description: AiSOC v1 curated detection. Triggers on the application signal described by 'AI Agent Escalated+ to a Higher-Privilege Tool'. Watch the 1 documented false-positive case before tuning.+version: 1.0.0+severity: high+tags:+- mitre.attack.t1548+- tlp.white+category: application+log_source:+ product: ai_guardrail+ service: runtime+detection:+ condition: |+ finding_type == "tool_escalation"+false_positives:+- Break-glass tool use during an incident, with a ticket+playbook: tpl-privilege-escalation+enabled: true+author: AiSOC+created: '2026-05-03'+modified: '2026-05-03'diff --git a/detections/application/ai-unapproved-model.yaml b/detections/application/ai-unapproved-model.yamlnew file mode 100644index 000000000..35d09ff97--- /dev/null+++ b/detections/application/ai-unapproved-model.yaml@@ -0,0 +1,23 @@+id: det-application-082+name: AI Agent Used an Unapproved Model+description: An agent called a model outside the approved set. Often benign drift, but it is also how+ data leaves a reviewed provider for an unreviewed one.+version: 1.0.0+severity: medium+tags:+- mitre.attack.t1078+- tlp.white+category: application+log_source:+ product: ai_guardrail+ service: runtime+detection:+ condition: |+ finding_type == "unapproved_model"+false_positives:+- Model newly approved but the inventory not yet updated+playbook: tpl-triage+enabled: true+author: AiSOC+created: '2026-05-03'+modified: '2026-05-03'diff --git a/detections/fixtures/negative/ai-agent-excessive-agency.json b/detections/fixtures/negative/ai-agent-excessive-agency.jsonnew file mode 100644index 000000000..ecc72eb33--- /dev/null+++ b/detections/fixtures/negative/ai-agent-excessive-agency.json@@ -0,0 +1,3 @@+{+ "finding_type": "not-excessive_agency"+}diff --git a/detections/fixtures/negative/ai-agent-tool-call-failed-repeatedly.json b/detections/fixtures/negative/ai-agent-tool-call-failed-repeatedly.jsonnew file mode 100644index 000000000..a72ff555f--- /dev/null+++ b/detections/fixtures/negative/ai-agent-tool-call-failed-repeatedly.json@@ -0,0 +1,3 @@+{+ "outcome": "not-denied"+}diff --git a/detections/fixtures/negative/ai-prompt-contained-credential.json b/detections/fixtures/negative/ai-prompt-contained-credential.jsonnew file mode 100644index 000000000..9cd99c70d--- /dev/null+++ b/detections/fixtures/negative/ai-prompt-contained-credential.json@@ -0,0 +1,5 @@+{+ "prompt_secret_kinds": [+ "__benign__"+ ]+}diff --git a/detections/fixtures/negative/ai-prompt-injection-detected.json b/detections/fixtures/negative/ai-prompt-injection-detected.jsonnew file mode 100644index 000000000..292827e0d--- /dev/null+++ b/detections/fixtures/negative/ai-prompt-injection-detected.json@@ -0,0 +1,3 @@+{+ "finding_type": "not-prompt_injection"+}diff --git a/detections/fixtures/negative/ai-sensitive-data-egress.json b/detections/fixtures/negative/ai-sensitive-data-egress.jsonnew file mode 100644index 000000000..74b89b295--- /dev/null+++ b/detections/fixtures/negative/ai-sensitive-data-egress.json@@ -0,0 +1,3 @@+{+ "finding_type": "not-sensitive_data_egress"+}diff --git a/detections/fixtures/negative/ai-shadow-agent-discovered.json b/detections/fixtures/negative/ai-shadow-agent-discovered.jsonnew file mode 100644index 000000000..354026e42--- /dev/null+++ b/detections/fixtures/negative/ai-shadow-agent-discovered.json@@ -0,0 +1,3 @@+{+ "finding_type": "not-shadow_ai"+}diff --git a/detections/fixtures/negative/ai-tool-escalation.json b/detections/fixtures/negative/ai-tool-escalation.jsonnew file mode 100644index 000000000..e18e51dd4--- /dev/null+++ b/detections/fixtures/negative/ai-tool-escalation.json@@ -0,0 +1,3 @@+{+ "finding_type": "not-tool_escalation"+}diff --git a/detections/fixtures/negative/ai-unapproved-model.json b/detections/fixtures/negative/ai-unapproved-model.jsonnew file mode 100644index 000000000..e9d98b1c9--- /dev/null+++ b/detections/fixtures/negative/ai-unapproved-model.json@@ -0,0 +1,3 @@+{+ "finding_type": "not-unapproved_model"+}diff --git a/detections/fixtures/positive/ai-agent-excessive-agency.json b/detections/fixtures/positive/ai-agent-excessive-agency.jsonnew file mode 100644index 000000000..f86be29eb--- /dev/null+++ b/detections/fixtures/positive/ai-agent-excessive-agency.json@@ -0,0 +1,3 @@+{+ "finding_type": "excessive_agency"+}diff --git a/detections/fixtures/positive/ai-agent-tool-call-failed-repeatedly.json b/detections/fixtures/positive/ai-agent-tool-call-failed-repeatedly.jsonnew file mode 100644index 000000000..34d1c8898--- /dev/null+++ b/detections/fixtures/positive/ai-agent-tool-call-failed-repeatedly.json@@ -0,0 +1,3 @@+{+ "outcome": "denied"+}diff --git a/detections/fixtures/positive/ai-prompt-contained-credential.json b/detections/fixtures/positive/ai-prompt-contained-credential.jsonnew file mode 100644index 000000000..60d3e2902--- /dev/null+++ b/detections/fixtures/positive/ai-prompt-contained-credential.json@@ -0,0 +1,5 @@+{+ "prompt_secret_kinds": [+ "aws_access_key"+ ]+}diff --git a/detections/fixtures/positive/ai-prompt-injection-detected.json b/detections/fixtures/positive/ai-prompt-injection-detected.jsonnew file mode 100644index 000000000..e433c36a5--- /dev/null+++ b/detections/fixtures/positive/ai-prompt-injection-detected.json@@ -0,0 +1,3 @@+{+ "finding_type": "prompt_injection"+}diff --git a/detections/fixtures/positive/ai-sensitive-data-egress.json b/detections/fixtures/positive/ai-sensitive-data-egress.jsonnew file mode 100644index 000000000..e36304cb9--- /dev/null+++ b/detections/fixtures/positive/ai-sensitive-data-egress.json@@ -0,0 +1,3 @@+{+ "finding_type": "sensitive_data_egress"+}diff --git a/detections/fixtures/positive/ai-shadow-agent-discovered.json b/detections/fixtures/positive/ai-shadow-agent-discovered.jsonnew file mode 100644index 000000000..5f91a778b--- /dev/null+++ b/detections/fixtures/positive/ai-shadow-agent-discovered.json@@ -0,0 +1,3 @@+{+ "finding_type": "shadow_ai"+}diff --git a/detections/fixtures/positive/ai-tool-escalation.json b/detections/fixtures/positive/ai-tool-escalation.jsonnew file mode 100644index 000000000..8830c2efc--- /dev/null+++ b/detections/fixtures/positive/ai-tool-escalation.json@@ -0,0 +1,3 @@+{+ "finding_type": "tool_escalation"+}diff --git a/detections/fixtures/positive/ai-unapproved-model.json b/detections/fixtures/positive/ai-unapproved-model.jsonnew file mode 100644index 000000000..c4fe898d6--- /dev/null+++ b/detections/fixtures/positive/ai-unapproved-model.json@@ -0,0 +1,3 @@+{+ "finding_type": "unapproved_model"+}diff --git a/detections/splunk-imports/_quarantine/README.md b/detections/splunk-imports/_quarantine/README.mdindex 8fec1fe0b..351618638 100644--- a/detections/splunk-imports/_quarantine/README.md+++ b/detections/splunk-imports/_quarantine/README.md@@ -1,6 +1,6 @@# Splunk-imports — quarantined rules-This directory holds **1,989 raw Splunk Enterprise Security rules** imported from public detection content. They ship **disabled** (`enabled: false`) and the AiSOC engine intentionally skips them at runtime — see [`detections/README.md`](../../README.md#tier-3-quarantined) for the tier definition.+This directory holds **2,005 raw Splunk Enterprise Security rules** imported from public detection content. They ship **disabled** (`enabled: false`) and the AiSOC engine intentionally skips them at runtime — see [`detections/README.md`](../../README.md#tier-3-quarantined) for the tier definition.**Why they're in the repo at all.** Detection content is the most valuable artefact a SOC owns, so we'd rather check the upstream lineage in (with attribution and `quarantine_reason`) than silently drop it. Translating these rules into native AiSOC detections is a long-running community workstream tracked through this index.@@ -10,11 +10,11 @@ This directory holds **1,989 raw Splunk Enterprise Security rules** imported fro| Category | Quarantined rules | Production | Experimental | Translation tracking issue || --- | ---: | ---: | ---: | --- |-| `endpoint` | 1,374 | 1,346 | 28 | **TBD** — umbrella issue not yet filed |+| `endpoint` | 1,390 | 1,359 | 31 | **TBD** — umbrella issue not yet filed || `cloud` | 318 | 285 | 33 | **TBD** — umbrella issue not yet filed || `application` | 198 | 164 | 34 | **TBD** — umbrella issue not yet filed || `network` | 99 | 77 | 22 | **TBD** — umbrella issue not yet filed |-| **Total** | **1,989** | **1,872** | **117** | |+| **Total** | **2,005** | **1,885** | **120** | |Categories come from the `tags.categories` field on each rule. `production` vs `experimental` reflects the upstream `notes.splunk_status` carried over from Splunk ES.@@ -22,7 +22,9 @@ Categories come from the `tags.categories` field on each rule. `production` vs `1. **Pick a rule** from one of the per-category sections below. Lower-severity, single-technique rules are the gentlest place to start.2. **Read the existing YAML** in this directory. The Splunk SPL is captured under `detection.splunk_spl`; the metadata (MITRE, severity, category, references) is already populated.-3. **Re-author the detection** under the right native bucket (`detections/<category>/`) using the AiSOC schema documented in [`apps/docs/docs/detections/`](../../../apps/docs/docs/detections/). Map the SPL search to the AiSOC OCSF stream — usually a `logsource` + `detection.condition` block. Carry the original `provenance.upstream_path` over so attribution is preserved.+3. **Re-author the detection as a Python spec**, not as YAML. This step used to say to write a `detection.condition` block under `detections/<category>/`, which does not work: everything under `detections/` is a *generated projection* of the spec modules and the engine never reads it. A rule authored that way passes CI, is counted by the truth table, and is never loaded — 44 rules in the native tier are in exactly that state. Add an `S(...)` entry to the matching `scripts/detection_specs_part3_<category>.py` with a flat `match_when`, then run `python3 scripts/generate_detections.py` followed by `python3 scripts/export_detection_ruleset.py`. Carry the original `provenance.upstream_path` over so attribution is preserved.+ - **Check every field name against the emitting connector's `normalize()` output.** `scripts/check_detection_fields.py` gates computed fields — counters, window sizes, allowlist booleans — which cannot fire at all, because nothing in the pipeline computes them. They need a windowed-engine rule or a fusion-time enrichment instead.+ - **SPL with `| stats` or `| tstats` is not translatable to `match_when`.** Aggregation over a window belongs in `services/fusion/app/services/windowed_detection.py`, which today has three hardcoded rules and no loader. Skip those until it has one.4. **Add fixtures** under `detections/fixtures/positive/<rule-id>.json` and `detections/fixtures/negative/<rule-id>.json`. [`scripts/validate_detections.py --strict-fixtures`](../../../scripts/validate_detections.py) will refuse to merge a rule that ships without both.5. **Delete the quarantined file** as part of the same PR — the rule now lives in the native tier and the quarantine entry is no longer the source of truth.6. **Re-run** `python3 scripts/build_quarantine_index.py` to regenerate this index, then commit the README delta with your translation. CI verifies the index is in sync (`--check` mode).@@ -40,14 +42,14 @@ Two soft conventions sit on top of the gate (not machine-enforced today, but exp## Inventory by category-### `endpoint` (1,374 rules)+### `endpoint` (1,390 rules)**Translation tracking issue:** **TBD** — umbrella issue not yet filed**Top MITRE techniques represented:**- [`T1562`](https://attack.mitre.org/techniques/T1562/) — 114 rules-- [`T1059`](https://attack.mitre.org/techniques/T1059/) — 103 rules+- [`T1059`](https://attack.mitre.org/techniques/T1059/) — 105 rules- [`T1218`](https://attack.mitre.org/techniques/T1218/) — 88 rules- [`T1112`](https://attack.mitre.org/techniques/T1112/) — 78 rules- [`T1548`](https://attack.mitre.org/techniques/T1548/) — 63 rules@@ -56,9 +58,9 @@ Two soft conventions sit on top of the gate (not machine-enforced today, but exp- [`T1087`](https://attack.mitre.org/techniques/T1087/) — 38 rules- [`T1003`](https://attack.mitre.org/techniques/T1003/) — 34 rules- [`T1055`](https://attack.mitre.org/techniques/T1055/) — 34 rules-- _… and 117 more techniques._+- _… and 118 more techniques._-<details><summary>Full rule list (1,374 rules)</summary>+<details><summary>Full rule list (1,390 rules)</summary>| Rule | File | Splunk status | Severity | MITRE || --- | --- | --- | --- | --- |@@ -151,6 +153,7 @@ Two soft conventions sit on top of the gate (not machine-enforced today, but exp| Detect AzureHound File Modifications | [`detect-azurehound-file-modifications.yaml`](./detect-azurehound-file-modifications.yaml) | `production` | `medium` | `T1069`, `T1087`, `T1482` || Detect Baron Samedit CVE-2021-3156 | [`detect-baron-samedit-cve-2021-3156.yaml`](./detect-baron-samedit-cve-2021-3156.yaml) | `experimental` | `medium` | `T1068` || Detect Baron Samedit CVE-2021-3156 Segfault | [`detect-baron-samedit-cve-2021-3156-segfault.yaml`](./detect-baron-samedit-cve-2021-3156-segfault.yaml) | `experimental` | `medium` | `T1068` |+| Detect Baron Samedit CVE-2021-3156 via OSQuery | [`detect-baron-samedit-cve-2021-3156-via-osquery.yaml`](./detect-baron-samedit-cve-2021-3156-via-osquery.yaml) | `experimental` | `medium` | `T1068` || Detect Certify Command Line Arguments | [`detect-certify-command-line-arguments.yaml`](./detect-certify-command-line-arguments.yaml) | `production` | `medium` | `T1649`, `T1105` || Detect Certify With PowerShell Script Block Logging | [`detect-certify-with-powershell-script-block-logging.yaml`](./detect-certify-with-powershell-script-block-logging.yaml) | `production` | `medium` | `T1059`, `T1649` || Detect Certipy File Modifications | [`detect-certipy-file-modifications.yaml`](./detect-certipy-file-modifications.yaml) | `production` | `medium` | `T1649`, `T1560` |@@ -380,6 +383,7 @@ Two soft conventions sit on top of the gate (not machine-enforced today, but exp| Linux Auditd Kernel Module Enumeration | [`linux-auditd-kernel-module-enumeration.yaml`](./linux-auditd-kernel-module-enumeration.yaml) | `production` | `medium` | `T1082`, `T1014` || Linux Auditd Kernel Module Using Rmmod Utility | [`linux-auditd-kernel-module-using-rmmod-utility.yaml`](./linux-auditd-kernel-module-using-rmmod-utility.yaml) | `production` | `medium` | `T1547` || Linux Auditd Nopasswd Entry In Sudoers File | [`linux-auditd-nopasswd-entry-in-sudoers-file.yaml`](./linux-auditd-nopasswd-entry-in-sudoers-file.yaml) | `production` | `medium` | `T1548` |+| Linux Auditd Osquery Service Stop | [`linux-auditd-osquery-service-stop.yaml`](./linux-auditd-osquery-service-stop.yaml) | `production` | `medium` | `T1489` || Linux Auditd Possible Access Or Modification Of Sshd Config File | [`linux-auditd-possible-access-or-modification-of-sshd-config-file.yaml`](./linux-auditd-possible-access-or-modification-of-sshd-config-file.yaml) | `production` | `medium` | `T1098` || Linux Auditd Possible Access To Credential Files | [`linux-auditd-possible-access-to-credential-files.yaml`](./linux-auditd-possible-access-to-credential-files.yaml) | `production` | `medium` | `T1003` || Linux Auditd Possible Access To Sudoers File | [`linux-auditd-possible-access-to-sudoers-file.yaml`](./linux-auditd-possible-access-to-sudoers-file.yaml) | `production` | `medium` | `T1548` |@@ -501,7 +505,19 @@ Two soft conventions sit on top of the gate (not machine-enforced today, but exp| Logon Script Event Trigger Execution | [`logon-script-event-trigger-execution.yaml`](./logon-script-event-trigger-execution.yaml) | `production` | `medium` | `T1037` || LOLBAS With Network Traffic | [`lolbas-with-network-traffic.yaml`](./lolbas-with-network-traffic.yaml) | `production` | `medium` | `T1105`, `T1567`, `T1218` || MacOS - Re-opened Applications | [`macos-re-opened-applications.yaml`](./macos-re-opened-applications.yaml) | `experimental` | `medium` | _n/a_ |+| MacOS Account Created | [`macos-account-created.yaml`](./macos-account-created.yaml) | `production` | `medium` | `T1136` |+| MacOS AMOS Stealer - Virtual Machine Check Activity | [`macos-amos-stealer-virtual-machine-check-activity.yaml`](./macos-amos-stealer-virtual-machine-check-activity.yaml) | `production` | `medium` | `T1059` |+| MacOS Data Chunking | [`macos-data-chunking.yaml`](./macos-data-chunking.yaml) | `production` | `medium` | `T1030` |+| MacOS Gatekeeper Bypass | [`macos-gatekeeper-bypass.yaml`](./macos-gatekeeper-bypass.yaml) | `production` | `medium` | `T1553` |+| MacOS Hidden Files and Directories | [`macos-hidden-files-and-directories.yaml`](./macos-hidden-files-and-directories.yaml) | `production` | `medium` | `T1564` |+| MacOS Kextload Usage | [`macos-kextload-usage.yaml`](./macos-kextload-usage.yaml) | `production` | `medium` | `T1543` |+| MacOS Keychains Dumped | [`macos-keychains-dumped.yaml`](./macos-keychains-dumped.yaml) | `production` | `medium` | `T1555` || MacOS List Firewall Rules | [`macos-list-firewall-rules.yaml`](./macos-list-firewall-rules.yaml) | `production` | `medium` | `T1016` |+| MacOS Log Removal | [`macos-log-removal.yaml`](./macos-log-removal.yaml) | `production` | `medium` | `T1070` |+| MacOS LoginHook Persistence | [`macos-loginhook-persistence.yaml`](./macos-loginhook-persistence.yaml) | `production` | `medium` | `T1037` |+| MacOS LOLbin | [`macos-lolbin.yaml`](./macos-lolbin.yaml) | `production` | `medium` | `T1059` |+| MacOS Network Share Discovery | [`macos-network-share-discovery.yaml`](./macos-network-share-discovery.yaml) | `production` | `medium` | `T1135` |+| MacOS plutil | [`macos-plutil.yaml`](./macos-plutil.yaml) | `production` | `medium` | `T1647` || Mailsniper Invoke functions | [`mailsniper-invoke-functions.yaml`](./mailsniper-invoke-functions.yaml) | `production` | `medium` | `T1114` || Malicious InProcServer32 Modification | [`malicious-inprocserver32-modification.yaml`](./malicious-inprocserver32-modification.yaml) | `production` | `medium` | `T1218`, `T1112` || Malicious Powershell Executed As A Service | [`malicious-powershell-executed-as-a-service.yaml`](./malicious-powershell-executed-as-a-service.yaml) | `production` | `medium` | `T1569` |@@ -586,6 +602,7 @@ Two soft conventions sit on top of the gate (not machine-enforced today, but exp| Process Execution via WMI | [`process-execution-via-wmi.yaml`](./process-execution-via-wmi.yaml) | `production` | `medium` | `T1047` || Process Kill Base On File Path | [`process-kill-base-on-file-path.yaml`](./process-kill-base-on-file-path.yaml) | `production` | `medium` | `T1562` || Process Writing DynamicWrapperX | [`process-writing-dynamicwrapperx.yaml`](./process-writing-dynamicwrapperx.yaml) | `production` | `medium` | `T1059`, `T1559` |+| Processes Tapping Keyboard Events | [`processes-tapping-keyboard-events.yaml`](./processes-tapping-keyboard-events.yaml) | `experimental` | `medium` | _n/a_ || Randomly Generated Scheduled Task Name | [`randomly-generated-scheduled-task-name.yaml`](./randomly-generated-scheduled-task-name.yaml) | `experimental` | `medium` | `T1053` || Randomly Generated Windows Service Name | [`randomly-generated-windows-service-name.yaml`](./randomly-generated-windows-service-name.yaml) | `experimental` | `medium` | `T1543` || Ransomware Notes bulk creation | [`ransomware-notes-bulk-creation.yaml`](./ransomware-notes-bulk-creation.yaml) | `production` | `medium` | `T1486` |@@ -688,6 +705,7 @@ Two soft conventions sit on top of the gate (not machine-enforced today, but exp| Suspicious mshta child process | [`suspicious-mshta-child-process.yaml`](./suspicious-mshta-child-process.yaml) | `production` | `medium` | `T1218` || Suspicious mshta spawn | [`suspicious-mshta-spawn.yaml`](./suspicious-mshta-spawn.yaml) | `production` | `medium` | `T1218` || Suspicious PlistBuddy Usage | [`suspicious-plistbuddy-usage.yaml`](./suspicious-plistbuddy-usage.yaml) | `experimental` | `medium` | `T1543` |+| Suspicious PlistBuddy Usage via OSquery | [`suspicious-plistbuddy-usage-via-osquery.yaml`](./suspicious-plistbuddy-usage-via-osquery.yaml) | `experimental` | `medium` | `T1543` || Suspicious Process Executed From Container File | [`suspicious-process-executed-from-container-file.yaml`](./suspicious-process-executed-from-container-file.yaml) | `production` | `medium` | `T1204`, `T1036` || Suspicious Reg exe Process | [`suspicious-reg-exe-process.yaml`](./suspicious-reg-exe-process.yaml) | `production` | `medium` | `T1112` || Suspicious Regsvr32 Register Suspicious Path | [`suspicious-regsvr32-register-suspicious-path.yaml`](./suspicious-regsvr32-register-suspicious-path.yaml) | `production` | `medium` | `T1218` |@@ -2131,4 +2149,4 @@ Two soft conventions sit on top of the gate (not machine-enforced today, but exp----_Generated by `scripts/build_quarantine_index.py`. Source: 1,989 YAML rules in this directory._+_Generated by `scripts/build_quarantine_index.py`. Source: 2,005 YAML rules in this directory._diff --git a/detections/splunk-imports/_migrated/detect-baron-samedit-cve-2021-3156-via-osquery.yaml b/detections/splunk-imports/_quarantine/detect-baron-samedit-cve-2021-3156-via-osquery.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/detect-baron-samedit-cve-2021-3156-via-osquery.yamlrename to detections/splunk-imports/_quarantine/detect-baron-samedit-cve-2021-3156-via-osquery.yamldiff --git a/detections/splunk-imports/_migrated/linux-auditd-osquery-service-stop.yaml b/detections/splunk-imports/_quarantine/linux-auditd-osquery-service-stop.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/linux-auditd-osquery-service-stop.yamlrename to detections/splunk-imports/_quarantine/linux-auditd-osquery-service-stop.yamldiff --git a/detections/splunk-imports/_migrated/macos-account-created.yaml b/detections/splunk-imports/_quarantine/macos-account-created.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-account-created.yamlrename to detections/splunk-imports/_quarantine/macos-account-created.yamldiff --git a/detections/splunk-imports/_migrated/macos-amos-stealer-virtual-machine-check-activity.yaml b/detections/splunk-imports/_quarantine/macos-amos-stealer-virtual-machine-check-activity.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-amos-stealer-virtual-machine-check-activity.yamlrename to detections/splunk-imports/_quarantine/macos-amos-stealer-virtual-machine-check-activity.yamldiff --git a/detections/splunk-imports/_migrated/macos-data-chunking.yaml b/detections/splunk-imports/_quarantine/macos-data-chunking.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-data-chunking.yamlrename to detections/splunk-imports/_quarantine/macos-data-chunking.yamldiff --git a/detections/splunk-imports/_migrated/macos-gatekeeper-bypass.yaml b/detections/splunk-imports/_quarantine/macos-gatekeeper-bypass.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-gatekeeper-bypass.yamlrename to detections/splunk-imports/_quarantine/macos-gatekeeper-bypass.yamldiff --git a/detections/splunk-imports/_migrated/macos-hidden-files-and-directories.yaml b/detections/splunk-imports/_quarantine/macos-hidden-files-and-directories.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-hidden-files-and-directories.yamlrename to detections/splunk-imports/_quarantine/macos-hidden-files-and-directories.yamldiff --git a/detections/splunk-imports/_migrated/macos-kextload-usage.yaml b/detections/splunk-imports/_quarantine/macos-kextload-usage.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-kextload-usage.yamlrename to detections/splunk-imports/_quarantine/macos-kextload-usage.yamldiff --git a/detections/splunk-imports/_migrated/macos-keychains-dumped.yaml b/detections/splunk-imports/_quarantine/macos-keychains-dumped.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-keychains-dumped.yamlrename to detections/splunk-imports/_quarantine/macos-keychains-dumped.yamldiff --git a/detections/splunk-imports/_migrated/macos-log-removal.yaml b/detections/splunk-imports/_quarantine/macos-log-removal.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-log-removal.yamlrename to detections/splunk-imports/_quarantine/macos-log-removal.yamldiff --git a/detections/splunk-imports/_migrated/macos-loginhook-persistence.yaml b/detections/splunk-imports/_quarantine/macos-loginhook-persistence.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-loginhook-persistence.yamlrename to detections/splunk-imports/_quarantine/macos-loginhook-persistence.yamldiff --git a/detections/splunk-imports/_migrated/macos-lolbin.yaml b/detections/splunk-imports/_quarantine/macos-lolbin.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-lolbin.yamlrename to detections/splunk-imports/_quarantine/macos-lolbin.yamldiff --git a/detections/splunk-imports/_migrated/macos-network-share-discovery.yaml b/detections/splunk-imports/_quarantine/macos-network-share-discovery.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-network-share-discovery.yamlrename to detections/splunk-imports/_quarantine/macos-network-share-discovery.yamldiff --git a/detections/splunk-imports/_migrated/macos-plutil.yaml b/detections/splunk-imports/_quarantine/macos-plutil.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/macos-plutil.yamlrename to detections/splunk-imports/_quarantine/macos-plutil.yamldiff --git a/detections/splunk-imports/_migrated/processes-tapping-keyboard-events.yaml b/detections/splunk-imports/_quarantine/processes-tapping-keyboard-events.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/processes-tapping-keyboard-events.yamlrename to detections/splunk-imports/_quarantine/processes-tapping-keyboard-events.yamldiff --git a/detections/splunk-imports/_migrated/suspicious-plistbuddy-usage-via-osquery.yaml b/detections/splunk-imports/_quarantine/suspicious-plistbuddy-usage-via-osquery.yamlsimilarity index 100%rename from detections/splunk-imports/_migrated/suspicious-plistbuddy-usage-via-osquery.yamlrename to detections/splunk-imports/_quarantine/suspicious-plistbuddy-usage-via-osquery.yamldiff --git a/docs/architecture/SYSTEM_DESIGN.md b/docs/architecture/SYSTEM_DESIGN.mdindex dc99f258a..f486ac747 100644--- a/docs/architecture/SYSTEM_DESIGN.md+++ b/docs/architecture/SYSTEM_DESIGN.md@@ -20,7 +20,7 @@ This document describes the end-to-end architecture of the AiSOC platform after┌─────────────────┐ ┌──────────────────────┐│ services/api │ │ services/connectors ││ inbox tokens + │ │ APScheduler poll │- │ HMAC webhooks │ │ 83 connector classes│+ │ HMAC webhooks │ │ 84 connector classes││ CEF / HEC / DNS│ │ push_case + status │└────────┬────────┘ └──────────┬───────────┘│ │@@ -91,7 +91,7 @@ This document describes the end-to-end architecture of the AiSOC platform after| `services/enrichment` | Go 1.21 | Per-IOC TTL-cached enrichment lookups | n/a || `services/fusion` | Python 3.11 | Simhash dedup → correlation → ML scoring → publish fused alerts | Background ML retrain on feedback || `services/api` | Python 3.11 | REST + WS, RBAC, case mgmt, rule engine, graph queries, ITSM webhook inbox, case fan-out | Schema migrations on boot |-| `services/connectors` | Python 3.11 | 83 connector classes, APScheduler poll, `push_case` / `push_status_change` for Jira & ServiceNow | CredentialVault decrypt at poll time |+| `services/connectors` | Python 3.11 | 84 connector classes, APScheduler poll, `push_case` / `push_status_change` for Jira & ServiceNow | CredentialVault decrypt at poll time || `services/agents` | Python 3.11 | LangGraph multi-agent investigation runs | Loads full ATT&CK STIX bundle on boot, optional Qdrant embed || `services/actions` | Python 3.11 | SOAR action execution with blast-radius gating | Approval workflows || `services/threatintel` | Python 3.11 | IOC/actor search API | APScheduler poll loop for TAXII/MISP/OTX/KEV |@@ -314,7 +314,7 @@ The following subsystems were added on top of the v2 design described above. The### 12.1 Connector Platform (`services/connectors`)-A first-class, in-process polling tier with **83 registered connector classes** spanning seven categories — `edr`, `siem`, `cloud`, `iam`, `saas`, `vcs`, `network`. Every connector subclasses `BaseConnector` and declares:+A first-class, in-process polling tier with **84 registered connector classes** spanning seven categories — `edr`, `siem`, `cloud`, `iam`, `saas`, `vcs`, `network`. Every connector subclasses `BaseConnector` and declares:* `schema()` — self-describing `ConnectorSchema(name, label, category, fields, oauth, default_poll_interval_seconds)` consumed by the web console for the connect form.* `capabilities()` — tuple of `Capability` enum values (`PULL_ALERTS`, `PUSH_CASE`, `PUSH_STATUS`, `FEDERATED_SEARCH`, …) that the orchestrator inspects at runtime.diff --git a/docs/connectors/conformance-matrix.md b/docs/connectors/conformance-matrix.mdindex ad6ab4ec0..2df5d930c 100644--- a/docs/connectors/conformance-matrix.md+++ b/docs/connectors/conformance-matrix.md@@ -6,11 +6,12 @@> async coroutines, valid capabilities, secret fields marked `secret`).> Live-vendor sandbox smoke is a separate wave; this gates the contract.-**83 / 83 connectors conform** to the runtime contract.+**84 / 84 connectors conform** to the runtime contract.| connector | category | fields | vaulted | caps | test_connection | fetch_alerts | normalize ||-----------|----------|-------:|--------:|-----:|:---------------:|:------------:|:---------:|| abnormal_security | saas | 2 | 1 | 3 | ✅ | ✅ | ✅ |+| ai_gateway | ai | 4 | 1 | 0 | ✅ | ✅ | ✅ || auditd | edr | 3 | 0 | 2 | ✅ | ✅ | ✅ || auth0 | iam | 3 | 1 | 3 | ✅ | ✅ | ✅ || aws_cloudtrail | cloud | 4 | 1 | 1 | ✅ | ✅ | ✅ |diff --git a/docs/detections/truth-table.md b/docs/detections/truth-table.mdindex e91861f73..f891fef81 100644--- a/docs/detections/truth-table.md+++ b/docs/detections/truth-table.md@@ -4,45 +4,64 @@> file in `validate-detections.yml`, so the numbers below can never quietly> diverge from what the engine actually runs. **Do not edit by hand.**-A rule is **executable** when it fires in AiSOC today: not quarantined-(`_quarantine/` or `enabled: false`) and its `detection` body is the native-AiSOC condition DSL, a Sigma selection/condition, or a runtime-engine language.-A rule is **non-executable** when quarantined or when its only body is an-untranslated upstream language (SPL / YARA-L / CAR pseudocode) — present for-provenance and coverage-mapping, not firing.+A rule is **executable** when the detection engine actually loads it — when+its id appears in `services/fusion/app/data/detection_ruleset.json`, the+compiled ruleset `DetectionEngine` reads at startup.++That is the only definition that means anything, because the YAML under+`detections/` is a *generated projection* of the Python spec modules in+`scripts/detection_specs*.py` — the engine never reads it. Editing a+`condition:` block or flipping `enabled:` has no effect on what fires. The+lever that reaches the engine is adding a spec and re-running+`scripts/export_detection_ruleset.py`.## Headline| metric | count ||--------|------:|-| rules on disk (total) | 6983 |-| **executable (fire today)** | **947** |-| non-executable (provenance/coverage only) | 6036 |+| rules on disk (total) | 6991 |+| **executable (loaded by the engine)** | **833** |+| non-executable (provenance/coverage only) | 6158 |+| — of which: enabled, but no compiled spec | 122 |++Those 122 rules are the ones an earlier version of this+table counted as executable. They carry `enabled: true` and a body whose+shape looks evaluable, and the engine has never seen them because no spec+produced a `match_when` for them. They are genuine work items, listed by+tier below, not a rounding error.## By tier-| tier | on disk | executable |-|------|--------:|-----------:|-| car (imported) | 99 | 0 |-| chronicle (imported) | 877 | 0 |-| community | 1 | 1 |-| native | 869 | 869 |-| sigma (imported) | 3132 | 77 |-| splunk (imported) | 2005 | 0 |+| tier | on disk | executable | enabled but not loaded |+|------|--------:|-----------:|-----------------------:|+| car (imported) | 99 | 0 | 0 |+| chronicle (imported) | 877 | 0 | 0 |+| community | 1 | 0 | 1 |+| native | 877 | 833 | 44 |+| sigma (imported) | 3132 | 0 | 77 |+| splunk (imported) | 2005 | 0 | 0 |## Why rules are non-executable| reason | count ||--------|------:|-| `enabled: false` | 115 |-| under `_quarantine/` (untranslated on import) | 5921 |+| `enabled: false` | 99 |+| enabled, but no compiled spec — the engine does not load it | 122 |+| under `_quarantine/` (untranslated on import) | 5937 |## How to read the README claim-The imported corpus is large (6983 rules on disk) and valuable as a+The imported corpus is large (6991 rules on disk) and valuable as aprovenance-tracked ATT&CK-mapped library, but the number that matters-operationally is **947 executable rules** — the ones the engine-fires against live telemetry. The README and marketplace must cite the-executable figure when describing detection *coverage*, and may cite the+operationally is **833 executable rules** — the ones the engine+loads and fires against live telemetry. The README and marketplace must cite+the executable figure when describing detection *coverage*, and may cite theon-disk figure only when explicitly describing the imported *library*.+Two things this table cannot tell you, stated so nobody infers them:++1. A loaded rule still has to match on a field some connector emits. That+ property is enforced separately by `scripts/check_detection_fields.py`.+2. Executable is not the same as tuned. `false_positives:` is prose and is+ not machine-checked; there is no per-rule false-positive-rate gate.+diff --git a/marketplace/curated.json b/marketplace/curated.jsonindex 5aabe750a..f3368bd94 100644--- a/marketplace/curated.json+++ b/marketplace/curated.json@@ -1,39 +1,38 @@{"$schema": "https://aisoc.example.com/schemas/curated/v1.json","version": "1.0.0",- "generated": "2026-07-13T06:40:32Z",+ "generated": "2026-09-22T15:54:13Z","stats": {- "considered": 1062,- "eligible": 1058,- "selected": 417,+ "considered": 1054,+ "eligible": 1051,+ "selected": 418,"min_per_family": 25,"min_total": 300,"quality_floor": 0.55,"unique_techniques": 117,"selected_by_tier": {- "imported": 42,- "native": 375+ "imported": 41,+ "native": 377},"selected_by_severity": {- "critical": 99,- "high": 208,+ "critical": 100,+ "high": 209,"low": 6,- "medium": 104+ "medium": 103},"selected_by_category": {- "_migrated": 1,- "application": 33,+ "application": 36,"cloud": 164,"data-exfil": 20,"endpoint": 117,- "identity": 70,+ "identity": 69,"network": 12}},"families": {"ransomware": {"label": "Ransomware",- "count": 49,+ "count": 48,"rule_ids": ["det-application-050","det-application-078",@@ -82,21 +81,21 @@"sigmahq-sigma-37222991-11e9-4b6d-8bdf-60fbe48f753e","sigmahq-sigma-87df9ee1-5416-453a-8a08-e8d4a51e9ce1","sigmahq-sigma-add64136-62e5-48ea-807e-88638d02df1e",- "sigmahq-sigma-c947b146-0abc-4c87-9c64-b17e9d7274a2",- "splunk-security-content-0c320fea-6e87-4b99-a884-74d09d4b655d"+ "sigmahq-sigma-c947b146-0abc-4c87-9c64-b17e9d7274a2"],"min_target": 25,"covered": true},"credential-access": {"label": "Credential Access",- "count": 85,+ "count": 86,"rule_ids": ["det-application-004","det-application-008","det-application-020","det-application-040","det-application-075",+ "det-application-085","det-cloud-047","det-cloud-074","det-cloud-101",@@ -224,8 +223,9 @@},"exfil": {"label": "Data Exfiltration",- "count": 41,+ "count": 42,"rule_ids": [+ "det-application-081","det-cloud-058","det-cloud-062","det-cloud-063",@@ -391,6 +391,7 @@"det-application-072","det-application-073","det-application-075",+ "det-application-080","det-cloud-001","det-cloud-007","det-cloud-014",@@ -459,7 +460,6 @@"det-endpoint-301","det-endpoint-302","det-identity-001",- "det-identity-002","det-identity-009","det-identity-020","det-identity-021",@@ -683,7 +683,7 @@"T1484.002": 1,"T1485": 31,"T1486": 5,- "T1489": 3,+ "T1489": 2,"T1490": 11,"T1496": 6,"T1505.003": 2,@@ -698,7 +698,7 @@"T1548.003": 1,"T1550": 4,"T1550.003": 1,- "T1552": 2,+ "T1552": 3,"T1552.001": 5,"T1552.005": 1,"T1552.007": 1,@@ -720,7 +720,7 @@"T1562.008": 8,"T1565": 1,"T1565.001": 1,- "T1567": 10,+ "T1567": 11,"T1567.002": 2,"T1569": 1,"T1570": 6,@@ -1568,6 +1568,81 @@"log_source_product": "openai","has_executable_body": true},+ {+ "id": "det-application-080",+ "name": "AI Agent Took Action Beyond Its Granted Scope",+ "path": "detections/application/ai-agent-excessive-agency.yaml",+ "tier": "native",+ "source": "core",+ "category": "application",+ "severity": "high",+ "mitre_techniques": [+ "T1078"+ ],+ "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": "ai_guardrail",+ "has_executable_body": true+ },+ {+ "id": "det-application-081",+ "name": "Sensitive Data Left via an AI Agent",+ "path": "detections/application/ai-sensitive-data-egress.yaml",+ "tier": "native",+ "source": "core",+ "category": "application",+ "severity": "critical",+ "mitre_techniques": [+ "T1567"+ ],+ "mitre_tactics": [],+ "families": [+ "exfil"+ ],+ "quality_score": 1.0,+ "quality_notes": [+ "tier:native(+0.5)",+ "mitre_techniques:1(+0.2)",+ "severity:critical(+0.150)",+ "executable(+0.15)"+ ],+ "log_source_product": "ai_guardrail",+ "has_executable_body": true+ },+ {+ "id": "det-application-085",+ "name": "Credential Material Present in an AI Prompt",+ "path": "detections/application/ai-prompt-contained-credential.yaml",+ "tier": "native",+ "source": "core",+ "category": "application",+ "severity": "high",+ "mitre_techniques": [+ "T1552"+ ],+ "mitre_tactics": [],+ "families": [+ "credential-access"+ ],+ "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": "ai_runtime",+ "has_executable_body": true+ },{"id": "det-cloud-001","name": "AWS Root Account Console Login",@@ -8331,32 +8406,6 @@"log_source_product": "okta","has_executable_body": true},- {- "id": "det-identity-002",- "name": "Impossible Travel Between Two Authentications",- "path": "detections/identity/impossible-travel.yaml",- "tier": "native",- "source": "core",- "category": "identity",- "severity": "high",- "mitre_techniques": [- "T1078"- ],- "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-003","name": "Password Spray Across Many Users from Single IP",@@ -11482,31 +11531,6 @@],"log_source_product": "windows","has_executable_body": true- },- {- "id": "splunk-security-content-0c320fea-6e87-4b99-a884-74d09d4b655d",- "name": "Linux Auditd Osquery Service Stop",- "path": "detections/splunk-imports/_migrated/linux-auditd-osquery-service-stop.yaml",- "tier": "imported",- "source": "splunk-security-content",- "category": "_migrated",- "severity": "medium",- "mitre_techniques": [- "T1489"- ],- "mitre_tactics": [],- "families": [- "ransomware"- ],- "quality_score": 0.605,- "quality_notes": [- "tier:imported(+0.3)",- "mitre_techniques:1(+0.2)",- "severity:medium(+0.105)",- "no_executable_body(0)"- ],- "log_source_product": "splunk",- "has_executable_body": false}]}diff --git a/marketplace/index.json b/marketplace/index.jsonindex ab81c855e..c5834bd98 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-07-13T06:13:47Z",+ "generated": "2026-09-22T15:54:12Z","categories": [{"id": "playbooks",@@ -20,24 +20,24 @@}],"stats": {- "total": 7146,+ "total": 7155,"playbooks": 62,- "detections": 7008,- "plugins": 76,- "verified": 1025,+ "detections": 7016,+ "plugins": 77,+ "verified": 1034,"community": 1,"by_tier": {"beta": 7,"community": 1,"imported": 6113,- "stable": 1025+ "stable": 1034},"detections_by_tier": {"community": 1,"imported": 6113,- "stable": 894+ "stable": 902},- "quarantined": 5921+ "quarantined": 5937},"mitre_coverage": {"techniques": {@@ -130,7 +130,7 @@"T1056.001": 4,"T1056.002": 4,"T1057": 8,- "T1059": 121,+ "T1059": 122,"T1059.001": 243,"T1059.002": 11,"T1059.003": 41,@@ -162,7 +162,7 @@"T1072": 9,"T1074": 3,"T1074.001": 6,- "T1078": 128,+ "T1078": 132,"T1078.001": 10,"T1078.002": 14,"T1078.003": 11,@@ -360,7 +360,7 @@"T1547.012": 7,"T1547.014": 3,"T1547.015": 3,- "T1548": 34,+ "T1548": 35,"T1548.001": 12,"T1548.002": 76,"T1548.003": 39,@@ -370,7 +370,7 @@"T1550.002": 7,"T1550.003": 9,"T1550.004": 2,- "T1552": 21,+ "T1552": 22,"T1552.001": 38,"T1552.002": 7,"T1552.003": 3,@@ -437,7 +437,7 @@"T1566.001": 52,"T1566.002": 14,"T1566.003": 1,- "T1567": 33,+ "T1567": 34,"T1567.001": 2,"T1567.002": 23,"T1568": 1,@@ -536,7 +536,7 @@"T1690": 1},"unique_techniques": 493,- "total_with_mitre": 5792,+ "total_with_mitre": 5800,"by_tier": {"community": {"T1078.004": 1@@ -580,7 +580,7 @@"T1055.001": 1,"T1055.012": 1,"T1056.001": 1,- "T1059": 8,+ "T1059": 9,"T1059.001": 5,"T1059.002": 3,"T1059.004": 8,@@ -595,7 +595,7 @@"T1071.001": 10,"T1071.004": 6,"T1074.001": 1,- "T1078": 37,+ "T1078": 41,"T1078.001": 4,"T1078.002": 3,"T1078.003": 1,@@ -693,7 +693,7 @@"T1547.006": 6,"T1547.010": 1,"T1547.015": 2,- "T1548": 1,+ "T1548": 2,"T1548.001": 6,"T1548.002": 4,"T1548.003": 3,@@ -702,7 +702,7 @@"T1550.002": 2,"T1550.003": 1,"T1550.004": 1,- "T1552": 1,+ "T1552": 2,"T1552.001": 12,"T1552.004": 2,"T1552.005": 2,@@ -747,7 +747,7 @@"T1566.001": 2,"T1566.002": 2,"T1566.003": 1,- "T1567": 12,+ "T1567": 13,"T1567.002": 7,"T1568.001": 2,"T1568.002": 2,@@ -30429,6 +30429,190 @@"enabled": true,"path": "detections/application/llm-project-deleted.yaml"},+ {+ "id": "det-application-079",+ "type": "detection",+ "name": "Prompt Injection Detected in AI Agent Context",+ "description": "A guardrail flagged instruction-override content reaching an agent's context. Injection is the delivery mechanism for every other agent abuse, so this is the earliest point at which the chain is visible.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "application",+ "mitre_techniques": [+ "T1059"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-triage",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-prompt-injection-detected.yaml"+ },+ {+ "id": "det-application-080",+ "type": "detection",+ "name": "AI Agent Took Action Beyond Its Granted Scope",+ "description": "The agent invoked a capability outside the scope it was granted. Unlike a compromised user, an agent has no intent to infer \u2014 a call outside its declared tool set is either a policy gap or someone steering it.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "application",+ "mitre_techniques": [+ "T1078"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-privilege-escalation",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-agent-excessive-agency.yaml"+ },+ {+ "id": "det-application-081",+ "type": "detection",+ "name": "Sensitive Data Left via an AI Agent",+ "description": "A guardrail matched sensitive content on its way out through an agent. An agent with retrieval access is an exfiltration path that authenticates as itself and looks like normal application traffic.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "critical",+ "category": "application",+ "mitre_techniques": [+ "T1567"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-data-exfil",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-sensitive-data-egress.yaml"+ },+ {+ "id": "det-application-082",+ "type": "detection",+ "name": "AI Agent Used an Unapproved Model",+ "description": "An agent called a model outside the approved set. Often benign drift, but it is also how data leaves a reviewed provider for an unreviewed one.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "medium",+ "category": "application",+ "mitre_techniques": [+ "T1078"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-triage",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-unapproved-model.yaml"+ },+ {+ "id": "det-application-083",+ "type": "detection",+ "name": "AI Agent Escalated to a Higher-Privilege Tool",+ "description": "AiSOC v1 curated detection. Triggers on the application signal described by 'AI Agent Escalated to a Higher-Privilege Tool'. Watch the 1 documented false-positive case before tuning.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "application",+ "mitre_techniques": [+ "T1548"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-privilege-escalation",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-tool-escalation.yaml"+ },+ {+ "id": "det-application-084",+ "type": "detection",+ "name": "Undeclared AI Agent Observed",+ "description": "Telemetry arrived from an agent absent from the inventory. Shadow AI is the AI-estate equivalent of an unmanaged endpoint: it cannot be governed, and its access is unreviewed.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "medium",+ "category": "application",+ "mitre_techniques": [+ "T1078"+ ],+ "log_source": "ai_guardrail",+ "playbook": "tpl-triage",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-shadow-agent-discovered.yaml"+ },+ {+ "id": "det-application-085",+ "type": "detection",+ "name": "Credential Material Present in an AI Prompt",+ "description": "A secret shape appeared in a prompt. Detected without the prompt content ever being transmitted: the SDK reports which patterns matched while sending only a digest, so this fires even under the default hashed capture mode.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "high",+ "category": "application",+ "mitre_techniques": [+ "T1552"+ ],+ "log_source": "ai_runtime",+ "playbook": "tpl-account-compromise",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-prompt-contained-credential.yaml"+ },+ {+ "id": "det-application-086",+ "type": "detection",+ "name": "AI Agent Tool Call Denied",+ "description": "A tool call was refused. Low on its own, and deliberately so \u2014 the value is as a building block once the windowed engine can express 'N denials in M minutes', which is the shape that distinguishes a probing agent from a misconfigured one.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [+ "tlp.white"+ ],+ "severity": "low",+ "category": "application",+ "mitre_techniques": [+ "T1078"+ ],+ "log_source": "ai_runtime",+ "playbook": "tpl-triage",+ "verified": true,+ "source": "core",+ "tier": "stable",+ "enabled": true,+ "path": "detections/application/ai-agent-tool-call-failed-repeatedly.yaml"+ },{"id": "det-cloud-001","type": "detection",@@ -158845,7 +159029,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1489"],@@ -158855,7 +159039,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/linux-auditd-osquery-service-stop.yaml",+ "path": "detections/splunk-imports/_quarantine/linux-auditd-osquery-service-stop.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "0c320fea-6e87-4b99-a884-74d09d4b655d",@@ -163991,7 +164176,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1068"],@@ -164001,7 +164186,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/detect-baron-samedit-cve-2021-3156-via-osquery.yaml",+ "path": "detections/splunk-imports/_quarantine/detect-baron-samedit-cve-2021-3156-via-osquery.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "1de31d5d-8fa6-4ee0-af89-17069134118a",@@ -164825,7 +165011,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1543.001"],@@ -164835,7 +165021,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/suspicious-plistbuddy-usage-via-osquery.yaml",+ "path": "detections/splunk-imports/_quarantine/suspicious-plistbuddy-usage-via-osquery.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "20ba6c32-c733-4a32-b64e-2688cf231399",@@ -167124,7 +167311,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": [],"log_source": null,"playbook": null,@@ -167132,7 +167319,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/processes-tapping-keyboard-events.yaml",+ "path": "detections/splunk-imports/_quarantine/processes-tapping-keyboard-events.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "2a371608-331d-4034-ae2c-21dda8f1d0ec",@@ -167780,7 +167968,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1553.001"],@@ -167790,7 +167978,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-gatekeeper-bypass.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-gatekeeper-bypass.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "2c9346f3-bbeb-48ce-8411-fc13d09d83a5",@@ -174408,7 +174597,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1136"],@@ -174418,7 +174607,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-account-created.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-account-created.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "491004ae-694f-453e-b1e0-fc1e65daeea1",@@ -175772,7 +175962,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1059.002"],@@ -175782,7 +175972,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-amos-stealer-virtual-machine-check-activity.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-amos-stealer-virtual-machine-check-activity.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "4e41ad21-9761-426d-8aa1-083712ff9f30",@@ -176535,7 +176726,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1564.001"],@@ -176545,7 +176736,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-hidden-files-and-directories.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-hidden-files-and-directories.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "51c43b7b-e406-45d2-9bad-5c67f07e6528",@@ -178362,7 +178554,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1059.004"],@@ -178372,7 +178564,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-lolbin.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-lolbin.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "58d270fb-5b39-418e-a855-4b8ac046805e",@@ -187489,7 +187682,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1030"],@@ -187499,7 +187692,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-data-chunking.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-data-chunking.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "7f1c8bed-9bd4-40b0-a1df-c262cbade0fc",@@ -195857,7 +196051,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1543"],@@ -195867,7 +196061,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-kextload-usage.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-kextload-usage.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "9d680775-84a6-4625-a8ea-8182b9427ce4",@@ -196591,7 +196786,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1037.002"],@@ -196601,7 +196796,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-loginhook-persistence.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-loginhook-persistence.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "a04832e7-9d1d-49b1-a684-e31bcd775c77",@@ -198420,7 +198616,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1135"],@@ -198430,7 +198626,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-network-share-discovery.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-network-share-discovery.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "a5f5fe52-8e50-4fb0-ad1b-780be6c0d857",@@ -198785,7 +198982,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1070"],@@ -198795,7 +198992,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-log-removal.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-log-removal.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "a7f2e891-3c4d-4a1b-9e6f-2b8d0c5a1f3e",@@ -205687,7 +205885,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1647"],@@ -205697,7 +205895,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-plutil.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-plutil.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "c11f2b57-92c1-4cd2-b46c-064eafb833ac",@@ -213404,7 +213603,7 @@"categories.endpoint"],"severity": "medium",- "category": "_migrated",+ "category": "_quarantine","mitre_techniques": ["T1555.001"],@@ -213414,7 +213613,8 @@"source": "splunk-security-content","tier": "imported","enabled": false,- "path": "detections/splunk-imports/_migrated/macos-keychains-dumped.yaml",+ "path": "detections/splunk-imports/_quarantine/macos-keychains-dumped.yaml",+ "quarantine_reason": "imported rule; upstream query language not directly executable by the AiSOC engine yet","provenance": {"source": "splunk/security_content","source_id": "dcb45a09-5e6f-441e-b2f8-cbbf923e36d9",@@ -224227,6 +224427,34 @@"tier": "stable","path": "plugins/abnormal_security/plugin.yaml"},+ {+ "id": "ai-gateway",+ "type": "plugin",+ "name": "AI Gateway / MCP Runtime",+ "description": "Pulls request logs from an LLM gateway or MCP server (LiteLLM, Portkey, Helicone, or an in-house proxy) so a SOC can see which agents call which tools and models, on whose behalf. One connector covers every application behind the gateway, which matters because the apps most in need of visibility are the ones nobody will retrofit an SDK into. For applications you do control, packages/aisoc-ai-sdk is the lower-friction push path. Routine activity is archived to the event lake and hunted; a guardrail violation becomes an alert.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "ai",+ "ai-spm",+ "llm",+ "agents",+ "mcp",+ "guardrails",+ "runtime",+ "connector"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/ai_gateway.py",+ "min_aisoc_version": "8.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/ai-gateway/plugin.yaml"+ },{"id": "aisoc-direct","type": "plugin",diff --git a/packages/aisoc-ai-sdk/README.md b/packages/aisoc-ai-sdk/README.mdnew file mode 100644index 000000000..1bc3ba949--- /dev/null+++ b/packages/aisoc-ai-sdk/README.md@@ -0,0 +1,147 @@+# aisoc-ai-sdk++Emit AI runtime telemetry — agent tool calls, model invocations, guardrail+findings — to AiSOC.++## Why this exists++AiSOC could already ingest an organisation's OpenAI and Anthropic **audit+logs**: who minted an API key, who was granted owner, whether MFA was turned+off. That is control-plane governance, and it is worth having.++It says nothing about what the agents did once they were running. Which tools+they invoked, on whose behalf, against which resources, and whether anything in+their retrieved context tried to give them new instructions.++This is the runtime half. Every span lands in the same pipeline as every other+security signal: OCSF normalized, archived to the ClickHouse lake, evaluated by+the detection engine, promoted, triaged.++## Install++```bash+pip install -e packages/aisoc-ai-sdk # PyPI publish lands in v8.1+```++## Use++Mint two inbox tokens — `POST /api/v1/inbox/tokens` — one with the+`ai-runtime` template and one with `ai-finding`:++```python+from aisoc_ai import AiSocAiClient++aisoc = AiSocAiClient(+ endpoint="https://aisoc.example.com/v1/inbox/<runtime-token>",+ finding_endpoint="https://aisoc.example.com/v1/inbox/<finding-token>",+ agent_id="support-bot",+)++# Routine activity. Archived to the lake and hunted, not alerted on.+aisoc.tool_call(+ "search_tickets",+ on_behalf_of="[email protected]",+ arguments={"query": "billing"}, # keys are sent, values are not+)++aisoc.model_call("gpt-4o", prompt=prompt, response=answer, prompt_tokens=412)++# A guardrail objected. Always promoted to an alert.+aisoc.finding(+ "prompt_injection",+ "Instruction override in retrieved document",+ confidence=0.91,+)+```++## Two endpoints, deliberately++The split is the design, not an inconvenience.++`tool_call` and `model_call` normalize to OCSF **6003 API Activity**. Category+6, so the promoter leaves them in the lake. An agent doing its job is not an+alert, and treating it as one floods the queue with an agent's own normal+operation.++`finding` normalizes to OCSF **2001 Security Finding**. Category 2, which the+promoter always promotes regardless of severity, because a guardrail has+already judged it worth a human's attention. Send a finding to the runtime+endpoint and it silently becomes routine telemetry — so the SDK warns loudly+when `finding_endpoint` is unset.++## What leaves your process++Prompts and model responses routinely contain whatever a user pasted in,+whatever a retrieval step pulled from an internal store, and whatever the model+then said about it. A SOC needs to detect abuse of the AI without becoming the+largest single collection of that text in the company.++So the default is `CaptureMode.HASHED`: a SHA-256 digest and a length, never+the content. That answers the questions detection actually asks — is this the+same prompt fifty times in a minute, did the response change after an injection+attempt, is this prompt anomalously long for this agent — without retaining the+text.++It also reports **which secret shapes** were present. So "this prompt contained+an AWS access key" is detectable, and the `ai-prompt-contained-credential` rule+fires, while the key itself never leaves your process.++| mode | what is sent |+| --- | --- |+| `HASHED` (default) | digest, length, matched secret-pattern names |+| `MASKED` | the above plus content with secret shapes replaced |+| `FULL` | the above plus content verbatim |++`MASKED` and `FULL` exist because incident response sometimes genuinely needs+the words. Both are opt-in per client, because that is a decision someone+should make deliberately rather than inherit from a default.++Tool arguments follow the same rule: parameter **names** are transmitted,+values are not. Which tool ran with which parameters is the detection signal;+the values are frequently the sensitive part.++## Failure behaviour++This is instrumentation inside your request path, so it is built to fail+quietly rather than loudly:++- **Never raises into your code.** Every public method returns a bool. A+ transport error, a rejected token or an unreachable AiSOC is a dropped span.+- **Never blocks.** Spans go onto a bounded queue drained by a background+ thread.+- **Never grows without limit.** A full queue drops the oldest span and counts+ the drop. Unbounded buffering inside your process is a worse outcome than+ losing telemetry.+- **Off when unconfigured.** No `endpoint` disables the client rather than+ raising, which is how an operator turns it off.++`client.stats()` returns emitted / sent / dropped / failed counters, so a+silent SDK is distinguishable from an idle one.++## Detections this feeds++`detections/application/ai-*.yaml`, authored in+`scripts/detection_specs_part3_application.py`:++| rule | fires on |+| --- | --- |+| `ai-prompt-injection-detected` | `finding_type: prompt_injection` |+| `ai-agent-excessive-agency` | `finding_type: excessive_agency` |+| `ai-sensitive-data-egress` | `finding_type: sensitive_data_egress` |+| `ai-unapproved-model` | `finding_type: unapproved_model` |+| `ai-tool-escalation` | `finding_type: tool_escalation` |+| `ai-shadow-agent-discovered` | `finding_type: shadow_ai` |+| `ai-prompt-contained-credential` | a secret shape in a prompt |+| `ai-agent-tool-call-failed-repeatedly` | a denied tool call |++## If you run a gateway instead++For apps you do not control, the `ai_gateway` connector pulls request logs from+LiteLLM, Portkey, Helicone or an in-house proxy and produces the same OCSF+shape. One connector covers every app behind the gateway, which matters because+the apps most in need of visibility are the ones nobody will retrofit an SDK+into.++## License++MIT.diff --git a/packages/aisoc-ai-sdk/aisoc_ai/__init__.py b/packages/aisoc-ai-sdk/aisoc_ai/__init__.pynew file mode 100644index 000000000..6e35bc65f--- /dev/null+++ b/packages/aisoc-ai-sdk/aisoc_ai/__init__.py@@ -0,0 +1,33 @@+"""Emit AI-estate telemetry to AiSOC from inside an agent or LLM app.++AiSOC could already ingest an organisation's OpenAI and Anthropic *audit logs*+— who minted an API key, who was made an owner. That is control-plane+governance and says nothing about what the agents did once running. This is the+runtime half: tool calls, model invocations and guardrail findings, landing in+the same pipeline as every other security signal.++ from aisoc_ai import AiSocAiClient++ aisoc = AiSocAiClient(+ endpoint="https://aisoc.example.com/v1/inbox/<runtime-token>",+ finding_endpoint="https://aisoc.example.com/v1/inbox/<finding-token>",+ agent_id="support-bot",+ )++ aisoc.tool_call("search_tickets", on_behalf_of="[email protected]")+ aisoc.finding("prompt_injection", "Instruction override in retrieved doc")++Prompt and response content is hashed by default and never transmitted unless+the caller opts in. See `redaction.py`.+"""++from aisoc_ai.client import AiSocAiClient+from aisoc_ai.redaction import CaptureMode, RedactedText, redact, secret_kinds++__all__ = [+ "AiSocAiClient",+ "CaptureMode",+ "RedactedText",+ "redact",+ "secret_kinds",+]diff --git a/packages/aisoc-ai-sdk/aisoc_ai/client.py b/packages/aisoc-ai-sdk/aisoc_ai/client.pynew file mode 100644index 000000000..4f4a82c73--- /dev/null+++ b/packages/aisoc-ai-sdk/aisoc_ai/client.py@@ -0,0 +1,325 @@+"""Emit AI-estate telemetry to AiSOC from inside an agent or LLM app.++AiSOC could already ingest an organisation's OpenAI and Anthropic *audit logs*+— who minted an API key, who was made an owner. That is control-plane+governance. It says nothing about what the agents actually did once running:+which tools they invoked, on whose behalf, against which resources, and+whether anything tried to steer them.++This is the runtime half. Point it at an inbox token and every tool call,+model invocation and guardrail finding lands in the same pipeline as every+other security signal — OCSF normalized, archived to the lake, matched by the+detection engine, promoted and triaged.++Two spans, matching the two ingest templates, and the distinction matters:++* `tool_call` / `model_call` are routine activity. They normalize to OCSF+ `6003` API Activity, which is category 6, so the promoter leaves them in the+ lake to be hunted. An agent doing its job is not an alert.+* `finding` is something a guardrail judged worth reporting. It normalizes to+ `2001` Security Finding, category 2, which the promoter always promotes.++Design constraints this file holds to:++**Never break the caller's app.** This is instrumentation inside somebody+else's request path. A network failure, a bad token or an unreachable AiSOC+must degrade to a dropped span, never to an exception escaping into their+agent. Every public method is therefore best-effort and returns a bool.++**Never block it either.** Emission is fire-and-forget onto a bounded queue+drained by a background worker. A full queue drops the oldest span and counts+the drop, because unbounded buffering inside a customer's process is a worse+failure than losing telemetry.++**Redaction before transmission, not after.** See `redaction.py`. Prompt and+response content is hashed by default and only ever sent when the caller opts+in explicitly.+"""++from __future__ import annotations++import atexit+import json+import logging+import queue+import threading+import time+import urllib.error+import urllib.request+import uuid+from dataclasses import dataclass, field+from typing import Any++from aisoc_ai.redaction import CaptureMode, redact, secret_kinds++logger = logging.getLogger("aisoc_ai")++#: Bounded so instrumentation cannot grow memory without limit in the host+#: process. Sized for a burst of agent activity between flushes, not for+#: riding out a long AiSOC outage.+_QUEUE_MAXSIZE = 1000++_BATCH_SIZE = 50+_FLUSH_INTERVAL_SECONDS = 2.0+_REQUEST_TIMEOUT_SECONDS = 5.0+++@dataclass+class _Counters:+ """Observable from the host process, so a silent SDK is diagnosable."""++ emitted: int = 0+ sent: int = 0+ dropped_queue_full: int = 0+ failed_transport: int = 0+++@dataclass+class AiSocAiClient:+ """Emits AI runtime spans to an AiSOC inbox token.++ `endpoint` is the full inbox URL, e.g.+ `https://aisoc.example.com/v1/inbox/<token>`. Mint the token with+ `POST /api/v1/inbox/tokens` and the `ai-runtime` template; findings go to a+ second token using the `ai-finding` template.+ """++ endpoint: str+ finding_endpoint: str | None = None+ agent_id: str = "unknown-agent"+ agent_name: str | None = None+ capture: CaptureMode = CaptureMode.HASHED+ enabled: bool = True++ _queue: queue.Queue = field(default_factory=lambda: queue.Queue(maxsize=_QUEUE_MAXSIZE), init=False)+ _worker: threading.Thread | None = field(default=None, init=False)+ _stop: threading.Event = field(default_factory=threading.Event, init=False)+ _counters: _Counters = field(default_factory=_Counters, init=False)++ def __post_init__(self) -> None:+ if not self.endpoint:+ # No endpoint configured is a legitimate state — it is how an+ # operator turns the SDK off — so it disables rather than raises.+ self.enabled = False+ return+ self._worker = threading.Thread(target=self._drain, name="aisoc-ai-emitter", daemon=True)+ self._worker.start()+ atexit.register(self.flush)++ # ── public API ────────────────────────────────────────────────────────++ def tool_call(+ self,+ tool_name: str,+ *,+ on_behalf_of: str | None = None,+ server_name: str | None = None,+ resource: str | None = None,+ arguments: dict[str, Any] | None = None,+ outcome: str = "success",+ latency_ms: float | None = None,+ session_id: str | None = None,+ severity: str = "info",+ ) -> bool:+ """Record that the agent invoked a tool.++ `arguments` keys are transmitted; values are not. Which tool was+ called with which parameter *names* is the detection signal, and the+ values are frequently the sensitive part.+ """+ return self._emit(+ self.endpoint,+ {+ "tool_name": tool_name,+ "server_name": server_name,+ "resource": resource,+ "argument_keys": sorted(arguments or {}),+ "outcome": outcome,+ "latency_ms": latency_ms,+ "session_id": session_id or str(uuid.uuid4()),+ "severity": severity,+ "on_behalf_of": on_behalf_of,+ },+ )++ def model_call(+ self,+ model: str,+ *,+ provider: str | None = None,+ prompt: str | None = None,+ response: str | None = None,+ prompt_tokens: int | None = None,+ completion_tokens: int | None = None,+ on_behalf_of: str | None = None,+ latency_ms: float | None = None,+ session_id: str | None = None,+ severity: str = "info",+ ) -> bool:+ """Record a model invocation.++ Prompt and response go through `redact()` first. In the default hashed+ mode the SOC receives a digest, a length, and — importantly — which+ secret shapes were present, so "this prompt contained an AWS key" is+ detectable without the key ever leaving the process.+ """+ redacted_prompt = redact(prompt, self.capture)+ redacted_response = redact(response, self.capture)+ payload: dict[str, Any] = {+ "tool_name": f"model:{model}",+ "model": model,+ "provider": provider,+ "prompt_tokens": prompt_tokens,+ "completion_tokens": completion_tokens,+ "prompt_sha256": redacted_prompt.sha256,+ "prompt_length": redacted_prompt.length,+ "response_sha256": redacted_response.sha256,+ "response_length": redacted_response.length,+ "prompt_secret_kinds": list(secret_kinds(prompt)),+ "latency_ms": latency_ms,+ "session_id": session_id or str(uuid.uuid4()),+ "severity": severity,+ "on_behalf_of": on_behalf_of,+ }+ if redacted_prompt.content is not None:+ payload["prompt"] = redacted_prompt.content+ if redacted_response.content is not None:+ payload["response"] = redacted_response.content+ return self._emit(self.endpoint, payload)++ def finding(+ self,+ finding_type: str,+ title: str,+ *,+ severity: str = "high",+ description: str | None = None,+ confidence: float | None = None,+ rule_id: str | None = None,+ matched_pattern: str | None = None,+ tool_name: str | None = None,+ model: str | None = None,+ on_behalf_of: str | None = None,+ session_id: str | None = None,+ ) -> bool:+ """Report something a guardrail judged worth a human's attention.++ Routed to `finding_endpoint` when configured, because findings use the+ `ai-finding` template (OCSF 2001, always promoted) rather than+ `ai-runtime` (6003, lake-only). Falling back to the runtime endpoint+ would silently downgrade a finding into routine activity, so the+ fallback is deliberate and logged.++ `finding_type` is the field detections match on: prompt_injection,+ excessive_agency, sensitive_data_egress, unapproved_model,+ tool_escalation, shadow_ai.+ """+ target = self.finding_endpoint+ if target is None:+ target = self.endpoint+ logger.warning(+ "aisoc_ai: no finding_endpoint configured; sending %r to the runtime "+ "endpoint, where it will normalize as routine activity and will not "+ "be promoted to an alert",+ finding_type,+ )+ return self._emit(+ target,+ {+ "finding_id": str(uuid.uuid4()),+ "finding_type": finding_type,+ "title": title,+ "description": description,+ "severity": severity,+ "confidence": confidence,+ "rule_id": rule_id,+ "matched_pattern": matched_pattern,+ "tool_name": tool_name,+ "model": model,+ "on_behalf_of": on_behalf_of,+ "session_id": session_id,+ },+ )++ def flush(self, timeout: float = 5.0) -> None:+ """Drain the queue. Called at interpreter exit."""+ if not self.enabled:+ return+ deadline = time.monotonic() + timeout+ while not self._queue.empty() and time.monotonic() < deadline:+ time.sleep(0.05)++ def close(self) -> None:+ self.flush()+ self._stop.set()++ def stats(self) -> dict[str, int]:+ """Counters, so an operator can tell a silent SDK from an idle one."""+ c = self._counters+ return {+ "emitted": c.emitted,+ "sent": c.sent,+ "dropped_queue_full": c.dropped_queue_full,+ "failed_transport": c.failed_transport,+ }++ # ── internals ─────────────────────────────────────────────────────────++ def _emit(self, target: str, payload: dict[str, Any]) -> bool:+ if not self.enabled:+ return False+ envelope = {+ "agent_id": self.agent_id,+ "agent_name": self.agent_name or self.agent_id,+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ **{k: v for k, v in payload.items() if v is not None},+ }+ self._counters.emitted += 1+ try:+ self._queue.put_nowait((target, envelope))+ except queue.Full:+ # Drop the oldest rather than the newest: recent agent behaviour is+ # more useful to a detection than a span from 30 seconds ago.+ self._counters.dropped_queue_full += 1+ try:+ self._queue.get_nowait()+ self._queue.put_nowait((target, envelope))+ except (queue.Empty, queue.Full):+ return False+ return True++ def _drain(self) -> None:+ """Background worker. Must never raise out of this thread."""+ while not self._stop.is_set():+ batches: dict[str, list[dict[str, Any]]] = {}+ deadline = time.monotonic() + _FLUSH_INTERVAL_SECONDS+ while len(batches.get(self.endpoint, [])) < _BATCH_SIZE and time.monotonic() < deadline:+ try:+ target, envelope = self._queue.get(timeout=0.2)+ except queue.Empty:+ continue+ batches.setdefault(target, []).append(envelope)++ for target, spans in batches.items():+ if spans:+ self._post(target, spans)++ def _post(self, target: str, spans: list[dict[str, Any]]) -> None:+ body = json.dumps(spans).encode("utf-8")+ request = urllib.request.Request( # noqa: S310 — operator-configured URL+ target,+ data=body,+ headers={"Content-Type": "application/json", "User-Agent": "aisoc-ai-sdk"},+ method="POST",+ )+ try:+ with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response: # noqa: S310+ if 200 <= response.status < 300:+ self._counters.sent += len(spans)+ else:+ self._counters.failed_transport += len(spans)+ except (urllib.error.URLError, OSError, ValueError) as exc:+ # Instrumentation must not surface a transport problem into the+ # host application's control flow.+ self._counters.failed_transport += len(spans)+ logger.debug("aisoc_ai: dropped %d span(s): %s", len(spans), exc)diff --git a/packages/aisoc-ai-sdk/aisoc_ai/redaction.py b/packages/aisoc-ai-sdk/aisoc_ai/redaction.pynew file mode 100644index 000000000..98b4cc076--- /dev/null+++ b/packages/aisoc-ai-sdk/aisoc_ai/redaction.py@@ -0,0 +1,101 @@+"""Redaction for AI telemetry, applied before anything leaves the process.++Prompts and model responses are the most sensitive payload in an AI estate.+They routinely contain whatever the user pasted in, whatever a retrieval step+pulled out of an internal store, and whatever the model then said about it. A+SOC needs to detect abuse of the AI without becoming the largest single+collection of that text in the organisation.++So the default is to send a hash and a length, never the content. That is+enough to answer the questions detection actually asks — is this the same+prompt we saw fifty times in the last minute, did the response body change+after an injection attempt, is this prompt anomalously long for this agent —+without retaining the text.++Full capture exists because incident response sometimes genuinely needs the+words, but it is opt-in per call site and per deployment, and even then the+common secret shapes are masked first. Opting in is a decision someone should+have to make deliberately rather than inherit from a default.+"""++from __future__ import annotations++import hashlib+import re+from dataclasses import dataclass+from enum import Enum+++class CaptureMode(str, Enum):+ """How much of a prompt or response leaves the process."""++ #: Hash and length only. The default.+ HASHED = "hashed"+ #: Content included, with secret-shaped substrings masked.+ MASKED = "masked"+ #: Content included verbatim. Requires an explicit opt-in.+ FULL = "full"+++#: Patterns masked before any content is sent, in MASKED mode.+#:+#: Deliberately narrow and high-confidence. A greedy redactor that mangles+#: ordinary prose trains people to turn redaction off, which is a worse+#: outcome than a narrow one that they leave on.+_SECRET_PATTERNS: tuple[tuple[str, re.Pattern[str]], None | str] | tuple = (+ ("aws_access_key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),+ ("github_token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b")),+ ("openai_key", re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b")),+ ("slack_token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}\b")),+ ("private_key", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----")),+ ("jwt", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b")),+ ("email", re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]{2,}\b")),+ ("credit_card", re.compile(r"\b(?:\d[ -]*?){13,16}\b")),+)+++@dataclass(frozen=True)+class RedactedText:+ """What the SDK will actually transmit for a prompt or response."""++ sha256: str+ length: int+ #: Present only when the caller opted into MASKED or FULL.+ content: str | None = None+ #: Names of the secret patterns that matched, in MASKED mode. Useful on+ #: its own: "this prompt contained an AWS key" is a finding even when the+ #: key itself is never sent.+ redacted_kinds: tuple[str, ...] = ()+++def redact(text: str | None, mode: CaptureMode = CaptureMode.HASHED) -> RedactedText:+ """Reduce `text` to what may leave the process under `mode`."""+ if text is None:+ return RedactedText(sha256="", length=0)++ digest = hashlib.sha256(text.encode("utf-8", errors="replace")).hexdigest()++ if mode is CaptureMode.HASHED:+ return RedactedText(sha256=digest, length=len(text))++ if mode is CaptureMode.FULL:+ return RedactedText(sha256=digest, length=len(text), content=text)++ masked = text+ kinds: list[str] = []+ for name, pattern in _SECRET_PATTERNS:+ masked, count = pattern.subn(f"[redacted:{name}]", masked)+ if count:+ kinds.append(name)+ return RedactedText(sha256=digest, length=len(text), content=masked, redacted_kinds=tuple(kinds))+++def secret_kinds(text: str | None) -> tuple[str, ...]:+ """Which secret shapes appear in `text`, without returning any of it.++ Callable in HASHED mode, where the content is never transmitted: knowing a+ prompt contained a private key is actionable even if the SOC never sees it.+ """+ if not text:+ return ()+ return tuple(name for name, pattern in _SECRET_PATTERNS if pattern.search(text))diff --git a/packages/aisoc-ai-sdk/pyproject.toml b/packages/aisoc-ai-sdk/pyproject.tomlnew file mode 100644index 000000000..b2479a33c--- /dev/null+++ b/packages/aisoc-ai-sdk/pyproject.toml@@ -0,0 +1,34 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "aisoc-ai-sdk"+version = "0.1.0"+description = "Emit AI runtime telemetry — agent tool calls, model invocations, guardrail findings — to AiSOC"+readme = "README.md"+license = { text = "MIT" }+authors = [+ { name = "Beenu Arora", email = "[email protected]" },+]+keywords = ["aisoc", "soc", "security", "ai-security", "llm", "agents", "mcp", "ai-spm"]+classifiers = [+ "Development Status :: 3 - Alpha",+ "Intended Audience :: Developers",+ "License :: OSI Approved :: MIT License",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ "Topic :: Security",+]+requires-python = ">=3.11"+# Deliberately zero dependencies. This runs inside somebody else's agent+# process, so it must not drag a transport library into their resolution.+dependencies = []++[project.urls]+Homepage = "https://github.com/beenuar/AiSOC"+Source = "https://github.com/beenuar/AiSOC/tree/main/packages/aisoc-ai-sdk"++[tool.hatch.build.targets.wheel]+packages = ["aisoc_ai"]diff --git a/packages/aisoc-ai-sdk/tests/test_ai_sdk.py b/packages/aisoc-ai-sdk/tests/test_ai_sdk.pynew file mode 100644index 000000000..d0d755994--- /dev/null+++ b/packages/aisoc-ai-sdk/tests/test_ai_sdk.py@@ -0,0 +1,207 @@+"""The SDK runs inside somebody else's agent, so its failure modes matter most.++Two properties are non-negotiable and get the most coverage here.++**Prompt content does not leave the process by default.** Prompts and model+responses routinely contain whatever a user pasted in and whatever a retrieval+step pulled out of an internal store. A SOC needs to detect abuse of the AI+without becoming the largest single collection of that text in the company.++**Instrumentation never breaks the host application.** A network failure, a bad+token or an unreachable AiSOC must degrade to a dropped span, never to an+exception escaping into the caller's request path.+"""++from __future__ import annotations++import json++import pytest+from aisoc_ai import AiSocAiClient, CaptureMode, redact, secret_kinds++RUNTIME = "https://aisoc.example.com/v1/inbox/runtime-token"+FINDINGS = "https://aisoc.example.com/v1/inbox/finding-token"+++def client(monkeypatch: pytest.MonkeyPatch):+ """A client whose background worker is replaced by a capture list."""+ sent: list[tuple[str, list[dict]]] = []++ monkeypatch.setattr(AiSocAiClient, "_drain", lambda self: None)+ c = AiSocAiClient(endpoint=RUNTIME, finding_endpoint=FINDINGS, agent_id="support-bot")+ monkeypatch.setattr(c, "_post", lambda target, spans: sent.append((target, spans)))++ def _drain_now():+ batches: dict[str, list[dict]] = {}+ while not c._queue.empty():+ target, envelope = c._queue.get_nowait()+ batches.setdefault(target, []).append(envelope)+ for target, spans in batches.items():+ c._post(target, spans)+ return sent++ c.drain_now = _drain_now # type: ignore[attr-defined]+ return c+++# ── redaction ─────────────────────────────────────────────────────────────+++def test_prompt_content_is_not_transmitted_by_default():+ """The single most important property in this package."""+ result = redact("the user's private medical history", CaptureMode.HASHED)+ assert result.content is None+ assert result.sha256+ assert result.length == len("the user's private medical history")+++def test_the_same_prompt_hashes_the_same_way():+ """Repeat detection is the point of sending a hash at all."""+ assert redact("abc").sha256 == redact("abc").sha256+ assert redact("abc").sha256 != redact("abd").sha256+++def test_masked_mode_removes_secret_shapes():+ result = redact("key AKIAIOSFODNN7EXAMPLE and sk-abcdefghijklmnopqrstuv", CaptureMode.MASKED)+ assert "AKIAIOSFODNN7EXAMPLE" not in (result.content or "")+ assert "sk-abcdefghijklmnopqrstuv" not in (result.content or "")+ assert set(result.redacted_kinds) == {"aws_access_key", "openai_key"}+++def test_full_mode_is_verbatim():+ """It exists for incident response, and must not silently half-redact."""+ text = "AKIAIOSFODNN7EXAMPLE"+ assert redact(text, CaptureMode.FULL).content == text+++def test_secret_shapes_are_detectable_without_sending_content():+ """ "This prompt contained a private key" is a finding on its own."""+ assert "private_key" in secret_kinds("-----BEGIN RSA PRIVATE KEY-----\nabc")+ assert secret_kinds("nothing sensitive here") == ()+++def test_none_and_empty_text_are_handled():+ assert redact(None).sha256 == ""+ assert redact(None).length == 0+ assert secret_kinds(None) == ()+ assert redact("", CaptureMode.MASKED).content == ""+++def test_a_model_call_sends_a_digest_not_the_prompt(client):+ client.model_call(+ "gpt-4o",+ prompt="patient record for [email protected]",+ response="summary text",+ prompt_tokens=120,+ )+ (_target, spans) = client.drain_now()[0]+ span = spans[0]+ assert "prompt" not in span+ assert "response" not in span+ assert span["prompt_sha256"]+ assert span["prompt_length"] == len("patient record for [email protected]")+ # And the fact it contained an email is still reported.+ assert "email" in span["prompt_secret_kinds"]+++def test_opting_into_capture_includes_masked_content(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(AiSocAiClient, "_drain", lambda self: None)+ sent: list = []+ c = AiSocAiClient(endpoint=RUNTIME, agent_id="a", capture=CaptureMode.MASKED)+ monkeypatch.setattr(c, "_post", lambda target, spans: sent.append(spans))+ c.model_call("gpt-4o", prompt="token AKIAIOSFODNN7EXAMPLE")+ target, envelope = c._queue.get_nowait()+ c._post(target, [envelope])+ assert "[redacted:aws_access_key]" in sent[0][0]["prompt"]+++# ── the routine / finding split ───────────────────────────────────────────+++def test_a_finding_goes_to_the_finding_endpoint(client):+ """Findings normalize to OCSF 2001 and are always promoted.++ Sending one to the runtime endpoint would normalize it as category 6 API+ Activity, which the promoter leaves in the lake — silently downgrading a+ detected injection into routine telemetry.+ """+ client.finding("prompt_injection", "Instruction override in retrieved doc")+ (target, spans) = client.drain_now()[0]+ assert target == FINDINGS+ assert spans[0]["finding_type"] == "prompt_injection"+++def test_a_tool_call_goes_to_the_runtime_endpoint(client):+ client.tool_call("search_tickets")+ (target, _spans) = client.drain_now()[0]+ assert target == RUNTIME+++def test_a_finding_without_a_finding_endpoint_warns(monkeypatch: pytest.MonkeyPatch, caplog):+ """Falling back is a real downgrade, so it must be loud."""+ monkeypatch.setattr(AiSocAiClient, "_drain", lambda self: None)+ c = AiSocAiClient(endpoint=RUNTIME, agent_id="a")+ monkeypatch.setattr(c, "_post", lambda target, spans: None)+ with caplog.at_level("WARNING"):+ c.finding("prompt_injection", "x")+ assert "will not be promoted" in caplog.text+++# ── tool-call argument handling ───────────────────────────────────────────+++def test_tool_argument_keys_are_sent_but_not_values(client):+ """Which parameters were used is the signal; the values are the risk."""+ client.tool_call("run_query", arguments={"sql": "SELECT * FROM patients", "limit": 10})+ (_target, spans) = client.drain_now()[0]+ span = spans[0]+ assert span["argument_keys"] == ["limit", "sql"]+ assert "SELECT * FROM patients" not in json.dumps(span)+++def test_on_behalf_of_is_carried(client):+ """An agent acting autonomously and one acting for a user differ in risk."""+ client.tool_call("delete_records", on_behalf_of="[email protected]")+ (_target, spans) = client.drain_now()[0]+ assert spans[0]["on_behalf_of"] == "[email protected]"+++# ── never break the host application ──────────────────────────────────────+++def test_no_endpoint_disables_rather_than_raising():+ """An unset endpoint is how an operator turns the SDK off."""+ c = AiSocAiClient(endpoint="", agent_id="a")+ assert c.enabled is False+ assert c.tool_call("anything") is False+++def test_a_transport_failure_does_not_raise(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(AiSocAiClient, "_drain", lambda self: None)+ c = AiSocAiClient(endpoint=RUNTIME, agent_id="a")++ def _boom(request, timeout=None): # noqa: ANN001+ raise OSError("connection refused")++ monkeypatch.setattr("urllib.request.urlopen", _boom)+ c.tool_call("search")+ target, envelope = c._queue.get_nowait()+ c._post(target, [envelope]) # must not raise+ assert c.stats()["failed_transport"] == 1+++def test_a_full_queue_drops_rather_than_growing(monkeypatch: pytest.MonkeyPatch):+ """Unbounded buffering inside a customer's process is the worse failure."""+ monkeypatch.setattr(AiSocAiClient, "_drain", lambda self: None)+ c = AiSocAiClient(endpoint=RUNTIME, agent_id="a")+ for i in range(1200):+ c.tool_call(f"tool-{i}")+ assert c._queue.qsize() <= 1000+ assert c.stats()["dropped_queue_full"] > 0+++def test_counters_make_a_silent_sdk_diagnosable(client):+ client.tool_call("a")+ client.tool_call("b")+ assert client.stats()["emitted"] == 2diff --git a/plugins/ai-gateway/plugin.yaml b/plugins/ai-gateway/plugin.yamlnew file mode 100644index 000000000..523d65057--- /dev/null+++ b/plugins/ai-gateway/plugin.yaml@@ -0,0 +1,40 @@+id: ai-gateway+name: AI Gateway / MCP Runtime+version: "1.0.0"+plugin_type: connector+tier: stable+description: >+ Pulls request logs from an LLM gateway or MCP server (LiteLLM, Portkey,+ Helicone, or an in-house proxy) so a SOC can see which agents call which+ tools and models, on whose behalf. One connector covers every application+ behind the gateway, which matters because the apps most in need of+ visibility are the ones nobody will retrofit an SDK into. For applications+ you do control, packages/aisoc-ai-sdk is the lower-friction push path.+ Routine activity is archived to the event lake and hunted; a guardrail+ violation becomes an alert.+author: AiSOC Core Team+tags: [ai, ai-spm, llm, agents, mcp, guardrails, runtime, connector]+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/ai_gateway.py+license: MIT+min_aisoc_version: "8.0.0"+config_schema:+ type: object+ required: [base_url, api_key]+ properties:+ base_url:+ type: string+ description: "Gateway base URL including scheme (e.g. https://llm-gateway.internal)"+ api_key:+ type: string+ description: "Gateway API key with read access to request logs"+ secret: true+ approved_models:+ type: string+ description: >+ Comma-separated list of approved models. Any model outside the list+ raises an unapproved_model finding. Leave blank to disable the check+ rather than flag every model.+ verify_tls:+ type: boolean+ default: true+ description: "Disable only for an internal gateway using a private CA"diff --git a/scripts/build_quarantine_index.py b/scripts/build_quarantine_index.pyindex 65bcfe58e..9c2d1e698 100644--- a/scripts/build_quarantine_index.py+++ b/scripts/build_quarantine_index.py@@ -193,10 +193,7 @@ def _render_mitre_lines(rules: Iterable[QuarantineRule]) -> list[str]:return ["_(No MITRE technique tags on the rules in this category.)_"]out = []for technique, count in counter.most_common(TOP_MITRE_PER_CATEGORY):- out.append(- f"- [`{technique}`](https://attack.mitre.org/techniques/{technique}/) "- f"— {count:,} rule{'s' if count != 1 else ''}"- )+ out.append(f"- [`{technique}`](https://attack.mitre.org/techniques/{technique}/) " f"— {count:,} rule{'s' if count != 1 else ''}")extra = len(counter) - TOP_MITRE_PER_CATEGORYif extra > 0:out.append(f"- _… and {extra:,} more techniques._")@@ -277,13 +274,31 @@ def render_readme(rules: list[QuarantineRule]) -> str:"category, references) is already populated.")lines.append(- "3. **Re-author the detection** under the right native bucket "- "(`detections/<category>/`) using the AiSOC schema documented in "- "[`apps/docs/docs/detections/`](../../../apps/docs/docs/detections/). "- "Map the SPL search to the AiSOC OCSF stream — usually a "- "`logsource` + `detection.condition` block. Carry the original "+ "3. **Re-author the detection as a Python spec**, not as YAML. This step "+ "used to say to write a `detection.condition` block under "+ "`detections/<category>/`, which does not work: everything under "+ "`detections/` is a *generated projection* of the spec modules and the "+ "engine never reads it. A rule authored that way passes CI, is counted "+ "by the truth table, and is never loaded — 44 rules in the native tier "+ "are in exactly that state. Add an `S(...)` entry to the matching "+ "`scripts/detection_specs_part3_<category>.py` with a flat `match_when`, "+ "then run `python3 scripts/generate_detections.py` followed by "+ "`python3 scripts/export_detection_ruleset.py`. Carry the original ""`provenance.upstream_path` over so attribution is preserved.")+ lines.append(+ " - **Check every field name against the emitting connector's "+ "`normalize()` output.** `scripts/check_detection_fields.py` gates "+ "computed fields — counters, window sizes, allowlist booleans — which "+ "cannot fire at all, because nothing in the pipeline computes them. "+ "They need a windowed-engine rule or a fusion-time enrichment instead."+ )+ lines.append(+ " - **SPL with `| stats` or `| tstats` is not translatable to "+ "`match_when`.** Aggregation over a window belongs in "+ "`services/fusion/app/services/windowed_detection.py`, which today has "+ "three hardcoded rules and no loader. Skip those until it has one."+ )lines.append("4. **Add fixtures** under `detections/fixtures/positive/<rule-id>.json` ""and `detections/fixtures/negative/<rule-id>.json`. "@@ -319,10 +334,7 @@ def render_readme(rules: list[QuarantineRule]) -> str:"and commit the regenerated README to make CI green.")lines.append("")- lines.append(- "Two soft conventions sit on top of the gate (not machine-enforced "- "today, but expected for translation PRs):"- )+ lines.append("Two soft conventions sit on top of the gate (not machine-enforced " "today, but expected for translation PRs):")lines.append("")lines.append("- **Reference an umbrella tracking issue.** When you translate a "@@ -363,10 +375,7 @@ def render_readme(rules: list[QuarantineRule]) -> str:lines.append("---")lines.append("")- lines.append(- "_Generated by `scripts/build_quarantine_index.py`. "- f"Source: {len(rules):,} YAML rules in this directory._"- )+ lines.append("_Generated by `scripts/build_quarantine_index.py`. " f"Source: {len(rules):,} YAML rules in this directory._")lines.append("")return "\n".join(lines)@@ -421,10 +430,7 @@ def main(argv: list[str] | None = None) -> int:return 0README_PATH.write_text(rendered)- print(- f"wrote {README_PATH.relative_to(REPO_ROOT)} "- f"({len(rules):,} rules indexed, {len(rendered):,} bytes)."- )+ print(f"wrote {README_PATH.relative_to(REPO_ROOT)} " f"({len(rules):,} rules indexed, {len(rendered):,} bytes).")return 0diff --git a/scripts/check_detection_fields.py b/scripts/check_detection_fields.pynew file mode 100644index 000000000..5a577ab04--- /dev/null+++ b/scripts/check_detection_fields.py@@ -0,0 +1,310 @@+#!/usr/bin/env python3+"""CI gate: a detection rule must match on fields some connector actually emits.++The detection matcher does a plain `event.get(field)` against the flat,+connector-normalized dict recovered from `raw_data`. There is no dotted-path+traversal and no aliasing. So a rule that names a field no connector ever+produces reads `None`, fails its first clause, and can never fire — while+still being loaded by the engine, still passing fixture replay, and still+counting toward the published executable total.++It passes fixture replay because fixtures are *synthesized from the rule*:+`build_positive(when)` in `scripts/detection_specs_part3_helpers.py` derives a+field value from the operator in the clause, so replaying it against the same+`match_when` is a tautology. The fixture gate proves the matcher works. It says+nothing about whether the field exists.++This gate closes that hole. It collects the field namespace connectors emit and+reports any rule that references something outside it.++Because the namespace is recovered by static analysis rather than by running+every connector, it deliberately **over**-approximates: every string-literal+dict key in a connector module counts as emitted. A false pass is a rule this+gate failed to catch; a false failure would be a rule wrongly blocked. Given+the gate's job is to stop regressions rather than to prove the corpus clean,+over-approximating is the safe direction.++Ratchet, not a clean bill of health. The corpus already contains unreachable+rules, and blocking CI on all of them would either stop every unrelated PR or+invite someone to weaken the gate. `MAX_UNREACHABLE` pins the current count so+it can only go down, exactly like `scripts/check_claim_gate_matrix.py`.++Usage:+ python3 scripts/check_detection_fields.py # enforce the ratchet+ python3 scripts/check_detection_fields.py --list # name every rule+ python3 scripts/check_detection_fields.py --fields # dump the namespace+"""++from __future__ import annotations++import argparse+import ast+import json+import re+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+RULESET = ROOT / "services" / "fusion" / "app" / "data" / "detection_ruleset.json"+CONNECTORS = ROOT / "services" / "connectors" / "app" / "connectors"+#: The AI SDK is a first-party emitter too — it posts spans straight to an+#: inbox token, so the fields it produces are as real as a connector's.+AI_SDK = ROOT / "packages" / "aisoc-ai-sdk" / "aisoc_ai"+TEMPLATES = ROOT / "services" / "ingest" / "internal" / "normalizer" / "templates"+NORMALIZER = ROOT / "services" / "ingest" / "internal" / "normalizer" / "normalizer.go"++#: Current number of engine-loaded rules that depend on a DERIVED or STATEFUL+#: field. This may only ever decrease. Lower it in the same PR that fixes+#: rules; never raise it to make a red build green.+MAX_UNREACHABLE = 138++#: Fields that no telemetry carries because they are computed, not observed:+#: sliding-window counters, allowlist membership, privilege flags, and+#: actor/target comparisons. A rule naming one of these cannot fire no matter+#: which connector is attached, because nothing computes it.+#:+#: They need one of two things that do not exist yet: evaluation in+#: `services/fusion/app/services/windowed_detection.py` (which has three+#: hardcoded rules and no loader), or a fusion-time enrichment step that+#: resolves the predicate. Until then they are honest work items.+_DERIVED_FIELD_PATTERN = re.compile(+ r"(_count$|^count_|_per_|time_window|_window_"+ r"|_in_allowlist$|_not_in_allowlist$"+ r"|_priv$|_is_admin$|_is_dc$|_eq_|_neq|^is_"+ r"|_age_days$|_age_hours$|_ratio$|_percent$"+ r"|^active_|_baseline|_is_first_|_seen_before$|_deviation)"+)++#: Operator suffixes the matcher strips to recover the field name. Order+#: matters: longer suffixes must be tried first so `not_contains_any` is not+#: shortened to `contains_any`. Mirrors `OPERATORS` in+#: `services/fusion/app/services/detection_matcher.py`.+_OPERATOR_SUFFIXES = (+ "not_contains_any",+ "not_startswith_any",+ "not_endswith_any",+ "not_startswith",+ "not_endswith",+ "contains_any",+ "contains_all",+ "pattern_match_any",+ "pattern_match",+ "startswith_any",+ "startswith",+ "endswith_any",+ "endswith",+ "match_any",+ "has_any",+ "not_in",+ "contains",+ "match",+ "gte",+ "lte",+ "in",+ "gt",+ "lt",+)++#: Fields the platform synthesizes rather than a connector emitting them:+#: fusion enrichment, the windowed engine's counters, and OCSF top-level keys+#: the engine falls back to when `raw_data` is absent.+_PLATFORM_FIELDS = frozenset(+ {+ "severity",+ "severity_id",+ "class_uid",+ "category_uid",+ "activity_id",+ "connector_type",+ "source",+ "tenant_id",+ "event_time",+ "time",+ "message",+ "raw_data",+ "raw_event",+ "title",+ "description",+ "external_id",+ "created_at",+ }+)+++def _strip_operator(key: str) -> str:+ for suffix in _OPERATOR_SUFFIXES:+ if key.endswith("_" + suffix):+ return key[: -len(suffix) - 1]+ return key+++def _rule_fields(match_when: dict) -> set[str]:+ """Field names a `match_when` clause reads, descending into any_of/all_of."""+ found: set[str] = set()+ for key, value in match_when.items():+ if key in {"any_of", "all_of"}:+ if isinstance(value, list):+ for sub in value:+ if isinstance(sub, dict):+ found |= _rule_fields(sub)+ continue+ found.add(_strip_operator(key))+ return found+++def _connector_namespace() -> set[str]:+ """Every string-literal dict key appearing in a connector module.++ Static over-approximation, by design: see the module docstring. Parsing the+ AST rather than regexing means a key split across lines or built with an+ f-string prefix is still picked up as a literal where one exists.+ """+ namespace: set[str] = set(_PLATFORM_FIELDS)+ sources = list(CONNECTORS.rglob("*.py"))+ if AI_SDK.is_dir():+ sources += list(AI_SDK.rglob("*.py"))+ for path in sorted(sources):+ try:+ tree = ast.parse(path.read_text(encoding="utf-8"))+ except (SyntaxError, OSError):+ continue+ for node in ast.walk(tree):+ if isinstance(node, ast.Dict):+ for key in node.keys:+ if isinstance(key, ast.Constant) and isinstance(key.value, str):+ namespace.add(key.value)+ # `d["key"] = v` and `d.get("key")` also declare a field name.+ elif isinstance(node, ast.Subscript) and isinstance(node.slice, ast.Constant):+ if isinstance(node.slice.value, str):+ namespace.add(node.slice.value)+ elif isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):+ if node.func.attr in {"get", "pop", "setdefault"} and node.args:+ first = node.args[0]+ if isinstance(first, ast.Constant) and isinstance(first.value, str):+ namespace.add(first.value)+ return namespace+++def _template_namespace() -> set[str]:+ """Source field names declared by inbox webhook templates.++ Read as text rather than with a YAML parser so this script has no+ third-party dependency; the shape is a flat `a.b.c: x.y.z` mapping.+ """+ namespace: set[str] = set()+ if not TEMPLATES.is_dir():+ return namespace+ for path in sorted(TEMPLATES.glob("*.yaml")):+ for line in path.read_text(encoding="utf-8").split("\n"):+ match = re.match(r"^\s{2,}([A-Za-z0-9_.]+)\s*:", line)+ if match:+ # Both ends of the mapping are legitimate field names: the left+ # is what arrives, the right is what the rule may match on.+ namespace.add(match.group(1).split(".")[-1])+ namespace.add(match.group(1))+ return namespace+++def _go_normalizer_namespace() -> set[str]:+ """Field names the Go OCSF normalizer maps, from its connectorProfiles."""+ namespace: set[str] = set()+ if not NORMALIZER.exists():+ return namespace+ for match in re.finditer(r'"([A-Za-z0-9_.]+)"\s*:\s*"([A-Za-z0-9_.]+)"', NORMALIZER.read_text(encoding="utf-8")):+ for side in match.groups():+ namespace.add(side)+ namespace.add(side.split(".")[-1])+ return namespace+++def scan() -> tuple[list[tuple[str, list[str]]], list[tuple[str, list[str]]], set[str], int]:+ """Returns (derived-field rules, vendor-field rules, namespace, total).++ Two classes, and only the first is a hard failure.++ **Derived / stateful** — the field is computed, not observed. No connector+ can ever supply it, so the rule is broken regardless of deployment. These+ are ratcheted.++ **Vendor payload** — the field is a real vendor key nested under+ `raw_event`. `DetectionEngine._raw_fields` merges that payload into the+ match namespace, so these are reachable whenever the attached vendor sends+ the field. Whether any given deployment does cannot be known statically,+ so these are reported for visibility rather than gated: failing on them+ would block correct rules for vendors nobody has connected yet.+ """+ if not RULESET.exists():+ print(f"ERROR: {RULESET.relative_to(ROOT)} missing — run scripts/export_detection_ruleset.py", file=sys.stderr)+ raise SystemExit(2)++ namespace = _connector_namespace() | _template_namespace() | _go_normalizer_namespace()+ rules = json.loads(RULESET.read_text(encoding="utf-8")).get("rules") or []++ derived: list[tuple[str, list[str]]] = []+ vendor: list[tuple[str, list[str]]] = []+ for rule in rules:+ missing = {f for f in _rule_fields(rule.get("match_when") or {}) if f not in namespace}+ if not missing:+ continue+ rule_id = str(rule.get("id", "?"))+ computed = sorted(f for f in missing if _DERIVED_FIELD_PATTERN.search(f))+ if computed:+ derived.append((rule_id, computed))+ else:+ vendor.append((rule_id, sorted(missing)))+ return derived, vendor, namespace, len(rules)+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--list", action="store_true", help="name every unreachable rule")+ parser.add_argument("--fields", action="store_true", help="dump the emitted field namespace")+ parser.add_argument(+ "--max-unreachable",+ type=int,+ default=MAX_UNREACHABLE,+ help=f"ratchet ceiling (default {MAX_UNREACHABLE})",+ )+ args = parser.parse_args()++ derived, vendor, namespace, total = scan()++ if args.fields:+ for name in sorted(namespace):+ print(name)+ return 0++ if args.list:+ print("# rules depending on a derived/stateful field (gated)")+ for rule_id, missing in derived:+ print(f"{rule_id}: {', '.join(missing)}")+ print("\n# rules depending on a vendor-payload field (informational)")+ for rule_id, missing in vendor:+ print(f"{rule_id}: {', '.join(missing)}")+ return 0++ print(f"detection fields: {total} engine rules examined")+ print(f" {len(derived)} depend on a derived/stateful field — cannot fire on any connector (gated)")+ print(f" {len(vendor)} reference a vendor-payload field — reachable when that vendor is attached")++ if len(derived) > args.max_unreachable:+ print(+ f"\nERROR: {len(derived)} rules depend on a computed field, over the ratchet "+ f"ceiling of {args.max_unreachable}.\n"+ "Such a field is never present in telemetry, so the rule cannot fire whatever\n"+ "is connected. Fixture replay will not catch it, because fixtures are\n"+ "synthesized from the rule being tested.\n"+ "Run with --list to see which. The fix is either a windowed-engine rule or a\n"+ "fusion-time enrichment that actually computes the predicate.",+ file=sys.stderr,+ )+ return 1++ if len(derived) < args.max_unreachable:+ print(f"\nThe ratchet can be tightened: lower MAX_UNREACHABLE to {len(derived)} " "in scripts/check_detection_fields.py.")++ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/detection_specs_part3_application.py b/scripts/detection_specs_part3_application.pyindex 6c7ffe5a1..25fa5aa6e 100644--- a/scripts/detection_specs_part3_application.py+++ b/scripts/detection_specs_part3_application.py@@ -19,66 +19,176 @@ from detection_specs_part3_helpers import ( # type: ignore[import-not-found]# Web-app attacks (15)# ---------------------------------------------------------------------------WEB_APP_RULES: list[dict] = [- S(slug="app-ssti-pattern", name="Server-Side Template Injection Pattern In Request",- severity="high", mitre=["t1190"], product="waf", service="http",- when={"event_type": "http_request", "body_contains_any": ["{{7*7}}", "${7*7}", "{%7*7%}", "<%= 7*7 %>"]},- fp=[FP_PENTEST], playbook="tpl-initial-access"),- S(slug="app-xxe-pattern", name="XML External Entity Reference In Request Body",- severity="high", mitre=["t1190"], product="waf", service="http",- when={"event_type": "http_request", "body_contains_any": ["<!ENTITY", "SYSTEM \"file://", "SYSTEM \"http://"]},- fp=["Approved XML SOAP integration"], playbook="tpl-initial-access"),- S(slug="app-nosql-injection", name="NoSQL Injection Operator In Request",- severity="high", mitre=["t1190"], product="waf", service="http",- when={"event_type": "http_request", "body_contains_any": ["$ne\":", "$gt\":", "$where\":", "$regex\":"]},- fp=[FP_PENTEST], playbook="tpl-initial-access"),- S(slug="app-graphql-introspection", name="GraphQL Introspection Query Against Production",- severity="medium", mitre=["t1213"], product="api-gateway", service="http",- when={"event_type": "http_request", "uri": "/graphql", "body_contains": "__schema", "environment": "prod"},- fp=["Approved schema documentation generator"], playbook="tpl-discovery"),- S(slug="app-graphql-deep-recursion", name="GraphQL Query With Excessive Recursion Depth",- severity="medium", mitre=["t1499"], product="api-gateway", service="http",- when={"event_type": "http_request", "uri": "/graphql", "query_depth_gt": 10},- fp=["Sanctioned bulk export"], playbook="tpl-impact"),- S(slug="app-jndi-log4shell", name="JNDI LDAP Lookup Pattern (Log4Shell-Style)",- severity="critical", mitre=["t1190"], product="waf", service="http",- when={"event_type": "http_request", "any_header_value_contains_any": ["${jndi:ldap://", "${jndi:rmi://", "${jndi:dns://"]},- fp=[FP_PENTEST], playbook="tpl-initial-access"),- S(slug="app-spring4shell-pattern", name="Spring4Shell Class Loader Manipulation Pattern",- severity="critical", mitre=["t1190"], product="waf", service="http",- when={"event_type": "http_request", "body_contains_any": ["class.module.classloader", "class.classLoader"]},- fp=[FP_PENTEST], playbook="tpl-initial-access"),- S(slug="app-deserialization-rce-marker", name="Java/.NET Deserialization Marker In Body",- severity="critical", mitre=["t1059"], product="waf", service="http",- when={"event_type": "http_request", "body_contains_any": ["rO0AB", "AAEAAAD/////AQAAAAAAAAAM", "TypeObject"]},- fp=["Inter-service signed payload (allow-listed)"], playbook="tpl-initial-access"),- S(slug="app-cookie-tampered-hmac", name="Session Cookie Failed HMAC Verification",- severity="medium", mitre=["t1185"], product="application", service="auth",- when={"event_type": "session_validate", "hmac_valid": False},- fp=["Stale cookie after key rotation"], playbook="tpl-credential-access"),- S(slug="app-account-enum-reset", name="High Volume Of Password Reset Requests From Single IP",- severity="medium", mitre=["t1110"], product="application", service="auth",- when={"event_type": "password_reset_request", "count_5min_per_ip_gt": 30},- fp=["Internal load test"], playbook="tpl-credential-access"),- S(slug="app-websocket-origin-bypass", name="WebSocket Upgrade From Cross-Origin Header",- severity="medium", mitre=["t1190"], product="application", service="ws",- when={"event_type": "ws_upgrade", "origin_matches_allowed_list": False},- fp=["Newly added integration partner (update allow-list)"], playbook="tpl-initial-access"),- S(slug="app-crlf-header-injection", name="CRLF Sequence In HTTP Header Value",- severity="high", mitre=["t1190"], product="waf", service="http",- when={"event_type": "http_request", "any_header_value_contains_any": ["%0d%0a", "\\r\\n"]},- fp=[FP_PENTEST], playbook="tpl-defense-evasion"),- S(slug="app-subdomain-takeover-cname", name="CNAME Pointing To Deleted SaaS Tenant",- severity="high", mitre=["t1583.001"], product="dns", service="resolver",- when={"event_type": "dns_response", "qtype": "CNAME", "target_endswith_any": [".herokudns.com", ".github.io", ".azurewebsites.net"], "target_resolves": False},- fp=["Pending tenant migration (verify ticket)"], playbook="tpl-initial-access"),- S(slug="app-cors-wildcard-with-creds", name="CORS Response With Wildcard Origin And Credentials Allowed",- severity="medium", mitre=["t1190"], product="application", service="http",- when={"event_type": "http_response", "header_access_control_allow_origin": "*", "header_access_control_allow_credentials": "true"},- fp=["Public unauthenticated API"], playbook="tpl-defense-evasion"),- S(slug="app-csp-disabled", name="Content-Security-Policy Header Removed From Production Response",- severity="medium", mitre=["t1190"], product="application", service="http",- when={"event_type": "http_response", "csp_header_present": False, "environment": "prod"},- fp=["Public marketing pages exempt from CSP"], playbook="tpl-defense-evasion"),+ S(+ slug="app-ssti-pattern",+ name="Server-Side Template Injection Pattern In Request",+ severity="high",+ mitre=["t1190"],+ product="waf",+ service="http",+ when={"event_type": "http_request", "body_contains_any": ["{{7*7}}", "${7*7}", "{%7*7%}", "<%= 7*7 %>"]},+ fp=[FP_PENTEST],+ playbook="tpl-initial-access",+ ),+ S(+ slug="app-xxe-pattern",+ name="XML External Entity Reference In Request Body",+ severity="high",+ mitre=["t1190"],+ product="waf",+ service="http",+ when={"event_type": "http_request", "body_contains_any": ["<!ENTITY", 'SYSTEM "file://', 'SYSTEM "http://']},+ fp=["Approved XML SOAP integration"],+ playbook="tpl-initial-access",+ ),+ S(+ slug="app-nosql-injection",+ name="NoSQL Injection Operator In Request",+ severity="high",+ mitre=["t1190"],+ product="waf",+ service="http",+ when={"event_type": "http_request", "body_contains_any": ['$ne":', '$gt":', '$where":', '$regex":']},+ fp=[FP_PENTEST],+ playbook="tpl-initial-access",+ ),+ S(+ slug="app-graphql-introspection",+ name="GraphQL Introspection Query Against Production",+ severity="medium",+ mitre=["t1213"],+ product="api-gateway",+ service="http",+ when={"event_type": "http_request", "uri": "/graphql", "body_contains": "__schema", "environment": "prod"},+ fp=["Approved schema documentation generator"],+ playbook="tpl-discovery",+ ),+ S(+ slug="app-graphql-deep-recursion",+ name="GraphQL Query With Excessive Recursion Depth",+ severity="medium",+ mitre=["t1499"],+ product="api-gateway",+ service="http",+ when={"event_type": "http_request", "uri": "/graphql", "query_depth_gt": 10},+ fp=["Sanctioned bulk export"],+ playbook="tpl-impact",+ ),+ S(+ slug="app-jndi-log4shell",+ name="JNDI LDAP Lookup Pattern (Log4Shell-Style)",+ severity="critical",+ mitre=["t1190"],+ product="waf",+ service="http",+ when={"event_type": "http_request", "any_header_value_contains_any": ["${jndi:ldap://", "${jndi:rmi://", "${jndi:dns://"]},+ fp=[FP_PENTEST],+ playbook="tpl-initial-access",+ ),+ S(+ slug="app-spring4shell-pattern",+ name="Spring4Shell Class Loader Manipulation Pattern",+ severity="critical",+ mitre=["t1190"],+ product="waf",+ service="http",+ when={"event_type": "http_request", "body_contains_any": ["class.module.classloader", "class.classLoader"]},+ fp=[FP_PENTEST],+ playbook="tpl-initial-access",+ ),+ S(+ slug="app-deserialization-rce-marker",+ name="Java/.NET Deserialization Marker In Body",+ severity="critical",+ mitre=["t1059"],+ product="waf",+ service="http",+ when={"event_type": "http_request", "body_contains_any": ["rO0AB", "AAEAAAD/////AQAAAAAAAAAM", "TypeObject"]},+ fp=["Inter-service signed payload (allow-listed)"],+ playbook="tpl-initial-access",+ ),+ S(+ slug="app-cookie-tampered-hmac",+ name="Session Cookie Failed HMAC Verification",+ severity="medium",+ mitre=["t1185"],+ product="application",+ service="auth",+ when={"event_type": "session_validate", "hmac_valid": False},+ fp=["Stale cookie after key rotation"],+ playbook="tpl-credential-access",+ ),+ S(+ slug="app-account-enum-reset",+ name="High Volume Of Password Reset Requests From Single IP",+ severity="medium",+ mitre=["t1110"],+ product="application",+ service="auth",+ when={"event_type": "password_reset_request", "count_5min_per_ip_gt": 30},+ fp=["Internal load test"],+ playbook="tpl-credential-access",+ ),+ S(+ slug="app-websocket-origin-bypass",+ name="WebSocket Upgrade From Cross-Origin Header",+ severity="medium",+ mitre=["t1190"],+ product="application",+ service="ws",+ when={"event_type": "ws_upgrade", "origin_matches_allowed_list": False},+ fp=["Newly added integration partner (update allow-list)"],+ playbook="tpl-initial-access",+ ),+ S(+ slug="app-crlf-header-injection",+ name="CRLF Sequence In HTTP Header Value",+ severity="high",+ mitre=["t1190"],+ product="waf",+ service="http",+ when={"event_type": "http_request", "any_header_value_contains_any": ["%0d%0a", "\\r\\n"]},+ fp=[FP_PENTEST],+ playbook="tpl-defense-evasion",+ ),+ S(+ slug="app-subdomain-takeover-cname",+ name="CNAME Pointing To Deleted SaaS Tenant",+ severity="high",+ mitre=["t1583.001"],+ product="dns",+ service="resolver",+ when={+ "event_type": "dns_response",+ "qtype": "CNAME",+ "target_endswith_any": [".herokudns.com", ".github.io", ".azurewebsites.net"],+ "target_resolves": False,+ },+ fp=["Pending tenant migration (verify ticket)"],+ playbook="tpl-initial-access",+ ),+ S(+ slug="app-cors-wildcard-with-creds",+ name="CORS Response With Wildcard Origin And Credentials Allowed",+ severity="medium",+ mitre=["t1190"],+ product="application",+ service="http",+ when={"event_type": "http_response", "header_access_control_allow_origin": "*", "header_access_control_allow_credentials": "true"},+ fp=["Public unauthenticated API"],+ playbook="tpl-defense-evasion",+ ),+ S(+ slug="app-csp-disabled",+ name="Content-Security-Policy Header Removed From Production Response",+ severity="medium",+ mitre=["t1190"],+ product="application",+ service="http",+ when={"event_type": "http_response", "csp_header_present": False, "environment": "prod"},+ fp=["Public marketing pages exempt from CSP"],+ playbook="tpl-defense-evasion",+ ),]@@ -86,54 +196,138 @@ WEB_APP_RULES: list[dict] = [# DevOps / CI / supply-chain (12)# ---------------------------------------------------------------------------DEVOPS_RULES: list[dict] = [- S(slug="app-ci-workflow-modified-by-non-owner", name="CI Workflow Modified By Account Without CODEOWNER Approval",- severity="high", mitre=["t1199"], product="github", service="repo",- when={"event_type": "push", "path_contains": ".github/workflows/", "approver_role_neq": "codeowner"},- fp=["Bootstrap of new repository"], playbook="tpl-supply-chain"),- S(slug="app-self-hosted-runner-external", name="Self-Hosted Runner Registered From External IP",- severity="critical", mitre=["t1199"], product="github", service="actions",- when={"event_type": "runner_register", "ip_is_internal": False},- fp=["Approved partner-hosted runner"], playbook="tpl-supply-chain"),- S(slug="app-build-signing-key-rotated", name="Build Artifact Signing Key Rotated Outside Maintenance Window",- severity="high", mitre=["t1554"], product="ci", service="signing",- when={"event_type": "key_rotation", "in_change_window": False},- fp=["Emergency key rotation (must be ticketed)"], playbook="tpl-supply-chain"),- S(slug="app-helm-chart-untrusted-repo", name="Helm Install From Unknown Chart Repository",- severity="high", mitre=["t1195.002"], product="kubernetes", service="helm",- when={"event_type": "helm_install", "repo_url_endswith_in_allow_list": False},- fp=["Pilot of new vendor chart"], playbook="tpl-supply-chain"),- S(slug="app-terraform-destroy-prod", name="terraform destroy Run Targeting Production Workspace",- severity="critical", mitre=["t1485"], product="terraform", service="cli",- when={"event_type": "terraform_run", "command": "destroy", "workspace_in": ["prod", "production"]},- fp=["Authorised infra teardown"], playbook="tpl-impact"),- S(slug="app-secret-published-to-slack", name="Newly Created Secret Has Slack Webhook Pattern",- severity="high", mitre=["t1078"], product="vault", service="secrets",- when={"event_type": "secret_create", "value_contains": "hooks.slack.com/services/"},- fp=["Approved alerting webhook"], playbook="tpl-credential-access"),- S(slug="app-deploy-key-added-github", name="SSH Deploy Key Added To GitHub Repository",- severity="medium", mitre=["t1098.004"], product="github", service="repo",- when={"event_type": "deploy_key.create"},- fp=["Sanctioned automation onboarding"], playbook="tpl-persistence"),- S(slug="app-npm-package-publish-new-account", name="NPM Package Published From New Account",- severity="high", mitre=["t1195.002"], product="npm", service="registry",- when={"event_type": "package_publish", "publisher_account_age_days_lt": 14, "package_visibility": "public"},- fp=["New maintainer onboarding"], playbook="tpl-supply-chain"),- S(slug="app-pypi-package-publish-new-ip", name="PyPI Package Published From New IP",- severity="medium", mitre=["t1195.002"], product="pypi", service="registry",- when={"event_type": "package_publish", "publisher_ip_seen_before": False},- fp=["New maintainer onboarding"], playbook="tpl-supply-chain"),- S(slug="app-docker-insecure-registry-flag", name="Docker Daemon Started With --insecure-registry Flag",- severity="medium", mitre=["t1195.002"], product="docker", service="dockerd",- when={"event_type": "daemon_config", "insecure_registries_count_gt": 0},- fp=["Internal mirror without TLS (deprecated, must be ticketed)"], playbook="tpl-supply-chain"),- S(slug="app-image-critical-cve-pushed", name="Container Image With Critical CVE Pushed To Prod Registry",- severity="high", mitre=["t1525"], product="container-registry", service="scan",- when={"event_type": "scan_result", "cvss_max_gte": 9.0, "registry_environment": "prod"},- fp=["Approved exception (must be ticketed)"], playbook="tpl-supply-chain"),- S(slug="app-protected-branch-disabled", name="Branch Protection Disabled On Protected Branch",- severity="high", mitre=["t1098.004"], product="github", service="repo",- when={"event_type_in": ["protected_branch.policy_override", "protected_branch.destroy"]},- fp=[FP_TUNING], playbook="tpl-supply-chain"),+ S(+ slug="app-ci-workflow-modified-by-non-owner",+ name="CI Workflow Modified By Account Without CODEOWNER Approval",+ severity="high",+ mitre=["t1199"],+ product="github",+ service="repo",+ when={"event_type": "push", "path_contains": ".github/workflows/", "approver_role_neq": "codeowner"},+ fp=["Bootstrap of new repository"],+ playbook="tpl-supply-chain",+ ),+ S(+ slug="app-self-hosted-runner-external",+ name="Self-Hosted Runner Registered From External IP",+ severity="critical",+ mitre=["t1199"],+ product="github",+ service="actions",+ when={"event_type": "runner_register", "ip_is_internal": False},+ fp=["Approved partner-hosted runner"],+ playbook="tpl-supply-chain",+ ),+ S(+ slug="app-build-signing-key-rotated",+ name="Build Artifact Signing Key Rotated Outside Maintenance Window",+ severity="high",+ mitre=["t1554"],+ product="ci",+ service="signing",+ when={"event_type": "key_rotation", "in_change_window": False},+ fp=["Emergency key rotation (must be ticketed)"],+ playbook="tpl-supply-chain",+ ),+ S(+ slug="app-helm-chart-untrusted-repo",+ name="Helm Install From Unknown Chart Repository",+ severity="high",+ mitre=["t1195.002"],+ product="kubernetes",+ service="helm",+ when={"event_type": "helm_install", "repo_url_endswith_in_allow_list": False},+ fp=["Pilot of new vendor chart"],+ playbook="tpl-supply-chain",+ ),+ S(+ slug="app-terraform-destroy-prod",+ name="terraform destroy Run Targeting Production Workspace",+ severity="critical",+ mitre=["t1485"],+ product="terraform",+ service="cli",+ when={"event_type": "terraform_run", "command": "destroy", "workspace_in": ["prod", "production"]},+ fp=["Authorised infra teardown"],+ playbook="tpl-impact",+ ),+ S(+ slug="app-secret-published-to-slack",+ name="Newly Created Secret Has Slack Webhook Pattern",+ severity="high",+ mitre=["t1078"],+ product="vault",+ service="secrets",+ when={"event_type": "secret_create", "value_contains": "hooks.slack.com/services/"},+ fp=["Approved alerting webhook"],+ playbook="tpl-credential-access",+ ),+ S(+ slug="app-deploy-key-added-github",+ name="SSH Deploy Key Added To GitHub Repository",+ severity="medium",+ mitre=["t1098.004"],+ product="github",+ service="repo",+ when={"event_type": "deploy_key.create"},+ fp=["Sanctioned automation onboarding"],+ playbook="tpl-persistence",+ ),+ S(+ slug="app-npm-package-publish-new-account",+ name="NPM Package Published From New Account",+ severity="high",+ mitre=["t1195.002"],+ product="npm",+ service="registry",+ when={"event_type": "package_publish", "publisher_account_age_days_lt": 14, "package_visibility": "public"},+ fp=["New maintainer onboarding"],+ playbook="tpl-supply-chain",+ ),+ S(+ slug="app-pypi-package-publish-new-ip",+ name="PyPI Package Published From New IP",+ severity="medium",+ mitre=["t1195.002"],+ product="pypi",+ service="registry",+ when={"event_type": "package_publish", "publisher_ip_seen_before": False},+ fp=["New maintainer onboarding"],+ playbook="tpl-supply-chain",+ ),+ S(+ slug="app-docker-insecure-registry-flag",+ name="Docker Daemon Started With --insecure-registry Flag",+ severity="medium",+ mitre=["t1195.002"],+ product="docker",+ service="dockerd",+ when={"event_type": "daemon_config", "insecure_registries_count_gt": 0},+ fp=["Internal mirror without TLS (deprecated, must be ticketed)"],+ playbook="tpl-supply-chain",+ ),+ S(+ slug="app-image-critical-cve-pushed",+ name="Container Image With Critical CVE Pushed To Prod Registry",+ severity="high",+ mitre=["t1525"],+ product="container-registry",+ service="scan",+ when={"event_type": "scan_result", "cvss_max_gte": 9.0, "registry_environment": "prod"},+ fp=["Approved exception (must be ticketed)"],+ playbook="tpl-supply-chain",+ ),+ S(+ slug="app-protected-branch-disabled",+ name="Branch Protection Disabled On Protected Branch",+ severity="high",+ mitre=["t1098.004"],+ product="github",+ service="repo",+ when={"event_type_in": ["protected_branch.policy_override", "protected_branch.destroy"]},+ fp=[FP_TUNING],+ playbook="tpl-supply-chain",+ ),]@@ -141,54 +335,138 @@ DEVOPS_RULES: list[dict] = [# SaaS / collaboration (12)# ---------------------------------------------------------------------------SAAS_RULES: list[dict] = [- S(slug="app-salesforce-mass-export", name="Salesforce Mass Data Export Initiated",- severity="high", mitre=["t1530"], product="salesforce", service="audit",- when={"event_type": "DataExport", "row_count_gt": 100000},- fp=["Approved data migration"], playbook="tpl-exfiltration"),- S(slug="app-salesforce-sandbox-refresh-anomaly", name="Salesforce Sandbox Refreshed Outside Change Window",- severity="medium", mitre=["t1199"], product="salesforce", service="audit",- when={"event_type": "SandboxRefresh", "in_change_window": False},- fp=["Emergency sandbox refresh (must be ticketed)"], playbook="tpl-defense-evasion"),- S(slug="app-workday-bank-info-changed", name="Workday Banking Info Changed Without HR Ticket",- severity="high", mitre=["t1098"], product="workday", service="audit",- when={"event_type": "BankAccountChange", "linked_ticket": False},- fp=["Self-service change with valid step-up auth"], playbook="tpl-impact"),- S(slug="app-zoom-recording-shared-external", name="Zoom Cloud Recording Shared Externally",- severity="medium", mitre=["t1530"], product="zoom", service="audit",- when={"event_type": "recording_share", "share_type": "external"},- fp=["Customer-facing webinar recording"], playbook="tpl-exfiltration"),- S(slug="app-box-public-link-mass-create", name="Box Created Many Public Links In Short Window",- severity="high", mitre=["t1567.002"], product="box", service="audit",- when={"event_type": "shared_link.create", "access": "open", "count_5min_per_user_gt": 20},- fp=["Marketing campaign content drop"], playbook="tpl-exfiltration"),- S(slug="app-notion-workspace-export", name="Notion Workspace Exported By Non-Admin",- severity="high", mitre=["t1530"], product="notion", service="audit",- when={"event_type": "workspace.export", "actor_is_admin": False},- fp=["Approved knowledge migration"], playbook="tpl-exfiltration"),- S(slug="app-confluence-space-export-bulk", name="Confluence Bulk Space Export",- severity="medium", mitre=["t1530"], product="confluence", service="audit",- when={"event_type": "space.export", "size_bytes_gt": 524288000},- fp=["Approved knowledge migration"], playbook="tpl-exfiltration"),- S(slug="app-servicenow-record-export-bulk", name="ServiceNow Bulk Record Export",- severity="medium", mitre=["t1530"], product="servicenow", service="audit",- when={"event_type": "record_export", "row_count_gt": 50000},- fp=["Approved reporting workflow"], playbook="tpl-exfiltration"),- S(slug="app-slack-file-shared-external", name="Slack File Shared To External Channel",- severity="medium", mitre=["t1567.002"], product="slack", service="audit",- when={"event_type": "file_shared", "channel_type": "external"},- fp=["Approved partner connect channel"], playbook="tpl-exfiltration"),- S(slug="app-slack-channel-public-conversion", name="Slack Private Channel Converted To Public",- severity="medium", mitre=["t1213"], product="slack", service="audit",- when={"event_type": "channel_convert_to_public"},- fp=["Approved transparency policy"], playbook="tpl-defense-evasion"),- S(slug="app-onedrive-anonymous-link-sensitive", name="OneDrive Anonymous Sharing Link Created For Sensitive File",- severity="high", mitre=["t1567.002"], product="m365", service="audit",- when={"event_type": "AnonymousLinkCreated", "sensitivity_label_in": ["Confidential", "Highly Confidential"]},- fp=["Approved external review"], playbook="tpl-exfiltration"),- S(slug="app-sharepoint-guest-tenantwide", name="SharePoint Tenant-Wide Guest Access Enabled",- severity="high", mitre=["t1078.004"], product="m365", service="audit",- when={"event_type": "TenantSettingChanged", "setting": "SharingCapability", "value": "ExternalUserSharingOnly"},- fp=["Approved tenant-level policy update"], playbook="tpl-defense-evasion"),+ S(+ slug="app-salesforce-mass-export",+ name="Salesforce Mass Data Export Initiated",+ severity="high",+ mitre=["t1530"],+ product="salesforce",+ service="audit",+ when={"event_type": "DataExport", "row_count_gt": 100000},+ fp=["Approved data migration"],+ playbook="tpl-exfiltration",+ ),+ S(+ slug="app-salesforce-sandbox-refresh-anomaly",+ name="Salesforce Sandbox Refreshed Outside Change Window",+ severity="medium",+ mitre=["t1199"],+ product="salesforce",+ service="audit",+ when={"event_type": "SandboxRefresh", "in_change_window": False},+ fp=["Emergency sandbox refresh (must be ticketed)"],+ playbook="tpl-defense-evasion",+ ),+ S(+ slug="app-workday-bank-info-changed",+ name="Workday Banking Info Changed Without HR Ticket",+ severity="high",+ mitre=["t1098"],+ product="workday",+ service="audit",+ when={"event_type": "BankAccountChange", "linked_ticket": False},+ fp=["Self-service change with valid step-up auth"],+ playbook="tpl-impact",+ ),+ S(+ slug="app-zoom-recording-shared-external",+ name="Zoom Cloud Recording Shared Externally",+ severity="medium",+ mitre=["t1530"],+ product="zoom",+ service="audit",+ when={"event_type": "recording_share", "share_type": "external"},+ fp=["Customer-facing webinar recording"],+ playbook="tpl-exfiltration",+ ),+ S(+ slug="app-box-public-link-mass-create",+ name="Box Created Many Public Links In Short Window",+ severity="high",+ mitre=["t1567.002"],+ product="box",+ service="audit",+ when={"event_type": "shared_link.create", "access": "open", "count_5min_per_user_gt": 20},+ fp=["Marketing campaign content drop"],+ playbook="tpl-exfiltration",+ ),+ S(+ slug="app-notion-workspace-export",+ name="Notion Workspace Exported By Non-Admin",+ severity="high",+ mitre=["t1530"],+ product="notion",+ service="audit",+ when={"event_type": "workspace.export", "actor_is_admin": False},+ fp=["Approved knowledge migration"],+ playbook="tpl-exfiltration",+ ),+ S(+ slug="app-confluence-space-export-bulk",+ name="Confluence Bulk Space Export",+ severity="medium",+ mitre=["t1530"],+ product="confluence",+ service="audit",+ when={"event_type": "space.export", "size_bytes_gt": 524288000},+ fp=["Approved knowledge migration"],+ playbook="tpl-exfiltration",+ ),+ S(+ slug="app-servicenow-record-export-bulk",+ name="ServiceNow Bulk Record Export",+ severity="medium",+ mitre=["t1530"],+ product="servicenow",+ service="audit",+ when={"event_type": "record_export", "row_count_gt": 50000},+ fp=["Approved reporting workflow"],+ playbook="tpl-exfiltration",+ ),+ S(+ slug="app-slack-file-shared-external",+ name="Slack File Shared To External Channel",+ severity="medium",+ mitre=["t1567.002"],+ product="slack",+ service="audit",+ when={"event_type": "file_shared", "channel_type": "external"},+ fp=["Approved partner connect channel"],+ playbook="tpl-exfiltration",+ ),+ S(+ slug="app-slack-channel-public-conversion",+ name="Slack Private Channel Converted To Public",+ severity="medium",+ mitre=["t1213"],+ product="slack",+ service="audit",+ when={"event_type": "channel_convert_to_public"},+ fp=["Approved transparency policy"],+ playbook="tpl-defense-evasion",+ ),+ S(+ slug="app-onedrive-anonymous-link-sensitive",+ name="OneDrive Anonymous Sharing Link Created For Sensitive File",+ severity="high",+ mitre=["t1567.002"],+ product="m365",+ service="audit",+ when={"event_type": "AnonymousLinkCreated", "sensitivity_label_in": ["Confidential", "Highly Confidential"]},+ fp=["Approved external review"],+ playbook="tpl-exfiltration",+ ),+ S(+ slug="app-sharepoint-guest-tenantwide",+ name="SharePoint Tenant-Wide Guest Access Enabled",+ severity="high",+ mitre=["t1078.004"],+ product="m365",+ service="audit",+ when={"event_type": "TenantSettingChanged", "setting": "SharingCapability", "value": "ExternalUserSharingOnly"},+ fp=["Approved tenant-level policy update"],+ playbook="tpl-defense-evasion",+ ),]@@ -196,10 +474,17 @@ SAAS_RULES: list[dict] = [# API misuse (1)# ---------------------------------------------------------------------------API_RULES: list[dict] = [- S(slug="app-graphql-mutation-anonymous", name="GraphQL Mutation Executed By Anonymous Caller",- severity="high", mitre=["t1190"], product="api-gateway", service="http",- when={"event_type": "graphql_op", "op_type": "mutation", "actor_authenticated": False},- fp=["Public mutation endpoint (allow-listed: subscribe / contact)"], playbook="tpl-initial-access"),+ S(+ slug="app-graphql-mutation-anonymous",+ name="GraphQL Mutation Executed By Anonymous Caller",+ severity="high",+ mitre=["t1190"],+ product="api-gateway",+ service="http",+ when={"event_type": "graphql_op", "op_type": "mutation", "actor_authenticated": False},+ fp=["Public mutation endpoint (allow-listed: subscribe / contact)"],+ playbook="tpl-initial-access",+ ),]@@ -213,53 +498,251 @@ API_RULES: list[dict] = [# detections — the SaaS-AI governance surface the leading platforms emphasise.# ---------------------------------------------------------------------------LLM_USAGE_RULES: list[dict] = [- S(slug="llm-api-key-created", name="LLM Provider API Key Created",- severity="medium", mitre=["t1098"], product="openai", service="audit",- when={"event_type_endswith": ".api_key.created"},- fp=["Planned key rotation (change ticket)", "New service onboarding"],- playbook="tpl-account-compromise"),- S(slug="llm-admin-key-created", name="LLM Provider Admin API Key Created",- severity="high", mitre=["t1098"], product="openai", service="audit",- when={"event_type_endswith": ".api_key.created", "key_scope": "admin"},- fp=["Documented break-glass admin key issuance"],- playbook="tpl-privilege-escalation"),- S(slug="llm-member-added-owner", name="LLM Provider Owner Role Granted",- severity="high", mitre=["t1098.003"], product="openai", service="audit",- when={"event_type_endswith": ".member.added", "role": "owner"},- fp=["Approved org owner change"], playbook="tpl-privilege-escalation"),- S(slug="llm-logging-disabled", name="LLM Provider Audit Logging Disabled",- severity="critical", mitre=["t1562.008"], product="openai", service="audit",- when={"event_type_contains": "logging", "action": "disabled"},- fp=["Vendor maintenance window (documented)"], playbook="tpl-defense-evasion"),- S(slug="llm-mfa-disabled", name="LLM Provider MFA Requirement Disabled",- severity="high", mitre=["t1556"], product="openai", service="audit",- when={"event_type_contains": "mfa", "action": "disabled"},- fp=["Approved auth-policy change"], playbook="tpl-defense-evasion"),- S(slug="llm-anthropic-workspace-created", name="Anthropic Workspace Created",- severity="low", mitre=["t1098"], product="anthropic", service="audit",- when={"event_type": "anthropic.workspace.created"},- fp=["Planned workspace provisioning"], playbook="tpl-triage"),- S(slug="llm-service-account-created", name="LLM Provider Service Account Created",- severity="medium", mitre=["t1136.003"], product="openai", service="audit",- when={"event_type_endswith": ".service_account.created"},- fp=["New automation onboarding (change ticket)"], playbook="tpl-persistence"),- S(slug="llm-project-deleted", name="LLM Provider Project Deleted",- severity="medium", mitre=["t1485"], product="openai", service="audit",- when={"event_type_endswith": ".project.archived"},- fp=["Planned project decommission"], playbook="tpl-triage"),+ S(+ slug="llm-api-key-created",+ name="LLM Provider API Key Created",+ severity="medium",+ mitre=["t1098"],+ product="openai",+ service="audit",+ when={"event_type_endswith": ".api_key.created"},+ fp=["Planned key rotation (change ticket)", "New service onboarding"],+ playbook="tpl-account-compromise",+ ),+ S(+ slug="llm-admin-key-created",+ name="LLM Provider Admin API Key Created",+ severity="high",+ mitre=["t1098"],+ product="openai",+ service="audit",+ when={"event_type_endswith": ".api_key.created", "key_scope": "admin"},+ fp=["Documented break-glass admin key issuance"],+ playbook="tpl-privilege-escalation",+ ),+ S(+ slug="llm-member-added-owner",+ name="LLM Provider Owner Role Granted",+ severity="high",+ mitre=["t1098.003"],+ product="openai",+ service="audit",+ when={"event_type_endswith": ".member.added", "role": "owner"},+ fp=["Approved org owner change"],+ playbook="tpl-privilege-escalation",+ ),+ S(+ slug="llm-logging-disabled",+ name="LLM Provider Audit Logging Disabled",+ severity="critical",+ mitre=["t1562.008"],+ product="openai",+ service="audit",+ when={"event_type_contains": "logging", "action": "disabled"},+ fp=["Vendor maintenance window (documented)"],+ playbook="tpl-defense-evasion",+ ),+ S(+ slug="llm-mfa-disabled",+ name="LLM Provider MFA Requirement Disabled",+ severity="high",+ mitre=["t1556"],+ product="openai",+ service="audit",+ when={"event_type_contains": "mfa", "action": "disabled"},+ fp=["Approved auth-policy change"],+ playbook="tpl-defense-evasion",+ ),+ S(+ slug="llm-anthropic-workspace-created",+ name="Anthropic Workspace Created",+ severity="low",+ mitre=["t1098"],+ product="anthropic",+ service="audit",+ when={"event_type": "anthropic.workspace.created"},+ fp=["Planned workspace provisioning"],+ playbook="tpl-triage",+ ),+ S(+ slug="llm-service-account-created",+ name="LLM Provider Service Account Created",+ severity="medium",+ mitre=["t1136.003"],+ product="openai",+ service="audit",+ when={"event_type_endswith": ".service_account.created"},+ fp=["New automation onboarding (change ticket)"],+ playbook="tpl-persistence",+ ),+ S(+ slug="llm-project-deleted",+ name="LLM Provider Project Deleted",+ severity="medium",+ mitre=["t1485"],+ product="openai",+ service="audit",+ when={"event_type_endswith": ".project.archived"},+ fp=["Planned project decommission"],+ playbook="tpl-triage",+ ),]# ---------------------------------------------------------------------------# Aggregate+# ----------------------------------------------------------------------------APPLICATION_EXTRA: list[dict] = (- WEB_APP_RULES- + DEVOPS_RULES- + SAAS_RULES- + API_RULES- + LLM_USAGE_RULES-)+# AI runtime detections — the customer's own agent / LLM / MCP estate.+#+# Distinct from LLM_USAGE_RULES above, and the distinction is the point. Those+# fire on an AI provider's *control plane*: who minted an API key, who was made+# an owner. Valuable, but it says nothing about what the agents did once+# running. These fire on runtime behaviour arriving from the `aisoc-ai-sdk`+# and the `ai-runtime` / `ai-finding` ingest templates.+#+# Every field below is one the SDK or a template actually emits. That is not a+# style note: the matcher does a flat `event.get(field)`, and 663 rules in this+# corpus were found matching on fields nothing produces — loaded by the engine,+# passing fixture replay (fixtures are synthesized from the rule), and unable+# to fire. `scripts/check_detection_fields.py` now gates that.+#+# Severity reflects what the signal means on its own, before triage. An agent+# reading a record it was designed to read is not an alert; an agent whose+# retrieved context tried to give it new instructions is.+# ---------------------------------------------------------------------------+AI_RUNTIME_RULES: list[dict] = [+ S(+ slug="ai-prompt-injection-detected",+ name="Prompt Injection Detected in AI Agent Context",+ severity="high",+ mitre=["t1059"],+ product="ai_guardrail",+ service="runtime",+ when={"finding_type": "prompt_injection"},+ fp=[+ "Security team testing the guardrail with a known payload",+ "A document legitimately quoting injection text, e.g. an awareness training page",+ ],+ playbook="tpl-triage",+ description=(+ "A guardrail flagged instruction-override content reaching an agent's context. "+ "Injection is the delivery mechanism for every other agent abuse, so this is "+ "the earliest point at which the chain is visible."+ ),+ ),+ S(+ slug="ai-agent-excessive-agency",+ name="AI Agent Took Action Beyond Its Granted Scope",+ severity="high",+ mitre=["t1078"],+ product="ai_guardrail",+ service="runtime",+ when={"finding_type": "excessive_agency"},+ fp=["Agent scope widened without the policy being updated to match"],+ playbook="tpl-privilege-escalation",+ description=(+ "The agent invoked a capability outside the scope it was granted. Unlike a "+ "compromised user, an agent has no intent to infer — a call outside its "+ "declared tool set is either a policy gap or someone steering it."+ ),+ ),+ S(+ slug="ai-sensitive-data-egress",+ name="Sensitive Data Left via an AI Agent",+ severity="critical",+ mitre=["t1567"],+ product="ai_guardrail",+ service="runtime",+ when={"finding_type": "sensitive_data_egress"},+ fp=["Approved data-processing workflow not yet added to the allowlist"],+ playbook="tpl-data-exfil",+ description=(+ "A guardrail matched sensitive content on its way out through an agent. An "+ "agent with retrieval access is an exfiltration path that authenticates as "+ "itself and looks like normal application traffic."+ ),+ ),+ S(+ slug="ai-unapproved-model",+ name="AI Agent Used an Unapproved Model",+ severity="medium",+ mitre=["t1078"],+ product="ai_guardrail",+ service="runtime",+ when={"finding_type": "unapproved_model"},+ fp=["Model newly approved but the inventory not yet updated"],+ playbook="tpl-triage",+ description=(+ "An agent called a model outside the approved set. Often benign drift, but it "+ "is also how data leaves a reviewed provider for an unreviewed one."+ ),+ ),+ S(+ slug="ai-tool-escalation",+ name="AI Agent Escalated to a Higher-Privilege Tool",+ severity="high",+ mitre=["t1548"],+ product="ai_guardrail",+ service="runtime",+ when={"finding_type": "tool_escalation"},+ fp=["Break-glass tool use during an incident, with a ticket"],+ playbook="tpl-privilege-escalation",+ ),+ S(+ slug="ai-shadow-agent-discovered",+ name="Undeclared AI Agent Observed",+ severity="medium",+ mitre=["t1078"],+ product="ai_guardrail",+ service="runtime",+ when={"finding_type": "shadow_ai"},+ fp=["A newly deployed agent that has not been registered yet"],+ playbook="tpl-triage",+ description=(+ "Telemetry arrived from an agent absent from the inventory. Shadow AI is the "+ "AI-estate equivalent of an unmanaged endpoint: it cannot be governed, and "+ "its access is unreviewed."+ ),+ ),+ S(+ slug="ai-prompt-contained-credential",+ name="Credential Material Present in an AI Prompt",+ severity="high",+ mitre=["t1552"],+ product="ai_runtime",+ service="runtime",+ when={"prompt_secret_kinds_has_any": ["aws_access_key", "github_token", "openai_key", "private_key", "slack_token"]},+ fp=["Security testing with a revoked key", "Developer pasting a sample key from documentation"],+ playbook="tpl-account-compromise",+ description=(+ "A secret shape appeared in a prompt. Detected without the prompt content "+ "ever being transmitted: the SDK reports which patterns matched while "+ "sending only a digest, so this fires even under the default hashed "+ "capture mode."+ ),+ ),+ S(+ slug="ai-agent-tool-call-failed-repeatedly",+ name="AI Agent Tool Call Denied",+ severity="low",+ mitre=["t1078"],+ product="ai_runtime",+ service="runtime",+ when={"outcome": "denied"},+ fp=["Agent retry logic against a transiently unavailable tool"],+ playbook="tpl-triage",+ description=(+ "A tool call was refused. Low on its own, and deliberately so — the value is "+ "as a building block once the windowed engine can express 'N denials in M "+ "minutes', which is the shape that distinguishes a probing agent from a "+ "misconfigured one."+ ),+ ),+]+++APPLICATION_EXTRA: list[dict] = WEB_APP_RULES + DEVOPS_RULES + SAAS_RULES + API_RULES + LLM_USAGE_RULES + AI_RUNTIME_RULES__all__ = [@@ -269,4 +752,5 @@ __all__ = ["SAAS_RULES","API_RULES","LLM_USAGE_RULES",+ "AI_RUNTIME_RULES",]diff --git a/scripts/detection_truth_table.py b/scripts/detection_truth_table.pyindex 985570297..ea623aafc 100644--- a/scripts/detection_truth_table.py+++ b/scripts/detection_truth_table.py@@ -14,12 +14,34 @@ coverage-mapping only), then renders an honest breakdown todrifts from the on-disk reality — so the headline number can never quietlydiverge from what actually runs.-A rule is EXECUTABLE when it is not quarantined (not under `_quarantine/`, not-`enabled: false`) AND its `detection` body is in a form the engine evaluates:-the native AiSOC `condition` DSL, a Sigma `selection`/`condition`, or one of the-runtime-engine languages. A rule is NON-EXECUTABLE when quarantined or when its-only body is an untranslated upstream language (`splunk_spl`, `chronicle_yaral`,-CAR pseudocode).+A rule is EXECUTABLE when the engine actually loads it — that is, when its id+appears in `services/fusion/app/data/detection_ruleset.json`, the compiled+ruleset `DetectionEngine` reads at startup.++That definition is deliberate, and it replaces an earlier one that classified a+rule by its file path and the key names inside its `detection:` body. The+earlier definition was wrong in a way that mattered, because the YAML under+`detections/` is a *generated projection* of the Python spec modules in+`scripts/detection_specs*.py` — the engine never reads it. So a rule could+carry `enabled: true` and a rendered `condition:` block, be counted here as+executable, and be entirely unknown to the engine. Three concrete cases this+file used to over-report:++* **77 imported Sigma rules** were counted because their body has a `selection`+ key. There is no Sigma evaluator anywhere in the repo.+* **44 native rules** have YAML and fixtures but no Python spec, so+ `export_detection_ruleset.py` never emitted them.+* The headline read **947** while the engine loaded **825**.++The practical consequence was worse than a wrong number: because the old+classifier keyed off `_quarantine/` membership, moving files out of quarantine+would have raised the published figure without changing what fires. A gate that+certifies a no-op is the specific failure this project's governance forbids, so+the count is now derived from the artifact the engine consumes.++Rules that look executable but are not loaded are reported separately as+`counted_but_not_loaded` rather than silently folded into either side — they+are real work items, and a reader deserves to see them.Usage:python3 scripts/detection_truth_table.py # regenerate the doc@@ -41,6 +63,10 @@ ROOT = Path(__file__).resolve().parent.parentDETECTIONS = ROOT / "detections"DOC = ROOT / "docs" / "detections" / "truth-table.md"+#: The compiled ruleset `services/fusion` loads at startup. This is the only+#: artifact that determines what fires, so it is the source of truth here.+RULESET = ROOT / "services" / "fusion" / "app" / "data" / "detection_ruleset.json"+# Directories under detections/ that are not rules.SKIP_DIRS = {"fixtures", "playbooks"}@@ -61,11 +87,43 @@ class Counts:by_tier: dict[str, int] = field(default_factory=dict)executable_by_tier: dict[str, int] = field(default_factory=dict)non_exec_reason: dict[str, int] = field(default_factory=dict)+ #: Rules whose body shape looks evaluable but whose id is absent from the+ #: compiled ruleset, so the engine has never seen them. Reported separately+ #: because they are the work items the old classifier was hiding.+ counted_but_not_loaded: int = 0+ not_loaded_by_tier: dict[str, int] = field(default_factory=dict)+ #: Ids present in the compiled ruleset with no corresponding YAML file.+ #: Should be zero; a non-zero value means the projection is out of sync.+ loaded_without_yaml: int = 0+ engine_rule_count: int = 0def bump(self, d: dict[str, int], key: str) -> None:d[key] = d.get(key, 0) + 1+def _engine_rule_ids() -> set[str]:+ """Ids the detection engine actually loads.++ An empty set is returned when the ruleset is missing, which makes the+ headline read zero rather than falling back to the body-shape heuristic.+ Reporting zero executable rules is loud and obviously wrong; quietly+ reverting to a heuristic that over-reports is not.+ """+ if not RULESET.exists():+ print(+ f"WARNING: {RULESET.relative_to(ROOT)} is missing — run "+ "scripts/export_detection_ruleset.py. Reporting zero executable rules.",+ file=sys.stderr,+ )+ return set()+ try:+ data = json.loads(RULESET.read_text(encoding="utf-8"))+ except (ValueError, OSError) as exc:+ print(f"WARNING: could not read {RULESET.relative_to(ROOT)}: {exc}", file=sys.stderr)+ return set()+ return {str(rule["id"]) for rule in data.get("rules") or [] if rule.get("id")}++def _tier_for(path: Path) -> str:rel = path.relative_to(DETECTIONS)top = rel.parts[0]@@ -116,6 +174,10 @@ def _iter_rule_files() -> list[Path]:def compute() -> Counts:counts = Counts()+ engine_ids = _engine_rule_ids()+ counts.engine_rule_count = len(engine_ids)+ seen_ids: set[str] = set()+for path in _iter_rule_files():counts.total += 1try:@@ -134,17 +196,31 @@ def compute() -> Counts:tier = _tier_for(path)counts.bump(counts.by_tier, tier)+ rule_id = str(data.get("id") or "")+ if rule_id:+ seen_ids.add(rule_id)++ # Engine membership decides executability. Everything else is a reason.+ if rule_id and rule_id in engine_ids:+ counts.executable += 1+ counts.bump(counts.executable_by_tier, tier)+ continue++ counts.non_executable += 1quarantined, reason = _is_quarantined(path, data)if quarantined:- counts.non_executable += 1counts.bump(counts.non_exec_reason, reason)- continue- if _has_executable_body(data):- counts.executable += 1- counts.bump(counts.executable_by_tier, tier)+ elif _has_executable_body(data):+ # The case the old classifier called executable: an enabled rule+ # with an evaluable-looking body that the engine does not load,+ # because no Python spec produced a `match_when` for it.+ counts.counted_but_not_loaded += 1+ counts.bump(counts.not_loaded_by_tier, tier)+ counts.bump(counts.non_exec_reason, "no_compiled_spec")else:- counts.non_executable += 1counts.bump(counts.non_exec_reason, "untranslated_upstream_language")++ counts.loaded_without_yaml = len(engine_ids - seen_ids)return counts@@ -156,27 +232,43 @@ def render_markdown(c: Counts) -> str:lines.append("> file in `validate-detections.yml`, so the numbers below can never quietly")lines.append("> diverge from what the engine actually runs. **Do not edit by hand.**")lines.append("")- lines.append("A rule is **executable** when it fires in AiSOC today: not quarantined")- lines.append("(`_quarantine/` or `enabled: false`) and its `detection` body is the native")- lines.append("AiSOC condition DSL, a Sigma selection/condition, or a runtime-engine language.")- lines.append("A rule is **non-executable** when quarantined or when its only body is an")- lines.append("untranslated upstream language (SPL / YARA-L / CAR pseudocode) — present for")- lines.append("provenance and coverage-mapping, not firing.")+ lines.append("A rule is **executable** when the detection engine actually loads it — when")+ lines.append("its id appears in `services/fusion/app/data/detection_ruleset.json`, the")+ lines.append("compiled ruleset `DetectionEngine` reads at startup.")+ lines.append("")+ lines.append("That is the only definition that means anything, because the YAML under")+ lines.append("`detections/` is a *generated projection* of the Python spec modules in")+ lines.append("`scripts/detection_specs*.py` — the engine never reads it. Editing a")+ lines.append("`condition:` block or flipping `enabled:` has no effect on what fires. The")+ lines.append("lever that reaches the engine is adding a spec and re-running")+ lines.append("`scripts/export_detection_ruleset.py`.")lines.append("")lines.append("## Headline")lines.append("")lines.append("| metric | count |")lines.append("|--------|------:|")lines.append(f"| rules on disk (total) | {c.total} |")- lines.append(f"| **executable (fire today)** | **{c.executable}** |")+ lines.append(f"| **executable (loaded by the engine)** | **{c.executable}** |")lines.append(f"| non-executable (provenance/coverage only) | {c.non_executable} |")+ lines.append(f"| — of which: enabled, but no compiled spec | {c.counted_but_not_loaded} |")lines.append("")+ if c.counted_but_not_loaded:+ lines.append(f"Those {c.counted_but_not_loaded} rules are the ones an earlier version of this")+ lines.append("table counted as executable. They carry `enabled: true` and a body whose")+ lines.append("shape looks evaluable, and the engine has never seen them because no spec")+ lines.append("produced a `match_when` for them. They are genuine work items, listed by")+ lines.append("tier below, not a rounding error.")+ lines.append("")+ if c.loaded_without_yaml:+ lines.append(f"**{c.loaded_without_yaml} ids are in the compiled ruleset with no YAML file.**")+ lines.append("The projection is out of sync — re-run `scripts/generate_detections.py`.")+ lines.append("")lines.append("## By tier")lines.append("")- lines.append("| tier | on disk | executable |")- lines.append("|------|--------:|-----------:|")+ lines.append("| tier | on disk | executable | enabled but not loaded |")+ lines.append("|------|--------:|-----------:|-----------------------:|")for tier in sorted(c.by_tier):- lines.append(f"| {tier} | {c.by_tier[tier]} | {c.executable_by_tier.get(tier, 0)} |")+ lines.append(f"| {tier} | {c.by_tier[tier]} | {c.executable_by_tier.get(tier, 0)} " f"| {c.not_loaded_by_tier.get(tier, 0)} |")lines.append("")lines.append("## Why rules are non-executable")lines.append("")@@ -186,6 +278,7 @@ def render_markdown(c: Counts) -> str:"quarantine_dir": "under `_quarantine/` (untranslated on import)","disabled": "`enabled: false`","untranslated_upstream_language": "body is an untranslated upstream language",+ "no_compiled_spec": "enabled, but no compiled spec — the engine does not load it","unparseable": "unparseable YAML",}for reason in sorted(c.non_exec_reason):@@ -197,10 +290,17 @@ def render_markdown(c: Counts) -> str:lines.append(f"The imported corpus is large ({c.total} rules on disk) and valuable as a")lines.append("provenance-tracked ATT&CK-mapped library, but the number that matters")lines.append(f"operationally is **{c.executable} executable rules** — the ones the engine")- lines.append("fires against live telemetry. The README and marketplace must cite the")- lines.append("executable figure when describing detection *coverage*, and may cite the")+ lines.append("loads and fires against live telemetry. The README and marketplace must cite")+ lines.append("the executable figure when describing detection *coverage*, and may cite the")lines.append("on-disk figure only when explicitly describing the imported *library*.")lines.append("")+ lines.append("Two things this table cannot tell you, stated so nobody infers them:")+ lines.append("")+ lines.append("1. A loaded rule still has to match on a field some connector emits. That")+ lines.append(" property is enforced separately by `scripts/check_detection_fields.py`.")+ lines.append("2. Executable is not the same as tuned. `false_positives:` is prose and is")+ lines.append(" not machine-checked; there is no per-rule false-positive-rate gate.")+ lines.append("")return "\n".join(lines)@@ -224,6 +324,10 @@ def main() -> int:"by_tier": counts.by_tier,"executable_by_tier": counts.executable_by_tier,"non_exec_reason": counts.non_exec_reason,+ "counted_but_not_loaded": counts.counted_but_not_loaded,+ "not_loaded_by_tier": counts.not_loaded_by_tier,+ "loaded_without_yaml": counts.loaded_without_yaml,+ "engine_rule_count": counts.engine_rule_count,},indent=2,sort_keys=True,diff --git a/services/connectors/app/connectors/__init__.py b/services/connectors/app/connectors/__init__.pyindex e1f0617db..8de7d55f1 100644--- a/services/connectors/app/connectors/__init__.py+++ b/services/connectors/app/connectors/__init__.py@@ -17,6 +17,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom app.connectors.abnormal_security import AbnormalSecurityConnector+from app.connectors.ai_gateway import AIGatewayConnectorfrom app.connectors.auditd import AuditdConnectorfrom app.connectors.auth0 import Auth0Connectorfrom app.connectors.aws_cloudtrail import AWSCloudTrailConnector@@ -150,6 +151,7 @@ _CONNECTOR_CLASSES: tuple[type[BaseConnector], ...] = (JumpCloudConnector,KubernetesAuditConnector,LaceworkConnector,+ AIGatewayConnector,LlmUsageConnector,M365AuditConnector,MicrosoftSentinelConnector,diff --git a/services/connectors/app/connectors/ai_gateway.py b/services/connectors/app/connectors/ai_gateway.pynew file mode 100644index 000000000..d14b96673--- /dev/null+++ b/services/connectors/app/connectors/ai_gateway.py@@ -0,0 +1,241 @@+"""AI gateway / MCP server runtime telemetry (pull side of the AI estate).++`llm_usage` covers the AI *control plane* — who minted an API key, who was made+an owner. This covers the runtime: which agents are calling which tools against+which resources, on whose behalf, and whether any guardrail objected.++Two ways telemetry arrives, and both land in the same OCSF shape:++* **Push**, via `aisoc-ai-sdk` posting spans to an inbox token with the+ `ai-runtime` / `ai-finding` templates. That is the low-friction path for an+ app the customer controls, and it needs no connector at all.+* **Pull**, this connector, for gateways that already aggregate AI traffic and+ expose a query API — LiteLLM, Portkey, Helicone, or an in-house proxy. An+ organisation that routes its models through a gateway gets coverage of every+ app behind it without instrumenting each one.++The pull path matters for the same reason an agentless scanner matters: the apps+you most need visibility into are the ones nobody will retrofit an SDK into.++Severity is derived, not trusted. A gateway reports usage; it has no opinion+about security. So a guardrail violation or a blocked request is raised here,+while routine completions stay `info` and are archived to the lake rather than+alerted on — the same routine/finding split the OCSF profiles encode.+"""++from __future__ import annotations++from typing import Any++import httpx+import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field++logger = structlog.get_logger()++_LIMIT = 200+_TIMEOUT = 30.0++#: Gateway outcome values that mean something refused the request. These are+#: the reason to pull at all: a gateway that blocked a call already made a+#: security decision, and the SOC should see it.+_BLOCKED_OUTCOMES = frozenset({"blocked", "denied", "rejected", "filtered", "guardrail_violation"})++#: Finding types the `ai-*` detection rules match on. Kept as a constant so the+#: mapping below and the specs in+#: `scripts/detection_specs_part3_application.py` cannot drift apart silently.+_FINDING_PROMPT_INJECTION = "prompt_injection"+_FINDING_UNAPPROVED_MODEL = "unapproved_model"+_FINDING_SENSITIVE_EGRESS = "sensitive_data_egress"+++class AIGatewayConnector(BaseConnector):+ """LLM gateway / MCP server request logs."""++ connector_id = "ai_gateway"+ connector_name = "AI Gateway / MCP Runtime"+ connector_category = "ai"++ def __init__(+ self,+ base_url: str,+ api_key: str,+ approved_models: str = "",+ verify_tls: bool = True,+ **_: Any,+ ) -> None:+ self._base_url = base_url.rstrip("/")+ self._api_key = api_key+ # Comma-separated, because the connector config UI collects a string.+ # An empty list means "do not judge", not "nothing is approved" — a+ # connector that alerted on every model until someone filled in a form+ # would be turned off within the hour.+ self._approved = {m.strip().lower() for m in approved_models.split(",") if m.strip()}+ self._verify_tls = verify_tls++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Pull request logs from an LLM gateway or MCP server (LiteLLM, Portkey, "+ "Helicone, or an in-house proxy) to see which agents call which tools and "+ "models, on whose behalf. Covers every app behind the gateway without "+ "instrumenting each one. For apps you control, the aisoc-ai-sdk push path "+ "is lower friction."+ ),+ docs_url="/docs/connectors/ai_gateway",+ capabilities=(Capability.PULL_ALERTS, Capability.PULL_AUDIT),+ fields=[+ Field("base_url", "string", "Gateway base URL", placeholder="https://llm-gateway.internal"),+ Field("api_key", "secret", "Gateway API key"),+ Field(+ "approved_models",+ "string",+ "Approved models (comma-separated)",+ required=False,+ placeholder="gpt-4o, claude-sonnet-4, llama-3.3-70b",+ help_text=(+ "Any model outside this list raises an unapproved_model finding. "+ "Leave blank to disable the check rather than flag everything."+ ),+ ),+ Field(+ "verify_tls",+ "boolean",+ "Verify TLS certificate",+ required=False,+ default=True,+ help_text="Disable only for an internal gateway using a private CA.",+ ),+ ],+ )++ # ── connectivity ──────────────────────────────────────────────────────++ async def test_connection(self) -> dict[str, Any]:+ if not self._base_url or not self._api_key:+ return {"success": False, "message": "base_url and api_key are both required"}+ try:+ async with httpx.AsyncClient(timeout=_TIMEOUT, verify=self._verify_tls) as client:+ resp = await client.get(+ f"{self._base_url}/v1/models",+ headers={"Authorization": f"Bearer {self._api_key}"},+ )+ except httpx.HTTPError as exc:+ return {"success": False, "message": f"could not reach the gateway: {exc}"}+ if resp.status_code in (401, 403):+ return {"success": False, "message": "gateway rejected the API key"}+ if resp.status_code >= 400:+ return {"success": False, "message": f"gateway returned HTTP {resp.status_code}"}+ return {"success": True, "message": "connected to the AI gateway"}++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ try:+ async with httpx.AsyncClient(timeout=_TIMEOUT, verify=self._verify_tls) as client:+ resp = await client.get(+ f"{self._base_url}/v1/logs",+ headers={"Authorization": f"Bearer {self._api_key}"},+ params={"since_seconds": since_seconds, "limit": _LIMIT},+ )+ resp.raise_for_status()+ body = resp.json()+ except (httpx.HTTPError, ValueError) as exc:+ logger.warning("ai_gateway.fetch_failed", error=str(exc))+ return []++ rows = body.get("data") or body.get("logs") or body if isinstance(body, list) else body.get("data") or []+ if not isinstance(rows, list):+ return []+ return [self.normalize(row) for row in rows if isinstance(row, dict)]++ # ── normalization ─────────────────────────────────────────────────────++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ """Fold a gateway log row into the canonical envelope.++ Emits `raw_event` (not `raw`), which is what the ingest normalizer's+ `isCanonicalEnvelope` check looks for and what the detection engine+ merges into its match namespace.+ """+ model = str(raw.get("model") or raw.get("model_name") or "")+ outcome = str(raw.get("status") or raw.get("outcome") or "success").lower()+ agent_id = str(raw.get("agent_id") or raw.get("user") or raw.get("api_key_alias") or "unknown-agent")+ tool_name = str(raw.get("tool") or raw.get("tool_name") or (f"model:{model}" if model else "unknown"))++ finding_type = self._finding_type(raw, model, outcome)+ severity = self._severity(finding_type, outcome)++ event: dict[str, Any] = {+ "source": self.connector_id,+ "category": self.connector_category,+ "severity": severity,+ "title": self._title(finding_type, tool_name, model, agent_id),+ "description": (f"agent={agent_id}; tool={tool_name}; model={model or 'n/a'}; outcome={outcome}"),+ "external_id": str(raw.get("id") or raw.get("request_id") or ""),+ "created_at": raw.get("timestamp") or raw.get("created_at") or raw.get("start_time"),+ # Flat fields the ai-* detection rules match on.+ "agent_id": agent_id,+ "agent_name": raw.get("agent_name") or agent_id,+ "tool_name": tool_name,+ "model": model,+ "provider": raw.get("provider") or raw.get("custom_llm_provider"),+ "server_name": raw.get("server_name") or raw.get("gateway"),+ "on_behalf_of": raw.get("end_user") or raw.get("on_behalf_of"),+ "outcome": outcome,+ "prompt_tokens": raw.get("prompt_tokens"),+ "completion_tokens": raw.get("completion_tokens"),+ "latency_ms": raw.get("latency_ms") or raw.get("duration_ms"),+ "session_id": raw.get("session_id") or raw.get("trace_id"),+ "raw_event": raw,+ }+ if finding_type:+ event["finding_type"] = finding_type+ return event++ def _finding_type(self, raw: dict[str, Any], model: str, outcome: str) -> str | None:+ """Classify a row, or None when it is routine activity.++ Ordered by seriousness rather than by how the gateway labelled it: a+ row can be both blocked and on an unapproved model, and the injection+ signal is the one an analyst needs first.+ """+ flagged = str(raw.get("guardrail") or raw.get("violation") or "").lower()+ if "injection" in flagged or bool(raw.get("prompt_injection")):+ return _FINDING_PROMPT_INJECTION+ if "pii" in flagged or "dlp" in flagged or "sensitive" in flagged:+ return _FINDING_SENSITIVE_EGRESS+ if self._approved and model and model.lower() not in self._approved:+ return _FINDING_UNAPPROVED_MODEL+ if outcome in _BLOCKED_OUTCOMES:+ # Something refused this and did not say why. Worth surfacing as a+ # denial rather than inventing a more specific finding type.+ return None+ return None++ @staticmethod+ def _severity(finding_type: str | None, outcome: str) -> str:+ if finding_type == _FINDING_SENSITIVE_EGRESS:+ return "critical"+ if finding_type == _FINDING_PROMPT_INJECTION:+ return "high"+ if finding_type == _FINDING_UNAPPROVED_MODEL:+ return "medium"+ if outcome in _BLOCKED_OUTCOMES:+ return "low"+ # Routine completions. Archived to the lake and hunted, not alerted on:+ # an agent doing its job is not an incident.+ return "info"++ @staticmethod+ def _title(finding_type: str | None, tool_name: str, model: str, agent_id: str) -> str:+ if finding_type == _FINDING_PROMPT_INJECTION:+ return f"Prompt injection flagged for agent {agent_id}"+ if finding_type == _FINDING_SENSITIVE_EGRESS:+ return f"Sensitive data flagged leaving via agent {agent_id}"+ if finding_type == _FINDING_UNAPPROVED_MODEL:+ return f"Agent {agent_id} used unapproved model {model}"+ return f"AI activity: {tool_name} by {agent_id}"diff --git a/services/connectors/app/connectors/auth0.py b/services/connectors/app/connectors/auth0.pyindex af25ba0d7..5f72bd5e5 100644--- a/services/connectors/app/connectors/auth0.py+++ b/services/connectors/app/connectors/auth0.py@@ -152,5 +152,5 @@ class Auth0Connector(BaseConnector):"description": raw.get("user_name") or raw.get("ip"),"alert_id": raw.get("_id") or raw.get("log_id"),"host": None,- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/carbon_black.py b/services/connectors/app/connectors/carbon_black.pyindex 56b5f25ca..43e7a3cd8 100644--- a/services/connectors/app/connectors/carbon_black.py+++ b/services/connectors/app/connectors/carbon_black.py@@ -241,7 +241,7 @@ class CarbonBlackConnector(BaseConnector):"alert_id": raw.get("id"),"host": raw.get("device_name"),"user": raw.get("device_username"),- "raw": raw,+ "raw_event": raw,}# audit logreturn {@@ -250,5 +250,5 @@ class CarbonBlackConnector(BaseConnector):"severity": "info","title": raw.get("description") or raw.get("flagged") or "Carbon Black audit event","user": raw.get("loginName"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/chronicle.py b/services/connectors/app/connectors/chronicle.pyindex cdf14f6b3..5daceb94f 100644--- a/services/connectors/app/connectors/chronicle.py+++ b/services/connectors/app/connectors/chronicle.py@@ -124,5 +124,5 @@ class ChronicleConnector(BaseConnector):"description": raw.get("description"),"alert_id": raw.get("id"),"host": None,- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/cisco_umbrella.py b/services/connectors/app/connectors/cisco_umbrella.pyindex 295fdedb1..170f08425 100644--- a/services/connectors/app/connectors/cisco_umbrella.py+++ b/services/connectors/app/connectors/cisco_umbrella.py@@ -154,5 +154,5 @@ class CiscoUmbrellaConnector(BaseConnector):"description": raw.get("threats") or raw.get("categories"),"alert_id": str(raw.get("id") or raw.get("timestamp") or ""),"host": raw.get("internalIp") or raw.get("device") or None,- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/cortex_xsiam.py b/services/connectors/app/connectors/cortex_xsiam.pyindex 84a39f813..8628139d7 100644--- a/services/connectors/app/connectors/cortex_xsiam.py+++ b/services/connectors/app/connectors/cortex_xsiam.py@@ -140,5 +140,5 @@ class CortexXSIAMConnector(BaseConnector):"description": raw.get("xdr_url"),"alert_id": str(raw.get("incident_id") or ""),"host": (raw.get("hosts") or [None])[0],- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/datadog_cloud_siem.py b/services/connectors/app/connectors/datadog_cloud_siem.pyindex 0366848d5..ec8c0ff28 100644--- a/services/connectors/app/connectors/datadog_cloud_siem.py+++ b/services/connectors/app/connectors/datadog_cloud_siem.py@@ -152,5 +152,5 @@ class DatadogCloudSIEMConnector(BaseConnector):"description": attrs.get("message"),"alert_id": raw.get("id"),"host": None,- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/devo.py b/services/connectors/app/connectors/devo.pyindex 5bb7c26ce..1f2794d31 100644--- a/services/connectors/app/connectors/devo.py+++ b/services/connectors/app/connectors/devo.py@@ -125,5 +125,5 @@ class DevoConnector(BaseConnector):"username": ctx.get("username") or ctx.get("user"),"event_type": f"devo.alert.{raw.get('name') or 'triggered'}","created_at": raw.get("createDate") or raw.get("timestamp"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/exabeam.py b/services/connectors/app/connectors/exabeam.pyindex 5a37c3344..bea0d39f5 100644--- a/services/connectors/app/connectors/exabeam.py+++ b/services/connectors/app/connectors/exabeam.py@@ -125,5 +125,5 @@ class ExabeamConnector(BaseConnector):"actor": user,"event_type": "exabeam.notable_session","created_at": raw.get("startTime") or raw.get("start_time"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/lacework.py b/services/connectors/app/connectors/lacework.pyindex d56846afc..0cf99d05a 100644--- a/services/connectors/app/connectors/lacework.py+++ b/services/connectors/app/connectors/lacework.py@@ -211,7 +211,7 @@ class LaceworkConnector(BaseConnector):"alert_id": raw.get("alertId") or raw.get("id"),"host": None,"stream": "alerts",- "raw": raw,+ "raw_event": raw,}def _normalize_policy(self, raw: dict[str, Any]) -> dict[str, Any]:@@ -239,5 +239,5 @@ class LaceworkConnector(BaseConnector):"policy_id": raw.get("policyId"),"resource_id": raw.get("resourceId"),"resource_type": raw.get("resourceType"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/llm_usage.py b/services/connectors/app/connectors/llm_usage.pyindex aa041f212..c8513fc47 100644--- a/services/connectors/app/connectors/llm_usage.py+++ b/services/connectors/app/connectors/llm_usage.py@@ -144,5 +144,13 @@ class LlmUsageConnector(BaseConnector):"actor": actor_email,"actor_email": actor_email,"created_at": raw.get("effective_at") or raw.get("occurred_at") or raw.get("timestamp"),- "raw": raw,+ # `raw_event`, not `raw`. The Go normalizer's isCanonicalEnvelope+ # check looks for `raw_event` + `source`; emitting `raw` missed it,+ # so these events fell through to the lenient fallback, borrowed the+ # splunk_enterprise profile, and were stamped Splunk / Network+ # Activity (class_uid 4001). Category 4 is not a finding, so the+ # promoter never turned any of them into an alert unless the+ # severity map happened to reach 4. The key name is also what+ # DetectionEngine._raw_fields merges into the match namespace.+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/mimecast.py b/services/connectors/app/connectors/mimecast.pyindex cc0f7332a..17f1ff7ac 100644--- a/services/connectors/app/connectors/mimecast.py+++ b/services/connectors/app/connectors/mimecast.py@@ -153,5 +153,5 @@ class MimecastConnector(BaseConnector):"description": raw.get("url"),"alert_id": raw.get("id"),"host": None,- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/netskope.py b/services/connectors/app/connectors/netskope.pyindex d3c795bb4..db5d36ab6 100644--- a/services/connectors/app/connectors/netskope.py+++ b/services/connectors/app/connectors/netskope.py@@ -116,5 +116,5 @@ class NetskopeConnector(BaseConnector):"actor": raw.get("user"),"event_type": f"netskope.alert.{alert_type or 'event'}","created_at": raw.get("timestamp"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/qradar.py b/services/connectors/app/connectors/qradar.pyindex 6b75d6ce3..61ec16b2d 100644--- a/services/connectors/app/connectors/qradar.py+++ b/services/connectors/app/connectors/qradar.py@@ -178,5 +178,5 @@ class QRadarConnector(BaseConnector):"src_ip": (raw.get("offense_source") if raw.get("offense_source_summary") == "IP" else None),"event_type": f"qradar.offense.{raw.get('offense_type', 'unknown')}","created_at": raw.get("start_time"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/rapid7_insightidr.py b/services/connectors/app/connectors/rapid7_insightidr.pyindex 7f924131d..02cbf0b8f 100644--- a/services/connectors/app/connectors/rapid7_insightidr.py+++ b/services/connectors/app/connectors/rapid7_insightidr.py@@ -142,5 +142,5 @@ class Rapid7InsightIDRConnector(BaseConnector):"description": raw.get("disposition"),"alert_id": raw.get("rrn") or raw.get("id"),"host": None,- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/salesforce.py b/services/connectors/app/connectors/salesforce.pyindex 656a7b4ba..c2d3c8d1b 100644--- a/services/connectors/app/connectors/salesforce.py+++ b/services/connectors/app/connectors/salesforce.py@@ -179,5 +179,5 @@ class SalesforceConnector(BaseConnector):"description": raw.get("Display"),"alert_id": raw.get("Id"),"host": None,- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/securonix.py b/services/connectors/app/connectors/securonix.pyindex 4846c0caa..52a9fa733 100644--- a/services/connectors/app/connectors/securonix.py+++ b/services/connectors/app/connectors/securonix.py@@ -121,5 +121,5 @@ class SecuronixConnector(BaseConnector):"actor": entity,"event_type": "securonix.incident","created_at": raw.get("lastUpdateDate"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/slack_audit.py b/services/connectors/app/connectors/slack_audit.pyindex 0034fefd7..dd4889719 100644--- a/services/connectors/app/connectors/slack_audit.py+++ b/services/connectors/app/connectors/slack_audit.py@@ -130,5 +130,5 @@ class SlackAuditConnector(BaseConnector):"description": f"actor={actor}" if actor else None,"alert_id": raw.get("id"),"host": None,- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/sumo_logic.py b/services/connectors/app/connectors/sumo_logic.pyindex 7a0a0e00b..e776abd8d 100644--- a/services/connectors/app/connectors/sumo_logic.py+++ b/services/connectors/app/connectors/sumo_logic.py@@ -156,5 +156,5 @@ class SumoLogicConnector(BaseConnector):"description": raw.get("description"),"alert_id": raw.get("id"),"host": None,- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/syslog_cef.py b/services/connectors/app/connectors/syslog_cef.pyindex b4917678f..c73fa0726 100644--- a/services/connectors/app/connectors/syslog_cef.py+++ b/services/connectors/app/connectors/syslog_cef.py@@ -162,7 +162,7 @@ class SyslogCefConnector(BaseConnector):"description": message[:500],"external_id": "","event_type": "syslog_cef.raw",- "raw": raw,+ "raw_event": raw,}ext = cef["ext"]return {@@ -177,5 +177,5 @@ class SyslogCefConnector(BaseConnector):"username": ext.get("suser") or ext.get("sourceUserName"),"actor": ext.get("suser") or ext.get("sourceUserName"),"event_type": f"syslog_cef.{(cef['device_product'] or 'cef').lower().replace(' ', '_')}",- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/tenable.py b/services/connectors/app/connectors/tenable.pyindex 7bbac2deb..3097ca45c 100644--- a/services/connectors/app/connectors/tenable.py+++ b/services/connectors/app/connectors/tenable.py@@ -126,5 +126,5 @@ class TenableConnector(BaseConnector):"description": raw.get("plugin_family"),"alert_id": str(raw.get("plugin_id")) if raw.get("plugin_id") else None,"host": None,- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/trellix_helix.py b/services/connectors/app/connectors/trellix_helix.pyindex 70f5154bd..988fa7ddc 100644--- a/services/connectors/app/connectors/trellix_helix.py+++ b/services/connectors/app/connectors/trellix_helix.py@@ -166,5 +166,5 @@ class TrellixHelixConnector(BaseConnector):"alert_id": raw.get("id"),"host": raw.get("hostname"),"user": raw.get("username"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/trend_vision_one.py b/services/connectors/app/connectors/trend_vision_one.pyindex 9236ba441..918ddee6c 100644--- a/services/connectors/app/connectors/trend_vision_one.py+++ b/services/connectors/app/connectors/trend_vision_one.py@@ -183,5 +183,5 @@ class TrendVisionOneConnector(BaseConnector):"description": raw.get("description"),"alert_id": raw.get("id") or raw.get("uuid"),"host": (raw.get("impactScope") or {}).get("entityValue"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/windows_event.py b/services/connectors/app/connectors/windows_event.pyindex 5cf23b1fa..d419d0681 100644--- a/services/connectors/app/connectors/windows_event.py+++ b/services/connectors/app/connectors/windows_event.py@@ -130,5 +130,5 @@ class WindowsEventConnector(BaseConnector):"process_name": data.get("Image") or data.get("NewProcessName"),"event_type": f"windows.{(channel or 'event').lower()}.{event_id}","created_at": raw.get("TimeCreated") or system.get("TimeCreated"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/app/connectors/zeek_suricata.py b/services/connectors/app/connectors/zeek_suricata.pyindex 9c293c26d..3be7ba8ae 100644--- a/services/connectors/app/connectors/zeek_suricata.py+++ b/services/connectors/app/connectors/zeek_suricata.py@@ -130,7 +130,7 @@ class ZeekSuricataConnector(BaseConnector):"dst_ip": raw.get("dest_ip"),"event_type": "zeek_suricata.suricata.alert","created_at": raw.get("timestamp"),- "raw": raw,+ "raw_event": raw,}def _normalize_zeek(self, raw: dict[str, Any]) -> dict[str, Any]:@@ -148,5 +148,5 @@ class ZeekSuricataConnector(BaseConnector):"dst_ip": raw.get("id.resp_h") or raw.get("dst"),"event_type": "zeek_suricata.zeek.notice","created_at": raw.get("ts"),- "raw": raw,+ "raw_event": raw,}diff --git a/services/connectors/tests/test_schemas.py b/services/connectors/tests/test_schemas.pyindex 4582dcc5a..1b7fbc184 100644--- a/services/connectors/tests/test_schemas.py+++ b/services/connectors/tests/test_schemas.py@@ -12,7 +12,11 @@ import pytestfrom app.connectors import CONNECTOR_REGISTRY, list_connector_schemasfrom app.connectors.base import BaseConnector, ConnectorSchema, Field-ALLOWED_CATEGORIES = {"siem", "edr", "cloud", "iam", "saas", "audit", "vcs", "ndr", "network"}+# `ai` is the customer's own AI estate: agents, LLM gateways, MCP servers.+# Deliberately its own category rather than folded into `saas`. A `saas`+# connector pulls a vendor's audit log; these pull runtime activity from+# software the customer operates, and the console groups by category.+ALLOWED_CATEGORIES = {"siem", "edr", "cloud", "iam", "saas", "audit", "vcs", "ndr", "network", "ai"}ALLOWED_FIELD_TYPES = {"string", "secret", "select", "textarea", "boolean", "number"}diff --git a/services/fusion/app/data/detection_ruleset.json b/services/fusion/app/data/detection_ruleset.jsonindex ea83583ff..798224cb3 100644--- a/services/fusion/app/data/detection_ruleset.json+++ b/services/fusion/app/data/detection_ruleset.json@@ -1,5 +1,5 @@{- "count": 825,+ "count": 833,"rules": [{"category": "application",@@ -1392,6 +1392,132 @@"severity": "medium","slug": "llm-project-deleted"},+ {+ "category": "application",+ "id": "det-application-079",+ "match_when": {+ "finding_type": "prompt_injection"+ },+ "mitre": [+ "T1059"+ ],+ "name": "Prompt Injection Detected in AI Agent Context",+ "product": "ai_guardrail",+ "service": "runtime",+ "severity": "high",+ "slug": "ai-prompt-injection-detected"+ },+ {+ "category": "application",+ "id": "det-application-080",+ "match_when": {+ "finding_type": "excessive_agency"+ },+ "mitre": [+ "T1078"+ ],+ "name": "AI Agent Took Action Beyond Its Granted Scope",+ "product": "ai_guardrail",+ "service": "runtime",+ "severity": "high",+ "slug": "ai-agent-excessive-agency"+ },+ {+ "category": "application",+ "id": "det-application-081",+ "match_when": {+ "finding_type": "sensitive_data_egress"+ },+ "mitre": [+ "T1567"+ ],+ "name": "Sensitive Data Left via an AI Agent",+ "product": "ai_guardrail",+ "service": "runtime",+ "severity": "critical",+ "slug": "ai-sensitive-data-egress"+ },+ {+ "category": "application",+ "id": "det-application-082",+ "match_when": {+ "finding_type": "unapproved_model"+ },+ "mitre": [+ "T1078"+ ],+ "name": "AI Agent Used an Unapproved Model",+ "product": "ai_guardrail",+ "service": "runtime",+ "severity": "medium",+ "slug": "ai-unapproved-model"+ },+ {+ "category": "application",+ "id": "det-application-083",+ "match_when": {+ "finding_type": "tool_escalation"+ },+ "mitre": [+ "T1548"+ ],+ "name": "AI Agent Escalated to a Higher-Privilege Tool",+ "product": "ai_guardrail",+ "service": "runtime",+ "severity": "high",+ "slug": "ai-tool-escalation"+ },+ {+ "category": "application",+ "id": "det-application-084",+ "match_when": {+ "finding_type": "shadow_ai"+ },+ "mitre": [+ "T1078"+ ],+ "name": "Undeclared AI Agent Observed",+ "product": "ai_guardrail",+ "service": "runtime",+ "severity": "medium",+ "slug": "ai-shadow-agent-discovered"+ },+ {+ "category": "application",+ "id": "det-application-085",+ "match_when": {+ "prompt_secret_kinds_has_any": [+ "aws_access_key",+ "github_token",+ "openai_key",+ "private_key",+ "slack_token"+ ]+ },+ "mitre": [+ "T1552"+ ],+ "name": "Credential Material Present in an AI Prompt",+ "product": "ai_runtime",+ "service": "runtime",+ "severity": "high",+ "slug": "ai-prompt-contained-credential"+ },+ {+ "category": "application",+ "id": "det-application-086",+ "match_when": {+ "outcome": "denied"+ },+ "mitre": [+ "T1078"+ ],+ "name": "AI Agent Tool Call Denied",+ "product": "ai_runtime",+ "service": "runtime",+ "severity": "low",+ "slug": "ai-agent-tool-call-failed-repeatedly"+ },{"category": "cloud","id": "det-cloud-001",diff --git a/services/fusion/app/services/detection_engine.py b/services/fusion/app/services/detection_engine.pyindex 405c59511..aa5c43ca6 100644--- a/services/fusion/app/services/detection_engine.py+++ b/services/fusion/app/services/detection_engine.py@@ -93,7 +93,44 @@ class DetectionEngine:@staticmethoddef _raw_fields(ocsf: dict[str, Any]) -> dict[str, Any]:- """Recover the connector-normalized flat fields the specs match on."""+ """Recover the flat field namespace the specs match on.++ `raw_data` carries the connector's own normalized dict, and connectors+ put the untouched vendor payload under `raw_event`. The matcher does a+ plain `event.get(field)` with no path traversal, so a rule naming a+ vendor field — `request_uri`, `target_image`, `call_trace` — read+ `None` and could never fire, however correct the rule was.++ The scale of that was not obvious: 663 of the 825 loaded rules+ referenced at least one field that was not visible, and fixture replay+ could not catch any of them because fixtures are synthesized from the+ rule rather than from real telemetry.++ The workaround in use was per-field hoisting inside individual+ connectors, e.g. in `llm_usage.normalize()`:++ # Emit the dotted event_type at the TOP LEVEL so the llm-*+ # detection rules (which match on `event_type`) fire++ which only ever fixed the one field someone noticed. Merging the nested+ payload once, here, fixes the class.++ Connector-normalized keys win on collision. The connector has already+ made a deliberate decision about `severity` or `title`, and a vendor+ field of the same name must not silently override it.+ """+ fields = DetectionEngine._decode_raw_data(ocsf)++ nested = fields.get("raw_event")+ if isinstance(nested, dict):+ merged = {k: v for k, v in nested.items() if isinstance(k, str)}+ merged.update(fields)+ return merged+ return fields++ @staticmethod+ def _decode_raw_data(ocsf: dict[str, Any]) -> dict[str, Any]:+ """The connector's normalized dict, or the OCSF top level as fallback."""raw = ocsf.get("raw_data")if isinstance(raw, str) and raw.strip():try:diff --git a/services/fusion/tests/test_detection_field_namespace.py b/services/fusion/tests/test_detection_field_namespace.pynew file mode 100644index 000000000..f16d5b203--- /dev/null+++ b/services/fusion/tests/test_detection_field_namespace.py@@ -0,0 +1,107 @@+"""Vendor fields nested in `raw_event` must be visible to detection rules.++`raw_data` carries the connector's own normalized dict, and connectors put the+untouched vendor payload under `raw_event`. The matcher does a plain+`event.get(field)` with no path traversal, so a rule naming a vendor field —+`request_uri`, `target_image`, `call_trace` — read `None` and could never fire,+however correct the rule was.++663 of the 825 loaded rules referenced at least one field that was not visible.+Fixture replay could not catch a single one, because fixtures are synthesized+from the rule they test rather than from real telemetry.++The workaround in the tree was per-field hoisting inside individual connectors+(`llm_usage.normalize()` carries a comment explaining that it lifts+`event_type` to the top level "so the llm-* detection rules fire"), which only+ever fixed the one field someone noticed.+"""++from __future__ import annotations++import json++from app.services.detection_engine import DetectionEngine+++def _ocsf(connector_payload: dict) -> dict:+ """An OCSF event as ingest produces it: raw_data is the connector's dict."""+ return {"raw_data": json.dumps(connector_payload), "class_uid": 2001}+++# ── the regression ────────────────────────────────────────────────────────+++def test_vendor_fields_under_raw_event_are_visible():+ """The case that silently disabled most of the corpus."""+ fields = DetectionEngine._raw_fields(+ _ocsf(+ {+ "source": "imperva",+ "severity": "high",+ "src_ip": "203.0.113.9",+ "raw_event": {"request_uri": "/?id=1' OR '1'='1", "method": "GET"},+ }+ )+ )+ assert fields["request_uri"] == "/?id=1' OR '1'='1"+ assert fields["method"] == "GET"+++def test_connector_fields_are_still_visible():+ fields = DetectionEngine._raw_fields(_ocsf({"source": "imperva", "src_ip": "203.0.113.9", "raw_event": {"method": "GET"}}))+ assert fields["source"] == "imperva"+ assert fields["src_ip"] == "203.0.113.9"+++def test_connector_normalization_wins_on_collision():+ """The connector made a deliberate decision; a vendor key must not undo it.++ A connector maps a vendor's idiosyncratic severity ladder onto AiSOC's five+ tiers. If the raw vendor `severity` overrode that, every severity-based+ rule and the promoter's `severity_id >= 4` floor would read the unmapped+ value.+ """+ fields = DetectionEngine._raw_fields(_ocsf({"severity": "critical", "raw_event": {"severity": "SEV-3"}}))+ assert fields["severity"] == "critical"+++# ── shapes that must not break ────────────────────────────────────────────+++def test_a_missing_raw_event_is_fine():+ fields = DetectionEngine._raw_fields(_ocsf({"source": "okta", "event_type": "user.session.start"}))+ assert fields["event_type"] == "user.session.start"+++def test_a_non_dict_raw_event_is_ignored():+ """Some connectors put a JSON string or a list there."""+ for payload in ('{"a": 1}', ["a", "b"], 42, None):+ fields = DetectionEngine._raw_fields(_ocsf({"source": "x", "raw_event": payload}))+ assert fields["source"] == "x"+++def test_malformed_raw_data_falls_back_to_the_ocsf_top_level():+ fields = DetectionEngine._raw_fields({"raw_data": "{not json", "class_uid": 2001})+ assert fields["class_uid"] == 2001+++def test_absent_raw_data_falls_back_to_the_ocsf_top_level():+ fields = DetectionEngine._raw_fields({"class_uid": 2001, "severity_id": 4})+ assert fields["severity_id"] == 4+++def test_nested_dicts_inside_raw_event_are_left_alone():+ """Only one level is merged. Deep traversal is not what the matcher does,+ and pretending otherwise would make rules look reachable when they are not.+ """+ fields = DetectionEngine._raw_fields(_ocsf({"raw_event": {"actor": {"email": "[email protected]"}, "verb": "create"}}))+ assert fields["verb"] == "create"+ assert fields["actor"] == {"email": "[email protected]"}+ assert "email" not in fields+++def test_non_string_keys_in_raw_event_are_dropped():+ """A JSON payload cannot produce these, but a direct dict caller could."""+ fields = DetectionEngine._raw_fields({"raw_data": "", "raw_event": {1: "x", "ok": "y"}})+ # Falls back to the OCSF top level here, which still must not raise.+ assert isinstance(fields, dict)diff --git a/services/ingest/internal/normalizer/normalizer.go b/services/ingest/internal/normalizer/normalizer.goindex 3b9855dc1..26af98c63 100644--- a/services/ingest/internal/normalizer/normalizer.go+++ b/services/ingest/internal/normalizer/normalizer.go@@ -184,6 +184,65 @@ var connectorProfiles = map[string]connectorProfile{"CRITICAL": 5, "HIGH": 4, "MEDIUM": 3, "LOW": 2, "INFORMATIONAL": 1,},},+ // ai_runtime / ai_guardrail — the customer's AI estate.+ //+ // Two profiles rather than one, and the split is load-bearing. Routine AI+ // activity (a tool call, a model invocation, an MCP request) is 6003 API+ // Activity: category 6, so should_promote() leaves it in the lake unless+ // severity reaches high, and analysts hunt it. A guardrail finding is 2001+ // Security Finding: category 2, which the promoter always promotes,+ // because something has already judged it worth a human's attention.+ //+ // Collapsing them would fail in one of two ways. All-2001 means a chatty+ // agent floods the alert queue with its own normal operation. All-6003+ // means a detected prompt injection sits silently in the lake.+ //+ // Field names match the ai-runtime.yaml / ai-finding.yaml webhook+ // templates so the pull and push paths produce the same OCSF shape.+ "ai_runtime": {+ product: OcsfProduct{Name: "AI Runtime", VendorName: "AiSOC"},+ classUID: 6003,+ className: "API Activity",+ fieldMap: map[string]string{+ "agent_id": "actor.process.name",+ "agent_name": "actor.process.path",+ "on_behalf_of": "actor.user.name",+ "tool_name": "activity_name",+ "model": "metadata.product.feature.name",+ "provider": "cloud.provider",+ "server_name": "resource.name",+ "source_ip": "src_endpoint.ip",+ "hostname": "src_endpoint.hostname",+ "outcome": "status_detail",+ "latency_ms": "duration",+ "timestamp": "time",+ },+ severityMap: map[string]int{+ "critical": 5, "high": 4, "medium": 3, "low": 2, "info": 1, "informational": 1,+ },+ },+ "ai_guardrail": {+ product: OcsfProduct{Name: "AI Guardrail", VendorName: "AiSOC"},+ classUID: 2001,+ className: "Security Finding",+ fieldMap: map[string]string{+ "finding_id": "finding.uid",+ "finding_type": "activity_name",+ "title": "message",+ "description": "finding.desc",+ "agent_id": "actor.process.name",+ "on_behalf_of": "actor.user.name",+ "model": "metadata.product.feature.name",+ "provider": "cloud.provider",+ "server_name": "resource.name",+ "source_ip": "src_endpoint.ip",+ "hostname": "src_endpoint.hostname",+ "timestamp": "time",+ },+ severityMap: map[string]int{+ "critical": 5, "high": 4, "medium": 3, "low": 2, "info": 1, "informational": 1,+ },+ },// kubernetes_audit — Track D, v7.1.0.//// The apiserver POSTs a v1 EventList batch and we explode it into@@ -305,6 +364,42 @@ func isCanonicalEnvelope(p map[string]interface{}) bool {return hasRaw && hasSource}+// genericProfile is the fallback for a connector type with no declared+// profile. It replaces a borrow of the splunk_enterprise profile, which was+// wrong in two compounding ways.+//+// First, attribution: splunk_enterprise stamps+// OcsfProduct{Name: "Splunk Enterprise", VendorName: "Splunk"}, and the+// promoter derives alert.source from metadata.product. Every profile-less+// connector's alerts therefore read as coming from Splunk. Only eight profiles+// are declared, so that was the majority of the catalogue.+//+// Second, and worse, promotion: splunk_enterprise is classUID 4001 (Network+// Activity) with an EMPTY severityMap. should_promote() requires OCSF category+// 2 or severity_id >= 4, and an empty map yields severity_id 0 — so category 4+// with severity 0 can satisfy neither branch. Those events were archived to the+// lake and could never become alerts, silently, for any connector without a+// profile.+//+// The generic profile uses 2001 Security Finding because a connector's+// fetch_alerts() contract is to return findings rather than raw telemetry, and+// carries the five-tier severity ladder so a vendor severity string maps.+// Product identity is derived from the connector type, so attribution is at+// worst uninformative rather than actively wrong.+func genericProfile(connectorType string) connectorProfile {+ name := connectorType+ if name == "" {+ name = "Connector"+ }+ return connectorProfile{+ product: OcsfProduct{Name: name, VendorName: name},+ classUID: 2001,+ className: "Security Finding",+ fieldMap: _canonicalFieldMap,+ severityMap: _canonicalSeverityMap,+ }+}+func canonicalProfile(connectorType string) connectorProfile {classUID, className := 2001, "Security Finding"if override, ok := canonicalClassByConnector[connectorType]; ok {@@ -340,8 +435,11 @@ func (n *Normalizer) Normalize(raw *RawEvent) (*NormalizedEvent, error) {if n.cfg.NormalizerMode == "strict" {return nil, fmt.Errorf("unknown connector type: %s", raw.ConnectorType)}- // Lenient: use generic profile- profile = connectorProfiles["splunk_enterprise"]+ // Lenient: a vendor-neutral generic profile. This used to borrow+ // splunk_enterprise, which mis-attributed every profile-less+ // connector to Splunk and — because that profile is category 4+ // with an empty severity map — made its events unpromotable.+ profile = genericProfile(raw.ConnectorType)log.Warn().Str("connector_type", raw.ConnectorType).Msg("Using generic profile for unknown connector")}}diff --git a/services/ingest/internal/normalizer/normalizer_test.go b/services/ingest/internal/normalizer/normalizer_test.goindex 16cbd7cd6..dedac3378 100644--- a/services/ingest/internal/normalizer/normalizer_test.go+++ b/services/ingest/internal/normalizer/normalizer_test.go@@ -10,6 +10,13 @@ func newTestNormalizer() *Normalizer {return &Normalizer{cfg: &config.Config{NormalizerMode: "strict"}, version: "test"}}+// newLenientNormalizer exercises the fallback path. Strict mode rejects an+// unknown connector type outright, so the generic-profile behaviour is only+// reachable in lenient mode — which is the deployed default.+func newLenientNormalizer() *Normalizer {+ return &Normalizer{cfg: &config.Config{NormalizerMode: "lenient"}, version: "test"}+}+// A canonical Splunk envelope (what SplunkConnector.fetch_alerts emits) must// normalize as an OCSF Security Finding with its fields preserved, so the// fusion promoter promotes it regardless of severity (#528).@@ -165,3 +172,136 @@ func TestCanonicalEnvelopeIdpMapsToAuthentication(t *testing.T) {t.Errorf("okta canonical class_uid = %v, want 3002 (Authentication)", ev.OcsfEvent["class_uid"])}}++// A connector with no declared profile must not be attributed to Splunk, and+// must still produce a promotable event.+//+// The lenient fallback used to borrow the splunk_enterprise profile. That was+// wrong twice over. Attribution: the promoter derives alert.source from+// metadata.product, so every profile-less connector's alerts read as Splunk —+// and only eight profiles are declared, so that was most of the catalogue.+// Promotion: splunk_enterprise is classUID 4001 (Network Activity) with an+// EMPTY severityMap, and should_promote() needs OCSF category 2 or+// severity_id >= 4. Category 4 with severity 0 satisfies neither, so those+// events were archived to the lake and could never become alerts.+func TestUnknownConnectorFallbackIsVendorNeutralAndPromotable(t *testing.T) {+ n := newLenientNormalizer()+ raw := &RawEvent{+ ConnectorID: "c-unknown",+ ConnectorType: "acme_xdr", // deliberately absent from connectorProfiles+ TenantID: "11111111-1111-1111-1111-111111111111",+ ReceivedAt: "2026-09-22T00:00:00Z",+ Payload: map[string]interface{}{+ // No "raw_event", so this is NOT a canonical envelope and the+ // profile lookup + fallback path is what runs.+ "title": "Suspicious binary executed",+ "severity": "high",+ "hostname": "ws-42",+ },+ }+ ev, err := n.Normalize(raw)+ if err != nil {+ t.Fatalf("Normalize error: %v", err)+ }+ ocsf := ev.OcsfEvent++ meta, ok := ocsf["metadata"].(map[string]interface{})+ if !ok {+ t.Fatalf("metadata missing from normalized event")+ }+ product, ok := meta["product"].(OcsfProduct)+ if !ok {+ t.Fatalf("metadata.product has unexpected type %T", meta["product"])+ }+ if product.VendorName == "Splunk" || product.Name == "Splunk Enterprise" {+ t.Errorf("profile-less connector attributed to Splunk: %+v", product)+ }+ if product.VendorName != "acme_xdr" {+ t.Errorf("VendorName = %q, want the connector type", product.VendorName)+ }++ // Category 2 (Findings) is what makes this promotable at all.+ if ocsf["class_uid"] != 2001 {+ t.Errorf("class_uid = %v, want 2001 so the promoter accepts it", ocsf["class_uid"])+ }+ if ocsf["category_uid"] != 2 {+ t.Errorf("category_uid = %v, want 2", ocsf["category_uid"])+ }+ // And the severity ladder must actually map, rather than yielding 0.+ if ocsf["severity_id"] != 4 {+ t.Errorf("severity_id = %v, want 4 — an empty severity map was the second half of the bug", ocsf["severity_id"])+ }+}++// The routine/finding split for AI telemetry is the whole design of the+// AI-estate capability, so it gets a test rather than a comment.+//+// Routine AI activity must land in category 6 so `should_promote()` leaves it+// in the lake — otherwise a chatty agent floods the alert queue with its own+// normal operation. A guardrail finding must land in category 2 so the+// promoter always promotes it regardless of severity — otherwise a detected+// prompt injection sits silently in the lake.+func TestAiRuntimeActivityIsNotAFinding(t *testing.T) {+ n := newTestNormalizer()+ ev, err := n.Normalize(&RawEvent{+ ConnectorID: "ai-1",+ ConnectorType: "ai_runtime",+ TenantID: "11111111-1111-1111-1111-111111111111",+ ReceivedAt: "2026-09-22T00:00:00Z",+ Payload: map[string]interface{}{+ "agent_id": "agent-support-bot",+ "tool_name": "search_tickets",+ "severity": "info",+ "timestamp": "2026-09-22T00:00:00Z",+ },+ })+ if err != nil {+ t.Fatalf("Normalize error: %v", err)+ }+ ocsf := ev.OcsfEvent+ if ocsf["class_uid"] != 6003 {+ t.Errorf("class_uid = %v, want 6003 (API Activity)", ocsf["class_uid"])+ }+ if ocsf["category_uid"] != 6 {+ t.Errorf("category_uid = %v, want 6 so routine activity is not auto-promoted", ocsf["category_uid"])+ }+ if ocsf["severity_id"] != 1 {+ t.Errorf("severity_id = %v, want 1 — an info tool call must not reach the promoter's floor", ocsf["severity_id"])+ }+ if ocsf["activity_name"] != "search_tickets" {+ t.Errorf("activity_name = %v, want the tool name", ocsf["activity_name"])+ }+}++func TestAiGuardrailFindingIsAlwaysPromotable(t *testing.T) {+ n := newTestNormalizer()+ ev, err := n.Normalize(&RawEvent{+ ConnectorID: "ai-2",+ ConnectorType: "ai_guardrail",+ TenantID: "11111111-1111-1111-1111-111111111111",+ ReceivedAt: "2026-09-22T00:00:00Z",+ Payload: map[string]interface{}{+ "finding_id": "gr-1",+ "finding_type": "prompt_injection",+ "title": "Instruction override detected in retrieved document",+ "agent_id": "agent-support-bot",+ // Deliberately low severity: category 2 must promote anyway,+ // because a guardrail has already judged this worth reporting.+ "severity": "low",+ "timestamp": "2026-09-22T00:00:00Z",+ },+ })+ if err != nil {+ t.Fatalf("Normalize error: %v", err)+ }+ ocsf := ev.OcsfEvent+ if ocsf["class_uid"] != 2001 {+ t.Errorf("class_uid = %v, want 2001 (Security Finding)", ocsf["class_uid"])+ }+ if ocsf["category_uid"] != 2 {+ t.Errorf("category_uid = %v, want 2 so the promoter always promotes it", ocsf["category_uid"])+ }+ if ocsf["activity_name"] != "prompt_injection" {+ t.Errorf("activity_name = %v, want the finding type detections match on", ocsf["activity_name"])+ }+}diff --git a/services/ingest/internal/normalizer/templates/ai-finding.yaml b/services/ingest/internal/normalizer/templates/ai-finding.yamlnew file mode 100644index 000000000..b7ab0671b--- /dev/null+++ b/services/ingest/internal/normalizer/templates/ai-finding.yaml@@ -0,0 +1,64 @@+# AI guardrail finding — something the customer's AI estate did that a+# guardrail, scanner or the SDK's own checks flagged.+#+# The counterpart to ai-runtime.yaml, and the split between them is the whole+# design. Routine AI activity is `6003` API Activity: category 6, so+# `should_promote()` leaves it in the lake unless severity reaches high, and it+# is hunted rather than alerted on. A finding is `2001` Security Finding:+# category 2, which the promoter always promotes regardless of severity,+# because something has already decided this is worth a human's attention.+#+# Getting that split wrong in either direction is the failure mode. Model+# everything as 2001 and a chatty agent floods the queue. Model everything as+# 6003 and a detected prompt injection sits silently in the lake.+#+# `finding_type` is the signal to write detections against: prompt_injection,+# excessive_agency, sensitive_data_egress, unapproved_model, tool_escalation,+# shadow_ai.+id: ai-finding+vendor_name: AiSOC+product_name: AI Guardrail+class_uid: 2001+class_name: Security Finding+activity_id: 1+field_map:+ finding_id: finding.uid+ finding_type: activity_name+ title: finding.title+ description: finding.desc+ # The principal and the AI asset it concerns.+ agent_id: actor.process.name+ agent_name: actor.process.path+ on_behalf_of: actor.user.name+ model: metadata.product.feature.name+ provider: cloud.provider+ server_name: resource.name+ tool_name: finding.evidence.tool_name+ # What tripped, and how sure the detector is. `confidence` is carried+ # because a guardrail's own uncertainty should reach triage rather than+ # being flattened into a severity tier.+ rule_id: finding.related_events.id+ confidence: finding.evidence.confidence+ matched_pattern: finding.evidence.matched_pattern+ # Provenance without content, same contract as ai-runtime.+ prompt_sha256: finding.evidence.prompt_sha256+ response_sha256: finding.evidence.response_sha256+ session_id: finding.evidence.session_id+ source_ip: src_endpoint.ip+ hostname: src_endpoint.hostname+severity_field: severity+severity_map:+ info: 1+ informational: 1+ low: 2+ medium: 3+ warning: 3+ high: 4+ critical: 5+ fatal: 6+time_field: timestamp+message_field: title+constants:+ source_type: ai-finding+ metadata.product.vendor_name: AiSOC+ metadata.product.name: AI Guardraildiff --git a/services/ingest/internal/normalizer/templates/ai-runtime.yaml b/services/ingest/internal/normalizer/templates/ai-runtime.yamlnew file mode 100644index 000000000..ef89e728f--- /dev/null+++ b/services/ingest/internal/normalizer/templates/ai-runtime.yaml@@ -0,0 +1,73 @@+# AI runtime activity — an agent or LLM app calling a tool or a model.+#+# This is the routine, high-volume half of AI-estate telemetry: every tool+# invocation, model call and MCP request the customer's AI makes. It is modelled+# on k8s-audit because the shape is the same question — which principal invoked+# which verb against which resource, and what came back.+#+# class_uid 6003 (API Activity) is deliberate. Category 6 is not Findings, so+# `should_promote()` requires severity_id >= 4 and routine activity stays in the+# ClickHouse lake where it is hunted rather than alerted on. A guardrail+# violation or an injection detection is a *finding* and uses ai-finding.yaml,+# which is category 2 and therefore always promoted.+#+# Prompt and response text are deliberately absent from the field map. The SDK+# sends hashes and lengths by default; an operator who opts into full capture+# gets the text under `raw_event`, which the detection engine can match on but+# which nothing here lifts into indexed OCSF fields.+id: ai-runtime+vendor_name: AiSOC+product_name: AI Runtime+class_uid: 6003+class_name: API Activity+activity_id: 1+field_map:+ # Identity of the calling principal. `agent_id` is the AI itself;+ # `actor.user.name` is the human on whose behalf it acted, when there is one.+ # Both matter: an agent acting autonomously and an agent acting for a user+ # are different risks.+ agent_id: actor.process.name+ agent_name: actor.process.path+ on_behalf_of: actor.user.name+ session_id: finding.uid+ # What was invoked.+ tool_name: activity_name+ model: metadata.product.feature.name+ provider: cloud.provider+ server_name: resource.name+ resource: finding.title+ # Where from.+ source_ip: src_endpoint.ip+ hostname: src_endpoint.hostname+ # Outcome and cost. Token counts are the closest thing to a blast-radius+ # signal an AI call has, so they are mapped rather than left in raw_event.+ outcome: status_detail+ status_code: status_code+ prompt_tokens: finding.evidence.prompt_tokens+ completion_tokens: finding.evidence.completion_tokens+ latency_ms: duration+ # Content provenance without the content.+ prompt_sha256: finding.evidence.prompt_sha256+ response_sha256: finding.evidence.response_sha256+ # Which secret shapes the prompt contained. The SDK computes this+ # locally and reports the pattern names while sending only a digest of+ # the prompt, so credential-in-prompt detection works even under the+ # default hashed capture mode where the text never leaves the process.+ prompt_secret_kinds: finding.evidence.prompt_secret_kinds+ argument_keys: finding.evidence.argument_keys+severity_field: severity+severity_map:+ info: 1+ informational: 1+ low: 2+ medium: 3+ warning: 3+ high: 4+ critical: 5+ fatal: 6+time_field: timestamp+message_field: tool_name+constants:+ source_type: ai-runtime+ metadata.product.vendor_name: AiSOC+ metadata.product.name: AI Runtimediff --git a/services/mcp/README.md b/services/mcp/README.mdindex 50dfd512b..7e1fadcfd 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -197,7 +197,19 @@ npx -y @aisoc/mcp doctor- **Your API key never leaves the machine** running this server. It's read from env or the host's local config file (mode `0600`) and used to sign requests to your AiSOC instance.- **Read-only by default** unless your API key has write scopes. `aisoc_run_investigation` requires `cases:investigate`; everything else only needs `cases:read` / `alerts:read`.-- **Audit trail.** Every tool call logged through this server lands in the AiSOC audit log with the calling user and the tool name. You can revoke the key and replay every action it took.+- **Audit trail.** Every tool call this server makes emits a structured+ `mcp.tool_call` record carrying the tool name, the calling key's subject, the+ argument keys (not values), latency and outcome. Note what the API's own+ audit log does *not* cover: `audit_middleware` only records mutating methods+ carrying a valid JWT, so the ten read tools (`aisoc_list_*`, `aisoc_get_*`,+ `aisoc_lake_query`) produce no server-side audit row, and what it does record+ is an HTTP path rather than a tool name. The tool-call records above are what+ gives you per-tool attribution.+ Set `AISOC_MCP_TELEMETRY_URL` to an AiSOC inbox token using the `ai-runtime`+ template to collect them; unset, nothing is emitted. `AISOC_MCP_AGENT_ID`+ names this server in the AI-estate inventory. Argument *keys* are recorded+ and values are not, because which tool ran with which parameters is the+ signal while the values are often the sensitive part.---diff --git a/services/mcp/src/server.ts b/services/mcp/src/server.tsindex 7d7c33ddc..b3f9a18f0 100644--- a/services/mcp/src/server.ts+++ b/services/mcp/src/server.ts@@ -42,6 +42,7 @@ import {formatErrorForTool,} from "./errors.js";import { ALL_TOOLS, TOOL_BY_NAME } from "./tools/index.js";+import { ToolCallTelemetry, argumentKeys } from "./telemetry.js";import type { ToolResult } from "./tools/types.js";/** Server instructions surfaced to MCP hosts during initialisation. */@@ -65,6 +66,10 @@ Every agent decision in AiSOC is logged to a persistent ledger; \*/export function buildServer(cfg: ServerConfig, log: Logger): Server {const client = new AisocClient(cfg, log);+ // This server is a standing read path into a customer's alerts, cases and+ // event lake, and until now nothing recorded what it read. Off unless+ // AISOC_MCP_TELEMETRY_URL is set.+ const telemetry = new ToolCallTelemetry(log);const server = new Server({ name: "@aisoc/mcp", version: packageVersion() },{@@ -88,8 +93,19 @@ export function buildServer(cfg: ServerConfig, log: Logger): Server {server.setRequestHandler(CallToolRequestSchema, async (request) => {const name = request.params.name;+ // Every exit path below records, including the failures. A tool call that+ // was refused is as much a part of the account of what this key did as one+ // that succeeded.+ const startedAt = Date.now();+ const keys = argumentKeys(request.params.arguments);const tool = TOOL_BY_NAME[name];if (!tool) {+ telemetry.record({+ tool_name: name,+ argument_keys: keys,+ outcome: "unknown_tool",+ latency_ms: Date.now() - startedAt,+ });// Unknown tool. Return as a tool-failure rather than throwing so the// agent gets a clear human message instead of a transport error.return toErrorResult(@@ -103,6 +119,12 @@ export function buildServer(cfg: ServerConfig, log: Logger): Server {const issues = parse.error.issues.map((i) => `${i.path.join(".") || "<root>"}: ${i.message}`,);+ telemetry.record({+ tool_name: name,+ argument_keys: keys,+ outcome: "invalid_arguments",+ latency_ms: Date.now() - startedAt,+ });return toErrorResult(formatErrorForTool(new InvalidArgumentsError(name, issues)),);@@ -110,8 +132,21 @@ export function buildServer(cfg: ServerConfig, log: Logger): Server {try {const result = await tool.handle({ client, log }, parse.data);+ telemetry.record({+ tool_name: name,+ argument_keys: keys,+ outcome: "success",+ latency_ms: Date.now() - startedAt,+ });return toSuccessResult(result);} catch (err) {+ telemetry.record({+ tool_name: name,+ argument_keys: keys,+ outcome: "error",+ latency_ms: Date.now() - startedAt,+ error_kind: err instanceof Error ? err.constructor.name : "unknown",+ });// Log full error to stderr for debugging; surface a sanitised message// to the agent. We deliberately don't include stack traces in the// MCP response (PII / secrets risk).diff --git a/services/mcp/src/telemetry.ts b/services/mcp/src/telemetry.tsnew file mode 100644index 000000000..ce23e923f--- /dev/null+++ b/services/mcp/src/telemetry.ts@@ -0,0 +1,167 @@+/**+ * Tool-call telemetry for this MCP server.+ *+ * The README claimed "every tool call logged through this server lands in the+ * AiSOC audit log with the calling user and the tool name. You can revoke the+ * key and replay every action it took." None of that was true. The server+ * emitted nothing, and the API's `audit_middleware` only records mutating+ * methods carrying a valid JWT, so the ten read tools (`aisoc_list_*`,+ * `aisoc_get_*`, `aisoc_lake_query`) produced no audit row at all — and what+ * it did record was an HTTP path rather than a tool name.+ *+ * That gap matters more here than in most places. This server is how an+ * assistant reads a customer's alerts, cases and event lake, which makes it a+ * standing data-egress path that nobody could account for after the fact.+ *+ * So AiSOC's own MCP server is the first monitored asset in the AI estate+ * capability. Records go to the same `ai-runtime` inbox template as any+ * customer agent, meaning the surface AiSOC ships is held to the contract it+ * asks customers to adopt.+ *+ * Three deliberate limits:+ *+ * - **Argument keys, never values.** Which tool ran with which parameter names+ * is the signal; the values are frequently the sensitive part (an alert id,+ * a lake query, a hostname).+ * - **Fire-and-forget.** Telemetry must not add latency to, or fail, a tool+ * call. Every failure path here is swallowed and counted.+ * - **Off unless configured.** No endpoint means no emission and no warning+ * spam; an operator who has not opted in has not misconfigured anything.+ */++import type { Logger } from "./config.js";++/** What we record about one tool invocation. */+export interface ToolCallRecord {+ tool_name: string;+ /** Parameter names supplied. Values are deliberately excluded. */+ argument_keys: string[];+ outcome: "success" | "error" | "invalid_arguments" | "unknown_tool";+ latency_ms: number;+ /** Subject of the calling key, when the transport made one available. */+ on_behalf_of?: string;+ error_kind?: string;+}++export interface TelemetryCounters {+ recorded: number;+ sent: number;+ failed: number;+}++const FLUSH_INTERVAL_MS = 2_000;+const MAX_BUFFER = 200;+const REQUEST_TIMEOUT_MS = 5_000;++/**+ * Buffers tool-call records and posts them to an AiSOC inbox token.+ *+ * Configured by `AISOC_MCP_TELEMETRY_URL`. Absent that, `enabled` is false and+ * every method is a no-op.+ */+export class ToolCallTelemetry {+ private readonly endpoint: string | undefined;+ private readonly agentId: string;+ private readonly log: Logger;+ private buffer: Record<string, unknown>[] = [];+ private timer: NodeJS.Timeout | undefined;+ private counters: TelemetryCounters = { recorded: 0, sent: 0, failed: 0 };++ constructor(log: Logger, endpoint = process.env.AISOC_MCP_TELEMETRY_URL) {+ this.log = log;+ this.endpoint = endpoint?.trim() || undefined;+ this.agentId = process.env.AISOC_MCP_AGENT_ID?.trim() || "aisoc-mcp-server";++ if (this.enabled) {+ this.timer = setInterval(() => void this.flush(), FLUSH_INTERVAL_MS);+ // Do not hold the process open purely to flush telemetry.+ this.timer.unref?.();+ }+ }++ get enabled(): boolean {+ return this.endpoint !== undefined;+ }++ stats(): TelemetryCounters {+ return { ...this.counters };+ }++ /** Record one tool call. Never throws. */+ record(entry: ToolCallRecord): void {+ if (!this.enabled) return;+ this.counters.recorded += 1;+ this.buffer.push({+ agent_id: this.agentId,+ agent_name: "AiSOC MCP Server",+ timestamp: new Date().toISOString(),+ tool_name: entry.tool_name,+ argument_keys: entry.argument_keys,+ outcome: entry.outcome,+ latency_ms: Math.round(entry.latency_ms),+ // A failed tool call is not a security finding, so routine severity.+ // The ai-runtime template maps this to OCSF 6003 API Activity, which is+ // category 6 and therefore lake-only rather than auto-promoted.+ severity: entry.outcome === "success" ? "info" : "low",+ ...(entry.on_behalf_of ? { on_behalf_of: entry.on_behalf_of } : {}),+ ...(entry.error_kind ? { error_kind: entry.error_kind } : {}),+ });++ // Bounded: an unreachable endpoint must not grow memory without limit.+ // Drop the oldest, because recent activity is the more useful signal.+ if (this.buffer.length > MAX_BUFFER) {+ this.buffer.splice(0, this.buffer.length - MAX_BUFFER);+ }+ }++ /** Post whatever is buffered. Never throws. */+ async flush(): Promise<void> {+ if (!this.enabled || this.buffer.length === 0) return;+ const batch = this.buffer;+ this.buffer = [];++ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);+ try {+ const res = await fetch(this.endpoint as string, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "User-Agent": "aisoc-mcp-telemetry",+ },+ body: JSON.stringify(batch),+ signal: controller.signal,+ });+ if (res.ok) {+ this.counters.sent += batch.length;+ } else {+ this.counters.failed += batch.length;+ this.log.info(`telemetry: inbox returned HTTP ${res.status}`);+ }+ } catch (err) {+ // Telemetry failure must never surface into a tool call's control flow.+ this.counters.failed += batch.length;+ this.log.info(+ `telemetry: dropped ${batch.length} record(s): ${String(err)}`,+ );+ } finally {+ clearTimeout(timeout);+ }+ }++ async close(): Promise<void> {+ if (this.timer) clearInterval(this.timer);+ await this.flush();+ }+}++/**+ * Parameter names from a tool-call argument object, sorted for stability.+ *+ * Values are never read. A stable order means a detection can match on the+ * key set without the gateway's iteration order mattering.+ */+export function argumentKeys(args: unknown): string[] {+ if (args === null || typeof args !== "object" || Array.isArray(args)) return [];+ return Object.keys(args as Record<string, unknown>).sort();+}diff --git a/services/mcp/tests/telemetry.test.ts b/services/mcp/tests/telemetry.test.tsnew file mode 100644index 000000000..451527429--- /dev/null+++ b/services/mcp/tests/telemetry.test.ts@@ -0,0 +1,146 @@+/**+ * The README claimed "every tool call logged through this server lands in the+ * AiSOC audit log with the calling user and the tool name. You can revoke the+ * key and replay every action it took."+ *+ * The server emitted nothing. The API's `audit_middleware` only records+ * mutating methods carrying a valid JWT, so the ten read tools produced no+ * audit row at all, and what it did record was an HTTP path rather than a tool+ * name. This server is a standing read path into a customer's alerts, cases+ * and event lake, so the gap was a data-egress path nobody could account for.+ */++import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";+import { ToolCallTelemetry, argumentKeys } from "../src/telemetry.js";++const log = { info: () => {}, error: () => {}, warn: () => {} } as never;+const ENDPOINT = "https://aisoc.example.com/v1/inbox/mcp-token";++describe("argumentKeys", () => {+ it("returns parameter names, never values", () => {+ // Which tool ran with which parameter names is the signal. The values are+ // frequently the sensitive part: an alert id, a lake query, a hostname.+ const keys = argumentKeys({ alert_id: "a-secret-id", limit: 10 });+ expect(keys).toEqual(["alert_id", "limit"]);+ expect(JSON.stringify(keys)).not.toContain("a-secret-id");+ });++ it("is sorted so a detection can match on the key set", () => {+ expect(argumentKeys({ z: 1, a: 2 })).toEqual(["a", "z"]);+ });++ it("handles the shapes a transport can actually deliver", () => {+ expect(argumentKeys(undefined)).toEqual([]);+ expect(argumentKeys(null)).toEqual([]);+ expect(argumentKeys([1, 2])).toEqual([]);+ expect(argumentKeys("string")).toEqual([]);+ });+});++describe("ToolCallTelemetry", () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ fetchMock = vi.fn(async () => ({ ok: true, status: 200 }) as never);+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("is disabled without an endpoint, and silently so", () => {+ // An operator who has not opted in has not misconfigured anything, so+ // this must not warn or buffer.+ const t = new ToolCallTelemetry(log, undefined);+ expect(t.enabled).toBe(false);+ t.record({+ tool_name: "aisoc_list_alerts",+ argument_keys: [],+ outcome: "success",+ latency_ms: 5,+ });+ expect(t.stats().recorded).toBe(0);+ });++ it("records a successful tool call", async () => {+ const t = new ToolCallTelemetry(log, ENDPOINT);+ t.record({+ tool_name: "aisoc_list_alerts",+ argument_keys: ["limit"],+ outcome: "success",+ latency_ms: 12,+ });+ await t.flush();++ expect(fetchMock).toHaveBeenCalledOnce();+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);+ expect(body).toHaveLength(1);+ expect(body[0].tool_name).toBe("aisoc_list_alerts");+ expect(body[0].argument_keys).toEqual(["limit"]);+ expect(body[0].outcome).toBe("success");+ expect(body[0].agent_id).toBe("aisoc-mcp-server");+ // Routine activity: the ai-runtime template maps info severity to OCSF+ // 6003 API Activity, category 6, which stays in the lake rather than+ // becoming an alert. A read tool doing its job is not an incident.+ expect(body[0].severity).toBe("info");+ });++ it("records refused calls too", async () => {+ // A tool call that was rejected is as much a part of the account of what+ // a key did as one that succeeded.+ const t = new ToolCallTelemetry(log, ENDPOINT);+ for (const outcome of ["error", "invalid_arguments", "unknown_tool"] as const) {+ t.record({ tool_name: "x", argument_keys: [], outcome, latency_ms: 1 });+ }+ await t.flush();+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);+ expect(body.map((r: { outcome: string }) => r.outcome)).toEqual([+ "error",+ "invalid_arguments",+ "unknown_tool",+ ]);+ expect(body.every((r: { severity: string }) => r.severity === "low")).toBe(true);+ });++ it("never throws when the inbox is unreachable", async () => {+ // Telemetry must not surface into a tool call's control flow.+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => {+ throw new Error("ECONNREFUSED");+ }),+ );+ const t = new ToolCallTelemetry(log, ENDPOINT);+ t.record({ tool_name: "x", argument_keys: [], outcome: "success", latency_ms: 1 });+ await expect(t.flush()).resolves.toBeUndefined();+ expect(t.stats().failed).toBe(1);+ });++ it("counts a non-2xx response as failed rather than sent", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false, status: 401 }) as never));+ const t = new ToolCallTelemetry(log, ENDPOINT);+ t.record({ tool_name: "x", argument_keys: [], outcome: "success", latency_ms: 1 });+ await t.flush();+ expect(t.stats().failed).toBe(1);+ expect(t.stats().sent).toBe(0);+ });++ it("bounds the buffer so an unreachable inbox cannot grow memory", async () => {+ const t = new ToolCallTelemetry(log, ENDPOINT);+ for (let i = 0; i < 500; i += 1) {+ t.record({ tool_name: `t-${i}`, argument_keys: [], outcome: "success", latency_ms: 1 });+ }+ await t.flush();+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);+ expect(body.length).toBeLessThanOrEqual(200);+ // The oldest are dropped, because recent activity is the useful signal.+ expect(body[body.length - 1].tool_name).toBe("t-499");+ });++ it("flushing an empty buffer makes no request", async () => {+ const t = new ToolCallTelemetry(log, ENDPOINT);+ await t.flush();+ expect(fetchMock).not.toHaveBeenCalled();+ });+});