diff --git a/crates/tinycomputer-browser/src/surface/mod.rs b/crates/tinycomputer-browser/src/surface/mod.rs index eff0bf146..75eda39bc 100644 --- a/crates/tinycomputer-browser/src/surface/mod.rs +++ b/crates/tinycomputer-browser/src/surface/mod.rs @@ -136,6 +136,9 @@ pub struct BrowserSurface { platform: Platform, cursor: Arc, perception: Perception, + /// Keep values from editable form controls out of every task observation. + /// The private `SecretHost` can type and verify them through the host APIs. + hide_form_values: bool, settle: Settle, denoised: Arc>, /// Set once the surface is let go ([`BrowserSurface::close`]): it is @@ -180,6 +183,7 @@ impl BrowserSurface { platform: Platform::current(), cursor: Arc::new(ScreenCursor::off()), perception: Perception::default(), + hide_form_values: false, settle: Settle::default(), denoised: Arc::new(Mutex::new(Denoised::default())), closed: Arc::new(AtomicBool::new(false)), @@ -233,6 +237,15 @@ impl BrowserSurface { self } + /// Hides values held by editable form controls from observations while + /// retaining their labels, roles, states, and refs. Host-side reads and + /// secret-fill verification continue to use the live control value. + #[must_use] + pub fn without_form_values(mut self) -> Self { + self.hide_form_values = true; + self + } + /// The same surface, drawing on `cursor` — the screen's one agent /// cursor, shared with the desktop surface — whenever its session has a /// window on screen. The cursor is cosmetic: every action is performed @@ -360,11 +373,15 @@ impl BrowserSurface { fn see(&self, root: Option<&str>) -> Option { self.keep_denoised(Denoised::default()); let id = self.ensure_session().ok()?; + let script = if self.hide_form_values { + sight::script_without_form_values(root) + } else { + sight::script(root) + }; // The timer is made inside the runtime `block` enters, not before. - let reading = self.browser.command( - &id, - json!({"action": "evaluate", "script": sight::script(root)}), - ); + let reading = self + .browser + .command(&id, json!({"action": "evaluate", "script": script})); let reply = self .block(async { tokio::time::timeout(READ_TIMEOUT, reading).await }) .ok()? diff --git a/crates/tinycomputer-browser/src/surface/operations.rs b/crates/tinycomputer-browser/src/surface/operations.rs index fa6c346a1..58e43c0e0 100644 --- a/crates/tinycomputer-browser/src/surface/operations.rs +++ b/crates/tinycomputer-browser/src/surface/operations.rs @@ -48,6 +48,9 @@ impl Surface for BrowserSurface { if !app.is_empty() { app.clone_into(&mut screen.app); } + if self.hide_form_values { + hide_form_values(&mut screen); + } return Ok(screen); } let request = SnapshotRequest { @@ -68,7 +71,11 @@ impl Surface for BrowserSurface { }) }) .map_err(|error| Box::new(failure("snapshot", &error)))?; - let mut screen = tree::screen(&snapshot.tree, &snapshot.title); + let mut screen = if self.hide_form_values { + tree::screen_without_form_values(&snapshot.tree, &snapshot.title) + } else { + tree::screen(&snapshot.tree, &snapshot.title) + }; if !app.is_empty() { app.clone_into(&mut screen.app); } @@ -342,6 +349,38 @@ impl Surface for BrowserSurface { } } +/// Removes editable control values from the screen returned to all task +/// models. The candidate's live ref, role, labels, state and actions remain, +/// and `Surface::read_value` still obtains the value directly for host-side +/// checks. +fn hide_form_values(screen: &mut Screen) { + fn hide(candidate: &mut Candidate) { + let editable = candidate + .available_actions + .iter() + .any(|action| matches!(action.as_str(), "SetValue" | "TypeText")) + || matches!( + candidate.role.as_str(), + "textbox" | "searchbox" | "combobox" | "textarea" | "spinbutton" + ) + || tree::is_form_role(&candidate.role); + if editable { + candidate.value = None; + } + for child in &mut candidate.children { + hide(child); + } + } + + for candidate in screen + .candidates + .iter_mut() + .chain(screen.text_nodes.iter_mut()) + { + hide(candidate); + } +} + impl BrowserSurface { /// Loads `request`'s address in session `id`. A heavy page can be read /// long before its `load` event fires. @@ -444,3 +483,47 @@ pub(crate) fn browser_key(combo: &str, platform: Platform) -> String { .collect::>() .join("+") } + +#[cfg(test)] +mod private_value_tests { + use serde_json::json; + use tinycomputer_core::surface::{Candidate, Screen}; + + use super::hide_form_values; + + #[test] + fn private_observations_hide_editable_values_and_keep_useful_structure() { + let mut screen = Screen { + app: "browser".into(), + window: None, + surface: "window".into(), + candidates: vec![Candidate { + ref_id: "field-1".into(), + role: "textbox".into(), + name: Some("Address".into()), + value: Some(json!("restored form content")), + available_actions: vec!["Click".into(), "SetValue".into()], + ..Candidate::default() + }], + context: vec!["A lamp is ready to buy.".into()], + unexplored: Vec::new(), + text_nodes: vec![Candidate { + ref_id: "rich-field".into(), + role: "document".into(), + name: Some("Message body".into()), + value: Some(json!("restored rich text")), + available_actions: vec!["SetValue".into()], + ..Candidate::default() + }], + }; + + hide_form_values(&mut screen); + + assert_eq!(screen.candidates[0].value, None); + assert_eq!(screen.candidates[0].name.as_deref(), Some("Address")); + assert_eq!(screen.candidates[0].ref_id, "field-1"); + assert_eq!(screen.text_nodes[0].value, None); + assert_eq!(screen.text_nodes[0].name.as_deref(), Some("Message body")); + assert_eq!(screen.context, ["A lamp is ready to buy."]); + } +} diff --git a/crates/tinycomputer-browser/src/surface/sight/mod.rs b/crates/tinycomputer-browser/src/surface/sight/mod.rs index f008e86c9..be2e14de6 100644 --- a/crates/tinycomputer-browser/src/surface/sight/mod.rs +++ b/crates/tinycomputer-browser/src/surface/sight/mod.rs @@ -84,6 +84,16 @@ const MAX_CONTEXT_LINES: usize = 60; /// ref from an earlier screen. #[must_use] pub(crate) fn script(root: Option<&str>) -> String { + script_with_form_values(root, true) +} + +/// The Sight observation script for a host that keeps form values private. +#[must_use] +pub(crate) fn script_without_form_values(root: Option<&str>) -> String { + script_with_form_values(root, false) +} + +fn script_with_form_values(root: Option<&str>, include_form_values: bool) -> String { let root = root.map_or(Value::Null, |reference| Value::String(selector(reference))); let limits = json!({ "controls": MAX_CONTROLS, @@ -91,6 +101,7 @@ pub(crate) fn script(root: Option<&str>) -> String { "labels": MAX_LABELS, "name": MAX_NAME, "text": MAX_TEXT, + "hideFormValues": !include_form_values, }); format!( "({})({root}, {limits})", diff --git a/crates/tinycomputer-browser/src/surface/sight/sight.js b/crates/tinycomputer-browser/src/surface/sight/sight.js index 5220a0f70..04c4504c5 100644 --- a/crates/tinycomputer-browser/src/surface/sight/sight.js +++ b/crates/tinycomputer-browser/src/surface/sight/sight.js @@ -76,6 +76,18 @@ } return false; }; + const PRIVATE_FIELD_ROLES = [ + 'textbox', 'searchbox', 'combobox', 'textarea', 'document', 'spinbutton', + 'checkbox', 'radio', 'switch', 'menuitemcheckbox', 'menuitemradio', + ]; + const privateField = (element) => ['input', 'select', 'textarea'].includes(tag(element)) + || takesText(element) || PRIVATE_FIELD_ROLES.includes(role(element)); + const insidePrivateField = (element) => { + for (let parent = element; parent; parent = parent.parentElement) { + if (privateField(parent)) return true; + } + return false; + }; // A box that takes typed text: a text-like input, a text area, or the // outermost editable region. Whatever role the page gives it. @@ -1204,7 +1216,8 @@ const parent = node.parentElement; if (!parent || !squash(node.data) || texts >= limits.texts) continue; if (lastText && lastText.contains(parent)) continue; - if (controls.has(parent) || insideControl(parent) || insideText(parent) || !shown(parent)) continue; + if (controls.has(parent) || insideControl(parent) || insideText(parent) || !shown(parent) + || (limits.hideFormValues && insidePrivateField(parent))) continue; const rect = box(parent); if (rect.bottom < -height || rect.top > 2 * height) continue; const dropped = noiseRoot(parent); @@ -1218,6 +1231,7 @@ continue; } const element = node; + if (limits.hideFormValues && insidePrivateField(element.parentElement)) continue; const dropped = noiseRoot(element); // An ad's own frame or picture is an ad whether or not it shows words. if (dropped === element && ['iframe', 'img'].includes(tag(element)) @@ -1308,7 +1322,7 @@ role: what, name, description, - value: valueOf(element, what), + value: limits.hideFormValues && privateField(element) ? '' : valueOf(element, what), states: statesOf(element, what), box: [box(element).x, box(element).y, box(element).width, box(element).height].map(Math.round), path: pathOf(element), diff --git a/crates/tinycomputer-browser/src/surface/sight/sight_tests/live_tests.rs b/crates/tinycomputer-browser/src/surface/sight/sight_tests/live_tests.rs index 09481dd37..6b7670b79 100644 --- a/crates/tinycomputer-browser/src/surface/sight/sight_tests/live_tests.rs +++ b/crates/tinycomputer-browser/src/surface/sight/sight_tests/live_tests.rs @@ -5,7 +5,7 @@ use serde_json::json; #[cfg(feature = "agent-browser")] -use crate::surface::sight::script; +use crate::surface::sight::{script, script_without_form_values}; /// Reads `html` by sight in a real browser: `None` unless /// `TINYCOMPUTER_LIVE_BROWSER=1`, since CI has no browser to launch. The @@ -165,6 +165,35 @@ async fn live_ad_iframes_and_sponsored_blocks_are_removed() { ); } +#[cfg(feature = "agent-browser")] +#[tokio::test] +async fn live_private_sight_omits_editable_descendant_content() { + const UNKNOWN: &str = "profile-autofill-unknown-7Qz9"; + let html = format!( + r#"
+
+ {UNKNOWN} + +
+

Order total is $12.50

+
"# + ); + let Some(mut readings) = + live_results(&html, &[script_without_form_values(None), script(None)]).await + else { + return; + }; + let private = readings.remove(0); + let public = readings.remove(0); + let private_text = private.to_string(); + let public_text = public.to_string(); + + assert!(!private_text.contains(UNKNOWN)); + assert!(private_text.contains("Message")); + assert!(private_text.contains("Order total is $12.50")); + assert!(public_text.contains(UNKNOWN)); +} + #[cfg(feature = "agent-browser")] #[tokio::test] async fn live_blank_containers_are_dropped() { diff --git a/crates/tinycomputer-browser/src/surface/sight/sight_tests/reading_tests.rs b/crates/tinycomputer-browser/src/surface/sight/sight_tests/reading_tests.rs index bac2b0894..7c36ea456 100644 --- a/crates/tinycomputer-browser/src/surface/sight/sight_tests/reading_tests.rs +++ b/crates/tinycomputer-browser/src/surface/sight/sight_tests/reading_tests.rs @@ -3,7 +3,18 @@ use serde_json::json; -use crate::surface::sight::{Denoised, denoised, is_seen, screen, script, selector}; +use crate::surface::sight::{ + Denoised, denoised, is_seen, screen, script, script_without_form_values, selector, +}; + +#[test] +fn private_sight_script_skips_form_content_descendants() { + let private = script_without_form_values(None); + let public = script(None); + + assert!(private.contains("\"hideFormValues\":true")); + assert!(public.contains("\"hideFormValues\":false")); +} /// A booking widget as sight reads it: a cookie dialog in front, a field /// named by the words above it, a city row a page marked `combobox`, and an @@ -108,7 +119,7 @@ fn the_script_is_called_with_its_root_and_limits() { assert!(whole.contains("data-tc-seen")); assert!( whole.ends_with( - r#"(null, {"controls":800,"labels":3000,"name":120,"text":160,"texts":400})"# + r#"(null, {"controls":800,"hideFormValues":false,"labels":3000,"name":120,"text":160,"texts":400})"# ) ); let under = script(Some("seen:7")); diff --git a/crates/tinycomputer-browser/src/surface/surface_tests/tree_tests.rs b/crates/tinycomputer-browser/src/surface/surface_tests/tree_tests.rs index 9b35d196a..7bdb8aea6 100644 --- a/crates/tinycomputer-browser/src/surface/surface_tests/tree_tests.rs +++ b/crates/tinycomputer-browser/src/surface/surface_tests/tree_tests.rs @@ -4,7 +4,7 @@ use serde_json::json; use super::PAGE; -use crate::surface::tree::{parse_line, screen}; +use crate::surface::tree::{parse_line, screen, screen_without_form_values}; #[test] fn a_line_parses_its_role_name_attributes_and_value() { @@ -103,6 +103,107 @@ fn dialogs_are_the_surface_in_front() { assert_eq!(capped.context.len(), 2, "duplicates are kept once"); } +#[test] +fn unreferenced_editable_values_do_not_become_shared_context() { + let parsed = screen( + "- heading \"Checkout\"\n- spinbutton: restored-control-value\n- text: Payment is ready\n", + "Shop", + ); + + assert_eq!(parsed.context, ["Checkout", "Payment is ready"]); + assert!(parsed.text_nodes.iter().any(|node| { + node.role == "spinbutton" + && node + .value + .as_ref() + .is_some_and(|value| value == "restored-control-value") + })); +} + +#[test] +fn private_tree_observations_hide_document_descendants_and_toggle_values() { + const UNKNOWN: &str = "profile-autofill-unknown-7Qz9"; + let tree = format!( + r#"- heading "Checkout" +- group + - document [ref=e1]: {UNKNOWN} + - text: {UNKNOWN} document body + - text "{UNKNOWN} named document body" + - generic "{UNKNOWN} ancestor label" + - button "{UNKNOWN} action" [ref=e5] + - menuitemcheckbox [ref=e2]: {UNKNOWN} + - text: {UNKNOWN} checkbox echo + - menuitemradio [ref=e3]: {UNKNOWN} + - text: {UNKNOWN} radio echo + - textbox "Email" [ref=e4]: {UNKNOWN} +- text: Order total is $12.50 +"# + ); + + let private = screen_without_form_values(&tree, "Checkout"); + let model_view = private + .context + .iter() + .cloned() + .chain( + private + .candidates + .iter() + .chain(&private.text_nodes) + .map(|node| tinycomputer_core::surface::describe(node, true).to_string()), + ) + .collect::>() + .join("\n"); + + assert!( + !model_view.contains(UNKNOWN), + "serialized candidate descriptions contain restored field text" + ); + assert!(model_view.contains("Email")); + assert!(model_view.contains("Order total is $12.50")); + assert_eq!(private.candidates[0].role, "document"); + assert_eq!(private.candidates[0].value, None); + assert_eq!(private.candidates[1].role, "menuitemcheckbox"); + assert_eq!(private.candidates[1].value, None); + assert_eq!(private.candidates[2].role, "menuitemradio"); + assert_eq!(private.candidates[2].value, None); + assert!(private.candidates[3].value.is_none()); + assert!(private.candidates.iter().all(|node| node.ref_id != "e5")); + assert!(private.candidates[0].description.is_none()); + assert!(private.text_nodes.iter().all(|node| { + node.value + .as_ref() + .is_none_or(|value| !value.to_string().contains(UNKNOWN)) + })); + + // The non-private surface keeps the normal tree's existing value + // behavior; the masking is enabled only for a host with SecretHost. + let public = screen(&tree, "Checkout"); + assert_eq!(public.candidates[0].value.as_ref(), Some(&json!(UNKNOWN))); + assert!( + public + .text_nodes + .iter() + .any(|node| node.value.as_ref() == Some(&json!(format!("{UNKNOWN} document body")))) + ); + assert!( + public + .text_nodes + .iter() + .any(|node| node.name.as_deref() == Some(&format!("{UNKNOWN} named document body"))) + ); + assert!( + public.candidates.iter().any(|node| node.ref_id == "e5" + && node.name.as_deref() == Some(&format!("{UNKNOWN} action"))) + ); + assert!( + public + .context + .iter() + .any(|line| line == "Order total is $12.50") + ); +} + #[test] fn repeated_containers_are_numbered_so_their_cards_group() { let page = "- list \"Results\"\n - listitem\n - text: IndiGo\n - text: ₹6,840\n - button \"Select\" [ref=e1]\n - listitem\n - text: Vistara\n - text: ₹7,210\n - button \"Select\" [ref=e2]\n- list \"More\"\n - listitem\n - button \"Next page\" [ref=e3]\n"; diff --git a/crates/tinycomputer-browser/src/surface/tree.rs b/crates/tinycomputer-browser/src/surface/tree.rs index 5cea37a95..2c6b62a0c 100644 --- a/crates/tinycomputer-browser/src/surface/tree.rs +++ b/crates/tinycomputer-browser/src/surface/tree.rs @@ -14,7 +14,19 @@ const MAX_CONTEXT_CHARS: usize = 160; /// Roles that contain a page's field content rather than its chrome; text /// inside them never reaches the shared context. -const FIELD_ROLES: &[&str] = &["textbox", "searchbox", "combobox", "textarea", "document"]; +const FIELD_ROLES: &[&str] = &[ + "textbox", + "searchbox", + "combobox", + "textarea", + "document", + "spinbutton", + "checkbox", + "radio", + "switch", + "menuitemcheckbox", + "menuitemradio", +]; /// Roles a value is typed into. const TYPED_ROLES: &[&str] = &["textbox", "searchbox", "combobox", "spinbutton", "textarea"]; @@ -143,6 +155,22 @@ fn closing_quote(body: &str) -> Option { /// A whole snapshot as a [`Screen`] of the page titled `title`. #[must_use] pub(crate) fn screen(tree: &str, title: &str) -> Screen { + screen_with_form_values(tree, title, true) +} + +/// Parses a tree while keeping form content out of every candidate and +/// description that could be shown to a task model. +#[must_use] +pub(crate) fn screen_without_form_values(tree: &str, title: &str) -> Screen { + screen_with_form_values(tree, title, false) +} + +/// Whether a role can contain user-entered or restored form content. +pub(crate) fn is_form_role(role: &str) -> bool { + FIELD_ROLES.contains(&role) +} + +fn screen_with_form_values(tree: &str, title: &str, include_form_values: bool) -> Screen { let mut candidates = Vec::new(); let mut context: Vec = Vec::new(); let mut text_nodes = Vec::new(); @@ -158,11 +186,18 @@ pub(crate) fn screen(tree: &str, title: &str) -> Screen { for (order, line) in tree.lines().filter_map(parse_line).enumerate() { ancestors.retain(|(depth, _, _)| *depth < line.depth); unnamed.retain(|(depth, _)| *depth < line.depth); + let inside_field = ancestors + .iter() + .any(|(_, _, role)| FIELD_ROLES.contains(&role.as_str())); // A value-bearing line's value is what was typed or selected into // it: private unless values are shared, and never a safe // description for an enclosing unnamed container. Its accessible // name — a label, not content — still is. - let describable = if VALUE_BEARING_ROLES.contains(&line.role.as_str()) { + let describable = if !include_form_values + && (inside_field || FIELD_ROLES.contains(&line.role.as_str())) + { + line.name.as_deref().filter(|_| !inside_field) + } else if VALUE_BEARING_ROLES.contains(&line.role.as_str()) { line.name.as_deref() } else { line.name.as_deref().or(line.value.as_deref()) @@ -176,35 +211,44 @@ pub(crate) fn screen(tree: &str, title: &str) -> Screen { .iter() .map(|(_, label, _)| label.clone()) .collect::>(); - let inside_field = ancestors - .iter() - .any(|(_, _, role)| FIELD_ROLES.contains(&role.as_str())); match line.role.as_str() { "dialog" if surface == "window" => "sheet".clone_into(&mut surface), "alertdialog" => "alert".clone_into(&mut surface), _ => {} } - let node = candidate(&line, path, order); - if line.reference().is_some() { - if !line.has("disabled") { - // A control with no name of its own — a list row whose - // `aria-labelledby` points nowhere — is named by what it - // shows. A text field — or a control holding a value — is not: - // what is inside it is its content, private unless values - // are shared. - if node.name.is_none() - && node.value.is_none() - && !TEXT_ENTRY_ROLES.contains(&line.role.as_str()) - { - unnamed.push((line.depth, candidates.len())); + if include_form_values || !inside_field { + let mut node = candidate(&line, path, order); + if !include_form_values && (inside_field || FIELD_ROLES.contains(&line.role.as_str())) { + node.value = None; + if inside_field && line.reference().is_none() { + // Unreferenced descendants become text_nodes. Their tree + // name can carry the same rich-field body as their value. + node.name = None; } - candidates.push(node); } - } else { - if !inside_field { - remember(&line, &mut context); + if line.reference().is_some() { + if !line.has("disabled") { + // A control with no name of its own — a list row whose + // `aria-labelledby` points nowhere — is named by what it + // shows. A text field — or a control holding a value — is not: + // what is inside it is its content, private unless values + // are shared. + if node.name.is_none() + && node.value.is_none() + && !TEXT_ENTRY_ROLES.contains(&line.role.as_str()) + { + unnamed.push((line.depth, candidates.len())); + } + candidates.push(node); + } + } else { + let is_field = FIELD_ROLES.contains(&line.role.as_str()) + || VALUE_BEARING_ROLES.contains(&line.role.as_str()); + if !inside_field && !is_field { + remember(&line, &mut context); + } + text_nodes.push(node); } - text_nodes.push(node); } siblings.truncate(line.depth + 1); siblings.resize_with(line.depth + 1, Default::default); diff --git a/crates/tinycomputer-engine/src/task/browser.rs b/crates/tinycomputer-engine/src/task/browser.rs index 0ab67bca8..5d922b8c2 100644 --- a/crates/tinycomputer-engine/src/task/browser.rs +++ b/crates/tinycomputer-engine/src/task/browser.rs @@ -6,8 +6,8 @@ use std::sync::{Arc, Mutex}; use tinycomputer_browser::{ActionContext, Browser, BrowserSurface, SessionOptions}; use tinycomputer_bus::agent::{PaymentMode, TaskConstraints, TaskId}; use tinycomputer_bus::browser::{ScreenshotRequest, SessionId}; -use tinycomputer_bus::{DesktopError, DesktopResponse, RunFlowRequest}; -use tinycomputer_core::surface::{Depth, Surface}; +use tinycomputer_bus::{DesktopError, DesktopResponse, JevOperation, RunFlowRequest}; +use tinycomputer_core::surface::{Candidate, Depth, Screen, Surface}; use super::{CaptureFuture, FlowFuture, FlowRunner, PrepareFuture, TextFuture}; use crate::SecretHost; @@ -54,7 +54,9 @@ impl BrowserRunner { } /// Uses `host` to resolve opaque secret handles and type them at the - /// moment a task fills a field. + /// moment a task fills a field. Editable control values are also hidden + /// from task observations while this host is present; the host can still + /// read and verify a field through the private surface APIs. #[must_use] pub fn with_secret_host(mut self, host: Arc) -> Self { self.secret_host = Some(host); @@ -94,7 +96,7 @@ impl BrowserRunner { options.allowed_origins.clone_from(&constraints.origins); } options.headless = !constraints.headed; - BrowserSurface::new( + let surface = BrowserSurface::new( self.browser.clone(), options, tokio::runtime::Handle::current(), @@ -103,7 +105,12 @@ impl BrowserRunner { task_id: Some(task.0.clone()), session_id: None, payment_in_play: constraints.payment == PaymentMode::FillThenApprove, - }) + }); + if self.secret_host.is_some() { + surface.without_form_values() + } else { + surface + } }; self.surfaces.lock().map_or_else( @@ -302,6 +309,7 @@ impl BrowserRunner { let mut request = request; request.task_id = Some(task.0.clone()); let secret_host = self.secret_host.clone(); + let task_id = task.0.clone(); Box::pin(async move { if surface.update_action_context(context).await.is_err() { return DesktopResponse::err( @@ -312,13 +320,398 @@ impl BrowserRunner { ), ); } - tinycomputer_engine_flow(surface, runtime, request, secret_host).await + match secret_host { + Some(host) => { + let surface = SecretRedactingSurface { + inner: surface, + host: host.clone(), + task_id, + }; + tinycomputer_engine_flow(surface, runtime, request, Some(host)).await + } + None => tinycomputer_engine_flow(surface, runtime, request, None).await, + } }) } } +/// Keeps known host-held values out of every model-facing screen and browser +/// reply while delegating live reads and actions to the underlying surface. +/// Editable field values are removed structurally by +/// `BrowserSurface::without_form_values`; this layer also scrubs page text, +/// labels, non-form values, and error output using the host's intent-scoped +/// redactor. +#[derive(Clone)] +struct SecretRedactingSurface { + inner: BrowserSurface, + host: Arc, + task_id: String, +} + +impl SecretRedactingSurface { + fn redact_screen(&self, screen: &mut Screen) { + redact_screen(&*self.host, &self.task_id, screen); + } + + fn redact_response(&self, response: DesktopResponse) -> DesktopResponse { + redact_response(&*self.host, &self.task_id, response) + } +} + +impl Surface for SecretRedactingSurface { + fn observe( + &self, + app: &str, + root: Option<&str>, + depth: Depth, + ) -> Result> { + let mut screen = match self.inner.observe(app, root, depth) { + Ok(screen) => screen, + Err(error) => { + return Err(redact_observation_error(&*self.host, &self.task_id, error)); + } + }; + self.redact_screen(&mut screen); + Ok(screen) + } + + fn execute( + &self, + operation: JevOperation, + target: Option, + text: Option, + ) -> DesktopResponse { + self.redact_response(self.inner.execute(operation, target, text)) + } + + fn authorize_secret_type(&self, target: &Candidate) -> Result { + self.inner.authorize_secret_type(target) + } + + fn read_value(&self, target: &Candidate) -> Option { + self.inner.read_value(target) + } + + fn paste(&self, app: &str, target: &Candidate, text: &str) -> DesktopResponse { + self.redact_response(self.inner.paste(app, target, text)) + } + + fn press(&self, app: &str, combo: &str) -> DesktopResponse { + self.redact_response(self.inner.press(app, combo)) + } + + fn launch(&self, app: &str) -> DesktopResponse { + self.redact_response(self.inner.launch(app)) + } + + fn settle(&self) { + self.inner.settle(); + } + + fn settle_briefly(&self) { + self.inner.settle_briefly(); + } + + fn await_change(&self, ms: u64) -> bool { + self.inner.await_change(ms) + } + + fn navigate(&self, url: &str) -> DesktopResponse { + self.redact_response(self.inner.navigate(url)) + } + + fn back(&self, app: &str) -> DesktopResponse { + self.redact_response(self.inner.back(app)) + } + + fn dismiss_cover(&self, target: &Candidate) -> DesktopResponse { + self.redact_response(self.inner.dismiss_cover(target)) + } +} + +fn redact_observation_error( + host: &dyn SecretHost, + task_id: &str, + response: Box, +) -> Box { + Box::new(redact_response(host, task_id, *response)) +} + +fn redact_response( + host: &dyn SecretHost, + task_id: &str, + response: DesktopResponse, +) -> DesktopResponse { + let redact = |text: &str| host.redact(task_id, text); + let Ok(mut value) = serde_json::to_value(response) else { + return redaction_failed_response(); + }; + + // These fields can be used to address or replay an operation. Rewriting + // them into a placeholder would make an apparently valid response point + // at a different target, so fail closed on a collision. + if operational_collision(&value, &redact) { + return redaction_failed_response(); + } + super::redact_value(&mut value, &redact); + serde_json::from_value(value).unwrap_or_else(|_| redaction_failed_response()) +} + +fn operational_collision(value: &serde_json::Value, redact: &impl Fn(&str) -> String) -> bool { + match value { + serde_json::Value::Object(fields) => fields.iter().any(|(key, value)| { + let operational = matches!( + key.as_str(), + "command" | "code" | "ref" | "ref_id" | "target" | "action" | "available_actions" + ); + (operational && value.as_str().is_some_and(|text| redact(text) != text)) + || operational_collision(value, redact) + }), + serde_json::Value::Array(items) => { + items.iter().any(|item| operational_collision(item, redact)) + } + _ => false, + } +} + +fn redaction_failed_response() -> DesktopResponse { + DesktopResponse::err( + "redaction", + DesktopError::new( + "REDACTION_FAILED", + "the browser response could not be safely redacted", + ), + ) +} + +fn redact_screen(host: &dyn SecretHost, task_id: &str, screen: &mut Screen) { + fn candidate(host: &dyn SecretHost, task_id: &str, node: &mut Candidate) -> bool { + let redact = |text: &str| host.redact(task_id, text); + let reference = redact(&node.ref_id); + let role = redact(&node.role); + // Refs and actions are executable metadata. If redaction finds a + // collision, omit the candidate instead of manufacturing an invalid + // target that could address a different control. + if reference != node.ref_id || role != node.role { + return false; + } + node.available_actions + .retain(|action| redact(action) == *action); + node.name = node.name.take().map(|text| redact(&text)); + node.description = node.description.take().map(|text| redact(&text)); + node.states.retain(|state| redact(state) == *state); + for path in &mut node.path { + *path = redact(path); + } + if let Some(value) = &mut node.value { + super::redact_value(value, &redact); + } + if let Some(bounds) = &mut node.bounds { + let original = bounds.clone(); + super::redact_value(bounds, &redact); + if *bounds != original { + node.bounds = None; + } + } + node.children + .retain_mut(|child| candidate(host, task_id, child)); + true + } + let redact = |text: &str| host.redact(task_id, text); + screen.app = redact(&screen.app); + screen.window = screen.window.take().map(|text| redact(&text)); + screen.surface = redact(&screen.surface); + for text in &mut screen.context { + *text = redact(text); + } + screen + .unexplored + .retain(|reference| redact(reference) == *reference); + screen + .candidates + .retain_mut(|node| candidate(host, task_id, node)); + screen + .text_nodes + .retain_mut(|node| candidate(host, task_id, node)); +} + +#[cfg(test)] +mod redaction_tests { + use std::sync::Arc; + + use serde_json::json; + use tinycomputer_bus::{DesktopError, DesktopResponse}; + use tinycomputer_core::surface::{Candidate, Screen, describe}; + + use super::{redact_observation_error, redact_response, redact_screen}; + use crate::{SecretHost, SecretTypeRequest}; + + struct Host; + + impl SecretHost for Host { + fn type_secret(&self, _request: &SecretTypeRequest) -> Result<(), String> { + Ok(()) + } + + fn redact(&self, _task_id: &str, text: &str) -> String { + text.replace("private-canary", "[hidden]") + .replace("123456789", "[hidden]") + } + } + + #[test] + fn jev_screen_context_and_candidate_labels_are_redacted_before_model_use() { + let host: Arc = Arc::new(Host); + let mut screen = Screen { + app: "browser".into(), + window: Some("private-canary page".into()), + surface: "window".into(), + candidates: vec![ + Candidate { + ref_id: "e1".into(), + role: "button".into(), + name: Some("private-canary action".into()), + value: Some( + json!({"private-canary": 123_456_789, "[hidden]": "private-canary"}), + ), + path: vec!["private-canary parent".into()], + states: vec!["private-canary selected".into()], + available_actions: vec!["Click".into(), "private-canary action".into()], + bounds: Some(json!({"x": 10, "y": 2})), + ..Candidate::default() + }, + Candidate { + ref_id: "private-canary-ref".into(), + role: "button".into(), + name: Some("Unsafe ref".into()), + available_actions: vec!["Click".into()], + ..Candidate::default() + }, + ], + context: vec!["Restored private-canary value".into()], + unexplored: vec!["private-canary-ref".into(), "e2".into()], + text_nodes: Vec::new(), + }; + + redact_screen(host.as_ref(), "task-1", &mut screen); + + let candidate = &screen.candidates[0]; + assert_eq!(candidate.name.as_deref(), Some("[hidden] action")); + assert_eq!(candidate.path, ["[hidden] parent"]); + assert!(candidate.states.is_empty()); + assert!(candidate.value.as_ref().is_some_and(|value| { + value["[hidden]"] == "[hidden]" && value["[hidden]#2"] == "[hidden]" + })); + assert!( + candidate + .bounds + .as_ref() + .is_some_and(|bounds| bounds["x"] == 10) + ); + assert_eq!(candidate.available_actions, ["Click"]); + assert!( + !screen + .candidates + .iter() + .any(|node| node.ref_id.contains("private-canary")) + ); + assert_eq!(screen.unexplored, ["e2"]); + assert_eq!(screen.context[0], "Restored [hidden] value"); + assert_eq!(screen.candidates[0].ref_id, "e1"); + } + + #[test] + fn observation_errors_are_redacted_before_they_are_returned() { + let host = Host; + let error = Box::new(DesktopResponse::err( + "observe", + DesktopError::new("private-canary-code", "page contained private-canary"), + )); + + let safe = redact_observation_error(&host, "task-1", error); + assert!(safe.error.as_ref().is_some_and(|error| { + error.code == "REDACTION_FAILED" + && error.message == "the browser response could not be safely redacted" + })); + } + + #[test] + fn response_redaction_covers_numeric_values_and_object_keys() { + let response = DesktopResponse::ok( + "snapshot", + json!({ + "metadata": {"private-canary": "123456789", "[hidden]": 123_456_789}, + "message": "private-canary", + }), + ); + + let safe = redact_response(&Host, "task-1", response); + assert!(safe.data.as_ref().is_some_and(|data| { + data["metadata"]["[hidden]"] == "[hidden]" + && data["metadata"]["[hidden]#2"] == "[hidden]" + && data["message"] == "[hidden]" + })); + } + + #[test] + fn response_with_secret_in_an_operational_ref_fails_closed() { + let response = DesktopResponse::ok( + "snapshot", + json!({"target": {"ref_id": "private-canary-ref"}}), + ); + + let safe = redact_response(&Host, "task-1", response); + + assert!(!safe.ok); + assert!( + safe.error + .as_ref() + .is_some_and(|error| error.code == "REDACTION_FAILED") + ); + } + + #[test] + fn secret_shaped_bounds_are_dropped_before_model_description() { + let host: Arc = Arc::new(Host); + let mut screen = Screen { + app: "browser".into(), + window: None, + surface: "window".into(), + candidates: vec![ + Candidate { + ref_id: "e1".into(), + role: "button".into(), + bounds: Some(json!({"x": 20, "y": 30, "width": 100, "height": 40})), + ..Candidate::default() + }, + Candidate { + ref_id: "e2".into(), + role: "group".into(), + bounds: Some(json!({"label": "private-canary", "offset": 123_456_789})), + ..Candidate::default() + }, + ], + context: Vec::new(), + unexplored: Vec::new(), + text_nodes: Vec::new(), + }; + + redact_screen(host.as_ref(), "task-1", &mut screen); + + assert_eq!( + screen.candidates[0].bounds, + Some(json!({"x": 20, "y": 30, "width": 100, "height": 40})) + ); + assert!(screen.candidates[1].bounds.is_none()); + let model_description = + serde_json::to_string(&describe(&screen.candidates[1], true)).unwrap_or_default(); + assert!(!model_description.contains("private-canary")); + assert!(!model_description.contains("123456789")); + } +} + async fn tinycomputer_engine_flow( - surface: BrowserSurface, + surface: impl Surface + Sync, runtime: JevRuntime, request: RunFlowRequest, secret_host: Option>, diff --git a/crates/tinycomputer-engine/src/task/browser_tests.rs b/crates/tinycomputer-engine/src/task/browser_tests.rs index 31b5d52de..c63532ecf 100644 --- a/crates/tinycomputer-engine/src/task/browser_tests.rs +++ b/crates/tinycomputer-engine/src/task/browser_tests.rs @@ -176,7 +176,7 @@ impl Engine for BrowserScriptEngine { "title" => json!({"title": "Local fixture"}), "snapshot" => { let snapshot = if self.0.echo_secret { - "- heading \"Browser runner fixture\" [ref=h1]\n- textbox \"Card number\" [ref=card]: 4111 1111 1111 1111" + "- heading \"Browser runner fixture\" [ref=h1]\n- textbox \"Card number\" [ref=card]: 4111 1111 1111 1111\n- textbox \"Email\" [ref=email]: unknown-autofill-canary\n- text: The saved card was 4111 1111 1111 1111" } else { "- heading \"Browser runner fixture\" [ref=h1]" }; @@ -484,6 +484,9 @@ async fn rescue_visible_text_is_redacted_by_the_host() -> Result<(), Box