Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions crates/tinycomputer-browser/src/action_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,19 @@ pub struct ActionTarget {
pub reference: Option<String>,
}

/// 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
Expand All @@ -42,6 +54,8 @@ pub struct ActionRequest {
pub current_url: Option<String>,
/// The requested destination for a navigation, when applicable.
pub destination_url: Option<String>,
/// Whether this request observes page content rather than acting on it.
pub observation: Option<ObservationKind>,
/// Host-supplied task context.
pub context: ActionContext,
}
Expand All @@ -61,6 +75,7 @@ impl ActionRequest {
target,
current_url,
destination_url,
observation: None,
context: context.clone(),
}
}
Expand All @@ -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<String>,
context: &ActionContext,
) -> Self {
Self {
payload: serde_json::json!({ "action": "observe" }),
target: None,
current_url,
destination_url: None,
observation: Some(kind),
context: context.clone(),
}
}
Expand All @@ -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()
}
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions crates/tinycomputer-browser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
40 changes: 39 additions & 1 deletion crates/tinycomputer-browser/src/sessions/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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()
Expand All @@ -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,
Expand Down Expand Up @@ -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")
Expand All @@ -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()?
Expand Down
116 changes: 115 additions & 1 deletion crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<Vec<String>>);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading