feat(actions): revoke_file_share across Drive, Graph, Box and Dropbox (WS4.5) (#2006)

## What

WS4.5 of the gap-closure program. A leaked document's blast radius is
its sharing grants, and the product had no verb for them — no executor
touched Google Drive, OneDrive/SharePoint, Box or Dropbox permissions at
all. This adds **`revoke_file_share`**: one capability, four vendor
arms, under the full action-governance contract.

## Design

- **One executor, four arms** (`executors/fileshare.py`), vendor
selected by which credentials appear — the registry answers "who can
revoke a file share?" with four concrete vendors (`google_workspace`,
`m365`, `box`, `dropbox`).
- **New clients** (`clients/fileshare_clients.py`), each method shape
taken from the vendor's published reference (cited per class): Drive v3
permissions (`supportsAllDrives` on every call;
`sendNotificationEmail=false` on restores), Graph driveItem permissions
(restore via `invite` with `sendInvitation=false` / `createLink`), Box
collaborations + the file's `shared_link` field, Dropbox `sharing/*`
RPCs (`quiet: true` on restores). The Google client reuses the existing
Workspace JWT mint with a Drive-scoped token (domain-wide delegation
authorizes per scope list, so it must be a separate grant — one-line
seam in the existing client, subclass owns its scopes).
- **Scoping**: `revoke=grantee` (requires `grantee_email`) / `links` /
`all` — ownership always survives, per-vendor owner-role tables.
- **The contract's three properties**, per vendor:
1. **Capture before write** — none of these APIs has a permissions
recycle bin; the pre-write listing is the only record of what to
restore, and it travels in `rollback_data`.
2. **Read-back verification** — the grant list is re-read after the
revocation and the action **fails naming what it still sees** if a
revoked grant is still present. A 2xx on the DELETE is the vendor
accepting the request, not the estate changing.
3. **Real rollback** — restores through each vendor's own re-grant
shape; returns `False` on refusal. The one honest limit is stated, not
papered over: **Graph, Box and Dropbox mint a new URL when a sharing
link is re-created** (vendor fact, recorded in the clients), so a link
rollback restores access shape and the result says so; Drive's `anyone`
grant is an ordinary permission and restores exactly.
- **Governance**: ANALYST approval on both doors
(`APPROVAL_REQUIRED_ACTIONS` + the capability contract —
`test_approval_doors_agree` holds them level), blast radius MEDIUM,
declared verification probe with a registered independent verifier
(`_probe_revoke_file_share`), `dry_run` strips credentials so the vendor
sees zero requests, nothing-matched is a **failure**, never a silent
success.

## Testing

`test_revoke_file_share_vendor_arms.py` — **14 cases** through the real
executor, clients and builtins against stateful mock vendors:
capture-before-write is the observed request order; a frozen "lying
vendor" (204 on DELETE, grant still listed) fails the action; scoping
spares the owner; rollback restores per vendor (Graph invite without
mail, Box collaboration, Dropbox quiet add, Drive exact permission; link
restores logged as new-URL); missing `drive_id` on the Graph arm is
refused; the probe answers gone/present/unverifiable.

**Negative controls (applied, observed failing, restored):**
1. Skipping the read-back comparison on the Drive arm →
`test_a_lying_vendor_fails_the_action` fails (the 204 is believed).
2. `rollback` returning `True` without acting (the exact WS1.1 defect
shape) → 5 rollback cases fail.

## Ratchets & gates

Full actions suite **2,116 passed** · connectors suite 2,025 passed
(Capability enum gained the mirror member) · builtin count pin 168 →
**172** + 4 canonical pairs · `docs/audit/executor-arms.json`
regenerated via `check_executor_arm_count.py --write` (172 arms / 67
verbs / 40 vendors) · `check_action_contract` OK (180 contracts
coherent) · vendored contracts synced
(`sync_vendored_action_contracts.py`) · `check_module_reachability` OK ·
mypy baseline OK · ruff clean · claim matrix +1 GATED row, tallies
recomputed by the script.

## Could not verify

