Skip to main content

adk_browser/tools/
navigate.rs

1//! Navigate tool for browser navigation.
2
3use crate::session::BrowserSession;
4use adk_core::egress::{ContextUrls, UrlSources, is_non_public};
5use adk_core::{Result, Tool, ToolContext};
6use async_trait::async_trait;
7use serde_json::{Value, json};
8use std::sync::Arc;
9
10/// Error code of a navigation refused because its URL did not appear in the conversation.
11pub const URL_NOT_IN_CONTEXT_CODE: &str = "browser.url_not_in_context";
12
13/// URL schemes the navigation tools accept unless configured otherwise.
14///
15/// `file:`, `javascript:`, `data:`, and browser-internal schemes such as `chrome:`
16/// are excluded: they read the host filesystem, run script, or reach browser
17/// settings rather than load a web page.
18pub const DEFAULT_ALLOWED_SCHEMES: &[&str] = &["http", "https"];
19
20/// The default scheme allowlist as owned strings.
21pub(crate) fn default_allowed_schemes() -> Vec<String> {
22    DEFAULT_ALLOWED_SCHEMES.iter().map(|scheme| (*scheme).to_string()).collect()
23}
24
25/// Host names that reach the local machine or a cloud metadata service without resolving to a
26/// public address.
27const PRIVATE_HOST_NAMES: &[&str] = &["localhost", "metadata.google.internal"];
28
29/// How long a navigation waits for the preflight DNS lookup.
30const RESOLVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
31
32/// What a model-supplied URL may point at.
33#[derive(Debug, Clone)]
34pub(crate) struct UrlPolicy {
35    pub(crate) allowed_schemes: Vec<String>,
36    pub(crate) allow_private_network: bool,
37    pub(crate) allow_unresolved_hosts: bool,
38    /// With sources, a URL is opened only when it appeared in them (the exfiltration rule).
39    pub(crate) url_sources: Option<UrlSources>,
40}
41
42impl Default for UrlPolicy {
43    fn default() -> Self {
44        Self {
45            allowed_schemes: default_allowed_schemes(),
46            allow_private_network: false,
47            allow_unresolved_hosts: false,
48            url_sources: None,
49        }
50    }
51}
52
53/// Why a URL's host was refused.
54enum HostRefusal {
55    /// The host is, or resolves to, a non-public address.
56    Private,
57    /// The host name does not resolve on the agent host, so its address is unknown.
58    Unresolved(String),
59}
60
61impl UrlPolicy {
62    /// Refuses `url` when the exfiltration rule is on and the URL did not appear in the
63    /// conversation `ctx` belongs to, so a model cannot carry data out in a URL it composed.
64    ///
65    /// Runs before any lookup, since a composed host name carries data to the resolver.
66    pub(crate) fn check_in_context(&self, url: &str, ctx: &dyn ToolContext) -> Result<()> {
67        let Some(sources) = &self.url_sources else { return Ok(()) };
68        if ContextUrls::from_tool_context(ctx, sources).contains(url) {
69            return Ok(());
70        }
71        Err(adk_core::AdkError::new(
72            adk_core::ErrorComponent::Tool,
73            adk_core::ErrorCategory::Forbidden,
74            URL_NOT_IN_CONTEXT_CODE,
75            "The URL did not appear earlier in the conversation, so the browser does not open \
76             it: only a URL a user message or a tool result already holds is opened, exactly as \
77             written there (query string included). Open a URL exactly as it appeared, or ask \
78             the user for the URL.",
79        ))
80    }
81
82    /// Rejects a URL that does not parse, whose scheme is not allowed, or — unless private
83    /// network access is enabled — whose host is loopback, private, link-local, or a cloud
84    /// metadata endpoint.
85    ///
86    /// A host name is resolved and refused when any address it resolves to is non-public, or
87    /// when it does not resolve here at all, unless unresolved hosts are allowed: the browser
88    /// may resolve such a name to a private address through its own resolver or a proxy.
89    pub(crate) async fn check(&self, url: &str) -> Result<()> {
90        let parsed = url::Url::parse(url)
91            .map_err(|e| adk_core::AdkError::tool(format!("Invalid URL '{url}': {e}")))?;
92        let scheme = parsed.scheme();
93        if !self.allowed_schemes.iter().any(|candidate| candidate.eq_ignore_ascii_case(scheme)) {
94            return Err(adk_core::AdkError::tool(format!(
95                "URL scheme '{scheme}' is not allowed; allowed schemes: {}. Configure \
96                 BrowserToolset::with_allowed_schemes to permit others.",
97                self.allowed_schemes.join(", ")
98            )));
99        }
100        match self.host_refusal(&parsed).await {
101            None => Ok(()),
102            Some(refusal) => Err(adk_core::AdkError::tool(refusal_message(url, &refusal))),
103        }
104    }
105
106    /// Checks the page the browser ended on after a navigation, which differs from the
107    /// requested URL when the site redirected. A refused page is replaced with
108    /// `about:blank` before the error returns, so later tools cannot read it.
109    ///
110    /// Returns the page's URL when it is allowed. The browser has already sent the request
111    /// by the time this runs, so this keeps the response from the model; only network
112    /// isolation keeps the request from reaching the address.
113    ///
114    /// # Errors
115    ///
116    /// Returns an error when the current URL cannot be read or points at a refused address.
117    pub(crate) async fn check_landing(&self, browser: &BrowserSession) -> Result<String> {
118        let current = browser.current_url().await?;
119        if self.allow_private_network {
120            return Ok(current);
121        }
122        // Pages without a host, such as `about:blank` or a browser error page, reach nothing.
123        let refusal = match url::Url::parse(&current) {
124            Ok(parsed) => match self.host_refusal(&parsed).await {
125                None => return Ok(current),
126                Some(refusal) => refusal_message(&current, &refusal),
127            },
128            Err(e) => format!("The browser reported a URL that does not parse: {e}."),
129        };
130        let cleared = match browser.navigate("about:blank").await {
131            Ok(()) => "The page was replaced with about:blank.".to_string(),
132            Err(e) => format!("Replacing the page with about:blank failed: {e}"),
133        };
134        Err(adk_core::AdkError::tool(format!(
135            "The browser ended on '{current}' after the navigation. {refusal} {cleared}"
136        )))
137    }
138
139    /// Returns why `parsed`'s host is refused, if it is.
140    async fn host_refusal(&self, parsed: &url::Url) -> Option<HostRefusal> {
141        if self.allow_private_network {
142            return None;
143        }
144        let private = match parsed.host()? {
145            url::Host::Ipv4(ip) => is_non_public(ip.into()),
146            url::Host::Ipv6(ip) => is_non_public(ip.into()),
147            url::Host::Domain(domain) => {
148                let domain = domain.trim_end_matches('.').to_ascii_lowercase();
149                if PRIVATE_HOST_NAMES.contains(&domain.as_str()) || domain.ends_with(".localhost") {
150                    true
151                } else {
152                    match resolve(&domain, parsed.port_or_known_default()).await {
153                        Some(addresses) => addresses.iter().any(|address| is_non_public(*address)),
154                        None if self.allow_unresolved_hosts => false,
155                        None => return Some(HostRefusal::Unresolved(domain)),
156                    }
157                }
158            }
159        };
160        private.then_some(HostRefusal::Private)
161    }
162}
163
164fn refusal_message(url: &str, refusal: &HostRefusal) -> String {
165    match refusal {
166        HostRefusal::Private => format!(
167            "URL '{url}' points at a private network address (loopback, private, \
168             link-local, or cloud metadata) and is not allowed. Configure \
169             BrowserToolset::with_private_network_access to permit it."
170        ),
171        HostRefusal::Unresolved(host) => format!(
172            "URL '{url}' was refused: its host '{host}' does not resolve on the agent host, \
173             so it cannot be checked against the private network policy. Configure \
174             BrowserToolset::with_unresolved_hosts to let the browser resolve it."
175        ),
176    }
177}
178
179/// Resolves `domain` within [`RESOLVE_TIMEOUT`]. Returns `None` when the lookup fails, times
180/// out, or yields no address.
181async fn resolve(domain: &str, port: Option<u16>) -> Option<Vec<std::net::IpAddr>> {
182    let lookup = tokio::net::lookup_host((domain, port.unwrap_or(80)));
183    match tokio::time::timeout(RESOLVE_TIMEOUT, lookup).await {
184        Ok(Ok(addresses)) => {
185            let addresses: Vec<_> = addresses.map(|address| address.ip()).collect();
186            (!addresses.is_empty()).then_some(addresses)
187        }
188        Ok(Err(_)) | Err(_) => None,
189    }
190}
191
192/// Tool for navigating to URLs.
193///
194/// Only URLs whose scheme is in the allowlist are opened; the default is
195/// [`DEFAULT_ALLOWED_SCHEMES`] (`http` and `https`). URLs that point at loopback,
196/// private, link-local, or cloud metadata addresses are refused until
197/// [`with_private_network_access`](Self::with_private_network_access) permits them, and so
198/// are host names that do not resolve on the agent host until
199/// [`with_unresolved_hosts`](Self::with_unresolved_hosts) permits them.
200///
201/// The page the browser ends on is checked again, so a redirect to a refused address fails
202/// the call and the page is replaced with `about:blank`.
203pub struct NavigateTool {
204    browser: Arc<BrowserSession>,
205    policy: UrlPolicy,
206}
207
208impl NavigateTool {
209    /// Create a new navigate tool with a shared browser session.
210    ///
211    /// The tool accepts [`DEFAULT_ALLOWED_SCHEMES`] until
212    /// [`with_allowed_schemes`](Self::with_allowed_schemes) replaces them, and refuses
213    /// private network addresses.
214    pub fn new(browser: Arc<BrowserSession>) -> Self {
215        Self { browser, policy: UrlPolicy::default() }
216    }
217
218    /// Permit or refuse URLs that point at a private network address.
219    ///
220    /// Refused by default: a page the model opens on `localhost`, a private range, or
221    /// `169.254.169.254` reaches services the agent's operator never exposed, such as an
222    /// admin console or a cloud metadata endpoint holding credentials. Enable this only for
223    /// an agent meant to browse an internal network.
224    ///
225    /// # Example
226    ///
227    /// ```rust,ignore
228    /// use adk_browser::{BrowserSession, NavigateTool};
229    /// use std::sync::Arc;
230    ///
231    /// let browser = Arc::new(BrowserSession::with_defaults());
232    /// let tool = NavigateTool::new(browser).with_private_network_access(true);
233    /// ```
234    #[must_use]
235    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
236        self.policy.allow_private_network = enabled;
237        self
238    }
239
240    /// Permit or refuse URLs whose host name does not resolve on the agent host.
241    ///
242    /// Refused by default: the agent cannot tell whether such a name reaches a private
243    /// address, and the browser may resolve it differently, through its own resolver or a
244    /// proxy. Enable this when the browser runs behind a proxy or on a remote WebDriver host
245    /// whose network the agent host cannot see; redirects are still checked against the page
246    /// the browser ends on.
247    ///
248    /// # Example
249    ///
250    /// ```rust,ignore
251    /// use adk_browser::{BrowserSession, NavigateTool};
252    /// use std::sync::Arc;
253    ///
254    /// let browser = Arc::new(BrowserSession::with_defaults());
255    /// let tool = NavigateTool::new(browser).with_unresolved_hosts(true);
256    /// ```
257    #[must_use]
258    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
259        self.policy.allow_unresolved_hosts = enabled;
260        self
261    }
262
263    /// Replace the URL schemes this tool accepts.
264    ///
265    /// Schemes are compared case-insensitively. Allowing `file` exposes the host
266    /// filesystem to the model, and allowing `javascript` or `data` lets it run
267    /// script outside `browser_evaluate_js`.
268    ///
269    /// # Example
270    ///
271    /// ```rust,ignore
272    /// use adk_browser::{BrowserSession, NavigateTool};
273    /// use std::sync::Arc;
274    ///
275    /// let browser = Arc::new(BrowserSession::with_defaults());
276    /// let tool = NavigateTool::new(browser).with_allowed_schemes(["https"]);
277    /// ```
278    #[must_use]
279    pub fn with_allowed_schemes<I, S>(mut self, schemes: I) -> Self
280    where
281        I: IntoIterator<Item = S>,
282        S: Into<String>,
283    {
284        self.policy.allowed_schemes = schemes.into_iter().map(Into::into).collect();
285        self
286    }
287
288    /// Opens only a URL that already appeared in the conversation's `sources`: a user
289    /// message or a tool result, exactly as written there. Off by default.
290    ///
291    /// A model that has read untrusted text can be told to put data it holds into a URL and
292    /// open it; under this rule a URL found only in what the model wrote is refused with
293    /// [`URL_NOT_IN_CONTEXT_CODE`] before the browser moves or any name is resolved. See
294    /// [`ContextUrls`] for the sources and the matching rule.
295    ///
296    /// # Example
297    ///
298    /// ```rust,ignore
299    /// use adk_browser::{BrowserSession, NavigateTool};
300    /// use adk_core::egress::UrlSources;
301    /// use std::sync::Arc;
302    ///
303    /// let browser = Arc::new(BrowserSession::with_defaults());
304    /// let tool = NavigateTool::new(browser).with_url_provenance(Some(UrlSources::default()));
305    /// ```
306    #[must_use]
307    pub fn with_url_provenance(mut self, sources: Option<UrlSources>) -> Self {
308        self.policy.url_sources = sources;
309        self
310    }
311}
312
313#[async_trait]
314impl Tool for NavigateTool {
315    fn name(&self) -> &str {
316        "browser_navigate"
317    }
318
319    fn description(&self) -> &str {
320        "Navigate the browser to a specified URL. Use this to open web pages \
321         (http and https URLs by default)."
322    }
323
324    fn parameters_schema(&self) -> Option<Value> {
325        Some(json!({
326            "type": "object",
327            "properties": {
328                "url": {
329                    "type": "string",
330                    "description": "The URL to navigate to (e.g., 'https://example.com')"
331                }
332            },
333            "required": ["url"]
334        }))
335    }
336
337    fn response_schema(&self) -> Option<Value> {
338        Some(json!({
339            "type": "object",
340            "properties": {
341                "success": { "type": "boolean" },
342                "url": { "type": "string" },
343                "title": { "type": "string" }
344            }
345        }))
346    }
347
348    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
349        let url = args
350            .get("url")
351            .and_then(|v| v.as_str())
352            .ok_or_else(|| adk_core::AdkError::tool("Missing 'url' parameter"))?;
353
354        self.policy.check_in_context(url, ctx.as_ref())?;
355        self.policy.check(url).await?;
356
357        // Navigate
358        self.browser.navigate(url).await?;
359        let current_url = self.policy.check_landing(&self.browser).await?;
360
361        // Get result info
362        let title = self.browser.title().await.unwrap_or_default();
363
364        // Include page context like interaction tools do
365        match self.browser.page_context().await {
366            Ok(page) => Ok(json!({
367                "success": true,
368                "url": current_url,
369                "title": title,
370                "page": page
371            })),
372            Err(e) => Ok(json!({
373                "success": true,
374                "url": current_url,
375                "title": title,
376                "page_context_error": e.to_string()
377            })),
378        }
379    }
380}
381
382/// Tool for going back in browser history.
383///
384/// The page the browser lands on is checked like a navigation: one that points at a
385/// private network address fails the call and is replaced with `about:blank`, unless
386/// [`with_private_network_access`](Self::with_private_network_access) permits it.
387pub struct BackTool {
388    browser: Arc<BrowserSession>,
389    policy: UrlPolicy,
390}
391
392impl BackTool {
393    pub fn new(browser: Arc<BrowserSession>) -> Self {
394        Self { browser, policy: UrlPolicy::default() }
395    }
396
397    /// Permit or refuse landing on a private network address. Refused by default.
398    ///
399    /// See [`NavigateTool::with_private_network_access`].
400    #[must_use]
401    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
402        self.policy.allow_private_network = enabled;
403        self
404    }
405
406    /// Permit or refuse landing on a host name that does not resolve on the agent host.
407    /// Refused by default.
408    ///
409    /// See [`NavigateTool::with_unresolved_hosts`].
410    #[must_use]
411    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
412        self.policy.allow_unresolved_hosts = enabled;
413        self
414    }
415}
416
417#[async_trait]
418impl Tool for BackTool {
419    fn name(&self) -> &str {
420        "browser_back"
421    }
422
423    fn description(&self) -> &str {
424        "Go back to the previous page in browser history."
425    }
426
427    fn parameters_schema(&self) -> Option<Value> {
428        Some(json!({
429            "type": "object",
430            "properties": {}
431        }))
432    }
433
434    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
435        self.browser.back().await?;
436
437        let url = self.policy.check_landing(&self.browser).await?;
438        let title = self.browser.title().await.unwrap_or_default();
439
440        // Include page context like interaction tools do
441        match self.browser.page_context().await {
442            Ok(page) => Ok(json!({
443                "success": true,
444                "url": url,
445                "title": title,
446                "page": page
447            })),
448            Err(e) => Ok(json!({
449                "success": true,
450                "url": url,
451                "title": title,
452                "page_context_error": e.to_string()
453            })),
454        }
455    }
456}
457
458/// Tool for going forward in browser history.
459///
460/// The page the browser lands on is checked like a navigation: one that points at a
461/// private network address fails the call and is replaced with `about:blank`, unless
462/// [`with_private_network_access`](Self::with_private_network_access) permits it.
463pub struct ForwardTool {
464    browser: Arc<BrowserSession>,
465    policy: UrlPolicy,
466}
467
468impl ForwardTool {
469    pub fn new(browser: Arc<BrowserSession>) -> Self {
470        Self { browser, policy: UrlPolicy::default() }
471    }
472
473    /// Permit or refuse landing on a private network address. Refused by default.
474    ///
475    /// See [`NavigateTool::with_private_network_access`].
476    #[must_use]
477    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
478        self.policy.allow_private_network = enabled;
479        self
480    }
481
482    /// Permit or refuse landing on a host name that does not resolve on the agent host.
483    /// Refused by default.
484    ///
485    /// See [`NavigateTool::with_unresolved_hosts`].
486    #[must_use]
487    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
488        self.policy.allow_unresolved_hosts = enabled;
489        self
490    }
491}
492
493#[async_trait]
494impl Tool for ForwardTool {
495    fn name(&self) -> &str {
496        "browser_forward"
497    }
498
499    fn description(&self) -> &str {
500        "Go forward to the next page in browser history."
501    }
502
503    fn parameters_schema(&self) -> Option<Value> {
504        Some(json!({
505            "type": "object",
506            "properties": {}
507        }))
508    }
509
510    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
511        self.browser.forward().await?;
512
513        let url = self.policy.check_landing(&self.browser).await?;
514        let title = self.browser.title().await.unwrap_or_default();
515
516        // Include page context like interaction tools do
517        match self.browser.page_context().await {
518            Ok(page) => Ok(json!({
519                "success": true,
520                "url": url,
521                "title": title,
522                "page": page
523            })),
524            Err(e) => Ok(json!({
525                "success": true,
526                "url": url,
527                "title": title,
528                "page_context_error": e.to_string()
529            })),
530        }
531    }
532}
533
534/// Tool for refreshing the current page.
535///
536/// The page the browser lands on is checked like a navigation: one that points at a
537/// private network address fails the call and is replaced with `about:blank`, unless
538/// [`with_private_network_access`](Self::with_private_network_access) permits it.
539pub struct RefreshTool {
540    browser: Arc<BrowserSession>,
541    policy: UrlPolicy,
542}
543
544impl RefreshTool {
545    pub fn new(browser: Arc<BrowserSession>) -> Self {
546        Self { browser, policy: UrlPolicy::default() }
547    }
548
549    /// Permit or refuse landing on a private network address. Refused by default.
550    ///
551    /// See [`NavigateTool::with_private_network_access`].
552    #[must_use]
553    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
554        self.policy.allow_private_network = enabled;
555        self
556    }
557
558    /// Permit or refuse landing on a host name that does not resolve on the agent host.
559    /// Refused by default.
560    ///
561    /// See [`NavigateTool::with_unresolved_hosts`].
562    #[must_use]
563    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
564        self.policy.allow_unresolved_hosts = enabled;
565        self
566    }
567}
568
569#[async_trait]
570impl Tool for RefreshTool {
571    fn name(&self) -> &str {
572        "browser_refresh"
573    }
574
575    fn description(&self) -> &str {
576        "Refresh the current page."
577    }
578
579    fn parameters_schema(&self) -> Option<Value> {
580        Some(json!({
581            "type": "object",
582            "properties": {}
583        }))
584    }
585
586    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
587        self.browser.refresh().await?;
588
589        let url = self.policy.check_landing(&self.browser).await?;
590        let title = self.browser.title().await.unwrap_or_default();
591
592        // Include page context like interaction tools do
593        match self.browser.page_context().await {
594            Ok(page) => Ok(json!({
595                "success": true,
596                "url": url,
597                "title": title,
598                "page": page
599            })),
600            Err(e) => Ok(json!({
601                "success": true,
602                "url": url,
603                "title": title,
604                "page_context_error": e.to_string()
605            })),
606        }
607    }
608}