Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(actions): let an investigation read the vendor a tenant actually runs (#914)
Beenu Arora147f89cc300e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ee667833c..ea7fac09d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -98,6 +98,61 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **An investigation can now read the vendor a tenant actually runs**+ (gap-closure Phase 4.2). Seven new read-only executors: SentinelOne agents+ and threats, Microsoft Defender alerts and an endpoint-telemetry search,+ Microsoft Entra ID sign-ins with the ID Protection risk record, Google+ Workspace login audit, and AWS CloudTrail `LookupEvents`.++ **The gap.** Three read verbs existed with one vendor arm each, which is a+ CrowdStrike-and-Okta surface rather than a vendor-read surface. A tenant on+ SentinelOne and Entra ID had the same investigation reach as a tenant with+ no EDR at all, because the verb existed and nothing implemented it for+ them: governed dispatch answered `executor_not_found`, which reads as a+ broken deployment rather than as a capability nobody wrote.++ **Five of the seven are new vendor arms on the three existing verbs**,+ which is what declaring a contract per capability rather than per vendor+ buys: they inherit the `READ_ONLY` classification automatically and cannot+ drift low. Only the two whose subject is neither a host nor a principal+ needed their own contract, `lookup_cloud_audit` and+ `lookup_endpoint_telemetry`.++ **A read failure is never an empty result**, and the tests assert the shape+ rather than the intent. A host the vendor does not hold is `SUCCEEDED` with+ `found: False`; a vendor that 5xxs is `FAILED` and carries **no** `count`,+ `detections` or `found` key at all, because a `count: 0` reaching a model+ is the strongest exonerating evidence there is and would be false. Entra's+ ID Protection leg is licensed, so it may fail without taking the sign-ins+ down and its absence reads as unknown rather than as no risk. Google+ Workspace's 403 names the missing `admin.reports.audit.readonly` scope,+ which is a configuration fact rather than an account with no logins.++ **No caller supplies query text.** Defender advanced hunting takes KQL, and+ these verbs are reachable from an investigation agent whose indicator was+ lifted out of attacker-influenced alert text. So the KQL lives in the+ executor as a closed set of four named templates, the caller passes a+ template name plus one indicator plus a window, and an unknown template is+ refused before the credential is even read. The accepted path is asserted+ on the KQL that reaches the wire rather than on the argument, with a+ hostile indicator appearing only in its escaped form. The same discipline+ applies per grammar: OData doubles a single quote for Entra, and the+ CloudTrail attribute key is checked against AWS's own closed vocabulary+ rather than escaped at all.++ **CloudTrail is read without adding boto3.** boto3 is not in the+ `aisoc-actions` image (measured: `ModuleNotFoundError`, against 1.43.101 in+ `aisoc-connectors`), and ADR-0007 has just published that image at 539 MB+ after moving the service into CORE. `LookupEvents` is one signed JSON POST,+ so the SigV4 signing is about sixty lines of `hmac` and `hashlib` and needs+ nothing outside the standard library. The canonical request is pinned line+ by line against the documented shape, `SignedHeaders` is parsed back out of+ the header the client produced and every name asserted present on the+ request, and the signing-key derivation is asserted sensitive to secret,+ date and region in turn so a dropped link cannot pass as a plausible hex+ string. **The live AWS path is unverified**: there is no funded AWS account+ here, so a signature AWS itself accepts has not been observed, and the+ documentation says so rather than implying otherwise.- **AiSOC's own MCP server gains triage verdicts, replay reports and adry-run-only action preview** (gap-closure Phase 5.6). Five new tools, 13 to18.@@ -216,6 +271,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0by this project, and the tool names given are examples to be replaced withwhat the vendor's own `tools/list` publishes.+- **`connectors` and `actions` now start on the default CORE profile, so theinvestigation agent has somewhere to reach** (gap-closure Phase 4.5,[ADR-0007](docs/decisions/0007-connectors-and-actions-in-core.md)).diff --git a/GAP_CLOSURE_PROGRESS.md b/GAP_CLOSURE_PROGRESS.mdindex 8917b9b41..417fe5489 100644--- a/GAP_CLOSURE_PROGRESS.md+++ b/GAP_CLOSURE_PROGRESS.md@@ -352,7 +352,7 @@ in D20.## Phase 4: Let the investigation agent reach the customer's tools- [ ] **4.1 Federated search tool** as a typed agent tool; the model never writes SPL, KQL or ES|QL.-- [ ] **4.2 Vendor read tools**, plus new read verbs for SentinelOne, Microsoft Entra ID, Google Workspace, AWS CloudTrail and Microsoft Defender.+- [~] **4.2 Vendor read tools**, plus new read verbs for SentinelOne, Microsoft Entra ID, Google Workspace, AWS CloudTrail and Microsoft Defender. The verbs half is shipped: seven new executors, five of them vendor arms on the three existing read verbs so they inherit the `READ_ONLY` contract and cannot drift low, and two new verbs (`lookup_cloud_audit`, `lookup_endpoint_telemetry`) whose subject is neither a host nor a principal. 25 tests against vendor-shaped synthetic payloads on the real HTTP path, asserting the pair that must never collapse: not-found is `SUCCEEDED` with `found: False`, a vendor 5xx is `FAILED` and carries no `count`, `detections` or `found` key at all. CloudTrail is read with hand-rolled SigV4 rather than boto3, which is measurably absent from the `aisoc-actions` image; the live AWS path is unverified and recorded as such (see D18). Exposing them **as agent tools through the API** is the other half and lands with 4.1 and 4.3.- [ ] **4.3 Tool handling**: advertise only configured backends, project and cap results, mark them untrusted, and surface a read failure as "could not check".- [ ] **4.4 Strategies** updated so `check_investigation_depth.py` still holds.- [x] **4.5 CORE decision**: measured, decided in [ADR-0007](docs/decisions/0007-connectors-and-actions-in-core.md), implemented. Both services join CORE. Measured with images pulled fresh from GHCR and `docker stats`, the same method as ADR-0006: `actions` 539 MB image / 45.99 MiB cold-start / 48.3 MiB at 40 hours, `connectors` 586 MB / 71.45 MiB / 76.51 MiB, together **124.8 MiB against an 8 GB budget, 1.5%**. Cross-checked against `litellm` at 471 MiB on the same host, which ADR-0006 measured at 451 MiB. ADR-0006's misleading-idle trap was checked for and is absent: neither moves more than 0.6 MiB under 100 requests, because both are network front ends with no model and no index. Both verified to boot and serve with zero configuration. The decision turned on something stronger than a feature gap, recorded as D17: CORE was already *configured* for both and started neither. The README's ~8 GB figure is deliberately not moved, and the lake and graph deliberately stay in `full`.@@ -694,6 +694,66 @@ needing its own measurement. After this change a CORE agent can reach aconfigured vendor and still cannot reach an event lake, and the eleven lakepivots report their data class is unavailable rather than returning empty.+### D18. Two of Phase 4.2's five vendors needed a client, not a read method, and one of them needed a signer++The plan says to "add read verbs for clients that already exist". Three of the+five were exactly that: `sentinelone_client.py`, `azure_entra_client.py` and+`google_workspace_client.py` each gained read methods beside the response+methods already there, and `defender_client.py` gained two.++**AWS was not.** The AWS client in `services/actions` is+`aws_security_groups.py`, which manages firewall rules and has no audit read.+Worse, it is built on boto3, and boto3 **is not installed in the actions+image**: measured on the published artefact, `import boto3` raises+`ModuleNotFoundError` in `aisoc-actions` and succeeds at 1.43.101 in+`aisoc-connectors`. So every live security-group call in that client already+degrades to "boto3 not installed in actions service", and a CloudTrail verb+built the same way would have been a declared capability that could never run.++Adding boto3 was the obvious fix and is the wrong one here. botocore is tens+of megabytes, and ADR-0007 in the PR immediately before this one has just+published this image at 539 MB and moved it into CORE on the strength of that+number. `LookupEvents` is a single signed JSON POST, so SigV4 by hand is about+sixty lines of `hmac` and `hashlib` with nothing outside the standard library.++**What that costs in honesty, stated rather than hidden.** A hand-rolled+signer is one header-ordering mistake from 403 on every call, and there is no+funded AWS account in this repository, so no signature has ever been offered+to AWS. What the tests pin is the algorithm against its specification: the+canonical request line by line, `SignedHeaders` parsed back out of the header+the client produced with every name asserted present on the request, and the+signing-key chain asserted sensitive to secret, date and region in turn so a+dropped link cannot pass as a plausible hex string. The live path is+**unverified**, and the claim-matrix row and the docs say so in those words.+That is the same position the plan takes for vendor MCP servers in 5.5.++The second one worth recording is the Google Workspace scope. The existing+client requests two directory scopes, and the login audit lives behind+`admin.reports.audit.readonly`, which is a third. A deployment whose service+account has not been granted it domain-wide gets a 403, and the executor's+error names the scope, because an operator reading "no logins" would conclude+the account was quiet.++### D19. Defender advanced hunting takes KQL, which is the one thing a caller may not supply++The plan asks for "a read-only advanced hunting query" and separately forbids+a model composing query text against a customer's estate. Both are right and+the naive reading of the first breaks the second, so the resolution is+recorded here.++The verb takes a **template name**, one indicator and a window. The KQL lives+in `_HUNT_TEMPLATES` in `defender_client.py` as four named queries, each+reading a `target` and a `window` the client binds as KQL `let` statements+and comparing by equality only, so a value has no way to become an operator.+An unknown template name is refused **before the credential is read**, so an+operator is not sent to look at their Azure app registration for a caller's+mistake, and the test asserts the vendor route was never called.++The verb is named `lookup_endpoint_telemetry` rather than `run_hunting_query`+deliberately. A verb named for running a query invites a later contributor to+add a `query` parameter, and the name is the cheapest place to encode the+constraint.+### D12. `unified_decision` had no production caller, and the plan names it anywayThe plan says to wire the promotion gate intodiff --git a/ROADMAP.md b/ROADMAP.mdindex 41f86fc46..3650f3f5a 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 **188 rows — 180 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 **193 rows — 185 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 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex ca94ef06d..4d9cf7e7d 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 | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `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: 180 rows+The last row is the one worth reading first. It is the honest index: 185 rows`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 0433f69fa..216bdc32a 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -196,6 +196,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| The agents service requests the MCP registry at a path the API service serves | `services/agents/app/mcp/registry_client.py` | `ci.yml` agents job (`test_mcp_registry_client.py::test_the_registry_url_matches_where_the_route_is_mounted`: the app mount, the v1 router prefix and the endpoint router prefix are read out of the API service's own source with `ast` and composed the way the service composes them, then compared against the URL the client builds. Proven able to fail by emptying `API_PREFIX`, which names both the requested path and the served set) | GATED | The same defect D16 records: Phase 1.2 shipped a client missing `/api/v1`, so every request would have 404'd while three suites stayed green, because the test asserted the URL the code produced rather than the URL the service serves. This service cannot import that one, so reading the other tree's source is the only comparison in the direction that drifts || No MCP tool AiSOC ships can perform a response action; the action tool is dry-run only | `services/mcp/README.md` (Actions are previewed, never performed); `apps/docs/docs/integrations/mcp.md` | `ci.yml :: mcp` (`tests/actions.test.ts`: the **source** of `services/mcp/src/` is read and no string may name `/live-actions/dispatch`, so a second action tool added later is caught rather than only the one under test; the preview handler is driven against a recording client and asserted to make exactly one request, to the dry-run path, carrying `dry_run: true`; and its strict schema is asserted to reject a caller-supplied `dry_run: false`. Proven able to fail by pointing the module constant at the dispatch path, which reds both the source scan and the request assertion) | GATED | The enforcing control is upstream: `POST /api/v1/live-actions/dry-run` forces `dry_run: true` server-side whatever the body says and proxies only that path. This row is the second lock, on the side an agent can see, because an MCP key is credential material that lives in an editor's configuration file || Every tool AiSOC's MCP server publishes carries honest behaviour annotations | `services/mcp/README.md` (Tools exposed); `apps/docs/docs/integrations/mcp.md` (Annotations, and what is read-only) | `ci.yml :: mcp` (`tests/actions.test.ts`: every tool in `ALL_TOOLS` must declare `readOnlyHint` as a boolean rather than leaving it absent, no tool may be annotated destructive, and the set of tools annotated **not** read-only is pinned to exactly `aisoc_run_investigation`, so a future write tool cannot arrive annotated read-only and a read tool cannot drift into looking state-changing) | GATED | The annotations are what a client reads to decide whether it may call a tool at all. AiSOC's own MCP client refuses a tool whose server sets `destructiveHint: true` or `readOnlyHint: false`, and treats an absent annotation as no claim, so a server publishing nothing forces every operator to vouch for every tool by name |+| MCP server exposes 13 tools | README L179 | `ci.yml :: mcp` | GATED | - |+| Prompt-injection resistance | (implied by agent claims) | `ci.yml :: python-test` (agents) runs `test_prompt_sanitizer.py`, `test_prompt_envelope.py` and `tests/adversarial/` — a 32-payload corpus grouped by attacker goal, enforcing a recall floor **and** a false-positive ceiling on real security content that reads adversarially. Action-trigger and exfiltration payloads are individually required rather than averaged, because an injected containment turns the SOC into a denial-of-service tool pointed at its own estate. Phase 3 adds a second, harder corpus at incident level (`test_injection_incidents.py`) whose payloads are written to fit the field they arrive in, enforcing a floor, a ceiling and an exact ratchet naming every current blind spot by id | GATED | obfuscation is an arms race and is recorded rather than individually required; two payloads are currently xfail and counted in the recall rate. The two corpora measure the same guard and are **not comparable**: one asks whether the guard recognises a string, the other whether it recognises it where an attacker can put it, and the second scores materially lower. Neither measures a model |+| An investigation can read the vendor a tenant actually runs, not just CrowdStrike and Okta | `plans/aisoc_gap_closure_plan.plan.md` (4.2); `services/actions/app/live_actions/investigation_reads.py` | `ci.yml` actions job (`test_investigation_reads_phase4.py`, 25 tests over seven new executors against vendor-shaped synthetic payloads on the real HTTP path. Each verb is tested for the pair that must never collapse: a host or principal the vendor does not hold is `SUCCEEDED` with `found: False`, a vendor that 5xxs is `FAILED`, and a failed read is asserted to carry **no** `count`, `detections` or `found` key, because a `count: 0` reaching a model is the strongest exonerating evidence there is and would be false. Entra's licensed risk leg may fail without taking the sign-ins down and reads as unknown rather than as no risk; Google Workspace's 403 names the missing `admin.reports.audit.readonly` scope rather than reporting an account with no logins) + `ci.yml` gates job (`check_action_contract.py`, 79 executors, and `check_capability_mirror` comparing the actions vocabulary against the connectors `Capability` enum in both directions) | GATED | Five of the seven are new vendor arms on the three existing read verbs, so they inherit the `READ_ONLY` contract and cannot drift low; only `lookup_cloud_audit` and `lookup_endpoint_telemetry` needed their own entry. **No call in this repository has been made against a live vendor** for any of them: there is no funded CrowdStrike, SentinelOne, Entra, Google Workspace, Defender or AWS account here, so the wire shapes are pinned against the vendors' published schemas and the live path is unverified, which the docs state rather than imply |+| A caller of a vendor read never supplies query text; the executor owns the query | `plans/aisoc_gap_closure_plan.plan.md` (4.1, 4.2); `services/actions/app/clients/defender_client.py` (`_HUNT_TEMPLATES`) | `ci.yml` actions job (`test_investigation_reads_phase4.py`: `lookup_endpoint_telemetry` is offered four rejected inputs including a bare KQL pipeline, a template name with a statement appended and a case variation, and each is refused **before the credential is read** with a route asserted uncalled, so a refused template cannot reach the vendor; the accepted path is asserted on the KQL that reaches the wire rather than on the argument, with a hostile indicator carrying a quote and a pipe appearing only in its escaped form; the window and row cap are asserted at 720h and 200 against a caller asking for 99,999h and 10,000 rows. Entra's OData literal is asserted the same way, with the doubled quote present and the single-quote form absent) | GATED | The escaping is grammar-specific and each grammar is handled at its own boundary: KQL escapes backslash and double quote, OData doubles a single quote, and the CloudTrail attribute key is checked against AWS's own closed vocabulary rather than escaped at all. A new vendor grammar needs its own escape and its own test; nothing structurally forces that beyond review |+| AWS CloudTrail is read without adding boto3 to a CORE service | `services/actions/app/clients/aws_cloudtrail_client.py`; [ADR-0007](../decisions/0007-connectors-and-actions-in-core.md) | `ci.yml` actions job (`test_investigation_reads_phase4.py`: the SigV4 canonical request is pinned line by line against the documented shape, including the blank line between canonical and signed headers and the body hash as the final line; `SignedHeaders` is parsed back out of the `Authorization` header the client produced and every name in it asserted present on the request, which is the failure mode of a hand-rolled signer; the signing-key derivation is asserted sensitive to secret, date **and** region in turn, so a dropped link in the chain cannot pass as a plausible hex string; a session token is asserted both signed and sent. `canonical_parts` is the function `_authorization` itself calls, so the test is not comparing a producer against a copy of itself) | GATED | **The live AWS path is unverified.** There is no funded AWS account in this repository, so what is gated is that the algorithm matches the specification and that the response parsing and projection work against a recorded payload. A signature that AWS itself accepts has not been observed. boto3 is deliberately not added: it is not in the `aisoc-actions` image (measured: `ModuleNotFoundError`, against 1.43.101 in `aisoc-connectors`) and ADR-0007 has just published that image at 539 MB |## Summary@@ -203,7 +208,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- GATED: 180+- GATED: 185- 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/aws_cloudtrail_client.py b/services/actions/app/clients/aws_cloudtrail_client.pynew file mode 100644index 000000000..7817a9c32--- /dev/null+++ b/services/actions/app/clients/aws_cloudtrail_client.py@@ -0,0 +1,346 @@+"""AWS CloudTrail ``LookupEvents``, for investigation rather than response.++Gap-closure Phase 4.2.++Why this is not boto3+---------------------+``aws_security_groups.py`` in this directory uses boto3 and degrades to+"boto3 not installed in actions service" on every live call, because **boto3+is not a dependency of this service**. Measured on the published image:+``import boto3`` raises ``ModuleNotFoundError`` in ``aisoc-actions`` and+succeeds in ``aisoc-connectors`` at 1.43.101. So the choice was to add boto3+here or to sign one request by hand.++boto3 plus botocore is tens of megabytes of wheel, and ADR-0007 has just+moved this service into the CORE profile on the strength of a 539 MB image+and 48 MiB resident. Paying that for one read verb would be trading a+published number for a convenience. ``LookupEvents`` is a single JSON POST+with a SigV4 ``Authorization`` header; the signing is about sixty lines of+``hmac`` and ``hashlib`` and needs nothing outside the standard library.++What is and is not verified+---------------------------+The canonical request, the string to sign, the derived signing key and the+header set are pinned by tests against fixed inputs, so the algorithm cannot+drift silently, and the response parsing and projection run against a+recorded CloudTrail payload through ``httpx.MockTransport``.++**No call has been made against live AWS from this repository.** There is no+funded AWS account here, so the live path is unverified and the documentation+says so rather than implying otherwise. That is the same position the plan+takes for vendor MCP servers: shipped, documented, and marked unverified+until somebody runs it.++Read-only by construction+-------------------------+``LookupEvents`` is the only action this client can name. The target header+is built from a constant, not from an argument, so there is no argument any+caller can pass that reaches a different CloudTrail API.+"""++from __future__ import annotations++import datetime as dt+import hashlib+import hmac+import json+from typing import Any++import httpx+import structlog++logger = structlog.get_logger()++_SERVICE = "cloudtrail"+_ALGORITHM = "AWS4-HMAC-SHA256"++#: The one API this client can call. A constant rather than a parameter: an+#: argument here would be the difference between a read client and a+#: general-purpose AWS client wearing a read client's name.+_TARGET = "CloudTrail_20131101.LookupEvents"++#: CloudTrail's own attribute vocabulary for LookupEvents, which is a closed+#: set the API defines. Named here so an unsupported key is refused with the+#: supported list rather than sent and rejected by AWS as a 400 that reads+#: like an outage.+LOOKUP_ATTRIBUTES: frozenset[str] = frozenset(+ {+ "AccessKeyId",+ "EventId",+ "EventName",+ "EventSource",+ "ReadOnly",+ "ResourceName",+ "ResourceType",+ "Username",+ }+)+++class CloudTrailLookupError(RuntimeError):+ """The lookup could not be performed. Never an empty result."""+++def _sign(key: bytes, message: str) -> bytes:+ return hmac.new(key, message.encode("utf-8"), hashlib.sha256).digest()+++def _signing_key(secret_access_key: str, date_stamp: str, region: str) -> bytes:+ """Derive the SigV4 signing key.++ Four chained HMACs over date, region, service and the fixed terminator,+ in that order, per the SigV4 specification. Split out so a test can pin+ the derivation itself rather than only the header it ends up in.+ """+ k_date = _sign(f"AWS4{secret_access_key}".encode(), date_stamp)+ k_region = _sign(k_date, region)+ k_service = _sign(k_region, _SERVICE)+ return _sign(k_service, "aws4_request")+++class AWSCloudTrailClient:+ """Sign and issue one CloudTrail ``LookupEvents`` request.++ Credentials are request-scoped, like every other client in this+ directory: the dispatcher treats a credential as belonging to the call so+ a multi-tenant deployment can route two tenants to two AWS accounts in+ one process.++ ``session_token`` is accepted so a deployment using short-lived+ credentials works. Minting them is not this client's job: STS is a+ different API with its own signing, and a half-implemented assume-role+ would be a capability that works on the operator's laptop and not in+ their account.+ """++ def __init__(+ self,+ access_key_id: str,+ secret_access_key: str,+ *,+ region: str = "us-east-1",+ session_token: str | None = None,+ transport: httpx.AsyncBaseTransport | None = None,+ ) -> None:+ self._access_key_id = access_key_id+ self._secret_access_key = secret_access_key+ self._region = region+ self._session_token = session_token+ # Injected only by tests. A real caller leaves it None and httpx uses+ # its own transport; this is here so the recorded-payload tests drive+ # the same signing and parsing code a live call would.+ self._transport = transport++ @property+ def endpoint(self) -> str:+ return f"https://{_SERVICE}.{self._region}.amazonaws.com/"++ @property+ def host(self) -> str:+ return f"{_SERVICE}.{self._region}.amazonaws.com"++ def _headers_to_sign(self, amz_date: str) -> dict[str, str]:+ """The headers SigV4 covers, lowercased because the spec signs them so.++ Sent to httpx in this same lowercase form rather than title-cased. HTTP+ header names are case-insensitive, and sending exactly the bytes that+ were signed removes any chance of the signature covering one spelling+ while the wire carries another.+ """+ headers = {+ "content-type": "application/x-amz-json-1.1",+ "host": self.host,+ "x-amz-date": amz_date,+ "x-amz-target": _TARGET,+ }+ if self._session_token:+ headers["x-amz-security-token"] = self._session_token+ return headers++ def canonical_parts(self, payload: str, amz_date: str, date_stamp: str) -> tuple[str, str, str]:+ """The canonical request, the string to sign, and the signed-header list.++ Public and returned as data so the tests can pin the algorithm itself+ rather than only the header it ends up inside. ``_authorization``+ calls **this**: a second copy of the canonical-request construction+ for the tests to read would be the one-directional gate this+ repository keeps finding, where a test compares a producer against a+ copy of itself and prints OK.+ """+ headers = self._headers_to_sign(amz_date)+ # Signed headers are the header names lowercased and sorted, and the+ # canonical headers are those same names with their values in the+ # same order. Both are derived from one sorted list so they cannot+ # disagree.+ signed_names = sorted(headers)+ canonical_headers = "".join(f"{name}:{headers[name].strip()}\n" for name in signed_names)+ signed_headers = ";".join(signed_names)++ canonical_request = "\n".join(+ [+ "POST",+ "/",+ "",+ canonical_headers,+ signed_headers,+ hashlib.sha256(payload.encode("utf-8")).hexdigest(),+ ]+ )+ string_to_sign = "\n".join(+ [+ _ALGORITHM,+ amz_date,+ f"{date_stamp}/{self._region}/{_SERVICE}/aws4_request",+ hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(),+ ]+ )+ return canonical_request, string_to_sign, signed_headers++ def _authorization(self, payload: str, amz_date: str, date_stamp: str) -> dict[str, str]:+ """The full header set for one signed POST."""+ _, string_to_sign, signed_headers = self.canonical_parts(payload, amz_date, date_stamp)+ signature = hmac.new(+ _signing_key(self._secret_access_key, date_stamp, self._region),+ string_to_sign.encode("utf-8"),+ hashlib.sha256,+ ).hexdigest()+ credential_scope = f"{date_stamp}/{self._region}/{_SERVICE}/aws4_request"+ return {+ **self._headers_to_sign(amz_date),+ "authorization": (+ f"{_ALGORITHM} Credential={self._access_key_id}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}"+ ),+ }++ async def lookup_events(+ self,+ *,+ attribute_key: str,+ attribute_value: str,+ hours: int = 24,+ limit: int = 50,+ now: dt.datetime | None = None,+ ) -> list[dict[str, Any]]:+ """Look up CloudTrail management events matching one attribute.++ ``attribute_key`` is checked against CloudTrail's own closed+ vocabulary rather than forwarded, so an unsupported key is refused+ here with the supported set named.++ Raises ``CloudTrailLookupError`` on any failure. It never returns an+ empty list to mean "the lookup did not work": an empty CloudTrail+ window is a real and common answer, and a caller that cannot tell the+ two apart will conclude a principal did nothing when in fact nobody+ looked.+ """+ if attribute_key not in LOOKUP_ATTRIBUTES:+ raise CloudTrailLookupError(+ f"{attribute_key!r} is not a CloudTrail lookup attribute; CloudTrail accepts {', '.join(sorted(LOOKUP_ATTRIBUTES))}"+ )+ if not str(attribute_value).strip():+ raise CloudTrailLookupError(f"a {attribute_key} value is required; an empty lookup would match the whole window")++ moment = now or dt.datetime.now(dt.UTC)+ window = max(1, min(hours, 720))+ payload = json.dumps(+ {+ "LookupAttributes": [{"AttributeKey": attribute_key, "AttributeValue": str(attribute_value)}],+ "StartTime": (moment - dt.timedelta(hours=window)).timestamp(),+ "EndTime": moment.timestamp(),+ "MaxResults": min(max(1, limit), 50),+ },+ separators=(",", ":"),+ )+ amz_date = moment.strftime("%Y%m%dT%H%M%SZ")+ date_stamp = moment.strftime("%Y%m%d")++ try:+ async with httpx.AsyncClient(timeout=30.0, transport=self._transport) as client:+ response = await client.post(+ self.endpoint,+ headers=self._authorization(payload, amz_date, date_stamp),+ content=payload,+ )+ except httpx.HTTPError as exc:+ raise CloudTrailLookupError(f"CloudTrail was unreachable: {type(exc).__name__}") from exc++ if response.status_code >= 400:+ # AWS returns its error type in a JSON body. Surfaced because the+ # difference between "these credentials cannot LookupEvents" and+ # "CloudTrail is down" is the difference between a configuration+ # fix and a wait, and both look the same as a bare 400.+ detail = ""+ try:+ body = response.json()+ detail = str(body.get("__type") or body.get("message") or "")+ except ValueError:+ detail = response.text[:200]+ raise CloudTrailLookupError(f"CloudTrail returned HTTP {response.status_code}: {detail or 'no detail'}")++ try:+ body = response.json()+ except ValueError as exc:+ raise CloudTrailLookupError("CloudTrail returned a body that is not JSON") from exc++ events = body.get("Events") or []+ projected = [_project_event(entry) for entry in events if isinstance(entry, dict)]+ logger.info("cloudtrail.lookup", attribute=attribute_key, count=len(projected))+ return projected+++def _mfa_authenticated(identity: dict[str, Any]) -> Any:+ """Whether the session was MFA-authenticated, or ``None`` if not stated.++ Pulled out rather than inlined as a chained conditional. Three levels of+ `.get(...) or {}` in one expression is unreadable, and the inline form+ re-fetched `sessionContext` so the value the guard inspected was not the+ value that was used.+ """+ session = identity.get("sessionContext")+ if not isinstance(session, dict):+ return None+ attributes = session.get("attributes")+ if not isinstance(attributes, dict):+ return None+ return attributes.get("mfaAuthenticated")+++def _project_event(entry: dict[str, Any]) -> dict[str, Any]:+ """Reduce one CloudTrail event to what an investigation reads.++ ``CloudTrailEvent`` is a JSON *string* holding the full record, which for+ a single API call routinely runs to several kilobytes of request+ parameters, response elements and TLS details. The nine fields below are+ the ones an analyst reads; the rest is token cost with a bounded amount of+ signal, and it is where injected text in a resource name would otherwise+ travel unexamined into a prompt.+ """+ detail: dict[str, Any] = {}+ raw = entry.get("CloudTrailEvent")+ if isinstance(raw, str):+ try:+ parsed = json.loads(raw)+ if isinstance(parsed, dict):+ detail = parsed+ except ValueError:+ # A malformed record is not a failed lookup. The envelope fields+ # below still answer the question; the detail is simply absent.+ logger.warning("cloudtrail.event_detail_unparseable", event_id=entry.get("EventId"))++ raw_identity = detail.get("userIdentity")+ identity: dict[str, Any] = raw_identity if isinstance(raw_identity, dict) else {}+ return {+ "event_id": entry.get("EventId"),+ "event_name": entry.get("EventName"),+ "event_source": entry.get("EventSource"),+ "event_time": entry.get("EventTime"),+ "username": entry.get("Username"),+ "read_only": entry.get("ReadOnly"),+ "region": detail.get("awsRegion"),+ "source_ip": detail.get("sourceIPAddress"),+ "user_agent": detail.get("userAgent"),+ "error_code": detail.get("errorCode"),+ "principal_type": identity.get("type"),+ "principal_arn": identity.get("arn"),+ "mfa_authenticated": _mfa_authenticated(identity),+ }diff --git a/services/actions/app/clients/azure_entra_client.py b/services/actions/app/clients/azure_entra_client.pyindex e4f12f27d..678158202 100644--- a/services/actions/app/clients/azure_entra_client.py+++ b/services/actions/app/clients/azure_entra_client.py@@ -44,6 +44,7 @@ from __future__ import annotationsimport secretsimport string+from datetime import UTC, datetime, timedeltafrom typing import Anyimport httpx@@ -56,6 +57,27 @@ _GRAPH = "https://graph.microsoft.com/v1.0"_GRAPH_BETA = "https://graph.microsoft.com/beta"+def _quote_odata_string(value: str) -> str:+ """Escape a value for a single-quoted OData string literal.++ OData escapes a single quote by doubling it, and that is the whole of the+ grammar's escaping rule. Everything else inside the quotes is literal.++ This matters because the read methods below are reachable, through the+ live-action registry, from an investigation agent, and the value it passes+ is a principal name lifted out of alert text. Alert text is+ attacker-influenced. A raw interpolation would let a crafted+ ``userPrincipalName`` close the literal and append a clause, which on a+ read endpoint means reading another principal's sign-ins.++ Control characters are dropped rather than escaped: a newline in a UPN is+ not a principal name, and there is no reading of it that is worth+ preserving.+ """+ cleaned = "".join(ch for ch in str(value) if ch.isprintable())+ return cleaned.replace("'", "''")++def _gen_temp_password(length: int = 16) -> str:"""Generate a Microsoft-policy-compliant temporary password.@@ -139,6 +161,105 @@ class AzureEntraClient:logger.warning("entra.get_user_enabled.failed", upn=user_principal_name, error=str(exc))return None+ async def list_sign_ins(+ self,+ user_principal_name: str,+ *,+ hours: int = 24,+ limit: int = 50,+ ) -> list[dict[str, Any]]:+ """Recent sign-in attempts for one principal, successes and failures.++ Gap-closure Phase 4.2. Read-only: a GET over ``/auditLogs/signIns``.++ Both outcomes are returned rather than only failures, because the+ question an identity investigation asks is not "did anything fail" but+ "what did the pattern look like": a single success from an unusual+ address after a run of failures is the finding, and filtering to+ failures hides exactly the event that matters.++ The filter is built here from a validated UPN and an integer window,+ never from caller-supplied text. ``$filter`` is OData rather than KQL,+ but it is still a query language and a principal name interpolated raw+ would be an injection point on a surface an agent can reach.+ """+ since = datetime.now(UTC) - timedelta(hours=max(1, min(hours, 720)))+ upn = _quote_odata_string(user_principal_name)+ async with httpx.AsyncClient(timeout=30.0) as client:+ await self._ensure_token(client)+ resp = await client.get(+ f"{_GRAPH}/auditLogs/signIns",+ headers=self._headers(),+ params={+ "$filter": (f"userPrincipalName eq '{upn}' and createdDateTime ge {since.strftime('%Y-%m-%dT%H:%M:%SZ')}"),+ "$top": min(limit, 100),+ "$orderby": "createdDateTime desc",+ },+ )+ resp.raise_for_status()+ raw = resp.json().get("value", []) or []+ return [self._project_sign_in(entry) for entry in raw if isinstance(entry, dict)]++ @staticmethod+ def _project_sign_in(entry: dict[str, Any]) -> dict[str, Any]:+ raw_status = entry.get("status")+ status: dict[str, Any] = raw_status if isinstance(raw_status, dict) else {}+ raw_location = entry.get("location")+ location: dict[str, Any] = raw_location if isinstance(raw_location, dict) else {}+ code = status.get("errorCode")+ return {+ "at": entry.get("createdDateTime"),+ "ip": entry.get("ipAddress"),+ "app": entry.get("appDisplayName"),+ "client": entry.get("clientAppUsed"),+ # errorCode 0 is Graph's "success". Rendered as a boolean so a+ # model is not invited to interpret a vendor error number, and+ # `None` stays None rather than becoming a confident False.+ "succeeded": (code == 0) if code is not None else None,+ "failure_reason": status.get("failureReason") if code else None,+ "conditional_access": entry.get("conditionalAccessStatus"),+ "risk_level": entry.get("riskLevelDuringSignIn"),+ "risk_state": entry.get("riskState"),+ "country": location.get("countryOrRegion"),+ "city": location.get("city"),+ }++ async def get_risky_user(self, user_principal_name: str) -> dict[str, Any] | None:+ """Entra ID Protection's own risk assessment for one principal.++ Gap-closure Phase 4.2. Read-only.++ ``None`` means Graph answered and holds no risk record for this+ principal, which is a real answer. It is **not** the same as a failed+ read, and the executor above keeps the two apart: a caller that cannot+ tell them apart will report an account as unremarkable because the+ lookup broke.++ ``/identityProtection/riskyUsers`` is a beta endpoint. Microsoft+ publishes it as such, so it is named here rather than being quietly+ pinned to v1.0, where it does not exist.+ """+ upn = _quote_odata_string(user_principal_name)+ async with httpx.AsyncClient(timeout=20.0) as client:+ await self._ensure_token(client)+ resp = await client.get(+ f"{_GRAPH_BETA}/identityProtection/riskyUsers",+ headers=self._headers(),+ params={"$filter": f"userPrincipalName eq '{upn}'", "$top": 1},+ )+ resp.raise_for_status()+ rows = resp.json().get("value", []) or []+ if not rows or not isinstance(rows[0], dict):+ return None+ row = rows[0]+ return {+ "risk_level": row.get("riskLevel"),+ "risk_state": row.get("riskState"),+ "risk_detail": row.get("riskDetail"),+ "last_updated": row.get("riskLastUpdatedDateTime"),+ "is_deleted": row.get("isDeleted"),+ }+async def disable_user(self, user_id: str) -> dict[str, Any]:async with httpx.AsyncClient(timeout=20.0) as client:await self._ensure_token(client)diff --git a/services/actions/app/clients/defender_client.py b/services/actions/app/clients/defender_client.pyindex 4eed0d62c..b8f101254 100644--- a/services/actions/app/clients/defender_client.py+++ b/services/actions/app/clients/defender_client.py@@ -13,6 +13,7 @@ from __future__ import annotationsfrom datetime import datetimefrom typing import Any+from urllib.parse import quoteimport httpximport structlog@@ -24,6 +25,58 @@ _MDE_SCOPE = "https://api.securitycenter.microsoft.com/.default"_MDE_BASE = "https://api.securitycenter.microsoft.com/api"+def _kql_escape(value: str) -> str:+ """Escape a value for a double-quoted KQL string literal.++ KQL escapes backslash and double quote inside a quoted string, and that+ is the whole grammar. Control characters are dropped rather than escaped:+ a newline in an indicator is not an indicator, and preserving it buys+ nothing while giving a crafted value somewhere to hide.++ The value is also length-capped. A multi-kilobyte "indicator" is not one,+ and an unbounded literal is a cheap way to make a query the service+ refuses, which reads to a caller as the telemetry being unavailable.+ """+ cleaned = "".join(ch for ch in str(value)[:512] if ch.isprintable())+ return cleaned.replace("\\", "\\\\").replace('"', '\\"')+++#: The only advanced-hunting queries this client will run.+#:+#: A closed set, because the caller is reachable from an investigation agent+#: and the plan forbids a model composing query text against a customer's+#: estate. Each template reads `target` and `window`, which `hunt_indicator`+#: binds as KQL `let` statements, and compares by equality only, so a value+#: has no way to become an operator. Adding a template is a reviewable change+#: to this dict rather than a string built at call time.+_HUNT_TEMPLATES: dict[str, str] = {+ "file_hash_sightings": (+ "DeviceFileEvents\n"+ "| where Timestamp > ago(window)\n"+ "| where SHA256 =~ target or SHA1 =~ target or MD5 =~ target\n"+ "| project Timestamp, DeviceName, FileName, FolderPath, InitiatingProcessAccountName, ActionType"+ ),+ "process_sightings": (+ "DeviceProcessEvents\n"+ "| where Timestamp > ago(window)\n"+ "| where FileName =~ target or SHA256 =~ target\n"+ "| project Timestamp, DeviceName, FileName, AccountName, InitiatingProcessFileName, ProcessCommandLine"+ ),+ "network_sightings": (+ "DeviceNetworkEvents\n"+ "| where Timestamp > ago(window)\n"+ "| where RemoteIP =~ target or RemoteUrl =~ target\n"+ "| project Timestamp, DeviceName, RemoteIP, RemoteUrl, RemotePort, InitiatingProcessFileName, ActionType"+ ),+ "logon_sightings": (+ "DeviceLogonEvents\n"+ "| where Timestamp > ago(window)\n"+ "| where AccountName =~ target or AccountUpn =~ target\n"+ "| project Timestamp, DeviceName, AccountName, AccountDomain, LogonType, RemoteIP, ActionType"+ ),+}++class DefenderClient:"""Async client for Microsoft Defender for Endpoint management actions."""@@ -100,6 +153,98 @@ class DefenderClient:logger.info("defender.resolved_alerts", count=len(results))return results[:limit]+ async def list_alerts_for_host(self, hostname: str, *, limit: int = 20) -> list[dict[str, Any]]:+ """Recent Defender alerts on one machine, whatever their status.++ Gap-closure Phase 4.2. Read-only.++ Resolved alerts are included on purpose. "This host raised the same+ alert three times last month and an analyst closed each as benign" is+ one of the few pieces of evidence that reliably settles a repeat+ finding, and a filter on open alerts throws it away.+ """+ machine = await self.find_machine(hostname)+ if machine is None:+ return []+ machine_id = str(machine.get("id") or "")+ if not machine_id:+ return []+ async with httpx.AsyncClient(timeout=30.0) as client:+ await self._ensure_token(client)+ resp = await client.get(+ f"{_MDE_BASE}/machines/{quote(machine_id, safe='')}/alerts",+ headers=self._headers(),+ params={"$top": min(limit, 100), "$orderby": "alertCreationTime desc"},+ )+ resp.raise_for_status()+ raw = resp.json().get("value", []) or []+ return [self._project_alert(entry) for entry in raw if isinstance(entry, dict)]++ @staticmethod+ def _project_alert(entry: dict[str, Any]) -> dict[str, Any]:+ return {+ "alert_id": entry.get("id"),+ "title": entry.get("title"),+ "severity": entry.get("severity"),+ "category": entry.get("category"),+ "status": entry.get("status"),+ "classification": entry.get("classification"),+ "determination": entry.get("determination"),+ "detection_source": entry.get("detectionSource"),+ "threat_family": entry.get("threatFamilyName"),+ "created_at": entry.get("alertCreationTime"),+ "resolved_at": entry.get("resolvedTime"),+ }++ async def hunt_indicator(+ self,+ template: str,+ indicator: str,+ *,+ hours: int = 24,+ limit: int = 50,+ ) -> list[dict[str, Any]]:+ """Run one of a fixed set of advanced-hunting queries for an indicator.++ Gap-closure Phase 4.2, and the constraint is the whole design.++ Defender's advanced hunting takes KQL. The plan is explicit that a+ model must never compose query text against a customer's estate, and+ that is a security boundary rather than a style preference: the+ indicator reaching this method was lifted out of a process command+ line or a file name, which is attacker-influenced, so a model relaying+ it into a query is one injected instruction away from an arbitrary+ query over the tenant's telemetry.++ So the KQL lives **here**, as a closed set of named templates, and the+ caller supplies a template name, one indicator and a window. An+ unknown template name is a ``ValueError``, not a fallback: falling+ back to a default query would answer a question nobody asked and the+ answer would look like evidence.++ The indicator is bound through a KQL ``let`` statement with a quoted+ string literal, and the quoting escapes backslash and double quote,+ which is the whole of KQL's string escape grammar. The templates+ compare against it by equality only, so there is no place for a+ value to become an operator.+ """+ query = _HUNT_TEMPLATES.get(template)+ if query is None:+ raise ValueError(f"unknown hunting template {template!r}; known templates are {', '.join(sorted(_HUNT_TEMPLATES))}")+ window = max(1, min(hours, 720))+ kql = f'let target = "{_kql_escape(indicator)}";\nlet window = {window}h;\n{query}\n| limit {min(limit, 200)}'+ async with httpx.AsyncClient(timeout=60.0) as client:+ await self._ensure_token(client)+ resp = await client.post(+ f"{_MDE_BASE}/advancedqueries/run",+ headers=self._headers(),+ json={"Query": kql},+ )+ resp.raise_for_status()+ body = resp.json() if resp.content else {}+ rows = body.get("Results") or []+ return [row for row in rows if isinstance(row, dict)]+async def find_machine(self, hostname: str) -> dict[str, Any] | None:"""Look up a machine by hostname in Defender for Endpoint."""async with httpx.AsyncClient(timeout=20.0) as client:diff --git a/services/actions/app/clients/factories.py b/services/actions/app/clients/factories.pyindex 9c799dc22..094a0f205 100644--- a/services/actions/app/clients/factories.py+++ b/services/actions/app/clients/factories.py@@ -21,6 +21,7 @@ does not move anyone's patch target.from __future__ import annotations+from app.clients.aws_cloudtrail_client import AWSCloudTrailClientfrom app.clients.aws_security_groups import AWSSecurityGroupsClientfrom app.clients.azure_entra_client import AzureEntraClientfrom app.clients.cloudflare_client import CloudflareClient@@ -49,6 +50,27 @@ def _aws_client(params: dict) -> AWSSecurityGroupsClient | None:)+def _cloudtrail_client(params: dict) -> AWSCloudTrailClient | None:+ """Build a CloudTrail read client from request-scoped credentials.++ Separate from ``_aws_client`` on purpose. That factory returns ``None``+ unless ``aws_security_group_id`` is present, which is correct for a+ firewall action and wrong for an audit read: a tenant with AWS keys and no+ security group would have had a CloudTrail verb answer "credentials not+ configured" while holding perfectly good credentials.+ """+ access_key = params.get("aws_access_key_id")+ secret_key = params.get("aws_secret_access_key")+ if not (access_key and secret_key):+ return None+ return AWSCloudTrailClient(+ access_key_id=str(access_key),+ secret_access_key=str(secret_key),+ region=str(params.get("aws_region") or "us-east-1"),+ session_token=params.get("aws_session_token"),+ )++def _cloudflare_client(params: dict) -> CloudflareClient | None:token = params.get("cf_api_token")if not token:@@ -171,6 +193,7 @@ def _s1_client(params: dict) -> SentinelOneClient | None:__all__ = ["_aws_client","_cloudflare_client",+ "_cloudtrail_client","_cortex_client","_cs_client","_entra_client",diff --git a/services/actions/app/clients/google_workspace_client.py b/services/actions/app/clients/google_workspace_client.pyindex 036cd0a4c..2aa5c1e25 100644--- a/services/actions/app/clients/google_workspace_client.py+++ b/services/actions/app/clients/google_workspace_client.py@@ -49,7 +49,9 @@ import jsonimport secretsimport stringimport time+from datetime import UTC, datetime, timedeltafrom typing import Any+from urllib.parse import quoteimport httpximport structlog@@ -58,10 +60,18 @@ logger = structlog.get_logger()_TOKEN_URI = "https://oauth2.googleapis.com/token"_DIRECTORY = "https://admin.googleapis.com/admin/directory/v1"+_REPORTS = "https://admin.googleapis.com/admin/reports/v1"_SCOPES = " ".join(["https://www.googleapis.com/auth/admin.directory.user","https://www.googleapis.com/auth/admin.directory.user.security",+ # Gap-closure Phase 4.2. Required by `list_login_events`, and listed+ # here rather than on a second client so one credential covers both+ # directions. A deployment whose service account has not had this+ # scope granted domain-wide gets a 403 on the login read and an+ # unchanged containment path, which is the safe asymmetry: the read+ # names the missing scope instead of reporting no logins.+ "https://www.googleapis.com/auth/admin.reports.audit.readonly",])@@ -157,6 +167,65 @@ class GoogleWorkspaceClient:def _headers(self) -> dict[str, str]:return {"Authorization": f"Bearer {self._token}", "Content-Type": "application/json"}+ async def list_login_events(+ self,+ user_email: str,+ *,+ hours: int = 24,+ limit: int = 50,+ ) -> list[dict[str, Any]]:+ """Recent login audit activity for one account.++ Gap-closure Phase 4.2. Read-only: a GET over the Reports API's+ ``login`` application activity feed.++ The Reports API takes the user key in the path and the window as+ RFC 3339 query parameters, so there is no query language to escape+ here. The address is still percent-encoded, because it arrives from+ alert text and a path segment carrying ``../`` would otherwise steer+ the request at a different Reports endpoint.++ Note the scope this needs. The two scopes this client already requests+ are directory scopes and do not cover reports; a deployment that has+ not granted ``admin.reports.audit.readonly`` to the service account+ gets a 403 here, which surfaces as a read failure naming the scope+ rather than as an account with no logins.+ """+ since = datetime.now(UTC) - timedelta(hours=max(1, min(hours, 720)))+ user_key = quote(str(user_email), safe="@")+ async with httpx.AsyncClient(timeout=30.0) as client:+ await self._ensure_token(client)+ resp = await client.get(+ f"{_REPORTS}/activities/users/{user_key}/applications/login",+ headers=self._headers(),+ params={"startTime": since.strftime("%Y-%m-%dT%H:%M:%SZ"), "maxResults": min(limit, 100)},+ )+ resp.raise_for_status()+ raw = resp.json().get("items", []) or []+ return [self._project_login(entry) for entry in raw if isinstance(entry, dict)]++ @staticmethod+ def _project_login(entry: dict[str, Any]) -> dict[str, Any]:+ raw_events = entry.get("events")+ events: list[Any] = raw_events if isinstance(raw_events, list) else []+ first: dict[str, Any] = events[0] if events and isinstance(events[0], dict) else {}+ params = {+ p.get("name"): (p.get("value") if p.get("value") is not None else p.get("boolValue"))+ for p in (first.get("parameters") or [])+ if isinstance(p, dict) and p.get("name")+ }+ raw_identity = entry.get("id")+ identity: dict[str, Any] = raw_identity if isinstance(raw_identity, dict) else {}+ return {+ "at": identity.get("time"),+ "event": first.get("name"),+ "ip": entry.get("ipAddress"),+ "login_type": params.get("login_type"),+ "challenge_method": params.get("login_challenge_method"),+ "is_suspicious": params.get("is_suspicious"),+ "failure_type": params.get("login_failure_type"),+ }+async def suspend_user(self, user_email: str) -> dict[str, Any]:async with httpx.AsyncClient(timeout=20.0) as client:await self._ensure_token(client)diff --git a/services/actions/app/clients/sentinelone_client.py b/services/actions/app/clients/sentinelone_client.pyindex 8e910b6e5..38726c6f3 100644--- a/services/actions/app/clients/sentinelone_client.py+++ b/services/actions/app/clients/sentinelone_client.py@@ -107,6 +107,49 @@ class SentinelOneClient:agents = resp.json().get("data", [])return agents[0] if agents else None+ async def list_threats(self, hostname: str, *, limit: int = 20) -> list[dict[str, Any]]:+ """Recent threats SentinelOne has recorded for a host.++ Gap-closure Phase 4.2. Read-only: the endpoint is a GET over+ ``/threats`` filtered by ``computerName``, and nothing here mitigates,+ dismisses or annotates a threat.++ The projection is deliberate and the list is short. A SentinelOne+ threat record nests ``threatInfo``, ``agentRealtimeInfo``,+ ``agentDetectionInfo``, ``mitigationStatus`` and more, which is a few+ kilobytes of JSON per threat for about eight fields of signal. An+ investigation wants to know what the EDR already concluded, not to+ re-derive it from the vendor's schema, and the rest is unbounded token+ cost on the hot path of every escalated alert.+ """+ async with httpx.AsyncClient(timeout=30.0) as client:+ resp = await client.get(+ f"{self._base_url}/threats",+ headers=self._headers(),+ params={"computerName": hostname, "limit": min(limit, 100), "sortBy": "createdAt", "sortOrder": "desc"},+ )+ resp.raise_for_status()+ raw = resp.json().get("data", []) or []+ return [self._project_threat(entry) for entry in raw if isinstance(entry, dict)]++ @staticmethod+ def _project_threat(entry: dict[str, Any]) -> dict[str, Any]:+ raw_info = entry.get("threatInfo")+ info: dict[str, Any] = raw_info if isinstance(raw_info, dict) else {}+ return {+ "threat_id": entry.get("id"),+ "name": info.get("threatName"),+ "classification": info.get("classification"),+ "confidence": info.get("confidenceLevel"),+ "verdict": info.get("analystVerdict"),+ "mitigation_status": info.get("mitigationStatus"),+ "sha256": info.get("sha256"),+ "file_path": info.get("filePath"),+ "process_user": info.get("processUser"),+ "detected_at": info.get("createdAt") or entry.get("createdAt"),+ "storyline": info.get("storyline"),+ }+async def _resolve_agent_uuid(self, client: httpx.AsyncClient, hostname: str) -> str:resp = await client.get(f"{self._base_url}/agents",diff --git a/services/actions/app/live_actions/builtins.py b/services/actions/app/live_actions/builtins.pyindex 529b79a7e..b3c162195 100644--- a/services/actions/app/live_actions/builtins.py+++ b/services/actions/app/live_actions/builtins.py@@ -81,12 +81,19 @@ from . import registryfrom .capability_contracts import apply_contractfrom .executor import LiveActionExecutorfrom .investigation_reads import (+ AWSLookupCloudAudit,CrowdStrikeGetDetections,CrowdStrikeGetHost,CrowdStrikeUnisolateHost,+ DefenderGetDetections,DefenderGetHost,+ DefenderLookupEndpointTelemetry,DefenderUnisolateHost,+ EntraGetUserActivity,+ GoogleWorkspaceGetUserActivity,OktaGetUserActivity,+ SentinelOneGetDetections,+ SentinelOneGetHost,)from .models import LiveActionRequest, LiveActionResult, LiveActionStatusfrom .vendor_breadth import VENDOR_BREADTH_EXECUTORS@@ -938,6 +945,18 @@ _BUILTIN_ADAPTERS: tuple[type[LiveActionExecutor], ...] = (CrowdStrikeGetDetections,DefenderGetHost,OktaGetUserActivity,+ # Gap-closure Phase 4.2. Three read verbs with one vendor arm each is a+ # CrowdStrike-and-Okta surface, not a vendor-read surface: a tenant on+ # SentinelOne and Entra ID had the same investigation reach as a tenant+ # with no EDR at all, because dispatch answered executor_not_found, which+ # reads as a broken deployment rather than as a capability nobody wrote.+ SentinelOneGetHost,+ SentinelOneGetDetections,+ DefenderGetDetections,+ EntraGetUserActivity,+ GoogleWorkspaceGetUserActivity,+ AWSLookupCloudAudit,+ DefenderLookupEndpointTelemetry,# Rollback for the most disruptive action, which had no executor.CrowdStrikeUnisolateHost,DefenderUnisolateHost,diff --git a/services/actions/app/live_actions/capabilities.py b/services/actions/app/live_actions/capabilities.pyindex 54326307c..55441b372 100644--- a/services/actions/app/live_actions/capabilities.py+++ b/services/actions/app/live_actions/capabilities.py@@ -84,6 +84,11 @@ KNOWN_CAPABILITIES: frozenset[str] = frozenset("get_detections","get_user_activity","search_siem",+ # Gap-closure Phase 4.2: a cloud control-plane audit lookup and an+ # indicator search over endpoint telemetry. Neither subject is a host+ # or a principal, so neither fits the three verbs above.+ "lookup_cloud_audit",+ "lookup_endpoint_telemetry","suspend_session","sync_detection_rule",# The return leg of a two-way SIEM integration: AiSOC's verdictdiff --git a/services/actions/app/live_actions/capability_contracts.py b/services/actions/app/live_actions/capability_contracts.pyindex 23357a936..37956ce2d 100644--- a/services/actions/app/live_actions/capability_contracts.py+++ b/services/actions/app/live_actions/capability_contracts.py@@ -88,6 +88,40 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {required_permission=_INVESTIGATE,note="Recent authentication events for a principal, from the IdP.",),+ "lookup_cloud_audit": CapabilityContract(+ impact=ActionImpact.READ_ONLY,+ approval=ApprovalRequirement.AUTOMATIC,+ reversal=Reversal.NOT_APPLICABLE,+ required_permission=_INVESTIGATE,+ has_verification_probe=False,+ verification_gap=(+ "A read leaves nothing behind to read back, so there is no write "+ "for a probe to confirm. Recorded rather than left blank so this "+ "reads as the answer it is and not as an omission."+ ),+ note=(+ "Cloud control-plane audit events for one principal, resource or "+ "API call. The window and the attribute are typed arguments; the "+ "caller never supplies query text."+ ),+ ),+ "lookup_endpoint_telemetry": CapabilityContract(+ impact=ActionImpact.READ_ONLY,+ approval=ApprovalRequirement.AUTOMATIC,+ reversal=Reversal.NOT_APPLICABLE,+ required_permission=_INVESTIGATE,+ has_verification_probe=False,+ verification_gap=("A read leaves nothing behind to read back. Same reasoning as lookup_cloud_audit and search_siem."),+ note=(+ "Sightings of one indicator in endpoint telemetry, through the "+ "EDR's own hunting index. The query is one of a closed set of "+ "templates the executor owns; a caller supplies a template name, "+ "an indicator and a window, never a query string. That is a "+ "security boundary rather than a convenience: this verb is "+ "reachable from an investigation agent, and the indicator it "+ "passes was lifted out of attacker-influenced alert text."+ ),+ ),"search_siem": CapabilityContract(impact=ActionImpact.READ_ONLY,approval=ApprovalRequirement.AUTOMATIC,diff --git a/services/actions/app/live_actions/investigation_reads.py b/services/actions/app/live_actions/investigation_reads.pyindex f3b23aba9..01898e594 100644--- a/services/actions/app/live_actions/investigation_reads.py+++ b/services/actions/app/live_actions/investigation_reads.py@@ -29,7 +29,17 @@ from typing import Anyimport structlog-from app.clients.factories import _cs_client, _mde_client, _okta_client+from app.clients.aws_cloudtrail_client import CloudTrailLookupError+from app.clients.defender_client import _HUNT_TEMPLATES+from app.clients.factories import (+ _cloudtrail_client,+ _cs_client,+ _entra_client,+ _gws_client,+ _mde_client,+ _okta_client,+ _s1_client,+)from app.live_actions.capability_contracts import apply_contractfrom app.live_actions.executor import LiveActionExecutorfrom app.live_actions.models import LiveActionRequest, LiveActionResult, LiveActionStatus@@ -315,6 +325,426 @@ class OktaGetUserActivity(LiveActionExecutor):)+# ─── Phase 4.2: the vendors an investigation could not reach ─────────────────+#+# Three verbs with one vendor arm each is not a vendor-read surface, it is a+# CrowdStrike-and-Okta surface. A tenant on SentinelOne and Entra ID had the+# same investigation reach as a tenant with no EDR at all, because the verb+# existed and nothing implemented it for them: dispatch answered+# `executor_not_found`, which reads as a broken deployment rather than as a+# capability nobody wrote.+#+# Five of the seven executors below are new *vendor arms on existing verbs*,+# which is the whole point of declaring a contract per capability rather than+# per vendor: they inherit `get_host` / `get_detections` / `get_user_activity`+# classifications automatically and cannot drift low. Only the two verbs whose+# subject is neither a host nor a principal needed a new contract.+++@apply_contract+class SentinelOneGetHost(LiveActionExecutor):+ vendor_id = "sentinelone"+ capability = "get_host"+ description = "Read an agent record from SentinelOne."+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ params: dict[str, Any] = request.params or {}+ target = str(request.target or params.get("hostname") or "")+ if request.dry_run:+ return _preview(self, request, target, "SentinelOne")++ client = _s1_client(params)+ if client is None:+ return _missing_credentials(self, request, "SentinelOne")++ try:+ agent = await client.find_agent(target)+ if agent is None:+ return _result(+ self,+ request,+ LiveActionStatus.SUCCEEDED,+ f"no SentinelOne agent matches {target}",+ details={"found": False, "hostname": target},+ )+ return _result(+ self,+ request,+ LiveActionStatus.SUCCEEDED,+ (+ f"{target}: {agent.get('osName') or 'unknown platform'}, "+ f"network {'disconnected' if agent.get('networkStatus') == 'disconnected' else agent.get('networkStatus') or 'unknown'}"+ ),+ details={+ "found": True,+ "agent_uuid": agent.get("uuid"),+ "hostname": agent.get("computerName"),+ "platform": agent.get("osName"),+ "os_version": agent.get("osRevision"),+ "agent_version": agent.get("agentVersion"),+ "local_ip": agent.get("lastIpToMgmt"),+ "external_ip": agent.get("externalIp"),+ "last_seen": agent.get("lastActiveDate"),+ "network_status": agent.get("networkStatus"),+ "infected": agent.get("infected"),+ "active_threats": agent.get("activeThreats"),+ "is_up_to_date": agent.get("isUpToDate"),+ },+ )+ except Exception as exc: # noqa: BLE001 - a vendor error is FAILED, never empty+ logger.warning("get_host.failed", vendor="sentinelone", error=str(exc))+ return _result(+ self,+ request,+ LiveActionStatus.FAILED,+ "SentinelOne read failed",+ error=f"SentinelOne read failed: {exc}",+ )+++@apply_contract+class SentinelOneGetDetections(LiveActionExecutor):+ vendor_id = "sentinelone"+ capability = "get_detections"+ description = "Read recent SentinelOne threats for a host."+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ params: dict[str, Any] = request.params or {}+ target = str(request.target or params.get("hostname") or "")+ if request.dry_run:+ return _preview(self, request, target, "SentinelOne")++ client = _s1_client(params)+ if client is None:+ return _missing_credentials(self, request, "SentinelOne")++ try:+ threats = await client.list_threats(target, limit=int(params.get("limit", 20)))+ return _result(+ self,+ request,+ LiveActionStatus.SUCCEEDED,+ f"{len(threats)} recent threat(s) on {target}",+ details={"found": True, "hostname": target, "count": len(threats), "detections": threats},+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("get_detections.failed", vendor="sentinelone", error=str(exc))+ return _result(+ self,+ request,+ LiveActionStatus.FAILED,+ "SentinelOne read failed",+ error=f"SentinelOne read failed: {exc}",+ )+++@apply_contract+class DefenderGetDetections(LiveActionExecutor):+ vendor_id = "defender"+ capability = "get_detections"+ description = "Read recent Microsoft Defender alerts for a host."+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ params: dict[str, Any] = request.params or {}+ target = str(request.target or params.get("hostname") or "")+ if request.dry_run:+ return _preview(self, request, target, "Defender")++ client = _mde_client(params)+ if client is None:+ return _missing_credentials(self, request, "Defender")++ try:+ # `list_alerts_for_host` resolves the machine first and returns an+ # empty list when there is none. That is indistinguishable from a+ # machine with no alerts, and the two are different answers, so the+ # resolution is done here where it can be reported.+ machine = await client.find_machine(target)+ if machine is None:+ return _result(+ self,+ request,+ LiveActionStatus.SUCCEEDED,+ f"no Defender machine matches {target}",+ details={"found": False, "hostname": target, "detections": []},+ )+ alerts = await client.list_alerts_for_host(target, limit=int(params.get("limit", 20)))+ return _result(+ self,+ request,+ LiveActionStatus.SUCCEEDED,+ f"{len(alerts)} recent Defender alert(s) on {target}",+ details={"found": True, "hostname": target, "count": len(alerts), "detections": alerts},+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("get_detections.failed", vendor="defender", error=str(exc))+ return _result(+ self,+ request,+ LiveActionStatus.FAILED,+ "Defender read failed",+ error=f"Defender read failed: {exc}",+ )+++@apply_contract+class EntraGetUserActivity(LiveActionExecutor):+ vendor_id = "entra"+ capability = "get_user_activity"+ description = "Read recent sign-ins and the risk assessment for an Entra ID principal."+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ params: dict[str, Any] = request.params or {}+ target = str(request.target or params.get("user_principal_name") or params.get("user_name") or "")+ if request.dry_run:+ return _preview(self, request, target, "Entra ID")++ client = _entra_client(params)+ if client is None:+ return _missing_credentials(self, request, "Entra ID")++ try:+ sign_ins = await client.list_sign_ins(+ target,+ hours=int(params.get("hours", 24)),+ limit=int(params.get("limit", 50)),+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("get_user_activity.failed", vendor="entra", error=str(exc))+ return _result(+ self,+ request,+ LiveActionStatus.FAILED,+ "Entra ID read failed",+ error=f"Entra ID sign-in read failed: {exc}",+ )++ # The risk record is a second call against a beta endpoint, and it is+ # allowed to fail without taking the sign-ins with it. Its absence is+ # reported as unknown rather than as "not at risk", because ID+ # Protection is a licensed feature and a tenant without it would+ # otherwise read as a tenant with a clean principal.+ risk: dict[str, Any] | None = None+ risk_error: str | None = None+ try:+ risk = await client.get_risky_user(target)+ except Exception as exc: # noqa: BLE001+ risk_error = f"{type(exc).__name__}: {exc}"+ logger.warning("get_user_activity.risk_unavailable", vendor="entra", error=risk_error)++ distinct_ips = sorted({str(row.get("ip")) for row in sign_ins if row.get("ip")})+ failures = sum(1 for row in sign_ins if row.get("succeeded") is False)+ details: dict[str, Any] = {+ "found": True,+ "user": target,+ "count": len(sign_ins),+ "sign_ins": sign_ins,+ "distinct_source_ips": distinct_ips,+ "failed_sign_ins": failures,+ }+ if risk is not None:+ details["risk"] = risk+ else:+ details["risk"] = None+ details["risk_unavailable_reason"] = risk_error or (+ "Entra ID Protection holds no risk record for this principal, which may mean "+ "no risk was detected or that the tenant is not licensed for it. Treat as "+ "unknown rather than clear."+ )+ return _result(+ self,+ request,+ LiveActionStatus.SUCCEEDED,+ (f"{len(sign_ins)} sign-in(s) for {target} from {len(distinct_ips)} distinct address(es), {failures} failed"),+ details=details,+ )+++@apply_contract+class GoogleWorkspaceGetUserActivity(LiveActionExecutor):+ vendor_id = "google_workspace"+ capability = "get_user_activity"+ description = "Read recent Google Workspace login audit events for an account."+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ params: dict[str, Any] = request.params or {}+ target = str(request.target or params.get("user_email") or params.get("user_name") or "")+ if request.dry_run:+ return _preview(self, request, target, "Google Workspace")++ client = _gws_client(params)+ if client is None:+ return _missing_credentials(self, request, "Google Workspace")++ try:+ events = await client.list_login_events(+ target,+ hours=int(params.get("hours", 24)),+ limit=int(params.get("limit", 50)),+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("get_user_activity.failed", vendor="google_workspace", error=str(exc))+ return _result(+ self,+ request,+ LiveActionStatus.FAILED,+ "Google Workspace read failed",+ error=(+ f"Google Workspace login audit read failed: {exc}. A 403 here usually means the "+ f"service account has not been granted admin.reports.audit.readonly domain-wide, "+ f"which is a configuration gap and not a statement about this account."+ ),+ )++ distinct_ips = sorted({str(row.get("ip")) for row in events if row.get("ip")})+ suspicious = sum(1 for row in events if row.get("is_suspicious") in (True, "true"))+ return _result(+ self,+ request,+ LiveActionStatus.SUCCEEDED,+ (f"{len(events)} login event(s) for {target} from {len(distinct_ips)} distinct address(es)"),+ details={+ "found": True,+ "user": target,+ "count": len(events),+ "logins": events,+ "distinct_source_ips": distinct_ips,+ "flagged_suspicious_by_google": suspicious,+ },+ )+++@apply_contract+class AWSLookupCloudAudit(LiveActionExecutor):+ vendor_id = "aws"+ capability = "lookup_cloud_audit"+ description = "Look up AWS CloudTrail management events for a principal, resource or API call."+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ params: dict[str, Any] = request.params or {}+ attribute_key = str(params.get("attribute_key") or "Username")+ target = str(request.target or params.get("attribute_value") or "")+ if request.dry_run:+ return _preview(self, request, f"{attribute_key}={target}", "AWS CloudTrail")++ client = _cloudtrail_client(params)+ if client is None:+ return _missing_credentials(self, request, "AWS CloudTrail")++ try:+ events = await client.lookup_events(+ attribute_key=attribute_key,+ attribute_value=target,+ hours=int(params.get("hours", 24)),+ limit=int(params.get("limit", 50)),+ )+ except CloudTrailLookupError as exc:+ # Deliberately FAILED, including for a refused attribute key. An+ # empty list here would be read as "this principal made no API+ # calls", which is a statement about the customer's account rather+ # than about our request.+ logger.warning("lookup_cloud_audit.failed", vendor="aws", error=str(exc))+ return _result(self, request, LiveActionStatus.FAILED, "CloudTrail lookup failed", error=str(exc))+ except Exception as exc: # noqa: BLE001+ logger.warning("lookup_cloud_audit.failed", vendor="aws", error=str(exc))+ return _result(+ self,+ request,+ LiveActionStatus.FAILED,+ "CloudTrail lookup failed",+ error=f"CloudTrail lookup failed: {exc}",+ )++ errors = sorted({str(row["error_code"]) for row in events if row.get("error_code")})+ return _result(+ self,+ request,+ LiveActionStatus.SUCCEEDED,+ f"{len(events)} CloudTrail event(s) for {attribute_key} {target}",+ details={+ "found": True,+ "attribute_key": attribute_key,+ "attribute_value": target,+ "count": len(events),+ "events": events,+ "api_error_codes": errors,+ },+ )+++@apply_contract+class DefenderLookupEndpointTelemetry(LiveActionExecutor):+ vendor_id = "defender"+ capability = "lookup_endpoint_telemetry"+ description = "Search Microsoft Defender endpoint telemetry for sightings of one indicator."+ requires_credentials = True++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ params: dict[str, Any] = request.params or {}+ template = str(params.get("template") or "")+ target = str(request.target or params.get("indicator") or "")+ if request.dry_run:+ return _preview(self, request, f"{template}:{target}", "Defender")++ # Checked before the credential, because an unknown template is a+ # caller error and reporting it as a credential problem would send an+ # operator to look at their Azure app registration.+ if template not in _HUNT_TEMPLATES:+ return _result(+ self,+ request,+ LiveActionStatus.FAILED,+ "unknown telemetry template",+ error=(+ f"{template!r} is not one of the telemetry templates this verb can run. "+ f"Known templates: {', '.join(sorted(_HUNT_TEMPLATES))}. Query text is not accepted."+ ),+ )++ client = _mde_client(params)+ if client is None:+ return _missing_credentials(self, request, "Defender")++ try:+ rows = await client.hunt_indicator(+ template,+ target,+ hours=int(params.get("hours", 24)),+ limit=int(params.get("limit", 50)),+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("lookup_endpoint_telemetry.failed", vendor="defender", error=str(exc))+ return _result(+ self,+ request,+ LiveActionStatus.FAILED,+ "Defender telemetry search failed",+ error=f"Defender telemetry search failed: {exc}",+ )++ hosts = sorted({str(row["DeviceName"]) for row in rows if row.get("DeviceName")})+ return _result(+ self,+ request,+ LiveActionStatus.SUCCEEDED,+ f"{len(rows)} sighting(s) of {target} across {len(hosts)} host(s)",+ details={+ "found": True,+ "template": template,+ "indicator": target,+ "count": len(rows),+ "distinct_hosts": hosts,+ "sightings": rows,+ },+ )++# ─── Rollback ────────────────────────────────────────────────────────────────## `unisolate_host` was declared as the reverse of `isolate_host` and had nodiff --git a/services/actions/tests/test_investigation_reads_phase4.py b/services/actions/tests/test_investigation_reads_phase4.pynew file mode 100644index 000000000..0956b9917--- /dev/null+++ b/services/actions/tests/test_investigation_reads_phase4.py@@ -0,0 +1,823 @@+"""Gap-closure Phase 4.2: the vendor reads an investigation could not make.++Every payload below is **synthetic**, shaped to the vendor's published+response schema, and no call in this file reaches a real vendor. That is+stated because a recorded-looking fixture that was in fact invented is the+kind of thing this repository publishes honestly or not at all.++Three properties are under test, and they are the three the plan turns on.++**A read failure is never an empty result.** Each executor has a test that+breaks its vendor and asserts the outcome is `FAILED` with an error that says+so, because an empty list reaching a model reads as evidence of absence and+gets reasoned on as if the host were clean. The distinction is asserted at+the executor boundary, which is where a caller sees it.++**Not-found and could-not-read are different answers.** A host that no longer+exists is `SUCCEEDED` with `found: False`; a vendor that 500s is `FAILED`.+Both tested for the same verb so the pair cannot collapse.++**Query text is built by the executor, never by its caller.** The Defender+telemetry verb takes a template name and refuses anything else, and the+Entra reads escape the principal name into the OData literal. Both are+asserted on the bytes that reach the wire rather than on the arguments,+because asserting on the arguments would be comparing the caller against+itself.+"""++from __future__ import annotations++import json+import uuid+from collections.abc import Mapping+from typing import Any++import httpx+import pytest+import respx+from app.clients import google_workspace_client as gws_module+from app.clients.aws_cloudtrail_client import AWSCloudTrailClient, CloudTrailLookupError, _signing_key+from app.clients.defender_client import _HUNT_TEMPLATES+from app.live_actions import dispatch, investigation_reads, register_builtin_executors+from app.live_actions.investigation_reads import (+ AWSLookupCloudAudit,+ DefenderGetDetections,+ DefenderLookupEndpointTelemetry,+ EntraGetUserActivity,+ GoogleWorkspaceGetUserActivity,+ SentinelOneGetDetections,+ SentinelOneGetHost,+)+from app.live_actions.models import LiveActionRequest, LiveActionStatus++S1_CONSOLE = "https://usea1-partners.sentinelone.net"+S1_API = f"{S1_CONSOLE}/web/api/v2.1"+GRAPH = "https://graph.microsoft.com/v1.0"+GRAPH_BETA = "https://graph.microsoft.com/beta"+MDE = "https://api.securitycenter.microsoft.com/api"+TOKEN_HOST = "https://login.microsoftonline.com"+GWS_REPORTS = "https://admin.googleapis.com/admin/reports/v1"++S1_CREDS = {"s1_console_url": S1_CONSOLE, "s1_api_token": "s1-token"}+MDE_CREDS = {"mde_tenant_id": "t", "mde_client_id": "c", "mde_client_secret": "s"}+ENTRA_CREDS = {"azure_tenant_id": "t", "azure_client_id": "c", "azure_client_secret": "s"}+AWS_CREDS = {"aws_access_key_id": "AKIAEXAMPLE", "aws_secret_access_key": "secret", "aws_region": "us-east-1"}++#: A Google service-account key has to parse and has to carry a usable RSA+#: private key, because the client signs a JWT during `_mint_token`. Rather+#: than ship a key, the tests that need a token stub `_ensure_token`, and this+#: shape exists only so the factory returns a client at all.+GWS_CREDS = {+ "gws_service_account_key": json.dumps({"client_email": "[email protected]", "private_key": "unused-in-these-tests"}),+ "gws_subject_email": "[email protected]",+}+++#: A fixed tenant so the dispatcher's per-tenant policy lookups are stable+#: across the file. `LiveActionRequest` types both of these as UUIDs.+TENANT = uuid.UUID("11111111-1111-1111-1111-111111111111")+++def _request(target: str, params: Mapping[str, Any]) -> LiveActionRequest:+ """Build a request. ``Mapping`` because ``dict`` is invariant in its value+ type, so a ``dict[str, str]`` credential bag is not a ``dict[str, object]``+ and every call site would need a cast."""+ return LiveActionRequest(+ request_id=uuid.uuid4(),+ capability="unused",+ vendor_id="unused",+ target=target,+ params=dict(params),+ dry_run=False,+ tenant_id=TENANT,+ )+++def _entra_token() -> None:+ respx.post(f"{TOKEN_HOST}/t/oauth2/v2.0/token").mock(return_value=httpx.Response(200, json={"access_token": "graph-token"}))+++def _mde_token() -> None:+ respx.post(f"{TOKEN_HOST}/t/oauth2/v2.0/token").mock(return_value=httpx.Response(200, json={"access_token": "mde-token"}))+++# --------------------------------------------------------------- SentinelOne+++async def test_sentinelone_get_host_projects_the_fields_that_matter() -> None:+ """A SentinelOne agent record is ~60 fields; twelve reach the caller."""+ respx.get(f"{S1_API}/agents").mock(+ return_value=httpx.Response(+ 200,+ json={+ "data": [+ {+ "uuid": "agent-uuid-1",+ "computerName": "WS-42",+ "osName": "Windows 11 Pro",+ "osRevision": "22631",+ "agentVersion": "23.4.2.350",+ "lastIpToMgmt": "10.1.2.3",+ "externalIp": "203.0.113.9",+ "lastActiveDate": "2026-09-26T10:00:00Z",+ "networkStatus": "connected",+ "infected": True,+ "activeThreats": 2,+ "isUpToDate": True,+ # Noise the projection must drop rather than forward.+ "licenseKey": "should-not-travel",+ "siteName": "Acme",+ "groupIp": "10.1.2.0",+ }+ ]+ },+ )+ )+ result = await SentinelOneGetHost().execute(_request("WS-42", S1_CREDS))++ assert result.status is LiveActionStatus.SUCCEEDED+ assert result.details["found"] is True+ assert result.details["agent_uuid"] == "agent-uuid-1"+ assert result.details["active_threats"] == 2+ # The projection is a bound on token cost and on what attacker-influenced+ # vendor text can carry into a prompt, so it is asserted as a closed set+ # rather than as "contains the fields I care about".+ assert "licenseKey" not in result.details+ assert "siteName" not in result.details+++async def test_sentinelone_get_host_distinguishes_absent_from_unreadable() -> None:+ """The pair that must never collapse, asserted in one test so it cannot."""+ respx.get(f"{S1_API}/agents").mock(return_value=httpx.Response(200, json={"data": []}))+ absent = await SentinelOneGetHost().execute(_request("GONE-01", S1_CREDS))++ assert absent.status is LiveActionStatus.SUCCEEDED+ assert absent.details["found"] is False++ respx.get(f"{S1_API}/agents").mock(return_value=httpx.Response(503, text="upstream unavailable"))+ broken = await SentinelOneGetHost().execute(_request("WS-42", S1_CREDS))++ assert broken.status is LiveActionStatus.FAILED+ assert "SentinelOne read failed" in (broken.error or "")+ # The load-bearing assertion: nothing in a failed read looks like a clean+ # host. `found` absent rather than False, and no empty record.+ assert "found" not in broken.details+++async def test_sentinelone_get_detections_reads_the_edr_verdict() -> None:+ respx.get(f"{S1_API}/threats").mock(+ return_value=httpx.Response(+ 200,+ json={+ "data": [+ {+ "id": "threat-1",+ "createdAt": "2026-09-26T09:00:00Z",+ "threatInfo": {+ "threatName": "Trojan.GenericKD",+ "classification": "Malware",+ "confidenceLevel": "malicious",+ "analystVerdict": "true_positive",+ "mitigationStatus": "mitigated",+ "sha256": "a" * 64,+ "filePath": "C:\\Users\\svc\\AppData\\evil.exe",+ "processUser": "ACME\\svc_deploy",+ "createdAt": "2026-09-26T09:00:00Z",+ "storyline": "A1B2C3",+ },+ }+ ]+ },+ )+ )+ result = await SentinelOneGetDetections().execute(_request("WS-42", S1_CREDS))++ assert result.status is LiveActionStatus.SUCCEEDED+ assert result.details["count"] == 1+ detection = result.details["detections"][0]+ assert detection["verdict"] == "true_positive"+ assert detection["classification"] == "Malware"+ assert detection["sha256"] == "a" * 64+++async def test_sentinelone_get_detections_failure_is_not_zero_detections() -> None:+ respx.get(f"{S1_API}/threats").mock(return_value=httpx.Response(500, text="boom"))+ result = await SentinelOneGetDetections().execute(_request("WS-42", S1_CREDS))++ assert result.status is LiveActionStatus.FAILED+ # A `count: 0` here would be read as "the EDR has nothing on this host",+ # which is the strongest possible exonerating evidence and would be false.+ assert "count" not in result.details+ assert "detections" not in result.details+++# ------------------------------------------------------------------ Defender+++async def test_defender_get_detections_includes_resolved_alerts() -> None:+ """Resolved alerts are the evidence that settles a repeat finding."""+ _mde_token()+ respx.get(f"{MDE}/machines").mock(return_value=httpx.Response(200, json={"value": [{"id": "machine-1", "computerDnsName": "WS-42"}]}))+ respx.get(f"{MDE}/machines/machine-1/alerts").mock(+ return_value=httpx.Response(+ 200,+ json={+ "value": [+ {+ "id": "alert-1",+ "title": "Suspicious PowerShell",+ "severity": "Medium",+ "category": "Execution",+ "status": "Resolved",+ "classification": "FalsePositive",+ "determination": "SecurityTesting",+ "detectionSource": "WindowsDefenderAtp",+ "alertCreationTime": "2026-09-01T08:00:00Z",+ "resolvedTime": "2026-09-01T09:00:00Z",+ },+ {+ "id": "alert-2",+ "title": "Suspicious PowerShell",+ "severity": "Medium",+ "status": "New",+ "alertCreationTime": "2026-09-26T08:00:00Z",+ },+ ]+ },+ )+ )+ result = await DefenderGetDetections().execute(_request("WS-42", MDE_CREDS))++ assert result.status is LiveActionStatus.SUCCEEDED+ assert result.details["count"] == 2+ statuses = {row["status"] for row in result.details["detections"]}+ assert statuses == {"Resolved", "New"}+ assert result.details["detections"][0]["classification"] == "FalsePositive"+++async def test_defender_get_detections_unresolvable_machine_is_not_a_clean_host() -> None:+ """A host Defender does not know is reported as not found, not as clean."""+ _mde_token()+ respx.get(f"{MDE}/machines").mock(return_value=httpx.Response(200, json={"value": []}))+ result = await DefenderGetDetections().execute(_request("UNKNOWN-01", MDE_CREDS))++ assert result.status is LiveActionStatus.SUCCEEDED+ assert result.details["found"] is False+ assert "no Defender machine matches" in result.summary+++async def test_defender_telemetry_refuses_anything_but_a_known_template() -> None:+ """The security boundary: no caller supplies query text.++ Refused before the credential is touched, so an operator is not sent to+ look at their Azure app registration for a caller's mistake.+ """+ route = respx.post(f"{MDE}/advancedqueries/run").mock(return_value=httpx.Response(200, json={"Results": []}))++ for attempt in (+ "DeviceProcessEvents | project *",+ "file_hash_sightings; DeviceInfo",+ "",+ "FILE_HASH_SIGHTINGS",+ ):+ result = await DefenderLookupEndpointTelemetry().execute(_request("a" * 64, {**MDE_CREDS, "template": attempt}))+ assert result.status is LiveActionStatus.FAILED, attempt+ assert "Query text is not accepted" in (result.error or ""), attempt++ assert not route.called, "a refused template must not reach the vendor"+++async def test_defender_telemetry_binds_the_indicator_and_never_interpolates_it() -> None:+ """Asserted on the KQL that reaches the wire, not on the argument."""+ _mde_token()+ captured: dict[str, str] = {}++ def run(request: httpx.Request) -> httpx.Response:+ captured["query"] = json.loads(request.content)["Query"]+ return httpx.Response(200, json={"Results": [{"DeviceName": "WS-42", "FileName": "evil.exe"}]})++ respx.post(f"{MDE}/advancedqueries/run").mock(side_effect=run)++ # A value carrying KQL syntax and a quote. If it were interpolated into+ # the query body rather than bound as a literal, the `|` would start a+ # new pipeline stage.+ hostile = 'abc" | project *; DeviceInfo //'+ result = await DefenderLookupEndpointTelemetry().execute(+ _request(hostile, {**MDE_CREDS, "template": "file_hash_sightings", "hours": 48})+ )++ assert result.status is LiveActionStatus.SUCCEEDED+ query = captured["query"]+ # The escaped form is present and the raw form is not, so the value+ # cannot have closed the literal.+ assert 'let target = "abc\\" | project *; DeviceInfo //";' in query+ assert "let window = 48h;" in query+ # The template body is the shipped constant, character for character.+ assert _HUNT_TEMPLATES["file_hash_sightings"] in query+ assert result.details["distinct_hosts"] == ["WS-42"]+++async def test_defender_telemetry_caps_the_window_and_the_row_count() -> None:+ _mde_token()+ captured: dict[str, str] = {}++ def run(request: httpx.Request) -> httpx.Response:+ captured["query"] = json.loads(request.content)["Query"]+ return httpx.Response(200, json={"Results": []})++ respx.post(f"{MDE}/advancedqueries/run").mock(side_effect=run)+ await DefenderLookupEndpointTelemetry().execute(+ _request("a" * 64, {**MDE_CREDS, "template": "network_sightings", "hours": 99_999, "limit": 10_000})+ )++ # 720h and 200 rows are the caps. A caller asking for a year of telemetry+ # at ten thousand rows is asking for a different job than a pivot, and an+ # uncapped request is a cheap way to stall a tool loop.+ assert "let window = 720h;" in captured["query"]+ assert "| limit 200" in captured["query"]+++# --------------------------------------------------------------- Entra ID+++async def test_entra_get_user_activity_returns_successes_and_failures() -> None:+ """Both outcomes, because the pattern is the finding."""+ _entra_token()+ respx.get(f"{GRAPH}/auditLogs/signIns").mock(+ return_value=httpx.Response(+ 200,+ json={+ "value": [+ {+ "createdDateTime": "2026-09-26T10:00:00Z",+ "ipAddress": "203.0.113.9",+ "appDisplayName": "Office 365 Exchange Online",+ "clientAppUsed": "Browser",+ "status": {"errorCode": 0},+ "conditionalAccessStatus": "success",+ "riskLevelDuringSignIn": "high",+ "riskState": "atRisk",+ "location": {"countryOrRegion": "NL", "city": "Amsterdam"},+ },+ {+ "createdDateTime": "2026-09-26T09:58:00Z",+ "ipAddress": "203.0.113.9",+ "status": {"errorCode": 50126, "failureReason": "Invalid username or password."},+ "location": {"countryOrRegion": "NL"},+ },+ ]+ },+ )+ )+ respx.get(f"{GRAPH_BETA}/identityProtection/riskyUsers").mock(+ return_value=httpx.Response(+ 200,+ json={+ "value": [+ {+ "riskLevel": "high",+ "riskState": "atRisk",+ "riskDetail": "none",+ "riskLastUpdatedDateTime": "2026-09-26T10:01:00Z",+ }+ ]+ },+ )+ )+ result = await EntraGetUserActivity().execute(_request("[email protected]", ENTRA_CREDS))++ assert result.status is LiveActionStatus.SUCCEEDED+ assert result.details["count"] == 2+ assert result.details["failed_sign_ins"] == 1+ assert result.details["distinct_source_ips"] == ["203.0.113.9"]+ assert result.details["risk"]["risk_level"] == "high"+ # errorCode 0 is Graph's success. Rendered as a boolean so a model is not+ # asked to interpret a vendor error number.+ assert result.details["sign_ins"][0]["succeeded"] is True+ assert result.details["sign_ins"][1]["succeeded"] is False+++async def test_entra_missing_risk_record_reads_as_unknown_not_as_clear() -> None:+ """ID Protection is licensed. Its absence must not exonerate an account."""+ _entra_token()+ respx.get(f"{GRAPH}/auditLogs/signIns").mock(return_value=httpx.Response(200, json={"value": []}))+ respx.get(f"{GRAPH_BETA}/identityProtection/riskyUsers").mock(return_value=httpx.Response(403, json={"error": {"code": "Forbidden"}}))++ result = await EntraGetUserActivity().execute(_request("[email protected]", ENTRA_CREDS))++ # The sign-in read succeeded, so the verb succeeds. The risk leg failing+ # must not take it down, and must not read as "no risk".+ assert result.status is LiveActionStatus.SUCCEEDED+ assert result.details["risk"] is None+ reason = result.details["risk_unavailable_reason"]+ assert reason+ assert "unknown" in reason.lower() or "HTTPStatusError" in reason+++async def test_entra_sign_in_read_failure_is_failed_not_empty() -> None:+ _entra_token()+ respx.get(f"{GRAPH}/auditLogs/signIns").mock(return_value=httpx.Response(500, text="boom"))+ result = await EntraGetUserActivity().execute(_request("[email protected]", ENTRA_CREDS))++ assert result.status is LiveActionStatus.FAILED+ assert "count" not in result.details+ assert "sign_ins" not in result.details+++async def test_entra_escapes_the_principal_into_the_odata_literal() -> None:+ """A UPN out of alert text must not be able to close the literal."""+ _entra_token()+ captured: dict[str, str] = {}++ def signins(request: httpx.Request) -> httpx.Response:+ captured["filter"] = request.url.params.get("$filter", "")+ return httpx.Response(200, json={"value": []})++ respx.get(f"{GRAPH}/auditLogs/signIns").mock(side_effect=signins)+ respx.get(f"{GRAPH_BETA}/identityProtection/riskyUsers").mock(return_value=httpx.Response(200, json={"value": []}))++ await EntraGetUserActivity().execute(_request("a' or userPrincipalName ne 'x", ENTRA_CREDS))++ # OData escapes a quote by doubling it. The doubled form present and the+ # single form absent is what proves the clause could not be closed.+ assert "'a'' or userPrincipalName ne ''x'" in captured["filter"]+ assert "'a' or" not in captured["filter"]+++# ------------------------------------------------------- Google Workspace+++async def test_google_workspace_login_audit_projects_and_counts(monkeypatch: pytest.MonkeyPatch) -> None:+ async def _no_token(self, client): # noqa: ANN001, ANN202+ self._token = "gws-token"++ monkeypatch.setattr(gws_module.GoogleWorkspaceClient, "_ensure_token", _no_token, raising=True)++ respx.get(f"{GWS_REPORTS}/activities/users/[email protected]/applications/login").mock(+ return_value=httpx.Response(+ 200,+ json={+ "items": [+ {+ "id": {"time": "2026-09-26T10:00:00.000Z"},+ "ipAddress": "198.51.100.7",+ "events": [+ {+ "name": "login_success",+ "parameters": [+ {"name": "login_type", "value": "google_password"},+ {"name": "is_suspicious", "boolValue": True},+ ],+ }+ ],+ },+ {+ "id": {"time": "2026-09-26T09:59:00.000Z"},+ "ipAddress": "198.51.100.8",+ "events": [+ {+ "name": "login_failure",+ "parameters": [{"name": "login_failure_type", "value": "login_failure_invalid_password"}],+ }+ ],+ },+ ]+ },+ )+ )+ result = await GoogleWorkspaceGetUserActivity().execute(_request("[email protected]", GWS_CREDS))++ assert result.status is LiveActionStatus.SUCCEEDED+ assert result.details["count"] == 2+ assert result.details["flagged_suspicious_by_google"] == 1+ assert result.details["distinct_source_ips"] == ["198.51.100.7", "198.51.100.8"]+ assert result.details["logins"][1]["failure_type"] == "login_failure_invalid_password"+++async def test_google_workspace_403_names_the_missing_scope(monkeypatch: pytest.MonkeyPatch) -> None:+ """A scope gap is a configuration fact, not an account with no logins."""++ async def _no_token(self, client): # noqa: ANN001, ANN202+ self._token = "gws-token"++ monkeypatch.setattr(gws_module.GoogleWorkspaceClient, "_ensure_token", _no_token, raising=True)+ respx.get(f"{GWS_REPORTS}/activities/users/[email protected]/applications/login").mock(+ return_value=httpx.Response(403, json={"error": {"message": "Not Authorized to access this resource/api"}})+ )++ result = await GoogleWorkspaceGetUserActivity().execute(_request("[email protected]", GWS_CREDS))++ assert result.status is LiveActionStatus.FAILED+ assert "admin.reports.audit.readonly" in (result.error or "")+ assert "count" not in result.details+++# ------------------------------------------------------------ AWS CloudTrail+++def _ct_client(transport: httpx.MockTransport) -> AWSCloudTrailClient:+ return AWSCloudTrailClient(+ access_key_id="AKIAEXAMPLE",+ secret_access_key="secret",+ region="us-east-1",+ transport=transport,+ )+++async def test_cloudtrail_signs_with_the_headers_it_sends() -> None:+ """The signature must cover exactly the headers that reach the wire.++ This is the failure mode of a hand-rolled SigV4: the signed-header list+ and the sent headers drift, and every call 403s. Asserted by parsing+ `SignedHeaders` out of the Authorization header the client produced and+ comparing it against the request's own header names.+ """+ captured: dict[str, httpx.Request] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["request"] = request+ return httpx.Response(200, json={"Events": []})++ client = _ct_client(httpx.MockTransport(handler))+ await client.lookup_events(attribute_key="Username", attribute_value="svc_deploy")++ request = captured["request"]+ auth = request.headers["authorization"]+ assert auth.startswith("AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/")+ assert "/us-east-1/cloudtrail/aws4_request," in auth++ signed = auth.split("SignedHeaders=")[1].split(",")[0].split(";")+ assert signed == sorted(signed), "SignedHeaders must be lowercase-sorted"+ for name in signed:+ assert name in request.headers, f"{name} was signed and not sent"+ assert request.headers["x-amz-target"] == "CloudTrail_20131101.LookupEvents"+ assert request.headers["content-type"] == "application/x-amz-json-1.1"+++def test_cloudtrail_canonical_request_is_the_documented_shape() -> None:+ """Pin the algorithm, not just the header it ends up in.++ `canonical_parts` is what `_authorization` itself calls, so this is not a+ second implementation the test compares against a copy of itself.+ """+ client = AWSCloudTrailClient("AKIAEXAMPLE", "secret", region="eu-west-1")+ payload = '{"MaxResults":1}'+ canonical, to_sign, signed_headers = client.canonical_parts(payload, "20260926T120000Z", "20260926")++ lines = canonical.split("\n")+ assert lines[0] == "POST"+ assert lines[1] == "/"+ assert lines[2] == "", "no query string on a CloudTrail POST"+ assert lines[3] == "content-type:application/x-amz-json-1.1"+ assert lines[4] == "host:cloudtrail.eu-west-1.amazonaws.com"+ assert lines[5] == "x-amz-date:20260926T120000Z"+ assert lines[6] == "x-amz-target:CloudTrail_20131101.LookupEvents"+ assert lines[7] == "", "a blank line separates canonical headers from signed headers"+ assert lines[8] == signed_headers == "content-type;host;x-amz-date;x-amz-target"+ # The payload hash is the last line, and it is the hash of the body.+ import hashlib++ assert lines[9] == hashlib.sha256(payload.encode()).hexdigest()++ scope_lines = to_sign.split("\n")+ assert scope_lines[0] == "AWS4-HMAC-SHA256"+ assert scope_lines[1] == "20260926T120000Z"+ assert scope_lines[2] == "20260926/eu-west-1/cloudtrail/aws4_request"+ assert scope_lines[3] == hashlib.sha256(canonical.encode()).hexdigest()+++def test_cloudtrail_signing_key_derivation_is_sensitive_to_every_input() -> None:+ """A derivation that ignores an input would still look correct.++ Each of secret, date, region is changed in turn and the key must move.+ Without this the chain could drop a link and every signature would still+ be a plausible-looking hex string.+ """+ base = _signing_key("secret", "20260926", "us-east-1")+ assert base != _signing_key("other", "20260926", "us-east-1")+ assert base != _signing_key("secret", "20260927", "us-east-1")+ assert base != _signing_key("secret", "20260926", "eu-west-1")+ assert len(base) == 32+++async def test_cloudtrail_session_token_is_signed_when_present() -> None:+ captured: dict[str, httpx.Request] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["request"] = request+ return httpx.Response(200, json={"Events": []})++ client = AWSCloudTrailClient(+ "AKIAEXAMPLE",+ "secret",+ region="us-east-1",+ session_token="FwoGZXIvYXdzE",+ transport=httpx.MockTransport(handler),+ )+ await client.lookup_events(attribute_key="Username", attribute_value="svc_deploy")++ request = captured["request"]+ signed = request.headers["authorization"].split("SignedHeaders=")[1].split(",")[0].split(";")+ # A session token that is sent and not signed is rejected by AWS, and a+ # token that is signed and not sent is too.+ assert "x-amz-security-token" in signed+ assert request.headers["x-amz-security-token"] == "FwoGZXIvYXdzE"+++async def test_cloudtrail_projects_the_nested_event_record() -> None:+ """`CloudTrailEvent` is a JSON string holding kilobytes per call."""+ inner = {+ "awsRegion": "us-east-1",+ "sourceIPAddress": "203.0.113.9",+ "userAgent": "aws-cli/2.15.0",+ "errorCode": "AccessDenied",+ "userIdentity": {+ "type": "AssumedRole",+ "arn": "arn:aws:sts::123456789012:assumed-role/deploy/svc_deploy",+ "sessionContext": {"attributes": {"mfaAuthenticated": "false"}},+ },+ "requestParameters": {"noise": "x" * 5000},+ "responseElements": {"more": "y" * 5000},+ }++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "Events": [+ {+ "EventId": "evt-1",+ "EventName": "GetSecretValue",+ "EventSource": "secretsmanager.amazonaws.com",+ "EventTime": "2026-09-26T10:00:00Z",+ "Username": "svc_deploy",+ "ReadOnly": "true",+ "CloudTrailEvent": json.dumps(inner),+ }+ ]+ },+ )++ events = await _ct_client(httpx.MockTransport(handler)).lookup_events(attribute_key="Username", attribute_value="svc_deploy")++ assert len(events) == 1+ event = events[0]+ assert event["event_name"] == "GetSecretValue"+ assert event["source_ip"] == "203.0.113.9"+ assert event["error_code"] == "AccessDenied"+ assert event["principal_arn"].endswith("svc_deploy")+ assert event["mfa_authenticated"] == "false"+ # The 10 KB of request parameters and response elements must not travel.+ assert "requestParameters" not in event+ assert "responseElements" not in event+ assert len(json.dumps(event)) < 800+++async def test_cloudtrail_malformed_detail_is_not_a_failed_lookup() -> None:+ """An unparseable record still answers the envelope-level question."""++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={"Events": [{"EventId": "evt-1", "EventName": "AssumeRole", "CloudTrailEvent": "{not json"}]},+ )++ events = await _ct_client(httpx.MockTransport(handler)).lookup_events(attribute_key="EventName", attribute_value="AssumeRole")++ assert len(events) == 1+ assert events[0]["event_name"] == "AssumeRole"+ assert events[0]["source_ip"] is None+++async def test_cloudtrail_refuses_an_attribute_aws_does_not_define() -> None:+ """Refused here, with the supported set named, rather than sent."""+ calls: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ calls.append(request)+ return httpx.Response(200, json={"Events": []})++ client = _ct_client(httpx.MockTransport(handler))+ with pytest.raises(CloudTrailLookupError) as exc:+ await client.lookup_events(attribute_key="SourceIPAddress", attribute_value="203.0.113.9")++ assert "not a CloudTrail lookup attribute" in str(exc.value)+ assert "Username" in str(exc.value)+ assert not calls+++async def test_cloudtrail_refuses_an_empty_value() -> None:+ client = _ct_client(httpx.MockTransport(lambda r: httpx.Response(200, json={"Events": []})))+ with pytest.raises(CloudTrailLookupError) as exc:+ await client.lookup_events(attribute_key="Username", attribute_value=" ")+ assert "would match the whole window" in str(exc.value)+++async def test_cloudtrail_executor_reports_failure_rather_than_no_activity(monkeypatch: pytest.MonkeyPatch) -> None:+ """An AccessDenied must never read as a principal that did nothing."""++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(400, json={"__type": "AccessDeniedException", "message": "not authorized"})++ executor = AWSLookupCloudAudit()+ request = _request("svc_deploy", {**AWS_CREDS, "attribute_key": "Username"})++ # The executor builds its own client from credentials, so the transport is+ # injected by patching the factory it calls. Patched at the executor's+ # import site rather than at the factory module, because that is the name+ # the executor actually resolves.+ #+ # Through `monkeypatch` on the from-imported module rather than+ # `import app.live_actions.investigation_reads as reads`: this file already+ # from-imports the executors, and mixing the two styles for one module is+ # what `py/import-and-import-from` flags.+ monkeypatch.setattr(+ investigation_reads,+ "_cloudtrail_client",+ lambda params: _ct_client(httpx.MockTransport(handler)),+ )+ result = await executor.execute(request)++ assert result.status is LiveActionStatus.FAILED+ assert "AccessDenied" in (result.error or "")+ assert "count" not in result.details+ assert "events" not in result.details+++# --------------------------------------------- governed dispatch, end to end+++async def test_every_new_read_verb_is_automatic_and_needs_no_approval() -> None:+ """A read gated behind an analyst is how an agent learns to conclude blind.++ Driven through `dispatch` rather than by reading the contract, so the+ assertion covers the door an agent actually comes through: the contract,+ the approval matrix and the dispatcher composing.+ """+ register_builtin_executors(overwrite=True)++ cases = [+ ("sentinelone", "get_host", "WS-42"),+ ("sentinelone", "get_detections", "WS-42"),+ ("defender", "get_detections", "WS-42"),+ ("entra", "get_user_activity", "[email protected]"),+ ("google_workspace", "get_user_activity", "[email protected]"),+ ("aws", "lookup_cloud_audit", "svc_deploy"),+ ("defender", "lookup_endpoint_telemetry", "a" * 64),+ ]+ for vendor_id, capability, target in cases:+ result = await dispatch(+ LiveActionRequest(+ request_id=uuid.uuid4(),+ capability=capability,+ vendor_id=vendor_id,+ target=target,+ params={},+ dry_run=True,+ tenant_id=TENANT,+ confidence=0.1,+ )+ )+ # A dry run with no credentials, at the lowest possible confidence.+ # The only outcome that must not appear is PENDING_APPROVAL: these+ # verbs change nothing, so nothing is waiting on a human.+ assert result.status is not LiveActionStatus.PENDING_APPROVAL, f"{vendor_id}/{capability} queued for approval"+ assert result.status is not LiveActionStatus.BLOCKED, f"{vendor_id}/{capability} was blocked by policy"diff --git a/services/actions/tests/test_live_action_builtins.py b/services/actions/tests/test_live_action_builtins.pyindex 62c6aa9be..fc2de1c87 100644--- a/services/actions/tests/test_live_action_builtins.py+++ b/services/actions/tests/test_live_action_builtins.py@@ -60,8 +60,13 @@ def test_register_builtin_executors_returns_full_count() -> None:# of a two-way SIEM integration: AiSOC's verdict back onto the notable,# signal, incident or offense that produced the alert. Plus 3 for the# verbs that were reachable from a recommendation and not from dispatch:- # Defender evidence acquisition, and the two ChatOps transports.- assert count == 66+ # Defender evidence acquisition, and the two ChatOps transports. Plus 7+ # from gap-closure Phase 4.2: five new vendor arms on the three existing+ # read verbs (SentinelOne agents and threats, Defender alerts, Entra+ # sign-ins, Google Workspace login audit) and two verbs whose subject is+ # neither a host nor a principal (AWS CloudTrail lookup, Defender+ # endpoint-telemetry search).+ assert count == 73def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:@@ -119,6 +124,18 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:("okta", "disable_user"),("okta", "force_mfa"),("okta", "get_user_activity"),+ # Gap-closure Phase 4.2. Five of these are new vendor arms on the+ # three read verbs above, which is what declaring a contract per+ # capability buys: they inherit the READ_ONLY classification and+ # cannot drift low. The two `lookup_*` verbs needed their own+ # contract because their subject is neither a host nor a principal.+ ("sentinelone", "get_host"),+ ("sentinelone", "get_detections"),+ ("defender", "get_detections"),+ ("entra", "get_user_activity"),+ ("google_workspace", "get_user_activity"),+ ("aws", "lookup_cloud_audit"),+ ("defender", "lookup_endpoint_telemetry"),("okta", "reset_password"),("okta", "suspend_session"),("pagerduty", "create_ticket"),@@ -172,7 +189,7 @@ def test_register_builtin_executors_is_idempotent_with_overwrite() -> None:register_builtin_executors()# Second call without overwrite would raise — confirm overwrite works.count = register_builtin_executors(overwrite=True)- assert count == 66+ assert count == 73def test_register_builtin_twice_without_overwrite_raises() -> None:diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.pyindex 3f8f5c6ed..717b194a6 100644--- a/services/connectors/app/connectors/base.py+++ b/services/connectors/app/connectors/base.py@@ -133,6 +133,15 @@ class Capability(str, Enum):GET_HOST = "get_host"GET_DETECTIONS = "get_detections"GET_USER_ACTIVITY = "get_user_activity"+ # Gap-closure Phase 4.2. Two reads that do not fit the three above+ # because their subject is neither a host nor a principal: a cloud+ # control-plane audit trail, and endpoint telemetry searched by+ # indicator. Both take typed arguments and build their own query text+ # server-side, which is the point: an investigation agent can reach+ # these, and the plan forbids a model composing query text against a+ # customer's estate.+ LOOKUP_CLOUD_AUDIT = "lookup_cloud_audit"+ LOOKUP_ENDPOINT_TELEMETRY = "lookup_endpoint_telemetry"SEARCH_SIEM = "search_siem"CREATE_NOTABLE_EVENT = "create_notable_event"SYNC_DETECTION_RULE = "sync_detection_rule"