Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(cua-driver): enforce private observation grants (#2579)

Francesco Bonacci6052381e9744
diff --git a/docs/content/docs/reference/cua-driver/permission-modes.mdx b/docs/content/docs/reference/cua-driver/permission-modes.mdx
index 928db87bd5..f846cbbaf3 100644
--- a/docs/content/docs/reference/cua-driver/permission-modes.mdx
+++ b/docs/content/docs/reference/cua-driver/permission-modes.mdx
@@ -5,18 +5,20 @@ description: Standard, bounded, and unrestricted startup modes, protected consen
import { Callout } from 'fumadocs-ui/components/callout';
-Cua Driver resolves authorization before a runtime accepts actions. Released
-CLI and SDK calls inherit one compatibility mode, so their behavior is
-unchanged. A trusted application may instead construct an immutable runtime
-ceiling and create session-bound action objects beneath it. A tool call cannot
-change either setting. Permission mode controls when work stops for protected
-human approval; permission policies still decide which calls are allowed.
+Cua Driver resolves authorization before a runtime accepts actions. Existing
+CLI and SDK method shapes remain valid and inherit one compatibility mode;
+active protected-resource adapters can now refuse a sensitive call before
+platform dispatch. A trusted application may instead construct an immutable
+runtime ceiling and create session-bound action objects beneath it. A tool call
+cannot change either setting. Permission mode controls when work stops for
+protected human approval; permission policies still decide which calls are
+allowed.
## Modes
| Mode | Startup | Human intervention | Existing logged-in profile |
| --- | --- | --- | --- |
-| `standard` | Default | Currently once for existing-profile attachment; other risk classes are metadata-only until their adapters ship | Requires a certified protected-consent provider and its persistent Stop indicator |
+| `standard` | Default | Once per exact user-owned observation 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 |
| `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 |
@@ -58,16 +60,18 @@ The current inventory is intentionally narrow:
| Adapter | State | Meaning |
| --- | --- | --- |
| `browser_prepare.existing_profile` | `active` | Existing-profile attachment applies the mode-specific protected-consent or unrestricted path. |
-| `private_observation` | `metadata_only` | User-window/display observation is classified but not protected by a shipped grant adapter. |
+| `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` | `metadata_only` | Generic desktop input is classified but not protected by a shipped grant adapter. |
| `file_transfer_and_output` | `metadata_only` | Uploads, downloads, and screenshot-to-file egress are classified but not protected by a shipped grant adapter. |
| `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. These
-groups remain metadata-only until an exact resource adapter, certified
+`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.
+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.
## Protected consent
@@ -79,14 +83,16 @@ provider activates a persistent indicator with a Stop control.
Ordinary MCP elicitation, MCP tool arguments, inherited standard input, a TTY,
environment variables, and files do not satisfy this contract. They are
-writable by the calling process. If the daemon has no certified provider,
-`standard` and `bounded` refuse existing-profile attachment.
+writable by the calling process. If the runtime has no certified provider,
+`standard` and `bounded` refuse user-owned private observation and
+existing-profile attachment before the platform backend can read the resource.
<Callout type="info">
The current standalone CLI/MCP daemon has no certified Codex or Claude host
provider. Its protected-consent status therefore reports `unavailable`.
- Isolated browser profiles remain available. A trusted embedding host can
- install the provider interface in process.
+ Proven driver-owned isolated browser profiles remain prompt-light. A trusted
+ embedding host can install the provider interface in process for user-owned
+ resources.
</Callout>
The old file-backed `browser-approve` artifact is disabled by default for
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
index 02cc3107fc..aaf833576c 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
@@ -301,18 +301,19 @@ pub const ENFORCEMENT_ADAPTERS: &[EnforcementAdapterDescriptor] = &[
EnforcementAdapterDescriptor {
id: "private_observation",
operations: PRIVATE_OBSERVATION_OPERATIONS,
- state: RiskEnforcement::MetadataOnly,
+ state: RiskEnforcement::Active,
risk_class: RiskClass::R2,
resource_kind: "user_window_or_display_observation",
scope_keys: PRIVATE_OBSERVATION_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: "desktop_input",
@@ -759,7 +760,14 @@ pub fn classify_tool_call(tool: &str, args: &Value) -> RiskAssessment {
};
RiskAssessment {
class,
- enforcement: RiskEnforcement::MetadataOnly,
+ enforcement: if matches!(
+ args.get("action").and_then(Value::as_str),
+ Some("get_text" | "query_dom")
+ ) {
+ RiskEnforcement::Active
+ } else {
+ RiskEnforcement::MetadataOnly
+ },
operation_sensitive: true,
}
}
@@ -773,7 +781,30 @@ pub fn classify_tool_call(tool: &str, args: &Value) -> RiskAssessment {
} else {
RiskClass::R2
},
- enforcement: RiskEnforcement::MetadataOnly,
+ // Screenshot-to-file is a compound observation + file-egress
+ // operation. It remains metadata-only as a whole until the file
+ // adapter ships, while the observation half is still enforced by
+ // the canonical adapter conjunction.
+ enforcement: if args
+ .get("screenshot_out_file")
+ .and_then(Value::as_str)
+ .is_some_and(|path| !path.is_empty())
+ {
+ RiskEnforcement::MetadataOnly
+ } else {
+ RiskEnforcement::Active
+ },
+ operation_sensitive: true,
+ },
+ "get_accessibility_tree"
+ | "list_apps"
+ | "list_windows"
+ | "debug_window_info"
+ | "get_browser_state"
+ | "escalate_session"
+ | "zoom" => RiskAssessment {
+ class: RiskClass::R2,
+ enforcement: RiskEnforcement::Active,
operation_sensitive: true,
},
"check_permissions" => RiskAssessment {
@@ -1247,7 +1278,7 @@ mod tests {
for tool in ["get_desktop_state", "get_window_state"] {
let observation = classify_tool_call(tool, &serde_json::json!({}));
assert_eq!(observation.class, RiskClass::R2);
- assert_eq!(observation.enforcement, RiskEnforcement::MetadataOnly);
+ assert_eq!(observation.enforcement, RiskEnforcement::Active);
let egress = classify_tool_call(
tool,
@@ -1311,12 +1342,11 @@ mod tests {
assert_eq!(
adapter_ids_with_state(RiskEnforcement::Active),
- vec!["browser_prepare.existing_profile"]
+ vec!["browser_prepare.existing_profile", "private_observation"]
);
assert_eq!(
adapter_ids_with_state(RiskEnforcement::MetadataOnly),
vec![
- "private_observation",
"desktop_input",
"file_transfer_and_output",
"browser_consequential_action",
@@ -1333,7 +1363,7 @@ mod tests {
);
assert_eq!(
adapter_ids_with_state_for_mode(PermissionMode::Standard, RiskEnforcement::Active),
- vec!["browser_prepare.existing_profile"]
+ vec!["browser_prepare.existing_profile", "private_observation"]
);
let existing = ENFORCEMENT_ADAPTERS
@@ -1416,12 +1446,11 @@ mod tests {
let status = status_json();
assert_eq!(
status["active_risk_enforcement"],
- serde_json::json!(["browser_prepare.existing_profile"])
+ serde_json::json!(["browser_prepare.existing_profile", "private_observation"])
);
assert_eq!(
status["metadata_only_risk_enforcement"],
serde_json::json!([
- "private_observation",
"desktop_input",
"file_transfer_and_output",
"browser_consequential_action",
@@ -1438,7 +1467,7 @@ mod tests {
);
assert_eq!(
status["effective_active_risk_enforcement"],
- serde_json::json!(["browser_prepare.existing_profile"])
+ serde_json::json!(["browser_prepare.existing_profile", "private_observation"])
);
assert_eq!(
status["effective_metadata_only_risk_enforcement"],
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
index db2b3aea1e..a0d8a21ecc 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
@@ -183,7 +183,6 @@ struct PreparedProfile {
pub(crate) struct ManagedBrowser {
child: Child,
- #[cfg(target_os = "windows")]
owned_pid: i64,
profile: PathBuf,
delete_profile: bool,
@@ -599,6 +598,12 @@ fn spawned_runtime_pid(ownership: &EndpointOwnershipProof) -> i64 {
}
impl BrowserEngine {
+ pub(crate) fn is_driver_owned_pid_for_session(&self, session: &str, pid: i64) -> bool {
+ self.managed_browsers.lock().unwrap().iter().any(|browser| {
+ browser.owned_pid == pid && browser.owner_sessions.iter().any(|owner| owner == session)
+ })
+ }
+
pub(crate) fn cleanup_prepared_session(&self, session: &str) {
self.managed_browsers
.lock()
@@ -713,7 +718,6 @@ impl BrowserEngine {
}
self.managed_browsers.lock().unwrap().push(ManagedBrowser {
child,
- #[cfg(target_os = "windows")]
owned_pid: prepared_pid,
profile: prepared_profile.path,
delete_profile: prepared_profile.delete_on_cleanup,
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
index f4df24a889..27cdddc1b6 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
@@ -11,7 +11,7 @@ use async_trait::async_trait;
use serde_json::{json, Value};
use crate::protocol::{Content, ToolResult};
-use crate::tool::{Tool, ToolDef, ToolRegistry};
+use crate::tool::{ProtectedResourceOwnership, Tool, ToolDef, ToolRegistry};
use crate::tool_args::ArgsExt;
use super::approval::MCP_HOST_APPROVAL_ARG;
@@ -93,6 +93,27 @@ fn schema_session() -> Value {
})
}
+fn browser_resource_ownership(engine: &BrowserEngine, args: &Value) -> ProtectedResourceOwnership {
+ let Some(session) = args
+ .get("session")
+ .and_then(Value::as_str)
+ .filter(|session| !session.is_empty())
+ else {
+ return ProtectedResourceOwnership::UserOwned;
+ };
+ let pid = args.get("pid").and_then(Value::as_i64).or_else(|| {
+ args.get("target_id")
+ .and_then(Value::as_str)
+ .and_then(|target_id| engine.store.get_target(session, target_id).ok())
+ .map(|target| target.pid)
+ });
+ if pid.is_some_and(|pid| engine.is_driver_owned_pid_for_session(session, pid)) {
+ ProtectedResourceOwnership::DriverOwned
+ } else {
+ ProtectedResourceOwnership::UserOwned
+ }
+}
+
fn semantic_ref_value(listed: &super::engine::SemanticListedRef) -> Value {
json!({
"ref": listed.external,
@@ -203,6 +224,18 @@ impl Tool for GetBrowserStateTool {
&self.def
}
+ async fn protected_resource_ownership(
+ &self,
+ adapter_id: &str,
+ args: &Value,
+ ) -> ProtectedResourceOwnership {
+ if adapter_id == "private_observation" {
+ browser_resource_ownership(&self.engine, args)
+ } else {
+ ProtectedResourceOwnership::UserOwned
+ }
+ }
+
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") {
@@ -1603,6 +1636,18 @@ impl Tool for BrowserDialogTool {
&self.def
}
+ async fn protected_resource_ownership(
+ &self,
+ adapter_id: &str,
+ args: &Value,
+ ) -> ProtectedResourceOwnership {
+ if adapter_id == "private_observation" {
+ browser_resource_ownership(&self.engine, args)
+ } else {
+ ProtectedResourceOwnership::UserOwned
+ }
+ }
+
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/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index bf78e822e9..4d48c215b8 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
@@ -2,6 +2,7 @@
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
+use std::time::Duration;
use async_trait::async_trait;
use serde_json::Value;
@@ -346,10 +347,30 @@ pub fn advertised_capabilities_for(tool_name: &str, input_schema: &Value) -> Vec
capabilities
}
+/// Runtime-owned provenance for protected-resource admission.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ProtectedResourceOwnership {
+ UserOwned,
+ DriverOwned,
+}
+
/// A callable tool handler. Object-safe — uses `Box<dyn Tool>`.
#[async_trait]
pub trait Tool: Send + Sync {
fn def(&self) -> &ToolDef;
+
+ /// Trusted implementation-side provenance for prompt-light disposable
+ /// resources. The default is deliberately conservative: caller arguments
+ /// never establish ownership, and an adapter may skip protected consent
+ /// only when the concrete tool can prove it from runtime-owned state.
+ async fn protected_resource_ownership(
+ &self,
+ _adapter_id: &str,
+ _args: &Value,
+ ) -> ProtectedResourceOwnership {
+ ProtectedResourceOwnership::UserOwned
+ }
+
async fn invoke(&self, args: Value) -> ToolResult;
}
@@ -678,6 +699,33 @@ impl ToolRegistry {
return result;
}
+ // 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
+ // avoids prompting for a call the session policy will refuse, while
+ // preserving the public arguments in the grant scope and the private
+ // runtime session key in its revocation lifecycle.
+ if crate::authorization::enforcement_adapters_for_call(resolved_name, &public_args)
+ .iter()
+ .any(|adapter| adapter.id == "private_observation")
+ && tool
+ .protected_resource_ownership("private_observation", &public_args)
+ .await
+ != ProtectedResourceOwnership::DriverOwned
+ {
+ if let Err(error) = self
+ .authorize_private_observation(
+ resolved_name,
+ &public_args,
+ context,
+ runtime_session.as_deref(),
+ )
+ .await
+ {
+ return protected_consent_refusal(error);
+ }
+ }
+
// Capture start time for recording timestamps only after validation.
let start_ms = now_ms();
@@ -796,6 +844,127 @@ impl ToolRegistry {
result
}
+
+ async fn authorize_private_observation(
+ &self,
+ tool_name: &str,
+ args: &Value,
+ context: &crate::session_authorization::EffectiveAuthorizationContext,
+ lifecycle_session: Option<&str>,
+ ) -> Result<(), crate::consent::ConsentError> {
+ 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 {
+ (
+ serde_json::json!({
+ "kind": "browser_target",
+ "target_id": target_id,
+ "tab_id": browser_tab,
+ }),
+ match browser_tab {
+ Some(tab_id) => {
+ format!("Allow Cua to observe browser target {target_id}, tab {tab_id}")
+ }
+ None => format!("Allow Cua to observe browser target {target_id}"),
+ },
+ )
+ } 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);
+ (
+ serde_json::json!({
+ "kind": "window",
+ "pid": pid,
+ "window_id": window_id,
+ }),
+ match pid {
+ Some(pid) => {
+ format!("Allow Cua to observe window {window_id} of process {pid}")
+ }
+ None => format!("Allow Cua to observe window {window_id}"),
+ },
+ )
+ } else if let Some(pid) = args.get("pid").and_then(Value::as_i64) {
+ (
+ serde_json::json!({
+ "kind": "application",
+ "pid": pid,
+ }),
+ 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)
+ {
+ // A trajectory-only recording does not capture the display when it
+ // starts. Each later action still passes its own observation/input
+ // adapters, and the grant key is bound to this runtime-private
+ // lifecycle session. Requiring display discovery here would make
+ // this safe, headless-capable mode unusable on Linux CI.
+ (
+ serde_json::json!({
+ "kind": "session_trajectory_recording",
+ "record_video": false,
+ }),
+ "Allow Cua to record separately authorized actions in this session".to_owned(),
+ )
+ } else {
+ // Whole-desktop and unfiltered listing calls are scoped to the
+ // current display geometry. Reading get_screen_size is R0 and
+ // content-free; calling its platform implementation directly
+ // avoids recursive authorization while making a display topology
+ // change produce a different grant digest.
+ let display = self
+ .tools
+ .get("get_screen_size")
+ .ok_or_else(|| {
+ crate::consent::ConsentError::Provider(
+ "display identity is unavailable".to_owned(),
+ )
+ })?
+ .invoke(serde_json::json!({}))
+ .await;
+ if display.is_error == Some(true) {
+ return Err(crate::consent::ConsentError::Provider(
+ "display identity could not be read".to_owned(),
+ ));
+ }
+ let display = display.structured_content.ok_or_else(|| {
+ crate::consent::ConsentError::Provider(
+ "display identity was not returned".to_owned(),
+ )
+ })?;
+ (
+ serde_json::json!({
+ "kind": "display",
+ "width": display.get("width").and_then(Value::as_u64),
+ "height": display.get("height").and_then(Value::as_u64),
+ "scale_factor": display.get("scale_factor").and_then(Value::as_f64),
+ }),
+ "Allow Cua to observe the current desktop".to_owned(),
+ )
+ };
+
+ self.protected_resource_grants
+ .authorize(
+ context,
+ "private_observation",
+ crate::authorization::RiskClass::R2,
+ lifecycle_session,
+ resource,
+ &format!("{summary} using {tool_name}"),
+ Duration::from_secs(30 * 60),
+ Duration::from_secs(8 * 60 * 60),
+ )
+ .await?;
+ Ok(())
+ }
}
fn is_physical_desktop_action(tool: &str) -> bool {
@@ -914,11 +1083,15 @@ mod runtime_isolation_tests {
};
use crate::{
authorization::PermissionMode,
+ consent::{
+ ConsentAction, ConsentRequest, IndicatorLease, ProtectedConsentProvider,
+ ProviderDecision,
+ },
protocol::ToolResult,
session_authorization::{SessionAuthorizationRegistry, SessionModeCeiling},
};
use std::sync::{
- atomic::{AtomicUsize, Ordering},
+ atomic::{AtomicBool, AtomicUsize, Ordering},
Arc,
};
use std::time::Duration;
@@ -941,6 +1114,78 @@ mod runtime_isolation_tests {
def: super::ToolDef,
}
+ struct ObservationProbe {
+ hits: Arc<AtomicUsize>,
+ def: super::ToolDef,
+ }
+
+ #[async_trait::async_trait]
+ impl super::Tool for ObservationProbe {
+ 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);
+ crate::protocol::ToolResult::text("private state")
+ .with_structured(serde_json::json!({"snapshot_id": 1}))
+ }
+ }
+
+ struct AcceptingProvider {
+ requests: AtomicUsize,
+ }
+
+ #[async_trait::async_trait]
+ impl ProtectedConsentProvider for AcceptingProvider {
+ fn provider_id(&self) -> &'static str {
+ "test.observation-provider"
+ }
+
+ async fn request_consent(
+ &self,
+ request: &ConsentRequest,
+ ) -> Result<ProviderDecision, String> {
+ self.requests.fetch_add(1, Ordering::SeqCst);
+ Ok(ProviderDecision {
+ action: ConsentAction::Accept,
+ request_digest: request.request_digest.clone(),
+ })
+ }
+
+ async fn activate_indicator(
+ &self,
+ request: &ConsentRequest,
+ ) -> Result<IndicatorLease, String> {
+ Ok(IndicatorLease::new(
+ format!("indicator-{}", request.generation),
+ Arc::new(AtomicBool::new(false)),
+ ))
+ }
+
+ async fn deactivate_indicator(&self, _indicator_id: &str) {}
+ }
+
+ fn observation_registry(
+ 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(),
+ description: "test observation".into(),
+ input_schema: serde_json::json!({"type": "object"}),
+ read_only: true,
+ destructive: false,
+ idempotent: true,
+ open_world: false,
+ },
+ }));
+ Arc::new(registry)
+ }
+
#[async_trait::async_trait]
impl super::Tool for ReplayProbe {
fn def(&self) -> &super::ToolDef {
@@ -1008,6 +1253,95 @@ mod runtime_isolation_tests {
drop(registry_b);
}
+ #[tokio::test]
+ async fn observation_refuses_before_platform_dispatch_without_a_protected_host() {
+ let hits = Arc::new(AtomicUsize::new(0));
+ let registry = observation_registry(None, hits.clone());
+ let result = registry
+ .invoke_with_context(
+ "get_window_state",
+ serde_json::json!({"pid": 42, "window_id": 7, "session": "review"}),
+ standard_context(),
+ )
+ .await;
+
+ assert_eq!(hits.load(Ordering::SeqCst), 0);
+ assert_eq!(result.is_error, Some(true));
+ assert_eq!(
+ result
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.pointer("/refusal/code"))
+ .and_then(serde_json::Value::as_str),
+ Some("protected_consent_required")
+ );
+ }
+
+ #[tokio::test]
+ async fn observation_reuses_only_the_exact_window_grant() {
+ let hits = Arc::new(AtomicUsize::new(0));
+ let provider = Arc::new(AcceptingProvider {
+ requests: AtomicUsize::new(0),
+ });
+ let registry = observation_registry(Some(provider.clone()), hits.clone());
+ let context = standard_context();
+ for window_id in [7, 7, 8] {
+ let result = registry
+ .invoke_with_context(
+ "get_window_state",
+ serde_json::json!({
+ "pid": 42,
+ "window_id": window_id,
+ "session": "review"
+ }),
+ 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);
+ }
+
+ #[tokio::test]
+ async fn trajectory_only_recording_does_not_require_live_display_discovery() {
+ let hits = Arc::new(AtomicUsize::new(0));
+ let provider = Arc::new(AcceptingProvider {
+ requests: AtomicUsize::new(0),
+ });
+ let mut registry =
+ super::ToolRegistry::new_with_protected_consent_provider(Some(provider.clone()));
+ registry.register(Box::new(ObservationProbe {
+ hits: hits.clone(),
+ def: super::ToolDef {
+ name: "start_recording".into(),
+ description: "test trajectory-only recording".into(),
+ input_schema: serde_json::json!({"type": "object"}),
+ read_only: false,
+ destructive: false,
+ idempotent: true,
+ open_world: false,
+ },
+ }));
+
+ let result = registry
+ .invoke_with_context(
+ "start_recording",
+ serde_json::json!({
+ "output_dir": "/synthetic/recording",
+ "record_video": false,
+ "session": "recording"
+ }),
+ standard_context(),
+ )
+ .await;
+
+ assert_ne!(result.is_error, Some(true));
+ assert_eq!(hits.load(Ordering::SeqCst), 1);
+ assert_eq!(provider.requests.load(Ordering::SeqCst), 1);
+ }
+
#[tokio::test]
async fn element_tokens_are_bound_to_the_dispatch_runtime_generation() {
let pid = 8_675_309;
@@ -1161,6 +1495,26 @@ fn permission_denied_result(message: String) -> ToolResult {
}))
}
+fn protected_consent_refusal(error: crate::consent::ConsentError) -> ToolResult {
+ let code = match &error {
+ crate::consent::ConsentError::Unavailable => "protected_consent_required",
+ crate::consent::ConsentError::Declined => "protected_consent_declined",
+ crate::consent::ConsentError::Canceled => "protected_consent_canceled",
+ crate::consent::ConsentError::DigestMismatch => "protected_consent_scope_mismatch",
+ crate::consent::ConsentError::Expired => "protected_consent_expired",
+ crate::consent::ConsentError::Indicator(_) => "protected_indicator_unavailable",
+ crate::consent::ConsentError::Provider(_) => "protected_consent_provider_failed",
+ };
+ let message = error.to_string();
+ ToolResult::error(message.clone()).with_structured(serde_json::json!({
+ "status": "refused",
+ "refusal": {
+ "code": code,
+ "message": message,
+ }
+ }))
+}
+
fn is_existing_profile_prepare(tool_name: &str, args: &Value) -> bool {
tool_name == "browser_prepare"
&& args
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.rs
index 220b28c79e..55f2191b4e 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
@@ -532,8 +532,44 @@ fn configure_linux_runtime(prepare_desktop_environment: bool) {
#[cfg(test)]
mod tests {
use super::*;
+ use async_trait::async_trait;
+ use cua_driver_core::consent::{
+ ConsentAction, ConsentRequest, IndicatorLease, ProtectedConsentProvider, ProviderDecision,
+ };
+ use std::sync::atomic::AtomicBool;
use std::time::Duration;
+ struct TestProtectedHost;
+
+ #[async_trait]
+ impl ProtectedConsentProvider for TestProtectedHost {
+ fn provider_id(&self) -> &'static str {
+ "test.runtime-protected-host"
+ }
+
+ async fn request_consent(
+ &self,
+ request: &ConsentRequest,
+ ) -> Result<ProviderDecision, String> {
+ Ok(ProviderDecision {
+ action: ConsentAction::Accept,
+ request_digest: request.request_digest.clone(),
+ })
+ }
+
+ async fn activate_indicator(
+ &self,
+ request: &ConsentRequest,
+ ) -> Result<IndicatorLease, String> {
+ Ok(IndicatorLease::new(
+ format!("test-indicator-{}", request.generation),
+ Arc::new(AtomicBool::new(false)),
+ ))
+ }
+
+ async fn deactivate_indicator(&self, _indicator_id: &str) {}
+ }
+
fn standard_options() -> RuntimeOptions {
let ceiling = SessionModeCeiling::for_trusted_sessions(
[PermissionMode::Standard],
@@ -542,7 +578,10 @@ mod tests {
Duration::from_secs(30),
)
.unwrap();
- RuntimeOptions::embedded_with_ceiling(false, ceiling, PermissionMode::Standard, None)
+ let mut options =
+ RuntimeOptions::embedded_with_ceiling(false, ceiling, PermissionMode::Standard, None);
+ options.protected_consent_provider = Some(Arc::new(TestProtectedHost));
+ options
}
#[tokio::test]
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.rs
index 1a45829153..86b04bd26a 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
@@ -31,17 +31,25 @@ impl RawDriver {
/// if the binary isn't built — callers early-return so an un-built binary
/// skips rather than fails.
pub fn spawn() -> Option<Self> {
- Self::spawn_daemon_backed(false)
+ Self::spawn_daemon_backed(false, &[])
+ }
+
+ /// Spawn the daemon-backed driver with an explicit test environment.
+ ///
+ /// Permission-mode tests use this to model a trusted host's launch-time
+ /// configuration without mutating the test process environment.
+ pub fn spawn_with_env(env: &[(&str, &str)]) -> Option<Self> {
+ Self::spawn_daemon_backed(false, env)
}
/// Spawn a daemon-backed raw driver with the certified platform overlay
/// host enabled. Cursor protocol tests use this deliberately; ordinary
/// protocol tests keep the no-overlay daemon so they remain headless.
pub fn spawn_with_overlay() -> Option<Self> {
- Self::spawn_daemon_backed(true)
+ Self::spawn_daemon_backed(true, &[])
}
- fn spawn_daemon_backed(overlay_enabled: bool) -> Option<Self> {
+ fn spawn_daemon_backed(overlay_enabled: bool, env: &[(&str, &str)]) -> Option<Self> {
let bin = driver_binary();
if !bin.exists() {
eprintln!("[testkit] driver binary not built at {bin:?} — skipping");
@@ -49,9 +57,9 @@ impl RawDriver {
}
let mut reaper = ChildReaper::new();
let daemon = if overlay_enabled {
- TestDaemon::spawn_with_overlay(&bin, &mut reaper, &[])?
+ TestDaemon::spawn_with_overlay(&bin, &mut reaper, env)?
} else {
- TestDaemon::spawn(&bin, &mut reaper, &[])?
+ TestDaemon::spawn(&bin, &mut reaper, env)?
};
let mut command = Command::new(&bin);
command
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs
index b4fbdeb699..cd469ab0ba 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs
@@ -21,7 +21,14 @@ fn code(response: &Value) -> Option<&str> {
#[test]
fn policies_are_isolated_immutable_and_enforced_over_mcp() {
- let mut driver = RawDriver::spawn().expect("spawn source-built driver");
+ // This test isolates capture-scope behavior. The trusted fixture opts
+ // into unrestricted mode at daemon launch so protected observation
+ // consent does not mask the scope policy being exercised.
+ let mut driver = RawDriver::spawn_with_env(&[
+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),
+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),
+ ])
+ .expect("spawn source-built driver");
driver.send(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
driver.recv();