No live tenant for any of the four vendors — the arms are proven against
mock vendors through the real clients' request construction (the same
standard WS1.1's `sync_detection_rule` arms set). Request/response
shapes follow each vendor's published reference, cited in the client
docstrings.
This commit is contained in:
Beenu Arora
2026-11-22 17:34:39 -08:00
committed by GitHub
parent fd7b246c24
commit 922b0c641e
18 changed files with 1583 additions and 10 deletions
+22
View File
@@ -86,6 +86,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
default honestly (it had claimed "subscribes to all five content types")
and names the stricter `ActivityFeed.ReadDlp` permission that
sensitive-data details require.
- **`revoke_file_share`: a leaked document's sharing grants are now a
governed action across all four file-sharing estates** (WS4.5 of the
gap-closure program) — Google Drive, OneDrive/SharePoint (Microsoft
Graph), Box and Dropbox, as four arms of one capability. The contract's
three properties, proven per vendor against stateful mock servers
(`test_revoke_file_share_vendor_arms.py`, 14 cases): prior grants are
**captured before every write** (none of these APIs has a permissions
recycle bin — the pre-write listing is the only record of what to
restore); the write is **verified by read-back**, so a vendor answering
2xx on the DELETE while still listing the grant fails the action naming
what it still sees; and **rollback restores the captured grants**
through each vendor's own re-grant shape (Graph invite without mail,
Box collaboration, Dropbox quiet add, Drive exact permission) —
returning False when the vendor refuses, and stating the one honest
limit instead of papering over it: Graph, Box and Dropbox mint a *new
URL* when a sharing link is re-created, so a link rollback restores
access shape, never the circulating URL (Drive's `anyone` grant is an
ordinary permission and restores exactly). ANALYST approval on both
governance doors; `grantee`/`links`/`all` scoping always spares
ownership; a dry run strips credentials so the vendor sees zero
requests; nothing-matched is a failure, not a silent success. Executor
arms 168 → 172.
- **Every open case has an accountable owner and a next-action clock**
(WS7.4, completing WS7 of the gap-closure program). An owner is a person
+1 -1
View File
@@ -45,7 +45,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
The claim-to-gate matrix stands at **410 rows — 401 GATED / 9 PARTIAL / 0 NO GATE**. Nine rows are PARTIAL, each naming what closes it: responder-app voice until a screen and an allowlisted on-device recogniser land with a device test; console internationalisation until the analyst surfaces render through `translate()` with a test that fails if a hardcoded string returns; "where does package P at version V run" until a connector fetches a code platform's SBOM, since the SPDX path is proven against a document and has no live producer; "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; "several individually unalarming signals become one finding" until a corpus replayed through fusion's own enrichment exists, because the balanced corpus carries vendor alert evidence while every weak signal is produced by that enrichment, so all 72 items score zero and `scripts/calibrate_weak_signals.py` refuses to publish a sweep rather than calibrate against nothing; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
The claim-to-gate matrix stands at **411 rows — 402 GATED / 9 PARTIAL / 0 NO GATE**. Nine rows are PARTIAL, each naming what closes it: responder-app voice until a screen and an allowlisted on-device recogniser land with a device test; console internationalisation until the analyst surfaces render through `translate()` with a test that fails if a hardcoded string returns; "where does package P at version V run" until a connector fetches a code platform's SBOM, since the SPDX path is proven against a document and has no live producer; "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; "several individually unalarming signals become one finding" until a corpus replayed through fusion's own enrichment exists, because the balanced corpus carries vendor alert evidence while every weak signal is produced by that enrichment, so all 72 items score zero and `scripts/calibrate_weak_signals.py` refuses to publish a sweep rather than calibrate against nothing; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
+1 -1
View File
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
The last row is the one worth reading first. It is the honest index: 401 rows
The last row is the one worth reading first. It is the honest index: 402 rows
`GATED`, 9 `PARTIAL`, and a ratchet that refuses to let a row sit at
`NO GATE`. Re-read the figure from the table rather than from here — a count
copied into prose goes stale in silence, which is why
+3 -2
View File
@@ -11,6 +11,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| A DLP alert normalizes into one finding whatever vendor raised it — policy, rule, data classes, file name/hash/size, channel, destination and its class, the enforcement the DLP product itself applied (`blocked` / `warned` / `allowed` / `audited`), user and device — with per-source profiles mapping only vendor-documented fields: an absent fact stays empty, a destination class is derived only from explicit vendor facts, an unstated enforcement stays null, and a source without a profile yields no finding rather than a best-effort parse | `services/api/app/services/dlp_finding.py`; `GET /alerts/{id}/dlp-finding` | `ci.yml :: Python — Tests` (api, `test_dlp_finding.py`, 15 cases over the vendors' own published shapes — Netskope's DLP alert export sample, the O365 Management Activity DLP schema with its 1–5 EnforcementMode ladder, Graph `alerts_v2` evidence objects — including absent-stays-empty, the managed_app-only destination-class rule, and the honest `finding: null` route answer) | core | GATED | Negative control recorded in the PR: corrupting one enforcement mapping fails two cases |
| The insider watchlist is a control, not a checkbox: a watchlist row is never indefinite (reason + future expiry required, expired rows stop elevating), a watchlisted identity's alerts are tagged and floored `info`/`low` → `medium` **through the existing business-context path** (a machine-owned `managed_yaml` document beside the analyst's verbatim `yaml_text`, same engine, same triage-worker application point, never a downgrade of `high`/`critical`), the transition onto the list opens a departure-review case whose lake half reports *could not check* rather than zero when unreachable, and the HR door (`workforce_members` status/last-day, per-tenant opt-in, default off) lists departing members idempotently without ever shortening a manual row | `services/api/app/services/insider_watchlist.py`; migration 168; `services/api/app/workers/insider_watchlist_sweep.py` | `ci.yml :: Python — Tests` (api `test_insider_watchlist.py` 21 cases: the generated document parses with the console's own loader and evaluated by the real engine floors low and never touches high/critical, adversarial reasons stay data, validation names each unmet requirement, the lookback renders per-event-type counts and an unreachable lake as unknown-not-zero, the HR door never overwrites an existing row; agents `test_business_context_managed_rules.py` 8 cases: the **agents service's independent grammar implementation** parses the same golden fixture bytes and applies the same floor, and a parse error in either document never withdraws the other's rules) + `integration.yml :: The insider watchlist expires, elevates and reviews for real (live Postgres)` (expiry exclusion is the rebuild SELECT's own WHERE; the console save and the watchlist upsert own one column each and must not clobber the other; `watchlist_source` is a DB CHECK; policy RLS judged under the NOBYPASSRLS role including the unbound sweep arm; the HR door end to end — workforce row → watchlist row + managed rule + review case — idempotent on the second sweep; fails at setup on the pre-change tree) | core | GATED | Negative controls recorded in the PR: removing the expiry exclusion fails the live rebuild test; removing the severity guard makes the floor a downgrade and fails two never-downgrade cases |
| The M365 audit connector's `DLP.All` stream is a real per-instance switch, not a promise: the `include_dlp` schema field (default off) reaches the wire — the subscription and content-listing calls name `DLP.All` only when the instance opted in — and an unparseable value means off, because a collector that defaults to on when it cannot read its own switch is a poll the tenant did not ask for | `services/connectors/app/connectors/m365_audit.py`; `apps/docs/docs/connectors/m365-audit.md` | `ci.yml :: Python — Tests` (connectors, `test_m365_audit_dlp_toggle.py`, 15 cases: the schema declares the field defaulting off, the module docstring no longer promises the switch "later", default polls exactly the four `Audit.*` types, five truthy spellings enable `DLP.All` and six garbage/falsy values mean off, and the fetch path is observed against a mock vendor — the content-type selection is read off the real HTTP requests, not off a constant) | core | GATED | Negative control recorded in the PR: forcing the coercion to always-off fails the four enable cases |
| A leaked document's sharing grants can be revoked as a governed action on all four file-sharing estates — Google Drive, OneDrive/SharePoint via Graph, Box and Dropbox — with **prior grants captured before every write** (none of these APIs has a permissions recycle bin), the write **verified by read-back** (a vendor answering 2xx on the DELETE while still listing the grant fails the action naming what it still sees), rollback restoring the captured grants, ANALYST approval on both governance doors, and the one honest limit stated rather than papered over: Graph, Box and Dropbox mint a new URL when a sharing link is re-created, so a link rollback restores access shape and says so, never the circulating URL | `services/actions/app/executors/fileshare.py`; `services/actions/app/clients/fileshare_clients.py`; `capability_contracts.py` (`revoke_file_share`) | `ci.yml :: Python — Tests` (actions, `test_revoke_file_share_vendor_arms.py`, 14 cases through the real executor and builtins against stateful mock vendors: capture-before-write is the observed request order, a frozen "lying vendor" whose DELETE answers 204 and deletes nothing fails the action, grantee/links/all scoping spares the owner, rollback restores through each vendor's own re-grant shape (Graph invite with `sendInvitation=false`, Box collaboration, Dropbox `add_file_member` quiet, Drive exact permission), a dry run through the adapter strips credentials so the mock vendor sees zero requests, nothing-matched is a failure not a silent success, and the independent probe answers gone/present/unverifiable; `test_live_action_builtins.py` pins the four arms in the canonical pair set at 172; `test_verification_coverage.py` holds the declared probe to its registered verifier) | core | GATED | Negative controls recorded in the PR: skipping the read-back comparison passes the lying vendor (1 case fails); a rollback returning True without acting fails 5 rollback cases |
| Every open case has an accountable owner — a person or an agent run — and a next-action clock: launching an investigation claims an unowned case for the run and never steals one a person holds, and `GET /cases/attention` surfaces open cases that are unowned or overdue with `owner_kind` named and `overdue_seconds` null until due (never a confident zero) | `services/api/app/api/v1/endpoints/cases.py` (`get_cases_attention`, `_claim_case_for_run`); migration 167 | `ci.yml :: Python — Tests` (api, `test_case_ownership_attention.py`: the feed names the owner kind per row and keeps not-yet-due as null; the claim SQL carries both no-person and no-agent predicates — the negative control removes them and the test fails; the query is tenant-scoped; the PATCH surface carries both fields) | core | GATED | - |
| The investigator carries named strategies for the reference-service surfaces — AI-agent misuse, data handling against business context, BEC payment fraud, SaaS OAuth abuse, cloud exposure — each declaring the pivots the depth gate grades it on | `services/agents/app/investigator/strategies.py` | `ci.yml :: Python — Tests` (agents, `test_deep_investigation.py::TestStrategySelection` — each of the five has its own selection row, technique-match outranking keywords, and disabling any one fails its row) + `ci.yml :: python-lint` (`check_investigation_depth.py`: 15 strategies, every expected pivot resolves to a real tool in both directions) | core | GATED | Negative control recorded in the PR: renaming one strategy id fails exactly its selection row |
| A case reaches `resolved` only through the tenant's resolution contract — containment verified-or-waived-with-reason, eradication and recovery recorded, root cause determined or undetermined (a hypothesis does not satisfy), affected entities derived from the case's own rows, customer notified channel-and-time — enforced by **one shared checker** at every writer: the PATCH gate (422 naming each gap), the war-room resolve decision (refusal note, no status write), and the inbound ITSM mirror (vendor resolve demoted to `contained` with the gaps in the system note, because a webhook cannot be 422'd); off by default per tenant | `services/api/app/services/case_resolution.py`; migration 166 | `ci.yml :: Python — Tests` (api, `test_case_resolution_contract.py`, 16 cases: the pure gap computation names every unmet requirement, a hypothesis is refused in so many words, toggled-off requirements do not gap, facts validation enforces verified-requires-reference / waived-requires-reason / notification-channel-and-time-together, and all three writers are driven through their real functions with the checker monkeypatched both ways) + `integration.yml :: Resolving a case is earned, and the contract's rows are tenant-scoped (live Postgres)` (the opt-in default is the real absent-row state, one-per-tenant policy and one-per-case facts are unique-constraint behaviour, the derived entity count is JSONB arithmetic over the real schema, RLS under the NOBYPASSRLS role; fails at setup on the pre-change tree) | core | GATED | Negative control recorded in the PR: forcing the checker to answer no-gaps fails two cases |
@@ -421,8 +422,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
- Total: 410
- GATED: 401
- Total: 411
- GATED: 402
- PARTIAL: 9
- NO GATE: 0
+33 -3
View File
@@ -1,9 +1,9 @@
{
"_comment": "Generated by scripts/check_executor_arm_count.py --write. Do not hand-edit; regenerate.",
"counting_rule": "Class-level `capability = \"...\"` declarations under services/actions/app/live_actions/, cross-checked against builtins._BUILTIN_ADAPTERS.",
"arms": 168,
"verbs": 66,
"vendors": 38,
"arms": 172,
"verbs": 67,
"vendors": 40,
"required_minimum": 150,
"by_capability": {
"ack_alert": [
@@ -230,6 +230,12 @@
"revoke_deploy_key": [
"github"
],
"revoke_file_share": [
"box",
"dropbox",
"google_workspace",
"m365"
],
"revoke_oauth_grant": [
"azure_entra",
"google_workspace",
@@ -1052,6 +1058,30 @@
"vendor_id": "github",
"capability": "revoke_deploy_key"
},
{
"module": "builtins",
"class": "BoxRevokeFileShare",
"vendor_id": "box",
"capability": "revoke_file_share"
},
{
"module": "builtins",
"class": "DropboxRevokeFileShare",
"vendor_id": "dropbox",
"capability": "revoke_file_share"
},
{
"module": "builtins",
"class": "GoogleDriveRevokeFileShare",
"vendor_id": "google_workspace",
"capability": "revoke_file_share"
},
{
"module": "builtins",
"class": "M365RevokeFileShare",
"vendor_id": "m365",
"capability": "revoke_file_share"
},
{
"module": "cloud_saas_arms",
"class": "EntraRevokeOAuthGrant",
@@ -0,0 +1,385 @@
"""Share-permission clients for the four file-sharing estates (WS4.5).
One capability — ``revoke_file_share`` — four vendors, and the client layer
holds only the vendor verbs the executor composes: list the grants on a
file, delete one, and re-create one (the rollback half). Every method shape
is taken from the vendor's own published contract, cited per class; nothing
is guessed, and a field the vendor does not publish is not invented.
Two vendor facts the executor's honesty depends on, recorded here because
they are vendor facts rather than implementation choices:
* **A revoked sharing link cannot be un-revoked.** Google Drive is the
exception (an ``anyone`` grant is an ordinary permission that restores
like any other); Microsoft Graph, Box and Dropbox all mint a **new URL**
when a link is re-created, so a rollback of a link revocation restores
*access shape*, not the circulating URL — the executor reports exactly
that instead of claiming a restore it cannot make.
* **Capture must come before the write**, because none of these APIs offers
a recycle bin for permissions: the pre-write listing is the only record
of what to restore.
All clients take an optional ``transport`` so tests drive the real request
construction against a mock vendor (the house seam, per
``test_sync_detection_rule_vendor_arms.py``).
"""
from __future__ import annotations
from typing import Any
import httpx
import structlog
from app.clients.google_workspace_client import GoogleWorkspaceClient
logger = structlog.get_logger()
_TIMEOUT = 20.0
# ---------------------------------------------------------------------------
# Google Drive (Drive API v3)
# ---------------------------------------------------------------------------
_DRIVE = "https://www.googleapis.com/drive/v3"
#: Full Drive scope: permission deletes and creates are writes. Domain-wide
#: delegation must authorize this scope for the service account; it is a
#: separate grant from the Admin SDK scopes the parent client mints.
_DRIVE_SCOPES = "https://www.googleapis.com/auth/drive"
class GoogleDriveShareClient(GoogleWorkspaceClient):
"""Drive v3 permissions, per Google's published reference.
Contract: ``GET/POST /drive/v3/files/{fileId}/permissions`` and
``DELETE /drive/v3/files/{fileId}/permissions/{permissionId}``
(https://developers.google.com/drive/api/reference/rest/v3/permissions).
``supportsAllDrives=true`` rides every call so shared-drive items work;
an ``anyone`` permission is Drive's spelling of a sharing link.
"""
_scopes = _DRIVE_SCOPES
def __init__(
self,
service_account_key: str | dict,
subject_email: str,
*,
transport: httpx.AsyncBaseTransport | None = None,
) -> None:
super().__init__(service_account_key, subject_email)
self._transport = transport
def _client(self) -> httpx.AsyncClient:
return httpx.AsyncClient(timeout=_TIMEOUT, transport=self._transport)
async def list_permissions(self, file_id: str) -> list[dict[str, Any]]:
async with self._client() as client:
await self._ensure_token(client)
resp = await client.get(
f"{_DRIVE}/files/{file_id}/permissions",
headers=self._headers(),
params={
"supportsAllDrives": "true",
"fields": "permissions(id,type,role,emailAddress,domain,allowFileDiscovery,expirationTime)",
},
)
resp.raise_for_status()
return list(resp.json().get("permissions") or [])
async def delete_permission(self, file_id: str, permission_id: str) -> None:
async with self._client() as client:
await self._ensure_token(client)
resp = await client.delete(
f"{_DRIVE}/files/{file_id}/permissions/{permission_id}",
headers=self._headers(),
params={"supportsAllDrives": "true"},
)
resp.raise_for_status()
async def create_permission(self, file_id: str, body: dict[str, Any]) -> dict[str, Any]:
"""The rollback half. ``sendNotificationEmail=false`` — restoring a
grant during an investigation must not mail the grantee."""
params: dict[str, str] = {"supportsAllDrives": "true"}
# Drive refuses sendNotificationEmail=false for `anyone`; only
# user/group grants accept it (the reference's own constraint).
if body.get("type") in ("user", "group"):
params["sendNotificationEmail"] = "false"
async with self._client() as client:
await self._ensure_token(client)
resp = await client.post(
f"{_DRIVE}/files/{file_id}/permissions",
headers=self._headers(),
params=params,
json=body,
)
resp.raise_for_status()
return dict(resp.json())
# ---------------------------------------------------------------------------
# OneDrive / SharePoint (Microsoft Graph)
# ---------------------------------------------------------------------------
_GRAPH = "https://graph.microsoft.com/v1.0"
_GRAPH_LOGIN = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"
class GraphDriveClient:
"""DriveItem permissions, per Microsoft Graph's published reference.
Contract: ``GET /drives/{drive-id}/items/{item-id}/permissions``,
``DELETE .../permissions/{perm-id}``, restore of user/group grants via
``POST .../invite`` and of links via ``POST .../createLink``
(https://learn.microsoft.com/graph/api/driveitem-list-permissions,
driveitem-invite, driveitem-createlink). A re-created link is a **new
URL** — Graph has no un-revoke.
"""
def __init__(
self,
tenant_id: str,
client_id: str,
client_secret: str,
*,
transport: httpx.AsyncBaseTransport | None = None,
) -> None:
self._tenant = tenant_id
self._client_id = client_id
self._client_secret = client_secret
self._token: str | None = None
self._transport = transport
def _client(self) -> httpx.AsyncClient:
return httpx.AsyncClient(timeout=_TIMEOUT, transport=self._transport)
async def _ensure_token(self, client: httpx.AsyncClient) -> None:
if self._token:
return
resp = await client.post(
_GRAPH_LOGIN.format(tenant=self._tenant),
data={
"grant_type": "client_credentials",
"client_id": self._client_id,
"client_secret": self._client_secret,
"scope": "https://graph.microsoft.com/.default",
},
)
resp.raise_for_status()
self._token = str(resp.json()["access_token"])
def _headers(self) -> dict[str, str]:
return {"Authorization": f"Bearer {self._token}"}
async def list_permissions(self, drive_id: str, item_id: str) -> list[dict[str, Any]]:
async with self._client() as client:
await self._ensure_token(client)
resp = await client.get(
f"{_GRAPH}/drives/{drive_id}/items/{item_id}/permissions",
headers=self._headers(),
)
resp.raise_for_status()
return list(resp.json().get("value") or [])
async def delete_permission(self, drive_id: str, item_id: str, permission_id: str) -> None:
async with self._client() as client:
await self._ensure_token(client)
resp = await client.delete(
f"{_GRAPH}/drives/{drive_id}/items/{item_id}/permissions/{permission_id}",
headers=self._headers(),
)
resp.raise_for_status()
async def invite(self, drive_id: str, item_id: str, *, emails: list[str], roles: list[str]) -> dict[str, Any]:
"""Restore a user/group grant. ``sendInvitation=false`` +
``requireSignIn=true`` — a rollback must not mail anyone."""
async with self._client() as client:
await self._ensure_token(client)
resp = await client.post(
f"{_GRAPH}/drives/{drive_id}/items/{item_id}/invite",
headers=self._headers(),
json={
"recipients": [{"email": e} for e in emails],
"roles": roles,
"requireSignIn": True,
"sendInvitation": False,
},
)
resp.raise_for_status()
return dict(resp.json())
async def create_link(self, drive_id: str, item_id: str, *, link_type: str, scope: str) -> dict[str, Any]:
async with self._client() as client:
await self._ensure_token(client)
resp = await client.post(
f"{_GRAPH}/drives/{drive_id}/items/{item_id}/createLink",
headers=self._headers(),
json={"type": link_type, "scope": scope},
)
resp.raise_for_status()
return dict(resp.json())
# ---------------------------------------------------------------------------
# Box
# ---------------------------------------------------------------------------
_BOX = "https://api.box.com/2.0"
class BoxShareClient:
"""File collaborations + shared links, per Box's published reference.
Contract: ``GET /2.0/files/{id}/collaborations``,
``DELETE /2.0/collaborations/{id}``, ``POST /2.0/collaborations``
(https://developer.box.com/reference/get-files-id-collaborations,
delete-collaborations-id, post-collaborations); the shared link lives
on the file object itself — read with a ``fields=shared_link`` GET,
remove by ``PUT`` with ``{"shared_link": null}``, re-create by ``PUT``
with settings (put-files-id). A re-created link is a **new URL**.
"""
def __init__(self, access_token: str, *, transport: httpx.AsyncBaseTransport | None = None) -> None:
self._token = access_token
self._transport = transport
def _client(self) -> httpx.AsyncClient:
return httpx.AsyncClient(timeout=_TIMEOUT, transport=self._transport)
def _headers(self) -> dict[str, str]:
return {"Authorization": f"Bearer {self._token}"}
async def list_collaborations(self, file_id: str) -> list[dict[str, Any]]:
async with self._client() as client:
resp = await client.get(f"{_BOX}/files/{file_id}/collaborations", headers=self._headers())
resp.raise_for_status()
return list(resp.json().get("entries") or [])
async def delete_collaboration(self, collaboration_id: str) -> None:
async with self._client() as client:
resp = await client.delete(f"{_BOX}/collaborations/{collaboration_id}", headers=self._headers())
resp.raise_for_status()
async def create_collaboration(self, file_id: str, *, login: str, role: str) -> dict[str, Any]:
async with self._client() as client:
resp = await client.post(
f"{_BOX}/collaborations",
headers=self._headers(),
json={
"item": {"type": "file", "id": file_id},
"accessible_by": {"type": "user", "login": login},
"role": role,
},
params={"notify": "false"},
)
resp.raise_for_status()
return dict(resp.json())
async def get_shared_link(self, file_id: str) -> dict[str, Any] | None:
async with self._client() as client:
resp = await client.get(
f"{_BOX}/files/{file_id}",
headers=self._headers(),
params={"fields": "shared_link"},
)
resp.raise_for_status()
return resp.json().get("shared_link")
async def remove_shared_link(self, file_id: str) -> None:
async with self._client() as client:
resp = await client.put(
f"{_BOX}/files/{file_id}",
headers=self._headers(),
params={"fields": "shared_link"},
json={"shared_link": None},
)
resp.raise_for_status()
async def set_shared_link(self, file_id: str, settings: dict[str, Any]) -> dict[str, Any]:
async with self._client() as client:
resp = await client.put(
f"{_BOX}/files/{file_id}",
headers=self._headers(),
params={"fields": "shared_link"},
json={"shared_link": settings},
)
resp.raise_for_status()
return dict(resp.json())
# ---------------------------------------------------------------------------
# Dropbox
# ---------------------------------------------------------------------------
_DROPBOX = "https://api.dropboxapi.com/2"
class DropboxShareClient:
"""File members + shared links, per Dropbox's published reference.
Contract: ``POST /2/sharing/list_file_members``,
``POST /2/sharing/remove_file_member_2``,
``POST /2/sharing/add_file_member`` (``quiet=true`` — no mail on
rollback), ``POST /2/sharing/list_shared_links`` (``direct_only``),
``POST /2/sharing/revoke_shared_link``,
``POST /2/sharing/create_shared_link_with_settings``
(https://www.dropbox.com/developers/documentation/http/documentation).
Dropbox states revoked links cannot be re-enabled; a re-created link is
a **new URL**.
"""
def __init__(self, access_token: str, *, transport: httpx.AsyncBaseTransport | None = None) -> None:
self._token = access_token
self._transport = transport
def _client(self) -> httpx.AsyncClient:
return httpx.AsyncClient(timeout=_TIMEOUT, transport=self._transport)
def _headers(self) -> dict[str, str]:
return {"Authorization": f"Bearer {self._token}", "Content-Type": "application/json"}
async def _post(self, path: str, body: dict[str, Any]) -> Any:
async with self._client() as client:
resp = await client.post(f"{_DROPBOX}{path}", headers=self._headers(), json=body)
resp.raise_for_status()
if resp.content:
return resp.json()
return None
async def list_file_members(self, file_id: str) -> dict[str, Any]:
return dict(await self._post("/sharing/list_file_members", {"file": file_id}))
async def remove_file_member(self, file_id: str, member_email: str) -> dict[str, Any]:
out = await self._post(
"/sharing/remove_file_member_2",
{"file": file_id, "member": {".tag": "email", "email": member_email}},
)
return dict(out or {})
async def add_file_member(self, file_id: str, member_email: str, access_level: str) -> dict[str, Any]:
out = await self._post(
"/sharing/add_file_member",
{
"file": file_id,
"members": [{".tag": "email", "email": member_email}],
"access_level": access_level,
"quiet": True,
},
)
return {"result": out}
async def list_shared_links(self, file_id: str) -> list[dict[str, Any]]:
out = await self._post("/sharing/list_shared_links", {"path": file_id, "direct_only": True})
return list((out or {}).get("links") or [])
async def revoke_shared_link(self, url: str) -> None:
await self._post("/sharing/revoke_shared_link", {"url": url})
async def create_shared_link(self, file_id: str) -> dict[str, Any]:
out = await self._post(
"/sharing/create_shared_link_with_settings",
{"path": file_id, "settings": {"audience": {".tag": "public"}}},
)
return dict(out or {})
@@ -132,7 +132,11 @@ class GoogleWorkspaceClient:
claims = {
"iss": self._key["client_email"],
"sub": self._subject,
"scope": _SCOPES,
# Subclasses narrow this to their own scope set (the Drive share
# client, WS4.5): a service account's domain-wide delegation is
# authorized per scope list, so a admin-SDK token and a Drive
# token are different grants and must stay different mints.
"scope": getattr(self, "_scopes", _SCOPES),
"aud": _TOKEN_URI,
"iat": now,
"exp": now + 3600,
+480
View File
@@ -0,0 +1,480 @@
"""``revoke_file_share`` — four estates, one contract (WS4.5).
What this verb is
-----------------
A leaked document's blast radius is its sharing grants. This executor
removes them — a named grantee's access, or the file's sharing link(s), or
both ("everything except the owner") — on Google Drive, OneDrive/SharePoint
(Microsoft Graph), Box and Dropbox, with the three properties every
destructive verb in this registry carries:
* **Prior grants are captured before the write** into ``rollback_data``.
None of these APIs has a recycle bin for permissions; the pre-write
listing is the only record of what to restore.
* **The write is verified by read-back**: the grant list is re-read after
the revocation and the action FAILS, naming what it still sees, if the
revoked grant is still present — a 2xx on the DELETE is the vendor
accepting the request, not the estate changing.
* **Rollback restores the captured grants** — and reports honestly what it
cannot restore: Graph, Box and Dropbox mint a **new URL** when a sharing
link is re-created (a vendor fact, recorded in
``clients/fileshare_clients.py``), so a link rollback restores access
shape and says ``restored_with_new_url`` rather than claiming the
circulating link works again. Google Drive's ``anyone`` grant is an
ordinary permission and restores exactly.
Request shape
-------------
``target``: the vendor's file identifier (Drive fileId, Graph itemId — with
``drive_id`` in parameters, Box file id, Dropbox file id or path).
``parameters.revoke``: ``"grantee"`` (requires ``grantee_email``),
``"links"`` (every sharing link / anyone-grant), or ``"all"`` (every grant
except ownership). Vendor credentials select the arm; with none present the
result is an honest simulation note, never an invented success.
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
import structlog
from app.clients.fileshare_clients import (
BoxShareClient,
DropboxShareClient,
GoogleDriveShareClient,
GraphDriveClient,
)
from app.executors.base import _SIM_FUNNEL_CTA, ActionRequest, ActionResult, BaseExecutor
from app.models.action import ActionStatus, BlastRadius
logger = structlog.get_logger()
_OWNER_ROLES_DRIVE = {"owner", "organizer", "fileOrganizer"}
_OWNER_ROLES_GRAPH = {"owner"}
_OWNER_ROLES_BOX = {"owner", "co-owner"}
_OWNER_LEVELS_DROPBOX = {"owner"}
_MODES = ("grantee", "links", "all")
def _drive_client(params: dict[str, Any]) -> GoogleDriveShareClient | None:
key = params.get("gws_service_account_key")
subject = params.get("gws_subject_email")
if key and subject:
return GoogleDriveShareClient(key, subject, transport=params.get("_transport"))
return None
def _graph_client(params: dict[str, Any]) -> GraphDriveClient | None:
tenant = params.get("azure_tenant_id")
client_id = params.get("azure_client_id")
secret = params.get("azure_client_secret")
if tenant and client_id and secret:
return GraphDriveClient(tenant, client_id, secret, transport=params.get("_transport"))
return None
def _box_client(params: dict[str, Any]) -> BoxShareClient | None:
token = params.get("box_access_token")
if token:
return BoxShareClient(token, transport=params.get("_transport"))
return None
def _dropbox_client(params: dict[str, Any]) -> DropboxShareClient | None:
token = params.get("dropbox_access_token")
if token:
return DropboxShareClient(token, transport=params.get("_transport"))
return None
def _wants(mode: str, *, is_link: bool, grantee_email: str, entry_email: str) -> bool:
"""Does this grant fall inside the requested revocation?"""
if mode == "all":
return True
if mode == "links":
return is_link
return bool(entry_email) and entry_email.lower() == grantee_email.lower()
class RevokeFileShareExecutor(BaseExecutor):
"""One executor, four vendor arms, selected by which credentials appear."""
async def execute(self, request: ActionRequest) -> ActionResult: # noqa: PLR0911 — one return per arm + guards
params = request.parameters
mode = str(params.get("revoke") or "grantee")
grantee = str(params.get("grantee_email") or "")
if mode not in _MODES:
return self._failed(request, f"revoke must be one of {_MODES}, got {mode!r}")
if mode == "grantee" and not grantee:
return self._failed(request, "revoke=grantee requires grantee_email")
if (drive := _drive_client(params)) is not None:
return await self._run_google(request, drive, mode, grantee)
if (graph := _graph_client(params)) is not None:
drive_id = str(params.get("drive_id") or "")
if not drive_id:
return self._failed(request, "the Graph arm requires drive_id alongside the item id")
return await self._run_graph(request, graph, drive_id, mode, grantee)
if (box := _box_client(params)) is not None:
return await self._run_box(request, box, mode, grantee)
if (dropbox := _dropbox_client(params)) is not None:
return await self._run_dropbox(request, dropbox, mode, grantee)
logger.warning("revoke_file_share.simulation", reason="no vendor credentials")
return ActionResult(
action_id=request.id,
status=ActionStatus.COMPLETED,
blast_radius=BlastRadius.MEDIUM,
output={
"action": "revoke_file_share",
"file": request.target,
"note": (
"Simulation mode — provide gws_service_account_key/gws_subject_email, "
"azure_tenant_id/azure_client_id/azure_client_secret (+drive_id), "
"box_access_token, or dropbox_access_token to enable live execution." + _SIM_FUNNEL_CTA
),
},
rollback_data={},
completed_at=datetime.utcnow(),
)
# ── shared result shapes ────────────────────────────────────────────
def _failed(self, request: ActionRequest, error: str) -> ActionResult:
return ActionResult(
action_id=request.id,
status=ActionStatus.FAILED,
blast_radius=BlastRadius.MEDIUM,
error=error,
completed_at=datetime.utcnow(),
)
def _done(
self,
request: ActionRequest,
*,
vendor: str,
revoked: list[dict[str, Any]],
rollback: dict[str, Any],
notes: list[str],
) -> ActionResult:
return ActionResult(
action_id=request.id,
status=ActionStatus.COMPLETED,
blast_radius=BlastRadius.MEDIUM,
output={
"success": True,
"action": "revoke_file_share",
"vendor": vendor,
"file": request.target,
"revoked": revoked,
"verified_by_readback": True,
"notes": notes,
},
rollback_data=rollback,
completed_at=datetime.utcnow(),
)
# ── Google Drive ────────────────────────────────────────────────────
async def _run_google(self, request: ActionRequest, client: GoogleDriveShareClient, mode: str, grantee: str) -> ActionResult:
file_id = request.target
try:
prior = await client.list_permissions(file_id)
targets = [
p
for p in prior
if p.get("role") not in _OWNER_ROLES_DRIVE
and _wants(
mode,
is_link=p.get("type") in ("anyone", "domain"),
grantee_email=grantee,
entry_email=str(p.get("emailAddress") or ""),
)
]
if not targets:
return self._failed(
request,
f"no matching non-owner grant on the file (mode={mode}, {len(prior)} grant(s) present) — nothing was revoked",
)
for p in targets:
await client.delete_permission(file_id, str(p["id"]))
after = await client.list_permissions(file_id)
except Exception as exc: # noqa: BLE001 — vendor refusal fails the action
logger.error("revoke_file_share.google.failed", error=str(exc)[:300])
return self._failed(request, str(exc))
remaining = {str(p.get("id")) for p in after}
still_there = [p for p in targets if str(p.get("id")) in remaining]
if still_there:
return self._failed(
request,
"read-back still shows revoked grant(s): " + ", ".join(str(p.get("id")) for p in still_there),
)
return self._done(
request,
vendor="google_drive",
revoked=[{"id": p.get("id"), "type": p.get("type"), "role": p.get("role"), "email": p.get("emailAddress")} for p in targets],
rollback={"vendor": "google_drive", "file_id": file_id, "grants": targets},
notes=["an `anyone` grant restores exactly on Drive — no URL changes"],
)
# ── OneDrive / SharePoint ───────────────────────────────────────────
async def _run_graph(
self,
request: ActionRequest,
client: GraphDriveClient,
drive_id: str,
mode: str,
grantee: str,
) -> ActionResult:
item_id = request.target
try:
prior = await client.list_permissions(drive_id, item_id)
targets = []
for p in prior:
roles = set(p.get("roles") or [])
if roles & _OWNER_ROLES_GRAPH:
continue
is_link = "link" in p
emails = [
str(((p.get("grantedToV2") or {}).get("user") or {}).get("email") or ""),
*(str((ident.get("user") or {}).get("email") or "") for ident in p.get("grantedToIdentitiesV2") or []),
]
entry_email = next((e for e in emails if e), "")
if _wants(mode, is_link=is_link, grantee_email=grantee, entry_email=entry_email):
targets.append(p)
if not targets:
return self._failed(
request,
f"no matching non-owner grant on the item (mode={mode}, {len(prior)} grant(s) present) — nothing was revoked",
)
for p in targets:
await client.delete_permission(drive_id, item_id, str(p["id"]))
after = await client.list_permissions(drive_id, item_id)
except Exception as exc: # noqa: BLE001
logger.error("revoke_file_share.graph.failed", error=str(exc)[:300])
return self._failed(request, str(exc))
remaining = {str(p.get("id")) for p in after}
still_there = [p for p in targets if str(p.get("id")) in remaining]
if still_there:
return self._failed(
request,
"read-back still shows revoked grant(s): " + ", ".join(str(p.get("id")) for p in still_there),
)
return self._done(
request,
vendor="m365_drive",
revoked=[{"id": p.get("id"), "link": "link" in p, "roles": p.get("roles")} for p in targets],
rollback={"vendor": "m365_drive", "drive_id": drive_id, "item_id": item_id, "grants": targets},
notes=["a re-created Graph sharing link is a new URL (vendor fact); user grants restore via invite without mail"],
)
# ── Box ─────────────────────────────────────────────────────────────
async def _run_box(self, request: ActionRequest, client: BoxShareClient, mode: str, grantee: str) -> ActionResult:
file_id = request.target
try:
collabs = await client.list_collaborations(file_id)
link = await client.get_shared_link(file_id)
collab_targets = [
c
for c in collabs
if c.get("role") not in _OWNER_ROLES_BOX
and _wants(
mode,
is_link=False,
grantee_email=grantee,
entry_email=str((c.get("accessible_by") or {}).get("login") or ""),
)
]
revoke_link = link is not None and mode in ("links", "all")
if not collab_targets and not revoke_link:
return self._failed(
request,
f"no matching non-owner grant on the file (mode={mode}, "
f"{len(collabs)} collaboration(s), shared_link={'present' if link else 'absent'}) "
"— nothing was revoked",
)
for c in collab_targets:
await client.delete_collaboration(str(c["id"]))
if revoke_link:
await client.remove_shared_link(file_id)
after = await client.list_collaborations(file_id)
link_after = await client.get_shared_link(file_id)
except Exception as exc: # noqa: BLE001
logger.error("revoke_file_share.box.failed", error=str(exc)[:300])
return self._failed(request, str(exc))
remaining = {str(c.get("id")) for c in after}
still_there = [c for c in collab_targets if str(c.get("id")) in remaining]
if still_there or (revoke_link and link_after is not None):
bits = [f"collaboration {c.get('id')}" for c in still_there]
if revoke_link and link_after is not None:
bits.append("the shared link")
return self._failed(request, "read-back still shows: " + ", ".join(bits))
return self._done(
request,
vendor="box",
revoked=[
*(
{"collaboration_id": c.get("id"), "login": (c.get("accessible_by") or {}).get("login"), "role": c.get("role")}
for c in collab_targets
),
*([{"shared_link": link.get("url")}] if revoke_link and link else []),
],
rollback={
"vendor": "box",
"file_id": file_id,
"collaborations": collab_targets,
"shared_link": link if revoke_link else None,
},
notes=["a re-created Box shared link is a new URL (vendor fact)"],
)
# ── Dropbox ─────────────────────────────────────────────────────────
async def _run_dropbox(self, request: ActionRequest, client: DropboxShareClient, mode: str, grantee: str) -> ActionResult:
file_id = request.target
try:
members = await client.list_file_members(file_id)
links = await client.list_shared_links(file_id)
user_targets = []
for u in members.get("users") or []:
level = str(((u.get("access_type") or {}).get(".tag")) or "")
email = str(((u.get("user") or {}).get("email")) or "")
if level in _OWNER_LEVELS_DROPBOX:
continue
if _wants(mode, is_link=False, grantee_email=grantee, entry_email=email):
user_targets.append({"email": email, "access_level": level})
link_targets = [link for link in links if mode in ("links", "all")]
if not user_targets and not link_targets:
return self._failed(
request,
f"no matching non-owner grant on the file (mode={mode}, "
f"{len(members.get('users') or [])} member(s), {len(links)} link(s)) "
"— nothing was revoked",
)
for u in user_targets:
await client.remove_file_member(file_id, u["email"])
for link in link_targets:
await client.revoke_shared_link(str(link.get("url")))
members_after = await client.list_file_members(file_id)
links_after = await client.list_shared_links(file_id)
except Exception as exc: # noqa: BLE001
logger.error("revoke_file_share.dropbox.failed", error=str(exc)[:300])
return self._failed(request, str(exc))
emails_after = {str(((u.get("user") or {}).get("email")) or "").lower() for u in members_after.get("users") or []}
still_members = [u for u in user_targets if u["email"].lower() in emails_after]
urls_after = {str(link.get("url")) for link in links_after}
still_links = [link for link in link_targets if str(link.get("url")) in urls_after]
if still_members or still_links:
bits = [f"member {u['email']}" for u in still_members]
bits += [f"link {link.get('url')}" for link in still_links]
return self._failed(request, "read-back still shows: " + ", ".join(bits))
return self._done(
request,
vendor="dropbox",
revoked=[
*({"member": u["email"], "access_level": u["access_level"]} for u in user_targets),
*({"shared_link": link.get("url")} for link in link_targets),
],
rollback={
"vendor": "dropbox",
"file_id": file_id,
"members": user_targets,
"links": link_targets,
},
notes=["Dropbox states a revoked link cannot be re-enabled; rollback mints a new URL"],
)
# ── rollback ────────────────────────────────────────────────────────
async def rollback(self, result: ActionResult, params: dict[str, Any] | None = None) -> bool:
"""Restore the captured grants. ``params`` carries credentials (they
are never stored in ``rollback_data``). Returns False when anything
could not be restored — and the per-entry report in the log names
what and why, including the new-URL caveat on re-created links."""
data = result.rollback_data or {}
vendor = data.get("vendor")
if not vendor or params is None:
return False
try:
if vendor == "google_drive":
client = _drive_client(params)
if client is None:
return False
for p in data.get("grants") or []:
body = {"role": p.get("role"), "type": p.get("type")}
if p.get("emailAddress"):
body["emailAddress"] = p["emailAddress"]
if p.get("domain"):
body["domain"] = p["domain"]
await client.create_permission(data["file_id"], body)
return True
if vendor == "m365_drive":
graph = _graph_client(params)
if graph is None:
return False
ok = True
for p in data.get("grants") or []:
if "link" in p:
link = p.get("link") or {}
await graph.create_link(
data["drive_id"],
data["item_id"],
link_type=str(link.get("type") or "view"),
scope=str(link.get("scope") or "organization"),
)
logger.info("revoke_file_share.rollback.new_link_url", vendor=vendor)
continue
emails = [
str(((p.get("grantedToV2") or {}).get("user") or {}).get("email") or ""),
*(str((ident.get("user") or {}).get("email") or "") for ident in p.get("grantedToIdentitiesV2") or []),
]
emails = [e for e in emails if e]
roles = list(p.get("roles") or ["read"])
if not emails:
logger.warning("revoke_file_share.rollback.unrestorable", vendor=vendor, reason="grant carries no grantee email")
ok = False
continue
await graph.invite(data["drive_id"], data["item_id"], emails=emails, roles=roles)
return ok
if vendor == "box":
box = _box_client(params)
if box is None:
return False
ok = True
for c in data.get("collaborations") or []:
login = str((c.get("accessible_by") or {}).get("login") or "")
if not login:
logger.warning("revoke_file_share.rollback.unrestorable", vendor=vendor, reason="collaboration carries no login")
ok = False
continue
await box.create_collaboration(data["file_id"], login=login, role=str(c.get("role") or "viewer"))
link = data.get("shared_link")
if link:
settings = {"access": link.get("access", "open")}
await box.set_shared_link(data["file_id"], settings)
logger.info("revoke_file_share.rollback.new_link_url", vendor=vendor)
return ok
if vendor == "dropbox":
dropbox = _dropbox_client(params)
if dropbox is None:
return False
for u in data.get("members") or []:
await dropbox.add_file_member(data["file_id"], u["email"], str(u.get("access_level") or "viewer"))
if data.get("links"):
await dropbox.create_shared_link(data["file_id"])
logger.info("revoke_file_share.rollback.new_link_url", vendor=vendor)
return True
except Exception as exc: # noqa: BLE001 — a vendor refusal is a failed rollback
logger.error("revoke_file_share.rollback.failed", vendor=vendor, error=str(exc)[:300])
return False
return False
@@ -51,6 +51,7 @@ from app.executors.endpoint import (
RunAVScanExecutor,
RunScriptExecutor,
)
from app.executors.fileshare import RevokeFileShareExecutor
from app.executors.identity import (
DisableUserExecutor,
ForceMFAExecutor,
@@ -602,6 +603,69 @@ class DefenderBlockIOC(_LegacyExecutorAdapter):
_credential_keys = _DEFENDER_IOC_KEYS
# ── WS4.5: revoke_file_share — four estates, one executor, four arms ──────
#
# One executor instance shared by the four adapters: the vendor arm is
# selected inside by which credentials appear, and each adapter's
# ``_credential_keys`` names exactly the set that selects its vendor (which
# is also what the dry-run credential-strip removes, so a dry run can only
# ever reach the simulation note).
_REVOKE_FILE_SHARE = RevokeFileShareExecutor()
_GOOGLE_DRIVE_SHARE_KEYS: tuple[str, ...] = ("gws_service_account_key", "gws_subject_email")
_M365_DRIVE_SHARE_KEYS: tuple[str, ...] = ("azure_tenant_id", "azure_client_id", "azure_client_secret")
_BOX_SHARE_KEYS: tuple[str, ...] = ("box_access_token",)
_DROPBOX_SHARE_KEYS: tuple[str, ...] = ("dropbox_access_token",)
@apply_contract
class GoogleDriveRevokeFileShare(_LegacyExecutorAdapter):
vendor_id = "google_workspace"
capability = "revoke_file_share"
description = "Remove a grantee's access or the sharing link(s) from a Google Drive file, with prior grants captured for rollback."
requires_credentials = True
_legacy_executor = _REVOKE_FILE_SHARE
_legacy_action_type = ActionType.REVOKE_FILE_SHARE
_credential_keys = _GOOGLE_DRIVE_SHARE_KEYS
@apply_contract
class M365RevokeFileShare(_LegacyExecutorAdapter):
vendor_id = "m365"
capability = "revoke_file_share"
description = (
"Remove a grantee's access or the sharing link(s) from a OneDrive/SharePoint "
"item via Microsoft Graph, with prior grants captured for rollback."
)
requires_credentials = True
_legacy_executor = _REVOKE_FILE_SHARE
_legacy_action_type = ActionType.REVOKE_FILE_SHARE
_credential_keys = _M365_DRIVE_SHARE_KEYS
@apply_contract
class BoxRevokeFileShare(_LegacyExecutorAdapter):
vendor_id = "box"
capability = "revoke_file_share"
description = "Remove a collaborator or the shared link from a Box file, with prior grants captured for rollback."
requires_credentials = True
_legacy_executor = _REVOKE_FILE_SHARE
_legacy_action_type = ActionType.REVOKE_FILE_SHARE
_credential_keys = _BOX_SHARE_KEYS
@apply_contract
class DropboxRevokeFileShare(_LegacyExecutorAdapter):
vendor_id = "dropbox"
capability = "revoke_file_share"
description = "Remove a file member or revoke the shared link(s) on a Dropbox file, with prior grants captured for rollback."
requires_credentials = True
_legacy_executor = _REVOKE_FILE_SHARE
_legacy_action_type = ActionType.REVOKE_FILE_SHARE
_credential_keys = _DROPBOX_SHARE_KEYS
# ---------------------------------------------------------------------------
# Two-way SIEM loop — AiSOC's verdict back onto the source finding
# ---------------------------------------------------------------------------
@@ -1189,6 +1253,11 @@ class GmailUnblockSender(_MailboxAdapter):
_BUILTIN_ADAPTERS: tuple[type[LiveActionExecutor], ...] = (
# WS4.5 — share revocation across the four file-sharing estates.
GoogleDriveRevokeFileShare,
M365RevokeFileShare,
BoxRevokeFileShare,
DropboxRevokeFileShare,
# Read-only investigation verbs. Registered first because they are
# the ones an agent should reach for before anything below them.
CrowdStrikeGetHost,
@@ -111,6 +111,10 @@ KNOWN_CAPABILITIES: frozenset[str] = frozenset(
# image does not contain.
"osquery_live_query",
"suspend_session",
# WS4.5 — remove sharing grants or links from a file across the
# four file-sharing estates (Drive, OneDrive/SharePoint, Box,
# Dropbox), prior grants captured for rollback.
"revoke_file_share",
"sync_detection_rule",
# The return leg of a two-way SIEM integration: AiSOC's verdict
# written back onto the vendor finding that produced the alert.
@@ -580,6 +580,30 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
),
note="Writes a record into someone else's queue. Noise, not damage.",
),
"revoke_file_share": CapabilityContract(
impact=ActionImpact.MODERATE,
approval=ApprovalRequirement.ANALYST,
reversal=Reversal.PLATFORM,
reverse_capability="revoke_file_share",
required_permission=_CONTAIN,
# Every arm re-reads the grant list after the revocation and FAILS,
# naming what it still sees, if a revoked grant is still present —
# a 2xx on the DELETE is the vendor accepting the request, not the
# estate changing.
has_verification_probe=True,
note=(
"Removes sharing grants or links from a file on Google Drive, "
"OneDrive/SharePoint, Box or Dropbox. Its own reverse: execute() "
"captures the prior grants into rollback_data before every write "
"(none of these APIs has a recycle bin for permissions), and "
"rollback restores them — with one honest limit, recorded per "
"vendor in the clients: Graph, Box and Dropbox mint a NEW URL "
"when a sharing link is re-created, so a link rollback restores "
"access shape, never the circulating URL. ANALYST approval: "
"cutting access to a document someone is working in is "
"disruption on the same shelf as the other containment verbs."
),
),
"sync_detection_rule": CapabilityContract(
impact=ActionImpact.MODERATE,
approval=ApprovalRequirement.ANALYST,
+12
View File
@@ -101,6 +101,10 @@ class ActionType(str, Enum):
RESTORE_EMAIL = "restore_email"
BLOCK_SENDER = "block_sender"
UNBLOCK_SENDER = "unblock_sender"
# WS4.5 — remove sharing grants / links from a file across the four
# file-sharing estates (Drive, OneDrive/SharePoint, Box, Dropbox). In
# this enum because the post-action verifier is keyed by ActionType.
REVOKE_FILE_SHARE = "revoke_file_share"
class ActionStatus(str, Enum):
@@ -186,6 +190,10 @@ ACTION_BLAST_RADIUS: dict[ActionType, BlastRadius] = {
ActionType.RESTORE_EMAIL: BlastRadius.LOW,
ActionType.BLOCK_SENDER: BlastRadius.LOW,
ActionType.UNBLOCK_SENDER: BlastRadius.LOW,
# WS4.5 — one file's sharing surface: above a queue flip, below a host
# isolation. Removing a grant interrupts whoever was working in the
# document, and every arm captures prior grants for rollback.
ActionType.REVOKE_FILE_SHARE: BlastRadius.MEDIUM,
}
# Actions that require explicit human approval
@@ -205,6 +213,10 @@ APPROVAL_REQUIRED_ACTIONS = {
# exists to catch.
ActionType.PURGE_EMAIL,
ActionType.BLOCK_SENDER,
# Removing somebody's access to a document they may be working in is
# never automatic either; the capability contract says ANALYST and the
# legacy door must agree (test_approval_doors_agree).
ActionType.REVOKE_FILE_SHARE,
}
@@ -15,6 +15,7 @@ from app.executors.endpoint import (
RunAVScanExecutor,
RunScriptExecutor,
)
from app.executors.fileshare import RevokeFileShareExecutor
from app.executors.identity import (
DisableUserExecutor,
ForceMFAExecutor,
@@ -65,6 +66,8 @@ EXECUTOR_REGISTRY = {
ActionType.CREATE_NOTABLE_EVENT: CreateNotableEventExecutor(),
ActionType.SYNC_DETECTION_RULE: SyncDetectionRuleExecutor(),
ActionType.UPDATE_WATCHER: UpdateWatcherExecutor(),
# WS4.5 — share revocation across the four file-sharing estates.
ActionType.REVOKE_FILE_SHARE: RevokeFileShareExecutor(),
ActionType.BLOCK_IOC: BlockIOCExecutor(),
# Phase 3.3 — alert lifecycle (Splunk ES / Elastic Security / MDE).
ActionType.ACK_ALERT: AckAlertExecutor(),
@@ -31,6 +31,12 @@ from typing import Any
import structlog
from app.clients.factories import _entra_client, _gmail_client, _m365_mail_client, _mde_client, _okta_client
from app.clients.fileshare_clients import (
BoxShareClient,
DropboxShareClient,
GoogleDriveShareClient,
GraphDriveClient,
)
from app.clients.gmail_client import GmailClient
from app.clients.m365_mail_client import RECOVERABLE_ITEMS
from app.core.config import get_settings
@@ -613,8 +619,75 @@ async def _probe_sync_detection_rule(target: str, params: dict[str, Any]) -> boo
return None
async def _probe_revoke_file_share(target: str, params: dict[str, Any]) -> bool | None:
"""The revoked grant is absent, by independent read-back (WS4.5).
The executor already read back once inside ``execute()``; this probe is
the *independent* second look the contract requires for a verb whose
failure mode is a 2xx that changed nothing. It re-lists the grants
through the same vendor client family and answers: ``False`` when a
grant the request asked to revoke is still visible, ``True`` when it is
gone, ``None`` when no vendor credentials (or no target identity) are
present — an unverifiable claim stays unverified rather than certified.
"""
mode = str(params.get("revoke") or "grantee")
grantee = str(params.get("grantee_email") or "").lower()
if mode == "grantee" and not grantee:
return None
try:
key, subject = params.get("gws_service_account_key"), params.get("gws_subject_email")
if key and subject:
drive = GoogleDriveShareClient(key, subject, transport=params.get("_transport"))
perms = await drive.list_permissions(target)
if mode == "grantee":
return not any(str(p.get("emailAddress") or "").lower() == grantee for p in perms)
return not any(p.get("type") in ("anyone", "domain") for p in perms)
if params.get("azure_tenant_id") and params.get("azure_client_id") and params.get("azure_client_secret"):
drive_id = str(params.get("drive_id") or "")
if not drive_id:
return None
graph = GraphDriveClient(
str(params["azure_tenant_id"]),
str(params["azure_client_id"]),
str(params["azure_client_secret"]),
transport=params.get("_transport"),
)
perms = await graph.list_permissions(drive_id, target)
if mode == "grantee":
def _emails(p: dict[str, Any]) -> list[str]:
out = [str(((p.get("grantedToV2") or {}).get("user") or {}).get("email") or "")]
out += [str((ident.get("user") or {}).get("email") or "") for ident in p.get("grantedToIdentitiesV2") or []]
return [e.lower() for e in out if e]
return not any(grantee in _emails(p) for p in perms)
return not any("link" in p for p in perms)
if params.get("box_access_token"):
box = BoxShareClient(str(params["box_access_token"]), transport=params.get("_transport"))
if mode == "grantee":
collabs = await box.list_collaborations(target)
return not any(str((c.get("accessible_by") or {}).get("login") or "").lower() == grantee for c in collabs)
return await box.get_shared_link(target) is None
if params.get("dropbox_access_token"):
dropbox = DropboxShareClient(str(params["dropbox_access_token"]), transport=params.get("_transport"))
if mode == "grantee":
members = await dropbox.list_file_members(target)
return not any(str(((u.get("user") or {}).get("email")) or "").lower() == grantee for u in members.get("users") or [])
return not await dropbox.list_shared_links(target)
except Exception as exc: # noqa: BLE001 — an unreachable vendor is indeterminate, never certified
logger.warning("verification.revoke_file_share_probe_error", target=target, error=str(exc)[:300])
return None
return None
_DEFAULT_PROBES: dict[ActionType, Probe] = {
ActionType.ISOLATE_HOST: _probe_isolate,
ActionType.REVOKE_FILE_SHARE: _probe_revoke_file_share,
ActionType.BLOCK_IP: _probe_block_ip,
ActionType.DISABLE_USER: _probe_disable_user,
ActionType.ALLOW_IP: _probe_allow_ip,
@@ -86,7 +86,9 @@ def test_register_builtin_executors_returns_full_count() -> None:
# `lookup_network_device`.
# Plus 1 from WS1.1: the Elastic `sync_detection_rule` arm, registered
# when the Splunk adapter stopped borrowing the Elastic executor.
assert count == 168
# Plus 4 from WS4.5: `revoke_file_share` across Google Drive,
# OneDrive/SharePoint (Graph), Box and Dropbox.
assert count == 172
def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:
@@ -123,6 +125,7 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:
("aws", "restore_role_sessions"),
("aws", "revoke_role_sessions"),
("aws_security_groups", "allow_ip"),
("box", "revoke_file_share"),
("aws_security_groups", "block_ip"),
("azure_entra", "disable_service_identity"),
("azure_entra", "disable_user"),
@@ -159,6 +162,7 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:
("defender", "suppress_alert"),
("defender", "unisolate_host"),
("defender", "update_alert_disposition"),
("dropbox", "revoke_file_share"),
("elastic", "ack_alert"),
("elastic", "search_siem"),
("elastic", "sync_detection_rule"),
@@ -193,6 +197,7 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:
("google_workspace", "get_oauth_grants"),
("google_workspace", "get_user_activity"),
("google_workspace", "purge_email"),
("google_workspace", "revoke_file_share"),
("google_workspace", "reset_password"),
("google_workspace", "restore_email"),
("google_workspace", "revoke_oauth_grant"),
@@ -202,6 +207,7 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:
("google_workspace", "unblock_sender"),
("jira", "create_ticket"),
("m365", "block_sender"),
("m365", "revoke_file_share"),
("m365", "purge_email"),
("m365", "restore_email"),
("m365", "search_mailboxes"),
@@ -299,7 +305,7 @@ def test_register_builtin_executors_is_idempotent_with_overwrite() -> None:
register_builtin_executors()
# Second call without overwrite would raise — confirm overwrite works.
count = register_builtin_executors(overwrite=True)
assert count == 168
assert count == 172
def test_register_builtin_twice_without_overwrite_raises() -> None:
@@ -0,0 +1,434 @@
"""`revoke_file_share` reaches the vendor it names, verifies, and rolls back.
What this closes (WS4.5 of the gap-closure program)
---------------------------------------------------
A leaked document's blast radius is its sharing grants, and the product had
no verb for them: no executor touched Drive, OneDrive/SharePoint, Box or
Dropbox permissions at all. This file pins the three properties the new
capability's contract declares, per vendor, against mock vendor servers
driven through the real clients:
* **Prior grants are captured before the write** — the executor's first
request is the listing, and ``rollback_data`` carries exactly what the
pre-write listing returned.
* **The write is verified by read-back** — a vendor that answers 2xx on the
DELETE but still lists the grant afterwards FAILS the action naming what
it still sees, because a 2xx is the vendor accepting the request, not the
estate changing.
* **Rollback restores the captured grants** and returns ``False`` when the
vendor refuses; a re-created sharing link on Graph/Box/Dropbox is a new
URL (vendor fact) and the restore happens through the link-creation call,
never through a pretended un-revoke.
* ``dry_run`` through the builtin adapter strips credentials, so the mock
vendor sees **zero requests**.
* The independent post-action probe answers gone/present/unverifiable
honestly.
"""
from __future__ import annotations
from typing import Any
from uuid import uuid4
import httpx
import pytest
from app.executors.fileshare import RevokeFileShareExecutor
from app.live_actions.builtins import (
BoxRevokeFileShare,
DropboxRevokeFileShare,
GoogleDriveRevokeFileShare,
M365RevokeFileShare,
)
from app.live_actions.capability_contracts import CAPABILITY_CONTRACTS
from app.live_actions.models import LiveActionRequest, LiveActionStatus
from app.models.action import ActionRequest, ActionStatus, ActionType
from app.services.verification import _probe_revoke_file_share
FILE = "file-123"
def _request(params: dict[str, Any]) -> ActionRequest:
return ActionRequest(
incident_id=uuid4(),
tenant_id=uuid4(),
action_type=ActionType.REVOKE_FILE_SHARE,
target=FILE,
parameters=params,
requested_by="tester",
rationale="",
)
# ---------------------------------------------------------------------------
# Google Drive
# ---------------------------------------------------------------------------
class _DriveVendor:
"""Drive v3 permissions, stateful; `frozen=True` simulates the lying
vendor whose DELETE answers 204 and deletes nothing."""
def __init__(self, *, frozen: bool = False) -> None:
self.permissions: dict[str, dict[str, Any]] = {
"p-owner": {"id": "p-owner", "type": "user", "role": "owner", "emailAddress": "owner@example.com"},
"p-mallory": {"id": "p-mallory", "type": "user", "role": "writer", "emailAddress": "mallory@example.com"},
"p-anyone": {"id": "p-anyone", "type": "anyone", "role": "reader"},
}
self.frozen = frozen
self.requests: list[str] = []
def handle(self, request: httpx.Request) -> httpx.Response:
self.requests.append(f"{request.method} {request.url.path}")
path = request.url.path
if path.endswith("/token"):
return httpx.Response(200, json={"access_token": "tok", "expires_in": 3600})
if request.method == "GET" and path.endswith("/permissions"):
return httpx.Response(200, json={"permissions": list(self.permissions.values())})
if request.method == "DELETE" and "/permissions/" in path:
perm_id = path.rsplit("/", 1)[-1]
if not self.frozen:
self.permissions.pop(perm_id, None)
return httpx.Response(204)
if request.method == "POST" and path.endswith("/permissions"):
import json as _json
body = _json.loads(request.content)
new_id = f"p-restored-{len(self.permissions)}"
self.permissions[new_id] = {"id": new_id, **body}
return httpx.Response(200, json=self.permissions[new_id])
return httpx.Response(404, json={"error": path})
@pytest.fixture(scope="module")
def sa_key() -> dict[str, Any]:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pem = key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
).decode()
return {"client_email": "svc@example.iam.gserviceaccount.com", "private_key": pem}
def _drive_params(vendor: _DriveVendor, sa_key: dict[str, Any], **extra: Any) -> dict[str, Any]:
return {
"gws_service_account_key": sa_key,
"gws_subject_email": "admin@example.com",
"_transport": httpx.MockTransport(vendor.handle),
**extra,
}
class TestGoogleDriveArm:
@pytest.mark.asyncio
async def test_revokes_a_grantee_with_capture_and_readback(self, sa_key: dict[str, Any]) -> None:
vendor = _DriveVendor()
result = await RevokeFileShareExecutor().execute(
_request(_drive_params(vendor, sa_key, revoke="grantee", grantee_email="mallory@example.com"))
)
assert result.status == ActionStatus.COMPLETED, result.error
assert result.output["verified_by_readback"] is True
# capture-before-write: the first vendor call after auth is the listing
api_calls = [r for r in vendor.requests if "/token" not in r]
assert api_calls[0].startswith("GET"), api_calls
# the captured prior grants are the rollback payload
captured = {g["id"] for g in result.rollback_data["grants"]}
assert captured == {"p-mallory"}
# the owner and the link survived a grantee-scoped revocation
assert "p-owner" in vendor.permissions and "p-anyone" in vendor.permissions
assert "p-mallory" not in vendor.permissions
@pytest.mark.asyncio
async def test_links_mode_removes_the_anyone_grant_only(self, sa_key: dict[str, Any]) -> None:
vendor = _DriveVendor()
result = await RevokeFileShareExecutor().execute(_request(_drive_params(vendor, sa_key, revoke="links")))
assert result.status == ActionStatus.COMPLETED, result.error
assert "p-anyone" not in vendor.permissions
assert "p-mallory" in vendor.permissions
@pytest.mark.asyncio
async def test_a_lying_vendor_fails_the_action(self, sa_key: dict[str, Any]) -> None:
"""204 on the DELETE, grant still listed — the read-back is the check."""
vendor = _DriveVendor(frozen=True)
result = await RevokeFileShareExecutor().execute(
_request(_drive_params(vendor, sa_key, revoke="grantee", grantee_email="mallory@example.com"))
)
assert result.status == ActionStatus.FAILED
assert "read-back still shows" in (result.error or "")
@pytest.mark.asyncio
async def test_rollback_restores_the_captured_grant(self, sa_key: dict[str, Any]) -> None:
vendor = _DriveVendor()
params = _drive_params(vendor, sa_key, revoke="grantee", grantee_email="mallory@example.com")
executor = RevokeFileShareExecutor()
result = await executor.execute(_request(params))
assert result.status == ActionStatus.COMPLETED
assert await executor.rollback(result, params) is True
emails = {p.get("emailAddress") for p in vendor.permissions.values()}
assert "mallory@example.com" in emails
@pytest.mark.asyncio
async def test_nothing_matching_is_a_failure_not_a_silent_success(self, sa_key: dict[str, Any]) -> None:
vendor = _DriveVendor()
result = await RevokeFileShareExecutor().execute(
_request(_drive_params(vendor, sa_key, revoke="grantee", grantee_email="nobody@example.com"))
)
assert result.status == ActionStatus.FAILED
assert "nothing was revoked" in (result.error or "")
@pytest.mark.asyncio
async def test_probe_answers_gone_and_present(self, sa_key: dict[str, Any]) -> None:
vendor = _DriveVendor()
params = _drive_params(vendor, sa_key, revoke="grantee", grantee_email="mallory@example.com")
assert await _probe_revoke_file_share(FILE, params) is False # still present
del vendor.permissions["p-mallory"]
assert await _probe_revoke_file_share(FILE, params) is True # gone
assert await _probe_revoke_file_share(FILE, {"revoke": "grantee"}) is None # unverifiable
# ---------------------------------------------------------------------------
# Microsoft Graph (OneDrive / SharePoint)
# ---------------------------------------------------------------------------
class _GraphVendor:
def __init__(self) -> None:
self.permissions: dict[str, dict[str, Any]] = {
"g-owner": {"id": "g-owner", "roles": ["owner"], "grantedToV2": {"user": {"email": "owner@example.com"}}},
"g-mallory": {"id": "g-mallory", "roles": ["write"], "grantedToV2": {"user": {"email": "mallory@example.com"}}},
"g-link": {"id": "g-link", "roles": ["read"], "link": {"type": "view", "scope": "anonymous", "webUrl": "https://1drv.ms/old"}},
}
self.requests: list[str] = []
self.invited: list[dict[str, Any]] = []
self.links_created: list[dict[str, Any]] = []
def handle(self, request: httpx.Request) -> httpx.Response:
import json as _json
self.requests.append(f"{request.method} {request.url.path}")
path = request.url.path
if path.endswith("/token"):
return httpx.Response(200, json={"access_token": "tok"})
if request.method == "GET" and path.endswith("/permissions"):
return httpx.Response(200, json={"value": list(self.permissions.values())})
if request.method == "DELETE" and "/permissions/" in path:
self.permissions.pop(path.rsplit("/", 1)[-1], None)
return httpx.Response(204)
if request.method == "POST" and path.endswith("/invite"):
body = _json.loads(request.content)
self.invited.append(body)
new_id = f"g-reinvited-{len(self.invited)}"
self.permissions[new_id] = {
"id": new_id,
"roles": body["roles"],
"grantedToV2": {"user": {"email": body["recipients"][0]["email"]}},
}
return httpx.Response(200, json={"value": [self.permissions[new_id]]})
if request.method == "POST" and path.endswith("/createLink"):
body = _json.loads(request.content)
self.links_created.append(body)
new_id = f"g-newlink-{len(self.links_created)}"
self.permissions[new_id] = {
"id": new_id,
"roles": ["read"],
"link": {"type": body["type"], "scope": body["scope"], "webUrl": "https://1drv.ms/NEW"},
}
return httpx.Response(201, json=self.permissions[new_id])
return httpx.Response(404, json={"error": path})
def _graph_params(vendor: _GraphVendor, **extra: Any) -> dict[str, Any]:
return {
"azure_tenant_id": "t",
"azure_client_id": "c",
"azure_client_secret": "s",
"drive_id": "drv-1",
"_transport": httpx.MockTransport(vendor.handle),
**extra,
}
class TestGraphArm:
@pytest.mark.asyncio
async def test_revokes_links_and_rolls_back_with_a_new_url(self) -> None:
vendor = _GraphVendor()
params = _graph_params(vendor, revoke="links")
executor = RevokeFileShareExecutor()
result = await executor.execute(_request(params))
assert result.status == ActionStatus.COMPLETED, result.error
assert "g-link" not in vendor.permissions
assert "g-mallory" in vendor.permissions # scoped to links
# the honest note travels on the result
assert any("new URL" in n for n in result.output["notes"])
# rollback re-creates the link (a NEW url, through createLink)
assert await executor.rollback(result, params) is True
assert vendor.links_created and vendor.links_created[0]["type"] == "view"
@pytest.mark.asyncio
async def test_grantee_rollback_restores_via_invite_without_mail(self) -> None:
vendor = _GraphVendor()
params = _graph_params(vendor, revoke="grantee", grantee_email="mallory@example.com")
executor = RevokeFileShareExecutor()
result = await executor.execute(_request(params))
assert result.status == ActionStatus.COMPLETED, result.error
assert await executor.rollback(result, params) is True
assert vendor.invited and vendor.invited[0]["sendInvitation"] is False
@pytest.mark.asyncio
async def test_missing_drive_id_is_refused(self) -> None:
vendor = _GraphVendor()
params = _graph_params(vendor, revoke="links")
params.pop("drive_id")
result = await RevokeFileShareExecutor().execute(_request(params))
assert result.status == ActionStatus.FAILED
assert "drive_id" in (result.error or "")
# ---------------------------------------------------------------------------
# Box
# ---------------------------------------------------------------------------
class _BoxVendor:
def __init__(self) -> None:
self.collabs: dict[str, dict[str, Any]] = {
"c-owner": {"id": "c-owner", "role": "owner", "accessible_by": {"type": "user", "login": "owner@example.com"}},
"c-mallory": {"id": "c-mallory", "role": "editor", "accessible_by": {"type": "user", "login": "mallory@example.com"}},
}
self.shared_link: dict[str, Any] | None = {"url": "https://box.com/s/old", "access": "open"}
self.requests: list[str] = []
def handle(self, request: httpx.Request) -> httpx.Response:
import json as _json
self.requests.append(f"{request.method} {request.url.path}")
path = request.url.path
if request.method == "GET" and path.endswith("/collaborations"):
return httpx.Response(200, json={"entries": list(self.collabs.values())})
if request.method == "DELETE" and "/collaborations/" in path:
self.collabs.pop(path.rsplit("/", 1)[-1], None)
return httpx.Response(204)
if request.method == "POST" and path.endswith("/collaborations"):
body = _json.loads(request.content)
new_id = f"c-restored-{len(self.collabs)}"
self.collabs[new_id] = {"id": new_id, "role": body["role"], "accessible_by": body["accessible_by"]}
return httpx.Response(201, json=self.collabs[new_id])
if request.method == "GET" and f"/files/{FILE}" in path:
return httpx.Response(200, json={"shared_link": self.shared_link})
if request.method == "PUT" and f"/files/{FILE}" in path:
body = _json.loads(request.content)
if body.get("shared_link") is None:
self.shared_link = None
else:
self.shared_link = {"url": "https://box.com/s/NEW", **body["shared_link"]}
return httpx.Response(200, json={"shared_link": self.shared_link})
return httpx.Response(404, json={"error": path})
class TestBoxArm:
@pytest.mark.asyncio
async def test_all_mode_revokes_collaboration_and_link_then_rolls_back(self) -> None:
vendor = _BoxVendor()
params = {"box_access_token": "tok", "_transport": httpx.MockTransport(vendor.handle), "revoke": "all"}
executor = RevokeFileShareExecutor()
result = await executor.execute(_request(params))
assert result.status == ActionStatus.COMPLETED, result.error
assert list(vendor.collabs) == ["c-owner"] # owner survives "all"
assert vendor.shared_link is None
assert await executor.rollback(result, params) is True
logins = {(c.get("accessible_by") or {}).get("login") for c in vendor.collabs.values()}
assert "mallory@example.com" in logins
assert vendor.shared_link is not None and vendor.shared_link["url"].endswith("NEW")
# ---------------------------------------------------------------------------
# Dropbox
# ---------------------------------------------------------------------------
class _DropboxVendor:
def __init__(self) -> None:
self.members: dict[str, str] = {"owner@example.com": "owner", "mallory@example.com": "editor"}
self.links: list[str] = ["https://db.tt/old"]
self.requests: list[str] = []
def handle(self, request: httpx.Request) -> httpx.Response:
import json as _json
self.requests.append(request.url.path)
path = request.url.path
body = _json.loads(request.content) if request.content else {}
if path.endswith("/list_file_members"):
return httpx.Response(
200,
json={"users": [{"user": {"email": e}, "access_type": {".tag": level}} for e, level in self.members.items()]},
)
if path.endswith("/remove_file_member_2"):
self.members.pop(body["member"]["email"], None)
return httpx.Response(200, json={".tag": "success"})
if path.endswith("/add_file_member"):
self.members[body["members"][0]["email"]] = body["access_level"]
return httpx.Response(200, json=[{"result": {".tag": "success"}}])
if path.endswith("/list_shared_links"):
return httpx.Response(200, json={"links": [{"url": u} for u in self.links]})
if path.endswith("/revoke_shared_link"):
self.links = [u for u in self.links if u != body["url"]]
return httpx.Response(200)
if path.endswith("/create_shared_link_with_settings"):
self.links.append("https://db.tt/NEW")
return httpx.Response(200, json={"url": "https://db.tt/NEW"})
return httpx.Response(404, json={"error": path})
class TestDropboxArm:
@pytest.mark.asyncio
async def test_all_mode_revokes_member_and_link_then_rolls_back(self) -> None:
vendor = _DropboxVendor()
params = {"dropbox_access_token": "tok", "_transport": httpx.MockTransport(vendor.handle), "revoke": "all"}
executor = RevokeFileShareExecutor()
result = await executor.execute(_request(params))
assert result.status == ActionStatus.COMPLETED, result.error
assert list(vendor.members) == ["owner@example.com"]
assert vendor.links == []
assert any("new URL" in n for n in result.output["notes"])
assert await executor.rollback(result, params) is True
assert "mallory@example.com" in vendor.members
assert vendor.links == ["https://db.tt/NEW"]
# ---------------------------------------------------------------------------
# The governed surface
# ---------------------------------------------------------------------------
class TestGovernance:
def test_the_contract_declares_probe_and_reverse(self) -> None:
contract = CAPABILITY_CONTRACTS["revoke_file_share"]
assert contract.has_verification_probe is True
assert contract.reverse_capability == "revoke_file_share"
@pytest.mark.asyncio
async def test_dry_run_through_the_builtin_touches_no_vendor(self, sa_key: dict[str, Any]) -> None:
vendor = _DriveVendor()
adapter = GoogleDriveRevokeFileShare()
result = await adapter.execute(
LiveActionRequest(
request_id=uuid4(),
capability="revoke_file_share",
vendor_id="google_workspace",
target=FILE,
params=_drive_params(vendor, sa_key, revoke="grantee", grantee_email="mallory@example.com"),
dry_run=True,
requested_by="tester",
)
)
assert result.status == LiveActionStatus.SIMULATED
assert vendor.requests == [], "a dry run must not touch the vendor"
def test_all_four_adapters_share_the_executor_and_the_capability(self) -> None:
adapters = [GoogleDriveRevokeFileShare, M365RevokeFileShare, BoxRevokeFileShare, DropboxRevokeFileShare]
assert {a.capability for a in adapters} == {"revoke_file_share"}
assert {a.vendor_id for a in adapters} == {"google_workspace", "m365", "box", "dropbox"}
@@ -580,6 +580,30 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
),
note="Writes a record into someone else's queue. Noise, not damage.",
),
"revoke_file_share": CapabilityContract(
impact=ActionImpact.MODERATE,
approval=ApprovalRequirement.ANALYST,
reversal=Reversal.PLATFORM,
reverse_capability="revoke_file_share",
required_permission=_CONTAIN,
# Every arm re-reads the grant list after the revocation and FAILS,
# naming what it still sees, if a revoked grant is still present —
# a 2xx on the DELETE is the vendor accepting the request, not the
# estate changing.
has_verification_probe=True,
note=(
"Removes sharing grants or links from a file on Google Drive, "
"OneDrive/SharePoint, Box or Dropbox. Its own reverse: execute() "
"captures the prior grants into rollback_data before every write "
"(none of these APIs has a recycle bin for permissions), and "
"rollback restores them — with one honest limit, recorded per "
"vendor in the clients: Graph, Box and Dropbox mint a NEW URL "
"when a sharing link is re-created, so a link rollback restores "
"access shape, never the circulating URL. ANALYST approval: "
"cutting access to a document someone is working in is "
"disruption on the same shelf as the other containment verbs."
),
),
"sync_detection_rule": CapabilityContract(
impact=ActionImpact.MODERATE,
approval=ApprovalRequirement.ANALYST,
@@ -210,6 +210,8 @@ class Capability(str, Enum):
SEARCH_SIEM = "search_siem"
CREATE_NOTABLE_EVENT = "create_notable_event"
SYNC_DETECTION_RULE = "sync_detection_rule"
# WS4.5 — share revocation across the four file-sharing estates.
REVOKE_FILE_SHARE = "revoke_file_share"
UPDATE_WATCHER = "update_watcher"
# The return leg. Ingest carries a vendor finding id in as `external_id`;
# this verb carries AiSOC's verdict back out to the same finding, so a