Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-driver): add protected permission modes and consent grants (#2383)

Francesco Bonaccic75e60636c11
diff --git a/docs/content/docs/concepts/how-permission-policies-work.mdx b/docs/content/docs/concepts/how-permission-policies-work.mdx
index 4a84a94af9..8a42964105 100644
--- a/docs/content/docs/concepts/how-permission-policies-work.mdx
+++ b/docs/content/docs/concepts/how-permission-policies-work.mdx
@@ -11,13 +11,21 @@ Cua Driver's permission policy engine sits between daemon clients (MCP, CLI, or
Every tool call reaches a running `cua-driver serve` daemon. A thin `cua-driver mcp` process proxies MCP calls over the local socket; `cua-driver call` sends its one request to the same daemon.
-The policy engine is always invoked in the daemon before tool execution. The MCP proxy also evaluates the policy when `CUA_DRIVER_POLICY_FILE` is present in its environment, providing an earlier defense-in-depth check. A denial at either point returns an error to the client; the tool implementation is never reached.
+The authorization coordinator is always invoked in the daemon before tool execution. It evaluates the built-in risk map, managed policy, user policy, and autonomous session manifest in order. The MCP proxy may repeat the user-policy check as an earlier defense-in-depth check. A denial at either point returns an error to the client; the tool implementation is never reached.
## Deny-by-default
The engine is deny-by-default. A tool that is not explicitly mentioned in the policy is blocked. This means adding a new tool to the driver does not automatically expose it to agents; each tool must be explicitly permitted.
-The deny-by-default behavior applies only when a policy is active. When `CUA_DRIVER_POLICY_FILE` is not set, the engine is disabled and every call is allowed, preserving the driver's original behavior for users who do not need access control.
+The deny-by-default behavior applies within each configured policy. When `CUA_DRIVER_POLICY_FILE` is unset, that layer is absent for compatibility. The reviewed built-in tool and risk map still rejects unknown tools, and the default permission mode remains `standard`.
+
+An explicitly configured policy path is an operator assertion that the layer must exist. If the path is missing, unreadable, empty, or invalid, the daemon exits before binding its action socket.
+
+## Policy composition and modes
+
+`CUA_DRIVER_MANAGED_POLICY_FILE` loads an administrator ceiling in the same YAML or Rego formats. A call must pass both the managed and user layers. The daemon hashes each immutable policy snapshot and includes those hashes in protected approval requests and status output.
+
+Permission mode is separate from capability policy. Policy answers whether a call is inside the allowed ceiling. Mode answers whether an allowed operation must stop for protected human approval. Approval and unrestricted mode cannot widen the policy ceiling. See [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes).
## Process-lifetime snapshot
@@ -76,7 +84,7 @@ A policy that allows `screenshot` permits an agent to take an unlimited number o
## Trust model
-The policy is evaluated in the same process as the tool implementation. An agent that has arbitrary code execution on the host can bypass the policy by calling the tool implementation directly. The engine is designed for use with agents that interact over the MCP protocol, not as a security boundary against code running locally.
+The policy is evaluated in the same process as the tool implementation. An agent that can replace or inject code into the daemon can bypass it. Local shell access alone does not turn ordinary MCP arguments, files, TTY input, or environment values into protected consent. Use a trusted launcher to own daemon startup settings and OS isolation to keep the agent from replacing the daemon.
For remote agents connecting through the daemon's network socket, the policy provides a meaningful boundary: the daemon will not execute a tool that the policy blocks, regardless of what the agent sends.
@@ -84,4 +92,5 @@ For remote agents connecting through the daemon's network socket, the policy pro
- [Restrict tool access with permission policies](/how-to-guides/driver/restrict-tool-access): step-by-step setup guide
- [Permission policies](/reference/cua-driver/permission-policies): YAML schema and Rego input interface
+- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): how mode, consent grants, and policy layers compose
- [Process model](/reference/cua-driver/process-model): how CLI and MCP clients reach the daemon
diff --git a/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx b/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
index b562dea087..36abc977b1 100644
--- a/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
+++ b/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
@@ -80,30 +80,39 @@ that is already running and authenticated. Cua Driver does not restart the
browser, copy the profile, or modify profile files. The route supports Chrome
and Edge on macOS and Windows, plus Chrome in the validated Linux X11 and Sway
configurations. Chromium and Edge have descriptor-backed Linux routes but are
-not yet product-validated there. Start a named driver session and mint an approval
-artifact for the exact process, native window, and session:
+not yet product-validated there. Start a named driver session and choose the
+permission mode before launching the daemon. The standalone daemon has no
+certified protected host provider, so `standard` and `autonomous` refuse
+logged-in profile attachment. For a disposable VM where you accept the risk,
+launch unrestricted mode explicitly:
```bash
-cua-driver browser-approve \
- --strategy existing_profile \
- --pid 844 \
- --window-id 10725 \
- --session research-1
+cua-driver serve \
+ --permission-mode unrestricted \
+ --dangerously-bypass-approvals
```
-The command requires an interactive terminal and asks you to type `APPROVE`.
-Pass its five-minute, single-use token to `browser_prepare`:
+Then request the exact process and native window:
```jsonc
browser_prepare({
"pid": 844,
"window_id": 10725,
"session": "research-1",
- "strategy": {"kind": "existing_profile"},
- "approval_token": "<token>"
+ "strategy": {"kind": "existing_profile"}
})
```
+> **Warning:** Unrestricted mode has no runtime Cua approval prompts and makes
+> no prompt-injection safety claim. Prefer `isolated_new`. Use unrestricted
+> existing-profile attachment only in an environment whose account and data
+> exposure you accept.
+
+A trusted embedding host can install the protected-consent provider described
+in [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes).
+In that configuration, `standard` prompts once for the bound browser resource,
+and `autonomous` uses the launch-approved session manifest.
+
The browser may display its own remote-debugging consent prompt. Cua Driver will
press only the exact browser-owned semantic allow action for this approved
process and window. An absent, ambiguous, dismissed, or unrecognized prompt is
diff --git a/docs/content/docs/how-to-guides/driver/keep-running.mdx b/docs/content/docs/how-to-guides/driver/keep-running.mdx
index 67facb0afa..f8973fdbf7 100644
--- a/docs/content/docs/how-to-guides/driver/keep-running.mdx
+++ b/docs/content/docs/how-to-guides/driver/keep-running.mdx
@@ -19,6 +19,11 @@ If you have a checkout of the [cua repo](https://github.com/trycua/cua), the hel
bash libs/cua-driver/scripts/install-local.sh --autostart
```
+Local installers embed the checkout's full Git commit in
+`get_config.source_sha`. A build from a modified or untracked source tree uses
+`<commit>-dirty` so it cannot be mistaken for an exact commit build. Source
+snapshots without `.git` must provide `CUA_DRIVER_SOURCE_SHA` explicitly.
+
If you installed via the one-line installer and have no checkout, create the plist yourself. Save this file at `~/Library/LaunchAgents/com.trycua.cua-driver.plist`:
```xml
diff --git a/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx b/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx
index 894019752d..a169986d3f 100644
--- a/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx
+++ b/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx
@@ -201,7 +201,7 @@ CUA_DRIVER_POLICY_FILE=~/.cua-driver/policy.yaml cua-driver serve
</Tab>
</Tabs>
-The policy is loaded once when the process starts. Changing the file while the daemon is running has no effect until the daemon restarts.
+The policy is loaded once when the process starts. Changing the file while the daemon is running has no effect until the daemon restarts. A missing or invalid configured file prevents the daemon from binding its action socket.
## Verify the policy is active
@@ -246,7 +246,7 @@ If you use `cua-driver autostart enable`, add the environment variable to the la
## Troubleshooting
**All calls are denied even though my policy allows them.**
-Check that `CUA_DRIVER_POLICY_FILE` points to the correct path and that the daemon has been restarted after setting the variable. A typo in the file path means the policy file is not found, which disables enforcement and allows all calls. A warning is logged at startup when the path does not exist.
+Check that `CUA_DRIVER_POLICY_FILE` points to the correct path and that the daemon has been restarted after setting the variable. A typo or unreadable file now fails daemon startup instead of disabling enforcement.
**The daemon fails to start with a policy parse error.**
YAML policies must not contain empty tool names, and Rego policies must define `data.cua.policy.allow` as a boolean rule. Run `cat $CUA_DRIVER_POLICY_FILE` to confirm the file is readable and syntactically valid.
@@ -255,10 +255,11 @@ YAML policies must not contain empty tool names, and Rego policies must define `
The rule might exist but the argument constraints are not satisfied. Check the denial message: `"argument 'text' must be at most 500 characters"` tells you which constraint failed. For Rego policies, add a `print` statement temporarily to trace which branch runs.
**I want to allow all tools.**
-Do not set `CUA_DRIVER_POLICY_FILE`. When the variable is absent, the policy engine is disabled and every tool call is allowed.
+Do not set `CUA_DRIVER_POLICY_FILE`. The user-policy layer is then absent. The built-in risk map, permission mode, managed policy, and active resource grants still apply.
## Related
- [Permission policies](/reference/cua-driver/permission-policies): full YAML schema and Rego interface reference
- [How permission policies work](/concepts/how-permission-policies-work): the engine internals, evaluation order, and trust model
+- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): standard, autonomous, and unrestricted startup
- [MCP tools](/reference/cua-driver/mcp-tools): complete list of tool names and their arguments
diff --git a/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx b/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
index 952e14b6ca..846f8fe109 100644
--- a/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
+++ b/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
@@ -16,18 +16,29 @@ profiles.
"pid": 844,
"window_id": 10725,
"session": "research-1",
- "strategy": {"kind": "existing_profile"},
- "approval_token": "<interactive one-use token>"
+ "strategy": {"kind": "existing_profile"}
}
```
`pid`, `window_id`, and `session` are required. `strategy` cannot be combined
-with legacy `allow_launch` or `profile` fields. The approval token must be
-minted by `cua-driver browser-approve` for the exact same values. It expires
-after five minutes, is consumed once, and is consumed by a mismatched attempt.
+with legacy `allow_launch` or `profile` fields. Authorization depends on the
+daemon's immutable [permission mode](/reference/cua-driver/permission-modes):
+
+- `standard` requests exact protected consent from a certified host provider.
+- `bounded` requires the launch-approved manifest to list this PID/window;
+ the provider activates its persistent Stop indicator without a second prompt.
+- `unrestricted` attaches without a runtime approval after the trusted launcher
+ supplied `--dangerously-bypass-approvals`.
The internal approval marker supplied by an MCP transport does not authorize
-this strategy.
+this strategy. The standalone daemon currently has no certified Codex or Claude
+host provider, so `standard` and `bounded` fail closed there. Use an isolated
+profile or an explicitly launched unrestricted daemon.
+
+The old `browser-approve` file artifact is disabled by default. A trusted
+launcher can temporarily enable it with
+`--allow-legacy-existing-profile-approval`. The artifact is same-user writable
+and is not protected human consent.
## Success result
@@ -80,7 +91,8 @@ by the previous generation.
| --- | --- |
| Network exposure | The accepted DevTools endpoint must be loopback-only. |
| Process binding | The endpoint, native window, and live process fingerprint must agree before every mutation. |
-| Driver authorization | Existing-profile setup needs a single-use interactive artifact; a model-supplied Boolean and ordinary MCP approval are insufficient. |
+| Driver authorization | Standard and bounded setup need a request-bound protected provider; a model-supplied Boolean, ordinary MCP approval, TTY input, and files are insufficient. |
+| Revocation | A protected grant cannot become live until its provider activates persistent Stop UI. `cua-driver revoke` and session end provide additional deny-only paths. |
| Capability scope | Targets, tabs, dialogs, frames, and refs are opaque, session-scoped, and invalidated after navigation or connection-generation changes. |
| Profile handling | Cua Driver does not copy, edit, restart, or terminate the selected existing profile. |
| Residual local risk | CDP itself is not authenticated. Another process running as the same OS user may connect to an exposed endpoint outside Cua Driver. |
@@ -104,6 +116,7 @@ for why Cua Driver uses CDP and which risks remain outside the driver.
| `browser_input_incomplete` | Keystroke typing delivered only a reported prefix. |
| `browser_route_unavailable` | The classified engine or platform has no accepted typed route. For Firefox and Safari, bounded detail identifies the required protocol and current lifecycle limitation. |
| `browser_input_trust_unavailable` | Trusted input cannot preserve background posture. Bounded detail identifies the explicit `dom_event` alternative when a synthetic ref-targeted action is acceptable. |
+| `browser_origin_outside_scope` | A bounded-mode tab left the manifest's allowed origin set; further mutation pauses. |
## Recording and telemetry
@@ -116,7 +129,7 @@ The content-free browser operation and refusal fields are documented in
## Platform scope
-The prompt-assisted route is available for Google Chrome and Microsoft Edge on
+The browser-setup route is implemented for Google Chrome and Microsoft Edge on
macOS and Windows. Chrome and Edge have product-specific acceptance evidence
on Linux X11. Chrome is also accepted on GNOME Wayland, and Chromium is
accepted alongside Chrome and Edge on the validated native-Wayland Sway lane.
@@ -124,7 +137,7 @@ The Chromium-family products use the same descriptor-backed Linux route, but
still need product-specific acceptance evidence on each desktop before they
are listed as validated. Every route
requires an
-exact approved PID and native window, one uniquely matched setup control, a
+exact authorized PID and native window, one uniquely matched setup control, a
loopback endpoint owned by that process, one exact browser-owned consent
action, and a fresh native/CDP rebind.
diff --git a/docs/content/docs/reference/cua-driver/cli-reference.mdx b/docs/content/docs/reference/cua-driver/cli-reference.mdx
index 205bb0f322..750b37a770 100644
--- a/docs/content/docs/reference/cua-driver/cli-reference.mdx
+++ b/docs/content/docs/reference/cua-driver/cli-reference.mdx
@@ -92,12 +92,17 @@ The daemon owns per-process state such as element-index caches, recording state,
| ---- | ---- | ------- | ----------- |
| `--socket` | String | — | Override the daemon socket or named-pipe path. |
| `--pid-file` | String | — | Override the pid-file path on Unix targets. |
+| `--permission-mode` | String | standard | Immutable agent authorization mode: standard, bounded, or unrestricted. |
+| `--session-policy` | String | — | Immutable tool manifest required in bounded mode. |
| `--host-bundle-id` | String | — | Advisory host bundle id label echoed in check_permissions output (embedded mode). |
**Flags:**
| Name | Description |
| ---- | ----------- |
+| `--dangerously-bypass-approvals` | Select unrestricted mode and acknowledge its risk. |
+| `--allow-legacy-existing-profile-approval` | Temporary migration flag for the unprotected file-backed existing-profile artifact. |
+| `--approve-session-policy` | Trusted-launcher confirmation that the exact bounded manifest was reviewed. |
| `--no-permissions-gate` | Skip the macOS first-launch permissions gate. |
| `--embedded` | Run embedded inside a host app: inherit the host's TCC grants, never prompt or relaunch. Also CUA_DRIVER_EMBEDDED=1. |
@@ -280,6 +285,25 @@ Print a pasteable install-layout and permission-attribution report.
## Other commands
+### `cua-driver revoke`
+
+Revoke one or all live authorization/session scopes.
+
+Revocation is deny-only and never accepts an approval token.
+
+**Options:**
+
+| Name | Type | Default | Description |
+| ---- | ---- | ------- | ----------- |
+| `--session` | String | — | Exact session id to stop and revoke. |
+| `--socket` | String | — | Override the daemon socket or named-pipe path. |
+
+**Flags:**
+
+| Name | Description |
+| ---- | ----------- |
+| `--all` | Stop and revoke every live session. |
+
### `cua-driver telemetry`
Inspect or change content-free product telemetry.
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index 98d23a87d6..4ae3184400 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -768,12 +768,12 @@ Read-only browser inspection. Mode 1 (bind): pass pid + window_id of a native br
### `browser_prepare`
-Explicitly prepare an owned DevTools endpoint for a browser pid. Existing endpoints are detected without side effects. Acting setup requires MCP-host approval or a short-lived token from the interactive browser-approve command, allow_launch=true, and a driver-owned isolated profile. It launches a separate browser and never copies, modifies, or terminates the requested user profile. Existing-profile attachment is explicit, requires an exact interactive approval artifact, and never treats ordinary MCP transport approval as profile consent. On proven platforms, that approval also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused.
+Explicitly prepare an owned DevTools endpoint for a browser pid. Existing endpoints are detected without side effects. Acting setup for an isolated profile requires host approval or a short-lived setup token plus allow_launch=true. It launches a separate browser and never copies, modifies, or terminates the requested user profile. Existing-profile attachment is explicit and follows the daemon's immutable permission mode: standard requires a certified protected-consent provider, bounded requires a launch-approved exact resource manifest plus protected indicator, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile consent. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused.
**Arguments:**
- `allow_launch` (boolean, optional): Allow a separate driver-owned isolated Chromium process to be launched (default false).
-- `approval_token` (string, optional): Single-use token minted by `cua-driver browser-approve` for direct CLI/raw use. Omit for an MCP-host-approved call.
+- `approval_token` (string, optional): Legacy single-use setup token. Existing-profile use is disabled unless a trusted launcher explicitly enables the same-user-writable compatibility path.
- `pid` (integer, required): Browser process id to prepare.
- `profile` (object, optional)
- `session` (string, optional): Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session.
diff --git a/docs/content/docs/reference/cua-driver/meta.json b/docs/content/docs/reference/cua-driver/meta.json
index 1caf6010cb..7b70992440 100644
--- a/docs/content/docs/reference/cua-driver/meta.json
+++ b/docs/content/docs/reference/cua-driver/meta.json
@@ -10,6 +10,7 @@
"browser-profile-attachment",
"browser-semantic-snapshots",
"action-selection-policy",
+ "permission-modes",
"permission-policies",
"contracts",
"platform-support",
diff --git a/docs/content/docs/reference/cua-driver/permission-modes.mdx b/docs/content/docs/reference/cua-driver/permission-modes.mdx
new file mode 100644
index 0000000000..350250ba20
--- /dev/null
+++ b/docs/content/docs/reference/cua-driver/permission-modes.mdx
@@ -0,0 +1,196 @@
+---
+title: Permission modes and bounded autonomy
+description: Standard, bounded, and unrestricted startup modes, protected consent, session manifests, and revocation in Cua Driver.
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+Cua Driver resolves one permission mode when the daemon starts. A tool call
+cannot change the mode. The mode controls when work stops for protected human
+approval; permission policies still decide which calls are allowed.
+
+## Modes
+
+| Mode | Startup | Human intervention | Existing logged-in profile |
+| --- | --- | --- | --- |
+| `standard` | Default | Currently once for existing-profile attachment; other risk classes are metadata-only until their adapters ship | Requires a certified protected-consent provider and its persistent Stop indicator |
+| `bounded` | `--permission-mode bounded --session-policy <path> --approve-session-policy` | Once when a trusted launcher reviews and approves the bounded manifest | Allowed only when the manifest names the exact PID/window and a certified indicator provider is available |
+| `unrestricted` | `--dangerously-bypass-approvals` | Once at trusted launch; no runtime Cua approval prompts | May attach without a protected provider after the explicit launch warning |
+
+`autonomous` remains a compatibility alias for `bounded`; new launchers and
+manifests should use `bounded`. `yolo` remains a configuration alias for
+`unrestricted`. The CLI's deliberately alarming bypass flag selects
+`unrestricted` and records the launch-time risk acknowledgement in one step.
+Passing `--permission-mode unrestricted` without that flag still fails closed.
+
+<Callout type="warn">
+ Unrestricted mode does not defend against prompt injection or unintended
+ input. It suppresses Cua approval prompts inside the same built-in, managed,
+ and user-policy ceilings. Run it only in a disposable VM or with accounts and
+ data whose full compromise you accept.
+</Callout>
+
+## The authorization stack
+
+Every daemon transport reaches the same authorization coordinator. A call
+must pass each active layer:
+
+1. The reviewed built-in tool and risk map.
+2. The administrator policy from `CUA_DRIVER_MANAGED_POLICY_FILE`, when set.
+3. The user policy from `CUA_DRIVER_POLICY_FILE`, when set.
+4. The bounded session manifest, in `bounded` mode.
+5. A live resource grant for adapters marked `risk.enforcement: "active"`.
+
+Each layer can narrow access. Approval and unrestricted mode cannot widen a
+policy layer. An unknown tool has no reviewed risk class and is denied.
+
+Tool-list and description responses include risk metadata with `class`,
+`enforcement`, `operation_sensitive`, and `version`. The first active adapter
+is `browser_prepare` with `strategy.kind=existing_profile`. Other listed risks
+are `metadata_only` until their resource, output, and revocation adapters ship.
+
+## Protected consent
+
+A protected provider must return a decision directly to the daemon over an
+authenticated host or OS channel. The request binds the decision to the daemon
+instance, request nonce, generation, mode, policy hashes, sessions, operation,
+expiry, and exact resource. An accepted request becomes live only after the
+provider activates a persistent indicator with a Stop control.
+
+Ordinary MCP elicitation, MCP tool arguments, inherited standard input, a TTY,
+environment variables, and files do not satisfy this contract. They are
+writable by the calling process. If the daemon has no certified provider,
+`standard` and `bounded` refuse existing-profile attachment.
+
+<Callout type="info">
+ The current standalone CLI/MCP daemon has no certified Codex or Claude host
+ provider. Its protected-consent status therefore reports `unavailable`.
+ Isolated browser profiles remain available. A trusted embedding host can
+ install the provider interface in process.
+</Callout>
+
+The old file-backed `browser-approve` artifact is disabled by default for
+existing profiles. A trusted launcher can temporarily enable it with
+`--allow-legacy-existing-profile-approval`, but the artifact is a compatibility
+mechanism, not protected human consent.
+It is accepted only in `standard` mode and cannot be combined with bounded
+or unrestricted startup.
+
+## Bounded session manifest
+
+The launcher loads one YAML manifest at startup and confirms it with the
+separate `--approve-session-policy` flag. The daemon hashes the file, keeps an
+immutable in-memory copy, and refuses to bind when the file is missing,
+invalid, unapproved, or already expired. The maximum lifetime is 24 hours.
+The idle timeout refreshes only after a fully authorized dispatch. Once it
+expires, the manifest is terminal for that daemon instance and cannot be
+revived by another call.
+
+```yaml
+version: 1
+mode: bounded
+expires_after: 8h
+idle_timeout: 30m
+
+resources:
+ browser:
+ existing_profiles:
+ - pid: 844
+ window_id: 10725
+ origins:
+ - https://docs.example.com
+ - https://app.example.com
+
+allow:
+ tools:
+ - start_session
+ - end_session
+ - get_browser_state
+ - browser_prepare
+ - browser_navigate
+ - browser_click
+ - browser_type
+
+deny:
+ tools:
+ - page
+
+ask:
+ tools:
+ - browser_download
+ - browser_set_input_files
+```
+
+Tools omitted from all three sets are denied. `ask` also denies unattended
+dispatch because an agent cannot accept its own prompt. A future protected
+host adapter may resume such a call after protected approval.
+
+For existing-profile preparation, the requested PID and native window must
+match an `existing_profiles` entry. Requested navigation must use an allowed
+origin. Before every browser mutation, the daemon reads the live top-level URL
+through CDP and refuses `browser_origin_outside_scope` if a redirect moved the
+tab outside the manifest.
+
+An origin-scoped manifest cannot also allow generic `page`, desktop input, or
+desktop-state tools that bypass the typed browser-origin adapter. Use
+`browser_click`, `browser_type`, and the other typed browser tools instead.
+
+PID/window binding reduces confused-deputy risk but does not provide permanent
+process identity over a long session: an OS can eventually reuse identifiers.
+Keep manifests short-lived and revoke or restart after a browser relaunch.
+Launch supervisors must preserve `--permission-mode`, the session-policy path,
+and its explicit approval flag on restart; falling back to default `standard`
+is a fail-closed change, not a continuation of the bounded session.
+
+## Embedded and managed launchers
+
+The CLI flag is intentionally convenient, but programmatic launchers retain a
+two-part contract. Set both values on the trusted daemon process:
+
+```sh
+CUA_DRIVER_PERMISSION_MODE=unrestricted \
+CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS=1 \
+ cua-driver serve --embedded --socket <private-socket>
+```
+
+Setting only the mode or only the acknowledgement fails before the daemon
+binds. Treat these as trusted-launch configuration, not tool arguments an
+agent can choose at runtime.
+
+## Managed controls
+
+Set `CUA_DRIVER_MANAGED_POLICY_FILE` to apply an administrator-owned YAML or
+Rego ceiling before the user policy. Both files are loaded once and intersected.
+An explicitly configured missing or invalid path prevents the daemon from
+binding its action endpoint.
+
+Administrators can also set `CUA_DRIVER_DISABLE_UNRESTRICTED=1`. The daemon
+then rejects unrestricted startup even when the danger flag is present.
+
+## Status and revocation
+
+`cua-driver status` reports the effective mode, policy hashes, session-manifest
+hash and expiry, active risk adapters, and protected-provider availability. It
+does not print policy contents or browser data.
+
+End one session and every grant it owns:
+
+```bash
+cua-driver revoke --session research-1
+```
+
+End all live authorization scopes:
+
+```bash
+cua-driver revoke --all
+```
+
+Session end, indicator Stop, grant expiry, policy-context mismatch, browser
+identity drift, reconnect exhaustion, and daemon restart also revoke the
+existing-profile grant.
+
+## Related
+
+- [Permission policies](/reference/cua-driver/permission-policies)
+- [Browser Profile Attachment](/reference/cua-driver/browser-profile-attachment)
+- [Restrict tool access](/how-to-guides/driver/restrict-tool-access)
diff --git a/docs/content/docs/reference/cua-driver/permission-policies.mdx b/docs/content/docs/reference/cua-driver/permission-policies.mdx
index eae5d29f21..a6d4291f26 100644
--- a/docs/content/docs/reference/cua-driver/permission-policies.mdx
+++ b/docs/content/docs/reference/cua-driver/permission-policies.mdx
@@ -5,7 +5,7 @@ description: YAML and Rego permission policy schema, environment variable, evalu
import { Callout } from 'fumadocs-ui/components/callout';
-Cua Driver evaluates a permission policy for every daemon tool call when `CUA_DRIVER_POLICY_FILE` is set. The daemon loads the policy once at process startup; the MCP proxy also evaluates the same policy when it is configured in the proxy environment. CLI and MCP calls therefore share the daemon enforcement point. This page is the reference for the file format, evaluation rules, and Rego interface.
+Cua Driver evaluates every daemon tool call against the configured policy stack. The daemon loads policies once at process startup; the MCP proxy may repeat the user-policy check as defense in depth. CLI, MCP, and raw-socket calls share the daemon enforcement point. This page describes the user and managed policy formats. [Permission modes](/reference/cua-driver/permission-modes) control when a permitted call also needs protected approval.
---
@@ -14,12 +14,13 @@ Cua Driver evaluates a permission policy for every daemon tool call when `CUA_DR
| Variable | Type | Default |
|---|---|---|
| `CUA_DRIVER_POLICY_FILE` | path to a `.yaml`, `.yml`, `.rego` file, or a directory | not set (policy disabled) |
+| `CUA_DRIVER_MANAGED_POLICY_FILE` | path to an administrator-owned policy with the same formats | not set |
When the variable is absent the policy engine is disabled and every call is allowed.
-When the path does not exist the engine starts and logs a warning; all calls are allowed (missing file is treated as no policy).
+When either variable is explicitly set, a missing, unreadable, empty, or invalid path prevents the daemon from binding its action endpoint. An unset variable still means that layer is absent.
-When the path exists but cannot be parsed, the engine fails to start and the daemon exits with an error.
+When both layers are present, a call must pass both. The user policy can narrow the managed policy but cannot widen it. `cua-driver status` reports a SHA-256 content hash for each loaded layer without exposing policy contents.
---
@@ -233,6 +234,8 @@ export CUA_DRIVER_POLICY_FILE=~/.cua-driver/policies
## Evaluation order
+The daemon first checks the managed policy and then the user policy. A denial or evaluation error in either layer stops the call. Within each YAML layer, evaluation follows this order:
+
For YAML policies:
1. Check `deny.tools` — if the tool is listed, **deny** immediately.
@@ -276,4 +279,5 @@ Permission denied: tool 'launch_app' is not allowed by the Rego policy
- [Restrict tool access with permission policies](/how-to-guides/driver/restrict-tool-access): step-by-step setup guide
- [How permission policies work](/concepts/how-permission-policies-work): evaluation engine internals and trust model
+- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): startup modes, session manifests, protected consent, and revocation
- [MCP tools](/reference/cua-driver/mcp-tools): tool names and argument schemas
diff --git a/libs/cua-driver/docs/driver-permission-modes-and-consent-plan.md b/libs/cua-driver/docs/driver-permission-modes-and-consent-plan.md
new file mode 100644
index 0000000000..1d3ccaa883
--- /dev/null
+++ b/libs/cua-driver/docs/driver-permission-modes-and-consent-plan.md
@@ -0,0 +1,1072 @@
+# Cua Driver Permission Modes, Capability Policy, and Human Consent Plan
+
+## Status
+
+- **State:** Reviewed draft / local; implementation plan, not yet a plan of record
+- **Plan date:** 2026-07-20
+- **Base:** exact `origin/main` commit `767acf25f25ea668ffab428e4f2e8985896de98e`
+- **Source version:** Cua Driver `0.9.1`
+- **Scope:** A driver-wide authorization model for MCP, CLI, raw-socket, and
+ embedded use, with `existing_profile` browser attachment as the first
+ high-risk capability migrated to it
+- **Related:**
+ [existing-profile attachment plan](browser-existing-profile-attachment-plan.md),
+ [browser tool implementation plan](browser-tool-implementation-plan.md),
+ [permission-policy concept](../../../docs/content/docs/concepts/how-permission-policies-work.mdx),
+ and [permission-policy reference](../../../docs/content/docs/reference/cua-driver/permission-policies.mdx)
+
+### Implemented contract amendment
+
+The implementation keeps this plan's three semantics but uses `bounded` as
+the canonical middle-mode value; `autonomous` remains a compatibility alias.
+This avoids conflating permission scope with an agent loop's task-continuation
+autonomy. For an interactive CLI launch, `--dangerously-bypass-approvals`
+selects `unrestricted` and serves as the explicit risk acknowledgement.
+Programmatic and embedded launchers retain the two-part
+`CUA_DRIVER_PERMISSION_MODE=unrestricted` plus
+`CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS=1` contract. References to
+`autonomous` below preserve the terminology used when this reviewed plan was
+written.
+
+This plan preserves the existing browser identity, endpoint, generation,
+reconnect, and cleanup work. The earlier attachment plan correctly rejects the
+generic MCP host marker as evidence of a human decision. This plan extends it
+by downgrading the assurance of the same-user-writable, file-backed TTY
+artifact and adding protected approval collectors plus driver-wide modes.
+
+## Definition of done
+
+This project is complete when Cua Driver has one coherent authorization model
+in which:
+
+1. `standard` is the default mode and asks through a protected channel only
+ when a capability or action needs human approval.
+2. `autonomous` runs without routine prompts inside a human-approved,
+ technically enforced capability envelope.
+3. `unrestricted` is an explicit launch-time bypass that the agent cannot
+ enable for itself and that is clearly unsafe outside an isolated
+ environment.
+4. The existing YAML/Rego permission engine remains the maximum capability
+ boundary in every mode; a mode can never turn a policy denial into an
+ allow.
+5. `existing_profile` cannot attach from an agent-facing transport unless a
+ protected approval or an already-valid autonomous/unrestricted grant covers
+ the exact operation.
+6. Every live high-risk grant is visible and revocable, and revocation stops
+ in-flight work, disconnects owned transports, and clears derived
+ capabilities.
+7. The daemon fails closed for configured policy errors, records the effective
+ mode and policy provenance, and has adversarial tests proving that the
+ model/tool channel cannot elevate either.
+8. Documentation accurately states the boundary: the daemon protects against
+ agents limited to its protocol. An agent with arbitrary code execution as
+ the same OS user can bypass the daemon unless the daemon, policy, socket,
+ browser, and agent are separated by an OS sandbox, service identity, VM, or
+ equivalent external boundary.
+
+Delivery requires merged code, cross-platform evidence for each advertised
+collector, release documentation, and post-install smoke tests. A local plan,
+passing unit tests, or a draft pull request is only a checkpoint.
+
+## Executive decision
+
+Adopt three user-facing modes:
+
+| Mode | Intended experience | Security meaning |
+|---|---|---|
+| `standard` | One protected approval for a high-risk resource, then additional approval only for consequential actions or scope expansion | Human remains in the loop at defined boundaries |
+| `autonomous` | One protected session-start approval, then unattended work inside a declared capability envelope | Prompts are replaced by narrow, pre-authorized technical policy—not by model judgment |
+| `unrestricted` | No runtime approval prompts after explicit trusted launch | User accepts prompt-injection and unintended-action risk; the same built-in capability ceiling, managed/user policy, and hard integrity controls still apply |
+
+`yolo` may be a deliberately alarming CLI alias, but `unrestricted` is the
+canonical configuration value. The full flag should be
+`--dangerously-bypass-approvals`.
+
+Do not add a second permission-policy system. The July 2026 YAML/Rego engine is
+the capability foundation. Add a separate mode and consent layer around it.
+
+## Terminology and authorization equation
+
+The design separates concepts that are easy to conflate:
+
+- **OS permission:** TCC, Accessibility, Screen Recording, Windows integrity,
+ portal access, and similar grants from the operating system to Cua Driver.
+- **Capability policy:** the maximum set of tools, arguments, resources, and
+ outputs an agent may use. YAML/Rego currently covers tools and input
+ arguments only.
+- **Permission mode:** when permitted work must stop for a human.
+- **Consent grant:** a bounded authorization for a specific subject, resource,
+ scope, purpose, and time.
+- **Hard invariant:** an integrity rule that no mode or policy can disable.
+
+The new `PermissionMode` name is an agent-authorization concept. It is
+unrelated to the existing macOS TCC startup “permissions gate,”
+`--no-permissions-gate`, and `CUA_DRIVER_RS_PERMISSIONS_GATE`; documentation
+and diagnostics must label the latter **OS permissions** to avoid ambiguity.
+
+The effective decision is an intersection:
+
+```text
+hard invariants
+ AND managed capability ceiling
+ AND user/session capability policy
+ AND mode-specific consent/grant decision
+ AND live resource identity proof
+```
+
+Evaluation rules:
+
+1. A hard-invariant failure always refuses.
+2. A managed-policy denial always refuses.
+3. A user/session-policy denial always refuses.
+4. If policy permits the call, the mode decides whether a protected approval
+ or existing grant is also required.
+5. Approval never widens policy; it only satisfies an `ask` requirement inside
+ the policy envelope.
+6. Resource identity is revalidated immediately before mutation and after
+ reconnect, regardless of mode.
+
+## Threat model
+
+### In scope
+
+Treat the calling model and any content it observes as untrusted. The agent
+may:
+
+- emit arbitrary MCP arguments and raw-socket bytes;
+- run the documented CLI through an agent-controlled shell;
+- own or synthesize a PTY and type `APPROVE`;
+- encounter indirect prompt injection in web pages, documents, messages,
+ terminal output, screenshots, and accessibility trees;
+- replay, reorder, race, or substitute requests and session identifiers;
+- attempt to hide indicators or invoke tools against Cua Driver's own UI;
+- trigger redirects, popups, downloads, uploads, clipboard reads, external
+ messages, purchases, account changes, and destructive actions through
+ apparently ordinary clicks or keystrokes.
+
+The primary protected deployment assumes the agent can reach Cua Driver only
+through an authenticated/authorized daemon transport and cannot modify the
+daemon binary, policy, launcher, approval broker, or OS security state.
+
+### Out of scope without external isolation
+
+The in-process policy engine is not a boundary against arbitrary same-user
+native code. A local agent with unrestricted shell execution can call OS input
+APIs directly, read same-user files, start a second driver, attach to exposed
+debugging endpoints, or modify user-owned launch configuration.
+
+For that threat, require at least one external boundary:
+
+- a separate OS user or service identity for the trusted daemon;
+- a sandbox that prevents the agent from changing launcher/policy files,
+ opening the daemon's private broker channel, or invoking equivalent OS APIs;
+- a VM/container with a dedicated browser profile;
+- managed device policy; or
+- approval on a second device.
+
+`unrestricted` never claims protection from prompt injection. On a personal
+logged-in profile it is an explicit acceptance of account-action and data-loss
+risk, not a secure mode.
+
+## Current-state findings
+
+### What is already strong
+
+- The daemon evaluates an active YAML/Rego policy before tool execution for
+ MCP, CLI, and raw-socket traffic.
+- Active policies are process-lifetime snapshots and deny unmentioned tools by
+ default.
+- Browser attachment artifacts are operation-bound, short-lived, single-use,
+ and consumed before validation.
+- Existing-profile grants bind session, process, native window, fingerprint,
+ endpoint, generation, and reconnect budget.
+- Existing-profile reconnect re-proves endpoint/process identity and
+ invalidates stale capabilities.
+- Session teardown and idle eviction already provide lifecycle hooks that can
+ revoke grants and remove UI.
+
+### Gaps to close
+
+| Priority | Gap | Consequence |
+|---|---|---|
+| P0 | Existing-profile approval is unsigned JSON in a same-user-writable temporary directory; its schema and UUID token format are public | Any same-user process can forge the artifact directly without invoking `browser-approve`; an agent-controlled PTY is a second, weaker forgery path |
+| P0 | Generic MCP provenance is injected for `browser_prepare` only for active proxy sessions, with a parallel marker for downloads | It is not proof that a person approved; existing-profile correctly rejects it, and the mechanism must not be generalized as consent |
+| P0 | No policy, or a configured policy path that does not exist, permits all calls | A typo or missing mount silently becomes unrestricted operation |
+| P0 | Mode/policy selection is not protected from a same-user local agent | A shell-capable agent may restart an unprotected daemon unless launch ownership is separated |
+| P1 | Policy decisions are only `Allow`, `Deny`, or `Error` | There is no protected `ask`/grant resolution layer |
+| P1 | The policy engine constrains tool inputs but not responses, navigation caused by clicks/redirects, quotas, or caller identity | Data access and exfiltration can occur after an apparently allowed call |
+| P1 | There is no persistent, non-optional high-risk-session indicator or emergency stop | Consent is not visibly ongoing or easily revocable |
+| P1 | The agent cursor can be hidden, customized, or disabled | It is useful feedback but cannot serve as the security indicator |
+| P1 | Generic low-level clicks and typing do not reveal semantic consequences | A policy cannot reliably infer purchases, sends, deletions, or account changes from coordinates alone |
+| P2 | Generic MCP elicitation does not mandate a protected human-only UI | A client, hook, or agent-host implementation may synthesize `accept` |
+| P2 | The policy engine does not authenticate callers | Different agents sharing a socket/process can inherit the same capability ceiling |
+| P2 | Audit telemetry is not yet a user-visible authorization ledger | Incident review cannot reconstruct grants, denials, scope changes, and revocations |
+
+## Mode contract
+
+### `standard` — default
+
+`standard` permits ordinary work inside policy without prompt fatigue but
+requires protected consent for:
+
+- attaching to a logged-in or user-owned profile;
+- first access to credentials, private data, clipboard reads, microphone,
+ camera, or other sensitive sources;
+- sending external messages, publishing, purchases, account/security changes,
+ destructive operations, and irreversible submissions;
+- expanding to a new app, profile, window, tab, origin, destination class, or
+ data sink outside the current grant;
+- renewal after expiry, daemon restart, identity change, OS lock, or explicit
+ revocation.
+
+Ordinary read/navigation/input inside the approved resource and scope does not
+prompt again. Exact-identity reconnect does not prompt again while the grant is
+live and within its reconnect budget.
+
+### `autonomous` — bounded unattended operation
+
+The human approves a session manifest before work begins. The manifest names:
+
+- agent/host identity where available;
+- requested duration and idle TTL;
+- permitted apps, profiles, windows, tabs, origins, paths, and destinations;
+- allowed capability classes and relevant argument/output bounds;
+- external side effects that are permitted, denied, or still require a human;
+- data-egress policy and rate/volume limits.
+
+Inside that manifest, calls run unattended. Scope expansion stops and asks; it
+never self-amends. High-consequence categories not explicitly present are
+denied, not inferred from the task prompt.
+
+This is the preferred long-running mode. It provides the productivity goal of
+Codex/Claude-style automation while retaining a technical sandbox.
+
+### `unrestricted` — explicit bypass
+
+`unrestricted` bypasses interactive Cua approval prompts, but it does not
+bypass:
+
+- managed policy;
+- daemon/process/endpoint identity proofs;
+- session ownership and generation invalidation;
+- persistent indicator and emergency revocation;
+- audit records;
+- cleanup, bounded retries, and circuit breakers;
+- OS permissions or platform security controls.
+
+It must be enabled outside the tool protocol through a trusted launcher,
+native settings surface protected by OS authentication, or managed
+configuration. It cannot be entered mid-session. The daemon must restart, show
+a high-severity warning, record the mode, and default back to `standard` on the
+next ordinary launch.
+
+Administrators can disable the mode entirely. On a normal personal profile the
+UI must state that it provides no defense against prompt injection. Product
+documentation should recommend it only for disposable profiles, VMs, or other
+externally isolated environments.
+
+### Built-in baseline and compatibility boundary
+
+All three modes use the same built-in capability ceiling. Mode changes prompt
+resolution, not which classified capabilities exist. Managed and user policy
+can narrow this ceiling; neither approval nor `unrestricted` can widen it.
+
+The built-in ceiling is reviewed and deny-by-default at the classification
+boundary:
+
+- R0 public metadata is included.
+- R1 reversible control is included, with no prompt when it targets a
+ driver-owned isolated resource.
+- R2 observation/control is included but requires a resource grant in
+ `standard`, a covering manifest in `autonomous`, and no prompt in
+ `unrestricted`.
+- R3 consequential operations are included only for typed, reviewed tools and
+ require an action grant in `standard` or explicit manifest entry in
+ `autonomous`.
+- R4/open-ended operations are included only when their implementation has a
+ reviewed enforcement adapter. `standard` uses takeover or exact approval;
+ `autonomous` requires a separately explicit entry; `unrestricted` runs them
+ without Cua prompts.
+- New or unclassified tools/sub-operations are denied in every mode until risk
+ metadata and an enforcement mapping are reviewed.
+- Hard-invariant targets, including Cua's own approval/revocation UI, are never
+ included.
+
+Before changing the default, maintainers must publish and test the exact
+current-tool inventory mapped to R0-R4, including legacy aliases and platform
+stubs. To limit breakage, all current tools remain representable in the
+ceiling, but `standard` may add prompts or refusals where current behavior is
+unprotected. The compatibility sequence remains opt-in, warning, then an
+announced default flip.
+
+## Risk and intervention model
+
+Classify capabilities, not model prose:
+
+| Class | Examples | `standard` | `autonomous` | `unrestricted` |
+|---|---|---|---|---|
+| R0: public metadata | tool schema, display size, driver version | Allow by policy | Allow by policy | Allow without prompt, inside the same ceiling |
+| R1: local reversible control | inspect a test app, click/type in an isolated profile | Allow inside scope | Allow inside manifest | Allow without prompt, inside the same ceiling |
+| R2: sensitive observation/control | screenshots, clipboard read, user documents, logged-in browser | Approve initial resource grant | Session-start manifest approval | Allow without prompt, inside the same ceiling; warn |
+| R3: consequential external action | send message, publish, upload, download, submit form | Action confirmation unless explicitly pre-authorized | Allow only if named in manifest; otherwise deny/ask | Allow without prompt only if the operation remains inside the same ceiling |
+| R4: critical/irreversible | credentials, payments, security settings, account deletion, legal acceptance | Human takeover or exact confirmation at the downstream action | Deny by default; require separately explicit grant | Allow without prompt only if inside the same ceiling; no safety claim |
+
+This classification is metadata attached to typed operations. It must not rely
+only on an LLM or classifier guessing what a generic click means.
+
+For generic pixel/keyboard tools, Cua cannot promise semantic interception.
+Therefore, when such tools target an authenticated or sensitive application:
+
+1. bind them to an approved app/window region;
+2. deny interaction with Cua-owned consent/indicator UI as a hard invariant;
+3. use typed downstream tools for known R3/R4 actions where possible;
+4. require takeover or a broader explicit grant when semantic action identity
+ cannot be proven;
+5. document that unrestricted generic input can perform any action visible to
+ that application.
+
+## Relationship to the YAML/Rego permission engine
+
+Keep the existing policy contract backward-compatible: policy answers whether
+a call is inside the capability envelope. A new authorization coordinator then
+resolves consent.
+
+```rust
+enum CapabilityDecision {
+ Allow,
+ Deny(String),
+ Error(String),
+}
+
+enum AuthorizationDecision {
+ Allow { grant_id: Option<GrantId> },
+ RequireApproval(ApprovalRequest),
+ Deny(String),
+ Error(String),
+}
+
+// Coordinator composition, not caller-controlled input:
+// (CapabilityDecision::Allow, typed_risk, startup_mode, live_grant)
+// -> AuthorizationDecision
+```
+
+Do not force existing Rego policies to return a new ternary value in the first
+release. `data.cua.policy.allow: boolean` remains valid. Risk metadata and mode
+resolution occur after policy evaluation.
+
+### Policy composition
+
+Load and intersect these layers:
+
+1. **Hard invariants:** compiled code, never configurable.
+2. **Managed policy:** administrator-owned; user and agent cannot widen it.
+3. **User policy:** optional YAML/Rego file; can only narrow managed policy.
+4. **Session manifest:** autonomous grant; can only narrow the prior layers.
+
+The daemon reports hashes and provenance for every active layer, never the
+policy contents or sensitive arguments in telemetry.
+
+### Fail-closed changes
+
+- If `CUA_DRIVER_POLICY_FILE` is explicitly set and missing, unreadable, empty
+ in an unintended way, or unsupported, daemon startup fails.
+- Absence of a user file must no longer implicitly mean `unrestricted` once
+ modes reach general availability. `standard` loads a built-in baseline.
+- `--permission-mode unrestricted` suppresses prompts within the same built-in
+ ceiling; it does not select a broader policy. Managed policy may reject the
+ mode.
+- The daemon eagerly loads and validates policy and mode before binding the
+ public socket. This requires moving current lazy `OnceLock` initialization
+ ahead of `UnixListener::bind`, not merely changing the missing-path branch.
+- Status/health output reports mode, policy-active booleans, hashes, collector
+ availability, and whether the launcher is protected.
+- No MCP tool may reload policy, change mode, enable bypass, or mint a grant.
+
+### Policy coverage extensions
+
+Add enforcement beyond `(tool, input arguments)`:
+
+- caller/transport identity and session ownership;
+- resource identity (app, PID, window, profile, tab, origin);
+- derived navigation, redirects, popups, and downloads;
+- output classification and bounds for screenshots, DOM/text, clipboard,
+ files, and browser data;
+- destination/egress policy for uploads, messages, and network requests;
+- per-session rate, count, and byte quotas where meaningful.
+
+Rego can receive a sanitized authorization context, but secrets, raw page
+content, cookies, typed text, and full paths must not be included by default.
+
+### MVP authorization vocabulary
+
+The repository already exposes a versioned dotted capability vocabulary from
+the centralized `default_capabilities_for` map in `tool.rs`. The first
+autonomous manifest uses canonical existing tool names plus that live map; it
+does not invent tokens outside the advertised vocabulary. Static reviewed risk
+metadata maps each canonical tool—and narrowly defined sub-operations where
+the implementation can prove them—to R0-R4 before mode resolution.
+
+Resource bindings such as PID, window, profile, tab, origin, and destination
+remain typed grant fields enforced by the relevant adapter; they are not
+reduced to regexes over arbitrary JSON. A later driver-wide phase may add
+tokens such as `browser.cookie.read`, but only after every additive name has a
+complete tool/sub-operation mapping, input/output semantics, and tests. New
+vocabulary cannot be used in an accepted manifest until enforcement exists.
+
+## Protected consent architecture
+
+### Approval request
+
+The daemon creates an internal request containing:
+
+- unguessable nonce and monotonically increasing generation;
+- daemon instance identity;
+- requesting host/transport identity where proven;
+- mode and policy hashes;
+- operation and risk class;
+- exact resource subject (for example PID, fingerprint, window, profile, tab);
+- human-readable scope, side effects, destinations, and duration;
+- request digest and expiry.
+
+The agent may receive a correlation ID and a redacted description. Possession
+of either never grants authority.
+
+### Approval broker
+
+Only an `ApprovalBroker` can resolve `RequireApproval`. The broker uses a
+private daemon-owned channel with OS peer credentials and returns the decision
+directly to the daemon. It never emits a bearer token into MCP results, CLI
+stdout, inherited stdin, environment variables, or files readable by the
+agent.
+
+The collector contract is pluggable. The MVP collector is a trusted host UI;
+OS authentication and second-device flows are optional stronger or hostless
+collectors that can ship independently:
+
+| Environment | Collector | Required property |
+|---|---|---|
+| Supported agent host | `ProtectedHostCollector` rendered by Codex, Claude, or another recognized client | Human response is outside the model/tool stream, hooks cannot auto-accept, and the authenticated result is bound to the exact request digest |
+| macOS GUI (optional) | `LAContext` biometric approval plus daemon-owned explanatory UI | Enrolled biometric binds the decision to the device owner rather than merely a person at the trusted host |
+| Windows GUI (optional) | Windows Hello/User Consent flow in a trusted daemon-owned UI | OS-authenticated result bound to the request |
+| Linux desktop (optional) | polkit action with a registered authentication agent | Authenticated action through the desktop agent, with exact Cua action identity |
+| Headless (optional) | second-device/device authorization flow | Approval occurs on a separately authenticated device and is bound to the request digest |
+
+Biometric authentication is not an MVP dependency. It strengthens the claim
+from “a person using the trusted host approved” to “the enrolled device owner
+approved,” and provides a possible local collector when no trusted host exists.
+If no recognized trusted host or optional protected collector is available,
+`existing_profile` refuses in `standard` and `autonomous`. It never falls back
+to passcode, TTY, or an agent-hosted confirmation. `unrestricted` remains the
+explicit exception after trusted launch-time risk acceptance.
+
+`/dev/tty` typed `APPROVE` is not a high-assurance collector when the agent can
+own a PTY or drive the terminal. It may remain temporarily as a clearly labeled
+legacy compatibility path for isolated-profile launch, but it must not
+authorize `existing_profile` under `standard` or `autonomous`.
+
+### MCP elicitation
+
+Generic `elicitation/create` is a transport feature, not automatically a
+protected consent boundary. The MCP specification permits clients to choose
+their interaction model, and automation/hooks may synthesize a response.
+
+Use elicitation only when the client negotiates a Cua-recognized protected
+approval-provider capability that guarantees:
+
+- the agent/model cannot generate or modify the response;
+- programmatic hooks cannot auto-accept protected requests;
+- the UI identifies Cua Driver and the exact operation;
+- accept/decline/cancel provenance is authenticated and request-bound;
+- replay and cross-client substitution are rejected.
+
+Without that contract, use an optional daemon-native or second-device
+collector if one is installed; otherwise refuse the request in `standard` and
+`autonomous`.
+Form elicitation may present a confirmation but must never request passwords,
+API keys, cookies, or biometrics.
+
+### Grant properties
+
+All grants are:
+
+- in-memory by default;
+- bound to daemon instance, policy hashes, mode, subject identity, resource,
+ session, scope, and purpose;
+- short-lived, with idle and absolute TTLs appropriate to risk;
+- monotonically generated so stale capabilities fail;
+- revocable and cancellation-aware;
+- non-transferable between transport sessions unless the approved manifest
+ explicitly identifies the shared host;
+- auditable by opaque ID without exposing a bearer credential.
+
+The current five-minute artifact TTL, 30-minute idle TTL, and eight-hour
+absolute browser grant are starting values, not universal defaults. R3/R4
+action confirmations should normally be single-use and expire in minutes.
+
+## Persistent indicator and revocation
+
+Every R2+ grant creates persistent visible state owned by the trusted daemon:
+
+- agent/session identity and color;
+- current mode;
+- controlled app/profile/window and, where possible, origin;
+- idle and absolute expiry separately, with the idle countdown visibly reset
+ only by activity that legitimately refreshes the grant;
+- **Stop** and **Details** controls;
+- high-severity styling for `unrestricted`.
+
+The indicator is separate from the agent cursor. The cursor remains optional
+activity feedback; the security indicator cannot be hidden, recolored into
+invisibility, or disabled while a high-risk grant is live.
+
+Add three revocation paths:
+
+1. persistent UI **Stop**;
+2. registered emergency keyboard shortcut as a human convenience;
+3. `cua-driver revoke [--session <id>|--all]` from a trusted local operator.
+
+The daemon must reject actions targeting its own broker, indicator, status
+item, or protected screen regions. Revocation closes browser/debug transports,
+cancels in-flight mutations, invalidates refs/targets, clears clipboard or
+temporary data owned by the grant, invokes session cleanup, and records the
+reason.
+
+The shortcut is not an authorization boundary because an input-capable agent
+may synthesize the same keys. Enforcement comes from the protected Stop broker,
+grant revocation, and self-target refusal. On a surface where a persistent
+tamper-resistant indicator cannot be rendered, R2+ grants are unavailable
+unless the approving out-of-band device or host provides a continuously
+reachable indicator and Stop control bound to the grant.
+
+This is a meaningful boundary only for agents constrained to the daemon. Same-
+user arbitrary native code still requires external isolation.
+
+## Existing-profile browser migration
+
+### Default behavior
+
+- `isolated_new` remains low-friction and uses the built-in standard policy.
+- `isolated_named` is treated as potentially persistent/sensitive and may need
+ an initial R2 grant depending on whether it contains authenticated state.
+- `existing_profile` is R2 at attach and may produce R3/R4 actions afterward.
+- In `standard`, `existing_profile` requires trusted consent before attach.
+- In `autonomous`, `existing_profile` requires a trusted approval covering it
+ in the session manifest; subsequent in-scope use is unattended.
+- `unrestricted` may attach without runtime approval after explicit trusted
+ launch-time risk acceptance. It cannot be entered or enabled by the running
+ agent.
+- If trusted consent is unavailable, `existing_profile` is unavailable in
+ `standard` and `autonomous`; it must not fall back to TTY approval.
+
+### Attach scope
+
+An existing-profile grant binds at least:
+
+- exact browser PID and process fingerprint;
+- browser product and proven profile identity where available;
+- native approval window and initial exact tab;
+- public session and authenticated transport identity;
+- endpoint owner, CDP generation, reconnect budget;
+- permitted origins/destination classes;
+- allowed browser capability classes;
+- idle/absolute expiry and policy hashes.
+
+The profile-wide CDP transport does not imply profile-wide authorization.
+Target attachment and command dispatch must be limited to tabs/resources
+covered by the grant.
+
+### Data and navigation controls
+
+- Do not expose cookie, credential, password, history, or unrestricted storage
+ extraction APIs to ordinary browser sessions.
+- Disable or separately gate legacy `page`, generic JavaScript, raw CDP, and
+ shell routes that could bypass typed browser restrictions.
+- Apply origin policy to every top-level navigation, including redirects,
+ `window.open`, target creation, history traversal, form submission, and
+ server/client-driven navigation—not only `browser_navigate(url)` arguments.
+- Pause or detach on unapproved cross-origin expansion.
+- Gate downloads, uploads, file pickers, clipboard, credential entry,
+ notifications, external-protocol launches, and permission prompts as
+ separate capabilities.
+- Never return secrets in refusal details, logs, recordings, or policy input.
+
+### Consequential actions
+
+Typed browser tools should surface known submit/action metadata when it can be
+proved, but Cua must not claim perfect semantic detection. For payments,
+credentials, account/security changes, legal acceptance, and destructive
+actions, use one of:
+
+- human takeover with model screenshots/input suspended;
+- downstream site/application integration that performs exact authorization;
+- exact single-use confirmation immediately before the action; or
+- an explicit `unrestricted` risk acceptance.
+
+Model-emitted “are you sure?” text and classifiers may reduce mistakes but are
+not authorization boundaries.
+
+### Transport direction
+
+Keep the current CDP transport while this consent work lands. Independently
+spike `chrome.debugger` extension/native-messaging transport. Current Chrome
+documentation lists the `Input` domain, so the spike should now test actual Cua
+command coverage, target/window identity, extension install/update trust,
+DevTools conflicts, service-worker lifecycle, enterprise controls, and
+cross-platform packaging rather than treating Input availability as unknown.
+
+Do not block the permission-mode project on that transport. If it proves
+viable, it is attractive for the real default profile because Chrome owns the
+debugger attachment UI and revocation semantics.
+
+## Driver-wide capability rollout
+
+After browser attachment, migrate capability groups in this order:
+
+1. **Screen and accessibility observation:** screenshot, window state, OCR,
+ accessibility text, recordings.
+2. **Input and application control:** mouse, keyboard, app launch/quit,
+ foreground changes, desktop-absolute input.
+3. **Clipboard and file transfer:** clipboard read/write, downloads, uploads,
+ file pickers.
+4. **Browser-authenticated control:** existing/named profiles, browser storage,
+ cross-origin navigation.
+5. **Sensitive devices:** microphone, camera, location, notifications.
+6. **Open-ended execution and egress:** shell, JavaScript, raw protocol access,
+ network destinations.
+7. **Consequential workflows:** messages, publishing, purchases, security and
+ account changes, deletion.
+
+Each group needs typed risk metadata, resource scoping, output/egress controls,
+grant lifecycle, indicator text, and adversarial tests before it is advertised
+as protected.
+
+## Proposed configuration surface
+
+Illustrative CLI:
+
+```text
+cua-driver serve --permission-mode standard
+cua-driver serve --permission-mode autonomous --session-policy /trusted/task.yaml
+cua-driver serve --permission-mode unrestricted --dangerously-bypass-approvals
+```
+
+Rules:
+
+- `--permission-mode` is accepted only by trusted daemon startup, never by
+ `call`, MCP, raw tool arguments, or a session tool.
+- `autonomous` without a protected session-manifest approval refuses to bind
+ the public socket or starts in a pending state that serves only health.
+- `unrestricted` requires both the mode and deliberately named danger flag in
+ CLI environments; native UI uses OS authentication and explicit warning.
+- Managed policy can restrict allowed modes, maximum TTLs, capabilities,
+ collectors, profiles, apps, origins, and egress.
+- Mode does not persist by default. Managed installations may persist it only
+ in configuration the agent cannot modify.
+- `status`, `doctor`, and `health_report` expose the effective mode and policy
+ provenance without exposing sensitive policy contents.
+
+Illustrative autonomous manifest:
+
+```yaml
+version: 1
+mode: autonomous
+expires_after: 8h
+idle_timeout: 30m
+
+resources:
+ applications:
+ - bundle_id: com.google.Chrome
+ browser:
+ profile: Work
+ origins:
+ - https://docs.example.com
+ - https://app.example.com
+
+allow:
+ tools:
+ - start_session
+ - end_session
+ - get_browser_state
+ - browser_navigate
+ - browser_click
+ - browser_type
+ - wait
+
+deny:
+ tools:
+ - page
+ - shell_execute
+
+ask:
+ tools:
+ - browser_download
+ - browser_set_input_files
+```
+
+`ask` belongs to the new session-manifest schema, not the existing YAML policy
+schema. The manifest is compiled into an immutable in-memory authorization
+layer and intersected with YAML/Rego and managed policy. The agent may propose
+a manifest but cannot approve or install it.
+
+## Human-intervention expectations
+
+| Scenario | Expected human interventions |
+|---|---:|
+| Read-only task in an isolated browser under `standard` | 0 |
+| Ordinary task in an already-approved logged-in profile under `standard` | 1 initial attach |
+| Same-identity reconnect while grant is live | 0 |
+| Send/publish/purchase/account change under `standard` | 1 immediately before each consequential action or takeover |
+| Eight-hour bounded task under `autonomous` | 1 session-manifest approval; 0 inside scope |
+| Autonomous scope expansion | 1 approval for the expansion |
+| `unrestricted` daemon session | 1 explicit trusted launch enablement; 0 runtime prompts |
+
+Expiry, daemon restart, browser identity change, OS lock/user switch, explicit
+Stop, managed-policy change, and reconnect-budget exhaustion require a new
+grant or produce a refusal.
+
+## Implementation architecture
+
+Add these core concepts without coupling them to one transport:
+
+```text
+AuthorizationCoordinator
+ ├── CapabilityPolicyStack
+ │ ├── HardInvariants
+ │ ├── ManagedPolicy
+ │ ├── UserPolicy (existing YAML/Rego)
+ │ └── SessionManifest
+ ├── RiskClassifier (typed metadata, not model authority)
+ ├── ApprovalBroker
+ │ ├── ProtectedHostCollector (MVP)
+ │ ├── MacOSBiometricCollector (optional)
+ │ ├── WindowsHelloCollector (optional)
+ │ ├── PolkitCollector (optional)
+ │ └── DeviceFlowCollector (optional)
+ ├── Grants (generalized from ExistingProfileGrants/GrantLookup)
+ ├── IndicatorController
+ └── AuditSink
+```
+
+Primary code areas:
+
+- `cua-driver-core/src/policy.rs`: policy stack, fail-closed loading,
+ authorization context, and composition.
+- `cua-driver-core/src/server.rs` and `cua-driver/src/serve.rs`: one canonical
+ authorization call before registry dispatch; remove consent inference from
+ generic transport provenance.
+- `cua-driver/src/proxy.rs`: early denial only; the daemon remains canonical
+ for grants and protected approval.
+- `cua-driver-core/src/session.rs`: grant ownership, teardown, idle eviction,
+ and transport identity.
+- `cua-driver-core/src/browser/approval.rs`: replace public artifacts for
+ `existing_profile` with broker-mediated grants; retain a compatibility path
+ only for low-risk isolated launch if needed.
+- `cua-driver-core/src/browser/grant.rs`, `prepare.rs`, `engine.rs`, and
+ `store.rs`: consume generic grants, add origin/capability scope, and enforce
+ revocation during attach/reconnect/action.
+- platform crates: trusted collectors and protected indicator adapters.
+- CLI/config/health schemas: startup mode, policy provenance, revoke/status.
+
+Today policy evaluation is duplicated in `serve.rs`, `server.rs`, and the
+separate stdio proxy process. Before adding the coordinator, refactor the two
+daemon dispatch paths to call exactly one daemon-side authorization function
+covering stdio, HTTP/MCP, CLI, and raw socket dispatch. The proxy keeps a
+redundant early-deny check as defense in depth and can never mint or satisfy a
+grant. The generic grant implementation should evolve
+`ExistingProfileGrants`, `GrantLookup`, and `PrepareAuthorization` rather than
+create a parallel browser-independent store.
+
+## Failure behavior
+
+| Failure | Required result |
+|---|---|
+| Policy explicitly configured but missing/unreadable | Daemon does not expose action socket |
+| User policy unset during migration window | Preserve documented allow-all compatibility and emit migration status/warning |
+| User policy unset after default flip | Load the reviewed built-in ceiling and `standard` mode |
+| Policy parse/evaluation error | Fail closed; stable structured error |
+| Unsupported/absent protected collector | Sensitive request refuses; no TTY fallback |
+| Approval timeout/cancel/decline | No grant; pending operation canceled |
+| Agent replays approval correlation ID | Refuse; ID is non-authoritative |
+| Agent changes PID/window/session after approval | Refuse and consume/cancel request |
+| Policy or mode changes | Existing incompatible grants revoked before new calls |
+| Indicator fails to render | R2+ grant is not activated or is immediately revoked |
+| Stop during in-flight action | Cancel where possible, report honest partial-delivery state, revoke derivatives |
+| Redirect/popup leaves approved origin scope | Pause/refuse/detach before further input or data release |
+| Browser/daemon restart | In-memory grant lost; require new approval |
+| Agent targets Cua consent/indicator UI | Hard refusal independent of mode |
+
+## Verification plan
+
+### Unit and property tests
+
+- Every combination of hard, managed, user, session, and mode decisions obeys
+ intersection semantics.
+- No `Deny` can become `Allow` after approval or mode resolution.
+- Explicit missing policy paths fail startup; absent policy selects built-in
+ `standard` after migration.
+- Policy aliases and reserved-argument sanitization still work.
+- Grants reject nonce replay, wrong daemon, wrong transport/session, wrong
+ resource, wrong policy hash, expiry, and generation mismatch.
+- Revocation is idempotent and invokes every cleanup hook exactly once.
+- Mode cannot be changed through any tool schema, reserved argument, MCP
+ metadata, environment injection into an existing process, or session revive.
+- A same-user process that writes a syntactically valid legacy approval JSON
+ file directly into the temporary artifact directory still cannot authorize
+ `existing_profile` in `standard` or `autonomous`.
+- Fuzz YAML/Rego inputs, authorization context sanitization, approval messages,
+ and grant serialization boundaries.
+
+### Adversarial integration tests
+
+- Agent-controlled PTY types `APPROVE`; `existing_profile` remains denied.
+- MCP client synthesizes elicitation `accept`; denied unless the protected-host
+ capability and authenticated response are present.
+- Approval for browser A is replayed against browser B, a new process
+ generation, another window, or another session.
+- Agent races Stop/revoke against connect, click, type, redirect, download, and
+ reconnect.
+- Agent tries to hide/click the indicator through element, pixel, background,
+ foreground, and browser routes.
+- Allowed navigation redirects or opens a target to a denied origin.
+- Allowed browser tool attempts cookie/storage extraction through legacy
+ `page`, JavaScript, raw CDP, shell, file, or response side channels.
+- Same-user untrusted launch attempts are tested in the supported sandboxed
+ deployment, and documentation explicitly marks unsandboxed bypasses.
+
+### Real-platform acceptance
+
+For every advertised platform/collector, record exact-SHA evidence for:
+
+- accept, decline, cancel, timeout, unavailable collector;
+- daemon restart and OS lock/user switch;
+- persistent indicator and all Stop paths;
+- standard initial attach plus prompt-free same-generation actions;
+- autonomous manifest approval plus hours-long bounded activity;
+- scope expansion, expiry, and revocation;
+- unrestricted launch warning and non-escalation from a standard session;
+- Chrome/Edge existing-profile attach, reconnect, wrong-target refusal, and
+ cross-origin enforcement;
+- installed artifact provenance and representative post-install smoke test.
+
+No platform/host combination advertises protected `existing_profile` until its
+selected collector and indicator rows pass in the real environment. Headless
+support requires a certified protected host or second-device flow;
+`/dev/tty` is not substituted.
+
+## General-release gate and explicit deferrals
+
+The initial protected-browser release requires all of the following:
+
+1. Explicitly configured missing/unreadable policy fails before socket bind;
+ unset remains compatible until the announced default flip.
+2. One canonical daemon-side authorization call covers every transport; proxy
+ checks are defense in depth only.
+3. Mode selection and grant minting are unreachable from the model/tool
+ channel.
+4. The exact built-in tool/risk baseline and migration behavior are published
+ and tested.
+5. `existing_profile` cannot use the file-backed artifact in `standard` or
+ `autonomous`; a protected local/host/device collector exists or the feature
+ remains unavailable.
+6. R2+ browser grants have a persistent indicator/Stop surface, including an
+ out-of-band substitute where local UI is unavailable.
+7. Existing browser identity, generation, reconnect, and teardown invariants
+ continue to pass.
+8. Browser-specific target/origin transitions and legacy/raw bypass routes are
+ enforced and adversarially tested.
+
+The following do not block the first-platform protected-browser release:
+
+- a fine-grained driver-wide dotted capability taxonomy;
+- generic output classification, egress quotas, and a user-visible audit
+ ledger beyond the browser-specific controls above;
+- collectors on platforms that remain explicitly unsupported;
+- full caller authentication for every legacy transport; and
+- the `chrome.debugger` transport spike.
+
+They remain required before Cua advertises the corresponding driver-wide or
+platform guarantee.
+
+## Delivery sequence
+
+### Phase 0 — immediate containment
+
+1. Mark the current `existing_profile` approval path experimental.
+2. Disable it by default for agent-facing production use unless an explicit
+ legacy feature flag is set by a trusted launcher.
+3. Change an explicitly configured missing policy path from allow-all to an
+ error and eagerly validate policy/mode before socket bind. Keep an unset
+ policy compatible during the migration window.
+4. Document that the file-backed approval artifact is same-user-forgeable and
+ is not a human-consent boundary.
+
+Exit: no accidental policy typo or ordinary agent transport silently gets a
+logged-in profile attachment.
+
+### Phase 1 — mode and policy foundation
+
+1. Refactor `serve.rs` and `server.rs` to call one canonical daemon-side
+ authorization function; retain the separate proxy check as early denial.
+2. Add `PermissionMode` and immutable startup provenance.
+3. Add the reviewed built-in ceiling and managed/user policy intersection.
+4. Add typed risk metadata and the canonical authorization coordinator.
+5. Expose mode/policy health without secrets.
+6. Prove every transport reaches the canonical daemon check.
+
+Exit: standard/autonomous/unrestricted decisions are deterministic and the
+agent cannot change them in-process.
+
+### Phase 2 — approval broker and grants
+
+1. Add broker protocol, request digest, private channel, grant store, and audit
+ vocabulary.
+2. Ship protected-host capability negotiation and certify the first Codex or
+ Claude trusted consent UI; do not trust generic elicitation.
+3. Add macOS biometrics, Windows Hello, polkit, and device flow as optional
+ collectors behind independent availability gates.
+4. When no certified collector is available, refuse `existing_profile` in
+ `standard` and `autonomous`; never downgrade to TTY confirmation.
+
+Exit: adversarial PTY and synthetic-MCP accept tests cannot mint a grant.
+
+### Phase 3 — indicator and revocation
+
+1. Add persistent status UI independent of agent cursor.
+2. Add Stop, emergency shortcut, trusted CLI revoke, and self-target denial.
+3. Wire every grant into session cleanup and in-flight cancellation.
+
+Exit: no R2+ grant can remain live without indicator and revocation coverage.
+
+### Phase 4 — migrate `existing_profile`
+
+1. Replace public artifact consumption with generic protected grants.
+2. Add tab/origin/capability scoping and redirect/popup enforcement.
+3. Gate legacy/raw routes and sensitive browser data.
+4. Certify attach, action, reconnect, expiry, and revocation on supported
+ browsers/platforms.
+
+Exit: one protected approval supports ordinary autonomous browser work, with
+new intervention only for scope expansion or consequential actions.
+
+### Phase 5 — autonomous and unrestricted UX
+
+1. Add session manifests and human review UI.
+2. Add managed limits and non-interactive deny behavior for undeclared actions.
+3. Add explicit unrestricted startup, severe warnings, admin disable, and
+ disposable-environment guidance.
+
+Exit: long-running tasks need one bounded approval; bypass cannot be entered by
+an already-running standard/autonomous agent.
+
+### Phase 6 — driver-wide coverage
+
+Migrate screen, input, clipboard/files, devices, shell/network, and
+consequential typed workflows in the priority order above. Each group ships
+only after input, output, egress, revocation, and live-platform tests pass.
+
+## Pull-request strategy
+
+Keep changes reviewable and release metadata accurate:
+
+1. `fix(cua-driver): fail closed before binding for configured permission policies`
+2. `refactor(cua-driver): unify daemon authorization dispatch`
+3. `feat(cua-driver): add permission modes and policy composition`
+4. `feat(cua-driver): add protected approval broker and grants`
+5. `feat(cua-driver): add persistent authorization indicator and revocation`
+6. `fix(cua-driver): require protected consent for existing browser profiles`
+7. `feat(cua-driver): add bounded autonomous session manifests`
+8. Platform collector PRs, split where implementation and evidence are
+ independently reviewable.
+
+Before each PR becomes ready, inspect its final files and live GitHub title,
+apply the appropriate release label/type, and wait for release-metadata CI.
+
+## Migration and compatibility
+
+1. Release the explicit-missing-policy fail-closed fix immediately.
+2. Add warnings and health diagnostics while the built-in standard policy is
+ opt-in during one compatibility window.
+3. Make `standard` the default in the next announced release boundary.
+4. Preserve existing YAML/Rego boolean policy syntax.
+5. Offer a migration command that prints a proposed policy/manifest but never
+ installs or approves it without trusted user action.
+6. Keep legacy TTY artifacts only for isolated-profile compatibility during a
+ bounded deprecation window.
+7. Do not silently map “policy absent” to `unrestricted`; require the explicit
+ mode/danger flag after the migration boundary.
+
+## Documentation requirements
+
+- One concept page separating OS permissions, capability policy, mode, and
+ grants.
+- One how-to per mode with realistic intervention expectations.
+- One managed-deployment guide explaining the required external boundary for
+ local shell-capable agents.
+- Browser guide warnings for logged-in profiles, prompt injection, raw data,
+ and unrestricted mode.
+- CLI/config/health reference generated from the implementation.
+- Threat-model and limitation statements repeated near the relevant controls,
+ not hidden in a security appendix.
+- Upgrade notes for policy fail-closed behavior and the standard-default
+ migration.
+
+## Open questions requiring spikes
+
+1. Is an optional macOS `LAContext` collector worth shipping for hostless use,
+ and can the installed daemon present it reliably without passcode fallback?
+2. What OS-authenticated protected-host attestation can Claude Code, Codex, and
+ other MCP clients provide beyond generic elicitation?
+3. Which indicator form remains persistent across Spaces, full-screen apps,
+ RDP, Wayland compositors, and accessibility tooling without becoming an
+ input obstruction?
+4. Can Cua reliably enforce tab/origin scope on every CDP target transition,
+ service-worker navigation, popup, external protocol, and download?
+5. Which generic input surfaces must be denied in protected authenticated
+ sessions because semantic consequence cannot be proven?
+6. What service ownership, authentication, expiry, audit, and offline failure
+ model should the required second-device fallback use?
+7. Does the `chrome.debugger` transport cover Cua's exact input, frame,
+ target-binding, and recording requirements in practice, and can its
+ extension/native-host supply chain be secured?
+
+## Source anchors
+
+- [MCP elicitation specification, revision 2025-11-25](https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation)
+- [OWASP LLM06:2025 Excessive Agency](https://genai.owasp.org/llmrisk/llm062025-excessive-agency/)
+- [Chrome remote-debugging security change](https://developer.chrome.com/blog/remote-debugging-port)
+- [`chrome.debugger` API and available CDP domains](https://developer.chrome.com/docs/extensions/reference/api/debugger)
+- [Claude Code permission modes](https://code.claude.com/docs/en/permission-modes)
+- [Running Codex safely at OpenAI](https://openai.com/index/running-codex-safely/)
+
+## Review record
+
+### Claude Code / Fable — 2026-07-20
+
+- **Method:** Read-only security and architecture review against exact base
+ `767acf25f`, including `policy.rs`, `serve.rs`, `server.rs`, `proxy.rs`,
+ `cli.rs`, browser approval/grant/prepare code, current policy docs, and the
+ earlier browser plans.
+- **Verdict:** Accept with major changes.
+- **Accepted corrections:** treat direct same-user artifact-file forgery as the
+ primary P0; make `unrestricted` suppress prompts without widening policy;
+ define the built-in baseline and default-flip boundary; make daemon dispatch
+ unification a prerequisite; eager-load policy before bind; accurately frame
+ the earlier plans; classify the emergency shortcut as an affordance; require
+ out-of-band indicator/Stop when local UI is unavailable; use existing tool
+ names for MVP manifests; add device-flow fallback; generalize the existing
+ browser grant store; disambiguate TCC permissions; and test direct artifact
+ forgery.
+- **Deferrals accepted:** generic driver-wide output/egress classification,
+ fine-grained dotted capability taxonomy, later-platform collectors, caller
+ authentication, user-visible audit ledger, and `chrome.debugger` do not block
+ the first-platform protected-browser release. Browser-specific origin/data
+ bypass controls remain mandatory.
+- **Rejected recommendations:** None during the review. A subsequent product
+ decision keeps biometrics and device flow optional, makes a certified
+ protected-host consent UI the MVP collector, and refuses protected attach
+ when no collector exists. It retains suppress-only `unrestricted`, a shared
+ reviewed ceiling, existing-tool MVP manifests, and an out-of-band
+ indicator/Stop substitute.
+- **Remaining work:** The technical spikes in the preceding section still need
+ implementation evidence; review acceptance does not make this a plan of
+ record.
diff --git a/libs/cua-driver/docs/driver-permission-modes-implementation-journal.md b/libs/cua-driver/docs/driver-permission-modes-implementation-journal.md
new file mode 100644
index 0000000000..ecf496dc4c
--- /dev/null
+++ b/libs/cua-driver/docs/driver-permission-modes-implementation-journal.md
@@ -0,0 +1,225 @@
+# Driver Permission Modes Implementation Journal
+
+> Contract update: the shipped canonical middle-mode name is `bounded`, with
+> `autonomous` retained as a compatibility alias. The interactive CLI danger
+> flag now selects `unrestricted` as well as acknowledging its risk; embedded
+> and environment-driven launchers still provide mode and acknowledgement as
+> two explicit values. Historical entries below use the names current when
+> each implementation step was recorded.
+
+## Status
+
+- **Goal:** Implement the reviewed driver permission-mode and consent plan.
+- **Branch:** `codex/cua-driver-permission-modes`
+- **Frozen base:** `origin/main` at
+ `767acf25f25ea668ffab428e4f2e8985896de98e`
+- **Source version:** Cua Driver `0.9.1`
+- **Umbrella issue:** [#2381](https://github.com/trycua/cua/issues/2381)
+- **Plan:** [driver-permission-modes-and-consent-plan.md](driver-permission-modes-and-consent-plan.md)
+
+This journal records exact-head implementation and validation evidence. A row
+is not called supported until the named public interface, independent oracle,
+and representative environment have passed on the same commit.
+
+## Frozen delivery slices
+
+1. Fail-closed policy startup and one canonical daemon authorization path.
+2. Immutable permission modes, policy composition, risk metadata, and status.
+3. Protected-host approval broker and generalized grants.
+4. Persistent indicator, Stop/revoke, and existing-profile migration.
+5. Autonomous manifests and explicit unrestricted startup.
+6. Driver-wide capability adapters, documentation, and platform certification.
+
+Each slice remains on this host-owned branch until it is independently tested
+and can be split into a reviewable PR without losing dependency history.
+
+## Support and evidence matrix
+
+| Environment | Public surface | Required result | Evidence state |
+|---|---|---|---|
+| macOS host | Rust unit/integration tests | Deterministic policy, mode, grant, and refusal contracts | Passed on `d29fd128f`; full workspace examples have a pre-existing macOS cross-target failure recorded below |
+| macOS Lume Aqua session | Installed `cua-driver` CLI/MCP/daemon | Mode/status/revoke, fail-closed protected attach, unrestricted lifecycle, provenance | Passed on `d29fd128f`; installed `0.9.1`, standard mode, protected collector unavailable |
+| Windows interactive session (not Session 0) | Installed CLI/MCP/daemon and Windows runner | Mode/policy parity; advertised collector and revocation behavior | Passed on `d29fd128f` in RDP session 4; installed `0.9.1`, standard mode, protected collector unavailable |
+| Linux SSH/headless | Installed CLI/MCP/daemon and Linux harness | Mode/policy parity and selected collector behavior | Passed on `d29fd128f`; installed `0.9.1`, standard mode, protected collector unavailable |
+| Linux X11 | Installed CLI/MCP/daemon and Linux harness | Mode/policy parity and selected collector behavior | Not claimed by this slice; no protected Linux GUI collector is advertised |
+| Linux Wayland | Installed CLI/MCP/daemon and Wayland harness | Mode/policy parity and selected collector behavior | Not claimed by this slice; no protected Linux GUI collector is advertised |
+| Headless transport | CLI/raw socket/MCP | Stable refusal when no certified trusted-consent collector exists | Passed on macOS, Windows, and Linux installed-daemon smoke checks |
+
+## Execution log
+
+### 2026-07-20 — orientation and baseline
+
+- Fetched `origin/main`; local base and fetched main both resolve to
+ `767acf25f25ea668ffab428e4f2e8985896de98e`.
+- Preserved the previously reviewed, uncommitted plan and created
+ `codex/cua-driver-permission-modes` from that exact commit.
+- Confirmed the first P0 gap in production code: a configured missing policy
+ path logs a warning and becomes `Ok(None)`, while daemon binding happens
+ before policy validation.
+- Confirmed policy checks are duplicated in core stdio MCP, daemon socket, and
+ stdio proxy dispatch.
+- Baseline commands passed:
+ - `cargo test -p cua-driver-core policy --all-features` — 13 passed.
+ - `cargo test -p cua-driver --bin cua-driver policy --all-features` — build
+ passed; no matching binary tests.
+
+### 2026-07-20 — containment and immutable startup modes
+
+- Explicitly configured missing/invalid policy paths now fail before Unix or
+ Windows daemon bind, and the stdio proxy validates before beginning MCP
+ dispatch.
+- Core stdio, direct daemon, and proxy paths use one canonical capability
+ policy function; the daemon remains authoritative and the proxy is only an
+ early-denial optimization.
+- Added immutable startup modes (`standard`, `autonomous`, `unrestricted`),
+ with `standard` as the default and a separately named danger acknowledgement
+ required for `unrestricted`.
+- Disabled the same-user-writable existing-profile artifact in production by
+ default. Standard/autonomous now return `browser_consent_required`; the
+ legacy path requires an explicit trusted-launcher compatibility flag.
+- Added direct CLI/daemon adversarial coverage for a syntactically valid forged
+ artifact and for unrestricted launch-time behavior.
+- Verification passed:
+ - `cargo test -p cua-driver-core policy --all-features` — 13 passed.
+ - `cargo test -p cua-driver-core authorization --all-features` — 5 passed.
+ - `cargo test -p cua-driver-core browser::v2_tests --all-features` — 29 passed.
+ - `cargo test -p cua-driver --test permission_policy_startup_test --all-features`
+ — 3 passed.
+ - Both new `daemon_required_test` authorization cases passed individually.
+ - `cargo test -p cua-driver --bin cua-driver cli::tests --all-features` —
+ 13 passed.
+ - `cargo fmt --all -- --check` — passed.
+
+### 2026-07-20 — protected-host contract spike
+
+- Current Codex documentation exposes MCP elicitation/approval UX, optional
+ automatic approval review, and desktop-host attestation on Codex's app-server
+ protocol. It does not define a verifiable Cua MCP-server attestation that
+ proves a human (rather than a hook/reviewer/client) accepted an elicitation.
+- MCP 2025-11-25 likewise leaves the client interaction model open and warns
+ servers not to trust unverified client-provided identity.
+- Decision: generic `elicitation/create` remains untrusted. The broker will
+ require a request-bound authenticated provider result and otherwise fail
+ closed. No Codex or Claude collector will be advertised as protected until a
+ concrete host contract can be verified end to end.
+- The live repository already has a versioned dotted capability vocabulary in
+ `tool.rs`. Risk metadata will extend that canonical map rather than create a
+ competing manifest vocabulary.
+
+### 2026-07-20 — modes, broker, grants, and bounded autonomy
+
+- Added the reviewed R0 through R4 risk map to every advertised tool. Unknown
+ tools fail closed. `browser_prepare.existing_profile` is the first active
+ resource adapter; other tools are explicitly marked `metadata_only`.
+- Added immutable managed and user policy layers with SHA-256 provenance and
+ intersection semantics. Either explicitly configured invalid path now fails
+ before the action socket binds.
+- Added request-bound protected consent with daemon instance, nonce,
+ generation, mode, policy hashes, exact sessions, resource, expiry, and digest.
+ Generic MCP elicitation, files, TTY input, and tool arguments cannot implement
+ the provider seam.
+- Made indicator activation a prerequisite for protected grants. Stop, exact
+ session teardown, expiry, reconnect exhaustion, and context drift revoke the
+ grant and release its browser connection.
+- Added `cua-driver revoke --session <id>` and `--all`, plus content-free mode,
+ policy, provider, and manifest status.
+- Added autonomous manifests with a 24-hour maximum, explicit launch approval,
+ deny-by-default tool sets, exact existing-profile PID/window scope, requested
+ origin checks, and live top-level origin checks before each browser mutation.
+- Added unrestricted startup warnings and
+ `CUA_DRIVER_DISABLE_UNRESTRICTED=1` for administrator disablement.
+- Added a hard refusal for PID-targeted tools that name the authorization
+ daemon itself.
+- Updated generated CLI/MCP references, policy concepts and how-to pages,
+ browser attachment docs, test matrix, and a new permission-mode reference.
+
+Verification on the macOS source host:
+
+- Core `policy`, `authorization`, `consent`, `session_manifest`, grant, session,
+ refusal, and browser v2 suites passed in targeted runs.
+- `permission_policy_startup_test`: 8 passed.
+- `daemon_required_test`: 7 passed.
+- CLI manifest/parser tests: 13 passed.
+- `cargo test -p cua-driver-core --no-default-features authorization`: 8 passed.
+- Generated documentation drift, public hygiene, and internal link checks
+ passed.
+- `cargo test --workspace --all-features` is not a valid all-host gate on
+ macOS: Linux-only examples `libei_input` and `screenshot_cascade` compile
+ against modules gated by `target_os=linux`. The failure occurred before test
+ execution and is unrelated to this change. Package-scoped and target-native
+ VM gates remain required.
+
+### 2026-07-20 — independent Fable implementation review
+
+- Claude Code Fable reviewed the uncommitted implementation against the plan
+ and returned **SHIP AFTER FIXES** with no P0 findings.
+- Closed every P1 finding before platform certification:
+ - enforced a terminal autonomous idle timeout at canonical dispatch;
+ - rejected origin-scoped manifests that also allow generic page/desktop
+ input surfaces outside the typed live-origin adapter;
+ - made the legacy artifact startup-invalid in autonomous and unrestricted
+ modes, preserving the mandatory autonomous indicator;
+ - extracted and directly tested the live-origin decision path used after
+ `Page.getFrameTree` and before browser mutation.
+- Closed the bounded P2 hardening items in the same pass: provider request and
+ indicator deadlines, final expiry checks, provider identity in status,
+ metadata-only old-daemon proxy fallback, change-during-load policy hashing,
+ and explicit indicator-lease teardown semantics.
+- Corrected documentation so `standard` describes only the currently active
+ existing-profile prompt, and documented PID reuse, origin-adapter exclusions,
+ terminal idle expiry, and restart-flag preservation.
+- Post-review targeted gates passed:
+ - session-manifest tests: 5 passed;
+ - consent tests: 6 passed;
+ - live-origin decision test: 1 passed;
+ - `permission_policy_startup_test`: 9 passed.
+
+### 2026-07-20 — exact-commit platform certification
+
+All three installation lanes used source commit
+`d29fd128f9b287198b3c595ebb987c9411c3af21` and Cua Driver version
+`0.9.1`. Each installed daemon reported `standard` mode and
+`protected consent collector: unavailable`; `get_config.source_sha` matched
+the synced commit. This is the intended fail-closed standalone posture, not a
+claim that a protected host provider ships in this slice.
+
+- macOS 26.5.2 arm64, disposable Lume Aqua VM
+ `cua-permission-modes-d29fd128f`:
+ - installed `/Applications/CuaDriver.app` with the repository's stable
+ signing identity and visible CLI `/Users/lume/.local/bin/cua-driver`;
+ - installed binary SHA-256
+ `fef4ca7e1574678f55ca7226e93667f0f05046f6234bdd4690bcfed89d131c3d`;
+ - `permission_policy_startup_test`: 9 passed in release mode;
+ - `daemon_required_test`: 7 passed in release mode.
+- Ubuntu 24.04 x86_64, Azure VM `cua-linux-071`:
+ - installed binary
+ `/home/azureuser/.cua-driver/packages/releases/0.0.0-local-release-x86_64-unknown-linux-gnu/cua-driver`;
+ - installed binary SHA-256
+ `0aa9f19eb0bb58e781fcdaf52a4d8c3c9aa56ca660132da4fad3390a4ef7e7be`;
+ - `permission_policy_startup_test`: 9 passed in release mode;
+ - `daemon_required_test`: 7 passed in release mode;
+ - the documented installer migration permanently swept the test VM's legacy
+ `/home/azureuser/.cua-driver-rs` directory after preserving telemetry.
+- Windows x86_64, Azure VM `cua-win-071`:
+ - established an RDP desktop with FreeRDP after independently matching its
+ TLS certificate SHA-256 to the certificate read over the trusted SSH
+ channel;
+ - ran the install and certification harness as `azureuser` in active RDP
+ session 4, with Explorer also in session 4; Session 0 was rejected by the
+ harness;
+ - installed binary
+ `C:\Users\azureuser\AppData\Local\Programs\Cua\cua-driver\bin\cua-driver.exe`;
+ - installed binary SHA-256
+ `8b3d58eb0f693f8a2eec1fed52fd2ab447419c5b165c675719e7bdcbd4550ba8`;
+ - `permission_policy_startup_test`: 9 passed in release mode;
+ - `daemon_required_test`: 7 passed in release mode;
+ - removed the temporary interactive scheduled certification task after the
+ structured result reported success.
+
+## Current work
+
+Implementation, review fixes, documentation, and exact-commit platform
+certification are complete. The remaining delivery work is to publish the
+branch, open the review PR, update umbrella issue #2381, and monitor repository
+checks. No standalone host is advertised as a certified protected provider;
+standard/autonomous existing-profile attachment remains fail closed.
diff --git a/libs/cua-driver/docs/test-matrix.md b/libs/cua-driver/docs/test-matrix.md
index 039f02d818..eaf83404bb 100644
--- a/libs/cua-driver/docs/test-matrix.md
+++ b/libs/cua-driver/docs/test-matrix.md
@@ -49,6 +49,8 @@ These run without the repo-local GUI applications:
| Schema gate | `schema_consistency_test.rs` | Shared tool schema parity across OS backends |
| Configuration transport | `transport_config_persistence_test.rs` | CLI and MCP configuration persistence |
| Token and protocol surfaces | `protocol_element_token_test.rs`, related tests | JSON-RPC-visible contract behavior |
+| Permission modes and policy startup | `permission_policy_startup_test.rs`, `daemon_required_test.rs`, core `authorization`, `policy`, and `session_manifest` tests | Fail-before-bind policy loading, managed/user intersection, immutable standard/autonomous/unrestricted startup, danger acknowledgement, admin disable, deny-by-default manifests, and canonical daemon dispatch |
+| Protected browser grants | Core `consent`, `browser::grant`, `browser::engine`, and `browser::v2_tests` | Exact request digests, provider authentication seam and deadline, persistent-indicator activation, Stop/session teardown, forged legacy artifact refusal, exact PID/window manifest scope, and the live-origin decision path used before mutation |
Some protocol tests spawn the driver process. They remain deterministic because
they do not launch a real target application or require a desktop. They should
diff --git a/libs/cua-driver/python/tests/test_install_local_signing.py b/libs/cua-driver/python/tests/test_install_local_signing.py
index e330fa76a0..f9f101c607 100644
--- a/libs/cua-driver/python/tests/test_install_local_signing.py
+++ b/libs/cua-driver/python/tests/test_install_local_signing.py
@@ -37,3 +37,28 @@ def test_tcc_reset_gates_marker_write_on_success() -> None:
assert "reset_succeeded=0" in script
# The marker is only written when no reset was needed or the reset succeeded.
assert '[ "$needs_reset" = 0 ] || [ "$reset_succeeded" = 1 ]' in script
+
+
+def test_unix_local_installer_always_embeds_source_provenance() -> None:
+ """Local builds derive Git provenance but preserve VM snapshot overrides."""
+ script = (
+ Path(__file__).resolve().parents[2] / "scripts" / "_install-local-rust.sh"
+ ).read_text()
+
+ assert 'if [ -z "${CUA_DRIVER_SOURCE_SHA:-}" ]; then' in script
+ assert "rev-parse --verify 'HEAD^{commit}'" in script
+ assert "status --porcelain --untracked-files=normal" in script
+ assert 'CUA_DRIVER_SOURCE_SHA="${CUA_DRIVER_SOURCE_SHA}-dirty"' in script
+ assert "export CUA_DRIVER_SOURCE_SHA" in script
+
+
+def test_windows_local_installer_always_embeds_source_provenance() -> None:
+ """The Windows developer installer follows the same provenance contract."""
+ script = (
+ Path(__file__).resolve().parents[2] / "scripts" / "install-local.ps1"
+ ).read_text()
+
+ assert "IsNullOrWhiteSpace($env:CUA_DRIVER_SOURCE_SHA)" in script
+ assert "rev-parse --verify 'HEAD^{commit}'" in script
+ assert "status --porcelain --untracked-files=normal" in script
+ assert '"$detectedSourceSha-dirty"' in script
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index a52097257f..ab1232e662 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -766,11 +766,13 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml_ng",
+ "sha2",
"tempfile",
"thiserror 1.0.69",
"tokio",
"tokio-tungstenite",
"tracing",
+ "url",
"uuid",
"windows 0.58.0",
]
@@ -3060,6 +3062,17 @@ dependencies = [
"digest",
]
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest",
+]
+
[[package]]
name = "sharded-slab"
version = "0.1.7"
diff --git a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
index 653f811404..d884fcffb3 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
@@ -72,6 +72,33 @@ in `check_permissions` output and logs — it is **not** a trust signal; trust
comes from the OS responsibility chain, so there is nothing to spoof by
setting it.
+## Choosing the agent permission mode
+
+Embedded hosts own their user-facing permission experience, but they must
+select Cua Driver's immutable daemon mode at trusted launch. The choices are:
+
+- `standard`: protected runtime approval for migrated sensitive operations.
+- `bounded`: unattended work inside an approved, exact session manifest.
+- `unrestricted`: no Cua runtime approvals; use only when the host accepts the
+ consequences of prompt injection and unintended actions.
+
+For unrestricted embedding, use the explicit two-part environment contract:
+
+```sh
+CUA_DRIVER_EMBEDDED=1 \
+CUA_DRIVER_PERMISSION_MODE=unrestricted \
+CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS=1 \
+ cua-driver serve --embedded --socket /tmp/yourapp-cua.sock
+```
+
+Both values are required and contradictory values fail before the daemon
+binds. They belong in trusted launcher configuration; never expose either as
+an agent-settable MCP or raw-socket argument. Interactive operators can use
+the equivalent single CLI shortcut, `--dangerously-bypass-approvals`, which
+selects unrestricted mode and records the acknowledgement. The older
+`autonomous` mode name remains accepted as an alias for `bounded` during
+migration.
+
## What embedded mode changes (and what it doesn't)
| | Standalone | Embedded (`CUA_DRIVER_EMBEDDED=1`) |
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml
index a3d3458473..5b356bca66 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml
@@ -30,6 +30,8 @@ image = { workspace = true }
tokio-tungstenite = "0.24"
futures-util = "0.3"
uuid = { workspace = true }
+sha2 = "0.10"
+url = "2.5"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
new file mode 100644
index 0000000000..dba67ff4c5
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
@@ -0,0 +1,598 @@
+//! Immutable daemon permission-mode configuration.
+//!
+//! Capability policy answers whether an operation is inside the configured
+//! ceiling. Permission mode answers whether an otherwise-permitted operation
+//! also needs trusted human consent. The mode is resolved once at daemon
+//! startup and cannot be changed by a tool call or transport argument.
+
+use std::sync::OnceLock;
+
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+pub const PERMISSION_MODE_ENV: &str = "CUA_DRIVER_PERMISSION_MODE";
+pub const DANGEROUS_BYPASS_ENV: &str = "CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS";
+pub const DISABLE_UNRESTRICTED_ENV: &str = "CUA_DRIVER_DISABLE_UNRESTRICTED";
+pub const LEGACY_EXISTING_PROFILE_APPROVAL_ENV: &str =
+ "CUA_DRIVER_ALLOW_LEGACY_EXISTING_PROFILE_APPROVAL";
+pub const RISK_METADATA_VERSION: &str = "1";
+
+/// Reviewed risk attached to a typed tool operation. `Unclassified` is a
+/// fail-closed sentinel and is never an executable risk tier.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum RiskClass {
+ R0,
+ R1,
+ R2,
+ R3,
+ R4,
+ Unclassified,
+}
+
+impl RiskClass {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::R0 => "r0",
+ Self::R1 => "r1",
+ Self::R2 => "r2",
+ Self::R3 => "r3",
+ Self::R4 => "r4",
+ Self::Unclassified => "unclassified",
+ }
+ }
+}
+
+/// Whether the resource adapter currently enforces the consent/grant
+/// semantics for this exact operation. Metadata-only entries are visible to
+/// clients and policy authors but intentionally retain compatibility until
+/// their resource, output, egress, and revocation adapters are complete.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum RiskEnforcement {
+ Active,
+ MetadataOnly,
+}
+
+impl RiskEnforcement {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Active => "active",
+ Self::MetadataOnly => "metadata_only",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct RiskAssessment {
+ pub class: RiskClass,
+ pub enforcement: RiskEnforcement,
+ pub operation_sensitive: bool,
+}
+
+/// Highest reviewed risk advertised for a tool. Runtime authorization uses
+/// [`classify_tool_call`] so compound tools can narrow to a typed operation.
+pub fn advertised_risk_for(tool: &str) -> RiskAssessment {
+ let class = match tool {
+ // Public driver/OS metadata with no user-content payload.
+ "get_screen_size"
+ | "get_cursor_position"
+ | "check_permissions"
+ | "get_config"
+ | "get_session_state"
+ | "get_agent_cursor_state"
+ | "get_recording_state"
+ | "check_for_update"
+ | "probe" => RiskClass::R0,
+
+ // Local reversible control and lifecycle operations.
+ "click"
+ | "double_click"
+ | "right_click"
+ | "drag"
+ | "scroll"
+ | "move_cursor"
+ | "mouse_button_down"
+ | "mouse_button_up"
+ | "mouse_drag"
+ | "parallel_mouse_drag"
+ | "type_text"
+ | "type_text_chars"
+ | "press_key"
+ | "hotkey"
+ | "set_value"
+ | "launch_app"
+ | "list_apps"
+ | "kill_app"
+ | "list_windows"
+ | "bring_to_front"
+ | "debug_window_info"
+ | "start_session"
+ | "end_session"
+ | "set_agent_cursor_enabled"
+ | "set_agent_cursor_motion"
+ | "set_agent_cursor_style"
+ | "stop_recording"
+ | "replay_trajectory" => RiskClass::R1,
+
+ // Surfaces that can reveal or control sensitive local/authenticated
+ // state. Most remain metadata-only until their resource adapters ship.
+ "zoom"
+ | "get_desktop_state"
+ | "get_accessibility_tree"
+ | "get_window_state"
+ | "set_config"
+ | "escalate_session"
+ | "start_recording"
+ | "get_browser_state"
+ | "browser_prepare"
+ | "browser_navigate"
+ | "browser_click"
+ | "browser_type"
+ | "browser_pointer" => RiskClass::R2,
+
+ // External/file side effects or generic compound action surfaces.
+ "install_ffmpeg"
+ | "page"
+ | "browser_dialog"
+ | "browser_set_input_files"
+ | "browser_download" => RiskClass::R3,
+
+ _ => RiskClass::Unclassified,
+ };
+ RiskAssessment {
+ class,
+ enforcement: RiskEnforcement::MetadataOnly,
+ operation_sensitive: matches!(tool, "browser_prepare" | "browser_dialog" | "page"),
+ }
+}
+
+/// Risk for the exact typed operation available at the canonical dispatch
+/// boundary. No page text, selectors, typed text, paths, or other content is
+/// retained by the returned value.
+pub fn classify_tool_call(tool: &str, args: &Value) -> RiskAssessment {
+ match tool {
+ "browser_prepare" => {
+ let existing =
+ args.pointer("/strategy/kind").and_then(Value::as_str) == Some("existing_profile");
+ if existing {
+ RiskAssessment {
+ class: RiskClass::R2,
+ enforcement: RiskEnforcement::Active,
+ operation_sensitive: true,
+ }
+ } else {
+ RiskAssessment {
+ class: RiskClass::R1,
+ enforcement: RiskEnforcement::MetadataOnly,
+ operation_sensitive: true,
+ }
+ }
+ }
+ "browser_dialog" => {
+ let class = match args.get("action").and_then(Value::as_str) {
+ Some("inspect") => RiskClass::R2,
+ Some("accept" | "dismiss") => RiskClass::R3,
+ _ => RiskClass::R3,
+ };
+ RiskAssessment {
+ class,
+ enforcement: RiskEnforcement::MetadataOnly,
+ operation_sensitive: true,
+ }
+ }
+ "page" => {
+ let class = match args.get("action").and_then(Value::as_str) {
+ Some("get_text" | "query_dom") => RiskClass::R2,
+ _ => RiskClass::R3,
+ };
+ RiskAssessment {
+ class,
+ enforcement: RiskEnforcement::MetadataOnly,
+ operation_sensitive: true,
+ }
+ }
+ _ => advertised_risk_for(tool),
+ }
+}
+
+pub fn risk_metadata_json(tool: &str) -> Value {
+ let risk = advertised_risk_for(tool);
+ serde_json::json!({
+ "class": risk.class.as_str(),
+ "enforcement": risk.enforcement.as_str(),
+ "operation_sensitive": risk.operation_sensitive,
+ "version": RISK_METADATA_VERSION,
+ })
+}
+
+/// Canonical daemon-side authorization entry point. Capability policy is
+/// evaluated first. Unknown/unreviewed tools then fail closed before registry
+/// dispatch; migrated resource adapters perform their typed grant check after
+/// this coordinator admits the call into the adapter.
+pub fn authorize_tool_call(
+ tool: &str,
+ args: &Value,
+) -> Result<RiskAssessment, crate::policy::AuthorizationError> {
+ enforce_hard_invariants(tool, args)?;
+ crate::policy::authorize_tool_call(tool, args)?;
+ let risk = classify_tool_call(tool, args);
+ if risk.class == RiskClass::Unclassified {
+ return Err(crate::policy::AuthorizationError::Denied(format!(
+ "tool '{tool}' has no reviewed risk classification"
+ )));
+ }
+ let mode = configured_permission_mode().map_err(crate::policy::AuthorizationError::Loading)?;
+ if mode == PermissionMode::Bounded {
+ let manifest = crate::session_manifest::configured_session_manifest()
+ .map_err(crate::policy::AuthorizationError::Loading)?
+ .ok_or_else(|| {
+ crate::policy::AuthorizationError::Loading(
+ "bounded session policy is unavailable".to_owned(),
+ )
+ })?;
+ if manifest.is_expired() {
+ return Err(crate::policy::AuthorizationError::Denied(
+ "bounded session policy expired".to_owned(),
+ ));
+ }
+ match manifest.decision(tool) {
+ crate::session_manifest::ManifestDecision::Allow => {
+ manifest
+ .authorize_call(tool, args)
+ .map_err(crate::policy::AuthorizationError::Denied)?;
+ manifest
+ .authorize_dispatch()
+ .map_err(crate::policy::AuthorizationError::Denied)?;
+ }
+ crate::session_manifest::ManifestDecision::Deny => {
+ return Err(crate::policy::AuthorizationError::Denied(format!(
+ "bounded session policy denies tool '{tool}'"
+ )))
+ }
+ crate::session_manifest::ManifestDecision::Ask => {
+ return Err(crate::policy::AuthorizationError::Denied(format!(
+ "bounded session policy requires protected approval for tool '{tool}'; unattended dispatch cannot auto-accept"
+ )))
+ }
+ crate::session_manifest::ManifestDecision::Undeclared => {
+ return Err(crate::policy::AuthorizationError::Denied(format!(
+ "tool '{tool}' is outside the bounded session policy"
+ )))
+ }
+ }
+ }
+ Ok(risk)
+}
+
+fn enforce_hard_invariants(
+ tool: &str,
+ args: &Value,
+) -> Result<(), crate::policy::AuthorizationError> {
+ // Provider and indicator adapters hosted by the daemon must never become
+ // an ordinary target. Coordinate-only desktop input cannot prove a target
+ // PID and therefore is not a protected-UI route; certified providers must
+ // render outside that surface and independently reject synthetic input.
+ let process_targeting_tool = matches!(
+ tool,
+ "click"
+ | "double_click"
+ | "right_click"
+ | "drag"
+ | "scroll"
+ | "type_text"
+ | "type_text_chars"
+ | "press_key"
+ | "hotkey"
+ | "set_value"
+ | "kill_app"
+ | "bring_to_front"
+ | "get_accessibility_tree"
+ | "get_window_state"
+ | "page"
+ | "browser_prepare"
+ );
+ if process_targeting_tool
+ && args.get("pid").and_then(Value::as_i64) == Some(i64::from(std::process::id()))
+ {
+ return Err(crate::policy::AuthorizationError::Denied(
+ "Cua Driver refuses operations that target its own authorization process".to_owned(),
+ ));
+ }
+ Ok(())
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PermissionMode {
+ Standard,
+ #[serde(alias = "autonomous")]
+ Bounded,
+ Unrestricted,
+}
+
+impl PermissionMode {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Standard => "standard",
+ Self::Bounded => "bounded",
+ Self::Unrestricted => "unrestricted",
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum PermissionModeError {
+ #[error("unknown permission mode '{0}'; expected standard, bounded, or unrestricted")]
+ Unknown(String),
+ #[error(
+ "permission mode unrestricted requires --dangerously-bypass-approvals at trusted daemon startup"
+ )]
+ MissingDangerAcknowledgement,
+ #[error("--dangerously-bypass-approvals cannot be combined with a non-unrestricted --permission-mode")]
+ UnexpectedDangerAcknowledgement,
+ #[error("permission mode bounded requires --session-policy <path> at trusted daemon startup")]
+ MissingSessionPolicy,
+ #[error("permission mode bounded requires --approve-session-policy at trusted daemon startup")]
+ MissingSessionPolicyApproval,
+ #[error(
+ "--session-policy/--approve-session-policy are valid only with --permission-mode bounded"
+ )]
+ UnexpectedSessionPolicy,
+ #[error("permission mode unrestricted is disabled by managed startup configuration")]
+ UnrestrictedDisabled,
+ #[error(
+ "--allow-legacy-existing-profile-approval is valid only with --permission-mode standard"
+ )]
+ UnexpectedLegacyApproval,
+}
+
+fn parse_permission_mode(
+ configured: Option<&str>,
+ dangerous_bypass: bool,
+) -> Result<PermissionMode, PermissionModeError> {
+ let mode = match configured.unwrap_or("standard") {
+ "standard" => PermissionMode::Standard,
+ "bounded" | "autonomous" => PermissionMode::Bounded,
+ "unrestricted" | "yolo" => PermissionMode::Unrestricted,
+ other => return Err(PermissionModeError::Unknown(other.to_owned())),
+ };
+ match (mode, dangerous_bypass) {
+ (PermissionMode::Unrestricted, false) => {
+ Err(PermissionModeError::MissingDangerAcknowledgement)
+ }
+ (PermissionMode::Standard | PermissionMode::Bounded, true) => {
+ Err(PermissionModeError::UnexpectedDangerAcknowledgement)
+ }
+ _ => Ok(mode),
+ }
+}
+
+fn env_flag(name: &str) -> bool {
+ std::env::var(name).is_ok_and(|value| {
+ matches!(
+ value.trim().to_ascii_lowercase().as_str(),
+ "1" | "true" | "yes" | "on"
+ )
+ })
+}
+
+/// Temporary migration escape hatch for the same-user-writable browser
+/// approval artifact. It is deliberately outside the public tool protocol and
+/// must never be described as protected human consent.
+pub fn legacy_existing_profile_approval_enabled() -> bool {
+ // Core's browser unit fixtures exercise the legacy artifact's binding,
+ // setup, reconnect, and cleanup mechanics directly. Integration tests
+ // compile this crate without `cfg(test)` and own the production-default
+ // refusal contract.
+ #[cfg(test)]
+ return true;
+
+ #[cfg(not(test))]
+ env_flag(LEGACY_EXISTING_PROFILE_APPROVAL_ENV)
+}
+
+static CONFIGURED_PERMISSION_MODE: OnceLock<Result<PermissionMode, String>> = OnceLock::new();
+
+/// Return the immutable process permission mode. An unset mode is `standard`.
+pub fn configured_permission_mode() -> Result<PermissionMode, String> {
+ CONFIGURED_PERMISSION_MODE
+ .get_or_init(|| {
+ let configured = std::env::var(PERMISSION_MODE_ENV).ok();
+ parse_permission_mode(configured.as_deref(), env_flag(DANGEROUS_BYPASS_ENV))
+ .map_err(|error| error.to_string())
+ })
+ .clone()
+}
+
+/// Validate every immutable authorization input before an action endpoint is
+/// bound. An unset user policy remains compatible; an explicitly configured
+/// invalid policy or mode is fatal.
+pub fn validate_startup_authorization() -> anyhow::Result<()> {
+ crate::policy::validate_configured_policy()?;
+ let mode = configured_permission_mode().map_err(anyhow::Error::msg)?;
+ if mode == PermissionMode::Unrestricted && env_flag(DISABLE_UNRESTRICTED_ENV) {
+ return Err(PermissionModeError::UnrestrictedDisabled.into());
+ }
+ if mode != PermissionMode::Standard && env_flag(LEGACY_EXISTING_PROFILE_APPROVAL_ENV) {
+ return Err(PermissionModeError::UnexpectedLegacyApproval.into());
+ }
+ let session_policy_configured =
+ std::env::var_os(crate::session_manifest::SESSION_POLICY_FILE_ENV).is_some();
+ let session_policy_approved = env_flag(crate::session_manifest::SESSION_POLICY_APPROVED_ENV);
+ match mode {
+ PermissionMode::Bounded => {
+ if !session_policy_configured {
+ return Err(PermissionModeError::MissingSessionPolicy.into());
+ }
+ if !session_policy_approved {
+ return Err(PermissionModeError::MissingSessionPolicyApproval.into());
+ }
+ let manifest = crate::session_manifest::configured_session_manifest()
+ .map_err(anyhow::Error::msg)?
+ .ok_or(PermissionModeError::MissingSessionPolicy)?;
+ if manifest.is_expired() {
+ anyhow::bail!("bounded session policy is already expired");
+ }
+ }
+ PermissionMode::Standard | PermissionMode::Unrestricted => {
+ if session_policy_configured || session_policy_approved {
+ return Err(PermissionModeError::UnexpectedSessionPolicy.into());
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Content-free authorization state suitable for status/health output.
+pub fn status_json() -> serde_json::Value {
+ let mode = configured_permission_mode();
+ let policy = crate::policy::configured_policy();
+ let managed_policy = crate::policy::configured_managed_policy();
+ let user_policy_sha256 = crate::policy::user_policy_sha256().ok().flatten();
+ let managed_policy_sha256 = crate::policy::managed_policy_sha256().ok().flatten();
+ let session_policy = crate::session_manifest::configured_session_manifest();
+ let session_policy_status = session_policy
+ .as_ref()
+ .ok()
+ .and_then(|manifest| *manifest)
+ .map(|manifest| {
+ let (allow, deny, ask) = manifest.counts();
+ serde_json::json!({
+ "sha256": manifest.sha256(),
+ "expires_unix_ms": manifest.expires_unix_ms(),
+ "idle_timeout_seconds": manifest.idle_timeout().as_secs(),
+ "allow_count": allow,
+ "deny_count": deny,
+ "ask_count": ask,
+ })
+ });
+ serde_json::json!({
+ "permission_mode": mode.as_ref().map(|mode| mode.as_str()).ok(),
+ "permission_mode_valid": mode.is_ok(),
+ "permission_mode_source": if std::env::var_os(PERMISSION_MODE_ENV).is_some() {
+ "trusted_startup_configuration"
+ } else {
+ "built_in_default"
+ },
+ "unrestricted_disabled_by_admin": env_flag(DISABLE_UNRESTRICTED_ENV),
+ "user_policy_configured": std::env::var_os(crate::policy::POLICY_FILE_ENV).is_some(),
+ "user_policy_active": matches!(policy, Ok(Some(_))),
+ "user_policy_valid": policy.is_ok(),
+ "user_policy_sha256": user_policy_sha256,
+ "managed_policy_configured": std::env::var_os(crate::policy::MANAGED_POLICY_FILE_ENV).is_some(),
+ "managed_policy_active": matches!(managed_policy, Ok(Some(_))),
+ "managed_policy_valid": managed_policy.is_ok(),
+ "managed_policy_sha256": managed_policy_sha256,
+ "built_in_ceiling": "reviewed_tool_and_risk_map_v1",
+ "legacy_existing_profile_approval": legacy_existing_profile_approval_enabled(),
+ "risk_metadata_version": RISK_METADATA_VERSION,
+ "active_risk_enforcement": ["browser_prepare.existing_profile"],
+ "protected_consent_collector": crate::consent::configured_provider_id(),
+ "session_policy_configured": std::env::var_os(crate::session_manifest::SESSION_POLICY_FILE_ENV).is_some(),
+ "session_policy_approved_at_startup": env_flag(crate::session_manifest::SESSION_POLICY_APPROVED_ENV),
+ "session_policy_valid": session_policy.is_ok(),
+ "session_policy": session_policy_status,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn standard_is_the_default() {
+ assert_eq!(
+ parse_permission_mode(None, false).unwrap(),
+ PermissionMode::Standard
+ );
+ }
+
+ #[test]
+ fn bounded_needs_no_bypass_flag() {
+ assert_eq!(
+ parse_permission_mode(Some("bounded"), false).unwrap(),
+ PermissionMode::Bounded
+ );
+ }
+
+ #[test]
+ fn autonomous_remains_a_compatibility_alias_for_bounded() {
+ assert_eq!(
+ parse_permission_mode(Some("autonomous"), false).unwrap(),
+ PermissionMode::Bounded
+ );
+ assert_eq!(
+ serde_json::from_str::<PermissionMode>("\"autonomous\"").unwrap(),
+ PermissionMode::Bounded
+ );
+ assert_eq!(
+ serde_json::to_string(&PermissionMode::Bounded).unwrap(),
+ "\"bounded\""
+ );
+ }
+
+ #[test]
+ fn unrestricted_requires_deliberate_acknowledgement() {
+ assert_eq!(
+ parse_permission_mode(Some("unrestricted"), false),
+ Err(PermissionModeError::MissingDangerAcknowledgement)
+ );
+ assert_eq!(
+ parse_permission_mode(Some("unrestricted"), true).unwrap(),
+ PermissionMode::Unrestricted
+ );
+ }
+
+ #[test]
+ fn danger_flag_cannot_weaken_another_mode() {
+ assert_eq!(
+ parse_permission_mode(Some("standard"), true),
+ Err(PermissionModeError::UnexpectedDangerAcknowledgement)
+ );
+ }
+
+ #[test]
+ fn yolo_is_only_an_alias_for_explicit_unrestricted() {
+ assert_eq!(
+ parse_permission_mode(Some("yolo"), true).unwrap(),
+ PermissionMode::Unrestricted
+ );
+ }
+
+ #[test]
+ fn existing_profile_is_the_first_actively_enforced_risk_operation() {
+ let existing = classify_tool_call(
+ "browser_prepare",
+ &serde_json::json!({"strategy": {"kind": "existing_profile"}}),
+ );
+ assert_eq!(existing.class, RiskClass::R2);
+ assert_eq!(existing.enforcement, RiskEnforcement::Active);
+
+ let isolated = classify_tool_call(
+ "browser_prepare",
+ &serde_json::json!({"profile": {"mode": "isolated_new"}}),
+ );
+ assert_eq!(isolated.class, RiskClass::R1);
+ assert_eq!(isolated.enforcement, RiskEnforcement::MetadataOnly);
+ }
+
+ #[test]
+ fn unknown_tools_are_unclassified_and_denied() {
+ let error = authorize_tool_call("new_unreviewed_tool", &serde_json::json!({}))
+ .expect_err("unknown risk must fail closed");
+ assert!(error
+ .to_string()
+ .contains("no reviewed risk classification"));
+ }
+
+ #[test]
+ fn process_targeted_tools_cannot_target_the_authorization_daemon() {
+ let error = authorize_tool_call(
+ "click",
+ &serde_json::json!({"pid": std::process::id(), "x": 1, "y": 1}),
+ )
+ .unwrap_err();
+ assert!(error.to_string().contains("authorization process"));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
index 7d2e9bfe84..17ec8baf00 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
@@ -70,6 +70,7 @@ pub struct BrowserEngine {
pub(crate) pool: CdpPool,
pub(crate) managed_browsers: ManagedBrowsers,
pub(crate) existing_profile_grants: ExistingProfileGrants,
+ pub(crate) approval_broker: crate::consent::ApprovalBroker,
mutation_gates: MutationGates,
reconnect_gates: ReconnectGates,
}
@@ -78,6 +79,21 @@ fn refuse(code: BrowserRefusalCode, msg: impl Into<String>) -> BrowserRefusal {
BrowserRefusal::new(code, msg)
}
+fn authorize_live_browser_origin(
+ manifest: Option<&crate::session_manifest::SessionManifest>,
+ live_url: &str,
+) -> Result<(), BrowserRefusal> {
+ let manifest = manifest.ok_or_else(|| {
+ refuse(
+ BrowserRefusalCode::BrowserOriginOutsideScope,
+ "the bounded session policy is unavailable",
+ )
+ })?;
+ manifest
+ .authorize_browser_url(live_url)
+ .map_err(|error| refuse(BrowserRefusalCode::BrowserOriginOutsideScope, error))
+}
+
fn route_err(context: &str, err: impl std::fmt::Display) -> BrowserRefusal {
refuse(
BrowserRefusalCode::BrowserRouteUnavailable,
@@ -387,12 +403,23 @@ impl BrowserEngine {
/// capability store. Platform crates call this once and register
/// the five tools via `register_browser_tools`.
pub fn new(platform: Arc<dyn BrowserPlatform>) -> Arc<Self> {
+ Self::new_with_protected_consent_provider(platform, None)
+ }
+
+ /// Create an engine with a provider installed by a trusted embedding host
+ /// or platform adapter. Ordinary MCP/CLI callers cannot register or replace
+ /// this provider after daemon startup.
+ pub fn new_with_protected_consent_provider(
+ platform: Arc<dyn BrowserPlatform>,
+ provider: Option<Arc<dyn crate::consent::ProtectedConsentProvider>>,
+ ) -> Arc<Self> {
let engine = Arc::new(Self {
platform,
store: BrowserStore::new(),
pool: CdpPool::new(),
managed_browsers: Default::default(),
existing_profile_grants: ExistingProfileGrants::new(),
+ approval_broker: crate::consent::ApprovalBroker::new(provider),
mutation_gates: MutationGates::new(),
reconnect_gates: ReconnectGates::new(),
});
@@ -401,14 +428,21 @@ impl BrowserEngine {
if let Some(engine) = weak.upgrade() {
engine.store.remove_session(session_id);
engine.cleanup_prepared_session(session_id);
- for (endpoint, generation) in
- engine.existing_profile_grants.remove_session(session_id)
- {
- engine.pool.release_claim_marker(&endpoint);
+ for grant in engine.existing_profile_grants.remove_session(session_id) {
+ engine.pool.release_claim_marker(&grant.endpoint_ws_url);
+ if let Some(protected) = grant.protected_consent.as_ref() {
+ protected.indicator.revoke();
+ }
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
let engine = engine.clone();
runtime.spawn(async move {
- engine.pool.release_existing(&endpoint, generation).await;
+ engine
+ .pool
+ .release_existing(&grant.endpoint_ws_url, grant.generation)
+ .await;
+ if let Some(protected) = grant.protected_consent.as_ref() {
+ engine.approval_broker.revoke(protected).await;
+ }
});
}
}
@@ -436,6 +470,9 @@ impl BrowserEngine {
self.pool
.release_existing(&grant.endpoint_ws_url, grant.generation)
.await;
+ if let Some(protected) = grant.protected_consent.as_ref() {
+ self.approval_broker.revoke(protected).await;
+ }
Err(refuse(
BrowserRefusalCode::BrowserConsentRequired,
"the existing-profile grant expired; approve this attachment again",
@@ -458,6 +495,9 @@ impl BrowserEngine {
self.pool
.release_existing(&grant.endpoint_ws_url, grant.generation)
.await;
+ if let Some(protected) = grant.protected_consent.as_ref() {
+ self.approval_broker.revoke(protected).await;
+ }
}
}
@@ -1202,6 +1242,36 @@ impl BrowserEngine {
}
let cdp_session = self.attach(&conn, &tab.cdp_target_id).await?;
+ if crate::authorization::configured_permission_mode()
+ .is_ok_and(|mode| mode == crate::authorization::PermissionMode::Bounded)
+ {
+ let frame_tree = conn
+ .call(Some(&cdp_session), "Page.getFrameTree", json!({}))
+ .await
+ .map_err(|error| {
+ route_err(
+ "could not prove the live browser origin before bounded-mode input",
+ error,
+ )
+ })?;
+ let live_url = frame_tree
+ .pointer("/frameTree/frame/url")
+ .and_then(Value::as_str)
+ .ok_or_else(|| {
+ refuse(
+ BrowserRefusalCode::BrowserOriginOutsideScope,
+ "the live top-level browser origin could not be proven",
+ )
+ })?;
+ let manifest =
+ crate::session_manifest::configured_session_manifest().map_err(|error| {
+ refuse(
+ BrowserRefusalCode::BrowserOriginOutsideScope,
+ format!("the bounded session policy is unavailable: {error}"),
+ )
+ })?;
+ authorize_live_browser_origin(manifest, live_url)?;
+ }
Ok(ValidatedTab {
conn,
record,
@@ -2420,4 +2490,34 @@ mod tests {
);
assert!(parse_frame_tree(&json!({})).is_none());
}
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn live_browser_origin_decision_refuses_redirect_outside_manifest_scope() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("session-policy.yaml");
+ std::fs::write(
+ &path,
+ r#"
+version: 1
+mode: bounded
+expires_after: 1h
+idle_timeout: 10m
+resources:
+ browser:
+ origins: [https://app.example.com]
+allow:
+ tools: [browser_navigate, browser_click]
+"#,
+ )
+ .unwrap();
+ let manifest = crate::session_manifest::load_manifest(&path).unwrap();
+
+ authorize_live_browser_origin(Some(&manifest), "https://app.example.com/work").unwrap();
+ let refusal =
+ authorize_live_browser_origin(Some(&manifest), "https://attacker.example/redirected")
+ .unwrap_err();
+ assert_eq!(refusal.code, BrowserRefusalCode::BrowserOriginOutsideScope);
+ assert!(authorize_live_browser_origin(None, "https://app.example.com").is_err());
+ }
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs
index 60f9d71d7e..761484ca1d 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs
@@ -33,6 +33,10 @@ pub(crate) struct ExistingProfileGrant {
pub endpoint_ws_url: String,
pub generation: u64,
pub reconnect_attempts_remaining: u8,
+ pub protected_consent: Option<crate::consent::ProtectedGrant>,
+ pub permission_mode: crate::authorization::PermissionMode,
+ pub managed_policy_sha256: Option<String>,
+ pub user_policy_sha256: Option<String>,
created_at: Instant,
last_used_at: Instant,
}
@@ -47,6 +51,17 @@ impl ExistingProfileGrant {
fn expired(&self, now: Instant) -> bool {
now.duration_since(self.last_used_at) > GRANT_IDLE_TTL
|| now.duration_since(self.created_at) > GRANT_ABSOLUTE_TTL
+ || self
+ .protected_consent
+ .as_ref()
+ .is_some_and(|grant| !grant.is_live())
+ }
+
+ fn authorization_context_matches(&self) -> bool {
+ crate::authorization::configured_permission_mode()
+ .is_ok_and(|mode| mode == self.permission_mode)
+ && crate::policy::managed_policy_sha256().ok().flatten() == self.managed_policy_sha256
+ && crate::policy::user_policy_sha256().ok().flatten() == self.user_policy_sha256
}
}
@@ -77,6 +92,7 @@ impl ExistingProfileGrants {
fingerprint: ProcessFingerprint,
browser: String,
endpoint_ws_url: String,
+ protected_consent: Option<crate::consent::ProtectedGrant>,
) -> ExistingProfileGrant {
let now = Instant::now();
let key = Self::key(public_session, transport_session, pid);
@@ -96,6 +112,11 @@ impl ExistingProfileGrants {
endpoint_ws_url,
generation,
reconnect_attempts_remaining: MAX_RECONNECT_ATTEMPTS,
+ protected_consent,
+ permission_mode: crate::authorization::configured_permission_mode()
+ .unwrap_or(crate::authorization::PermissionMode::Standard),
+ managed_policy_sha256: crate::policy::managed_policy_sha256().ok().flatten(),
+ user_policy_sha256: crate::policy::user_policy_sha256().ok().flatten(),
created_at: now,
last_used_at: now,
};
@@ -115,7 +136,7 @@ impl ExistingProfileGrants {
let Some(grant) = grants.get_mut(&key) else {
return GrantLookup::Missing;
};
- if grant.expired(now) {
+ if grant.expired(now) || !grant.authorization_context_matches() {
return GrantLookup::Expired(grants.remove(&key).expect("expired grant exists"));
}
grant.last_used_at = now;
@@ -134,12 +155,12 @@ impl ExistingProfileGrants {
.remove(&Self::key(public_session, transport_session, pid))
}
- pub fn remove_session(&self, session: &str) -> Vec<(String, u64)> {
+ pub fn remove_session(&self, session: &str) -> Vec<ExistingProfileGrant> {
let mut removed = Vec::new();
self.inner.lock().unwrap().retain(|_, grant| {
let keep = grant.public_session != session && grant.transport_session != session;
if !keep {
- removed.push((grant.endpoint_ws_url.clone(), grant.generation));
+ removed.push(grant.clone());
}
keep
});
@@ -196,6 +217,7 @@ mod tests {
fingerprint(42),
"chromium".to_owned(),
"ws://127.0.0.1:1/devtools/browser/x".to_owned(),
+ None,
);
assert!(matches!(
grants.lookup("public-a", Some("transport-a"), 42),
@@ -222,6 +244,7 @@ mod tests {
fingerprint(42),
"chromium".to_owned(),
"ws://127.0.0.1:1/devtools/browser/x".to_owned(),
+ None,
);
assert_eq!(grants.remove_session("transport-a").len(), 1);
assert!(matches!(
@@ -241,6 +264,7 @@ mod tests {
fingerprint(42),
"chromium".to_owned(),
"ws://127.0.0.1:1/devtools/browser/x".to_owned(),
+ None,
);
let key = ExistingProfileGrants::key("public-a", Some("transport-a"), 42);
grants
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
index ed77e98be9..0d8f36cb2e 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
@@ -675,6 +675,12 @@ impl BrowserEngine {
&self,
request: PrepareRequest,
) -> Result<PrepareOutcome, BrowserRefusal> {
+ enum ConsentPath {
+ Protected,
+ LegacyArtifact,
+ Unrestricted,
+ }
+
let window_id = request.window_id.ok_or_else(|| {
refusal(
BrowserRefusalCode::BrowserConsentRequired,
@@ -686,24 +692,49 @@ impl BrowserEngine {
window_id,
session: request.session.clone(),
};
- match request.authorization.as_ref() {
- Some(PrepareAuthorization::ApprovalArtifact(token)) => {
- consume_existing_profile_approval(token, &scope)?;
- }
- // The ordinary MCP destructive-tool marker proves transport
- // provenance, not a person's approval of their authenticated
- // profile. It is deliberately insufficient here.
- Some(PrepareAuthorization::McpHost) | None => {
- return Err(refusal(
- BrowserRefusalCode::BrowserConsentRequired,
- "existing-profile attachment requires a fresh operation-bound browser-approve artifact",
- )
- .with_detail(serde_json::json!({
- "approval_request_id": uuid::Uuid::new_v4().to_string(),
- "approval_command": "cua-driver browser-approve --strategy existing_profile --pid <pid> --window-id <window_id> --session <session>",
- })));
+ let mode = crate::authorization::configured_permission_mode().map_err(|error| {
+ refusal(
+ BrowserRefusalCode::BrowserConsentRequired,
+ format!("permission mode is unavailable: {error}"),
+ )
+ })?;
+ let consent_path = if mode == crate::authorization::PermissionMode::Unrestricted {
+ ConsentPath::Unrestricted
+ } else if self.approval_broker.provider_id().is_some() {
+ ConsentPath::Protected
+ } else if crate::authorization::legacy_existing_profile_approval_enabled() {
+ match request.authorization.as_ref() {
+ Some(PrepareAuthorization::ApprovalArtifact(token)) => {
+ consume_existing_profile_approval(token, &scope)?;
+ ConsentPath::LegacyArtifact
+ }
+ // The ordinary MCP destructive-tool marker proves transport
+ // provenance, not a person's approval of their authenticated
+ // profile. It is deliberately insufficient here.
+ Some(PrepareAuthorization::McpHost) | None => {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserConsentRequired,
+ "legacy existing-profile compatibility requires a fresh operation-bound browser-approve artifact",
+ )
+ .with_detail(serde_json::json!({
+ "approval_request_id": uuid::Uuid::new_v4().to_string(),
+ "approval_command": "cua-driver browser-approve --strategy existing_profile --pid <pid> --window-id <window_id> --session <session>",
+ "legacy_approval_enabled": true,
+ })));
+ }
}
- }
+ } else {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserConsentRequired,
+ "existing-profile attachment requires a certified trusted-consent provider in standard/bounded mode; the legacy file-backed artifact is disabled",
+ )
+ .with_detail(serde_json::json!({
+ "permission_mode": mode.as_str(),
+ "trusted_consent_required": true,
+ "legacy_approval_enabled": false,
+ "protected_consent_collector": self.approval_broker.provider_id(),
+ })));
+ };
if request.profile.is_some() || request.allow_launch {
return Err(refusal(
BrowserRefusalCode::BrowserConsentRequired,
@@ -830,6 +861,58 @@ impl BrowserEngine {
return Err(error);
}
+ // Consent is collected only after the exact process, native window,
+ // browser product, and endpoint owner have all been proven. This keeps
+ // the human-visible request exact and avoids activating an indicator
+ // for a target that cannot be attached.
+ let protected_consent = if matches!(consent_path, ConsentPath::Protected) {
+ let transport_session = request
+ .transport_session
+ .as_deref()
+ .unwrap_or(request.session.as_str());
+ let approval_request = self.approval_broker.request(
+ mode,
+ "browser_prepare.existing_profile",
+ crate::authorization::RiskClass::R2,
+ request.session.clone(),
+ transport_session.to_owned(),
+ serde_json::json!({
+ "pid": request.pid,
+ "window_id": window_id,
+ "process_fingerprint": fingerprint.clone(),
+ "browser_product": classification.product_kind,
+ "endpoint_owner_pid": endpoint.ownership.owner_pid,
+ }),
+ format!(
+ "Attach Cua Driver to {:?} window {} using its logged-in profile",
+ classification.product_kind, window_id
+ ),
+ );
+ Some(
+ if mode == crate::authorization::PermissionMode::Bounded {
+ self.approval_broker
+ .activate_preapproved(&approval_request)
+ .await
+ } else {
+ self.approval_broker.approve(&approval_request).await
+ }
+ .map_err(|error| {
+ refusal(
+ BrowserRefusalCode::BrowserConsentRequired,
+ format!("protected existing-profile consent was not granted: {error}"),
+ )
+ .with_detail(serde_json::json!({
+ "permission_mode": mode.as_str(),
+ "trusted_consent_required": true,
+ "provider": self.approval_broker.provider_id(),
+ "approval_request_id": approval_request.nonce,
+ }))
+ })?,
+ )
+ } else {
+ None
+ };
+
let previous_grant = self
.existing_profile_grant(
&request.session,
@@ -840,6 +923,9 @@ impl BrowserEngine {
let previous_grant = match previous_grant {
Ok(grant) => grant,
Err(error) => {
+ if let Some(protected) = protected_consent.as_ref() {
+ self.approval_broker.revoke(protected).await;
+ }
let error = with_setup_side_effects(error, &setup);
if setup_pending {
return Err(setup_guard
@@ -860,11 +946,15 @@ impl BrowserEngine {
fingerprint,
"chromium".to_owned(),
endpoint.ws_url.clone(),
+ protected_consent,
);
if let Some(previous) = previous_grant {
self.pool
.release_existing(&previous.endpoint_ws_url, previous.generation)
.await;
+ if let Some(protected) = previous.protected_consent.as_ref() {
+ self.approval_broker.revoke(protected).await;
+ }
if previous.endpoint_ws_url != endpoint.ws_url {
self.pool.release_claim_marker(&previous.endpoint_ws_url);
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/refusal.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/refusal.rs
index fb71950b7c..51863b4486 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/refusal.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/refusal.rs
@@ -61,6 +61,9 @@ pub enum BrowserRefusalCode {
/// A semantic ref is live, but it does not declare the requested typed
/// browser action.
BrowserActionUnavailable,
+ /// The live top-level document left the origin set approved in the
+ /// bounded session manifest. Further browser input is paused.
+ BrowserOriginOutsideScope,
}
impl BrowserRefusalCode {
@@ -82,6 +85,7 @@ impl BrowserRefusalCode {
Self::BrowserReconnectExhausted => "browser_reconnect_exhausted",
Self::BrowserInputIncomplete => "browser_input_incomplete",
Self::BrowserActionUnavailable => "browser_action_unavailable",
+ Self::BrowserOriginOutsideScope => "browser_origin_outside_scope",
}
}
}
@@ -186,6 +190,10 @@ mod tests {
BrowserRefusalCode::BrowserActionUnavailable,
"browser_action_unavailable",
),
+ (
+ BrowserRefusalCode::BrowserOriginOutsideScope,
+ "browser_origin_outside_scope",
+ ),
];
for (code, wire) in all {
assert_eq!(code.as_str(), wire);
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
index 0677b3fec7..7318cbddf4 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
@@ -393,13 +393,15 @@ impl BrowserPrepareTool {
name: "browser_prepare".into(),
description: "Explicitly prepare an owned DevTools endpoint for a browser \
pid. Existing endpoints are detected without side effects. Acting setup \
- requires MCP-host approval or a short-lived token from the interactive \
- browser-approve command, allow_launch=true, and a driver-owned isolated \
- profile. It launches a separate browser and never copies, modifies, or \
- terminates the requested user profile. Existing-profile attachment is \
- explicit, requires an exact interactive approval artifact, and never \
- treats ordinary MCP transport approval as profile consent. On proven \
- platforms, that approval also permits one bounded exact-window setup: \
+ for an isolated profile requires host approval or a short-lived setup \
+ token plus allow_launch=true. It launches a separate browser and never \
+ copies, modifies, or terminates the requested user profile. Existing-profile \
+ attachment is explicit and follows the daemon's immutable permission mode: \
+ standard requires a certified protected-consent provider, bounded requires \
+ a launch-approved exact resource manifest plus protected indicator, and \
+ unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP \
+ transport approval never proves profile consent. On proven platforms, an \
+ authorized request also permits one bounded exact-window setup: \
open the recognized browser product's fixed remote-debugging page, toggle \
its uniquely matched per-instance checkbox, prove the PID-owned loopback \
endpoint, and close the temporary tab. Every visible effect is reported; \
@@ -412,7 +414,7 @@ impl BrowserPrepareTool {
"window_id": { "type": "integer", "description": "Exact native window approval anchor; required for strategy.kind=existing_profile." },
"approval_token": {
"type": "string",
- "description": "Single-use token minted by `cua-driver browser-approve` for direct CLI/raw use. Omit for an MCP-host-approved call."
+ "description": "Legacy single-use setup token. Existing-profile use is disabled unless a trusted launcher explicitly enables the same-user-writable compatibility path."
},
"allow_launch": {
"type": "boolean",
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
index e4443e4226..49ba71c349 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
@@ -866,6 +866,74 @@ async fn existing_profile_only_fixture() -> Fixture {
}
}
+struct FixtureProtectedProvider {
+ consent_seen: AtomicBool,
+ stopped: Arc<AtomicBool>,
+}
+
+#[async_trait]
+impl crate::consent::ProtectedConsentProvider for FixtureProtectedProvider {
+ fn provider_id(&self) -> &'static str {
+ "test.browser-protected-provider"
+ }
+
+ async fn request_consent(
+ &self,
+ request: &crate::consent::ConsentRequest,
+ ) -> Result<crate::consent::ProviderDecision, String> {
+ self.consent_seen.store(true, Ordering::SeqCst);
+ Ok(crate::consent::ProviderDecision {
+ action: crate::consent::ConsentAction::Accept,
+ request_digest: request.request_digest.clone(),
+ })
+ }
+
+ async fn activate_indicator(
+ &self,
+ _request: &crate::consent::ConsentRequest,
+ ) -> Result<crate::consent::IndicatorLease, String> {
+ Ok(crate::consent::IndicatorLease::new(
+ "browser-indicator",
+ self.stopped.clone(),
+ ))
+ }
+
+ async fn deactivate_indicator(&self, _indicator_id: &str) {
+ self.stopped.store(true, Ordering::SeqCst);
+ }
+}
+
+async fn protected_existing_profile_fixture() -> (Fixture, Arc<FixtureProtectedProvider>) {
+ let state = Arc::new(StdMutex::new(FixtureState::default()));
+ let server = MockCdpServer::start(fixture_handler(state.clone())).await;
+ let setup_invoked = Arc::new(AtomicBool::new(false));
+ let provider = Arc::new(FixtureProtectedProvider {
+ consent_seen: AtomicBool::new(false),
+ stopped: Arc::new(AtomicBool::new(false)),
+ });
+ let engine = BrowserEngine::new_with_protected_consent_provider(
+ Arc::new(FixturePlatform {
+ ws_url: server.ws_url(),
+ trusted_input_limited: false,
+ managed_endpoint_visible: false,
+ existing_endpoint_visible: Arc::new(AtomicBool::new(true)),
+ setup_invoked: setup_invoked.clone(),
+ setup_aborted: Arc::new(AtomicBool::new(false)),
+ stall_consent: false,
+ }),
+ Some(provider.clone()),
+ );
+ (
+ Fixture {
+ state,
+ _server: server,
+ engine,
+ setup_invoked,
+ },
+ provider,
+ )
+}
+
async fn existing_profile_setup_fixture() -> (Fixture, Arc<AtomicBool>) {
let state = Arc::new(StdMutex::new(FixtureState::default()));
let server = MockCdpServer::start(fixture_handler(state.clone())).await;
@@ -955,6 +1023,44 @@ async fn approved_existing_profile_attach_claims_then_binds_one_generation() {
crate::session::fire_session_end("transport-v2-attach");
}
+#[tokio::test]
+async fn protected_provider_accepts_exact_attach_and_stop_revokes_the_grant() {
+ const PROTECTED_SESSION: &str = "protected-provider-v2";
+ const PROTECTED_TRANSPORT: &str = "protected-transport-v2";
+ let (f, provider) = protected_existing_profile_fixture().await;
+ let prepare = BrowserPrepareTool::new(f.engine.clone())
+ .invoke(json!({
+ "pid": 1,
+ "window_id": 7,
+ "session": PROTECTED_SESSION,
+ "_transport_session_id": PROTECTED_TRANSPORT,
+ "strategy": { "kind": "existing_profile" }
+ }))
+ .await;
+ assert_eq!(
+ structured(&prepare)["status"],
+ "ok",
+ "{}",
+ structured(&prepare)
+ );
+ assert!(provider.consent_seen.load(Ordering::SeqCst));
+ assert!(!provider.stopped.load(Ordering::SeqCst));
+
+ crate::session::fire_session_end(PROTECTED_TRANSPORT);
+ tokio::task::yield_now().await;
+ assert!(provider.stopped.load(Ordering::SeqCst));
+
+ let state = GetBrowserStateTool::new(f.engine.clone())
+ .invoke(json!({
+ "pid": 1,
+ "window_id": 7,
+ "session": PROTECTED_SESSION,
+ "_transport_session_id": PROTECTED_TRANSPORT
+ }))
+ .await;
+ assert_eq!(structured(&state)["status"], "refused");
+}
+
#[tokio::test]
async fn approved_existing_profile_setup_reports_exact_side_effects() {
let (f, setup_invoked) = existing_profile_setup_fixture().await;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs
new file mode 100644
index 0000000000..30b2567281
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs
@@ -0,0 +1,494 @@
+//! Protected consent provider seam.
+//!
+//! Ordinary MCP elicitation, tool arguments, inherited stdio, files, and
+//! environment variables never implement this trait. A provider is installed
+//! in-process by a trusted host/platform adapter and returns its decision
+//! directly to the daemon, bound to the exact request digest. Out-of-process
+//! implementations must authenticate their private channel before adapting it
+//! to this interface.
+
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, OnceLock};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use sha2::{Digest, Sha256};
+use uuid::Uuid;
+
+use crate::authorization::{PermissionMode, RiskClass};
+
+const DEFAULT_REQUEST_TTL: Duration = Duration::from_secs(2 * 60);
+static CONFIGURED_PROVIDER_ID: OnceLock<&'static str> = OnceLock::new();
+
+pub fn configured_provider_id() -> Option<&'static str> {
+ CONFIGURED_PROVIDER_ID.get().copied()
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ConsentAction {
+ Accept,
+ Decline,
+ Cancel,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ProviderDecision {
+ pub action: ConsentAction,
+ pub request_digest: String,
+}
+
+/// Exact, bounded request rendered by a protected provider. `resource` is
+/// typed by the caller and never copied into telemetry or refusal strings.
+#[derive(Debug, Clone, Serialize)]
+pub struct ConsentRequest {
+ pub schema: &'static str,
+ pub nonce: String,
+ pub generation: u64,
+ pub daemon_instance: String,
+ pub permission_mode: PermissionMode,
+ pub managed_policy_sha256: Option<String>,
+ pub user_policy_sha256: Option<String>,
+ pub operation: String,
+ pub risk_class: RiskClass,
+ pub public_session: String,
+ pub transport_session: String,
+ pub resource: Value,
+ pub human_summary: String,
+ pub expires_unix_ms: u128,
+ pub request_digest: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct IndicatorLease {
+ pub id: String,
+ revoked: Arc<AtomicBool>,
+}
+
+impl IndicatorLease {
+ pub fn new(id: impl Into<String>, revoked: Arc<AtomicBool>) -> Self {
+ Self {
+ id: id.into(),
+ revoked,
+ }
+ }
+
+ pub fn revoked(&self) -> bool {
+ self.revoked.load(Ordering::Acquire)
+ }
+
+ pub fn revoke(&self) {
+ self.revoked.store(true, Ordering::Release);
+ }
+}
+
+/// Trusted integration contract. Implementors must keep approval and Stop UI
+/// outside model/tool control and must not auto-accept protected requests.
+/// The returned indicator lease is authoritative: the provider must bind its
+/// visible state to the lease's revocation flag so session teardown remains
+/// effective even when an asynchronous deactivate callback cannot run.
+#[async_trait]
+pub trait ProtectedConsentProvider: Send + Sync + 'static {
+ fn provider_id(&self) -> &'static str;
+
+ async fn request_consent(&self, request: &ConsentRequest) -> Result<ProviderDecision, String>;
+
+ /// Activate persistent, non-optional visible state with a Stop control.
+ /// Returning an error prevents the grant from becoming live.
+ async fn activate_indicator(&self, request: &ConsentRequest) -> Result<IndicatorLease, String>;
+
+ async fn deactivate_indicator(&self, indicator_id: &str);
+}
+
+#[derive(Debug, Clone)]
+pub struct ProtectedGrant {
+ pub id: Uuid,
+ pub provider_id: &'static str,
+ pub request_digest: String,
+ pub indicator: IndicatorLease,
+}
+
+impl ProtectedGrant {
+ pub fn is_live(&self) -> bool {
+ !self.indicator.revoked()
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum ConsentError {
+ #[error("no certified protected-consent provider is available")]
+ Unavailable,
+ #[error("protected consent was declined")]
+ Declined,
+ #[error("protected consent was canceled")]
+ Canceled,
+ #[error("protected consent provider failed: {0}")]
+ Provider(String),
+ #[error("protected consent response did not match the exact request digest")]
+ DigestMismatch,
+ #[error("protected consent expired before activation")]
+ Expired,
+ #[error("persistent consent indicator could not be activated: {0}")]
+ Indicator(String),
+}
+
+#[derive(Clone)]
+pub struct ApprovalBroker {
+ daemon_instance: Arc<str>,
+ next_generation: Arc<AtomicU64>,
+ provider: Option<Arc<dyn ProtectedConsentProvider>>,
+}
+
+impl ApprovalBroker {
+ pub fn unavailable() -> Self {
+ Self::new(None)
+ }
+
+ pub fn new(provider: Option<Arc<dyn ProtectedConsentProvider>>) -> Self {
+ if let Some(provider) = provider.as_ref() {
+ let _ = CONFIGURED_PROVIDER_ID.set(provider.provider_id());
+ }
+ Self {
+ daemon_instance: Arc::from(Uuid::new_v4().to_string()),
+ next_generation: Arc::new(AtomicU64::new(1)),
+ provider,
+ }
+ }
+
+ pub fn provider_id(&self) -> Option<&'static str> {
+ self.provider
+ .as_ref()
+ .map(|provider| provider.provider_id())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub fn request(
+ &self,
+ permission_mode: PermissionMode,
+ operation: impl Into<String>,
+ risk_class: RiskClass,
+ public_session: impl Into<String>,
+ transport_session: impl Into<String>,
+ resource: Value,
+ human_summary: impl Into<String>,
+ ) -> ConsentRequest {
+ let expires_unix_ms = now_unix_ms() + DEFAULT_REQUEST_TTL.as_millis();
+ let mut request = ConsentRequest {
+ schema: "cua-protected-consent-request-v1",
+ nonce: Uuid::new_v4().to_string(),
+ generation: self.next_generation.fetch_add(1, Ordering::Relaxed),
+ daemon_instance: self.daemon_instance.to_string(),
+ permission_mode,
+ managed_policy_sha256: crate::policy::managed_policy_sha256().ok().flatten(),
+ user_policy_sha256: crate::policy::user_policy_sha256().ok().flatten(),
+ operation: operation.into(),
+ risk_class,
+ public_session: public_session.into(),
+ transport_session: transport_session.into(),
+ resource,
+ human_summary: human_summary.into(),
+ expires_unix_ms,
+ request_digest: String::new(),
+ };
+ request.request_digest = digest_request(&request);
+ request
+ }
+
+ pub async fn approve(&self, request: &ConsentRequest) -> Result<ProtectedGrant, ConsentError> {
+ let provider = self.provider.as_ref().ok_or(ConsentError::Unavailable)?;
+ if request.expires_unix_ms < now_unix_ms() {
+ return Err(ConsentError::Expired);
+ }
+ if request.request_digest != digest_request(request) {
+ return Err(ConsentError::DigestMismatch);
+ }
+ let decision = tokio::time::timeout(remaining(request)?, provider.request_consent(request))
+ .await
+ .map_err(|_| ConsentError::Provider("request timed out".to_owned()))?
+ .map_err(ConsentError::Provider)?;
+ if decision.request_digest != request.request_digest {
+ return Err(ConsentError::DigestMismatch);
+ }
+ match decision.action {
+ ConsentAction::Accept => {}
+ ConsentAction::Decline => return Err(ConsentError::Declined),
+ ConsentAction::Cancel => return Err(ConsentError::Canceled),
+ }
+ if request.expires_unix_ms < now_unix_ms() {
+ return Err(ConsentError::Expired);
+ }
+ let indicator =
+ tokio::time::timeout(remaining(request)?, provider.activate_indicator(request))
+ .await
+ .map_err(|_| ConsentError::Indicator("activation timed out".to_owned()))?
+ .map_err(ConsentError::Indicator)?;
+ if request.expires_unix_ms < now_unix_ms() {
+ indicator.revoke();
+ provider.deactivate_indicator(&indicator.id).await;
+ return Err(ConsentError::Expired);
+ }
+ Ok(ProtectedGrant {
+ id: Uuid::new_v4(),
+ provider_id: provider.provider_id(),
+ request_digest: request.request_digest.clone(),
+ indicator,
+ })
+ }
+
+ /// Activate the mandatory indicator for an operation already covered by a
+ /// launch-approved bounded manifest. This never asks or accepts an
+ /// in-band decision; the manifest remains the authorization and the
+ /// provider supplies only persistent visible Stop state.
+ pub async fn activate_preapproved(
+ &self,
+ request: &ConsentRequest,
+ ) -> Result<ProtectedGrant, ConsentError> {
+ let provider = self.provider.as_ref().ok_or(ConsentError::Unavailable)?;
+ if request.expires_unix_ms < now_unix_ms() {
+ return Err(ConsentError::Expired);
+ }
+ if request.request_digest != digest_request(request) {
+ return Err(ConsentError::DigestMismatch);
+ }
+ let indicator =
+ tokio::time::timeout(remaining(request)?, provider.activate_indicator(request))
+ .await
+ .map_err(|_| ConsentError::Indicator("activation timed out".to_owned()))?
+ .map_err(ConsentError::Indicator)?;
+ if request.expires_unix_ms < now_unix_ms() {
+ indicator.revoke();
+ provider.deactivate_indicator(&indicator.id).await;
+ return Err(ConsentError::Expired);
+ }
+ Ok(ProtectedGrant {
+ id: Uuid::new_v4(),
+ provider_id: provider.provider_id(),
+ request_digest: request.request_digest.clone(),
+ indicator,
+ })
+ }
+
+ pub async fn revoke(&self, grant: &ProtectedGrant) {
+ grant.indicator.revoke();
+ if let Some(provider) = &self.provider {
+ if provider.provider_id() == grant.provider_id {
+ provider.deactivate_indicator(&grant.indicator.id).await;
+ }
+ }
+ }
+}
+
+fn now_unix_ms() -> u128 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+}
+
+fn remaining(request: &ConsentRequest) -> Result<Duration, ConsentError> {
+ let remaining_ms = request
+ .expires_unix_ms
+ .checked_sub(now_unix_ms())
+ .ok_or(ConsentError::Expired)?;
+ let remaining_ms = u64::try_from(remaining_ms).unwrap_or(u64::MAX);
+ if remaining_ms == 0 {
+ return Err(ConsentError::Expired);
+ }
+ Ok(Duration::from_millis(remaining_ms))
+}
+
+fn digest_request(request: &ConsentRequest) -> String {
+ let canonical = serde_json::json!({
+ "schema": request.schema,
+ "nonce": request.nonce,
+ "generation": request.generation,
+ "daemon_instance": request.daemon_instance,
+ "permission_mode": request.permission_mode,
+ "managed_policy_sha256": request.managed_policy_sha256,
+ "user_policy_sha256": request.user_policy_sha256,
+ "operation": request.operation,
+ "risk_class": request.risk_class,
+ "public_session": request.public_session,
+ "transport_session": request.transport_session,
+ "resource": request.resource,
+ "human_summary": request.human_summary,
+ "expires_unix_ms": request.expires_unix_ms,
+ });
+ let bytes = serde_json::to_vec(&canonical).expect("serialize protected consent request");
+ format!("{:x}", Sha256::digest(bytes))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Mutex;
+
+ struct FakeProvider {
+ action: ConsentAction,
+ replace_digest: bool,
+ indicator_error: bool,
+ indicator_delay: Duration,
+ revoked: Arc<AtomicBool>,
+ deactivated: Mutex<Vec<String>>,
+ requests: AtomicU64,
+ }
+
+ #[async_trait]
+ impl ProtectedConsentProvider for FakeProvider {
+ fn provider_id(&self) -> &'static str {
+ "test.protected-provider"
+ }
+
+ async fn request_consent(
+ &self,
+ request: &ConsentRequest,
+ ) -> Result<ProviderDecision, String> {
+ self.requests.fetch_add(1, Ordering::SeqCst);
+ Ok(ProviderDecision {
+ action: self.action,
+ request_digest: if self.replace_digest {
+ "forged".to_owned()
+ } else {
+ request.request_digest.clone()
+ },
+ })
+ }
+
+ async fn activate_indicator(
+ &self,
+ _request: &ConsentRequest,
+ ) -> Result<IndicatorLease, String> {
+ tokio::time::sleep(self.indicator_delay).await;
+ if self.indicator_error {
+ return Err("indicator unavailable".to_owned());
+ }
+ Ok(IndicatorLease::new("indicator-1", self.revoked.clone()))
+ }
+
+ async fn deactivate_indicator(&self, indicator_id: &str) {
+ self.deactivated
+ .lock()
+ .unwrap()
+ .push(indicator_id.to_owned());
+ }
+ }
+
+ fn provider(action: ConsentAction) -> Arc<FakeProvider> {
+ Arc::new(FakeProvider {
+ action,
+ replace_digest: false,
+ indicator_error: false,
+ indicator_delay: Duration::ZERO,
+ revoked: Arc::new(AtomicBool::new(false)),
+ deactivated: Mutex::new(Vec::new()),
+ requests: AtomicU64::new(0),
+ })
+ }
+
+ fn request(broker: &ApprovalBroker) -> ConsentRequest {
+ broker.request(
+ PermissionMode::Standard,
+ "browser_prepare.existing_profile",
+ RiskClass::R2,
+ "public-session",
+ "transport-session",
+ serde_json::json!({"pid": 42, "window_id": 7}),
+ "Attach to Chromium window 7",
+ )
+ }
+
+ #[tokio::test]
+ async fn exact_accept_activates_a_revocable_indicator() {
+ let provider = provider(ConsentAction::Accept);
+ let broker = ApprovalBroker::new(Some(provider.clone()));
+ let grant = broker.approve(&request(&broker)).await.unwrap();
+ assert!(grant.is_live());
+ broker.revoke(&grant).await;
+ assert!(!grant.is_live());
+ assert_eq!(
+ provider.deactivated.lock().unwrap().as_slice(),
+ ["indicator-1"]
+ );
+ }
+
+ #[tokio::test]
+ async fn missing_provider_fails_closed() {
+ let broker = ApprovalBroker::unavailable();
+ assert_eq!(
+ broker.approve(&request(&broker)).await.unwrap_err(),
+ ConsentError::Unavailable
+ );
+ }
+
+ #[tokio::test]
+ async fn forged_digest_never_activates_a_grant() {
+ let fake = FakeProvider {
+ action: ConsentAction::Accept,
+ replace_digest: true,
+ indicator_error: false,
+ indicator_delay: Duration::ZERO,
+ revoked: Arc::new(AtomicBool::new(false)),
+ deactivated: Mutex::new(Vec::new()),
+ requests: AtomicU64::new(0),
+ };
+ let broker = ApprovalBroker::new(Some(Arc::new(fake)));
+ assert_eq!(
+ broker.approve(&request(&broker)).await.unwrap_err(),
+ ConsentError::DigestMismatch
+ );
+ }
+
+ #[tokio::test]
+ async fn indicator_failure_prevents_grant_activation() {
+ let provider = Arc::new(FakeProvider {
+ action: ConsentAction::Accept,
+ replace_digest: false,
+ indicator_error: true,
+ indicator_delay: Duration::ZERO,
+ revoked: Arc::new(AtomicBool::new(false)),
+ deactivated: Mutex::new(Vec::new()),
+ requests: AtomicU64::new(0),
+ });
+ let broker = ApprovalBroker::new(Some(provider));
+ assert!(matches!(
+ broker.approve(&request(&broker)).await,
+ Err(ConsentError::Indicator(_))
+ ));
+ }
+
+ #[tokio::test]
+ async fn launch_preapproved_autonomy_activates_indicator_without_a_second_prompt() {
+ let provider = provider(ConsentAction::Decline);
+ let broker = ApprovalBroker::new(Some(provider.clone()));
+ let grant = broker
+ .activate_preapproved(&request(&broker))
+ .await
+ .unwrap();
+ assert!(grant.is_live());
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test]
+ async fn provider_cannot_activate_an_indicator_after_request_expiry() {
+ let provider = Arc::new(FakeProvider {
+ action: ConsentAction::Accept,
+ replace_digest: false,
+ indicator_error: false,
+ indicator_delay: Duration::from_millis(50),
+ revoked: Arc::new(AtomicBool::new(false)),
+ deactivated: Mutex::new(Vec::new()),
+ requests: AtomicU64::new(0),
+ });
+ let broker = ApprovalBroker::new(Some(provider));
+ let mut expiring = request(&broker);
+ expiring.expires_unix_ms = now_unix_ms() + 15;
+ expiring.request_digest = digest_request(&expiring);
+
+ assert!(matches!(
+ broker.approve(&expiring).await,
+ Err(ConsentError::Indicator(message)) if message.contains("timed out")
+ ));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
index d58a64ef7f..3a22669594 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
@@ -32,10 +32,12 @@ pub fn embedded_mode() -> bool {
std::env::var_os(EMBEDDED_ENV).is_some_and(|v| v == "1")
}
+pub mod authorization;
pub mod browser;
pub mod capture_mode;
pub mod capture_scope;
pub mod cdp;
+pub mod consent;
pub mod cursor_sampler;
pub mod element_cache;
pub mod element_token;
@@ -53,6 +55,7 @@ pub mod recording_tools;
pub mod recording_zoom;
pub mod server;
pub mod session;
+pub mod session_manifest;
pub mod session_tools;
pub mod socket_io;
pub mod text_sanitize;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/policy.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/policy.rs
index 9017c238c5..b674f55613 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/policy.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/policy.rs
@@ -1,16 +1,15 @@
//! Optional permission-policy enforcement for MCP tool calls.
-use std::path::Path;
-#[cfg(feature = "rego")]
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::sync::OnceLock;
-#[cfg(any(feature = "yaml", feature = "rego"))]
use anyhow::Context;
use anyhow::{bail, Result};
use serde_json::Value;
+use sha2::{Digest, Sha256};
pub const POLICY_FILE_ENV: &str = "CUA_DRIVER_POLICY_FILE";
+pub const MANAGED_POLICY_FILE_ENV: &str = "CUA_DRIVER_MANAGED_POLICY_FILE";
#[cfg(feature = "rego")]
const REGO_ALLOW_RULE: &str = "data.cua.policy.allow";
@@ -32,11 +31,17 @@ pub enum PolicyEngine {
}
impl PolicyEngine {
- /// Load a policy file or Rego policy directory. A missing path disables
- /// enforcement to preserve the driver's behavior when no policy is present.
+ /// Load an explicitly configured policy file or Rego policy directory.
+ ///
+ /// Callers represent an *unset* policy as `None` before invoking this
+ /// function. Once a path is supplied, a missing path is a configuration
+ /// error rather than an implicit request to disable enforcement.
pub fn load(path: &Path) -> Result<Option<Self>> {
if !path.exists() {
- return Ok(None);
+ bail!(
+ "configured permission policy path does not exist: {}",
+ path.display()
+ );
}
if path.is_dir() {
@@ -110,32 +115,190 @@ fn canonical_tool_name(tool: &str) -> &str {
}
}
-static CONFIGURED_POLICY: OnceLock<Result<Option<PolicyEngine>, String>> = OnceLock::new();
+#[derive(Debug, Clone)]
+struct ConfiguredPolicyLayer {
+ engine: PolicyEngine,
+ sha256: String,
+}
+
+static CONFIGURED_POLICY: OnceLock<Result<Option<ConfiguredPolicyLayer>, String>> = OnceLock::new();
+static CONFIGURED_MANAGED_POLICY: OnceLock<Result<Option<ConfiguredPolicyLayer>, String>> =
+ OnceLock::new();
+
+fn policy_files(path: &Path) -> Result<Vec<PathBuf>> {
+ if path.is_file() {
+ return Ok(vec![path.to_path_buf()]);
+ }
+ let mut files = Vec::new();
+ for entry in std::fs::read_dir(path)
+ .with_context(|| format!("failed to read policy directory {}", path.display()))?
+ {
+ let entry = entry.with_context(|| {
+ format!(
+ "failed to read an entry in policy directory {}",
+ path.display()
+ )
+ })?;
+ let entry_path = entry.path();
+ if entry_path.is_file()
+ && entry_path
+ .extension()
+ .and_then(|extension| extension.to_str())
+ .is_some_and(|extension| extension.eq_ignore_ascii_case("rego"))
+ {
+ files.push(entry_path);
+ }
+ }
+ files.sort();
+ Ok(files)
+}
+
+fn policy_sha256(path: &Path) -> Result<String> {
+ let files = policy_files(path)?;
+ let mut digest = Sha256::new();
+ digest.update(b"cua-driver-policy-v1\0");
+ for file in files {
+ let name = file
+ .file_name()
+ .and_then(|value| value.to_str())
+ .unwrap_or("policy");
+ let bytes = std::fs::read(&file)
+ .with_context(|| format!("failed to hash policy {}", file.display()))?;
+ digest.update((name.len() as u64).to_be_bytes());
+ digest.update(name.as_bytes());
+ digest.update((bytes.len() as u64).to_be_bytes());
+ digest.update(bytes);
+ }
+ Ok(format!("{:x}", digest.finalize()))
+}
+
+fn load_configured_layer(env_name: &str) -> Result<Option<ConfiguredPolicyLayer>, String> {
+ let Some(path_os) = std::env::var_os(env_name) else {
+ return Ok(None);
+ };
+ let path = Path::new(&path_os);
+ if !path.exists() {
+ return Err(format!(
+ "configured permission policy path does not exist: {}",
+ path.display()
+ ));
+ }
+ let hash_before_load = policy_sha256(path).map_err(|error| error.to_string())?;
+ let engine = PolicyEngine::load(path).map_err(|error| error.to_string())?;
+ let Some(engine) = engine else {
+ return Ok(None);
+ };
+ let sha256 = policy_sha256(path).map_err(|error| error.to_string())?;
+ if hash_before_load != sha256 {
+ return Err(format!(
+ "configured permission policy changed while it was being loaded: {}",
+ path.display()
+ ));
+ }
+ Ok(Some(ConfiguredPolicyLayer { engine, sha256 }))
+}
/// Return the process-wide policy configured through [`POLICY_FILE_ENV`].
/// The file is loaded once so stdio and HTTP requests use the same immutable
/// policy snapshot for the lifetime of the driver process.
pub fn configured_policy() -> Result<Option<&'static PolicyEngine>, String> {
- match CONFIGURED_POLICY.get_or_init(|| {
- let Some(path_os) = std::env::var_os(POLICY_FILE_ENV) else {
- return Ok(None);
- };
- let path = Path::new(&path_os);
- if !path.exists() {
- tracing::warn!(
- path = %path.display(),
- "{POLICY_FILE_ENV} is set but the path does not exist; \
- policy enforcement is disabled"
- );
- return Ok(None);
- }
- PolicyEngine::load(path).map_err(|error| error.to_string())
- }) {
- Ok(policy) => Ok(policy.as_ref()),
+ match CONFIGURED_POLICY.get_or_init(|| load_configured_layer(POLICY_FILE_ENV)) {
+ Ok(policy) => Ok(policy.as_ref().map(|layer| &layer.engine)),
+ Err(error) => Err(error.clone()),
+ }
+}
+
+/// Return the immutable administrator-owned ceiling. A user policy is always
+/// intersected with this layer and can never widen it.
+pub fn configured_managed_policy() -> Result<Option<&'static PolicyEngine>, String> {
+ match CONFIGURED_MANAGED_POLICY.get_or_init(|| load_configured_layer(MANAGED_POLICY_FILE_ENV)) {
+ Ok(policy) => Ok(policy.as_ref().map(|layer| &layer.engine)),
+ Err(error) => Err(error.clone()),
+ }
+}
+
+fn layer_sha256(
+ layer: &'static OnceLock<Result<Option<ConfiguredPolicyLayer>, String>>,
+ env_name: &str,
+) -> Result<Option<String>, String> {
+ match layer.get_or_init(|| load_configured_layer(env_name)) {
+ Ok(policy) => Ok(policy.as_ref().map(|configured| configured.sha256.clone())),
Err(error) => Err(error.clone()),
}
}
+pub fn user_policy_sha256() -> Result<Option<String>, String> {
+ layer_sha256(&CONFIGURED_POLICY, POLICY_FILE_ENV)
+}
+
+pub fn managed_policy_sha256() -> Result<Option<String>, String> {
+ layer_sha256(&CONFIGURED_MANAGED_POLICY, MANAGED_POLICY_FILE_ENV)
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum AuthorizationError {
+ #[error("Permission denied: {0}")]
+ Denied(String),
+ #[error("Policy evaluation error: {0}")]
+ Evaluation(String),
+ #[error("Policy loading error: {0}")]
+ Loading(String),
+}
+
+fn authorize_policy_layers<'a>(
+ tool: &str,
+ args: &Value,
+ layers: impl IntoIterator<Item = (&'a str, &'a PolicyEngine)>,
+) -> Result<(), AuthorizationError> {
+ for (name, policy) in layers {
+ match policy.evaluate(tool, args) {
+ PolicyDecision::Allow => {}
+ PolicyDecision::Deny(reason) => {
+ return Err(AuthorizationError::Denied(format!(
+ "{name} policy: {reason}"
+ )))
+ }
+ PolicyDecision::Error(message) => {
+ return Err(AuthorizationError::Evaluation(format!(
+ "{name} policy: {message}"
+ )))
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Canonical process-wide capability-policy decision for one tool call.
+///
+/// Every daemon dispatch path must call this function immediately before
+/// registry lookup/invocation. A proxy may also call it as an early denial,
+/// but the daemon remains authoritative.
+pub fn authorize_tool_call(tool: &str, args: &Value) -> Result<(), AuthorizationError> {
+ let managed = configured_managed_policy()
+ .map_err(|message| AuthorizationError::Loading(format!("managed policy: {message}")))?;
+ let user = configured_policy()
+ .map_err(|message| AuthorizationError::Loading(format!("user policy: {message}")))?;
+ let mut layers = Vec::with_capacity(2);
+ if let Some(policy) = managed {
+ layers.push(("managed", policy));
+ }
+ if let Some(policy) = user {
+ layers.push(("user", policy));
+ }
+ authorize_policy_layers(tool, args, layers)
+}
+
+/// Eagerly validate the immutable process policy before any action endpoint is
+/// exposed. This prevents a configured typo from producing a listening daemon
+/// that only discovers the error after clients begin issuing calls.
+pub fn validate_configured_policy() -> Result<(), AuthorizationError> {
+ configured_managed_policy()
+ .map_err(|message| AuthorizationError::Loading(format!("managed policy: {message}")))?;
+ configured_policy()
+ .map_err(|message| AuthorizationError::Loading(format!("user policy: {message}")))?;
+ Ok(())
+}
+
#[cfg(feature = "yaml")]
#[derive(Debug, Clone)]
pub struct YamlPolicy {
@@ -537,6 +700,7 @@ impl RegoPolicy {
#[cfg(test)]
mod tests {
use super::*;
+ #[cfg(any(feature = "yaml", feature = "rego"))]
use std::fs;
use tempfile::tempdir;
@@ -576,6 +740,52 @@ deny:
));
}
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn managed_and_user_layers_are_intersected() {
+ let managed = yaml_policy("allow:\n tools: [click, wait]\n");
+ let user = yaml_policy("allow:\n tools: [wait]\n");
+
+ authorize_policy_layers(
+ "wait",
+ &serde_json::json!({}),
+ [("managed", &managed), ("user", &user)],
+ )
+ .unwrap();
+
+ let denied = authorize_policy_layers(
+ "click",
+ &serde_json::json!({"x": 1, "y": 2}),
+ [("managed", &managed), ("user", &user)],
+ )
+ .expect_err("user layer must be able to narrow managed allow");
+ assert!(denied.to_string().contains("user policy"));
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn policy_hash_is_content_bound_and_stable() {
+ let dir = tempdir().unwrap();
+ let first = dir.path().join("first.yaml");
+ let second = dir.path().join("second.yaml");
+ fs::write(&first, "allow:\n tools: [wait]\n").unwrap();
+ fs::write(&second, "allow:\n tools: [wait]\n").unwrap();
+ assert_eq!(
+ policy_sha256(&first).unwrap(),
+ policy_sha256(&first).unwrap()
+ );
+ assert_ne!(
+ policy_sha256(&first).unwrap(),
+ policy_sha256(&second).unwrap(),
+ "file identity is included so separately managed sources have distinct provenance"
+ );
+ fs::write(&first, "allow:\n tools: [click]\n").unwrap();
+ assert_ne!(
+ policy_sha256(&first).unwrap(),
+ policy_sha256(&second).unwrap()
+ );
+ }
+
#[cfg(feature = "yaml")]
#[test]
fn yaml_enforces_numeric_string_and_allowed_constraints() {
@@ -761,9 +971,12 @@ allow if {
}
#[test]
- fn missing_policy_file_disables_enforcement() {
+ fn explicitly_configured_missing_policy_fails_closed() {
let dir = tempdir().unwrap();
let missing = dir.path().join("missing.yaml");
- assert!(PolicyEngine::load(&missing).unwrap().is_none());
+ let error = PolicyEngine::load(&missing).unwrap_err();
+ assert!(error
+ .to_string()
+ .contains("configured permission policy path does not exist"));
}
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
index c1a4a9de0e..a44a4f74b8 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
@@ -4,7 +4,7 @@ use std::sync::{Arc, OnceLock};
use std::time::Instant;
use tracing::warn;
-use crate::policy::{configured_policy, PolicyDecision};
+use crate::authorization::authorize_tool_call;
use crate::protocol::{initialize_result, InitializeMetadata, Request, Response, ResponseBody};
use crate::tool::ToolRegistry;
@@ -148,6 +148,7 @@ pub enum ToolRefusalCode {
BrowserReconnectExhausted,
BrowserInputIncomplete,
BrowserActionUnavailable,
+ BrowserOriginOutsideScope,
Other,
}
@@ -170,6 +171,7 @@ impl ToolRefusalCode {
Self::BrowserReconnectExhausted => "browser_reconnect_exhausted",
Self::BrowserInputIncomplete => "browser_input_incomplete",
Self::BrowserActionUnavailable => "browser_action_unavailable",
+ Self::BrowserOriginOutsideScope => "browser_origin_outside_scope",
Self::Other => "other",
}
}
@@ -195,6 +197,7 @@ impl ToolRefusalCode {
Some("browser_reconnect_exhausted") => Self::BrowserReconnectExhausted,
Some("browser_input_incomplete") => Self::BrowserInputIncomplete,
Some("browser_action_unavailable") => Self::BrowserActionUnavailable,
+ Some("browser_origin_outside_scope") => Self::BrowserOriginOutsideScope,
Some(_) | None => Self::Other,
}
}
@@ -219,6 +222,7 @@ impl From<crate::browser::refusal::BrowserRefusalCode> for ToolRefusalCode {
BrowserRefusalCode::BrowserReconnectExhausted => Self::BrowserReconnectExhausted,
BrowserRefusalCode::BrowserInputIncomplete => Self::BrowserInputIncomplete,
BrowserRefusalCode::BrowserActionUnavailable => Self::BrowserActionUnavailable,
+ BrowserRefusalCode::BrowserOriginOutsideScope => Self::BrowserOriginOutsideScope,
}
}
}
@@ -793,32 +797,8 @@ pub async fn handle_request(
Err(e) => Response::error(id, -32602, format!("Invalid params: {e}")),
Ok(mut call) => {
crate::tool_args::sanitize_reserved_args(&mut call.args);
- match configured_policy() {
- Ok(Some(policy)) => match policy.evaluate(&call.name, &call.args) {
- PolicyDecision::Allow => {}
- PolicyDecision::Deny(reason) => {
- return Response::error(
- id,
- -32603,
- format!("Permission denied: {reason}"),
- );
- }
- PolicyDecision::Error(message) => {
- return Response::error(
- id,
- -32603,
- format!("Policy evaluation error: {message}"),
- );
- }
- },
- Ok(None) => {}
- Err(message) => {
- return Response::error(
- id,
- -32603,
- format!("Policy loading error: {message}"),
- );
- }
+ if let Err(error) = authorize_tool_call(&call.name, &call.args) {
+ return Response::error(id, -32603, error.to_string());
}
let public_session = call
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
index 754dfa558e..59d5a5c1fa 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
@@ -311,6 +311,17 @@ pub fn fire_session_end(session_id: &str) -> bool {
true
}
+/// Revoke every currently tracked session. This is intentionally callable by
+/// a local operator control path without requiring an authorization grant:
+/// revocation can only remove authority, never create it.
+pub fn revoke_all_sessions() -> usize {
+ let sessions: Vec<String> = activity().lock().unwrap().keys().cloned().collect();
+ for session in &sessions {
+ end_session(session);
+ }
+ sessions.len()
+}
+
/// Whether `fire_session_end` has already run for this `session_id`. The
/// daemon-side authority for "this session is permanently gone"; the macOS
/// overlay keeps its own render-side tombstone keyed on the same id.
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
new file mode 100644
index 0000000000..7cc87a6a2d
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
@@ -0,0 +1,587 @@
+//! Immutable bounded-autonomy manifest loaded at trusted daemon startup.
+//!
+//! The agent may propose this file, but selecting and approving it is a
+//! launcher responsibility. The manifest only narrows the built-in,
+//! managed, and user policy layers; it cannot introduce unreviewed tools.
+
+use std::collections::HashSet;
+use std::path::Path;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+#[cfg(feature = "yaml")]
+use serde::Deserialize;
+#[cfg(feature = "yaml")]
+use sha2::{Digest, Sha256};
+
+pub const SESSION_POLICY_FILE_ENV: &str = "CUA_DRIVER_SESSION_POLICY_FILE";
+pub const SESSION_POLICY_APPROVED_ENV: &str = "CUA_DRIVER_SESSION_POLICY_APPROVED";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ManifestDecision {
+ Allow,
+ Deny,
+ Ask,
+ Undeclared,
+}
+
+#[derive(Debug, Clone)]
+pub struct SessionManifest {
+ sha256: String,
+ expires_unix_ms: u128,
+ idle_timeout: Duration,
+ allow: HashSet<String>,
+ deny: HashSet<String>,
+ ask: HashSet<String>,
+ existing_profiles: HashSet<(i64, u64)>,
+ browser_origins: HashSet<String>,
+ last_authorized_dispatch: Arc<Mutex<Instant>>,
+ idle_expired: Arc<AtomicBool>,
+}
+
+impl SessionManifest {
+ pub fn sha256(&self) -> &str {
+ &self.sha256
+ }
+
+ pub fn expires_unix_ms(&self) -> u128 {
+ self.expires_unix_ms
+ }
+
+ pub fn idle_timeout(&self) -> Duration {
+ self.idle_timeout
+ }
+
+ pub fn counts(&self) -> (usize, usize, usize) {
+ (self.allow.len(), self.deny.len(), self.ask.len())
+ }
+
+ pub fn decision(&self, tool: &str) -> ManifestDecision {
+ let tool = canonical_tool_name(tool);
+ if self.deny.contains(tool) {
+ ManifestDecision::Deny
+ } else if self.ask.contains(tool) {
+ ManifestDecision::Ask
+ } else if self.allow.contains(tool) {
+ ManifestDecision::Allow
+ } else {
+ ManifestDecision::Undeclared
+ }
+ }
+
+ /// Enforce resource fields for adapters that have completed migration.
+ /// An allow-list entry for a tool never implies access to an undeclared
+ /// browser process, native window, or origin.
+ pub fn authorize_call(&self, tool: &str, args: &serde_json::Value) -> Result<(), String> {
+ match tool {
+ "browser_prepare"
+ if args
+ .pointer("/strategy/kind")
+ .and_then(serde_json::Value::as_str)
+ == Some("existing_profile") =>
+ {
+ let pid = args
+ .get("pid")
+ .and_then(serde_json::Value::as_i64)
+ .ok_or_else(|| "bounded existing-profile access requires pid".to_owned())?;
+ let window_id = args
+ .get("window_id")
+ .and_then(serde_json::Value::as_u64)
+ .ok_or_else(|| {
+ "bounded existing-profile access requires window_id".to_owned()
+ })?;
+ if !self.existing_profiles.contains(&(pid, window_id)) {
+ return Err(format!(
+ "browser pid {pid} window {window_id} is outside the bounded session policy"
+ ));
+ }
+ }
+ "browser_navigate" => {
+ let url = args
+ .get("url")
+ .and_then(serde_json::Value::as_str)
+ .ok_or_else(|| "bounded browser navigation requires url".to_owned())?;
+ self.authorize_browser_url(url)?;
+ }
+ _ => {}
+ }
+ Ok(())
+ }
+
+ /// Validate a live top-level document after redirects and before input.
+ pub fn authorize_browser_url(&self, raw: &str) -> Result<(), String> {
+ let origin = canonical_origin(raw)?;
+ if self.browser_origins.contains(&origin) {
+ Ok(())
+ } else {
+ Err(format!(
+ "browser origin '{origin}' is outside the bounded session policy"
+ ))
+ }
+ }
+
+ pub fn is_expired(&self) -> bool {
+ self.expires_unix_ms < now_unix_ms()
+ }
+
+ pub fn is_idle_expired(&self) -> bool {
+ self.idle_expired.load(Ordering::Acquire)
+ }
+
+ /// Refresh the bounded-mode idle lease only after a call passed every
+ /// manifest decision and resource check. Once the idle lease expires it is
+ /// terminal for this daemon instance; a tool call cannot revive it.
+ pub fn authorize_dispatch(&self) -> Result<(), String> {
+ if self.is_idle_expired() {
+ return Err("bounded session policy idle timeout exceeded".to_owned());
+ }
+ let now = Instant::now();
+ let mut last = self.last_authorized_dispatch.lock().unwrap();
+ if now.duration_since(*last) > self.idle_timeout {
+ self.idle_expired.store(true, Ordering::Release);
+ return Err("bounded session policy idle timeout exceeded".to_owned());
+ }
+ *last = now;
+ Ok(())
+ }
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawManifest {
+ version: u32,
+ mode: String,
+ expires_after: String,
+ idle_timeout: String,
+ #[serde(default)]
+ resources: RawResources,
+ #[serde(default)]
+ allow: RawToolSet,
+ #[serde(default)]
+ deny: RawToolSet,
+ #[serde(default)]
+ ask: RawToolSet,
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, Default, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawResources {
+ #[serde(default)]
+ browser: RawBrowserResources,
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, Default, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawBrowserResources {
+ #[serde(default)]
+ existing_profiles: Vec<RawExistingProfile>,
+ #[serde(default)]
+ origins: Vec<String>,
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawExistingProfile {
+ pid: i64,
+ window_id: u64,
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, Default, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawToolSet {
+ #[serde(default)]
+ tools: Vec<String>,
+}
+
+static CONFIGURED_MANIFEST: OnceLock<Result<Option<SessionManifest>, String>> = OnceLock::new();
+
+pub fn configured_session_manifest() -> Result<Option<&'static SessionManifest>, String> {
+ match CONFIGURED_MANIFEST.get_or_init(load_configured_manifest) {
+ Ok(manifest) => Ok(manifest.as_ref()),
+ Err(error) => Err(error.clone()),
+ }
+}
+
+fn load_configured_manifest() -> Result<Option<SessionManifest>, String> {
+ let Some(path) = std::env::var_os(SESSION_POLICY_FILE_ENV) else {
+ return Ok(None);
+ };
+ load_manifest(Path::new(&path)).map(Some)
+}
+
+pub(crate) fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
+ let bytes = std::fs::read(path)
+ .map_err(|error| format!("failed to read session policy {}: {error}", path.display()))?;
+ if bytes.is_empty() {
+ return Err(format!("session policy {} is empty", path.display()));
+ }
+ #[cfg(feature = "yaml")]
+ let raw: RawManifest = serde_yaml_ng::from_slice(&bytes)
+ .map_err(|error| format!("failed to parse session policy {}: {error}", path.display()))?;
+ #[cfg(not(feature = "yaml"))]
+ return Err("session policy support requires the yaml feature".to_owned());
+
+ #[cfg(feature = "yaml")]
+ {
+ if raw.version != 1 {
+ return Err(format!(
+ "unsupported session policy version {}; expected 1",
+ raw.version
+ ));
+ }
+ if !matches!(raw.mode.as_str(), "bounded" | "autonomous") {
+ return Err("session policy mode must be bounded".to_owned());
+ }
+ let expires_after = parse_duration(&raw.expires_after)?;
+ let idle_timeout = parse_duration(&raw.idle_timeout)?;
+ if expires_after.is_zero() || expires_after > Duration::from_secs(24 * 60 * 60) {
+ return Err("expires_after must be greater than zero and no more than 24h".to_owned());
+ }
+ if idle_timeout.is_zero() || idle_timeout > expires_after {
+ return Err(
+ "idle_timeout must be greater than zero and no more than expires_after".to_owned(),
+ );
+ }
+ let allow = validate_tools("allow", raw.allow.tools)?;
+ let deny = validate_tools("deny", raw.deny.tools)?;
+ let ask = validate_tools("ask", raw.ask.tools)?;
+ if allow.is_empty() {
+ return Err("session policy allow.tools must not be empty".to_owned());
+ }
+ for tool in &allow {
+ if deny.contains(tool) || ask.contains(tool) {
+ return Err(format!(
+ "session policy tool '{tool}' appears in more than one decision set"
+ ));
+ }
+ }
+ for tool in &deny {
+ if ask.contains(tool) {
+ return Err(format!(
+ "session policy tool '{tool}' appears in more than one decision set"
+ ));
+ }
+ }
+ let mut existing_profiles = HashSet::new();
+ for profile in raw.resources.browser.existing_profiles {
+ if profile.pid <= 0 || profile.window_id == 0 {
+ return Err(
+ "browser existing_profiles entries require positive pid and window_id"
+ .to_owned(),
+ );
+ }
+ if !existing_profiles.insert((profile.pid, profile.window_id)) {
+ return Err(format!(
+ "browser existing_profiles repeats pid {} window {}",
+ profile.pid, profile.window_id
+ ));
+ }
+ }
+ let mut browser_origins = HashSet::new();
+ for raw_origin in raw.resources.browser.origins {
+ let origin = canonical_origin(&raw_origin)?;
+ if origin != raw_origin.trim().trim_end_matches('/') {
+ return Err(format!(
+ "browser origin '{raw_origin}' must be an exact canonical origin without a path"
+ ));
+ }
+ if !browser_origins.insert(origin.clone()) {
+ return Err(format!("browser origins repeats '{origin}'"));
+ }
+ }
+ if !browser_origins.is_empty() {
+ const ORIGIN_BYPASS_TOOLS: &[&str] = &[
+ "page",
+ "click",
+ "double_click",
+ "right_click",
+ "drag",
+ "scroll",
+ "type_text",
+ "press_key",
+ "hotkey",
+ "set_value",
+ "mouse_button_down",
+ "mouse_button_up",
+ "mouse_drag",
+ "parallel_mouse_drag",
+ "get_accessibility_tree",
+ "get_window_state",
+ "get_desktop_state",
+ ];
+ if let Some(tool) = ORIGIN_BYPASS_TOOLS
+ .iter()
+ .find(|tool| allow.contains(**tool))
+ {
+ return Err(format!(
+ "origin-scoped bounded manifests cannot allow '{tool}' because it bypasses the typed browser origin adapter"
+ ));
+ }
+ }
+
+ let mut digest = Sha256::new();
+ digest.update(b"cua-driver-session-policy-v1\0");
+ digest.update(&bytes);
+ Ok(SessionManifest {
+ sha256: format!("{:x}", digest.finalize()),
+ expires_unix_ms: now_unix_ms() + expires_after.as_millis(),
+ idle_timeout,
+ allow,
+ deny,
+ ask,
+ existing_profiles,
+ browser_origins,
+ last_authorized_dispatch: Arc::new(Mutex::new(Instant::now())),
+ idle_expired: Arc::new(AtomicBool::new(false)),
+ })
+ }
+}
+
+#[cfg(feature = "yaml")]
+fn validate_tools(section: &str, tools: Vec<String>) -> Result<HashSet<String>, String> {
+ let mut validated = HashSet::new();
+ for tool in tools {
+ let canonical = canonical_tool_name(tool.trim()).to_owned();
+ if canonical.is_empty()
+ || crate::authorization::advertised_risk_for(&canonical).class
+ == crate::authorization::RiskClass::Unclassified
+ {
+ return Err(format!(
+ "session policy {section}.tools contains unknown or unreviewed tool '{tool}'"
+ ));
+ }
+ if !validated.insert(canonical.clone()) {
+ return Err(format!(
+ "session policy {section}.tools repeats '{canonical}'"
+ ));
+ }
+ }
+ Ok(validated)
+}
+
+fn canonical_tool_name(tool: &str) -> &str {
+ match tool {
+ "type_text_chars" => "type_text",
+ other => other,
+ }
+}
+
+fn canonical_origin(raw: &str) -> Result<String, String> {
+ let value = raw.trim();
+ if value == "about:blank" {
+ return Ok(value.to_owned());
+ }
+ let parsed =
+ url::Url::parse(value).map_err(|_| format!("invalid browser URL or origin '{raw}'"))?;
+ if !matches!(parsed.scheme(), "http" | "https") {
+ return Err(format!(
+ "browser URL or origin '{raw}' must use http or https"
+ ));
+ }
+ let host = parsed
+ .host_str()
+ .ok_or_else(|| format!("browser URL or origin '{raw}' has no host"))?;
+ let mut origin = format!("{}://{}", parsed.scheme(), host);
+ if let Some(port) = parsed.port() {
+ origin.push(':');
+ origin.push_str(&port.to_string());
+ }
+ Ok(origin)
+}
+
+#[cfg(any(feature = "yaml", test))]
+fn parse_duration(raw: &str) -> Result<Duration, String> {
+ let value = raw.trim();
+ if value.len() < 2 {
+ return Err(format!(
+ "invalid duration '{raw}'; use forms such as 30m or 8h"
+ ));
+ }
+ let (number, unit) = value.split_at(value.len() - 1);
+ let number = number
+ .parse::<u64>()
+ .map_err(|_| format!("invalid duration '{raw}'; use forms such as 30m or 8h"))?;
+ let seconds = match unit {
+ "s" => number,
+ "m" => number.saturating_mul(60),
+ "h" => number.saturating_mul(60 * 60),
+ _ => {
+ return Err(format!(
+ "invalid duration unit in '{raw}'; expected s, m, or h"
+ ))
+ }
+ };
+ Ok(Duration::from_secs(seconds))
+}
+
+fn now_unix_ms() -> u128 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[cfg(feature = "yaml")]
+ fn manifest(source: &str) -> Result<SessionManifest, String> {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("manifest.yaml");
+ std::fs::write(&path, source).unwrap();
+ load_manifest(&path)
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn manifest_is_deny_by_default_and_preserves_ask() {
+ let loaded = manifest(
+ r#"
+version: 1
+mode: bounded
+expires_after: 8h
+idle_timeout: 30m
+resources: {}
+allow:
+ tools: [start_session, get_browser_state]
+deny:
+ tools: [page]
+ask:
+ tools: [browser_download]
+"#,
+ )
+ .unwrap();
+ assert_eq!(loaded.decision("start_session"), ManifestDecision::Allow);
+ assert_eq!(loaded.decision("page"), ManifestDecision::Deny);
+ assert_eq!(loaded.decision("browser_download"), ManifestDecision::Ask);
+ assert_eq!(loaded.decision("click"), ManifestDecision::Undeclared);
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn autonomous_manifest_mode_remains_a_compatibility_alias() {
+ let loaded = manifest(
+ "version: 1\nmode: autonomous\nexpires_after: 1h\nidle_timeout: 5m\nallow:\n tools: [get_config]\n",
+ )
+ .unwrap();
+ assert_eq!(loaded.decision("get_config"), ManifestDecision::Allow);
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn browser_resources_bind_existing_profile_and_origins() {
+ let manifest = manifest(
+ r#"
+version: 1
+mode: bounded
+expires_after: 8h
+idle_timeout: 30m
+resources:
+ browser:
+ existing_profiles:
+ - pid: 42
+ window_id: 7
+ origins:
+ - https://app.example.com
+allow:
+ tools: [browser_prepare, browser_navigate]
+"#,
+ )
+ .unwrap();
+
+ manifest
+ .authorize_call(
+ "browser_prepare",
+ &serde_json::json!({
+ "pid": 42,
+ "window_id": 7,
+ "strategy": {"kind": "existing_profile"}
+ }),
+ )
+ .unwrap();
+ assert!(manifest
+ .authorize_call(
+ "browser_prepare",
+ &serde_json::json!({
+ "pid": 42,
+ "window_id": 8,
+ "strategy": {"kind": "existing_profile"}
+ }),
+ )
+ .is_err());
+ manifest
+ .authorize_browser_url("https://app.example.com/work?q=1")
+ .unwrap();
+ assert!(manifest
+ .authorize_browser_url("https://evil.example/redirect")
+ .is_err());
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn idle_timeout_is_terminal_and_origin_bypass_tools_are_rejected() {
+ let loaded = manifest(
+ r#"
+version: 1
+mode: bounded
+expires_after: 1h
+idle_timeout: 1s
+resources: {}
+allow:
+ tools: [get_config]
+"#,
+ )
+ .unwrap();
+ *loaded.last_authorized_dispatch.lock().unwrap() =
+ Instant::now().checked_sub(Duration::from_secs(2)).unwrap();
+ assert!(loaded.authorize_dispatch().is_err());
+ assert!(loaded.is_idle_expired());
+ assert!(loaded.authorize_dispatch().is_err());
+
+ assert!(manifest(
+ r#"
+version: 1
+mode: bounded
+expires_after: 1h
+idle_timeout: 10m
+resources:
+ browser:
+ origins: [https://app.example.com]
+allow:
+ tools: [browser_navigate, page]
+"#,
+ )
+ .unwrap_err()
+ .contains("bypasses the typed browser origin adapter"));
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn unknown_and_overlapping_tools_are_rejected() {
+ let unknown = manifest(
+ "version: 1\nmode: bounded\nexpires_after: 1h\nidle_timeout: 5m\nallow:\n tools: [future_tool]\n",
+ )
+ .unwrap_err();
+ assert!(unknown.contains("unknown or unreviewed"));
+
+ let overlap = manifest(
+ "version: 1\nmode: bounded\nexpires_after: 1h\nidle_timeout: 5m\nallow:\n tools: [click]\ndeny:\n tools: [click]\n",
+ )
+ .unwrap_err();
+ assert!(overlap.contains("more than one decision set"));
+ }
+
+ #[test]
+ fn duration_parser_is_bounded_and_explicit() {
+ assert_eq!(parse_duration("30m").unwrap(), Duration::from_secs(1800));
+ assert!(parse_duration("30").is_err());
+ assert!(parse_duration("1d").is_err());
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index 9b21b31ad0..d6cd558de6 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -51,6 +51,7 @@ impl ToolDef {
// claim is a one-file change, and sibling PRs touching
// individual tool files don't conflict with this surface.
let caps = default_capabilities_for(&self.name);
+ let risk = crate::authorization::risk_metadata_json(&self.name);
serde_json::json!({
"name": self.name,
"description": self.description,
@@ -62,6 +63,7 @@ impl ToolDef {
"openWorldHint": self.open_world,
},
"capabilities": caps,
+ "risk": risk,
})
}
}
@@ -854,6 +856,18 @@ mod capability_tests {
}
}
+ #[test]
+ fn every_known_tool_has_reviewed_risk_metadata() {
+ for name in TOOLS_REQUIRING_CAPABILITIES {
+ let risk = crate::authorization::advertised_risk_for(name);
+ assert_ne!(
+ risk.class,
+ crate::authorization::RiskClass::Unclassified,
+ "tool {name:?} must have a reviewed risk classification"
+ );
+ }
+ }
+
#[test]
fn every_claimed_capability_is_in_the_canonical_vocabulary() {
let vocab: std::collections::HashSet<&str> = CANONICAL_VOCABULARY.iter().copied().collect();
@@ -957,6 +971,15 @@ mod capability_tests {
);
}
+ #[test]
+ fn to_list_entry_includes_versioned_risk_metadata() {
+ let entry = dummy_def("browser_prepare").to_list_entry();
+ assert_eq!(entry["risk"]["class"], "r2");
+ assert_eq!(entry["risk"]["enforcement"], "metadata_only");
+ assert_eq!(entry["risk"]["operation_sensitive"], true);
+ assert_eq!(entry["risk"]["version"], "1");
+ }
+
#[test]
fn to_list_entry_includes_empty_capabilities_array_for_unknown_tool() {
// Even when no capabilities are claimed, the field is still
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs
index 4e64aec584..57c6768a9c 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs
@@ -26,6 +26,13 @@ pub struct CliDriver {
impl CliDriver {
pub fn new() -> Self {
+ Self::with_daemon_env(&[])
+ }
+
+ /// Start a test-owned daemon with explicit immutable startup settings.
+ /// This is used for permission-mode and policy tests; tool-call child
+ /// processes remain ordinary clients and do not receive these values.
+ pub fn with_daemon_env(env: &[(&str, &str)]) -> Self {
let bin = driver_binary();
if !bin.exists() {
return CliDriver {
@@ -35,7 +42,7 @@ impl CliDriver {
};
}
let mut reaper = ChildReaper::new();
- let daemon = TestDaemon::spawn(&bin, &mut reaper, &[]);
+ let daemon = TestDaemon::spawn(&bin, &mut reaper, env);
CliDriver {
bin,
_reaper: Some(reaper),
@@ -47,6 +54,10 @@ impl CliDriver {
pub fn available(&self) -> bool {
self.bin.exists() && self.daemon.is_some()
}
+
+ pub fn daemon_socket(&self) -> Option<&str> {
+ self.daemon.as_ref().map(|daemon| daemon.socket.as_str())
+ }
}
impl Default for CliDriver {
@@ -93,10 +104,16 @@ impl Driver for CliDriver {
};
let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
+ let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
// The CLI prints structuredContent (pretty JSON) or plain text — parse
// when it's JSON, else keep it as text.
let structured = serde_json::from_str::<Value>(&stdout).unwrap_or(Value::Null);
let is_error = !out.status.success();
- ToolResponse::new(stdout, structured, is_error, Value::Null)
+ let text = if stdout.is_empty() && is_error {
+ stderr
+ } else {
+ stdout
+ };
+ ToolResponse::new(text, structured, is_error, Value::Null)
}
}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index 07feeed248..3abd7c11f1 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -44,6 +44,19 @@ pub enum Command {
},
Serve {
socket: Option<String>,
+ /// Immutable agent-authorization mode selected at trusted daemon
+ /// startup. This is distinct from the macOS OS-permissions gate.
+ permission_mode: Option<String>,
+ /// Deliberate unrestricted-mode selector and risk acknowledgement.
+ dangerously_bypass_approvals: bool,
+ /// Temporary trusted-launcher compatibility path for the forgeable
+ /// file-backed existing-profile approval artifact.
+ allow_legacy_existing_profile_approval: bool,
+ /// Immutable bounded-autonomy manifest selected by the trusted
+ /// launcher. Valid only in bounded mode.
+ session_policy: Option<String>,
+ /// Deliberate launch-time confirmation that the manifest was reviewed.
+ approve_session_policy: bool,
/// True when `--no-permissions-gate` is on argv. The env-var
/// `CUA_DRIVER_RS_PERMISSIONS_GATE=0` short-circuits the gate too
/// (checked inside the gate itself), so the flag is only one of
@@ -58,6 +71,11 @@ pub enum Command {
Stop {
socket: Option<String>,
},
+ Revoke {
+ socket: Option<String>,
+ session: Option<String>,
+ all: bool,
+ },
Status {
socket: Option<String>,
},
@@ -178,6 +196,8 @@ const VALUE_FLAGS: &[&str] = &[
"--screenshot-out-file",
"--client",
"--socket",
+ "--permission-mode",
+ "--session-policy",
"--pid-file",
"--type",
"--host-bundle-id",
@@ -234,6 +254,7 @@ fn finite_command_name_from_args(args: &[String]) -> Option<&'static str> {
Some("manifest") => Some("manifest"),
Some("call") => Some("call"),
Some("stop") => Some("stop"),
+ Some("revoke") => Some("revoke"),
Some("status") => Some("status"),
Some("recording") => Some("recording"),
Some("dump-docs") => Some("dump_docs"),
@@ -396,7 +417,7 @@ pub fn parse_command() -> Command {
env!("CARGO_PKG_VERSION")
);
println!("Usage: cua-driver [SUBCOMMAND] [OPTIONS]");
- println!("Subcommands: mcp, list-tools, describe, call, serve, stop, status, config, telemetry, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, browser-approve, manifest");
+ println!("Subcommands: mcp, list-tools, describe, call, serve, stop, revoke, status, config, telemetry, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, browser-approve, manifest");
println!();
println!("permissions options (macOS):");
println!(" cua-driver permissions status Report Accessibility + Screen Recording status. Read-only (no prompt).");
@@ -443,6 +464,31 @@ pub fn parse_command() -> Command {
println!(" --window-id <window_id> --session <session>");
println!(" Approve attachment to one exact existing browser request.");
println!();
+ println!("agent authorization (serve only):");
+ println!(" --permission-mode <mode> standard (default), bounded, or unrestricted.");
+ println!(
+ " --dangerously-bypass-approvals Select unrestricted mode and acknowledge its risk."
+ );
+ println!(" The mode is fixed for the daemon lifetime and cannot");
+ println!(" be changed by a tool call.");
+ println!(" --allow-legacy-existing-profile-approval");
+ println!(" Temporary migration flag for the forgeable file-backed");
+ println!(" approval artifact; never treated as protected consent.");
+ println!(" This is separate from --no-permissions-gate, which only");
+ println!(
+ " controls the macOS OS-permission onboarding UI."
+ );
+ println!(
+ " --session-policy <path> Required in bounded mode; immutable tool manifest."
+ );
+ println!(" --approve-session-policy Required with --session-policy; the trusted launcher asserts");
+ println!(" that the human reviewed this exact manifest at startup.");
+ println!();
+ println!("authorization revocation:");
+ println!(" cua-driver revoke --session <id> Stop and revoke one session's grants.");
+ println!(" cua-driver revoke --all Stop and revoke every live session.");
+ println!(" Revocation is deny-only and never needs a token.");
+ println!();
println!("mcp options:");
println!(" --embedded Connect to a daemon spawned by the host app (also:");
println!(" CUA_DRIVER_EMBEDDED=1). Embedded hosts must start");
@@ -604,11 +650,32 @@ pub fn parse_command() -> Command {
Some("mcp-config") => Command::McpConfig { client: mcp_client },
Some("serve") => Command::Serve {
socket,
+ permission_mode: flag_value(&args, "--permission-mode"),
+ dangerously_bypass_approvals: args
+ .iter()
+ .any(|a| a == "--dangerously-bypass-approvals"),
+ allow_legacy_existing_profile_approval: args
+ .iter()
+ .any(|a| a == "--allow-legacy-existing-profile-approval"),
+ session_policy: flag_value(&args, "--session-policy"),
+ approve_session_policy: args.iter().any(|a| a == "--approve-session-policy"),
// Bare flag — present anywhere on argv counts as "skip the gate".
no_permissions_gate: args.iter().any(|a| a == "--no-permissions-gate"),
claude_code_compat,
},
Some("stop") => Command::Stop { socket },
+ Some("revoke") => {
+ let all = args.iter().any(|a| a == "--all");
+ if all == approval_session.is_some() {
+ eprintln!("revoke requires exactly one of --session <id> or --all");
+ process::exit(64);
+ }
+ Command::Revoke {
+ socket,
+ session: approval_session,
+ all,
+ }
+ }
Some("status") => Command::Status { socket },
Some("recording") => {
let subcommand = pos.next().unwrap_or("status").to_string();
@@ -1301,6 +1368,11 @@ pub fn build_manifest() -> serde_json::Value {
"description": "Run the long-lived daemon — backs the proxy/auto-relaunch path on macOS and the autostart Session 1+ daemon on Windows.",
"args": [
{ "name": "--socket", "type": "string", "description": "Override the listen socket path." },
+ { "name": "--permission-mode", "type": "string", "description": "Immutable daemon authorization mode: standard, bounded, or unrestricted." },
+ { "name": "--dangerously-bypass-approvals", "type": "flag", "description": "Select unrestricted mode and acknowledge its risk." },
+ { "name": "--allow-legacy-existing-profile-approval", "type": "flag", "description": "Temporary migration flag for the unprotected file-backed existing-profile artifact." },
+ { "name": "--session-policy", "type": "string", "description": "Immutable tool manifest required in bounded mode." },
+ { "name": "--approve-session-policy", "type": "flag", "description": "Trusted-launcher confirmation that the exact bounded manifest was reviewed." },
{ "name": "--no-permissions-gate", "type": "flag", "description": "Skip the macOS TCC first-launch gate." },
{ "name": "--claude-code-computer-use-compat", "type": "flag", "description": "Forwarded by the MCP proxy when the client asked for the compat surface." },
{ "name": "--embedded", "type": "flag", "description": "Run embedded inside a host app: inherit the host's TCC grants, never prompt or relaunch. Also CUA_DRIVER_EMBEDDED=1." },
@@ -1309,6 +1381,13 @@ pub fn build_manifest() -> serde_json::Value {
{ "name": "stop",
"description": "Stop a running daemon by sending it a shutdown request.",
"args": [ { "name": "--socket", "type": "string", "description": "Override the daemon socket path." } ] },
+ { "name": "revoke",
+ "description": "Revoke one session or every live authorization scope without minting new authority.",
+ "args": [
+ { "name": "--session", "type": "string", "description": "Exact session id to stop and revoke." },
+ { "name": "--all", "type": "flag", "description": "Stop and revoke every live session." },
+ { "name": "--socket", "type": "string", "description": "Override the daemon socket path." }
+ ] },
{ "name": "status",
"description": "Report daemon status (running / not / unhealthy).",
"args": [ { "name": "--socket", "type": "string", "description": "Override the daemon socket path." } ] },
@@ -2476,9 +2555,14 @@ fn cli_docs_json() -> serde_json::Value {
"options": [
{"name":"socket","short_name":null,"help":"Override the daemon socket or named-pipe path.","type":"String","default_value":null,"is_optional":true},
{"name":"pid-file","short_name":null,"help":"Override the pid-file path on Unix targets.","type":"String","default_value":null,"is_optional":true},
+ {"name":"permission-mode","short_name":null,"help":"Immutable agent authorization mode: standard, bounded, or unrestricted.","type":"String","default_value":"standard","is_optional":true},
+ {"name":"session-policy","short_name":null,"help":"Immutable tool manifest required in bounded mode.","type":"String","default_value":null,"is_optional":true},
{"name":"host-bundle-id","short_name":null,"help":"Advisory host bundle id label echoed in check_permissions output (embedded mode).","type":"String","default_value":null,"is_optional":true}
],
"flags": [
+ {"name":"dangerously-bypass-approvals","short_name":null,"help":"Select unrestricted mode and acknowledge its risk.","default_value":false},
+ {"name":"allow-legacy-existing-profile-approval","short_name":null,"help":"Temporary migration flag for the unprotected file-backed existing-profile artifact.","default_value":false},
+ {"name":"approve-session-policy","short_name":null,"help":"Trusted-launcher confirmation that the exact bounded manifest was reviewed.","default_value":false},
{"name":"no-permissions-gate","short_name":null,"help":"Skip the macOS first-launch permissions gate.","default_value":false},
{"name":"embedded","short_name":null,"help":"Run embedded inside a host app: inherit the host's TCC grants, never prompt or relaunch. Also CUA_DRIVER_EMBEDDED=1.","default_value":false}
],
@@ -2493,6 +2577,20 @@ fn cli_docs_json() -> serde_json::Value {
"flags": no_flags,
"subcommands": no_subcommands
},
+ {
+ "name": "revoke",
+ "abstract": "Revoke one or all live authorization/session scopes.",
+ "discussion": "Revocation is deny-only and never accepts an approval token.",
+ "arguments": no_args,
+ "options": [
+ {"name":"session","short_name":null,"help":"Exact session id to stop and revoke.","type":"String","default_value":null,"is_optional":true},
+ {"name":"socket","short_name":null,"help":"Override the daemon socket or named-pipe path.","type":"String","default_value":null,"is_optional":true}
+ ],
+ "flags": [
+ {"name":"all","short_name":null,"help":"Stop and revoke every live session.","default_value":false}
+ ],
+ "subcommands": no_subcommands
+ },
{
"name": "status",
"abstract": "Report whether a Cua Driver daemon is running.",
@@ -3419,6 +3517,7 @@ mod tests {
"call",
"serve",
"stop",
+ "revoke",
"status",
"mcp-config",
"manifest",
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
index 8726556ae6..f3ab76caf5 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -1,3 +1,5 @@
+#![recursion_limit = "256"]
+
//! cua-driver-rs — cross-platform background computer-use automation daemon.
//!
//! Runs a daemon-backed MCP JSON-RPC 2.0 proxy over stdio. The platform
@@ -41,6 +43,59 @@ fn init_logging() {
telemetry::register_stdio_observer();
}
+fn configure_startup_permission_mode(
+ permission_mode: Option<&str>,
+ dangerously_bypass_approvals: bool,
+ allow_legacy_existing_profile_approval: bool,
+ session_policy: Option<&str>,
+ approve_session_policy: bool,
+) -> anyhow::Result<()> {
+ if let Some(mode) = permission_mode {
+ std::env::set_var(cua_driver_core::authorization::PERMISSION_MODE_ENV, mode);
+ } else if dangerously_bypass_approvals
+ && std::env::var_os(cua_driver_core::authorization::PERMISSION_MODE_ENV).is_none()
+ {
+ // The alarming CLI flag is both the unrestricted-mode selector and
+ // the user's explicit launch-time risk acknowledgement. Embedded and
+ // environment-driven launchers retain the two-part mode + acceptance
+ // contract because they do not pass through this CLI normalization.
+ std::env::set_var(
+ cua_driver_core::authorization::PERMISSION_MODE_ENV,
+ "unrestricted",
+ );
+ }
+ if dangerously_bypass_approvals {
+ std::env::set_var(cua_driver_core::authorization::DANGEROUS_BYPASS_ENV, "1");
+ }
+ if allow_legacy_existing_profile_approval {
+ std::env::set_var(
+ cua_driver_core::authorization::LEGACY_EXISTING_PROFILE_APPROVAL_ENV,
+ "1",
+ );
+ }
+ if let Some(path) = session_policy {
+ std::env::set_var(
+ cua_driver_core::session_manifest::SESSION_POLICY_FILE_ENV,
+ path,
+ );
+ }
+ if approve_session_policy {
+ std::env::set_var(
+ cua_driver_core::session_manifest::SESSION_POLICY_APPROVED_ENV,
+ "1",
+ );
+ }
+ cua_driver_core::authorization::validate_startup_authorization()?;
+ if cua_driver_core::authorization::configured_permission_mode()
+ .is_ok_and(|mode| mode == cua_driver_core::authorization::PermissionMode::Unrestricted)
+ {
+ eprintln!(
+ "DANGER: Cua Driver is running in unrestricted mode. Runtime approval prompts are disabled; prompt injection or unintended input may act with every capability allowed by the built-in, managed, and user policy ceilings. Use only in a disposable or fully trusted environment."
+ );
+ }
+ Ok(())
+}
+
/// Execute finite commands in a child so the parent can observe every exit,
/// including validation failures and legacy `process::exit` paths. Delivery is
/// delegated to a detached, no-output worker after the child exits, so network
@@ -264,9 +319,24 @@ fn main() {
}
cli::Command::Serve {
socket,
+ permission_mode,
+ dangerously_bypass_approvals,
+ allow_legacy_existing_profile_approval,
+ session_policy,
+ approve_session_policy,
no_permissions_gate,
claude_code_compat,
} => {
+ if let Err(error) = configure_startup_permission_mode(
+ permission_mode.as_deref(),
+ dangerously_bypass_approvals,
+ allow_legacy_existing_profile_approval,
+ session_policy.as_deref(),
+ approve_session_policy,
+ ) {
+ eprintln!("cua-driver: authorization startup error: {error}");
+ std::process::exit(64);
+ }
responsibility::reexec_disclaimed_if_needed();
let gate_opts =
platform_macos::permissions::GateOpts::from_env_and_flag(no_permissions_gate);
@@ -448,6 +518,15 @@ fn main() {
serve::run_stop_cmd(&sp);
return;
}
+ cli::Command::Revoke {
+ socket,
+ session,
+ all,
+ } => {
+ let sp = socket.unwrap_or_else(serve::default_socket_path);
+ serve::run_revoke_cmd(&sp, session.as_deref(), all);
+ return;
+ }
cli::Command::Status { socket } => {
let sp = socket.unwrap_or_else(serve::default_socket_path);
let pid_path = serve::default_pid_file_path();
@@ -619,9 +698,21 @@ fn main() -> anyhow::Result<()> {
}
cli::Command::Serve {
socket,
+ permission_mode,
+ dangerously_bypass_approvals,
+ allow_legacy_existing_profile_approval,
+ session_policy,
+ approve_session_policy,
no_permissions_gate,
claude_code_compat,
} => {
+ configure_startup_permission_mode(
+ permission_mode.as_deref(),
+ dangerously_bypass_approvals,
+ allow_legacy_existing_profile_approval,
+ session_policy.as_deref(),
+ approve_session_policy,
+ )?;
responsibility::reexec_disclaimed_if_needed();
telemetry::capture_start(
telemetry::event::SERVE_START_LEGACY,
@@ -655,6 +746,15 @@ fn main() -> anyhow::Result<()> {
serve::run_stop_cmd(&sp);
return Ok(());
}
+ cli::Command::Revoke {
+ socket,
+ session,
+ all,
+ } => {
+ let sp = socket.unwrap_or_else(serve::default_socket_path);
+ serve::run_revoke_cmd(&sp, session.as_deref(), all);
+ return Ok(());
+ }
cli::Command::Status { socket } => {
let sp = socket.unwrap_or_else(serve::default_socket_path);
let pid_path = serve::default_pid_file_path();
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
index c2d2357627..9cb1d716da 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
@@ -19,7 +19,7 @@
use std::sync::Arc;
-use cua_driver_core::policy::{configured_policy, PolicyDecision};
+use cua_driver_core::policy::{authorize_tool_call, validate_configured_policy};
use cua_driver_core::protocol::{initialize_result, Request, Response};
use cua_driver_core::server::{
observe_proxy_session_started, observe_proxy_tool_completed, tool_observation_timer,
@@ -43,7 +43,7 @@ use crate::serve::{is_daemon_listening, send_request, DaemonRequest, ToolObserva
/// advertises zero tools and then errors on every call. Matches
/// Swift `makeProxy`'s `fetchProxyToolList` pre-check.
pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {
- configured_policy().map_err(anyhow::Error::msg)?;
+ validate_configured_policy()?;
if !is_daemon_listening(&socket_path) {
anyhow::bail!(
"cua-driver-rs daemon not reachable on {socket_path}. Start it \
@@ -444,6 +444,18 @@ fn fetch_tools_list_from_daemon(
.map(serde_json::Value::String)
.collect()
});
+ let risk = t.get("risk").cloned().unwrap_or_else(|| {
+ name.as_str()
+ .map(cua_driver_core::authorization::risk_metadata_json)
+ .unwrap_or_else(|| {
+ serde_json::json!({
+ "class": "unclassified",
+ "enforcement": "metadata_only",
+ "operation_sensitive": false,
+ "version": cua_driver_core::authorization::RISK_METADATA_VERSION,
+ })
+ })
+ });
serde_json::json!({
"name": name,
"description": description,
@@ -455,6 +467,7 @@ fn fetch_tools_list_from_daemon(
"openWorldHint": open_world,
},
"capabilities": capabilities,
+ "risk": risk,
})
})
.collect();
@@ -518,32 +531,8 @@ async fn handle_proxy_request(
"tools/call" => match req.tool_call() {
Err(e) => Response::error(id, -32602, format!("Invalid params: {e}")),
Ok(call) => {
- match configured_policy() {
- Ok(Some(policy)) => match policy.evaluate(&call.name, &call.args) {
- PolicyDecision::Allow => {}
- PolicyDecision::Deny(reason) => {
- return Response::error(
- id,
- -32603,
- format!("Permission denied: {reason}"),
- );
- }
- PolicyDecision::Error(message) => {
- return Response::error(
- id,
- -32603,
- format!("Policy evaluation error: {message}"),
- );
- }
- },
- Ok(None) => {}
- Err(message) => {
- return Response::error(
- id,
- -32603,
- format!("Policy loading error: {message}"),
- );
- }
+ if let Err(error) = authorize_tool_call(&call.name, &call.args) {
+ return Response::error(id, -32603, error.to_string());
}
forward_tool_call(
id,
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
index 60dbdb98e1..75bef0765a 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -475,23 +475,9 @@ async fn invoke_daemon_tool(
// Evaluate before registry lookup so a deny-by-default policy does not leak
// whether an unapproved name happens to be registered. This also preserves
// the MCP policy contract now that every call passes through the daemon.
- match cua_driver_core::policy::configured_policy() {
- Ok(Some(policy)) => match policy.evaluate(&tool_name, &args) {
- cua_driver_core::policy::PolicyDecision::Allow => {}
- cua_driver_core::policy::PolicyDecision::Deny(reason) => {
- observe_daemon_error(observation, 1);
- return DaemonResponse::err(format!("Permission denied: {reason}"), 1);
- }
- cua_driver_core::policy::PolicyDecision::Error(message) => {
- observe_daemon_error(observation, 1);
- return DaemonResponse::err(format!("Policy evaluation error: {message}"), 1);
- }
- },
- Ok(None) => {}
- Err(message) => {
- observe_daemon_error(observation, 1);
- return DaemonResponse::err(format!("Policy loading error: {message}"), 1);
- }
+ if let Err(error) = cua_driver_core::authorization::authorize_tool_call(&tool_name, &args) {
+ observe_daemon_error(observation, 1);
+ return DaemonResponse::err(error.to_string(), 1);
}
if !known_tool {
@@ -740,6 +726,8 @@ pub async fn run_serve(
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::UnixListener;
+ cua_driver_core::authorization::validate_startup_authorization()?;
+
// Create parent directory.
if let Some(dir) = std::path::Path::new(socket_path).parent() {
std::fs::create_dir_all(dir)?;
@@ -844,6 +832,7 @@ pub async fn run_serve(
let tools: Vec<serde_json::Value> = reg.iter_defs()
.map(|(name, def)| {
let caps = cua_driver_core::tool::default_capabilities_for(name);
+ let risk = cua_driver_core::authorization::risk_metadata_json(name);
serde_json::json!({
"name": name,
"description": def.description,
@@ -853,6 +842,7 @@ pub async fn run_serve(
"idempotent": def.idempotent,
"open_world": def.open_world,
"capabilities": caps,
+ "risk": risk,
})
})
.collect();
@@ -893,6 +883,43 @@ pub async fn run_serve(
}
}
}
+ "authorization_status" => {
+ let resp = DaemonResponse::ok(
+ cua_driver_core::authorization::status_json()
+ );
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
+ "revoke_authorization" => {
+ let args = req.args.as_ref().unwrap_or(&serde_json::Value::Null);
+ let all = args.get("all").and_then(serde_json::Value::as_bool)
+ .unwrap_or(false);
+ let session = args.get("session")
+ .and_then(serde_json::Value::as_str)
+ .filter(|value| !value.is_empty());
+ let result = if all && session.is_none() {
+ let count = cua_driver_core::session::revoke_all_sessions();
+ Ok(serde_json::json!({"revoked": count, "scope": "all"}))
+ } else if !all {
+ session.map_or_else(
+ || Err("revoke_authorization requires session or all=true"),
+ |session| {
+ cua_driver_core::session::end_session(session);
+ Ok(serde_json::json!({"revoked": 1, "scope": "session"}))
+ },
+ )
+ } else {
+ Err("revoke_authorization accepts exactly one of session or all=true")
+ };
+ let resp = match result {
+ Ok(value) => DaemonResponse::ok(value),
+ Err(error) => DaemonResponse::err(error, 64),
+ };
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
"call" => {
// Recording idle-TTL liveness: any serviced tool
// call counts as activity (#1764).
@@ -1208,6 +1235,8 @@ pub async fn run_serve(
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::windows::named_pipe::ServerOptions;
+ cua_driver_core::authorization::validate_startup_authorization()?;
+
eprintln!("Cua Driver daemon listening on {socket_path}");
// Build the cross-IL security descriptor once, reuse on every pipe
@@ -1323,6 +1352,7 @@ pub async fn run_serve(
let tools: Vec<serde_json::Value> = reg.iter_defs()
.map(|(name, def)| {
let caps = cua_driver_core::tool::default_capabilities_for(name);
+ let risk = cua_driver_core::authorization::risk_metadata_json(name);
serde_json::json!({
"name": name,
"description": def.description,
@@ -1332,6 +1362,7 @@ pub async fn run_serve(
"idempotent": def.idempotent,
"open_world": def.open_world,
"capabilities": caps,
+ "risk": risk,
})
})
.collect();
@@ -1362,6 +1393,43 @@ pub async fn run_serve(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
}
+ "authorization_status" => {
+ let resp = DaemonResponse::ok(
+ cua_driver_core::authorization::status_json()
+ );
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
+ "revoke_authorization" => {
+ let args = req.args.as_ref().unwrap_or(&serde_json::Value::Null);
+ let all = args.get("all").and_then(serde_json::Value::as_bool)
+ .unwrap_or(false);
+ let session = args.get("session")
+ .and_then(serde_json::Value::as_str)
+ .filter(|value| !value.is_empty());
+ let result = if all && session.is_none() {
+ let count = cua_driver_core::session::revoke_all_sessions();
+ Ok(serde_json::json!({"revoked": count, "scope": "all"}))
+ } else if !all {
+ session.map_or_else(
+ || Err("revoke_authorization requires session or all=true"),
+ |session| {
+ cua_driver_core::session::end_session(session);
+ Ok(serde_json::json!({"revoked": 1, "scope": "session"}))
+ },
+ )
+ } else {
+ Err("revoke_authorization accepts exactly one of session or all=true")
+ };
+ let resp = match result {
+ Ok(value) => DaemonResponse::ok(value),
+ Err(error) => DaemonResponse::err(error, 64),
+ };
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
"call" => {
// Recording idle-TTL liveness (#1764).
last_activity.store(
@@ -1590,12 +1658,113 @@ pub fn run_status_cmd(socket_path: &str, pid_file_path: &str) {
} else {
println!(" pid: unknown (no pid file)");
}
+ let request = DaemonRequest {
+ method: "authorization_status".to_owned(),
+ name: None,
+ args: None,
+ session_id: None,
+ observation_origin: Some(ToolObservationOrigin::Direct),
+ };
+ if let Ok(response) = send_request(socket_path, &request) {
+ if let Some(status) = response.result {
+ println!(
+ " permission mode: {} ({})",
+ status["permission_mode"].as_str().unwrap_or("invalid"),
+ status["permission_mode_source"]
+ .as_str()
+ .unwrap_or("unknown source")
+ );
+ println!(
+ " user policy: configured={}, active={}, valid={}",
+ status["user_policy_configured"].as_bool().unwrap_or(false),
+ status["user_policy_active"].as_bool().unwrap_or(false),
+ status["user_policy_valid"].as_bool().unwrap_or(false),
+ );
+ if let Some(hash) = status["user_policy_sha256"].as_str() {
+ println!(" user policy sha256: {hash}");
+ }
+ println!(
+ " managed policy: configured={}, active={}, valid={}",
+ status["managed_policy_configured"]
+ .as_bool()
+ .unwrap_or(false),
+ status["managed_policy_active"].as_bool().unwrap_or(false),
+ status["managed_policy_valid"].as_bool().unwrap_or(false),
+ );
+ if let Some(hash) = status["managed_policy_sha256"].as_str() {
+ println!(" managed policy sha256: {hash}");
+ }
+ println!(
+ " protected consent collector: {}",
+ status["protected_consent_collector"]
+ .as_str()
+ .unwrap_or("unavailable")
+ );
+ println!(
+ " session policy: configured={}, approved_at_startup={}, valid={}",
+ status["session_policy_configured"]
+ .as_bool()
+ .unwrap_or(false),
+ status["session_policy_approved_at_startup"]
+ .as_bool()
+ .unwrap_or(false),
+ status["session_policy_valid"].as_bool().unwrap_or(false),
+ );
+ if let Some(manifest) = status["session_policy"].as_object() {
+ println!(
+ " session policy sha256: {}",
+ manifest
+ .get("sha256")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or("unknown")
+ );
+ }
+ }
+ }
} else {
eprintln!("Cua Driver daemon is not running");
std::process::exit(1);
}
}
+/// Revoke one authorization/session scope or every live scope. This local
+/// control is intentionally deny-only and never accepts a grant token.
+pub fn run_revoke_cmd(socket_path: &str, session: Option<&str>, all: bool) {
+ let request = DaemonRequest {
+ method: "revoke_authorization".to_owned(),
+ name: None,
+ args: Some(if all {
+ serde_json::json!({"all": true})
+ } else {
+ serde_json::json!({"session": session})
+ }),
+ session_id: None,
+ observation_origin: Some(ToolObservationOrigin::Direct),
+ };
+ match send_request(socket_path, &request) {
+ Ok(response) if response.ok => {
+ let result = response.result.unwrap_or_default();
+ println!(
+ "Revoked {} authorization scope(s).",
+ result["revoked"].as_u64().unwrap_or(0)
+ );
+ }
+ Ok(response) => {
+ eprintln!(
+ "{}",
+ response
+ .error
+ .unwrap_or_else(|| "authorization revocation failed".to_owned())
+ );
+ std::process::exit(response.exit_code.unwrap_or(1));
+ }
+ Err(error) => {
+ eprintln!("authorization revocation failed: {error}");
+ std::process::exit(1);
+ }
+ }
+}
+
// ── Tests ───────────────────────────────────────────────────────────────────
#[cfg(all(test, unix))]
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs
index 254fdad13f..873efe5363 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/daemon_required_test.rs
@@ -69,3 +69,171 @@ fn cli_call_succeeds_through_test_owned_daemon() {
assert!(!response.is_error(), "CLI call failed: {}", response.text());
assert!(response.structured().is_object());
}
+
+#[test]
+fn revoke_cli_ends_the_exact_live_session() {
+ let mut driver = CliDriver::new();
+ assert!(driver.available(), "test daemon failed to start");
+ let session = format!("revoke-cli-{}", std::process::id());
+ let started = driver.call(
+ "start_session",
+ serde_json::json!({"session": session, "capture_scope": "window"}),
+ );
+ assert!(!started.is_error(), "start failed: {}", started.text());
+
+ let output = Command::new(env!("CARGO_BIN_EXE_cua-driver"))
+ .args([
+ "revoke",
+ "--session",
+ &session,
+ "--socket",
+ driver.daemon_socket().expect("test daemon socket"),
+ ])
+ .output()
+ .expect("run authorization revoke command");
+ assert!(
+ output.status.success(),
+ "revoke failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let state = driver.call("get_session_state", serde_json::json!({"session": session}));
+ assert!(state.is_error());
+}
+
+#[test]
+fn forged_legacy_artifact_cannot_authorize_existing_profile_in_standard_mode() {
+ let mut driver = CliDriver::new();
+ assert!(driver.available(), "test daemon failed to start");
+
+ let token = uuid::Uuid::new_v4().to_string();
+ let approval_root = std::env::temp_dir().join("cua-driver-browser-approvals-v1");
+ std::fs::create_dir_all(&approval_root).expect("create legacy approval directory");
+ let artifact_path = approval_root.join(format!("{token}.json"));
+ let expires_unix_ms = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_millis()
+ + 60_000;
+ std::fs::write(
+ &artifact_path,
+ serde_json::to_vec(&serde_json::json!({
+ "schema": "cua-browser-existing-profile-approval-v1",
+ "token": token,
+ "scope": {
+ "pid": 42,
+ "window_id": 7,
+ "session": "forged-standard-attach"
+ },
+ "expires_unix_ms": expires_unix_ms
+ }))
+ .unwrap(),
+ )
+ .expect("write syntactically valid forged legacy artifact");
+
+ let response = driver.call(
+ "browser_prepare",
+ serde_json::json!({
+ "pid": 42,
+ "window_id": 7,
+ "session": "forged-standard-attach",
+ "strategy": { "kind": "existing_profile" },
+ "approval_token": token
+ }),
+ );
+ let _ = std::fs::remove_file(&artifact_path);
+
+ assert_eq!(response.structured()["status"], "refused");
+ assert_eq!(
+ response.structured()["refusal"]["code"],
+ "browser_consent_required"
+ );
+ assert_eq!(
+ response.structured()["refusal"]["detail"]["legacy_approval_enabled"],
+ false
+ );
+ assert!(
+ response.structured()["refusal"]["message"]
+ .as_str()
+ .is_some_and(|message| message.contains("file-backed artifact is disabled")),
+ "unexpected refusal: {}",
+ response.structured()
+ );
+}
+
+#[test]
+fn unrestricted_mode_skips_runtime_existing_profile_consent() {
+ let mut driver = CliDriver::with_daemon_env(&[
+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),
+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),
+ ]);
+ assert!(
+ driver.available(),
+ "unrestricted test daemon failed to start"
+ );
+
+ let response = driver.call(
+ "browser_prepare",
+ serde_json::json!({
+ "pid": i64::MAX,
+ "window_id": 7,
+ "session": "unrestricted-attach",
+ "strategy": { "kind": "existing_profile" }
+ }),
+ );
+
+ assert_eq!(response.structured()["status"], "refused");
+ assert_ne!(
+ response.structured()["refusal"]["code"],
+ "browser_consent_required",
+ "unrestricted attach unexpectedly requested runtime consent: {}",
+ response.structured()
+ );
+}
+
+#[test]
+fn bounded_manifest_is_an_immutable_deny_by_default_layer() {
+ let directory = tempfile::tempdir().expect("temporary bounded policy directory");
+ let policy_path = directory.path().join("bounded.yaml");
+ std::fs::write(
+ &policy_path,
+ r#"
+version: 1
+mode: bounded
+expires_after: 1h
+idle_timeout: 10m
+resources: {}
+allow:
+ tools: [get_config]
+deny:
+ tools: [list_apps]
+"#,
+ )
+ .expect("write bounded policy");
+ let policy = policy_path.display().to_string();
+ let mut driver = CliDriver::with_daemon_env(&[
+ ("CUA_DRIVER_PERMISSION_MODE", "bounded"),
+ ("CUA_DRIVER_SESSION_POLICY_FILE", &policy),
+ ("CUA_DRIVER_SESSION_POLICY_APPROVED", "1"),
+ ]);
+ assert!(driver.available(), "bounded test daemon failed to start");
+
+ let allowed = driver.call("get_config", serde_json::json!({}));
+ assert!(
+ !allowed.is_error(),
+ "allowed call failed: {}",
+ allowed.text()
+ );
+
+ let denied = driver.call("list_apps", serde_json::json!({}));
+ assert!(denied.is_error());
+ assert!(denied
+ .text()
+ .contains("bounded session policy denies tool 'list_apps'"));
+
+ let undeclared = driver.call("get_screen_size", serde_json::json!({}));
+ assert!(undeclared.is_error());
+ assert!(undeclared
+ .text()
+ .contains("outside the bounded session policy"));
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/permission_policy_startup_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/permission_policy_startup_test.rs
new file mode 100644
index 0000000000..bad72f3e74
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/permission_policy_startup_test.rs
@@ -0,0 +1,272 @@
+//! Explicit permission-policy configuration must fail before a daemon exposes
+//! an action endpoint.
+
+use std::process::Command;
+
+fn test_socket(directory: &tempfile::TempDir, suffix: &str) -> String {
+ #[cfg(unix)]
+ {
+ directory
+ .path()
+ .join(format!("{suffix}.sock"))
+ .display()
+ .to_string()
+ }
+ #[cfg(target_os = "windows")]
+ {
+ format!(r"\\.\pipe\cua-driver-{suffix}-{}", std::process::id())
+ }
+}
+
+fn rejected_serve(socket: &str, extra_args: &[&str]) -> std::process::Output {
+ let mut command = Command::new(env!("CARGO_BIN_EXE_cua-driver"));
+ command.args([
+ "serve",
+ "--socket",
+ socket,
+ "--no-overlay",
+ "--no-permissions-gate",
+ ]);
+ command.args(extra_args);
+ command
+ .env("CUA_DRIVER_RS_PERMISSIONS_GATE", "0")
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
+ .output()
+ .expect("run rejected cua-driver serve configuration")
+}
+
+#[test]
+fn missing_configured_policy_prevents_daemon_startup() {
+ let directory = tempfile::tempdir().expect("temporary policy test directory");
+ let missing_policy = directory.path().join("missing-policy.yaml");
+
+ let socket = test_socket(&directory, "missing-policy");
+ let output = Command::new(env!("CARGO_BIN_EXE_cua-driver"))
+ .args([
+ "serve",
+ "--socket",
+ &socket,
+ "--no-overlay",
+ "--no-permissions-gate",
+ ])
+ .env("CUA_DRIVER_POLICY_FILE", &missing_policy)
+ .env("CUA_DRIVER_RS_PERMISSIONS_GATE", "0")
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
+ .output()
+ .expect("run cua-driver serve with a missing configured policy");
+
+ assert!(
+ !output.status.success(),
+ "daemon unexpectedly started with a missing configured policy"
+ );
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("configured permission policy path does not exist"),
+ "unexpected stderr: {stderr}"
+ );
+
+ #[cfg(unix)]
+ assert!(
+ !std::path::Path::new(&socket).exists(),
+ "daemon bound its socket before rejecting the configured policy"
+ );
+}
+
+#[test]
+fn missing_managed_policy_prevents_daemon_startup() {
+ let directory = tempfile::tempdir().expect("temporary managed policy test directory");
+ let missing_policy = directory.path().join("missing-managed-policy.yaml");
+ let socket = test_socket(&directory, "missing-managed-policy");
+ let output = Command::new(env!("CARGO_BIN_EXE_cua-driver"))
+ .args([
+ "serve",
+ "--socket",
+ &socket,
+ "--no-overlay",
+ "--no-permissions-gate",
+ ])
+ .env("CUA_DRIVER_MANAGED_POLICY_FILE", &missing_policy)
+ .env("CUA_DRIVER_RS_PERMISSIONS_GATE", "0")
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
+ .output()
+ .expect("run cua-driver serve with a missing managed policy");
+
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("managed policy")
+ && stderr.contains("configured permission policy path does not exist"),
+ "unexpected stderr: {stderr}"
+ );
+ #[cfg(unix)]
+ assert!(!std::path::Path::new(&socket).exists());
+}
+
+#[test]
+fn unrestricted_mode_requires_the_danger_acknowledgement_before_bind() {
+ let directory = tempfile::tempdir().expect("temporary mode test directory");
+ let socket = test_socket(&directory, "unrestricted-no-ack");
+ let output = rejected_serve(&socket, &["--permission-mode", "unrestricted"]);
+
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("requires --dangerously-bypass-approvals"),
+ "unexpected stderr: {stderr}"
+ );
+ #[cfg(unix)]
+ assert!(!std::path::Path::new(&socket).exists());
+}
+
+#[test]
+fn danger_acknowledgement_cannot_weaken_standard_mode() {
+ let directory = tempfile::tempdir().expect("temporary mode test directory");
+ let socket = test_socket(&directory, "standard-danger-ack");
+ let output = rejected_serve(
+ &socket,
+ &[
+ "--permission-mode",
+ "standard",
+ "--dangerously-bypass-approvals",
+ ],
+ );
+
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("cannot be combined with a non-unrestricted --permission-mode"),
+ "unexpected stderr: {stderr}"
+ );
+ #[cfg(unix)]
+ assert!(!std::path::Path::new(&socket).exists());
+}
+
+#[test]
+fn danger_flag_alone_selects_unrestricted_and_managed_config_can_disable_it() {
+ let directory = tempfile::tempdir().expect("temporary mode test directory");
+ let socket = test_socket(&directory, "unrestricted-admin-disabled");
+ let output = Command::new(env!("CARGO_BIN_EXE_cua-driver"))
+ .args([
+ "serve",
+ "--socket",
+ &socket,
+ "--no-overlay",
+ "--no-permissions-gate",
+ "--dangerously-bypass-approvals",
+ ])
+ .env("CUA_DRIVER_DISABLE_UNRESTRICTED", "1")
+ .env("CUA_DRIVER_RS_PERMISSIONS_GATE", "0")
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
+ .output()
+ .expect("run administratively disabled unrestricted mode");
+
+ assert!(!output.status.success());
+ assert!(String::from_utf8_lossy(&output.stderr)
+ .contains("unrestricted is disabled by managed startup configuration"));
+ #[cfg(unix)]
+ assert!(!std::path::Path::new(&socket).exists());
+}
+
+fn write_valid_session_policy(directory: &tempfile::TempDir) -> String {
+ let path = directory.path().join("session-policy.yaml");
+ std::fs::write(
+ &path,
+ r#"
+version: 1
+mode: bounded
+expires_after: 1h
+idle_timeout: 10m
+resources: {}
+allow:
+ tools: [start_session, get_session_state, end_session]
+deny:
+ tools: [page]
+ask:
+ tools: [browser_download]
+"#,
+ )
+ .unwrap();
+ path.display().to_string()
+}
+
+#[test]
+fn bounded_mode_requires_a_session_policy_before_bind() {
+ let directory = tempfile::tempdir().expect("temporary bounded test directory");
+ let socket = test_socket(&directory, "bounded-no-policy");
+ let output = rejected_serve(&socket, &["--permission-mode", "bounded"]);
+ assert!(!output.status.success());
+ assert!(String::from_utf8_lossy(&output.stderr).contains("requires --session-policy"));
+ #[cfg(unix)]
+ assert!(!std::path::Path::new(&socket).exists());
+}
+
+#[test]
+fn bounded_mode_requires_launch_time_manifest_approval_before_bind() {
+ let directory = tempfile::tempdir().expect("temporary bounded test directory");
+ let policy = write_valid_session_policy(&directory);
+ let socket = test_socket(&directory, "bounded-no-approval");
+ let output = rejected_serve(
+ &socket,
+ &["--permission-mode", "bounded", "--session-policy", &policy],
+ );
+ assert!(!output.status.success());
+ assert!(String::from_utf8_lossy(&output.stderr).contains("requires --approve-session-policy"));
+ #[cfg(unix)]
+ assert!(!std::path::Path::new(&socket).exists());
+}
+
+#[test]
+fn session_policy_cannot_be_smuggled_into_standard_mode() {
+ let directory = tempfile::tempdir().expect("temporary standard test directory");
+ let policy = write_valid_session_policy(&directory);
+ let socket = test_socket(&directory, "standard-session-policy");
+ let output = rejected_serve(
+ &socket,
+ &[
+ "--permission-mode",
+ "standard",
+ "--session-policy",
+ &policy,
+ "--approve-session-policy",
+ ],
+ );
+ assert!(!output.status.success());
+ assert!(String::from_utf8_lossy(&output.stderr).contains("valid only with"));
+ #[cfg(unix)]
+ assert!(!std::path::Path::new(&socket).exists());
+}
+
+#[test]
+fn legacy_existing_profile_approval_cannot_bypass_bounded_indicator() {
+ let directory = tempfile::tempdir().expect("temporary bounded test directory");
+ let policy = write_valid_session_policy(&directory);
+ let socket = test_socket(&directory, "bounded-legacy-approval");
+ let output = rejected_serve(
+ &socket,
+ &[
+ "--permission-mode",
+ "bounded",
+ "--session-policy",
+ &policy,
+ "--approve-session-policy",
+ "--allow-legacy-existing-profile-approval",
+ ],
+ );
+ assert!(!output.status.success());
+ assert!(String::from_utf8_lossy(&output.stderr)
+ .contains("valid only with --permission-mode standard"));
+ #[cfg(unix)]
+ assert!(!std::path::Path::new(&socket).exists());
+}
+
+#[test]
+fn autonomous_mode_name_remains_a_bounded_compatibility_alias() {
+ let directory = tempfile::tempdir().expect("temporary mode alias test directory");
+ let socket = test_socket(&directory, "autonomous-alias");
+ let output = rejected_serve(&socket, &["--permission-mode", "autonomous"]);
+ assert!(!output.status.success());
+ assert!(String::from_utf8_lossy(&output.stderr)
+ .contains("permission mode bounded requires --session-policy"));
+ #[cfg(unix)]
+ assert!(!std::path::Path::new(&socket).exists());
+}
diff --git a/libs/cua-driver/scripts/_install-local-rust.sh b/libs/cua-driver/scripts/_install-local-rust.sh
index c58f5877d1..a11b2d500d 100755
--- a/libs/cua-driver/scripts/_install-local-rust.sh
+++ b/libs/cua-driver/scripts/_install-local-rust.sh
@@ -48,6 +48,27 @@ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# under libs/cua-driver/rust/.
REPO_ROOT="$(cd "$SCRIPT_DIR/../rust" && pwd)"
+# Embed local-build provenance in `get_config`. An explicit value remains
+# authoritative for source snapshots copied to VMs without `.git`; otherwise
+# derive HEAD from the checkout that is actually being built. Keep dirty local
+# developer builds honest instead of claiming byte-for-byte provenance from
+# the clean commit.
+if [ -z "${CUA_DRIVER_SOURCE_SHA:-}" ]; then
+ if ! command -v git >/dev/null 2>&1; then
+ echo "error: git is required to determine CUA_DRIVER_SOURCE_SHA; set it explicitly for a source snapshot" >&2
+ exit 1
+ fi
+ CUA_DRIVER_SOURCE_SHA="$(git -C "$REPO_ROOT" rev-parse --verify 'HEAD^{commit}' 2>/dev/null || true)"
+ if ! printf '%s' "$CUA_DRIVER_SOURCE_SHA" | grep -Eq '^[0-9a-fA-F]{40}([0-9a-fA-F]{24})?$'; then
+ echo "error: could not determine an exact Git commit for $REPO_ROOT; set CUA_DRIVER_SOURCE_SHA explicitly" >&2
+ exit 1
+ fi
+ if [ -n "$(git -C "$REPO_ROOT" status --porcelain --untracked-files=normal 2>/dev/null)" ]; then
+ CUA_DRIVER_SOURCE_SHA="${CUA_DRIVER_SOURCE_SHA}-dirty"
+ fi
+fi
+export CUA_DRIVER_SOURCE_SHA
+
# --- Load shared daemon-cleanup helpers ---------------------------------
#
# Sibling _install-common.sh defines stop_cua_driver_daemons +
@@ -161,6 +182,7 @@ VERSIONED_DIR="$RELEASES_DIR/$VERSION_TAG-$TARGET_TRIPLE"
echo "${BOLD}${BLUE}cua-driver-rs local installer${NORMAL}"
echo " source: ${BOLD}$REPO_ROOT${NORMAL}"
+echo " sha: ${BOLD}$CUA_DRIVER_SOURCE_SHA${NORMAL}"
echo " config: ${BOLD}$BUILD_CONFIG${NORMAL}"
echo " target: ${BOLD}$TARGET_TRIPLE${NORMAL}"
echo " bin: ${BOLD}$BIN_DIR/cua-driver${NORMAL}"
diff --git a/libs/cua-driver/scripts/install-local.ps1 b/libs/cua-driver/scripts/install-local.ps1
index 2e45fde4a6..886e355611 100644
--- a/libs/cua-driver/scripts/install-local.ps1
+++ b/libs/cua-driver/scripts/install-local.ps1
@@ -67,6 +67,25 @@ $RepoRoot = (Resolve-Path "$ScriptDir\..\rust").Path
$BinaryName = "cua-driver.exe"
# Always release-config — matches the binary install.ps1 hands end users.
$Config = "release"
+
+# Embed local-build provenance in `get_config`. Preserve an explicit value for
+# source snapshots copied to VMs without `.git`; otherwise derive the commit
+# from the checkout being built. Mark dirty developer trees honestly instead
+# of presenting their binaries as exact products of the clean commit.
+if ([string]::IsNullOrWhiteSpace($env:CUA_DRIVER_SOURCE_SHA)) {
+ if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
+ throw "git is required to determine CUA_DRIVER_SOURCE_SHA; set it explicitly for a source snapshot"
+ }
+ $detectedSourceSha = (& git -C $RepoRoot rev-parse --verify 'HEAD^{commit}' 2>$null | Out-String).Trim()
+ if ($LASTEXITCODE -ne 0 -or $detectedSourceSha -notmatch '^[0-9a-fA-F]{40}([0-9a-fA-F]{24})?$') {
+ throw "could not determine an exact Git commit for $RepoRoot; set CUA_DRIVER_SOURCE_SHA explicitly"
+ }
+ $dirtyState = (& git -C $RepoRoot status --porcelain --untracked-files=normal 2>$null | Out-String).Trim()
+ if ($LASTEXITCODE -ne 0) {
+ throw "could not determine whether the source tree is dirty: $RepoRoot"
+ }
+ $env:CUA_DRIVER_SOURCE_SHA = if ($dirtyState) { "$detectedSourceSha-dirty" } else { $detectedSourceSha }
+}
# Arch detection — use $env:PROCESSOR_ARCHITECTURE rather than
# RuntimeInformation::OSArchitecture so this works under
# Set-StrictMode -Version Latest (same fix as install.ps1 PR #1631).
@@ -142,6 +161,7 @@ function Write-Step($msg) { Write-Host "==> $msg" -ForegroundColor Cyan }
Write-Step "cua-driver-rs local installer (Windows)"
Write-Host " source: $RepoRoot"
+Write-Host " sha: $env:CUA_DRIVER_SOURCE_SHA"
Write-Host " config: $Config"
Write-Host " target: $Target"
Write-Host " visible: $VisibleBinDir"