| 1 | //! Unified guarded fetch pipeline for `fetch_url` and `web.run`. |
| 2 | |
| 3 | use std::collections::BTreeMap; |
| 4 | use std::sync::Arc; |
| 5 | use std::time::{Duration, Instant}; |
| 6 | #[cfg(not(any(test, feature = "test-support")))] |
| 7 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 8 | |
| 9 | use futures_util::StreamExt; |
| 10 | use serde::Serialize; |
| 11 | |
| 12 | use super::adapter::AdapterResult; |
| 13 | use super::cache::{self, CachedFetch}; |
| 14 | use super::extract::is_js_shell_error; |
| 15 | use super::guard::{validate_fetch_target, validate_network_policy}; |
| 16 | use crate::tools::spec::{ToolContext, ToolError}; |
| 17 | use codewhale_agent_contract::worker_profile::ShellPolicy; |
| 18 | use codewhale_net::guard::{DnsPin, PrivateTargets, guarded_reqwest_client_builder}; |
| 19 | use codewhale_runtime::features::Feature; |
| 20 | |
| 21 | pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(15); |
| 22 | pub const HARD_MAX_TIMEOUT: Duration = Duration::from_secs(60); |
| 23 | pub const DEFAULT_MAX_BYTES: usize = 1_000_000; |
| 24 | pub const HARD_MAX_BYTES: usize = 10 * 1024 * 1024; |
| 25 | const MAX_REDIRECTS: usize = 5; |
| 26 | const USER_AGENT: &str = concat!( |
| 27 | "Mozilla/5.0 (compatible; codewhale/", |
| 28 | env!("CARGO_PKG_VERSION"), |
| 29 | "; +https://github.com/codewhale-hq/CodeWhale)" |
| 30 | ); |
| 31 | |
| 32 | #[derive(Debug, Clone)] |
| 33 | pub struct FetchOptions { |
| 34 | pub timeout: Duration, |
| 35 | pub max_bytes: usize, |
| 36 | pub accept: &'static str, |
| 37 | pub user_agent: &'static str, |
| 38 | method: reqwest::Method, |
| 39 | range: Option<&'static str>, |
| 40 | } |
| 41 | |
| 42 | impl FetchOptions { |
| 43 | pub fn new(timeout: Duration, max_bytes: usize, accept: &'static str) -> Self { |
| 44 | Self { |
| 45 | timeout: timeout.min(HARD_MAX_TIMEOUT), |
| 46 | max_bytes: max_bytes.clamp(1, HARD_MAX_BYTES), |
| 47 | accept, |
| 48 | user_agent: USER_AGENT, |
| 49 | method: reqwest::Method::GET, |
| 50 | range: None, |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /// Request with the shared browser user-agent instead of the Codewhale |
| 55 | /// one. [`fetch_readable`] uses this only as the one-shot fallback after |
| 56 | /// a site refused the default agent with 401/403. |
| 57 | #[must_use] |
| 58 | pub fn with_browser_user_agent(mut self) -> Self { |
| 59 | self.user_agent = super::scrape::BROWSER_USER_AGENT; |
| 60 | self |
| 61 | } |
| 62 | |
| 63 | fn uses_browser_user_agent(&self) -> bool { |
| 64 | self.user_agent == super::scrape::BROWSER_USER_AGENT |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | #[derive(Debug, Clone)] |
| 69 | pub struct FetchedPayload { |
| 70 | pub url: String, |
| 71 | pub status: u16, |
| 72 | pub headers: BTreeMap<String, String>, |
| 73 | pub content_type: String, |
| 74 | pub bytes: Arc<Vec<u8>>, |
| 75 | pub truncated: bool, |
| 76 | pub cache_hit: bool, |
| 77 | pub retries: usize, |
| 78 | pub redirects: usize, |
| 79 | } |
| 80 | |
| 81 | /// Whether one request may be answered from a cache, or must revalidate. |
| 82 | /// |
| 83 | /// `Revalidate` bypasses the session fetch cache *and* asks every intermediary |
| 84 | /// to revalidate. An edge cache can hold a prerendered variant while an origin |
| 85 | /// MISS serves the client-side shell, so the same URL alternates between |
| 86 | /// readable and unreadable depending on which variant answered (#5904). |
| 87 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 88 | enum CacheMode { |
| 89 | Default, |
| 90 | Revalidate, |
| 91 | } |
| 92 | |
| 93 | impl CacheMode { |
| 94 | const fn is_revalidate(self) -> bool { |
| 95 | matches!(self, Self::Revalidate) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | /// Response headers that explain the cache state behind a 200. |
| 100 | /// |
| 101 | /// These are the four that distinguish "the edge served a prerendered page" |
| 102 | /// from "the origin served the JavaScript shell", so both the success and the |
| 103 | /// failure receipt carry whichever of them the response actually had. |
| 104 | const CACHE_STATE_HEADERS: [&str; 4] = [ |
| 105 | "age", |
| 106 | "cf-cache-status", |
| 107 | "x-nextjs-prerender", |
| 108 | "x-vercel-cache", |
| 109 | ]; |
| 110 | |
| 111 | /// One request inside a readable-fetch sequence, as it appears on the receipt. |
| 112 | #[derive(Debug, Clone, Serialize)] |
| 113 | pub struct FetchAttempt { |
| 114 | /// 1-based position in the sequence. |
| 115 | pub attempt: usize, |
| 116 | pub status: u16, |
| 117 | /// Whether the session fetch cache answered this attempt. |
| 118 | pub cache_hit: bool, |
| 119 | /// Whether this attempt sent `Cache-Control: no-cache` / `Pragma: no-cache` |
| 120 | /// and skipped the session cache. |
| 121 | pub cache_busted: bool, |
| 122 | /// Whether this attempt is the one that yielded a readable document. |
| 123 | pub produced_content: bool, |
| 124 | /// Whether this attempt used the browser user-agent after the default |
| 125 | /// agent was refused with 401/403. |
| 126 | #[serde(skip_serializing_if = "std::ops::Not::not")] |
| 127 | pub browser_user_agent: bool, |
| 128 | /// `age`, `cf-cache-status`, `x-nextjs-prerender`, `x-vercel-cache` — only |
| 129 | /// those the response actually carried. |
| 130 | #[serde(skip_serializing_if = "BTreeMap::is_empty")] |
| 131 | pub cache_headers: BTreeMap<String, String>, |
| 132 | } |
| 133 | |
| 134 | impl FetchAttempt { |
| 135 | fn record( |
| 136 | payload: &FetchedPayload, |
| 137 | attempt: usize, |
| 138 | mode: CacheMode, |
| 139 | browser_user_agent: bool, |
| 140 | ) -> Self { |
| 141 | Self { |
| 142 | attempt, |
| 143 | status: payload.status, |
| 144 | cache_hit: payload.cache_hit, |
| 145 | cache_busted: mode.is_revalidate(), |
| 146 | produced_content: false, |
| 147 | browser_user_agent, |
| 148 | cache_headers: cache_state_headers(&payload.headers), |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | fn summarize(&self) -> String { |
| 153 | let mut facts = vec![format!("HTTP {}", self.status)]; |
| 154 | if self.cache_hit { |
| 155 | facts.push("session cache hit".to_string()); |
| 156 | } |
| 157 | if self.browser_user_agent { |
| 158 | facts.push("browser user-agent".to_string()); |
| 159 | } |
| 160 | for (name, value) in &self.cache_headers { |
| 161 | facts.push(format!("{name}={value}")); |
| 162 | } |
| 163 | let label = if self.cache_busted { |
| 164 | format!("attempt {} (Cache-Control: no-cache)", self.attempt) |
| 165 | } else { |
| 166 | format!("attempt {}", self.attempt) |
| 167 | }; |
| 168 | format!("{label}: {}", facts.join(", ")) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | fn cache_state_headers(headers: &BTreeMap<String, String>) -> BTreeMap<String, String> { |
| 173 | CACHE_STATE_HEADERS |
| 174 | .iter() |
| 175 | .filter_map(|name| { |
| 176 | headers |
| 177 | .get(*name) |
| 178 | .map(|value| ((*name).to_string(), value.clone())) |
| 179 | }) |
| 180 | .collect() |
| 181 | } |
| 182 | |
| 183 | /// The extraction step [`fetch_readable`] may run against either attempt. |
| 184 | /// |
| 185 | /// Spelled as an explicit boxed future over an *owned* payload rather than as |
| 186 | /// an `AsyncFn` over a borrowed one: the callers live inside |
| 187 | /// `async fn execute(&self, .., &ToolContext)` futures that must stay `Send`, |
| 188 | /// and a higher-ranked borrow of the payload would force the returned future |
| 189 | /// to outlive the tool context it reads. |
| 190 | pub type ExtractFuture<'a, T> = |
| 191 | std::pin::Pin<Box<dyn Future<Output = AdapterResult<T>> + Send + 'a>>; |
| 192 | |
| 193 | /// A fetch that produced a readable document or a partial page, plus the |
| 194 | /// attempts it took. |
| 195 | #[derive(Debug)] |
| 196 | pub struct ReadableFetch<T> { |
| 197 | pub payload: FetchedPayload, |
| 198 | pub document: Readable<T>, |
| 199 | pub attempts: Vec<FetchAttempt>, |
| 200 | } |
| 201 | |
| 202 | #[derive(Debug)] |
| 203 | pub enum Readable<T> { |
| 204 | Document(T), |
| 205 | Partial(PartialPage), |
| 206 | } |
| 207 | |
| 208 | #[derive(Debug)] |
| 209 | pub struct PartialPage { |
| 210 | pub document: super::extract::ExtractedDocument, |
| 211 | pub note: String, |
| 212 | } |
| 213 | |
| 214 | /// Fetch `url` and extract it, re-fetching once past every cache when a 2xx |
| 215 | /// response that was not cut off at `max_bytes` yields no readable content. |
| 216 | /// |
| 217 | /// This is the single place that turns the JS-shell case into a second chance, |
| 218 | /// then into a partial page built from the response's title and description, |
| 219 | /// or an error the model can act on when the head carries neither. `extract` |
| 220 | /// runs against the fetched payload; only [`is_js_shell_error`] failures earn |
| 221 | /// the second request, so transport failures keep the existing single-retry |
| 222 | /// behavior of one request. |
| 223 | pub async fn fetch_readable<'e, T, F>( |
| 224 | url: &str, |
| 225 | options: &FetchOptions, |
| 226 | context: &ToolContext, |
| 227 | tool_label: &str, |
| 228 | extract: F, |
| 229 | ) -> Result<ReadableFetch<T>, ToolError> |
| 230 | where |
| 231 | F: Fn(FetchedPayload) -> ExtractFuture<'e, T>, |
| 232 | { |
| 233 | fetch_readable_inner(url, options, context, tool_label, None, extract).await |
| 234 | } |
| 235 | |
| 236 | #[cfg(any(test, feature = "test-support"))] |
| 237 | pub async fn fetch_readable_with_initial_pin<'e, T, F>( |
| 238 | url: &str, |
| 239 | options: &FetchOptions, |
| 240 | context: &ToolContext, |
| 241 | tool_label: &str, |
| 242 | initial_pin: DnsPin, |
| 243 | extract: F, |
| 244 | ) -> Result<ReadableFetch<T>, ToolError> |
| 245 | where |
| 246 | F: Fn(FetchedPayload) -> ExtractFuture<'e, T>, |
| 247 | { |
| 248 | fetch_readable_inner( |
| 249 | url, |
| 250 | options, |
| 251 | context, |
| 252 | tool_label, |
| 253 | Some(initial_pin), |
| 254 | extract, |
| 255 | ) |
| 256 | .await |
| 257 | } |
| 258 | |
| 259 | async fn fetch_readable_inner<'e, T, F>( |
| 260 | url: &str, |
| 261 | options: &FetchOptions, |
| 262 | context: &ToolContext, |
| 263 | tool_label: &str, |
| 264 | test_initial_pin: Option<DnsPin>, |
| 265 | extract: F, |
| 266 | ) -> Result<ReadableFetch<T>, ToolError> |
| 267 | where |
| 268 | F: Fn(FetchedPayload) -> ExtractFuture<'e, T>, |
| 269 | { |
| 270 | let mut attempts: Vec<FetchAttempt> = Vec::with_capacity(3); |
| 271 | let mut options = options.clone(); |
| 272 | for mode in [CacheMode::Default, CacheMode::Revalidate] { |
| 273 | let mut payload = fetch_inner( |
| 274 | url, |
| 275 | &options, |
| 276 | context, |
| 277 | tool_label, |
| 278 | test_initial_pin.clone(), |
| 279 | mode, |
| 280 | ) |
| 281 | .await?; |
| 282 | // Many sites refuse non-browser agents outright. One retry as a |
| 283 | // browser is the fallback; a second refusal is final. |
| 284 | if matches!(payload.status, 401 | 403) && !options.uses_browser_user_agent() { |
| 285 | attempts.push(FetchAttempt::record( |
| 286 | &payload, |
| 287 | attempts.len() + 1, |
| 288 | mode, |
| 289 | false, |
| 290 | )); |
| 291 | options = options.with_browser_user_agent(); |
| 292 | payload = fetch_inner( |
| 293 | url, |
| 294 | &options, |
| 295 | context, |
| 296 | tool_label, |
| 297 | test_initial_pin.clone(), |
| 298 | mode, |
| 299 | ) |
| 300 | .await?; |
| 301 | } |
| 302 | let mut record = FetchAttempt::record( |
| 303 | &payload, |
| 304 | attempts.len() + 1, |
| 305 | mode, |
| 306 | options.uses_browser_user_agent(), |
| 307 | ); |
| 308 | match extract(payload.clone()).await { |
| 309 | Ok(document) => { |
| 310 | record.produced_content = true; |
| 311 | attempts.push(record); |
| 312 | return Ok(ReadableFetch { |
| 313 | payload, |
| 314 | document: Readable::Document(document), |
| 315 | attempts, |
| 316 | }); |
| 317 | } |
| 318 | Err(error) |
| 319 | if error.content() |
| 320 | && is_js_shell_error(&error.error) |
| 321 | && payload.truncated |
| 322 | && (200..300).contains(&payload.status) => |
| 323 | { |
| 324 | attempts.push(record); |
| 325 | return shell_outcome(payload, attempts, context, Some(options.max_bytes)); |
| 326 | } |
| 327 | // A 2xx whose body held no readable content is the one failure a |
| 328 | // second request can fix: the first response may have been a |
| 329 | // cached client-side shell. |
| 330 | Err(error) |
| 331 | if error.content() |
| 332 | && is_js_shell_error(&error.error) |
| 333 | && (200..300).contains(&payload.status) |
| 334 | && mode == CacheMode::Default => |
| 335 | { |
| 336 | attempts.push(record); |
| 337 | } |
| 338 | Err(error) => { |
| 339 | attempts.push(record); |
| 340 | if error.content() && is_js_shell_error(&error.error) { |
| 341 | return shell_outcome(payload, attempts, context, None); |
| 342 | } |
| 343 | return Err(error.error); |
| 344 | } |
| 345 | } |
| 346 | } |
| 347 | unreachable!("the revalidate pass either returns a document or an error"); |
| 348 | } |
| 349 | |
| 350 | fn shell_outcome<T>( |
| 351 | payload: FetchedPayload, |
| 352 | attempts: Vec<FetchAttempt>, |
| 353 | context: &ToolContext, |
| 354 | truncated_at: Option<usize>, |
| 355 | ) -> Result<ReadableFetch<T>, ToolError> { |
| 356 | let note = js_shell_message(&payload.url, &attempts, context, truncated_at); |
| 357 | let summary = (200..300) |
| 358 | .contains(&payload.status) |
| 359 | .then(|| { |
| 360 | super::extract::head_summary(&payload.url, Some(&payload.content_type), &payload.bytes) |
| 361 | }) |
| 362 | .flatten(); |
| 363 | match summary { |
| 364 | Some(document) => Ok(ReadableFetch { |
| 365 | payload, |
| 366 | document: Readable::Partial(PartialPage { document, note }), |
| 367 | attempts, |
| 368 | }), |
| 369 | None => Err(ToolError::execution_failed(note)), |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | /// The terminal JS-shell message — the error, or the note on a partial page — |
| 374 | /// carrying the failure receipt and the recovery the *calling role* actually |
| 375 | /// owns. |
| 376 | fn js_shell_message( |
| 377 | url: &str, |
| 378 | attempts: &[FetchAttempt], |
| 379 | context: &ToolContext, |
| 380 | truncated_at: Option<usize>, |
| 381 | ) -> String { |
| 382 | let receipt = attempts |
| 383 | .iter() |
| 384 | .map(FetchAttempt::summarize) |
| 385 | .collect::<Vec<_>>() |
| 386 | .join("; "); |
| 387 | let marker = super::extract::JS_SHELL_MARKER; |
| 388 | let recovery = js_shell_recovery(url, context); |
| 389 | match truncated_at { |
| 390 | None => format!( |
| 391 | "{marker} {url} after {count} attempts, the second past every cache ({receipt}). The response parsed but held no readable body, which usually means the page renders its content with JavaScript. Recovery: {recovery}", |
| 392 | count = attempts.len(), |
| 393 | ), |
| 394 | Some(limit) if limit < HARD_MAX_BYTES => format!( |
| 395 | "{marker} {url} in the first {limit} bytes, where the response was cut off ({receipt}). Either the readable content starts past that cap or the page renders it with JavaScript. Recovery: retry with a larger `max_bytes` (up to {HARD_MAX_BYTES}). If the whole page still has no readable body, {recovery}" |
| 396 | ), |
| 397 | Some(limit) => format!( |
| 398 | "{marker} {url} in the first {limit} bytes, the fetch limit, where the response was cut off ({receipt}). Either the readable content starts past that limit or the page renders it with JavaScript. Recovery: {recovery}" |
| 399 | ), |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | /// Whether the model-facing `Web` tool is reachable from this context. |
| 404 | /// |
| 405 | /// Both facts already exist: the web family is feature-gated, and a |
| 406 | /// network-denied Fleet worker carries `network_access: Some(false)` on the |
| 407 | /// authority envelope that also removes the web tools from its registry |
| 408 | /// (`codewhale_agent_contract::role::NETWORK_TOOL_DENYLIST`). Nothing new is registered here. |
| 409 | fn web_tool_available(context: &ToolContext) -> bool { |
| 410 | context.features.enabled(Feature::WebSearch) && network_authorized(context) |
| 411 | } |
| 412 | |
| 413 | /// Whether this role could shell out to `curl` as a last resort: a full shell |
| 414 | /// directly, a read-only shell only through a networked `read_only: true` run. |
| 415 | fn shell_fallback_available(context: &ToolContext) -> bool { |
| 416 | match context.shell_policy { |
| 417 | ShellPolicy::Full => network_authorized(context), |
| 418 | ShellPolicy::ReadOnly => { |
| 419 | crate::tools::shell::readonly_enforced_lane_available(context) |
| 420 | && crate::tools::shell::readonly_lane_network_access(context) |
| 421 | } |
| 422 | ShellPolicy::None => false, |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | pub fn network_authorized(context: &ToolContext) -> bool { |
| 427 | context |
| 428 | .tool_authority |
| 429 | .as_deref() |
| 430 | .is_none_or(|authority| authority.network_access != Some(false)) |
| 431 | && context |
| 432 | .child_host |
| 433 | .as_deref() |
| 434 | .is_none_or(|child| !child.network_is_denied()) |
| 435 | } |
| 436 | |
| 437 | /// The raw-HTML fetch a JS-shell recovery suggests, as a `Web` tool input. |
| 438 | fn raw_fetch_call(url: &str) -> serde_json::Value { |
| 439 | serde_json::json!({"action": "fetch", "url": url, "format": "raw"}) |
| 440 | } |
| 441 | |
| 442 | /// The HTTP extractor cannot execute JavaScript. Recovery names any browser |
| 443 | /// the session is authorized to use. |
| 444 | fn js_shell_recovery(url: &str, context: &ToolContext) -> String { |
| 445 | let same_result = |
| 446 | "This HTTP fetch/extraction path does not execute JavaScript (`web.run` shares it)."; |
| 447 | let browser = context |
| 448 | .browser_tool |
| 449 | .as_deref() |
| 450 | .filter(|_| network_authorized(context)) |
| 451 | .map(|tool| { |
| 452 | format!( |
| 453 | " This session has a browser tool that runs JavaScript: to read the rendered page, open {url} with `{tool}`." |
| 454 | ) |
| 455 | }) |
| 456 | .unwrap_or_default(); |
| 457 | if web_tool_available(context) { |
| 458 | return format!( |
| 459 | "{same_result}{browser} Many JavaScript pages embed their content as JSON in a script tag; to look for it, fetch the raw HTML with `Web {call}`. Otherwise search for another source of the same content.", |
| 460 | call = raw_fetch_call(url), |
| 461 | ); |
| 462 | } |
| 463 | if shell_fallback_available(context) { |
| 464 | let lane = if context.shell_policy == ShellPolicy::ReadOnly { |
| 465 | " run with `read_only: true`" |
| 466 | } else { |
| 467 | "" |
| 468 | }; |
| 469 | format!( |
| 470 | "{same_result}{browser} Inspect the raw HTML with a shell fetch (`curl -sSL`){lane} for embedded data, or use a rendering tool." |
| 471 | ) |
| 472 | } else if browser.is_empty() { |
| 473 | format!( |
| 474 | "{same_result} This role cannot fall back to a shell fetch, so report this URL as unreadable rather than substituting another source." |
| 475 | ) |
| 476 | } else { |
| 477 | format!( |
| 478 | "{same_result}{browser} This role cannot fall back to a shell fetch, so if the browser cannot render it either, report this URL as unreadable rather than substituting another source." |
| 479 | ) |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | pub fn rendering_browser_tool<'a>(names: impl IntoIterator<Item = &'a str>) -> Option<String> { |
| 484 | let names = names |
| 485 | .into_iter() |
| 486 | .filter(|name| name.starts_with("mcp_")) |
| 487 | .collect::<Vec<_>>(); |
| 488 | let computer_use_browser = names.iter().copied().find(|name| { |
| 489 | name.strip_suffix("_browser") |
| 490 | .is_some_and(|server| names.contains(&format!("{server}_computer").as_str())) |
| 491 | }); |
| 492 | ["_browser_navigate", "_puppeteer_navigate", "_navigate_page"] |
| 493 | .into_iter() |
| 494 | .find_map(|suffix| names.iter().copied().find(|name| name.ends_with(suffix))) |
| 495 | .or(computer_use_browser) |
| 496 | .map(str::to_string) |
| 497 | } |
| 498 | |
| 499 | #[cfg(any(test, feature = "test-support"))] |
| 500 | pub async fn fetch_with_initial_pin( |
| 501 | url: &str, |
| 502 | options: &FetchOptions, |
| 503 | context: &ToolContext, |
| 504 | tool_label: &str, |
| 505 | initial_pin: DnsPin, |
| 506 | ) -> Result<FetchedPayload, ToolError> { |
| 507 | fetch_inner( |
| 508 | url, |
| 509 | options, |
| 510 | context, |
| 511 | tool_label, |
| 512 | Some(initial_pin), |
| 513 | CacheMode::Default, |
| 514 | ) |
| 515 | .await |
| 516 | } |
| 517 | |
| 518 | async fn fetch_inner( |
| 519 | url: &str, |
| 520 | options: &FetchOptions, |
| 521 | context: &ToolContext, |
| 522 | tool_label: &str, |
| 523 | test_initial_pin: Option<DnsPin>, |
| 524 | cache_mode: CacheMode, |
| 525 | ) -> Result<FetchedPayload, ToolError> { |
| 526 | let initial_url = reqwest::Url::parse(url) |
| 527 | .map_err(|err| ToolError::invalid_input(format!("invalid URL: {err}")))?; |
| 528 | if !matches!(initial_url.scheme(), "http" | "https") { |
| 529 | return Err(ToolError::invalid_input( |
| 530 | "only http:// and https:// URLs are supported", |
| 531 | )); |
| 532 | } |
| 533 | |
| 534 | // Validation precedes cache lookup so a policy tightened during the |
| 535 | // session cannot be bypassed by a previously cached response. |
| 536 | let validated_initial_pin = match test_initial_pin { |
| 537 | Some(pin) => pin, |
| 538 | None => { |
| 539 | validate_fetch_target( |
| 540 | &initial_url, |
| 541 | context, |
| 542 | tool_label, |
| 543 | PrivateTargets::TypedLocalHosts, |
| 544 | ) |
| 545 | .await? |
| 546 | } |
| 547 | }; |
| 548 | |
| 549 | if let Some(cached) = (!cache_mode.is_revalidate()) |
| 550 | .then(|| { |
| 551 | cache::get( |
| 552 | &context.state_namespace, |
| 553 | &initial_url, |
| 554 | options.accept, |
| 555 | options.max_bytes, |
| 556 | ) |
| 557 | }) |
| 558 | .flatten() |
| 559 | { |
| 560 | let cached_url = reqwest::Url::parse(&cached.url).map_err(|err| { |
| 561 | ToolError::execution_failed(format!("cached response URL was invalid: {err}")) |
| 562 | })?; |
| 563 | let cached_host = cached_url.host_str().ok_or_else(|| { |
| 564 | ToolError::execution_failed("cached response URL did not include a host") |
| 565 | })?; |
| 566 | // No network request occurs on a cache hit, so DNS/SSRF validation is |
| 567 | // unnecessary. The final redirect destination still needs a policy |
| 568 | // check in case the session policy was tightened after insertion. |
| 569 | validate_network_policy(cached_host, context, tool_label)?; |
| 570 | return Ok(from_cached(cached, true, 0)); |
| 571 | } |
| 572 | |
| 573 | let deadline = Instant::now() + options.timeout; |
| 574 | let mut last_transient = None; |
| 575 | for attempt in 0..=1 { |
| 576 | let remaining = deadline.saturating_duration_since(Instant::now()); |
| 577 | if remaining.is_zero() { |
| 578 | break; |
| 579 | } |
| 580 | match fetch_attempt( |
| 581 | initial_url.clone(), |
| 582 | options, |
| 583 | context, |
| 584 | tool_label, |
| 585 | remaining, |
| 586 | validated_initial_pin.clone(), |
| 587 | cache_mode, |
| 588 | ) |
| 589 | .await |
| 590 | { |
| 591 | Ok(payload) if is_transient_status(payload.status) && attempt == 0 => { |
| 592 | last_transient = Some(format!("HTTP {}", payload.status)); |
| 593 | } |
| 594 | Ok(payload) => { |
| 595 | let fetched = from_cached(payload.clone(), false, attempt); |
| 596 | if (200..300).contains(&payload.status) { |
| 597 | cache::insert( |
| 598 | &context.state_namespace, |
| 599 | &initial_url, |
| 600 | options.accept, |
| 601 | payload, |
| 602 | ); |
| 603 | } |
| 604 | return Ok(fetched); |
| 605 | } |
| 606 | Err(AttemptError::Fatal(error)) => return Err(error), |
| 607 | Err(AttemptError::Transient(message)) if attempt == 0 => { |
| 608 | last_transient = Some(message); |
| 609 | } |
| 610 | Err(AttemptError::Transient(message)) => { |
| 611 | return Err(ToolError::execution_failed(format!( |
| 612 | "request failed after one retry: {message}" |
| 613 | ))); |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | let delay = retry_delay(); |
| 618 | if deadline.saturating_duration_since(Instant::now()) <= delay { |
| 619 | break; |
| 620 | } |
| 621 | tokio::time::sleep(delay).await; |
| 622 | } |
| 623 | |
| 624 | Err(ToolError::execution_failed(format!( |
| 625 | "request timed out before retry completed{}", |
| 626 | last_transient |
| 627 | .map(|message| format!(" (last failure: {message})")) |
| 628 | .unwrap_or_default() |
| 629 | ))) |
| 630 | } |
| 631 | |
| 632 | pub async fn reachable_status( |
| 633 | url: &str, |
| 634 | timeout: Duration, |
| 635 | context: &ToolContext, |
| 636 | tool_label: &str, |
| 637 | ) -> Result<u16, ToolError> { |
| 638 | let target = reqwest::Url::parse(url) |
| 639 | .map_err(|err| ToolError::invalid_input(format!("invalid URL: {err}")))?; |
| 640 | let timeout = timeout.min(HARD_MAX_TIMEOUT); |
| 641 | let deadline = Instant::now() + timeout; |
| 642 | let head = FetchOptions { |
| 643 | method: reqwest::Method::HEAD, |
| 644 | ..FetchOptions::new(timeout, 1, "*/*") |
| 645 | }; |
| 646 | let ranged = FetchOptions { |
| 647 | range: Some("bytes=0-0"), |
| 648 | ..FetchOptions::new(timeout, 1, "*/*").with_browser_user_agent() |
| 649 | }; |
| 650 | let probe = async { |
| 651 | let mut outcome = Err(ToolError::execution_failed("link check did not run")); |
| 652 | for (attempt, options) in [head, ranged].iter().enumerate() { |
| 653 | let remaining = deadline.saturating_duration_since(Instant::now()); |
| 654 | let budget = if attempt == 0 { |
| 655 | remaining / 2 |
| 656 | } else { |
| 657 | remaining |
| 658 | }; |
| 659 | if budget.is_zero() { |
| 660 | break; |
| 661 | } |
| 662 | outcome = match fetch_attempt( |
| 663 | target.clone(), |
| 664 | options, |
| 665 | context, |
| 666 | tool_label, |
| 667 | budget, |
| 668 | None, |
| 669 | CacheMode::Default, |
| 670 | ) |
| 671 | .await |
| 672 | { |
| 673 | Ok(payload) if (200..300).contains(&payload.status) => return Ok(payload.status), |
| 674 | Ok(payload) => Ok(payload.status), |
| 675 | Err(AttemptError::Fatal(error)) => return Err(error), |
| 676 | Err(AttemptError::Transient(message)) => Err(ToolError::execution_failed(message)), |
| 677 | }; |
| 678 | } |
| 679 | outcome |
| 680 | }; |
| 681 | tokio::time::timeout(timeout, probe) |
| 682 | .await |
| 683 | .unwrap_or_else(|_| { |
| 684 | Err(ToolError::Timeout { |
| 685 | seconds: timeout.as_secs().max(1), |
| 686 | }) |
| 687 | }) |
| 688 | } |
| 689 | |
| 690 | #[derive(Debug)] |
| 691 | enum AttemptError { |
| 692 | Fatal(ToolError), |
| 693 | Transient(String), |
| 694 | } |
| 695 | |
| 696 | async fn fetch_attempt( |
| 697 | initial_url: reqwest::Url, |
| 698 | options: &FetchOptions, |
| 699 | context: &ToolContext, |
| 700 | tool_label: &str, |
| 701 | timeout: Duration, |
| 702 | initial_pin: DnsPin, |
| 703 | cache_mode: CacheMode, |
| 704 | ) -> Result<CachedFetch, AttemptError> { |
| 705 | let mut current_url = initial_url; |
| 706 | let mut redirects = 0usize; |
| 707 | let mut initial_pin = initial_pin; |
| 708 | let deadline = Instant::now() + timeout; |
| 709 | |
| 710 | let response = loop { |
| 711 | let dns_pin = if redirects == 0 { |
| 712 | match initial_pin.take() { |
| 713 | Some(pin) => Some(pin), |
| 714 | None => validate_fetch_target( |
| 715 | ¤t_url, |
| 716 | context, |
| 717 | tool_label, |
| 718 | PrivateTargets::TypedLocalHosts, |
| 719 | ) |
| 720 | .await |
| 721 | .map_err(AttemptError::Fatal)?, |
| 722 | } |
| 723 | } else { |
| 724 | validate_fetch_target( |
| 725 | ¤t_url, |
| 726 | context, |
| 727 | tool_label, |
| 728 | PrivateTargets::TypedLocalHosts, |
| 729 | ) |
| 730 | .await |
| 731 | .map_err(AttemptError::Fatal)? |
| 732 | }; |
| 733 | |
| 734 | let remaining = deadline.saturating_duration_since(Instant::now()); |
| 735 | if remaining.is_zero() { |
| 736 | return Err(AttemptError::Transient( |
| 737 | "request timed out while following redirects".to_string(), |
| 738 | )); |
| 739 | } |
| 740 | let mut builder = guarded_reqwest_client_builder() |
| 741 | .timeout(remaining) |
| 742 | .user_agent(options.user_agent) |
| 743 | .redirect(reqwest::redirect::Policy::none()); |
| 744 | if let Some((hostname, validated_ip)) = dns_pin { |
| 745 | builder = builder.resolve(&hostname, std::net::SocketAddr::new(validated_ip, 0)); |
| 746 | } |
| 747 | let client = builder.build().map_err(|err| { |
| 748 | AttemptError::Fatal(ToolError::execution_failed(format!( |
| 749 | "failed to build HTTP client: {err}" |
| 750 | ))) |
| 751 | })?; |
| 752 | let mut request = client |
| 753 | .request(options.method.clone(), current_url.clone()) |
| 754 | .header("Accept", options.accept) |
| 755 | .header("Accept-Language", "en-US,en;q=0.5"); |
| 756 | if let Some(range) = options.range { |
| 757 | request = request.header(reqwest::header::RANGE, range); |
| 758 | } |
| 759 | if cache_mode.is_revalidate() { |
| 760 | // `no-cache` (revalidate), not `no-store`: the shared caches still |
| 761 | // get to serve a validated copy, which is what recovers a page |
| 762 | // whose prerendered variant exists but was not the one served. |
| 763 | // `Pragma` is the HTTP/1.0 spelling some CDNs still honor. |
| 764 | request = request |
| 765 | .header("Cache-Control", "no-cache") |
| 766 | .header("Pragma", "no-cache"); |
| 767 | } |
| 768 | let response = request |
| 769 | .send() |
| 770 | .await |
| 771 | .map_err(|err| AttemptError::Transient(err.to_string()))?; |
| 772 | |
| 773 | if !response.status().is_redirection() { |
| 774 | break response; |
| 775 | } |
| 776 | if redirects >= MAX_REDIRECTS { |
| 777 | return Err(AttemptError::Fatal(ToolError::execution_failed( |
| 778 | "request exceeded the five-redirect limit", |
| 779 | ))); |
| 780 | } |
| 781 | let Some(location) = response |
| 782 | .headers() |
| 783 | .get(reqwest::header::LOCATION) |
| 784 | .and_then(|value| value.to_str().ok()) |
| 785 | else { |
| 786 | break response; |
| 787 | }; |
| 788 | current_url = response.url().join(location).map_err(|err| { |
| 789 | AttemptError::Fatal(ToolError::execution_failed(format!( |
| 790 | "invalid redirect location: {err}" |
| 791 | ))) |
| 792 | })?; |
| 793 | redirects += 1; |
| 794 | }; |
| 795 | |
| 796 | let final_url = response.url().to_string(); |
| 797 | let status = response.status().as_u16(); |
| 798 | let content_type = response |
| 799 | .headers() |
| 800 | .get(reqwest::header::CONTENT_TYPE) |
| 801 | .and_then(|value| value.to_str().ok()) |
| 802 | .unwrap_or("application/octet-stream") |
| 803 | .to_string(); |
| 804 | let headers = response_headers(response.headers()); |
| 805 | let mut stream = response.bytes_stream(); |
| 806 | let mut bytes = Vec::with_capacity(options.max_bytes.min(64 * 1024)); |
| 807 | let mut truncated = false; |
| 808 | while let Some(chunk) = stream.next().await { |
| 809 | let chunk = chunk.map_err(|err| AttemptError::Transient(err.to_string()))?; |
| 810 | let remaining = options.max_bytes.saturating_sub(bytes.len()); |
| 811 | if chunk.len() > remaining { |
| 812 | bytes.extend_from_slice(&chunk[..remaining]); |
| 813 | truncated = true; |
| 814 | break; |
| 815 | } |
| 816 | bytes.extend_from_slice(&chunk); |
| 817 | if bytes.len() == options.max_bytes { |
| 818 | // A response exactly at the cap may be complete. Ask for one more |
| 819 | // chunk to distinguish exact length from actual truncation. |
| 820 | if let Some(next) = stream.next().await { |
| 821 | let next = next.map_err(|err| AttemptError::Transient(err.to_string()))?; |
| 822 | truncated = !next.is_empty(); |
| 823 | } |
| 824 | break; |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | Ok(CachedFetch { |
| 829 | url: final_url, |
| 830 | status, |
| 831 | headers, |
| 832 | content_type, |
| 833 | bytes: Arc::new(bytes), |
| 834 | truncated, |
| 835 | redirects, |
| 836 | }) |
| 837 | } |
| 838 | |
| 839 | fn from_cached(payload: CachedFetch, cache_hit: bool, retries: usize) -> FetchedPayload { |
| 840 | FetchedPayload { |
| 841 | url: payload.url, |
| 842 | status: payload.status, |
| 843 | headers: payload.headers, |
| 844 | content_type: payload.content_type, |
| 845 | bytes: payload.bytes, |
| 846 | truncated: payload.truncated, |
| 847 | cache_hit, |
| 848 | retries, |
| 849 | redirects: payload.redirects, |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | fn response_headers(headers: &reqwest::header::HeaderMap) -> BTreeMap<String, String> { |
| 854 | headers |
| 855 | .iter() |
| 856 | .filter(|(name, _)| { |
| 857 | !matches!( |
| 858 | name.as_str(), |
| 859 | "authorization" |
| 860 | | "proxy-authorization" |
| 861 | | "cookie" |
| 862 | | "set-cookie" |
| 863 | | "set-cookie2" |
| 864 | | "x-api-key" |
| 865 | | "api-key" |
| 866 | ) |
| 867 | }) |
| 868 | .filter_map(|(name, value)| { |
| 869 | value |
| 870 | .to_str() |
| 871 | .ok() |
| 872 | .map(|value| (name.as_str().to_ascii_lowercase(), value.to_string())) |
| 873 | }) |
| 874 | .collect() |
| 875 | } |
| 876 | |
| 877 | fn is_transient_status(status: u16) -> bool { |
| 878 | (500..600).contains(&status) |
| 879 | } |
| 880 | |
| 881 | fn retry_delay() -> Duration { |
| 882 | #[cfg(any(test, feature = "test-support"))] |
| 883 | return Duration::ZERO; |
| 884 | |
| 885 | #[cfg(not(any(test, feature = "test-support")))] |
| 886 | { |
| 887 | let jitter_ms = SystemTime::now() |
| 888 | .duration_since(UNIX_EPOCH) |
| 889 | .map(|duration| u64::from(duration.subsec_nanos()) % 41) |
| 890 | .unwrap_or(0); |
| 891 | Duration::from_millis(30 + jitter_ms) |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | #[cfg(test)] |
| 896 | mod tests { |
| 897 | use std::collections::BTreeMap; |
| 898 | use std::net::{IpAddr, Ipv4Addr}; |
| 899 | use std::sync::Arc; |
| 900 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 901 | |
| 902 | use serde_json::json; |
| 903 | use wiremock::matchers::{method, path}; |
| 904 | use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate}; |
| 905 | |
| 906 | use super::*; |
| 907 | |
| 908 | fn context(namespace: &str) -> ToolContext { |
| 909 | ToolContext::new(".").with_state_namespace(namespace) |
| 910 | } |
| 911 | |
| 912 | fn pin() -> DnsPin { |
| 913 | Some(( |
| 914 | "public.example".to_string(), |
| 915 | IpAddr::V4(Ipv4Addr::LOCALHOST), |
| 916 | )) |
| 917 | } |
| 918 | |
| 919 | #[derive(Clone)] |
| 920 | struct FailOnce { |
| 921 | calls: Arc<AtomicUsize>, |
| 922 | } |
| 923 | |
| 924 | impl Respond for FailOnce { |
| 925 | fn respond(&self, _request: &Request) -> ResponseTemplate { |
| 926 | if self.calls.fetch_add(1, Ordering::SeqCst) == 0 { |
| 927 | ResponseTemplate::new(503).set_body_json(json!({"error": "retry"})) |
| 928 | } else { |
| 929 | ResponseTemplate::new(200) |
| 930 | .insert_header("content-type", "text/plain") |
| 931 | .set_body_string("recovered response") |
| 932 | } |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | #[tokio::test] |
| 937 | async fn transient_server_error_retries_once_then_caches() { |
| 938 | let server = MockServer::start().await; |
| 939 | let calls = Arc::new(AtomicUsize::new(0)); |
| 940 | Mock::given(method("GET")) |
| 941 | .and(path("/retry")) |
| 942 | .respond_with(FailOnce { |
| 943 | calls: Arc::clone(&calls), |
| 944 | }) |
| 945 | .mount(&server) |
| 946 | .await; |
| 947 | let url = format!("http://public.example:{}/retry", server.address().port()); |
| 948 | let options = FetchOptions::new(Duration::from_secs(5), 1_024, "text/plain"); |
| 949 | let context = context("fetch-retry-cache"); |
| 950 | |
| 951 | let first = fetch_with_initial_pin(&url, &options, &context, "test", pin()) |
| 952 | .await |
| 953 | .expect("retry succeeds"); |
| 954 | assert_eq!(first.status, 200); |
| 955 | assert_eq!(first.retries, 1); |
| 956 | assert!(!first.cache_hit); |
| 957 | assert_eq!(&*first.bytes, b"recovered response"); |
| 958 | |
| 959 | let second = fetch_with_initial_pin(&url, &options, &context, "test", pin()) |
| 960 | .await |
| 961 | .expect("cache hit"); |
| 962 | assert!(second.cache_hit); |
| 963 | assert_eq!(calls.load(Ordering::SeqCst), 2); |
| 964 | } |
| 965 | |
| 966 | #[tokio::test] |
| 967 | async fn truncated_cache_refetches_when_larger_body_is_requested() { |
| 968 | let server = MockServer::start().await; |
| 969 | Mock::given(method("GET")) |
| 970 | .and(path("/large")) |
| 971 | .respond_with( |
| 972 | ResponseTemplate::new(200) |
| 973 | .insert_header("content-type", "text/plain") |
| 974 | .set_body_string("0123456789"), |
| 975 | ) |
| 976 | .mount(&server) |
| 977 | .await; |
| 978 | let url = format!("http://public.example:{}/large", server.address().port()); |
| 979 | let context = context("fetch-truncated-refetch"); |
| 980 | |
| 981 | let small = fetch_with_initial_pin( |
| 982 | &url, |
| 983 | &FetchOptions::new(Duration::from_secs(5), 4, "text/plain"), |
| 984 | &context, |
| 985 | "test", |
| 986 | pin(), |
| 987 | ) |
| 988 | .await |
| 989 | .expect("small fetch"); |
| 990 | assert_eq!(&*small.bytes, b"0123"); |
| 991 | assert!(small.truncated); |
| 992 | |
| 993 | let large = fetch_with_initial_pin( |
| 994 | &url, |
| 995 | &FetchOptions::new(Duration::from_secs(5), 16, "text/plain"), |
| 996 | &context, |
| 997 | "test", |
| 998 | pin(), |
| 999 | ) |
| 1000 | .await |
| 1001 | .expect("larger refetch"); |
| 1002 | assert_eq!(&*large.bytes, b"0123456789"); |
| 1003 | assert!(!large.truncated); |
| 1004 | assert!(!large.cache_hit); |
| 1005 | } |
| 1006 | |
| 1007 | /// A Vercel-style edge that serves the client-side shell to an ordinary |
| 1008 | /// request and the prerendered page to a revalidating one (#5904). |
| 1009 | #[derive(Clone)] |
| 1010 | struct ShellUntilRevalidated { |
| 1011 | calls: Arc<AtomicUsize>, |
| 1012 | always_shell: bool, |
| 1013 | } |
| 1014 | |
| 1015 | const JS_SHELL_BODY: &str = "<html><head><title>Pricing</title></head><body><div id='root'></div><script>boot()</script></body></html>"; |
| 1016 | const PRERENDERED_BODY: &str = "<html><head><title>Pricing</title></head><body><main><h1>Pricing</h1><p>The prerendered variant carries the full pricing table for every plan.</p></main></body></html>"; |
| 1017 | |
| 1018 | impl Respond for ShellUntilRevalidated { |
| 1019 | fn respond(&self, request: &Request) -> ResponseTemplate { |
| 1020 | self.calls.fetch_add(1, Ordering::SeqCst); |
| 1021 | let revalidating = request |
| 1022 | .headers |
| 1023 | .get("cache-control") |
| 1024 | .and_then(|value| value.to_str().ok()) |
| 1025 | .is_some_and(|value| value.contains("no-cache")); |
| 1026 | if revalidating && !self.always_shell { |
| 1027 | ResponseTemplate::new(200) |
| 1028 | .insert_header("content-type", "text/html") |
| 1029 | .insert_header("x-vercel-cache", "HIT") |
| 1030 | .insert_header("x-nextjs-prerender", "1") |
| 1031 | .insert_header("age", "12") |
| 1032 | .set_body_string(PRERENDERED_BODY) |
| 1033 | } else { |
| 1034 | ResponseTemplate::new(200) |
| 1035 | .insert_header("content-type", "text/html") |
| 1036 | .insert_header("x-vercel-cache", "MISS") |
| 1037 | .set_body_string(JS_SHELL_BODY) |
| 1038 | } |
| 1039 | } |
| 1040 | } |
| 1041 | |
| 1042 | async fn js_shell_server(always_shell: bool) -> (MockServer, Arc<AtomicUsize>) { |
| 1043 | let server = MockServer::start().await; |
| 1044 | let calls = Arc::new(AtomicUsize::new(0)); |
| 1045 | Mock::given(method("GET")) |
| 1046 | .and(path("/pricing")) |
| 1047 | .respond_with(ShellUntilRevalidated { |
| 1048 | calls: Arc::clone(&calls), |
| 1049 | always_shell, |
| 1050 | }) |
| 1051 | .mount(&server) |
| 1052 | .await; |
| 1053 | (server, calls) |
| 1054 | } |
| 1055 | |
| 1056 | fn extract_html_document( |
| 1057 | payload: FetchedPayload, |
| 1058 | ) -> ExtractFuture<'static, super::super::extract::ExtractedDocument> { |
| 1059 | Box::pin(async move { |
| 1060 | super::super::extract::extract_document( |
| 1061 | &payload.url, |
| 1062 | Some(&payload.content_type), |
| 1063 | &payload.bytes, |
| 1064 | payload.truncated, |
| 1065 | None, |
| 1066 | ) |
| 1067 | .await |
| 1068 | }) |
| 1069 | } |
| 1070 | |
| 1071 | #[tokio::test] |
| 1072 | async fn js_shell_is_refetched_past_every_cache_before_it_becomes_an_error() { |
| 1073 | let (server, calls) = js_shell_server(false).await; |
| 1074 | let url = format!("http://public.example:{}/pricing", server.address().port()); |
| 1075 | let context = context("js-shell-recovers"); |
| 1076 | |
| 1077 | let readable = fetch_readable_with_initial_pin( |
| 1078 | &url, |
| 1079 | &FetchOptions::new(Duration::from_secs(5), 65_536, "text/html"), |
| 1080 | &context, |
| 1081 | "fetch_url", |
| 1082 | pin(), |
| 1083 | extract_html_document, |
| 1084 | ) |
| 1085 | .await |
| 1086 | .expect("the revalidated response carries the prerendered page"); |
| 1087 | |
| 1088 | let Readable::Document(document) = &readable.document else { |
| 1089 | panic!("the revalidated response carries the prerendered page"); |
| 1090 | }; |
| 1091 | assert!( |
| 1092 | document.markdown.contains("full pricing table"), |
| 1093 | "the second attempt's content must be what the caller receives: {}", |
| 1094 | document.markdown |
| 1095 | ); |
| 1096 | assert_eq!(calls.load(Ordering::SeqCst), 2, "exactly one extra request"); |
| 1097 | assert_eq!(readable.attempts.len(), 2); |
| 1098 | assert!(!readable.attempts[0].cache_busted); |
| 1099 | assert!(!readable.attempts[0].produced_content); |
| 1100 | assert_eq!( |
| 1101 | readable.attempts[0].cache_headers.get("x-vercel-cache"), |
| 1102 | Some(&"MISS".to_string()), |
| 1103 | "the failing attempt keeps the header that explains its cache state" |
| 1104 | ); |
| 1105 | assert!(readable.attempts[1].cache_busted); |
| 1106 | assert!(readable.attempts[1].produced_content); |
| 1107 | assert_eq!( |
| 1108 | readable.attempts[1].cache_headers.get("x-vercel-cache"), |
| 1109 | Some(&"HIT".to_string()) |
| 1110 | ); |
| 1111 | assert_eq!( |
| 1112 | readable.attempts[1].cache_headers.get("x-nextjs-prerender"), |
| 1113 | Some(&"1".to_string()) |
| 1114 | ); |
| 1115 | assert_eq!( |
| 1116 | readable.attempts[1].cache_headers.get("age"), |
| 1117 | Some(&"12".to_string()) |
| 1118 | ); |
| 1119 | } |
| 1120 | |
| 1121 | #[tokio::test] |
| 1122 | async fn two_shells_degrade_with_the_escalation_the_calling_role_owns() { |
| 1123 | let (server, calls) = js_shell_server(true).await; |
| 1124 | let url = format!("http://public.example:{}/pricing", server.address().port()); |
| 1125 | let options = FetchOptions::new(Duration::from_secs(5), 65_536, "text/html"); |
| 1126 | |
| 1127 | let mut browser = context("js-shell-browser-role"); |
| 1128 | browser.execution.browser_tool = Some("mcp_playwright_browser_navigate".to_string()); |
| 1129 | let readable = fetch_readable_with_initial_pin( |
| 1130 | &url, |
| 1131 | &options, |
| 1132 | &browser, |
| 1133 | "fetch_url", |
| 1134 | pin(), |
| 1135 | extract_html_document, |
| 1136 | ) |
| 1137 | .await |
| 1138 | .expect("a titled shell degrades to its head"); |
| 1139 | let Readable::Partial(partial) = readable.document else { |
| 1140 | panic!("two shells must not yield a readable document"); |
| 1141 | }; |
| 1142 | assert_eq!(partial.document.title.as_deref(), Some("Pricing")); |
| 1143 | let message = partial.note; |
| 1144 | assert_eq!(calls.load(Ordering::SeqCst), 2, "no third request"); |
| 1145 | assert!( |
| 1146 | message.contains("This HTTP fetch/extraction path does not execute JavaScript") |
| 1147 | && message.contains("`mcp_playwright_browser_navigate`") |
| 1148 | && !message.contains("no Codewhale web tool runs JavaScript"), |
| 1149 | "the recovery must distinguish the HTTP extractor from the available browser: {message}" |
| 1150 | ); |
| 1151 | // The suggested call must be one the `Web` tool schema accepts. |
| 1152 | let call = message |
| 1153 | .split_once("`Web ") |
| 1154 | .and_then(|(_, tail)| tail.split_once('`')) |
| 1155 | .map(|(call, _)| call) |
| 1156 | .expect("the recovery names a Web call"); |
| 1157 | let call: serde_json::Value = serde_json::from_str(call).expect("suggested call is JSON"); |
| 1158 | assert_eq!(call, raw_fetch_call(&url)); |
| 1159 | let schema = crate::tools::spec::ToolSpec::input_schema( |
| 1160 | &crate::tools::web_tool::WebTool::new("Web"), |
| 1161 | ); |
| 1162 | let validator = jsonschema::options() |
| 1163 | .with_draft(jsonschema::Draft::Draft202012) |
| 1164 | .build(&schema) |
| 1165 | .expect("Web schema compiles"); |
| 1166 | assert!( |
| 1167 | validator.is_valid(&call), |
| 1168 | "suggested call must satisfy the Web schema: {call}" |
| 1169 | ); |
| 1170 | assert!( |
| 1171 | message.contains("attempt 1") |
| 1172 | && message.contains("attempt 2 (Cache-Control: no-cache)"), |
| 1173 | "the failure receipt names both attempts: {message}" |
| 1174 | ); |
| 1175 | assert!( |
| 1176 | message.contains("x-vercel-cache=MISS"), |
| 1177 | "the failure receipt carries the cache-state headers: {message}" |
| 1178 | ); |
| 1179 | |
| 1180 | // A read-only worker whose envelope denies network keeps `Web{fetch}` |
| 1181 | // but loses `web.run` and any shell fallback, so the note must say so |
| 1182 | // instead of naming a surface the role cannot call. |
| 1183 | let mut denied = context("js-shell-read-only-role"); |
| 1184 | denied.shell_policy = ShellPolicy::ReadOnly; |
| 1185 | denied.execution.tool_authority = |
| 1186 | Some(Arc::new(crate::tools::spec::ToolAuthorityEnvelope { |
| 1187 | schema_version: 1, |
| 1188 | owner: "scout".to_string(), |
| 1189 | authority: crate::tools::spec::ToolMutationAuthority::ReadOnly, |
| 1190 | network_access: Some(false), |
| 1191 | shell: crate::tools::spec::ToolShellAuthority::ReadOnly, |
| 1192 | verification: crate::tools::spec::ToolVerificationAuthority::None, |
| 1193 | writable_roots: Vec::new(), |
| 1194 | writable_files: Vec::new(), |
| 1195 | coordination_contracts: Vec::new(), |
| 1196 | })); |
| 1197 | let readable = fetch_readable_with_initial_pin( |
| 1198 | &url, |
| 1199 | &options, |
| 1200 | &denied, |
| 1201 | "fetch_url", |
| 1202 | pin(), |
| 1203 | extract_html_document, |
| 1204 | ) |
| 1205 | .await |
| 1206 | .expect("a titled shell degrades to its head"); |
| 1207 | let Readable::Partial(partial) = readable.document else { |
| 1208 | panic!("two shells must not yield a readable document"); |
| 1209 | }; |
| 1210 | let message = partial.note; |
| 1211 | assert!( |
| 1212 | !message.contains("`Web "), |
| 1213 | "a role without the web tools must not be sent to one: {message}" |
| 1214 | ); |
| 1215 | assert!( |
| 1216 | message.contains("cannot fall back to a shell fetch"), |
| 1217 | "read-only roles must not be sent to curl: {message}" |
| 1218 | ); |
| 1219 | } |
| 1220 | |
| 1221 | #[derive(Clone)] |
| 1222 | struct RefuseBots { |
| 1223 | calls: Arc<AtomicUsize>, |
| 1224 | } |
| 1225 | |
| 1226 | impl Respond for RefuseBots { |
| 1227 | fn respond(&self, request: &Request) -> ResponseTemplate { |
| 1228 | self.calls.fetch_add(1, Ordering::SeqCst); |
| 1229 | let agent = request |
| 1230 | .headers |
| 1231 | .get("user-agent") |
| 1232 | .and_then(|value| value.to_str().ok()) |
| 1233 | .unwrap_or_default(); |
| 1234 | if agent.contains("codewhale") { |
| 1235 | ResponseTemplate::new(403).set_body_string("bots not welcome") |
| 1236 | } else { |
| 1237 | ResponseTemplate::new(200) |
| 1238 | .insert_header("content-type", "text/plain") |
| 1239 | .set_body_string("browser body") |
| 1240 | } |
| 1241 | } |
| 1242 | } |
| 1243 | |
| 1244 | #[tokio::test] |
| 1245 | async fn forbidden_default_agent_retries_once_as_a_browser() { |
| 1246 | let server = MockServer::start().await; |
| 1247 | let calls = Arc::new(AtomicUsize::new(0)); |
| 1248 | Mock::given(method("GET")) |
| 1249 | .and(path("/guarded")) |
| 1250 | .respond_with(RefuseBots { |
| 1251 | calls: Arc::clone(&calls), |
| 1252 | }) |
| 1253 | .mount(&server) |
| 1254 | .await; |
| 1255 | let url = format!("http://public.example:{}/guarded", server.address().port()); |
| 1256 | |
| 1257 | let readable = fetch_readable_with_initial_pin( |
| 1258 | &url, |
| 1259 | &FetchOptions::new(Duration::from_secs(5), 1_024, "text/plain"), |
| 1260 | &context("fetch-403-browser-retry"), |
| 1261 | "fetch_url", |
| 1262 | pin(), |
| 1263 | |payload: FetchedPayload| { |
| 1264 | Box::pin(async move { Ok(String::from_utf8_lossy(&payload.bytes).into_owned()) }) |
| 1265 | }, |
| 1266 | ) |
| 1267 | .await |
| 1268 | .expect("the browser-agent retry reads the page"); |
| 1269 | |
| 1270 | assert!(matches!(&readable.document, Readable::Document(body) if body == "browser body")); |
| 1271 | assert_eq!(readable.payload.status, 200); |
| 1272 | assert_eq!(calls.load(Ordering::SeqCst), 2, "exactly one browser retry"); |
| 1273 | assert_eq!(readable.attempts.len(), 2); |
| 1274 | assert_eq!(readable.attempts[0].status, 403); |
| 1275 | assert!(!readable.attempts[0].browser_user_agent); |
| 1276 | assert!(readable.attempts[1].browser_user_agent); |
| 1277 | assert!(readable.attempts[1].produced_content); |
| 1278 | } |
| 1279 | |
| 1280 | #[tokio::test] |
| 1281 | async fn a_browser_refusal_is_final() { |
| 1282 | let server = MockServer::start().await; |
| 1283 | let calls = Arc::new(AtomicUsize::new(0)); |
| 1284 | Mock::given(method("GET")) |
| 1285 | .and(path("/closed")) |
| 1286 | .respond_with({ |
| 1287 | let calls = Arc::clone(&calls); |
| 1288 | move |_: &Request| { |
| 1289 | calls.fetch_add(1, Ordering::SeqCst); |
| 1290 | ResponseTemplate::new(403) |
| 1291 | } |
| 1292 | }) |
| 1293 | .mount(&server) |
| 1294 | .await; |
| 1295 | let url = format!("http://public.example:{}/closed", server.address().port()); |
| 1296 | |
| 1297 | let readable = fetch_readable_with_initial_pin( |
| 1298 | &url, |
| 1299 | &FetchOptions::new(Duration::from_secs(5), 1_024, "text/plain"), |
| 1300 | &context("fetch-403-final"), |
| 1301 | "fetch_url", |
| 1302 | pin(), |
| 1303 | |payload: FetchedPayload| Box::pin(async move { Ok(payload.status) }), |
| 1304 | ) |
| 1305 | .await |
| 1306 | .expect("the 403 is handed to the caller, which owns non-2xx rendering"); |
| 1307 | |
| 1308 | assert!(matches!(readable.document, Readable::Document(403))); |
| 1309 | assert_eq!(calls.load(Ordering::SeqCst), 2, "no third request"); |
| 1310 | } |
| 1311 | |
| 1312 | #[tokio::test] |
| 1313 | async fn transport_failures_do_not_earn_a_cache_busting_refetch() { |
| 1314 | let server = MockServer::start().await; |
| 1315 | let calls = Arc::new(AtomicUsize::new(0)); |
| 1316 | Mock::given(method("GET")) |
| 1317 | .and(path("/flaky")) |
| 1318 | .respond_with(FailOnce { |
| 1319 | calls: Arc::clone(&calls), |
| 1320 | }) |
| 1321 | .mount(&server) |
| 1322 | .await; |
| 1323 | let url = format!("http://public.example:{}/flaky", server.address().port()); |
| 1324 | let context = context("js-shell-transport-retry"); |
| 1325 | |
| 1326 | let readable = fetch_readable_with_initial_pin( |
| 1327 | &url, |
| 1328 | &FetchOptions::new(Duration::from_secs(5), 1_024, "text/plain"), |
| 1329 | &context, |
| 1330 | "fetch_url", |
| 1331 | pin(), |
| 1332 | |payload: FetchedPayload| { |
| 1333 | Box::pin(async move { Ok(String::from_utf8_lossy(&payload.bytes).into_owned()) }) |
| 1334 | }, |
| 1335 | ) |
| 1336 | .await |
| 1337 | .expect("the existing transport retry still recovers"); |
| 1338 | |
| 1339 | assert!( |
| 1340 | matches!(&readable.document, Readable::Document(body) if body == "recovered response") |
| 1341 | ); |
| 1342 | assert_eq!( |
| 1343 | calls.load(Ordering::SeqCst), |
| 1344 | 2, |
| 1345 | "the 503 costs the existing single transport retry and nothing more" |
| 1346 | ); |
| 1347 | assert_eq!( |
| 1348 | readable.attempts.len(), |
| 1349 | 1, |
| 1350 | "a transport retry is not a readable-fetch attempt" |
| 1351 | ); |
| 1352 | assert_eq!(readable.payload.retries, 1); |
| 1353 | assert!(!readable.attempts[0].cache_busted); |
| 1354 | assert!(readable.attempts[0].produced_content); |
| 1355 | } |
| 1356 | |
| 1357 | #[test] |
| 1358 | fn fetch_user_agent_tracks_the_crate_version() { |
| 1359 | assert!( |
| 1360 | USER_AGENT.contains(concat!("codewhale/", env!("CARGO_PKG_VERSION"))), |
| 1361 | "guarded-fetch UA must never pin a stale release: {USER_AGENT}" |
| 1362 | ); |
| 1363 | } |
| 1364 | |
| 1365 | #[test] |
| 1366 | fn response_headers_drop_set_cookie_values() { |
| 1367 | let mut headers = reqwest::header::HeaderMap::new(); |
| 1368 | headers.insert("content-type", "text/plain".parse().unwrap()); |
| 1369 | headers.insert("set-cookie", "session=secret".parse().unwrap()); |
| 1370 | headers.insert("x-api-key", "secret".parse().unwrap()); |
| 1371 | |
| 1372 | let filtered = response_headers(&headers); |
| 1373 | |
| 1374 | assert_eq!( |
| 1375 | filtered.get("content-type").map(String::as_str), |
| 1376 | Some("text/plain") |
| 1377 | ); |
| 1378 | assert!(!filtered.contains_key("set-cookie")); |
| 1379 | assert!(!filtered.contains_key("x-api-key")); |
| 1380 | } |
| 1381 | |
| 1382 | #[tokio::test] |
| 1383 | async fn tightened_network_policy_blocks_an_existing_cache_entry() { |
| 1384 | use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 1385 | |
| 1386 | let url = reqwest::Url::parse("https://example.com/cached").unwrap(); |
| 1387 | cache::insert( |
| 1388 | "policy-cache", |
| 1389 | &url, |
| 1390 | "text/plain", |
| 1391 | CachedFetch { |
| 1392 | url: url.to_string(), |
| 1393 | status: 200, |
| 1394 | headers: BTreeMap::new(), |
| 1395 | content_type: "text/plain".to_string(), |
| 1396 | bytes: Arc::new(b"cached".to_vec()), |
| 1397 | truncated: false, |
| 1398 | redirects: 0, |
| 1399 | }, |
| 1400 | ); |
| 1401 | let policy = NetworkPolicy { |
| 1402 | default: Decision::Deny.into(), |
| 1403 | allow: Vec::new(), |
| 1404 | deny: Vec::new(), |
| 1405 | proxy: Vec::new(), |
| 1406 | proxy_fake_ip_cidrs: Vec::new(), |
| 1407 | audit: false, |
| 1408 | }; |
| 1409 | let context = |
| 1410 | context("policy-cache").with_network_policy(NetworkPolicyDecider::new(policy, None)); |
| 1411 | |
| 1412 | let error = fetch_inner( |
| 1413 | url.as_str(), |
| 1414 | &FetchOptions::new(Duration::from_secs(1), 100, "text/plain"), |
| 1415 | &context, |
| 1416 | "fetch_url", |
| 1417 | None, |
| 1418 | CacheMode::Default, |
| 1419 | ) |
| 1420 | .await |
| 1421 | .expect_err("policy must win over cache"); |
| 1422 | assert!(error.to_string().contains("blocked by network policy")); |
| 1423 | } |
| 1424 | |
| 1425 | #[tokio::test] |
| 1426 | async fn tightened_network_policy_checks_cached_redirect_destination() { |
| 1427 | use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 1428 | |
| 1429 | let initial_url = reqwest::Url::parse("https://8.8.8.8/cached").unwrap(); |
| 1430 | cache::insert( |
| 1431 | "redirect-policy-cache", |
| 1432 | &initial_url, |
| 1433 | "text/plain", |
| 1434 | CachedFetch { |
| 1435 | url: "https://1.1.1.1/redirected".to_string(), |
| 1436 | status: 200, |
| 1437 | headers: BTreeMap::new(), |
| 1438 | content_type: "text/plain".to_string(), |
| 1439 | bytes: Arc::new(b"cached".to_vec()), |
| 1440 | truncated: false, |
| 1441 | redirects: 1, |
| 1442 | }, |
| 1443 | ); |
| 1444 | let policy = NetworkPolicy { |
| 1445 | default: Decision::Allow.into(), |
| 1446 | allow: Vec::new(), |
| 1447 | deny: vec!["1.1.1.1".to_string()], |
| 1448 | proxy: Vec::new(), |
| 1449 | proxy_fake_ip_cidrs: Vec::new(), |
| 1450 | audit: false, |
| 1451 | }; |
| 1452 | let context = context("redirect-policy-cache") |
| 1453 | .with_network_policy(NetworkPolicyDecider::new(policy, None)); |
| 1454 | |
| 1455 | let error = fetch_inner( |
| 1456 | initial_url.as_str(), |
| 1457 | &FetchOptions::new(Duration::from_secs(1), 100, "text/plain"), |
| 1458 | &context, |
| 1459 | "fetch_url", |
| 1460 | None, |
| 1461 | CacheMode::Default, |
| 1462 | ) |
| 1463 | .await |
| 1464 | .expect_err("final redirect policy must win over cache"); |
| 1465 | assert!(error.to_string().contains("1.1.1.1")); |
| 1466 | assert!(error.to_string().contains("blocked by network policy")); |
| 1467 | } |
| 1468 | } |
| 1469 |