Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(driver): add YAML and Rego permission policies (#2235)

r33drichardsafb25d740ba7
diff --git a/.github/workflows/ci-nix-linux.yml b/.github/workflows/ci-nix-linux.yml
index b99fff3480..2ae8d65cb2 100644
--- a/.github/workflows/ci-nix-linux.yml
+++ b/.github/workflows/ci-nix-linux.yml
@@ -42,6 +42,10 @@ jobs:
attribute: cua-driver-build
- name: Rust unit tests
attribute: cua-driver-linux-rust-unit
+ - name: YAML policy VM
+ attribute: cua-driver-policy-yaml
+ - name: Rego policy VM
+ attribute: cua-driver-policy-rego
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Install Nix
diff --git a/docs/content/docs/concepts/how-permission-policies-work.mdx b/docs/content/docs/concepts/how-permission-policies-work.mdx
new file mode 100644
index 0000000000..fc6cc9d433
--- /dev/null
+++ b/docs/content/docs/concepts/how-permission-policies-work.mdx
@@ -0,0 +1,90 @@
+---
+title: How permission policies work
+description: How the Cua Driver permission policy engine evaluates YAML and Rego policies, the trust model, and the guarantees the engine makes.
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+Cua Driver's permission policy engine sits between an MCP client and the tool implementation. Before the driver executes any tool call it asks the policy engine whether the call is allowed. This page explains how the engine is structured, when it is active, and what guarantees it provides.
+
+## The enforcement point
+
+Every MCP tool call passes through one of two dispatch paths:
+
+- **In-process dispatch.** The MCP server receives the call directly, normalizes arguments, and executes the tool in the same process.
+- **Daemon-proxy dispatch.** A thin `cua-driver mcp` process proxies the call to a running `cua-driver serve` daemon over a Unix socket.
+
+The policy engine is invoked at the in-process MCP handler and at the proxy layer: once in the proxy before it forwards the call, and once in the daemon before it executes it. A policy denial at either point returns an error to the client; the tool implementation is never reached.
+
+## Deny-by-default
+
+The engine is deny-by-default. A tool that is not explicitly mentioned in the policy is blocked. This means adding a new tool to the driver does not automatically expose it to agents; each tool must be explicitly permitted.
+
+The deny-by-default behavior applies only when a policy is active. When `CUA_DRIVER_POLICY_FILE` is not set, the engine is disabled and every call is allowed, preserving the driver's original behavior for users who do not need access control.
+
+## Process-lifetime snapshot
+
+The policy file is loaded once when the daemon or in-process server starts. All subsequent calls share the same immutable policy object for the lifetime of that process. There is no reload endpoint and no hot-swap path. Changing the policy takes effect only after the process restarts.
+
+This makes the policy a reliable static contract: the same rule that was in effect when the daemon started will still be in effect when the last tool call of the session runs.
+
+## YAML evaluation
+
+A YAML policy encodes three data structures at load time:
+
+- A set of denied tool names (`deny.tools`). These are checked first, before allow rules.
+- A set of unconditionally allowed tool names (`allow.tools`).
+- A list of compiled rules (`allow.rules`), each pairing a tool name with a set of compiled constraints.
+
+At evaluation time, for a given `(tool, arguments)` pair:
+
+1. If the tool name is in the deny set, return **Deny**.
+2. If the tool name is in the allow set, return **Allow**.
+3. Find all rules whose `tool` field matches. If there are none, return **Deny**.
+4. For each matching rule, test all constraints against the argument object. If all pass, return **Allow**. If any fail, collect the failure reason and try the next rule.
+5. If no rule passed, return **Deny** with the collected reasons.
+
+Regular expression patterns in YAML constraints are compiled once at load time using the RE2-compatible Rust regex engine. There is no backtracking and no lookahead, which bounds evaluation time regardless of input length.
+
+## Rego evaluation
+
+Rego policies are loaded into a [Regorus](https://github.com/microsoft/regorus) engine — a Rust-native OPA evaluator — at process startup. The engine validates that `data.cua.policy.allow` exists and evaluates to a boolean on a synthetic input before accepting the policy. A policy whose rule returns the wrong type is rejected at load time, not at call time.
+
+At evaluation time, the driver:
+
+1. Constructs the input object: `{ "server": "cua-driver", "tool": "<canonical name>", "arguments": { … } }`.
+2. Clones the engine (the clone carries the compiled policy but gets a fresh input).
+3. Sets the input and evaluates `data.cua.policy.allow`.
+4. Maps the result: `true` → Allow, `false` or `undefined` → Deny, error → Error.
+
+Because Regorus runs fully in-process and does not spawn a subprocess, there is no IPC overhead for each call.
+
+## Argument sanitization before evaluation
+
+Two transformations happen before the arguments reach the policy engine:
+
+- **`_session_id` removal.** The daemon injects a `_session_id` field for session tracking. This is an internal implementation detail that is not relevant to policy decisions, so it is stripped before evaluation.
+- **Tool name canonicalization.** The deprecated `type_text_chars` alias is normalized to `type_text` before any rule is consulted, so policies written against the canonical name cover both forms automatically.
+
+## What the engine does not cover
+
+The policy engine controls **which tool calls are executed**. It does not:
+
+- Inspect or modify tool responses.
+- Limit screenshot output, file paths read, or network traffic.
+- Enforce rate limits or per-session quotas.
+- Authenticate or identify the caller.
+
+A policy that allows `screenshot` permits an agent to take an unlimited number of screenshots. A policy that allows `type_text` with a length constraint still permits the agent to call `type_text` up to the character limit on each call. Use the policy to define an allowed set of operations; combine it with OS-level sandboxing and process isolation if you need stronger guarantees.
+
+## Trust model
+
+The policy is evaluated in the same process as the tool implementation. An agent that has arbitrary code execution on the host can bypass the policy by calling the tool implementation directly. The engine is designed for use with agents that interact over the MCP protocol, not as a security boundary against code running locally.
+
+For remote agents connecting through the daemon's network socket, the policy provides a meaningful boundary: the daemon will not execute a tool that the policy blocks, regardless of what the agent sends.
+
+## Related
+
+- [Restrict tool access with permission policies](/how-to-guides/driver/restrict-tool-access): step-by-step setup guide
+- [Permission policies](/reference/cua-driver/permission-policies): YAML schema and Rego input interface
+- [Process model](/reference/cua-driver/process-model): how the daemon and in-process MCP server relate
diff --git a/docs/content/docs/concepts/meta.json b/docs/content/docs/concepts/meta.json
index 165fdab216..e1cca1107c 100644
--- a/docs/content/docs/concepts/meta.json
+++ b/docs/content/docs/concepts/meta.json
@@ -1 +1 @@
-{ "title": "Concepts", "icon": "Lightbulb", "pages": ["index", "what-is-computer-use", "the-no-foreground-contract", "capture-and-delivery-modalities", "how-cua-driver-is-validated", "how-sandboxes-work", "how-lume-unattended-setup-works", "how-sip-works-in-lume-vms", "how-lume-expands-macos-disks"] }
+{ "title": "Concepts", "icon": "Lightbulb", "pages": ["index", "what-is-computer-use", "the-no-foreground-contract", "capture-and-delivery-modalities", "how-permission-policies-work", "how-cua-driver-is-validated", "how-sandboxes-work", "how-lume-unattended-setup-works", "how-sip-works-in-lume-vms", "how-lume-expands-macos-disks"] }
diff --git a/docs/content/docs/how-to-guides/driver/meta.json b/docs/content/docs/how-to-guides/driver/meta.json
index 256d587f5b..0d0735f10d 100644
--- a/docs/content/docs/how-to-guides/driver/meta.json
+++ b/docs/content/docs/how-to-guides/driver/meta.json
@@ -1 +1 @@
-{ "title": "Driver", "pages": ["install", "connect-your-agent", "drive-a-web-page", "keep-running", "personalize-cursor", "update", "windows-ssh"] }
+{ "title": "Driver", "pages": ["install", "connect-your-agent", "drive-a-web-page", "keep-running", "restrict-tool-access", "personalize-cursor", "update", "windows-ssh"] }
diff --git a/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx b/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx
new file mode 100644
index 0000000000..2d5f6460d5
--- /dev/null
+++ b/docs/content/docs/how-to-guides/driver/restrict-tool-access.mdx
@@ -0,0 +1,219 @@
+---
+title: Restrict tool access with permission policies
+description: Use YAML or Rego policies to control which MCP tools an agent can call and what arguments it may pass.
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+import { Tabs, Tab } from 'fumadocs-ui/components/tabs';
+
+Cua Driver's permission policy engine lets you define exactly which tools an agent may call, and — for sensitive tools — restrict the argument values it can supply. The engine is deny-by-default: any tool not explicitly allowed is blocked. Two policy formats are supported — YAML for straightforward allow/deny lists and Rego for programmable logic.
+
+## Before you start
+
+- Cua Driver installed and working (`cua-driver --version`)
+- A running `cua-driver serve` daemon (or a process about to be started)
+- For Rego policies: a build with the `rego` feature enabled (included in the default release binary)
+
+## Create a YAML policy
+
+Create a file, for example `~/.cua-driver/policy.yaml`, that lists the tools you want to allow:
+
+```yaml
+allow:
+ tools:
+ - screenshot
+ - get_window_state
+ - list_apps
+ - list_windows
+ - click
+ - type_text
+ - press_key
+ - scroll
+ - launch_app
+ - wait
+deny:
+ tools:
+ - shell_execute
+```
+
+Every tool in `allow.tools` is unconditionally permitted. Every tool in `deny.tools` is rejected even if it also appears in an allow rule. Any tool not mentioned in either section is denied by the default policy.
+
+## Add argument constraints to a YAML policy
+
+Use `allow.rules` to permit a tool only when its arguments satisfy bounds, length, pattern, or allowed-value checks:
+
+```yaml
+allow:
+ tools:
+ - screenshot
+ - get_window_state
+ rules:
+ - tool: type_text
+ constraints:
+ text:
+ max_length: 500
+ pattern: "^[\\x20-\\x7E\\n\\t]*$" # printable ASCII only
+ - tool: scroll
+ constraints:
+ amount:
+ min: -20
+ max: 20
+ - tool: launch_app
+ constraints:
+ bundle_id:
+ allowed:
+ - "com.apple.Safari"
+ - "com.google.Chrome"
+ - "com.microsoft.VSCode"
+deny:
+ tools:
+ - shell_execute
+```
+
+Each `constraints` key matches a JSON argument name. A rule allows the call only when **all** constraints pass. If you list the same tool in more than one rule, the call is allowed when **any** rule matches.
+
+<Callout type="info">
+ The `type_text_chars` tool name is automatically aliased to `type_text` before policy evaluation, so a rule on `type_text` covers both forms.
+</Callout>
+
+## Create a Rego policy
+
+For more complex access control — for example, allowing different tool sets based on the active task or runtime conditions — write a Rego policy:
+
+```rego
+package cua.policy
+
+import rego.v1
+
+# Tools that are always allowed.
+safe_tools := {
+ "screenshot",
+ "get_window_state",
+ "list_apps",
+ "list_windows",
+ "click",
+ "press_key",
+ "scroll",
+ "wait",
+}
+
+allow if {
+ input.tool in safe_tools
+}
+
+# Allow type_text only for short printable strings.
+allow if {
+ input.tool == "type_text"
+ count(input.arguments.text) <= 500
+ regex.match(`^[\x20-\x7E\n\t]*$`, input.arguments.text)
+}
+```
+
+Save this as `~/.cua-driver/policy.rego`. The policy engine evaluates `data.cua.policy.allow`; the rule must produce a boolean. `undefined` is treated as `false` (deny).
+
+## Load a policy directory (Rego only)
+
+When you point the environment variable at a directory instead of a single file, the engine loads every `.rego` file in that directory in lexicographic order:
+
+```bash
+mkdir -p ~/.cua-driver/policies
+# Place policy files in the directory:
+# 00_safe_tools.rego
+# 10_type_text.rego
+```
+
+Set the environment variable to the directory path:
+
+```bash
+export CUA_DRIVER_POLICY_FILE=~/.cua-driver/policies
+```
+
+<Callout type="warn">
+ A directory path only works with Rego. Pointing it at a directory when the `rego` feature is disabled returns an error on startup.
+</Callout>
+
+## Enable the policy
+
+Set `CUA_DRIVER_POLICY_FILE` to the path of your policy file before starting the driver:
+
+<Tabs items={['bash/zsh', 'fish', 'env for a single process']}>
+ <Tab value="bash/zsh">
+```bash
+export CUA_DRIVER_POLICY_FILE=~/.cua-driver/policy.yaml
+cua-driver serve
+```
+ </Tab>
+ <Tab value="fish">
+```fish
+set -x CUA_DRIVER_POLICY_FILE ~/.cua-driver/policy.yaml
+cua-driver serve
+```
+ </Tab>
+ <Tab value="env for a single process">
+```bash
+CUA_DRIVER_POLICY_FILE=~/.cua-driver/policy.yaml cua-driver serve
+```
+ </Tab>
+</Tabs>
+
+The policy is loaded once when the process starts. Changing the file while the daemon is running has no effect until the daemon restarts.
+
+## Verify the policy is active
+
+Make a call that should be denied and confirm the error:
+
+```bash
+cua-driver call shell_execute '{"command":"echo hello"}'
+# Error: tool 'shell_execute' is explicitly denied
+```
+
+Make a call that should be allowed:
+
+```bash
+cua-driver call screenshot '{}'
+# ✅ ...
+```
+
+## Add the policy to autostart (macOS launchd)
+
+If you use `cua-driver autostart enable`, add the environment variable to the launchd plist so it is set when the daemon starts automatically:
+
+1. Find the plist file:
+ ```bash
+ cat ~/Library/LaunchAgents/com.trycua.cua-driver.plist
+ ```
+
+2. Add an `EnvironmentVariables` key:
+ ```xml
+ <key>EnvironmentVariables</key>
+ <dict>
+ <key>CUA_DRIVER_POLICY_FILE</key>
+ <string>/Users/you/.cua-driver/policy.yaml</string>
+ </dict>
+ ```
+
+3. Reload the agent:
+ ```bash
+ launchctl unload ~/Library/LaunchAgents/com.trycua.cua-driver.plist
+ launchctl load ~/Library/LaunchAgents/com.trycua.cua-driver.plist
+ ```
+
+## Troubleshooting
+
+**All calls are denied even though my policy allows them.**
+Check that `CUA_DRIVER_POLICY_FILE` points to the correct path and that the daemon has been restarted after setting the variable. A typo in the file path means the policy file is not found, which disables enforcement and allows all calls. A warning is logged at startup when the path does not exist.
+
+**The daemon fails to start with a policy parse error.**
+YAML policies must not contain empty tool names, and Rego policies must define `data.cua.policy.allow` as a boolean rule. Run `cat $CUA_DRIVER_POLICY_FILE` to confirm the file is readable and syntactically valid.
+
+**A tool I allowed still returns a denial.**
+The rule might exist but the argument constraints are not satisfied. Check the denial message: `"argument 'text' must be at most 500 characters"` tells you which constraint failed. For Rego policies, add a `print` statement temporarily to trace which branch runs.
+
+**I want to allow all tools.**
+Do not set `CUA_DRIVER_POLICY_FILE`. When the variable is absent, the policy engine is disabled and every tool call is allowed.
+
+## Related
+
+- [Permission policies](/reference/cua-driver/permission-policies): full YAML schema and Rego interface reference
+- [How permission policies work](/concepts/how-permission-policies-work): the engine internals, evaluation order, and trust model
+- [MCP tools](/reference/cua-driver/mcp-tools): complete list of tool names and their arguments
diff --git a/docs/content/docs/reference/cua-driver/cli-reference.mdx b/docs/content/docs/reference/cua-driver/cli-reference.mdx
index f573b51583..d4cc946db4 100644
--- a/docs/content/docs/reference/cua-driver/cli-reference.mdx
+++ b/docs/content/docs/reference/cua-driver/cli-reference.mdx
@@ -7,7 +7,7 @@ description: Command-line interface specification for Cua Driver
AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
Generated by: npx tsx scripts/docs-generators/cua-driver.ts
Source: cua-driver dump-docs
- Version: 0.8.1
+ Version: 0.8.2
*/}
Cross-platform computer-use automation driver. Install via the official script:
@@ -16,7 +16,7 @@ Cross-platform computer-use automation driver. Install via the official script:
curl -fsSL https://cua.ai/driver/install.sh | bash
```
-Documented against Cua Driver **0.8.1**. Run `cua-driver --version` for your installed version.
+Documented against Cua Driver **0.8.2**. Run `cua-driver --version` for your installed version.
The macOS-only `cua-driver permissions` command is documented separately in [macOS permissions](/reference/cua-driver/macos-permissions).
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index 80e96b85fa..fd2d306f74 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -7,7 +7,7 @@ description: Reference for every MCP tool Cua Driver exposes
AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
Generated by: npx tsx scripts/docs-generators/cua-driver.ts
Source: cua-driver dump-docs
- Version: 0.8.1
+ Version: 0.8.2
*/}
import { Callout } from 'fumadocs-ui/components/callout';
diff --git a/docs/content/docs/reference/cua-driver/meta.json b/docs/content/docs/reference/cua-driver/meta.json
index ae2d6dd5a4..bb831d4a6a 100644
--- a/docs/content/docs/reference/cua-driver/meta.json
+++ b/docs/content/docs/reference/cua-driver/meta.json
@@ -8,6 +8,7 @@
"mcp-tools",
"mcp-tool-notes",
"action-selection-policy",
+ "permission-policies",
"contracts",
"platform-support",
"platform-roadmap",
diff --git a/docs/content/docs/reference/cua-driver/permission-policies.mdx b/docs/content/docs/reference/cua-driver/permission-policies.mdx
new file mode 100644
index 0000000000..d532a758fd
--- /dev/null
+++ b/docs/content/docs/reference/cua-driver/permission-policies.mdx
@@ -0,0 +1,279 @@
+---
+title: Permission policies
+description: YAML and Rego permission policy schema, environment variable, evaluation rules, and Rego input interface for Cua Driver.
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+Cua Driver evaluates a permission policy for every MCP tool call when `CUA_DRIVER_POLICY_FILE` is set. The policy is loaded once at process startup and applies to both in-process MCP dispatch and daemon-proxy dispatch. This page is the reference for the file format, evaluation rules, and Rego interface.
+
+---
+
+## Environment variable
+
+| Variable | Type | Default |
+|---|---|---|
+| `CUA_DRIVER_POLICY_FILE` | path to a `.yaml`, `.yml`, `.rego` file, or a directory | not set (policy disabled) |
+
+When the variable is absent the policy engine is disabled and every call is allowed.
+
+When the path does not exist the engine starts and logs a warning; all calls are allowed (missing file is treated as no policy).
+
+When the path exists but cannot be parsed, the engine fails to start and the daemon exits with an error.
+
+---
+
+## YAML policy format
+
+### Top-level structure
+
+```yaml
+allow: # what to permit (default: nothing allowed)
+ tools: [] # tool names allowed unconditionally
+ rules: [] # rules with argument constraints
+deny: # hard overrides (checked first)
+ tools: [] # tool names always blocked
+```
+
+Both `allow` and `deny` are optional and default to empty lists. A policy with neither section blocks every call.
+
+`deny.tools` is checked before `allow.tools` and `allow.rules`. A tool in `deny.tools` is rejected even if it also appears in an allow section.
+
+### Shorthand forms
+
+The `allow` and `deny` fields also accept a flat list of strings as a shorthand for the `tools` sub-key:
+
+```yaml
+allow:
+ - screenshot
+ - wait
+deny:
+ - shell_execute
+```
+
+### `allow.tools`
+
+A list of tool names that are permitted for any argument values. Order does not matter.
+
+```yaml
+allow:
+ tools:
+ - screenshot
+ - get_window_state
+ - list_apps
+```
+
+### `allow.rules`
+
+A list of tool rules. Each rule names a tool and an optional set of argument constraints. A call matches a rule when all constraints for that rule pass. If the same tool appears in multiple rules, the call is allowed when **any** rule matches.
+
+```yaml
+allow:
+ rules:
+ - tool: type_text
+ constraints:
+ text:
+ max_length: 200
+ - tool: scroll
+ constraints:
+ amount:
+ min: -10
+ max: 10
+```
+
+The `constraints` map keys are JSON argument names (snake_case, matching the names in [MCP tools](/reference/cua-driver/mcp-tools)).
+
+### Constraint fields
+
+Each constraint object may include one or more of the following checks. At least one check is required.
+
+| Field | Type | Applies to | Meaning |
+|---|---|---|---|
+| `min` | number | numeric argument | argument value must be ≥ this |
+| `max` | number | numeric argument | argument value must be ≤ this |
+| `max_length` | integer | string argument | Unicode codepoint count must not exceed this |
+| `pattern` | string (regex) | string argument | argument must match this regular expression |
+| `allowed` | list of JSON values | any | argument must equal one of the listed values |
+
+When both `min` and `max` are set, `min` must be ≤ `max` or the policy fails to load.
+
+The `pattern` field uses the [Rust regex crate](https://docs.rs/regex) syntax (RE2-compatible; no backtracking, no lookahead).
+
+### `deny.tools`
+
+A list of tool names that are unconditionally blocked, regardless of allow rules.
+
+```yaml
+deny:
+ tools:
+ - shell_execute
+ - run_javascript
+```
+
+### Full YAML example
+
+```yaml
+allow:
+ tools:
+ - screenshot
+ - get_window_state
+ - list_apps
+ - list_windows
+ - click
+ - press_key
+ - scroll
+ - hotkey
+ - wait
+ rules:
+ - tool: type_text
+ constraints:
+ text:
+ max_length: 500
+ pattern: "^[\\x20-\\x7E\\n\\t]*$"
+ - tool: launch_app
+ constraints:
+ bundle_id:
+ allowed:
+ - "com.apple.Safari"
+ - "com.google.Chrome"
+ - "com.microsoft.VSCode"
+ - tool: scroll
+ constraints:
+ amount:
+ min: -20
+ max: 20
+deny:
+ tools:
+ - shell_execute
+ - run_javascript
+```
+
+---
+
+## Rego policy format
+
+Rego policies must define a rule named `data.cua.policy.allow`. The engine uses [Regorus](https://github.com/microsoft/regorus) 0.10.x, which implements the OPA policy language.
+
+### Package declaration
+
+```rego
+package cua.policy
+```
+
+### `allow` rule
+
+The rule must evaluate to a `boolean`. `undefined` is treated as `false` (deny).
+
+```rego
+package cua.policy
+
+import rego.v1
+
+allow if {
+ # rule body
+}
+```
+
+### Input object
+
+The engine sets `input` to the following object for each call:
+
+| Field | Type | Description |
+|---|---|---|
+| `input.server` | string | Always `"cua-driver"` |
+| `input.tool` | string | Canonical tool name (e.g. `"type_text"`) |
+| `input.arguments` | object | Tool arguments with `_session_id` removed |
+
+`input.tool` is normalized before evaluation: `type_text_chars` is mapped to `type_text`.
+
+### Minimal Rego example
+
+```rego
+package cua.policy
+
+import rego.v1
+
+safe_tools := {
+ "screenshot",
+ "get_window_state",
+ "list_apps",
+ "list_windows",
+ "click",
+ "press_key",
+ "scroll",
+ "wait",
+}
+
+allow if {
+ input.tool in safe_tools
+}
+
+allow if {
+ input.tool == "type_text"
+ count(input.arguments.text) <= 500
+}
+```
+
+### Loading multiple Rego files
+
+Point `CUA_DRIVER_POLICY_FILE` at a directory to load all `.rego` files in that directory. Files are loaded in lexicographic order (sort by filename), which controls rule merge order across files.
+
+```
+~/.cua-driver/policies/
+ 00_base.rego
+ 10_type_text.rego
+ 20_launch_app.rego
+```
+
+```bash
+export CUA_DRIVER_POLICY_FILE=~/.cua-driver/policies
+```
+
+---
+
+## Evaluation order
+
+For YAML policies:
+
+1. Check `deny.tools` — if the tool is listed, **deny** immediately.
+2. Check `allow.tools` — if the tool is listed, **allow** immediately.
+3. Evaluate `allow.rules` for matching rules — if any rule's constraints pass, **allow**.
+4. No match — **deny** with `"tool 'X' is not allowed by the YAML policy"`.
+
+For Rego policies:
+
+1. Evaluate `data.cua.policy.allow` with the call's input.
+2. `true` → **allow**; `false` or `undefined` → **deny**; evaluation error → **error** (the call is blocked with the engine error message).
+
+---
+
+## Tool name normalization
+
+Before any policy evaluation the driver canonicalizes deprecated aliases:
+
+| Alias | Canonical name |
+|---|---|
+| `type_text_chars` | `type_text` |
+
+Write policies against the canonical name; the alias is accepted automatically.
+
+---
+
+## Denial response
+
+When a call is blocked, the MCP response is a tool error with a human-readable message:
+
+```
+Permission denied: tool 'shell_execute' is explicitly denied
+Permission denied: tool 'launch_app' is not allowed by the YAML policy
+Permission denied: tool 'type_text' argument constraints were not satisfied: argument 'text' must be at most 500 characters
+Permission denied: tool 'launch_app' is not allowed by the Rego policy
+```
+
+---
+
+## Related
+
+- [Restrict tool access with permission policies](/how-to-guides/driver/restrict-tool-access): step-by-step setup guide
+- [How permission policies work](/concepts/how-permission-policies-work): evaluation engine internals and trust model
+- [MCP tools](/reference/cua-driver/mcp-tools): tool names and argument schemas
diff --git a/flake.nix b/flake.nix
index 7fe61048bc..59169cb306 100644
--- a/flake.nix
+++ b/flake.nix
@@ -128,6 +128,14 @@
inherit pkgs;
src = rustSrc;
};
+ cua-driver-policy-yaml = import ./nix/cua-driver/tests/policy-yaml.nix {
+ inherit pkgs;
+ cuaDriver = cuaDriverPackage;
+ };
+ cua-driver-policy-rego = import ./nix/cua-driver/tests/policy-rego.nix {
+ inherit pkgs;
+ cuaDriver = cuaDriverPackage;
+ };
};
devShells.cua-driver-wayland-e2e = waylandE2eShell [ ];
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 4d35084711..b87601d34b 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -8,6 +8,20 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "ahash"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
+dependencies = [
+ "cfg-if",
+ "getrandom 0.3.4",
+ "once_cell",
+ "serde",
+ "version_check",
+ "zerocopy",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.4"
@@ -17,6 +31,21 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "allocator-api2"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "annotate-snippets"
version = "0.9.2"
@@ -299,6 +328,21 @@ dependencies = [
"syn",
]
+[[package]]
+name = "bit-set"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
+dependencies = [
+ "bit-vec",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
+
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -354,12 +398,34 @@ dependencies = [
"piper",
]
+[[package]]
+name = "borrow-or-share"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c"
+
+[[package]]
+name = "bstr"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530"
+dependencies = [
+ "memchr",
+ "serde_core",
+]
+
[[package]]
name = "bumpalo"
version = "3.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
+[[package]]
+name = "bytecount"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e"
+
[[package]]
name = "bytemuck"
version = "1.25.0"
@@ -432,6 +498,40 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+[[package]]
+name = "chacha20"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.0",
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "chrono"
+version = "0.4.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
+dependencies = [
+ "iana-time-zone",
+ "js-sys",
+ "num-traits",
+ "wasm-bindgen",
+ "windows-link 0.2.1",
+]
+
+[[package]]
+name = "chrono-tz"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
+dependencies = [
+ "chrono",
+ "phf",
+]
+
[[package]]
name = "clang-sys"
version = "1.8.1"
@@ -443,6 +543,15 @@ dependencies = [
"libloading",
]
+[[package]]
+name = "cobs"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
+dependencies = [
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "concurrent-queue"
version = "2.5.0"
@@ -557,6 +666,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.0"
@@ -639,9 +757,13 @@ dependencies = [
"anyhow",
"async-trait",
"image",
+ "regex",
+ "regorus",
"serde",
"serde_json",
- "thiserror",
+ "serde_yaml_ng",
+ "tempfile",
+ "thiserror 1.0.69",
"tokio",
"tracing",
"windows 0.58.0",
@@ -783,6 +905,15 @@ version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
+[[package]]
+name = "email_address"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "embed-manifest"
version = "1.5.0"
@@ -803,6 +934,18 @@ dependencies = [
"winreg",
]
+[[package]]
+name = "embedded-io"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced"
+
+[[package]]
+name = "embedded-io"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
+
[[package]]
name = "endi"
version = "1.1.1"
@@ -865,7 +1008,7 @@ dependencies = [
"cfg-if",
"libc",
"nix 0.23.2",
- "thiserror",
+ "thiserror 1.0.69",
]
[[package]]
@@ -889,6 +1032,17 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "fancy-regex"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1e1dacd0d2082dfcf1351c4bdd566bbe89a2b263235a2b50058f1e130a47277"
+dependencies = [
+ "bit-set",
+ "regex-automata",
+ "regex-syntax",
+]
+
[[package]]
name = "fastrand"
version = "2.4.1"
@@ -936,6 +1090,17 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
+[[package]]
+name = "fluent-uri"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e"
+dependencies = [
+ "borrow-or-share",
+ "ref-cast",
+ "serde",
+]
+
[[package]]
name = "fnv"
version = "1.0.7"
@@ -948,6 +1113,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
[[package]]
name = "fontdb"
version = "0.22.0"
@@ -1011,6 +1182,16 @@ dependencies = [
"percent-encoding",
]
+[[package]]
+name = "fraction"
+version = "0.15.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e076045bb43dac435333ed5f04caf35c7463631d0dae2deb2638d94dd0a5b872"
+dependencies = [
+ "lazy_static",
+ "num",
+]
+
[[package]]
name = "funty"
version = "2.0.0"
@@ -1149,6 +1330,20 @@ dependencies = [
"wasi",
]
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+ "wasm-bindgen",
+]
+
[[package]]
name = "getrandom"
version = "0.4.2"
@@ -1157,7 +1352,8 @@ checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
dependencies = [
"cfg-if",
"libc",
- "r-efi",
+ "r-efi 6.0.0",
+ "rand_core 0.10.1",
"wasip2",
"wasip3",
]
@@ -1168,13 +1364,36 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
+[[package]]
+name = "globset"
+version = "0.4.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e47d37d2ae4464254884b60ab7071be2b876a9c35b696bd018ddcc76847309cd"
+dependencies = [
+ "aho-corasick",
+ "bstr",
+ "regex-automata",
+ "regex-syntax",
+]
+
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
- "foldhash",
+ "foldhash 0.1.5",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash 0.2.0",
]
[[package]]
@@ -1217,6 +1436,30 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+[[package]]
+name = "iana-time-zone"
+version = "0.1.65"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
+dependencies = [
+ "android_system_properties",
+ "core-foundation-sys",
+ "iana-time-zone-haiku",
+ "js-sys",
+ "log",
+ "wasm-bindgen",
+ "windows-core 0.61.2",
+]
+
+[[package]]
+name = "iana-time-zone-haiku"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "icu_collections"
version = "2.2.0"
@@ -1359,6 +1602,12 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "ipnet"
+version = "2.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
+
[[package]]
name = "itertools"
version = "0.12.1"
@@ -1386,6 +1635,42 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "jsonschema"
+version = "0.46.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0a699d3e77675e6aa4bfffe3b907c8b5f7ed3241f9965bffb25475ad4b08d05"
+dependencies = [
+ "ahash",
+ "bytecount",
+ "data-encoding",
+ "email_address",
+ "fancy-regex",
+ "fraction",
+ "getrandom 0.3.4",
+ "idna",
+ "itoa",
+ "jsonschema-regex",
+ "num-cmp",
+ "num-traits",
+ "percent-encoding",
+ "referencing",
+ "regex",
+ "serde",
+ "serde_json",
+ "unicode-general-category",
+ "uuid-simd",
+]
+
+[[package]]
+name = "jsonschema-regex"
+version = "0.46.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbd1086b01b9349fd4ef9a07433965af64c8ce8159abe633a189e4ff817bd13"
+dependencies = [
+ "regex-syntax",
+]
+
[[package]]
name = "kurbo"
version = "0.11.3"
@@ -1507,6 +1792,12 @@ version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+[[package]]
+name = "lru"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b6180140927ee907000b0aa540091f6ea512ead4447c92b8fc35bc72788a5a6"
+
[[package]]
name = "matchers"
version = "0.2.0"
@@ -1559,6 +1850,12 @@ dependencies = [
"nom 1.2.4",
]
+[[package]]
+name = "micromap"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74"
+
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -1596,6 +1893,15 @@ dependencies = [
"pxfm",
]
+[[package]]
+name = "msvc_spectre_libs"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29e871a9861f3664f18b7e04e9301d4edd55090c2dadb4b1c602e26ab32b1f5b"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "native-tls"
version = "0.2.18"
@@ -1662,12 +1968,81 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "num"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
+dependencies = [
+ "num-bigint",
+ "num-complex",
+ "num-integer",
+ "num-iter",
+ "num-rational",
+ "num-traits",
+]
+
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-cmp"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa"
+
+[[package]]
+name = "num-complex"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "num-conv"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967"
+[[package]]
+name = "num-integer"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-iter"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-bigint",
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -1841,6 +2216,12 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "outref"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
+
[[package]]
name = "parking"
version = "2.2.1"
@@ -1876,6 +2257,24 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+[[package]]
+name = "phf"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
+dependencies = [
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_shared"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
+dependencies = [
+ "siphasher",
+]
+
[[package]]
name = "pico-args"
version = "0.5.0"
@@ -1922,7 +2321,7 @@ dependencies = [
"nix 0.27.1",
"once_cell",
"pipewire-sys",
- "thiserror",
+ "thiserror 1.0.69",
]
[[package]]
@@ -1967,7 +2366,7 @@ dependencies = [
"reis",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 1.0.69",
"tiny-skia",
"tokio",
"tracing",
@@ -2009,7 +2408,7 @@ dependencies = [
"screencapturekit",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 1.0.69",
"tiny-skia",
"tokio",
"tokio-tungstenite",
@@ -2031,7 +2430,7 @@ dependencies = [
"pip-preview",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 1.0.69",
"tiny-skia",
"tokio",
"tracing",
@@ -2078,6 +2477,18 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "postcard"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
+dependencies = [
+ "cobs",
+ "embedded-io 0.4.0",
+ "embedded-io 0.6.1",
+ "serde",
+]
+
[[package]]
name = "potential_utf"
version = "0.1.5"
@@ -2155,6 +2566,12 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
[[package]]
name = "r-efi"
version = "6.0.0"
@@ -2175,7 +2592,18 @@ checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
dependencies = [
"libc",
"rand_chacha",
- "rand_core",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "rand"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.2",
+ "rand_core 0.10.1",
]
[[package]]
@@ -2185,7 +2613,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
- "rand_core",
+ "rand_core 0.6.4",
]
[[package]]
@@ -2197,6 +2625,12 @@ dependencies = [
"getrandom 0.2.17",
]
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -2214,7 +2648,44 @@ checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
dependencies = [
"getrandom 0.2.17",
"libredox",
- "thiserror",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "ref-cast"
+version = "1.0.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d"
+dependencies = [
+ "ref-cast-impl",
+]
+
+[[package]]
+name = "ref-cast-impl"
+version = "1.0.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "referencing"
+version = "0.46.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fbf332a2f81899f6836f22c03da73dae8a664c32e3016b84692c23cddadc95d"
+dependencies = [
+ "ahash",
+ "fluent-uri",
+ "getrandom 0.3.4",
+ "hashbrown 0.16.1",
+ "itoa",
+ "micromap",
+ "parking_lot",
+ "percent-encoding",
+ "serde_json",
]
[[package]]
@@ -2246,6 +2717,39 @@ version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
+[[package]]
+name = "regorus"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "419a0413adeece71e4d4a64fb75adc359cb807496f0dfd10f429517be908b807"
+dependencies = [
+ "anyhow",
+ "chrono",
+ "chrono-tz",
+ "data-encoding",
+ "globset",
+ "indexmap",
+ "ipnet",
+ "jsonschema",
+ "lazy_static",
+ "lru",
+ "msvc_spectre_libs",
+ "num-bigint",
+ "num-traits",
+ "parking_lot",
+ "postcard",
+ "rand 0.10.2",
+ "regex",
+ "semver",
+ "serde",
+ "serde_json",
+ "serde_yaml",
+ "spin",
+ "thiserror 2.0.18",
+ "url",
+ "uuid",
+]
+
[[package]]
name = "reis"
version = "0.7.0"
@@ -2389,6 +2893,12 @@ dependencies = [
"unicode-script",
]
+[[package]]
+name = "ryu"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+
[[package]]
name = "schannel"
version = "0.1.29"
@@ -2506,6 +3016,32 @@ dependencies = [
"serde",
]
+[[package]]
+name = "serde_yaml"
+version = "0.9.34+deprecated"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
+dependencies = [
+ "indexmap",
+ "itoa",
+ "ryu",
+ "serde",
+ "unsafe-libyaml",
+]
+
+[[package]]
+name = "serde_yaml_ng"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f"
+dependencies = [
+ "indexmap",
+ "itoa",
+ "ryu",
+ "serde",
+ "unsafe-libyaml",
+]
+
[[package]]
name = "sha1"
version = "0.10.6"
@@ -2513,7 +3049,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
- "cpufeatures",
+ "cpufeatures 0.2.17",
"digest",
]
@@ -2594,6 +3130,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "spin"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3"
+
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -2707,7 +3249,16 @@ version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
- "thiserror-impl",
+ "thiserror-impl 1.0.69",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
+dependencies = [
+ "thiserror-impl 2.0.18",
]
[[package]]
@@ -2721,6 +3272,17 @@ dependencies = [
"syn",
]
+[[package]]
+name = "thiserror-impl"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "thread_local"
version = "1.1.9"
@@ -3020,9 +3582,9 @@ dependencies = [
"httparse",
"log",
"native-tls",
- "rand",
+ "rand 0.8.6",
"sha1",
- "thiserror",
+ "thiserror 1.0.69",
"utf-8",
]
@@ -3061,6 +3623,12 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "260bc6647b3893a9a90668360803a15f96b85a5257b1c3a0c3daf6ae2496de42"
+[[package]]
+name = "unicode-general-category"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f"
+
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -3103,6 +3671,12 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+[[package]]
+name = "unsafe-libyaml"
+version = "0.2.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
+
[[package]]
name = "untrusted"
version = "0.9.0"
@@ -3206,10 +3780,21 @@ checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76"
dependencies = [
"getrandom 0.4.2",
"js-sys",
+ "rand 0.10.2",
"serde_core",
"wasm-bindgen",
]
+[[package]]
+name = "uuid-simd"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8"
+dependencies = [
+ "outref",
+ "vsimd",
+]
+
[[package]]
name = "valuable"
version = "0.1.1"
@@ -3234,6 +3819,12 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+[[package]]
+name = "vsimd"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
+
[[package]]
name = "vswhom"
version = "0.1.0"
diff --git a/libs/cua-driver/rust/README.md b/libs/cua-driver/rust/README.md
index 96b339b73b..8cb4f69444 100644
--- a/libs/cua-driver/rust/README.md
+++ b/libs/cua-driver/rust/README.md
@@ -55,3 +55,40 @@ See `crates/cua-driver/tests/README.md` for the test matrix.
- `target/`: Cargo output, ignored.
- `test-apps/harness-*/`: staged harness apps, ignored.
- `test-apps/README.md`: explains how staged harness outputs are produced.
+
+## Permission Policies
+
+Set `CUA_DRIVER_POLICY_FILE` to enforce a deny-by-default policy on MCP
+`tools/call` requests. If the variable is unset, or points to a path that does
+not exist, the driver keeps its backward-compatible behavior with no policy
+enforcement. Supported paths are:
+
+- `.yaml` / `.yml`: a single YAML policy file.
+- `.rego`: a single Rego policy file.
+- A directory: all top-level `.rego` files are loaded in sorted order.
+
+YAML policies allow unconstrained tools through `allow.tools`, constrained
+calls through `allow.rules`, and explicit overrides through `deny.tools`:
+
+```yaml
+allow:
+ tools: [screenshot, scroll, wait]
+ rules:
+ - tool: click
+ constraints:
+ x: { min: 0, max: 1920 }
+ y: { min: 0, max: 1080 }
+ - tool: type_text
+ constraints:
+ text: { max_length: 1000, pattern: "^[a-zA-Z0-9\\s]+$" }
+ - tool: launch_app
+ constraints:
+ app:
+ allowed: [Calculator, TextEdit, Safari]
+deny:
+ tools: [shell_execute, file_delete]
+```
+
+Rego policies must expose a boolean rule at `data.cua.policy.allow`. The input
+shape is `{ "server": "cua-driver", "tool": <name>, "arguments": <object> }`.
+Regorus evaluates policies in-process; no OPA service is required.
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml
index 71d23bbca3..35ae60937a 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml
@@ -3,6 +3,11 @@ name = "cua-driver-core"
version.workspace = true
edition.workspace = true
+[features]
+default = ["yaml", "rego"]
+yaml = ["dep:serde_yaml_ng", "dep:regex"]
+rego = ["dep:regorus"]
+
[dependencies]
tokio = { workspace = true }
serde = { workspace = true }
@@ -11,6 +16,9 @@ anyhow = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
async-trait = "0.1"
+serde_yaml_ng = { version = "0.10", optional = true }
+regex = { version = "1", optional = true }
+regorus = { version = "0.10.1", optional = true }
# Used by the shared `image_utils` module — pure PNG/JPEG/resize/crosshair
# helpers extracted from `platform-{macos,windows,linux}/src/capture.rs` so
# all three platforms call the same code path.
@@ -19,5 +27,8 @@ image = { workspace = true }
# Used by `cursor_sampler::sample_cursor` to poll the OS mouse position
# during video recording. Same version as platform-windows uses to avoid
# a duplicate crate version.
+[dev-dependencies]
+tempfile = "3"
+
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging"] }
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
index 18b3d4ef72..21ffab2168 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
@@ -41,6 +41,7 @@ pub mod health_report;
pub mod image_utils;
pub mod page;
pub mod pip_hook;
+pub mod policy;
pub mod protocol;
pub mod cursor_sampler;
pub mod recording;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/policy.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/policy.rs
new file mode 100644
index 0000000000..fa96486074
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/policy.rs
@@ -0,0 +1,771 @@
+//! Optional permission-policy enforcement for MCP tool calls.
+
+use std::path::Path;
+#[cfg(feature = "rego")]
+use std::path::PathBuf;
+use std::sync::OnceLock;
+
+#[cfg(any(feature = "yaml", feature = "rego"))]
+use anyhow::Context;
+use anyhow::{bail, Result};
+use serde_json::Value;
+
+pub const POLICY_FILE_ENV: &str = "CUA_DRIVER_POLICY_FILE";
+#[cfg(feature = "rego")]
+const REGO_ALLOW_RULE: &str = "data.cua.policy.allow";
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum PolicyDecision {
+ Allow,
+ Deny(String),
+ Error(String),
+}
+
+#[derive(Debug, Clone)]
+pub enum PolicyEngine {
+ #[cfg(feature = "yaml")]
+ Yaml(YamlPolicy),
+ #[cfg(feature = "rego")]
+ Rego(Box<RegoPolicy>),
+ #[cfg(not(any(feature = "yaml", feature = "rego")))]
+ Disabled,
+}
+
+impl PolicyEngine {
+ /// Load a policy file or Rego policy directory. A missing path disables
+ /// enforcement to preserve the driver's behavior when no policy is present.
+ pub fn load(path: &Path) -> Result<Option<Self>> {
+ if !path.exists() {
+ return Ok(None);
+ }
+
+ if path.is_dir() {
+ #[cfg(feature = "rego")]
+ {
+ return Ok(Some(Self::Rego(Box::new(RegoPolicy::load_directory(
+ path,
+ )?))));
+ }
+ #[cfg(not(feature = "rego"))]
+ bail!("Rego policy support is not enabled");
+ }
+
+ let extension = path
+ .extension()
+ .and_then(|extension| extension.to_str())
+ .map(str::to_ascii_lowercase)
+ .ok_or_else(|| {
+ anyhow::anyhow!("policy file has no supported extension: {}", path.display())
+ })?;
+
+ match extension.as_str() {
+ "yaml" | "yml" => {
+ #[cfg(feature = "yaml")]
+ {
+ Ok(Some(Self::Yaml(YamlPolicy::load(path)?)))
+ }
+ #[cfg(not(feature = "yaml"))]
+ bail!("YAML policy support is not enabled")
+ }
+ "rego" => {
+ #[cfg(feature = "rego")]
+ {
+ Ok(Some(Self::Rego(Box::new(RegoPolicy::load_files(&[
+ path.to_path_buf()
+ ])?))))
+ }
+ #[cfg(not(feature = "rego"))]
+ bail!("Rego policy support is not enabled")
+ }
+ _ => bail!(
+ "unsupported policy format for {}; expected .yaml, .yml, .rego, or a directory",
+ path.display()
+ ),
+ }
+ }
+
+ pub fn evaluate(&self, tool: &str, args: &Value) -> PolicyDecision {
+ let tool = canonical_tool_name(tool);
+ let mut sanitized_args;
+ let args = if args.get("_session_id").is_some() {
+ sanitized_args = args.clone();
+ if let Some(object) = sanitized_args.as_object_mut() {
+ object.remove("_session_id");
+ }
+ &sanitized_args
+ } else {
+ args
+ };
+
+ #[cfg(not(any(feature = "yaml", feature = "rego")))]
+ let _ = (tool, args);
+ match self {
+ #[cfg(feature = "yaml")]
+ Self::Yaml(policy) => policy.evaluate(tool, args),
+ #[cfg(feature = "rego")]
+ Self::Rego(policy) => policy.evaluate(tool, args),
+ #[cfg(not(any(feature = "yaml", feature = "rego")))]
+ Self::Disabled => PolicyDecision::Error("policy support is not enabled".to_owned()),
+ }
+ }
+}
+
+fn canonical_tool_name(tool: &str) -> &str {
+ match tool {
+ "type_text_chars" => "type_text",
+ other => other,
+ }
+}
+
+static CONFIGURED_POLICY: OnceLock<Result<Option<PolicyEngine>, String>> = OnceLock::new();
+
+/// Return the process-wide policy configured through [`POLICY_FILE_ENV`].
+/// The file is loaded once so stdio and HTTP requests use the same immutable
+/// policy snapshot for the lifetime of the driver process.
+pub fn configured_policy() -> Result<Option<&'static PolicyEngine>, String> {
+ match CONFIGURED_POLICY.get_or_init(|| {
+ let Some(path_os) = std::env::var_os(POLICY_FILE_ENV) else {
+ return Ok(None);
+ };
+ let path = Path::new(&path_os);
+ if !path.exists() {
+ tracing::warn!(
+ path = %path.display(),
+ "{POLICY_FILE_ENV} is set but the path does not exist; \
+ policy enforcement is disabled"
+ );
+ return Ok(None);
+ }
+ PolicyEngine::load(path).map_err(|error| error.to_string())
+ }) {
+ Ok(policy) => Ok(policy.as_ref()),
+ Err(error) => Err(error.clone()),
+ }
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, Clone)]
+pub struct YamlPolicy {
+ allowed_tools: Vec<String>,
+ rules: Vec<YamlRule>,
+ denied_tools: Vec<String>,
+}
+
+#[cfg(feature = "yaml")]
+impl YamlPolicy {
+ fn load(path: &Path) -> Result<Self> {
+ let source = std::fs::read_to_string(path)
+ .with_context(|| format!("failed to read YAML policy {}", path.display()))?;
+ Self::from_str(&source)
+ .with_context(|| format!("failed to parse YAML policy {}", path.display()))
+ }
+
+ fn from_str(source: &str) -> Result<Self> {
+ let document: RawYamlPolicy = serde_yaml_ng::from_str(source)?;
+ let (allowed_tools, raw_rules) = document.allow.into_parts();
+ let denied_tools = document.deny.into_tools();
+ for tool in allowed_tools.iter().chain(&denied_tools) {
+ if tool.trim().is_empty() {
+ bail!("YAML tool lists cannot contain an empty tool name");
+ }
+ }
+ let rules = raw_rules
+ .into_iter()
+ .map(YamlRule::compile)
+ .collect::<Result<Vec<_>>>()?;
+ Ok(Self {
+ allowed_tools,
+ rules,
+ denied_tools,
+ })
+ }
+
+ fn evaluate(&self, tool: &str, args: &Value) -> PolicyDecision {
+ if self.denied_tools.iter().any(|denied| denied == tool) {
+ return PolicyDecision::Deny(format!("tool '{tool}' is explicitly denied"));
+ }
+ if self.allowed_tools.iter().any(|allowed| allowed == tool) {
+ return PolicyDecision::Allow;
+ }
+
+ let matching_rules: Vec<&YamlRule> =
+ self.rules.iter().filter(|rule| rule.tool == tool).collect();
+ if matching_rules.is_empty() {
+ return PolicyDecision::Deny(format!(
+ "tool '{tool}' is not allowed by the YAML policy"
+ ));
+ }
+
+ let mut failures = Vec::new();
+ for rule in matching_rules {
+ match rule.matches(args) {
+ Ok(()) => return PolicyDecision::Allow,
+ Err(reason) => failures.push(reason),
+ }
+ }
+ PolicyDecision::Deny(format!(
+ "tool '{tool}' argument constraints were not satisfied: {}",
+ failures.join("; ")
+ ))
+ }
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, serde::Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawYamlPolicy {
+ #[serde(default)]
+ allow: RawAllow,
+ #[serde(default)]
+ deny: RawDeny,
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, serde::Deserialize)]
+#[serde(untagged)]
+enum RawAllow {
+ Detailed(RawAllowDetailed),
+ Entries(Vec<RawAllowEntry>),
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, serde::Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawAllowDetailed {
+ #[serde(default)]
+ tools: Vec<String>,
+ #[serde(default)]
+ rules: Vec<RawYamlRule>,
+}
+
+#[cfg(feature = "yaml")]
+impl Default for RawAllow {
+ fn default() -> Self {
+ Self::Detailed(RawAllowDetailed {
+ tools: Vec::new(),
+ rules: Vec::new(),
+ })
+ }
+}
+
+#[cfg(feature = "yaml")]
+impl RawAllow {
+ fn into_parts(self) -> (Vec<String>, Vec<RawYamlRule>) {
+ match self {
+ Self::Detailed(section) => (section.tools, section.rules),
+ Self::Entries(entries) => {
+ let mut tools = Vec::new();
+ let mut rules = Vec::new();
+ for entry in entries {
+ match entry {
+ RawAllowEntry::Tool(tool) => tools.push(tool),
+ RawAllowEntry::Rule(rule) => rules.push(rule),
+ }
+ }
+ (tools, rules)
+ }
+ }
+ }
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, serde::Deserialize)]
+#[serde(untagged)]
+enum RawAllowEntry {
+ Tool(String),
+ Rule(RawYamlRule),
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, serde::Deserialize)]
+#[serde(untagged)]
+enum RawDeny {
+ Detailed(RawDenyDetailed),
+ Tools(Vec<String>),
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, serde::Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawDenyDetailed {
+ #[serde(default)]
+ tools: Vec<String>,
+}
+
+#[cfg(feature = "yaml")]
+impl Default for RawDeny {
+ fn default() -> Self {
+ Self::Detailed(RawDenyDetailed { tools: Vec::new() })
+ }
+}
+
+#[cfg(feature = "yaml")]
+impl RawDeny {
+ fn into_tools(self) -> Vec<String> {
+ match self {
+ Self::Detailed(section) => section.tools,
+ Self::Tools(tools) => tools,
+ }
+ }
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, serde::Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawYamlRule {
+ tool: String,
+ #[serde(default)]
+ constraints: std::collections::BTreeMap<String, RawConstraint>,
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, serde::Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawConstraint {
+ min: Option<f64>,
+ max: Option<f64>,
+ max_length: Option<usize>,
+ pattern: Option<String>,
+ allowed: Option<Vec<Value>>,
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, Clone)]
+struct YamlRule {
+ tool: String,
+ constraints: std::collections::BTreeMap<String, Constraint>,
+}
+
+#[cfg(feature = "yaml")]
+impl YamlRule {
+ fn compile(raw: RawYamlRule) -> Result<Self> {
+ if raw.tool.trim().is_empty() {
+ bail!("YAML allow rule has an empty tool name");
+ }
+ let constraints = raw
+ .constraints
+ .into_iter()
+ .map(|(argument, constraint)| {
+ Constraint::compile(constraint)
+ .with_context(|| format!("invalid constraint for '{}.{}'", raw.tool, argument))
+ .map(|constraint| (argument, constraint))
+ })
+ .collect::<Result<_>>()?;
+ Ok(Self {
+ tool: raw.tool,
+ constraints,
+ })
+ }
+
+ fn matches(&self, args: &Value) -> Result<(), String> {
+ let object = args
+ .as_object()
+ .ok_or_else(|| "arguments must be a JSON object".to_owned())?;
+ for (argument, constraint) in &self.constraints {
+ let value = object
+ .get(argument)
+ .ok_or_else(|| format!("missing required argument '{argument}'"))?;
+ constraint.matches(argument, value)?;
+ }
+ Ok(())
+ }
+}
+
+#[cfg(feature = "yaml")]
+#[derive(Debug, Clone)]
+struct Constraint {
+ min: Option<f64>,
+ max: Option<f64>,
+ max_length: Option<usize>,
+ pattern: Option<regex::Regex>,
+ allowed: Option<Vec<Value>>,
+}
+
+#[cfg(feature = "yaml")]
+impl Constraint {
+ fn compile(raw: RawConstraint) -> Result<Self> {
+ if raw.min.is_none()
+ && raw.max.is_none()
+ && raw.max_length.is_none()
+ && raw.pattern.is_none()
+ && raw.allowed.is_none()
+ {
+ bail!("constraint must define at least one check");
+ }
+ if let (Some(min), Some(max)) = (raw.min, raw.max) {
+ if min > max {
+ bail!("min cannot be greater than max");
+ }
+ }
+ let pattern = raw
+ .pattern
+ .map(|pattern| regex::Regex::new(&pattern))
+ .transpose()
+ .context("invalid regex pattern")?;
+ Ok(Self {
+ min: raw.min,
+ max: raw.max,
+ max_length: raw.max_length,
+ pattern,
+ allowed: raw.allowed,
+ })
+ }
+
+ fn matches(&self, argument: &str, value: &Value) -> Result<(), String> {
+ if self.min.is_some() || self.max.is_some() {
+ let number = value
+ .as_f64()
+ .ok_or_else(|| format!("argument '{argument}' must be a number"))?;
+ if let Some(min) = self.min {
+ if number < min {
+ return Err(format!("argument '{argument}' must be >= {min}"));
+ }
+ }
+ if let Some(max) = self.max {
+ if number > max {
+ return Err(format!("argument '{argument}' must be <= {max}"));
+ }
+ }
+ }
+ if self.max_length.is_some() || self.pattern.is_some() {
+ let text = value
+ .as_str()
+ .ok_or_else(|| format!("argument '{argument}' must be a string"))?;
+ if let Some(max_length) = self.max_length {
+ if text.chars().count() > max_length {
+ return Err(format!(
+ "argument '{argument}' must be at most {max_length} characters"
+ ));
+ }
+ }
+ if let Some(pattern) = &self.pattern {
+ if !pattern.is_match(text) {
+ return Err(format!(
+ "argument '{argument}' does not match the required pattern"
+ ));
+ }
+ }
+ }
+ if let Some(allowed) = &self.allowed {
+ if !allowed.contains(value) {
+ return Err(format!(
+ "argument '{argument}' is not in the allowed values"
+ ));
+ }
+ }
+ Ok(())
+ }
+}
+
+#[cfg(feature = "rego")]
+#[derive(Debug, Clone)]
+pub struct RegoPolicy {
+ engine: regorus::Engine,
+}
+
+#[cfg(feature = "rego")]
+impl RegoPolicy {
+ fn load_directory(path: &Path) -> Result<Self> {
+ let mut files = Vec::new();
+ for entry in std::fs::read_dir(path)
+ .with_context(|| format!("failed to read Rego policy directory {}", path.display()))?
+ {
+ let entry = entry.with_context(|| {
+ format!(
+ "failed to read an entry in Rego policy directory {}",
+ path.display()
+ )
+ })?;
+ let entry_path = entry.path();
+ if entry_path.is_file()
+ && entry_path
+ .extension()
+ .and_then(|extension| extension.to_str())
+ .is_some_and(|extension| extension.eq_ignore_ascii_case("rego"))
+ {
+ files.push(entry_path);
+ }
+ }
+ files.sort();
+ if files.is_empty() {
+ bail!(
+ "Rego policy directory {} contains no .rego files",
+ path.display()
+ );
+ }
+ Self::load_files(&files)
+ }
+
+ fn load_files(paths: &[PathBuf]) -> Result<Self> {
+ let mut engine = regorus::Engine::new();
+ for path in paths {
+ engine
+ .add_policy_from_file(path)
+ .with_context(|| format!("failed to load Rego policy {}", path.display()))?;
+ }
+ engine.set_input_json(r#"{"server":"cua-driver","tool":"","arguments":{}}"#)?;
+ match engine
+ .eval_rule(REGO_ALLOW_RULE.to_owned())
+ .context("failed to validate data.cua.policy.allow")?
+ {
+ regorus::Value::Bool(_) | regorus::Value::Undefined => {}
+ value => bail!("{REGO_ALLOW_RULE} must evaluate to a boolean, got {value:?}"),
+ }
+ Ok(Self { engine })
+ }
+
+ fn evaluate(&self, tool: &str, args: &Value) -> PolicyDecision {
+ let input = serde_json::json!({
+ "server": "cua-driver",
+ "tool": tool,
+ "arguments": args,
+ });
+ let input_json = match serde_json::to_string(&input) {
+ Ok(input) => input,
+ Err(error) => return PolicyDecision::Error(error.to_string()),
+ };
+ let mut engine = self.engine.clone();
+ if let Err(error) = engine.set_input_json(&input_json) {
+ return PolicyDecision::Error(error.to_string());
+ }
+ match engine.eval_rule(REGO_ALLOW_RULE.to_owned()) {
+ Ok(regorus::Value::Bool(true)) => PolicyDecision::Allow,
+ Ok(regorus::Value::Bool(false) | regorus::Value::Undefined) => {
+ PolicyDecision::Deny(format!("tool '{tool}' is not allowed by the Rego policy"))
+ }
+ Ok(value) => PolicyDecision::Error(format!(
+ "{REGO_ALLOW_RULE} must evaluate to a boolean, got {value:?}"
+ )),
+ Err(error) => PolicyDecision::Error(error.to_string()),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::fs;
+ use tempfile::tempdir;
+
+ #[cfg(feature = "yaml")]
+ fn yaml_policy(source: &str) -> PolicyEngine {
+ PolicyEngine::Yaml(YamlPolicy::from_str(source).unwrap())
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn yaml_parses_and_evaluates_tool_lists() {
+ let policy = yaml_policy(
+ r#"
+allow:
+ tools: [screenshot, wait]
+deny:
+ tools: [shell_execute]
+"#,
+ );
+ assert_eq!(
+ policy.evaluate("screenshot", &serde_json::json!({})),
+ PolicyDecision::Allow
+ );
+ assert!(matches!(
+ policy.evaluate("shell_execute", &serde_json::json!({})),
+ PolicyDecision::Deny(reason) if reason.contains("explicitly denied")
+ ));
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn yaml_is_deny_by_default() {
+ let policy = yaml_policy("allow:\n tools: [screenshot]\n");
+ assert!(matches!(
+ policy.evaluate("click", &serde_json::json!({"x": 10, "y": 10})),
+ PolicyDecision::Deny(_)
+ ));
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn yaml_enforces_numeric_string_and_allowed_constraints() {
+ let policy = yaml_policy(
+ r#"
+allow:
+ rules:
+ - tool: click
+ constraints:
+ x: { min: 0, max: 1920 }
+ y: { min: 0, max: 1080 }
+ - tool: type
+ constraints:
+ text: { max_length: 5, pattern: "^[a-z]+$" }
+ - tool: launch_app
+ constraints:
+ app:
+ allowed: [Calculator, TextEdit]
+"#,
+ );
+ assert_eq!(
+ policy.evaluate("click", &serde_json::json!({"x": 1920, "y": 0})),
+ PolicyDecision::Allow
+ );
+ assert!(matches!(
+ policy.evaluate("click", &serde_json::json!({"x": 1921, "y": 0})),
+ PolicyDecision::Deny(_)
+ ));
+ assert_eq!(
+ policy.evaluate("type", &serde_json::json!({"text": "hello"})),
+ PolicyDecision::Allow
+ );
+ assert!(matches!(
+ policy.evaluate("type", &serde_json::json!({"text": "hello!"})),
+ PolicyDecision::Deny(_)
+ ));
+ assert_eq!(
+ policy.evaluate("launch_app", &serde_json::json!({"app": "Calculator"})),
+ PolicyDecision::Allow
+ );
+ assert!(matches!(
+ policy.evaluate("launch_app", &serde_json::json!({"app": "Terminal"})),
+ PolicyDecision::Deny(_)
+ ));
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn explicit_deny_overrides_allow() {
+ let policy = yaml_policy("allow:\n tools: [screenshot]\ndeny:\n tools: [screenshot]\n");
+ assert!(matches!(
+ policy.evaluate("screenshot", &serde_json::json!({})),
+ PolicyDecision::Deny(_)
+ ));
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn empty_tool_names_fail_at_load_time() {
+ let error = YamlPolicy::from_str("allow:\n tools: ['']\n").unwrap_err();
+ assert!(error.to_string().contains("empty tool name"));
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn invalid_patterns_fail_at_load_time() {
+ let error = YamlPolicy::from_str(
+ "allow:\n rules:\n - tool: type\n constraints:\n text: { pattern: '[' }\n",
+ )
+ .unwrap_err();
+ assert!(error.to_string().contains("invalid constraint"));
+ }
+
+ #[cfg(feature = "rego")]
+ #[test]
+ fn rego_evaluates_allow_and_constraints() {
+ let dir = tempdir().unwrap();
+ let path = dir.path().join("policy.rego");
+ fs::write(
+ &path,
+ r#"
+package cua.policy
+
+default allow = false
+
+allow if {
+ input.server == "cua-driver"
+ input.tool == "screenshot"
+}
+
+allow if {
+ input.tool == "click"
+ input.arguments.x >= 0
+ input.arguments.x <= 1920
+ input.arguments.y >= 0
+ input.arguments.y <= 1080
+}
+"#,
+ )
+ .unwrap();
+ let policy = PolicyEngine::load(&path).unwrap().unwrap();
+ assert_eq!(
+ policy.evaluate("screenshot", &serde_json::json!({})),
+ PolicyDecision::Allow
+ );
+ assert_eq!(
+ policy.evaluate("click", &serde_json::json!({"x": 20, "y": 30})),
+ PolicyDecision::Allow
+ );
+ assert!(matches!(
+ policy.evaluate("click", &serde_json::json!({"x": 2000, "y": 30})),
+ PolicyDecision::Deny(_)
+ ));
+ assert!(matches!(
+ policy.evaluate("shell_execute", &serde_json::json!({})),
+ PolicyDecision::Deny(_)
+ ));
+ }
+
+ #[cfg(feature = "rego")]
+ #[test]
+ fn rego_directory_loads_all_policy_files() {
+ let dir = tempdir().unwrap();
+ fs::write(
+ dir.path().join("base.rego"),
+ "package cua.policy\ndefault allow = false\n",
+ )
+ .unwrap();
+ fs::write(
+ dir.path().join("screenshot.rego"),
+ "package cua.policy\nallow if input.tool == \"screenshot\"\n",
+ )
+ .unwrap();
+ let policy = PolicyEngine::load(dir.path()).unwrap().unwrap();
+ assert_eq!(
+ policy.evaluate("screenshot", &serde_json::json!({})),
+ PolicyDecision::Allow
+ );
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn policy_uses_canonical_tool_names() {
+ let policy = yaml_policy("allow:\n tools: [type_text]\n");
+ assert_eq!(
+ policy.evaluate("type_text_chars", &serde_json::json!({"text": "hello"})),
+ PolicyDecision::Allow
+ );
+ }
+
+ #[cfg(feature = "rego")]
+ #[test]
+ fn rego_does_not_receive_internal_session_arguments() {
+ let dir = tempdir().unwrap();
+ let path = dir.path().join("policy.rego");
+ fs::write(
+ &path,
+ r#"
+package cua.policy
+
+default allow = false
+
+allow if {
+ input.tool == "click"
+ object.keys(input.arguments) == {"x"}
+}
+"#,
+ )
+ .unwrap();
+ let policy = PolicyEngine::load(&path).unwrap().unwrap();
+ assert_eq!(
+ policy.evaluate(
+ "click",
+ &serde_json::json!({"x": 10, "_session_id": "internal"})
+ ),
+ PolicyDecision::Allow
+ );
+ }
+
+ #[test]
+ fn missing_policy_file_disables_enforcement() {
+ let dir = tempdir().unwrap();
+ let missing = dir.path().join("missing.yaml");
+ assert!(PolicyEngine::load(&missing).unwrap().is_none());
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
index db10ba089a..b16736f281 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
@@ -5,6 +5,7 @@ use std::time::Instant;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tracing::{debug, error, warn};
+use crate::policy::{configured_policy, PolicyDecision};
use crate::protocol::{initialize_result, InitializeMetadata, Request, Response, ResponseBody};
use crate::tool::ToolRegistry;
@@ -263,6 +264,7 @@ pub fn observe_proxy_tool_completed(outcome: ToolCompletionObservation) {
/// responses to stdout. Exits when stdin reaches EOF or a fatal I/O
/// error occurs.
pub async fn run(registry: Arc<ToolRegistry>) -> anyhow::Result<()> {
+ configured_policy().map_err(anyhow::Error::msg)?;
let stdin = tokio::io::stdin();
let stdout = tokio::io::stdout();
let mut reader = BufReader::new(stdin);
@@ -571,6 +573,33 @@ pub async fn handle_request(req: Request, id: serde_json::Value, registry: &Arc<
"tools/call" => match req.tool_call() {
Err(e) => Response::error(id, -32602, format!("Invalid params: {e}")),
Ok(call) => {
+ match configured_policy() {
+ Ok(Some(policy)) => match policy.evaluate(&call.name, &call.args) {
+ PolicyDecision::Allow => {}
+ PolicyDecision::Deny(reason) => {
+ return Response::error(
+ id,
+ -32603,
+ format!("Permission denied: {reason}"),
+ );
+ }
+ PolicyDecision::Error(message) => {
+ return Response::error(
+ id,
+ -32603,
+ format!("Policy evaluation error: {message}"),
+ );
+ }
+ },
+ Ok(None) => {}
+ Err(message) => {
+ return Response::error(
+ id,
+ -32603,
+ format!("Policy loading error: {message}"),
+ );
+ }
+ }
let result = registry.invoke(&call.name, call.args).await;
match serde_json::to_value(result) {
Ok(v) => Response::ok(id, v),
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
index 4013538a77..b11a771692 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
@@ -25,6 +25,7 @@
use std::sync::Arc;
+use cua_driver_core::policy::{configured_policy, PolicyDecision};
use cua_driver_core::protocol::{initialize_result, Request, Response};
use cua_driver_core::server::{
observe_proxy_session_started, observe_proxy_tool_completed, tool_observation_timer,
@@ -51,6 +52,7 @@ use crate::serve::{
/// advertises zero tools and then errors on every call. Matches
/// Swift `makeProxy`'s `fetchProxyToolList` pre-check.
pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {
+ configured_policy().map_err(anyhow::Error::msg)?;
if !is_daemon_listening(&socket_path) {
anyhow::bail!(
"cua-driver-rs daemon not reachable on {socket_path}. Start it \
@@ -498,6 +500,33 @@ async fn handle_proxy_request(
"tools/call" => match req.tool_call() {
Err(e) => Response::error(id, -32602, format!("Invalid params: {e}")),
Ok(call) => {
+ match configured_policy() {
+ Ok(Some(policy)) => match policy.evaluate(&call.name, &call.args) {
+ PolicyDecision::Allow => {}
+ PolicyDecision::Deny(reason) => {
+ return Response::error(
+ id,
+ -32603,
+ format!("Permission denied: {reason}"),
+ );
+ }
+ PolicyDecision::Error(message) => {
+ return Response::error(
+ id,
+ -32603,
+ format!("Policy evaluation error: {message}"),
+ );
+ }
+ },
+ Ok(None) => {}
+ Err(message) => {
+ return Response::error(
+ id,
+ -32603,
+ format!("Policy loading error: {message}"),
+ );
+ }
+ }
forward_tool_call(
id,
call.name,
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
index 6be819e27c..fa8f7b93ba 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -428,6 +428,26 @@ async fn invoke_daemon_tool(
return DaemonResponse::err(format!("Unknown tool: {tool_name}"), 64);
}
+ // Policy enforcement — defense-in-depth for direct daemon socket connections.
+ match cua_driver_core::policy::configured_policy() {
+ Ok(Some(policy)) => match policy.evaluate(&tool_name, &args) {
+ cua_driver_core::policy::PolicyDecision::Allow => {}
+ cua_driver_core::policy::PolicyDecision::Deny(reason) => {
+ observe_daemon_error(observation, 1);
+ return DaemonResponse::err(format!("Permission denied: {reason}"), 1);
+ }
+ cua_driver_core::policy::PolicyDecision::Error(message) => {
+ observe_daemon_error(observation, 1);
+ return DaemonResponse::err(format!("Policy evaluation error: {message}"), 1);
+ }
+ },
+ Ok(None) => {}
+ Err(message) => {
+ observe_daemon_error(observation, 1);
+ return DaemonResponse::err(format!("Policy loading error: {message}"), 1);
+ }
+ }
+
let session_context = observation_transport.and_then(|transport| {
let transport = match transport {
crate::telemetry::Transport::McpStdio => {
diff --git a/nix/cua-driver/README.md b/nix/cua-driver/README.md
index 7de0b2f6d6..1fbaa586c8 100644
--- a/nix/cua-driver/README.md
+++ b/nix/cua-driver/README.md
@@ -7,6 +7,8 @@ builds and desktop-session dependencies for the canonical Rust harnesses.
| --- | --- | --- |
| `cua-driver-build` | Build the shipped Linux package from the locked Rust source | `ci-nix-linux.yml` |
| `cua-driver-linux-rust-unit` | Compile and run the source-owned headless Rust tests | `ci-nix-linux.yml` |
+| `cua-driver-policy-yaml` | Run YAML permission-policy MCP checks in a NixOS VM | Flake check |
+| `cua-driver-policy-rego` | Run embedded Rego permission-policy MCP checks in a NixOS VM | Flake check |
| `cua-driver-wayland-e2e` | Provide the Sway, GTK, WebKit, Electron, capture, and Rust toolchain used by native Wayland E2E | `e2e-rust-linux-wayland.yml` |
| `cua-driver-inject-e2e` | Provide the same typed harness toolchain plus the nested `cua-compositor` package | Experimental nested-injection workflow |
| `cua-compositor-build` | Build the optional compositor-owned injection backend against pinned wlroots | Flake check |
diff --git a/nix/cua-driver/tests/README.md b/nix/cua-driver/tests/README.md
index 3b699d7616..a48e163569 100644
--- a/nix/cua-driver/tests/README.md
+++ b/nix/cua-driver/tests/README.md
@@ -5,6 +5,8 @@ Nix expressions are grouped by what they prove:
| Path | Role |
| --- | --- |
| `rust-unit.nix` | Source-built Rust workspace checks without a desktop session |
+| `policy-yaml.nix` | NixOS VM stdio checks for YAML allow, deny, and argument constraints |
+| `policy-rego.nix` | NixOS VM stdio checks for embedded Rego policy evaluation |
This directory intentionally contains no desktop behavior catalog. Nix builds
the driver, unit checks, session dependencies, and optional compositor package.
diff --git a/nix/cua-driver/tests/policy-rego.nix b/nix/cua-driver/tests/policy-rego.nix
new file mode 100644
index 0000000000..25d6131a3b
--- /dev/null
+++ b/nix/cua-driver/tests/policy-rego.nix
@@ -0,0 +1,73 @@
+# NixOS VM integration test for embedded Rego permission enforcement.
+{
+ pkgs,
+ cuaDriver,
+ ...
+}:
+
+let
+ testCommand = ''
+ set -euo pipefail
+ mkdir -p /tmp/policy
+ cat > /tmp/policy/base.rego <<'POLICY'
+ package cua.policy
+
+ default allow = false
+ POLICY
+ cat > /tmp/policy/tools.rego <<'POLICY'
+ package cua.policy
+
+ allow if input.tool == "screenshot"
+
+ allow if {
+ input.tool == "click"
+ input.arguments.x >= 0
+ input.arguments.x <= 1920
+ input.arguments.y >= 0
+ input.arguments.y <= 1080
+ }
+ POLICY
+
+ coproc DRIVER {
+ env \
+ CUA_DRIVER_POLICY_FILE=/tmp/policy \
+ CUA_DRIVER_RS_TELEMETRY_ENABLED=false \
+ cua-driver mcp --no-daemon-relaunch 2>/tmp/driver.log
+ }
+ trap 'kill "$DRIVER_PID" 2>/dev/null || true' EXIT
+ exec 3>&"''${DRIVER[1]}"
+ exec 4<&"''${DRIVER[0]}"
+
+ request() {
+ printf '%s\n' "$1" >&3
+ IFS= read -r response <&4
+ }
+
+ request '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
+ jq -e '.id == 1 and .result != null' <<<"$response" >/dev/null
+
+ request '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"screenshot","arguments":{}}}'
+ jq -e '.id == 2 and .error == null and .result != null' <<<"$response" >/dev/null
+
+ request '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"shell_execute","arguments":{}}}'
+ jq -e '.id == 3 and (.error.message | startswith("Permission denied:"))' <<<"$response" >/dev/null
+
+ request '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"click","arguments":{"x":2000,"y":100}}}'
+ jq -e '.id == 4 and (.error.message | startswith("Permission denied:"))' <<<"$response" >/dev/null
+ '';
+in
+pkgs.testers.runNixOSTest {
+ name = "cua-driver-policy-rego";
+
+ nodes.machine = {
+ environment.systemPackages = [
+ cuaDriver
+ pkgs.jq
+ ];
+ };
+
+ testScript = ''
+ start_all()
+ machine.succeed(${builtins.toJSON testCommand})
+ '';
+}
diff --git a/nix/cua-driver/tests/policy-yaml.nix b/nix/cua-driver/tests/policy-yaml.nix
new file mode 100644
index 0000000000..a76238de17
--- /dev/null
+++ b/nix/cua-driver/tests/policy-yaml.nix
@@ -0,0 +1,67 @@
+# NixOS VM integration test for YAML permission-policy enforcement.
+{
+ pkgs,
+ cuaDriver,
+ ...
+}:
+
+let
+ testCommand = ''
+ set -euo pipefail
+ cat > /tmp/policy.yaml <<'POLICY'
+ allow:
+ tools:
+ - screenshot
+ rules:
+ - tool: click
+ constraints:
+ x: { min: 0, max: 1920 }
+ y: { min: 0, max: 1080 }
+ deny:
+ tools:
+ - shell_execute
+ POLICY
+
+ coproc DRIVER {
+ env \
+ CUA_DRIVER_POLICY_FILE=/tmp/policy.yaml \
+ CUA_DRIVER_RS_TELEMETRY_ENABLED=false \
+ cua-driver mcp --no-daemon-relaunch 2>/tmp/driver.log
+ }
+ trap 'kill "$DRIVER_PID" 2>/dev/null || true' EXIT
+ exec 3>&"''${DRIVER[1]}"
+ exec 4<&"''${DRIVER[0]}"
+
+ request() {
+ printf '%s\n' "$1" >&3
+ IFS= read -r response <&4
+ }
+
+ request '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
+ jq -e '.id == 1 and .result != null' <<<"$response" >/dev/null
+
+ request '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"screenshot","arguments":{}}}'
+ jq -e '.id == 2 and .error == null and .result != null' <<<"$response" >/dev/null
+
+ request '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"shell_execute","arguments":{}}}'
+ jq -e '.id == 3 and (.error.message | startswith("Permission denied:"))' <<<"$response" >/dev/null
+
+ request '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"click","arguments":{"x":1921,"y":100}}}'
+ jq -e '.id == 4 and (.error.message | startswith("Permission denied:"))' <<<"$response" >/dev/null
+ '';
+in
+pkgs.testers.runNixOSTest {
+ name = "cua-driver-policy-yaml";
+
+ nodes.machine = {
+ environment.systemPackages = [
+ cuaDriver
+ pkgs.jq
+ ];
+ };
+
+ testScript = ''
+ start_all()
+ machine.succeed(${builtins.toJSON testCommand})
+ '';
+}