1use 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
10pub const URL_NOT_IN_CONTEXT_CODE: &str = "browser.url_not_in_context";
12
13pub const DEFAULT_ALLOWED_SCHEMES: &[&str] = &["http", "https"];
19
20pub(crate) fn default_allowed_schemes() -> Vec<String> {
22 DEFAULT_ALLOWED_SCHEMES.iter().map(|scheme| (*scheme).to_string()).collect()
23}
24
25const PRIVATE_HOST_NAMES: &[&str] = &["localhost", "metadata.google.internal"];
28
29const RESOLVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
31
32#[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 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
53enum HostRefusal {
55 Private,
57 Unresolved(String),
59}
60
61impl UrlPolicy {
62 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 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 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 let refusal = match url::Url::parse(¤t) {
124 Ok(parsed) => match self.host_refusal(&parsed).await {
125 None => return Ok(current),
126 Some(refusal) => refusal_message(¤t, &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 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
179async 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
192pub struct NavigateTool {
204 browser: Arc<BrowserSession>,
205 policy: UrlPolicy,
206}
207
208impl NavigateTool {
209 pub fn new(browser: Arc<BrowserSession>) -> Self {
215 Self { browser, policy: UrlPolicy::default() }
216 }
217
218 #[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 #[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 #[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 #[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 self.browser.navigate(url).await?;
359 let current_url = self.policy.check_landing(&self.browser).await?;
360
361 let title = self.browser.title().await.unwrap_or_default();
363
364 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
382pub 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 #[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 #[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 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
458pub 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 #[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 #[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 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
534pub 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 #[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 #[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 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}