diff --git a/crates/tinycomputer-browser/src/action_gate.rs b/crates/tinycomputer-browser/src/action_gate.rs index c050f7ead..ad491b9c4 100644 --- a/crates/tinycomputer-browser/src/action_gate.rs +++ b/crates/tinycomputer-browser/src/action_gate.rs @@ -25,7 +25,19 @@ pub struct ActionTarget { pub reference: Option, } -/// Information a trusted host may inspect before the browser acts. +/// Page content an engine caller is about to receive. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ObservationKind { + /// The page's accessibility tree and controls. + Snapshot, + /// The page's extracted text, Markdown, or HTML. + ReadPage, + /// A screenshot of the page. + Screenshot, +} + +/// Information a trusted host may inspect before the browser acts or returns +/// page content. /// /// `payload` contains the requested action and its value, including typed /// text. It is intentionally omitted from `Debug`; implementations must treat @@ -42,6 +54,8 @@ pub struct ActionRequest { pub current_url: Option, /// The requested destination for a navigation, when applicable. pub destination_url: Option, + /// Whether this request observes page content rather than acting on it. + pub observation: Option, /// Host-supplied task context. pub context: ActionContext, } @@ -61,6 +75,7 @@ impl ActionRequest { target, current_url, destination_url, + observation: None, context: context.clone(), } } @@ -82,6 +97,22 @@ impl ActionRequest { target, current_url, destination_url, + observation: None, + context: context.clone(), + } + } + + pub(crate) fn observation( + kind: ObservationKind, + current_url: Option, + context: &ActionContext, + ) -> Self { + Self { + payload: serde_json::json!({ "action": "observe" }), + target: None, + current_url, + destination_url: None, + observation: Some(kind), context: context.clone(), } } @@ -98,6 +129,7 @@ impl std::fmt::Debug for ActionRequest { .field("target", &self.target) .field("current_url", &self.current_url) .field("destination_url", &self.destination_url) + .field("observation", &self.observation) .field("context", &self.context) .finish_non_exhaustive() } @@ -116,7 +148,8 @@ pub enum ActionVerdict { }, } -/// A synchronous host policy consulted before every typed or raw action. +/// A synchronous host policy consulted before every typed or raw action and +/// before a snapshot, page read, or screenshot can expose content. pub trait ActionGate: Send + Sync { /// Decide whether this request may reach the page. fn check(&self, request: &ActionRequest) -> ActionVerdict; diff --git a/crates/tinycomputer-browser/src/lib.rs b/crates/tinycomputer-browser/src/lib.rs index a5e7ec3ae..4466a7182 100644 --- a/crates/tinycomputer-browser/src/lib.rs +++ b/crates/tinycomputer-browser/src/lib.rs @@ -50,6 +50,7 @@ mod surface; pub use action_gate::{ ActionContext, ActionGate, ActionRequest, ActionTarget, ActionVerdict, AllowAllActions, + ObservationKind, }; pub use engine::{Engine, Launcher, Reply}; pub use error::{Error, Result}; diff --git a/crates/tinycomputer-browser/src/sessions/page.rs b/crates/tinycomputer-browser/src/sessions/page.rs index f4ba2bfb1..e6598f665 100644 --- a/crates/tinycomputer-browser/src/sessions/page.rs +++ b/crates/tinycomputer-browser/src/sessions/page.rs @@ -8,7 +8,7 @@ use tinycomputer_bus::browser::{ }; use super::{Browser, Session}; -use crate::action_gate::ActionRequest; +use crate::action_gate::{ActionRequest, ObservationKind}; use crate::convert; use crate::deep; use crate::error::{Error, Result}; @@ -112,10 +112,24 @@ impl Browser { let session = self.session(id)?; let mut session = session.lock().await; session.check_if_readable(false).await?; + // The URL lookup above is an internal engine command and is not sent + // through the gate. Read the live address once more immediately before + // content is observed, without recursively gating that URL lookup. + let current_url = session.action_url().await; + self.check_action(&ActionRequest::observation( + ObservationKind::Snapshot, + current_url, + &session.action_context, + ))?; let data = session.run(convert::snapshot(&request)).await?; let controls = session.find_deep(request.selector.as_deref()).await; let page = session.page().await?; let page = session.admit(page).await?; + self.check_action(&ActionRequest::observation( + ObservationKind::Snapshot, + Some(page.url.clone()), + &session.action_context, + ))?; session.sequence += 1; let mut snapshot = reply::snapshot( &data, @@ -252,6 +266,7 @@ impl Browser { }), current_url: Some(current_url.clone()), destination_url: None, + observation: None, context: session.action_context.clone(), })?; Ok(current_url) @@ -266,6 +281,12 @@ impl Browser { let session = self.session(id)?; let mut session = session.lock().await; session.check_if_readable(false).await?; + let current_url = session.action_url().await; + self.check_action(&ActionRequest::observation( + ObservationKind::ReadPage, + current_url, + &session.action_context, + ))?; let data = session.run(convert::read(&request)).await?; let content = ["content", "text", "html"] .into_iter() @@ -276,6 +297,11 @@ impl Browser { let content = content.chars().take(request.max_chars).collect(); let page = session.page().await?; let page = session.admit(page).await?; + self.check_action(&ActionRequest::observation( + ObservationKind::ReadPage, + Some(page.url.clone()), + &session.action_context, + ))?; Ok(PageText { url: page.url, title: page.title, @@ -413,6 +439,12 @@ impl Browser { let path = session.scratch_file("shot", self.next(), extension)?; let command = convert::screenshot(&request, &path)?; session.check_if_readable(false).await?; + let current_url = session.action_url().await; + self.check_action(&ActionRequest::observation( + ObservationKind::Screenshot, + current_url, + &session.action_context, + ))?; let data = session.run(command).await?; let written = data .get("path") @@ -423,6 +455,12 @@ impl Browser { let _removed = std::fs::remove_file(&written); // A picture of a page that turned out refused is never handed over. session.check_if_readable(true).await?; + let current_url = session.action_url().await; + self.check_action(&ActionRequest::observation( + ObservationKind::Screenshot, + current_url, + &session.action_context, + ))?; within_cap(bytes.len().div_ceil(3) * 4)?; let (width, height) = reply::image_size(&bytes); self.lock_outputs()? diff --git a/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs b/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs index 0e3e23730..826bcb46c 100644 --- a/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs +++ b/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use tinycomputer_bus::browser::{ Action, EvaluateRequest, LocateBy, Locator, NavigateRequest, ReadFormat, ReadRequest, - SessionOptions, SnapshotRequest, Target, + ScreenshotRequest, SessionOptions, SnapshotRequest, Target, }; use super::open; @@ -70,6 +70,120 @@ impl ActionGate for RefuseUnknownCurrentUrl { } } +struct RefuseUntrustedObservations; + +impl ActionGate for RefuseUntrustedObservations { + fn check(&self, request: &ActionRequest) -> ActionVerdict { + if request.observation.is_some() + && request + .current_url + .as_deref() + .is_some_and(|url| !url.starts_with("https://") || url.contains("127.0.0.1")) + { + ActionVerdict::Refuse { + reason: "page URL is not public HTTPS".to_owned(), + } + } else { + ActionVerdict::Allow + } + } +} + +#[tokio::test] +async fn untrusted_page_observations_are_refused_before_content_reaches_the_engine() { + for url in ["http://shop.test/", "https://127.0.0.1/"] { + let url = url.to_owned(); + let fake = Fake::scripted(move |command| { + (command["action"] == "url").then(|| ok(&serde_json::json!({"url": url.clone()}))) + }); + let browser = Browser::with_scratch( + Arc::new(fake.clone()), + super::scratch("blocked-observation"), + ) + .with_action_gate(Arc::new(RefuseUntrustedObservations)); + let id = browser + .open_session(SessionOptions::default()) + .await + .unwrap() + .id; + + assert!(matches!( + browser.snapshot(&id, SnapshotRequest::default()).await, + Err(Error::ActionRefused { .. }) + )); + assert!(matches!( + browser.read_page(&id, ReadRequest::default()).await, + Err(Error::ActionRefused { .. }) + )); + assert!(matches!( + browser.screenshot(&id, ScreenshotRequest::default()).await, + Err(Error::ActionRefused { .. }) + )); + let actions = fake.actions(); + assert!(!actions.contains(&"snapshot".to_owned()), "{actions:?}"); + assert!(!actions.contains(&"read".to_owned()), "{actions:?}"); + assert!(!actions.contains(&"screenshot".to_owned()), "{actions:?}"); + browser.close_session(&id).await.unwrap(); + } +} + +#[tokio::test] +async fn a_snapshot_is_discarded_if_the_live_url_changes_during_observation() { + let url = Arc::new(std::sync::Mutex::new("https://shop.test/".to_owned())); + let page_url = url.clone(); + let fake = Fake::scripted(move |command| match command["action"].as_str() { + Some("url") => Some(ok(&serde_json::json!({ + "url": page_url.lock().unwrap().clone(), + }))), + Some("snapshot") => { + *page_url.lock().unwrap() = "http://127.0.0.1/".to_owned(); + Some(ok(&serde_json::json!({ + "snapshot": "text from the page that must not be returned", + "refs": {}, + }))) + } + _ => None, + }); + let browser = Browser::with_scratch(Arc::new(fake), super::scratch("redirected-observation")) + .with_action_gate(Arc::new(RefuseUntrustedObservations)); + let id = browser + .open_session(SessionOptions::default()) + .await + .unwrap() + .id; + + assert!(matches!( + browser.snapshot(&id, SnapshotRequest::default()).await, + Err(Error::ActionRefused { .. }) + )); +} + +#[test] +fn browser_surface_never_exposes_an_untrusted_page_snapshot_to_its_runner() { + use crate::surface::{BrowserSurface, Perception}; + use tinycomputer_core::surface::{Depth, Surface}; + + let runtime = tokio::runtime::Runtime::new().unwrap(); + let fake = Fake::scripted(|command| { + (command["action"] == "url").then(|| ok(&serde_json::json!({"url": "https://127.0.0.1/"}))) + }); + let browser = + Browser::with_scratch(Arc::new(fake.clone()), super::scratch("runner-observation")) + .with_action_gate(Arc::new(RefuseUntrustedObservations)); + let surface = BrowserSurface::new( + Arc::new(browser), + SessionOptions::default(), + runtime.handle().clone(), + ) + .with_perception(Perception::Tree); + + assert!(surface.observe("browser", None, Depth::Full).is_err()); + assert!( + !fake.actions().contains(&"snapshot".to_owned()), + "the runner must be refused before the accessibility tree is read" + ); +} + #[derive(Default)] struct CaptureActionRequest(std::sync::Mutex>); diff --git a/crates/tinycomputer-browser/src/surface/surface_tests/operations_tests.rs b/crates/tinycomputer-browser/src/surface/surface_tests/operations_tests.rs index 7c80beb8c..30363ce10 100644 --- a/crates/tinycomputer-browser/src/surface/surface_tests/operations_tests.rs +++ b/crates/tinycomputer-browser/src/surface/surface_tests/operations_tests.rs @@ -58,6 +58,7 @@ fn secret_type_preflight_uses_gate_metadata_without_sending_text_to_the_page() { target: request.target.clone(), current_url: request.current_url.clone(), destination_url: request.destination_url.clone(), + observation: request.observation, context: request.context.clone(), }); ActionVerdict::Refuse {