Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cua-driver): enforce consequential and privileged actions (#2585)
Francesco Bonaccidf368a7698a0
diff --git a/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx b/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdxindex d24faabafb..7bdcd15dd6 100644--- a/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx+++ b/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx@@ -150,17 +150,20 @@ assert status['source']['attribution'] == 'driver-daemon'PY```-Run the prompt-capable live probe explicitly, then exercise both the-accessibility and capture paths:+Run the human-owned permission setup command from the VM's interactive+Terminal. Agent and daemon tool calls are deliberately read-only and cannot+raise macOS permission UI. Then exercise both the accessibility and capture+paths:```bash-/Users/lume/.local/bin/cua-driver call check_permissions '{"prompt":true}' \+/Users/lume/.local/bin/cua-driver permissions grant+/Users/lume/.local/bin/cua-driver permissions status --json \> /tmp/cua-driver-permissions-live.json/usr/bin/python3 - <<'PY'import jsonwith open('/tmp/cua-driver-permissions-live.json') as source:- status = json.load(source)['structuredContent']+ status = json.load(source)assert status['screen_recording_capturable'] is Trueassert status['direct_capture_status'] == 'ready'diff --git a/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx b/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdxindex dc3e0558df..5cbe4a6052 100644--- a/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx+++ b/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx@@ -223,9 +223,10 @@ Verify the app-owned grants, signature, capture result, and SIP state:and .source.attribution == "driver-daemon"'-"$DRIVER" call check_permissions '{"prompt":true}' | jq -e '- .structuredContent.screen_recording_capturable == true- and .structuredContent.direct_capture_status == "ready"+"$DRIVER" permissions grant+"$DRIVER" permissions status --json | jq -e '+ .screen_recording_capturable == true+ and .direct_capture_status == "ready"'jq -e 'diff --git a/docs/content/docs/reference/cua-driver/macos-permissions.mdx b/docs/content/docs/reference/cua-driver/macos-permissions.mdxindex 68909157fe..62b05410a4 100644--- a/docs/content/docs/reference/cua-driver/macos-permissions.mdx+++ b/docs/content/docs/reference/cua-driver/macos-permissions.mdx@@ -35,8 +35,12 @@ private-window-picker bypass dialog when ScreenCaptureKit is queried,`direct_capture_status: "not_checked"`. This preserves the command's read-only,no-prompt contract.-`permissions grant` explains the additional dialog before deliberately-triggering it, then requires a successful live capture probe. macOS describes+`permissions grant` never sends a prompt-capable request over the daemon+socket. It launches a short-lived instance of the installed CuaDriver app+through LaunchServices, explains the additional dialog before deliberately+triggering it, and requires a successful live capture probe. The child returns+only content-free grant status through a private temporary file; that file+cannot grant permission or widen an agent session. macOS describesthe combined privacy category as screen and system-audio recording even thoughCua Driver's current ScreenCaptureKit recorder captures screen video only anddoes not enable audio capture. The consent is limited to macOS capture; it doesdiff --git a/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx b/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdxindex c317167696..8ea017ada2 100644--- a/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx@@ -29,7 +29,7 @@ A few parameters are platform-specific by design and are intentionally NOT part| ----------------- | -------- | --- || `launch_app` identifiers | macOS: `bundle_id`, `urls`. Windows: `aumid`, `launch_path`, `path`, `start_minimized`. | App launch is OS-native. `name` is the portable fallback that works on both. || `debug_window_info` | Windows only | A window-handle / class / rect / z-order debug tool with no macOS or Linux counterpart. |-| `check_permissions.prompt` | macOS only | Raises the TCC permission dialogs; there is no Windows or Linux equivalent of TCC. |+| `check_permissions.prompt` | macOS only | Public tool calls are read-only by default. `prompt:true` is refused before platform dispatch; use the human-run `cua-driver permissions grant` setup command, which launches the installed app through LaunchServices. There is no Windows or Linux equivalent of TCC. || Windowless screen-absolute (desktop-scope) clicks/scrolls | all three platforms, **exposed differently** | The capability exists everywhere, but the knob differs: macOS takes a **per-call `scope:"desktop"`** parameter on the pointer tools, while Windows and Linux gate it on the persisted **`capture_scope:"desktop"`** config (`set_config`). So a per-call `scope` param appears only on macOS; on Windows/Linux you opt in once via config. Unifying this knob is a tracked follow-up. || `modifier` on a *background* click | honored on macOS and Linux; dropped on a Windows background click | A Windows background click goes through UIA Invoke / PostMessage, which carry no live keyboard state, so `modifier` takes effect only on the `delivery_mode:"foreground"` (SendInput) rung there. |diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdxindex e6206fdacd..58f59b8159 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx@@ -687,7 +687,7 @@ Returns: `accessibility` + `screen_recording` (booleans from the TCC preflight A**Arguments:**- `probe_direct_capture` (boolean, optional): When prompting and Screen Recording is granted, also run the live ScreenCaptureKit probe that may raise Tahoe's direct-capture consent. Default true. Set false for a staged Accessibility/Screen Recording request.-- `prompt` (boolean, optional): Raise the system permission prompts for missing grants. Default true.+- `prompt` (boolean, optional): Raise the system permission prompts for missing grants. Default false; only a trusted host setup route may set true.### `health_report`diff --git a/docs/content/docs/reference/cua-driver/permission-modes.mdx b/docs/content/docs/reference/cua-driver/permission-modes.mdxindex 3e8ce97ba3..c1ea6b6f1d 100644--- a/docs/content/docs/reference/cua-driver/permission-modes.mdx+++ b/docs/content/docs/reference/cua-driver/permission-modes.mdx@@ -18,7 +18,7 @@ allowed.| Mode | Startup | Human intervention | Existing logged-in profile || --- | --- | --- | --- |-| `standard` | Default | Once per exact user-owned observation, input, or file-transfer scope and once for existing-profile attachment; grants are reused until expiry, scope change, or Stop | Requires a certified protected-consent provider and its persistent Stop indicator |+| `standard` | Default | Once per exact protected resource or typed action, including user-owned observation/input, file transfer, process termination, persistent configuration, and existing-profile attachment; grants are reused only within their exact scope | 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 |@@ -55,7 +55,7 @@ Tool-list and description responses include risk metadata with `class`,selectors, resource scope keys, grant TTL, indicator requirement, revocationtriggers, refusal code, and provider requirement.-The current inventory is intentionally narrow:+The current inventory is fail-closed:| Adapter | State | Meaning || --- | --- | --- |@@ -63,15 +63,18 @@ The current inventory is intentionally narrow:| `private_observation` | `active` | User-window, application, browser-target, and display observation requires an exact expiring grant. Proven driver-owned isolated browser resources remain prompt-light. || `desktop_input` | `active` | Window/application input is bound to the exact PID/window and delivery mode; desktop-coordinate input is bound to current display geometry. || `file_transfer_and_output` | `active` | Uploads, downloads, screenshot/recording output, trajectory replay, and confirmed dependency installation are bound to canonical exact paths or a typed install action. |-| `browser_consequential_action` | `metadata_only` | Mutating dialogs and generic page actions are classified but not protected by a shipped grant adapter. |-| `devices`, `shell_and_network` | `not_exposed` | Cua Driver does not expose these open-ended capabilities. |--`metadata_only` is classification, not runtime consent enforcement. The-remaining groups stay metadata-only until an exact resource adapter, certified-protected host, persistent Stop indicator, revocation path, and representative-platform tests all ship. Screenshot-to-file and recording calls are compound:-their observation half is protected now, but they remain metadata-only as a-whole until file egress is also enforced.+| `browser_consequential_action` | `active` | Page-owned dialog accept/dismiss is bound to the exact browser binding, tab, dialog generation, action, and delivery mode. Sensitive prompt text is represented only by a presence bit, never copied into a grant digest. |+| `browser_bound_input` | `active` | Typed navigation and browser input use implementation-attested target, tab, process, and binding evidence. Proven driver-owned isolated browsers remain prompt-light. |+| `browser_unbounded_script` | `active` | Legacy `page` mutations have no exact browser binding and are denied in `standard` and `bounded`; only trusted launch-time acceptance of `unrestricted` can admit them. |+| `process_control` | `active` | `kill_app` approval binds an OS process fingerprint, which is re-proved immediately before termination to reject PID reuse. |+| `os_permission_prompt` | `active` | Agent tool calls cannot raise protected OS permission UI in any mode. `check_permissions` is read-only by default and explicit `prompt:true` is refused before platform dispatch. On macOS, the human-run `cua-driver permissions grant` setup command launches the installed app through LaunchServices; macOS owns the actual approval UI. |+| `driver_configuration` | `active` | Persistent `set_config` changes require an exact protected grant in `standard` and an approved bounded scope in `bounded`. |+| `clipboard`, `devices`, `shell_and_network` | `not_exposed` | Cua Driver does not expose these open-ended capabilities. |++No exposed sensitive route remains `metadata_only`. Compound calls must satisfy+every adapter they cross: screenshot-to-file needs both observation and exact+file-output grants, while trajectory replay needs exact file input and desktop+input grants.## Protected consent@@ -84,9 +87,10 @@ 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 arewritable by the calling process. If the runtime has no certified provider,-`standard` and `bounded` refuse user-owned private observation, desktop input,-file transfer/output, and existing-profile attachment before the platform-backend can access the resource.+`standard` and `bounded` refuse protected user-owned resources and typed+actions—including observation, input, file transfer/output, process control,+persistent configuration, and existing-profile attachment—before platform+dispatch when the required host is unavailable.<Callout type="info">The current standalone CLI/MCP daemon has no certified Codex or Claude host@@ -127,6 +131,25 @@ resources:origins:- https://docs.example.com- https://app.example.com+ desktop:+ applications:+ - 844+ windows:+ - pid: 844+ window_id: 10725+ display: false+ files:+ read:+ - /Users/alice/approved/upload.pdf+ write:+ - /Users/alice/approved/downloads+ processes:+ terminate:+ - 844+ driver_configuration:+ changes:+ - key: max_image_dimension+ value: 1200allow:tools:@@ -137,6 +160,8 @@ allow:- browser_navigate- browser_click- browser_type+ - browser_set_input_files+ - browser_downloaddeny:tools:@@ -144,8 +169,7 @@ deny:ask:tools:- - browser_download- - browser_set_input_files+ - install_ffmpeg```Tools omitted from all three sets are denied. `ask` also denies unattended@@ -153,10 +177,30 @@ dispatch because an agent cannot accept its own prompt. A future protectedhost 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.+match an `existing_profiles` entry. That exact entry also covers observation+and input for the same browser process/window; listing it again under+`desktop.applications` or `desktop.windows` is optional. The duplicate entries+above are intentional examples of how to authorize generic desktop tools for+the same target. `desktop.display: true` is required for unfiltered desktop+observation, desktop-coordinate input, or `escalate_session`.++Requested navigation must use an allowed origin. Before every typed browser+mutation, the daemon reads the live top-level URL through CDP and refuses if a+redirect moved the tab outside the manifest. Only the canonical origin reaches+the authorization broker; URL paths, queries, and fragments do not.++File entries are exact. Existing paths and the deepest existing ancestor of a+future output are resolved when the manifest loads, so later symlink changes+fail closed. Do not end a manifest path with a directory separator. Uploads and+replay use `files.read`; downloads, screenshots, and recordings use+`files.write`. `processes.terminate` contains exact PIDs, and+`driver_configuration.changes` contains exact key/value pairs.++Two bounded exceptions are deliberately tool-scoped rather than+resource-scoped: trajectory-only recording records only actions that pass+their own adapters, and the typed `install_ffmpeg(confirm:true)` route names+one fixed dependency. Both still need an `allow.tools` entry. Put+`install_ffmpeg` under `ask` to keep unattended installation denied.An origin-scoped manifest cannot also allow generic `page`, desktop input, ordesktop-state tools that bypass the typed browser-origin adapter. Usediff --git a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md b/libs/cua-driver/rust/Skills/cua-driver/MACOS.mdindex 377968542a..7917c97371 100644--- a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md+++ b/libs/cua-driver/rust/Skills/cua-driver/MACOS.md@@ -311,13 +311,14 @@ macOS-specific residuals worth knowing (the rest of the capture/dispatch/addressing params are a shared cross-platform contract — see `SKILL.md` →_Cross-platform parameter contract_):-- **`check_permissions.prompt` is macOS-only.** In the signed standalone- service, `true` may raise the TCC Accessibility / Screen-Recording dialogs- and run the direct ScreenCaptureKit probe. In an in-process SDK runtime,- private embedded host, or `cua-driver mcp --direct`, the host owns permission- UX: the driver forces this request into a read-only check, reports- `source.attribution:"host"`, and leaves direct-capture readiness- `not_checked`. There is no Windows/Linux equivalent.+- **`check_permissions.prompt` is macOS-only and public calls are+ status-only.** Omitted `prompt` defaults to `false`; explicit `true` is+ refused before platform dispatch in every mode. For a signed standalone+ install, the human-run `cua-driver permissions grant` command launches a+ short-lived CuaDriver app instance through LaunchServices so macOS owns the+ approval UI and direct ScreenCaptureKit probe. In an in-process SDK runtime,+ private embedded host, or `cua-driver mcp --direct`, the embedding host owns+ permission UX. There is no Windows/Linux equivalent.- **`session` always worked on macOS;** the cross-platform change is thatWindows/Linux stopped _rejecting_ it. No macOS-side change to how youpass it.@@ -376,9 +377,9 @@ so a naive read-back "confirms" a value that isn't really there.The driver **detects Electron and refuses to trust that echo**: anAX-path `type_text` on an Electron app returns `effect:"unverifiable"` +`escalation:{recommended:"px"}`, **never** a false `verified:true`.- (On Catalyst the AX value reads back unreadable, so it reports- unverified too.) Bottom line: on these surfaces **do not trust the AX- confirm — the screenshot in the same response is the only truth.**+(On Catalyst the AX value reads back unreadable, so it reports+unverified too.) Bottom line: on these surfaces **do not trust the AX+confirm — the screenshot in the same response is the only truth.**Fix — **one call**: `type_text({pid, window_id, x, y, text})`. Passing`x,y` (no `element_index`) is the **element px action** form of@@ -421,7 +422,7 @@ functional and one perceptual:state go `DISABLED` when their owning app isn't the key window(Preview rotate, IINA speed change, most editor commands).AXPick + AXPress will dispatch successfully from the driver's side but- no-op at the target — you get a silent false-pass.+ no-op at the target — you get a silent false-pass.- **Perceptual (matters for demos, screen recordings, and anythingthe user watches live):** macOS's screen-rendered menu baralways belongs to the _frontmost_ app. AXPick on a backgroundeddiff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.mdindex 5960358ff4..b848bbe9b2 100644--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md@@ -695,7 +695,7 @@ schema-rejected.Genuinely platform-specific params stay OUT of the shared contract bydesign (launch-app identifiers, the Windows-only `debug_window_info`, the-macOS-only `check_permissions.prompt`). The per-OS files list the+macOS-only status-only `check_permissions.prompt`). The per-OS files list theresiduals that matter when you drive on that platform.## Pixel-coordinate clicksdiff --git a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.tomlindex 8f1430d0b0..4fddd8f175 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml+++ b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml@@ -2,6 +2,7 @@name = "cua-driver-core"version.workspace = trueedition.workspace = true+publish = false[features]default = ["yaml", "rego"]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.rsindex eb39f4f443..8fbdbce142 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs@@ -222,10 +222,7 @@ const FILE_TRANSFER_SCOPE_KEYS: &[&str] = &["user_policy_sha256",];-const CONSEQUENTIAL_OPERATIONS: &[&str] = &[- "browser_dialog[action=accept|dismiss]",- "page[action!=get_text|query_dom]",-];+const CONSEQUENTIAL_OPERATIONS: &[&str] = &["browser_dialog[action=accept|dismiss]"];const CONSEQUENTIAL_SCOPE_KEYS: &[&str] = &["daemon_generation","public_session",@@ -238,7 +235,17 @@ const CONSEQUENTIAL_SCOPE_KEYS: &[&str] = &["user_policy_sha256",];-const UNBOUNDED_SCRIPT_OPERATIONS: &[&str] = &["page[action=execute_javascript]"];+const UNBOUNDED_SCRIPT_OPERATIONS: &[&str] = &[+ "page[action=execute_javascript|click_element|insert_text|type_keystrokes|enable_javascript_apple_events]",+];++const LEGACY_PAGE_MUTATING_ACTIONS: &[&str] = &[+ "execute_javascript",+ "click_element",+ "insert_text",+ "type_keystrokes",+ "enable_javascript_apple_events",+];const BROWSER_BOUND_INPUT_OPERATIONS: &[&str] = &["browser_navigate",@@ -352,71 +359,74 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[EnforcementAdapterDescriptor {id: "browser_consequential_action",operations: CONSEQUENTIAL_OPERATIONS,- state: RiskEnforcement::MetadataOnly,+ state: RiskEnforcement::Active,risk_class: RiskClass::R3,resource_kind: "typed_browser_consequential_action",scope_keys: CONSEQUENTIAL_SCOPE_KEYS,- grant_type: None,- idle_ttl_seconds: None,- absolute_ttl_seconds: None,- indicator_requirement: "not_implemented",+ grant_type: Some("protected_resource_grant"),+ idle_ttl_seconds: Some(5 * 60),+ absolute_ttl_seconds: Some(30 * 60),+ indicator_requirement: "required_in_standard_and_bounded",revocation_triggers: SESSION_REVOCATION,- refusal_code: None,- provider_requirement: "certified_protected_host_not_implemented",- enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::MetadataOnly),+ refusal_code: Some("protected_consent_required"),+ provider_requirement:+ "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",+ enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),},EnforcementAdapterDescriptor {id: "browser_unbounded_script",operations: UNBOUNDED_SCRIPT_OPERATIONS,- state: RiskEnforcement::MetadataOnly,+ state: RiskEnforcement::Active,risk_class: RiskClass::R3,resource_kind: "unbounded_authenticated_page_script",scope_keys: &[],- grant_type: None,+ grant_type: Some("trusted_launch_mode_gate"),idle_ttl_seconds: None,absolute_ttl_seconds: None,indicator_requirement: "not_grantable_in_standard_or_bounded",revocation_triggers: &[],- refusal_code: None,- provider_requirement: "typed_bounded_adapter_required_before_activation",- enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::MetadataOnly),+ refusal_code: Some("unbounded_operation_requires_unrestricted"),+ provider_requirement: "unrestricted_mode_with_trusted_launch_time_risk_acknowledgement",+ enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),},EnforcementAdapterDescriptor {id: "browser_bound_input",operations: BROWSER_BOUND_INPUT_OPERATIONS,- state: RiskEnforcement::MetadataOnly,+ state: RiskEnforcement::Active,risk_class: RiskClass::R2,resource_kind: "authenticated_browser_binding_and_tab_input",scope_keys: BROWSER_BOUND_INPUT_SCOPE_KEYS,- grant_type: None,- idle_ttl_seconds: None,- absolute_ttl_seconds: None,- indicator_requirement: "not_implemented",+ grant_type: Some("protected_resource_grant"),+ idle_ttl_seconds: Some(30 * 60),+ absolute_ttl_seconds: Some(8 * 60 * 60),+ indicator_requirement: "required_in_standard_and_bounded",revocation_triggers: SESSION_REVOCATION,- refusal_code: None,- provider_requirement: "certified_protected_host_not_implemented",- enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::MetadataOnly),+ refusal_code: Some("protected_consent_required"),+ provider_requirement:+ "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",+ enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),},EnforcementAdapterDescriptor {id: "process_control",operations: PROCESS_CONTROL_OPERATIONS,- state: RiskEnforcement::MetadataOnly,+ state: RiskEnforcement::Active,risk_class: RiskClass::R3,resource_kind: "exact_process_termination",scope_keys: PROCESS_CONTROL_SCOPE_KEYS,- grant_type: None,- idle_ttl_seconds: None,- absolute_ttl_seconds: None,- indicator_requirement: "not_implemented",+ grant_type: Some("protected_resource_grant"),+ idle_ttl_seconds: Some(2 * 60),+ absolute_ttl_seconds: Some(10 * 60),+ indicator_requirement: "required_in_standard_and_bounded",revocation_triggers: SESSION_REVOCATION,- refusal_code: None,- provider_requirement: "certified_protected_host_not_implemented",- enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::MetadataOnly),+ refusal_code: Some("protected_consent_required"),+ provider_requirement:+ "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",+ enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),},EnforcementAdapterDescriptor {id: "os_permission_prompt",operations: OS_PERMISSION_PROMPT_OPERATIONS,- state: RiskEnforcement::MetadataOnly,+ state: RiskEnforcement::Active,risk_class: RiskClass::R2,resource_kind: "operating_system_permission_prompt",scope_keys: &["daemon_generation", "permission_mode"],@@ -425,14 +435,14 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[absolute_ttl_seconds: None,indicator_requirement: "never_agent_controllable",revocation_triggers: &[],- refusal_code: None,- provider_requirement: "trusted_host_setup_required_before_activation",- enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::MetadataOnly),+ refusal_code: Some("os_permission_prompt_requires_trusted_host"),+ provider_requirement: "trusted_host_setup_outside_the_agent_tool_path",+ enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),},EnforcementAdapterDescriptor {id: "driver_configuration",operations: DRIVER_CONFIGURATION_OPERATIONS,- state: RiskEnforcement::MetadataOnly,+ state: RiskEnforcement::Active,risk_class: RiskClass::R2,resource_kind: "persistent_driver_configuration",scope_keys: &[@@ -441,14 +451,15 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &["managed_policy_sha256","user_policy_sha256",],- grant_type: None,- idle_ttl_seconds: None,- absolute_ttl_seconds: None,- indicator_requirement: "not_implemented",+ grant_type: Some("protected_resource_grant"),+ idle_ttl_seconds: Some(5 * 60),+ absolute_ttl_seconds: Some(30 * 60),+ indicator_requirement: "required_in_standard_and_bounded",revocation_triggers: SESSION_REVOCATION,- refusal_code: None,- provider_requirement: "certified_protected_host_not_implemented",- enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::MetadataOnly),+ refusal_code: Some("protected_consent_required"),+ provider_requirement:+ "protected_consent_in_standard; protected_indicator_in_bounded; none_in_unrestricted",+ enforcement_by_mode: AdapterEnforcement::uniform(RiskEnforcement::Active),},EnforcementAdapterDescriptor {id: "clipboard",@@ -592,21 +603,21 @@ pub fn enforcement_adapters_for_call(add("file_transfer_and_output");}- if (tool == "browser_dialog"+ if tool == "browser_dialog"&& matches!(args.get("action").and_then(Value::as_str),Some("accept" | "dismiss")- ))- || (tool == "page"- && !matches!(- args.get("action").and_then(Value::as_str),- Some("get_text" | "query_dom")- ))+ ){add("browser_consequential_action");}- if tool == "page" && args.get("action").and_then(Value::as_str) == Some("execute_javascript") {+ if tool == "page"+ && args+ .get("action")+ .and_then(Value::as_str)+ .is_some_and(|action| LEGACY_PAGE_MUTATING_ACTIONS.contains(&action))+ {add("browser_unbounded_script");}@@ -618,7 +629,7 @@ pub fn enforcement_adapters_for_call(add("process_control");}- if tool == "check_permissions" && args.get("prompt").and_then(Value::as_bool).unwrap_or(true) {+ if tool == "check_permissions" && args.get("prompt").and_then(Value::as_bool).unwrap_or(false) {add("os_permission_prompt");}@@ -683,7 +694,8 @@ pub fn advertised_risk_for(tool: &str) -> RiskAssessment {| "set_agent_cursor_style" => RiskClass::R1,// Surfaces that can reveal or control sensitive local/authenticated- // state. Most remain metadata-only until their resource adapters ship.+ // state. Active adapters still decide their exact resource scope at+ // the canonical registry boundary before platform dispatch."zoom"| "list_apps"| "list_windows"@@ -800,13 +812,13 @@ pub fn classify_tool_call(tool: &str, args: &Value) -> RiskAssessment {operation_sensitive: true,},"check_permissions" => RiskAssessment {- class: if args.get("prompt").and_then(Value::as_bool).unwrap_or(true) {+ class: if args.get("prompt").and_then(Value::as_bool).unwrap_or(false) {RiskClass::R2} else {RiskClass::R0},enforcement: RiskEnforcement::MetadataOnly,- operation_sensitive: args.get("prompt").and_then(Value::as_bool).unwrap_or(true),+ operation_sensitive: args.get("prompt").and_then(Value::as_bool).unwrap_or(false),},"browser_set_input_files"| "browser_download"@@ -1315,16 +1327,15 @@ mod tests {#[test]fn os_permission_prompt_is_argument_sensitive() {- let read_only =- classify_tool_call("check_permissions", &serde_json::json!({"prompt": false}));- assert_eq!(read_only.class, RiskClass::R0);- assert!(!read_only.operation_sensitive);-- for args in [serde_json::json!({}), serde_json::json!({"prompt": true})] {- let prompting = classify_tool_call("check_permissions", &args);- assert_eq!(prompting.class, RiskClass::R2);- assert!(prompting.operation_sensitive);+ for args in [serde_json::json!({}), serde_json::json!({"prompt": false})] {+ let read_only = classify_tool_call("check_permissions", &args);+ assert_eq!(read_only.class, RiskClass::R0);+ assert!(!read_only.operation_sensitive);}+ let prompting =+ classify_tool_call("check_permissions", &serde_json::json!({"prompt": true}));+ assert_eq!(prompting.class, RiskClass::R2);+ assert!(prompting.operation_sensitive);assert_eq!(advertised_risk_for("check_permissions").class,RiskClass::R2@@ -1368,12 +1379,7 @@ mod tests {"browser_prepare.existing_profile","private_observation","desktop_input",- "file_transfer_and_output"- ]- );- assert_eq!(- adapter_ids_with_state(RiskEnforcement::MetadataOnly),- vec![+ "file_transfer_and_output","browser_consequential_action","browser_unbounded_script","browser_bound_input",@@ -1382,6 +1388,10 @@ mod tests {"driver_configuration",]);+ assert_eq!(+ adapter_ids_with_state(RiskEnforcement::MetadataOnly),+ Vec::<&str>::new()+ );assert_eq!(adapter_ids_with_state(RiskEnforcement::NotExposed),vec!["clipboard", "devices", "shell_and_network"]@@ -1392,7 +1402,13 @@ mod tests {"browser_prepare.existing_profile","private_observation","desktop_input",- "file_transfer_and_output"+ "file_transfer_and_output",+ "browser_consequential_action",+ "browser_unbounded_script",+ "browser_bound_input",+ "process_control",+ "os_permission_prompt",+ "driver_configuration",]);@@ -1423,7 +1439,13 @@ mod tests {);assert_eq!(ids("page", serde_json::json!({"action": "execute_javascript"})),- vec!["browser_consequential_action", "browser_unbounded_script"]+ vec!["browser_unbounded_script"]+ );+ assert!(ids("page", serde_json::json!({})).is_empty());+ assert!(ids("page", serde_json::json!({"action": "unknown"})).is_empty());+ assert_eq!(+ ids("browser_dialog", serde_json::json!({"action": "accept"})),+ vec!["browser_consequential_action"]);assert_eq!(ids("start_recording", serde_json::json!({})),@@ -1471,7 +1493,7 @@ mod tests {);assert_eq!(ids("check_permissions", serde_json::json!({})),- vec!["os_permission_prompt"]+ Vec::<&str>::new());assert_eq!(ids("set_config", serde_json::json!({})),@@ -1488,12 +1510,7 @@ mod tests {"browser_prepare.existing_profile","private_observation","desktop_input",- "file_transfer_and_output"- ])- );- assert_eq!(- status["metadata_only_risk_enforcement"],- serde_json::json!([+ "file_transfer_and_output","browser_consequential_action","browser_unbounded_script","browser_bound_input",@@ -1502,6 +1519,10 @@ mod tests {"driver_configuration"]));+ assert_eq!(+ status["metadata_only_risk_enforcement"],+ serde_json::json!([])+ );assert_eq!(status["not_exposed_risk_enforcement"],serde_json::json!(["clipboard", "devices", "shell_and_network"])@@ -1512,7 +1533,13 @@ mod tests {"browser_prepare.existing_profile","private_observation","desktop_input",- "file_transfer_and_output"+ "file_transfer_and_output",+ "browser_consequential_action",+ "browser_unbounded_script",+ "browser_bound_input",+ "process_control",+ "os_permission_prompt",+ "driver_configuration"]));assert_eq!(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.rsindex 7985f33755..00b825c0a8 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@@ -28,6 +28,7 @@ use std::sync::{Arc, Mutex, Weak};use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};use serde_json::{json, Value};+use sha2::{Digest, Sha256};use uuid::Uuid;use crate::session::register_scoped_session_end_hook;@@ -103,6 +104,32 @@ fn authorize_live_browser_origin(.map_err(|error| refuse(BrowserRefusalCode::BrowserOriginOutsideScope, error))}+fn protected_live_origin_scope(raw: &str) -> Result<String, BrowserRefusal> {+ if raw.trim() == "about:blank" {+ return Ok("about:blank".to_owned());+ }+ let parsed = url::Url::parse(raw).map_err(|_| {+ refuse(+ BrowserRefusalCode::BrowserWrongTargetRefused,+ "the live top-level browser URL is invalid",+ )+ })?;+ let origin = parsed.origin().ascii_serialization();+ if origin != "null" {+ return Ok(origin);+ }++ // Opaque origins (for example file: and data:) cannot safely share one+ // generic "null" grant. Bind them to a one-way document digest without+ // sending the full path/query/fragment to the consent provider.+ let digest = Sha256::digest(raw.as_bytes());+ let digest = digest+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect::<String>();+ Ok(format!("{}:sha256:{digest}", parsed.scheme()))+}+fn route_err(context: &str, err: impl std::fmt::Display) -> BrowserRefusal {refuse(BrowserRefusalCode::BrowserRouteUnavailable,@@ -1404,24 +1431,7 @@ impl BrowserEngine {.map(Ok).unwrap_or_else(crate::authorization::configured_permission_mode);if dispatch_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 live_url = self.live_top_level_url(&conn, &cdp_session).await?;let manifest = match dispatch_context.as_deref() {Some(context) => context.bounded_manifest(),None => {@@ -1433,7 +1443,7 @@ impl BrowserEngine {})?}};- authorize_live_browser_origin(manifest, live_url)?;+ authorize_live_browser_origin(manifest, &live_url)?;}Ok(ValidatedTab {conn,@@ -1444,6 +1454,46 @@ impl BrowserEngine {})}+ async fn live_top_level_url(+ &self,+ conn: &CdpConnection,+ cdp_session: &str,+ ) -> Result<String, BrowserRefusal> {+ let frame_tree = conn+ .call(Some(cdp_session), "Page.getFrameTree", json!({}))+ .await+ .map_err(|error| {+ route_err("could not prove the live top-level browser document", error)+ })?;+ frame_tree+ .pointer("/frameTree/frame/url")+ .and_then(Value::as_str)+ .filter(|url| !url.is_empty())+ .map(str::to_owned)+ .ok_or_else(|| {+ refuse(+ BrowserRefusalCode::BrowserOriginOutsideScope,+ "the live top-level browser origin could not be proven",+ )+ })+ }++ pub(crate) async fn attest_protected_tab(+ &self,+ session: &str,+ target_id: &str,+ tab_id: &str,+ ) -> Result<(ValidatedTab, String), BrowserRefusal> {+ let validated = self+ .revalidate_for_mutation(session, target_id, Some(tab_id))+ .await?;+ let live_url = self+ .live_top_level_url(&validated.conn, &validated.cdp_session)+ .await?;+ let live_origin = protected_live_origin_scope(&live_url)?;+ Ok((validated, live_origin))+ }+/// Animate platform-owned browser feedback without coupling it to input/// delivery. Only main-frame viewport points are mapped: child-frame CDP/// coordinates are not necessarily in the top-level viewport space, and adiff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rsindex a836d9cc90..1ae2bf5de1 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs@@ -13,7 +13,7 @@ use async_trait::async_trait;use serde_json::{json, Value};use crate::protocol::ToolResult;-use crate::tool::{Tool, ToolDef};+use crate::tool::{ProtectedResourceOwnership, Tool, ToolDef};use crate::tool_args::ArgsExt;use super::cdp_ws::CdpConnection;@@ -21,6 +21,7 @@ use super::engine::{BrowserEngine, ValidatedTab};use super::platform::BrowserVisualActionKind;use super::refusal::{BrowserRefusal, BrowserRefusalCode};use super::store::{BrowserActionKind, FrameKind, FrameRef};+use super::tools::{browser_protected_resource_scope, browser_resource_ownership};#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum PointerAction {@@ -729,6 +730,30 @@ impl Tool for BrowserPointerTool {&self.def}+ async fn protected_resource_ownership(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> ProtectedResourceOwnership {+ if adapter_id == "browser_bound_input" {+ browser_resource_ownership(&self.engine, args)+ } else {+ ProtectedResourceOwnership::UserOwned+ }+ }++ async fn protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ if adapter_id == "browser_bound_input" {+ browser_protected_resource_scope(&self.engine, args, "browser_pointer").await+ } else {+ Ok(None)+ }+ }+async fn invoke(&self, args: Value) -> ToolResult {let target_id = match args.require_str("target_id") {Ok(value) => value,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.rsindex f0376141b0..5ee552a1fc 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@@ -93,7 +93,10 @@ fn schema_session() -> Value {})}-fn browser_resource_ownership(engine: &BrowserEngine, args: &Value) -> ProtectedResourceOwnership {+pub(crate) fn browser_resource_ownership(+ engine: &BrowserEngine,+ args: &Value,+) -> ProtectedResourceOwnership {let Some(session) = args.get("session").and_then(Value::as_str)@@ -120,6 +123,84 @@ fn browser_resource_ownership(engine: &BrowserEngine, args: &Value) -> Protected}}+pub(crate) async fn browser_protected_resource_scope(+ engine: &BrowserEngine,+ args: &Value,+ tool_name: &str,+) -> Result<Option<Value>, String> {+ let session = args+ .get("session")+ .and_then(Value::as_str)+ .filter(|session| !session.is_empty())+ .ok_or_else(|| "the browser operation requires an explicit session".to_owned())?;+ let target_id = args+ .get("target_id")+ .and_then(Value::as_str)+ .filter(|target| !target.is_empty())+ .ok_or_else(|| "the browser operation requires an exact target_id".to_owned())?;+ let tab_id = args+ .get("tab_id")+ .and_then(Value::as_str)+ .filter(|tab| !tab.is_empty())+ .ok_or_else(|| "the browser operation requires an exact tab_id".to_owned())?;+ let runtime_session = crate::tool::current_dispatch_authorization_context()+ .map(|context| context.runtime_session_key(session))+ .unwrap_or_else(|| session.to_owned());+ let (validated, live_origin) = engine+ .attest_protected_tab(&runtime_session, target_id, tab_id)+ .await+ .map_err(|error| error.message)?;+ let target = validated.record;+ let tab = validated.tab;+ let requested_origin = if tool_name == "browser_navigate" {+ let requested = args+ .get("url")+ .and_then(Value::as_str)+ .ok_or_else(|| "browser_navigate requires a destination URL".to_owned())?;+ if requested.to_ascii_lowercase().starts_with("about:") {+ Some("about:".to_owned())+ } else {+ let parsed = url::Url::parse(requested)+ .map_err(|_| "the destination URL is invalid".to_owned())?;+ Some(parsed.origin().ascii_serialization())+ }+ } else {+ None+ };+ let action_class = match tool_name {+ "get_browser_state" => "page_observation",+ "browser_navigate" => "navigation",+ "browser_dialog" => "page_dialog_resolution",+ _ => "page_input",+ };+ let mut resource = json!({+ "kind": "authenticated_browser_tab",+ "target_id": target_id,+ "tab_id": tab_id,+ "pid": target.pid,+ "process_fingerprint": target.fingerprint,+ "binding_generation": target.generation,+ "cdp_target_id": tab.cdp_target_id,+ "tab_generation": tab.generation,+ "live_origin": live_origin,+ "requested_origin": requested_origin,+ "action_class": action_class,+ });+ if tool_name == "browser_dialog" {+ resource["dialog_id"] = args.get("dialog_id").cloned().unwrap_or(Value::Null);+ resource["dialog_action"] = args.get("action").cloned().unwrap_or(Value::Null);+ resource["delivery_mode"] = Value::String(+ args.get("delivery_mode")+ .and_then(Value::as_str)+ .unwrap_or("background")+ .to_owned(),+ );+ resource["prompt_text_present"] =+ Value::Bool(args.get("prompt_text").and_then(Value::as_str).is_some());+ }+ Ok(Some(resource))+}+fn semantic_ref_value(listed: &super::engine::SemanticListedRef) -> Value {json!({"ref": listed.external,@@ -242,6 +323,20 @@ impl Tool for GetBrowserStateTool {}}+ async fn protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ if adapter_id == "private_observation"+ && args.get("target_id").and_then(Value::as_str).is_some()+ {+ browser_protected_resource_scope(&self.engine, args, "get_browser_state").await+ } else {+ Ok(None)+ }+ }+async fn invoke(&self, args: Value) -> ToolResult {// Snapshot mode: target_id (+ tab_id) — uses existing capabilities.if let Some(target_id) = args.opt_str("target_id") {@@ -681,6 +776,30 @@ impl Tool for BrowserNavigateTool {&self.def}+ async fn protected_resource_ownership(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> ProtectedResourceOwnership {+ if adapter_id == "browser_bound_input" {+ browser_resource_ownership(&self.engine, args)+ } else {+ ProtectedResourceOwnership::UserOwned+ }+ }++ async fn protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ if adapter_id == "browser_bound_input" {+ browser_protected_resource_scope(&self.engine, args, "browser_navigate").await+ } else {+ Ok(None)+ }+ }+async fn invoke(&self, args: Value) -> ToolResult {let (target_id, tab_id, url) = match (args.require_str("target_id"),@@ -806,6 +925,30 @@ impl Tool for BrowserClickTool {&self.def}+ async fn protected_resource_ownership(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> ProtectedResourceOwnership {+ if adapter_id == "browser_bound_input" {+ browser_resource_ownership(&self.engine, args)+ } else {+ ProtectedResourceOwnership::UserOwned+ }+ }++ async fn protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ if adapter_id == "browser_bound_input" {+ browser_protected_resource_scope(&self.engine, args, "browser_click").await+ } else {+ Ok(None)+ }+ }+async fn invoke(&self, args: Value) -> ToolResult {let (target_id, tab_id) = match (args.require_str("target_id"), args.require_str("tab_id")){@@ -1236,6 +1379,30 @@ impl Tool for BrowserTypeTool {&self.def}+ async fn protected_resource_ownership(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> ProtectedResourceOwnership {+ if adapter_id == "browser_bound_input" {+ browser_resource_ownership(&self.engine, args)+ } else {+ ProtectedResourceOwnership::UserOwned+ }+ }++ async fn protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ if adapter_id == "browser_bound_input" {+ browser_protected_resource_scope(&self.engine, args, "browser_type").await+ } else {+ Ok(None)+ }+ }+async fn invoke(&self, args: Value) -> ToolResult {let (target_id, tab_id, text) = match (args.require_str("target_id"),@@ -1647,13 +1814,31 @@ impl Tool for BrowserDialogTool {adapter_id: &str,args: &Value,) -> ProtectedResourceOwnership {- if adapter_id == "private_observation" {+ if matches!(+ adapter_id,+ "private_observation" | "browser_consequential_action"+ ) {browser_resource_ownership(&self.engine, args)} else {ProtectedResourceOwnership::UserOwned}}+ async fn protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ if matches!(+ adapter_id,+ "private_observation" | "browser_consequential_action"+ ) {+ browser_protected_resource_scope(&self.engine, args, "browser_dialog").await+ } else {+ Ok(None)+ }+ }+async fn invoke(&self, args: Value) -> ToolResult {let (target_id, tab_id, action) = match (args.require_str("target_id"),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.rsindex e4636c3d5f..75a0edfb5e 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@@ -27,7 +27,8 @@ use super::platform::{use super::pointer::BrowserPointerTool;use super::refusal::BrowserRefusal;use super::tools::{- BrowserClickTool, BrowserNavigateTool, BrowserPrepareTool, BrowserTypeTool, GetBrowserStateTool,+ browser_protected_resource_scope, BrowserClickTool, BrowserNavigateTool, BrowserPrepareTool,+ BrowserTypeTool, GetBrowserStateTool,};use super::types::{BrowserClassification, BrowserEngineFamily, BrowserProduct, EndpointOwnershipMethod,@@ -45,6 +46,7 @@ struct FixtureState {oopif_supported: bool,oopif_present: bool,emit_rogue_attach: bool,+ main_url: String,main_loader: String,iframe_loader: String,oopif_loader: String,@@ -70,6 +72,7 @@ impl Default for FixtureState {oopif_supported: true,oopif_present: true,emit_rogue_attach: false,+ main_url: "https://fixture.test/".into(),main_loader: "L_MAIN_1".into(),iframe_loader: "L_IFRAME_1".into(),oopif_loader: "L_OOPIF_1".into(),@@ -442,7 +445,7 @@ fn fixture_handler(state: SharedState) -> MockHandler {"frame": {"id": "F_MAIN","loaderId": st.main_loader.clone(),- "url": "https://fixture.test/",+ "url": st.main_url.clone(),},"childFrames": [{"frame": {@@ -1884,6 +1887,50 @@ async fn rogue_attach_announcements_are_contained() {// ── Mutation routing + frame identity revalidation ──────────────────────────+#[tokio::test]+async fn protected_browser_scope_reproves_live_origin_and_omits_sensitive_url_text() {+ let f = fixture().await;+ let (target, tab) = bind(&f).await;+ let args = json!({+ "target_id": target,+ "tab_id": tab,+ "session": SESSION,+ "x": 10,+ "y": 20,+ });++ let first = browser_protected_resource_scope(&f.engine, &args, "browser_click")+ .await+ .unwrap()+ .unwrap();+ assert_eq!(first["live_origin"], "https://fixture.test");+ assert!(+ !first.to_string().contains("secret"),+ "the resource must not contain a full URL"+ );+ let observation = browser_protected_resource_scope(&f.engine, &args, "get_browser_state")+ .await+ .unwrap()+ .unwrap();+ assert_eq!(observation["action_class"], "page_observation");+ assert_eq!(first["action_class"], "page_input");++ f.state.lock().unwrap().main_url = "https://bank.example/transfer?secret=one-time-token".into();+ let second = browser_protected_resource_scope(&f.engine, &args, "browser_click")+ .await+ .unwrap()+ .unwrap();+ assert_eq!(second["live_origin"], "https://bank.example");+ assert_ne!(+ first, second,+ "cross-origin navigation must rotate the grant scope"+ );+ assert!(+ !second.to_string().contains("one-time-token"),+ "query text must never reach the consent resource"+ );+}+#[tokio::test]async fn click_routes_oopif_refs_through_the_contained_child_session() {let f = 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.rsindex 04573ea1f1..1cb96220ac 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs@@ -128,6 +128,8 @@ pub enum ConsentError {Expired,#[error("persistent consent indicator could not be activated: {0}")]Indicator(String),+ #[error("protected resource is outside the bounded session policy: {0}")]+ BoundedResource(String),}#[derive(Clone)]@@ -402,6 +404,16 @@ impl ProtectedResourceGrants {if context.mode() == PermissionMode::Unrestricted {return Ok(None);}+ if context.mode() == PermissionMode::Bounded {+ let manifest = context.bounded_manifest().ok_or_else(|| {+ ConsentError::BoundedResource(+ "bounded mode has no approved session manifest".to_owned(),+ )+ })?;+ manifest+ .authorize_protected_resource(adapter_id, &resource)+ .map_err(ConsentError::BoundedResource)?;+ }let resource_digest = digest_resource(adapter_id, &resource);let key = resource_grant_key(context, lifecycle_session, adapter_id, &resource_digest);if let Some(grant) = self.lookup(&key, context) {@@ -489,6 +501,21 @@ impl ProtectedResourceGrants {removed}+ pub fn revoke_resource(+ &self,+ context: &crate::session_authorization::EffectiveAuthorizationContext,+ lifecycle_session: Option<&str>,+ adapter_id: &str,+ resource: &Value,+ ) -> Option<ProtectedGrant> {+ let digest = digest_resource(adapter_id, resource);+ let key = resource_grant_key(context, lifecycle_session, adapter_id, &digest);+ self.grants.lock().unwrap().remove(&key).map(|grant| {+ grant.protected.indicator.revoke();+ grant.protected+ })+ }+pub fn revoke_all(&self) -> Vec<ProtectedGrant> {let mut grants = self.grants.lock().unwrap();let removed = grantsdiff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rsindex 89f1b54132..f093d6e298 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@@ -35,7 +35,7 @@ impl ToolProvider for ToolRegistry {name: &str,arguments: serde_json::Value,) -> Result<serde_json::Value, String> {- serde_json::to_value(self.invoke(name, arguments).await)+ serde_json::to_value(self.invoke_from_trusted_adapter(name, arguments).await).map_err(|error| format!("Serialize error: {error}"))}}@@ -909,11 +909,63 @@ fn tool_error_result(message: String, structured: serde_json::Value) -> serde_js#[cfg(test)]mod observation_tests {use super::*;+ use std::sync::Mutex;++ struct CapturingProvider {+ arguments: Mutex<Option<serde_json::Value>>,+ }++ #[async_trait::async_trait]+ impl ToolProvider for CapturingProvider {+ fn tools_list(&self) -> serde_json::Value {+ serde_json::json!({"tools": []})+ }++ async fn invoke_tool(+ &self,+ _name: &str,+ arguments: serde_json::Value,+ ) -> Result<serde_json::Value, String> {+ self.arguments.lock().unwrap().replace(arguments);+ Ok(serde_json::json!({"content": [], "isError": false}))+ }+ }fn timer(known: bool, valid: bool, path: StdioExecutionPath) -> ToolObservationTimer {ToolObservationTimer::start("click".to_owned(), known, valid, path)}+ #[tokio::test]+ async fn mcp_boundary_replaces_forged_reserved_fields_with_host_evidence() {+ let provider = CapturingProvider {+ arguments: Mutex::new(None),+ };+ let request: Request = serde_json::from_value(serde_json::json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {+ "name": "browser_download",+ "arguments": {+ "session": "public",+ "_session_id": "forged-owner",+ "_transport_session_id": "forged-transport",+ "_cua_browser_download_mcp_host_approved": false,+ "_protected_process_fingerprint": {"pid": 1}+ }+ }+ }))+ .unwrap();+ let response = handle_request(request, serde_json::json!(1), &provider).await;+ assert!(matches!(response.body, ResponseBody::Result { .. }));++ let arguments = provider.arguments.lock().unwrap().clone().unwrap();+ assert_eq!(arguments["_session_id"], "public");+ assert_eq!(arguments["_transport_session_id"], "public");+ assert_eq!(arguments["_cua_browser_download_mcp_host_approved"], true);+ assert!(arguments.get("_protected_process_fingerprint").is_none());+ }+#[test]fn successful_mixed_output_is_shape_only() {let response = Response::ok(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.rsindex e63ea78098..7a2927a2de 100644--- 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@@ -5,7 +5,7 @@//! managed, and user policy layers; it cannot introduce unreviewed tools.use std::collections::HashSet;-use std::path::Path;+use std::path::{Component, Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex, OnceLock};use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};@@ -36,6 +36,13 @@ pub struct SessionManifest {ask: HashSet<String>,existing_profiles: HashSet<(i64, u64)>,browser_origins: HashSet<String>,+ desktop_applications: HashSet<i64>,+ desktop_windows: HashSet<(i64, u64)>,+ desktop_display: bool,+ readable_paths: HashSet<String>,+ writable_paths: HashSet<String>,+ terminable_pids: HashSet<i64>,+ configuration_changes: Vec<(String, serde_json::Value)>,last_authorized_dispatch: Arc<Mutex<Instant>>,idle_expired: Arc<AtomicBool>,}@@ -114,13 +121,220 @@ impl SessionManifest {let origin = canonical_origin(raw)?;if self.browser_origins.contains(&origin) {Ok(())+ } else {+ Err("the live browser origin is outside the bounded session policy".to_owned())+ }+ }++ /// Match the implementation-attested resource of an active adapter+ /// against the immutable bounded manifest. A tool allow-list entry alone+ /// never widens the resources approved at launch.+ pub fn authorize_protected_resource(+ &self,+ adapter_id: &str,+ resource: &serde_json::Value,+ ) -> Result<(), String> {+ let kind = resource+ .get("kind")+ .and_then(serde_json::Value::as_str)+ .ok_or_else(|| format!("{adapter_id} did not attest a resource kind"))?;+ let refused = || {+ Err(format!(+ "{adapter_id} resource kind '{kind}' is outside the bounded session policy"+ ))+ };+ match adapter_id {+ "private_observation" => match kind {+ "window" => self.authorize_desktop_window(resource),+ "application" => self.authorize_desktop_application(resource),+ "display" => self.desktop_display.then_some(()).ok_or_else(|| {+ "desktop display observation is outside the bounded session policy".to_owned()+ }),+ "browser_target" | "authenticated_browser_tab" => {+ self.authorize_resource_origin(resource)+ }+ // `escalate_session` always expands a browser-scoped session+ // to desktop scope; it has no caller-selectable capture_scope+ // argument. Require the immutable manifest's display grant+ // directly instead of keying enforcement on a field the tool+ // can never send.+ "session_capture_scope" => self.desktop_display.then_some(()).ok_or_else(|| {+ "desktop capture escalation is outside the bounded session policy".to_owned()+ }),+ "session_trajectory_recording" => Ok(()),+ _ => refused(),+ },+ "desktop_input" => match kind {+ "window_input" => self.authorize_desktop_window(resource),+ "application_input" => self.authorize_desktop_application(resource),+ "display_input" => self.desktop_display.then_some(()).ok_or_else(|| {+ "desktop-wide input is outside the bounded session policy".to_owned()+ }),+ _ => refused(),+ },+ "file_transfer_and_output" => self.authorize_file_resource(kind, resource),+ "browser_bound_input" | "browser_consequential_action" => {+ self.authorize_resource_origin(resource)+ }+ "process_control" => {+ let pid = resource+ .pointer("/fingerprint/pid")+ .and_then(serde_json::Value::as_i64)+ .ok_or_else(|| "process control did not attest a pid".to_owned())?;+ if self.terminable_pids.contains(&pid) {+ Ok(())+ } else {+ Err(format!(+ "process pid {pid} is outside the bounded session policy"+ ))+ }+ }+ "driver_configuration" => {+ let changes = resource+ .get("exact_changes")+ .and_then(serde_json::Value::as_object)+ .ok_or_else(|| {+ "driver configuration did not attest exact changes".to_owned()+ })?;+ for (key, value) in changes {+ if !self+ .configuration_changes+ .iter()+ .any(|(allowed_key, allowed_value)| {+ allowed_key == key && allowed_value == value+ })+ {+ return Err(format!(+ "driver configuration change '{key}' is outside the bounded session policy"+ ));+ }+ }+ Ok(())+ }+ _ => refused(),+ }+ }++ fn authorize_desktop_window(&self, resource: &serde_json::Value) -> Result<(), String> {+ let pid = resource+ .get("pid")+ .and_then(serde_json::Value::as_i64)+ .ok_or_else(|| "window resource did not attest a pid".to_owned())?;+ let window_id = resource+ .get("window_id")+ .and_then(serde_json::Value::as_u64)+ .ok_or_else(|| "window resource did not attest a window_id".to_owned())?;+ if self.desktop_windows.contains(&(pid, window_id))+ || self.existing_profiles.contains(&(pid, window_id))+ {+ Ok(())+ } else {+ Err(format!(+ "desktop pid {pid} window {window_id} is outside the bounded session policy"+ ))+ }+ }++ fn authorize_desktop_application(&self, resource: &serde_json::Value) -> Result<(), String> {+ let pid = resource+ .get("pid")+ .and_then(serde_json::Value::as_i64)+ .ok_or_else(|| "application resource did not attest a pid".to_owned())?;+ if self.desktop_applications.contains(&pid)+ || self+ .existing_profiles+ .iter()+ .any(|(profile_pid, _)| *profile_pid == pid)+ {+ Ok(())} else {Err(format!(- "browser origin '{origin}' is outside the bounded session policy"+ "desktop application pid {pid} is outside the bounded session policy"))}}+ fn authorize_resource_origin(&self, resource: &serde_json::Value) -> Result<(), String> {+ let origin = resource+ .get("live_origin")+ .and_then(serde_json::Value::as_str)+ .ok_or_else(|| "browser resource did not attest a live origin".to_owned())?;+ if self.browser_origins.contains(origin) {+ Ok(())+ } else {+ Err("the live browser origin is outside the bounded session policy".to_owned())+ }+ }++ fn authorize_file_resource(+ &self,+ kind: &str,+ resource: &serde_json::Value,+ ) -> Result<(), String> {+ let all_allowed = |values: &serde_json::Value, allowed: &HashSet<String>| {+ values.as_array().is_some_and(|values| {+ !values.is_empty()+ && values+ .iter()+ .all(|value| value.as_str().is_some_and(|path| allowed.contains(path)))+ })+ };+ match kind {+ "browser_upload" => {+ if all_allowed(&resource["canonical_paths"], &self.readable_paths) {+ Ok(())+ } else {+ Err(+ "one or more upload paths are outside the bounded session policy"+ .to_owned(),+ )+ }+ }+ "trajectory_replay" => self.authorize_exact_path(+ resource,+ "canonical_source_directory",+ &self.readable_paths,+ ),+ "browser_download" => self.authorize_exact_path(+ resource,+ "canonical_destination_root",+ &self.writable_paths,+ ),+ "screenshot_output" => {+ self.authorize_exact_path(resource, "canonical_output_path", &self.writable_paths)+ }+ "recording_output" | "recording_finalize" => self.authorize_exact_path(+ resource,+ "canonical_output_directory",+ &self.writable_paths,+ ),+ // The exact dependency and confirmation bit are fixed by the+ // typed install_ffmpeg route; the manifest's tool allow is the+ // reviewed bounded decision.+ "dependency_install" => Ok(()),+ _ => Err(format!(+ "file resource kind '{kind}' is outside the bounded session policy"+ )),+ }+ }++ fn authorize_exact_path(+ &self,+ resource: &serde_json::Value,+ key: &str,+ allowed: &HashSet<String>,+ ) -> Result<(), String> {+ let path = resource+ .get(key)+ .and_then(serde_json::Value::as_str)+ .ok_or_else(|| format!("file resource did not attest {key}"))?;+ if allowed.contains(path) {+ Ok(())+ } else {+ Err("the exact path is outside the bounded session policy".to_owned())+ }+ }+pub fn is_expired(&self) -> bool {self.expires_unix_ms < now_unix_ms()}@@ -171,6 +385,14 @@ struct RawManifest {struct RawResources {#[serde(default)]browser: RawBrowserResources,+ #[serde(default)]+ desktop: RawDesktopResources,+ #[serde(default)]+ files: RawFileResources,+ #[serde(default)]+ processes: RawProcessResources,+ #[serde(default)]+ driver_configuration: RawDriverConfigurationResources,}#[cfg(feature = "yaml")]@@ -191,6 +413,60 @@ struct RawExistingProfile {window_id: u64,}+#[cfg(feature = "yaml")]+#[derive(Debug, Default, Deserialize)]+#[serde(deny_unknown_fields)]+struct RawDesktopResources {+ #[serde(default)]+ applications: Vec<i64>,+ #[serde(default)]+ windows: Vec<RawDesktopWindow>,+ #[serde(default)]+ display: bool,+}++#[cfg(feature = "yaml")]+#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct RawDesktopWindow {+ pid: i64,+ window_id: u64,+}++#[cfg(feature = "yaml")]+#[derive(Debug, Default, Deserialize)]+#[serde(deny_unknown_fields)]+struct RawFileResources {+ #[serde(default)]+ read: Vec<String>,+ #[serde(default)]+ write: Vec<String>,+}++#[cfg(feature = "yaml")]+#[derive(Debug, Default, Deserialize)]+#[serde(deny_unknown_fields)]+struct RawProcessResources {+ #[serde(default)]+ terminate: Vec<i64>,+}++#[cfg(feature = "yaml")]+#[derive(Debug, Default, Deserialize)]+#[serde(deny_unknown_fields)]+struct RawDriverConfigurationResources {+ #[serde(default)]+ changes: Vec<RawConfigurationChange>,+}++#[cfg(feature = "yaml")]+#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct RawConfigurationChange {+ key: String,+ value: serde_json::Value,+}+#[cfg(feature = "yaml")]#[derive(Debug, Default, Deserialize)]#[serde(deny_unknown_fields)]@@ -231,17 +507,54 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {#[cfg(feature = "yaml")]{- if raw.version != 1 {+ let RawManifest {+ version,+ mode,+ expires_after,+ idle_timeout,+ resources,+ allow,+ deny,+ ask,+ } = raw;+ let RawResources {+ browser,+ desktop,+ files,+ processes,+ driver_configuration,+ } = resources;+ let RawBrowserResources {+ existing_profiles: raw_existing_profiles,+ origins: raw_browser_origins,+ } = browser;+ let RawDesktopResources {+ applications: raw_desktop_applications,+ windows: raw_desktop_windows,+ display: desktop_display,+ } = desktop;+ let RawFileResources {+ read: raw_readable_paths,+ write: raw_writable_paths,+ } = files;+ let RawProcessResources {+ terminate: raw_terminable_pids,+ } = processes;+ let RawDriverConfigurationResources {+ changes: raw_configuration_changes,+ } = driver_configuration;++ if version != 1 {return Err(format!("unsupported session policy version {}; expected 1",- raw.version+ version));}- if !matches!(raw.mode.as_str(), "bounded" | "autonomous") {+ if !matches!(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)?;+ let expires_after = parse_duration(&expires_after)?;+ let idle_timeout = parse_duration(&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());}@@ -250,9 +563,9 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {"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)?;+ let allow = validate_tools("allow", allow.tools)?;+ let deny = validate_tools("deny", deny.tools)?;+ let ask = validate_tools("ask", ask.tools)?;if allow.is_empty() {return Err("session policy allow.tools must not be empty".to_owned());}@@ -271,7 +584,7 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {}}let mut existing_profiles = HashSet::new();- for profile in raw.resources.browser.existing_profiles {+ for profile in raw_existing_profiles {if profile.pid <= 0 || profile.window_id == 0 {return Err("browser existing_profiles entries require positive pid and window_id"@@ -286,7 +599,7 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {}}let mut browser_origins = HashSet::new();- for raw_origin in raw.resources.browser.origins {+ for raw_origin in raw_browser_origins {let origin = canonical_origin(&raw_origin)?;if origin != raw_origin.trim().trim_end_matches('/') {return Err(format!(@@ -297,6 +610,43 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {return Err(format!("browser origins repeats '{origin}'"));}}+ let desktop_applications =+ validate_positive_pids("desktop applications", raw_desktop_applications)?;+ let mut desktop_windows = HashSet::new();+ for window in raw_desktop_windows {+ if window.pid <= 0 || window.window_id == 0 {+ return Err("desktop windows entries require positive pid and window_id".to_owned());+ }+ if !desktop_windows.insert((window.pid, window.window_id)) {+ return Err(format!(+ "desktop windows repeats pid {} window {}",+ window.pid, window.window_id+ ));+ }+ }+ let readable_paths = validate_manifest_paths("files.read", raw_readable_paths)?;+ let writable_paths = validate_manifest_paths("files.write", raw_writable_paths)?;+ let terminable_pids = validate_positive_pids("processes.terminate", raw_terminable_pids)?;+ let mut configuration_changes = Vec::new();+ for change in raw_configuration_changes {+ let key = change.key.trim();+ if key.is_empty() || key == "capture_scope" {+ return Err(+ "driver_configuration changes require a non-retired config key".to_owned(),+ );+ }+ if configuration_changes+ .iter()+ .any(|(existing_key, existing_value)| {+ existing_key == key && existing_value == &change.value+ })+ {+ return Err(format!(+ "driver_configuration changes repeats exact change '{key}'"+ ));+ }+ configuration_changes.push((key.to_owned(), change.value));+ }if !browser_origins.is_empty() {const ORIGIN_BYPASS_TOOLS: &[&str] = &["page",@@ -339,6 +689,13 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {ask,existing_profiles,browser_origins,+ desktop_applications,+ desktop_windows,+ desktop_display,+ readable_paths,+ writable_paths,+ terminable_pids,+ configuration_changes,last_authorized_dispatch: Arc::new(Mutex::new(Instant::now())),idle_expired: Arc::new(AtomicBool::new(false)),})@@ -374,6 +731,116 @@ fn canonical_tool_name(tool: &str) -> &str {}}+#[cfg(feature = "yaml")]+fn validate_positive_pids(section: &str, pids: Vec<i64>) -> Result<HashSet<i64>, String> {+ let mut validated = HashSet::new();+ for pid in pids {+ if pid <= 0 {+ return Err(format!("{section} entries must be positive pids"));+ }+ if !validated.insert(pid) {+ return Err(format!("{section} repeats pid {pid}"));+ }+ }+ Ok(validated)+}++#[cfg(feature = "yaml")]+fn validate_manifest_paths(section: &str, paths: Vec<String>) -> Result<HashSet<String>, String> {+ let mut validated = HashSet::new();+ for raw in paths {+ let trimmed = raw.trim();+ let path = Path::new(trimmed);+ if !path.is_absolute()+ || path.components().any(|component| {+ matches!(+ component,+ std::path::Component::ParentDir | std::path::Component::CurDir+ )+ })+ {+ return Err(format!(+ "{section} path '{raw}' must be absolute and contain no '..' components"+ ));+ }+ if path.parent().is_none() {+ return Err(format!(+ "{section} path '{raw}' must not name a filesystem root"+ ));+ }+ if trimmed.len()+ > path+ .components()+ .next()+ .map_or(0, |root| root.as_os_str().len())+ && (trimmed.ends_with('/') || trimmed.ends_with('\\'))+ {+ return Err(format!(+ "{section} path '{raw}' must not end with a directory separator"+ ));+ }+ let normalized = path.to_string_lossy().into_owned();+ if normalized != trimmed {+ return Err(format!(+ "{section} path '{raw}' must use its normalized spelling"+ ));+ }+ let canonical = canonical_manifest_path(path).map_err(|error| {+ format!("{section} path '{raw}' could not be resolved safely: {error}")+ })?;+ if !validated.insert(canonical.clone()) {+ return Err(format!("{section} repeats path '{canonical}'"));+ }+ }+ Ok(validated)+}++#[cfg(feature = "yaml")]+fn canonical_manifest_path(path: &Path) -> Result<String, String> {+ if path.exists() {+ return std::fs::canonicalize(path)+ .map(|path| path.to_string_lossy().into_owned())+ .map_err(|error| error.to_string());+ }++ let mut existing = path;+ let mut suffix = Vec::new();+ while !existing.exists() {+ match std::fs::symlink_metadata(existing) {+ Ok(metadata) if metadata.file_type().is_symlink() => {+ return Err("path contains a broken symbolic link".to_owned())+ }+ Ok(_) => return Err("path contains an unavailable filesystem entry".to_owned()),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => return Err(error.to_string()),+ }+ let name = existing+ .file_name()+ .ok_or_else(|| "path has no existing ancestor".to_owned())?;+ suffix.push(name.to_os_string());+ existing = existing+ .parent()+ .ok_or_else(|| "path has no existing ancestor".to_owned())?;+ }+ let metadata = std::fs::symlink_metadata(existing).map_err(|error| error.to_string())?;+ if !metadata.is_dir() {+ return Err("existing ancestor is not a directory".to_owned());+ }+ let mut canonical = std::fs::canonicalize(existing).map_err(|error| error.to_string())?;+ for component in suffix.into_iter().rev() {+ let component_path = PathBuf::from(&component);+ if !matches!(+ component_path.components().next(),+ Some(Component::Normal(_))+ ) || component_path.components().count() != 1+ {+ return Err("path contains an unsafe component".to_owned());+ }+ canonical.push(component);+ }+ Ok(canonical.to_string_lossy().into_owned())+}+fn canonical_origin(raw: &str) -> Result<String, String> {let value = raw.trim();if value == "about:blank" {@@ -521,11 +988,269 @@ allow:manifest.authorize_browser_url("https://app.example.com/work?q=1").unwrap();+ manifest+ .authorize_protected_resource(+ "private_observation",+ &serde_json::json!({"kind": "window", "pid": 42, "window_id": 7}),+ )+ .unwrap();+ manifest+ .authorize_protected_resource(+ "desktop_input",+ &serde_json::json!({"kind": "application_input", "pid": 42}),+ )+ .unwrap();assert!(manifest.authorize_browser_url("https://evil.example/redirect").is_err());}+ #[cfg(feature = "yaml")]+ #[test]+ fn about_blank_uses_one_manifest_and_protected_resource_spelling() {+ let manifest = manifest(+ r#"+version: 1+mode: bounded+expires_after: 8h+idle_timeout: 30m+resources:+ browser:+ origins: [about:blank]+allow:+ tools: [browser_click]+"#,+ )+ .unwrap();++ manifest.authorize_browser_url("about:blank").unwrap();+ manifest+ .authorize_protected_resource(+ "browser_bound_input",+ &serde_json::json!({+ "kind": "authenticated_browser_tab",+ "live_origin": "about:blank"+ }),+ )+ .unwrap();+ }++ #[cfg(feature = "yaml")]+ #[test]+ fn desktop_escalation_requires_the_manifest_display_grant() {+ let without_display = manifest(+ r#"+version: 1+mode: bounded+expires_after: 8h+idle_timeout: 30m+resources: {}+allow:+ tools: [escalate_session]+"#,+ )+ .unwrap();+ assert!(without_display+ .authorize_protected_resource(+ "private_observation",+ &serde_json::json!({+ "kind": "session_capture_scope",+ "capture_scope": "desktop"+ }),+ )+ .is_err());++ let with_display = manifest(+ r#"+version: 1+mode: bounded+expires_after: 8h+idle_timeout: 30m+resources:+ desktop:+ display: true+allow:+ tools: [escalate_session]+"#,+ )+ .unwrap();+ with_display+ .authorize_protected_resource(+ "private_observation",+ &serde_json::json!({+ "kind": "session_capture_scope",+ "capture_scope": "desktop"+ }),+ )+ .unwrap();+ }++ #[cfg(feature = "yaml")]+ #[test]+ fn protected_resources_are_exactly_bounded_by_the_manifest() {+ let root = tempfile::tempdir().unwrap();+ let input = root.path().join("cua-input.txt");+ let output = root.path().join("cua-output.png");+ let outside = root.path().join("other.png");+ let input_yaml = serde_json::to_string(&input.to_string_lossy()).unwrap();+ let output_yaml = serde_json::to_string(&output.to_string_lossy()).unwrap();+ let canonical_input = canonical_manifest_path(&input).unwrap();+ let canonical_outside = canonical_manifest_path(&outside).unwrap();+ let loaded = manifest(&format!(+ r#"+version: 1+mode: bounded+expires_after: 8h+idle_timeout: 30m+resources:+ browser:+ origins: [https://app.example.com]+ desktop:+ applications: [42]+ windows:+ - pid: 42+ window_id: 7+ display: false+ files:+ read: [{}]+ write: [{}]+ processes:+ terminate: [42]+ driver_configuration:+ changes:+ - key: max_image_dimension+ value: 1200+allow:+ tools:+ - browser_click+ - browser_set_input_files+ - kill_app+ - set_config+"#,+ input_yaml, output_yaml+ ))+ .unwrap();++ loaded+ .authorize_protected_resource(+ "private_observation",+ &serde_json::json!({"kind": "window", "pid": 42, "window_id": 7}),+ )+ .unwrap();+ assert!(loaded+ .authorize_protected_resource(+ "private_observation",+ &serde_json::json!({"kind": "window", "pid": 42, "window_id": 8}),+ )+ .is_err());+ assert!(loaded+ .authorize_protected_resource(+ "private_observation",+ &serde_json::json!({"kind": "display"}),+ )+ .is_err());++ loaded+ .authorize_protected_resource(+ "browser_bound_input",+ &serde_json::json!({+ "kind": "authenticated_browser_tab",+ "live_origin": "https://app.example.com"+ }),+ )+ .unwrap();+ assert!(loaded+ .authorize_protected_resource(+ "browser_bound_input",+ &serde_json::json!({+ "kind": "authenticated_browser_tab",+ "live_origin": "https://other.example.com"+ }),+ )+ .is_err());++ loaded+ .authorize_protected_resource(+ "file_transfer_and_output",+ &serde_json::json!({+ "kind": "browser_upload",+ "canonical_paths": [canonical_input]+ }),+ )+ .unwrap();+ assert!(loaded+ .authorize_protected_resource(+ "file_transfer_and_output",+ &serde_json::json!({+ "kind": "screenshot_output",+ "canonical_output_path": canonical_outside+ }),+ )+ .is_err());++ loaded+ .authorize_protected_resource(+ "process_control",+ &serde_json::json!({+ "kind": "process_instance",+ "fingerprint": {"pid": 42}+ }),+ )+ .unwrap();+ assert!(loaded+ .authorize_protected_resource(+ "process_control",+ &serde_json::json!({+ "kind": "process_instance",+ "fingerprint": {"pid": 43}+ }),+ )+ .is_err());++ loaded+ .authorize_protected_resource(+ "driver_configuration",+ &serde_json::json!({+ "kind": "driver_configuration",+ "exact_changes": {"max_image_dimension": 1200}+ }),+ )+ .unwrap();+ assert!(loaded+ .authorize_protected_resource(+ "driver_configuration",+ &serde_json::json!({+ "kind": "driver_configuration",+ "exact_changes": {"max_image_dimension": 800}+ }),+ )+ .is_err());+ }++ #[cfg(feature = "yaml")]+ #[test]+ fn manifest_file_resources_reject_filesystem_roots() {+ let root = std::path::Path::new(std::path::MAIN_SEPARATOR_STR)+ .to_string_lossy()+ .into_owned();+ let error = validate_manifest_paths("files.write", vec![root]).unwrap_err();+ assert!(error.contains("must not name a filesystem root"));+ }++ #[cfg(all(feature = "yaml", unix))]+ #[test]+ fn manifest_file_resources_reject_broken_symlink_leaves() {+ use std::os::unix::fs::symlink;++ let dir = tempfile::tempdir().unwrap();+ let link = dir.path().join("broken-output");+ symlink(dir.path().join("missing-target"), &link).unwrap();+ let error =+ validate_manifest_paths("files.write", vec![link.to_string_lossy().into_owned()])+ .unwrap_err();+ assert!(error.contains("broken symbolic link"));+ }+#[cfg(feature = "yaml")]#[test]fn idle_timeout_is_terminal_and_origin_bypass_tools_are_rejected() {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.rsindex 229012b4c4..efd7e9781c 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@@ -30,6 +30,9 @@ tokio::task_local! {/// surface; caller arguments and public session labels cannot influence it.static DISPATCH_AUTHORIZATION_CONTEXT:Arc<crate::session_authorization::EffectiveAuthorizationContext>;+ /// Adapter-proved per-call facts inherited by nested registry dispatch.+ /// This value is never populated from the caller's public JSON object.+ static DISPATCH_TRUSTED_INVOCATION_EVIDENCE: TrustedInvocationEvidence;/// Opaque generation for runtime-owned mutable resources. Nested/// dispatches inherit this key, while public arguments can never select it.static DISPATCH_RUNTIME_SCOPE: String;@@ -372,6 +375,33 @@ pub trait Tool: Send + Sync {ProtectedResourceOwnership::UserOwned}+ /// Return implementation-attested identity for an exact protected+ /// resource. Callers cannot supply this value directly. Adapters that+ /// require process or browser identity fail closed when the concrete tool+ /// cannot produce it.+ async fn protected_resource_scope(+ &self,+ _adapter_id: &str,+ _args: &Value,+ ) -> Result<Option<Value>, String> {+ Ok(None)+ }++ /// Re-prove a protected scope immediately before a destructive dispatch.+ /// The default is conservative equality against a fresh attestation.+ async fn validate_protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ approved_scope: &Value,+ ) -> Result<(), String> {+ match self.protected_resource_scope(adapter_id, args).await? {+ Some(current) if current == *approved_scope => Ok(()),+ Some(_) => Err("the protected resource identity changed before dispatch".to_owned()),+ None => Err("the protected resource identity cannot be re-proven".to_owned()),+ }+ }+async fn invoke(&self, args: Value) -> ToolResult;}@@ -385,6 +415,75 @@ impl Drop for RuntimeCleanup {}}+/// Transport evidence admitted only through a trusted protocol adapter.+///+/// The values are extracted from the adapter's private argument envelope and+/// then removed before the canonical authorization boundary evaluates caller+/// input. Keeping the evidence separate lets the registry reject forged+/// underscore-prefixed fields without discarding facts proved by the host+/// transport.+#[derive(Clone, Debug, Default)]+pub struct TrustedInvocationEvidence {+ session_id: Option<String>,+ transport_session_id: Option<String>,+ browser_prepare_mcp_host_approved: bool,+ browser_download_mcp_host_approved: bool,+}++impl TrustedInvocationEvidence {+ #[doc(hidden)]+ pub fn extract_from_adapter_args(args: &mut Value) -> Self {+ let mut evidence = Self::default();+ if let Some(arguments) = args.as_object_mut() {+ evidence.session_id = arguments+ .remove("_session_id")+ .and_then(|value| value.as_str().map(str::to_owned))+ .filter(|value| !value.is_empty());+ evidence.transport_session_id = arguments+ .remove("_transport_session_id")+ .and_then(|value| value.as_str().map(str::to_owned))+ .filter(|value| !value.is_empty());+ evidence.browser_prepare_mcp_host_approved = arguments+ .remove(crate::browser::approval::MCP_HOST_APPROVAL_ARG)+ .and_then(|value| value.as_bool())+ == Some(true);+ evidence.browser_download_mcp_host_approved = arguments+ .remove(crate::browser::download::MCP_HOST_DOWNLOAD_APPROVAL_ARG)+ .and_then(|value| value.as_bool())+ == Some(true);+ }+ crate::tool_args::sanitize_reserved_args(args);+ evidence+ }++ fn apply_runtime_args(&self, args: &mut Value) {+ let Some(arguments) = args.as_object_mut() else {+ return;+ };+ if let Some(session) = self.session_id.as_ref() {+ arguments.insert("_session_id".to_owned(), Value::String(session.clone()));+ }+ if let Some(session) = self.transport_session_id.as_ref() {+ arguments.insert(+ "_transport_session_id".to_owned(),+ Value::String(session.clone()),+ );+ }+ if self.browser_prepare_mcp_host_approved {+ arguments.insert(+ crate::browser::approval::MCP_HOST_APPROVAL_ARG.to_owned(),+ Value::Bool(true),+ );+ }+ if self.browser_download_mcp_host_approved {+ arguments.insert(+ crate::browser::download::MCP_HOST_DOWNLOAD_APPROVAL_ARG.to_owned(),+ Value::Bool(true),+ );+ }+ }+}+/// Thread-safe collection of all registered tools.pub struct ToolRegistry {tools: HashMap<String, Box<dyn Tool>>,@@ -588,6 +687,9 @@ impl ToolRegistry {pub async fn invoke(&self, name: &str, args: Value) -> ToolResult {if let Ok(context) = DISPATCH_AUTHORIZATION_CONTEXT.try_with(Arc::clone) {let mut args = args;+ let evidence = DISPATCH_TRUSTED_INVOCATION_EVIDENCE+ .try_with(Clone::clone)+ .unwrap_or_default();crate::tool_args::sanitize_reserved_args(&mut args);if let Some(bound_session) = context.public_session() {let Some(arguments) = args.as_object_mut() else {@@ -610,7 +712,9 @@ impl ToolRegistry {Value::String(bound_session.to_owned()),);}- return self.invoke_authorized(name, args, context.as_ref()).await;+ return self+ .invoke_authorized(name, args, context.as_ref(), &evidence)+ .await;}let context = match crate::session_authorization::configured_registry().and_then(crate::session_authorization::SessionAuthorizationRegistry::legacy_context)@@ -625,6 +729,25 @@ impl ToolRegistry {self.invoke_with_context(name, args, context).await}+ /// Invoke from a protocol adapter that already stripped caller-owned+ /// reserved fields before adding its own transport evidence.+ #[doc(hidden)]+ pub async fn invoke_from_trusted_adapter(&self, name: &str, mut args: Value) -> ToolResult {+ let evidence = TrustedInvocationEvidence::extract_from_adapter_args(&mut args);+ let context = match crate::session_authorization::configured_registry()+ .and_then(crate::session_authorization::SessionAuthorizationRegistry::legacy_context)+ {+ Ok(context) => context,+ Err(error) => {+ return permission_denied_result(format!(+ "authorization configuration is invalid: {error}"+ ))+ }+ };+ self.invoke_with_context_and_evidence(name, args, context, evidence)+ .await+ }+/// Invoke through an immutable context chosen by the trusted runtime host.////// The task-local scope deliberately propagates the same authority through@@ -635,15 +758,36 @@ impl ToolRegistry {name: &str,args: Value,context: Arc<crate::session_authorization::EffectiveAuthorizationContext>,+ ) -> ToolResult {+ self.invoke_with_context_and_evidence(+ name,+ args,+ context,+ TrustedInvocationEvidence::default(),+ )+ .await+ }++ #[doc(hidden)]+ pub async fn invoke_with_context_and_evidence(+ &self,+ name: &str,+ args: Value,+ context: Arc<crate::session_authorization::EffectiveAuthorizationContext>,+ evidence: TrustedInvocationEvidence,) -> ToolResult {let runtime_scope = context.runtime_scope_key();DISPATCH_RUNTIME_SCOPE.scope(runtime_scope, async {- DISPATCH_AUTHORIZATION_CONTEXT- .scope(- context.clone(),- self.invoke_authorized(name, args, context.as_ref()),- )+ DISPATCH_TRUSTED_INVOCATION_EVIDENCE+ .scope(evidence.clone(), async {+ DISPATCH_AUTHORIZATION_CONTEXT+ .scope(+ context.clone(),+ self.invoke_authorized(name, args, context.as_ref(), &evidence),+ )+ .await+ }).await}).await@@ -654,7 +798,15 @@ impl ToolRegistry {name: &str,mut args: Value,context: &crate::session_authorization::EffectiveAuthorizationContext,+ evidence: &TrustedInvocationEvidence,) -> ToolResult {+ // This function is the canonical native dispatch boundary. Keep+ // transport-side stripping as defense in depth, but never trust a+ // future same-process embedder to remember it: underscore-prefixed+ // fields carry registry-internal attestations and must not be+ // caller-forgeable here.+ crate::tool_args::sanitize_reserved_args(&mut args);+// Deprecated alias: `type_text_chars` → `type_text`. Swift's// ToolRegistry.swift keeps the same alias (with stderr warning) for// backwards compatibility with hermes-agent builds that still emit@@ -693,7 +845,7 @@ impl ToolRegistry {// but mutable core/platform state must not be keyed by that// caller-chosen label alone. Translate it only after authorization so// policy and manifests continue to evaluate the public request.- let runtime_prefix = namespace_runtime_args(&mut args, context);+ let runtime_prefix = namespace_runtime_args(&mut args, context, evidence);let runtime_session = args.get("session").and_then(Value::as_str)@@ -713,6 +865,38 @@ impl ToolRegistry {return result;}+ let active_adapters =+ crate::authorization::enforcement_adapters_for_call(resolved_name, &public_args);+ let has_adapter = |id: &str| active_adapters.iter().any(|adapter| adapter.id == id);++ // Raw/legacy page mutations have no exact browser binding. They are+ // not grantable through a model-time confirmation: only a trusted+ // host's unrestricted launch acknowledgement admits them, and the+ // legacy feature flag still applies downstream.+ if has_adapter("browser_unbounded_script")+ && context.mode() != crate::authorization::PermissionMode::Unrestricted+ {+ return protected_refusal(+ "unbounded_operation_requires_unrestricted",+ "legacy page mutation is unbounded and requires unrestricted mode with trusted launch-time risk acceptance",+ );+ }++ // Cua may report OS permission state, but an agent tool call never+ // manufactures a protected system prompt. Host setup happens outside+ // the model/tool stream in every permission mode.+ if has_adapter("os_permission_prompt")+ && tool+ .protected_resource_ownership("os_permission_prompt", &public_args)+ .await+ != ProtectedResourceOwnership::DriverOwned+ {+ return protected_refusal(+ "os_permission_prompt_requires_trusted_host",+ "operating-system permission prompts must be initiated by a trusted host outside the agent tool path; call check_permissions with prompt=false to inspect state",+ );+ }+// Resource adapters run at the same canonical boundary as policy and// manifest admission, after session capture-scope validation but// before recording or the platform tool can observe user state. This@@ -733,9 +917,7 @@ impl ToolRegistry {.is_driver_owned_pid(public_session, pid)})});- if crate::authorization::enforcement_adapters_for_call(resolved_name, &public_args)- .iter()- .any(|adapter| adapter.id == "private_observation")+ if has_adapter("private_observation")&& !runtime_proves_driver_owned&& tool.protected_resource_ownership("private_observation", &public_args)@@ -744,6 +926,7 @@ impl ToolRegistry {{if let Err(error) = self.authorize_private_observation(+ tool.as_ref(),resolved_name,&public_args,context,@@ -754,10 +937,7 @@ impl ToolRegistry {return protected_consent_refusal(error);}}- if crate::authorization::enforcement_adapters_for_call(resolved_name, &public_args)- .iter()- .any(|adapter| adapter.id == "file_transfer_and_output")- {+ if has_adapter("file_transfer_and_output") {if let Err(refusal) = self.authorize_file_transfer(resolved_name,@@ -773,14 +953,10 @@ impl ToolRegistry {// approval. Dispatch must receive those same values, while the// private session namespace remains transport-internal.args = public_args.clone();- namespace_runtime_args(&mut args, context);+ namespace_runtime_args(&mut args, context, evidence);}let recording_args = recording_args_for(resolved_name, &public_args);- if crate::authorization::enforcement_adapters_for_call(resolved_name, &public_args)- .iter()- .any(|adapter| adapter.id == "desktop_input")- && !runtime_proves_driver_owned- {+ if has_adapter("desktop_input") && !runtime_proves_driver_owned {if let Err(error) = self.authorize_desktop_input(resolved_name,@@ -793,6 +969,128 @@ impl ToolRegistry {return protected_consent_refusal(error);}}+ if has_adapter("browser_consequential_action")+ && tool+ .protected_resource_ownership("browser_consequential_action", &public_args)+ .await+ != ProtectedResourceOwnership::DriverOwned+ {+ let approved_scope = match self+ .authorize_attested_resource(+ tool.as_ref(),+ "browser_consequential_action",+ crate::authorization::RiskClass::R3,+ &public_args,+ context,+ runtime_session.as_deref(),+ "Allow Cua to resolve this exact page-owned browser dialog",+ Duration::from_secs(5 * 60),+ Duration::from_secs(30 * 60),+ )+ .await+ {+ Ok(scope) => scope,+ Err(refusal) => return refusal,+ };+ if let Err(refusal) = self+ .validate_attested_resource(+ tool.as_ref(),+ "browser_consequential_action",+ &public_args,+ context,+ runtime_session.as_deref(),+ &approved_scope,+ )+ .await+ {+ return refusal;+ }+ }+ if has_adapter("browser_bound_input")+ && tool+ .protected_resource_ownership("browser_bound_input", &public_args)+ .await+ != ProtectedResourceOwnership::DriverOwned+ {+ let approved_scope = match self+ .authorize_attested_resource(+ tool.as_ref(),+ "browser_bound_input",+ crate::authorization::RiskClass::R2,+ &public_args,+ context,+ runtime_session.as_deref(),+ "Allow Cua to control this exact authenticated browser tab",+ Duration::from_secs(30 * 60),+ Duration::from_secs(8 * 60 * 60),+ )+ .await+ {+ Ok(scope) => scope,+ Err(refusal) => return refusal,+ };+ if let Err(refusal) = self+ .validate_attested_resource(+ tool.as_ref(),+ "browser_bound_input",+ &public_args,+ context,+ runtime_session.as_deref(),+ &approved_scope,+ )+ .await+ {+ return refusal;+ }+ }+ if has_adapter("process_control") && !runtime_proves_driver_owned {+ let approved_scope = match self+ .authorize_attested_resource(+ tool.as_ref(),+ "process_control",+ crate::authorization::RiskClass::R3,+ &public_args,+ context,+ runtime_session.as_deref(),+ "Allow Cua to force-terminate this exact process instance",+ Duration::from_secs(2 * 60),+ Duration::from_secs(10 * 60),+ )+ .await+ {+ Ok(scope) => scope,+ Err(refusal) => return refusal,+ };+ if let Err(refusal) = self+ .validate_attested_resource(+ tool.as_ref(),+ "process_control",+ &public_args,+ context,+ runtime_session.as_deref(),+ &approved_scope,+ )+ .await+ {+ return refusal;+ }+ if context.mode() != crate::authorization::PermissionMode::Unrestricted {+ args["_protected_process_fingerprint"] = approved_scope["fingerprint"].clone();+ }+ }+ if has_adapter("driver_configuration") {+ if let Err(refusal) = self+ .authorize_driver_configuration(+ tool.as_ref(),+ &public_args,+ context,+ runtime_session.as_deref(),+ )+ .await+ {+ return refusal;+ }+ }// Capture start time for recording timestamps only after validation.let start_ms = now_ms();@@ -915,6 +1213,7 @@ impl ToolRegistry {async fn authorize_private_observation(&self,+ tool: &dyn Tool,tool_name: &str,args: &Value,context: &crate::session_authorization::EffectiveAuthorizationContext,@@ -923,15 +1222,16 @@ impl ToolRegistry {if context.mode() == crate::authorization::PermissionMode::Unrestricted {return Ok(());}+ let browser_scope = tool+ .protected_resource_scope("private_observation", args)+ .await+ .map_err(crate::consent::ConsentError::Provider)?;let browser_target = args.get("target_id").and_then(Value::as_str);let browser_tab = args.get("tab_id").and_then(Value::as_str);- let (resource, summary) = if let Some(target_id) = browser_target {+ let (resource, summary) = if let Some(resource) = browser_scope {+ let target_id = browser_target.unwrap_or("unknown");(- serde_json::json!({- "kind": "browser_target",- "target_id": target_id,- "tab_id": browser_tab,- }),+ resource,match browser_tab {Some(tab_id) => {format!("Allow Cua to observe browser target {target_id}, tab {tab_id}")@@ -939,6 +1239,18 @@ impl ToolRegistry {None => format!("Allow Cua to observe browser target {target_id}"),},)+ } else if browser_target.is_some() {+ return Err(crate::consent::ConsentError::Provider(+ "browser observation did not attest a live top-level origin".to_owned(),+ ));+ } else if tool_name == "escalate_session" {+ (+ serde_json::json!({+ "kind": "session_capture_scope",+ "capture_scope": "desktop",+ }),+ "Allow Cua to expand this session's observation scope".to_owned(),+ )} else if let Some(window_id) = args.get("window_id").and_then(Value::as_u64) {let pid = args.get("pid").and_then(Value::as_i64);(@@ -962,14 +1274,6 @@ impl ToolRegistry {}),format!("Allow Cua to observe process {pid}"),)- } else if tool_name == "escalate_session" {- (- serde_json::json!({- "kind": "session_capture_scope",- "capture_scope": args.get("capture_scope"),- }),- "Allow Cua to expand this session's observation scope".to_owned(),- )} else if tool_name == "start_recording"&& args.get("record_video").and_then(Value::as_bool) != Some(true){@@ -1265,6 +1569,172 @@ impl ToolRegistry {.map_err(protected_consent_refusal)?;Ok(())}++ #[allow(clippy::too_many_arguments)]+ async fn authorize_attested_resource(+ &self,+ tool: &dyn Tool,+ adapter_id: &str,+ risk_class: crate::authorization::RiskClass,+ args: &Value,+ context: &crate::session_authorization::EffectiveAuthorizationContext,+ lifecycle_session: Option<&str>,+ human_summary: &str,+ idle_ttl: Duration,+ absolute_ttl: Duration,+ ) -> Result<Value, ToolResult> {+ if context.mode() == crate::authorization::PermissionMode::Unrestricted {+ return Ok(Value::Null);+ }+ let resource = tool+ .protected_resource_scope(adapter_id, args)+ .await+ .map_err(|message| protected_scope_refusal(&message))?+ .ok_or_else(|| {+ protected_scope_refusal(+ "the concrete tool cannot attest an exact protected resource scope",+ )+ })?;+ self.protected_resource_grants+ .authorize(+ context,+ adapter_id,+ risk_class,+ lifecycle_session,+ resource.clone(),+ human_summary,+ idle_ttl,+ absolute_ttl,+ )+ .await+ .map_err(protected_consent_refusal)?;+ Ok(resource)+ }++ async fn validate_attested_resource(+ &self,+ tool: &dyn Tool,+ adapter_id: &str,+ args: &Value,+ context: &crate::session_authorization::EffectiveAuthorizationContext,+ lifecycle_session: Option<&str>,+ approved_scope: &Value,+ ) -> Result<(), ToolResult> {+ if context.mode() == crate::authorization::PermissionMode::Unrestricted {+ return Ok(());+ }+ if let Err(message) = tool+ .validate_protected_resource_scope(adapter_id, args, approved_scope)+ .await+ {+ if let Some(grant) = self.protected_resource_grants.revoke_resource(+ context,+ lifecycle_session,+ adapter_id,+ approved_scope,+ ) {+ self.approval_broker.revoke(&grant).await;+ }+ return Err(protected_refusal(+ "protected_resource_scope_stale",+ &message,+ ));+ }+ Ok(())+ }++ async fn authorize_driver_configuration(+ &self,+ tool: &dyn Tool,+ args: &Value,+ context: &crate::session_authorization::EffectiveAuthorizationContext,+ lifecycle_session: Option<&str>,+ ) -> Result<(), ToolResult> {+ if args.get("capture_scope").is_some()+ || args.get("key").and_then(Value::as_str) == Some("capture_scope")+ {+ return Err(+ ToolResult::error(+ "config key 'capture_scope' is retired; pass capture_scope=auto|window|desktop to start_session",+ )+ .with_structured(serde_json::json!({+ "code": "config_key_retired",+ "key": "capture_scope",+ "replacement": "start_session.capture_scope",+ })),+ );+ }+ if context.mode() == crate::authorization::PermissionMode::Unrestricted {+ return Ok(());+ }+ let properties = tool+ .def()+ .input_schema+ .get("properties")+ .and_then(Value::as_object)+ .ok_or_else(|| protected_scope_refusal("set_config has no reviewable input schema"))?;+ let object = args+ .as_object()+ .ok_or_else(|| protected_scope_refusal("set_config arguments must be an object"))?;+ for key in object.keys() {+ if key == "session" || key.starts_with('_') {+ continue;+ }+ if !properties.contains_key(key) {+ return Err(protected_scope_refusal(&format!(+ "set_config field '{key}' is not present in the concrete tool schema"+ )));+ }+ }++ let mut exact = serde_json::Map::new();+ if let Some(key) = args.get("key").and_then(Value::as_str) {+ if matches!(key, "key" | "value" | "session" | "_session_id")+ || !properties.contains_key(key)+ {+ return Err(protected_scope_refusal(&format!(+ "set_config key '{key}' is not present in the concrete tool schema"+ )));+ }+ let value = args+ .get("value")+ .ok_or_else(|| protected_scope_refusal("set_config key requires an exact value"))?;+ exact.insert(key.to_owned(), value.clone());+ } else if args.get("value").is_some() {+ return Err(protected_scope_refusal(+ "set_config value requires an exact key",+ ));+ }+ for (key, value) in object {+ if matches!(key.as_str(), "session" | "key" | "value") || key.starts_with('_') {+ continue;+ }+ exact.insert(key.clone(), value.clone());+ }+ if exact.is_empty() {+ return Err(protected_scope_refusal(+ "set_config did not contain a reviewed configuration field",+ ));+ }+ let keys = exact.keys().cloned().collect::<Vec<_>>().join(", ");+ self.protected_resource_grants+ .authorize(+ context,+ "driver_configuration",+ crate::authorization::RiskClass::R2,+ lifecycle_session,+ serde_json::json!({+ "kind": "driver_configuration",+ "exact_changes": exact,+ }),+ &format!("Allow Cua to change exact driver configuration field(s): {keys}"),+ Duration::from_secs(5 * 60),+ Duration::from_secs(30 * 60),+ )+ .await+ .map_err(protected_consent_refusal)?;+ Ok(())+ }}fn required_path_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, ToolResult> {@@ -1359,6 +1829,24 @@ fn canonical_proposed_path(raw: &str) -> Result<String, ToolResult> {let mut existing = path.as_path();let mut suffix = Vec::new();while !existing.exists() {+ match std::fs::symlink_metadata(existing) {+ Ok(metadata) if metadata.file_type().is_symlink() => {+ return Err(protected_scope_refusal(+ "the output path contains a broken symbolic link",+ ))+ }+ Ok(_) => {+ return Err(protected_scope_refusal(+ "the output path contains an unavailable filesystem entry",+ ))+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(_) => {+ return Err(protected_scope_refusal(+ "the output path could not be inspected safely",+ ))+ }+ }let name = existing.file_name().ok_or_else(|| protected_scope_refusal("the output path has no existing ancestor"))?;@@ -1416,11 +1904,24 @@ fn is_physical_desktop_action(tool: &str) -> bool {fn namespace_runtime_args(args: &mut Value,context: &crate::session_authorization::EffectiveAuthorizationContext,+ evidence: &TrustedInvocationEvidence,) -> String {let runtime_prefix = format!("__cua_runtime_{}:", context.runtime_scope_key());+ if !args.is_object() {+ return runtime_prefix;+ }+ evidence.apply_runtime_args(args);let Some(arguments) = args.as_object_mut() else {return runtime_prefix;};+ if !arguments.contains_key("_transport_session_id") {+ if let Some(session) = context.transport_session() {+ arguments.insert(+ "_transport_session_id".to_owned(),+ Value::String(session.to_owned()),+ );+ }+ }// The registry is the first boundary shared by every transport and the// direct SDK. Transport adapters may already have injected `_session_id`,// but a direct runtime call only carries the public `session` field. Mint@@ -1437,7 +1938,12 @@ fn namespace_runtime_args(arguments.insert("_session_id".to_owned(), Value::String(session));}}- for key in ["session", "_session_id", "cursor_id"] {+ for key in [+ "session",+ "_session_id",+ "_transport_session_id",+ "cursor_id",+ ] {let Some(public) = arguments.get(key).and_then(Value::as_str)@@ -1504,7 +2010,7 @@ fn restore_public_runtime_value(value: &mut Value, runtime_prefix: &str) -> boolmod runtime_isolation_tests {use super::{canonical_proposed_path, desktop_action_coordinator, namespace_runtime_args,- restore_public_runtime_result, DISPATCH_RUNTIME_SCOPE,+ restore_public_runtime_result, TrustedInvocationEvidence, DISPATCH_RUNTIME_SCOPE,};use crate::{authorization::PermissionMode,@@ -1563,17 +2069,60 @@ mod runtime_isolation_tests {def: super::ToolDef,}+ struct AttestedProbe {+ hits: Arc<AtomicUsize>,+ scope: serde_json::Value,+ stale_before_dispatch: bool,+ def: super::ToolDef,+ }+#[async_trait::async_trait]- impl super::Tool for ArgumentProbe {+ impl super::Tool for AttestedProbe {fn def(&self) -> &super::ToolDef {&self.def}- async fn invoke(&self, args: serde_json::Value) -> crate::protocol::ToolResult {- self.hits.fetch_add(1, Ordering::SeqCst);- self.last_args.lock().unwrap().replace(args.clone());- crate::protocol::ToolResult::text("file operation ran")- .with_structured(serde_json::json!({"received": args}))+ async fn protected_resource_scope(+ &self,+ _adapter_id: &str,+ _args: &serde_json::Value,+ ) -> Result<Option<serde_json::Value>, String> {+ Ok(Some(self.scope.clone()))+ }++ async fn validate_protected_resource_scope(+ &self,+ _adapter_id: &str,+ _args: &serde_json::Value,+ approved_scope: &serde_json::Value,+ ) -> Result<(), String> {+ if self.stale_before_dispatch {+ return Err("synthetic process identity changed".to_owned());+ }+ if *approved_scope == self.scope {+ Ok(())+ } else {+ Err("synthetic scope mismatch".to_owned())+ }+ }++ async fn invoke(&self, _args: serde_json::Value) -> crate::protocol::ToolResult {+ self.hits.fetch_add(1, Ordering::SeqCst);+ crate::protocol::ToolResult::text("attested operation ran")+ }+ }++ #[async_trait::async_trait]+ impl super::Tool for ArgumentProbe {+ fn def(&self) -> &super::ToolDef {+ &self.def+ }++ async fn invoke(&self, args: serde_json::Value) -> crate::protocol::ToolResult {+ self.hits.fetch_add(1, Ordering::SeqCst);+ self.last_args.lock().unwrap().replace(args.clone());+ crate::protocol::ToolResult::text("file operation ran")+ .with_structured(serde_json::json!({"received": args}))}}@@ -1627,12 +2176,20 @@ mod runtime_isolation_tests {fn observation_registry(provider: Option<Arc<dyn ProtectedConsentProvider>>,hits: Arc<AtomicUsize>,+ ) -> Arc<super::ToolRegistry> {+ observation_registry_for("get_window_state", provider, hits)+ }++ fn observation_registry_for(+ name: &str,+ provider: Option<Arc<dyn ProtectedConsentProvider>>,+ hits: Arc<AtomicUsize>,) -> Arc<super::ToolRegistry> {let mut registry = super::ToolRegistry::new_with_protected_consent_provider(provider);registry.register(Box::new(ObservationProbe {hits,def: super::ToolDef {- name: "get_window_state".into(),+ name: name.to_owned(),description: "test observation".into(),input_schema: serde_json::json!({"type": "object"}),read_only: true,@@ -1686,6 +2243,69 @@ mod runtime_isolation_tests {Arc::new(registry)}+ fn attested_registry(+ name: &str,+ provider: Option<Arc<dyn ProtectedConsentProvider>>,+ hits: Arc<AtomicUsize>,+ stale_before_dispatch: bool,+ ) -> Arc<super::ToolRegistry> {+ let mut registry = super::ToolRegistry::new_with_protected_consent_provider(provider);+ registry.register(Box::new(AttestedProbe {+ hits,+ scope: serde_json::json!({+ "kind": "synthetic_attested_resource",+ "identity": "exact-1",+ }),+ stale_before_dispatch,+ def: super::ToolDef {+ name: name.to_owned(),+ description: "test attested protected resource".into(),+ input_schema: serde_json::json!({"type": "object"}),+ read_only: false,+ destructive: name == "kill_app",+ idempotent: false,+ open_world: name.starts_with("browser_"),+ },+ }));+ Arc::new(registry)+ }++ fn argument_registry(+ name: &str,+ provider: Option<Arc<dyn ProtectedConsentProvider>>,+ hits: Arc<AtomicUsize>,+ ) -> Arc<super::ToolRegistry> {+ let mut registry = super::ToolRegistry::new_with_protected_consent_provider(provider);+ let input_schema = if name == "set_config" {+ serde_json::json!({+ "type": "object",+ "properties": {+ "key": {"type": "string"},+ "value": {},+ "max_image_dimension": {"type": "integer"},+ "experimental_pip": {"type": "boolean"}+ },+ "additionalProperties": false+ })+ } else {+ serde_json::json!({"type": "object"})+ };+ registry.register(Box::new(ArgumentProbe {+ hits,+ last_args: Arc::new(Mutex::new(None)),+ def: super::ToolDef {+ name: name.to_owned(),+ description: "test typed operation".into(),+ input_schema,+ read_only: false,+ destructive: false,+ idempotent: false,+ open_world: name == "page",+ },+ }));+ Arc::new(registry)+ }+#[async_trait::async_trait]impl super::Tool for ReplayProbe {fn def(&self) -> &super::ToolDef {@@ -1966,6 +2586,339 @@ mod runtime_isolation_tests {);}+ #[tokio::test]+ async fn legacy_page_mutations_require_trusted_unrestricted_launch_acceptance() {+ let hits = Arc::new(AtomicUsize::new(0));+ let registry = argument_registry("page", None, hits.clone());+ let denied = registry+ .invoke_with_context(+ "page",+ serde_json::json!({+ "action": "execute_javascript",+ "pid": 42,+ "window_id": 7,+ "javascript": "1 + 1",+ "session": "legacy"+ }),+ standard_context(),+ )+ .await;+ assert_eq!(hits.load(Ordering::SeqCst), 0);+ assert_eq!(+ denied+ .structured_content+ .as_ref()+ .and_then(|value| value.pointer("/refusal/code"))+ .and_then(serde_json::Value::as_str),+ Some("unbounded_operation_requires_unrestricted")+ );++ let allowed = registry+ .invoke_with_context(+ "page",+ serde_json::json!({+ "action": "execute_javascript",+ "pid": 42,+ "window_id": 7,+ "javascript": "1 + 1",+ "session": "legacy"+ }),+ unrestricted_context(),+ )+ .await;+ assert_ne!(allowed.is_error, Some(true));+ assert_eq!(hits.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn os_permission_prompt_is_never_agent_controllable() {+ let hits = Arc::new(AtomicUsize::new(0));+ let registry = argument_registry("check_permissions", None, hits.clone());+ for context in [standard_context(), unrestricted_context()] {+ let denied = registry+ .invoke_with_context(+ "check_permissions",+ serde_json::json!({"prompt": true, "session": "permissions"}),+ context,+ )+ .await;+ assert_eq!(+ denied+ .structured_content+ .as_ref()+ .and_then(|value| value.pointer("/refusal/code"))+ .and_then(serde_json::Value::as_str),+ Some("os_permission_prompt_requires_trusted_host")+ );+ }+ let inspected = registry+ .invoke_with_context(+ "check_permissions",+ serde_json::json!({"prompt": false, "session": "permissions"}),+ standard_context(),+ )+ .await;+ assert_ne!(inspected.is_error, Some(true));+ let inspected_default = registry+ .invoke_with_context(+ "check_permissions",+ serde_json::json!({"session": "permissions"}),+ standard_context(),+ )+ .await;+ assert_ne!(inspected_default.is_error, Some(true));+ assert_eq!(hits.load(Ordering::SeqCst), 2);+ }++ #[tokio::test]+ async fn typed_browser_grants_require_attested_exact_resources() {+ let denied_hits = Arc::new(AtomicUsize::new(0));+ let denied = attested_registry("browser_click", None, denied_hits.clone(), false)+ .invoke_with_context(+ "browser_click",+ serde_json::json!({+ "target_id": "target-1",+ "tab_id": "tab-1",+ "session": "browser"+ }),+ standard_context(),+ )+ .await;+ assert_eq!(denied_hits.load(Ordering::SeqCst), 0);+ assert_eq!(+ denied+ .structured_content+ .as_ref()+ .and_then(|value| value.pointer("/refusal/code"))+ .and_then(serde_json::Value::as_str),+ Some("protected_consent_required")+ );++ let hits = Arc::new(AtomicUsize::new(0));+ let provider = Arc::new(AcceptingProvider {+ requests: AtomicUsize::new(0),+ });+ let registry =+ attested_registry("browser_click", Some(provider.clone()), hits.clone(), false);+ let context = standard_context();+ for _ in 0..2 {+ let result = registry+ .invoke_with_context(+ "browser_click",+ serde_json::json!({+ "target_id": "target-1",+ "tab_id": "tab-1",+ "session": "browser"+ }),+ context.clone(),+ )+ .await;+ assert_ne!(result.is_error, Some(true));+ }+ assert_eq!(hits.load(Ordering::SeqCst), 2);+ assert_eq!(provider.requests.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn process_identity_is_reproved_after_consent_before_termination() {+ let hits = Arc::new(AtomicUsize::new(0));+ let provider = Arc::new(AcceptingProvider {+ requests: AtomicUsize::new(0),+ });+ let registry = attested_registry("kill_app", Some(provider.clone()), hits.clone(), true);+ let result = registry+ .invoke_with_context(+ "kill_app",+ serde_json::json!({"pid": 424242, "session": "process"}),+ standard_context(),+ )+ .await;+ assert_eq!(hits.load(Ordering::SeqCst), 0);+ assert_eq!(provider.requests.load(Ordering::SeqCst), 1);+ assert_eq!(+ result+ .structured_content+ .as_ref()+ .and_then(|value| value.pointer("/refusal/code"))+ .and_then(serde_json::Value::as_str),+ Some("protected_resource_scope_stale")+ );+ }++ #[tokio::test]+ async fn browser_identity_is_reproved_after_consent_before_input() {+ let hits = Arc::new(AtomicUsize::new(0));+ let provider = Arc::new(AcceptingProvider {+ requests: AtomicUsize::new(0),+ });+ let registry =+ attested_registry("browser_click", Some(provider.clone()), hits.clone(), true);+ let result = registry+ .invoke_with_context(+ "browser_click",+ serde_json::json!({+ "target_id": "target-1",+ "tab_id": "tab-1",+ "session": "browser"+ }),+ standard_context(),+ )+ .await;+ assert_eq!(hits.load(Ordering::SeqCst), 0);+ assert_eq!(provider.requests.load(Ordering::SeqCst), 1);+ assert_eq!(+ result+ .structured_content+ .as_ref()+ .and_then(|value| value.pointer("/refusal/code"))+ .and_then(serde_json::Value::as_str),+ Some("protected_resource_scope_stale")+ );+ }++ #[tokio::test]+ async fn browser_observation_without_a_live_origin_attestation_fails_closed() {+ let hits = Arc::new(AtomicUsize::new(0));+ let provider = Arc::new(AcceptingProvider {+ requests: AtomicUsize::new(0),+ });+ let registry =+ observation_registry_for("get_browser_state", Some(provider.clone()), hits.clone());+ let result = registry+ .invoke_with_context(+ "get_browser_state",+ serde_json::json!({+ "target_id": "caller-supplied-target",+ "tab_id": "caller-supplied-tab",+ "session": "browser"+ }),+ standard_context(),+ )+ .await;+ assert_eq!(result.is_error, Some(true));+ assert_eq!(hits.load(Ordering::SeqCst), 0);+ assert_eq!(provider.requests.load(Ordering::SeqCst), 0);+ assert!(result+ .content+ .iter()+ .any(|item| format!("{item:?}").contains("live top-level origin")));+ }++ #[tokio::test]+ async fn invoke_with_context_strips_reserved_caller_arguments_at_the_registry_boundary() {+ let hits = Arc::new(AtomicUsize::new(0));+ let last_args = Arc::new(Mutex::new(None));+ let registry = file_registry(None, hits.clone(), last_args.clone());+ let result = registry+ .invoke_with_context(+ "browser_set_input_files",+ serde_json::json!({+ "_protected_process_fingerprint": {"pid": 1},+ "_session_id": "forged",+ "files": ["/does/not/matter"]+ }),+ unrestricted_context(),+ )+ .await;+ assert_ne!(result.is_error, Some(true));+ assert_eq!(hits.load(Ordering::SeqCst), 1);+ let received = last_args.lock().unwrap().clone().unwrap();+ assert!(received.get("_protected_process_fingerprint").is_none());+ assert!(received.get("_session_id").is_none());+ }++ #[tokio::test]+ async fn trusted_adapter_evidence_is_restored_only_after_caller_fields_are_stripped() {+ let hits = Arc::new(AtomicUsize::new(0));+ let last_args = Arc::new(Mutex::new(None));+ let registry = file_registry(None, hits.clone(), last_args.clone());+ let mut args = serde_json::json!({+ "session": "public",+ "_session_id": "trusted-owner",+ "_transport_session_id": "transport-a",+ "_cua_browser_prepare_mcp_host_approved": true,+ "_cua_browser_download_mcp_host_approved": true,+ "_protected_process_fingerprint": {"pid": 1},+ "files": ["/does/not/matter"]+ });+ let evidence = TrustedInvocationEvidence::extract_from_adapter_args(&mut args);+ assert!(args+ .as_object()+ .unwrap()+ .keys()+ .all(|key| !key.starts_with('_')));++ let result = registry+ .invoke_with_context_and_evidence(+ "browser_set_input_files",+ args,+ unrestricted_context(),+ evidence,+ )+ .await;+ assert_ne!(result.is_error, Some(true));+ assert_eq!(hits.load(Ordering::SeqCst), 1);+ let received = last_args.lock().unwrap().clone().unwrap();+ assert!(received+ .get("_session_id")+ .and_then(serde_json::Value::as_str)+ .is_some_and(|value| value.ends_with(":trusted-owner")));+ assert!(received+ .get("_transport_session_id")+ .and_then(serde_json::Value::as_str)+ .is_some_and(|value| value.ends_with(":transport-a")));+ assert_eq!(+ received["_cua_browser_prepare_mcp_host_approved"],+ serde_json::Value::Bool(true)+ );+ assert_eq!(+ received["_cua_browser_download_mcp_host_approved"],+ serde_json::Value::Bool(true)+ );+ assert!(received.get("_protected_process_fingerprint").is_none());+ }++ #[tokio::test]+ async fn driver_configuration_grants_bind_exact_changes() {+ let hits = Arc::new(AtomicUsize::new(0));+ let provider = Arc::new(AcceptingProvider {+ requests: AtomicUsize::new(0),+ });+ let registry = argument_registry("set_config", Some(provider.clone()), hits.clone());+ let context = standard_context();+ for dimension in [800, 800, 1200] {+ let result = registry+ .invoke_with_context(+ "set_config",+ serde_json::json!({+ "key": "max_image_dimension",+ "value": dimension,+ "session": "config"+ }),+ context.clone(),+ )+ .await;+ assert_ne!(result.is_error, Some(true));+ }+ assert_eq!(hits.load(Ordering::SeqCst), 3);+ assert_eq!(provider.requests.load(Ordering::SeqCst), 2);++ let unknown = registry+ .invoke_with_context(+ "set_config",+ serde_json::json!({+ "key": "future_unreviewed_setting",+ "value": true,+ "session": "config"+ }),+ context,+ )+ .await;+ assert_eq!(unknown.is_error, Some(true));+ assert_eq!(hits.load(Ordering::SeqCst), 3);+ assert_eq!(provider.requests.load(Ordering::SeqCst), 2);+ }+#[test]fn proposed_output_scope_canonicalizes_the_existing_ancestor_without_creating_output() {let root = tempfile::tempdir().unwrap();@@ -2080,7 +3033,11 @@ mod runtime_isolation_tests {"_session_id": "shared-session","cursor_id": "shared-cursor",});- let prefix = namespace_runtime_args(&mut args, context.as_ref());+ let prefix = namespace_runtime_args(+ &mut args,+ context.as_ref(),+ &TrustedInvocationEvidence::default(),+ );assert_eq!(args["session"], format!("{prefix}shared-session"));assert_eq!(args["_session_id"], format!("{prefix}shared-session"));assert_eq!(args["cursor_id"], format!("{prefix}shared-cursor"));@@ -2111,7 +3068,11 @@ mod runtime_isolation_tests {fn runtime_namespace_restoration_refuses_duplicate_public_object_keys() {let context = standard_context();let mut args = serde_json::json!({"session": "shared-session"});- let prefix = namespace_runtime_args(&mut args, context.as_ref());+ let prefix = namespace_runtime_args(+ &mut args,+ context.as_ref(),+ &TrustedInvocationEvidence::default(),+ );let mut result = ToolResult::text("ambiguous").with_structured(serde_json::json!({"shared-session": "public",format!("{prefix}shared-session"): "private",@@ -2133,7 +3094,11 @@ mod runtime_isolation_tests {fn runtime_mints_a_private_ownership_key_for_direct_session_calls() {let context = standard_context();let mut args = serde_json::json!({"session": "direct-session"});- let prefix = namespace_runtime_args(&mut args, context.as_ref());+ let prefix = namespace_runtime_args(+ &mut args,+ context.as_ref(),+ &TrustedInvocationEvidence::default(),+ );assert_eq!(args["session"], format!("{prefix}direct-session"));assert_eq!(args["_session_id"], format!("{prefix}direct-session"));}@@ -2146,7 +3111,11 @@ mod runtime_isolation_tests {"_session_id": "default","cursor_id": "default",});- namespace_runtime_args(&mut args, context.as_ref());+ namespace_runtime_args(+ &mut args,+ context.as_ref(),+ &TrustedInvocationEvidence::default(),+ );assert_eq!(args["session"], "default");assert_eq!(args["_session_id"], "default");assert_eq!(args["cursor_id"], "default");@@ -2172,6 +3141,7 @@ fn protected_consent_refusal(error: crate::consent::ConsentError) -> ToolResultcrate::consent::ConsentError::Expired => "protected_consent_expired",crate::consent::ConsentError::Indicator(_) => "protected_indicator_unavailable",crate::consent::ConsentError::Provider(_) => "protected_consent_provider_failed",+ crate::consent::ConsentError::BoundedResource(_) => "bounded_resource_outside_manifest",};let message = error.to_string();ToolResult::error(message.clone()).with_structured(serde_json::json!({@@ -2184,10 +3154,14 @@ fn protected_consent_refusal(error: crate::consent::ConsentError) -> ToolResult}fn protected_scope_refusal(message: &str) -> ToolResult {+ protected_refusal("protected_resource_scope_invalid", message)+}++fn protected_refusal(code: &str, message: &str) -> ToolResult {ToolResult::error(message).with_structured(serde_json::json!({"status": "refused","refusal": {- "code": "protected_resource_scope_invalid",+ "code": code,"message": message,}}))diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rsindex 2bd57e899d..f80f77df52 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs@@ -1328,6 +1328,34 @@ impl NativeAbiDriver {})}+ pub(crate) async fn invoke_from_trusted_adapter(+ &self,+ name: &str,+ arguments: Value,+ ) -> Result<Value, DriverError> {+ let runtime = {+ let handle = *self.handle.lock().unwrap();+ if handle.is_null() {+ return Err(DriverError::Shutdown);+ }+ unsafe {+ handle+ .cast::<CuaDriverHandle>()+ .as_ref()+ .expect("live ABI handle is non-null")+ .runtime+ .clone()+ }+ };+ let result = runtime+ .invoke_from_trusted_adapter(name, arguments)+ .await+ .ok_or(DriverError::Shutdown)?;+ serde_json::to_value(result).map_err(|error| DriverError::Protocol {+ reason: format!("serialize {name} trusted-adapter result: {error}"),+ })+ }+pub(crate) async fn shutdown(&self) -> Result<(), DriverError> {let (receiver, guard) = {let (sender, receiver) = oneshot::channel();diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rsindex e5ced1d057..ae03212a2b 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs@@ -1299,7 +1299,7 @@ impl CuaDriver {pub async fn call_tool_from_trusted_adapter(&self,name: &str,- arguments: Value,+ mut arguments: Value,) -> Result<ToolResult, DriverError> {if !arguments.is_object() {return Err(DriverError::InvalidArguments {@@ -1307,6 +1307,18 @@ impl CuaDriver {reason: "arguments must be a JSON object".into(),});}+ if let DriverBackend::Embedded(runtime) = &self.backend {+ let raw = runtime.invoke_from_trusted_adapter(name, arguments).await?;+ return normalize_result(raw);+ }++ // Trust evidence is local to the adapter/runtime boundary. A private+ // worker re-establishes it in the child; remote and daemon transports+ // derive their own evidence from their authenticated connection and+ // must never receive underscore-prefixed claims from this process.+ if !matches!(&self.backend, DriverBackend::PrivateWorker(_)) {+ cua_driver_core::tool_args::sanitize_reserved_args(&mut arguments);+ }self.invoke(name, arguments).await}@@ -1807,17 +1819,32 @@ mod tests {);if std::env::var("CUA_REQUIRE_GUI").as_deref() == Ok("1") {- for session in [&first_session, &second_session] {- let windows = session- .call_tool("list_windows".into(), "{}".into())- .await- .unwrap();- assert!(- !windows.is_error,- "direct runtime could not inspect the GUI: {}",- windows.text- );- }+ let standard_windows = first_session+ .call_tool("list_windows".into(), "{}".into())+ .await+ .unwrap();+ assert!(+ standard_windows.is_error+ && matches!(+ standard_windows.error_code.as_deref(),+ Some(+ "protected_consent_required" | "protected_consent_provider_failed"+ )+ ),+ "a standard direct runtime without usable protected-consent prerequisites must fail closed: code={:?} text={}",+ standard_windows.error_code,+ standard_windows.text+ );++ let unrestricted_windows = second_session+ .call_tool("list_windows".into(), "{}".into())+ .await+ .unwrap();+ assert!(+ !unrestricted_windows.is_error,+ "explicitly acknowledged unrestricted runtime could not inspect the GUI: {}",+ unrestricted_windows.text+ );}let second_recording_dir = tempfile::tempdir().unwrap();diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rsindex 55f2191b4e..2e60bda011 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs@@ -102,7 +102,6 @@ pub(crate) struct RuntimeSession {connection: AuthenticatedActionConnection,context: Arc<EffectiveAuthorizationContext>,public_session: String,- transport_session: String,}impl RuntimeSession {@@ -127,14 +126,6 @@ impl RuntimeSession {"session".to_owned(),Value::String(self.public_session.clone()),);- arguments.insert(- "_session_id".to_owned(),- Value::String(self.public_session.clone()),- );- arguments.insert(- "_transport_session_id".to_owned(),- Value::String(self.transport_session.clone()),- );let result = self.runtime.invoke_with_context(name, args, self.context.clone())@@ -238,11 +229,43 @@ impl DriverRuntime {.await}+ pub(crate) async fn invoke_from_trusted_adapter(+ &self,+ name: &str,+ mut args: Value,+ ) -> Option<CoreToolResult> {+ let evidence =+ cua_driver_core::tool::TrustedInvocationEvidence::extract_from_adapter_args(&mut args);+ self.invoke_with_context_and_evidence(+ name,+ args,+ self.compatibility_context.clone(),+ evidence,+ )+ .await+ }+async fn invoke_with_context(&self,name: &str,args: Value,context: Arc<EffectiveAuthorizationContext>,+ ) -> Option<CoreToolResult> {+ self.invoke_with_context_and_evidence(+ name,+ args,+ context,+ cua_driver_core::tool::TrustedInvocationEvidence::default(),+ )+ .await+ }++ async fn invoke_with_context_and_evidence(+ &self,+ name: &str,+ args: Value,+ context: Arc<EffectiveAuthorizationContext>,+ evidence: cua_driver_core::tool::TrustedInvocationEvidence,) -> Option<CoreToolResult> {if !self.is_running() {return None;@@ -259,7 +282,10 @@ impl DriverRuntime {.map(|session| context.runtime_session_key(session))}).flatten();- let result = self.registry.invoke_with_context(name, args, context).await;+ let result = self+ .registry+ .invoke_with_context_and_evidence(name, args, context, evidence)+ .await;if let Some(session) = ending_session {// `end_session` is a lifecycle boundary: do not report completion// until any recording owned by the session has finalized.@@ -293,7 +319,6 @@ impl DriverRuntime {connection,context,public_session,- transport_session,}))}}diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rsindex e1da659180..0ead6820fd 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs@@ -62,6 +62,21 @@ impl McpDriver {args: &[&str],recording_label: Option<&str>,) -> Option<Self> {+ let mut daemon_env = env.to_vec();+ let e2e_unrestricted = std::env::var_os("CUA_E2E_UNRESTRICTED_GUI").is_some();+ let caller_selected_mode = daemon_env+ .iter()+ .any(|(name, _)| *name == "CUA_DRIVER_PERMISSION_MODE");+ if args.is_empty() && e2e_unrestricted && !caller_selected_mode {+ // Canonical GUI behavior runners execute in disposable desktops+ // and opt into this testkit-only switch. Translate it at the+ // daemon boundary so unrelated SDK/runtime tests in the same+ // runner do not inherit product authorization variables.+ daemon_env.extend([+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),+ ]);+ }let bin = driver_binary();if !bin.exists() {eprintln!("[testkit] driver binary not built at {bin:?} — skipping");@@ -72,7 +87,7 @@ impl McpDriver {let daemon = if args.is_empty() {// Environment that changes tool behavior belongs on the daemon,// because the stdio process is now only a transport proxy.- Some(TestDaemon::spawn(&bin, &mut reaper, env)?)+ Some(TestDaemon::spawn(&bin, &mut reaper, &daemon_env)?)} else {None};@@ -95,7 +110,7 @@ impl McpDriver {} else {cmd.args(args);}- for (key, value) in env {+ for (key, value) in &daemon_env {cmd.env(key, value);}let mut driver = spawn_in_job(&mut cmd)diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rsindex 86b04bd26a..fc003fe791 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs@@ -49,6 +49,11 @@ impl RawDriver {Self::spawn_daemon_backed(true, &[])}+ /// Spawn an overlay-enabled daemon with explicit trusted launch settings.+ pub fn spawn_with_overlay_and_env(env: &[(&str, &str)]) -> Option<Self> {+ Self::spawn_daemon_backed(true, env)+ }+fn spawn_daemon_backed(overlay_enabled: bool, env: &[(&str, &str)]) -> Option<Self> {let bin = driver_binary();if !bin.exists() {diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rsindex 1b5c261773..70c4a3033f 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs@@ -2518,16 +2518,13 @@ fn permission_grant_needs_direct_capture(structured: &serde_json::Value) -> bool&& !permission_flag(structured, "screen_recording_capturable")}-fn permission_check_request(- prompt: bool,- probe_direct_capture: bool,-) -> crate::serve::DaemonRequest {+fn permission_status_request() -> crate::serve::DaemonRequest {crate::serve::DaemonRequest {method: "call".into(),name: Some("check_permissions".into()),args: Some(serde_json::json!({- "prompt": prompt,- "probe_direct_capture": probe_direct_capture,+ "prompt": false,+ "probe_direct_capture": false,})),session_id: None,observation_origin: Some(crate::serve::ToolObservationOrigin::Direct),@@ -2535,6 +2532,172 @@ fn permission_check_request(}}+/// Handle the private LaunchServices child used by `permissions grant`.+///+/// This runs before ordinary CLI wrapping and never opens a daemon socket. The+/// app bundle asks macOS for the grants under its own responsible-process+/// identity, and macOS remains the only surface that can approve them.+#[cfg(target_os = "macos")]+pub fn run_permissions_host_request_if_requested() -> Option<i32> {+ use std::io::Write as _;+ use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};++ let args = std::env::args().skip(1).collect::<Vec<_>>();+ if args.first().map(String::as_str) != Some(platform_macos::tools::PERMISSIONS_HOST_REQUEST_ARG)+ {+ return None;+ }+ if !crate::bundle::is_executable_inside_cuadriver_app() {+ eprintln!("permission host request requires the installed CuaDriver app bundle");+ return Some(77);+ }+ let result_file = args+ .windows(2)+ .find(|pair| pair[0] == "--result-file")+ .map(|pair| pair[1].clone());+ let Some(result_file) = result_file else {+ eprintln!("permission host request omitted --result-file");+ return Some(64);+ };+ let result_path = std::path::Path::new(&result_file);+ let expected_parent = std::fs::canonicalize(std::env::temp_dir()).ok();+ let actual_parent = result_path.parent().and_then(|parent| {+ std::fs::canonicalize(parent)+ .ok()+ .or_else(|| Some(parent.to_path_buf()))+ });+ let valid_name = result_path+ .file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("cua-driver-permissions-") && name.ends_with(".json"));+ if !valid_name || expected_parent != actual_parent {+ eprintln!("permission host result path is outside the private temporary-file namespace");+ return Some(64);+ }+ let probe_direct_capture = args.iter().any(|arg| arg == "--probe-direct-capture");+ let runtime = match tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ {+ Ok(runtime) => runtime,+ Err(error) => {+ eprintln!("permission host runtime failed: {error}");+ return Some(70);+ }+ };+ let result = runtime.block_on(+ platform_macos::tools::request_permissions_from_launchservices_host(probe_direct_capture),+ );+ let payload = match serde_json::to_vec(&result) {+ Ok(payload) => payload,+ Err(error) => {+ eprintln!("permission host result serialization failed: {error}");+ return Some(70);+ }+ };+ let write_result = std::fs::OpenOptions::new()+ .write(true)+ .truncate(true)+ .custom_flags(libc::O_NOFOLLOW)+ .open(result_path)+ .and_then(|mut file| {+ file.set_permissions(std::fs::Permissions::from_mode(0o600))?;+ file.write_all(&payload)+ });+ match write_result {+ Ok(()) => Some(0),+ Err(error) => {+ eprintln!("permission host result write failed: {error}");+ Some(74)+ }+ }+}++#[cfg(target_os = "macos")]+fn request_permissions_via_launchservices(+ probe_direct_capture: bool,+) -> Result<serde_json::Value, String> {+ use std::fs::OpenOptions;+ use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};+ use std::process::{Command as ProcessCommand, Stdio};+ use std::time::{SystemTime, UNIX_EPOCH};++ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map_err(|error| format!("system clock unavailable: {error}"))?+ .as_nanos();+ let result_file = std::env::temp_dir().join(format!(+ "cua-driver-permissions-{}-{nonce}.json",+ std::process::id()+ ));+ let file = OpenOptions::new()+ .write(true)+ .create_new(true)+ .mode(0o600)+ .open(&result_file)+ .map_err(|error| format!("create permission result file: {error}"))?;+ file.set_permissions(std::fs::Permissions::from_mode(0o600))+ .map_err(|error| format!("secure permission result file: {error}"))?;++ let app_name = crate::bundle::app_name();+ let app_path = crate::bundle::app_bundle_path();+ let mut args = vec![+ "-n".to_owned(),+ "-W".to_owned(),+ "-g".to_owned(),+ app_path.to_owned(),+ "--args".to_owned(),+ platform_macos::tools::PERMISSIONS_HOST_REQUEST_ARG.to_owned(),+ "--result-file".to_owned(),+ result_file.to_string_lossy().into_owned(),+ ];+ if probe_direct_capture {+ args.push("--probe-direct-capture".to_owned());+ }+ let mut child = ProcessCommand::new("/usr/bin/open")+ .args(&args)+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .map_err(|error| format!("launch {app_name} permission host: {error}"))?;+ let status = {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(180);+ loop {+ match child.try_wait() {+ Ok(Some(status)) => break Ok(status),+ Ok(None) if std::time::Instant::now() < deadline => {+ std::thread::sleep(std::time::Duration::from_millis(100));+ }+ Ok(None) => {+ let _ = child.kill();+ let _ = child.wait();+ break Err(format!(+ "{app_name} permission host timed out after 180 seconds"+ ));+ }+ Err(error) => break Err(format!("wait for {app_name} permission host: {error}")),+ }+ }+ };+ let payload = status.and_then(|status| {+ if !status.success() {+ return Err(format!(+ "{app_name} permission host exited with {:?}",+ status.code()+ ));+ }+ std::fs::read(&result_file).map_err(|error| format!("read permission host result: {error}"))+ });+ let _ = std::fs::remove_file(&result_file);+ let payload = payload?;+ let result: serde_json::Value = serde_json::from_slice(&payload)+ .map_err(|error| format!("parse permission host result: {error}"))?;+ result+ .get("structuredContent")+ .cloned()+ .ok_or_else(|| "permission host returned no structured status".to_owned())+}+/// Launch CuaDriver via LaunchServices so the permission prompt attributes to/// com.trycua.driver, wait (user-paced) for the daemon to come up — its socket/// only appears once the permissions gate passes, i.e. the grant was given —@@ -2582,22 +2745,19 @@ fn run_permissions_grant() {// and only a fresh process image sees a later grant. During each// restart the socket briefly disappears, so tolerate transient// connection failures rather than bailing on the first one.- let req = permission_check_request(false, false);- // A daemon that is already inside the permission gate may be a- // prompt-suppressed re-exec. Merely polling it cannot register a- // missing Screen Recording row. Re-raise the two required TCC requests- // through the daemon identity, but deliberately defer Tahoe's separate- // direct-capture probe until after the explanation below.- let prompt_req = permission_check_request(true, false);+ let req = permission_status_request();+ // A dedicated LaunchServices child requests the grants under the+ // CuaDriver app identity. No prompt-capable method exists on the+ // agent-reachable daemon socket.+ let staged_status = request_permissions_via_launchservices(false).ok();let poll_deadline = std::time::Instant::now() + std::time::Duration::from_secs(180);- let mut ax = false;- let mut sr = false;- let mut required_prompts_requested = !daemon_already_running;+ let mut ax = staged_status+ .as_ref()+ .is_some_and(|status| permission_flag(status, "accessibility"));+ let mut sr = staged_status+ .as_ref()+ .is_some_and(|status| permission_flag(status, "screen_recording"));loop {- if !required_prompts_requested {- required_prompts_requested = crate::serve::send_request(&socket, &prompt_req)- .is_ok_and(|response| response.ok);- }if let Some(structured) = crate::serve::send_request(&socket, &req).ok().filter(|r| r.ok)@@ -2648,32 +2808,15 @@ fn run_permissions_grant() {);println!("Choose Allow to request and verify direct capture now…");- let direct_req = permission_check_request(true, true);- let direct_deadline = std::time::Instant::now() + std::time::Duration::from_secs(180);- let mut direct_status = None;- loop {- if let Some(structured) = crate::serve::send_request(&socket, &direct_req)- .ok()- .filter(|r| r.ok)- .and_then(|r| r.result)- .and_then(|res| res.get("structuredContent").cloned())- {- direct_status = Some(structured.clone());- if permission_grant_is_ready(&structured) {- println!(- "\n✅ {app_name} has Accessibility, Screen Recording, and direct capture access. You're set."- );- return;- }- // The explicit probe returned a real negative result (the- // user denied the consent or ScreenCaptureKit failed). Do not- // hammer the user with the same system dialog in a poll loop.- break;- }- if std::time::Instant::now() >= direct_deadline {- break;- }- std::thread::sleep(std::time::Duration::from_secs(2));+ let direct_status = request_permissions_via_launchservices(true).ok();+ if direct_status+ .as_ref()+ .is_some_and(permission_grant_is_ready)+ {+ println!(+ "\n✅ {app_name} has Accessibility, Screen Recording, and direct capture access. You're set."+ );+ return;}eprintln!("\n❌ {app_name} still cannot use direct ScreenCaptureKit capture.");@@ -3753,21 +3896,16 @@ mod tests {}#[test]- fn permission_grant_stages_required_prompts_before_direct_capture() {- let staged = permission_check_request(true, false);- let staged_args = staged.args.expect("staged request args");- assert_eq!(staged_args.get("prompt"), Some(&serde_json::json!(true)));+ fn permission_status_request_is_read_only_and_uses_the_public_tool_route() {+ let status = permission_status_request();+ assert_eq!(status.method, "call");+ assert_eq!(status.name.as_deref(), Some("check_permissions"));+ let args = status.args.expect("status request args");+ assert_eq!(args.get("prompt"), Some(&serde_json::json!(false)));assert_eq!(- staged_args.get("probe_direct_capture"),+ args.get("probe_direct_capture"),Some(&serde_json::json!(false)));-- let direct = permission_check_request(true, true);- let direct_args = direct.args.expect("direct request args");- assert_eq!(- direct_args.get("probe_direct_capture"),- Some(&serde_json::json!(true))- );}#[test]diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rsindex efcba682fc..9dd58d2e29 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs@@ -397,6 +397,9 @@ mod mcp_runtime_selection_tests {#[cfg(target_os = "macos")]fn main() {init_logging();+ if let Some(code) = cli::run_permissions_host_request_if_requested() {+ std::process::exit(code);+ }if let Some(generation) = private_worker::requested_generation() {let (initialized_tx, initialized_rx) = std::sync::mpsc::sync_channel(1);std::thread::spawn(move || {diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/permission_prompt_authorization_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/permission_prompt_authorization_test.rsnew file mode 100644index 0000000000..e99e6dc16a--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/tests/permission_prompt_authorization_test.rs@@ -0,0 +1,36 @@+// SPDX-License-Identifier: MIT++//! Cross-platform socket proof for protected operating-system permission UI.++use cua_driver_testkit::RawDriver;++#[test]+fn standard_mode_refuses_protected_permission_prompt_over_real_socket() {+ let mut driver = RawDriver::spawn_with_env(&[("CUA_DRIVER_PERMISSION_MODE", "standard")])+ .expect("the permission-authorization proof requires a built, spawnable driver");++ driver.send(&serde_json::json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {}+ }));+ driver.recv();+ driver.send(&serde_json::json!({+ "jsonrpc": "2.0",+ "id": 2,+ "method": "tools/call",+ "params": {+ "name": "check_permissions",+ "arguments": {"prompt": true}+ }+ }));+ let response = driver.recv();+ assert_eq!(response["id"], 2);+ assert!(+ response["result"]["isError"].as_bool().unwrap_or(false)+ && response["result"]["structuredContent"]["refusal"]["code"]+ == "os_permission_prompt_requires_trusted_host",+ "standard mode did not fail closed: {response}"+ );+}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rsindex 9a664b0e39..afed5d9990 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs@@ -121,8 +121,65 @@ async fn private_worker_inherits_the_interactive_linux_display_scope() {);let driver = cua_driver_sdk::CuaDriver::create_private_worker(worker_options()).unwrap();+ let standard = driver+ .create_trusted_session(TrustedSessionOptions {+ public_session: "worker-standard-display-scope".into(),+ mode: SessionPermissionMode::Standard,+ ttl_seconds: 60,+ idle_ttl_seconds: 30,+ bounded_manifest_path: None,+ })+ .unwrap();+ let refused = standard+ .call_tool("list_windows".into(), "{}".into())+ .await+ .unwrap();+ assert!(+ refused+ .error_code+ .as_deref()+ .is_some_and(|code| code.starts_with("protected_consent_")),+ "standard worker observation without a protected consent host must fail closed: {}",+ refused.text+ );+ standard.close();++ let session = driver+ .create_trusted_session(TrustedSessionOptions {+ public_session: "worker-display-scope".into(),+ mode: SessionPermissionMode::Unrestricted,+ ttl_seconds: 60,+ idle_ttl_seconds: 30,+ bounded_manifest_path: None,+ })+ .unwrap();+ let started = session+ .call_tool(+ "start_session".into(),+ serde_json::json!({+ "session": "worker-display-scope",+ "capture_scope": "desktop"+ })+ .to_string(),+ )+ .await+ .unwrap();+ assert!(+ !started.is_error,+ "worker could not declare the trusted desktop capture scope: {}",+ started.text+ );+ let started_structured: serde_json::Value = serde_json::from_str(+ started+ .structured_json+ .as_deref()+ .expect("start_session omitted structuredContent"),+ )+ .unwrap();+ assert_eq!(started_structured["capture_scope"], "desktop");+ assert_eq!(started_structured["effective_scope"], "desktop");if has_x11 {- let desktop = driver+ let desktop = session.call_tool("get_desktop_state".into(), "{}".into()).await.unwrap();@@ -132,7 +189,7 @@ async fn private_worker_inherits_the_interactive_linux_display_scope() {desktop.text);} else {- let windows = driver+ let windows = session.call_tool("list_windows".into(), "{}".into()).await.unwrap();@@ -142,6 +199,19 @@ async fn private_worker_inherits_the_interactive_linux_display_scope() {windows.text);}+ let ended = session+ .call_tool(+ "end_session".into(),+ serde_json::json!({"session": "worker-display-scope"}).to_string(),+ )+ .await+ .unwrap();+ assert!(+ !ended.is_error,+ "worker could not end session: {}",+ ended.text+ );+ session.close();driver.shutdown().await.unwrap();}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rsindex 7c063c2af6..fb9a7ed09b 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs@@ -11,6 +11,13 @@use cua_driver_testkit::RawDriver;+fn spawn_unrestricted() -> Option<RawDriver> {+ RawDriver::spawn_with_env(&[+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),+ ])+}+#[test]#[cfg(target_os = "windows")]fn screenshot() {@@ -329,7 +336,7 @@ fn zoom_from_zoom_click_round_trip() {#[cfg(any(target_os = "macos", target_os = "windows"))]fn recording_session() {//! Enable recording, invoke a non-read-only tool (recorded), disable, verify action.json written.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -529,7 +536,7 @@ fn start_recording_record_video_flag_accepted() {//! session enters the enabled state. Full video lifecycle is//! covered by the manual demo + the per-platform smoke when//! ffmpeg is installed.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -572,7 +579,7 @@ fn replay_trajectory() {//! Write a minimal no-GUI trajectory, replay it, verify succeeded=1.//! The test daemon deliberately starts with `--no-overlay`, so an//! agent-cursor move would correctly refuse before exercising replay.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -695,7 +702,7 @@ fn click_debug_image_out() {fn set_config_screenshot_resize() {//! set_config(max_image_dimension=200) then screenshot — returned image must//! have both dimensions ≤ 200. Verifies the ResizeRegistry pipeline end-to-end.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rsindex 9a738c65ca..297d9d6937 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs@@ -255,7 +255,7 @@ fn tools_list_schema_shape() {}#[test]-fn legacy_page_mutation_flag_is_read_by_the_spawned_daemon() {+fn legacy_page_mutation_requires_unrestricted_launch_and_operator_opt_in() {let args = serde_json::json!({"action": "enable_javascript_apple_events","user_has_confirmed_enabling": false@@ -266,16 +266,18 @@ fn legacy_page_mutation_flag_is_read_by_the_spawned_daemon() {let response = driver.call("page", args.clone());assert!(response.is_error(), "mutation must refuse by default");assert!(- response- .text()- .contains("CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1"),- "default refusal must name the operator gate: {}",+ response.text().contains("requires unrestricted mode"),+ "default refusal must name the trusted launch gate: {}",response.text());}- let mut driver = McpDriver::spawn_with_env(&[("CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS", "1")])- .expect("spawn source-built driver with daemon-scoped compatibility flag");+ let mut driver = McpDriver::spawn_with_env(&[+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),+ ("CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS", "1"),+ ])+ .expect("spawn source-built driver with unrestricted legacy compatibility enabled");let response = driver.call("page", args);assert!(response.is_error(),diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rsindex 8044148555..ac5c06d558 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs@@ -14,6 +14,13 @@use cua_driver_testkit::RawDriver;+fn spawn_unrestricted_with_overlay() -> Option<RawDriver> {+ RawDriver::spawn_with_overlay_and_env(&[+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),+ ])+}+#[test]#[cfg(any(target_os = "macos", target_os = "windows"))]fn concurrent_clients() {@@ -52,7 +59,7 @@ fn concurrent_clients_with_cursor_moves() {//! This covers the multi-cursor use case where two Codex agents run simultaneously.let mut drivers: Vec<RawDriver> = Vec::new();for _ in 0..2 {- let Some(d) = RawDriver::spawn_with_overlay() else {+ let Some(d) = spawn_unrestricted_with_overlay() else {return;};drivers.push(d);@@ -102,10 +109,10 @@ fn concurrent_multi_driver_isolation() {//! Two cua-driver processes running simultaneously with different cursor IDs.//! Verifies that concurrent sessions don't interfere — each tracks its own//! cursor state and the overlay stays alive under concurrent load.- let Some(mut child_a) = RawDriver::spawn_with_overlay() else {+ let Some(mut child_a) = spawn_unrestricted_with_overlay() else {return;};- let Some(mut child_b) = RawDriver::spawn_with_overlay() else {+ let Some(mut child_b) = spawn_unrestricted_with_overlay() else {return;};@@ -215,7 +222,7 @@ fn concurrent_multi_driver_isolation() {#[cfg(any(target_os = "macos", target_os = "windows"))]fn multi_cursor_instance_state() {//! Two cursor instances can be created with different IDs; each has independent state.- let Some(mut d) = RawDriver::spawn_with_overlay() else {+ let Some(mut d) = spawn_unrestricted_with_overlay() else {return;};@@ -352,7 +359,7 @@ fn overlay_move_cursor_stays_alive() {//! sends commands via the global channel. Any crash in the render thread (e.g. wrong//! GCD queue pointer, bad CGImage argument types) would cause this test to fail with//! an early EOF or a non-zero exit code.- let Some(mut d) = RawDriver::spawn_with_overlay() else {+ let Some(mut d) = spawn_unrestricted_with_overlay() else {return;};@@ -412,7 +419,7 @@ fn overlay_move_cursor_stays_alive() {fn set_agent_cursor_motion_bezier_knobs() {//! set_agent_cursor_motion with Bezier/timing knobs — verifies schema accepts them//! and returns a non-error response with the updated values in the response text.- let Some(mut d) = RawDriver::spawn_with_overlay() else {+ let Some(mut d) = spawn_unrestricted_with_overlay() else {return;};diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rsindex 1e7ae9a33b..f0cfcec9ee 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs@@ -13,10 +13,17 @@use cua_driver_testkit::RawDriver;+fn spawn_unrestricted() -> Option<RawDriver> {+ RawDriver::spawn_with_env(&[+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),+ ])+}+#[test]#[cfg(any(target_os = "macos", target_os = "windows"))]fn tools_call_list_apps() {- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -63,7 +70,7 @@ fn tools_call_list_apps() {#[test]#[cfg(any(target_os = "macos", target_os = "windows"))]fn get_config_and_check_permissions() {- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -84,7 +91,7 @@ fn get_config_and_check_permissions() {d.send(&serde_json::json!({"jsonrpc":"2.0","id":3,"method":"tools/call",- "params":{"name":"check_permissions","arguments":{}}+ "params":{"name":"check_permissions","arguments":{"prompt":false}}}));let resp = d.recv();assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));@@ -142,7 +149,7 @@ fn get_config_and_check_permissions() {#[cfg(any(target_os = "macos", target_os = "windows"))]fn get_accessibility_tree() {//! get_accessibility_tree returns a lightweight process+window snapshot.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -185,7 +192,7 @@ fn get_accessibility_tree() {#[cfg(any(target_os = "macos", target_os = "windows"))]fn list_windows_structured_content() {//! Verify list_windows returns structuredContent.windows array with expected fields.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -224,7 +231,7 @@ fn list_windows_structured_content() {#[test]#[cfg(any(target_os = "macos", target_os = "windows"))]fn get_screen_size_and_cursor_position() {- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -278,7 +285,7 @@ fn get_window_state_returns_both_with_opt_out() {//! Perception is mode-agnostic: get_window_state returns BOTH the tree AND a//! screenshot by default (the deprecated `capture_mode` arg is ignored), and//! `include_screenshot:false` is the opt-out that returns the tree only.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -395,7 +402,7 @@ fn get_window_state_returns_both_with_opt_out() {fn scroll_tool() {//! scroll with direction=down, by=line, amount=1 against the first available window.//! Verifies the tool is accepted and returns content, not a protocol error.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -444,7 +451,7 @@ fn scroll_tool() {fn type_text_tool() {//! Opens TextEdit (or reuses it if already running) and types a short string via type_text.//! Skips gracefully if TextEdit is not available or has no window.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -510,7 +517,7 @@ fn type_text_tool() {#[cfg(target_os = "windows")]fn type_text_notepad() {//! Launch Notepad, type a short string via type_text. Skips if Notepad unavailable.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -579,7 +586,7 @@ fn type_text_chars_tool() {//! Verify type_text_chars with delay_ms is accepted without error (dry-run via TextEdit or//! a pid that accepts WM_CHAR). We just verify the tool responds with a non-error.//! Skips gracefully if no visible TextEdit window.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -631,7 +638,7 @@ fn type_text_chars_tool() {#[cfg(any(target_os = "macos", target_os = "windows"))]fn hotkey_keys_array() {//! Verify hotkey accepts a keys array without a protocol error.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -681,7 +688,7 @@ fn hotkey_keys_array() {fn press_key_harmless() {//! press_key with a harmless key (F24 — virtually no app responds to it) sent to the//! first available window. Just verifies the tool doesn't return a protocol error.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -722,7 +729,7 @@ fn press_key_harmless() {fn click_pixel_path() {//! click at window-local (5, 5) — title bar area, safe to click without disrupting UI.//! Verifies the pixel-coordinate path for click works without a protocol error.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -760,7 +767,7 @@ fn click_pixel_path() {#[test]#[cfg(target_os = "windows")]fn double_click_and_right_click() {- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -813,7 +820,7 @@ fn double_click_and_right_click() {#[cfg(target_os = "macos")]fn double_click_and_right_click_pixel_path() {//! double_click and right_click at title-bar coords — verifies both tools accept pixel path.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};@@ -875,7 +882,7 @@ fn double_click_and_right_click_pixel_path() {fn set_value_via_element_index() {//! get_window_state on TextEdit → find a text-area element → set_value on it.//! Skips gracefully if TextEdit is not available.- let Some(mut d) = RawDriver::spawn() else {+ let Some(mut d) = spawn_unrestricted() else {return;};diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rsindex 48cc384323..9db18a1861 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs@@ -734,8 +734,14 @@ fn spawn_driver(label: &str) -> McpDriver {#[cfg(not(target_os = "macos"))]fn spawn_standard_driver(label: &str) -> McpDriver {- McpDriver::spawn_named(label)- .expect("cua-driver binary/daemon is required for standalone browser E2E")+ McpDriver::spawn_named_with_env(+ label,+ &[+ ("CUA_DRIVER_PERMISSION_MODE", "standard"),+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "0"),+ ],+ )+ .expect("cua-driver binary/daemon is required for standalone browser E2E")}#[cfg(target_os = "linux")]@@ -1120,16 +1126,6 @@ fn launch_browser_with_html(spec: &BrowserSpec, label: &str, html: String) -> Brlaunch_browser_with_driver(spec, label, html, spawn_driver(label))}-#[cfg(not(target_os = "macos"))]-fn launch_browser_in_standard_mode(spec: &BrowserSpec, label: &str) -> BrowserFixture {- launch_browser_with_driver(- spec,- label,- standalone_fixture_html(),- spawn_standard_driver(label),- )-}-fn launch_browser_with_driver(spec: &BrowserSpec,label: &str,@@ -2158,17 +2154,22 @@ fn run_existing_profile_standard_refusal(spec: &BrowserSpec) {RefusalCode::BrowserConsentRequired,),|evidence| {- let mut fixture = launch_browser_in_standard_mode(spec, &scenario);+ // Fixture discovery, posture, and evidence capture are protected+ // desktop operations in their own right. Keep those on the+ // explicitly unrestricted disposable-test driver, then use a+ // separate standard daemon solely as the authorization subject.+ let mut fixture = launch_browser(spec, &scenario);+ let mut standard_driver =+ spawn_standard_driver(&format!("{scenario}-authorization-subject"));+ fixture.driver.start_behavior_recording();*evidence = recording_evidence(fixture.driver.recording_dir());run_with_background_oracles(&mut fixture, |fixture| {let session = format!("standalone-standard-refusal-{}", fixture.pid);- let started = fixture- .driver+ let started = standard_driver.call("start_session", serde_json::json!({ "session": session }));assert!(!started.is_error(), "start_session failed: {}", started.raw);- fixture.driver.start_behavior_recording();- let refused = fixture.driver.call(+ let refused = standard_driver.call("browser_prepare",serde_json::json!({"pid": fixture.pid as i64,@@ -2190,12 +2191,16 @@ fn run_existing_profile_standard_refusal(spec: &BrowserSpec) {refused.raw);wait_for_text(&fixture.server, "lbl-counter", "counter=0");- Observation::refused(+ let observation = Observation::refused(RefusalCode::BrowserConsentRequired,vec![OracleKind::FixtureState],refused.text(),Evidence::default(),- )+ );+ let ended =+ standard_driver.call("end_session", serde_json::json!({ "session": session }));+ assert!(!ended.is_error(), "end_session failed: {}", ended.raw);+ observation})},);diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rsindex 20ab826d48..b859c7e643 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs@@ -6828,7 +6828,46 @@ impl Tool for KillAppTool {})}+ async fn protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ if adapter_id != "process_control" {+ return Ok(None);+ }+ use cua_driver_core::browser::platform::BrowserPlatform;+ let pid = args+ .get("pid")+ .and_then(Value::as_i64)+ .filter(|pid| *pid > 0)+ .ok_or_else(|| "kill_app requires a positive integer pid".to_owned())?;+ let fingerprint = crate::browser_platform::LinuxBrowserPlatform+ .process_fingerprint(pid)+ .await+ .map_err(|error| error.message)?;+ Ok(Some(json!({+ "kind": "process_instance",+ "fingerprint": fingerprint,+ })))+ }+async fn invoke(&self, args: Value) -> ToolResult {+ if let Some(expected) = args.get("_protected_process_fingerprint") {+ let current = match self+ .protected_resource_scope("process_control", &args)+ .await+ {+ Ok(Some(scope)) => scope["fingerprint"].clone(),+ Ok(None) => Value::Null,+ Err(message) => return kill_app_stale_process_refusal(message),+ };+ if current != *expected {+ return kill_app_stale_process_refusal(+ "the process identity changed at the termination boundary".to_owned(),+ );+ }+ }let pid_i = match args.get("pid").and_then(|v| v.as_i64()) {Some(p) if p > 0 && p <= i32::MAX as i64 => p as i32,Some(_) => {@@ -6854,6 +6893,16 @@ impl Tool for KillAppTool {}}+fn kill_app_stale_process_refusal(message: String) -> ToolResult {+ ToolResult::error(message.clone()).with_structured(json!({+ "status": "refused",+ "refusal": {+ "code": "protected_resource_scope_stale",+ "message": message,+ }+ }))+}+// ── bring_to_front (Linux) ───────────────────────────────────────────────────pub struct BringToFrontTool;diff --git a/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rsindex fc8a04158f..110295617f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs@@ -305,7 +305,7 @@ pub(crate) fn locate_by_name(name: &str) -> Option<AppLocator> {/// this file) to avoid pulling in a plist crate just for this.fn bundle_id_for_app_path(app_path: &str) -> Option<String> {let plist = format!("{app_path}/Contents/Info.plist");- let out = Command::new("plutil")+ let out = Command::new("/usr/bin/plutil").args(["-extract", "CFBundleIdentifier", "raw", "-o", "-", &plist]).output().ok()?;diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rsindex e2894b2574..fbcb7e5e02 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rs@@ -1,7 +1,7 @@use async_trait::async_trait;use cua_driver_core::{protocol::ToolResult,- tool::{Tool, ToolDef},+ tool::{ProtectedResourceOwnership, Tool, ToolDef},};use serde_json::Value;use std::sync::Arc;@@ -12,6 +12,10 @@ use crate::permissions::status::{screen_recording_granted,};+/// Private argv sentinel shared by the trusted CLI launcher and the public+/// launch_app refusal.+pub const PERMISSIONS_HOST_REQUEST_ARG: &str = "__permissions-host-request";+pub struct CheckPermissionsTool {state: Arc<ToolState>,}@@ -22,6 +26,19 @@ impl CheckPermissionsTool {}}+/// LaunchServices-hosted permission setup entrypoint. This is deliberately+/// not registered as an agent tool or exposed on the daemon socket: the+/// standalone `permissions grant` command launches the app bundle and macOS+/// owns the actual approval UI.+pub async fn request_from_launchservices_host(probe_direct_capture: bool) -> ToolResult {+ let tool = CheckPermissionsTool::new(Arc::new(ToolState::new(false, false, None)));+ tool.invoke(serde_json::json!({+ "prompt": true,+ "probe_direct_capture": probe_direct_capture,+ }))+ .await+}+fn driver_bundle_id_for_executable(executable: &str) -> Option<&'static str> {if executable.contains("/CuaDriverLocal.app/Contents/MacOS/") {Some("com.trycua.driver.local")@@ -179,7 +196,8 @@ fn def() -> &'static ToolDef {"properties": {"prompt": {"type": "boolean",- "description": "Raise the system permission prompts for missing grants. Default true.",+ "description": "Raise the system permission prompts for missing grants. Default false; only a trusted host setup route may set true.",+ "default": false,},"probe_direct_capture": {"type": "boolean",@@ -188,8 +206,9 @@ fn def() -> &'static ToolDef {},"additionalProperties": false,}),- // Not read_only because the default path may raise a modal dialog- // (mirrors Swift annotation `readOnlyHint: false`).+ // Not read_only because an explicit prompt=true would raise a modal+ // dialog if invoked by the trusted host helper. The public registry+ // refuses that shape before platform dispatch.read_only: false,destructive: false,idempotent: true,@@ -203,15 +222,30 @@ impl Tool for CheckPermissionsTool {def()}+ async fn protected_resource_ownership(+ &self,+ adapter_id: &str,+ _args: &Value,+ ) -> ProtectedResourceOwnership {+ if adapter_id == "os_permission_prompt"+ && !should_prompt_permissions(true, self.state.host_owns_permission_ux)+ {+ ProtectedResourceOwnership::DriverOwned+ } else {+ ProtectedResourceOwnership::UserOwned+ }+ }+async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;- // Default to prompting — same default + rationale as Swift.+ // Public calls default to read-only inspection. Only the+ // LaunchServices-hosted setup route passes prompt=true.// Embedded mode hard-disables prompting regardless of the arg (the// host owns the grant flow). This and the startup gate are the only// `request_*` call sites, so both being gated makes prompts// unreachable when embedded.let should_prompt = should_prompt_permissions(- args.bool_or("prompt", true),+ args.bool_or("prompt", false),self.state.host_owns_permission_ux,);let probe_direct_capture = args.bool_or("probe_direct_capture", true);diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/kill_app.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/kill_app.rsindex 3683d9480e..c7c75e9072 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/kill_app.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/kill_app.rs@@ -12,6 +12,7 @@use async_trait::async_trait;use cua_driver_core::{+ browser::platform::BrowserPlatform,protocol::ToolResult,tool::{Tool, ToolDef},};@@ -50,7 +51,47 @@ impl Tool for KillAppTool {def()}+ async fn protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ if adapter_id != "process_control" {+ return Ok(None);+ }+ let pid = args+ .get("pid")+ .and_then(Value::as_i64)+ .filter(|pid| *pid > 0)+ .ok_or_else(|| "kill_app requires a positive integer pid".to_owned())?;+ let fingerprint = crate::browser::MacOsBrowserPlatform::default()+ .process_fingerprint(pid)+ .await+ .map_err(|error| error.message)?;+ Ok(Some(serde_json::json!({+ "kind": "process_instance",+ "fingerprint": fingerprint,+ })))+ }+async fn invoke(&self, args: Value) -> ToolResult {+ if let Some(expected) = args.get("_protected_process_fingerprint") {+ let current = match self+ .protected_resource_scope("process_control", &args)+ .await+ {+ Ok(Some(scope)) => scope["fingerprint"].clone(),+ Ok(None) => Value::Null,+ Err(message) => {+ return stale_process_refusal(message);+ }+ };+ if current != *expected {+ return stale_process_refusal(+ "the process identity changed at the termination boundary".to_owned(),+ );+ }+ }let pid_i = match args.get("pid").and_then(|v| v.as_i64()) {Some(p) if p > 0 && p <= i32::MAX as i64 => p as i32,Some(_) => {@@ -81,3 +122,13 @@ impl Tool for KillAppTool {}}}++fn stale_process_refusal(message: String) -> ToolResult {+ ToolResult::error(message.clone()).with_structured(serde_json::json!({+ "status": "refused",+ "refusal": {+ "code": "protected_resource_scope_stale",+ "message": message,+ }+ }))+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rsindex 30245570d2..5eefcebde1 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs@@ -96,6 +96,12 @@ impl Tool for LaunchAppTool {let webkit_inspector_port = args.opt_u64("webkit_inspector_port").map(|v| v as u16);let creates_new_instance = args.bool_or("creates_new_application_instance", false);let additional_arguments: Vec<String> = args.str_array("additional_arguments");+ if additional_arguments+ .iter()+ .any(|argument| argument == super::check_permissions::PERMISSIONS_HOST_REQUEST_ARG)+ {+ return protected_host_launch_refusal();+ }if additional_arguments.iter().any(|argument| contains_remote_debugging_flag(argument))@@ -110,6 +116,9 @@ impl Tool for LaunchAppTool {"Provide either bundle_id or name to identify the app to launch.",);}+ if bundle_id.as_deref().is_some_and(is_cua_driver_bundle_id) {+ return protected_host_launch_refusal();+ }if let Some(ref bid) = bundle_id {if crate::apps::resolve_bundle_id_to_locator(bid).is_none() {return structured_launch_error(@@ -119,12 +128,19 @@ impl Tool for LaunchAppTool {);}} else if let Some(ref n) = name {- if crate::apps::locate_by_name(n).is_none() {+ let Some(locator) = crate::apps::locate_by_name(n) else {return structured_launch_error("APP_NOT_INSTALLED",format!("No installed macOS app found for name '{n}'."),serde_json::json!({ "name": n }),);+ };+ let (_, resolved_bundle_id) = locator.app_ref_and_bundle_id();+ if resolved_bundle_id+ .as_deref()+ .is_some_and(is_cua_driver_bundle_id)+ {+ return protected_host_launch_refusal();}}if let Some(err) = preflight_file_urls(&urls) {@@ -478,6 +494,18 @@ fn contains_remote_debugging_flag(value: &str) -> bool {lower.contains("--remote-debugging-port") || lower.contains("--remote-debugging-pipe")}+fn is_cua_driver_bundle_id(bundle_id: &str) -> bool {+ matches!(bundle_id, "com.trycua.driver" | "com.trycua.driver.local")+}++fn protected_host_launch_refusal() -> ToolResult {+ structured_launch_error(+ "PROTECTED_HOST_ENTRYPOINT",+ "launch_app cannot launch Cua Driver's protected host; operating-system permission UI must originate outside the agent tool stream".to_owned(),+ serde_json::json!({}),+ )+}+// ── Blocking helpers ──────────────────────────────────────────────────────────/// Poll for the pid's layer-0 windows, retrying up to 5x100ms to absorb@@ -603,7 +631,12 @@ fn hex_value(byte: u8) -> Option<u8> {#[cfg(test)]mod tests {- use super::{contains_remote_debugging_flag, local_file_target, preflight_file_urls};+ use super::{+ contains_remote_debugging_flag, is_cua_driver_bundle_id, local_file_target,+ preflight_file_urls, LaunchAppTool,+ };+ use cua_driver_core::tool::Tool;+ use serde_json::json;use std::path::PathBuf;#[test]@@ -659,4 +692,39 @@ mod tests {"--user-data-dir=/tmp/profile"));}++ #[test]+ fn recognizes_release_and_local_protected_host_bundle_ids() {+ assert!(is_cua_driver_bundle_id("com.trycua.driver"));+ assert!(is_cua_driver_bundle_id("com.trycua.driver.local"));+ assert!(!is_cua_driver_bundle_id("com.trycua.harness.tauri"));+ }++ #[tokio::test]+ async fn launch_app_cannot_reach_private_permission_host_entrypoint() {+ let result = LaunchAppTool+ .invoke(json!({+ "bundle_id": "com.example.not-installed",+ "additional_arguments": [+ "__permissions-host-request",+ "--result-file",+ "/tmp/cua-driver-permissions-forged.json"+ ]+ }))+ .await;+ assert_eq!(result.is_error, Some(true));+ assert_eq!(+ result.structured_content.unwrap()["error"],+ "PROTECTED_HOST_ENTRYPOINT"+ );++ let result = LaunchAppTool+ .invoke(json!({ "bundle_id": "com.trycua.driver" }))+ .await;+ assert_eq!(result.is_error, Some(true));+ assert_eq!(+ result.structured_content.unwrap()["error"],+ "PROTECTED_HOST_ENTRYPOINT"+ );+ }}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rsindex 07b6217ba1..57124ecc45 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs@@ -40,6 +40,11 @@ use std::sync::Arc;use crate::{ax::cache::ElementCache, cursor::state::CursorRegistry};+pub use check_permissions::{+ request_from_launchservices_host as request_permissions_from_launchservices_host,+ PERMISSIONS_HOST_REQUEST_ARG,+};+/// Per-process zoom context — stores the padded crop origin and resize scale/// from the most recent `zoom` call, so `click(from_zoom=true)` can translate/// zoom-image pixel coordinates back to full-window coordinates.diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rsindex b5301629a9..ae70e1c017 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs@@ -8207,7 +8207,46 @@ impl Tool for KillAppTool {})}+ async fn protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ if adapter_id != "process_control" {+ return Ok(None);+ }+ use cua_driver_core::browser::platform::BrowserPlatform;+ let pid = args+ .get("pid")+ .and_then(Value::as_i64)+ .filter(|pid| *pid > 0)+ .ok_or_else(|| "kill_app requires a positive integer pid".to_owned())?;+ let fingerprint = crate::browser_platform::WindowsBrowserPlatform::default()+ .process_fingerprint(pid)+ .await+ .map_err(|error| error.message)?;+ Ok(Some(json!({+ "kind": "process_instance",+ "fingerprint": fingerprint,+ })))+ }+async fn invoke(&self, args: Value) -> ToolResult {+ if let Some(expected) = args.get("_protected_process_fingerprint") {+ let current = match self+ .protected_resource_scope("process_control", &args)+ .await+ {+ Ok(Some(scope)) => scope["fingerprint"].clone(),+ Ok(None) => Value::Null,+ Err(message) => return kill_app_stale_process_refusal(message),+ };+ if current != *expected {+ return kill_app_stale_process_refusal(+ "the process identity changed at the termination boundary".to_owned(),+ );+ }+ }let pid_v: u32 = match args.get("pid").and_then(|v| v.as_u64()) {Some(p) if p > 0 && p <= u32::MAX as u64 => p as u32,Some(_) => {@@ -8277,6 +8316,16 @@ impl Tool for KillAppTool {}}+fn kill_app_stale_process_refusal(message: String) -> ToolResult {+ ToolResult::error(message.clone()).with_structured(json!({+ "status": "refused",+ "refusal": {+ "code": "protected_resource_scope_stale",+ "message": message,+ }+ }))+}+// ── debug_window_info ─────────────────────────────────────────────────────────//// Diagnostic tool: dump everything the daemon (Session 2 when launched viadiff --git a/libs/cua-driver/tests/runners/macos-lume/README.md b/libs/cua-driver/tests/runners/macos-lume/README.mdindex 13ad608b79..279d0654ca 100644--- a/libs/cua-driver/tests/runners/macos-lume/README.md+++ b/libs/cua-driver/tests/runners/macos-lume/README.md@@ -199,9 +199,9 @@ explicitly requests an Apple Events-backed browser or app operation; do notpre-grant those in the seed. These are normal macOS consent flows; do not edit`TCC.db`. Rerun the commands and require them to finish without another prompt.Then verify the daemon's own-identity and the read-only status contract before running the explicit live-capture probe. The first command must not raise a dialog; the second is-intentionally prompt-capable:+identity and the read-only status contract before running the explicit+LaunchServices-hosted grant flow. The first command must not raise a dialog;+the second is intentionally prompt-capable and must be run by the human:```bash~/.local/bin/cua-driver-local permissions status --json | jq -e '@@ -211,15 +211,16 @@ intentionally prompt-capable:and .direct_capture_status == "not_checked"and .source.attribution == "driver-daemon"'-~/.local/bin/cua-driver-local call check_permissions '{"prompt":true}' | jq -e '- .structuredContent.screen_recording_capturable == true- and .structuredContent.direct_capture_status == "ready"+~/.local/bin/cua-driver-local permissions grant+~/.local/bin/cua-driver-local permissions status --json | jq -e '+ .accessibility == true+ and .screen_recording == true'codesign -d -r- /Applications/CuaDriverLocal.app 2>&1 | grep 'certificate leaf'csrutil status```-All four commands must succeed, and `csrutil status` must report disabled.+All five commands must succeed, and `csrutil status` must report disabled.Stop the builder and clone it to a date/version-named private seed plus twostopped backups:diff --git a/libs/cua-driver/tests/runners/macos-lume/run-all.sh b/libs/cua-driver/tests/runners/macos-lume/run-all.shindex 5e5510f6b0..b1adbf4497 100755--- a/libs/cua-driver/tests/runners/macos-lume/run-all.sh+++ b/libs/cua-driver/tests/runners/macos-lume/run-all.sh@@ -149,6 +149,9 @@ if ! grep -Fq "certificate leaf" "${ARTIFACT_DIR}/codesign-requirement.txt"; thefiINSTALLED_BIN="${HOME}/.local/bin/cua-driver-local"+export CUA_E2E_INSTALLED_DRIVER_BIN="${INSTALLED_BIN}"+# install-local.sh intentionally uses a separate namespace from release installs.+export CUA_E2E_MACOS_DAEMON_SOCKET="${CUA_E2E_MACOS_DAEMON_SOCKET:-${HOME}/Library/Caches/cua-driver-local/cua-driver-local.sock}"PERMISSIONS_FILE="${ARTIFACT_DIR}/permissions.json"PERMISSIONS_READY=0for _ in 1 2 3 4 5 6 7 8 9 10; do@@ -171,16 +174,57 @@ if [[ "${PERMISSIONS_READY}" != 1 ]]; thenexit 1fi-LIVE_PERMISSIONS_FILE="${ARTIFACT_DIR}/permissions-live-capture.json"-if ! "${INSTALLED_BIN}" call check_permissions '{"prompt":true}' \- > "${LIVE_PERMISSIONS_FILE}" \- || ! jq -e '- (.structuredContent // .) as $permissions- | $permissions.screen_recording_capturable == true- and $permissions.direct_capture_status == "ready"- ' "${LIVE_PERMISSIONS_FILE}" >/dev/null; then- cat "${LIVE_PERMISSIONS_FILE}" >&2 || true- echo "The cloned golden image does not have usable direct ScreenCaptureKit consent" >&2+LOCAL_PLIST="${HOME}/Library/LaunchAgents/com.trycua.cua-driver-local.plist"+RESTORE_STANDARD_DAEMON=0+restore_standard_daemon() {+ local command_status=$?+ trap - EXIT+ if [[ "${RESTORE_STANDARD_DAEMON}" != 1 ]]; then+ exit "${command_status}"+ fi+ set +e+ echo "[AUTHORIZATION] Restoring the worker's standard autostart daemon"+ "${INSTALLED_BIN}" stop --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" >/dev/null 2>&1+ launchctl load "${LOCAL_PLIST}"+ local standard_ready=0+ for _ in 1 2 3 4 5 6 7 8 9 10; do+ if "${INSTALLED_BIN}" status --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" \+ | grep -Fq "permission mode: standard"; then+ standard_ready=1+ break+ fi+ sleep 1+ done+ if [[ "${standard_ready}" != 1 ]]; then+ echo "The disposable worker could not restore its standard autostart daemon" >&2+ if [[ "${command_status}" == 0 ]]; then+ command_status=1+ fi+ fi+ set -e+ exit "${command_status}"+}+trap restore_standard_daemon EXIT++echo "[AUTHORIZATION] Starting the disposable worker daemon in unrestricted mode"+launchctl unload "${LOCAL_PLIST}" 2>/dev/null || true+"${INSTALLED_BIN}" stop --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" >/dev/null 2>&1 || true+RESTORE_STANDARD_DAEMON=1+open -n -g /Applications/CuaDriverLocal.app --args \+ serve \+ --permission-mode unrestricted \+ --dangerously-bypass-approvals+UNRESTRICTED_READY=0+for _ in 1 2 3 4 5 6 7 8 9 10; do+ if "${INSTALLED_BIN}" status --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" \+ | grep -Fq "permission mode: unrestricted"; then+ UNRESTRICTED_READY=1+ break+ fi+ sleep 1+done+if [[ "${UNRESTRICTED_READY}" != 1 ]]; then+ echo "The macOS behavior matrix could not start its unrestricted worker daemon" >&2exit 1fi@@ -190,9 +234,6 @@ if ! "${INSTALLED_BIN}" list_apps '{}' > "${ARTIFACT_DIR}/driver-list-apps.json"exit 2fi-# install-local.sh intentionally uses a separate namespace from release installs.-export CUA_E2E_MACOS_DAEMON_SOCKET="${CUA_E2E_MACOS_DAEMON_SOCKET:-${HOME}/Library/Caches/cua-driver-local/cua-driver-local.sock}"-echo "[E2E] Running the canonical macOS matrix"if [[ "${NO_BUILD}" == 1 ]]; then"${REPO_ROOT}/scripts/ci/macos/run-rust-e2e.sh" --no-build@@ -202,28 +243,6 @@ fiif [[ "${RUN_STANDALONE_BROWSER}" == 1 ]]; thenecho "[E2E] Running the optional standalone browser matrix"- LOCAL_PLIST="${HOME}/Library/LaunchAgents/com.trycua.cua-driver-local.plist"- echo "[AUTHORIZATION] Restarting the disposable worker daemon in unrestricted mode"- launchctl unload "${LOCAL_PLIST}" 2>/dev/null || true- "${INSTALLED_BIN}" stop --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" >/dev/null 2>&1 || true- open -n -g /Applications/CuaDriverLocal.app --args \- serve \- --permission-mode unrestricted \- --dangerously-bypass-approvals- UNRESTRICTED_READY=0- for _ in 1 2 3 4 5 6 7 8 9 10; do- if "${INSTALLED_BIN}" status --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" \- | grep -Fq "permission mode: unrestricted"; then- UNRESTRICTED_READY=1- break- fi- sleep 1- done- if [[ "${UNRESTRICTED_READY}" != 1 ]]; then- echo "The standalone-browser lane could not start its unrestricted worker daemon" >&2- exit 1- fi-BROWSER_ARTIFACT_DIR="${REPO_ROOT}/artifacts/cua-driver/macos-standalone-browser"if [[ -d "${BROWSER_ARTIFACT_DIR}" ]] \&& [[ -n "$(find "${BROWSER_ARTIFACT_DIR}" -mindepth 1 -print -quit)" ]]; then@@ -237,9 +256,6 @@ if [[ "${RUN_STANDALONE_BROWSER}" == 1 ]]; thenBROWSER_STATUS=$?set -e- echo "[AUTHORIZATION] Restoring the worker's standard autostart daemon"- "${INSTALLED_BIN}" stop --socket "${CUA_E2E_MACOS_DAEMON_SOCKET}" >/dev/null 2>&1 || true- launchctl load "${LOCAL_PLIST}"if [[ "${BROWSER_STATUS}" != 0 ]]; thenexit "${BROWSER_STATUS}"fidiff --git a/scripts/ci/linux/run-rust-e2e.sh b/scripts/ci/linux/run-rust-e2e.shindex ee3fd87517..1c348d9b89 100755--- a/scripts/ci/linux/run-rust-e2e.sh+++ b/scripts/ci/linux/run-rust-e2e.sh@@ -57,6 +57,12 @@ export CUA_TEST_APPS_ROOT="${RUST_ROOT}/test-apps"export CUA_TEST_REQUIRE_FIXTURES=1export CUA_TEST_DRIVER_STDERR=1export CUA_E2E_FORBID_SKIPS=1+# The canonical behavior matrix runs inside a disposable CI desktop and must+# exercise protected GUI operations without interactive approvals. This+# testkit-only switch authorizes its spawned behavior daemons without leaking+# product authorization variables into SDK/runtime tests in the same runner.+# Focused tests can still select standard/bounded mode explicitly.+export CUA_E2E_UNRESTRICTED_GUI=1# This runner contract requires a real or virtual desktop. Make GUI-dependent# lifecycle proofs fail instead of silently returning without evidence.export CUA_REQUIRE_GUI=1@@ -172,6 +178,8 @@ run_test() {}if [[ "${SUITE}" == shared || "${SUITE}" == all ]]; then+ run_test protected-permission-prompt-socket \+ cargo test -p cua-driver --test permission_prompt_authorization_test -- --test-threads=1run_test sdk-runtime-contract \cargo test -p cua-driver-sdk --lib -- --test-threads=1run_test sdk-runtime-configuration \diff --git a/scripts/ci/macos/run-rust-e2e.sh b/scripts/ci/macos/run-rust-e2e.shindex a998f642d5..6f7377663c 100755--- a/scripts/ci/macos/run-rust-e2e.sh+++ b/scripts/ci/macos/run-rust-e2e.sh@@ -18,6 +18,8 @@ Usage: run-rust-e2e.sh [--no-build]Run from a logged-in macOS desktop after install-local and TCC authorization.The testkit proxies MCP calls through the installed CuaDriver daemon.The installed daemon must embed the same CUA_DRIVER_SOURCE_SHA as this source.+Because this is a disposable behavior-test desktop, that daemon must have been+started with --permission-mode unrestricted --dangerously-bypass-approvals.Maintainers should use libs/cua-driver/tests/runners/macos-lume/run-all.sh.The contributor-facing command always runs the complete matrix.EOF@@ -115,6 +117,14 @@ if [[ ! -x "${CUA_TEST_DRIVER_BIN}" ]]; thenecho "Required driver binary was not built: ${CUA_TEST_DRIVER_BIN}" >&2exit 1fi+MACOS_DAEMON_SOCKET="${CUA_E2E_MACOS_DAEMON_SOCKET:-${HOME}/Library/Caches/cua-driver/cua-driver.sock}"+MACOS_DAEMON_BIN="${CUA_E2E_INSTALLED_DRIVER_BIN:-${CUA_TEST_DRIVER_BIN}}"+if ! "${MACOS_DAEMON_BIN}" status --socket "${MACOS_DAEMON_SOCKET}" \+ | grep -Fq "permission mode: unrestricted"; then+ echo "macOS canonical E2E requires an explicitly unrestricted disposable worker daemon" >&2+ echo "Use tests/runners/macos-lume/run-all.sh, which restores standard mode afterward" >&2+ exit 1+firequired_fixtures=()required_fixtures+=("${CUA_TEST_APPS_ROOT}/harness-electron/CuaTestHarness.Electron.app")@@ -174,6 +184,10 @@ run_test() {}if [[ "${SUITE}" == shared || "${SUITE}" == all ]]; then+ run_test protected-permission-prompt-socket cargo test -p cua-driver \+ --test permission_prompt_authorization_test -- --test-threads=1+ run_test protected-host-self-launch cargo test -p platform-macos \+ launch_app::tests -- --test-threads=1run_test sdk-runtime-contract cargo test -p cua-driver-sdk --lib -- --test-threads=1run_test sdk-runtime-configuration cargo test -p cua-driver-sdk \--test runtime_configuration -- --test-threads=1diff --git a/scripts/ci/windows/run-rust-e2e.ps1 b/scripts/ci/windows/run-rust-e2e.ps1index 65416523eb..ac58255147 100644--- a/scripts/ci/windows/run-rust-e2e.ps1+++ b/scripts/ci/windows/run-rust-e2e.ps1@@ -50,6 +50,11 @@ $env:CUA_TEST_APPS_ROOT = Join-Path $rustRoot "test-apps"$env:CUA_TEST_REQUIRE_FIXTURES = "1"$env:CUA_TEST_DRIVER_STDERR = "1"$env:CUA_E2E_FORBID_SKIPS = "1"+# This matrix runs in a disposable, authenticated desktop session. This+# testkit-only switch gives spawned behavior daemons explicit unrestricted+# authorization without leaking product authorization variables into the+# SDK/runtime tests executed by this runner.+$env:CUA_E2E_UNRESTRICTED_GUI = "1"$sourceMarker = Join-Path $repoRoot ".cua-e2e-source-sha"if (Test-Path $sourceMarker) {$env:CUA_E2E_SOURCE_MARKER = $sourceMarker@@ -255,6 +260,10 @@ function Test-E2eRecordings {$script:FailureCount = 0if ($suite -in @("shared", "all")) {+ Invoke-CargoTest "protected permission prompt socket" @(+ "test", "-p", "cua-driver", "--test", "permission_prompt_authorization_test", "--",+ "--test-threads=1"+ )Invoke-CargoTest "SDK runtime contract" @("test", "-p", "cua-driver-sdk", "--lib", "--", "--test-threads=1")