use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fs;
use std::io::{self, Read, Write};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use htmd::{
element_handler::{HandlerResult, Handlers},
Element, HtmlToMarkdown,
};
use markup5ever_rcdom::{Node, NodeData};
use reqwest::blocking::{Client, Response as HttpResponse};
use reqwest::header::{
ACCEPT, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_TYPE, LOCATION, USER_AGENT,
};
use reqwest::redirect::Policy;
use secret_rules::audit::{AuditReason, AuditRecordV1, Decision};
use secret_rules::location::{
evaluate_request_with_connect, location_kind_token, LabelOutcome, LabelRule, Location,
RequestView,
};
use secret_rules::material::{check_admissible, encode_for_location};
use secret_rules::scrub::{MatcherSet, ScrubError, Scrubber};
use secret_rules::target::{normalize_request_target, ConnectAuthority};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use url::Url;
use zeroize::Zeroizing;
use crate::lang_id::language_by_extension;
#[path = "url_fetch_sensitive.rs"]
#[cfg(not(any(test, feature = "test-support")))]
mod sensitive;
#[path = "url_fetch_sensitive.rs"]
#[cfg(any(test, feature = "test-support"))]
pub mod sensitive;
const MAX_RESPONSE_BYTES: u64 = 8 * 1024 * 1024;
const CACHE_TTL_MS: u64 = 24 * 60 * 60 * 1000;
const CONNECT_TIMEOUT: Duration = Duration::from_millis(10_000);
const HEADERS_TIMEOUT: Duration = Duration::from_millis(15_000);
const BODY_CHUNK_TIMEOUT: Duration = Duration::from_millis(15_000);
const MAX_REDIRECTS: usize = 5;
const URL_FETCH_CEILING: Duration = Duration::from_secs(20);
pub const URL_REPLY_MARGIN: Duration = Duration::from_secs(1);
const URL_READ_BACK_RESERVE: Duration = Duration::from_secs(2);
const RESIDUAL_CHECK_RESERVE: Duration = Duration::from_millis(1500);
const MIN_USEFUL_ATTEMPT: Duration = Duration::from_secs(1);
const TRANSIENT_RETRY_ATTEMPTS: usize = 2;
const TRANSIENT_RETRY_BACKOFFS_MS: [u64; TRANSIENT_RETRY_ATTEMPTS] = [200, 600];
const 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";
const USER_AGENT_VALUE: &str = "aft-opencode-plugin";
const CONVERTED_MARKDOWN_CONTENT_TYPE: &str = "text/markdown; charset=utf-8";
#[derive(Clone, Default)]
pub struct UrlFetchOptions {
pub allow_private: bool,
#[doc(hidden)]
pub public_host_overrides: Vec<(String, Vec<IpAddr>)>,
#[doc(hidden)]
pub connect_overrides: Vec<(String, SocketAddr)>,
#[doc(hidden)]
pub atomic_write_observer: Option<Arc<dyn Fn(&Path, &Path) + Send + Sync>>,
#[doc(hidden)]
pub lookup_override: Option<HostLookup>,
#[doc(hidden)]
pub connect_delay: Option<Duration>,
#[doc(hidden)]
pub tls_config: Option<rustls::ClientConfig>,
#[cfg(all(unix, any(test, feature = "test-support")))]
#[doc(hidden)]
pub reply_clock_for_test: Option<ReplyClock>,
}
#[cfg(all(unix, any(test, feature = "test-support")))]
type ReplyClock = Arc<dyn Fn() -> Instant + Send + Sync>;
pub type HostLookup = Arc<dyn Fn(&str) -> io::Result<Vec<IpAddr>> + Send + Sync>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FetchPhase {
Dns,
Connect,
Headers,
Body,
}
impl FetchPhase {
pub fn as_str(self) -> &'static str {
match self {
Self::Dns => "dns",
Self::Connect => "connect",
Self::Headers => "headers",
Self::Body => "body",
}
}
}
#[derive(Debug, Clone)]
pub struct UrlFetchError {
code: &'static str,
message: String,
phase: Option<FetchPhase>,
status: Option<u16>,
retry_after: Option<Duration>,
cut_by_call_budget: bool,
}
impl UrlFetchError {
fn new(message: impl Into<String>) -> Self {
Self {
code: "url_fetch_failed",
message: message.into(),
phase: None,
status: None,
retry_after: None,
cut_by_call_budget: false,
}
}
fn timeout(phase: FetchPhase, message: impl Into<String>) -> Self {
Self {
code: "url_fetch_timeout",
phase: Some(phase),
..Self::new(message)
}
}
fn secret(code: &'static str, message: impl Into<String>) -> Self {
Self {
code,
..Self::new(message)
}
}
fn after_secret_sent(mut self) -> Self {
if let Some(rest) = self.message.strip_prefix(SECRET_FETCH_REFUSED) {
self.message = format!("{SECRET_FETCH_REFUSED_AFTER_SEND}{rest}");
}
self
}
fn http_status(status: u16, message: impl Into<String>) -> Self {
Self {
status: Some(status),
..Self::new(message)
}
}
pub fn code(&self) -> &'static str {
self.code
}
pub fn phase(&self) -> Option<FetchPhase> {
self.phase
}
pub fn retry_after(&self) -> Option<Duration> {
self.retry_after
}
fn worth_remembering(&self) -> bool {
if self.cut_by_call_budget || self.retry_after.is_some() {
return false;
}
self.code == "url_fetch_timeout"
|| self
.status
.is_some_and(|status| status >= 400 && status != 408 && status != 429)
}
}
#[derive(Debug, Clone, Copy)]
struct FetchDeadline {
at: Instant,
allowed: Duration,
set_by_call: bool,
}
impl FetchDeadline {
fn for_current_call() -> Self {
let now = Instant::now();
let ceiling = now + URL_FETCH_CEILING;
let at = match crate::bounded_io::current() {
Some(budget) => budget
.deadline
.checked_sub(URL_REPLY_MARGIN + URL_READ_BACK_RESERVE)
.unwrap_or(now)
.clamp(now, ceiling),
None => ceiling,
};
Self {
at,
allowed: at.saturating_duration_since(now),
set_by_call: at < ceiling,
}
}
fn remaining(&self) -> Duration {
self.at.saturating_duration_since(Instant::now())
}
fn expired(&self) -> bool {
self.remaining().is_zero()
}
fn timeout_error(&self, phase: FetchPhase, url: &str) -> UrlFetchError {
UrlFetchError {
cut_by_call_budget: self.set_by_call,
..UrlFetchError::timeout(
phase,
format!(
"URL fetch timed out in the {} phase: the {}ms fetch deadline elapsed fetching {url}",
phase.as_str(),
self.allowed.as_millis()
),
)
}
}
}
impl fmt::Display for UrlFetchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for UrlFetchError {}
#[derive(Debug, Serialize, Deserialize)]
struct CacheMeta {
url: String,
#[serde(rename = "contentType")]
content_type: String,
extension: String,
#[serde(rename = "fetchedAt")]
fetched_at: u64,
#[serde(default)]
download_truncated: bool,
#[serde(default)]
downloaded_bytes: usize,
#[serde(default)]
total_bytes: Option<u64>,
}
pub fn is_http_url(value: &str) -> bool {
value.starts_with("http://") || value.starts_with("https://")
}
pub fn fetch_url_to_cache(
url: &str,
storage_dir: &Path,
options: UrlFetchOptions,
) -> Result<PathBuf, UrlFetchError> {
let key = FailureKey::new(storage_dir, url, options.allow_private);
let result = download_to_cache(url, storage_dir, options, &key);
record_fetch(&result);
match &result {
Ok(_) => forget_failure(&key),
Err(error) if error.worth_remembering() => remember_failure(key, error),
Err(_) => {}
}
result
}
fn record_fetch<T>(result: &Result<T, UrlFetchError>) {
timing::record(|times| {
times.fetches += 1;
if let Err(error) = result {
times.error = Some((error.code(), error.phase()));
}
});
}
const FAILURE_MEMORY: Duration = Duration::from_secs(60);
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct FailureKey {
storage_dir: PathBuf,
url: String,
allow_private: bool,
}
impl FailureKey {
fn new(storage_dir: &Path, url: &str, allow_private: bool) -> Self {
Self {
storage_dir: storage_dir.to_path_buf(),
url: url.to_string(),
allow_private,
}
}
}
struct RememberedFailure {
error: UrlFetchError,
at: Instant,
}
fn failure_memory() -> &'static std::sync::Mutex<HashMap<FailureKey, RememberedFailure>> {
static FAILURES: std::sync::OnceLock<std::sync::Mutex<HashMap<FailureKey, RememberedFailure>>> =
std::sync::OnceLock::new();
FAILURES.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}
fn remembered_failure(key: &FailureKey) -> Option<UrlFetchError> {
let failures = failure_memory()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let remembered = failures.get(key)?;
let age = remembered.at.elapsed();
let retry_after = FAILURE_MEMORY
.checked_sub(age)
.filter(|left| !left.is_zero())?;
let mut error = remembered.error.clone();
error.message = format!(
"{} (cached failure from {}s ago; this URL is fetched again after {}s)",
error.message,
age.as_secs(),
retry_after.as_secs_f64().ceil() as u64
);
error.retry_after = Some(retry_after);
Some(error)
}
fn remember_failure(key: FailureKey, error: &UrlFetchError) {
let mut failures = failure_memory()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
failures.retain(|_, remembered| remembered.at.elapsed() < FAILURE_MEMORY);
failures.insert(
key,
RememberedFailure {
error: error.clone(),
at: Instant::now(),
},
);
}
fn forget_failure(key: &FailureKey) {
failure_memory()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(key);
}
#[cfg(any(test, feature = "test-support"))]
#[derive(Default)]
struct CacheReadStall {
reached: std::sync::atomic::AtomicUsize,
released: std::sync::Mutex<bool>,
release: std::sync::Condvar,
}
#[cfg(any(test, feature = "test-support"))]
impl CacheReadStall {
#[cfg_attr(not(test), allow(dead_code))]
fn release(&self) {
*self.released.lock().unwrap() = true;
self.release.notify_all();
}
}
#[cfg(any(test, feature = "test-support"))]
fn cache_read_stalls() -> &'static std::sync::Mutex<HashMap<PathBuf, Arc<CacheReadStall>>> {
static STALLS: std::sync::OnceLock<std::sync::Mutex<HashMap<PathBuf, Arc<CacheReadStall>>>> =
std::sync::OnceLock::new();
STALLS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code))]
fn stall_cache_reads(storage_dir: &Path) -> Arc<CacheReadStall> {
let stall = Arc::new(CacheReadStall::default());
cache_read_stalls()
.lock()
.unwrap()
.insert(storage_dir.to_path_buf(), Arc::clone(&stall));
stall
}
#[cfg(any(test, feature = "test-support"))]
fn stall_cache_read_if_requested(storage_dir: &Path) {
let Some(stall) = cache_read_stalls()
.lock()
.unwrap()
.get(storage_dir)
.cloned()
else {
return;
};
stall
.reached
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let released = stall.released.lock().unwrap();
let _ = stall
.release
.wait_timeout_while(released, Duration::from_secs(10), |released| !*released);
}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code))]
fn age_remembered_failure(key: &FailureKey, by: Duration) {
if let Some(remembered) = failure_memory()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get_mut(key)
{
remembered.at = remembered
.at
.checked_sub(by)
.expect("clock far enough along");
}
}
struct CacheCheckInput {
storage_dir: PathBuf,
hash: String,
meta_file: PathBuf,
url: Url,
}
type CacheCheckResult = Result<Option<PathBuf>, UrlFetchError>;
#[derive(Default)]
struct CacheCheck {
result: std::sync::Mutex<Option<CacheCheckResult>>,
done: std::sync::Condvar,
}
fn cache_checks() -> &'static std::sync::Mutex<HashMap<FailureKey, Arc<CacheCheck>>> {
static CHECKS: std::sync::OnceLock<std::sync::Mutex<HashMap<FailureKey, Arc<CacheCheck>>>> =
std::sync::OnceLock::new();
CHECKS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}
fn cache_check_deadline() -> Instant {
let now = Instant::now();
let ceiling = now + URL_FETCH_CEILING;
match crate::bounded_io::current() {
Some(budget) => budget
.deadline
.checked_sub(URL_REPLY_MARGIN)
.unwrap_or(now)
.clamp(now, ceiling),
None => ceiling,
}
}
fn bounded_cache_check(
key: &FailureKey,
input: CacheCheckInput,
deadline: Instant,
) -> CacheCheckResult {
let check = {
let mut checks = cache_checks()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match checks.get(key) {
Some(running) => Arc::clone(running),
None => {
let check = Arc::new(CacheCheck::default());
checks.insert(key.clone(), Arc::clone(&check));
let worker = Arc::clone(&check);
let worker_key = key.clone();
thread::spawn(move || {
let result = fresh_cached_path(
&input.storage_dir,
&input.hash,
&input.meta_file,
&input.url,
);
*worker
.result
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(result);
worker.done.notify_all();
cache_checks()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(&worker_key);
});
check
}
}
};
let mut result = check
.result
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
loop {
if let Some(result) = result.as_ref() {
return result.clone();
}
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
return Ok(None);
}
result = check
.done
.wait_timeout(result, left)
.unwrap_or_else(std::sync::PoisonError::into_inner)
.0;
}
}
fn download_to_cache(
url: &str,
storage_dir: &Path,
options: UrlFetchOptions,
failure_key: &FailureKey,
) -> Result<PathBuf, UrlFetchError> {
let parsed = Url::parse(url).map_err(|_| UrlFetchError::new(format!("Invalid URL: {url}")))?;
let deadline = FetchDeadline::for_current_call();
let fetch_url = rewrite_url_for_fetch(&parsed);
let approved = Arc::new(ApprovedHosts::default());
let hash = hash_url(url);
let meta_file = meta_path(storage_dir, &hash);
if let Some(remembered) = remembered_failure(failure_key) {
let check = CacheCheckInput {
storage_dir: storage_dir.to_path_buf(),
hash,
meta_file,
url: fetch_url.clone(),
};
let Some(cached) = bounded_cache_check(failure_key, check, cache_check_deadline())? else {
timing::record(|times| times.remembered_failures += 1);
return Err(remembered);
};
validate_public_url(&fetch_url, &options, &deadline, &approved)?;
timing::record(|times| times.cache_hits += 1);
return Ok(cached);
}
let dir = cache_dir(storage_dir);
crate::private_storage::open_dir(storage_dir, &dir).map_err(|error| {
UrlFetchError::new(format!(
"Failed to create URL cache directory {}: {error}",
dir.display()
))
})?;
let cached = fresh_cached_path(storage_dir, &hash, &meta_file, &fetch_url)?;
validate_public_url(&fetch_url, &options, &deadline, &approved)?;
if let Some(cached) = cached {
timing::record(|times| times.cache_hits += 1);
return Ok(cached);
}
let response = fetch_with_redirects(&fetch_url, url, &options, &deadline, approved)?;
if !response.status().is_success() {
return Err(UrlFetchError::http_status(
response.status().as_u16(),
format!(
"HTTP {} {} fetching {url}",
response.status().as_u16(),
response.status().canonical_reason().unwrap_or("")
),
));
}
let content_type = response
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or("text/plain")
.to_string();
let (extension, from_source_path) =
resolve_fetch_extension(&fetch_url, &content_type).ok_or_else(|| {
UrlFetchError::new(format!(
"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)"
))
})?;
let total_bytes = response.content_length();
let (mut body, download_truncated) = read_response_body(response, url, &deadline)?;
let downloaded_bytes = body.len();
if download_truncated {
if let Err(error) = std::str::from_utf8(&body) {
if error.error_len().is_none() {
body.truncate(error.valid_up_to());
}
}
}
if from_source_path && body_contains_nul_in_prefix(&body) {
return Err(UrlFetchError::new(format!(
"Binary content detected for source URL {url}"
)));
}
let (body, content_type, extension) = if extension == ".html" {
(
convert_html_body_to_markdown(&body, url)?,
CONVERTED_MARKDOWN_CONTENT_TYPE.to_string(),
".md",
)
} else {
(body, content_type, extension)
};
let content_file = content_path(storage_dir, &hash, extension);
atomic_write(&content_file, &body, &options)?;
let meta = CacheMeta {
url: url.to_string(),
content_type,
extension: extension.to_string(),
fetched_at: now_ms(),
download_truncated,
downloaded_bytes,
total_bytes,
};
let meta_bytes = serde_json::to_vec(&meta).map_err(|error| {
UrlFetchError::new(format!("Failed to encode URL cache metadata: {error}"))
})?;
atomic_write(&meta_file, &meta_bytes, &options)?;
Ok(content_file)
}
pub fn cached_url_document(
url: &str,
storage_dir: &Path,
options: &UrlFetchOptions,
) -> Result<Option<PathBuf>, UrlFetchError> {
let parsed = Url::parse(url).map_err(|_| UrlFetchError::new(format!("Invalid URL: {url}")))?;
let deadline = FetchDeadline::for_current_call();
let fetch_url = rewrite_url_for_fetch(&parsed);
let hash = hash_url(url);
let check = CacheCheckInput {
storage_dir: storage_dir.to_path_buf(),
meta_file: meta_path(storage_dir, &hash),
hash,
url: fetch_url.clone(),
};
let key = FailureKey::new(storage_dir, url, options.allow_private);
let Some(cached) = bounded_cache_check(&key, check, cache_check_deadline())? else {
return Ok(None);
};
validate_public_url(&fetch_url, options, &deadline, &ApprovedHosts::default())?;
timing::record(|times| times.cache_hits += 1);
Ok(Some(cached))
}
pub const SECRET_FETCH_DIR: &str = "url_secret_fetch";
pub const SECRET_FETCH_REFUSED: &str =
"Secret placeholder fetch refused; no request carrying the secret was sent";
#[rustfmt::skip]
test_support_visibility! {
pub(crate) const SECRET_FETCH_REFUSED_AFTER_SEND: &str =
"Secret placeholder fetch stopped after a request carrying the secret was sent; its response was not used";
}
const SECRET_PLANNING_KEY: &[u8] = b"url-fetch-planning-value-0000";
const MAX_SECRET_CODINGS: usize = 4;
pub fn secret_labels_in_url(url: &str) -> Option<Vec<String>> {
if !secret_rules::placeholder::contains_placeholder_prefix_loose(url) {
return None;
}
let decoded = percent_decode_path_segment(url);
let mut labels: Vec<String> = Vec::new();
for text in [url, decoded.as_str()] {
for placeholder in secret_rules::placeholder::scan(text) {
if !labels.iter().any(|label| label == placeholder.label) {
labels.push(placeholder.label.to_string());
}
}
}
Some(labels)
}
pub fn create_secret_fetch_dir(storage_dir: &Path) -> Result<PathBuf, UrlFetchError> {
let parent = storage_dir.join(SECRET_FETCH_DIR);
let failed = |error: io::Error| {
UrlFetchError::new(format!(
"Failed to create a private folder for a placeholder fetch under {}: {error}",
parent.display()
))
};
crate::private_storage::open_dir(storage_dir, &parent).map_err(failed)?;
let dir = parent.join(random_nonce());
crate::private_storage::create_dir(&dir).map_err(failed)?;
Ok(dir)
}
pub struct SecretFetch {
pub vault: Arc<dyn crate::secret::SecretVault>,
pub authorization: Option<crate::secret::SecretScope>,
pub labels: Vec<String>,
#[cfg(any(test, feature = "test-support"))]
pub test_https_port: Option<u16>,
pub call_id: String,
pub cancellation: SecretFetchCancellation,
}
impl SecretFetch {
pub fn new(
vault: Arc<dyn crate::secret::SecretVault>,
authorization: Option<crate::secret::SecretScope>,
labels: Vec<String>,
test_https_port: Option<u16>,
call_id: String,
cancellation: SecretFetchCancellation,
) -> Self {
#[cfg(not(any(test, feature = "test-support")))]
let _ = test_https_port;
Self {
vault,
authorization,
labels,
#[cfg(any(test, feature = "test-support"))]
test_https_port,
call_id,
cancellation,
}
}
}
#[derive(Clone, Default)]
pub struct SecretFetchCancellation {
job: Option<crate::executor::JobCancellation>,
deadline: Option<Instant>,
#[cfg(all(unix, any(test, feature = "test-support")))]
clock: Option<ReplyClock>,
}
impl SecretFetchCancellation {
pub fn for_current_call(_options: &UrlFetchOptions) -> Self {
Self {
job: crate::executor::current_job_cancellation(),
deadline: crate::secret::call_context::current_fetch_reply_deadline(),
#[cfg(all(unix, any(test, feature = "test-support")))]
clock: _options.reply_clock_for_test.clone(),
}
}
fn now(&self) -> Instant {
#[cfg(all(unix, any(test, feature = "test-support")))]
if let Some(clock) = &self.clock {
return clock();
}
Instant::now()
}
pub(crate) fn is_cancelled(&self) -> bool {
self.reason().is_some()
}
pub(crate) fn reason(&self) -> Option<crate::secret::requests::UseError> {
self.job
.as_ref()
.is_some_and(|job| job.cancel_requested_before_commit())
.then_some(crate::secret::requests::UseError::Cancelled)
.or_else(|| {
self.deadline
.is_some_and(|at| self.now() >= at)
.then_some(crate::secret::requests::UseError::Expired)
})
}
pub(crate) async fn cancelled(&self) {
loop {
if self.is_cancelled() {
return;
}
let delay = self.deadline.map_or(Duration::from_millis(25), |deadline| {
deadline
.saturating_duration_since(self.now())
.min(Duration::from_millis(25))
});
tokio::time::sleep(delay).await;
}
}
}
#[rustfmt::skip]
test_support_visibility! {
#[derive(Default)]
pub(crate) struct HeldKeys(Vec<(String, Zeroizing<Vec<u8>>)>);
}
impl HeldKeys {
fn matchers(&self) -> Result<Vec<MatcherSet>, ScrubError> {
self.0
.iter()
.map(|(label, key)| MatcherSet::new(label, key))
.collect()
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) fn hold(&mut self, label: &str, key: &[u8]) -> Result<(), ScrubError> {
if self
.0
.iter()
.any(|(held, bytes)| held == label && bytes.as_slice() == key)
{
return Ok(());
}
let mut matchers = self.matchers()?;
matchers.push(MatcherSet::new(label, key)?);
Scrubber::new(matchers)?;
self.0
.push((label.to_string(), Zeroizing::new(key.to_vec())));
Ok(())
}
}
fn scrub(&self, bytes: &[u8]) -> Result<Vec<u8>, ScrubError> {
let mut scrubber = Scrubber::new(self.matchers()?)?;
let mut clean = scrubber.push(bytes);
clean.extend_from_slice(&scrubber.finish());
Ok(clean)
}
fn keys(&self) -> Vec<&[u8]> {
self.0.iter().map(|(_, key)| key.as_slice()).collect()
}
pub(crate) fn sanitize_detail(&self, detail: &str) -> String {
let deadline = Instant::now() + DETAIL_CHECK_LIMIT;
match self.scrub(detail.as_bytes()) {
Ok(clean) if self.reveal(&clean, deadline).is_clean() => {
String::from_utf8_lossy(&clean).into_owned()
}
_ => String::new(),
}
}
fn reveal(&self, bytes: &[u8], deadline: Instant) -> secret_rules::RevealOutcome {
secret_rules::reveal_outcome(bytes, &self.keys(), Some(deadline))
}
}
const DETAIL_CHECK_LIMIT: Duration = Duration::from_millis(100);
fn refuse_unless_clean(
outcome: secret_rules::RevealOutcome,
found: &str,
url: &str,
) -> Result<(), UrlFetchError> {
match outcome {
secret_rules::RevealOutcome::Clean => Ok(()),
secret_rules::RevealOutcome::Found => Err(secret_fetch_refused(found, url)),
secret_rules::RevealOutcome::Exhausted => {
Err(secret_fetch_refused("residual_check_exhausted", url))
}
secret_rules::RevealOutcome::OutOfTime => {
Err(secret_fetch_refused("residual_check_timeout", url))
}
}
}
fn secret_fetch_refused(reason: &str, url: &str) -> UrlFetchError {
UrlFetchError::secret(
crate::secret::SECRET_REFUSED,
format!("{SECRET_FETCH_REFUSED} ({reason}): {url}"),
)
}
fn scrub_refusal(url: &str) -> impl Fn(ScrubError) -> UrlFetchError + '_ {
move |_| secret_fetch_refused("scrubber_unavailable", url)
}
pub fn fetch_url_with_secrets(
logical_url: &str,
document_dir: &Path,
options: UrlFetchOptions,
secrets: &SecretFetch,
) -> Result<PathBuf, UrlFetchError> {
let key_sent = std::cell::Cell::new(false);
let result = fetch_with_secrets(logical_url, document_dir, options, secrets, &key_sent)
.map_err(|error| {
if key_sent.get() {
error.after_secret_sent()
} else {
error
}
});
record_fetch(&result);
result
}
fn fetch_with_secrets(
logical_url: &str,
document_dir: &Path,
options: UrlFetchOptions,
secrets: &SecretFetch,
key_sent: &std::cell::Cell<bool>,
) -> Result<PathBuf, UrlFetchError> {
let mut current = Url::parse(logical_url)
.map_err(|_| UrlFetchError::new(format!("Invalid URL: {logical_url}")))?;
current.set_fragment(None);
let start = current.clone();
let mut deadline = FetchDeadline::for_current_call();
let approved = Arc::new(ApprovedHosts::default());
let progress = Arc::new(ConnectProgress::default());
let client = build_client(
&options,
Arc::clone(&approved),
Arc::clone(&progress),
false,
Some(secrets.cancellation.clone()),
)?;
let mut held = HeldKeys::default();
let mut hop = 0;
let response = loop {
if secrets.cancellation.is_cancelled() {
return Err(secret_fetch_refused("missing_material", logical_url));
}
validate_public_url(¤t, &options, &deadline, &approved)?;
let waiting = Instant::now();
let outbound = secret_hop(¤t, hop, secrets, &mut held)?;
let waited = waiting.elapsed();
deadline.at += waited;
crate::bounded_io::exclude_secret_approval_wait(waited);
let sent = send_request(
&client,
¤t,
Some(SecretSend {
shown: current.as_str(),
held: &held,
released: outbound.is_some(),
cancellation: &secrets.cancellation,
key_sent,
outbound: outbound.as_ref(),
}),
&deadline,
&progress,
);
drop(outbound);
let response = sent?;
if !response.status().is_redirection() {
break response;
}
if hop == MAX_REDIRECTS {
return Err(UrlFetchError::new(format!(
"Too many redirects fetching {logical_url}"
)));
}
if response.headers().get_all(LOCATION).iter().any(|value| {
value
.as_bytes()
.iter()
.any(|byte| *byte < 0x20 || *byte == 0x7f)
}) {
return Err(secret_fetch_refused("redirect_control_byte", logical_url));
}
let location = scrubbed_header(&response, LOCATION, &held, logical_url, &deadline)?
.filter(|value| value.bytes().all(|byte| (0x20..0x7f).contains(&byte)))
.ok_or_else(|| {
UrlFetchError::new(format!(
"Redirect from {} missing Location header",
current.as_str()
))
})?;
let mut next = current.join(&location).map_err(|error| {
UrlFetchError::new(format!(
"Invalid redirect Location '{location}' from {}: {error}",
current.as_str()
))
})?;
next.set_fragment(None);
refuse_unless_clean(
held.reveal(next.as_str().as_bytes(), header_check_deadline(&deadline)),
"redirect_discloses_key",
logical_url,
)?;
current = next;
hop += 1;
timing::record(|times| times.redirects += 1);
};
let status = response.status();
if !status.is_success() {
return Err(UrlFetchError::http_status(
status.as_u16(),
format!(
"HTTP {} {} fetching {logical_url}",
status.as_u16(),
status.canonical_reason().unwrap_or("")
),
));
}
let content_type = scrubbed_header(&response, CONTENT_TYPE, &held, logical_url, &deadline)?
.unwrap_or_else(|| "text/plain".to_string());
if response.headers().get_all(CONTENT_ENCODING).iter().count() > 1 {
return Err(secret_fetch_refused("content_encoding", logical_url));
}
let codings = match scrubbed_header(&response, CONTENT_ENCODING, &held, logical_url, &deadline)?
{
Some(value) => secret_content_codings(&value, logical_url)?,
None if response.headers().contains_key(CONTENT_ENCODING) => {
return Err(secret_fetch_refused("content_encoding", logical_url));
}
None => Vec::new(),
};
let (extension, from_source_path) = resolve_fetch_extension(&start, &content_type)
.ok_or_else(|| {
UrlFetchError::new(format!(
"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)"
))
})?;
let is_html =
extension == ".html" || resolve_extension_from_content_type(&content_type) == Some(".html");
let total_bytes = codings
.is_empty()
.then(|| response.content_length())
.flatten();
let sanitize = |detail: &str| held.sanitize_detail(detail);
#[cfg(any(test, feature = "test-support"))]
let response: Box<dyn Read + Send> =
match TEST_BODY_READ_ERROR.with(|slot| slot.borrow().clone()) {
Some(message) => Box::new(FailingBody(message)),
None => Box::new(response),
};
let (raw, mut download_truncated) =
read_response_body_with(response, logical_url, &deadline, &sanitize)?;
let decoded = decode_secret_body(&raw, &codings, &mut download_truncated, logical_url)?;
let mut body = held.scrub(&decoded).map_err(scrub_refusal(logical_url))?;
drop(decoded);
let downloaded_bytes = body.len();
if download_truncated {
if let Err(error) = std::str::from_utf8(&body) {
if error.error_len().is_none() {
body.truncate(error.valid_up_to());
}
}
}
if from_source_path && !is_html && body_contains_nul_in_prefix(&body) {
return Err(UrlFetchError::new(format!(
"Binary content detected for source URL {logical_url}"
)));
}
let (body, content_type, extension) = if is_html {
let markdown = convert_html_body_to_markdown(&body, logical_url)?;
(
held.scrub(&markdown).map_err(scrub_refusal(logical_url))?,
CONVERTED_MARKDOWN_CONTENT_TYPE.to_string(),
".md",
)
} else {
(body, content_type, extension)
};
refuse_unless_clean(
held.reveal(&body, residual_check_deadline(&deadline)),
"document_discloses_key",
logical_url,
)?;
let content_file = document_dir.join(format!("document{extension}"));
write_secret_document(&content_file, &body)?;
let meta = CacheMeta {
url: logical_url.to_string(),
content_type,
extension: extension.to_string(),
fetched_at: now_ms(),
download_truncated,
downloaded_bytes,
total_bytes,
};
let meta_bytes = serde_json::to_vec(&meta).map_err(|error| {
UrlFetchError::new(format!("Failed to encode URL fetch metadata: {error}"))
})?;
write_secret_document(&content_file.with_extension("meta.json"), &meta_bytes)?;
Ok(content_file)
}
fn write_secret_document(path: &Path, bytes: &[u8]) -> Result<(), UrlFetchError> {
crate::private_storage::write(path, bytes).map_err(|error| {
UrlFetchError::new(format!(
"Failed to write placeholder fetch document {}: {error}",
path.display()
))
})
}
fn scrubbed_header(
response: &HttpResponse,
name: reqwest::header::HeaderName,
held: &HeldKeys,
url: &str,
deadline: &FetchDeadline,
) -> Result<Option<String>, UrlFetchError> {
let Some(value) = response.headers().get(&name) else {
return Ok(None);
};
let clean = held.scrub(value.as_bytes()).map_err(scrub_refusal(url))?;
refuse_unless_clean(
held.reveal(&clean, header_check_deadline(deadline)),
"header_discloses_key",
url,
)?;
Ok(String::from_utf8(clean).ok())
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
static TEST_BODY_READ_ERROR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}
#[cfg(any(test, feature = "test-support"))]
pub fn inject_secret_body_read_error_for_test(message: String) -> impl Drop {
struct Restore;
impl Drop for Restore {
fn drop(&mut self) {
TEST_BODY_READ_ERROR.with(|slot| slot.replace(None));
}
}
TEST_BODY_READ_ERROR.with(|slot| slot.replace(Some(message)));
Restore
}
#[cfg(any(test, feature = "test-support"))]
struct FailingBody(String);
#[cfg(any(test, feature = "test-support"))]
impl Read for FailingBody {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Err(io::Error::other(self.0.clone()))
}
}
fn residual_check_deadline(deadline: &FetchDeadline) -> Instant {
#[cfg(any(test, feature = "test-support"))]
if let Some(limit) = TEST_RESIDUAL_LIMIT.with(std::cell::Cell::get) {
return Instant::now() + limit;
}
deadline.at + RESIDUAL_CHECK_RESERVE
}
fn header_check_deadline(deadline: &FetchDeadline) -> Instant {
#[cfg(any(test, feature = "test-support"))]
if let Some(limit) = TEST_RESIDUAL_LIMIT.with(std::cell::Cell::get) {
return Instant::now() + limit;
}
deadline.at
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
static TEST_RESIDUAL_LIMIT: std::cell::Cell<Option<Duration>> = const { std::cell::Cell::new(None) };
}
#[cfg(any(test, feature = "test-support"))]
pub fn limit_secret_residual_check_for_test(limit: Duration) -> impl Drop {
struct Restore;
impl Drop for Restore {
fn drop(&mut self) {
TEST_RESIDUAL_LIMIT.with(|slot| slot.set(None));
}
}
TEST_RESIDUAL_LIMIT.with(|slot| slot.set(Some(limit)));
Restore
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SecretCoding {
Identity,
Gzip,
Deflate,
Brotli,
}
fn secret_content_codings(value: &str, url: &str) -> Result<Vec<SecretCoding>, UrlFetchError> {
let mut codings = Vec::new();
for token in value.split(',').map(str::trim) {
let coding = if token.eq_ignore_ascii_case("identity") {
SecretCoding::Identity
} else if token.eq_ignore_ascii_case("gzip") || token.eq_ignore_ascii_case("x-gzip") {
SecretCoding::Gzip
} else if token.eq_ignore_ascii_case("deflate") {
SecretCoding::Deflate
} else if token.eq_ignore_ascii_case("br") {
SecretCoding::Brotli
} else {
return Err(secret_fetch_refused("content_encoding", url));
};
if codings.len() >= MAX_SECRET_CODINGS || codings.contains(&coding) {
return Err(secret_fetch_refused("content_encoding", url));
}
codings.push(coding);
}
Ok(codings)
}
fn decode_secret_body(
body: &[u8],
codings: &[SecretCoding],
truncated: &mut bool,
url: &str,
) -> Result<sensitive::Bytes, UrlFetchError> {
use async_compression::tokio::bufread::{BrotliDecoder, GzipDecoder, ZlibDecoder};
use tokio::io::{AsyncRead, BufReader};
let mut data = sensitive::Factory::current().copy(body);
for coding in codings.iter().rev() {
let input: &[u8] = &data;
let reader: std::pin::Pin<Box<dyn AsyncRead + Send + '_>> = match coding {
SecretCoding::Identity => continue,
SecretCoding::Gzip => {
let mut decoder = GzipDecoder::new(BufReader::new(input));
decoder.multiple_members(true);
Box::pin(decoder)
}
SecretCoding::Deflate => Box::pin(ZlibDecoder::new(BufReader::new(input))),
SecretCoding::Brotli => Box::pin(BrotliDecoder::new(BufReader::new(input))),
};
let input_truncated = *truncated;
let (output, cut) = drain_decoder(reader, input_truncated).map_err(|()| {
UrlFetchError::new(format!("Failed to decode the response body for {url}"))
})?;
if cut {
*truncated = true;
}
data = output;
}
Ok(data)
}
fn drain_decoder(
mut reader: std::pin::Pin<Box<dyn tokio::io::AsyncRead + Send + '_>>,
input_truncated: bool,
) -> Result<(sensitive::Bytes, bool), ()> {
use std::future::Future;
use tokio::io::AsyncReadExt;
let factory = sensitive::Factory::current();
let mut output = factory.with_capacity(0);
let polled = {
let decoding = async {
let mut buffer = factory.zeroed(16 * 1024);
loop {
match reader.read(&mut buffer).await {
Ok(0) => return Ok(false),
Ok(count) => {
let room = (MAX_RESPONSE_BYTES as usize).saturating_sub(output.len());
output.extend_from_slice(&buffer[..count.min(room)]);
if count > room {
return Ok(true);
}
}
Err(_) if input_truncated => return Ok(false),
Err(_) => return Err(()),
}
}
};
let mut decoding = std::pin::pin!(decoding);
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
decoding.as_mut().poll(&mut context)
};
match polled {
std::task::Poll::Ready(Ok(cut)) => Ok((output, cut)),
std::task::Poll::Ready(Err(())) | std::task::Poll::Pending => Err(()),
}
}
#[rustfmt::skip]
test_support_visibility! {
fn secret_hop(
current: &Url,
hop: usize,
secrets: &SecretFetch,
held: &mut HeldKeys,
) -> Result<Option<SecretOutboundUrl>, UrlFetchError> {
let logical = current.as_str();
let path = current.path();
let target = match current.query() {
Some(query) => format!("{path}?{query}"),
None => path.to_string(),
};
let authority = (current.scheme() == "https")
.then(|| current.host_str().zip(current.port_or_known_default()))
.flatten()
.and_then(|(host, port)| {
secret_rules::target::canonical_host(host)
.ok()
.map(|host| ConnectAuthority { host, port })
});
let Some(authority) = authority else {
emit_hop_audit(secrets, held, hop, None, &[], |_| {
(Decision::Literal, AuditReason::OutOfScope)
})
.map_err(|_| secret_fetch_refused("audit_unavailable", logical))?;
return Ok(None);
};
let refused = |held: &HeldKeys, reason: &str| {
let _ = emit_hop_audit(secrets, held, hop, Some(&authority), &[], |_| {
(Decision::Refused, AuditReason::Refused)
});
secret_fetch_refused(reason, logical)
};
let mut rules = Vec::new();
let mut materials = Vec::new();
let present = secret_labels_in_url(logical).unwrap_or_default();
let normalized = normalize_request_target(path).map_err(|_| refused(held, "malformed_path"))?;
let addressed = crate::secret::ApiKeyTarget {
scheme: "https".into(),
host: authority.host.clone(),
port: Some(443),
path: String::from_utf8(normalized.wire).map_err(|_| refused(held, "malformed_path"))?,
};
let mut eligible = Vec::new();
for label in &secrets.labels {
let https_port = authority.port == 443;
#[cfg(any(test, feature = "test-support"))]
let https_port = https_port || secrets.test_https_port == Some(authority.port);
if !https_port || !present.contains(label) {
continue;
}
eligible.push(label.clone());
}
let answers = crate::secret::fetch::use_current_secret_labels(
secrets.vault.clone(),
&eligible,
&addressed,
&target,
&secrets.cancellation,
);
for (label, answer) in eligible.iter().zip(answers) {
let answer = match answer {
crate::secret::fetch::FetchDecision::InvalidPlan(reason) => {
return Err(refused(held, reason))
}
crate::secret::fetch::FetchDecision::Proceed(answer) => answer,
crate::secret::fetch::FetchDecision::Refuse(crate::secret::LabelOutcome::Refuse {
code,
message,
}) => {
let _ = refused(held, "missing_material");
return Err(UrlFetchError::secret(code, message));
}
_ => return Err(refused(held, "missing_material")),
};
if let crate::secret::UseAnswer::Released(released) = answer {
let (location, material) = released.into_parts();
let location = secret_rules::location::parse_vault_location(&location)
.ok_or_else(|| refused(held, "missing_material"))?;
if !matches!(location, Location::Query(_)) {
return Err(refused(held, "missing_material"));
}
if check_admissible(material.expose(), label, &location).is_err() {
return Err(refused(held, "material_not_admissible"));
}
held.hold(label, material.expose())
.map_err(|_| refused(held, "replacement_discloses_key"))?;
rules.push(LabelRule {
label: label.clone(),
host: addressed.host.clone(),
port: authority.port,
path_prefix: addressed.path.clone(),
location,
});
materials.push(Some(material));
}
}
let planning: Vec<(String, Vec<u8>)> = rules
.iter()
.map(|rule| (rule.label.clone(), SECRET_PLANNING_KEY.to_vec()))
.collect();
let view = RequestView::new(&target, Vec::new());
let plan = evaluate_request_with_connect(&view, &authority, &rules, &planning);
if let Some(refusal) = plan.refusal {
return Err(refused(&*held, refusal.reason()));
}
let query_start = path.len() + 1;
let mut edits: Vec<(usize, usize, Zeroizing<Vec<u8>>)> = Vec::new();
for ((rule, outcome), material) in rules.iter().zip(&plan.labels).zip(&materials) {
if let LabelOutcome::Substituted {
byte_start,
byte_end,
..
} = outcome
{
let (Some(material), true) = (material, *byte_start >= query_start) else {
return Err(refused(&*held, "missing_material"));
};
let encoded = encode_for_location(material.expose(), &rule.label, &rule.location)
.map_err(|_| refused(&*held, "material_not_admissible"))?;
edits.push((
byte_start - query_start,
byte_end - query_start,
Zeroizing::new(encoded),
));
}
}
let decide = |label: &str| -> (Decision, AuditReason) {
let outcome = rules
.iter()
.position(|rule| rule.label == label)
.and_then(|index| plan.labels.get(index));
match outcome {
Some(LabelOutcome::Substituted { .. }) => (Decision::Substituted, AuditReason::Matched),
Some(LabelOutcome::NotWholeValue) => (Decision::Literal, AuditReason::NotWholeValue),
_ => (Decision::Literal, AuditReason::OutOfScope),
}
};
if edits.is_empty() {
emit_hop_audit(secrets, held, hop, Some(&authority), &rules, decide)
.map_err(|_| secret_fetch_refused("audit_unavailable", logical))?;
return Ok(None);
}
edits.sort_by_key(|(start, _, _)| *start);
let query = current.query().unwrap_or_default().as_bytes();
let substituted =
substitute_query(query, &edits).ok_or_else(|| refused(held, "malformed_query"))?;
let Ok(substituted) = std::str::from_utf8(&substituted) else {
return Err(refused(&*held, "malformed_query"));
};
let Ok(normalized) = normalize_request_target(path) else {
return Err(refused(&*held, "malformed_path"));
};
let Ok(wire_path) = std::str::from_utf8(&normalized.wire) else {
return Err(refused(&*held, "malformed_path"));
};
emit_hop_audit(secrets, held, hop, Some(&authority), &rules, decide)
.map_err(|_| secret_fetch_refused("audit_unavailable", logical))?;
secret_outbound_url(current, wire_path, substituted)
.map(Some)
.ok_or_else(|| refused(held, "malformed_query"))
}
}
#[cfg(any(test, feature = "test-support"))]
thread_local! { pub static SECRET_URL_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }
#[rustfmt::skip]
test_support_visibility! {
struct SecretOutboundUrl(sensitive::Bytes);
}
impl std::ops::Deref for SecretOutboundUrl {
type Target = str;
fn deref(&self) -> &str {
std::str::from_utf8(&self.0).expect("URL serialization is UTF-8")
}
}
impl SecretOutboundUrl {
fn as_str(&self) -> &str {
self
}
}
impl fmt::Debug for SecretOutboundUrl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ProtectedOutboundUrl")
}
}
fn secret_outbound_url(
current: &Url,
wire_path: &str,
substituted: &str,
) -> Option<SecretOutboundUrl> {
#[cfg(any(test, feature = "test-support"))]
SECRET_URL_BUILDS.with(|n| n.set(n.get() + 1));
let prefix = ¤t[..url::Position::BeforePath];
let capacity = prefix
.len()
.checked_add(wire_path.len())?
.checked_add(1)?
.checked_add(substituted.len())?;
let mut serialized = sensitive::Factory::current().with_capacity(capacity);
serialized.extend_from_slice(prefix.as_bytes());
serialized.extend_from_slice(wire_path.as_bytes());
serialized.extend_from_slice(b"?");
serialized.extend_from_slice(substituted.as_bytes());
Some(SecretOutboundUrl(serialized))
}
fn substitute_query(
query: &[u8],
edits: &[(usize, usize, Zeroizing<Vec<u8>>)],
) -> Option<Zeroizing<Vec<u8>>> {
let final_len = edits
.iter()
.try_fold(query.len(), |len, (start, end, value)| {
len.checked_sub(end.checked_sub(*start)?)?
.checked_add(value.len())
})?;
let mut substituted = Zeroizing::new(Vec::with_capacity(final_len));
let mut cursor = 0;
for (start, end, replacement) in edits {
if *start < cursor || *end < *start || *end > query.len() {
return None;
}
substituted.extend_from_slice(&query[cursor..*start]);
substituted.extend_from_slice(replacement);
cursor = *end;
}
substituted.extend_from_slice(&query[cursor..]);
Some(substituted)
}
fn emit_hop_audit(
secrets: &SecretFetch,
held: &HeldKeys,
hop: usize,
authority: Option<&ConnectAuthority>,
rules: &[LabelRule],
decide: impl Fn(&str) -> (Decision, AuditReason),
) -> Result<(), ()> {
let origin = format!("{}#{hop}", secrets.call_id);
let keys = held.keys();
let mut failed = false;
for label in &secrets.labels {
let (decision, reason) = decide(label);
let mut record = AuditRecordV1::new(
crate::secret::now_ms(),
label,
decision,
reason,
&secrets.call_id,
&origin,
)
.with_scope(
secrets
.authorization
.as_ref()
.map(crate::secret::SecretScope::to_scope_ref),
);
if let Some(authority) = authority {
record.host = Some(authority.host.clone());
record.port = Some(authority.port);
}
if let Some(rule) = rules.iter().find(|rule| &rule.label == label) {
record = record.with_rule(
&rule.host,
rule.port,
&rule.path_prefix,
location_kind_token(&rule.location),
);
}
if record.to_json_line_with_keys(&keys).is_err() || secrets.vault.audit(&record).is_err() {
failed = true;
}
}
if failed {
Err(())
} else {
Ok(())
}
}
#[derive(Debug, Clone)]
struct CleanupMemoEntry {
len: u64,
modified: SystemTime,
fetched_at: u64,
extension: String,
}
fn cleanup_memo() -> &'static std::sync::Mutex<HashMap<PathBuf, HashMap<String, CleanupMemoEntry>>>
{
static MEMO: std::sync::OnceLock<
std::sync::Mutex<HashMap<PathBuf, HashMap<String, CleanupMemoEntry>>>,
> = std::sync::OnceLock::new();
MEMO.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
pub static CLEANUP_META_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
pub fn cleanup_url_cache(storage_dir: &Path) -> Result<usize, UrlFetchError> {
cleanup_url_cache_at(storage_dir, now_ms())
}
fn cleanup_url_cache_at(storage_dir: &Path, now: u64) -> Result<usize, UrlFetchError> {
let dir = cache_dir(storage_dir);
if !dir.exists() {
return Ok(0);
}
let entries = fs::read_dir(&dir).map_err(|error| {
UrlFetchError::new(format!(
"URL cache cleanup failed reading {}: {error}",
dir.display()
))
})?;
let mut removed = 0usize;
let previous = cleanup_memo()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(&dir)
.unwrap_or_default();
let mut kept = HashMap::new();
for entry in entries.flatten() {
let path = entry.path();
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
continue;
};
if !name.ends_with(".meta.json") {
continue;
}
let version = entry
.metadata()
.ok()
.and_then(|metadata| Some((metadata.len(), metadata.modified().ok()?)));
let remembered = version.and_then(|(len, modified)| {
previous
.get(name)
.filter(|known| known.len == len && known.modified == modified)
.cloned()
});
let facts = match remembered {
Some(known) => known,
None => {
#[cfg(any(test, feature = "test-support"))]
CLEANUP_META_READS.with(|reads| reads.set(reads.get() + 1));
let meta = fs::read_to_string(&path)
.ok()
.and_then(|content| serde_json::from_str::<CacheMeta>(&content).ok());
let Some(meta) = meta else {
if fs::remove_file(&path).is_ok() {
removed += 1;
}
continue;
};
let (len, modified) = version.unwrap_or((u64::MAX, UNIX_EPOCH));
CleanupMemoEntry {
len,
modified,
fetched_at: meta.fetched_at,
extension: meta.extension,
}
}
};
if now.saturating_sub(facts.fetched_at) <= CACHE_TTL_MS {
if version.is_some() {
kept.insert(name.to_string(), facts);
}
continue;
}
let hash = name.trim_end_matches(".meta.json");
let content = content_path(storage_dir, hash, &facts.extension);
let _ = fs::remove_file(content);
if fs::remove_file(&path).is_ok() {
removed += 1;
}
}
cleanup_memo()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(dir, kept);
Ok(removed)
}
#[doc(hidden)]
pub fn cache_content_path_for_url(storage_dir: &Path, url: &str, extension: &str) -> PathBuf {
content_path(storage_dir, &hash_url(url), extension)
}
#[doc(hidden)]
pub fn cache_meta_path_for_url(storage_dir: &Path, url: &str) -> PathBuf {
meta_path(storage_dir, &hash_url(url))
}
pub fn download_notice(path: &Path) -> Option<String> {
let meta_path = path.with_extension("meta.json");
let meta: CacheMeta = serde_json::from_slice(&fs::read(meta_path).ok()?).ok()?;
if !meta.download_truncated {
return None;
}
let total = meta
.total_bytes
.map(|n| n.to_string())
.unwrap_or_else(|| format!("≥{}", meta.downloaded_bytes + 1));
Some(format!(
"Download truncated at {} of {total} bytes; narrow with a smaller URL or server-side filters (only the downloaded prefix was inspected)",
meta.downloaded_bytes
))
}
#[doc(hidden)]
pub fn is_private_ip_for_test(ip: IpAddr) -> bool {
is_private_ip(ip)
}
fn cache_dir(storage_dir: &Path) -> PathBuf {
storage_dir.join("url_cache")
}
fn hash_url(url: &str) -> String {
let digest = Sha256::digest(url.as_bytes());
format!("{digest:x}").chars().take(16).collect()
}
fn rewrite_url_for_fetch(url: &Url) -> Url {
let original = url.clone();
let mut rewritten = url.clone();
rewritten.set_fragment(None);
let Some(host) = url.host_str() else {
return rewritten;
};
if !matches!(url.scheme(), "http" | "https") {
return rewritten;
}
let segments: Vec<&str> = url
.path_segments()
.map(|segments| segments.collect())
.unwrap_or_default();
let (raw_host, raw_path) = if matches!(host, "github.com" | "www.github.com") {
if segments.len() >= 5 && matches!(segments[2], "blob" | "raw") {
(
"raw.githubusercontent.com",
format!(
"/{}/{}/{}/{}",
segments[0],
segments[1],
segments[3],
segments[4..].join("/")
),
)
} else {
return rewritten;
}
} else if host == "gitlab.com"
&& segments.len() >= 6
&& segments[2] == "-"
&& segments[3] == "blob"
{
(
"gitlab.com",
format!(
"/{}/{}/-/raw/{}/{}",
segments[0],
segments[1],
segments[4],
segments[5..].join("/")
),
)
} else {
return rewritten;
};
rewritten
.set_host(Some(raw_host))
.expect("raw content host should be a valid URL host");
rewritten.set_path(&raw_path);
log::debug!(
"url_fetch: rewriting web-view URL to raw content: {} -> {}",
original,
rewritten
);
rewritten
}
fn meta_path(storage_dir: &Path, hash: &str) -> PathBuf {
cache_dir(storage_dir).join(format!("{hash}.meta.json"))
}
fn content_path(storage_dir: &Path, hash: &str, extension: &str) -> PathBuf {
cache_dir(storage_dir).join(format!("{hash}{extension}"))
}
fn fresh_cached_path(
storage_dir: &Path,
hash: &str,
meta_file: &Path,
url: &Url,
) -> Result<Option<PathBuf>, UrlFetchError> {
#[cfg(any(test, feature = "test-support"))]
stall_cache_read_if_requested(storage_dir);
if !meta_file.exists() {
return Ok(None);
}
let meta = match fs::read_to_string(meta_file)
.ok()
.and_then(|content| serde_json::from_str::<CacheMeta>(&content).ok())
{
Some(meta) => meta,
None => return Ok(None),
};
let age = now_ms().saturating_sub(meta.fetched_at);
if meta.extension == ".html" {
return Ok(None);
}
let content_type = meta.content_type.as_str();
let current = resolve_fetch_extension(url, content_type);
let expected_ext = current.map(|(ext, _)| if ext == ".html" { ".md" } else { ext });
if expected_ext != Some(meta.extension.as_str()) {
return Ok(None);
}
let cached = content_path(storage_dir, hash, &meta.extension);
let legacy_oversized = meta.downloaded_bytes == 0
&& fs::metadata(&cached).is_ok_and(|m| m.len() > MAX_RESPONSE_BYTES);
if age < CACHE_TTL_MS && cached.exists() && !legacy_oversized {
return Ok(Some(cached));
}
Ok(None)
}
fn fetch_with_redirects(
start_url: &Url,
original_url: &str,
options: &UrlFetchOptions,
deadline: &FetchDeadline,
approved: Arc<ApprovedHosts>,
) -> Result<HttpResponse, UrlFetchError> {
let progress = Arc::new(ConnectProgress::default());
let client = build_client(
options,
Arc::clone(&approved),
Arc::clone(&progress),
true,
None,
)?;
let mut current_url = start_url.clone();
for redirect_count in 0..=MAX_REDIRECTS {
validate_public_url(¤t_url, options, deadline, &approved)?;
let response = send_with_transient_retries(&client, ¤t_url, deadline, &progress)?;
if !response.status().is_redirection() {
return Ok(response);
}
if redirect_count == MAX_REDIRECTS {
return Err(UrlFetchError::new(format!(
"Too many redirects fetching {original_url}"
)));
}
let location = response
.headers()
.get(LOCATION)
.and_then(|value| value.to_str().ok())
.ok_or_else(|| {
UrlFetchError::new(format!(
"Redirect from {} missing Location header",
current_url.as_str()
))
})?;
current_url = current_url.join(location).map_err(|error| {
UrlFetchError::new(format!(
"Invalid redirect Location '{location}' from {}: {error}",
current_url.as_str()
))
})?;
timing::record(|times| times.redirects += 1);
}
Err(UrlFetchError::new(format!(
"Too many redirects fetching {original_url}"
)))
}
fn send_with_transient_retries(
client: &Client,
target: &Url,
deadline: &FetchDeadline,
progress: &ConnectProgress,
) -> Result<HttpResponse, UrlFetchError> {
send_request(client, target, None, deadline, progress)
}
#[derive(Clone, Copy)]
struct SecretSend<'a> {
shown: &'a str,
held: &'a HeldKeys,
released: bool,
cancellation: &'a SecretFetchCancellation,
key_sent: &'a std::cell::Cell<bool>,
outbound: Option<&'a SecretOutboundUrl>,
}
fn send_request(
client: &Client,
target: &Url,
secret: Option<SecretSend<'_>>,
deadline: &FetchDeadline,
progress: &ConnectProgress,
) -> Result<HttpResponse, UrlFetchError> {
let started = Instant::now();
let (attempts_before, connect_before) = progress.totals();
let result = send_request_attempts(client, target, secret, deadline, progress);
let elapsed = started.elapsed();
let (attempts, connect) = progress.totals();
timing::record(|times| {
times.first_byte += elapsed;
times.connect += connect.saturating_sub(connect_before);
times.retries += (attempts - attempts_before).saturating_sub(1) as u32;
});
result
}
fn send_request_attempts(
client: &Client,
target: &Url,
secret: Option<SecretSend<'_>>,
deadline: &FetchDeadline,
progress: &ConnectProgress,
) -> Result<HttpResponse, UrlFetchError> {
let named = secret.map_or(target.as_str(), |secret| secret.shown);
let held = secret.map(|secret| secret.held);
let mut attempt = 0;
loop {
let remaining = deadline.remaining();
if remaining.is_zero() {
return Err(deadline.timeout_error(FetchPhase::Connect, named));
}
progress.begin_attempt();
let outbound = match secret.and_then(|secret| secret.outbound) {
Some(outbound) => Url::parse(outbound.as_str())
.map_err(|_| secret_fetch_refused("malformed_query", named))?,
None => target.clone(),
};
let mut request = client
.get(outbound)
.header(USER_AGENT, USER_AGENT_VALUE)
.header(ACCEPT, ACCEPT_HEADER)
.timeout(remaining.min(HEADERS_TIMEOUT));
if held.is_some() {
request = request.header(ACCEPT_ENCODING, "identity");
}
if secret.is_some_and(|secret| secret.cancellation.is_cancelled()) {
return Err(secret_fetch_refused("missing_material", named));
}
if let Some(secret) = secret.filter(|secret| secret.released) {
secret.key_sent.set(true);
}
let error = match request.send() {
Ok(response) => return Ok(response),
Err(error) => error,
};
if secret.is_some_and(|secret| secret.cancellation.is_cancelled()) {
return Err(secret_fetch_refused("missing_material", named));
}
let phase = error
.is_timeout()
.then(|| timed_out_phase(&error, progress));
let retryable = !secret.is_some_and(|secret| secret.released)
&& is_transient_reqwest_error(&error)
&& phase != Some(FetchPhase::Headers);
let backoff = TRANSIENT_RETRY_BACKOFFS_MS
.get(attempt)
.map(|ms| Duration::from_millis(*ms))
.filter(|backoff| retryable && *backoff + MIN_USEFUL_ATTEMPT <= deadline.remaining());
if let Some(backoff) = backoff {
thread::sleep(backoff);
attempt += 1;
continue;
}
return Err(send_failure(error, phase, deadline, named, held));
}
}
fn send_failure(
error: reqwest::Error,
phase: Option<FetchPhase>,
deadline: &FetchDeadline,
named: &str,
held: Option<&HeldKeys>,
) -> UrlFetchError {
let error = if held.is_some() {
error.without_url()
} else {
error
};
let detail = reqwest_error_detail(&error);
let detail = match held {
Some(held) => held.sanitize_detail(&detail),
None => detail,
};
if let Some(phase) = phase {
return request_timeout_error(&detail, phase, deadline, named);
}
if detail.is_empty() {
return UrlFetchError::new(format!("Failed to fetch {named}"));
}
UrlFetchError::new(format!("Failed to fetch {named}: {detail}"))
}
fn timed_out_phase(error: &reqwest::Error, progress: &ConnectProgress) -> FetchPhase {
if progress.lookup_pending() {
FetchPhase::Dns
} else if progress.connect_pending() || error.is_connect() {
FetchPhase::Connect
} else {
FetchPhase::Headers
}
}
fn request_timeout_error(
detail: &str,
phase: FetchPhase,
deadline: &FetchDeadline,
target: &str,
) -> UrlFetchError {
if deadline.expired() {
return deadline.timeout_error(phase, target);
}
let limit = match phase {
FetchPhase::Dns | FetchPhase::Connect => CONNECT_TIMEOUT,
FetchPhase::Headers | FetchPhase::Body => HEADERS_TIMEOUT,
};
UrlFetchError::timeout(
phase,
format!(
"URL fetch timed out in the {} phase after the {}ms limit fetching {}: {}",
phase.as_str(),
limit.as_millis(),
target,
detail
),
)
}
fn is_transient_reqwest_error(error: &reqwest::Error) -> bool {
error.is_connect() || error.is_timeout() || error.is_request()
}
fn build_client(
options: &UrlFetchOptions,
approved: Arc<ApprovedHosts>,
progress: Arc<ConnectProgress>,
automatic_replays: bool,
cancellation: Option<SecretFetchCancellation>,
) -> Result<Client, UrlFetchError> {
let resolver = GuardedResolver {
approved,
connect_overrides: options.connect_overrides.clone(),
lookup_override: options.lookup_override.clone(),
progress: Arc::clone(&progress),
};
let builder = Client::builder()
.redirect(Policy::none())
.connect_timeout(CONNECT_TIMEOUT)
.connector_layer(TrackConnect {
progress,
delay: options.connect_delay,
cancellation,
})
.dns_resolver(Arc::new(resolver));
let builder = if automatic_replays {
builder
} else {
builder.retry(reqwest::retry::never())
};
let tls_config = match &options.tls_config {
Some(config) => config.clone(),
None => crate::platform_tls::client_config().map_err(|error| {
UrlFetchError::new(format!("Failed to configure URL fetch TLS: {error}"))
})?,
};
builder
.use_preconfigured_tls(tls_config)
.build()
.map_err(|error| UrlFetchError::new(format!("Failed to build URL fetch client: {error}")))
}
#[derive(Default)]
struct ApprovedHosts(std::sync::Mutex<HashMap<String, Vec<IpAddr>>>);
impl ApprovedHosts {
fn get(&self, host: &str) -> Option<Vec<IpAddr>> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(host)
.cloned()
}
fn insert(&self, host: &str, addresses: Vec<IpAddr>) {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(host.to_string(), addresses);
}
}
#[derive(Default)]
struct ConnectProgress(std::sync::Mutex<AttemptProgress>);
#[derive(Default)]
struct AttemptProgress {
attempt: u64,
lookup_pending: bool,
connect_pending: bool,
connect_time: Duration,
}
impl ConnectProgress {
fn state(&self) -> std::sync::MutexGuard<'_, AttemptProgress> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn begin_attempt(&self) {
let mut state = self.state();
state.attempt += 1;
state.lookup_pending = false;
state.connect_pending = false;
}
fn connect_started(&self) -> u64 {
let mut state = self.state();
state.connect_pending = true;
state.attempt
}
fn connected(&self, attempt: u64) {
let mut state = self.state();
if state.attempt == attempt {
state.connect_pending = false;
}
}
fn connect_pending(&self) -> bool {
self.state().connect_pending
}
fn add_connect_time(&self, elapsed: Duration) {
self.state().connect_time += elapsed;
}
fn totals(&self) -> (u64, Duration) {
let state = self.state();
(state.attempt, state.connect_time)
}
fn lookup_started(&self) -> u64 {
let mut state = self.state();
state.lookup_pending = true;
state.attempt
}
fn lookup_answered(&self, attempt: u64) {
let mut state = self.state();
if state.attempt == attempt {
state.lookup_pending = false;
}
}
fn lookup_pending(&self) -> bool {
self.state().lookup_pending
}
}
#[derive(Clone)]
struct TrackConnect {
progress: Arc<ConnectProgress>,
delay: Option<Duration>,
cancellation: Option<SecretFetchCancellation>,
}
impl<S> tower_layer::Layer<S> for TrackConnect {
type Service = TrackedConnector<S>;
fn layer(&self, inner: S) -> Self::Service {
TrackedConnector {
inner,
progress: Arc::clone(&self.progress),
delay: self.delay,
cancellation: self.cancellation.clone(),
}
}
}
#[derive(Clone)]
struct TrackedConnector<S> {
inner: S,
progress: Arc<ConnectProgress>,
delay: Option<Duration>,
cancellation: Option<SecretFetchCancellation>,
}
impl<S, Target> tower_service::Service<Target> for TrackedConnector<S>
where
S: tower_service::Service<Target>,
S::Future: Send + 'static,
S::Response: Send + 'static,
S::Error: Into<Box<dyn std::error::Error + Send + Sync>> + Send + 'static,
{
type Response = S::Response;
type Error = Box<dyn std::error::Error + Send + Sync>;
type Future = std::pin::Pin<
Box<dyn std::future::Future<Output = Result<S::Response, Self::Error>> + Send>,
>;
fn poll_ready(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx).map_err(Into::into)
}
fn call(&mut self, target: Target) -> Self::Future {
let attempt = self.progress.connect_started();
let progress = Arc::clone(&self.progress);
let delay = self.delay;
let cancellation = self.cancellation.clone();
let connecting = self.inner.call(target);
Box::pin(async move {
let _timer = ConnectTimer {
progress: Arc::clone(&progress),
started: Instant::now(),
};
if let Some(delay) = delay {
tokio::time::sleep(delay).await;
}
let connection = connecting.await.map_err(Into::into)?;
if cancellation.is_some_and(|cancel| cancel.is_cancelled()) {
return Err(std::io::Error::from(std::io::ErrorKind::Interrupted).into());
}
progress.connected(attempt);
Ok(connection)
})
}
}
struct ConnectTimer {
progress: Arc<ConnectProgress>,
started: Instant,
}
impl Drop for ConnectTimer {
fn drop(&mut self) {
self.progress.add_connect_time(self.started.elapsed());
}
}
struct GuardedResolver {
approved: Arc<ApprovedHosts>,
connect_overrides: Vec<(String, SocketAddr)>,
lookup_override: Option<HostLookup>,
progress: Arc<ConnectProgress>,
}
impl reqwest::dns::Resolve for GuardedResolver {
fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
let host = name.as_str().to_string();
let ready = |addresses: Vec<SocketAddr>| -> reqwest::dns::Resolving {
Box::pin(std::future::ready(Ok(
Box::new(addresses.into_iter()) as reqwest::dns::Addrs
)))
};
if let Some((_, address)) = self
.connect_overrides
.iter()
.find(|(override_host, _)| *override_host == host)
{
return ready(vec![*address]);
}
if let Some(addresses) = self.approved.get(&host) {
return ready(
addresses
.into_iter()
.map(|ip| SocketAddr::new(ip, 0))
.collect(),
);
}
let progress = Arc::clone(&self.progress);
let attempt = progress.lookup_started();
let (sender, receiver) = tokio::sync::oneshot::channel();
let lookup = self.lookup_override.clone();
thread::spawn(move || {
let _ = sender.send(lookup_host(&host, lookup.as_ref()));
});
Box::pin(async move {
let answer: Result<io::Result<Vec<IpAddr>>, _> = receiver.await;
progress.lookup_answered(attempt);
let addresses = answer
.unwrap_or_else(|_| Err(io::Error::other("host lookup stopped before answering")))
.map_err(|error| Box::new(error) as Box<dyn Error + Send + Sync>)?;
Ok(
Box::new(addresses.into_iter().map(|ip| SocketAddr::new(ip, 0)))
as reqwest::dns::Addrs,
)
})
}
}
fn lookup_host(host: &str, lookup_override: Option<&HostLookup>) -> io::Result<Vec<IpAddr>> {
if let Some(lookup) = lookup_override {
return lookup(host);
}
Ok((host, 0).to_socket_addrs()?.map(|addr| addr.ip()).collect())
}
fn validate_public_url(
url: &Url,
options: &UrlFetchOptions,
deadline: &FetchDeadline,
approved: &ApprovedHosts,
) -> Result<(), UrlFetchError> {
let started = Instant::now();
let result = check_public_url(url, options, deadline, approved);
let elapsed = started.elapsed();
timing::record(|times| times.lookup += elapsed);
result
}
fn check_public_url(
url: &Url,
options: &UrlFetchOptions,
deadline: &FetchDeadline,
approved: &ApprovedHosts,
) -> Result<(), UrlFetchError> {
if url.scheme() != "http" && url.scheme() != "https" {
return Err(UrlFetchError::new(format!(
"Only http:// and https:// URLs are supported, got: {}:",
url.scheme()
)));
}
if options.allow_private {
return Ok(());
}
let host = url
.host_str()
.ok_or_else(|| UrlFetchError::new(format!("URL missing host: {url}")))?;
let host_for_parse = host
.trim_matches(['[', ']'])
.split('%')
.next()
.unwrap_or(host);
if let Ok(ip) = host_for_parse.parse::<IpAddr>() {
reject_private_ip(host, ip)?;
return Ok(());
}
if host_for_parse.contains(':') {
return Err(UrlFetchError::new(format!(
"Blocked private URL host {host} ({host_for_parse})"
)));
}
if approved.get(host_for_parse).is_some() {
return Ok(());
}
let addresses = resolve_host_ips(host_for_parse, url.as_str(), options, deadline)?;
if addresses.is_empty() {
return Err(UrlFetchError::new(format!(
"Failed to resolve URL host {host}"
)));
}
for ip in &addresses {
reject_private_ip(host, *ip)?;
}
approved.insert(host_for_parse, addresses);
Ok(())
}
fn resolve_host_ips(
host: &str,
url: &str,
options: &UrlFetchOptions,
deadline: &FetchDeadline,
) -> Result<Vec<IpAddr>, UrlFetchError> {
if let Some((_, ips)) = options
.public_host_overrides
.iter()
.find(|(override_host, _)| override_host == host)
{
return Ok(ips.clone());
}
let remaining = deadline.remaining();
if remaining.is_zero() {
return Err(deadline.timeout_error(FetchPhase::Dns, url));
}
let (sender, receiver) = mpsc::channel();
let owned_host = host.to_string();
let lookup = options.lookup_override.clone();
thread::spawn(move || {
let _ = sender.send(lookup_host(&owned_host, lookup.as_ref()));
});
match receiver.recv_timeout(remaining) {
Ok(Ok(addresses)) => Ok(addresses),
Ok(Err(error)) => Err(UrlFetchError::new(format!(
"Failed to resolve URL host {host}: {error}"
))),
Err(mpsc::RecvTimeoutError::Timeout) => Err(deadline.timeout_error(FetchPhase::Dns, url)),
Err(mpsc::RecvTimeoutError::Disconnected) => Err(UrlFetchError::new(format!(
"Failed to resolve URL host {host}: lookup stopped before answering"
))),
}
}
fn reject_private_ip(host: &str, ip: IpAddr) -> Result<(), UrlFetchError> {
if is_private_ip(ip) {
return Err(UrlFetchError::new(format!(
"Blocked private URL host {host} ({ip})"
)));
}
Ok(())
}
pub fn is_private_or_reserved_ip(ip: IpAddr) -> bool {
is_private_ip(ip)
}
fn is_private_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(ipv4) => is_private_ipv4(ipv4),
IpAddr::V6(ipv6) => is_private_ipv6(ipv6),
}
}
fn is_private_ipv4(ip: Ipv4Addr) -> bool {
let [a, b, _, _] = ip.octets();
a == 0
|| a == 10
|| a == 127
|| (a == 172 && (16..=31).contains(&b))
|| (a == 192 && b == 168)
|| (a == 169 && b == 254)
|| (a == 100 && (64..=127).contains(&b))
|| (a == 198 && (18..=19).contains(&b))
|| a >= 224
}
fn is_private_ipv6(ip: Ipv6Addr) -> bool {
let segments = ip.segments();
let top_six_zero = segments[..6].iter().all(|segment| *segment == 0);
let is_mapped = segments[..5].iter().all(|segment| *segment == 0) && segments[5] == 0xffff;
if is_mapped || top_six_zero {
let embedded = Ipv4Addr::new(
(segments[6] >> 8) as u8,
(segments[6] & 0xff) as u8,
(segments[7] >> 8) as u8,
(segments[7] & 0xff) as u8,
);
return is_private_ipv4(embedded);
}
let first = segments[0];
(0xfe80..=0xfeff).contains(&first) || (0xfc00..=0xfdff).contains(&first) || first >= 0xff00
}
const BINARY_SNIFF_PREFIX: usize = 8 * 1024;
fn body_contains_nul_in_prefix(body: &[u8]) -> bool {
let end = body.len().min(BINARY_SNIFF_PREFIX);
body[..end].contains(&0)
}
fn resolve_fetch_extension(url: &Url, content_type: &str) -> Option<(&'static str, bool)> {
if let Some(ext) = extension_from_url_path(url) {
return Some((ext, true));
}
resolve_extension_from_content_type(content_type).map(|ext| (ext, false))
}
#[rustfmt::skip]
test_support_visibility! {
fn extension_from_url_path(url: &Url) -> Option<&'static str> {
let path = url.path();
if path.is_empty() || path == "/" {
return None;
}
let segment = path.rsplit('/').next().unwrap_or(path);
let file_name = percent_decode_path_segment(segment);
let dot = file_name.rfind('.')?;
let ext = &file_name[dot + 1..];
if ext.is_empty() {
return None;
}
let probe = Path::new("file").with_extension(ext);
if language_by_extension(&probe).is_some() {
static_extension_for_lang_ext(ext)
} else {
None
}
}
}
fn percent_decode_path_segment(segment: &str) -> String {
let mut out = String::with_capacity(segment.len());
let bytes = segment.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
if let (Some(h1), Some(h2)) = (from_hex(bytes[i + 1]), from_hex(bytes[i + 2])) {
out.push(char::from(h1 << 4 | h2));
i += 3;
continue;
}
}
out.push(bytes[i] as char);
i += 1;
}
out
}
fn from_hex(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
#[rustfmt::skip]
test_support_visibility! {
fn static_extension_for_lang_ext(ext: &str) -> Option<&'static str> {
match ext.to_ascii_lowercase().as_str() {
"ts" | "mts" | "cts" => Some(".ts"),
"tsx" => Some(".tsx"),
"js" => Some(".js"),
"jsx" => Some(".jsx"),
"mjs" => Some(".mjs"),
"cjs" => Some(".cjs"),
"py" | "pyi" => Some(".py"),
"rs" => Some(".rs"),
"go" => Some(".go"),
"c" => Some(".c"),
"h" => Some(".h"),
"cc" | "cpp" | "cxx" | "hpp" | "hh" => Some(".cpp"),
"zig" => Some(".zig"),
"cs" => Some(".cs"),
"sh" | "bash" | "zsh" => Some(".sh"),
"html" | "htm" => Some(".html"),
"md" | "markdown" | "mdx" => Some(".md"),
"sol" => Some(".sol"),
"scss" => Some(".scss"),
"vue" => Some(".vue"),
"json" | "jsonc" => Some(".json"),
"scala" | "sc" => Some(".scala"),
"java" => Some(".java"),
"rb" => Some(".rb"),
"kt" | "kts" => Some(".kt"),
"swift" => Some(".swift"),
"inc" | "php" => Some(".php"),
"lua" => Some(".lua"),
"pl" | "pm" | "t" => Some(".pl"),
"yaml" | "yml" => Some(".yaml"),
_ => None,
}
}
}
fn resolve_extension_from_content_type(content_type: &str) -> Option<&'static str> {
let lower = content_type.to_ascii_lowercase();
let media_type = lower
.split(';')
.next()
.unwrap_or("")
.split(',')
.next()
.unwrap_or("")
.trim();
match media_type {
"text/html"
| "application/xhtml+xml"
| "application/vnd.github.html"
| "application/vnd.github+html" => Some(".html"),
"text/markdown"
| "text/x-markdown"
| "application/markdown"
| "application/vnd.github.raw"
| "application/vnd.github+raw"
| "application/vnd.github.v3.raw"
| "text/plain" => Some(".md"),
"application/json" | "application/ld+json" => Some(".json"),
other if other.ends_with("+json") => Some(".json"),
"text/javascript" | "application/javascript" | "application/ecmascript" => Some(".js"),
"text/typescript" | "application/typescript" => Some(".ts"),
_ => None,
}
}
fn convert_html_body_to_markdown(body: &[u8], url: &str) -> Result<Vec<u8>, UrlFetchError> {
let started = Instant::now();
let result = html_body_to_markdown(body, url);
let elapsed = started.elapsed();
timing::record(|times| times.convert += elapsed);
result
}
fn html_body_to_markdown(body: &[u8], url: &str) -> Result<Vec<u8>, UrlFetchError> {
let html = String::from_utf8_lossy(body);
let mut markdown = html_to_markdown_converter()
.convert(&html)
.map_err(|error| {
UrlFetchError::new(format!(
"Failed to convert HTML from {url} to Markdown: {error}"
))
})?;
if !markdown.ends_with('\n') {
markdown.push('\n');
}
Ok(markdown.into_bytes())
}
const SKIPPED_HTML_TAGS: [&str; 8] = [
"head", "script", "style", "nav", "footer", "aside", "noscript", "button",
];
fn html_to_markdown_converter() -> HtmlToMarkdown {
HtmlToMarkdown::builder()
.skip_tags(SKIPPED_HTML_TAGS.to_vec())
.add_handler(
vec!["pre"],
|handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
if node_has_descendant_tag(element.node, "code") {
Some(fenced_code_block(&element).into())
} else {
handlers.fallback(element)
}
},
)
.add_handler(
vec!["a"],
|handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
if is_permalink_anchor(&element)
|| handlers.walk_children(element.node).content.trim() == "§"
{
None
} else if element_attr_value(&element, "href")
.is_some_and(|href| href.trim() == "#")
{
Some(handlers.walk_children(element.node).content.into())
} else {
handlers.fallback(element)
}
},
)
.add_handler(
vec!["header"],
|handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
if should_skip_header(&element) {
None
} else {
handlers.fallback(element)
}
},
)
.add_handler(
vec!["span"],
|handlers: &dyn Handlers, element: Element| -> Option<HandlerResult> {
if element_has_class_token(&element, "token-line") {
let mut content = handlers.walk_children(element.node).content;
content.push('\n');
Some(content.into())
} else {
handlers.fallback(element)
}
},
)
.build()
}
fn fenced_code_block(element: &Element<'_>) -> String {
let mut text = PreformattedText::default();
text.collect(element.node);
let mut code = text.output;
if code.ends_with('\n') {
code.pop();
}
let fence = code_fence_for(&code);
let language = find_descendant_element(element.node, "code")
.and_then(|code| node_class_attr(&code))
.as_deref()
.and_then(language_from_class)
.or_else(|| element_attr_value(element, "class").and_then(language_from_class));
let mut block = String::from("\n\n");
block.push_str(&fence);
if let Some(language) = language {
block.push_str(&language);
}
block.push('\n');
block.push_str(&code);
block.push('\n');
block.push_str(&fence);
block.push_str("\n\n");
block
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum PreLineBreak {
None,
Line,
Block,
}
fn pre_line_break(tag: &str, class: Option<&str>) -> PreLineBreak {
let has_class =
|token: &str| class.is_some_and(|value| value.split_ascii_whitespace().any(|c| c == token));
match tag {
"tr" | "li" => PreLineBreak::Line,
"span" if has_class("token-line") || has_class("line") => PreLineBreak::Line,
"div" | "p" => PreLineBreak::Block,
_ => PreLineBreak::None,
}
}
#[derive(Default)]
struct PreformattedText {
output: String,
pending_break: bool,
}
impl PreformattedText {
fn flush_pending_break(&mut self) {
if self.pending_break {
self.output.push('\n');
self.pending_break = false;
}
}
fn push_text(&mut self, text: &str) {
if text.is_empty() {
return;
}
if self.pending_break && text.starts_with('\n') {
self.pending_break = false;
}
self.flush_pending_break();
self.output.push_str(text);
}
fn collect(&mut self, node: &Node) {
for child in node.children.borrow().iter() {
match &child.data {
NodeData::Text { contents } => self.push_text(&contents.borrow()),
NodeData::Element { name, attrs, .. } => {
let tag = name.local.as_ref();
if SKIPPED_HTML_TAGS.contains(&tag) {
continue;
}
if tag == "br" {
self.flush_pending_break();
self.output.push('\n');
continue;
}
let line_break = {
let attrs = attrs.borrow();
let class = attrs
.iter()
.find(|attr| attr.name.local.as_ref() == "class")
.map(|attr| attr.value.as_ref());
pre_line_break(tag, class)
};
if line_break == PreLineBreak::None {
self.collect(child);
continue;
}
self.flush_pending_break();
let line_start = self.output.len();
self.collect(child);
let line = &self.output[line_start..];
let line_ended = self.pending_break || line.ends_with('\n');
let ends_line = match line_break {
PreLineBreak::None => false,
PreLineBreak::Line => !line_ended,
PreLineBreak::Block => !line.is_empty() && !line_ended,
};
if ends_line {
self.pending_break = true;
}
}
_ => {}
}
}
}
}
fn code_fence_for(code: &str) -> String {
let mut longest = 0;
let mut current = 0;
for ch in code.chars() {
if ch == '`' {
current += 1;
longest = longest.max(current);
} else {
current = 0;
}
}
"`".repeat((longest + 1).max(3))
}
fn language_from_class(class: &str) -> Option<String> {
class
.split_ascii_whitespace()
.find_map(|token| token.strip_prefix("language-"))
.filter(|language| !language.is_empty())
.map(str::to_string)
}
fn node_has_descendant_tag(node: &Node, tag: &str) -> bool {
find_descendant_element(node, tag).is_some()
}
fn find_descendant_element(node: &Node, tag: &str) -> Option<Rc<Node>> {
for child in node.children.borrow().iter() {
if let NodeData::Element { name, .. } = &child.data {
if name.local.as_ref() == tag {
return Some(Rc::clone(child));
}
if let Some(found) = find_descendant_element(child, tag) {
return Some(found);
}
}
}
None
}
fn node_class_attr(node: &Node) -> Option<String> {
match &node.data {
NodeData::Element { attrs, .. } => attrs
.borrow()
.iter()
.find(|attr| attr.name.local.as_ref() == "class")
.map(|attr| attr.value.to_string()),
_ => None,
}
}
fn is_permalink_anchor(element: &Element<'_>) -> bool {
element_has_class_token(element, "hash-link")
|| element_has_class_token(element, "doc-anchor")
|| element_attr_value(element, "aria-label")
.is_some_and(|value| value.to_ascii_lowercase().starts_with("direct link to"))
}
fn should_skip_header(element: &Element<'_>) -> bool {
element_has_class_token(element, "navbar")
|| element_has_class_token(element, "site-header")
|| element_has_class_token(element, "site-nav")
|| element_has_class_token(element, "topbar")
|| element_attr_value(element, "role")
.is_some_and(|value| value.eq_ignore_ascii_case("banner"))
|| element_attr_value(element, "id").is_some_and(|value| {
let value = value.to_ascii_lowercase();
value.contains("navbar") || value.contains("site-header") || value.contains("site-nav")
})
}
fn element_has_class_token(element: &Element<'_>, token: &str) -> bool {
element_attr_value(element, "class")
.is_some_and(|value| value.split_ascii_whitespace().any(|class| class == token))
}
fn element_attr_value<'a>(element: &'a Element<'_>, name: &str) -> Option<&'a str> {
element
.attrs
.iter()
.find(|attr| attr.name.local.as_ref() == name)
.map(|attr| attr.value.as_ref())
}
enum BodyReadEvent {
Chunk(sensitive::Bytes),
Done,
Error(io::ErrorKind, sensitive::Bytes, Duration),
}
fn read_response_body(
response: impl Read + Send + 'static,
url: &str,
deadline: &FetchDeadline,
) -> Result<(Vec<u8>, bool), UrlFetchError> {
read_response_body_with(response, url, deadline, &|detail: &str| detail.to_string())
.map(|(body, truncated)| (body.into_plain_vec(), truncated))
}
fn read_response_body_with(
response: impl Read + Send + 'static,
url: &str,
deadline: &FetchDeadline,
detail: &dyn Fn(&str) -> String,
) -> Result<(sensitive::Bytes, bool), UrlFetchError> {
let (tx, rx) = mpsc::sync_channel(1);
let factory = sensitive::Factory::current();
let worker = factory.clone();
thread::spawn(move || {
let mut response = response.take(MAX_RESPONSE_BYTES + 1);
let mut buffer = worker.zeroed(16 * 1024);
loop {
let read_started = Instant::now();
match response.read(&mut buffer) {
Ok(0) => {
let _ = tx.send(BodyReadEvent::Done);
break;
}
Ok(n) => {
if tx
.send(BodyReadEvent::Chunk(worker.copy(&buffer[..n])))
.is_err()
{
break;
}
}
Err(error) => {
let kind = error.kind();
let message = worker.format(format_args!("{error}"));
let waited = read_started.elapsed();
let _ = tx.send(BodyReadEvent::Error(kind, message, waited));
break;
}
}
}
});
struct BodyTimer {
started: Instant,
bytes: u64,
}
impl Drop for BodyTimer {
fn drop(&mut self) {
let (elapsed, bytes) = (self.started.elapsed(), self.bytes);
timing::record(|times| {
times.body += elapsed;
times.body_bytes += bytes;
});
}
}
let mut timer = BodyTimer {
started: Instant::now(),
bytes: 0,
};
let mut chunks = factory.with_capacity(0);
let mut total = 0u64;
let slow_body_error = || {
if deadline.expired() {
deadline.timeout_error(FetchPhase::Body, url)
} else {
body_stall_error(url)
}
};
loop {
let wait = BODY_CHUNK_TIMEOUT.min(deadline.remaining());
if wait.is_zero() {
return Err(deadline.timeout_error(FetchPhase::Body, url));
}
match rx.recv_timeout(wait) {
Ok(BodyReadEvent::Chunk(chunk)) => {
let remaining = (MAX_RESPONSE_BYTES - total) as usize;
chunks.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
total += chunk.len() as u64;
timer.bytes = total;
if total > MAX_RESPONSE_BYTES {
return Ok((chunks, true));
}
}
Ok(BodyReadEvent::Done) => return Ok((chunks, false)),
Ok(BodyReadEvent::Error(kind, message, waited)) => {
return Err(body_read_failure(
deadline,
url,
kind,
&detail(std::str::from_utf8(&message).unwrap_or_default()),
waited,
));
}
Err(mpsc::RecvTimeoutError::Timeout) => return Err(slow_body_error()),
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err(UrlFetchError::new(format!(
"Failed to read response body for {url}: body reader stopped unexpectedly"
)));
}
}
}
}
fn body_read_failure(
deadline: &FetchDeadline,
url: &str,
kind: io::ErrorKind,
message: &str,
waited: Duration,
) -> UrlFetchError {
if deadline.expired() {
return deadline.timeout_error(FetchPhase::Body, url);
}
if waited >= BODY_CHUNK_TIMEOUT || is_body_stall_kind(kind) {
return body_stall_error(url);
}
if message.is_empty() {
return UrlFetchError::new(format!("Failed to read response body for {url}"));
}
UrlFetchError::new(format!("Failed to read response body for {url}: {message}"))
}
fn body_stall_error(url: &str) -> UrlFetchError {
UrlFetchError::timeout(
FetchPhase::Body,
format!(
"Body read stalled (no data for {}ms) fetching {url}",
BODY_CHUNK_TIMEOUT.as_millis()
),
)
}
fn is_body_stall_kind(kind: io::ErrorKind) -> bool {
matches!(kind, io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock)
}
fn atomic_write(
final_path: &Path,
bytes: &[u8],
options: &UrlFetchOptions,
) -> Result<(), UrlFetchError> {
let parent = final_path.parent().unwrap_or_else(|| Path::new("."));
crate::private_storage::create_dir_all(parent).map_err(|error| {
UrlFetchError::new(format!(
"Failed to create URL cache parent {}: {error}",
parent.display()
))
})?;
let file_name = final_path
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| {
UrlFetchError::new(format!("Invalid cache path: {}", final_path.display()))
})?;
let tmp_path = final_path.with_file_name(format!(
"{file_name}.tmp-{}-{}",
std::process::id(),
random_nonce()
));
let write_result = (|| -> io::Result<()> {
let mut file = crate::private_storage::create(&tmp_path)?;
file.write_all(bytes)?;
file.flush()?;
Ok(())
})();
if let Err(error) = write_result {
let _ = fs::remove_file(&tmp_path);
return Err(UrlFetchError::new(format!(
"Failed to write URL cache temp file {}: {error}",
tmp_path.display()
)));
}
if let Some(observer) = &options.atomic_write_observer {
observer(&tmp_path, final_path);
}
fs::rename(&tmp_path, final_path).map_err(|error| {
let _ = fs::remove_file(&tmp_path);
UrlFetchError::new(format!(
"Failed to finalize URL cache file {}: {error}",
final_path.display()
))
})
}
fn random_nonce() -> String {
let mut bytes = [0u8; 8];
if getrandom::fill(&mut bytes).is_err() {
let fallback = now_ms() ^ u64::from(std::process::id());
bytes = fallback.to_le_bytes();
}
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
}
out
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
.try_into()
.unwrap_or(u64::MAX)
}
fn reqwest_error_detail(error: &reqwest::Error) -> String {
if error.is_timeout() {
return format!("timeout: {error}");
}
if let Some(source) = error.source() {
return format!("{source}");
}
error.to_string()
}
pub mod timing {
use std::cell::RefCell;
use std::fmt::Write as _;
use std::time::Duration;
use super::FetchPhase;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct UrlFetchTimes {
pub fetches: u32,
pub cache_hits: u32,
pub remembered_failures: u32,
pub lookup: Duration,
pub connect: Duration,
pub first_byte: Duration,
pub body: Duration,
pub body_bytes: u64,
pub convert: Duration,
pub redirects: u32,
pub retries: u32,
pub error: Option<(&'static str, Option<FetchPhase>)>,
}
impl UrlFetchTimes {
pub fn render(&self) -> String {
let ms = |duration: Duration| duration.as_secs_f64() * 1000.0;
let mut out = format!(
"url_fetch=fetches:{},cache_hits:{},remembered:{},lookup:{:.2},connect:{:.2},first_byte:{:.2},body:{:.2},bytes:{},convert:{:.2},redirects:{},retries:{}",
self.fetches,
self.cache_hits,
self.remembered_failures,
ms(self.lookup),
ms(self.connect),
ms(self.first_byte),
ms(self.body),
self.body_bytes,
ms(self.convert),
self.redirects,
self.retries,
);
if let Some((code, phase)) = self.error {
let _ = write!(out, ",error:{code}");
if let Some(phase) = phase {
let _ = write!(out, "/{}", phase.as_str());
}
}
out
}
}
thread_local! {
static COLLECTOR: RefCell<Option<UrlFetchTimes>> = const { RefCell::new(None) };
}
#[must_use = "a scope collects nothing once dropped"]
pub struct FetchTimesScope {
owns: bool,
}
pub fn begin() -> FetchTimesScope {
let owns = COLLECTOR.with(|collector| {
let mut collector = collector.borrow_mut();
if collector.is_some() {
return false;
}
*collector = Some(UrlFetchTimes::default());
true
});
FetchTimesScope { owns }
}
impl FetchTimesScope {
pub fn finish(mut self) -> Option<UrlFetchTimes> {
if !self.owns {
return None;
}
self.owns = false;
COLLECTOR
.with(|collector| collector.replace(None))
.filter(|times| times.fetches > 0)
}
}
impl Drop for FetchTimesScope {
fn drop(&mut self) {
if self.owns {
COLLECTOR.with(|collector| collector.replace(None));
}
}
}
pub(super) fn record(update: impl FnOnce(&mut UrlFetchTimes)) {
COLLECTOR.with(|collector| {
if let Some(times) = collector.borrow_mut().as_mut() {
update(times);
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use url::Url;
#[test]
fn h_header_url_cache_preserves_ambiguous_extension() {
assert_eq!(super::static_extension_for_lang_ext("h"), Some(".h"));
}
fn write_cache_entry(storage: &Path, hash: &str, url: &str, fetched_at: u64) -> PathBuf {
let dir = cache_dir(storage);
fs::create_dir_all(&dir).unwrap();
let meta = CacheMeta {
url: url.to_string(),
content_type: "text/markdown".to_string(),
extension: ".md".to_string(),
fetched_at,
download_truncated: false,
downloaded_bytes: 4,
total_bytes: Some(4),
};
fs::write(content_path(storage, hash, ".md"), "body").unwrap();
let meta_file = meta_path(storage, hash);
fs::write(&meta_file, serde_json::to_vec(&meta).unwrap()).unwrap();
meta_file
}
fn cleanup_counting_reads(storage: &Path, now: u64) -> (usize, usize) {
CLEANUP_META_READS.with(|reads| reads.set(0));
let removed = cleanup_url_cache_at(storage, now).unwrap();
(removed, CLEANUP_META_READS.with(std::cell::Cell::get))
}
#[test]
fn url_cache_cleanup_does_not_reread_unchanged_metadata() {
let storage = tempfile::tempdir().unwrap();
let now = 10 * CACHE_TTL_MS;
for index in 0..3 {
write_cache_entry(
storage.path(),
&format!("fresh{index}"),
"https://example.com/a",
now - 1_000,
);
}
let stale = write_cache_entry(
storage.path(),
"stale",
"https://example.com/b",
now - CACHE_TTL_MS - 1,
);
assert_eq!(cleanup_counting_reads(storage.path(), now), (1, 4));
assert!(!stale.exists());
assert!(!content_path(storage.path(), "stale", ".md").exists());
assert_eq!(cleanup_counting_reads(storage.path(), now), (0, 0));
}
#[test]
fn url_cache_cleanup_memo_still_expires_and_notices_rewrites() {
let storage = tempfile::tempdir().unwrap();
let now = 10 * CACHE_TTL_MS;
let kept = write_cache_entry(storage.path(), "kept", "https://example.com/a", now);
let rewritten =
write_cache_entry(storage.path(), "rewritten", "https://example.com/b", now);
assert_eq!(cleanup_counting_reads(storage.path(), now), (0, 2));
write_cache_entry(
storage.path(),
"rewritten",
"https://example.com/b-longer",
now - CACHE_TTL_MS - 1,
);
assert_eq!(cleanup_counting_reads(storage.path(), now), (1, 1));
assert!(!rewritten.exists());
assert!(kept.exists());
assert_eq!(
cleanup_counting_reads(storage.path(), now + CACHE_TTL_MS + 1),
(1, 0)
);
assert!(!kept.exists());
}
#[test]
fn web_view_urls_rewrite_to_raw_content() {
let cases = [
(
"https://github.com/owner/repo/blob/main/docs/guide.md?download=1#L42",
"https://raw.githubusercontent.com/owner/repo/main/docs/guide.md?download=1",
),
(
"https://github.com/owner/repo/raw/v1.2/src/lib.rs?raw=1#L7",
"https://raw.githubusercontent.com/owner/repo/v1.2/src/lib.rs?raw=1",
),
(
"https://www.github.com/owner/repo/blob/main/README.md",
"https://raw.githubusercontent.com/owner/repo/main/README.md",
),
(
"https://gitlab.com/owner/repo/-/blob/main/docs/guide.md?plain=1#L4",
"https://gitlab.com/owner/repo/-/raw/main/docs/guide.md?plain=1",
),
];
for (input, expected) in cases {
let url = Url::parse(input).unwrap();
assert_eq!(rewrite_url_for_fetch(&url).as_str(), expected);
}
}
#[test]
fn non_web_view_urls_are_not_rewritten() {
for input in [
"https://gist.github.com/owner/abcdef/blob/main/file.md",
"https://github.com/owner/repo",
"https://github.com/owner/repo/blob",
"https://api.github.com/repos/owner/repo",
"https://notgithub.com/owner/repo/blob/main/file.md",
"https://gitlab.example.com/owner/repo/-/blob/main/file.md",
] {
let url = Url::parse(input).unwrap();
assert_eq!(rewrite_url_for_fetch(&url).as_str(), input);
}
}
#[test]
fn extension_from_path_uses_parser_mapping() {
let url = Url::parse("https://example.com/pkg/index.mjs").unwrap();
let (ext, from_path) = resolve_fetch_extension(&url, "text/javascript").unwrap();
assert_eq!(ext, ".mjs");
assert!(from_path);
}
#[test]
fn text_plain_rs_url_ignores_content_type_gate() {
let url = Url::parse("https://raw.githubusercontent.com/o/r/main/lib.rs").unwrap();
let (ext, from_path) = resolve_fetch_extension(&url, "text/plain").unwrap();
assert_eq!(ext, ".rs");
assert!(from_path);
}
#[test]
fn extensionless_javascript_maps_to_js() {
let url = Url::parse("https://cdn.example/bundle").unwrap();
let (ext, from_path) = resolve_fetch_extension(&url, "text/javascript").unwrap();
assert_eq!(ext, ".js");
assert!(!from_path);
}
#[test]
fn extensionless_plain_stays_md() {
let url = Url::parse("https://example.com/readme").unwrap();
let (ext, _) = resolve_fetch_extension(&url, "text/plain").unwrap();
assert_eq!(ext, ".md");
}
#[test]
fn query_and_fragment_do_not_break_path_extension() {
let url = Url::parse("https://example.com/src/file.ts?v=2#L10").unwrap();
let (ext, from_path) = resolve_fetch_extension(&url, "text/plain").unwrap();
assert_eq!(ext, ".ts");
assert!(from_path);
}
#[test]
fn percent_encoded_path_segment() {
let url = Url::parse("https://example.com/foo%2Fbar.rs").unwrap();
let (ext, _) = resolve_fetch_extension(&url, "text/plain").unwrap();
assert_eq!(ext, ".rs");
}
#[test]
fn binary_sniff_detects_nul() {
let mut body = vec![b'f', b'n', 0, b' '];
assert!(body_contains_nul_in_prefix(&body));
body = vec![b'h'; 9000];
assert!(!body_contains_nul_in_prefix(&body));
}
#[test]
fn unsupported_pdf_still_errors_via_resolve() {
let url = Url::parse("https://example.com/doc.pdf").unwrap();
assert!(resolve_fetch_extension(&url, "application/pdf").is_none());
}
#[test]
fn is_permalink_anchor_doc_anchor_class_drops_anchor() {
let md = html_to_markdown_converter()
.convert("<a class=\"doc-anchor\" href=\"#stdio-transport\">x</a>")
.unwrap();
assert_eq!(
md.trim(),
"",
"doc-anchor permalink should be dropped: {md:?}"
);
}
#[test]
fn html_to_markdown_rustdoc_heading_cleanup() {
let html = "<main><h1>Function <span class=\"fn\">stdio</span> <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>";
let md = html_to_markdown_converter().convert(html).unwrap();
assert!(md.contains("# Function stdio"), "{md:?}");
assert!(!md.contains("Copy item path"), "{md:?}");
assert!(md.contains("## stdio"), "{md:?}");
assert!(!md.contains("[stdio](#)"), "{md:?}");
assert!(md.contains("## StdIO Transport"), "{md:?}");
assert!(!md.contains('§'), "{md:?}");
assert!(!md.contains("](#stdio-transport)"), "{md:?}");
}
#[test]
fn html_to_markdown_docusaurus_hash_link_still_dropped() {
let html = "<h2>The Retain Pipeline<a class=\"hash-link\" href=\"#x\" aria-label=\"Direct link to The Retain Pipeline\">\u{200b}</a></h2>";
let md = html_to_markdown_converter().convert(html).unwrap();
assert!(md.contains("## The Retain Pipeline"), "{md:?}");
assert!(!md.contains('\u{200b}'), "{md:?}");
}
const CHROME_AUTO_CONNECT_HTML: &str =
include_str!("../../aft/tests/fixtures/url_html/chrome_auto_connect.html");
fn fenced_blocks(markdown: &str) -> Vec<(String, String)> {
let mut blocks = Vec::new();
let mut open: Option<(String, usize, Vec<String>)> = None;
for line in markdown.lines() {
let trimmed = line.trim_start();
match open.take() {
None => {
if trimmed.starts_with("```") {
let indent = line.len() - trimmed.len();
open = Some((trimmed.to_string(), indent, Vec::new()));
}
}
Some((fence_line, indent, mut body)) => {
let fence: String = fence_line.chars().take_while(|c| *c == '`').collect();
if trimmed == fence {
blocks.push((fence_line, body.join("\n")));
} else {
let unindented = line
.strip_prefix(&" ".repeat(indent))
.unwrap_or(line.trim_start());
body.push(unindented.to_string());
open = Some((fence_line, indent, body));
}
}
}
}
assert!(open.is_none(), "unclosed fence in {markdown}");
blocks
}
#[test]
fn html_to_markdown_pre_closed_code_early_stays_one_fenced_block() {
let md = html_to_markdown_converter()
.convert(CHROME_AUTO_CONNECT_HTML)
.unwrap();
let blocks = fenced_blocks(&md);
assert_eq!(blocks.len(), 1, "{md}");
let (fence_line, body) = &blocks[0];
assert_eq!(fence_line, "```", "{md}");
assert_eq!(
body,
concat!(
"{\n",
" \"mcpServers\": {\n",
" \"chrome-devtools\": {\n",
" \"command\": \"npx\",\n",
" \"args\": [\"chrome-devtools-mcp@latest\", \"--autoConnect\"]\n",
" }\n",
" }\n",
"}",
),
"{md}"
);
assert!(
md.contains(r#""args": ["chrome-devtools-mcp@latest", "--autoConnect"]"#),
"{md}"
);
assert!(!md.contains("```ome"), "{md}");
}
#[test]
fn html_to_markdown_pre_keeps_code_verbatim() {
let html = "<pre><code class=\"language-md\">line *one*\n\n\n\n # not a heading <b>\n</code></pre>";
let md = html_to_markdown_converter().convert(html).unwrap();
assert_eq!(
md.trim(),
"```md\nline *one*\n\n\n\n # not a heading <b>\n```",
"{md:?}"
);
}
#[test]
fn html_to_markdown_code_containing_triple_backticks_gets_longer_fence() {
let html = "<pre><code>Example:\n```rust\nfn main() {}\n```\n</code></pre>";
let md = html_to_markdown_converter().convert(html).unwrap();
assert_eq!(
md.trim(),
"````\nExample:\n```rust\nfn main() {}\n```\n````",
"{md:?}"
);
let html = "<pre><code>a ````` run</code></pre>";
let md = html_to_markdown_converter().convert(html).unwrap();
assert_eq!(md.trim(), "``````\na ````` run\n``````", "{md:?}");
}
#[test]
fn html_to_markdown_pre_without_code_keeps_htmd_rendering() {
let html = "<pre>plain preformatted</pre>";
let md = html_to_markdown_converter().convert(html).unwrap();
assert!(!md.contains("```"), "{md:?}");
assert!(md.contains("plain preformatted"), "{md:?}");
}
#[test]
fn html_to_markdown_pre_per_line_divs_keep_their_lines() {
let md = html_to_markdown_converter()
.convert(include_str!(
"../../aft/tests/fixtures/url_html/per_line_divs.html"
))
.unwrap();
let blocks = fenced_blocks(&md);
assert_eq!(blocks.len(), 1, "{md}");
assert_eq!(blocks[0].0, "```js", "{md}");
assert_eq!(
blocks[0].1, "function greet(name) {\n return `Hello, ${name}`;\n\n}",
"{md}"
);
}
#[test]
fn html_to_markdown_pre_table_rows_keep_their_lines() {
let md = html_to_markdown_converter()
.convert(include_str!(
"../../aft/tests/fixtures/url_html/table_rows.html"
))
.unwrap();
let blocks = fenced_blocks(&md);
assert_eq!(blocks.len(), 1, "{md}");
assert_eq!(blocks[0].0, "```python", "{md}");
assert_eq!(
blocks[0].1, "def add(a, b):\n return a + b\n\nprint(add(1, 2))",
"{md}"
);
}
#[test]
fn html_to_markdown_pre_shiki_line_spans_keep_their_lines() {
let md = html_to_markdown_converter()
.convert(include_str!(
"../../aft/tests/fixtures/url_html/shiki_lines.html"
))
.unwrap();
let blocks = fenced_blocks(&md);
assert_eq!(blocks.len(), 1, "{md}");
assert_eq!(blocks[0].0, "```", "{md}");
assert_eq!(
blocks[0].1,
"const total = items.reduce((sum, item) => sum + item.price, 0);\n\nconsole.log(total);",
"{md}"
);
}
#[test]
fn html_to_markdown_pre_list_item_lines_keep_their_lines() {
let html = "<pre><code><ol><li>first</li><li></li><li> third</li></ol></code></pre>";
let md = html_to_markdown_converter().convert(html).unwrap();
assert_eq!(md.trim(), "```\nfirst\n\n third\n```", "{md:?}");
}
#[test]
fn html_to_markdown_pre_newline_text_between_lines_is_not_doubled() {
let html = "<pre><code><span class=\"line\">a</span>\n<span class=\"line\">b</span>\n<div>c\n</div></code></pre>";
let md = html_to_markdown_converter().convert(html).unwrap();
assert_eq!(md.trim(), "```\na\nb\nc\n```", "{md:?}");
}
#[test]
fn code_fence_for_outgrows_longest_backtick_run() {
assert_eq!(code_fence_for("no ticks"), "```");
assert_eq!(code_fence_for("`inline` ``double``"), "```");
assert_eq!(code_fence_for("```"), "````");
assert_eq!(code_fence_for("``` and ````"), "`````");
}
#[test]
fn html_conversion_markdown_escapes_an_entity_decoded_character() {
let markdown =
convert_html_body_to_markdown(b"<p>abcdef*1234567890</p>", "https://example.test/")
.unwrap();
let text = String::from_utf8(markdown).unwrap();
assert!(text.contains("abcdef\\*1234567890"), "{text}");
}
#[test]
fn a_failed_body_read_in_a_placeholder_fetch_is_scrubbed_of_held_keys() {
struct Failing;
impl Read for Failing {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Err(io::Error::other(
"error reading body for url (https://api.test/v1?key=fetch-secret-key%2F0123456789%2Babc)",
))
}
}
let mut held = HeldKeys::default();
held.hold("test", b"fetch-secret-key/0123456789+abc")
.unwrap();
let deadline = FetchDeadline::for_current_call();
let sanitize = |detail: &str| held.sanitize_detail(detail);
let error = read_response_body_with(Failing, "https://api.test/v1", &deadline, &sanitize)
.expect_err("the read fails");
let text = error.to_string();
assert!(!text.contains("fetch-secret-key"), "{text}");
assert!(text.contains("key={{ck-secret:test}})"), "{text}");
}
#[test]
fn a_placeholder_fetch_send_failure_drops_the_request_url() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(move || {
let accepted = listener.accept();
thread::sleep(Duration::from_secs(5));
drop(accepted);
});
let url = format!("http://{addr}/v1?key=fetch-secret-key%2F0123456789%2Babc");
let error = Client::builder()
.timeout(Duration::from_millis(300))
.build()
.unwrap()
.get(&url)
.send()
.expect_err("the silent server times the request out");
assert!(error.to_string().contains("for url"), "{error}");
let mut held = HeldKeys::default();
held.hold("test", b"fetch-secret-key/0123456789+abc")
.unwrap();
let deadline = FetchDeadline::for_current_call();
let failure = send_failure(
error,
Some(FetchPhase::Headers),
&deadline,
"http://api.test/v1?key={{ck-secret:test}}",
Some(&held),
);
let text = failure.to_string();
assert!(text.contains("timed out"), "{text}");
assert!(!text.contains("for url"), "{text}");
assert!(!text.contains("fetch-secret-key"), "{text}");
}
#[test]
fn deprecated_site_local_ipv6_is_private() {
for address in ["fec0::1", "feff::1", "fef0:1::1"] {
let ip: IpAddr = address.parse().unwrap();
assert!(is_private_ip(ip), "{address}");
}
assert!(!is_private_ip("2606:4700::1".parse().unwrap()));
}
}
#[cfg(any(test, feature = "test-support"))]
#[path = "url_fetch_deadline_tests.rs"]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
pub mod deadline_tests;
#[cfg(test)]
mod fetch_times_tests {
use super::timing::UrlFetchTimes;
use super::*;
use std::net::TcpListener;
const DOCUMENT: &[u8] = b"# Guide\n\n## Install\n\nRun the installer.\n";
fn slow_server(before_headers: Duration, before_body: Duration) -> SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
let address = listener.local_addr().expect("test server address");
thread::spawn(move || {
for mut stream in listener.incoming().flatten() {
thread::spawn(move || {
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let mut head = Vec::new();
let mut buffer = [0u8; 1024];
while !head.windows(4).any(|window| window == b"\r\n\r\n") {
match stream.read(&mut buffer) {
Ok(0) | Err(_) => return,
Ok(n) => head.extend_from_slice(&buffer[..n]),
}
}
thread::sleep(before_headers);
let headers = format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/markdown\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
DOCUMENT.len()
);
if stream.write_all(headers.as_bytes()).is_err() {
return;
}
let _ = stream.flush();
thread::sleep(before_body);
let _ = stream.write_all(DOCUMENT);
});
}
});
address
}
fn local() -> UrlFetchOptions {
UrlFetchOptions {
allow_private: true,
..UrlFetchOptions::default()
}
}
fn timed_fetch(
budget: Duration,
url: &str,
storage: &Path,
) -> (Result<PathBuf, UrlFetchError>, UrlFetchTimes) {
let _call = crate::bounded_io::enter(Some(crate::bounded_io::Budget::after(budget)));
let scope = timing::begin();
let result = fetch_url_to_cache(url, storage, local());
let times = scope.finish().expect("the fetch was counted");
(result, times)
}
#[test]
fn url_fetch_times_split_a_slow_download_and_count_a_cache_hit() {
let storage = tempfile::tempdir().unwrap();
let address = slow_server(Duration::from_millis(300), Duration::from_millis(200));
let url = format!("http://127.0.0.1:{}/guide.md", address.port());
let (result, times) = timed_fetch(Duration::from_secs(10), &url, storage.path());
result.expect("the slow server answers within the deadline");
assert_eq!(times.fetches, 1, "{times:?}");
assert_eq!(times.cache_hits, 0, "{times:?}");
assert_eq!(times.remembered_failures, 0, "{times:?}");
assert_eq!((times.redirects, times.retries), (0, 0), "{times:?}");
assert_eq!(times.error, None, "{times:?}");
assert!(times.first_byte >= Duration::from_millis(300), "{times:?}");
assert!(times.connect <= times.first_byte, "{times:?}");
assert!(times.body >= Duration::from_millis(150), "{times:?}");
assert_eq!(times.body_bytes, DOCUMENT.len() as u64, "{times:?}");
let rendered = times.render();
assert!(
rendered.starts_with("url_fetch=fetches:1,cache_hits:0,remembered:0,"),
"{rendered}"
);
assert!(!rendered.contains("guide"), "{rendered}");
assert!(!rendered.contains(' '), "{rendered}");
let (result, times) = timed_fetch(Duration::from_secs(10), &url, storage.path());
result.expect("the cached copy is served");
assert_eq!((times.fetches, times.cache_hits), (1, 1), "{times:?}");
assert_eq!(times.first_byte, Duration::ZERO, "{times:?}");
assert_eq!(times.body_bytes, 0, "{times:?}");
}
#[test]
fn url_fetch_times_name_a_timeout_and_its_phase() {
let storage = tempfile::tempdir().unwrap();
let address = slow_server(Duration::from_secs(60), Duration::ZERO);
let url = format!("http://127.0.0.1:{}/silent.md", address.port());
let (result, times) = timed_fetch(Duration::from_secs(5), &url, storage.path());
let error = result.expect_err("a server that never answers fails");
assert_eq!(error.code(), "url_fetch_timeout", "{error}");
assert_eq!(
times.error,
Some(("url_fetch_timeout", Some(FetchPhase::Headers))),
"{times:?}"
);
assert!(
times.first_byte >= Duration::from_millis(1_500),
"{times:?}"
);
assert_eq!(times.body_bytes, 0, "{times:?}");
assert!(
times.render().ends_with(",error:url_fetch_timeout/headers"),
"{}",
times.render()
);
}
#[test]
fn url_fetch_times_collect_only_inside_the_outermost_scope() {
timing::record(|times| times.fetches += 1);
assert_eq!(timing::begin().finish(), None, "nothing ran in this scope");
let outer = timing::begin();
let inner = timing::begin();
timing::record(|times| times.fetches += 1);
assert_eq!(inner.finish(), None);
timing::record(|times| times.fetches += 1);
assert_eq!(outer.finish().map(|times| times.fetches), Some(2));
drop(timing::begin());
timing::record(|times| times.fetches += 1);
assert_eq!(timing::begin().finish(), None, "a dropped scope closed");
}
#[test]
fn url_fetch_times_render_every_field_in_milliseconds() {
let times = UrlFetchTimes {
fetches: 2,
cache_hits: 1,
remembered_failures: 0,
lookup: Duration::from_micros(2_100),
connect: Duration::from_millis(40),
first_byte: Duration::from_micros(5_800_004),
body: Duration::from_millis(300),
body_bytes: 51_234,
convert: Duration::from_millis(4),
redirects: 1,
retries: 0,
error: Some(("url_fetch_failed", None)),
};
assert_eq!(
times.render(),
"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"
);
}
}
#[cfg(test)]
mod secret_audit_regressions {
use super::*;
#[test]
fn substituted_query_allocates_its_exact_complete_size_before_copying_any_key() {
let first = Zeroizing::new(vec![b'a'; 1001]);
let second = Zeroizing::new(vec![b'b'; 2103]);
let result = substitute_query(b"a=x&b=y", &[(2, 3, first), (6, 7, second)]).unwrap();
assert_eq!(result.len(), 5 + 1001 + 2103);
assert_eq!(
result.capacity(),
result.len(),
"a later key must not reallocate a buffer that already contains an earlier key"
);
assert_eq!(&result[..2], b"a=");
assert_eq!(&result[1003..1006], b"&b=");
}
#[test]
fn approval_wait_preserves_the_fetch_and_read_back_network_budget() {
let _scope = crate::bounded_io::enter(Some(crate::bounded_io::Budget::after(
Duration::from_secs(25),
)));
let before = crate::bounded_io::current().unwrap().deadline;
let deadline = FetchDeadline::for_current_call();
let person_wait = Duration::from_secs(360);
crate::bounded_io::exclude_secret_approval_wait(person_wait);
assert_eq!(
crate::bounded_io::current().unwrap().deadline,
before + person_wait
);
assert_eq!(deadline.allowed, URL_FETCH_CEILING);
}
}