feat(actions): governed undo route — executor rollbacks reachable in production (#2016)

## The gap

Nothing in production called an executor's `rollback()`.
`services/actions` had no undo route and no worker invoked one, so
`SplunkSyncDetectionRuleExecutor.rollback`,
`ElasticSyncDetectionRuleExecutor.rollback` and every other executor's
reversal was reachable only from tests — while the capability contracts
advertise `reverse_capability` on every platform-reversible verb and the
executors capture `rollback_data` on every destructive one. A reversal
the product cannot dispatch is a promise the docs make and the product
breaks.

## What this adds

**`POST /actions/{action_id}/rollback` on the actions service**
(service-token-guarded beside approve/reject/reconcile; logic in
`app/services/undo.py`):

- **The record decides what is reversed.** The verb, the target and the
vendor come from the stored action record (`rollback_data.vendor`, with
execution output as fallback) — the caller chooses none of them. A
record that captured nothing (simulation-mode forward run) or names no
vendor is refused with the reason (422).
- **State guard = one conditional UPDATE.**
`action_store.claim_rollback()` moves `completed → rolling_back` (new
`ActionStatus.ROLLING_BACK`, added to the store's intent-locked set)
exactly as `claim_for_execution` claims a forward run — Postgres
row-lock plus predicate re-evaluation elects one executor across
replicas and retries. An action that never executed, was already rolled
back, is mid-reversal, or has an unestablished outcome is refused 409
naming which. The claim lands under its own `rollback` key so the
forward dispatch provenance survives the undo.
- **The reversal is governed like a forward dispatch.** The undo is
graded against the **reverse** capability's own contract through the
same `evaluate_contract` every forward door calls (tenant tier,
confidence with `None` as the lowest band, asset criticality, response
schedule). A reversal graded `analyst`/`mandatory_human` does not run
until a distinct approver is bound — permission-checked and
separation-of-duties-compared against the undo's requester via the same
`authorize_approver` the approve door uses; `prohibited` never runs. The
invoking principal needs the forward verb's own execution-tier
permission (`authorize_action`).
- **Credentials arrive per call, never from the record.** The body's
`auth_config` carries connector-schema fields translated at the boundary
by the same `resolve_params` forward dispatch uses. Verbs whose legacy
reversal cannot accept per-call credentials (every one-argument
`rollback(result)` today) are refused up front (422) rather than queued
for an approval that could only simulate — only the credential-capable
arms are dispatchable, which is currently the two `sync_detection_rule`
arms, and the route generalises as arms widen.
- **The executor's boolean is reported honestly.** Only a confirmed
reversal settles the record to `rolled_back`, stamping `rolled_back_at`,
`rolled_back_by` (the approver when one decided, else the principal) and
full provenance (requester, approver, separation-of-duties state,
vendor, grading requirement and reason). A `False` — vendor refusal,
missing reversal state — is a **failed undo**: the record returns to
`completed` (the effect is in force, the undo retryable) with the error
recorded. Never a success.

**`POST /api/v1/actions/{action_id}/undo` on the API**
(session-authenticated, `require_permission("actions:execute")` — the
same permission as the forward playbook-step door; logic in
`app/services/action_undo.py`):

- **The request cannot carry credentials.** The body model refuses
unknown fields (`extra="forbid"`), so there is no key to put a token or
a destination in; it carries only `confidence`. Credentials are resolved
server-side at dispatch time: the tenant's enabled connector for the
vendor the record executed against (honouring per-instance capability
downscoping, via the playbook hop's own `_pick_connector`), decrypted
through the vault, merged with the connector's operational config —
mirroring `playbook_step_dispatch` exactly.
- **A queued undo follows the forward approval flow.**
`pending_approval` from the grading creates an `AgentApproval` row
(`kind: action_undo`, requester stamped from authenticated context) in
the same approvals inbox forward actions use; the response carries the
`approval_id`. Deciding it re-drives the reversal through
`_dispatch_decision`'s new undo branch with the deciding identity bound
as approver and the stamped requester kept separate — the requester
cannot approve their own undo, and credentials are resolved freshly at
decide time so nothing secret ever waits in a queue. A denial executes
nothing.
- **Every outcome is audited**: `emit_audit(action="actions:undo",
resource="action", resource_id=<action id>)` with the status, the
reversal verdict, the vendor, the verb, the target, and the approval id
when one was queued.

`docs/openapi.yaml` regenerated — purely additive (+85 lines, 0
deletions). No migration: the record fields ride the existing JSONB
record column, and the approvals table already exists.

## Failing-test-first

`services/actions/tests/test_action_undo_route.py` was written first
against the absent route (TestClient over the real router, in-memory
store, **real `SplunkSyncDetectionRule` adapter against the mock Splunk
management API from `test_sync_detection_rule_vendor_arms.py`**):

- before implementation: **12 failed, 1 passed** (the cross-tenant 404
passes vacuously while the route is absent);
- after: **13 passed**, including the headline — forward
`sync_detection_rule` executed through the real Splunk arm (prior
definition captured), undone through the route with an approver bound,
and the mock vendor shows the prior SPL **and schedule** restored; the
seeded records carry no credentials, so the restore happening at all
proves the credentials came from the request's `auth_config` (the
stored-integration path) and were translated `base_url/token →
splunk_url/splunk_token` at the boundary.

`services/api/tests/test_action_undo.py` likewise failed on collection
before the endpoint existed, then **10 passed**: vault-not-request
credential sourcing, credential-bearing bodies refused by validation,
pending-approval row creation, decide-path re-drive with the deciding
identity, denial executing nothing, vendor refusals and upstream state
refusals surfacing with their reasons, and the audit row.

Approval grading proven in both shapes, the way the forward tests do it:
the analyst-tier reversal (`sync_detection_rule`, whose reverse is
itself, declared `analyst`) queues with the vendor untouched and runs
only once a distinct, permitted approver is bound —
requester-as-approver and an under-permissioned approver both 403 before
the vendor; the auto-allowed shape (`block_sender`, whose reverse
`unblock_sender` is low-impact/`automatic`) runs with no approver at
tier L3 with confidence above the floor, via a capturing adapter
monkeypatched into the live registry exactly as the forward suites stub
`EXECUTOR_REGISTRY`.

## Negative controls (run on the committed tree, then restored)

**Credential resolution severed** (`params = resolve_params(vendor_id,
…)` replaced with `params = {}` in
`services/actions/app/services/undo.py`):

```
FAILED tests/test_action_undo_route.py::TestApprovalGoverned::test_a_bound_approver_releases_the_reversal
E       AssertionError: assert 'undo_failed' == 'rolled_back'
```

The break produced an honest *failed undo*, not a fake success — the
designed failure direction. Restored via `git checkout --`; the named
test passes again.

**Grading severed** (the graded requirement forced to `automatic` before
it is consulted):

```
FAILED tests/test_action_undo_route.py::TestApprovalGoverned::test_an_analyst_tier_reversal_waits_for_an_approver
E       AssertionError: assert 'rolled_back' == 'pending_approval'
```

With governance cut out, the undo ran unapproved and the test caught it.
Restored; all 13 pass.

## Gates (run pipelessly, exit codes echoed)

| gate | exit |
| --- | --- |
| `scripts/check_route_auth.py` | 0 |
| `scripts/check_route_tenant_scope.py` | 0 |
| `scripts/check_tenant_query_predicates.py` | 0 |
| `scripts/check_module_reachability.py` | 0 |
| `scripts/check_action_contract.py` | 0 |
| `scripts/check_mypy_baseline.py` (21 trees + unmanaged: "no tree got
worse") | 0 |
| `ruff format --check` / `ruff check` (services/actions, services/api)
| 0 / 0 |
| `scripts/export_openapi.py --check` | 0 |

Full suites at the final tree: `services/actions` **2145 passed, 10
skipped**; `services/api` **5603 passed, 272 skipped, 1 xfailed**.

## Scope notes

- The two `sync_detection_rule` arms are the only reversals that can
take per-call credentials today; every other executor's
`rollback(result)` is one-argument and is refused up front with the
reason rather than dispatched into a simulation that would read as an
undo. Widening an arm to `rollback(result, params)` makes it
dispatchable with no route change.
- A worker dying between the rollback claim and the settle leaves the
record visibly `rolling_back` — the same stranding semantics as a
forward `running` claim, and deliberately a visible state rather than an
invisible one.

---------

Co-authored-by: beenuar <beenuar@users.noreply.github.com>
This commit is contained in:
Beenu Arora
2026-11-22 19:26:09 -08:00
committed by GitHub
co-authored by beenuar
parent 41351bde74
commit 5216d06169
13 changed files with 2166 additions and 7 deletions
+26
View File
@@ -69,6 +69,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
answer. 15 cases over the vendors' own shapes; the negative control
corrupts one enforcement mapping and watches two fail.
- **A completed response action can now actually be undone.** Every
destructive executor captured `rollback_data` and every platform-reversible
verb's contract named a `reverse_capability`, but no route or worker ever
invoked an executor's `rollback()` — the reversal the docs promised was
reachable only from tests. `POST /api/v1/actions/{action_id}/undo`
(session-authenticated, `actions:execute`) resolves the tenant's stored
integration server-side — the request body cannot carry credentials, since
unknown fields are refused — and drives the actions service's new
`POST /actions/{action_id}/rollback`, which grades the undo against the
**reverse** capability's own contract through the same approval matrix as
forward dispatch: an analyst-tier reversal queues in the approvals inbox
and is re-driven at decide time with the deciding identity bound as
approver (the requester cannot approve their own undo), a prohibited one
never runs. The reversal is claimed with one conditional UPDATE
(`completed → rolling_back`) before any vendor is contacted, so two undo
requests elect one executor; an action that never executed or was already
rolled back is refused with the reason. The outcome is honest: only a
reversal the executor confirms moves the record to `rolled_back` (stamping
`rolled_back_at`/`rolled_back_by` and the vendor outcome); a vendor
refusal is a **failed undo** that leaves the action `completed` — in
force and retryable — never a success. Proven end to end against a mock
Splunk management API: a `sync_detection_rule` executed through the real
vendor arm, then restored to its captured prior definition through the
route, with the credential-incapable legacy reversals refused up front
rather than simulated.
### Added
- **The insider watchlist is a control, not a checkbox.**
`user_risk_profiles.is_watchlisted` existed since
+85
View File
@@ -12854,6 +12854,66 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
/api/v1/actions/{action_id}/undo:
post:
tags:
- actions
summary: Reverse a completed response action
description: 'Reverse one completed action through its executor''s own rollback.
The reversal is graded against the reverse capability''s contract before
anything runs. The answer is always 200 with a status naming what
happened — ``rolled_back``, ``undo_failed`` (the vendor refused; the
action is still in force), ``pending_approval`` (queued in the approvals
inbox, ``approval_id`` included) or ``refused`` (the contract prohibits
the reversal). 4xx is reserved for requests that cannot be served at
all: an action that never executed or was already rolled back (409), a
verb the platform cannot reverse or a missing integration (422), an
action this tenant does not own (404).'
operationId: undo_action_api_v1_actions__action_id__undo_post
security:
- HTTPBearer: []
parameters:
- name: action_id
in: path
required: true
schema:
type: string
format: uuid
title: Action Id
requestBody:
required: true
content:
application/json:
schema:
anyOf:
- $ref: '#/components/schemas/ActionUndoRequest'
- type: 'null'
title: Body
responses:
'200':
description: Successful Response
content:
application/json:
schema:
type: object
additionalProperties: true
title: Response Undo Action Api V1 Actions Action Id Undo Post
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
/api/v1/costs/dashboard:
get:
tags:
@@ -23995,6 +24055,31 @@ components:
- effective_tier
- effective_reason
title: ActionPolicy
ActionUndoRequest:
properties:
confidence:
anyOf:
- type: number
maximum: 1.0
minimum: 0.0
- type: 'null'
title: Confidence
additionalProperties: false
type: object
title: ActionUndoRequest
description: 'What a caller may say about an undo: how sure they are, and nothing
else.
``extra="forbid"`` is the control, not a nicety. The reversal''s
credentials come from the tenant''s stored integration through the vault,
and the vendor comes from the action record itself — a body that could
carry either would let a caller steer a reversal somewhere it was never
aimed, so a request naming any other field is refused outright.'
AddAlertsRequest:
properties:
alert_ids:
+66 -1
View File
@@ -35,7 +35,7 @@ from app.security.authz import (
)
from app.security.chatops_identity import resolve_approver
from app.security.chatops_token import ChatOpsTokenError, verify_token
from app.services import action_store
from app.services import action_store, undo
from app.services.action_store import ActionIntentConflict, ActionStoreUnavailable, ClaimOutcome
from app.services.approval_gate import apply_matrix
from app.services.blast_radius import BlastRadiusGate
@@ -710,6 +710,71 @@ async def reconcile_action(
return record
class UndoActionRequest(BaseModel):
"""What a reversal needs that the stored record deliberately lacks.
``auth_config`` carries the tenant's connector credentials in schema
field names, resolved server-side by the API service from the vault —
the executors never store credentials in ``rollback_data``, so they have
to arrive per call, exactly as they do on forward dispatch. ``approver``
is the deciding identity when the reverse capability's grading demands
one; ``requester`` is who asked for the undo, kept separate so
separation of duties has two identities to compare.
"""
auth_config: dict[str, Any] = Field(default_factory=dict)
principal: ActionPrincipal | None = None
approver: ActionPrincipal | None = None
requester: ActionPrincipal | None = None
confidence: float | None = Field(default=None, ge=0.0, le=1.0)
requested_by: str = Field(default="", max_length=200)
@router.post("/actions/{action_id}/rollback")
async def rollback_action(
action_id: str,
request: Request,
body: UndoActionRequest | None = None,
_auth: None = Depends(require_service_auth),
):
"""Reverse a completed action through its executor's own rollback.
Graded against the **reverse** capability's contract before anything
runs, with the same matrix forward dispatch uses — an undo of an
analyst-tier reversal waits for a distinct approver, and a prohibited
one never runs. The reversal is claimed in durable storage before the
vendor is contacted, so two undo requests elect one executor.
Governance outcomes are 200 with a status naming which one it was
(``rolled_back``, ``undo_failed``, ``pending_approval``, ``refused``),
the same single-shape contract the dispatch report keeps. 4xx is
reserved for requests this route will not serve: an action that never
executed or was already rolled back (409, naming it), a verb the
platform cannot reverse (422), a caller naming no tenant (400).
"""
tenant_id = (request.headers.get(_TENANT_HEADER) or "").strip()
if not tenant_id:
raise HTTPException(
status_code=400,
detail=f"a reversal acts on one tenant's estate; declare it on {_TENANT_HEADER}",
)
payload = body or UndoActionRequest()
try:
report = await undo.undo_action(
action_id,
tenant_id=tenant_id,
auth_config=payload.auth_config,
principal=payload.principal,
approver=payload.approver,
requester=payload.requester,
confidence=payload.confidence,
requested_by=payload.requested_by or "aisoc-api",
)
except undo.UndoRefused as refusal:
raise HTTPException(status_code=refusal.status_code, detail=refusal.detail) from refusal
return report.as_dict()
_CHOICE_COPY: dict[str, dict[str, str]] = {
"acknowledge": {
"headline": "Thanks — recorded as acknowledged.",
+5
View File
@@ -130,6 +130,11 @@ class ActionStatus(str, Enum):
#: Not a terminal success: `services/api`'s usage meter counts `completed`
#: as the one status meaning a vendor was touched, and that stays true.
RECONCILIATION_REQUIRED = "reconciliation_required"
#: Claimed for reversal. Same discipline as ``RUNNING``: written to the
#: durable store *before* the vendor is asked to undo anything, so two
#: undo requests elect one executor and a replica that dies mid-reversal
#: leaves a record visibly in flight rather than one nobody started.
ROLLING_BACK = "rolling_back"
ROLLED_BACK = "rolled_back"
+96 -1
View File
@@ -206,7 +206,12 @@ def _column_text(value: Any) -> str:
#: this module is the storage layer and the column holds text; importing the
#: enum here would make the SQL depend on the executor contract, which is the
#: coupling 055 avoided by storing the record whole.
_INTENT_LOCKED_STATUSES = ("awaiting_approval", "running", "reconciliation_required")
#:
#: ``rolling_back`` is locked for the reversal's version of the same reason:
#: what gets undone must be what executed, and a submission that retargeted a
#: record mid-reversal would change what the executor is in the middle of
#: restoring.
_INTENT_LOCKED_STATUSES = ("awaiting_approval", "running", "reconciliation_required", "rolling_back")
#: The same tuple as a SQL list. Built rather than written twice so the two
#: cannot drift, and quoted here because these are fixed identifiers from a
@@ -492,6 +497,96 @@ async def claim_for_execution(
await conn.close()
async def claim_rollback(action_id: str, *, tenant_id: str, claimed_by: str) -> Claim:
"""Take exclusive ownership of an action's reversal, durably, or refuse.
The same one conditional ``UPDATE`` as :func:`claim_for_execution`, and
for the same reason: two undo requests — two replicas, or one operator
and one retry — must elect exactly one executor before a vendor is asked
to restore anything. Postgres locks the row, the loser re-evaluates
``status = 'completed'`` against the committed ``rolling_back`` and
matches nothing.
Deliberately not a call into :func:`claim_for_execution`: that function
writes its claim under ``dispatch``, which on a completed record holds
the forward execution's provenance. A reversal that overwrote it would
erase the record of the thing being reversed, so the claim lands under
``rollback`` and the settle (an ordinary :func:`save`) replaces it with
the outcome.
Only ``completed`` can be claimed. Everything else is a state in which
there is no effect to undo (never ran), nothing left to undo (already
rolled back) or an outcome nobody has established yet — the caller turns
``current_status`` into the right refusal.
"""
claimed_at = datetime.now(UTC).isoformat()
claim_note = {"state": "claimed", "claimed_by": claimed_by, "claimed_at": claimed_at}
dsn = _dsn()
if dsn is None:
async with _MEMORY_CLAIM_LOCK:
record = _MEMORY.get(action_id)
if record is None or str(record.get("tenant_id") or "") != str(tenant_id):
return Claim(ClaimOutcome.NOT_FOUND)
current = _column_text(record.get("status"))
if current != "completed":
return Claim(ClaimOutcome.WRONG_STATE, record=dict(record), current_status=current)
record["status"] = "rolling_back"
record["rollback"] = claim_note
return Claim(ClaimOutcome.CLAIMED, record=dict(record))
try:
conn = await _connect(dsn)
except Exception as exc: # noqa: BLE001
_report_degraded("rollback_claim_connect_failed", action_id, exc)
return Claim(ClaimOutcome.STORE_UNAVAILABLE)
try:
row = await conn.fetchrow(
"""
UPDATE aisoc_action_records
SET status = 'rolling_back',
record = jsonb_set(
jsonb_set(record, '{status}', to_jsonb('rolling_back'::text), true),
'{rollback}', $3::jsonb, true
),
updated_at = now()
WHERE id = $1
AND tenant_id = $2
AND status = 'completed'
RETURNING record
""",
action_id,
str(tenant_id),
json.dumps(claim_note),
)
except Exception as exc: # noqa: BLE001
_report_degraded("rollback_claim_failed", action_id, exc)
await conn.close()
return Claim(ClaimOutcome.STORE_UNAVAILABLE)
try:
if row is not None:
global _DB_CONFIRMED
_DB_CONFIRMED = True
record = json.loads(row["record"])
_MEMORY[action_id] = record
return Claim(ClaimOutcome.CLAIMED, record=record)
existing = await _fetch_record(conn, action_id, str(tenant_id))
if existing is None:
_MEMORY.pop(action_id, None)
return Claim(ClaimOutcome.NOT_FOUND)
current = _column_text(existing.get("status"))
_MEMORY[action_id] = existing
return Claim(ClaimOutcome.WRONG_STATE, record=existing, current_status=current)
except Exception as exc: # noqa: BLE001
_report_degraded("rollback_claim_readback_failed", action_id, exc)
return Claim(ClaimOutcome.STORE_UNAVAILABLE)
finally:
await conn.close()
async def claim_chatops_reply(action_id: str, *, tenant_id: str, replied_at: str | None = None) -> bool:
"""Record the one reply a ChatOps verification prompt gets. True if this is it.
+426
View File
@@ -0,0 +1,426 @@
"""Dispatch the reversal of a completed action, under the same governance as
the forward dispatch that produced it.
Every executor's ``rollback()`` was reachable only from tests. The capability
contracts advertise ``reverse_capability`` for each platform-reversible verb
and the executors capture ``rollback_data`` on every destructive one, but no
route or worker ever invoked a reversal — a promise the docs made and the
product could not keep. This module is the missing dispatch, shaped like the
forward one so an undo can never be a governance bypass:
* **The record decides what is being reversed.** The action id names a stored
record; its ``rollback_data`` (prior state, never credentials) and the
vendor it executed against come from that record, never from the caller.
* **Credentials arrive per call.** The executors' own docstrings state that
credentials are never stored in ``rollback_data``; they reach the reversal
through ``auth_config`` — connector-schema fields the API resolves from the
tenant's stored integration — translated at this boundary exactly as
forward dispatch translates them.
* **The reverse capability's contract grades the undo.** The same
``evaluate_contract`` every forward door calls, applied to the
``reverse_capability``'s own entry: an undo whose reversal is declared
analyst-tier waits for a distinct approver, one whose reversal is
prohibited never runs, and confidence below the floor queues exactly as a
forward dispatch would.
* **One conditional UPDATE claims the reversal.** ``completed →
rolling_back`` before the vendor is contacted, so two undo requests elect
one executor — the same durable-claim discipline as forward execution.
* **The executor's boolean is reported honestly.** ``False`` is a failed
undo naming the vendor refusal, and the action stays ``completed`` — still
in force, still retryable. Only a reversal that really ran moves the
record to ``rolled_back``.
"""
from __future__ import annotations
import inspect
import os
import socket
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any
from uuid import UUID, uuid4
import structlog
from app.live_actions import registry
from app.live_actions.capability_contracts import CAPABILITY_CONTRACTS, contract_for_action_type
from app.live_actions.contract import ApprovalRequirement, Reversal
from app.live_actions.models import LiveActionResult, LiveActionStatus
from app.models.action import ActionPrincipal, ActionRequest, ActionStatus, ActionType
from app.security.authz import SOD_UNEVALUATED, ActionAuthzError, authorize_action, authorize_approver
from app.services import action_store
from app.services.action_store import ActionIntentConflict, ActionStoreUnavailable, ClaimOutcome
from app.services.approval_gate import _resolve_tier
from app.services.approval_matrix import evaluate_contract
from app.services.asset_lookup import asset_criticality_for_target
from app.services.credential_resolver import resolve_params
from app.services.response_schedule_store import resolve_response_schedule
logger = structlog.get_logger(__name__)
#: Which replica claimed the reversal — same provenance the dispatch claim
#: records, for the same operator holding a stuck ``rolling_back`` record.
_WORKER_ID = f"{socket.gethostname()}/{os.getpid()}"
class UndoRefused(Exception):
"""The undo request itself is refusable, with an HTTP status and a reason.
Raised for caller errors — an action that never executed, one already
rolled back, a verb the platform cannot reverse — and translated by the
route into the matching 4xx/5xx. Governance outcomes (pending approval, a
prohibited reversal, a vendor refusal) are *not* refusals: they are
reported in an :class:`UndoReport` so the caller has one shape to read,
the same split the forward dispatch report draws.
"""
def __init__(self, status_code: int, detail: str) -> None:
super().__init__(detail)
self.status_code = status_code
self.detail = detail
@dataclass(frozen=True)
class UndoReport:
"""What actually happened to one undo request.
``reversed_`` is the single field that means the vendor's state was
restored. Every other outcome — queued for approval, refused by contract,
refused by the vendor — is ``False`` and ``status`` names which one.
"""
action_id: str
status: str # rolled_back | undo_failed | pending_approval | refused
reversed_: bool
vendor_id: str = ""
requirement: str = ""
reason: str = ""
summary: str = ""
error: str = ""
rolled_back_at: str = ""
rolled_back_by: str = ""
def as_dict(self) -> dict[str, Any]:
out: dict[str, Any] = {
"action_id": self.action_id,
"status": self.status,
"reversed": self.reversed_,
"summary": self.summary,
}
for key in ("vendor_id", "requirement", "reason", "error", "rolled_back_at", "rolled_back_by"):
value = getattr(self, key)
if value:
out[key] = value
return out
def _status_text(record: dict[str, Any]) -> str:
return str(getattr(record.get("status"), "value", record.get("status")))
def _state_guard(action_id: str, record: dict[str, Any]) -> None:
"""Refuse, with the reason, any record not in a reversible state.
A friendly pre-read: the durable claim below re-evaluates the same
predicate, so a race between two undo requests is settled by Postgres,
not by this check.
"""
current = _status_text(record)
if current == ActionStatus.COMPLETED.value:
return
if current == ActionStatus.ROLLED_BACK.value:
rolled_back_at = record.get("rolled_back_at") or "an earlier time"
rolled_back_by = record.get("rolled_back_by") or "an unrecorded identity"
raise UndoRefused(
409,
f"this action was already rolled back at {rolled_back_at} by {rolled_back_by}; there is nothing left to undo",
)
if current == ActionStatus.ROLLING_BACK.value:
raise UndoRefused(409, "another worker is already rolling this action back")
if current in (ActionStatus.RUNNING.value, ActionStatus.RECONCILIATION_REQUIRED.value):
raise UndoRefused(
409,
f"this action's outcome is not settled (current: {current}); reconcile it before deciding whether to undo it",
)
raise UndoRefused(
409,
f"only a completed action can be rolled back (current: {current}); this one never executed, so there is no effect to undo",
)
def _reversal_route(action_id: str, record: dict[str, Any]) -> tuple[ActionType, str, str, dict[str, Any], Any]:
"""Resolve what would be reversed and who can reverse it, or refuse.
Returns ``(action_type, reverse_capability, vendor_id, rollback_data,
adapter)``. Everything here is derived from the stored record and the
registry — the caller chooses none of it, which is what keeps an undo
aimed at the vendor the action actually ran against.
"""
raw_type = str(record.get("action_type") or "")
try:
action_type = ActionType(raw_type)
except ValueError as exc:
raise UndoRefused(422, f"the record names a verb this service does not know ({raw_type!r})") from exc
contract = contract_for_action_type(action_type.value)
if contract is None:
raise UndoRefused(
422,
f"'{action_type.value}' has no capability contract, so its reversal cannot be graded; nothing ungradable is dispatched",
)
if contract.reversal is not Reversal.PLATFORM or not contract.reverse_capability:
raise UndoRefused(
422,
f"the platform cannot undo '{action_type.value}': its contract declares reversal '{contract.reversal.value}'",
)
if contract.reverse_capability not in CAPABILITY_CONTRACTS:
raise UndoRefused(
422,
f"'{action_type.value}' names reverse capability '{contract.reverse_capability}', which has no contract to grade against",
)
rollback_data = dict(record.get("rollback_data") or {})
if not rollback_data:
raise UndoRefused(
422,
"the action captured no reversal state (it may have run in simulation mode); there is nothing to restore",
)
output = record.get("output") or {}
vendor_id = str(rollback_data.get("vendor") or (output.get("vendor") if isinstance(output, dict) else "") or "")
if not vendor_id:
raise UndoRefused(
422,
"the record does not name the vendor it executed against, so credentials cannot be resolved for the reversal",
)
adapter = registry.get_executor(vendor_id, action_type.value)
if adapter is None:
raise UndoRefused(422, f"no executor is registered for {vendor_id}/{action_type.value}")
# Can per-call credentials reach this reversal at all? The adapter widens
# ``rollback`` to take ``params`` only when the wrapped executor does; a
# one-argument reversal would run with no way to connect and could only
# simulate or fail. Refused before grading, because queueing an approval
# for an undo that can never run is a trap for the approver.
legacy = getattr(adapter, "_legacy_executor", None)
rollback_fn = getattr(legacy, "rollback", None) if legacy is not None else getattr(adapter, "rollback", None)
if not callable(rollback_fn):
raise UndoRefused(422, f"{vendor_id}/{action_type.value} declares no reversal")
if "params" not in inspect.signature(rollback_fn).parameters:
raise UndoRefused(
422,
f"the {vendor_id}/{action_type.value} reversal cannot accept per-call credentials yet, so it cannot be dispatched",
)
return action_type, contract.reverse_capability, vendor_id, rollback_data, adapter
async def undo_action(
action_id: str,
*,
tenant_id: str,
auth_config: dict[str, Any] | None = None,
principal: ActionPrincipal | None = None,
approver: ActionPrincipal | None = None,
requester: ActionPrincipal | None = None,
confidence: float | None = None,
requested_by: str = "aisoc-api",
) -> UndoReport:
"""Reverse one completed action through its executor's ``rollback``.
The order below is the control, mirroring forward dispatch: a
tenant-narrowed authoritative read, the state and reversal-route guards,
the invoking principal's authorization, the reverse capability's grading,
an approver bound under separation of duties when the grading demands
one, the durable claim, and only then the vendor.
"""
try:
record = await action_store.get(action_id, tenant_id=tenant_id, authoritative=True)
except ActionStoreUnavailable as exc:
raise UndoRefused(503, "the action store is unavailable; nothing was reversed") from exc
if not record:
raise UndoRefused(404, "Action not found")
_state_guard(action_id, record)
action_type, reverse_capability, vendor_id, rollback_data, adapter = _reversal_route(action_id, record)
log = logger.bind(
action_id=action_id,
tenant_id=tenant_id,
action_type=action_type.value,
reverse_capability=reverse_capability,
vendor_id=vendor_id,
)
# The invoking principal needs the same execution-tier permission the
# forward verb demanded: undoing a containment-grade act is itself a
# containment-grade act. Same check, same code, same settings-driven
# principal requirement as ``POST /actions``.
probe = ActionRequest(
id=UUID(action_id),
incident_id=UUID(str(record.get("incident_id") or uuid4())),
tenant_id=UUID(str(tenant_id)),
action_type=action_type,
target=str(record.get("target") or ""),
rationale="",
parameters={},
principal=principal,
requested_by=requested_by,
)
try:
authorize_action(probe)
except ActionAuthzError as exc:
log.warning("action_undo.principal_refused", reason=str(exc))
raise UndoRefused(403, str(exc)) from exc
decision = evaluate_contract(
contract=CAPABILITY_CONTRACTS[reverse_capability],
confidence=confidence,
tier=await _resolve_tier(tenant_id),
asset_criticality=await asset_criticality_for_target(tenant_id, record.get("target")),
schedule=await resolve_response_schedule(tenant_id),
)
if decision.is_blocked:
log.info("action_undo.refused_by_contract", reason=decision.reason)
return UndoReport(
action_id=action_id,
status="refused",
reversed_=False,
vendor_id=vendor_id,
requirement=decision.requirement.value,
reason=decision.reason,
summary=f"'{action_type.value}' on {record.get('target')}: the reversal is refused by contract — {decision.reason}",
)
sod = SOD_UNEVALUATED
if decision.requirement is not ApprovalRequirement.AUTOMATIC:
if approver is None:
log.info("action_undo.pending_approval", reason=decision.reason)
return UndoReport(
action_id=action_id,
status="pending_approval",
reversed_=False,
vendor_id=vendor_id,
requirement=decision.requirement.value,
reason=decision.reason,
summary=(
f"'{action_type.value}' on {record.get('target')}: the reversal needs "
f"{decision.requirement.value} approval before it runs — {decision.reason}"
),
)
# The approver must hold the verb's permission, belong to the
# record's tenant, and not be the undo's own requester. Reused from
# the approve door rather than restated, so the two cannot drift —
# with the requester being the *undo's* requester: the forward
# action's requester already got their action, and comparing against
# them would let the person who asked for the undo wave it through.
undo_requester_id = (requester.user_id if requester else None) or (principal.user_id if principal else None)
sod_context = {
"action_type": action_type.value,
"tenant_id": str(record.get("tenant_id") or tenant_id),
"requested_by_user_id": undo_requester_id,
}
try:
sod = authorize_approver(sod_context, approver)
except ActionAuthzError as exc:
log.warning("action_undo.approver_refused", reason=str(exc))
raise UndoRefused(403, str(exc)) from exc
claim = await action_store.claim_rollback(action_id, tenant_id=tenant_id, claimed_by=_WORKER_ID)
if not claim.ok:
if claim.outcome is ClaimOutcome.STORE_UNAVAILABLE:
raise UndoRefused(503, "the action store is unavailable, so the reversal was not authorized; nothing was sent to the vendor")
if claim.outcome is ClaimOutcome.NOT_FOUND:
raise UndoRefused(404, "Action not found")
current = claim.current_status or "unknown"
if current == ActionStatus.ROLLED_BACK.value:
raise UndoRefused(409, "this action was already rolled back; there is nothing left to undo")
raise UndoRefused(409, f"the reversal was not claimed: the action is no longer in a reversible state (current: {current})")
params = resolve_params(vendor_id, dict(auth_config or {})) if auth_config else {}
live_result = LiveActionResult(
request_id=UUID(action_id),
status=LiveActionStatus.SUCCEEDED,
capability=action_type.value,
vendor_id=vendor_id,
summary=f"recorded execution of {action_type.value} on {record.get('target')}",
details={**(record.get("output") or {}), "rollback_data": rollback_data},
)
error = ""
try:
reversed_ok = bool(await adapter.rollback(live_result, params=params))
if not reversed_ok:
error = "the executor reported the reversal did not run (vendor refusal or missing reversal state)"
except Exception as exc: # noqa: BLE001 — a claimed reversal must always settle
# Logged in full, echoed by type only: vendor exceptions carry
# internal hostnames, same reasoning as the forward dispatch.
log.error("action_undo.executor_crashed", error=str(exc), exc_info=True)
reversed_ok = False
error = f"the reversal raised {type(exc).__name__}"
now = datetime.now(UTC).isoformat()
settled = claim.record or record
acted_by = (approver.user_id if approver else None) or (principal.user_id if principal else None) or requested_by
provenance: dict[str, Any] = {
"state": "reversed" if reversed_ok else "failed",
"requested_by": requested_by,
"approved_by": approver.user_id if approver else None,
"separation_of_duties": sod,
"vendor_id": vendor_id,
"reverse_capability": reverse_capability,
"requirement": decision.requirement.value,
"reason": decision.reason,
"claimed_by": _WORKER_ID,
"settled_at": now,
}
if reversed_ok:
settled["status"] = ActionStatus.ROLLED_BACK
settled["rolled_back_at"] = now
settled["rolled_back_by"] = acted_by
else:
# The effect is still in force. ``completed`` is the honest state and
# keeps the undo retryable; the provenance says what was attempted
# and why it did not take.
settled["status"] = ActionStatus.COMPLETED
provenance["error"] = error
settled["rollback"] = provenance
try:
await action_store.save(settled)
except ActionIntentConflict: # pragma: no cover - a reversal changes no intent
log.error("action_undo.settle_write_refused")
log.info(
"action_undo.settled",
reversed=reversed_ok,
requirement=decision.requirement.value,
acted_by=acted_by,
error=error or None,
)
if reversed_ok:
return UndoReport(
action_id=action_id,
status="rolled_back",
reversed_=True,
vendor_id=vendor_id,
requirement=decision.requirement.value,
reason=decision.reason,
summary=f"'{action_type.value}' on {record.get('target')} was reversed on {vendor_id}",
rolled_back_at=now,
rolled_back_by=acted_by,
)
return UndoReport(
action_id=action_id,
status="undo_failed",
reversed_=False,
vendor_id=vendor_id,
requirement=decision.requirement.value,
reason=decision.reason,
error=error,
summary=f"'{action_type.value}' on {record.get('target')}: the reversal did not take — {error}",
)
@@ -0,0 +1,463 @@
"""``POST /actions/{action_id}/rollback``: the route that makes reversals real.
Every executor's ``rollback()`` was reachable only from tests: no route and no
worker invoked one, so the ``reverse_capability`` the contracts advertise and
the ``rollback_data`` captured on every destructive verb fed a reversal the
product could not dispatch. These tests drive the new route end to end against
the same mock Splunk management API the forward vendor-arm tests use, through
the real ``SplunkSyncDetectionRule`` adapter — the vendor fake is what shows
the prior definition coming back.
What is pinned here, in order of importance:
* the reversal is **governed**: an undo whose reverse capability requires
analyst approval does not run until a distinct approver is bound, exactly
as forward dispatch queues the forward verb;
* credentials reach the executor from the request's ``auth_config`` (resolved
server-side by the API from the tenant's stored integration) and never from
the stored record — the seeded records carry none;
* the state guard is one conditional UPDATE: an action that never executed or
was already rolled back is refused with the reason, and a vendor refusal is
a FAILED undo, never a success.
"""
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
from typing import Any
from uuid import UUID, uuid4
import pytest
from app.api import router as router_module
from app.live_actions import register_builtin_executors, registry
from app.live_actions.builtins import SplunkSyncDetectionRule
from app.live_actions.models import LiveActionRequest, LiveActionResult, LiveActionStatus
from app.models.action import ActionPrincipal, ActionStatus
from app.security.authz import require_service_auth
from app.services import action_store
from fastapi import FastAPI
from fastapi.testclient import TestClient
from test_sync_detection_rule_vendor_arms import SPL, _FakeSplunk, _wire_splunk
TENANT = "11111111-1111-1111-1111-111111111111"
TENANT_UUID = UUID(TENANT)
OTHER_TENANT = "22222222-2222-2222-2222-222222222222"
RULE_NAME = "AiSOC - brute force by user"
PRIOR_SPL = "index=main | stats count"
#: Connector-schema credentials, the shape the API resolves out of the vault.
#: The route translates them into the executor's vendor-prefixed params, which
#: is the same boundary translation forward dispatch performs.
SPLUNK_AUTH_CONFIG = {"base_url": "https://splunk.example:8089", "token": "tok-1"}
REQUESTER = ActionPrincipal(
user_id="rory@example.com",
permissions=["actions:execute:medium"],
tenant_id=TENANT_UUID,
)
APPROVER = ActionPrincipal(
user_id="dana@example.com",
permissions=["actions:execute:medium"],
tenant_id=TENANT_UUID,
)
@pytest.fixture(autouse=True)
def _clean_store():
action_store.clear()
yield
action_store.clear()
@pytest.fixture(autouse=True)
def _registered_builtins():
"""The live registry is populated at app startup; these tests build a bare
FastAPI app, so register the builtin adapters the way ``main`` does."""
register_builtin_executors(overwrite=True)
@pytest.fixture()
def client() -> TestClient:
app = FastAPI()
app.include_router(router_module.router, prefix="/api/v1")
app.dependency_overrides[require_service_auth] = lambda: None
return TestClient(app)
def _splunk_request(**overrides: Any) -> LiveActionRequest:
params = {
"splunk_url": "https://splunk.example:8089",
"splunk_token": "tok-1",
"query": SPL,
"schedule": "*/10 * * * *",
"severity": "high",
}
params.update(overrides.pop("params", {}))
return LiveActionRequest(
capability="sync_detection_rule",
vendor_id="splunk",
tenant_id=uuid4(),
target=RULE_NAME,
params=params,
requested_by="test@aisoc.internal",
**overrides,
)
def _seed_completed(result: LiveActionResult, *, action_type: str = "sync_detection_rule", target: str = RULE_NAME) -> str:
"""Persist the record the classic door would have written for ``result``.
``parameters`` is deliberately empty: the undo's credentials must come
from the request (where the API puts the tenant's stored integration),
and a test that seeded them into the record could not tell the two
sources apart.
"""
details = dict(result.details)
rollback_data = details.pop("rollback_data", {})
record = {
"id": str(result.request_id),
"tenant_id": TENANT,
"status": ActionStatus.COMPLETED,
"action_type": action_type,
"target": target,
"incident_id": str(uuid4()),
"parameters": {},
"output": details,
"rollback_data": rollback_data,
"requested_by_user_id": REQUESTER.user_id,
}
asyncio.run(action_store.save(record))
return record["id"]
def _execute_forward(splunk: _FakeSplunk) -> str:
"""Run the real Splunk arm against the fake vendor and persist the record."""
result = asyncio.run(SplunkSyncDetectionRule().execute(_splunk_request()))
assert result.status == LiveActionStatus.SUCCEEDED
assert splunk.searches[RULE_NAME]["search"].strip() == SPL
return _seed_completed(result)
def _record(action_id: str, tenant: str = TENANT) -> dict[str, Any]:
record = asyncio.run(action_store.get(action_id, tenant_id=tenant))
assert record is not None, f"no record stored for {action_id}"
return record
def _status_of(record: dict[str, Any]) -> str:
return str(getattr(record["status"], "value", record["status"]))
def _undo(client: TestClient, action_id: str, *, tenant: str = TENANT, **body: Any):
payload: dict[str, Any] = {
"auth_config": SPLUNK_AUTH_CONFIG,
"principal": REQUESTER.model_dump(mode="json"),
"requested_by": "user:rory@example.com",
}
payload.update(body)
return client.post(
f"/api/v1/actions/{action_id}/rollback",
json=payload,
headers={"X-Tenant-ID": tenant},
)
@pytest.fixture()
def splunk(monkeypatch: pytest.MonkeyPatch) -> _FakeSplunk:
fake = _FakeSplunk()
fake.searches[RULE_NAME] = {
"search": PRIOR_SPL,
"cron_schedule": "*/30 * * * *",
"alert.severity": "medium",
}
_wire_splunk(monkeypatch, fake)
return fake
class TestApprovalGoverned:
"""The reverse capability's contract grades the undo before anything runs."""
def test_an_analyst_tier_reversal_waits_for_an_approver(self, client: TestClient, splunk: _FakeSplunk):
"""sync_detection_rule's reverse is itself, declared analyst — the
undo must queue, the vendor must not be touched, and the record must
stay exactly as it was."""
action_id = _execute_forward(splunk)
writes_before = len(splunk.requests)
response = _undo(client, action_id)
assert response.status_code == 200
body = response.json()
assert body["status"] == "pending_approval"
assert body["reversed"] is False
assert body["requirement"] == "analyst"
assert splunk.requests[writes_before:] == [], "a queued undo must not touch the vendor"
assert _status_of(_record(action_id)) == "completed"
def test_a_bound_approver_releases_the_reversal(self, client: TestClient, splunk: _FakeSplunk):
"""The headline: executed forward through the real Splunk arm, undone
through the route, and the mock vendor shows the prior definition —
SPL and schedule both — restored."""
action_id = _execute_forward(splunk)
response = _undo(
client,
action_id,
approver=APPROVER.model_dump(mode="json"),
requester=REQUESTER.model_dump(mode="json"),
)
assert response.status_code == 200, response.json()
body = response.json()
assert body["status"] == "rolled_back"
assert body["reversed"] is True
assert splunk.searches[RULE_NAME]["search"].strip() == PRIOR_SPL
assert splunk.searches[RULE_NAME]["cron_schedule"] == "*/30 * * * *"
record = _record(action_id)
assert _status_of(record) == "rolled_back"
assert record["rolled_back_by"] == APPROVER.user_id
assert record["rolled_back_at"]
provenance = record["rollback"]
assert provenance["state"] == "reversed"
assert provenance["requested_by"] == "user:rory@example.com"
assert provenance["approved_by"] == APPROVER.user_id
assert provenance["vendor_id"] == "splunk"
def test_the_requester_cannot_approve_their_own_undo(self, client: TestClient, splunk: _FakeSplunk):
action_id = _execute_forward(splunk)
response = _undo(
client,
action_id,
approver=REQUESTER.model_dump(mode="json"),
requester=REQUESTER.model_dump(mode="json"),
)
assert response.status_code == 403
assert "duties" in response.json()["detail"].lower()
assert splunk.searches[RULE_NAME]["search"].strip() == SPL, "the refusal must come before the vendor"
def test_an_approver_without_the_permission_is_refused(self, client: TestClient, splunk: _FakeSplunk):
action_id = _execute_forward(splunk)
weak = ActionPrincipal(user_id="intern@example.com", permissions=["actions:read"], tenant_id=TENANT_UUID)
response = _undo(
client,
action_id,
approver=weak.model_dump(mode="json"),
requester=REQUESTER.model_dump(mode="json"),
)
assert response.status_code == 403
assert splunk.searches[RULE_NAME]["search"].strip() == SPL
def test_an_automatic_tier_reversal_runs_without_an_approver(
self,
client: TestClient,
monkeypatch: pytest.MonkeyPatch,
):
"""block_sender's reverse (unblock_sender) is low-impact and declared
automatic: at a tier that permits it, with confidence above the floor,
the undo runs with no approver bound — the same auto-allowed shape
forward dispatch grades through the same matrix."""
monkeypatch.setenv("AISOC_MATURITY_TIER", "L3")
calls: list[tuple[LiveActionResult, dict[str, Any] | None]] = []
class _CapturingAdapter:
vendor_id = "m365"
capability = "block_sender"
async def rollback(self, result: LiveActionResult, params: dict[str, Any] | None = None) -> bool:
calls.append((result, params))
return True
monkeypatch.setitem(registry._REGISTRY, ("m365", "block_sender"), (_CapturingAdapter(), "builtin"))
action_id = _seed_completed(
LiveActionResult(
request_id=uuid4(),
status=LiveActionStatus.SUCCEEDED,
capability="block_sender",
vendor_id="m365",
summary="blocked",
details={"rollback_data": {"vendor": "m365", "sender": "spoof@example.net"}},
),
action_type="block_sender",
target="spoof@example.net",
)
response = _undo(
client,
action_id,
auth_config={"tenant_id": "t", "client_id": "c", "client_secret": "s"},
confidence=0.95,
)
assert response.status_code == 200
body = response.json()
assert body["status"] == "rolled_back"
assert body["reversed"] is True
assert len(calls) == 1
result, _params = calls[0]
assert result.details["rollback_data"]["sender"] == "spoof@example.net"
assert _record(action_id)["rolled_back_by"] == REQUESTER.user_id
class TestStateGuards:
def test_an_action_that_never_executed_is_refused(self, client: TestClient, splunk: _FakeSplunk):
action_id = str(uuid4())
asyncio.run(
action_store.save(
{
"id": action_id,
"tenant_id": TENANT,
"status": ActionStatus.AWAITING_APPROVAL,
"action_type": "sync_detection_rule",
"target": RULE_NAME,
"incident_id": str(uuid4()),
"parameters": {},
}
)
)
response = _undo(client, action_id, approver=APPROVER.model_dump(mode="json"))
assert response.status_code == 409
assert "awaiting_approval" in response.json()["detail"]
def test_an_already_rolled_back_action_is_refused_with_the_reason(self, client: TestClient, splunk: _FakeSplunk):
action_id = _execute_forward(splunk)
first = _undo(
client,
action_id,
approver=APPROVER.model_dump(mode="json"),
requester=REQUESTER.model_dump(mode="json"),
)
assert first.json()["status"] == "rolled_back"
second = _undo(
client,
action_id,
approver=APPROVER.model_dump(mode="json"),
requester=REQUESTER.model_dump(mode="json"),
)
assert second.status_code == 409
assert "already" in second.json()["detail"].lower()
def test_a_record_that_captured_nothing_is_refused(self, client: TestClient, splunk: _FakeSplunk):
"""A simulation-mode forward action stores an empty rollback_data;
there is no state to restore and the route must say so rather than
guess a vendor."""
action_id = _seed_completed(
LiveActionResult(
request_id=uuid4(),
status=LiveActionStatus.SUCCEEDED,
capability="sync_detection_rule",
vendor_id="splunk",
summary="simulated",
details={},
)
)
response = _undo(client, action_id, approver=APPROVER.model_dump(mode="json"))
assert response.status_code == 422
assert "captured" in response.json()["detail"].lower()
def test_a_tenant_cannot_undo_another_tenants_action(self, client: TestClient, splunk: _FakeSplunk):
action_id = _execute_forward(splunk)
response = _undo(client, action_id, tenant=OTHER_TENANT, approver=APPROVER.model_dump(mode="json"))
assert response.status_code == 404
def test_a_caller_naming_no_tenant_is_refused(self, client: TestClient, splunk: _FakeSplunk):
action_id = _execute_forward(splunk)
response = client.post(
f"/api/v1/actions/{action_id}/rollback",
json={"auth_config": SPLUNK_AUTH_CONFIG},
)
assert response.status_code == 400
def test_a_verb_whose_reversal_cannot_take_credentials_is_refused_up_front(self, client: TestClient, splunk: _FakeSplunk):
"""isolate_host's legacy rollback takes no params, so per-call
credentials cannot reach it; the route refuses before grading rather
than queueing an approval for an undo that can never run."""
action_id = _seed_completed(
LiveActionResult(
request_id=uuid4(),
status=LiveActionStatus.SUCCEEDED,
capability="isolate_host",
vendor_id="crowdstrike",
summary="contained",
details={"rollback_data": {"vendor": "crowdstrike", "device_id": "dev-1"}},
),
action_type="isolate_host",
target="WKSTN-01",
)
response = _undo(client, action_id, approver=APPROVER.model_dump(mode="json"))
assert response.status_code == 422
assert "credential" in response.json()["detail"].lower()
class TestHonestOutcomes:
def test_a_vendor_refusal_is_a_failed_undo_never_a_success(
self,
client: TestClient,
monkeypatch: pytest.MonkeyPatch,
):
"""The action created the rule (no prior), so the reversal is a
delete; the vendor refuses it. The executor returns False and the
record must say the undo failed while the action stays in force."""
fake = _FakeSplunk(refuse_delete=True)
_wire_splunk(monkeypatch, fake)
action_id = _execute_forward(fake)
response = _undo(
client,
action_id,
approver=APPROVER.model_dump(mode="json"),
requester=REQUESTER.model_dump(mode="json"),
)
assert response.status_code == 200
body = response.json()
assert body["status"] == "undo_failed"
assert body["reversed"] is False
assert RULE_NAME in fake.searches, "the rule is still there; saying otherwise would be the lie this route exists to remove"
record = _record(action_id)
assert _status_of(record) == "completed", "a failed undo leaves the action in force and retryable"
assert record["rollback"]["state"] == "failed"
assert record.get("rolled_back_at") is None
def test_the_undo_outcome_is_audited_on_the_record(self, client: TestClient, splunk: _FakeSplunk):
"""Who asked, who approved, which action, which vendor, what the
executor answered — readable off the record afterwards."""
action_id = _execute_forward(splunk)
before = datetime.now(UTC).isoformat()
_undo(
client,
action_id,
approver=APPROVER.model_dump(mode="json"),
requester=REQUESTER.model_dump(mode="json"),
)
record = _record(action_id)
provenance = record["rollback"]
assert provenance["approved_by"] == APPROVER.user_id
assert provenance["requested_by"] == "user:rory@example.com"
assert provenance["vendor_id"] == "splunk"
assert provenance["state"] == "reversed"
assert provenance["requirement"] == "analyst"
assert record["rolled_back_at"] >= before
@@ -0,0 +1,142 @@
"""The console's door to reversing a completed response action.
Every destructive executor captures ``rollback_data`` and its contract names
a ``reverse_capability``, but no production surface could dispatch a
reversal. This route is the missing door, shaped like the forward one: it
authenticates a person, resolves the tenant's stored integration server-side,
and hands the governed decision to ``services/actions``, which grades the
reverse capability's contract and claims the reversal durably before any
vendor is contacted.
**The request carries no credentials, by construction.** The body refuses
unknown fields outright, so there is no key to put a token in — the vault and
the tenant's connector row are the only credential source, which is the same
property the playbook-step dispatch holds and the reason both live behind
this service.
**An undo the grading queues follows the forward approval flow.** It lands in
the approvals inbox as a pending row naming what would be reversed; deciding
it re-drives the reversal with the deciding identity bound as approver, and
the requester cannot approve their own undo.
"""
from __future__ import annotations
import uuid
from typing import Annotated, Any
import structlog
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, Field
from app.api.v1.deps import AuthUser, require_permission
from app.api.v1.endpoints.approvals import create_undo_approval
from app.db.rls import TenantDBSession
from app.services import action_undo
from app.services.audit import emit_audit
logger = structlog.get_logger(__name__)
router = APIRouter(prefix="/actions", tags=["actions"])
class ActionUndoRequest(BaseModel):
"""What a caller may say about an undo: how sure they are, and nothing else.
``extra="forbid"`` is the control, not a nicety. The reversal's
credentials come from the tenant's stored integration through the vault,
and the vendor comes from the action record itself — a body that could
carry either would let a caller steer a reversal somewhere it was never
aimed, so a request naming any other field is refused outright.
"""
model_config = {"extra": "forbid"}
#: How good the reason for reversing is, 0..1. An input to the reverse
#: capability's approval grading, exactly as forward dispatch takes it;
#: omitted means the lowest band, never a free pass.
confidence: float | None = Field(default=None, ge=0.0, le=1.0)
@router.post("/{action_id}/undo", summary="Reverse a completed response action")
async def undo_action(
action_id: uuid.UUID,
body: ActionUndoRequest | None,
user: Annotated[AuthUser, Depends(require_permission("actions:execute"))],
db: TenantDBSession,
request: Request,
) -> dict[str, Any]:
"""Reverse one completed action through its executor's own rollback.
The reversal is graded against the reverse capability's contract before
anything runs. The answer is always 200 with a status naming what
happened — ``rolled_back``, ``undo_failed`` (the vendor refused; the
action is still in force), ``pending_approval`` (queued in the approvals
inbox, ``approval_id`` included) or ``refused`` (the contract prohibits
the reversal). 4xx is reserved for requests that cannot be served at
all: an action that never executed or was already rolled back (409), a
verb the platform cannot reverse or a missing integration (422), an
action this tenant does not own (404).
"""
principal = {
"user_id": str(user.user_id),
"tenant_id": str(user.tenant_id),
"email": getattr(user, "email", None),
"roles": [user.role] if user.role else [],
"permissions": user.effective_permissions(),
}
requested_by = f"user:{user.email}" if getattr(user, "email", None) else f"user:{user.user_id}"
confidence = body.confidence if body else None
try:
report = await action_undo.drive_undo(
db,
tenant_id=user.tenant_id,
action_id=str(action_id),
principal=principal,
requested_by=requested_by,
confidence=confidence,
)
except action_undo.UndoNotPossible as refusal:
raise HTTPException(status_code=refusal.status_code, detail=refusal.detail) from refusal
payload = report.as_dict()
if report.status == "pending_approval":
approval = await create_undo_approval(
db,
user,
undo_of=str(action_id),
action_type=report.action_type,
target=report.target,
vendor_id=report.vendor_id,
confidence=confidence,
requirement=report.requirement,
reason=report.reason,
requested_by=requested_by,
)
payload["approval_id"] = str(approval.id)
await emit_audit(
db=db,
tenant_id=user.tenant_id,
actor_id=user.user_id,
actor_email=getattr(user, "email", None),
# Session vs API key must be distinguishable in the trail
# (check_audit_coverage): the prefix is None for a session.
api_key_prefix=getattr(user, "api_key_prefix", None),
action="actions:undo",
resource="action",
resource_id=str(action_id),
changes={
"status": report.status,
"reversed": report.reversed_,
"vendor_id": report.vendor_id,
"action_type": report.action_type,
"target": report.target,
"requirement": report.requirement,
"error": report.error or None,
"approval_id": payload.get("approval_id"),
},
request=request,
)
return payload
+145 -1
View File
@@ -37,11 +37,13 @@ import httpx
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field
from sqlalchemy import and_, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.deps import AuthUser, require_permission
from app.core.config import settings
from app.db.rls import TenantDBSession
from app.models.responder import AgentApproval
from app.services import action_undo
from app.services.actions_client import ActionsServiceError, decide_action, submit_action
from app.services.approval_delivery import deliver_approval
from app.services.branding.resolver import resolve_branding
@@ -119,6 +121,12 @@ class ApprovalDecisionRequest(BaseModel):
#: evaluated against it would be forgeable from the body.
_REQUESTER_KEY = "requester_principal"
#: ``action.kind`` for an approval that gates the *reversal* of a completed
#: action rather than a forward execution. Dispatching one re-drives the undo
#: with the deciding identity bound as approver; it never reaches
#: ``submit_action``, which would run the forward verb a second time.
_UNDO_KIND = "action_undo"
#: Dispatch states recorded on the approval row.
#:
#: ``dispatching`` is the one that did not exist. ``_dispatch_decision`` ran
@@ -491,7 +499,7 @@ async def decide_approval(
}
await db.commit()
dispatch = await _dispatch_decision(row, user, approve=body.decision == "approve")
dispatch = await _dispatch_decision(row, user, approve=body.decision == "approve", db=db)
row.action = {**(row.action or {}), "dispatch": dispatch}
await db.commit()
@@ -531,6 +539,7 @@ async def _dispatch_decision(
user: AuthUser,
*,
approve: bool,
db: AsyncSession | None = None,
) -> dict[str, Any]:
"""Carry a decision through to ``services/actions``.
@@ -549,8 +558,14 @@ async def _dispatch_decision(
processed; the actions service claims an execution
durably before contacting a vendor, so the answer
exists upstream and must be read rather than guessed.
``db`` is needed only for an undo approval, whose dispatch resolves the
tenant's connector credentials freshly at decide time — nothing secret
waits in the queue.
"""
action = row.action or {}
if action.get("kind") == _UNDO_KIND:
return await _dispatch_undo_decision(db, row, user, approve=approve)
action_type = action.get("action_type") or action.get("type")
target = action.get("target")
if not isinstance(action_type, str) or not action_type.strip():
@@ -646,6 +661,135 @@ async def _dispatch_decision(
}
async def _dispatch_undo_decision(
db: AsyncSession | None,
row: AgentApproval,
user: AuthUser,
*,
approve: bool,
) -> dict[str, Any]:
"""Carry a decision on a queued reversal through to the actions service.
A denial executes nothing and has nothing upstream to reject — unlike a
forward action, no pending record exists in the actions service; this row
*is* the queue. An approval re-drives the undo with the deciding
principal bound as approver and the stamped requester kept separate, so
separation of duties upstream compares two real identities; the actions
service re-grades the reverse capability and claims the reversal durably,
which is also what makes a double-decide safe.
"""
action = row.action or {}
undo_of = str(action.get("undo_of") or "")
if not undo_of:
return {"state": _DISPATCH_NOT_EXECUTABLE, "reason": "approval names no action to undo"}
if not approve:
return {"state": _DISPATCH_DECLINED, "undo_of": undo_of}
if db is None:
# Without a session there is no vault read and no connector row, so
# nothing could be dispatched honestly.
return {"state": _DISPATCH_FAILED, "stage": "undo", "undo_of": undo_of, "detail": "no database session to resolve credentials with"}
principal = {
"user_id": str(user.user_id),
"tenant_id": str(user.tenant_id),
"email": getattr(user, "email", None),
"roles": [user.role] if user.role else [],
"permissions": user.effective_permissions(),
}
requester = action.get(_REQUESTER_KEY)
if not isinstance(requester, dict) or not requester.get("user_id"):
requester = None
raw_confidence = action.get("confidence")
confidence = float(raw_confidence) if isinstance(raw_confidence, (int, float)) else None
try:
report = await action_undo.drive_undo(
db,
tenant_id=row.tenant_id,
action_id=undo_of,
principal=principal,
approver=principal,
requester=requester,
confidence=confidence,
requested_by=str(action.get("requested_by_label") or row.requested_by or "aisoc-api"),
)
except action_undo.UndoNotPossible as exc:
logger.warning(
"Undo approval dispatch refused",
extra={"approval_id": str(row.id), "undo_of": undo_of, "status": exc.status_code, "detail": exc.detail},
)
state = _DISPATCH_UNKNOWN if exc.indeterminate else _DISPATCH_FAILED
return {"state": state, "stage": "undo", "undo_of": undo_of, "detail": exc.detail}
if report.status == "rolled_back":
return {
"state": _DISPATCH_EXECUTED,
"undo_of": undo_of,
"action_status": "rolled_back",
"vendor_id": report.vendor_id,
}
return {
"state": _DISPATCH_FAILED,
"stage": "undo",
"undo_of": undo_of,
"detail": report.error or report.reason or f"the reversal answered {report.status!r}",
}
async def create_undo_approval(
db: AsyncSession,
user: AuthUser,
*,
undo_of: str,
action_type: str,
target: str,
vendor_id: str,
confidence: float | None,
requirement: str,
reason: str,
requested_by: str,
) -> AgentApproval:
"""Queue a reversal the reverse capability's grading held for a human.
The forward flow's own shape: the durable queue for a decision is this
table, the decision arrives through ``/{id}/decide``, and the dispatch is
re-driven at decide time with the deciding identity bound — which is also
when credentials are freshly resolved, so nothing secret ever waits in a
queue. The requester is stamped from authenticated context exactly as
:func:`create_approval` stamps it, which is what lets separation of
duties refuse the asker approving their own undo.
"""
row = AgentApproval(
tenant_id=user.tenant_id,
requested_by=requested_by[:120],
title=f"Undo {action_type} on {target}"[:200],
summary=reason or f"Reversing '{action_type}' on {target} requires {requirement} approval.",
risk_level="high" if requirement == "mandatory_human" else "medium",
action={
"kind": _UNDO_KIND,
"undo_of": undo_of,
"action_type": action_type,
"target": target,
"vendor_id": vendor_id,
"confidence": confidence,
"requested_by_label": requested_by,
_REQUESTER_KEY: _requester_principal(user),
},
status="pending",
)
db.add(row)
await db.commit()
await db.refresh(row)
await _notify_realtime(row, event="approval_request")
delivery = await deliver_approval(row, await resolve_branding(db, user.tenant_id))
row.action = {**(row.action or {}), "delivery": delivery.as_dict()}
await db.commit()
await db.refresh(row)
return row
async def _notify_realtime(row: AgentApproval, *, event: str) -> None:
"""Fan out an agent event to the realtime service.
+8
View File
@@ -5,6 +5,7 @@ from fastapi import APIRouter
from app.api.v1.endpoints import (
access_conditions,
access_review,
action_undo,
admin_users,
agent_tools,
agents,
@@ -253,8 +254,15 @@ api_router.include_router(effective_permissions.router)
# credential. `app/services/email_approval.py` had minted URLs pointing at
# /v1/actions/email-decide, which no router served, so every approve and deny
# button in a rendered email linked to a 404.
#
# Registered before the undo route so the literal /actions/email-decide
# segment is matched ahead of /actions/{action_id}/... parameters.
api_router.include_router(email_approval.router)
# Reversal of a completed response action: resolves the tenant's stored
# integration server-side and drives the actions service's governed rollback.
api_router.include_router(action_undo.router)
# Cost dashboard — WS-H1 (buyer-value plan).
# Aggregates LLM spend / token volume from aisoc_run_costs joined with
# investigation_runs, plus action counts from audit_log and BYOK savings
+263
View File
@@ -0,0 +1,263 @@
"""Drive the reversal of a completed action through the actions service.
The executors capture ``rollback_data`` on every destructive verb and the
capability contracts name a ``reverse_capability`` for each platform-reversible
one, but nothing in production could dispatch a reversal. This module is the
API's half of the undo path, and it decides the same two things the
playbook-step dispatch decides for a forward action — **which connector** and
**which credentials** — because those are tenant facts and this is the only
service that can read them. Whether the undo may run is decided where the
contract lives: ``services/actions`` grades the reverse capability and claims
the reversal durably before any vendor is contacted.
Two hard rules, inherited from the forward hop:
* Credentials are resolved from the tenant's stored integration through the
vault, per call, at the moment of dispatch — never from the caller's
request (the route's body cannot carry them) and never from the stored
action record (the executors never put them there).
* The vendor is a fact of the record, not a choice. The reversal goes to the
vendor the action executed against; a record that does not name one is
refused rather than guessed at.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
import structlog
from sqlalchemy.ext.asyncio import AsyncSession
from app._vendor.action_contracts.capability_contracts import contract_for_action_type
from app.security.credential_vault import CredentialVaultError, get_vault
from app.services import actions_client
from app.services.playbook_step_dispatch import _operational_config, _pick_connector
logger = structlog.get_logger(__name__)
#: Upstream refusals whose status and reason are the caller's to see. These
#: are statements about the undo request itself — the action never executed,
#: it was already rolled back, the verb has no platform reverse — and
#: flattening them into a 502 would hide exactly the sentence the operator
#: needs.
_PASSTHROUGH_STATUSES: frozenset[int] = frozenset({400, 403, 404, 409, 422})
class UndoNotPossible(Exception):
"""This undo request cannot be served, with the HTTP status naming why."""
def __init__(self, status_code: int, detail: str, *, indeterminate: bool = False) -> None:
super().__init__(detail)
self.status_code = status_code
self.detail = detail
#: True when the actions service may have acted and never answered.
#: A decide path records this as "unknown" rather than "failed",
#: because the reversal is claimed durably upstream and the answer
#: exists there to be read.
self.indeterminate = indeterminate
@dataclass(frozen=True)
class UndoDispatchReport:
"""What actually happened to one undo request, in one shape.
``reversed_`` is the single field that means the vendor's state was
restored. A queued approval, a contract refusal and a vendor refusal are
all ``False``, each naming which one it was — the same honesty contract
the playbook-step report keeps for forward actions.
"""
action_id: str
status: str # rolled_back | undo_failed | pending_approval | refused
reversed_: bool
action_type: str = ""
target: str = ""
vendor_id: str = ""
requirement: str = ""
reason: str = ""
summary: str = ""
error: str = ""
rolled_back_at: str = ""
rolled_back_by: str = ""
def as_dict(self) -> dict[str, Any]:
out: dict[str, Any] = {
"action_id": self.action_id,
"status": self.status,
"reversed": self.reversed_,
"summary": self.summary,
}
for key in ("action_type", "target", "vendor_id", "requirement", "reason", "error", "rolled_back_at", "rolled_back_by"):
value = getattr(self, key)
if value:
out[key] = value
return out
async def _load_record(action_id: str, tenant_id: str) -> dict[str, Any]:
try:
return await actions_client.get_action(action_id=action_id, tenant_id=tenant_id)
except actions_client.ActionsServiceError as exc:
raise _translated(exc) from exc
def _translated(exc: actions_client.ActionsServiceError) -> UndoNotPossible:
if exc.status_code in _PASSTHROUGH_STATUSES:
return UndoNotPossible(exc.status_code or 502, exc.upstream_detail, indeterminate=exc.indeterminate)
return UndoNotPossible(
502,
exc.upstream_detail
if exc.status_code
else "The action service is unreachable. It runs in the `full` and `chatops` compose profiles.",
indeterminate=exc.indeterminate,
)
async def _resolve_reversal_credentials(
db: AsyncSession,
*,
tenant_id: Any,
record: dict[str, Any],
) -> tuple[str, dict[str, Any]]:
"""``(vendor_id, auth_config)`` for the vendor this record executed against.
The vendor comes from the record's own ``rollback_data`` (stamped by the
executor at capture time) with the execution output as fallback. The
connector lookup is the forward hop's own: enabled, owned by this tenant,
not downscoped away from the reverse verb.
"""
rollback_data = record.get("rollback_data") or {}
output = record.get("output") or {}
vendor_id = str(
(rollback_data.get("vendor") if isinstance(rollback_data, dict) else "")
or (output.get("vendor") if isinstance(output, dict) else "")
or ""
)
if not vendor_id:
raise UndoNotPossible(
422,
"the action record does not name the vendor it executed against, so no stored integration can be resolved for the reversal",
)
# The verb being performed now is the reverse capability; a tenant that
# downscoped it off this connector has said "not this verb here", and an
# undo does not outrank that any more than a playbook step does.
contract = contract_for_action_type(str(record.get("action_type") or ""))
reverse_capability = (contract.reverse_capability if contract else "") or str(record.get("action_type") or "")
connector = await _pick_connector(
db,
tenant_id=tenant_id,
capability=reverse_capability,
implementers=[vendor_id],
pinned="",
)
if connector is None:
raise UndoNotPossible(
422,
f"this tenant has no enabled {vendor_id} connector that may perform "
f"'{reverse_capability}', so the reversal has no credentials to run with",
)
try:
auth_config = get_vault().decrypt_dict(connector.auth_config or {})
except CredentialVaultError as exc:
# Reported, never downgraded: an undo that silently ran without
# credentials would be recorded as a vendor refusal, which sends the
# operator to the wrong console. Same rule as the forward hop.
logger.warning("action_undo.credentials_undecryptable", vendor_id=vendor_id)
raise UndoNotPossible(
503,
f"credentials for {vendor_id} could not be decrypted, so the reversal did not run",
) from exc
auth_config.update(_operational_config(connector))
return vendor_id, auth_config
def _interpret(action_id: str, record: dict[str, Any], body: dict[str, Any]) -> UndoDispatchReport:
"""Translate the actions service's answer into the report shape.
An unrecognised status is a failure, not a success — the actions service
owns this vocabulary, and a new member arriving here means this reader
is behind.
"""
status = str(body.get("status") or "")
common = {
"action_id": action_id,
"action_type": str(record.get("action_type") or ""),
"target": str(record.get("target") or ""),
"vendor_id": str(body.get("vendor_id") or ""),
"requirement": str(body.get("requirement") or ""),
"reason": str(body.get("reason") or ""),
"summary": str(body.get("summary") or ""),
}
if status == "rolled_back":
return UndoDispatchReport(
**common,
status="rolled_back",
reversed_=bool(body.get("reversed")),
rolled_back_at=str(body.get("rolled_back_at") or ""),
rolled_back_by=str(body.get("rolled_back_by") or ""),
)
if status in ("undo_failed", "pending_approval", "refused"):
return UndoDispatchReport(
**common,
status=status,
reversed_=False,
error=str(body.get("error") or ""),
)
logger.warning("action_undo.unrecognised_status", status=status, action_id=action_id)
return UndoDispatchReport(
**common,
status="undo_failed",
reversed_=False,
error=f"the action service answered an unrecognised status {status!r}; treated as not reversed",
)
async def drive_undo(
db: AsyncSession,
*,
tenant_id: Any,
action_id: str,
principal: dict[str, Any],
requested_by: str,
confidence: float | None = None,
approver: dict[str, Any] | None = None,
requester: dict[str, Any] | None = None,
) -> UndoDispatchReport:
"""Load the record, resolve the tenant's credentials, and dispatch the reversal.
Called from two places with the same body and different identities: the
undo route (no ``approver`` — a reversal the grading queues comes back
``pending_approval``) and the approval decide path (``approver`` is the
deciding principal, ``requester`` the stamped originator, so separation
of duties upstream has two identities to compare).
"""
record = await _load_record(action_id, str(tenant_id))
vendor_id, auth_config = await _resolve_reversal_credentials(db, tenant_id=tenant_id, record=record)
try:
body = await actions_client.undo_action(
action_id=action_id,
tenant_id=str(tenant_id),
auth_config=auth_config,
principal=principal,
approver=approver,
requester=requester,
confidence=confidence,
requested_by=requested_by,
)
except actions_client.ActionsServiceError as exc:
raise _translated(exc) from exc
report = _interpret(action_id, record, body)
logger.info(
"action_undo.dispatched",
action_id=action_id,
vendor_id=vendor_id,
status=report.status,
reversed=report.reversed_,
)
return report
+72 -4
View File
@@ -18,6 +18,7 @@ from __future__ import annotations
import re
from typing import Any
from uuid import UUID
import httpx
import structlog
@@ -86,11 +87,12 @@ def service_headers() -> dict[str, str]:
return headers
async def _post(path: str, payload: dict[str, Any] | None) -> dict[str, Any]:
async def _post(path: str, payload: dict[str, Any] | None, extra_headers: dict[str, str] | None = None) -> dict[str, Any]:
url = f"{base_url()}{path}"
headers = {**service_headers(), **(extra_headers or {})}
try:
async with httpx.AsyncClient(timeout=_TIMEOUT_SECONDS) as client:
response = await client.post(url, headers=service_headers(), json=payload)
response = await client.post(url, headers=headers, json=payload)
except httpx.ConnectError as exc:
# Nothing was written to a socket, so nothing was processed.
raise ActionsServiceError(f"actions service unreachable: {exc}") from exc
@@ -112,11 +114,12 @@ async def _post(path: str, payload: dict[str, Any] | None) -> dict[str, Any]:
return body
async def _get(path: str) -> Any:
async def _get(path: str, extra_headers: dict[str, str] | None = None) -> Any:
url = f"{base_url()}{path}"
headers = {**service_headers(), **(extra_headers or {})}
try:
async with httpx.AsyncClient(timeout=_TIMEOUT_SECONDS) as client:
response = await client.get(url, headers=service_headers())
response = await client.get(url, headers=headers)
except httpx.HTTPError as exc:
raise ActionsServiceError(f"actions service unreachable: {exc}") from exc
if response.status_code >= 400:
@@ -128,6 +131,20 @@ async def _get(path: str) -> Any:
raise ActionsServiceError("actions service returned a non-JSON body") from exc
def _action_id_segment(action_id: str) -> str:
"""An action id safe to interpolate into the upstream path.
Action ids are UUIDs minted by this platform. Parsing rather than
pattern-matching refuses anything else before it can steer a request
carrying the service token somewhere it was not aimed — the same guard
the capability identifier gets.
"""
try:
return str(UUID(str(action_id)))
except ValueError as exc:
raise ActionsServiceError(f"{action_id!r} is not an action id") from exc
#: Capability verbs are short identifiers from a closed vocabulary. This one
#: is interpolated into an upstream path that carries the service token, so
#: it is checked here rather than trusted — the same guard the browser-facing
@@ -256,6 +273,57 @@ async def decide_action(
return await _post(f"/api/v1/actions/{action_id}/{verb}", body or None)
async def get_action(*, action_id: str, tenant_id: str) -> dict[str, Any]:
"""Read one action record, tenant-narrowed.
The tenant travels on the header the actions service reads for its
scoped read; a caller that owns the record gets it whole — including
``rollback_data`` and the vendor it executed against — and one that does
not gets the same 404 as for a record that never existed.
"""
safe_id = _action_id_segment(action_id)
body = await _get(f"/api/v1/actions/{safe_id}", extra_headers={"X-Tenant-ID": tenant_id})
if not isinstance(body, dict):
raise ActionsServiceError("actions service returned an unexpected body shape")
return body
async def undo_action(
*,
action_id: str,
tenant_id: str,
auth_config: dict[str, Any] | None = None,
principal: dict[str, Any] | None = None,
approver: dict[str, Any] | None = None,
requester: dict[str, Any] | None = None,
confidence: float | None = None,
requested_by: str = "aisoc-api",
) -> dict[str, Any]:
"""Ask the actions service to reverse one completed action.
``auth_config`` carries the tenant's decrypted connector credentials in
connector-schema field names, exactly as :func:`dispatch_live_action`
sends them for a forward execution; the actions service translates them
at its boundary and they are never persisted anywhere. ``approver`` is
sent only when a queued undo has been decided — the actions service
grades the reverse capability itself and binds the approver under
separation of duties against ``requester``.
"""
safe_id = _action_id_segment(action_id)
payload: dict[str, Any] = {"requested_by": requested_by}
if auth_config:
payload["auth_config"] = auth_config
if principal is not None:
payload["principal"] = principal
if approver is not None:
payload["approver"] = approver
if requester is not None:
payload["requester"] = requester
if confidence is not None:
payload["confidence"] = confidence
return await _post(f"/api/v1/actions/{safe_id}/rollback", payload, extra_headers={"X-Tenant-ID": tenant_id})
async def dispatch_live_action(
*,
capability: str,
+369
View File
@@ -0,0 +1,369 @@
"""``POST /actions/{action_id}/undo``: the user-facing door to a reversal.
This layer decides two things and no more — which connector holds the
credentials for the vendor the action executed against, and where a reversal
that needs a human goes to wait — exactly the split the playbook-step
dispatch draws. Whether the undo may run belongs to ``services/actions``,
which grades the reverse capability's contract.
The load-bearing assertions:
* credentials come from the tenant's stored integration through the vault,
never from the request — the request body cannot even carry them, because
unknown fields are refused;
* an undo the grading queues lands in the approvals inbox, and the decide
path re-drives it with the deciding identity bound as the approver;
* every outcome is audited with who asked, which action, and what the
reversal answered.
"""
from __future__ import annotations
import uuid
from types import SimpleNamespace
from typing import Any, cast
import pytest
from app.api.v1.deps import CurrentUser
from app.api.v1.endpoints import action_undo as endpoint_module
from app.api.v1.endpoints import approvals as approvals_module
from app.models.responder import AgentApproval
from app.services import action_undo as service_module
from app.services import actions_client
from fastapi import Request
from pydantic import ValidationError
from sqlalchemy.ext.asyncio import AsyncSession
pytestmark = pytest.mark.asyncio
TENANT = uuid.uuid4()
ACTION_ID = str(uuid.uuid4())
def _user(**overrides: Any) -> CurrentUser:
base: dict[str, Any] = {
"user_id": uuid.uuid4(),
"tenant_id": TENANT,
"role": "analyst",
"email": "rory@example.com",
"resolved_permissions": frozenset({"actions:execute", "actions:execute:medium", "cases:write"}),
}
base.update(overrides)
return CurrentUser(**base)
def _stored_record(**overrides: Any) -> dict[str, Any]:
record = {
"id": ACTION_ID,
"tenant_id": str(TENANT),
"status": "completed",
"action_type": "sync_detection_rule",
"target": "AiSOC - brute force by user",
"output": {"vendor": "splunk", "rule_name": "AiSOC - brute force by user"},
"rollback_data": {"vendor": "splunk", "name": "AiSOC - brute force by user", "prior": {"search": "index=main"}},
"parameters": {},
}
record.update(overrides)
return record
class _Connector:
connector_type = "splunk"
name = "splunk"
auth_config = {"token": "vault:v1:ciphertext"}
connector_config = {"base_url": "https://splunk.example:8089"}
allowed_capabilities = None
class _Vault:
def decrypt_dict(self, blob: dict) -> dict:
return {"token": "decrypted-from-vault"}
def _wire(
monkeypatch: pytest.MonkeyPatch,
*,
record: dict[str, Any] | None = None,
connector: Any = _Connector(),
upstream: dict[str, Any] | Exception | None = None,
) -> list[dict[str, Any]]:
"""Stand in for the actions service, the tenant database and the vault."""
sent: list[dict[str, Any]] = []
async def _get_action(**kwargs: Any) -> dict[str, Any]:
if record is None:
raise actions_client.ActionsServiceError("Action not found", status_code=404, upstream_detail="Action not found")
return record
async def _undo_action(**kwargs: Any) -> dict[str, Any]:
sent.append(kwargs)
if isinstance(upstream, Exception):
raise upstream
return upstream or {
"action_id": kwargs["action_id"],
"status": "rolled_back",
"reversed": True,
"vendor_id": "splunk",
"rolled_back_at": "2026-11-22T00:00:00+00:00",
"rolled_back_by": "rory@example.com",
}
async def _pick(db: Any, *, tenant_id: Any, capability: str, implementers: list[str], pinned: str) -> Any:
return connector
monkeypatch.setattr(actions_client, "get_action", _get_action, raising=False)
monkeypatch.setattr(actions_client, "undo_action", _undo_action, raising=False)
monkeypatch.setattr(service_module, "_pick_connector", _pick)
monkeypatch.setattr(service_module, "get_vault", _Vault)
return sent
class _AuditSpy:
def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None:
self.calls: list[dict[str, Any]] = []
async def _emit(**kwargs: Any) -> None:
self.calls.append(kwargs)
monkeypatch.setattr(endpoint_module, "emit_audit", _emit)
async def _call_route(
monkeypatch: pytest.MonkeyPatch,
*,
user: CurrentUser | None = None,
body: endpoint_module.ActionUndoRequest | None = None,
) -> dict[str, Any]:
return await endpoint_module.undo_action(
action_id=uuid.UUID(ACTION_ID),
body=body,
user=user or _user(),
# Stand-ins: the seams underneath (connector pick, vault, actions
# client, audit) are monkeypatched, so nothing reads past the type.
db=cast(AsyncSession, SimpleNamespace()),
request=cast(Request, None),
)
class TestCredentialsComeFromTheStoredIntegration:
async def test_the_vault_not_the_request_supplies_the_credentials(self, monkeypatch: pytest.MonkeyPatch):
"""The request body carries nothing credential-shaped; what reaches
the actions service is the vault's decrypted connector config plus
the connector's operational settings."""
sent = _wire(monkeypatch, record=_stored_record())
_AuditSpy(monkeypatch)
report = await _call_route(monkeypatch)
assert report["status"] == "rolled_back"
assert len(sent) == 1
auth_config = sent[0]["auth_config"]
assert auth_config["token"] == "decrypted-from-vault"
assert auth_config["base_url"] == "https://splunk.example:8089"
assert sent[0]["tenant_id"] == str(TENANT)
async def test_a_credential_bearing_body_is_refused(self):
"""Unknown fields are refused outright, so there is no way to smuggle
a credential or a destination through this route."""
with pytest.raises(ValidationError):
endpoint_module.ActionUndoRequest(splunk_token="tok-1")
with pytest.raises(ValidationError):
endpoint_module.ActionUndoRequest(auth_config={"token": "tok-1"})
async def test_a_tenant_without_the_connector_is_told_so(self, monkeypatch: pytest.MonkeyPatch):
_wire(monkeypatch, record=_stored_record(), connector=None)
_AuditSpy(monkeypatch)
with pytest.raises(Exception) as excinfo:
await _call_route(monkeypatch)
assert getattr(excinfo.value, "status_code", None) == 422
assert "splunk" in str(getattr(excinfo.value, "detail", ""))
class TestApprovalFlow:
async def test_a_queued_undo_lands_in_the_approvals_inbox(self, monkeypatch: pytest.MonkeyPatch):
_wire(
monkeypatch,
record=_stored_record(),
upstream={
"action_id": ACTION_ID,
"status": "pending_approval",
"reversed": False,
"requirement": "analyst",
"reason": "The action's contract requires analyst approval even at 95% confidence.",
"vendor_id": "splunk",
},
)
_AuditSpy(monkeypatch)
created: list[dict[str, Any]] = []
async def _create(db: Any, user: Any, **kwargs: Any) -> Any:
created.append(kwargs)
return SimpleNamespace(id=uuid.UUID("99999999-9999-9999-9999-999999999999"))
monkeypatch.setattr(endpoint_module, "create_undo_approval", _create)
report = await _call_route(monkeypatch)
assert report["status"] == "pending_approval"
assert report["reversed"] is False
assert report["approval_id"] == "99999999-9999-9999-9999-999999999999"
assert len(created) == 1
assert created[0]["undo_of"] == ACTION_ID
assert created[0]["action_type"] == "sync_detection_rule"
async def test_the_decide_path_re_drives_the_undo_with_the_deciding_identity(self, monkeypatch: pytest.MonkeyPatch):
"""Approving the queued undo carries the decision through with the
decider bound as approver and the stamped requester kept separate —
the same identity split the forward decide path sends."""
driven: list[dict[str, Any]] = []
async def _drive(db: Any, **kwargs: Any) -> Any:
driven.append(kwargs)
return SimpleNamespace(
status="rolled_back",
reversed_=True,
vendor_id="splunk",
error="",
as_dict=lambda: {"status": "rolled_back"},
)
monkeypatch.setattr(service_module, "drive_undo", _drive)
requester_stamp = {"user_id": str(uuid.uuid4()), "tenant_id": str(TENANT), "permissions": ["actions:execute:medium"]}
row = SimpleNamespace(
id=uuid.uuid4(),
tenant_id=TENANT,
run_id=None,
summary="undo it",
title="Undo sync_detection_rule",
requested_by="user:rory@example.com",
action={
"kind": "action_undo",
"undo_of": ACTION_ID,
"action_type": "sync_detection_rule",
"target": "AiSOC - brute force by user",
"confidence": 0.95,
approvals_module._REQUESTER_KEY: requester_stamp,
},
)
decider = _user(email="dana@example.com")
dispatch = await approvals_module._dispatch_decision(
cast(AgentApproval, row), decider, approve=True, db=cast(AsyncSession, SimpleNamespace())
)
assert dispatch["state"] == approvals_module._DISPATCH_EXECUTED
assert len(driven) == 1
assert driven[0]["action_id"] == ACTION_ID
assert driven[0]["approver"]["user_id"] == str(decider.user_id)
assert driven[0]["requester"] == requester_stamp
assert driven[0]["confidence"] == 0.95
async def test_a_denied_undo_executes_nothing(self, monkeypatch: pytest.MonkeyPatch):
async def _drive(db: Any, **kwargs: Any) -> Any: # pragma: no cover - must not be called
raise AssertionError("a denial must not reach the actions service")
monkeypatch.setattr(service_module, "drive_undo", _drive)
row = SimpleNamespace(
id=uuid.uuid4(),
tenant_id=TENANT,
run_id=None,
summary="undo it",
title="Undo sync_detection_rule",
requested_by="user:rory@example.com",
action={"kind": "action_undo", "undo_of": ACTION_ID},
)
dispatch = await approvals_module._dispatch_decision(
cast(AgentApproval, row), _user(), approve=False, db=cast(AsyncSession, SimpleNamespace())
)
assert dispatch["state"] == approvals_module._DISPATCH_DECLINED
async def test_a_failed_redriven_undo_is_reported_failed(self, monkeypatch: pytest.MonkeyPatch):
async def _drive(db: Any, **kwargs: Any) -> Any:
return SimpleNamespace(
status="undo_failed",
reversed_=False,
vendor_id="splunk",
error="the vendor refused the delete",
as_dict=lambda: {"status": "undo_failed"},
)
monkeypatch.setattr(service_module, "drive_undo", _drive)
row = SimpleNamespace(
id=uuid.uuid4(),
tenant_id=TENANT,
run_id=None,
summary="undo it",
title="Undo sync_detection_rule",
requested_by="user:rory@example.com",
action={"kind": "action_undo", "undo_of": ACTION_ID},
)
dispatch = await approvals_module._dispatch_decision(
cast(AgentApproval, row), _user(), approve=True, db=cast(AsyncSession, SimpleNamespace())
)
assert dispatch["state"] == approvals_module._DISPATCH_FAILED
assert "refused" in dispatch["detail"]
class TestHonestReporting:
async def test_a_vendor_refusal_reaches_the_caller_as_a_failed_undo(self, monkeypatch: pytest.MonkeyPatch):
_wire(
monkeypatch,
record=_stored_record(),
upstream={
"action_id": ACTION_ID,
"status": "undo_failed",
"reversed": False,
"vendor_id": "splunk",
"error": "the executor reported the reversal did not run (vendor refusal or missing reversal state)",
},
)
_AuditSpy(monkeypatch)
report = await _call_route(monkeypatch)
assert report["status"] == "undo_failed"
assert report["reversed"] is False
assert "did not run" in report["error"]
async def test_upstream_state_refusals_keep_their_reason(self, monkeypatch: pytest.MonkeyPatch):
_wire(
monkeypatch,
record=_stored_record(),
upstream=actions_client.ActionsServiceError(
"409",
status_code=409,
upstream_detail="this action was already rolled back at 2026-11-21 by dana; there is nothing left to undo",
),
)
_AuditSpy(monkeypatch)
with pytest.raises(Exception) as excinfo:
await _call_route(monkeypatch)
assert getattr(excinfo.value, "status_code", None) == 409
assert "already rolled back" in str(getattr(excinfo.value, "detail", ""))
async def test_the_outcome_is_audited(self, monkeypatch: pytest.MonkeyPatch):
_wire(monkeypatch, record=_stored_record())
audit = _AuditSpy(monkeypatch)
user = _user()
await _call_route(monkeypatch, user=user)
assert len(audit.calls) == 1
entry = audit.calls[0]
assert entry["action"] == "actions:undo"
assert entry["resource"] == "action"
assert entry["resource_id"] == ACTION_ID
assert entry["actor_id"] == user.user_id
changes = entry["changes"]
assert changes["status"] == "rolled_back"
assert changes["reversed"] is True
assert changes["vendor_id"] == "splunk"