Skip to main content

adk_harness/web/
mod.rs

1//! External content under governance (spec 3.1 §7.20).
2//!
3//! `web_fetch` and `web_search` are governed tools of class `Web { allowlisted }`: the
4//! policy decides them by the URL's host against [`WebConfig::allowed_domains`], and
5//! everything they return reaches the model only inside a delimited untrusted block,
6//! size-capped, with injection matches labelled and secret patterns redacted
7//! (spec 3.1 §9.2 I46–I49). The fetch allowlist is never a search filter: what a search
8//! covers is [`WebConfig::search_domains`] (spec 3.1 §7.32, I73).
9//!
10//! The configuration types compile in every build; the tools, the fetch client, the
11//! HTML-to-text pass and the screening need feature `web`.
12
13use std::fmt;
14#[cfg(feature = "web")]
15use std::sync::Arc;
16use std::time::Duration;
17
18pub use adk_core::egress::{ToolResultSources, UrlSources};
19use adk_core::{Result, async_trait};
20use serde::{Deserialize, Serialize};
21
22use crate::mode::HarnessMode;
23
24pub mod domain;
25pub use domain::fixture;
26#[cfg(feature = "web")]
27mod fetch;
28#[cfg(feature = "web")]
29mod html;
30#[cfg(feature = "web")]
31pub(crate) mod provider;
32#[cfg(feature = "web")]
33mod screen;
34#[cfg(feature = "web")]
35mod search;
36
37pub use domain::{
38    ParsedUrl, UrlRefusal, domain_matches, host_allowlisted, is_private_host, url_allowlisted,
39    url_host, url_names_private_target,
40};
41#[cfg(feature = "web")]
42pub use fetch::{
43    DELIVERED_TEXT_MAX, FetchBody, FetchRefusal, Fetched, Fetcher, NON_PATH_BUDGET, RequestSigner,
44    TRUNCATION_MARKER, hex_sha256,
45};
46#[cfg(feature = "web")]
47pub use html::{TextShape, decode_entities, html_to_text, html_to_text_at};
48#[cfg(feature = "web")]
49pub use screen::{
50    INJECTION_LABEL, INJECTION_PHRASES, NOT_SCREENED, SECRET_REDACTION, Screened, has_secret,
51    redact_secrets, screen, screening_label,
52};
53#[cfg(feature = "web")]
54pub use search::{DeepSeekSearch, SearxngSearch};
55
56/// Configuration of the web tools (spec 3.1 §7.20, §7.32).
57///
58/// | Setting | Meaning |
59/// |---|---|
60/// | `allowed_domains` | hosts `web_fetch` and the browser pack's navigation reach without approval; never forwarded to a search |
61/// | `fetch_domains` | the fetch filter: the only hosts, or the hosts never, `web_fetch` and navigation reach, redirect hops included; no approval widens it |
62/// | `url_provenance` | when a fetched URL must already appear in the conversation, so a model cannot carry data out in a URL it composed |
63/// | `url_sources` | which parts of the conversation count for `url_provenance` |
64/// | `search_domains` | the search filter: forwarded to the provider's search where it takes one, applied to the governed `web_search`'s results; `None` searches every domain |
65///
66/// # Example
67///
68/// ```rust
69/// use adk_harness::web::{SearchDomains, UrlProvenance, WebConfig};
70///
71/// let config = WebConfig {
72///     allowed_domains: vec!["docs.rs".into()],
73///     fetch_domains: Some(SearchDomains::Blocked(vec!["pastebin.com".into()])),
74///     search_domains: Some(SearchDomains::Allowed(vec!["docs.rs".into(), "rust-lang.org".into()])),
75///     ..WebConfig::default()
76/// };
77/// assert_eq!(config.url_provenance, UrlProvenance::Unattended);
78/// assert_eq!(config.max_bytes, 1024 * 1024);
79/// assert_eq!(config.max_url_len, 2048);
80/// assert_eq!(config.max_query_len, 512);
81/// assert_eq!(config.timeout.as_secs(), 20);
82/// assert_eq!(config.max_redirects, 5);
83/// assert_eq!(config.max_fetches_per_turn, 20);
84/// ```
85#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase", default)]
87pub struct WebConfig {
88    /// Hosts `web_fetch` and the browser pack reach without approval: exact hosts or
89    /// `*.example.com`, the `DomainIn` grammar. Never forwarded to a search (I73).
90    pub allowed_domains: Vec<String>,
91    /// The fetch filter: `web_fetch` and the browser pack's navigation reach only the
92    /// allowed domains, or never the blocked ones, each covering its subdomains. It applies
93    /// to the URL and every redirect hop, and no approval or standing rule widens it: the
94    /// policy denies a call outside it before anyone is asked. `None` filters nothing.
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub fetch_domains: Option<SearchDomains>,
97    /// When `web_fetch` and the browser pack's navigation fetch only URLs that already
98    /// appeared in the conversation ([`UrlProvenance`]).
99    pub url_provenance: UrlProvenance,
100    /// The parts of the conversation a URL may come from under `url_provenance`: user
101    /// messages and every tool result except the shell's, by default, since a shell prints
102    /// whatever URL a command builds.
103    pub url_sources: UrlSources,
104    /// The search filter (spec 3.1 §7.32): forwarded where the provider's search takes one
105    /// (Anthropic both lists, OpenAI an allowed list), applied to the governed
106    /// `web_search`'s results, and named in the banner where the provider takes none
107    /// (Gemini, DeepSeek). `None` searches every domain.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub search_domains: Option<SearchDomains>,
110    /// Bytes read on the wire per fetch; 64 KiB of text are delivered, the rest cut with
111    /// a marker.
112    pub max_bytes: usize,
113    /// Longest URL the tool sends.
114    pub max_url_len: usize,
115    /// Longest search query the tool runs.
116    pub max_query_len: usize,
117    /// Per-request timeout.
118    #[serde(with = "duration_secs")]
119    pub timeout: Duration,
120    /// Redirects followed within one call.
121    pub max_redirects: u8,
122    /// Fetches per turn; the turn's further fetches are refused.
123    pub max_fetches_per_turn: u32,
124    /// The `User-Agent` header.
125    pub user_agent: String,
126}
127
128impl Default for WebConfig {
129    fn default() -> Self {
130        Self {
131            allowed_domains: Vec::new(),
132            fetch_domains: None,
133            url_provenance: UrlProvenance::default(),
134            url_sources: UrlSources::default().except_tools(SHELL_TOOLS),
135            search_domains: None,
136            max_bytes: 1024 * 1024,
137            max_url_len: 2048,
138            max_query_len: 512,
139            timeout: Duration::from_secs(20),
140            max_redirects: 5,
141            max_fetches_per_turn: 20,
142            user_agent: format!(
143                "adk-harness/{} (+https://github.com/zavora-ai/adk-rust)",
144                env!("CARGO_PKG_VERSION")
145            ),
146        }
147    }
148}
149
150/// The harness's shell tools, whose results are not URL sources by default: a shell prints
151/// whatever URL the command it ran built.
152pub const SHELL_TOOLS: [&str; 2] = ["bash", "shell_output"];
153
154/// When the web tools fetch only URLs that already appeared in the conversation
155/// (the exfiltration rule).
156///
157/// A model that read untrusted text can be told to put data it holds into a URL and fetch
158/// it. Under the rule, `web_fetch` and the browser pack's navigation take a URL only when it
159/// appeared, exactly, in a user message or a tool result ([`WebConfig::url_sources`]);
160/// a URL found only in what the model wrote is refused with
161/// `harness.web.url_not_in_context`, before any DNS lookup. A redirect the server sends is
162/// not the model's choice, so it is checked against the fetch filter and the egress policy,
163/// not the rule; a redirect to another host comes back as `redirect_to`, a tool result, so
164/// the next call may fetch it.
165///
166/// | Value | The rule applies |
167/// |---|---|
168/// | `Off` | never |
169/// | `Unattended` (default) | in Auto mode, where no person sees a call before it runs: edits run unasked, a held web call may be answered by the auto reviewer (a model), and kernel partitions and goals run unwatched |
170/// | `Always` | in every mode, as Anthropic's server-side `web_fetch` applies it |
171///
172/// In Ask, Plan and Read-only modes every fetch outside `allowed_domains` waits for a person
173/// who sees the URL, so `Unattended` leaves those modes as they were; an allowlisted host
174/// still receives a composed URL there without asking, which `Always` closes.
175///
176/// # Example
177///
178/// ```rust
179/// use adk_harness::HarnessMode;
180/// use adk_harness::web::UrlProvenance;
181///
182/// assert!(UrlProvenance::default().applies(HarnessMode::Auto));
183/// assert!(!UrlProvenance::default().applies(HarnessMode::Ask));
184/// assert!(UrlProvenance::Always.applies(HarnessMode::ReadOnly));
185/// assert!(!UrlProvenance::Off.applies(HarnessMode::Auto));
186/// ```
187#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
188#[serde(rename_all = "camelCase")]
189#[non_exhaustive]
190pub enum UrlProvenance {
191    /// Never: any URL the policy admits is fetched.
192    Off,
193    /// In Auto mode.
194    #[default]
195    Unattended,
196    /// In every mode.
197    Always,
198}
199
200impl UrlProvenance {
201    /// Whether the rule applies to a call made in `mode`.
202    pub fn applies(self, mode: HarnessMode) -> bool {
203        match self {
204            Self::Off => false,
205            Self::Unattended => mode == HarnessMode::Auto,
206            Self::Always => true,
207        }
208    }
209}
210
211/// What a web search may return, by domain (spec 3.1 §7.32), and as
212/// [`WebConfig::fetch_domains`] what a fetch may reach: a filter separate from the fetch
213/// allowlist.
214///
215/// Each entry is a domain such as `docs.rs`; it covers the domain and its subdomains, as
216/// Anthropic's and OpenAI's search filters read it, and a leading `*.` is dropped. A
217/// workspace file may only [`narrow`](Self::narrow) the filter the operator or user set.
218///
219/// # Example
220///
221/// ```rust
222/// use adk_harness::web::SearchDomains;
223///
224/// let only = SearchDomains::Allowed(vec!["rust-lang.org".into()]);
225/// assert!(only.permits("doc.rust-lang.org"));
226/// assert!(!only.permits("evil-rust-lang.org"));
227/// assert_eq!(only.to_string(), "only rust-lang.org");
228///
229/// let blocked = SearchDomains::Blocked(vec!["pinterest.com".into()]);
230/// assert!(!blocked.permits("www.pinterest.com"));
231/// assert_eq!(blocked.to_string(), "every domain except pinterest.com");
232/// ```
233#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
234#[serde(rename_all = "camelCase")]
235pub enum SearchDomains {
236    /// Only these domains and their subdomains.
237    Allowed(Vec<String>),
238    /// Every domain but these and their subdomains.
239    Blocked(Vec<String>),
240}
241
242/// `domain` lowercased, without a leading `*.` or a trailing dot.
243fn search_domain(domain: &str) -> String {
244    let domain = domain.trim().to_ascii_lowercase();
245    let domain = domain.strip_prefix("*.").unwrap_or(&domain);
246    domain.strip_suffix('.').unwrap_or(domain).to_string()
247}
248
249/// Whether `host` is `domain` or one of its subdomains.
250fn covered(host: &str, domain: &str) -> bool {
251    let (host, domain) = (search_domain(host), search_domain(domain));
252    !domain.is_empty()
253        && (host == domain || host.strip_suffix(&domain).is_some_and(|sub| sub.ends_with('.')))
254}
255
256impl SearchDomains {
257    /// The domains the filter lists.
258    pub fn domains(&self) -> &[String] {
259        match self {
260            Self::Allowed(domains) | Self::Blocked(domains) => domains,
261        }
262    }
263
264    /// Whether a result from `host` passes the filter.
265    pub fn permits(&self, host: &str) -> bool {
266        match self {
267            Self::Allowed(domains) => domains.iter().any(|domain| covered(host, domain)),
268            Self::Blocked(domains) => !domains.iter().any(|domain| covered(host, domain)),
269        }
270    }
271
272    /// Whether the filter lets no domain through: an empty allowed list.
273    pub fn permits_none(&self) -> bool {
274        matches!(self, Self::Allowed(domains) if domains.is_empty())
275    }
276
277    /// The filter `ceiling` (the operator's or user's, `None` for every domain) narrowed by
278    /// `workspace`, a workspace file's filter, which may only narrow it (spec 3.1 §7.32,
279    /// I3).
280    ///
281    /// | Ceiling | Workspace | Result |
282    /// |---|---|---|
283    /// | none | any | the workspace's |
284    /// | allowed `a` | allowed `b` | allowed: the entries of each the other covers |
285    /// | allowed `a` | blocked `b` | allowed: `a` without the entries that overlap `b` |
286    /// | blocked `a` | allowed `b` | allowed: `b` without the entries that overlap `a` |
287    /// | blocked `a` | blocked `b` | blocked: both |
288    ///
289    /// # Example
290    ///
291    /// ```rust
292    /// use adk_harness::web::SearchDomains;
293    ///
294    /// let user = SearchDomains::Allowed(vec!["rust-lang.org".into(), "docs.rs".into()]);
295    /// let workspace = SearchDomains::Allowed(vec!["doc.rust-lang.org".into(), "evil.example".into()]);
296    /// assert_eq!(
297    ///     SearchDomains::narrow(Some(&user), &workspace),
298    ///     SearchDomains::Allowed(vec!["doc.rust-lang.org".into()])
299    /// );
300    /// ```
301    pub fn narrow(ceiling: Option<&Self>, workspace: &Self) -> Self {
302        let overlaps = |a: &str, b: &str| covered(a, b) || covered(b, a);
303        let unique = |domains: Vec<String>| {
304            let mut out: Vec<String> = Vec::new();
305            for domain in domains {
306                if !out.contains(&domain) {
307                    out.push(domain);
308                }
309            }
310            out
311        };
312        match (ceiling, workspace) {
313            (None, workspace) => workspace.clone(),
314            (Some(Self::Allowed(a)), Self::Allowed(b)) => {
315                let within = |x: &String, of: &[String]| of.iter().any(|y| covered(x, y));
316                let both =
317                    b.iter().filter(|x| within(x, a)).chain(a.iter().filter(|x| within(x, b)));
318                Self::Allowed(unique(both.cloned().collect()))
319            }
320            (Some(Self::Allowed(allowed)), Self::Blocked(blocked))
321            | (Some(Self::Blocked(blocked)), Self::Allowed(allowed)) => Self::Allowed(unique(
322                allowed
323                    .iter()
324                    .filter(|x| !blocked.iter().any(|y| overlaps(x, y)))
325                    .cloned()
326                    .collect(),
327            )),
328            (Some(Self::Blocked(a)), Self::Blocked(b)) => {
329                Self::Blocked(unique(a.iter().chain(b).cloned().collect()))
330            }
331        }
332    }
333}
334
335impl fmt::Display for SearchDomains {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        match self {
338            Self::Allowed(domains) if domains.is_empty() => f.write_str("no domain"),
339            Self::Allowed(domains) => write!(f, "only {}", domains.join(", ")),
340            Self::Blocked(domains) if domains.is_empty() => f.write_str("every domain"),
341            Self::Blocked(domains) => write!(f, "every domain except {}", domains.join(", ")),
342        }
343    }
344}
345
346mod duration_secs {
347    use std::time::Duration;
348
349    use serde::{Deserialize, Deserializer, Serializer};
350
351    pub fn serialize<S: Serializer>(value: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
352        serializer.serialize_u64(value.as_secs())
353    }
354
355    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
356        u64::deserialize(deserializer).map(Duration::from_secs)
357    }
358}
359
360/// One result of a [`SearchProvider`] (spec 3.1 §7.20 `web_search`).
361#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
362#[serde(rename_all = "camelCase")]
363pub struct SearchHit {
364    /// The result's title.
365    pub title: String,
366    /// The result's URL.
367    pub url: String,
368    /// The result's snippet.
369    pub snippet: String,
370}
371
372/// The operator's search backend behind `web_search` (spec 3.1 §7.20).
373///
374/// The harness screens and delimits what a provider returns and fetches no page; a
375/// provider that reaches the network applies its own credentials, never the harness's.
376///
377/// # Example
378///
379/// ```rust
380/// use adk_harness::web::{SearchHit, SearchProvider};
381///
382/// #[derive(Debug)]
383/// struct Fixed;
384///
385/// #[async_trait::async_trait]
386/// impl SearchProvider for Fixed {
387///     fn name(&self) -> &str {
388///         "fixed"
389///     }
390///     async fn search(&self, query: &str, limit: usize, _site: Option<&str>) -> adk_core::Result<Vec<SearchHit>> {
391///         Ok(vec![SearchHit { title: query.into(), url: "https://docs.rs/".into(), snippet: String::new() }]
392///             .into_iter()
393///             .take(limit)
394///             .collect())
395///     }
396/// }
397/// ```
398#[async_trait]
399pub trait SearchProvider: fmt::Debug + Send + Sync {
400    /// The provider's name, recorded in `harness.web.searched`.
401    fn name(&self) -> &str;
402
403    /// Searches `query`, returning at most `limit` hits, restricted to `site` when given.
404    ///
405    /// # Errors
406    ///
407    /// Returns the provider's error; the tool reports it to the model.
408    async fn search(&self, query: &str, limit: usize, site: Option<&str>)
409    -> Result<Vec<SearchHit>>;
410}
411
412/// Which provider-executed search and URL tools the harness declares (spec 3.1 §7.20
413/// "Provider-native search and fetch").
414///
415/// The default, [`provider_default`](Self::provider_default), is the search built-in of the
416/// provider the harness model's client serves ([`adk_core::Llm::native_web_search`]):
417/// Gemini `google_search`, Anthropic `web_search`, OpenAI Responses `web_search` or
418/// DeepSeek Responses `web_search`. A configured
419/// [`SearchProvider`](crate::HarnessAgentBuilder::search_provider) replaces it with the
420/// governed `web_search`; [`off`](Self::off) declares none. The per-provider flags stay for
421/// explicit control and attach only for the provider the model's client serves.
422///
423/// # Example
424///
425/// ```rust
426/// use adk_harness::web::ProviderWebTools;
427///
428/// assert_eq!(ProviderWebTools::default(), ProviderWebTools::provider_default());
429/// assert!(ProviderWebTools::provider_default().native_search);
430/// assert!(!ProviderWebTools::off().any());
431/// let explicit = ProviderWebTools { gemini_url_context: true, ..ProviderWebTools::off() };
432/// assert!(explicit.any() && !explicit.native_search);
433/// ```
434#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
435#[serde(rename_all = "camelCase", default)]
436pub struct ProviderWebTools {
437    /// The search built-in of the provider the harness model's client serves, whichever
438    /// it is; replaced by a configured search provider.
439    pub native_search: bool,
440    /// Anthropic `web_search`, with the search filter forwarded.
441    pub anthropic_web_search: bool,
442    /// OpenAI `web_search`, with an allowed search filter forwarded.
443    pub openai_web_search: bool,
444    /// Gemini `google_search`; it takes no search filter, so every domain.
445    pub gemini_google_search: bool,
446    /// Gemini `url_context`; it reads the URLs the prompt names.
447    pub gemini_url_context: bool,
448}
449
450impl Default for ProviderWebTools {
451    fn default() -> Self {
452        Self::provider_default()
453    }
454}
455
456impl ProviderWebTools {
457    /// The model provider's own search and nothing else: what a harness with
458    /// [`web`](crate::HarnessAgentBuilder::web) declares unless told otherwise.
459    pub fn provider_default() -> Self {
460        Self { native_search: true, ..Self::off() }
461    }
462
463    /// No provider-executed tool: `web_search` exists only through a configured search
464    /// provider.
465    pub fn off() -> Self {
466        Self {
467            native_search: false,
468            anthropic_web_search: false,
469            openai_web_search: false,
470            gemini_google_search: false,
471            gemini_url_context: false,
472        }
473    }
474
475    /// Whether any provider tool is enabled.
476    pub fn any(&self) -> bool {
477        self.native_search
478            || self.anthropic_web_search
479            || self.openai_web_search
480            || self.gemini_google_search
481            || self.gemini_url_context
482    }
483}
484
485/// Which path `web_search` takes in a built harness (spec 3.1 §7.20), as
486/// [`HarnessInfo::web_search`](crate::HarnessInfo::web_search) reports it.
487///
488/// # Example
489///
490/// ```rust
491/// use adk_harness::web::WebSearchPath;
492///
493/// use adk_harness::web::SearchDomains;
494///
495/// let path = WebSearchPath::Provider {
496///     provider: "anthropic".into(),
497///     tool: "web_search".into(),
498///     filter: Some(SearchDomains::Allowed(vec!["docs.rs".into()])),
499///     filter_applied: true,
500/// };
501/// assert_eq!(path.to_string(), "anthropic web_search, run by the provider: only docs.rs");
502///
503/// let path = WebSearchPath::Provider {
504///     provider: "gemini".into(),
505///     tool: "google_search".into(),
506///     filter: Some(SearchDomains::Allowed(vec!["docs.rs".into()])),
507///     filter_applied: false,
508/// };
509/// assert_eq!(
510///     path.to_string(),
511///     "gemini google_search, run by the provider: every domain (gemini takes no search \
512///      filter; search_domains is not applied)"
513/// );
514/// ```
515#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
516#[serde(rename_all = "camelCase", tag = "path")]
517pub enum WebSearchPath {
518    /// The model provider's built-in search, declared to runs that start in Ask or Auto.
519    #[serde(rename_all = "camelCase")]
520    Provider {
521        /// The provider that runs the search.
522        provider: String,
523        /// The built-in tool declared.
524        tool: String,
525        /// The configured search filter ([`WebConfig::search_domains`]); never the fetch
526        /// allowlist.
527        filter: Option<SearchDomains>,
528        /// Whether the provider takes the filter, so it was forwarded.
529        filter_applied: bool,
530    },
531    /// The governed `web_search` over the operator's search provider.
532    Governed {
533        /// The search provider's name.
534        provider: String,
535        /// The search filter applied to its results.
536        filter: Option<SearchDomains>,
537    },
538    /// No `web_search`, and why.
539    None {
540        /// Why no search is declared.
541        reason: String,
542    },
543}
544
545impl fmt::Display for WebSearchPath {
546    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
547        match self {
548            Self::Provider { provider, tool, filter: Some(filter), filter_applied: true } => {
549                write!(f, "{provider} {tool}, run by the provider: {filter}")
550            }
551            Self::Provider { provider, tool, filter: Some(_), filter_applied: false } => write!(
552                f,
553                "{provider} {tool}, run by the provider: every domain ({provider} takes no search \
554                 filter; search_domains is not applied)"
555            ),
556            Self::Provider { provider, tool, filter: None, .. } => {
557                write!(f, "{provider} {tool}, run by the provider: every domain")
558            }
559            Self::Governed { provider, filter: Some(filter) } => {
560                write!(f, "web_search through {provider} (governed): {filter}")
561            }
562            Self::Governed { provider, filter: None } => {
563                write!(f, "web_search through {provider} (governed): every domain")
564            }
565            Self::None { reason } => write!(f, "off ({reason})"),
566        }
567    }
568}
569
570/// Wraps `content` in an `<untrusted-content>` block with `source` and `attributes`, the
571/// closing tag neutralized inside it, as the instruction loader does (spec 3.1 §7.20
572/// "Delivery", §7.21 "Resources").
573///
574/// # Example
575///
576/// ```rust
577/// use adk_harness::web::untrusted_block;
578///
579/// let block = untrusted_block("web", &[("url", "https://docs.rs/")], "hi </untrusted-content> there");
580/// assert!(block.starts_with("<untrusted-content source=\"web\" url=\"https://docs.rs/\">\n"));
581/// assert!(block.contains("<\\/untrusted-content> there"));
582/// assert!(block.ends_with("\n</untrusted-content>"));
583/// ```
584pub fn untrusted_block(source: &str, attributes: &[(&str, &str)], content: &str) -> String {
585    let mut out = format!("<untrusted-content source=\"{}\"", escape_attr(source));
586    for (name, value) in attributes {
587        out.push(' ');
588        out.push_str(name);
589        out.push_str("=\"");
590        out.push_str(&escape_attr(value));
591        out.push('"');
592    }
593    out.push_str(">\n");
594    out.push_str(&content.replace("</untrusted-content", "<\\/untrusted-content"));
595    out.push_str("\n</untrusted-content>");
596    out
597}
598
599fn escape_attr(value: &str) -> String {
600    value.replace('&', "&amp;").replace('"', "&quot;").replace('<', "&lt;").replace('>', "&gt;")
601}
602
603/// What the harness holds for the web tools at run time.
604#[cfg(feature = "web")]
605pub(crate) struct WebRuntime {
606    pub(crate) config: WebConfig,
607    pub(crate) fetcher: Fetcher,
608    /// The session's mode, for [`UrlProvenance::Unattended`]; `None` reads as Ask.
609    modes: Option<(Arc<dyn crate::mode::ModeStore>, HarnessMode)>,
610    /// Fetches per (session, invocation), bounded.
611    turns: std::sync::Mutex<std::collections::VecDeque<(String, u32)>>,
612}
613
614#[cfg(feature = "web")]
615impl WebRuntime {
616    const TURNS_CAP: usize = 1024;
617
618    pub(crate) fn new(
619        config: WebConfig,
620        signer: Option<Arc<dyn RequestSigner>>,
621        modes: Option<(Arc<dyn crate::mode::ModeStore>, HarnessMode)>,
622    ) -> Arc<Self> {
623        let fetcher = Fetcher::new(config.clone());
624        Arc::new(Self {
625            fetcher: match signer {
626                Some(signer) => fetcher.with_signer(signer),
627                None => fetcher,
628            },
629            config,
630            modes,
631            turns: std::sync::Mutex::new(std::collections::VecDeque::new()),
632        })
633    }
634
635    /// Whether [`WebConfig::url_provenance`] applies to this call: by the session's mode as
636    /// the policy reads it, and as Auto when the mode store cannot be read.
637    pub(crate) async fn provenance_applies(&self, ctx: &dyn adk_core::ToolContext) -> bool {
638        provenance_applies(self.config.url_provenance, self.modes.as_ref(), ctx).await
639    }
640
641    /// Counts one fetch of the turn; `Err(cap)` once the turn reached
642    /// `max_fetches_per_turn`.
643    pub(crate) fn count_fetch(
644        &self,
645        session_id: &str,
646        invocation_id: &str,
647    ) -> std::result::Result<u32, u32> {
648        let key = format!("{session_id}\u{1f}{invocation_id}");
649        let cap = self.config.max_fetches_per_turn;
650        let mut turns = self.turns.lock().unwrap_or_else(|e| e.into_inner());
651        if let Some((_, count)) = turns.iter_mut().find(|(k, _)| *k == key) {
652            if *count >= cap {
653                return Err(cap);
654            }
655            *count += 1;
656            return Ok(*count);
657        }
658        if cap == 0 {
659            return Err(cap);
660        }
661        while turns.len() >= Self::TURNS_CAP {
662            turns.pop_front();
663        }
664        turns.push_back((key, 1));
665        Ok(1)
666    }
667}
668
669/// Whether `provenance` applies to a call in `ctx`, the session's mode read from `modes`
670/// (`None` reads as Ask), and as Auto when the store cannot be read.
671#[cfg(feature = "web")]
672pub(crate) async fn provenance_applies(
673    provenance: UrlProvenance,
674    modes: Option<&(Arc<dyn crate::mode::ModeStore>, HarnessMode)>,
675    ctx: &dyn adk_core::ToolContext,
676) -> bool {
677    let mode = match modes {
678        _ if matches!(provenance, UrlProvenance::Off | UrlProvenance::Always) => HarnessMode::Ask,
679        None => HarnessMode::Ask,
680        Some((store, default_mode)) => {
681            match store.get(ctx.app_name(), ctx.user_id(), ctx.session_id()).await {
682                Ok(Some(record)) => record.mode_for_invocation(ctx.invocation_id()),
683                Ok(None) => *default_mode,
684                Err(error) => {
685                    tracing::warn!(error = %error, "mode store unavailable; applying the url rule");
686                    HarnessMode::Auto
687                }
688            }
689        }
690    };
691    provenance.applies(mode)
692}
693
694#[cfg(all(test, feature = "web"))]
695mod tests {
696    use super::*;
697
698    #[test]
699    fn fetches_are_counted_per_turn_and_capped() {
700        let runtime = WebRuntime::new(
701            WebConfig { max_fetches_per_turn: 2, ..WebConfig::default() },
702            None,
703            None,
704        );
705        assert_eq!(runtime.count_fetch("s1", "inv-1"), Ok(1));
706        assert_eq!(runtime.count_fetch("s1", "inv-1"), Ok(2));
707        assert_eq!(runtime.count_fetch("s1", "inv-1"), Err(2));
708        assert_eq!(runtime.count_fetch("s1", "inv-2"), Ok(1), "a new turn starts fresh");
709        assert_eq!(runtime.count_fetch("s2", "inv-1"), Ok(1), "another session is separate");
710    }
711
712    #[test]
713    fn search_domains_cover_subdomains_and_never_lookalikes() {
714        let only = SearchDomains::Allowed(vec!["*.Rust-Lang.org".into(), "docs.rs".into()]);
715        assert!(only.permits("rust-lang.org") && only.permits("doc.rust-lang.org"));
716        assert!(only.permits("docs.rs") && !only.permits("evil-docs.rs"));
717        assert!(!only.permits("example.com"));
718        let blocked = SearchDomains::Blocked(vec!["pinterest.com".into()]);
719        assert!(!blocked.permits("pinterest.com") && blocked.permits("example.com"));
720        assert!(SearchDomains::Allowed(vec![]).permits_none());
721        assert!(!SearchDomains::Blocked(vec![]).permits_none());
722    }
723
724    #[test]
725    fn a_workspace_filter_only_narrows_the_ceiling() {
726        let allowed =
727            |d: &[&str]| SearchDomains::Allowed(d.iter().map(|d| d.to_string()).collect());
728        let blocked =
729            |d: &[&str]| SearchDomains::Blocked(d.iter().map(|d| d.to_string()).collect());
730        // No ceiling: the workspace's filter.
731        assert_eq!(SearchDomains::narrow(None, &blocked(&["a.io"])), blocked(&["a.io"]));
732        // Allowed and allowed: what both cover.
733        assert_eq!(
734            SearchDomains::narrow(Some(&allowed(&["docs.rs"])), &allowed(&["evil.example"])),
735            allowed(&[])
736        );
737        assert_eq!(
738            SearchDomains::narrow(
739                Some(&allowed(&["doc.rust-lang.org"])),
740                &allowed(&["rust-lang.org"])
741            ),
742            allowed(&["doc.rust-lang.org"])
743        );
744        // Allowed and blocked: the allowed list without what the blocked list touches.
745        assert_eq!(
746            SearchDomains::narrow(
747                Some(&allowed(&["docs.rs", "rust-lang.org"])),
748                &blocked(&["blog.rust-lang.org"])
749            ),
750            allowed(&["docs.rs"])
751        );
752        assert_eq!(
753            SearchDomains::narrow(
754                Some(&blocked(&["pinterest.com"])),
755                &allowed(&["docs.rs", "pinterest.com"])
756            ),
757            allowed(&["docs.rs"])
758        );
759        // Blocked and blocked: both lists.
760        assert_eq!(
761            SearchDomains::narrow(Some(&blocked(&["a.io"])), &blocked(&["b.io", "a.io"])),
762            blocked(&["a.io", "b.io"])
763        );
764    }
765
766    #[test]
767    fn the_search_path_names_the_filter_never_the_fetch_allowlist() {
768        let path = |filter, filter_applied| WebSearchPath::Provider {
769            provider: "anthropic".into(),
770            tool: "web_search".into(),
771            filter,
772            filter_applied,
773        };
774        assert_eq!(
775            path(None, true).to_string(),
776            "anthropic web_search, run by the provider: every domain"
777        );
778        assert_eq!(
779            path(Some(SearchDomains::Blocked(vec!["pinterest.com".into()])), true).to_string(),
780            "anthropic web_search, run by the provider: every domain except pinterest.com"
781        );
782        let governed = WebSearchPath::Governed {
783            provider: "searxng".into(),
784            filter: Some(SearchDomains::Allowed(vec!["docs.rs".into()])),
785        };
786        assert_eq!(governed.to_string(), "web_search through searxng (governed): only docs.rs");
787    }
788
789    #[test]
790    fn config_round_trips_through_serde() {
791        let config = WebConfig {
792            allowed_domains: vec!["docs.rs".into()],
793            search_domains: Some(SearchDomains::Blocked(vec!["pinterest.com".into()])),
794            ..WebConfig::default()
795        };
796        let json = serde_json::to_value(&config).unwrap();
797        assert_eq!(json["allowedDomains"][0], "docs.rs");
798        assert_eq!(json["searchDomains"]["blocked"][0], "pinterest.com");
799        assert_eq!(json["timeout"], 20);
800        let back: WebConfig = serde_json::from_value(json).unwrap();
801        assert_eq!(back, config);
802    }
803}