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.

fix(actions): one grading function for both dispatch doors, and probes for the verbs that could have one (#873)

Beenu Arora6608c8e26b5e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84939699a..648864163 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### The documented quick start broke the product, and then the product had nothing to show
+
Every item below passed the existing test suite and failed on a real
deployment. They are grouped by what a new user actually hit, in the order
they hit it.
@@ -189,6 +190,7 @@ number is the one the requirement is sized against.
### Added
+
- **`RENDER_FALLBACK_EXEMPT` is now checked in both directions.**
`ALLOWED_ILLUSTRATIVE` had a staleness check from the start and this list
had none, so an exemption could outlive the code it excused and go on
@@ -346,8 +348,32 @@ number is the one the requirement is sized against.
also caught `<ul role="alert">`, which is not an allowed role for a list and
left its items without a list parent.
+- **Verification probes for the disruptive endpoint verbs.** `kill_process`
+ and `quarantine_file` had their success inferred from CrowdStrike RTR
+ accepting a command; both now read the effect back over the read-only tier
+ of the same batch API — the process table for the PID, the path for the
+ removed file. Absence is only trusted when the output can be recognised as
+ what it claims to be, so an unparseable `ps` listing is indeterminate
+ rather than "the process is gone", and only a line's first column is read
+ as a PID so a surviving child does not report its dead parent as alive.
+ `run_av_scan` joins them because it is automatic and Defender replies
+ `Pending` the moment it queues the sweep: it reads the machine action's
+ terminal state, and says indeterminate while the scan is still running.
+
+- **Every verb with an `ActionType` now either declares a probe or records
+ why it has none.** Eleven bridged response verbs had neither, which failed
+ safe but made three different situations look the same: nobody wrote it,
+ the vendor exposes no read-back, and there is nothing to read back. The
+ eight without probes now state which — including `reset_password`, where
+ the obvious candidate read is the *wrong* one rather than a missing one
+ (the executor issues a recovery link, so `passwordChanged` moves later and
+ only if the user follows it, and a probe watching it would report FAILED
+ for every correct reset). The below-MODERATE waiver must now name itself,
+ because `run_av_scan` had been taking it silently.
+
### Changed
+
- **`readme_gates.py` covers the governance documents.** Its `FIGURE_DOCS`
list named one compliance page, which is why `ROADMAP.md` drifted with CI
green. `ROADMAP.md` and `RELEASES.md` are now on the list, the matrix
@@ -379,8 +405,17 @@ number is the one the requirement is sized against.
freshness gate reads only the date — which a refresh keeps current — so a
row could be two days old and still labelled two majors behind.
+- `tests/test_approval_doors_agree.py` gates the invariant rather than the
+ instance: both live doors swept over every capability, autonomy tier and
+ confidence band, asserting the same answer to "did a vendor get touched
+ without a human". Structural checks alongside it fail a door that imports
+ the raw matrix or branches on a specific impact tier, which is the shape a
+ re-introduced bypass has. Against the previous tree it reports five
+ disagreements across 345 combinations.
+
### Fixed
+
- **`check_mock_data_gated.py` reported "All sample-data fallbacks are gated
behind demo mode." on a tree carrying nine of them.** Each gap was confirmed
by running the gate's own patterns against the live lines rather than by
@@ -862,8 +897,45 @@ number is the one the requirement is sized against.
hosted demo the dock now reports that the copilot could not be reached, with
the error, instead of emitting a reply.
+- **A pure read sat in the analyst approval queue, because the two dispatch
+ doors graded the same verb differently.** `search_siem` declares
+ `read_only` impact and `automatic` approval, and the contract gate's own
+ rule is that a read requiring approval "is either mis-classified or is not
+ actually a read". At the default autonomy tier `POST /actions` returned
+ `awaiting_approval` for it while `POST /live-actions/dispatch` executed it.
+ The dispatcher's docstring says its contract block exists so that a verb is
+ not "graded differently depending on which door it came through", and that
+ is precisely what was happening.
+
+ The cause was one table entry, not a missing bypass.
+ `TIER_MAX_AUTOMATIC["L1"]` was `None`, meaning "auto-executes nothing",
+ while `maturity.py` defines L1 as "MINIMAL blast-radius actions are
+ automatic" and `_AUTO_ALLOWED_AT_TIER` gives it `{MINIMAL}` — which
+ `_IMPACT_BLAST` equates with READ_ONLY impact. The registry door had grown
+ a local READ_ONLY short-circuit to route around it; the legacy door had
+ not. L1 now reads `READ_ONLY`, and only reads move: every impact above it
+ still outranks the ceiling and still returns ANALYST, exactly as the `None`
+ branch did. L0 keeps `None`, which now means one thing only — observe, not
+ even a read.
+
+ With the ceiling correct the bypass is unnecessary, so it is gone.
+ `approval_matrix.evaluate_contract()` takes a contract whole and is the
+ single entry both doors call, which removes the per-door unpacking that let
+ them drift in the first place.
+
+- **`update_alert_disposition` had no `ACTION_BLAST_RADIUS` entry**, found by
+ the new cross-door sweep rather than reported. Four readers of that table
+ supplied two different fallbacks — `blast_radius.py` to MEDIUM, which is
+ exactly `_AUTO_EXECUTE_LIMIT`, and the three tier gates to HIGH — so the
+ legacy door auto-executed the disposition writeback while the registry door
+ held it for a whitelist it could never match. It now carries the LOW entry
+ its own contract asks for ("classified the same as create_notable_event"),
+ and `blast_radius.py` fails closed like its three siblings.
+=======
+
### Removed
+
- **`apps/web/src/components/copilot/InvestigationChat.tsx`** — canned
threat-intel replies ("VirusTotal: 14/87 engines flagged malicious",
"Associated campaigns: APT-42"), a fixed context sidebar, no API call for
@@ -917,6 +989,7 @@ number is the one the requirement is sized against.
from the registry now. `packHelpers.ts` mapped step types to integration
badges as a `Record<string, …>` covering eighteen of twenty-two, so a
playbook built from the other four claimed to use no integrations at all.
+
## [10.0.0] — 2026-09-25
**Two ways for a control to be absent: not written, or written and not
diff --git a/PROGRESS-p4a.md b/PROGRESS-p4a.md
new file mode 100644
index 000000000..683f41e75
--- /dev/null
+++ b/PROGRESS-p4a.md
@@ -0,0 +1,45 @@
+# Phase 4a — read-only approval split + verification probes
+
+Worktree: `/Users/beenu/Desktop/AiSOC-p4a`, branch `fix/read-only-approval-and-probes` off `origin/main` (46b1ad74).
+
+## Item 1 — a pure read in the analyst queue
+
+- [x] Reproduced through the API: `POST /actions` with `search_siem` at the default tier returned
+ `awaiting_approval`; `POST /live-actions/dispatch` executed the same verb.
+- [x] Root cause: `TIER_MAX_AUTOMATIC["L1"] = None`, contradicting `maturity.py`
+ (`_AUTO_ALLOWED_AT_TIER[L1_NOTIFY] = {MINIMAL}`) and `_IMPACT_BLAST` (READ_ONLY <=> MINIMAL).
+- [x] Unified: new `approval_matrix.evaluate_contract()` is the single grading entry; the
+ dispatcher's local READ_ONLY bypass deleted; `approval_gate` calls the same function.
+- [x] Two tests that *encoded* the defect rewritten to assert the correct behaviour (both halves).
+- [x] Second instance found by the sweep: `update_alert_disposition` had no `ACTION_BLAST_RADIUS`
+ entry, and four call sites read that table with two different fallbacks (MEDIUM vs HIGH).
+ Added the entry (LOW, per its own contract note); `blast_radius.py` now fails closed to HIGH.
+- [x] Cross-door sweep: 345 combinations. Baseline on origin/main: 5 disagreements. Now: 0.
+- [ ] Invariant test file committed.
+
+## Item 2 — eleven bridged response verbs with no probe
+
+Unprobed: block_ioc, create_notable_event, create_ticket, force_mfa, kill_process,
+quarantine_file, reset_password, revoke_session, run_av_scan, run_script, search_siem.
+Priority: kill_process, quarantine_file, run_script.
+
+- [ ] Classify each: real probe / honest unverified / demote.
+
+## Constraints in force
+
+- autospec'd signature tests for any new vendor arm
+- dry-run credential-strip list must match the client factory exactly (AST test re-derives it)
+- no fake success; `executed` is the only field meaning a vendor was touched
+- CHANGELOG under `[Unreleased]`, expect conflicts, resolve as union
+
+## Status at PR open
+
+PR: https://github.com/beenuar/AiSOC/pull/873 (4 commits)
+- ee99dae3 approval fix + invariant test
+- 960b2a38 probes
+- 010a1600 changelog
+- e5a4e8f8 claim-to-gate row (140 rows, 132 GATED / 8 PARTIAL / 0 NO GATE)
+
+Local verification: 737 actions tests pass (671 on main); mypy 24 findings = baseline;
+ruff clean; check_action_contract OK; check_claim_gate_matrix OK; attribution OK.
+Remaining: watch CI, resolve conflicts, merge without --delete-branch, confirm main moved.
diff --git a/RELEASES.md b/RELEASES.md
index f6c1d49c6..1c263f795 100644
--- a/RELEASES.md
+++ b/RELEASES.md
@@ -2,7 +2,7 @@
This file mirrors what used to live in the "What's new" section of [`README.md`](README.md). The complete, machine-readable inventory (with file paths, env-var diffs, and per-release test counts) lives in [`CHANGELOG.md`](CHANGELOG.md).
-> **TL;DR for first-time visitors:** AiSOC is on `v10.0.0`, released 2026-09-25 — a release about controls that were written and not reachable. Row-level security covered 92 tables and filtered nothing, because every service connected to Postgres as a superuser; fifty-eight routes carried no authentication at all; UEBA reported healthy and could not write an anomaly; AI triage was wired to a gateway both of its resolvers ignored. **It is a major because upgrading requires action** — services now connect as a DML-only `aisoc_app` role. Every product claim is backed by a failing CI test (claim-to-gate matrix: 143 rows — 135 GATED / 8 PARTIAL / 0 NO GATE). The latest GitHub release with notes and downloads: <https://github.com/beenuar/AiSOC/releases/latest>.
+> **TL;DR for first-time visitors:** AiSOC is on `v10.0.0`, released 2026-09-25 — a release about controls that were written and not reachable. Row-level security covered 92 tables and filtered nothing, because every service connected to Postgres as a superuser; fifty-eight routes carried no authentication at all; UEBA reported healthy and could not write an anomaly; AI triage was wired to a gateway both of its resolvers ignored. **It is a major because upgrading requires action** — services now connect as a DML-only `aisoc_app` role. Every product claim is backed by a failing CI test (claim-to-gate matrix: 144 rows — 136 GATED / 8 PARTIAL / 0 NO GATE). The latest GitHub release with notes and downloads: <https://github.com/beenuar/AiSOC/releases/latest>.
---
diff --git a/ROADMAP.md b/ROADMAP.md
index dcb4955c7..ce1a372d5 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **143 rows — 135 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **144 rows — 136 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 47a5fde06..a371040da 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: 135 rows
+The last row is the one worth reading first. It is the honest index: 136 rows
`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refuses
to let a row sit at `NO GATE`.
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 77cafe7ce..49d71252b 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -151,10 +151,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Published detection / marketplace counts match the tree | landing page (`Hero.tsx`, `ConnectorsMarquee.tsx`, `FeatureGrid.tsx`, `Pillars.tsx`), `ContributorLeaderboard.tsx` | `ci.yml :: python-lint` (`generate_corpus_stats.py --check` — the counts are generated into `apps/web/src/data/corpus-stats.json` + `corpusStats.ts` and imported, so a surface cannot carry its own literal; the generator reconciles three independent sources against each other — the compiled engine ruleset, `docs/detections/truth-table.md` and `marketplace/index.json` — and refuses to publish if they disagree. The landing page previously gave three different wrong answers at once: 6,998 detections in four places, 7,117 marketplace items, and 218 rules on the leaderboard, with no gate on any of them) | GATED | - |
| The corpus figure the product executes is distinguished from the corpus on disk | landing page, `docs/detections/truth-table.md` | `ci.yml :: python-lint` (`generate_corpus_stats.py --check` emits `executable` and `onDisk`/`quarantined` as separate fields and the UI leads with `EXECUTABLE_DETECTION_COUNT`; ~85% of the indexed corpus sits under `_quarantine/` and is never loaded, so quoting the on-disk figure as the detection capability presents quarantined rules as executable) | GATED | - |
| The retracted 75.3% alert-reduction figure is never presented as a measurement | `apps/docs/docs/benchmark.md`, `benchmarks/alert-reduction.md`, `BenchmarkResults.tsx`, `ComparisonTable.tsx`, `benchmark/page.tsx` | `ci.yml :: python-lint` (`check_alert_reduction_claims.py --check` — scans every published surface: no file may assert the legacy harness runs the production grouping ("faithful re-implementation", "same logic"), any file quoting 75.3% must carry the retraction, the `alert_reduction` suite card may not be declared `kind: 'measurement'`, and every surface publishing the real figure must quote `PUBLISHED_REDUCTION_PCT` from `services/fusion/tests/test_alert_reduction_real.py`, which that test asserts against its own measurement — so the chain from measurement to prose has no hand-copied link. `benchmark.md` had withdrawn the claim while two other surfaces went on asserting it, and `benchmark.md` itself re-asserted it in its own intro blockquote) | GATED | - |
+| The same verb is graded identically whichever dispatch door it arrives through | README (graduated autonomy); `concepts/live-actions.md` | `ci.yml` actions job (`test_approval_doors_agree.py` — both live doors driven over 23 capabilities x 5 tiers x 3 confidence bands, 345 combinations, asserting the same answer to "did a vendor get touched without a human". A dry-run preview does not count as a touch, since the registry door downgrades an over-tier request to one. Against the previous tree it reports 5 disagreements: `search_siem` is read_only and automatic and sat in the analyst queue at the default tier while executing through the other door, because `TIER_MAX_AUTOMATIC["L1"]` said a tier the ladder defines as "MINIMAL blast-radius actions are automatic" auto-executes nothing; and `update_alert_disposition` was the one ActionType with no `ACTION_BLAST_RADIUS` entry, which is not a missing entry but two different ones, since the four readers of that table supply two different fallbacks. Structural checks alongside it fail a door that imports the raw matrix or compares against a specific `ActionImpact` inside its grading path — the shape a re-introduced bypass has — and require every `ActionType` to carry an explicit blast radius so neither fallback decides anything) | GATED | the grading itself is one function, `approval_matrix.evaluate_contract`, rather than two kept in agreement by discipline; the sweep exists for the axis it cannot unify, which is each door's separate blast-radius layer |
## Summary
-- GATED: 135
+- GATED: 136
- PARTIAL: 8
- 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/services/actions/app/clients/crowdstrike_rtr.py b/services/actions/app/clients/crowdstrike_rtr.py
index cf2c57388..7a733c39f 100644
--- a/services/actions/app/clients/crowdstrike_rtr.py
+++ b/services/actions/app/clients/crowdstrike_rtr.py
@@ -295,3 +295,101 @@ class CrowdStrikeRTRClient:
)
resp.raise_for_status()
return {"device_id": device_id, "action": "run_script", "response": resp.json()}
+
+ async def _read_only_command(self, device_id: str, base_command: str, command_string: str) -> str | None:
+ """Run an RTR *read* command and return this host's stdout.
+
+ ``/real-time-response/combined/batch-command/v1`` is the read-only
+ tier of the same batch API the containment commands above use —
+ ``ls``, ``ps``, ``cat``, ``netstat``. It is a separate endpoint from
+ ``batch-active-responder-command`` (``kill``, ``rm``) and
+ ``batch-admin-command`` (``runscript``) precisely because it cannot
+ change anything, so a verification path can hold read scope only.
+
+ Returns ``None`` — never ``""`` — for every way this can fail to
+ produce an answer: no session, a non-200, a host missing from the
+ batch response, or a command the agent reported incomplete. The
+ callers treat ``None`` as indeterminate, and an empty string is a
+ real result (``ls`` on a path that is gone), so collapsing the two
+ would turn "could not ask" into evidence.
+ """
+ try:
+ async with httpx.AsyncClient(timeout=60.0) as client:
+ await self._ensure_token(client)
+ batch_id = await self._init_rtr_session(client, device_id)
+ resp = await client.post(
+ f"{self._base_url}/real-time-response/combined/batch-command/v1",
+ headers=self._auth_headers(),
+ json={
+ "base_command": base_command,
+ "batch_id": batch_id,
+ "command_string": command_string,
+ "optional_hosts": [device_id],
+ },
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "crowdstrike.read_only_command.http_error",
+ device_id=device_id,
+ base_command=base_command,
+ status=resp.status_code,
+ )
+ return None
+ host = (resp.json().get("combined", {}).get("resources", {}) or {}).get(device_id)
+ if not isinstance(host, dict):
+ return None
+ if host.get("complete") is False:
+ # The agent is offline or still working. Not an answer.
+ return None
+ stdout = host.get("stdout")
+ return stdout if isinstance(stdout, str) else None
+ except Exception as exc: # noqa: BLE001 - indeterminate, never a false confirmation
+ logger.warning(
+ "crowdstrike.read_only_command.failed",
+ device_id=device_id,
+ base_command=base_command,
+ error=str(exc),
+ )
+ return None
+
+ async def is_process_running(self, device_id: str, pid: int) -> bool | None:
+ """Whether ``pid`` still appears in the host's process table.
+
+ The read-back for ``kill_process``, whose own response says only that
+ RTR accepted a ``kill``. ``None`` means the question could not be
+ answered.
+
+ Absence is only trusted when the output looks like a process table —
+ at least one line whose first column is a number. If RTR returns
+ something this cannot parse, no PID is found, and reporting that as
+ "the process is gone" would confirm a kill from output we did not
+ understand. Only the first column is matched, so a surviving child
+ listing the dead PID as its parent does not read as the process
+ itself.
+ """
+ stdout = await self._read_only_command(device_id, "ps", "ps")
+ if stdout is None:
+ return None
+
+ first_columns = [line.split()[0] for line in stdout.splitlines() if line.split()]
+ numeric = [column for column in first_columns if column.isdigit()]
+ if not numeric:
+ logger.warning("crowdstrike.is_process_running.unparsed", device_id=device_id)
+ return None
+ return str(pid) in numeric
+
+ async def path_exists(self, device_id: str, path: str) -> bool | None:
+ """Whether ``path`` still resolves on the host.
+
+ The read-back for ``quarantine_file``, which is implemented as an RTR
+ ``rm``: the effect to confirm is the file's absence.
+
+ ``ls`` on a path that is gone returns an error and no stdout, so an
+ empty listing is the confirmation. That makes the empty string
+ load-bearing, which is why ``_read_only_command`` distinguishes it
+ from ``None``.
+ """
+ stdout = await self._read_only_command(device_id, "ls", f"ls '{path}'")
+ if stdout is None:
+ return None
+ return bool(stdout.strip())
diff --git a/services/actions/app/executors/endpoint.py b/services/actions/app/executors/endpoint.py
index caac1992b..87fc6c91f 100644
--- a/services/actions/app/executors/endpoint.py
+++ b/services/actions/app/executors/endpoint.py
@@ -515,6 +515,12 @@ class RunScriptExecutor(BaseExecutor):
#: the executor and the verification probe cannot look for different things.
INVESTIGATION_PACKAGE_ACTION = "CollectInvestigationPackage"
+#: The MDE machine-action type an antivirus sweep produces, for the same
+#: reason. ``DefenderClient.run_av_scan`` posts to ``/runAntiVirusScan`` and
+#: returns the queued action's id; this is what that action is called when
+#: the verification probe has to find it by type instead.
+AV_SCAN_ACTION = "RunAntiVirusScan"
+
class CaptureForensicsExecutor(BaseExecutor):
"""Acquire a forensic evidence package from a host.
diff --git a/services/actions/app/live_actions/capability_contracts.py b/services/actions/app/live_actions/capability_contracts.py
index c0d32ff0d..23357a936 100644
--- a/services/actions/app/live_actions/capability_contracts.py
+++ b/services/actions/app/live_actions/capability_contracts.py
@@ -93,6 +93,14 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
approval=ApprovalRequirement.AUTOMATIC,
reversal=Reversal.NOT_APPLICABLE,
required_permission=_READ,
+ has_verification_probe=False,
+ verification_gap=(
+ "A read leaves nothing behind to read back. Verification answers "
+ "'did the write land', and there is no write — the results are "
+ "the response, and a second query would not confirm the first, it "
+ "would be another one. Recorded rather than left blank so this "
+ "reads as the answer it is and not as an omission."
+ ),
note="A query. Safe at any confidence, which is the point of separating impact from confidence.",
),
# ── Endpoint containment ───────────────────────────────────────────────
@@ -130,7 +138,16 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
reversal=Reversal.PLATFORM,
reverse_capability="restore_file",
required_permission=_CONTAIN,
- note="Quarantining a legitimate binary breaks whatever depended on it.",
+ has_verification_probe=True,
+ note=(
+ "Quarantining a legitimate binary breaks whatever depended on it. "
+ "The CrowdStrike arm is an RTR 'rm', so the probe reads the path "
+ "back with 'ls': the effect is the file's absence, and RTR "
+ "accepting a delete is not the same fact. SentinelOne's arm "
+ "fetches the file into the forensics vault instead of removing "
+ "it, so the probe reports indeterminate there rather than "
+ "checking for an absence that arm never causes."
+ ),
),
"restore_file": CapabilityContract(
impact=ActionImpact.MODERATE,
@@ -144,10 +161,16 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
approval=ApprovalRequirement.ANALYST,
reversal=Reversal.SELF_HEALING,
required_permission=_CONTAIN,
+ has_verification_probe=True,
note=(
"A killed process cannot be un-killed, but the effect does not "
"persist: a service restarts, a user runs the program again. "
- "Self-healing is the honest answer here, not 'irreversible'."
+ "Self-healing is the honest answer here, not 'irreversible'. "
+ "The probe re-reads the host's process table over RTR, because "
+ "an accepted 'kill' and a dead process differ whenever the agent "
+ "is offline or the process is protected. SentinelOne targets "
+ "binaries by hash and lists no processes, so that arm reports "
+ "indeterminate."
),
),
"run_av_scan": CapabilityContract(
@@ -155,7 +178,16 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
approval=ApprovalRequirement.AUTOMATIC,
reversal=Reversal.SELF_HEALING,
required_permission=_CONTAIN,
- note="Consumes CPU on one host and finishes. Nothing to undo.",
+ has_verification_probe=True,
+ note=(
+ "Consumes CPU on one host and finishes. Nothing to undo. It is "
+ "automatic, and Defender replies 'Pending' the instant it queues "
+ "the sweep — so the response is the one thing that certainly is "
+ "not the confirmation. The probe reads the machine action's "
+ "terminal state instead, and answers indeterminate while the "
+ "scan is still running, which an immediate post-dispatch check "
+ "almost always is."
+ ),
),
"run_script": CapabilityContract(
impact=ActionImpact.SEVERE,
@@ -288,7 +320,18 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
reversal=Reversal.SELF_HEALING,
required_permission=_IDENTITY,
has_verification_probe=False,
- verification_gap="Same absent read-back as suspend_session.",
+ verification_gap=(
+ "Same absent read-back as suspend_session, stated here rather than "
+ "by reference because a gap that points at another entry stops "
+ "being checkable when that entry changes. Okta withdrew session "
+ "listing from the Management API and Entra's revokeSignInSessions "
+ "returns only an acknowledgement, so neither provider will say "
+ "whether the sessions are gone. The nearest readable field, "
+ "Entra's signInSessionsValidFromDateTime, moves when the call is "
+ "accepted rather than when the tokens stop working, so a probe "
+ "reading it would report VERIFIED on the strength of the same "
+ "acknowledgement the executor already has."
+ ),
),
"reset_password": CapabilityContract(
impact=ActionImpact.HIGH,
@@ -300,7 +343,14 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
"Neither Okta nor Entra exposes a readable 'password was reset' state. "
"The user's lifecycle status is unchanged by a reset, so a probe "
"reading it would confirm nothing and report VERIFIED for a reset that "
- "never happened — worse than reporting unverified."
+ "never happened — worse than reporting unverified. The obvious "
+ "candidate, Okta's passwordChanged timestamp, is the wrong read and "
+ "not merely a missing one: the executor calls "
+ "lifecycle/reset_password with sendEmail, which issues a recovery "
+ "link. The password changes later, if the user follows it, so a "
+ "probe watching that field would report FAILED for every correctly "
+ "executed reset and VERIFIED only once the user had already "
+ "recovered. Entra's lastPasswordChangeDateTime behaves the same way."
),
note="The user recovers through the normal reset flow, but is locked out until they do.",
),
@@ -380,6 +430,15 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
reversal=Reversal.PLATFORM,
reverse_capability="allow_hash",
required_permission=_CONTAIN,
+ has_verification_probe=False,
+ verification_gap=(
+ "Same absent read as block_ioc, of which this is the narrowest "
+ "case: the indicator API creates and deletes and offers no list "
+ "to compare against. Unlike block_ioc this one is automatic, so "
+ "the gap is load-bearing and worth restating — it has no "
+ "ActionType either, which means a probe could not be keyed to it "
+ "even if Defender grew the read tomorrow."
+ ),
note=(
"A hash identifies one exact binary, so a wrong block affects only "
"that file. The narrowest containment the platform has, and the "
@@ -399,6 +458,16 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
reversal=Reversal.PLATFORM,
reverse_capability="allow_ioc",
required_permission=_NETWORK,
+ has_verification_probe=False,
+ verification_gap=(
+ "Defender's indicator API is write-only in this client: block_ioc "
+ "creates one and remove_ioc deletes one by id, and there is no read "
+ "of the current indicator set to compare against. Confirming the "
+ "indicator exists would also be the weaker of the two available "
+ "claims — what a responder needs to know is whether it is being "
+ "enforced on the estate, and Defender reports indicator "
+ "distribution nowhere this client can reach."
+ ),
note="Breadth depends on the indicator type, so it is classified at the worst case.",
),
"allow_ioc": CapabilityContract(
@@ -414,6 +483,17 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
approval=ApprovalRequirement.AUTOMATIC,
reversal=Reversal.MANUAL_ONLY,
required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "The creation is synchronous — Splunk's /services/notable_events "
+ "either writes the notable or returns an error, with no queued "
+ "state in between — so unlike run_av_scan the response really is "
+ "the confirmation. It is also the only one available: the reply "
+ "carries no event_id, and get_notable_event_state needs one. "
+ "Searching the notable index by rule name instead would match any "
+ "notable that rule has ever produced, which is a probe that "
+ "passes without the action."
+ ),
note="Writes a record into someone else's queue. Noise, not damage.",
),
"sync_detection_rule": CapabilityContract(
@@ -422,6 +502,15 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
reversal=Reversal.PLATFORM,
reverse_capability="sync_detection_rule",
required_permission=_CONTAIN,
+ has_verification_probe=False,
+ verification_gap=(
+ "The client writes correlation searches and watchers through "
+ "create-or-update calls and exposes no read of the saved "
+ "definition, so there is nothing to compare the intended content "
+ "against. Confirming the object merely exists would be the wrong "
+ "check anyway: this verb's failure mode is a rule that saved with "
+ "different content, not one that did not save."
+ ),
note=(
"Changing detection content in the customer's SIEM can silence a "
"rule as easily as add one. Its own reverse: sync the prior version."
@@ -433,6 +522,12 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
reversal=Reversal.PLATFORM,
reverse_capability="update_watcher",
required_permission=_CONTAIN,
+ has_verification_probe=False,
+ verification_gap=(
+ "Same absence as sync_detection_rule, which this is the Elastic "
+ "spelling of: the write goes through a create-or-update and no "
+ "read of the stored watcher comes back to compare against."
+ ),
),
"update_alert_disposition": CapabilityContract(
impact=ActionImpact.LOW,
@@ -503,24 +598,56 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
approval=ApprovalRequirement.AUTOMATIC,
reversal=Reversal.MANUAL_ONLY,
required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "This is the case the probe rule waives, and it is worth writing "
+ "down rather than leaving as an absence. Jira, ServiceNow and "
+ "PagerDuty all return the identifier they allocated, and none of "
+ "them can allocate one without having created the record — so the "
+ "response is the confirmation, in the strict sense that a "
+ "read-back could not tell us anything the create did not. The "
+ "identifier is also what every later step uses, so a fabricated "
+ "one fails loudly at the next transition rather than passing "
+ "silently."
+ ),
),
"push_case": CapabilityContract(
impact=ActionImpact.LOW,
approval=ApprovalRequirement.AUTOMATIC,
reversal=Reversal.MANUAL_ONLY,
required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "Creates a record in the ticketing system and gets its identifier "
+ "back, the same as create_ticket: the identifier cannot exist "
+ "without the record."
+ ),
),
"push_status": CapabilityContract(
impact=ActionImpact.LOW,
approval=ApprovalRequirement.AUTOMATIC,
reversal=Reversal.MANUAL_ONLY,
required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "Updates a record the caller already holds the identifier for, "
+ "and the vendors answer with the transition they applied. No "
+ "ActionType keys this one, so a probe could not be reached for it "
+ "in any case."
+ ),
),
"notify": CapabilityContract(
impact=ActionImpact.LOW,
approval=ApprovalRequirement.AUTOMATIC,
reversal=Reversal.MANUAL_ONLY,
required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "Chat platforms return the posted message's timestamp, which is "
+ "the confirmation — they cannot allocate one for a message they "
+ "did not post. Reading the channel back afterwards would answer a "
+ "different question, whether anyone has since deleted it."
+ ),
note=("A message cannot be unsent, but paging the wrong channel is embarrassment rather than impact."),
),
}
diff --git a/services/actions/app/live_actions/dispatcher.py b/services/actions/app/live_actions/dispatcher.py
index b7e6e3d06..6c1f3a1df 100644
--- a/services/actions/app/live_actions/dispatcher.py
+++ b/services/actions/app/live_actions/dispatcher.py
@@ -38,7 +38,7 @@ from uuid import uuid4
import structlog
from app.models.action import ActionRequest, ActionType
-from app.services.approval_matrix import evaluate as evaluate_matrix
+from app.services.approval_matrix import evaluate_contract
from app.services.autonomy_safety import (
_BLAST_ORDER,
ACTION_BLAST_RADIUS,
@@ -245,22 +245,14 @@ def _apply_capability_contract(
)
return decision
- if contract.impact is ActionImpact.READ_ONLY and contract.approval is ApprovalRequirement.AUTOMATIC:
- # A read has nothing to raise. `capability_contracts` calls the read
- # verbs "automatic by construction ... gating a read behind an analyst
- # is how an agent learns to conclude without looking", and
- # `approval_matrix`'s own docstring names an enrichment stuck in an
- # approval queue as a failure mode it exists to prevent — yet its tier
- # ceiling returns ANALYST for every impact at L0 and L1, which is the
- # default tier. Rather than overturn `TIER_MAX_AUTOMATIC`, which is a
- # deliberate posture for state-changing impact and is tested as one,
- # the read case keeps whatever blast radius decided. That still blocks
- # at L0, where nothing executes at all.
- return decision
-
- verdict = evaluate_matrix(
- impact=contract.impact,
- declared_approval=contract.approval,
+ # The whole grading, in one shared call. This used to short-circuit
+ # READ_ONLY + AUTOMATIC before reaching the matrix, because the matrix's
+ # tier ceiling was `None` at L1 and put a pure read in the analyst queue.
+ # The legacy door had no such bypass, so `search_siem` executed here and
+ # queued there. The ceiling is fixed at its source now, so the bypass is
+ # gone and both doors read the same answer out of the same function.
+ verdict = evaluate_contract(
+ contract=contract,
confidence=request.confidence,
tier=tier_label,
)
diff --git a/services/actions/app/models/action.py b/services/actions/app/models/action.py
index 17dcf9647..5c7720b6f 100644
--- a/services/actions/app/models/action.py
+++ b/services/actions/app/models/action.py
@@ -135,6 +135,15 @@ ACTION_BLAST_RADIUS: dict[ActionType, BlastRadius] = {
# because there's a documented unsuppress path in every vendor.
ActionType.ACK_ALERT: BlastRadius.MINIMAL,
ActionType.SUPPRESS_ALERT: BlastRadius.LOW,
+ # The one member that had no entry, which meant it had no single blast
+ # radius: four call sites read this table with two different fallbacks,
+ # `blast_radius.py` to MEDIUM and the three tier gates to HIGH. So the
+ # legacy door auto-executed the writeback while the registry door held it
+ # for a whitelist it could never match — the same verb, two grades,
+ # decided by a default nobody chose. LOW is what its own contract asks
+ # for: "classified the same as create_notable_event ... it changes a
+ # queue item, not an estate", and create_notable_event is LOW.
+ ActionType.UPDATE_ALERT_DISPOSITION: BlastRadius.LOW,
}
# Actions that require explicit human approval
diff --git a/services/actions/app/services/approval_gate.py b/services/actions/app/services/approval_gate.py
index cc530ea4d..a2087eed7 100644
--- a/services/actions/app/services/approval_gate.py
+++ b/services/actions/app/services/approval_gate.py
@@ -45,7 +45,7 @@ import structlog
from app.live_actions.capability_contracts import contract_for_action_type
from app.live_actions.contract import ApprovalRequirement
from app.models.action import ActionRequest, ActionStatus, BlastRadius
-from app.services.approval_matrix import evaluate as evaluate_matrix
+from app.services.approval_matrix import evaluate_contract
logger = structlog.get_logger()
@@ -103,9 +103,15 @@ async def apply_matrix(
)
return status, reason
- decision = evaluate_matrix(
- impact=contract.impact,
- declared_approval=contract.approval,
+ # The same shared grading the registry door runs. This used to unpack the
+ # contract into `evaluate`'s arguments here, and the dispatcher unpacked
+ # it again over there — two call sites, and only one of them grew a
+ # read-only bypass when the matrix's L1 ceiling turned out to gate reads.
+ # `search_siem` is read_only/automatic and came back `awaiting_approval`
+ # through this door at the default tier while executing through the
+ # other. One function now answers for both.
+ decision = evaluate_contract(
+ contract=contract,
confidence=request.confidence,
tier=await _resolve_tier(request.tenant_id),
)
diff --git a/services/actions/app/services/approval_matrix.py b/services/actions/app/services/approval_matrix.py
index be8343585..60124cc84 100644
--- a/services/actions/app/services/approval_matrix.py
+++ b/services/actions/app/services/approval_matrix.py
@@ -34,6 +34,7 @@ from __future__ import annotations
import logging
from dataclasses import dataclass
+from typing import Protocol
from app.live_actions.contract import (
NEVER_AUTONOMOUS,
@@ -43,6 +44,25 @@ from app.live_actions.contract import (
logger = logging.getLogger("aisoc.approval_matrix")
+
+class _Contract(Protocol):
+ """The two fields a capability contract contributes to a grading.
+
+ Structural rather than an import of ``CapabilityContract``: this module
+ lives in ``app.services`` and that one in ``app.live_actions``, whose
+ package ``__init__`` already imports the dispatcher, which imports this
+ module. Naming the class would close that loop.
+ """
+
+ @property
+ def impact(self) -> ActionImpact:
+ """What this does to the estate if the finding is wrong."""
+
+ @property
+ def approval(self) -> ApprovalRequirement:
+ """Baseline requirement, which the matrix may raise and never lower."""
+
+
#: Confidence floor per impact tier for a *fully automatic* execution.
#: Below the floor, the action drops to analyst approval.
#:
@@ -65,9 +85,27 @@ TIER_ORDER = ("L0", "L1", "L2", "L3", "L4")
#: The highest impact each tier may execute without an analyst, *given* the
#: confidence floor above is also met.
+#:
+#: ``None`` means exactly one thing: this tier executes nothing at all. That
+#: is true of L0 and of L0 only. ``maturity.py`` defines the ladder as "L0 —
+#: Observe: all actions routed to approval queue. L1 — Notify: MINIMAL
+#: blast-radius actions are automatic", and ``_AUTO_ALLOWED_AT_TIER`` encodes
+#: it as ``set()`` for L0 and ``{MINIMAL}`` for L1. READ_ONLY impact is the
+#: same thing as MINIMAL blast radius — ``dispatcher._IMPACT_BLAST`` maps one
+#: onto the other — so L1's entry here is READ_ONLY.
+#:
+#: It read ``None``, which put a pure read into the analyst queue at the
+#: default tier. That is the failure mode this module's own docstring opens
+#: by naming, and the contract gate calls a read requiring approval
+#: "mis-classified or not actually a read". The registry door had grown a
+#: local bypass to route around it; this table entry is where the answer
+#: belongs, so there is one of it.
+#:
+#: Only READ_ONLY moves. Every impact above it ranks higher than the L1
+#: ceiling and still returns ANALYST, exactly as the ``None`` branch did.
TIER_MAX_AUTOMATIC: dict[str, ActionImpact | None] = {
- "L0": None, # observe only
- "L1": None, # recommend only
+ "L0": None, # observe only — not even a read
+ "L1": ActionImpact.READ_ONLY, # notify: reads run, nothing acts
"L2": ActionImpact.READ_ONLY,
"L3": ActionImpact.MODERATE, # reversible actions
"L4": ActionImpact.HIGH, # bounded response; never SEVERE or IRREVERSIBLE
@@ -227,3 +265,39 @@ def evaluate(
confidence=score,
tier=tier,
)
+
+
+def evaluate_contract(
+ *,
+ contract: _Contract,
+ confidence: float | None,
+ tier: str,
+) -> ApprovalDecision:
+ """Grade a capability contract. **The one place a door may decide.**
+
+ Every entry point that grades a verb calls this and nothing else:
+ ``approval_gate.apply_matrix`` behind ``POST /actions``,
+ ``dispatcher._apply_capability_contract`` behind
+ ``POST /live-actions/dispatch`` and the playbook bridge.
+
+ It exists because the two doors were separately responsible for
+ unpacking a contract into :func:`evaluate`'s four arguments, and one of
+ them grew a local short-circuit the other did not have. ``search_siem``
+ is read_only/automatic and returned ``awaiting_approval`` through the
+ legacy door while executing through the registry door — the same verb
+ graded differently depending on which door it came through, which is the
+ precise thing the dispatcher's docstring says its contract block exists
+ to stop.
+
+ Keeping the unpacking here is what makes that structural rather than a
+ matter of discipline. A third door gets the answer by calling this; it
+ cannot get a different one without reimplementing the function, and
+ ``tests/test_approval_doors_agree.py`` sweeps both live doors over every
+ capability, tier and confidence band to catch it if one does.
+ """
+ return evaluate(
+ impact=contract.impact,
+ declared_approval=contract.approval,
+ confidence=confidence,
+ tier=tier,
+ )
diff --git a/services/actions/app/services/blast_radius.py b/services/actions/app/services/blast_radius.py
index 83549f542..8d1ac6cf9 100644
--- a/services/actions/app/services/blast_radius.py
+++ b/services/actions/app/services/blast_radius.py
@@ -41,7 +41,14 @@ class BlastRadiusGate:
- APPROVED: safe to execute automatically
- AWAITING_APPROVAL: requires human approval before execution
"""
- blast_radius = ACTION_BLAST_RADIUS.get(request.action_type, BlastRadius.MEDIUM)
+ # Fails closed to HIGH, matching the three tier gates that read the
+ # same table. It used to fall back to MEDIUM, which is exactly
+ # `_AUTO_EXECUTE_LIMIT` — so a verb nobody had classified landed on
+ # the permissive side of the limit here and on the restrictive side
+ # everywhere else. `update_alert_disposition` was that verb.
+ # `test_approval_doors_agree.py` now requires an explicit entry for
+ # every member, so this default should never decide anything again.
+ blast_radius = ACTION_BLAST_RADIUS.get(request.action_type, BlastRadius.HIGH)
# Check if action type always requires approval
if request.action_type in APPROVAL_REQUIRED_ACTIONS:
diff --git a/services/actions/app/services/verification.py b/services/actions/app/services/verification.py
index 48194ce34..5649620b5 100644
--- a/services/actions/app/services/verification.py
+++ b/services/actions/app/services/verification.py
@@ -31,7 +31,7 @@ from typing import Any
import structlog
from app.clients.factories import _entra_client, _mde_client, _okta_client
-from app.executors.endpoint import INVESTIGATION_PACKAGE_ACTION, _cs_client
+from app.executors.endpoint import AV_SCAN_ACTION, INVESTIGATION_PACKAGE_ACTION, _cs_client
from app.executors.siem import _ack_vendor, _qradar_client, _splunk_client
from app.models.action import ActionType
from app.services.disposition_writeback import WritebackAction, plan_writeback
@@ -90,6 +90,68 @@ async def _probe_isolate(target: str, params: dict[str, Any]) -> bool | None:
return status.lower() in _CONTAINED_STATES
+async def _probe_kill_process(target: str, params: dict[str, Any]) -> bool | None:
+ """Confirm a process is gone by reading the host's process table.
+
+ ``kill_process`` is one of three disruptive endpoint verbs whose success
+ was inferred from RTR accepting the command. RTR accepting a ``kill`` and
+ the process being dead are different facts: the agent may be offline, the
+ PID may have been recycled, the process may be protected.
+
+ Only the CrowdStrike arm is readable. The SentinelOne arm targets
+ binaries by hash through the management plane and exposes no process
+ listing, so it answers indeterminate — the same shape as
+ :func:`_probe_block_ip`, where only AWS security groups can be re-read.
+
+ A PID is required. Without one there is no question to ask, and guessing
+ from ``process_name`` would confirm the wrong thing on a host running two
+ copies of it.
+ """
+ cs = _cs_client(params)
+ if cs is None:
+ return None
+ pid = params.get("pid")
+ if pid is None:
+ return None
+ try:
+ pid_int = int(pid)
+ except (TypeError, ValueError):
+ return None
+
+ device_id = await cs.get_device_id(target)
+ if not device_id:
+ return None
+ running = await cs.is_process_running(device_id, pid_int)
+ return None if running is None else not running
+
+
+async def _probe_quarantine_file(target: str, params: dict[str, Any]) -> bool | None:
+ """Confirm a quarantined file is actually gone from the host.
+
+ ``QuarantineFileExecutor`` issues an RTR ``rm``, so the effect to confirm
+ is the file's absence at that path. Reading it back is the difference
+ between "RTR accepted a delete" and "the binary is no longer there to be
+ run again".
+
+ SentinelOne's arm is a different action — it fetches the file into the
+ forensics vault rather than removing it — so its absence is not the
+ effect and this reports indeterminate rather than probing for the wrong
+ thing.
+ """
+ cs = _cs_client(params)
+ if cs is None:
+ return None
+ file_path = params.get("file_path")
+ if not isinstance(file_path, str) or not file_path.strip():
+ return None
+
+ device_id = await cs.get_device_id(target)
+ if not device_id:
+ return None
+ still_there = await cs.path_exists(device_id, file_path)
+ return None if still_there is None else not still_there
+
+
async def _probe_block_ip(target: str, params: dict[str, Any]) -> bool | None:
"""Confirm an IP block by re-reading the enforcing rule set.
@@ -222,6 +284,58 @@ async def _probe_capture_forensics(target: str, params: dict[str, Any]) -> bool
return bool(await mde.get_investigation_package_uri(str(action_id)))
+async def _probe_run_av_scan(target: str, params: dict[str, Any]) -> bool | None:
+ """Confirm an AV scan actually ran, not merely that one was requested.
+
+ Defender queues a machine action and replies ``Pending`` immediately, so
+ the executor's own response is the clearest possible case of "the API
+ accepted the request" standing in for an effect. This reads the action's
+ terminal state instead, on the same three outcomes as
+ :func:`_probe_capture_forensics`:
+
+ * ``Succeeded`` → True.
+ * ``Failed`` / ``TimeOut`` / ``Cancelled`` → False, a real alarm: the
+ responder believes the host was swept and it was not.
+ * ``Pending`` / ``InProgress`` → None. A full scan takes minutes, so the
+ immediate post-dispatch probe lands here almost every time, and "not
+ finished" is not "did not happen".
+
+ Unlike the forensics probe there is no artefact to fetch afterwards. A
+ clean sweep produces nothing, so absence of findings is the expected
+ result and cannot be part of the check — ``Succeeded`` is the whole
+ claim, and it is the claim Defender is actually making.
+
+ The SentinelOne arm returns no action id and exposes no equivalent read,
+ so it answers indeterminate rather than borrowing Defender's.
+ """
+ mde = _mde_client(params)
+ if mde is None:
+ return None
+
+ action_id = params.get("mde_action_id")
+ if not action_id:
+ machine = await mde.find_machine(target)
+ if not machine or not machine.get("id"):
+ return None
+ actions = await mde.list_machine_actions(str(machine["id"]), AV_SCAN_ACTION, limit=5)
+ if not actions:
+ return None
+ action_id = actions[0].get("id")
+ if not action_id:
+ return None
+
+ action = await mde.get_machine_action(str(action_id))
+ if not action:
+ return None
+
+ status = str(action.get("status") or "").lower()
+ logger.info("verification.run_av_scan.read", target=target, mde_action_id=str(action_id), mde_status=status)
+
+ if status in _MDE_ACTION_TERMINAL_FAILURES:
+ return False
+ return True if status == _MDE_ACTION_SUCCEEDED else None
+
+
async def _probe_allow_ip(target: str, params: dict[str, Any]) -> bool | None:
"""Confirm an IP block was actually removed.
@@ -343,6 +457,12 @@ _DEFAULT_PROBES: dict[ActionType, Probe] = {
ActionType.UPDATE_ALERT_DISPOSITION: _probe_alert_disposition,
ActionType.ACK_ALERT: _probe_ack_alert,
ActionType.SUPPRESS_ALERT: _probe_suppress_alert,
+ # The disruptive endpoint verbs. Their success was inferred from RTR or
+ # Defender accepting the request, which is the claim this module exists
+ # to separate from the effect.
+ ActionType.KILL_PROCESS: _probe_kill_process,
+ ActionType.QUARANTINE_FILE: _probe_quarantine_file,
+ ActionType.RUN_AV_SCAN: _probe_run_av_scan,
}
diff --git a/services/actions/tests/test_approval_doors_agree.py b/services/actions/tests/test_approval_doors_agree.py
new file mode 100644
index 000000000..93bbf2029
--- /dev/null
+++ b/services/actions/tests/test_approval_doors_agree.py
@@ -0,0 +1,423 @@
+"""Both dispatch doors must grade the same verb the same way.
+
+The instance that prompted this: ``search_siem`` declares ``read_only``
+impact and ``automatic`` approval, and the contract gate's own rule is that a
+read requiring approval "is either mis-classified or is not actually a read".
+At the default autonomy tier it came back ``awaiting_approval`` from
+``POST /actions`` and executed from ``POST /live-actions/dispatch``.
+
+``dispatcher``'s docstring said the contract block existed so that the same
+verb would not be "graded differently depending on which door it came
+through", and that is what was happening — because the registry door had
+grown a local READ_ONLY short-circuit to route around a matrix tier ceiling
+that gated reads, and the legacy door had not.
+
+Fixing the instance is a one-line table change. What stops the next one is
+this file, which sweeps **both live doors over every capability, every
+autonomy tier and every confidence band** and asserts they reach the same
+answer to the only question that matters: did a vendor get touched without a
+human. A third door, a new tier, a new verb or a re-introduced bypass all
+fail here.
+
+The sweep found a second instance immediately, unrelated to reads:
+``update_alert_disposition`` had no ``ACTION_BLAST_RADIUS`` entry, and the
+four readers of that table fall back to two different values. See
+``test_every_action_type_has_an_explicit_blast_radius``.
+
+Against ``origin/main`` this file reports 5 disagreements across 345
+combinations; the change it ships with takes that to 0.
+"""
+
+from __future__ import annotations
+
+import ast
+import inspect
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+from uuid import uuid4
+
+import pytest
+from app.api.live_actions_router import router as live_router
+from app.api.router import router as legacy_router
+from app.live_actions import registry
+from app.live_actions.capability_contracts import CAPABILITY_CONTRACTS
+from app.live_actions.models import LiveActionRequest, LiveActionResult, LiveActionStatus
+from app.models.action import (
+ ACTION_BLAST_RADIUS,
+ ActionRequest,
+ ActionResult,
+ ActionStatus,
+ ActionType,
+ BlastRadius,
+)
+from app.services import action_store, tenant_policy
+from app.services.executor_registry import EXECUTOR_REGISTRY
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+#: Every verb both doors can see. The legacy door is keyed on ``ActionType``
+#: and the registry door on a capability string, so the intersection is where
+#: a disagreement is even expressible.
+SHARED_CAPABILITIES = sorted(k for k in CAPABILITY_CONTRACTS if k in {a.value for a in ActionType})
+
+TIERS = ("L0", "L1", "L2", "L3", "L4")
+
+#: No score, a middling one, and a perfect one. The bands matter more than
+#: the values: the floors are 0%, 90%, 98% and 99%, and "missing" must behave
+#: as the lowest band rather than as a free pass.
+CONFIDENCES: tuple[float | None, ...] = (None, 0.5, 1.0)
+
+
+def test_the_sweep_covers_every_impact_tier() -> None:
+ """A sweep that silently stopped covering an impact would still pass."""
+ covered = {CAPABILITY_CONTRACTS[c].impact for c in SHARED_CAPABILITIES}
+ assert len(SHARED_CAPABILITIES) >= 20
+ assert {i.value for i in covered} == {"read_only", "low", "moderate", "high", "severe"}
+
+
+class _VendorTouches:
+ """Records whether a real vendor call was made, by either door.
+
+ ``executed`` is the single field that means a vendor was actually
+ touched. A dry-run preview reaches the executor with its credentials
+ stripped and changes nothing, so it does not count — the registry door
+ downgrades an over-tier request to a preview rather than refusing it,
+ and counting that as execution would report a disagreement that is not
+ one.
+ """
+
+ def __init__(self) -> None:
+ self.executed = False
+
+ def reset(self) -> None:
+ self.executed = False
+
+
+def touches() -> _VendorTouches:
+ return _VendorTouches()
+
+
+def client(monkeypatch: pytest.MonkeyPatch, touches: _VendorTouches) -> TestClient:
+ """Both doors mounted on one app, with recording executors behind each.
+
+ Stubbing at the executor boundary and not below it means everything under
+ test — authz, both gates, the contract, the tier resolution — is the real
+ production code path.
+ """
+ monkeypatch.setenv("AISOC_DEV_MODE", "true")
+
+ class _LegacyRecorder:
+ async def execute(self, request: ActionRequest) -> ActionResult:
+ touches.executed = True
+ return ActionResult(
+ action_id=request.id,
+ status=ActionStatus.COMPLETED,
+ blast_radius=BlastRadius.MINIMAL,
+ output={},
+ rollback_data={},
+ completed_at=datetime.now(UTC),
+ )
+
+ async def rollback(self, result: ActionResult) -> bool:
+ return True
+
+ class _LiveRecorder:
+ async def execute(self, request: LiveActionRequest) -> LiveActionResult:
+ if not request.dry_run:
+ touches.executed = True
+ return LiveActionResult(
+ request_id=request.request_id,
+ status=LiveActionStatus.SUCCEEDED,
+ capability=request.capability,
+ vendor_id=request.vendor_id,
+ summary="executed",
+ )
+
+ # `list(...)` rather than iterating the enum class directly: CodeQL
+ # resolves `ActionType` through its `str` base and reports the class
+ # object as non-iterable, which is a false positive it raises at `error`.
+ for action_type in list(ActionType):
+ monkeypatch.setitem(EXECUTOR_REGISTRY, action_type, _LegacyRecorder())
+ monkeypatch.setattr(registry, "get_executor", lambda vendor, capability: _LiveRecorder())
+
+ app = FastAPI()
+ app.include_router(legacy_router)
+ app.include_router(live_router)
+ return TestClient(app)
+
+
[email protected](autouse=True)
+def _clean_policy_cache(monkeypatch: pytest.MonkeyPatch):
+ """The tenant policy is cached for 30s and these tests move the tier."""
+ tenant_policy._cache.clear()
+ yield
+ tenant_policy._cache.clear()
+ action_store.clear()
+
+
+def _through_legacy_door(
+ client: TestClient,
+ touches: _VendorTouches,
+ capability: str,
+ confidence: float | None,
+) -> bool:
+ touches.reset()
+ body: dict[str, Any] = {
+ "incident_id": str(uuid4()),
+ "tenant_id": str(uuid4()),
+ "action_type": capability,
+ "target": "WKSTN-01",
+ }
+ if confidence is not None:
+ body["confidence"] = confidence
+ response = client.post("/actions", json=body)
+ assert response.status_code == 200, response.text
+ return touches.executed
+
+
+def _through_registry_door(
+ client: TestClient,
+ touches: _VendorTouches,
+ capability: str,
+ confidence: float | None,
+) -> bool:
+ touches.reset()
+ body: dict[str, Any] = {
+ "request_id": str(uuid4()),
+ "capability": capability,
+ "vendor_id": "crowdstrike",
+ "target": "WKSTN-01",
+ "tenant_id": str(uuid4()),
+ "dry_run": False,
+ }
+ if confidence is not None:
+ body["confidence"] = confidence
+ response = client.post("/live-actions/dispatch", json=body)
+ assert response.status_code == 200, response.text
+ return touches.executed
+
+
[email protected]("tier", TIERS)
+def test_both_doors_reach_the_same_verdict_for_every_verb(
+ client: TestClient,
+ touches: _VendorTouches,
+ monkeypatch: pytest.MonkeyPatch,
+ tier: str,
+) -> None:
+ """The invariant, swept live rather than argued from the source.
+
+ Parametrised by tier rather than by every combination so a failure names
+ the tier and then lists every verb that disagreed at it — one run tells
+ you the shape of the break instead of one cell of it.
+ """
+ monkeypatch.setenv("AISOC_MATURITY_TIER", tier)
+
+ disagreements: list[str] = []
+ for capability in SHARED_CAPABILITIES:
+ for confidence in CONFIDENCES:
+ tenant_policy._cache.clear()
+ legacy = _through_legacy_door(client, touches, capability, confidence)
+ tenant_policy._cache.clear()
+ registry_door = _through_registry_door(client, touches, capability, confidence)
+ if legacy != registry_door:
+ contract = CAPABILITY_CONTRACTS[capability]
+ disagreements.append(
+ f"{capability} (impact={contract.impact.value}, "
+ f"approval={contract.approval.value}) at {tier} "
+ f"confidence={confidence}: POST /actions executed={legacy}, "
+ f"POST /live-actions/dispatch executed={registry_door}"
+ )
+
+ assert not disagreements, "the two dispatch doors grade the same verb differently:\n " + "\n ".join(disagreements)
+
+
+def test_a_read_executes_through_both_doors_at_the_default_tier(
+ client: TestClient,
+ touches: _VendorTouches,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The reported instance, pinned by name.
+
+ The sweep above would catch it, but a sweep failure reads as "something
+ disagreed somewhere". This one says what broke.
+ """
+ monkeypatch.delenv("AISOC_MATURITY_TIER", raising=False)
+
+ assert _through_legacy_door(client, touches, "search_siem", 1.0) is True
+ assert _through_registry_door(client, touches, "search_siem", 1.0) is True
+
+
+def test_neither_door_executes_anything_at_the_observe_tier(
+ client: TestClient,
+ touches: _VendorTouches,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Agreement is worthless if the agreed answer is "always run".
+
+ L0 is the one tier whose ceiling is ``None``, and it has to mean it — for
+ a read as much as for a containment.
+ """
+ monkeypatch.setenv("AISOC_MATURITY_TIER", "L0")
+
+ for capability in SHARED_CAPABILITIES:
+ tenant_policy._cache.clear()
+ assert _through_legacy_door(client, touches, capability, 1.0) is False, f"{capability} executed at L0 via POST /actions"
+ tenant_policy._cache.clear()
+ assert _through_registry_door(client, touches, capability, 1.0) is False, f"{capability} executed at L0 via /live-actions/dispatch"
+
+
+def test_a_severe_verb_executes_through_neither_door_at_any_tier(
+ client: TestClient,
+ touches: _VendorTouches,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """And agreement is worse than worthless if it agrees on the wrong side."""
+ for tier in TIERS:
+ monkeypatch.setenv("AISOC_MATURITY_TIER", tier)
+ tenant_policy._cache.clear()
+ assert _through_legacy_door(client, touches, "run_script", 1.0) is False
+ tenant_policy._cache.clear()
+ assert _through_registry_door(client, touches, "run_script", 1.0) is False
+
+
+class TestTheDecisionLivesInOnePlace:
+ """Agreement by construction, not by two implementations staying in step.
+
+ The sweep catches a divergence after someone writes it. These catch the
+ shape of it at review time, and they are what a third door would trip.
+ """
+
+ def test_both_doors_call_the_shared_grading_function(self) -> None:
+ from app.live_actions import dispatcher
+ from app.services import approval_gate
+
+ for module in (approval_gate, dispatcher):
+ source = inspect.getsource(module)
+ called = {
+ node.func.id for node in ast.walk(ast.parse(source)) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
+ }
+ assert "evaluate_contract" in called, f"{module.__name__} grades a contract without calling the shared entry point"
+
+ def test_no_door_unpacks_a_contract_into_the_raw_matrix(self) -> None:
+ """``evaluate`` unpacked by hand at a call site is how this started.
+
+ Both doors used to build its four arguments themselves, which is what
+ let one of them wrap the call in a READ_ONLY short-circuit the other
+ did not have. ``evaluate_contract`` takes the contract whole so there
+ is nothing to unpack differently.
+
+ Checked at the *import*, not the call: on the tree this replaces,
+ both doors imported ``evaluate as evaluate_matrix``, so looking only
+ at the called name would have found nothing wrong with either of
+ them.
+ """
+ from app.live_actions import dispatcher
+ from app.services import approval_gate
+
+ for module in (approval_gate, dispatcher):
+ tree = ast.parse(inspect.getsource(module))
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.ImportFrom) or node.module != "app.services.approval_matrix":
+ continue
+ imported = {alias.name for alias in node.names}
+ assert "evaluate" not in imported, (
+ f"{module.__name__} imports approval_matrix.evaluate "
+ f"(as {[a.asname or a.name for a in node.names]}). A door that "
+ f"unpacks a contract into the matrix itself can wrap that call "
+ f"in a rule the other door does not have — use evaluate_contract."
+ )
+
+ def test_no_door_branches_on_a_specific_impact_tier(self) -> None:
+ """A re-introduced bypass has a recognisable shape: a door deciding
+ for itself that one impact tier is special.
+
+ Reading ``ActionImpact`` to build a *table* is fine and the dispatcher
+ does it (``_IMPACT_BLAST``). Comparing against one member inside the
+ grading path is the bypass.
+ """
+ from app.live_actions import dispatcher
+ from app.services import approval_gate
+
+ for module in (approval_gate, dispatcher):
+ tree = ast.parse(inspect.getsource(module))
+ for function in ast.walk(tree):
+ if not isinstance(function, ast.FunctionDef | ast.AsyncFunctionDef):
+ continue
+ if "contract" not in function.name and "matrix" not in function.name:
+ continue
+ for node in ast.walk(function):
+ if not isinstance(node, ast.Compare):
+ continue
+ rendered = ast.unparse(node)
+ assert "ActionImpact." not in rendered, (
+ f"{module.__name__}.{function.name} compares against a specific "
+ f"impact tier ({rendered!r}). That is the shape of the bypass this "
+ f"file exists to prevent — put the rule in approval_matrix instead."
+ )
+
+
+def test_every_action_type_has_an_explicit_blast_radius() -> None:
+ """A missing entry is not a missing entry; it is two different entries.
+
+ Four call sites read ``ACTION_BLAST_RADIUS`` and they fall back
+ differently — ``blast_radius.py`` to HIGH now, the three tier gates to
+ HIGH already, and ``blast_radius.py`` to MEDIUM before this change, which
+ is exactly ``_AUTO_EXECUTE_LIMIT``. So an unclassified verb sat on the
+ permissive side of the limit at one door and the restrictive side at the
+ others. ``update_alert_disposition`` was that verb: the legacy door
+ auto-executed it while the registry door queued it for a whitelist it
+ could never match.
+
+ Requiring an entry means the fallback never decides anything, which is
+ the only way two fallbacks cannot disagree.
+ """
+ unclassified = [a.value for a in ActionType if a not in ACTION_BLAST_RADIUS]
+ assert unclassified == [], (
+ f"ActionType members with no blast radius: {unclassified}. Each reader "
+ f"of ACTION_BLAST_RADIUS supplies its own default, so an absent entry "
+ f"gives the verb a different risk rating at every door."
+ )
+
+
+def test_the_tier_ceiling_table_matches_the_tier_that_ladder_it_mirrors() -> None:
+ """``TIER_MAX_AUTOMATIC`` and ``_AUTO_ALLOWED_AT_TIER`` are one ladder.
+
+ They are two spellings of "what may this tier run without a human", keyed
+ on impact and on blast radius respectively, and ``_IMPACT_BLAST`` is the
+ declared correspondence between the two keys. The entry that disagreed
+ was L1: the blast ladder allowed MINIMAL, the impact ladder allowed
+ nothing, and READ_ONLY impact is MINIMAL blast.
+
+ Only the "executes nothing at all" boundary is asserted, not the whole
+ mapping. The impact ladder is deliberately stricter than the blast ladder
+ higher up — L2 reads where the blast ladder would let it act — and the
+ composition rule permits that. What it does not permit is one ladder
+ saying a tier runs something and the other saying it runs nothing.
+ """
+ from app.live_actions.dispatcher import _IMPACT_BLAST
+ from app.services.approval_matrix import TIER_MAX_AUTOMATIC
+ from app.services.maturity import _AUTO_ALLOWED_AT_TIER, MaturityTier
+
+ for tier in MaturityTier:
+ label = tier.name.split("_")[0]
+ ceiling = TIER_MAX_AUTOMATIC[label]
+ allowed = _AUTO_ALLOWED_AT_TIER[tier]
+ assert bool(ceiling is None) == (not allowed), (
+ f"{label}: the impact ladder says it auto-executes "
+ f"{'nothing' if ceiling is None else ceiling.value + ' and below'} "
+ f"while the blast ladder allows {sorted(b.value for b in allowed)}"
+ )
+ if ceiling is not None:
+ assert _IMPACT_BLAST[ceiling] in allowed, (
+ f"{label} auto-executes up to {ceiling.value} impact, which is "
+ f"{_IMPACT_BLAST[ceiling].value} blast radius, and the blast "
+ f"ladder does not allow it"
+ )
+
+
+def test_this_file_is_wired_into_the_service_suite() -> None:
+ """A gate nobody runs is a gate that certifies nothing."""
+ assert Path(__file__).parent.name == "tests"
diff --git a/services/actions/tests/test_approval_gate_wiring.py b/services/actions/tests/test_approval_gate_wiring.py
index 70933298d..40ffb8103 100644
--- a/services/actions/tests/test_approval_gate_wiring.py
+++ b/services/actions/tests/test_approval_gate_wiring.py
@@ -125,22 +125,37 @@ class TestTheTierIsHonoured:
assert after == ActionStatus.APPROVED
@pytest.mark.asyncio
- async def test_a_read_runs_at_l2_where_it_did_not_at_l1(self, monkeypatch: pytest.MonkeyPatch):
+ async def test_a_read_needs_no_confidence_at_any_acting_tier(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("AISOC_MATURITY_TIER", "L2")
after, _ = await _gated(_request(ActionType.SEARCH_SIEM, confidence=0.0))
assert after == ActionStatus.APPROVED
@pytest.mark.asyncio
- async def test_the_default_tier_executes_nothing(self, monkeypatch: pytest.MonkeyPatch):
- """L1 is notify-only, which is the platform's copilot-default posture.
- This is a real tightening of POST /actions, which was tier-unaware."""
+ async def test_the_default_tier_reads_without_asking_and_acts_only_with_permission(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ):
+ """L1 is notify-only, and a query is not an act.
+
+ This replaces a test that asserted ``search_siem`` reached the
+ approval queue here. It did, and that was the bug: ``search_siem``
+ declares ``read_only`` impact and ``automatic`` approval, and the
+ contract gate's own rule is that a read requiring approval "is either
+ mis-classified or is not actually a read". The registry door executed
+ it at the same tier, so one verb had two grades.
+
+ The notify-only posture is asserted in the same test rather than
+ deleted with the defect, because that posture is real: a
+ state-changing verb must still queue here.
+ """
monkeypatch.delenv("AISOC_MATURITY_TIER", raising=False)
- request = _request(ActionType.SEARCH_SIEM, confidence=1.0)
- after, reason = await _gated(request)
+ read, _ = await _gated(_request(ActionType.SEARCH_SIEM, confidence=1.0))
+ assert read == ActionStatus.APPROVED
- assert after == ActionStatus.AWAITING_APPROVAL
+ act, reason = await _gated(_request(ActionType.CREATE_TICKET, confidence=1.0))
+ assert act == ActionStatus.AWAITING_APPROVAL
assert "L1" in reason
diff --git a/services/actions/tests/test_approval_matrix.py b/services/actions/tests/test_approval_matrix.py
index 459848275..d993b7f22 100644
--- a/services/actions/tests/test_approval_matrix.py
+++ b/services/actions/tests/test_approval_matrix.py
@@ -95,11 +95,51 @@ class TestConfidence:
class TestTiers:
- @pytest.mark.parametrize("tier", ["L0", "L1"])
- def test_observe_and_recommend_tiers_execute_nothing(self, tier: str) -> None:
- decision = evaluate(impact=ActionImpact.READ_ONLY, declared_approval=AUTO, confidence=1.0, tier=tier)
+ @pytest.mark.parametrize("impact", list(ActionImpact))
+ def test_the_observe_tier_executes_nothing_at_all(self, impact: ActionImpact) -> None:
+ """L0 is the one tier whose ceiling is ``None``, and it means it.
+
+ Widened from READ_ONLY alone to every impact: ``None`` now has
+ exactly one meaning in ``TIER_MAX_AUTOMATIC`` and this is the
+ assertion of it. ``maturity.py`` defines L0 as "all actions routed to
+ the approval queue" and ``_AUTO_ALLOWED_AT_TIER`` gives it the empty
+ set.
+ """
+ decision = evaluate(impact=impact, declared_approval=AUTO, confidence=1.0, tier="L0")
assert not decision.can_auto_execute
+ def test_the_notify_tier_reads_and_does_not_act(self) -> None:
+ """L1 used to gate a pure read, and that was the defect.
+
+ This test replaces one that asserted the opposite. It was not a
+ posture being relaxed — it contradicted the ladder it claimed to
+ encode. ``maturity.py``: "L1 — Notify: MINIMAL blast-radius actions
+ are automatic", and ``_AUTO_ALLOWED_AT_TIER[L1_NOTIFY]`` is
+ ``{MINIMAL}``, which ``dispatcher._IMPACT_BLAST`` equates with
+ READ_ONLY impact. The module docstring above opens by naming "an IOC
+ enrichment stuck in an approval queue because the tier is low" as a
+ failure mode, and the contract gate calls a read that needs approval
+ mis-classified. Three statements of the same rule, and the table said
+ otherwise at the default tier.
+
+ Both halves are pinned here, where the old test pinned neither
+ correctly: a read runs, and nothing above a read does.
+ """
+ assert evaluate(impact=ActionImpact.READ_ONLY, declared_approval=AUTO, confidence=1.0, tier="L1").can_auto_execute
+ for impact in (ActionImpact.LOW, ActionImpact.MODERATE, ActionImpact.HIGH):
+ decision = evaluate(impact=impact, declared_approval=AUTO, confidence=1.0, tier="L1")
+ assert not decision.can_auto_execute, f"L1 must not auto-execute {impact.value} impact"
+
+ def test_a_read_whose_contract_wants_an_analyst_still_gets_one(self) -> None:
+ """The tier ceiling moved; the contract's own floor did not.
+
+ READ_ONLY + ANALYST is a legal declaration — the contract gate only
+ forbids READ_ONLY + MANDATORY_HUMAN/PROHIBITED — so the ceiling change
+ must not swallow it.
+ """
+ decision = evaluate(impact=ActionImpact.READ_ONLY, declared_approval=ANALYST, confidence=1.0, tier="L4")
+ assert decision.requirement is ANALYST
+
def test_l2_reads_but_does_not_act(self) -> None:
assert evaluate(impact=ActionImpact.READ_ONLY, declared_approval=AUTO, confidence=1.0, tier="L2").can_auto_execute
assert not evaluate(impact=ActionImpact.LOW, declared_approval=AUTO, confidence=1.0, tier="L2").can_auto_execute
diff --git a/services/actions/tests/test_endpoint_verification_probes.py b/services/actions/tests/test_endpoint_verification_probes.py
new file mode 100644
index 000000000..2d20ebb55
--- /dev/null
+++ b/services/actions/tests/test_endpoint_verification_probes.py
@@ -0,0 +1,433 @@
+"""Probes for the three disruptive endpoint verbs that had none.
+
+``kill_process``, ``quarantine_file`` and ``run_script`` change an endpoint,
+and their success was inferred from a vendor API accepting the request. That
+is the same claim the isolation probe used to make when it returned
+``bool(device_id)`` — "the host exists", offered as "the host is contained".
+
+Two of the three now have a real read-back and the third does not, for a
+reason recorded on its contract:
+
+* ``kill_process`` — RTR ``ps``, checking the PID is gone.
+* ``quarantine_file`` — RTR ``ls``, checking the path is gone.
+* ``run_script`` — nothing to probe. The platform does not know what an
+ arbitrary script was supposed to do, so no read-back can confirm it did
+ it. It is mandatory-human, and the approver is the verification.
+
+``run_av_scan`` is here too. It is not disruptive, but it is *automatic*, and
+Defender replies ``Pending`` the instant it queues the sweep — so its
+response is the clearest case in the service of an acknowledgement standing
+in for an effect.
+
+Most of what follows is about the indeterminate case, because that is where
+these probes can do harm. A probe that cannot reach the vendor, or cannot
+parse what the vendor said, must answer "I do not know". Answering "yes"
+certifies a process that is still running.
+"""
+
+from __future__ import annotations
+
+import inspect
+import json
+from typing import Any
+from unittest.mock import AsyncMock, create_autospec
+
+import httpx
+import pytest
+import respx
+from app.clients.crowdstrike_rtr import CrowdStrikeRTRClient
+from app.clients.defender_client import DefenderClient
+from app.executors.endpoint import AV_SCAN_ACTION
+from app.live_actions.capability_contracts import CAPABILITY_CONTRACTS
+from app.models.action import ActionType
+from app.services import verification as module
+from app.services.verification import (
+ _DEFAULT_PROBES,
+ _probe_kill_process,
+ _probe_quarantine_file,
+ _probe_run_av_scan,
+)
+
+CS_PARAMS: dict[str, Any] = {"cs_client_id": "cid", "cs_client_secret": "unit-test-placeholder", "pid": 4242}
+FILE_PARAMS: dict[str, Any] = {
+ "cs_client_id": "cid",
+ "cs_client_secret": "unit-test-placeholder",
+ "file_path": "C:\\Users\\Public\\evil.exe",
+}
+
+#: A realistic RTR ``ps`` listing: header row, then one line per process with
+#: the PID in the first column.
+PS_OUTPUT = "PID PPID ImageName\n4242 1180 evil.exe\n1180 712 explorer.exe\n"
+PS_OUTPUT_WITHOUT_TARGET = "PID PPID ImageName\n1180 712 explorer.exe\n"
+
+
+def _cs(monkeypatch: pytest.MonkeyPatch, **methods: Any) -> AsyncMock:
+ client = AsyncMock()
+ client.get_device_id = AsyncMock(return_value="dev-1")
+ for name, value in methods.items():
+ setattr(client, name, AsyncMock(return_value=value))
+ monkeypatch.setattr(module, "_cs_client", lambda params: client)
+ return client
+
+
+class TestKillProcessProbe:
+ @pytest.mark.asyncio
+ async def test_a_pid_gone_from_the_table_verifies(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _cs(monkeypatch, is_process_running=False)
+ assert await _probe_kill_process("WKSTN-01", CS_PARAMS) is True
+
+ @pytest.mark.asyncio
+ async def test_a_pid_still_in_the_table_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The alarm this probe exists for: RTR took the kill, nothing died."""
+ _cs(monkeypatch, is_process_running=True)
+ assert await _probe_kill_process("WKSTN-01", CS_PARAMS) is False
+
+ @pytest.mark.asyncio
+ async def test_an_unreadable_process_table_is_indeterminate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _cs(monkeypatch, is_process_running=None)
+ assert await _probe_kill_process("WKSTN-01", CS_PARAMS) is None
+
+ @pytest.mark.asyncio
+ async def test_no_crowdstrike_credentials_is_indeterminate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The SentinelOne arm lands here: it kills by hash and lists nothing."""
+ monkeypatch.setattr(module, "_cs_client", lambda params: None)
+ assert await _probe_kill_process("WKSTN-01", CS_PARAMS) is None
+
+ @pytest.mark.asyncio
+ async def test_a_missing_pid_is_indeterminate_not_verified(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Without a PID there is no question to ask.
+
+ Falling back to ``process_name`` would confirm the wrong thing on a
+ host running two copies of it, and defaulting to True would certify
+ every kill the S1 arm ever made.
+ """
+ client = _cs(monkeypatch, is_process_running=False)
+ assert await _probe_kill_process("WKSTN-01", {"cs_client_id": "c", "cs_client_secret": "s"}) is None
+ client.is_process_running.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_a_non_numeric_pid_is_indeterminate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _cs(monkeypatch, is_process_running=False)
+ assert await _probe_kill_process("WKSTN-01", {**CS_PARAMS, "pid": "not-a-pid"}) is None
+
+ @pytest.mark.asyncio
+ async def test_an_unresolvable_host_is_indeterminate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A renamed host is not the same fact as "the kill did not take"."""
+ client = _cs(monkeypatch, is_process_running=False)
+ client.get_device_id = AsyncMock(return_value=None)
+ assert await _probe_kill_process("WKSTN-01", CS_PARAMS) is None
+
+
+class TestQuarantineFileProbe:
+ @pytest.mark.asyncio
+ async def test_a_removed_file_verifies(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _cs(monkeypatch, path_exists=False)
+ assert await _probe_quarantine_file("WKSTN-01", FILE_PARAMS) is True
+
+ @pytest.mark.asyncio
+ async def test_a_file_still_on_disk_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _cs(monkeypatch, path_exists=True)
+ assert await _probe_quarantine_file("WKSTN-01", FILE_PARAMS) is False
+
+ @pytest.mark.asyncio
+ async def test_an_unreadable_path_is_indeterminate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _cs(monkeypatch, path_exists=None)
+ assert await _probe_quarantine_file("WKSTN-01", FILE_PARAMS) is None
+
+ @pytest.mark.asyncio
+ async def test_no_file_path_is_indeterminate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _cs(monkeypatch, path_exists=False)
+ assert await _probe_quarantine_file("WKSTN-01", {"cs_client_id": "c", "cs_client_secret": "s"}) is None
+ client.path_exists.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_the_sentinelone_arm_is_indeterminate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """S1 fetches the file into the forensics vault; it does not remove it.
+
+ So its absence is not the effect, and probing for one would report
+ FAILED for an arm that worked correctly.
+ """
+ monkeypatch.setattr(module, "_cs_client", lambda params: None)
+ assert await _probe_quarantine_file("WKSTN-01", {"s1_console_url": "https://x", "s1_api_token": "t"}) is None
+
+
+class TestRunAVScanProbe:
+ @pytest.mark.asyncio
+ async def test_a_succeeded_scan_verifies(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ mde = AsyncMock()
+ mde.get_machine_action = AsyncMock(return_value={"id": "act-1", "status": "Succeeded"})
+ monkeypatch.setattr(module, "_mde_client", lambda params: mde)
+ assert await _probe_run_av_scan("WKSTN-01", {"mde_action_id": "act-1"}) is True
+
+ @pytest.mark.parametrize("status", ["Failed", "TimeOut", "Cancelled"])
+ @pytest.mark.asyncio
+ async def test_terminal_failures_are_a_real_alarm(self, monkeypatch: pytest.MonkeyPatch, status: str) -> None:
+ mde = AsyncMock()
+ mde.get_machine_action = AsyncMock(return_value={"id": "act-1", "status": status})
+ monkeypatch.setattr(module, "_mde_client", lambda params: mde)
+ assert await _probe_run_av_scan("WKSTN-01", {"mde_action_id": "act-1"}) is False
+
+ @pytest.mark.parametrize("status", ["Pending", "InProgress"])
+ @pytest.mark.asyncio
+ async def test_a_running_scan_is_indeterminate(self, monkeypatch: pytest.MonkeyPatch, status: str) -> None:
+ """Where the immediate post-dispatch probe lands nearly every time.
+
+ Reporting VERIFIED here would certify a sweep that has not started,
+ which is exactly the state Defender returns from the executor.
+ """
+ mde = AsyncMock()
+ mde.get_machine_action = AsyncMock(return_value={"id": "act-1", "status": status})
+ monkeypatch.setattr(module, "_mde_client", lambda params: mde)
+ assert await _probe_run_av_scan("WKSTN-01", {"mde_action_id": "act-1"}) is None
+
+ @pytest.mark.asyncio
+ async def test_it_finds_the_newest_scan_when_no_action_id_was_passed(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ mde = AsyncMock()
+ mde.find_machine = AsyncMock(return_value={"id": "mde-1"})
+ mde.list_machine_actions = AsyncMock(return_value=[{"id": "act-7"}])
+ mde.get_machine_action = AsyncMock(return_value={"id": "act-7", "status": "Succeeded"})
+ monkeypatch.setattr(module, "_mde_client", lambda params: mde)
+
+ assert await _probe_run_av_scan("WKSTN-01", {}) is True
+ mde.list_machine_actions.assert_awaited_once_with("mde-1", AV_SCAN_ACTION, limit=5)
+
+ @pytest.mark.asyncio
+ async def test_it_asks_for_av_scans_and_not_some_other_action_type(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The wrong action type would read back a different action's status.
+
+ A host that had a forensic package collected an hour ago would report
+ its AV scan as Succeeded on the strength of that.
+ """
+ assert AV_SCAN_ACTION == "RunAntiVirusScan"
+
+ @pytest.mark.asyncio
+ async def test_no_defender_credentials_is_indeterminate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(module, "_mde_client", lambda params: None)
+ assert await _probe_run_av_scan("WKSTN-01", {}) is None
+
+ @pytest.mark.asyncio
+ async def test_a_host_with_no_scan_history_is_indeterminate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ mde = AsyncMock()
+ mde.find_machine = AsyncMock(return_value={"id": "mde-1"})
+ mde.list_machine_actions = AsyncMock(return_value=[])
+ monkeypatch.setattr(module, "_mde_client", lambda params: mde)
+ assert await _probe_run_av_scan("WKSTN-01", {}) is None
+
+
+class TestTheRTRReadCommands:
+ """The client half, against mocked HTTP rather than a mocked client.
+
+ A probe that calls a correct client method on a client that parses the
+ vendor wrongly is still a probe that certifies falsely.
+ """
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_a_pid_present_in_the_listing_reads_as_running(self) -> None:
+ _mock_rtr(stdout=PS_OUTPUT)
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ assert await client.is_process_running("dev-1", 4242) is True
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_a_pid_absent_from_the_listing_reads_as_gone(self) -> None:
+ _mock_rtr(stdout=PS_OUTPUT_WITHOUT_TARGET)
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ assert await client.is_process_running("dev-1", 4242) is False
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_a_pid_appearing_only_as_a_parent_reads_as_gone(self) -> None:
+ """Only the first column is a PID.
+
+ A surviving child listing the killed process as its parent would
+ otherwise report the kill as failed on every run.
+ """
+ _mock_rtr(stdout="PID PPID ImageName\n9001 4242 child.exe\n")
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ assert await client.is_process_running("dev-1", 4242) is False
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_output_that_is_not_a_process_table_is_indeterminate(self) -> None:
+ """The guard against a false confirmation from an unparsed response.
+
+ If RTR returns an error page, a prompt, or a format this does not
+ understand, no PID is found — and "no PID found" would otherwise read
+ as "the process is gone".
+ """
+ _mock_rtr(stdout="Access denied. The user is not authorized to run this command.")
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ assert await client.is_process_running("dev-1", 4242) is None
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_an_incomplete_command_is_indeterminate(self) -> None:
+ """An offline agent leaves the batch entry incomplete."""
+ _mock_rtr(stdout="", complete=False)
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ assert await client.is_process_running("dev-1", 4242) is None
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_a_host_missing_from_the_batch_response_is_indeterminate(self) -> None:
+ respx.post("https://api.crowdstrike.com/oauth2/token").mock(return_value=httpx.Response(200, json={"access_token": "t"}))
+ respx.post("https://api.crowdstrike.com/real-time-response/combined/batch-init-session/v1").mock(
+ return_value=httpx.Response(200, json={"batch_id": "b-1"})
+ )
+ respx.post("https://api.crowdstrike.com/real-time-response/combined/batch-command/v1").mock(
+ return_value=httpx.Response(200, json={"combined": {"resources": {"some-other-host": {"stdout": PS_OUTPUT}}}})
+ )
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ assert await client.is_process_running("dev-1", 4242) is None
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_a_non_200_is_indeterminate(self) -> None:
+ respx.post("https://api.crowdstrike.com/oauth2/token").mock(return_value=httpx.Response(200, json={"access_token": "t"}))
+ respx.post("https://api.crowdstrike.com/real-time-response/combined/batch-init-session/v1").mock(
+ return_value=httpx.Response(200, json={"batch_id": "b-1"})
+ )
+ respx.post("https://api.crowdstrike.com/real-time-response/combined/batch-command/v1").mock(return_value=httpx.Response(403))
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ assert await client.is_process_running("dev-1", 4242) is None
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_a_transport_failure_is_indeterminate(self) -> None:
+ respx.post("https://api.crowdstrike.com/oauth2/token").mock(side_effect=httpx.ConnectError("unreachable"))
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ assert await client.path_exists("dev-1", "C:\\evil.exe") is None
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_an_empty_listing_means_the_path_is_gone(self) -> None:
+ """The one place an empty string is a result rather than an absence.
+
+ ``ls`` on a removed path returns no stdout, so ``_read_only_command``
+ has to distinguish "" from None or the quarantine could never verify.
+ """
+ _mock_rtr(stdout="")
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ assert await client.path_exists("dev-1", "C:\\evil.exe") is False
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_a_listing_with_content_means_the_path_is_still_there(self) -> None:
+ _mock_rtr(stdout="Directory listing for C:\\Users\\Public\\\n-rw-r--r-- evil.exe 184320\n")
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ assert await client.path_exists("dev-1", "C:\\Users\\Public\\evil.exe") is True
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_reads_go_to_the_read_only_command_tier(self) -> None:
+ """Not ``batch-active-responder-command``, which is where ``rm`` lives.
+
+ A verification path that posts to the mutating endpoint is one typo
+ away from deleting the thing it was asked to check.
+ """
+ seen: dict[str, Any] = {}
+
+ def record(request: httpx.Request) -> httpx.Response:
+ seen["url"] = str(request.url)
+ seen["body"] = request.read().decode()
+ return httpx.Response(200, json={"combined": {"resources": {"dev-1": {"stdout": PS_OUTPUT, "complete": True}}}})
+
+ respx.post("https://api.crowdstrike.com/oauth2/token").mock(return_value=httpx.Response(200, json={"access_token": "t"}))
+ respx.post("https://api.crowdstrike.com/real-time-response/combined/batch-init-session/v1").mock(
+ return_value=httpx.Response(200, json={"batch_id": "b-1"})
+ )
+ respx.post("https://api.crowdstrike.com/real-time-response/combined/batch-command/v1").mock(side_effect=record)
+
+ client = CrowdStrikeRTRClient(client_id="cid", client_secret="unit-test-placeholder")
+ await client.is_process_running("dev-1", 4242)
+
+ assert seen["url"].endswith("/real-time-response/combined/batch-command/v1")
+ assert json.loads(seen["body"])["base_command"] == "ps"
+
+
+def _mock_rtr(*, stdout: str, complete: bool = True) -> None:
+ respx.post("https://api.crowdstrike.com/oauth2/token").mock(return_value=httpx.Response(200, json={"access_token": "t"}))
+ respx.post("https://api.crowdstrike.com/real-time-response/combined/batch-init-session/v1").mock(
+ return_value=httpx.Response(200, json={"batch_id": "b-1"})
+ )
+ respx.post("https://api.crowdstrike.com/real-time-response/combined/batch-command/v1").mock(
+ return_value=httpx.Response(200, json={"combined": {"resources": {"dev-1": {"stdout": stdout, "complete": complete}}}})
+ )
+
+
+class TestProbesCallTheirClientsWithSignaturesThatExist:
+ """Autospec, for the reason this service has learned twice.
+
+ Simulation mode never constructs a vendor client, so a wrong keyword is
+ invisible until a live call raises ``TypeError``. It is worse in a probe
+ than in an executor: ``PostActionVerifier.verify`` catches every
+ exception and reports UNVERIFIED, so a probe calling a method that does
+ not exist would degrade silently and permanently to "we could not check"
+ — with a contract next to it declaring that we could.
+ """
+
+ @pytest.mark.asyncio
+ async def test_kill_process_probe_matches_the_rtr_client(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ client = create_autospec(CrowdStrikeRTRClient, spec_set=True, instance=True)
+ client.get_device_id.return_value = "dev-1"
+ client.is_process_running.return_value = False
+ monkeypatch.setattr(module, "_cs_client", lambda params: client)
+
+ assert await _probe_kill_process("WKSTN-01", CS_PARAMS) is True
+ client.is_process_running.assert_awaited_once_with("dev-1", 4242)
+
+ @pytest.mark.asyncio
+ async def test_quarantine_file_probe_matches_the_rtr_client(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ client = create_autospec(CrowdStrikeRTRClient, spec_set=True, instance=True)
+ client.get_device_id.return_value = "dev-1"
+ client.path_exists.return_value = False
+ monkeypatch.setattr(module, "_cs_client", lambda params: client)
+
+ assert await _probe_quarantine_file("WKSTN-01", FILE_PARAMS) is True
+ client.path_exists.assert_awaited_once_with("dev-1", FILE_PARAMS["file_path"])
+
+ @pytest.mark.asyncio
+ async def test_av_scan_probe_matches_the_defender_client(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ client = create_autospec(DefenderClient, spec_set=True, instance=True)
+ client.find_machine.return_value = {"id": "mde-1"}
+ client.list_machine_actions.return_value = [{"id": "act-7"}]
+ client.get_machine_action.return_value = {"id": "act-7", "status": "Succeeded"}
+ monkeypatch.setattr(module, "_mde_client", lambda params: client)
+
+ assert await _probe_run_av_scan("WKSTN-01", {}) is True
+ client.list_machine_actions.assert_awaited_once_with("mde-1", AV_SCAN_ACTION, limit=5)
+ client.get_machine_action.assert_awaited_once_with("act-7")
+
+ def test_the_read_commands_are_real_methods_on_the_real_client(self) -> None:
+ """An autospec of a class that lost a method passes vacuously.
+
+ ``create_autospec`` builds from whatever the class has, so if
+ ``is_process_running`` were deleted the tests above would fail on the
+ attribute — but a *renamed* one would not be caught by anything that
+ only asserts the probe's own behaviour against a mock.
+ """
+ for name in ("is_process_running", "path_exists"):
+ method = getattr(CrowdStrikeRTRClient, name, None)
+ assert method is not None, f"CrowdStrikeRTRClient.{name} is gone; the probe that calls it will report UNVERIFIED forever"
+ assert inspect.iscoroutinefunction(method)
+
+
+class TestTheContractsMatchWhatShipped:
+ @pytest.mark.parametrize("capability", ["kill_process", "quarantine_file", "run_av_scan"])
+ def test_the_new_probes_are_declared_and_registered(self, capability: str) -> None:
+ assert CAPABILITY_CONTRACTS[capability].has_verification_probe is True
+ assert ActionType(capability) in _DEFAULT_PROBES
+
+ def test_run_script_still_reports_unverified_and_says_why(self) -> None:
+ """The honest answer, not an absence.
+
+ No read-back can confirm an arbitrary script did what it was meant to
+ — the platform does not know what that was. The exit code says it
+ ran, which is a different claim. An invented probe here would be one
+ that cannot fail.
+ """
+ contract = CAPABILITY_CONTRACTS["run_script"]
+ assert contract.has_verification_probe is False
+ assert ActionType.RUN_SCRIPT not in _DEFAULT_PROBES
+ assert "nothing to probe" in contract.verification_gap.lower()
diff --git a/services/actions/tests/test_verification.py b/services/actions/tests/test_verification.py
index 41a0e848c..33892491d 100644
--- a/services/actions/tests/test_verification.py
+++ b/services/actions/tests/test_verification.py
@@ -77,10 +77,21 @@ async def test_unverified_without_credentials(monkeypatch):
async def test_unverified_for_action_without_probe():
+ """A verb with no probe says so by name, in the shipped configuration.
+
+ The verb is derived rather than named. This used to assert on
+ ``QUARANTINE_FILE``, which now has a probe — so the test would have gone
+ green for the wrong reason if the stand-in had been swapped for another
+ hardcoded verb that later gained one too.
+ """
v = PostActionVerifier()
- res = await v.verify(ActionType.QUARANTINE_FILE, "x", {})
+ unprobed = [a for a in ActionType if a not in v.probes]
+ assert unprobed, "every ActionType has a probe; this test no longer proves anything and should be deleted"
+
+ res = await v.verify(unprobed[0], "x", {})
assert res.outcome == VerificationOutcome.UNVERIFIED
assert "no read-back verifier" in res.reason
+ assert unprobed[0].value in res.reason
async def test_probe_error_is_unverified_never_false_verified(monkeypatch):
diff --git a/services/actions/tests/test_verification_coverage.py b/services/actions/tests/test_verification_coverage.py
index 8720756c9..80e9d758c 100644
--- a/services/actions/tests/test_verification_coverage.py
+++ b/services/actions/tests/test_verification_coverage.py
@@ -52,14 +52,85 @@ class TestDeclarationsMatchReality:
continue
assert contract.verification_gap.strip(), f"{capability} is {contract.impact.value} impact with no probe and no stated reason"
+ def test_every_dispatchable_verb_either_probes_or_says_why_not(self) -> None:
+ """Widened from HIGH/SEVERE to every verb a probe could be written for.
+
+ Eleven of the fourteen response verbs the playbook engine bridges had
+ no probe. That failed *safe* — the verifier returns UNVERIFIED naming
+ the missing verifier — so nothing was being certified falsely. What it
+ did not do was distinguish the three answers that absence can have:
+
+ * nobody has written it yet;
+ * the vendor exposes no read-back;
+ * there is nothing to read back, because the action changes nothing
+ or because the response genuinely is the confirmation.
+
+ Those are the same silence, and the first one is the only one that is
+ a gap. Requiring a sentence turns the next one into a decision
+ somebody made in review, which is the whole reason the field exists.
+
+ Scoped to capabilities with an ``ActionType`` because probes are keyed
+ on it — see the sibling test for the ones that structurally cannot
+ have one.
+ """
+ dispatchable = {a.value for a in ActionType}
+ silent = [
+ capability
+ for capability, contract in CAPABILITY_CONTRACTS.items()
+ if capability in dispatchable and not contract.has_verification_probe and not contract.verification_gap.strip()
+ ]
+ assert silent == [], (
+ f"no probe and no reason recorded for: {sorted(silent)}. "
+ f"Write the reason — 'the vendor exposes no read-back', 'the "
+ f"response is the confirmation', 'a read changes nothing' are all "
+ f"answers; saying nothing is not."
+ )
+
+ def test_a_capability_with_no_action_type_cannot_claim_a_probe(self) -> None:
+ """Probes are keyed on ``ActionType``, so a verb without one is
+ unverifiable by construction rather than by vendor limitation.
+
+ The dispatcher already reports this honestly at runtime. Asserting it
+ here stops a contract from *declaring* a probe the verifier could
+ never reach, which would be a claim with nothing behind it.
+ """
+ dispatchable = {a.value for a in ActionType}
+ for capability, contract in CAPABILITY_CONTRACTS.items():
+ if capability in dispatchable:
+ continue
+ assert not contract.has_verification_probe, (
+ f"{capability} declares a verification probe and has no ActionType to key one on, so nothing can ever run it"
+ )
+
def test_unverifiable_actions_are_not_automatic(self) -> None:
- """Unverifiable means not autonomous, whatever the confidence."""
+ """Unverifiable means not autonomous, whatever the confidence.
+
+ The waiver below MODERATE is not a blanket one. It exists for the
+ case where the response genuinely *is* the confirmation — a created
+ ticket returns the identifier the vendor allocated, and it could not
+ allocate one without creating the record — so an automatic verb that
+ takes the waiver has to say which case it is in. ``run_av_scan`` is
+ why: it is LOW and automatic and Defender replies ``Pending``, so the
+ response is the one thing it certainly is not, and a blanket waiver
+ let it ship with nothing checking a sweep had run.
+ """
for capability, contract in CAPABILITY_CONTRACTS.items():
if contract.approval != ApprovalRequirement.AUTOMATIC:
continue
- if contract.impact in (ActionImpact.READ_ONLY, ActionImpact.LOW):
- # A created ticket returns its own id; the response is the
- # confirmation.
+ if contract.has_verification_probe:
+ continue
+ if contract.impact is ActionImpact.READ_ONLY:
+ # Not a waiver. A read leaves nothing behind, so there is no
+ # effect for a probe to find — a property of the tier rather
+ # than a judgement about a particular verb, asserted once
+ # here instead of restated on each of them.
+ continue
+ if contract.impact is ActionImpact.LOW:
+ assert contract.verification_gap.strip(), (
+ f"{capability} is automatic at {contract.impact.value} impact and takes the "
+ f"'the response is the confirmation' waiver without saying so. State it on "
+ f"the contract, or give the verb a probe."
+ )
continue
assert contract.has_verification_probe, (
f"{capability} is automatic at {contract.impact.value} impact with nothing checking the effect"