Skip to main content

aft_base/
url_fetch.rs

1use std::collections::HashMap;
2use std::error::Error;
3use std::fmt;
4use std::fs;
5use std::io::{self, Read, Write};
6use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
7use std::path::{Path, PathBuf};
8use std::rc::Rc;
9use std::sync::{mpsc, Arc};
10use std::thread;
11use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
12
13use htmd::{
14    element_handler::{HandlerResult, Handlers},
15    Element, HtmlToMarkdown,
16};
17use markup5ever_rcdom::{Node, NodeData};
18use reqwest::blocking::{Client, Response as HttpResponse};
19use reqwest::header::{
20    ACCEPT, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_TYPE, LOCATION, USER_AGENT,
21};
22use reqwest::redirect::Policy;
23use secret_rules::audit::{AuditReason, AuditRecordV1, Decision};
24use secret_rules::location::{
25    evaluate_request_with_connect, location_kind_token, LabelOutcome, LabelRule, Location,
26    RequestView,
27};
28use secret_rules::material::{check_admissible, encode_for_location};
29use secret_rules::scrub::{MatcherSet, ScrubError, Scrubber};
30use secret_rules::target::{normalize_request_target, ConnectAuthority};
31use serde::{Deserialize, Serialize};
32use sha2::{Digest, Sha256};
33use url::Url;
34use zeroize::Zeroizing;
35
36use crate::lang_id::language_by_extension;
37
38#[path = "url_fetch_sensitive.rs"]
39#[cfg(not(any(test, feature = "test-support")))]
40mod sensitive;
41#[path = "url_fetch_sensitive.rs"]
42#[cfg(any(test, feature = "test-support"))]
43pub mod sensitive;
44
45const MAX_RESPONSE_BYTES: u64 = 8 * 1024 * 1024;
46const CACHE_TTL_MS: u64 = 24 * 60 * 60 * 1000;
47/// Longest a request may take to set up its connection (name lookup, TCP
48/// and TLS), within the fetch deadline.
49const CONNECT_TIMEOUT: Duration = Duration::from_millis(10_000);
50/// Longest a request may wait for the response headers, counted from the
51/// start of the request, within the fetch deadline. reqwest applies the same
52/// limit to each later read of the body.
53const HEADERS_TIMEOUT: Duration = Duration::from_millis(15_000);
54const BODY_CHUNK_TIMEOUT: Duration = Duration::from_millis(15_000);
55const MAX_REDIRECTS: usize = 5;
56
57/// Longest one URL fetch may take, whatever budget the call has left. Every
58/// phase (name lookup, connect, response headers, body) shares this one
59/// deadline, so redirects and retries cannot multiply it.
60const URL_FETCH_CEILING: Duration = Duration::from_secs(20);
61/// The last part of the call's budget, kept for building and sending the
62/// reply. Neither the download nor reading the downloaded document back may
63/// use it, so the reply reaches the caller before the call's own deadline.
64pub const URL_REPLY_MARGIN: Duration = Duration::from_secs(1);
65/// The part of the call's budget before the reply margin that the download
66/// leaves for the work after it: converting HTML, writing the cache, and
67/// reading the document back. A download that ends at its deadline still has
68/// this much time for that work.
69const URL_READ_BACK_RESERVE: Duration = Duration::from_secs(2);
70/// The part of the read-back reserve a placeholder fetch's final residual
71/// key check may use, counted from the end of the download deadline. The
72/// rest stays for writing and reading the document back.
73const RESIDUAL_CHECK_RESERVE: Duration = Duration::from_millis(1500);
74/// A transient failure is retried only when the backoff plus at least this
75/// much time for the next attempt still fit before the fetch deadline.
76const MIN_USEFUL_ATTEMPT: Duration = Duration::from_secs(1);
77
78/// Retry budget for transient connect/transport failures only. Agents
79/// shouldn't have to retry manually for a single TCP/TLS hiccup. We cap
80/// at 2 retries (= 3 total attempts) with short jittered backoff so a
81/// genuinely-broken host fails fast instead of dragging the foreground
82/// fetch out to many seconds.
83///
84/// We deliberately do NOT retry on:
85///   - HTTP error status (4xx/5xx) — the server actually answered
86///   - Redirect errors / SSRF rejections — those are deterministic
87///   - Body read stalls — already handled by BODY_CHUNK_TIMEOUT
88const TRANSIENT_RETRY_ATTEMPTS: usize = 2;
89const TRANSIENT_RETRY_BACKOFFS_MS: [u64; TRANSIENT_RETRY_ATTEMPTS] = [200, 600];
90const ACCEPT_HEADER: &str = "application/vnd.github.raw, text/markdown, text/x-markdown, text/html;q=0.9, application/json;q=0.8, text/plain;q=0.5";
91const USER_AGENT_VALUE: &str = "aft-opencode-plugin";
92const CONVERTED_MARKDOWN_CONTENT_TYPE: &str = "text/markdown; charset=utf-8";
93
94#[derive(Clone, Default)]
95pub struct UrlFetchOptions {
96    pub allow_private: bool,
97    /// Test hook: treat a hostname as resolving to these IPs during SSRF validation.
98    /// Production callers leave this empty and use `std::net::ToSocketAddrs`.
99    #[doc(hidden)]
100    pub public_host_overrides: Vec<(String, Vec<IpAddr>)>,
101    /// Test hook: force reqwest to connect a hostname to a local mock server while
102    /// SSRF validation still sees `public_host_overrides` above.
103    #[doc(hidden)]
104    pub connect_overrides: Vec<(String, SocketAddr)>,
105    /// Test hook: observes the temp path immediately before the atomic rename.
106    #[doc(hidden)]
107    pub atomic_write_observer: Option<Arc<dyn Fn(&Path, &Path) + Send + Sync>>,
108    /// Test hook: answers host name lookups in place of the system resolver,
109    /// so a test can stall or redirect name resolution without a network.
110    #[doc(hidden)]
111    pub lookup_override: Option<HostLookup>,
112    /// Test hook: holds every connection attempt this long before it starts
113    /// connecting, standing in for a host that does not answer the connect.
114    #[doc(hidden)]
115    pub connect_delay: Option<Duration>,
116    /// Test hook: the TLS configuration to use instead of the platform
117    /// verifier, so a test can trust a local HTTPS server's certificate.
118    #[doc(hidden)]
119    pub tls_config: Option<rustls::ClientConfig>,
120    #[cfg(all(unix, any(test, feature = "test-support")))]
121    #[doc(hidden)]
122    pub reply_clock_for_test: Option<ReplyClock>,
123}
124
125#[cfg(all(unix, any(test, feature = "test-support")))]
126type ReplyClock = Arc<dyn Fn() -> Instant + Send + Sync>;
127
128/// A host name lookup: the host's addresses, or the lookup's error.
129pub type HostLookup = Arc<dyn Fn(&str) -> io::Result<Vec<IpAddr>> + Send + Sync>;
130
131/// The part of a fetch that was running when its deadline or a stall limit
132/// stopped it.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum FetchPhase {
135    Dns,
136    Connect,
137    Headers,
138    Body,
139}
140
141impl FetchPhase {
142    pub fn as_str(self) -> &'static str {
143        match self {
144            Self::Dns => "dns",
145            Self::Connect => "connect",
146            Self::Headers => "headers",
147            Self::Body => "body",
148        }
149    }
150}
151
152#[derive(Debug, Clone)]
153pub struct UrlFetchError {
154    code: &'static str,
155    message: String,
156    phase: Option<FetchPhase>,
157    /// HTTP status of a server that answered with an error.
158    status: Option<u16>,
159    /// Set on a remembered failure: how long until a call fetches again.
160    retry_after: Option<Duration>,
161    /// Set when the fetch stopped (or never started) only because the
162    /// calling tool call had too little budget left. Such a failure says
163    /// nothing about the server, so it is never remembered.
164    cut_by_call_budget: bool,
165}
166
167impl UrlFetchError {
168    fn new(message: impl Into<String>) -> Self {
169        Self {
170            code: "url_fetch_failed",
171            message: message.into(),
172            phase: None,
173            status: None,
174            retry_after: None,
175            cut_by_call_budget: false,
176        }
177    }
178
179    fn timeout(phase: FetchPhase, message: impl Into<String>) -> Self {
180        Self {
181            code: "url_fetch_timeout",
182            phase: Some(phase),
183            ..Self::new(message)
184        }
185    }
186
187    /// A placeholder fetch refused by its secret rules or the vault, with the
188    /// secret reply code (`secret_refused`, `secrets_unavailable`, ...).
189    fn secret(code: &'static str, message: impl Into<String>) -> Self {
190        Self {
191            code,
192            ..Self::new(message)
193        }
194    }
195
196    /// This error reworded for a refusal that came after a request carrying a
197    /// key was sent; any other error is returned unchanged.
198    fn after_secret_sent(mut self) -> Self {
199        if let Some(rest) = self.message.strip_prefix(SECRET_FETCH_REFUSED) {
200            self.message = format!("{SECRET_FETCH_REFUSED_AFTER_SEND}{rest}");
201        }
202        self
203    }
204
205    fn http_status(status: u16, message: impl Into<String>) -> Self {
206        Self {
207            status: Some(status),
208            ..Self::new(message)
209        }
210    }
211
212    /// Response error code: `url_fetch_timeout` when a deadline or stall
213    /// limit stopped the fetch, otherwise `url_fetch_failed`.
214    pub fn code(&self) -> &'static str {
215        self.code
216    }
217
218    /// The phase a timed-out fetch was in; `None` for other failures.
219    pub fn phase(&self) -> Option<FetchPhase> {
220        self.phase
221    }
222
223    /// For a failure repeated from memory instead of a new fetch, the time
224    /// until a call for the same URL fetches it again.
225    pub fn retry_after(&self) -> Option<Duration> {
226        self.retry_after
227    }
228
229    /// Failures that would very likely repeat on an immediate retry, and
230    /// cost the retry the same wait: timeouts, server errors (5xx), and
231    /// client errors (4xx) other than 408 Request Timeout and 429 Too Many
232    /// Requests. Refusals by the SSRF check and other local errors are cheap
233    /// to reproduce and are not remembered.
234    ///
235    /// Only failures the server or network caused are remembered: a timeout
236    /// cut short by the caller's budget is not, and neither is a failure
237    /// that is itself being repeated from memory.
238    fn worth_remembering(&self) -> bool {
239        if self.cut_by_call_budget || self.retry_after.is_some() {
240            return false;
241        }
242        self.code == "url_fetch_timeout"
243            || self
244                .status
245                .is_some_and(|status| status >= 400 && status != 408 && status != 429)
246    }
247}
248
249/// One deadline for a whole fetch, taken from the call's filesystem budget
250/// (less the read-back reserve and the reply margin) and capped at
251/// [`URL_FETCH_CEILING`]. A call with no budget gets the ceiling.
252#[derive(Debug, Clone, Copy)]
253struct FetchDeadline {
254    at: Instant,
255    allowed: Duration,
256    /// The call's budget, not the URL ceiling, set this deadline: a fetch it
257    /// stops was stopped by the caller, not by a slow server.
258    set_by_call: bool,
259}
260
261impl FetchDeadline {
262    fn for_current_call() -> Self {
263        let now = Instant::now();
264        let ceiling = now + URL_FETCH_CEILING;
265        let at = match crate::bounded_io::current() {
266            Some(budget) => budget
267                .deadline
268                .checked_sub(URL_REPLY_MARGIN + URL_READ_BACK_RESERVE)
269                .unwrap_or(now)
270                .clamp(now, ceiling),
271            None => ceiling,
272        };
273        Self {
274            at,
275            allowed: at.saturating_duration_since(now),
276            set_by_call: at < ceiling,
277        }
278    }
279
280    fn remaining(&self) -> Duration {
281        self.at.saturating_duration_since(Instant::now())
282    }
283
284    fn expired(&self) -> bool {
285        self.remaining().is_zero()
286    }
287
288    fn timeout_error(&self, phase: FetchPhase, url: &str) -> UrlFetchError {
289        UrlFetchError {
290            cut_by_call_budget: self.set_by_call,
291            ..UrlFetchError::timeout(
292                phase,
293                format!(
294                    "URL fetch timed out in the {} phase: the {}ms fetch deadline elapsed fetching {url}",
295                    phase.as_str(),
296                    self.allowed.as_millis()
297                ),
298            )
299        }
300    }
301}
302
303impl fmt::Display for UrlFetchError {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        f.write_str(&self.message)
306    }
307}
308
309impl std::error::Error for UrlFetchError {}
310
311#[derive(Debug, Serialize, Deserialize)]
312struct CacheMeta {
313    url: String,
314    #[serde(rename = "contentType")]
315    content_type: String,
316    extension: String,
317    #[serde(rename = "fetchedAt")]
318    fetched_at: u64,
319    #[serde(default)]
320    download_truncated: bool,
321    #[serde(default)]
322    downloaded_bytes: usize,
323    #[serde(default)]
324    total_bytes: Option<u64>,
325}
326
327pub fn is_http_url(value: &str) -> bool {
328    value.starts_with("http://") || value.starts_with("https://")
329}
330
331/// Fetch `url` into the URL cache under `storage_dir` and return the cached
332/// document's path. A failure worth remembering (see
333/// [`UrlFetchError::worth_remembering`]) is repeated for
334/// [`FAILURE_MEMORY`] instead of a new fetch, so an agent that retries a
335/// page the server failed gets its answer at once instead of waiting again.
336/// A document already in the cache is served regardless.
337pub fn fetch_url_to_cache(
338    url: &str,
339    storage_dir: &Path,
340    options: UrlFetchOptions,
341) -> Result<PathBuf, UrlFetchError> {
342    let key = FailureKey::new(storage_dir, url, options.allow_private);
343    let result = download_to_cache(url, storage_dir, options, &key);
344    record_fetch(&result);
345    match &result {
346        Ok(_) => forget_failure(&key),
347        Err(error) if error.worth_remembering() => remember_failure(key, error),
348        Err(_) => {}
349    }
350    result
351}
352
353/// Count one document asked for in the call's fetch times, with its error.
354fn record_fetch<T>(result: &Result<T, UrlFetchError>) {
355    timing::record(|times| {
356        times.fetches += 1;
357        if let Err(error) = result {
358            times.error = Some((error.code(), error.phase()));
359        }
360    });
361}
362
363/// How long a remembered failure stands in for a new fetch of its URL.
364const FAILURE_MEMORY: Duration = Duration::from_secs(60);
365
366/// A remembered failure is specific to the cache it would have filled and to
367/// whether private addresses were allowed.
368#[derive(Clone, Debug, PartialEq, Eq, Hash)]
369struct FailureKey {
370    storage_dir: PathBuf,
371    url: String,
372    allow_private: bool,
373}
374
375impl FailureKey {
376    fn new(storage_dir: &Path, url: &str, allow_private: bool) -> Self {
377        Self {
378            storage_dir: storage_dir.to_path_buf(),
379            url: url.to_string(),
380            allow_private,
381        }
382    }
383}
384
385struct RememberedFailure {
386    error: UrlFetchError,
387    at: Instant,
388}
389
390/// Remembered failures. Expired entries are dropped on every insert, and a
391/// lookup ignores an entry older than [`FAILURE_MEMORY`].
392fn failure_memory() -> &'static std::sync::Mutex<HashMap<FailureKey, RememberedFailure>> {
393    static FAILURES: std::sync::OnceLock<std::sync::Mutex<HashMap<FailureKey, RememberedFailure>>> =
394        std::sync::OnceLock::new();
395    FAILURES.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
396}
397
398fn remembered_failure(key: &FailureKey) -> Option<UrlFetchError> {
399    let failures = failure_memory()
400        .lock()
401        .unwrap_or_else(std::sync::PoisonError::into_inner);
402    let remembered = failures.get(key)?;
403    let age = remembered.at.elapsed();
404    let retry_after = FAILURE_MEMORY
405        .checked_sub(age)
406        .filter(|left| !left.is_zero())?;
407    let mut error = remembered.error.clone();
408    error.message = format!(
409        "{} (cached failure from {}s ago; this URL is fetched again after {}s)",
410        error.message,
411        age.as_secs(),
412        retry_after.as_secs_f64().ceil() as u64
413    );
414    error.retry_after = Some(retry_after);
415    Some(error)
416}
417
418fn remember_failure(key: FailureKey, error: &UrlFetchError) {
419    let mut failures = failure_memory()
420        .lock()
421        .unwrap_or_else(std::sync::PoisonError::into_inner);
422    failures.retain(|_, remembered| remembered.at.elapsed() < FAILURE_MEMORY);
423    failures.insert(
424        key,
425        RememberedFailure {
426            error: error.clone(),
427            at: Instant::now(),
428        },
429    );
430}
431
432fn forget_failure(key: &FailureKey) {
433    failure_memory()
434        .lock()
435        .unwrap_or_else(std::sync::PoisonError::into_inner)
436        .remove(key);
437}
438
439/// Test hook: a document-cache read under `storage_dir` that blocks until
440/// released (or for at most 10 s, so a broken test cannot hang the suite),
441/// standing in for a cache filesystem that stops answering.
442#[cfg(any(test, feature = "test-support"))]
443#[derive(Default)]
444struct CacheReadStall {
445    reached: std::sync::atomic::AtomicUsize,
446    released: std::sync::Mutex<bool>,
447    release: std::sync::Condvar,
448}
449
450#[cfg(any(test, feature = "test-support"))]
451impl CacheReadStall {
452    #[cfg_attr(not(test), allow(dead_code))]
453    fn release(&self) {
454        *self.released.lock().unwrap() = true;
455        self.release.notify_all();
456    }
457}
458
459#[cfg(any(test, feature = "test-support"))]
460fn cache_read_stalls() -> &'static std::sync::Mutex<HashMap<PathBuf, Arc<CacheReadStall>>> {
461    static STALLS: std::sync::OnceLock<std::sync::Mutex<HashMap<PathBuf, Arc<CacheReadStall>>>> =
462        std::sync::OnceLock::new();
463    STALLS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
464}
465
466#[cfg(any(test, feature = "test-support"))]
467#[cfg_attr(not(test), allow(dead_code))]
468fn stall_cache_reads(storage_dir: &Path) -> Arc<CacheReadStall> {
469    let stall = Arc::new(CacheReadStall::default());
470    cache_read_stalls()
471        .lock()
472        .unwrap()
473        .insert(storage_dir.to_path_buf(), Arc::clone(&stall));
474    stall
475}
476
477#[cfg(any(test, feature = "test-support"))]
478fn stall_cache_read_if_requested(storage_dir: &Path) {
479    let Some(stall) = cache_read_stalls()
480        .lock()
481        .unwrap()
482        .get(storage_dir)
483        .cloned()
484    else {
485        return;
486    };
487    stall
488        .reached
489        .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
490    let released = stall.released.lock().unwrap();
491    let _ = stall
492        .release
493        .wait_timeout_while(released, Duration::from_secs(10), |released| !*released);
494}
495
496/// Test hook: make one remembered failure `by` older.
497#[cfg(any(test, feature = "test-support"))]
498#[cfg_attr(not(test), allow(dead_code))]
499fn age_remembered_failure(key: &FailureKey, by: Duration) {
500    if let Some(remembered) = failure_memory()
501        .lock()
502        .unwrap_or_else(std::sync::PoisonError::into_inner)
503        .get_mut(key)
504    {
505        remembered.at = remembered
506            .at
507            .checked_sub(by)
508            .expect("clock far enough along");
509    }
510}
511
512/// What a document-cache check needs, owned so a helper thread can run it.
513struct CacheCheckInput {
514    storage_dir: PathBuf,
515    hash: String,
516    meta_file: PathBuf,
517    url: Url,
518}
519
520type CacheCheckResult = Result<Option<PathBuf>, UrlFetchError>;
521
522/// A document-cache check running on a helper thread. Calls that find one
523/// running for their URL wait for it instead of starting another, so a cache
524/// filesystem that stops answering holds at most one thread per URL.
525#[derive(Default)]
526struct CacheCheck {
527    result: std::sync::Mutex<Option<CacheCheckResult>>,
528    done: std::sync::Condvar,
529}
530
531fn cache_checks() -> &'static std::sync::Mutex<HashMap<FailureKey, Arc<CacheCheck>>> {
532    static CHECKS: std::sync::OnceLock<std::sync::Mutex<HashMap<FailureKey, Arc<CacheCheck>>>> =
533        std::sync::OnceLock::new();
534    CHECKS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
535}
536
537/// The latest a bounded cache check may answer: the call's deadline less the
538/// reply margin, or the URL ceiling for a call without a budget.
539fn cache_check_deadline() -> Instant {
540    let now = Instant::now();
541    let ceiling = now + URL_FETCH_CEILING;
542    match crate::bounded_io::current() {
543        Some(budget) => budget
544            .deadline
545            .checked_sub(URL_REPLY_MARGIN)
546            .unwrap_or(now)
547            .clamp(now, ceiling),
548        None => ceiling,
549    }
550}
551
552/// Run (or join) the document-cache check for `key` and wait for it until
553/// `deadline`. `Ok(None)` means no usable cached copy, including a check
554/// that did not finish in time.
555fn bounded_cache_check(
556    key: &FailureKey,
557    input: CacheCheckInput,
558    deadline: Instant,
559) -> CacheCheckResult {
560    let check = {
561        let mut checks = cache_checks()
562            .lock()
563            .unwrap_or_else(std::sync::PoisonError::into_inner);
564        match checks.get(key) {
565            Some(running) => Arc::clone(running),
566            None => {
567                let check = Arc::new(CacheCheck::default());
568                checks.insert(key.clone(), Arc::clone(&check));
569                let worker = Arc::clone(&check);
570                let worker_key = key.clone();
571                thread::spawn(move || {
572                    let result = fresh_cached_path(
573                        &input.storage_dir,
574                        &input.hash,
575                        &input.meta_file,
576                        &input.url,
577                    );
578                    *worker
579                        .result
580                        .lock()
581                        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(result);
582                    worker.done.notify_all();
583                    cache_checks()
584                        .lock()
585                        .unwrap_or_else(std::sync::PoisonError::into_inner)
586                        .remove(&worker_key);
587                });
588                check
589            }
590        }
591    };
592    let mut result = check
593        .result
594        .lock()
595        .unwrap_or_else(std::sync::PoisonError::into_inner);
596    loop {
597        if let Some(result) = result.as_ref() {
598            return result.clone();
599        }
600        let left = deadline.saturating_duration_since(Instant::now());
601        if left.is_zero() {
602            return Ok(None);
603        }
604        result = check
605            .done
606            .wait_timeout(result, left)
607            .unwrap_or_else(std::sync::PoisonError::into_inner)
608            .0;
609    }
610}
611
612/// A document that is cached is served (after the SSRF check) even while a
613/// failure of the same URL is remembered; only a cache miss is answered by a
614/// remembered failure. With a failure remembered, the call waits for the
615/// cache check only until its deadline less the reply margin; a check still
616/// running then counts as a miss, and its helper thread may run on.
617fn download_to_cache(
618    url: &str,
619    storage_dir: &Path,
620    options: UrlFetchOptions,
621    failure_key: &FailureKey,
622) -> Result<PathBuf, UrlFetchError> {
623    let parsed = Url::parse(url).map_err(|_| UrlFetchError::new(format!("Invalid URL: {url}")))?;
624    let deadline = FetchDeadline::for_current_call();
625    let fetch_url = rewrite_url_for_fetch(&parsed);
626    let approved = Arc::new(ApprovedHosts::default());
627    let hash = hash_url(url);
628    let meta_file = meta_path(storage_dir, &hash);
629
630    // With a failure remembered, the answer is already in memory, so the call
631    // must not wait on the cache check past its deadline; the check runs on
632    // a helper thread that may outlive the call. No directory is created:
633    // nothing will be written.
634    if let Some(remembered) = remembered_failure(failure_key) {
635        let check = CacheCheckInput {
636            storage_dir: storage_dir.to_path_buf(),
637            hash,
638            meta_file,
639            url: fetch_url.clone(),
640        };
641        let Some(cached) = bounded_cache_check(failure_key, check, cache_check_deadline())? else {
642            timing::record(|times| times.remembered_failures += 1);
643            return Err(remembered);
644        };
645        validate_public_url(&fetch_url, &options, &deadline, &approved)?;
646        timing::record(|times| times.cache_hits += 1);
647        return Ok(cached);
648    }
649
650    let dir = cache_dir(storage_dir);
651    crate::private_storage::open_dir(storage_dir, &dir).map_err(|error| {
652        UrlFetchError::new(format!(
653            "Failed to create URL cache directory {}: {error}",
654            dir.display()
655        ))
656    })?;
657
658    let cached = fresh_cached_path(storage_dir, &hash, &meta_file, &fetch_url)?;
659    // A cache hit is checked too: the request may refuse private addresses
660    // that the call which filled the cache allowed.
661    validate_public_url(&fetch_url, &options, &deadline, &approved)?;
662    if let Some(cached) = cached {
663        timing::record(|times| times.cache_hits += 1);
664        return Ok(cached);
665    }
666
667    let response = fetch_with_redirects(&fetch_url, url, &options, &deadline, approved)?;
668    if !response.status().is_success() {
669        return Err(UrlFetchError::http_status(
670            response.status().as_u16(),
671            format!(
672                "HTTP {} {} fetching {url}",
673                response.status().as_u16(),
674                response.status().canonical_reason().unwrap_or("")
675            ),
676        ));
677    }
678
679    let content_type = response
680        .headers()
681        .get(CONTENT_TYPE)
682        .and_then(|value| value.to_str().ok())
683        .unwrap_or("text/plain")
684        .to_string();
685    let (extension, from_source_path) =
686        resolve_fetch_extension(&fetch_url, &content_type).ok_or_else(|| {
687            UrlFetchError::new(format!(
688                "Unsupported content type '{content_type}' for {url}. Supported: text/html, text/markdown, application/json, text/plain; source files via URL path extension (e.g. .rs, .ts, .mjs)"
689            ))
690        })?;
691
692    let total_bytes = response.content_length();
693    let (mut body, download_truncated) = read_response_body(response, url, &deadline)?;
694    let downloaded_bytes = body.len();
695    // A byte ceiling can bisect the final UTF-8 character. Do not turn an
696    // otherwise valid document prefix into an unreadable cache entry.
697    if download_truncated {
698        if let Err(error) = std::str::from_utf8(&body) {
699            if error.error_len().is_none() {
700                body.truncate(error.valid_up_to());
701            }
702        }
703    }
704    if from_source_path && body_contains_nul_in_prefix(&body) {
705        return Err(UrlFetchError::new(format!(
706            "Binary content detected for source URL {url}"
707        )));
708    }
709    let (body, content_type, extension) = if extension == ".html" {
710        (
711            convert_html_body_to_markdown(&body, url)?,
712            CONVERTED_MARKDOWN_CONTENT_TYPE.to_string(),
713            ".md",
714        )
715    } else {
716        (body, content_type, extension)
717    };
718
719    let content_file = content_path(storage_dir, &hash, extension);
720    atomic_write(&content_file, &body, &options)?;
721
722    let meta = CacheMeta {
723        url: url.to_string(),
724        content_type,
725        extension: extension.to_string(),
726        fetched_at: now_ms(),
727        download_truncated,
728        downloaded_bytes,
729        total_bytes,
730    };
731    let meta_bytes = serde_json::to_vec(&meta).map_err(|error| {
732        UrlFetchError::new(format!("Failed to encode URL cache metadata: {error}"))
733    })?;
734    atomic_write(&meta_file, &meta_bytes, &options)?;
735
736    Ok(content_file)
737}
738
739/// The fresh cached copy of `url` under `storage_dir`, if there is one. Reads
740/// only: it creates no folder, writes nothing and downloads nothing. The cache
741/// check is bounded by the call's deadline like a remembered failure's (a
742/// stalled cache drive counts as a miss), and a cached copy passes the same
743/// scheme and private-address checks as a download before it is served.
744pub fn cached_url_document(
745    url: &str,
746    storage_dir: &Path,
747    options: &UrlFetchOptions,
748) -> Result<Option<PathBuf>, UrlFetchError> {
749    let parsed = Url::parse(url).map_err(|_| UrlFetchError::new(format!("Invalid URL: {url}")))?;
750    let deadline = FetchDeadline::for_current_call();
751    let fetch_url = rewrite_url_for_fetch(&parsed);
752    let hash = hash_url(url);
753    let check = CacheCheckInput {
754        storage_dir: storage_dir.to_path_buf(),
755        meta_file: meta_path(storage_dir, &hash),
756        hash,
757        url: fetch_url.clone(),
758    };
759    let key = FailureKey::new(storage_dir, url, options.allow_private);
760    let Some(cached) = bounded_cache_check(&key, check, cache_check_deadline())? else {
761        return Ok(None);
762    };
763    validate_public_url(&fetch_url, options, &deadline, &ApprovedHosts::default())?;
764    timing::record(|times| times.cache_hits += 1);
765    Ok(Some(cached))
766}
767
768/// Folder, under the cache root, that holds the private per-call folders of
769/// placeholder fetches. It is a sibling of the URL cache, never inside it.
770pub const SECRET_FETCH_DIR: &str = "url_secret_fetch";
771
772/// The start of every refusal a placeholder fetch makes on its own (as opposed
773/// to a refusal the vault decided) before any request carrying a key was sent.
774/// One constant so the wording is reviewed once; the message goes on to name a
775/// stable reason token and the URL as the agent wrote it, with the
776/// placeholder and never a key.
777pub const SECRET_FETCH_REFUSED: &str =
778    "Secret placeholder fetch refused; no request carrying the secret was sent";
779
780#[rustfmt::skip]
781test_support_visibility! {
782/// The start of the same refusals once a request carrying a key has been sent:
783/// the response (or a later hop) was refused, so the claim above would be
784/// false.
785pub(crate) const SECRET_FETCH_REFUSED_AFTER_SEND: &str =
786    "Secret placeholder fetch stopped after a request carrying the secret was sent; its response was not used";
787}
788
789/// A stand-in key used only to plan where a placeholder fetch would
790/// substitute. Real vault bytes are asked for only once a rule matches.
791const SECRET_PLANNING_KEY: &[u8] = b"url-fetch-planning-value-0000";
792
793/// The most content codings a placeholder fetch decodes from one response.
794const MAX_SECRET_CODINGS: usize = 4;
795
796/// Every label of a well-formed placeholder in `url`, in order and without
797/// repeats, or `None` when the URL mentions no placeholder at all.
798///
799/// A percent-encoded placeholder counts as well as a literal one, because a
800/// query value is compared after decoding. `Some` with no labels means the URL
801/// mentions the placeholder prefix only in a malformed way: such a URL still
802/// takes the placeholder path (no cache, no web-view rewrite), it just has
803/// nothing to substitute.
804pub fn secret_labels_in_url(url: &str) -> Option<Vec<String>> {
805    if !secret_rules::placeholder::contains_placeholder_prefix_loose(url) {
806        return None;
807    }
808    let decoded = percent_decode_path_segment(url);
809    let mut labels: Vec<String> = Vec::new();
810    for text in [url, decoded.as_str()] {
811        for placeholder in secret_rules::placeholder::scan(text) {
812            if !labels.iter().any(|label| label == placeholder.label) {
813                labels.push(placeholder.label.to_string());
814            }
815        }
816    }
817    Some(labels)
818}
819
820/// Create the private folder one placeholder fetch writes its document into,
821/// under `storage_dir` but outside the URL cache. The caller owns the folder
822/// and deletes it when its call returns.
823pub fn create_secret_fetch_dir(storage_dir: &Path) -> Result<PathBuf, UrlFetchError> {
824    let parent = storage_dir.join(SECRET_FETCH_DIR);
825    let failed = |error: io::Error| {
826        UrlFetchError::new(format!(
827            "Failed to create a private folder for a placeholder fetch under {}: {error}",
828            parent.display()
829        ))
830    };
831    crate::private_storage::open_dir(storage_dir, &parent).map_err(failed)?;
832    let dir = parent.join(random_nonce());
833    // `create_dir` fails when the folder exists, so no other call shares it.
834    crate::private_storage::create_dir(&dir).map_err(failed)?;
835    Ok(dir)
836}
837
838/// What a placeholder fetch may do with its secrets.
839pub struct SecretFetch {
840    /// The vault each addressed request and audit record go to.
841    pub vault: Arc<dyn crate::secret::SecretVault>,
842    /// The call's authorization scope; `None` only when the URL holds no
843    /// well-formed placeholder, in which case nothing is resolved or audited.
844    pub authorization: Option<crate::secret::SecretScope>,
845    /// Every label found in the URL, in order.
846    pub labels: Vec<String>,
847    /// Map an ephemeral test upstream to the vault's HTTPS/443 target.
848    #[cfg(any(test, feature = "test-support"))]
849    pub test_https_port: Option<u16>,
850    /// The fetch call's id: audit records name it, plus the hop index.
851    pub call_id: String,
852    /// The foreground call's cancellation and absolute reply deadline.
853    pub cancellation: SecretFetchCancellation,
854}
855
856impl SecretFetch {
857    // Cargo feature unification can change test-only fields; keep the constructor signature fixed.
858    pub fn new(
859        vault: Arc<dyn crate::secret::SecretVault>,
860        authorization: Option<crate::secret::SecretScope>,
861        labels: Vec<String>,
862        test_https_port: Option<u16>,
863        call_id: String,
864        cancellation: SecretFetchCancellation,
865    ) -> Self {
866        #[cfg(not(any(test, feature = "test-support")))]
867        let _ = test_https_port;
868        Self {
869            vault,
870            authorization,
871            labels,
872            #[cfg(any(test, feature = "test-support"))]
873            test_https_port,
874            call_id,
875            cancellation,
876        }
877    }
878}
879
880#[derive(Clone, Default)]
881pub struct SecretFetchCancellation {
882    job: Option<crate::executor::JobCancellation>,
883    deadline: Option<Instant>,
884    #[cfg(all(unix, any(test, feature = "test-support")))]
885    clock: Option<ReplyClock>,
886}
887impl SecretFetchCancellation {
888    pub fn for_current_call(_options: &UrlFetchOptions) -> Self {
889        Self {
890            job: crate::executor::current_job_cancellation(),
891            deadline: crate::secret::call_context::current_fetch_reply_deadline(),
892            #[cfg(all(unix, any(test, feature = "test-support")))]
893            clock: _options.reply_clock_for_test.clone(),
894        }
895    }
896    fn now(&self) -> Instant {
897        #[cfg(all(unix, any(test, feature = "test-support")))]
898        if let Some(clock) = &self.clock {
899            return clock();
900        }
901        Instant::now()
902    }
903    pub(crate) fn is_cancelled(&self) -> bool {
904        self.reason().is_some()
905    }
906    pub(crate) fn reason(&self) -> Option<crate::secret::requests::UseError> {
907        self.job
908            .as_ref()
909            .is_some_and(|job| job.cancel_requested_before_commit())
910            .then_some(crate::secret::requests::UseError::Cancelled)
911            .or_else(|| {
912                self.deadline
913                    .is_some_and(|at| self.now() >= at)
914                    .then_some(crate::secret::requests::UseError::Expired)
915            })
916    }
917    pub(crate) async fn cancelled(&self) {
918        loop {
919            if self.is_cancelled() {
920                return;
921            }
922            let delay = self.deadline.map_or(Duration::from_millis(25), |deadline| {
923                deadline
924                    .saturating_duration_since(self.now())
925                    .min(Duration::from_millis(25))
926            });
927            tokio::time::sleep(delay).await;
928        }
929    }
930}
931
932#[rustfmt::skip]
933test_support_visibility! {
934/// Keys the vault released during one placeholder fetch. They are kept, wiped
935/// on drop, only until the fetch returns, so every header and body read after
936/// a key was sent is scrubbed of it.
937/// These retained bytes are scrub patterns, never authorization or material
938/// for another send; every request obtains its own release from the vault.
939#[derive(Default)]
940pub(crate) struct HeldKeys(Vec<(String, Zeroizing<Vec<u8>>)>);
941}
942
943impl HeldKeys {
944    fn matchers(&self) -> Result<Vec<MatcherSet>, ScrubError> {
945        self.0
946            .iter()
947            .map(|(label, key)| MatcherSet::new(label, key))
948            .collect()
949    }
950
951    #[rustfmt::skip]
952    test_support_visibility! {
953
954    /// Hold `key` for `label`, refusing a key whose matcher would collide with
955    /// one already held (the scrubber could then write one key into a reply).
956    pub(crate) fn hold(&mut self, label: &str, key: &[u8]) -> Result<(), ScrubError> {
957        if self
958            .0
959            .iter()
960            .any(|(held, bytes)| held == label && bytes.as_slice() == key)
961        {
962            return Ok(());
963        }
964        let mut matchers = self.matchers()?;
965        matchers.push(MatcherSet::new(label, key)?);
966        Scrubber::new(matchers)?;
967        self.0
968            .push((label.to_string(), Zeroizing::new(key.to_vec())));
969        Ok(())
970    }
971    }
972
973    /// `bytes` with every held key replaced by its label's placeholder.
974    fn scrub(&self, bytes: &[u8]) -> Result<Vec<u8>, ScrubError> {
975        let mut scrubber = Scrubber::new(self.matchers()?)?;
976        let mut clean = scrubber.push(bytes);
977        clean.extend_from_slice(&scrubber.finish());
978        Ok(clean)
979    }
980
981    fn keys(&self) -> Vec<&[u8]> {
982        self.0.iter().map(|(_, key)| key.as_slice()).collect()
983    }
984
985    /// Error text from a library (reqwest, the decoders) with every held key
986    /// replaced by its placeholder. Text that still spells a key after that,
987    /// or that cannot be scrubbed, is dropped whole.
988    pub(crate) fn sanitize_detail(&self, detail: &str) -> String {
989        let deadline = Instant::now() + DETAIL_CHECK_LIMIT;
990        match self.scrub(detail.as_bytes()) {
991            Ok(clean) if self.reveal(&clean, deadline).is_clean() => {
992                String::from_utf8_lossy(&clean).into_owned()
993            }
994            _ => String::new(),
995        }
996    }
997
998    /// Whether `bytes` still spell a held key, as they stand or after a URL
999    /// parser or reader normalizes them, checked until `deadline` (see
1000    /// [`secret_rules::reveal_outcome`]).
1001    fn reveal(&self, bytes: &[u8], deadline: Instant) -> secret_rules::RevealOutcome {
1002        secret_rules::reveal_outcome(bytes, &self.keys(), Some(deadline))
1003    }
1004}
1005
1006/// The longest the residual check of a library error's text may run; such
1007/// text is short, and text the check cannot clear in time is dropped.
1008const DETAIL_CHECK_LIMIT: Duration = Duration::from_millis(100);
1009
1010/// Refuse unless the residual check found `bytes` clean: `found` names the
1011/// refusal when a key was spelled, and a check that could not finish refuses
1012/// as exhausted or timed out.
1013fn refuse_unless_clean(
1014    outcome: secret_rules::RevealOutcome,
1015    found: &str,
1016    url: &str,
1017) -> Result<(), UrlFetchError> {
1018    match outcome {
1019        secret_rules::RevealOutcome::Clean => Ok(()),
1020        secret_rules::RevealOutcome::Found => Err(secret_fetch_refused(found, url)),
1021        secret_rules::RevealOutcome::Exhausted => {
1022            Err(secret_fetch_refused("residual_check_exhausted", url))
1023        }
1024        secret_rules::RevealOutcome::OutOfTime => {
1025            Err(secret_fetch_refused("residual_check_timeout", url))
1026        }
1027    }
1028}
1029
1030fn secret_fetch_refused(reason: &str, url: &str) -> UrlFetchError {
1031    UrlFetchError::secret(
1032        crate::secret::SECRET_REFUSED,
1033        format!("{SECRET_FETCH_REFUSED} ({reason}): {url}"),
1034    )
1035}
1036
1037fn scrub_refusal(url: &str) -> impl Fn(ScrubError) -> UrlFetchError + '_ {
1038    move |_| secret_fetch_refused("scrubber_unavailable", url)
1039}
1040
1041/// Fetch `logical_url`, a URL that mentions a secret placeholder, into
1042/// `document_dir` and return the converted document's path.
1043///
1044/// The URL cache is never read or written, and the web-view rewrite is
1045/// skipped, so the URL the vault's rule is matched against is the one the
1046/// agent gave. Every hop, redirects included, is checked against the private
1047/// address policy and then evaluated from scratch against the granted rules:
1048/// only a hop a rule covers gets a copy of the URL with the key in its query.
1049/// Every response header this function reads (`Location` first of all) and
1050/// the body are scrubbed of each key released so far before they are used, and
1051/// every message names `logical_url` (or a scrubbed redirect target), never a
1052/// URL that held a key.
1053pub fn fetch_url_with_secrets(
1054    logical_url: &str,
1055    document_dir: &Path,
1056    options: UrlFetchOptions,
1057    secrets: &SecretFetch,
1058) -> Result<PathBuf, UrlFetchError> {
1059    let key_sent = std::cell::Cell::new(false);
1060    let result = fetch_with_secrets(logical_url, document_dir, options, secrets, &key_sent)
1061        .map_err(|error| {
1062            // A refusal written as "nothing was sent" is reworded once a request
1063            // carrying the key has gone out.
1064            if key_sent.get() {
1065                error.after_secret_sent()
1066            } else {
1067                error
1068            }
1069        });
1070    record_fetch(&result);
1071    result
1072}
1073
1074/// [`fetch_url_with_secrets`], recording in `key_sent` when a request that
1075/// carried a key has been sent (or attempted).
1076fn fetch_with_secrets(
1077    logical_url: &str,
1078    document_dir: &Path,
1079    options: UrlFetchOptions,
1080    secrets: &SecretFetch,
1081    key_sent: &std::cell::Cell<bool>,
1082) -> Result<PathBuf, UrlFetchError> {
1083    let mut current = Url::parse(logical_url)
1084        .map_err(|_| UrlFetchError::new(format!("Invalid URL: {logical_url}")))?;
1085    // A fragment never reaches a server, and a rule never matches one.
1086    current.set_fragment(None);
1087    let start = current.clone();
1088    let mut deadline = FetchDeadline::for_current_call();
1089    let approved = Arc::new(ApprovedHosts::default());
1090    let progress = Arc::new(ConnectProgress::default());
1091    let client = build_client(
1092        &options,
1093        Arc::clone(&approved),
1094        Arc::clone(&progress),
1095        false,
1096        Some(secrets.cancellation.clone()),
1097    )?;
1098    let mut held = HeldKeys::default();
1099    let mut hop = 0;
1100    let response = loop {
1101        if secrets.cancellation.is_cancelled() {
1102            return Err(secret_fetch_refused("missing_material", logical_url));
1103        }
1104        validate_public_url(&current, &options, &deadline, &approved)?;
1105        let waiting = Instant::now();
1106        let outbound = secret_hop(&current, hop, secrets, &mut held)?;
1107        // Approval is a separate person-wait budget, not network time.
1108        let waited = waiting.elapsed();
1109        deadline.at += waited;
1110        crate::bounded_io::exclude_secret_approval_wait(waited);
1111        let sent = send_request(
1112            &client,
1113            &current,
1114            Some(SecretSend {
1115                shown: current.as_str(),
1116                held: &held,
1117                released: outbound.is_some(),
1118                cancellation: &secrets.cancellation,
1119                key_sent,
1120                outbound: outbound.as_ref(),
1121            }),
1122            &deadline,
1123            &progress,
1124        );
1125        // Wipe this function's copy of the key-bearing URL now that it is sent.
1126        drop(outbound);
1127        let response = sent?;
1128        if !response.status().is_redirection() {
1129            break response;
1130        }
1131        if hop == MAX_REDIRECTS {
1132            return Err(UrlFetchError::new(format!(
1133                "Too many redirects fetching {logical_url}"
1134            )));
1135        }
1136        // A control byte never belongs in a Location, and URL parsing would
1137        // drop some of them (a tab), joining text the scrubber saw apart.
1138        if response.headers().get_all(LOCATION).iter().any(|value| {
1139            value
1140                .as_bytes()
1141                .iter()
1142                .any(|byte| *byte < 0x20 || *byte == 0x7f)
1143        }) {
1144            return Err(secret_fetch_refused("redirect_control_byte", logical_url));
1145        }
1146        let location = scrubbed_header(&response, LOCATION, &held, logical_url, &deadline)?
1147            .filter(|value| value.bytes().all(|byte| (0x20..0x7f).contains(&byte)))
1148            .ok_or_else(|| {
1149                UrlFetchError::new(format!(
1150                    "Redirect from {} missing Location header",
1151                    current.as_str()
1152                ))
1153            })?;
1154        let mut next = current.join(&location).map_err(|error| {
1155            UrlFetchError::new(format!(
1156                "Invalid redirect Location '{location}' from {}: {error}",
1157                current.as_str()
1158            ))
1159        })?;
1160        next.set_fragment(None);
1161        // Joining normalizes the URL (dot segments collapse, the host is
1162        // lowercased, escapes are kept), which can reassemble a key the
1163        // header scrub did not see. Check the URL exactly as it will be
1164        // looked up, sent and named, before any of that happens.
1165        refuse_unless_clean(
1166            held.reveal(next.as_str().as_bytes(), header_check_deadline(&deadline)),
1167            "redirect_discloses_key",
1168            logical_url,
1169        )?;
1170        current = next;
1171        hop += 1;
1172        timing::record(|times| times.redirects += 1);
1173    };
1174
1175    let status = response.status();
1176    if !status.is_success() {
1177        return Err(UrlFetchError::http_status(
1178            status.as_u16(),
1179            format!(
1180                "HTTP {} {} fetching {logical_url}",
1181                status.as_u16(),
1182                status.canonical_reason().unwrap_or("")
1183            ),
1184        ));
1185    }
1186    let content_type = scrubbed_header(&response, CONTENT_TYPE, &held, logical_url, &deadline)?
1187        .unwrap_or_else(|| "text/plain".to_string());
1188    // `HeaderMap::get` reads only the first field. A second Content-Encoding
1189    // field could name a coding behind an `identity` first one, so repeated
1190    // fields refuse the response rather than being read in part.
1191    if response.headers().get_all(CONTENT_ENCODING).iter().count() > 1 {
1192        return Err(secret_fetch_refused("content_encoding", logical_url));
1193    }
1194    let codings = match scrubbed_header(&response, CONTENT_ENCODING, &held, logical_url, &deadline)?
1195    {
1196        Some(value) => secret_content_codings(&value, logical_url)?,
1197        None if response.headers().contains_key(CONTENT_ENCODING) => {
1198            return Err(secret_fetch_refused("content_encoding", logical_url));
1199        }
1200        None => Vec::new(),
1201    };
1202    let (extension, from_source_path) = resolve_fetch_extension(&start, &content_type)
1203        .ok_or_else(|| {
1204            UrlFetchError::new(format!(
1205                "Unsupported content type '{content_type}' for {logical_url}. Supported: text/html, text/markdown, application/json, text/plain; source files via URL path extension (e.g. .rs, .ts, .mjs)"
1206            ))
1207        })?;
1208    // An HTML response is converted whatever its path says (an index.php
1209    // page, or a .json endpoint answering with an HTML error page). Kept raw,
1210    // its markup would hide a key split across tags or spelled with entities
1211    // from the scrub while any browser shows it; converted, the residual
1212    // check below sees the text a reader sees.
1213    let is_html =
1214        extension == ".html" || resolve_extension_from_content_type(&content_type) == Some(".html");
1215    let total_bytes = codings
1216        .is_empty()
1217        .then(|| response.content_length())
1218        .flatten();
1219    // A failed read's text comes from reqwest and may name the request URL,
1220    // which held the key; it is scrubbed like everything else read back.
1221    let sanitize = |detail: &str| held.sanitize_detail(detail);
1222    #[cfg(any(test, feature = "test-support"))]
1223    let response: Box<dyn Read + Send> =
1224        match TEST_BODY_READ_ERROR.with(|slot| slot.borrow().clone()) {
1225            Some(message) => Box::new(FailingBody(message)),
1226            None => Box::new(response),
1227        };
1228    let (raw, mut download_truncated) =
1229        read_response_body_with(response, logical_url, &deadline, &sanitize)?;
1230    let decoded = decode_secret_body(&raw, &codings, &mut download_truncated, logical_url)?;
1231    let mut body = held.scrub(&decoded).map_err(scrub_refusal(logical_url))?;
1232    drop(decoded);
1233    let downloaded_bytes = body.len();
1234    if download_truncated {
1235        if let Err(error) = std::str::from_utf8(&body) {
1236            if error.error_len().is_none() {
1237                body.truncate(error.valid_up_to());
1238            }
1239        }
1240    }
1241    if from_source_path && !is_html && body_contains_nul_in_prefix(&body) {
1242        return Err(UrlFetchError::new(format!(
1243            "Binary content detected for source URL {logical_url}"
1244        )));
1245    }
1246    let (body, content_type, extension) = if is_html {
1247        // Converting HTML can decode entities into new text, so the converted
1248        // document is scrubbed again before it is written.
1249        let markdown = convert_html_body_to_markdown(&body, logical_url)?;
1250        (
1251            held.scrub(&markdown).map_err(scrub_refusal(logical_url))?,
1252            CONVERTED_MARKDOWN_CONTENT_TYPE.to_string(),
1253            ".md",
1254        )
1255    } else {
1256        (body, content_type, extension)
1257    };
1258
1259    // The scrub replaced every spelling it recognised, but conversion and
1260    // plain readers undo more (a Markdown-escaped `\*`, an HTML entity kept in
1261    // a page served under a source path). A document that still spells a held
1262    // key after those is refused, never written; so is one the check could
1263    // not finish, within its work budget or before its share of the call's
1264    // read-back reserve ran out.
1265    refuse_unless_clean(
1266        held.reveal(&body, residual_check_deadline(&deadline)),
1267        "document_discloses_key",
1268        logical_url,
1269    )?;
1270    let content_file = document_dir.join(format!("document{extension}"));
1271    write_secret_document(&content_file, &body)?;
1272    // The metadata sits where `download_notice` looks for it, so a truncated
1273    // download is disclosed exactly as a cached one is.
1274    let meta = CacheMeta {
1275        url: logical_url.to_string(),
1276        content_type,
1277        extension: extension.to_string(),
1278        fetched_at: now_ms(),
1279        download_truncated,
1280        downloaded_bytes,
1281        total_bytes,
1282    };
1283    let meta_bytes = serde_json::to_vec(&meta).map_err(|error| {
1284        UrlFetchError::new(format!("Failed to encode URL fetch metadata: {error}"))
1285    })?;
1286    write_secret_document(&content_file.with_extension("meta.json"), &meta_bytes)?;
1287    Ok(content_file)
1288}
1289
1290fn write_secret_document(path: &Path, bytes: &[u8]) -> Result<(), UrlFetchError> {
1291    crate::private_storage::write(path, bytes).map_err(|error| {
1292        UrlFetchError::new(format!(
1293            "Failed to write placeholder fetch document {}: {error}",
1294            path.display()
1295        ))
1296    })
1297}
1298
1299/// A response header's value, scrubbed of every held key before anything
1300/// reads it; `None` when the header is absent or not text.
1301fn scrubbed_header(
1302    response: &HttpResponse,
1303    name: reqwest::header::HeaderName,
1304    held: &HeldKeys,
1305    url: &str,
1306    deadline: &FetchDeadline,
1307) -> Result<Option<String>, UrlFetchError> {
1308    let Some(value) = response.headers().get(&name) else {
1309        return Ok(None);
1310    };
1311    let clean = held.scrub(value.as_bytes()).map_err(scrub_refusal(url))?;
1312    // The scrubbed value is read, joined or quoted next; a key it still
1313    // spells in a form the scrub missed refuses the response instead.
1314    refuse_unless_clean(
1315        held.reveal(&clean, header_check_deadline(deadline)),
1316        "header_discloses_key",
1317        url,
1318    )?;
1319    Ok(String::from_utf8(clean).ok())
1320}
1321
1322#[cfg(any(test, feature = "test-support"))]
1323thread_local! {
1324    /// When set, a placeholder fetch's body read fails with this text, so a
1325    /// test can check what the call site does with a library error.
1326    static TEST_BODY_READ_ERROR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
1327}
1328
1329/// Make this thread's placeholder fetches fail their body read with
1330/// `message` until the returned guard drops.
1331#[cfg(any(test, feature = "test-support"))]
1332pub fn inject_secret_body_read_error_for_test(message: String) -> impl Drop {
1333    struct Restore;
1334    impl Drop for Restore {
1335        fn drop(&mut self) {
1336            TEST_BODY_READ_ERROR.with(|slot| slot.replace(None));
1337        }
1338    }
1339    TEST_BODY_READ_ERROR.with(|slot| slot.replace(Some(message)));
1340    Restore
1341}
1342
1343/// A response body whose every read fails with the injected text.
1344#[cfg(any(test, feature = "test-support"))]
1345struct FailingBody(String);
1346
1347#[cfg(any(test, feature = "test-support"))]
1348impl Read for FailingBody {
1349    fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1350        Err(io::Error::other(self.0.clone()))
1351    }
1352}
1353
1354/// When a placeholder fetch's final residual key check must stop: its share
1355/// of the read-back reserve after the download deadline, or sooner in a test
1356/// that injects a shorter limit.
1357fn residual_check_deadline(deadline: &FetchDeadline) -> Instant {
1358    #[cfg(any(test, feature = "test-support"))]
1359    if let Some(limit) = TEST_RESIDUAL_LIMIT.with(std::cell::Cell::get) {
1360        return Instant::now() + limit;
1361    }
1362    deadline.at + RESIDUAL_CHECK_RESERVE
1363}
1364
1365/// When the residual check of a response header or a joined redirect URL
1366/// must stop: the download deadline, since those checks run while the fetch
1367/// is still downloading, or sooner in a test that injects a shorter limit.
1368fn header_check_deadline(deadline: &FetchDeadline) -> Instant {
1369    #[cfg(any(test, feature = "test-support"))]
1370    if let Some(limit) = TEST_RESIDUAL_LIMIT.with(std::cell::Cell::get) {
1371        return Instant::now() + limit;
1372    }
1373    deadline.at
1374}
1375
1376#[cfg(any(test, feature = "test-support"))]
1377thread_local! {
1378    /// When set, each of a placeholder fetch's residual checks (headers,
1379    /// redirect URLs, the document) stops this long after it starts, so a
1380    /// test can reach the timeout without a slow document.
1381    static TEST_RESIDUAL_LIMIT: std::cell::Cell<Option<Duration>> = const { std::cell::Cell::new(None) };
1382}
1383
1384/// Make this thread's placeholder fetches stop their residual check `limit`
1385/// after it starts, until the returned guard drops.
1386#[cfg(any(test, feature = "test-support"))]
1387pub fn limit_secret_residual_check_for_test(limit: Duration) -> impl Drop {
1388    struct Restore;
1389    impl Drop for Restore {
1390        fn drop(&mut self) {
1391            TEST_RESIDUAL_LIMIT.with(|slot| slot.set(None));
1392        }
1393    }
1394    TEST_RESIDUAL_LIMIT.with(|slot| slot.set(Some(limit)));
1395    Restore
1396}
1397
1398/// A content coding a placeholder fetch can undo before scrubbing.
1399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1400enum SecretCoding {
1401    Identity,
1402    Gzip,
1403    Deflate,
1404    Brotli,
1405}
1406
1407/// The codings a response declares, in the order they were applied. A server
1408/// may encode the body although the request asked for `identity`; any coding
1409/// this function cannot undo refuses the document, because an encoded key
1410/// cannot be scrubbed. A coding named twice refuses it too: no ordinary server
1411/// encodes a body twice the same way, and the limit on stacked codings stays
1412/// meaningful.
1413fn secret_content_codings(value: &str, url: &str) -> Result<Vec<SecretCoding>, UrlFetchError> {
1414    let mut codings = Vec::new();
1415    for token in value.split(',').map(str::trim) {
1416        let coding = if token.eq_ignore_ascii_case("identity") {
1417            SecretCoding::Identity
1418        } else if token.eq_ignore_ascii_case("gzip") || token.eq_ignore_ascii_case("x-gzip") {
1419            SecretCoding::Gzip
1420        } else if token.eq_ignore_ascii_case("deflate") {
1421            SecretCoding::Deflate
1422        } else if token.eq_ignore_ascii_case("br") {
1423            SecretCoding::Brotli
1424        } else {
1425            return Err(secret_fetch_refused("content_encoding", url));
1426        };
1427        if codings.len() >= MAX_SECRET_CODINGS || codings.contains(&coding) {
1428            return Err(secret_fetch_refused("content_encoding", url));
1429        }
1430        codings.push(coding);
1431    }
1432    Ok(codings)
1433}
1434
1435/// Undo `codings` (last applied first), keeping at most
1436/// [`MAX_RESPONSE_BYTES`] of output. A body whose download was cut short keeps
1437/// what decoded before the cut; any other decoding failure refuses it.
1438fn decode_secret_body(
1439    body: &[u8],
1440    codings: &[SecretCoding],
1441    truncated: &mut bool,
1442    url: &str,
1443) -> Result<sensitive::Bytes, UrlFetchError> {
1444    use async_compression::tokio::bufread::{BrotliDecoder, GzipDecoder, ZlibDecoder};
1445    use tokio::io::{AsyncRead, BufReader};
1446
1447    let mut data = sensitive::Factory::current().copy(body);
1448    for coding in codings.iter().rev() {
1449        let input: &[u8] = &data;
1450        let reader: std::pin::Pin<Box<dyn AsyncRead + Send + '_>> = match coding {
1451            SecretCoding::Identity => continue,
1452            SecretCoding::Gzip => {
1453                let mut decoder = GzipDecoder::new(BufReader::new(input));
1454                decoder.multiple_members(true);
1455                Box::pin(decoder)
1456            }
1457            SecretCoding::Deflate => Box::pin(ZlibDecoder::new(BufReader::new(input))),
1458            SecretCoding::Brotli => Box::pin(BrotliDecoder::new(BufReader::new(input))),
1459        };
1460        let input_truncated = *truncated;
1461        let (output, cut) = drain_decoder(reader, input_truncated).map_err(|()| {
1462            UrlFetchError::new(format!("Failed to decode the response body for {url}"))
1463        })?;
1464        if cut {
1465            *truncated = true;
1466        }
1467        data = output;
1468    }
1469    Ok(data)
1470}
1471
1472/// Read a decoder over an in-memory body to its end, keeping at most
1473/// [`MAX_RESPONSE_BYTES`]. Returns the output and whether the ceiling cut it.
1474/// A body whose download was already cut (`input_truncated`) ends mid-stream;
1475/// what decoded before the cut is kept as a usable prefix.
1476fn drain_decoder(
1477    mut reader: std::pin::Pin<Box<dyn tokio::io::AsyncRead + Send + '_>>,
1478    input_truncated: bool,
1479) -> Result<(sensitive::Bytes, bool), ()> {
1480    use std::future::Future;
1481    use tokio::io::AsyncReadExt;
1482
1483    let factory = sensitive::Factory::current();
1484    let mut output = factory.with_capacity(0);
1485    let polled = {
1486        let decoding = async {
1487            let mut buffer = factory.zeroed(16 * 1024);
1488            loop {
1489                match reader.read(&mut buffer).await {
1490                    Ok(0) => return Ok(false),
1491                    Ok(count) => {
1492                        let room = (MAX_RESPONSE_BYTES as usize).saturating_sub(output.len());
1493                        output.extend_from_slice(&buffer[..count.min(room)]);
1494                        if count > room {
1495                            return Ok(true);
1496                        }
1497                    }
1498                    Err(_) if input_truncated => return Ok(false),
1499                    Err(_) => return Err(()),
1500                }
1501            }
1502        };
1503        // The input is already in memory, so no read ever waits: one poll
1504        // runs the decoder to its end without an async runtime.
1505        let mut decoding = std::pin::pin!(decoding);
1506        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
1507        decoding.as_mut().poll(&mut context)
1508    };
1509    match polled {
1510        std::task::Poll::Ready(Ok(cut)) => Ok((output, cut)),
1511        std::task::Poll::Ready(Err(())) | std::task::Poll::Pending => Err(()),
1512    }
1513}
1514
1515#[rustfmt::skip]
1516test_support_visibility! {
1517
1518/// Decide one hop of a placeholder fetch; every hop, redirects included, is
1519/// evaluated as a new request.
1520///
1521/// Returns the URL to send when a rule substitutes a key into this hop, or
1522/// `None` to send `current` itself, whose placeholders then go out literally.
1523/// Only `query` rules substitute; another location refuses before any card or
1524/// releasing retry. Each scanned label gets one audit record for the hop,
1525/// and a hop whose records cannot be written is not sent.
1526fn secret_hop(
1527    current: &Url,
1528    hop: usize,
1529    secrets: &SecretFetch,
1530    held: &mut HeldKeys,
1531) -> Result<Option<SecretOutboundUrl>, UrlFetchError> {
1532    let logical = current.as_str();
1533    let path = current.path();
1534    let target = match current.query() {
1535        Some(query) => format!("{path}?{query}"),
1536        None => path.to_string(),
1537    };
1538    // Only an HTTPS hop can carry a key.
1539    let authority = (current.scheme() == "https")
1540        .then(|| current.host_str().zip(current.port_or_known_default()))
1541        .flatten()
1542        .and_then(|(host, port)| {
1543            secret_rules::target::canonical_host(host)
1544                .ok()
1545                .map(|host| ConnectAuthority { host, port })
1546        });
1547    let Some(authority) = authority else {
1548        emit_hop_audit(secrets, held, hop, None, &[], |_| {
1549            (Decision::Literal, AuditReason::OutOfScope)
1550        })
1551        .map_err(|_| secret_fetch_refused("audit_unavailable", logical))?;
1552        return Ok(None);
1553    };
1554    let refused = |held: &HeldKeys, reason: &str| {
1555        let _ = emit_hop_audit(secrets, held, hop, Some(&authority), &[], |_| {
1556            (Decision::Refused, AuditReason::Refused)
1557        });
1558        secret_fetch_refused(reason, logical)
1559    };
1560
1561    let mut rules = Vec::new();
1562    let mut materials = Vec::new();
1563    let present = secret_labels_in_url(logical).unwrap_or_default();
1564    let normalized = normalize_request_target(path).map_err(|_| refused(held, "malformed_path"))?;
1565    let addressed = crate::secret::ApiKeyTarget {
1566        scheme: "https".into(),
1567        host: authority.host.clone(),
1568        port: Some(443),
1569        path: String::from_utf8(normalized.wire).map_err(|_| refused(held, "malformed_path"))?,
1570    };
1571    let mut eligible = Vec::new();
1572    for label in &secrets.labels {
1573        let https_port = authority.port == 443;
1574        #[cfg(any(test, feature = "test-support"))]
1575        let https_port = https_port || secrets.test_https_port == Some(authority.port);
1576        if !https_port || !present.contains(label) {
1577            continue;
1578        }
1579        eligible.push(label.clone());
1580    }
1581    let answers = crate::secret::fetch::use_current_secret_labels(
1582        secrets.vault.clone(),
1583        &eligible,
1584        &addressed,
1585        &target,
1586        &secrets.cancellation,
1587    );
1588    for (label, answer) in eligible.iter().zip(answers) {
1589        let answer = match answer {
1590            crate::secret::fetch::FetchDecision::InvalidPlan(reason) => {
1591                return Err(refused(held, reason))
1592            }
1593            crate::secret::fetch::FetchDecision::Proceed(answer) => answer,
1594
1595            crate::secret::fetch::FetchDecision::Refuse(crate::secret::LabelOutcome::Refuse {
1596                code,
1597                message,
1598            }) => {
1599                let _ = refused(held, "missing_material");
1600                return Err(UrlFetchError::secret(code, message));
1601            }
1602            _ => return Err(refused(held, "missing_material")),
1603        };
1604        if let crate::secret::UseAnswer::Released(released) = answer {
1605            let (location, material) = released.into_parts();
1606            let location = secret_rules::location::parse_vault_location(&location)
1607                .ok_or_else(|| refused(held, "missing_material"))?;
1608            if !matches!(location, Location::Query(_)) {
1609                return Err(refused(held, "missing_material"));
1610            }
1611            if check_admissible(material.expose(), label, &location).is_err() {
1612                return Err(refused(held, "material_not_admissible"));
1613            }
1614            held.hold(label, material.expose())
1615                .map_err(|_| refused(held, "replacement_discloses_key"))?;
1616            rules.push(LabelRule {
1617                label: label.clone(),
1618                host: addressed.host.clone(),
1619                port: authority.port,
1620                path_prefix: addressed.path.clone(),
1621                location,
1622            });
1623            materials.push(Some(material));
1624        }
1625    }
1626    // Plan with a stand-in key first: the rules decide where a key would go,
1627    // and refuse an ambiguous request before copying released bytes into a URL.
1628    let planning: Vec<(String, Vec<u8>)> = rules
1629        .iter()
1630        .map(|rule| (rule.label.clone(), SECRET_PLANNING_KEY.to_vec()))
1631        .collect();
1632    let view = RequestView::new(&target, Vec::new());
1633    let plan = evaluate_request_with_connect(&view, &authority, &rules, &planning);
1634    if let Some(refusal) = plan.refusal {
1635        return Err(refused(&*held, refusal.reason()));
1636    }
1637
1638    let query_start = path.len() + 1;
1639    let mut edits: Vec<(usize, usize, Zeroizing<Vec<u8>>)> = Vec::new();
1640    for ((rule, outcome), material) in rules.iter().zip(&plan.labels).zip(&materials) {
1641        if let LabelOutcome::Substituted {
1642            byte_start,
1643            byte_end,
1644            ..
1645        } = outcome
1646        {
1647            let (Some(material), true) = (material, *byte_start >= query_start) else {
1648                return Err(refused(&*held, "missing_material"));
1649            };
1650            let encoded = encode_for_location(material.expose(), &rule.label, &rule.location)
1651                .map_err(|_| refused(&*held, "material_not_admissible"))?;
1652            edits.push((
1653                byte_start - query_start,
1654                byte_end - query_start,
1655                Zeroizing::new(encoded),
1656            ));
1657        }
1658    }
1659    let decide = |label: &str| -> (Decision, AuditReason) {
1660        let outcome = rules
1661            .iter()
1662            .position(|rule| rule.label == label)
1663            .and_then(|index| plan.labels.get(index));
1664        match outcome {
1665            Some(LabelOutcome::Substituted { .. }) => (Decision::Substituted, AuditReason::Matched),
1666            Some(LabelOutcome::NotWholeValue) => (Decision::Literal, AuditReason::NotWholeValue),
1667            _ => (Decision::Literal, AuditReason::OutOfScope),
1668        }
1669    };
1670    if edits.is_empty() {
1671        emit_hop_audit(secrets, held, hop, Some(&authority), &rules, decide)
1672            .map_err(|_| secret_fetch_refused("audit_unavailable", logical))?;
1673        return Ok(None);
1674    }
1675
1676    edits.sort_by_key(|(start, _, _)| *start);
1677    let query = current.query().unwrap_or_default().as_bytes();
1678    let substituted =
1679        substitute_query(query, &edits).ok_or_else(|| refused(held, "malformed_query"))?;
1680    let Ok(substituted) = std::str::from_utf8(&substituted) else {
1681        return Err(refused(&*held, "malformed_query"));
1682    };
1683    // The path sent with a key is the normalized path the rule matched,
1684    // never another spelling of it.
1685    let Ok(normalized) = normalize_request_target(path) else {
1686        return Err(refused(&*held, "malformed_path"));
1687    };
1688    let Ok(wire_path) = std::str::from_utf8(&normalized.wire) else {
1689        return Err(refused(&*held, "malformed_path"));
1690    };
1691    emit_hop_audit(secrets, held, hop, Some(&authority), &rules, decide)
1692        .map_err(|_| secret_fetch_refused("audit_unavailable", logical))?;
1693    secret_outbound_url(current, wire_path, substituted)
1694        .map(Some)
1695        .ok_or_else(|| refused(held, "malformed_query"))
1696}
1697}
1698
1699#[cfg(any(test, feature = "test-support"))]
1700thread_local! { pub static SECRET_URL_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }
1701
1702#[rustfmt::skip]
1703test_support_visibility! {
1704struct SecretOutboundUrl(sensitive::Bytes);
1705}
1706impl std::ops::Deref for SecretOutboundUrl {
1707    type Target = str;
1708    fn deref(&self) -> &str {
1709        std::str::from_utf8(&self.0).expect("URL serialization is UTF-8")
1710    }
1711}
1712impl SecretOutboundUrl {
1713    fn as_str(&self) -> &str {
1714        self
1715    }
1716}
1717impl fmt::Debug for SecretOutboundUrl {
1718    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1719        f.write_str("ProtectedOutboundUrl")
1720    }
1721}
1722
1723fn secret_outbound_url(
1724    current: &Url,
1725    wire_path: &str,
1726    substituted: &str,
1727) -> Option<SecretOutboundUrl> {
1728    #[cfg(any(test, feature = "test-support"))]
1729    SECRET_URL_BUILDS.with(|n| n.set(n.get() + 1));
1730    let prefix = &current[..url::Position::BeforePath];
1731    let capacity = prefix
1732        .len()
1733        .checked_add(wire_path.len())?
1734        .checked_add(1)?
1735        .checked_add(substituted.len())?;
1736    // Build the complete serialization in protected, pre-sized storage instead
1737    // of reallocating a partially key-bearing Url with clone/set_query.
1738    let mut serialized = sensitive::Factory::current().with_capacity(capacity);
1739    serialized.extend_from_slice(prefix.as_bytes());
1740    serialized.extend_from_slice(wire_path.as_bytes());
1741    serialized.extend_from_slice(b"?");
1742    serialized.extend_from_slice(substituted.as_bytes());
1743    Some(SecretOutboundUrl(serialized))
1744}
1745
1746fn substitute_query(
1747    query: &[u8],
1748    edits: &[(usize, usize, Zeroizing<Vec<u8>>)],
1749) -> Option<Zeroizing<Vec<u8>>> {
1750    let final_len = edits
1751        .iter()
1752        .try_fold(query.len(), |len, (start, end, value)| {
1753            len.checked_sub(end.checked_sub(*start)?)?
1754                .checked_add(value.len())
1755        })?;
1756    // Allocate the complete result before copying the first credential: growing
1757    // a partially filled Vec would free an old, unwiped credential allocation.
1758    let mut substituted = Zeroizing::new(Vec::with_capacity(final_len));
1759    let mut cursor = 0;
1760    for (start, end, replacement) in edits {
1761        if *start < cursor || *end < *start || *end > query.len() {
1762            return None;
1763        }
1764        substituted.extend_from_slice(&query[cursor..*start]);
1765        substituted.extend_from_slice(replacement);
1766        cursor = *end;
1767    }
1768    substituted.extend_from_slice(&query[cursor..]);
1769    Some(substituted)
1770}
1771
1772/// One audit record per scanned label for one hop. A record is handed to the
1773/// vault only after the crate's writer checked it against every held key.
1774fn emit_hop_audit(
1775    secrets: &SecretFetch,
1776    held: &HeldKeys,
1777    hop: usize,
1778    authority: Option<&ConnectAuthority>,
1779    rules: &[LabelRule],
1780    decide: impl Fn(&str) -> (Decision, AuditReason),
1781) -> Result<(), ()> {
1782    let origin = format!("{}#{hop}", secrets.call_id);
1783    let keys = held.keys();
1784    let mut failed = false;
1785    for label in &secrets.labels {
1786        let (decision, reason) = decide(label);
1787        let mut record = AuditRecordV1::new(
1788            crate::secret::now_ms(),
1789            label,
1790            decision,
1791            reason,
1792            &secrets.call_id,
1793            &origin,
1794        )
1795        .with_scope(
1796            secrets
1797                .authorization
1798                .as_ref()
1799                .map(crate::secret::SecretScope::to_scope_ref),
1800        );
1801        if let Some(authority) = authority {
1802            record.host = Some(authority.host.clone());
1803            record.port = Some(authority.port);
1804        }
1805        if let Some(rule) = rules.iter().find(|rule| &rule.label == label) {
1806            record = record.with_rule(
1807                &rule.host,
1808                rule.port,
1809                &rule.path_prefix,
1810                location_kind_token(&rule.location),
1811            );
1812        }
1813        if record.to_json_line_with_keys(&keys).is_err() || secrets.vault.audit(&record).is_err() {
1814            failed = true;
1815        }
1816    }
1817    if failed {
1818        Err(())
1819    } else {
1820        Ok(())
1821    }
1822}
1823
1824/// What a cleanup sweep learned from one metadata file, kept so the next sweep
1825/// can skip re-reading it. `len` and `modified` identify the file version the
1826/// fetch time was read from: the cache rewrites metadata only through a rename
1827/// of a freshly written file, which always produces a new modification time.
1828#[derive(Debug, Clone)]
1829struct CleanupMemoEntry {
1830    len: u64,
1831    modified: SystemTime,
1832    fetched_at: u64,
1833    extension: String,
1834}
1835
1836/// Per cache directory, the metadata facts of the last sweep, keyed by file
1837/// name. Every configure runs the cleanup sweep, and almost every metadata
1838/// file is unchanged since the previous one, so an unchanged file costs one
1839/// stat instead of an open, a read and a JSON parse. A sweep replaces its
1840/// directory's map with only the files it saw and kept, so removed entries do
1841/// not accumulate.
1842fn cleanup_memo() -> &'static std::sync::Mutex<HashMap<PathBuf, HashMap<String, CleanupMemoEntry>>>
1843{
1844    static MEMO: std::sync::OnceLock<
1845        std::sync::Mutex<HashMap<PathBuf, HashMap<String, CleanupMemoEntry>>>,
1846    > = std::sync::OnceLock::new();
1847    MEMO.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
1848}
1849
1850#[cfg(any(test, feature = "test-support"))]
1851thread_local! {
1852    /// Metadata files the cleanup sweep opened on this thread, for tests that
1853    /// check unchanged files are not read again.
1854    pub static CLEANUP_META_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1855}
1856
1857pub fn cleanup_url_cache(storage_dir: &Path) -> Result<usize, UrlFetchError> {
1858    cleanup_url_cache_at(storage_dir, now_ms())
1859}
1860
1861fn cleanup_url_cache_at(storage_dir: &Path, now: u64) -> Result<usize, UrlFetchError> {
1862    let dir = cache_dir(storage_dir);
1863    if !dir.exists() {
1864        return Ok(0);
1865    }
1866
1867    let entries = fs::read_dir(&dir).map_err(|error| {
1868        UrlFetchError::new(format!(
1869            "URL cache cleanup failed reading {}: {error}",
1870            dir.display()
1871        ))
1872    })?;
1873    let mut removed = 0usize;
1874    // Taken out for the sweep and put back at the end, so the lock is never
1875    // held across file I/O. A concurrent sweep of the same directory finds no
1876    // memo and reads every file, which is only slower.
1877    let previous = cleanup_memo()
1878        .lock()
1879        .unwrap_or_else(std::sync::PoisonError::into_inner)
1880        .remove(&dir)
1881        .unwrap_or_default();
1882    let mut kept = HashMap::new();
1883
1884    for entry in entries.flatten() {
1885        let path = entry.path();
1886        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
1887            continue;
1888        };
1889        if !name.ends_with(".meta.json") {
1890            continue;
1891        }
1892
1893        let version = entry
1894            .metadata()
1895            .ok()
1896            .and_then(|metadata| Some((metadata.len(), metadata.modified().ok()?)));
1897        let remembered = version.and_then(|(len, modified)| {
1898            previous
1899                .get(name)
1900                .filter(|known| known.len == len && known.modified == modified)
1901                .cloned()
1902        });
1903        let facts = match remembered {
1904            Some(known) => known,
1905            None => {
1906                #[cfg(any(test, feature = "test-support"))]
1907                CLEANUP_META_READS.with(|reads| reads.set(reads.get() + 1));
1908                let meta = fs::read_to_string(&path)
1909                    .ok()
1910                    .and_then(|content| serde_json::from_str::<CacheMeta>(&content).ok());
1911                let Some(meta) = meta else {
1912                    if fs::remove_file(&path).is_ok() {
1913                        removed += 1;
1914                    }
1915                    continue;
1916                };
1917                let (len, modified) = version.unwrap_or((u64::MAX, UNIX_EPOCH));
1918                CleanupMemoEntry {
1919                    len,
1920                    modified,
1921                    fetched_at: meta.fetched_at,
1922                    extension: meta.extension,
1923                }
1924            }
1925        };
1926
1927        if now.saturating_sub(facts.fetched_at) <= CACHE_TTL_MS {
1928            // A file whose version could not be read is not remembered, so the
1929            // next sweep reads it again.
1930            if version.is_some() {
1931                kept.insert(name.to_string(), facts);
1932            }
1933            continue;
1934        }
1935
1936        let hash = name.trim_end_matches(".meta.json");
1937        let content = content_path(storage_dir, hash, &facts.extension);
1938        let _ = fs::remove_file(content);
1939        if fs::remove_file(&path).is_ok() {
1940            removed += 1;
1941        }
1942    }
1943
1944    cleanup_memo()
1945        .lock()
1946        .unwrap_or_else(std::sync::PoisonError::into_inner)
1947        .insert(dir, kept);
1948    Ok(removed)
1949}
1950
1951#[doc(hidden)]
1952pub fn cache_content_path_for_url(storage_dir: &Path, url: &str, extension: &str) -> PathBuf {
1953    content_path(storage_dir, &hash_url(url), extension)
1954}
1955
1956#[doc(hidden)]
1957pub fn cache_meta_path_for_url(storage_dir: &Path, url: &str) -> PathBuf {
1958    meta_path(storage_dir, &hash_url(url))
1959}
1960
1961/// Disclose a partial download separately from any later rendering cut. Keys
1962/// or headings after this prefix have not been inspected.
1963pub fn download_notice(path: &Path) -> Option<String> {
1964    let meta_path = path.with_extension("meta.json");
1965    let meta: CacheMeta = serde_json::from_slice(&fs::read(meta_path).ok()?).ok()?;
1966    if !meta.download_truncated {
1967        return None;
1968    }
1969    let total = meta
1970        .total_bytes
1971        .map(|n| n.to_string())
1972        .unwrap_or_else(|| format!("≥{}", meta.downloaded_bytes + 1));
1973    Some(format!(
1974        "Download truncated at {} of {total} bytes; narrow with a smaller URL or server-side filters (only the downloaded prefix was inspected)",
1975        meta.downloaded_bytes
1976    ))
1977}
1978
1979#[doc(hidden)]
1980pub fn is_private_ip_for_test(ip: IpAddr) -> bool {
1981    is_private_ip(ip)
1982}
1983
1984fn cache_dir(storage_dir: &Path) -> PathBuf {
1985    storage_dir.join("url_cache")
1986}
1987
1988fn hash_url(url: &str) -> String {
1989    let digest = Sha256::digest(url.as_bytes());
1990    format!("{digest:x}").chars().take(16).collect()
1991}
1992
1993/// Rewrite well-known web-view links before fetching because those pages serve
1994/// an HTML application shell instead of the file contents agents need to read.
1995fn rewrite_url_for_fetch(url: &Url) -> Url {
1996    let original = url.clone();
1997    let mut rewritten = url.clone();
1998    rewritten.set_fragment(None);
1999
2000    let Some(host) = url.host_str() else {
2001        return rewritten;
2002    };
2003    if !matches!(url.scheme(), "http" | "https") {
2004        return rewritten;
2005    }
2006
2007    let segments: Vec<&str> = url
2008        .path_segments()
2009        .map(|segments| segments.collect())
2010        .unwrap_or_default();
2011    let (raw_host, raw_path) = if matches!(host, "github.com" | "www.github.com") {
2012        if segments.len() >= 5 && matches!(segments[2], "blob" | "raw") {
2013            (
2014                "raw.githubusercontent.com",
2015                format!(
2016                    "/{}/{}/{}/{}",
2017                    segments[0],
2018                    segments[1],
2019                    segments[3],
2020                    segments[4..].join("/")
2021                ),
2022            )
2023        } else {
2024            return rewritten;
2025        }
2026    } else if host == "gitlab.com"
2027        && segments.len() >= 6
2028        && segments[2] == "-"
2029        && segments[3] == "blob"
2030    {
2031        (
2032            "gitlab.com",
2033            format!(
2034                "/{}/{}/-/raw/{}/{}",
2035                segments[0],
2036                segments[1],
2037                segments[4],
2038                segments[5..].join("/")
2039            ),
2040        )
2041    } else {
2042        return rewritten;
2043    };
2044
2045    rewritten
2046        .set_host(Some(raw_host))
2047        .expect("raw content host should be a valid URL host");
2048    rewritten.set_path(&raw_path);
2049    log::debug!(
2050        "url_fetch: rewriting web-view URL to raw content: {} -> {}",
2051        original,
2052        rewritten
2053    );
2054    rewritten
2055}
2056
2057fn meta_path(storage_dir: &Path, hash: &str) -> PathBuf {
2058    cache_dir(storage_dir).join(format!("{hash}.meta.json"))
2059}
2060
2061fn content_path(storage_dir: &Path, hash: &str, extension: &str) -> PathBuf {
2062    cache_dir(storage_dir).join(format!("{hash}{extension}"))
2063}
2064
2065fn fresh_cached_path(
2066    storage_dir: &Path,
2067    hash: &str,
2068    meta_file: &Path,
2069    url: &Url,
2070) -> Result<Option<PathBuf>, UrlFetchError> {
2071    #[cfg(any(test, feature = "test-support"))]
2072    stall_cache_read_if_requested(storage_dir);
2073    if !meta_file.exists() {
2074        return Ok(None);
2075    }
2076
2077    let meta = match fs::read_to_string(meta_file)
2078        .ok()
2079        .and_then(|content| serde_json::from_str::<CacheMeta>(&content).ok())
2080    {
2081        Some(meta) => meta,
2082        None => return Ok(None),
2083    };
2084    let age = now_ms().saturating_sub(meta.fetched_at);
2085    if meta.extension == ".html" {
2086        return Ok(None);
2087    }
2088
2089    let content_type = meta.content_type.as_str();
2090    let current = resolve_fetch_extension(url, content_type);
2091    // An HTML page is stored converted to Markdown, so a URL whose path ends
2092    // in .html or .htm finds its cached copy under .md. Comparing against
2093    // .html would miss the cache on every call and fetch, convert and
2094    // re-parse the whole page again.
2095    let expected_ext = current.map(|(ext, _)| if ext == ".html" { ".md" } else { ext });
2096    if expected_ext != Some(meta.extension.as_str()) {
2097        return Ok(None);
2098    }
2099
2100    let cached = content_path(storage_dir, hash, &meta.extension);
2101    // Old cache entries predate the iterator ceiling and may contain an
2102    // unbounded body. Refetch those rather than reintroducing the missed cap.
2103    let legacy_oversized = meta.downloaded_bytes == 0
2104        && fs::metadata(&cached).is_ok_and(|m| m.len() > MAX_RESPONSE_BYTES);
2105    if age < CACHE_TTL_MS && cached.exists() && !legacy_oversized {
2106        return Ok(Some(cached));
2107    }
2108    Ok(None)
2109}
2110
2111fn fetch_with_redirects(
2112    start_url: &Url,
2113    original_url: &str,
2114    options: &UrlFetchOptions,
2115    deadline: &FetchDeadline,
2116    approved: Arc<ApprovedHosts>,
2117) -> Result<HttpResponse, UrlFetchError> {
2118    let progress = Arc::new(ConnectProgress::default());
2119    let client = build_client(
2120        options,
2121        Arc::clone(&approved),
2122        Arc::clone(&progress),
2123        true,
2124        None,
2125    )?;
2126    let mut current_url = start_url.clone();
2127
2128    for redirect_count in 0..=MAX_REDIRECTS {
2129        validate_public_url(&current_url, options, deadline, &approved)?;
2130        let response = send_with_transient_retries(&client, &current_url, deadline, &progress)?;
2131
2132        if !response.status().is_redirection() {
2133            return Ok(response);
2134        }
2135        if redirect_count == MAX_REDIRECTS {
2136            return Err(UrlFetchError::new(format!(
2137                "Too many redirects fetching {original_url}"
2138            )));
2139        }
2140
2141        let location = response
2142            .headers()
2143            .get(LOCATION)
2144            .and_then(|value| value.to_str().ok())
2145            .ok_or_else(|| {
2146                UrlFetchError::new(format!(
2147                    "Redirect from {} missing Location header",
2148                    current_url.as_str()
2149                ))
2150            })?;
2151        current_url = current_url.join(location).map_err(|error| {
2152            UrlFetchError::new(format!(
2153                "Invalid redirect Location '{location}' from {}: {error}",
2154                current_url.as_str()
2155            ))
2156        })?;
2157        timing::record(|times| times.redirects += 1);
2158    }
2159
2160    Err(UrlFetchError::new(format!(
2161        "Too many redirects fetching {original_url}"
2162    )))
2163}
2164
2165/// Issue a single GET with the configured User-Agent + Accept headers and
2166/// transparently retry only on transient connect/transport failures.
2167///
2168/// Returns the response (including 4xx/5xx — caller decides how to treat
2169/// those). On a non-transient reqwest error (e.g. an HTTP-shaped reply that
2170/// reqwest still surfaces as Err, or a TLS handshake fault that doesn't read
2171/// as `is_connect`), the original error is returned immediately so the user
2172/// sees the real failure without an artificial 800ms-plus delay.
2173///
2174/// Every attempt is limited to the time left before `deadline`, and a retry
2175/// runs only when its backoff plus [`MIN_USEFUL_ATTEMPT`] still fit, so
2176/// retries can never stretch a fetch past its deadline.
2177fn send_with_transient_retries(
2178    client: &Client,
2179    target: &Url,
2180    deadline: &FetchDeadline,
2181    progress: &ConnectProgress,
2182) -> Result<HttpResponse, UrlFetchError> {
2183    send_request(client, target, None, deadline, progress)
2184}
2185
2186#[derive(Clone, Copy)]
2187struct SecretSend<'a> {
2188    shown: &'a str,
2189    held: &'a HeldKeys,
2190    released: bool,
2191    cancellation: &'a SecretFetchCancellation,
2192    key_sent: &'a std::cell::Cell<bool>,
2193    outbound: Option<&'a SecretOutboundUrl>,
2194}
2195
2196/// [`send_with_transient_retries`] for one request. With `secret` set, the
2197/// request belongs to a placeholder fetch: every message names the given
2198/// placeholder URL instead of `target`, a failure is reported through
2199/// [`send_failure`] with the held keys, and the request asks for an unencoded
2200/// response so the body can be scrubbed byte for byte.
2201fn send_request(
2202    client: &Client,
2203    target: &Url,
2204    secret: Option<SecretSend<'_>>,
2205    deadline: &FetchDeadline,
2206    progress: &ConnectProgress,
2207) -> Result<HttpResponse, UrlFetchError> {
2208    let started = Instant::now();
2209    let (attempts_before, connect_before) = progress.totals();
2210    let result = send_request_attempts(client, target, secret, deadline, progress);
2211    let elapsed = started.elapsed();
2212    let (attempts, connect) = progress.totals();
2213    timing::record(|times| {
2214        times.first_byte += elapsed;
2215        times.connect += connect.saturating_sub(connect_before);
2216        times.retries += (attempts - attempts_before).saturating_sub(1) as u32;
2217    });
2218    result
2219}
2220
2221/// [`send_request`]'s attempts, without its timing.
2222fn send_request_attempts(
2223    client: &Client,
2224    target: &Url,
2225    secret: Option<SecretSend<'_>>,
2226    deadline: &FetchDeadline,
2227    progress: &ConnectProgress,
2228) -> Result<HttpResponse, UrlFetchError> {
2229    let named = secret.map_or(target.as_str(), |secret| secret.shown);
2230    let held = secret.map(|secret| secret.held);
2231    let mut attempt = 0;
2232    loop {
2233        let remaining = deadline.remaining();
2234        if remaining.is_zero() {
2235            return Err(deadline.timeout_error(FetchPhase::Connect, named));
2236        }
2237        // A per-request timeout replaces reqwest's default 30 s, which would
2238        // otherwise let one silent server hold each attempt for 30 s.
2239        progress.begin_attempt();
2240        // Parse directly from protected serialization and move the Url into
2241        // reqwest. AFT must not clone a key-bearing URL's ordinary String.
2242        let outbound = match secret.and_then(|secret| secret.outbound) {
2243            Some(outbound) => Url::parse(outbound.as_str())
2244                .map_err(|_| secret_fetch_refused("malformed_query", named))?,
2245            None => target.clone(),
2246        };
2247        let mut request = client
2248            .get(outbound)
2249            .header(USER_AGENT, USER_AGENT_VALUE)
2250            .header(ACCEPT, ACCEPT_HEADER)
2251            .timeout(remaining.min(HEADERS_TIMEOUT));
2252        if held.is_some() {
2253            request = request.header(ACCEPT_ENCODING, "identity");
2254        }
2255        if secret.is_some_and(|secret| secret.cancellation.is_cancelled()) {
2256            return Err(secret_fetch_refused("missing_material", named));
2257        }
2258        if let Some(secret) = secret.filter(|secret| secret.released) {
2259            secret.key_sent.set(true);
2260        }
2261        let error = match request.send() {
2262            Ok(response) => return Ok(response),
2263            Err(error) => error,
2264        };
2265        if secret.is_some_and(|secret| secret.cancellation.is_cancelled()) {
2266            // A cancelled secret request returns its existing refusal rather
2267            // than exposing a transport error from connection setup.
2268            return Err(secret_fetch_refused("missing_material", named));
2269        }
2270        let phase = error
2271            .is_timeout()
2272            .then(|| timed_out_phase(&error, progress));
2273        // A server that accepted the request and stayed silent until the
2274        // headers limit is not a passing connection fault; retrying it would
2275        // only spend the rest of the deadline the same way.
2276        // One released key authorizes one send attempt, even if the peer received
2277        // the credential and reset before its response reached this process.
2278        let retryable = !secret.is_some_and(|secret| secret.released)
2279            && is_transient_reqwest_error(&error)
2280            && phase != Some(FetchPhase::Headers);
2281        let backoff = TRANSIENT_RETRY_BACKOFFS_MS
2282            .get(attempt)
2283            .map(|ms| Duration::from_millis(*ms))
2284            .filter(|backoff| retryable && *backoff + MIN_USEFUL_ATTEMPT <= deadline.remaining());
2285        if let Some(backoff) = backoff {
2286            thread::sleep(backoff);
2287            attempt += 1;
2288            continue;
2289        }
2290        return Err(send_failure(error, phase, deadline, named, held));
2291    }
2292}
2293
2294/// The error for a request that failed for good, naming `named`. For a
2295/// placeholder fetch (`held` set) reqwest's error first loses its URL, which
2296/// carried the key, and the detail left is scrubbed of every held key (or
2297/// dropped if it still spells one).
2298fn send_failure(
2299    error: reqwest::Error,
2300    phase: Option<FetchPhase>,
2301    deadline: &FetchDeadline,
2302    named: &str,
2303    held: Option<&HeldKeys>,
2304) -> UrlFetchError {
2305    let error = if held.is_some() {
2306        error.without_url()
2307    } else {
2308        error
2309    };
2310    let detail = reqwest_error_detail(&error);
2311    let detail = match held {
2312        Some(held) => held.sanitize_detail(&detail),
2313        None => detail,
2314    };
2315    if let Some(phase) = phase {
2316        return request_timeout_error(&detail, phase, deadline, named);
2317    }
2318    if detail.is_empty() {
2319        return UrlFetchError::new(format!("Failed to fetch {named}"));
2320    }
2321    UrlFetchError::new(format!("Failed to fetch {named}: {detail}"))
2322}
2323
2324/// Name the phase a timed-out request was in: a name lookup still running in
2325/// the resolver, then connection setup still running (or reported by reqwest
2326/// as the cause), and otherwise the wait for the response headers.
2327fn timed_out_phase(error: &reqwest::Error, progress: &ConnectProgress) -> FetchPhase {
2328    if progress.lookup_pending() {
2329        FetchPhase::Dns
2330    } else if progress.connect_pending() || error.is_connect() {
2331        FetchPhase::Connect
2332    } else {
2333        FetchPhase::Headers
2334    }
2335}
2336
2337fn request_timeout_error(
2338    detail: &str,
2339    phase: FetchPhase,
2340    deadline: &FetchDeadline,
2341    target: &str,
2342) -> UrlFetchError {
2343    if deadline.expired() {
2344        return deadline.timeout_error(phase, target);
2345    }
2346    let limit = match phase {
2347        FetchPhase::Dns | FetchPhase::Connect => CONNECT_TIMEOUT,
2348        FetchPhase::Headers | FetchPhase::Body => HEADERS_TIMEOUT,
2349    };
2350    UrlFetchError::timeout(
2351        phase,
2352        format!(
2353            "URL fetch timed out in the {} phase after the {}ms limit fetching {}: {}",
2354            phase.as_str(),
2355            limit.as_millis(),
2356            target,
2357            detail
2358        ),
2359    )
2360}
2361
2362/// Classify a reqwest error as transient (worth a quick retry) vs terminal.
2363///
2364/// Transient: TCP connect failures, request-build/send TCP-level failures
2365/// that don't carry status, and timeouts. These typically clear on a single
2366/// retry — agents shouldn't have to ask twice for a momentary blip.
2367///
2368/// Terminal: anything where reqwest got far enough to decode an HTTP-shaped
2369/// reply (`is_status()`, `is_body()`, `is_decode()`). Retrying those would
2370/// just hammer a server that already answered.
2371fn is_transient_reqwest_error(error: &reqwest::Error) -> bool {
2372    error.is_connect() || error.is_timeout() || error.is_request()
2373}
2374
2375fn build_client(
2376    options: &UrlFetchOptions,
2377    approved: Arc<ApprovedHosts>,
2378    progress: Arc<ConnectProgress>,
2379    automatic_replays: bool,
2380    cancellation: Option<SecretFetchCancellation>,
2381) -> Result<Client, UrlFetchError> {
2382    let resolver = GuardedResolver {
2383        approved,
2384        connect_overrides: options.connect_overrides.clone(),
2385        lookup_override: options.lookup_override.clone(),
2386        progress: Arc::clone(&progress),
2387    };
2388    let builder = Client::builder()
2389        .redirect(Policy::none())
2390        .connect_timeout(CONNECT_TIMEOUT)
2391        .connector_layer(TrackConnect {
2392            progress,
2393            delay: options.connect_delay,
2394            cancellation,
2395        })
2396        .dns_resolver(Arc::new(resolver));
2397    let builder = if automatic_replays {
2398        builder
2399    } else {
2400        builder.retry(reqwest::retry::never())
2401    };
2402
2403    let tls_config = match &options.tls_config {
2404        Some(config) => config.clone(),
2405        None => crate::platform_tls::client_config().map_err(|error| {
2406            UrlFetchError::new(format!("Failed to configure URL fetch TLS: {error}"))
2407        })?,
2408    };
2409
2410    builder
2411        .use_preconfigured_tls(tls_config)
2412        .build()
2413        .map_err(|error| UrlFetchError::new(format!("Failed to build URL fetch client: {error}")))
2414}
2415
2416/// Host names the SSRF check resolved and approved during one fetch, with
2417/// the addresses it approved. The resolver hands reqwest exactly these, so
2418/// the connection cannot reach an address that a second lookup returned (a
2419/// DNS-rebinding answer), and a redirect back to the same host needs no new
2420/// lookup.
2421#[derive(Default)]
2422struct ApprovedHosts(std::sync::Mutex<HashMap<String, Vec<IpAddr>>>);
2423
2424impl ApprovedHosts {
2425    fn get(&self, host: &str) -> Option<Vec<IpAddr>> {
2426        self.0
2427            .lock()
2428            .unwrap_or_else(std::sync::PoisonError::into_inner)
2429            .get(host)
2430            .cloned()
2431    }
2432
2433    fn insert(&self, host: &str, addresses: Vec<IpAddr>) {
2434        self.0
2435            .lock()
2436            .unwrap_or_else(std::sync::PoisonError::into_inner)
2437            .insert(host.to_string(), addresses);
2438    }
2439}
2440
2441/// Connection-setup progress of the current request attempt, read when the
2442/// request times out to name the phase it was in. A step that a timeout
2443/// abandoned never reports its end, so each attempt starts from a clean
2444/// state and a step reports its end only to the attempt that started it.
2445#[derive(Default)]
2446struct ConnectProgress(std::sync::Mutex<AttemptProgress>);
2447
2448#[derive(Default)]
2449struct AttemptProgress {
2450    attempt: u64,
2451    lookup_pending: bool,
2452    connect_pending: bool,
2453    /// Time spent setting up connections, summed over every attempt of the
2454    /// fetch, including attempts a timeout abandoned.
2455    connect_time: Duration,
2456}
2457
2458impl ConnectProgress {
2459    fn state(&self) -> std::sync::MutexGuard<'_, AttemptProgress> {
2460        self.0
2461            .lock()
2462            .unwrap_or_else(std::sync::PoisonError::into_inner)
2463    }
2464
2465    fn begin_attempt(&self) {
2466        let mut state = self.state();
2467        state.attempt += 1;
2468        state.lookup_pending = false;
2469        state.connect_pending = false;
2470    }
2471
2472    /// Returns the attempt the connection belongs to.
2473    fn connect_started(&self) -> u64 {
2474        let mut state = self.state();
2475        state.connect_pending = true;
2476        state.attempt
2477    }
2478
2479    fn connected(&self, attempt: u64) {
2480        let mut state = self.state();
2481        if state.attempt == attempt {
2482            state.connect_pending = false;
2483        }
2484    }
2485
2486    fn connect_pending(&self) -> bool {
2487        self.state().connect_pending
2488    }
2489
2490    fn add_connect_time(&self, elapsed: Duration) {
2491        self.state().connect_time += elapsed;
2492    }
2493
2494    /// Attempts begun and connection setup time so far, for the fetch times.
2495    fn totals(&self) -> (u64, Duration) {
2496        let state = self.state();
2497        (state.attempt, state.connect_time)
2498    }
2499
2500    /// Returns the attempt the lookup belongs to.
2501    fn lookup_started(&self) -> u64 {
2502        let mut state = self.state();
2503        state.lookup_pending = true;
2504        state.attempt
2505    }
2506
2507    fn lookup_answered(&self, attempt: u64) {
2508        let mut state = self.state();
2509        if state.attempt == attempt {
2510            state.lookup_pending = false;
2511        }
2512    }
2513
2514    fn lookup_pending(&self) -> bool {
2515        self.state().lookup_pending
2516    }
2517}
2518
2519/// Connector layer that records when a request starts and finishes setting
2520/// up its connection, so a timeout can tell a stalled connect from a server
2521/// that accepted the connection and never answered.
2522#[derive(Clone)]
2523struct TrackConnect {
2524    progress: Arc<ConnectProgress>,
2525    delay: Option<Duration>,
2526    cancellation: Option<SecretFetchCancellation>,
2527}
2528
2529impl<S> tower_layer::Layer<S> for TrackConnect {
2530    type Service = TrackedConnector<S>;
2531
2532    fn layer(&self, inner: S) -> Self::Service {
2533        TrackedConnector {
2534            inner,
2535            progress: Arc::clone(&self.progress),
2536            delay: self.delay,
2537            cancellation: self.cancellation.clone(),
2538        }
2539    }
2540}
2541
2542#[derive(Clone)]
2543struct TrackedConnector<S> {
2544    inner: S,
2545    progress: Arc<ConnectProgress>,
2546    delay: Option<Duration>,
2547    cancellation: Option<SecretFetchCancellation>,
2548}
2549
2550impl<S, Target> tower_service::Service<Target> for TrackedConnector<S>
2551where
2552    S: tower_service::Service<Target>,
2553    S::Future: Send + 'static,
2554    S::Response: Send + 'static,
2555    S::Error: Into<Box<dyn std::error::Error + Send + Sync>> + Send + 'static,
2556{
2557    type Response = S::Response;
2558    type Error = Box<dyn std::error::Error + Send + Sync>;
2559    type Future = std::pin::Pin<
2560        Box<dyn std::future::Future<Output = Result<S::Response, Self::Error>> + Send>,
2561    >;
2562
2563    fn poll_ready(
2564        &mut self,
2565        cx: &mut std::task::Context<'_>,
2566    ) -> std::task::Poll<Result<(), Self::Error>> {
2567        self.inner.poll_ready(cx).map_err(Into::into)
2568    }
2569
2570    fn call(&mut self, target: Target) -> Self::Future {
2571        let attempt = self.progress.connect_started();
2572        let progress = Arc::clone(&self.progress);
2573        let delay = self.delay;
2574        let cancellation = self.cancellation.clone();
2575        let connecting = self.inner.call(target);
2576        Box::pin(async move {
2577            // Records on drop too, so a connect a timeout abandons still
2578            // counts the time it took.
2579            let _timer = ConnectTimer {
2580                progress: Arc::clone(&progress),
2581                started: Instant::now(),
2582            };
2583            if let Some(delay) = delay {
2584                tokio::time::sleep(delay).await;
2585            }
2586            let connection = connecting.await.map_err(Into::into)?;
2587            // The inner connector includes DNS, TCP and TLS. Check again at
2588            // its handover boundary, before hyper can write request bytes.
2589            if cancellation.is_some_and(|cancel| cancel.is_cancelled()) {
2590                return Err(std::io::Error::from(std::io::ErrorKind::Interrupted).into());
2591            }
2592            progress.connected(attempt);
2593            Ok(connection)
2594        })
2595    }
2596}
2597
2598/// Adds the time since `started` to the fetch's connection setup time when
2599/// dropped.
2600struct ConnectTimer {
2601    progress: Arc<ConnectProgress>,
2602    started: Instant,
2603}
2604
2605impl Drop for ConnectTimer {
2606    fn drop(&mut self) {
2607        self.progress.add_connect_time(self.started.elapsed());
2608    }
2609}
2610
2611/// The resolver reqwest uses for every connection of a fetch.
2612///
2613/// A host the SSRF check approved gets exactly the approved addresses. Any
2614/// other host is looked up here without the SSRF check: that is a proxy host,
2615/// or any host when private addresses are allowed. The lookup runs on its own
2616/// thread so the request's timeout can abandon it: the request stops waiting
2617/// at the fetch deadline, although the system resolver's thread may run on
2618/// until its lookup returns.
2619struct GuardedResolver {
2620    approved: Arc<ApprovedHosts>,
2621    connect_overrides: Vec<(String, SocketAddr)>,
2622    lookup_override: Option<HostLookup>,
2623    progress: Arc<ConnectProgress>,
2624}
2625
2626impl reqwest::dns::Resolve for GuardedResolver {
2627    fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
2628        let host = name.as_str().to_string();
2629        // Port 0 tells reqwest to use the URL's port.
2630        let ready = |addresses: Vec<SocketAddr>| -> reqwest::dns::Resolving {
2631            Box::pin(std::future::ready(Ok(
2632                Box::new(addresses.into_iter()) as reqwest::dns::Addrs
2633            )))
2634        };
2635        if let Some((_, address)) = self
2636            .connect_overrides
2637            .iter()
2638            .find(|(override_host, _)| *override_host == host)
2639        {
2640            return ready(vec![*address]);
2641        }
2642        if let Some(addresses) = self.approved.get(&host) {
2643            return ready(
2644                addresses
2645                    .into_iter()
2646                    .map(|ip| SocketAddr::new(ip, 0))
2647                    .collect(),
2648            );
2649        }
2650        let progress = Arc::clone(&self.progress);
2651        let attempt = progress.lookup_started();
2652        let (sender, receiver) = tokio::sync::oneshot::channel();
2653        let lookup = self.lookup_override.clone();
2654        thread::spawn(move || {
2655            let _ = sender.send(lookup_host(&host, lookup.as_ref()));
2656        });
2657        Box::pin(async move {
2658            let answer: Result<io::Result<Vec<IpAddr>>, _> = receiver.await;
2659            progress.lookup_answered(attempt);
2660            let addresses = answer
2661                .unwrap_or_else(|_| Err(io::Error::other("host lookup stopped before answering")))
2662                .map_err(|error| Box::new(error) as Box<dyn Error + Send + Sync>)?;
2663            Ok(
2664                Box::new(addresses.into_iter().map(|ip| SocketAddr::new(ip, 0)))
2665                    as reqwest::dns::Addrs,
2666            )
2667        })
2668    }
2669}
2670
2671fn lookup_host(host: &str, lookup_override: Option<&HostLookup>) -> io::Result<Vec<IpAddr>> {
2672    if let Some(lookup) = lookup_override {
2673        return lookup(host);
2674    }
2675    Ok((host, 0).to_socket_addrs()?.map(|addr| addr.ip()).collect())
2676}
2677
2678/// Refuse a URL that is not http(s) or that points at a private address.
2679/// A host name is resolved under the fetch deadline and its approved
2680/// addresses are recorded in `approved` for the resolver.
2681fn validate_public_url(
2682    url: &Url,
2683    options: &UrlFetchOptions,
2684    deadline: &FetchDeadline,
2685    approved: &ApprovedHosts,
2686) -> Result<(), UrlFetchError> {
2687    let started = Instant::now();
2688    let result = check_public_url(url, options, deadline, approved);
2689    let elapsed = started.elapsed();
2690    timing::record(|times| times.lookup += elapsed);
2691    result
2692}
2693
2694/// [`validate_public_url`] without its timing.
2695fn check_public_url(
2696    url: &Url,
2697    options: &UrlFetchOptions,
2698    deadline: &FetchDeadline,
2699    approved: &ApprovedHosts,
2700) -> Result<(), UrlFetchError> {
2701    if url.scheme() != "http" && url.scheme() != "https" {
2702        return Err(UrlFetchError::new(format!(
2703            "Only http:// and https:// URLs are supported, got: {}:",
2704            url.scheme()
2705        )));
2706    }
2707    if options.allow_private {
2708        return Ok(());
2709    }
2710
2711    let host = url
2712        .host_str()
2713        .ok_or_else(|| UrlFetchError::new(format!("URL missing host: {url}")))?;
2714    let host_for_parse = host
2715        .trim_matches(['[', ']'])
2716        .split('%')
2717        .next()
2718        .unwrap_or(host);
2719
2720    if let Ok(ip) = host_for_parse.parse::<IpAddr>() {
2721        reject_private_ip(host, ip)?;
2722        return Ok(());
2723    }
2724    if host_for_parse.contains(':') {
2725        return Err(UrlFetchError::new(format!(
2726            "Blocked private URL host {host} ({host_for_parse})"
2727        )));
2728    }
2729    if approved.get(host_for_parse).is_some() {
2730        return Ok(());
2731    }
2732
2733    let addresses = resolve_host_ips(host_for_parse, url.as_str(), options, deadline)?;
2734    if addresses.is_empty() {
2735        return Err(UrlFetchError::new(format!(
2736            "Failed to resolve URL host {host}"
2737        )));
2738    }
2739    for ip in &addresses {
2740        reject_private_ip(host, *ip)?;
2741    }
2742    approved.insert(host_for_parse, addresses);
2743    Ok(())
2744}
2745
2746/// Resolve `host` on a helper thread and wait for it no longer than the
2747/// fetch deadline; the system resolver itself has no timeout.
2748fn resolve_host_ips(
2749    host: &str,
2750    url: &str,
2751    options: &UrlFetchOptions,
2752    deadline: &FetchDeadline,
2753) -> Result<Vec<IpAddr>, UrlFetchError> {
2754    if let Some((_, ips)) = options
2755        .public_host_overrides
2756        .iter()
2757        .find(|(override_host, _)| override_host == host)
2758    {
2759        return Ok(ips.clone());
2760    }
2761
2762    let remaining = deadline.remaining();
2763    if remaining.is_zero() {
2764        return Err(deadline.timeout_error(FetchPhase::Dns, url));
2765    }
2766    let (sender, receiver) = mpsc::channel();
2767    let owned_host = host.to_string();
2768    let lookup = options.lookup_override.clone();
2769    thread::spawn(move || {
2770        let _ = sender.send(lookup_host(&owned_host, lookup.as_ref()));
2771    });
2772    match receiver.recv_timeout(remaining) {
2773        Ok(Ok(addresses)) => Ok(addresses),
2774        Ok(Err(error)) => Err(UrlFetchError::new(format!(
2775            "Failed to resolve URL host {host}: {error}"
2776        ))),
2777        Err(mpsc::RecvTimeoutError::Timeout) => Err(deadline.timeout_error(FetchPhase::Dns, url)),
2778        Err(mpsc::RecvTimeoutError::Disconnected) => Err(UrlFetchError::new(format!(
2779            "Failed to resolve URL host {host}: lookup stopped before answering"
2780        ))),
2781    }
2782}
2783
2784fn reject_private_ip(host: &str, ip: IpAddr) -> Result<(), UrlFetchError> {
2785    if is_private_ip(ip) {
2786        return Err(UrlFetchError::new(format!(
2787            "Blocked private URL host {host} ({ip})"
2788        )));
2789    }
2790    Ok(())
2791}
2792
2793/// True for any private/link-local/CGNAT/benchmark/multicast/reserved/loopback
2794/// address (the full set this module refuses to fetch). Exposed so the semantic
2795/// embedding SSRF guard shares one authoritative range list instead of keeping a
2796/// drifting copy. Note: this INCLUDES loopback — callers that intentionally
2797/// allow loopback (e.g. a local Ollama endpoint) must exclude it themselves.
2798pub fn is_private_or_reserved_ip(ip: IpAddr) -> bool {
2799    is_private_ip(ip)
2800}
2801
2802fn is_private_ip(ip: IpAddr) -> bool {
2803    match ip {
2804        IpAddr::V4(ipv4) => is_private_ipv4(ipv4),
2805        IpAddr::V6(ipv6) => is_private_ipv6(ipv6),
2806    }
2807}
2808
2809fn is_private_ipv4(ip: Ipv4Addr) -> bool {
2810    let [a, b, _, _] = ip.octets();
2811    a == 0
2812        || a == 10
2813        || a == 127
2814        || (a == 172 && (16..=31).contains(&b))
2815        || (a == 192 && b == 168)
2816        || (a == 169 && b == 254)
2817        // RFC 6598 Shared Address Space (CGNAT): 100.64.0.0/10. Not globally
2818        // routable; used for provider/VPC-internal endpoints — must not be
2819        // reachable via SSRF.
2820        || (a == 100 && (64..=127).contains(&b))
2821        // RFC 2544 benchmark subnet: 198.18.0.0/15. Reserved, non-routable.
2822        || (a == 198 && (18..=19).contains(&b))
2823        || a >= 224
2824}
2825
2826fn is_private_ipv6(ip: Ipv6Addr) -> bool {
2827    let segments = ip.segments();
2828    let top_six_zero = segments[..6].iter().all(|segment| *segment == 0);
2829    let is_mapped = segments[..5].iter().all(|segment| *segment == 0) && segments[5] == 0xffff;
2830    if is_mapped || top_six_zero {
2831        let embedded = Ipv4Addr::new(
2832            (segments[6] >> 8) as u8,
2833            (segments[6] & 0xff) as u8,
2834            (segments[7] >> 8) as u8,
2835            (segments[7] & 0xff) as u8,
2836        );
2837        return is_private_ipv4(embedded);
2838    }
2839
2840    let first = segments[0];
2841    // fe80::/10 link-local, fec0::/10 deprecated site-local (still routed
2842    // inside some networks), fc00::/7 unique local, ff00::/8 multicast.
2843    (0xfe80..=0xfeff).contains(&first) || (0xfc00..=0xfdff).contains(&first) || first >= 0xff00
2844}
2845
2846const BINARY_SNIFF_PREFIX: usize = 8 * 1024;
2847
2848fn body_contains_nul_in_prefix(body: &[u8]) -> bool {
2849    let end = body.len().min(BINARY_SNIFF_PREFIX);
2850    body[..end].contains(&0)
2851}
2852
2853/// Resolve cache extension: URL path (parsed, percent-decoded) first for source
2854/// languages AFT parses; otherwise content-type mapping.
2855fn resolve_fetch_extension(url: &Url, content_type: &str) -> Option<(&'static str, bool)> {
2856    if let Some(ext) = extension_from_url_path(url) {
2857        return Some((ext, true));
2858    }
2859    resolve_extension_from_content_type(content_type).map(|ext| (ext, false))
2860}
2861
2862#[rustfmt::skip]
2863test_support_visibility! {
2864
2865fn extension_from_url_path(url: &Url) -> Option<&'static str> {
2866    let path = url.path();
2867    if path.is_empty() || path == "/" {
2868        return None;
2869    }
2870    let segment = path.rsplit('/').next().unwrap_or(path);
2871    let file_name = percent_decode_path_segment(segment);
2872    let dot = file_name.rfind('.')?;
2873    let ext = &file_name[dot + 1..];
2874    if ext.is_empty() {
2875        return None;
2876    }
2877    let probe = Path::new("file").with_extension(ext);
2878    if language_by_extension(&probe).is_some() {
2879        static_extension_for_lang_ext(ext)
2880    } else {
2881        None
2882    }
2883}
2884}
2885
2886fn percent_decode_path_segment(segment: &str) -> String {
2887    let mut out = String::with_capacity(segment.len());
2888    let bytes = segment.as_bytes();
2889    let mut i = 0;
2890    while i < bytes.len() {
2891        if bytes[i] == b'%' && i + 2 < bytes.len() {
2892            if let (Some(h1), Some(h2)) = (from_hex(bytes[i + 1]), from_hex(bytes[i + 2])) {
2893                out.push(char::from(h1 << 4 | h2));
2894                i += 3;
2895                continue;
2896            }
2897        }
2898        out.push(bytes[i] as char);
2899        i += 1;
2900    }
2901    out
2902}
2903
2904fn from_hex(byte: u8) -> Option<u8> {
2905    match byte {
2906        b'0'..=b'9' => Some(byte - b'0'),
2907        b'a'..=b'f' => Some(byte - b'a' + 10),
2908        b'A'..=b'F' => Some(byte - b'A' + 10),
2909        _ => None,
2910    }
2911}
2912
2913#[rustfmt::skip]
2914test_support_visibility! {
2915
2916/// Dotted cache extension for a path extension that `detect_language` accepts.
2917fn static_extension_for_lang_ext(ext: &str) -> Option<&'static str> {
2918    match ext.to_ascii_lowercase().as_str() {
2919        "ts" | "mts" | "cts" => Some(".ts"),
2920        "tsx" => Some(".tsx"),
2921        "js" => Some(".js"),
2922        "jsx" => Some(".jsx"),
2923        "mjs" => Some(".mjs"),
2924        "cjs" => Some(".cjs"),
2925        "py" | "pyi" => Some(".py"),
2926        "rs" => Some(".rs"),
2927        "go" => Some(".go"),
2928        "c" => Some(".c"),
2929        "h" => Some(".h"),
2930        "cc" | "cpp" | "cxx" | "hpp" | "hh" => Some(".cpp"),
2931        "zig" => Some(".zig"),
2932        "cs" => Some(".cs"),
2933        "sh" | "bash" | "zsh" => Some(".sh"),
2934        "html" | "htm" => Some(".html"),
2935        "md" | "markdown" | "mdx" => Some(".md"),
2936        "sol" => Some(".sol"),
2937        "scss" => Some(".scss"),
2938        "vue" => Some(".vue"),
2939        "json" | "jsonc" => Some(".json"),
2940        "scala" | "sc" => Some(".scala"),
2941        "java" => Some(".java"),
2942        "rb" => Some(".rb"),
2943        "kt" | "kts" => Some(".kt"),
2944        "swift" => Some(".swift"),
2945        "inc" | "php" => Some(".php"),
2946        "lua" => Some(".lua"),
2947        "pl" | "pm" | "t" => Some(".pl"),
2948        "yaml" | "yml" => Some(".yaml"),
2949        _ => None,
2950    }
2951}
2952}
2953
2954fn resolve_extension_from_content_type(content_type: &str) -> Option<&'static str> {
2955    let lower = content_type.to_ascii_lowercase();
2956    let media_type = lower
2957        .split(';')
2958        .next()
2959        .unwrap_or("")
2960        .split(',')
2961        .next()
2962        .unwrap_or("")
2963        .trim();
2964
2965    match media_type {
2966        "text/html"
2967        | "application/xhtml+xml"
2968        | "application/vnd.github.html"
2969        | "application/vnd.github+html" => Some(".html"),
2970        "text/markdown"
2971        | "text/x-markdown"
2972        | "application/markdown"
2973        | "application/vnd.github.raw"
2974        | "application/vnd.github+raw"
2975        | "application/vnd.github.v3.raw"
2976        | "text/plain" => Some(".md"),
2977        "application/json" | "application/ld+json" => Some(".json"),
2978        other if other.ends_with("+json") => Some(".json"),
2979        "text/javascript" | "application/javascript" | "application/ecmascript" => Some(".js"),
2980        "text/typescript" | "application/typescript" => Some(".ts"),
2981        _ => None,
2982    }
2983}
2984
2985fn convert_html_body_to_markdown(body: &[u8], url: &str) -> Result<Vec<u8>, UrlFetchError> {
2986    let started = Instant::now();
2987    let result = html_body_to_markdown(body, url);
2988    let elapsed = started.elapsed();
2989    timing::record(|times| times.convert += elapsed);
2990    result
2991}
2992
2993/// [`convert_html_body_to_markdown`] without its timing.
2994fn html_body_to_markdown(body: &[u8], url: &str) -> Result<Vec<u8>, UrlFetchError> {
2995    let html = String::from_utf8_lossy(body);
2996    let mut markdown = html_to_markdown_converter()
2997        .convert(&html)
2998        .map_err(|error| {
2999            UrlFetchError::new(format!(
3000                "Failed to convert HTML from {url} to Markdown: {error}"
3001            ))
3002        })?;
3003    if !markdown.ends_with('\n') {
3004        markdown.push('\n');
3005    }
3006    Ok(markdown.into_bytes())
3007}
3008
3009/// Page chrome dropped from the converted Markdown. The `<pre>` text walker
3010/// skips the same tags so a copy button inside a code block stays out of it.
3011const SKIPPED_HTML_TAGS: [&str; 8] = [
3012    "head", "script", "style", "nav", "footer", "aside", "noscript", "button",
3013];
3014
3015fn html_to_markdown_converter() -> HtmlToMarkdown {
3016    HtmlToMarkdown::builder()
3017        .skip_tags(SKIPPED_HTML_TAGS.to_vec())
3018        .add_handler(
3019            vec!["pre"],
3020            |handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
3021                if node_has_descendant_tag(element.node, "code") {
3022                    Some(fenced_code_block(&element).into())
3023                } else {
3024                    handlers.fallback(element)
3025                }
3026            },
3027        )
3028        .add_handler(
3029            vec!["a"],
3030            |handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
3031                if is_permalink_anchor(&element)
3032                    || handlers.walk_children(element.node).content.trim() == "§"
3033                {
3034                    None
3035                } else if element_attr_value(&element, "href")
3036                    .is_some_and(|href| href.trim() == "#")
3037                {
3038                    Some(handlers.walk_children(element.node).content.into())
3039                } else {
3040                    handlers.fallback(element)
3041                }
3042            },
3043        )
3044        .add_handler(
3045            vec!["header"],
3046            |handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
3047                if should_skip_header(&element) {
3048                    None
3049                } else {
3050                    handlers.fallback(element)
3051                }
3052            },
3053        )
3054        .add_handler(
3055            vec!["span"],
3056            |handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
3057                if element_has_class_token(&element, "token-line") {
3058                    let mut content = handlers.walk_children(element.node).content;
3059                    content.push('\n');
3060                    Some(content.into())
3061                } else {
3062                    handlers.fallback(element)
3063                }
3064            },
3065        )
3066        .build()
3067}
3068
3069/// Render a `<pre>` that holds code as one fenced block built from the raw
3070/// text of the whole `<pre>`, not just its `<code>` child.
3071///
3072/// htmd fences only the `<code>` element and renders whatever follows it in
3073/// the `<pre>` as ordinary text. Real pages close `</code>` early: the Chrome
3074/// DevTools docs end `<code>` in the middle of a JSON string, and the HTML
3075/// parser then leaves the rest of the block as `<pre>` children after the
3076/// `<code>`. A browser still shows that as one block, so the Markdown must too.
3077/// Walking the text ourselves also keeps htmd's text handling (escaping,
3078/// collapsing blank lines) away from code that has to be copied verbatim.
3079fn fenced_code_block(element: &Element<'_>) -> String {
3080    let mut text = PreformattedText::default();
3081    text.collect(element.node);
3082    // A break still pending after the last line ends the block, so it is
3083    // dropped rather than written.
3084    let mut code = text.output;
3085    // The line break before `</code>` or `</pre>` ends the last line; it is
3086    // not an extra blank line inside the block.
3087    if code.ends_with('\n') {
3088        code.pop();
3089    }
3090    let fence = code_fence_for(&code);
3091    let language = find_descendant_element(element.node, "code")
3092        .and_then(|code| node_class_attr(&code))
3093        .as_deref()
3094        .and_then(language_from_class)
3095        .or_else(|| element_attr_value(element, "class").and_then(language_from_class));
3096
3097    let mut block = String::from("\n\n");
3098    block.push_str(&fence);
3099    if let Some(language) = language {
3100        block.push_str(&language);
3101    }
3102    block.push('\n');
3103    block.push_str(&code);
3104    block.push('\n');
3105    block.push_str(&fence);
3106    block.push_str("\n\n");
3107    block
3108}
3109
3110/// How an element inside a `<pre>` ends the text line it holds.
3111///
3112/// Many highlighters emit one element per source line with no newline text
3113/// between them: Prism `span.token-line` (Docusaurus), Shiki `span.line`,
3114/// `<li>` per line, table rows (highlight.js line-numbers plugin), or plain
3115/// per-line `<div>`s. A browser still shows separate lines, so the copied
3116/// text must break after each one.
3117#[derive(Clone, Copy, PartialEq, Eq)]
3118enum PreLineBreak {
3119    /// Inline element: adds no break.
3120    None,
3121    /// One source line, so it always ends a line, even when empty (an empty
3122    /// row or `span.line` is a blank line of code).
3123    Line,
3124    /// Generic block (`<div>`, `<p>`): ends a line only when it holds text,
3125    /// so an empty line-number `<div>` beside the code does not add a blank
3126    /// line.
3127    Block,
3128}
3129
3130fn pre_line_break(tag: &str, class: Option<&str>) -> PreLineBreak {
3131    let has_class =
3132        |token: &str| class.is_some_and(|value| value.split_ascii_whitespace().any(|c| c == token));
3133    match tag {
3134        "tr" | "li" => PreLineBreak::Line,
3135        "span" if has_class("token-line") || has_class("line") => PreLineBreak::Line,
3136        "div" | "p" => PreLineBreak::Block,
3137        _ => PreLineBreak::None,
3138    }
3139}
3140
3141/// The raw text of a `<pre>`, collected exactly as written: no escaping and
3142/// no whitespace changes.
3143///
3144/// A per-line element (see [`PreLineBreak`]) ends its line with a *pending*
3145/// break rather than a written one. Some highlighters already put a newline
3146/// between their line elements (Shiki's default output does) and some do
3147/// not; the pending break is written only when more of the block follows
3148/// and is absorbed when that next text already starts with a newline, so
3149/// both layouts give one line per element.
3150#[derive(Default)]
3151struct PreformattedText {
3152    output: String,
3153    pending_break: bool,
3154}
3155
3156impl PreformattedText {
3157    fn flush_pending_break(&mut self) {
3158        if self.pending_break {
3159            self.output.push('\n');
3160            self.pending_break = false;
3161        }
3162    }
3163
3164    fn push_text(&mut self, text: &str) {
3165        if text.is_empty() {
3166            return;
3167        }
3168        if self.pending_break && text.starts_with('\n') {
3169            self.pending_break = false;
3170        }
3171        self.flush_pending_break();
3172        self.output.push_str(text);
3173    }
3174
3175    fn collect(&mut self, node: &Node) {
3176        for child in node.children.borrow().iter() {
3177            match &child.data {
3178                NodeData::Text { contents } => self.push_text(&contents.borrow()),
3179                NodeData::Element { name, attrs, .. } => {
3180                    let tag = name.local.as_ref();
3181                    if SKIPPED_HTML_TAGS.contains(&tag) {
3182                        continue;
3183                    }
3184                    if tag == "br" {
3185                        // A `<br>` right after a finished line starts an
3186                        // empty line, as it does in a browser.
3187                        self.flush_pending_break();
3188                        self.output.push('\n');
3189                        continue;
3190                    }
3191                    let line_break = {
3192                        let attrs = attrs.borrow();
3193                        let class = attrs
3194                            .iter()
3195                            .find(|attr| attr.name.local.as_ref() == "class")
3196                            .map(|attr| attr.value.as_ref());
3197                        pre_line_break(tag, class)
3198                    };
3199                    if line_break == PreLineBreak::None {
3200                        self.collect(child);
3201                        continue;
3202                    }
3203                    // A new line element starts on its own line, so the
3204                    // previous one's break is written before measuring this
3205                    // one's text.
3206                    self.flush_pending_break();
3207                    let line_start = self.output.len();
3208                    self.collect(child);
3209                    let line = &self.output[line_start..];
3210                    let line_ended = self.pending_break || line.ends_with('\n');
3211                    let ends_line = match line_break {
3212                        PreLineBreak::None => false,
3213                        PreLineBreak::Line => !line_ended,
3214                        PreLineBreak::Block => !line.is_empty() && !line_ended,
3215                    };
3216                    if ends_line {
3217                        self.pending_break = true;
3218                    }
3219                }
3220                _ => {}
3221            }
3222        }
3223    }
3224}
3225
3226/// A backtick fence one longer than the longest backtick run in `code`
3227/// (at least three), so a run inside the code can never close the block.
3228fn code_fence_for(code: &str) -> String {
3229    let mut longest = 0;
3230    let mut current = 0;
3231    for ch in code.chars() {
3232        if ch == '`' {
3233            current += 1;
3234            longest = longest.max(current);
3235        } else {
3236            current = 0;
3237        }
3238    }
3239    "`".repeat((longest + 1).max(3))
3240}
3241
3242/// The `xyz` of a `language-xyz` class token, the convention both Prism and
3243/// highlight.js use to name a code block's language.
3244fn language_from_class(class: &str) -> Option<String> {
3245    class
3246        .split_ascii_whitespace()
3247        .find_map(|token| token.strip_prefix("language-"))
3248        .filter(|language| !language.is_empty())
3249        .map(str::to_string)
3250}
3251
3252fn node_has_descendant_tag(node: &Node, tag: &str) -> bool {
3253    find_descendant_element(node, tag).is_some()
3254}
3255
3256/// The first element named `tag` below `node`, depth first.
3257fn find_descendant_element(node: &Node, tag: &str) -> Option<Rc<Node>> {
3258    for child in node.children.borrow().iter() {
3259        if let NodeData::Element { name, .. } = &child.data {
3260            if name.local.as_ref() == tag {
3261                return Some(Rc::clone(child));
3262            }
3263            if let Some(found) = find_descendant_element(child, tag) {
3264                return Some(found);
3265            }
3266        }
3267    }
3268    None
3269}
3270
3271fn node_class_attr(node: &Node) -> Option<String> {
3272    match &node.data {
3273        NodeData::Element { attrs, .. } => attrs
3274            .borrow()
3275            .iter()
3276            .find(|attr| attr.name.local.as_ref() == "class")
3277            .map(|attr| attr.value.to_string()),
3278        _ => None,
3279    }
3280}
3281
3282fn is_permalink_anchor(element: &Element<'_>) -> bool {
3283    element_has_class_token(element, "hash-link")
3284        || element_has_class_token(element, "doc-anchor")
3285        || element_attr_value(element, "aria-label")
3286            .is_some_and(|value| value.to_ascii_lowercase().starts_with("direct link to"))
3287}
3288
3289fn should_skip_header(element: &Element<'_>) -> bool {
3290    element_has_class_token(element, "navbar")
3291        || element_has_class_token(element, "site-header")
3292        || element_has_class_token(element, "site-nav")
3293        || element_has_class_token(element, "topbar")
3294        || element_attr_value(element, "role")
3295            .is_some_and(|value| value.eq_ignore_ascii_case("banner"))
3296        || element_attr_value(element, "id").is_some_and(|value| {
3297            let value = value.to_ascii_lowercase();
3298            value.contains("navbar") || value.contains("site-header") || value.contains("site-nav")
3299        })
3300}
3301
3302fn element_has_class_token(element: &Element<'_>, token: &str) -> bool {
3303    element_attr_value(element, "class")
3304        .is_some_and(|value| value.split_ascii_whitespace().any(|class| class == token))
3305}
3306
3307fn element_attr_value<'a>(element: &'a Element<'_>, name: &str) -> Option<&'a str> {
3308    element
3309        .attrs
3310        .iter()
3311        .find(|attr| attr.name.local.as_ref() == name)
3312        .map(|attr| attr.value.as_ref())
3313}
3314
3315enum BodyReadEvent {
3316    Chunk(sensitive::Bytes),
3317    Done,
3318    /// A read failed after waiting this long for data.
3319    Error(io::ErrorKind, sensitive::Bytes, Duration),
3320}
3321
3322/// Read at most [`MAX_RESPONSE_BYTES`] (plus one lookahead byte) of the body.
3323/// Two limits stop a slow body: no data for [`BODY_CHUNK_TIMEOUT`], and the
3324/// fetch deadline, which also stops a server that sends a little data just
3325/// often enough to avoid the stall limit.
3326///
3327/// Whether a failed read was a timeout is decided mainly by time: reqwest
3328/// reports both its per-read limit and its whole-request limit as an
3329/// `io::Error` of kind `Other` (its blocking `Read` impl wraps the timeout
3330/// with `into_io`), and which of those timers or this function's own wait
3331/// fires first differs between platforms. So a failed read is a body-phase
3332/// timeout when the fetch deadline has passed, when the read had waited at
3333/// least [`BODY_CHUNK_TIMEOUT`] for data, or when its kind is `TimedOut` or
3334/// `WouldBlock`.
3335fn read_response_body(
3336    response: impl Read + Send + 'static,
3337    url: &str,
3338    deadline: &FetchDeadline,
3339) -> Result<(Vec<u8>, bool), UrlFetchError> {
3340    read_response_body_with(response, url, deadline, &|detail: &str| detail.to_string())
3341        .map(|(body, truncated)| (body.into_plain_vec(), truncated))
3342}
3343
3344/// [`read_response_body`] with `detail` applied to the text of a failed read
3345/// before it goes into the error, so a placeholder fetch can scrub it.
3346fn read_response_body_with(
3347    response: impl Read + Send + 'static,
3348    url: &str,
3349    deadline: &FetchDeadline,
3350    detail: &dyn Fn(&str) -> String,
3351) -> Result<(sensitive::Bytes, bool), UrlFetchError> {
3352    // Bound the producer, not just its consumer: an unbounded channel can
3353    // queue the entire response before the caller notices the byte ceiling.
3354    let (tx, rx) = mpsc::sync_channel(1);
3355    let factory = sensitive::Factory::current();
3356    let worker = factory.clone();
3357    thread::spawn(move || {
3358        // One lookahead byte distinguishes an exact-size body from a cut,
3359        // including chunked responses without Content-Length.
3360        let mut response = response.take(MAX_RESPONSE_BYTES + 1);
3361        let mut buffer = worker.zeroed(16 * 1024);
3362        loop {
3363            let read_started = Instant::now();
3364            match response.read(&mut buffer) {
3365                Ok(0) => {
3366                    let _ = tx.send(BodyReadEvent::Done);
3367                    break;
3368                }
3369                Ok(n) => {
3370                    if tx
3371                        .send(BodyReadEvent::Chunk(worker.copy(&buffer[..n])))
3372                        .is_err()
3373                    {
3374                        break;
3375                    }
3376                }
3377                Err(error) => {
3378                    let kind = error.kind();
3379                    let message = worker.format(format_args!("{error}"));
3380                    let waited = read_started.elapsed();
3381                    let _ = tx.send(BodyReadEvent::Error(kind, message, waited));
3382                    break;
3383                }
3384            }
3385        }
3386    });
3387
3388    /// Records the body's read time and the bytes received when dropped, so
3389    /// every way out of the read loop counts.
3390    struct BodyTimer {
3391        started: Instant,
3392        bytes: u64,
3393    }
3394    impl Drop for BodyTimer {
3395        fn drop(&mut self) {
3396            let (elapsed, bytes) = (self.started.elapsed(), self.bytes);
3397            timing::record(|times| {
3398                times.body += elapsed;
3399                times.body_bytes += bytes;
3400            });
3401        }
3402    }
3403    let mut timer = BodyTimer {
3404        started: Instant::now(),
3405        bytes: 0,
3406    };
3407    let mut chunks = factory.with_capacity(0);
3408    let mut total = 0u64;
3409    let slow_body_error = || {
3410        if deadline.expired() {
3411            deadline.timeout_error(FetchPhase::Body, url)
3412        } else {
3413            body_stall_error(url)
3414        }
3415    };
3416    loop {
3417        let wait = BODY_CHUNK_TIMEOUT.min(deadline.remaining());
3418        if wait.is_zero() {
3419            return Err(deadline.timeout_error(FetchPhase::Body, url));
3420        }
3421        match rx.recv_timeout(wait) {
3422            Ok(BodyReadEvent::Chunk(chunk)) => {
3423                let remaining = (MAX_RESPONSE_BYTES - total) as usize;
3424                chunks.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
3425                total += chunk.len() as u64;
3426                timer.bytes = total;
3427                if total > MAX_RESPONSE_BYTES {
3428                    return Ok((chunks, true));
3429                }
3430            }
3431            Ok(BodyReadEvent::Done) => return Ok((chunks, false)),
3432            Ok(BodyReadEvent::Error(kind, message, waited)) => {
3433                return Err(body_read_failure(
3434                    deadline,
3435                    url,
3436                    kind,
3437                    &detail(std::str::from_utf8(&message).unwrap_or_default()),
3438                    waited,
3439                ));
3440            }
3441            Err(mpsc::RecvTimeoutError::Timeout) => return Err(slow_body_error()),
3442            Err(mpsc::RecvTimeoutError::Disconnected) => {
3443                return Err(UrlFetchError::new(format!(
3444                    "Failed to read response body for {url}: body reader stopped unexpectedly"
3445                )));
3446            }
3447        }
3448    }
3449}
3450
3451/// How a failed body read is reported. It is a body-phase timeout when the
3452/// fetch deadline has passed or the read had waited at least
3453/// [`BODY_CHUNK_TIMEOUT`], whatever its kind (see [`read_response_body`]);
3454/// the kinds `TimedOut` and `WouldBlock` also count as a body stall.
3455fn body_read_failure(
3456    deadline: &FetchDeadline,
3457    url: &str,
3458    kind: io::ErrorKind,
3459    message: &str,
3460    waited: Duration,
3461) -> UrlFetchError {
3462    if deadline.expired() {
3463        return deadline.timeout_error(FetchPhase::Body, url);
3464    }
3465    if waited >= BODY_CHUNK_TIMEOUT || is_body_stall_kind(kind) {
3466        return body_stall_error(url);
3467    }
3468    if message.is_empty() {
3469        return UrlFetchError::new(format!("Failed to read response body for {url}"));
3470    }
3471    UrlFetchError::new(format!("Failed to read response body for {url}: {message}"))
3472}
3473
3474fn body_stall_error(url: &str) -> UrlFetchError {
3475    UrlFetchError::timeout(
3476        FetchPhase::Body,
3477        format!(
3478            "Body read stalled (no data for {}ms) fetching {url}",
3479            BODY_CHUNK_TIMEOUT.as_millis()
3480        ),
3481    )
3482}
3483
3484fn is_body_stall_kind(kind: io::ErrorKind) -> bool {
3485    matches!(kind, io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock)
3486}
3487
3488fn atomic_write(
3489    final_path: &Path,
3490    bytes: &[u8],
3491    options: &UrlFetchOptions,
3492) -> Result<(), UrlFetchError> {
3493    let parent = final_path.parent().unwrap_or_else(|| Path::new("."));
3494    crate::private_storage::create_dir_all(parent).map_err(|error| {
3495        UrlFetchError::new(format!(
3496            "Failed to create URL cache parent {}: {error}",
3497            parent.display()
3498        ))
3499    })?;
3500
3501    let file_name = final_path
3502        .file_name()
3503        .and_then(|name| name.to_str())
3504        .ok_or_else(|| {
3505            UrlFetchError::new(format!("Invalid cache path: {}", final_path.display()))
3506        })?;
3507    let tmp_path = final_path.with_file_name(format!(
3508        "{file_name}.tmp-{}-{}",
3509        std::process::id(),
3510        random_nonce()
3511    ));
3512
3513    let write_result = (|| -> io::Result<()> {
3514        let mut file = crate::private_storage::create(&tmp_path)?;
3515        file.write_all(bytes)?;
3516        file.flush()?;
3517        Ok(())
3518    })();
3519    if let Err(error) = write_result {
3520        let _ = fs::remove_file(&tmp_path);
3521        return Err(UrlFetchError::new(format!(
3522            "Failed to write URL cache temp file {}: {error}",
3523            tmp_path.display()
3524        )));
3525    }
3526
3527    if let Some(observer) = &options.atomic_write_observer {
3528        observer(&tmp_path, final_path);
3529    }
3530
3531    fs::rename(&tmp_path, final_path).map_err(|error| {
3532        let _ = fs::remove_file(&tmp_path);
3533        UrlFetchError::new(format!(
3534            "Failed to finalize URL cache file {}: {error}",
3535            final_path.display()
3536        ))
3537    })
3538}
3539
3540fn random_nonce() -> String {
3541    let mut bytes = [0u8; 8];
3542    if getrandom::fill(&mut bytes).is_err() {
3543        let fallback = now_ms() ^ u64::from(std::process::id());
3544        bytes = fallback.to_le_bytes();
3545    }
3546    let mut out = String::with_capacity(bytes.len() * 2);
3547    for byte in bytes {
3548        use std::fmt::Write as _;
3549        let _ = write!(out, "{byte:02x}");
3550    }
3551    out
3552}
3553
3554fn now_ms() -> u64 {
3555    SystemTime::now()
3556        .duration_since(UNIX_EPOCH)
3557        .unwrap_or_default()
3558        .as_millis()
3559        .try_into()
3560        .unwrap_or(u64::MAX)
3561}
3562
3563fn reqwest_error_detail(error: &reqwest::Error) -> String {
3564    if error.is_timeout() {
3565        return format!("timeout: {error}");
3566    }
3567    if let Some(source) = error.source() {
3568        return format!("{source}");
3569    }
3570    error.to_string()
3571}
3572
3573/// Where the time of one tool call's URL fetches went, for the daemon's
3574/// slow-call log line.
3575///
3576/// A fetch spends almost all of its time off the calling thread: the HTTP
3577/// client runs the connection and the body read on its own runtime, and name
3578/// lookups run on helper threads. So a slow URL outline shows a long `exec`
3579/// with almost no CPU, the same as a call blocked on a lock. These counters
3580/// say which part of the fetch the time went to.
3581///
3582/// Collection is per thread and only while a [`FetchTimesScope`] is open on
3583/// that thread; anywhere else every recorder costs one thread-local read and
3584/// records nothing. Only what the calling thread waited for is recorded, so
3585/// the totals stay within the call's own wall time (connection setup is the
3586/// exception: it is measured where it runs and is part of `first_byte`).
3587pub mod timing {
3588    use std::cell::RefCell;
3589    use std::fmt::Write as _;
3590    use std::time::Duration;
3591
3592    use super::FetchPhase;
3593
3594    /// Every URL fetch one call made, summed.
3595    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3596    pub struct UrlFetchTimes {
3597        /// Documents asked for: downloads, cache hits and failures answered
3598        /// from memory.
3599        pub fetches: u32,
3600        /// Served from the URL cache with no request sent.
3601        pub cache_hits: u32,
3602        /// Answered with a failure remembered from an earlier fetch of the
3603        /// same URL, with no request sent.
3604        pub remembered_failures: u32,
3605        /// The private-address check's host name lookups, which run before
3606        /// each request (and before a cache hit is served).
3607        pub lookup: Duration,
3608        /// Connection setup (TCP and TLS) inside the HTTP client, summed over
3609        /// attempts. Part of `first_byte`.
3610        pub connect: Duration,
3611        /// From sending each request until its response headers arrived,
3612        /// including connection setup, the server's own time to answer, and
3613        /// any retry backoff; summed over redirect hops.
3614        pub first_byte: Duration,
3615        /// Reading response bodies.
3616        pub body: Duration,
3617        /// Body bytes received.
3618        pub body_bytes: u64,
3619        /// Converting HTML pages to Markdown, on the calling thread.
3620        pub convert: Duration,
3621        /// Redirects followed.
3622        pub redirects: u32,
3623        /// Requests sent again after a transient connection failure.
3624        pub retries: u32,
3625        /// The last failed fetch's error code and, for a timeout, its phase.
3626        pub error: Option<(&'static str, Option<FetchPhase>)>,
3627    }
3628
3629    impl UrlFetchTimes {
3630        /// `url_fetch=fetches:1,cache_hits:0,remembered:0,lookup:2.10,
3631        /// connect:40.00,first_byte:5800.00,body:300.00,bytes:51234,
3632        /// convert:4.00,redirects:0,retries:0` (milliseconds for times), then
3633        /// `,error:<code>[/<phase>]` when a fetch failed. One field with no
3634        /// spaces and no URL: the host is already in the call's target kind.
3635        pub fn render(&self) -> String {
3636            let ms = |duration: Duration| duration.as_secs_f64() * 1000.0;
3637            let mut out = format!(
3638                "url_fetch=fetches:{},cache_hits:{},remembered:{},lookup:{:.2},connect:{:.2},first_byte:{:.2},body:{:.2},bytes:{},convert:{:.2},redirects:{},retries:{}",
3639                self.fetches,
3640                self.cache_hits,
3641                self.remembered_failures,
3642                ms(self.lookup),
3643                ms(self.connect),
3644                ms(self.first_byte),
3645                ms(self.body),
3646                self.body_bytes,
3647                ms(self.convert),
3648                self.redirects,
3649                self.retries,
3650            );
3651            if let Some((code, phase)) = self.error {
3652                let _ = write!(out, ",error:{code}");
3653                if let Some(phase) = phase {
3654                    let _ = write!(out, "/{}", phase.as_str());
3655                }
3656            }
3657            out
3658        }
3659    }
3660
3661    thread_local! {
3662        static COLLECTOR: RefCell<Option<UrlFetchTimes>> = const { RefCell::new(None) };
3663    }
3664
3665    /// An open collection on this thread; see [`begin`].
3666    #[must_use = "a scope collects nothing once dropped"]
3667    pub struct FetchTimesScope {
3668        /// This scope opened the collection. A scope opened while another
3669        /// was open leaves the outer one collecting and reports nothing.
3670        owns: bool,
3671    }
3672
3673    /// Start collecting this thread's URL fetch times.
3674    pub fn begin() -> FetchTimesScope {
3675        let owns = COLLECTOR.with(|collector| {
3676            let mut collector = collector.borrow_mut();
3677            if collector.is_some() {
3678                return false;
3679            }
3680            *collector = Some(UrlFetchTimes::default());
3681            true
3682        });
3683        FetchTimesScope { owns }
3684    }
3685
3686    impl FetchTimesScope {
3687        /// Stop collecting. `None` when no fetch ran, or for a scope nested
3688        /// inside another.
3689        pub fn finish(mut self) -> Option<UrlFetchTimes> {
3690            if !self.owns {
3691                return None;
3692            }
3693            self.owns = false;
3694            COLLECTOR
3695                .with(|collector| collector.replace(None))
3696                .filter(|times| times.fetches > 0)
3697        }
3698    }
3699
3700    impl Drop for FetchTimesScope {
3701        fn drop(&mut self) {
3702            // An early return or a panic still closes the collection, so the
3703            // next call on this thread starts clean.
3704            if self.owns {
3705                COLLECTOR.with(|collector| collector.replace(None));
3706            }
3707        }
3708    }
3709
3710    /// Apply `update` to the open collection, if there is one.
3711    pub(super) fn record(update: impl FnOnce(&mut UrlFetchTimes)) {
3712        COLLECTOR.with(|collector| {
3713            if let Some(times) = collector.borrow_mut().as_mut() {
3714                update(times);
3715            }
3716        });
3717    }
3718}
3719
3720#[cfg(test)]
3721mod tests {
3722
3723    use super::*;
3724    use url::Url;
3725
3726    #[test]
3727    fn h_header_url_cache_preserves_ambiguous_extension() {
3728        assert_eq!(super::static_extension_for_lang_ext("h"), Some(".h"));
3729    }
3730
3731    fn write_cache_entry(storage: &Path, hash: &str, url: &str, fetched_at: u64) -> PathBuf {
3732        let dir = cache_dir(storage);
3733        fs::create_dir_all(&dir).unwrap();
3734        let meta = CacheMeta {
3735            url: url.to_string(),
3736            content_type: "text/markdown".to_string(),
3737            extension: ".md".to_string(),
3738            fetched_at,
3739            download_truncated: false,
3740            downloaded_bytes: 4,
3741            total_bytes: Some(4),
3742        };
3743        fs::write(content_path(storage, hash, ".md"), "body").unwrap();
3744        let meta_file = meta_path(storage, hash);
3745        fs::write(&meta_file, serde_json::to_vec(&meta).unwrap()).unwrap();
3746        meta_file
3747    }
3748
3749    fn cleanup_counting_reads(storage: &Path, now: u64) -> (usize, usize) {
3750        CLEANUP_META_READS.with(|reads| reads.set(0));
3751        let removed = cleanup_url_cache_at(storage, now).unwrap();
3752        (removed, CLEANUP_META_READS.with(std::cell::Cell::get))
3753    }
3754
3755    /// Every configure sweeps the URL cache, so a sweep must not reopen
3756    /// metadata files that have not changed since the previous sweep.
3757    #[test]
3758    fn url_cache_cleanup_does_not_reread_unchanged_metadata() {
3759        let storage = tempfile::tempdir().unwrap();
3760        let now = 10 * CACHE_TTL_MS;
3761        for index in 0..3 {
3762            write_cache_entry(
3763                storage.path(),
3764                &format!("fresh{index}"),
3765                "https://example.com/a",
3766                now - 1_000,
3767            );
3768        }
3769        let stale = write_cache_entry(
3770            storage.path(),
3771            "stale",
3772            "https://example.com/b",
3773            now - CACHE_TTL_MS - 1,
3774        );
3775
3776        assert_eq!(cleanup_counting_reads(storage.path(), now), (1, 4));
3777        assert!(!stale.exists());
3778        assert!(!content_path(storage.path(), "stale", ".md").exists());
3779
3780        // Nothing changed: no metadata file is opened again.
3781        assert_eq!(cleanup_counting_reads(storage.path(), now), (0, 0));
3782    }
3783
3784    /// A remembered fetch time is still compared with the current time, and a
3785    /// rewritten metadata file is read again, so the memo never keeps an entry
3786    /// alive past its TTL.
3787    #[test]
3788    fn url_cache_cleanup_memo_still_expires_and_notices_rewrites() {
3789        let storage = tempfile::tempdir().unwrap();
3790        let now = 10 * CACHE_TTL_MS;
3791        let kept = write_cache_entry(storage.path(), "kept", "https://example.com/a", now);
3792        let rewritten =
3793            write_cache_entry(storage.path(), "rewritten", "https://example.com/b", now);
3794        assert_eq!(cleanup_counting_reads(storage.path(), now), (0, 2));
3795
3796        // A different size is a different version even within one mtime tick.
3797        write_cache_entry(
3798            storage.path(),
3799            "rewritten",
3800            "https://example.com/b-longer",
3801            now - CACHE_TTL_MS - 1,
3802        );
3803        assert_eq!(cleanup_counting_reads(storage.path(), now), (1, 1));
3804        assert!(!rewritten.exists());
3805        assert!(kept.exists());
3806
3807        // The unchanged file expires from its remembered fetch time.
3808        assert_eq!(
3809            cleanup_counting_reads(storage.path(), now + CACHE_TTL_MS + 1),
3810            (1, 0)
3811        );
3812        assert!(!kept.exists());
3813    }
3814
3815    #[test]
3816    fn web_view_urls_rewrite_to_raw_content() {
3817        let cases = [
3818            (
3819                "https://github.com/owner/repo/blob/main/docs/guide.md?download=1#L42",
3820                "https://raw.githubusercontent.com/owner/repo/main/docs/guide.md?download=1",
3821            ),
3822            (
3823                "https://github.com/owner/repo/raw/v1.2/src/lib.rs?raw=1#L7",
3824                "https://raw.githubusercontent.com/owner/repo/v1.2/src/lib.rs?raw=1",
3825            ),
3826            (
3827                "https://www.github.com/owner/repo/blob/main/README.md",
3828                "https://raw.githubusercontent.com/owner/repo/main/README.md",
3829            ),
3830            (
3831                "https://gitlab.com/owner/repo/-/blob/main/docs/guide.md?plain=1#L4",
3832                "https://gitlab.com/owner/repo/-/raw/main/docs/guide.md?plain=1",
3833            ),
3834        ];
3835
3836        for (input, expected) in cases {
3837            let url = Url::parse(input).unwrap();
3838            assert_eq!(rewrite_url_for_fetch(&url).as_str(), expected);
3839        }
3840    }
3841
3842    #[test]
3843    fn non_web_view_urls_are_not_rewritten() {
3844        for input in [
3845            "https://gist.github.com/owner/abcdef/blob/main/file.md",
3846            "https://github.com/owner/repo",
3847            "https://github.com/owner/repo/blob",
3848            "https://api.github.com/repos/owner/repo",
3849            "https://notgithub.com/owner/repo/blob/main/file.md",
3850            "https://gitlab.example.com/owner/repo/-/blob/main/file.md",
3851        ] {
3852            let url = Url::parse(input).unwrap();
3853            assert_eq!(rewrite_url_for_fetch(&url).as_str(), input);
3854        }
3855    }
3856
3857    #[test]
3858    fn extension_from_path_uses_parser_mapping() {
3859        let url = Url::parse("https://example.com/pkg/index.mjs").unwrap();
3860        let (ext, from_path) = resolve_fetch_extension(&url, "text/javascript").unwrap();
3861        assert_eq!(ext, ".mjs");
3862        assert!(from_path);
3863    }
3864
3865    #[test]
3866    fn text_plain_rs_url_ignores_content_type_gate() {
3867        let url = Url::parse("https://raw.githubusercontent.com/o/r/main/lib.rs").unwrap();
3868        let (ext, from_path) = resolve_fetch_extension(&url, "text/plain").unwrap();
3869        assert_eq!(ext, ".rs");
3870        assert!(from_path);
3871    }
3872
3873    #[test]
3874    fn extensionless_javascript_maps_to_js() {
3875        let url = Url::parse("https://cdn.example/bundle").unwrap();
3876        let (ext, from_path) = resolve_fetch_extension(&url, "text/javascript").unwrap();
3877        assert_eq!(ext, ".js");
3878        assert!(!from_path);
3879    }
3880
3881    #[test]
3882    fn extensionless_plain_stays_md() {
3883        let url = Url::parse("https://example.com/readme").unwrap();
3884        let (ext, _) = resolve_fetch_extension(&url, "text/plain").unwrap();
3885        assert_eq!(ext, ".md");
3886    }
3887
3888    #[test]
3889    fn query_and_fragment_do_not_break_path_extension() {
3890        let url = Url::parse("https://example.com/src/file.ts?v=2#L10").unwrap();
3891        let (ext, from_path) = resolve_fetch_extension(&url, "text/plain").unwrap();
3892        assert_eq!(ext, ".ts");
3893        assert!(from_path);
3894    }
3895
3896    #[test]
3897    fn percent_encoded_path_segment() {
3898        let url = Url::parse("https://example.com/foo%2Fbar.rs").unwrap();
3899        // path is /foo%2Fbar.rs - segment is foo%2Fbar.rs -> decode to foo/bar.rs -> ext rs
3900        let (ext, _) = resolve_fetch_extension(&url, "text/plain").unwrap();
3901        assert_eq!(ext, ".rs");
3902    }
3903
3904    #[test]
3905    fn binary_sniff_detects_nul() {
3906        let mut body = vec![b'f', b'n', 0, b' '];
3907        assert!(body_contains_nul_in_prefix(&body));
3908        body = vec![b'h'; 9000];
3909        assert!(!body_contains_nul_in_prefix(&body));
3910    }
3911
3912    #[test]
3913    fn unsupported_pdf_still_errors_via_resolve() {
3914        let url = Url::parse("https://example.com/doc.pdf").unwrap();
3915        assert!(resolve_fetch_extension(&url, "application/pdf").is_none());
3916    }
3917
3918    #[test]
3919    fn is_permalink_anchor_doc_anchor_class_drops_anchor() {
3920        let md = html_to_markdown_converter()
3921            .convert("<a class=\"doc-anchor\" href=\"#stdio-transport\">x</a>")
3922            .unwrap();
3923        assert_eq!(
3924            md.trim(),
3925            "",
3926            "doc-anchor permalink should be dropped: {md:?}"
3927        );
3928    }
3929
3930    #[test]
3931    fn html_to_markdown_rustdoc_heading_cleanup() {
3932        let html = "<main><h1>Function <span class=\"fn\">stdio</span>&nbsp;<button id=\"copy-path\">Copy item path</button></h1><h2 class=\"location\"><a href=\"#\">stdio</a></h2><h2><a class=\"doc-anchor\" href=\"#stdio-transport\">§</a>StdIO Transport</h2></main>";
3933        let md = html_to_markdown_converter().convert(html).unwrap();
3934        assert!(md.contains("# Function stdio"), "{md:?}");
3935        assert!(!md.contains("Copy item path"), "{md:?}");
3936        assert!(md.contains("## stdio"), "{md:?}");
3937        assert!(!md.contains("[stdio](#)"), "{md:?}");
3938        assert!(md.contains("## StdIO Transport"), "{md:?}");
3939        assert!(!md.contains('§'), "{md:?}");
3940        assert!(!md.contains("](#stdio-transport)"), "{md:?}");
3941    }
3942
3943    #[test]
3944    fn html_to_markdown_docusaurus_hash_link_still_dropped() {
3945        let html = "<h2>The Retain Pipeline<a class=\"hash-link\" href=\"#x\" aria-label=\"Direct link to The Retain Pipeline\">\u{200b}</a></h2>";
3946        let md = html_to_markdown_converter().convert(html).unwrap();
3947        assert!(md.contains("## The Retain Pipeline"), "{md:?}");
3948        assert!(!md.contains('\u{200b}'), "{md:?}");
3949    }
3950
3951    const CHROME_AUTO_CONNECT_HTML: &str =
3952        include_str!("../../aft/tests/fixtures/url_html/chrome_auto_connect.html");
3953
3954    /// The fenced blocks of `markdown` as (opening fence line, body). Body
3955    /// lines lose only the indentation the opening fence has (a list item's
3956    /// indent), so the code's own indentation is compared as written.
3957    fn fenced_blocks(markdown: &str) -> Vec<(String, String)> {
3958        let mut blocks = Vec::new();
3959        let mut open: Option<(String, usize, Vec<String>)> = None;
3960        for line in markdown.lines() {
3961            let trimmed = line.trim_start();
3962            match open.take() {
3963                None => {
3964                    if trimmed.starts_with("```") {
3965                        let indent = line.len() - trimmed.len();
3966                        open = Some((trimmed.to_string(), indent, Vec::new()));
3967                    }
3968                }
3969                Some((fence_line, indent, mut body)) => {
3970                    let fence: String = fence_line.chars().take_while(|c| *c == '`').collect();
3971                    if trimmed == fence {
3972                        blocks.push((fence_line, body.join("\n")));
3973                    } else {
3974                        let unindented = line
3975                            .strip_prefix(&" ".repeat(indent))
3976                            .unwrap_or(line.trim_start());
3977                        body.push(unindented.to_string());
3978                        open = Some((fence_line, indent, body));
3979                    }
3980                }
3981            }
3982        }
3983        assert!(open.is_none(), "unclosed fence in {markdown}");
3984        blocks
3985    }
3986
3987    #[test]
3988    fn html_to_markdown_pre_closed_code_early_stays_one_fenced_block() {
3989        // The live page closes </code> inside the "chrome-devtools-mcp@latest"
3990        // string; everything after it must still land inside the same fence.
3991        let md = html_to_markdown_converter()
3992            .convert(CHROME_AUTO_CONNECT_HTML)
3993            .unwrap();
3994        let blocks = fenced_blocks(&md);
3995        assert_eq!(blocks.len(), 1, "{md}");
3996        let (fence_line, body) = &blocks[0];
3997        assert_eq!(fence_line, "```", "{md}");
3998        assert_eq!(
3999            body,
4000            concat!(
4001                "{\n",
4002                "  \"mcpServers\": {\n",
4003                "    \"chrome-devtools\": {\n",
4004                "      \"command\": \"npx\",\n",
4005                "      \"args\": [\"chrome-devtools-mcp@latest\", \"--autoConnect\"]\n",
4006                "    }\n",
4007                "  }\n",
4008                "}",
4009            ),
4010            "{md}"
4011        );
4012        assert!(
4013            md.contains(r#""args": ["chrome-devtools-mcp@latest", "--autoConnect"]"#),
4014            "{md}"
4015        );
4016        assert!(!md.contains("```ome"), "{md}");
4017    }
4018
4019    #[test]
4020    fn html_to_markdown_pre_keeps_code_verbatim() {
4021        let html = "<pre><code class=\"language-md\">line *one*\n\n\n\n  # not a heading &lt;b&gt;\n</code></pre>";
4022        let md = html_to_markdown_converter().convert(html).unwrap();
4023        assert_eq!(
4024            md.trim(),
4025            "```md\nline *one*\n\n\n\n  # not a heading <b>\n```",
4026            "{md:?}"
4027        );
4028    }
4029
4030    #[test]
4031    fn html_to_markdown_code_containing_triple_backticks_gets_longer_fence() {
4032        let html = "<pre><code>Example:\n```rust\nfn main() {}\n```\n</code></pre>";
4033        let md = html_to_markdown_converter().convert(html).unwrap();
4034        assert_eq!(
4035            md.trim(),
4036            "````\nExample:\n```rust\nfn main() {}\n```\n````",
4037            "{md:?}"
4038        );
4039
4040        let html = "<pre><code>a ````` run</code></pre>";
4041        let md = html_to_markdown_converter().convert(html).unwrap();
4042        assert_eq!(md.trim(), "``````\na ````` run\n``````", "{md:?}");
4043    }
4044
4045    #[test]
4046    fn html_to_markdown_pre_without_code_keeps_htmd_rendering() {
4047        let html = "<pre>plain preformatted</pre>";
4048        let md = html_to_markdown_converter().convert(html).unwrap();
4049        assert!(!md.contains("```"), "{md:?}");
4050        assert!(md.contains("plain preformatted"), "{md:?}");
4051    }
4052
4053    #[test]
4054    fn html_to_markdown_pre_per_line_divs_keep_their_lines() {
4055        let md = html_to_markdown_converter()
4056            .convert(include_str!(
4057                "../../aft/tests/fixtures/url_html/per_line_divs.html"
4058            ))
4059            .unwrap();
4060        let blocks = fenced_blocks(&md);
4061        assert_eq!(blocks.len(), 1, "{md}");
4062        // The template literal's single backticks leave the fence at three.
4063        assert_eq!(blocks[0].0, "```js", "{md}");
4064        assert_eq!(
4065            blocks[0].1, "function greet(name) {\n  return `Hello, ${name}`;\n\n}",
4066            "{md}"
4067        );
4068    }
4069
4070    #[test]
4071    fn html_to_markdown_pre_table_rows_keep_their_lines() {
4072        let md = html_to_markdown_converter()
4073            .convert(include_str!(
4074                "../../aft/tests/fixtures/url_html/table_rows.html"
4075            ))
4076            .unwrap();
4077        let blocks = fenced_blocks(&md);
4078        assert_eq!(blocks.len(), 1, "{md}");
4079        assert_eq!(blocks[0].0, "```python", "{md}");
4080        assert_eq!(
4081            blocks[0].1, "def add(a, b):\n    return a + b\n\nprint(add(1, 2))",
4082            "{md}"
4083        );
4084    }
4085
4086    #[test]
4087    fn html_to_markdown_pre_shiki_line_spans_keep_their_lines() {
4088        let md = html_to_markdown_converter()
4089            .convert(include_str!(
4090                "../../aft/tests/fixtures/url_html/shiki_lines.html"
4091            ))
4092            .unwrap();
4093        let blocks = fenced_blocks(&md);
4094        assert_eq!(blocks.len(), 1, "{md}");
4095        assert_eq!(blocks[0].0, "```", "{md}");
4096        assert_eq!(
4097            blocks[0].1,
4098            "const total = items.reduce((sum, item) => sum + item.price, 0);\n\nconsole.log(total);",
4099            "{md}"
4100        );
4101    }
4102
4103    #[test]
4104    fn html_to_markdown_pre_list_item_lines_keep_their_lines() {
4105        let html = "<pre><code><ol><li>first</li><li></li><li>  third</li></ol></code></pre>";
4106        let md = html_to_markdown_converter().convert(html).unwrap();
4107        assert_eq!(md.trim(), "```\nfirst\n\n  third\n```", "{md:?}");
4108    }
4109
4110    #[test]
4111    fn html_to_markdown_pre_newline_text_between_lines_is_not_doubled() {
4112        // Lines that already end in newline text must not gain a second break.
4113        let html = "<pre><code><span class=\"line\">a</span>\n<span class=\"line\">b</span>\n<div>c\n</div></code></pre>";
4114        let md = html_to_markdown_converter().convert(html).unwrap();
4115        assert_eq!(md.trim(), "```\na\nb\nc\n```", "{md:?}");
4116    }
4117
4118    #[test]
4119    fn code_fence_for_outgrows_longest_backtick_run() {
4120        assert_eq!(code_fence_for("no ticks"), "```");
4121        assert_eq!(code_fence_for("`inline` ``double``"), "```");
4122        assert_eq!(code_fence_for("```"), "````");
4123        assert_eq!(code_fence_for("``` and ````"), "`````");
4124    }
4125
4126    /// htmd decodes an HTML entity into its character and then escapes that
4127    /// character for Markdown, so the converted text spells a key in a form
4128    /// the byte matchers alone do not recognise.
4129    #[test]
4130    fn html_conversion_markdown_escapes_an_entity_decoded_character() {
4131        let markdown =
4132            convert_html_body_to_markdown(b"<p>abcdef&#42;1234567890</p>", "https://example.test/")
4133                .unwrap();
4134        let text = String::from_utf8(markdown).unwrap();
4135        assert!(text.contains("abcdef\\*1234567890"), "{text}");
4136    }
4137
4138    /// The text of a failed body read can name the request URL, which held
4139    /// the key in a placeholder fetch; it is scrubbed before it is reported.
4140    #[test]
4141    fn a_failed_body_read_in_a_placeholder_fetch_is_scrubbed_of_held_keys() {
4142        struct Failing;
4143        impl Read for Failing {
4144            fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
4145                Err(io::Error::other(
4146                    "error reading body for url (https://api.test/v1?key=fetch-secret-key%2F0123456789%2Babc)",
4147                ))
4148            }
4149        }
4150        let mut held = HeldKeys::default();
4151        held.hold("test", b"fetch-secret-key/0123456789+abc")
4152            .unwrap();
4153        let deadline = FetchDeadline::for_current_call();
4154        let sanitize = |detail: &str| held.sanitize_detail(detail);
4155        let error = read_response_body_with(Failing, "https://api.test/v1", &deadline, &sanitize)
4156            .expect_err("the read fails");
4157        let text = error.to_string();
4158        assert!(!text.contains("fetch-secret-key"), "{text}");
4159        assert!(text.contains("key={{ck-secret:test}})"), "{text}");
4160    }
4161
4162    /// reqwest prints the request URL in its own error text; a placeholder
4163    /// fetch's failure must drop it (the URL held the key), not merely scrub
4164    /// the key out of it.
4165    #[test]
4166    fn a_placeholder_fetch_send_failure_drops_the_request_url() {
4167        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4168        let addr = listener.local_addr().unwrap();
4169        thread::spawn(move || {
4170            // Accept one connection and hold it open without answering.
4171            let accepted = listener.accept();
4172            thread::sleep(Duration::from_secs(5));
4173            drop(accepted);
4174        });
4175        let url = format!("http://{addr}/v1?key=fetch-secret-key%2F0123456789%2Babc");
4176        let error = Client::builder()
4177            .timeout(Duration::from_millis(300))
4178            .build()
4179            .unwrap()
4180            .get(&url)
4181            .send()
4182            .expect_err("the silent server times the request out");
4183        assert!(error.to_string().contains("for url"), "{error}");
4184        let mut held = HeldKeys::default();
4185        held.hold("test", b"fetch-secret-key/0123456789+abc")
4186            .unwrap();
4187        let deadline = FetchDeadline::for_current_call();
4188        let failure = send_failure(
4189            error,
4190            Some(FetchPhase::Headers),
4191            &deadline,
4192            "http://api.test/v1?key={{ck-secret:test}}",
4193            Some(&held),
4194        );
4195        let text = failure.to_string();
4196        assert!(text.contains("timed out"), "{text}");
4197        assert!(!text.contains("for url"), "{text}");
4198        assert!(!text.contains("fetch-secret-key"), "{text}");
4199    }
4200
4201    #[test]
4202    fn deprecated_site_local_ipv6_is_private() {
4203        for address in ["fec0::1", "feff::1", "fef0:1::1"] {
4204            let ip: IpAddr = address.parse().unwrap();
4205            assert!(is_private_ip(ip), "{address}");
4206        }
4207        assert!(!is_private_ip("2606:4700::1".parse().unwrap()));
4208    }
4209}
4210
4211#[cfg(any(test, feature = "test-support"))]
4212/// The fetch times the slow-call line reports, measured against local
4213/// servers that are slow in a known phase.
4214#[path = "url_fetch_deadline_tests.rs"]
4215#[cfg_attr(not(test), allow(dead_code, unused_imports))]
4216pub mod deadline_tests;
4217
4218#[cfg(test)]
4219mod fetch_times_tests {
4220    use super::timing::UrlFetchTimes;
4221    use super::*;
4222    use std::net::TcpListener;
4223
4224    const DOCUMENT: &[u8] = b"# Guide\n\n## Install\n\nRun the installer.\n";
4225
4226    /// Answers every connection: reads the request head, waits
4227    /// `before_headers`, sends the response headers, waits `before_body`,
4228    /// then sends [`DOCUMENT`] and closes.
4229    fn slow_server(before_headers: Duration, before_body: Duration) -> SocketAddr {
4230        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
4231        let address = listener.local_addr().expect("test server address");
4232        thread::spawn(move || {
4233            for mut stream in listener.incoming().flatten() {
4234                thread::spawn(move || {
4235                    let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
4236                    let mut head = Vec::new();
4237                    let mut buffer = [0u8; 1024];
4238                    while !head.windows(4).any(|window| window == b"\r\n\r\n") {
4239                        match stream.read(&mut buffer) {
4240                            Ok(0) | Err(_) => return,
4241                            Ok(n) => head.extend_from_slice(&buffer[..n]),
4242                        }
4243                    }
4244                    thread::sleep(before_headers);
4245                    let headers = format!(
4246                        "HTTP/1.1 200 OK\r\ncontent-type: text/markdown\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
4247                        DOCUMENT.len()
4248                    );
4249                    if stream.write_all(headers.as_bytes()).is_err() {
4250                        return;
4251                    }
4252                    let _ = stream.flush();
4253                    thread::sleep(before_body);
4254                    let _ = stream.write_all(DOCUMENT);
4255                });
4256            }
4257        });
4258        address
4259    }
4260
4261    fn local() -> UrlFetchOptions {
4262        UrlFetchOptions {
4263            allow_private: true,
4264            ..UrlFetchOptions::default()
4265        }
4266    }
4267
4268    /// One fetch under a call budget, inside a fetch-times scope.
4269    fn timed_fetch(
4270        budget: Duration,
4271        url: &str,
4272        storage: &Path,
4273    ) -> (Result<PathBuf, UrlFetchError>, UrlFetchTimes) {
4274        let _call = crate::bounded_io::enter(Some(crate::bounded_io::Budget::after(budget)));
4275        let scope = timing::begin();
4276        let result = fetch_url_to_cache(url, storage, local());
4277        let times = scope.finish().expect("the fetch was counted");
4278        (result, times)
4279    }
4280
4281    #[test]
4282    fn url_fetch_times_split_a_slow_download_and_count_a_cache_hit() {
4283        let storage = tempfile::tempdir().unwrap();
4284        let address = slow_server(Duration::from_millis(300), Duration::from_millis(200));
4285        let url = format!("http://127.0.0.1:{}/guide.md", address.port());
4286
4287        let (result, times) = timed_fetch(Duration::from_secs(10), &url, storage.path());
4288        result.expect("the slow server answers within the deadline");
4289        assert_eq!(times.fetches, 1, "{times:?}");
4290        assert_eq!(times.cache_hits, 0, "{times:?}");
4291        assert_eq!(times.remembered_failures, 0, "{times:?}");
4292        assert_eq!((times.redirects, times.retries), (0, 0), "{times:?}");
4293        assert_eq!(times.error, None, "{times:?}");
4294        // The server held the headers 300 ms after it read the request, and
4295        // the body another 200 ms after the headers.
4296        assert!(times.first_byte >= Duration::from_millis(300), "{times:?}");
4297        assert!(times.connect <= times.first_byte, "{times:?}");
4298        assert!(times.body >= Duration::from_millis(150), "{times:?}");
4299        assert_eq!(times.body_bytes, DOCUMENT.len() as u64, "{times:?}");
4300        let rendered = times.render();
4301        assert!(
4302            rendered.starts_with("url_fetch=fetches:1,cache_hits:0,remembered:0,"),
4303            "{rendered}"
4304        );
4305        assert!(!rendered.contains("guide"), "{rendered}");
4306        assert!(!rendered.contains(' '), "{rendered}");
4307
4308        // The same URL again is served from the cache: no request, no body.
4309        let (result, times) = timed_fetch(Duration::from_secs(10), &url, storage.path());
4310        result.expect("the cached copy is served");
4311        assert_eq!((times.fetches, times.cache_hits), (1, 1), "{times:?}");
4312        assert_eq!(times.first_byte, Duration::ZERO, "{times:?}");
4313        assert_eq!(times.body_bytes, 0, "{times:?}");
4314    }
4315
4316    #[test]
4317    fn url_fetch_times_name_a_timeout_and_its_phase() {
4318        let storage = tempfile::tempdir().unwrap();
4319        let address = slow_server(Duration::from_secs(60), Duration::ZERO);
4320        let url = format!("http://127.0.0.1:{}/silent.md", address.port());
4321        // A 5 s call budget leaves the fetch a 2 s deadline (see
4322        // `FetchDeadline::for_current_call`).
4323        let (result, times) = timed_fetch(Duration::from_secs(5), &url, storage.path());
4324        let error = result.expect_err("a server that never answers fails");
4325        assert_eq!(error.code(), "url_fetch_timeout", "{error}");
4326        assert_eq!(
4327            times.error,
4328            Some(("url_fetch_timeout", Some(FetchPhase::Headers))),
4329            "{times:?}"
4330        );
4331        assert!(
4332            times.first_byte >= Duration::from_millis(1_500),
4333            "{times:?}"
4334        );
4335        assert_eq!(times.body_bytes, 0, "{times:?}");
4336        assert!(
4337            times.render().ends_with(",error:url_fetch_timeout/headers"),
4338            "{}",
4339            times.render()
4340        );
4341    }
4342
4343    #[test]
4344    fn url_fetch_times_collect_only_inside_the_outermost_scope() {
4345        timing::record(|times| times.fetches += 1);
4346        assert_eq!(timing::begin().finish(), None, "nothing ran in this scope");
4347
4348        let outer = timing::begin();
4349        let inner = timing::begin();
4350        timing::record(|times| times.fetches += 1);
4351        assert_eq!(inner.finish(), None);
4352        timing::record(|times| times.fetches += 1);
4353        assert_eq!(outer.finish().map(|times| times.fetches), Some(2));
4354
4355        drop(timing::begin());
4356        timing::record(|times| times.fetches += 1);
4357        assert_eq!(timing::begin().finish(), None, "a dropped scope closed");
4358    }
4359
4360    #[test]
4361    fn url_fetch_times_render_every_field_in_milliseconds() {
4362        let times = UrlFetchTimes {
4363            fetches: 2,
4364            cache_hits: 1,
4365            remembered_failures: 0,
4366            lookup: Duration::from_micros(2_100),
4367            connect: Duration::from_millis(40),
4368            first_byte: Duration::from_micros(5_800_004),
4369            body: Duration::from_millis(300),
4370            body_bytes: 51_234,
4371            convert: Duration::from_millis(4),
4372            redirects: 1,
4373            retries: 0,
4374            error: Some(("url_fetch_failed", None)),
4375        };
4376        assert_eq!(
4377            times.render(),
4378            "url_fetch=fetches:2,cache_hits:1,remembered:0,lookup:2.10,connect:40.00,first_byte:5800.00,body:300.00,bytes:51234,convert:4.00,redirects:1,retries:0,error:url_fetch_failed"
4379        );
4380    }
4381}
4382
4383#[cfg(test)]
4384mod secret_audit_regressions {
4385    use super::*;
4386    #[test]
4387    fn substituted_query_allocates_its_exact_complete_size_before_copying_any_key() {
4388        let first = Zeroizing::new(vec![b'a'; 1001]);
4389        let second = Zeroizing::new(vec![b'b'; 2103]);
4390        let result = substitute_query(b"a=x&b=y", &[(2, 3, first), (6, 7, second)]).unwrap();
4391        assert_eq!(result.len(), 5 + 1001 + 2103);
4392        assert_eq!(
4393            result.capacity(),
4394            result.len(),
4395            "a later key must not reallocate a buffer that already contains an earlier key"
4396        );
4397        assert_eq!(&result[..2], b"a=");
4398        assert_eq!(&result[1003..1006], b"&b=");
4399    }
4400    #[test]
4401    fn approval_wait_preserves_the_fetch_and_read_back_network_budget() {
4402        let _scope = crate::bounded_io::enter(Some(crate::bounded_io::Budget::after(
4403            Duration::from_secs(25),
4404        )));
4405        let before = crate::bounded_io::current().unwrap().deadline;
4406        let deadline = FetchDeadline::for_current_call();
4407        let person_wait = Duration::from_secs(360);
4408        crate::bounded_io::exclude_secret_approval_wait(person_wait);
4409        assert_eq!(
4410            crate::bounded_io::current().unwrap().deadline,
4411            before + person_wait
4412        );
4413        assert_eq!(deadline.allowed, URL_FETCH_CEILING);
4414    }
4415}