#![forbid(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use std::borrow::Cow;
use std::collections::HashMap;
use std::future::Future;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use futures_io::{AsyncRead, AsyncWrite};
use hyper::body::{Body as _, Bytes, Frame, Incoming, SizeHint};
use hyper::header::{HeaderName, HeaderValue};
use hyper::http::uri::Scheme;
use hyper::{Method, Request, Response, StatusCode, Uri, Version};
use ostrya_rt as rt;
use std::pin::Pin;
use std::task::{Context, Poll, Waker, ready};
mod error;
pub mod gate;
mod io;
mod tls;
pub use self::error::{Error, Result};
use gate::{Gate, Permit};
#[doc(hidden)]
pub use io::{FuturesIo, RtExecutor, RtTimer, WriteVectored};
#[doc(hidden)]
pub use tls::server_config;
use tls::{ClientConfigs, client_config};
pub use tls::{ClientIdentity, TlsOptions, TrustRoots};
const USER_AGENT: &str = concat!("ostrya/", env!("CARGO_PKG_VERSION"));
const IDENTITY: &str = "identity";
const CHUNKED: &str = "chunked";
const PROXY_VARIABLES: [&str; 7] = [
"http_proxy",
"https_proxy",
"HTTPS_PROXY",
"all_proxy",
"ALL_PROXY",
"no_proxy",
"NO_PROXY",
];
const PROXY_SCHEME: &str = "http://";
const REDIRECTS: [StatusCode; 5] = [
StatusCode::MOVED_PERMANENTLY,
StatusCode::FOUND,
StatusCode::SEE_OTHER,
StatusCode::TEMPORARY_REDIRECT,
StatusCode::PERMANENT_REDIRECT,
];
const UPLOAD_REDIRECTS: [StatusCode; 2] = [
StatusCode::TEMPORARY_REDIRECT,
StatusCode::PERMANENT_REDIRECT,
];
const AMBIGUOUS_AUTHORIZATION: &str =
"basic-auth credentials and an authorization header both set Authorization: pass one of them";
const AMBIGUOUS_BEARER: &str =
"a bearer token and an authorization header both set Authorization: pass one of them";
const BASIC_AND_BEARER: &str =
"basic-auth credentials and a bearer token both set Authorization: pass one of them";
const HOST_COMES_FROM_THE_URL: &str = "the host header is set from the url the request is sent to";
const CONNECTION_HEADERS: [&str; 9] = [
"connection",
"content-length",
"expect",
"keep-alive",
"proxy-connection",
"te",
"trailer",
"transfer-encoding",
"upgrade",
];
const UPLOAD_FRAME: usize = 64 * 1024;
const SMALL_FRAME: usize = 4 * 1024;
const UPLOAD_IDLE: Duration = Duration::from_secs(2);
const DRAIN_LIMIT: u64 = 64 * 1024;
const H2_STREAM_WINDOW: u32 = 2 * 1024 * 1024;
const H2_MAX_WINDOW: u32 = i32::MAX as u32;
const H2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(15);
const H2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub enum Priority {
Low,
#[default]
Normal,
High,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Protocol {
Http11,
Http2,
}
#[derive(Clone, Eq, PartialEq)]
pub struct BasicAuth {
pub user: String,
pub password: String,
}
impl std::fmt::Debug for BasicAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BasicAuth")
.field("user", &self.user)
.field("password", &"<redacted>")
.finish()
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct BearerToken {
pub token: String,
}
impl std::fmt::Debug for BearerToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BearerToken")
.field("token", &"<redacted>")
.finish()
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Validators {
pub etag: Option<String>,
pub last_modified: Option<String>,
}
impl Validators {
pub fn is_empty(&self) -> bool {
self.etag.is_none() && self.last_modified.is_none()
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LowSpeed {
pub limit: u32,
pub time: Duration,
}
impl LowSpeed {
fn whole_seconds(&self) -> Duration {
let partial = u64::from(self.time.subsec_nanos() > 0);
Duration::from_secs(self.time.as_secs().saturating_add(partial))
}
}
const SAMPLE_PERIOD: Duration = Duration::from_secs(1);
const RATE_SPAN: usize = 5;
#[derive(Clone, Default)]
pub enum Proxy {
None,
#[default]
Environment,
Variables(Vec<(String, String)>),
Url(String),
}
impl std::fmt::Debug for Proxy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Proxy::None => f.write_str("None"),
Proxy::Environment => f.write_str("Environment"),
Proxy::Variables(variables) => f
.debug_tuple("Variables")
.field(&RedactedVariables { variables })
.finish(),
Proxy::Url(url) => f.debug_tuple("Url").field(&RedactedUrl::url(url)).finish(),
}
}
}
struct RedactedVariables<'a> {
variables: &'a [(String, String)],
}
impl std::fmt::Debug for RedactedVariables<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let RedactedVariables { variables } = self;
f.debug_list()
.entries(
variables
.iter()
.map(|(name, value)| (name, RedactedUrl::url(value))),
)
.finish()
}
}
struct RedactedHeaders<F> {
names: F,
}
impl<'a, F, I> std::fmt::Debug for RedactedHeaders<F>
where
F: Fn() -> I,
I: Iterator<Item = &'a str>,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list()
.entries((self.names)().map(|name| (name, "<redacted>")))
.finish()
}
}
struct RedactedUrl<'a> {
text: &'a str,
absolute: bool,
}
impl<'a> RedactedUrl<'a> {
fn url(text: &'a str) -> RedactedUrl<'a> {
RedactedUrl {
text,
absolute: true,
}
}
fn path(text: &'a str) -> RedactedUrl<'a> {
RedactedUrl {
text,
absolute: false,
}
}
}
impl std::fmt::Debug for RedactedUrl<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use std::fmt::Write as _;
let RedactedUrl { text, absolute } = *self;
let (scheme, rest) = if absolute {
let end = scheme_len(text);
let rest = &text[end..];
let rest = rest.rfind('@').map_or(rest, |at| &rest[at + 1..]);
(&text[..end], rest)
} else {
("", text)
};
let (shown, query, fragment) = match rest.find(['?', '#']) {
None => (rest, false, false),
Some(at) if rest[at..].starts_with('#') => (&rest[..at], false, true),
Some(at) => (&rest[..at], true, rest[at..].contains('#')),
};
f.write_char('"')?;
for c in scheme.chars().chain(shown.chars()) {
if c == '\'' {
f.write_char(c)?;
} else {
for escaped in c.escape_debug() {
f.write_char(escaped)?;
}
}
}
if query {
f.write_str("?<redacted>")?;
}
if fragment {
f.write_str("#<redacted>")?;
}
f.write_char('"')
}
}
struct RedactedUrls<'a> {
urls: &'a [String],
}
impl std::fmt::Debug for RedactedUrls<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let RedactedUrls { urls } = self;
f.debug_list()
.entries(urls.iter().map(|url| RedactedUrl::url(url)))
.finish()
}
}
#[derive(Clone)]
pub struct FetcherOptions {
pub mirrors: Vec<String>,
pub headers: Vec<(String, String)>,
pub basic_auth: Option<BasicAuth>,
pub bearer_token: Option<BearerToken>,
pub allow_cleartext_credentials: bool,
pub tls: TlsOptions,
pub proxy: Proxy,
pub http2: bool,
pub max_retries: u32,
pub max_redirects: u32,
pub max_outstanding: usize,
pub connect_timeout: Duration,
pub progress_timeout: Duration,
pub low_speed: Option<LowSpeed>,
pub fetch_timeout: Option<Duration>,
}
impl Default for FetcherOptions {
fn default() -> Self {
FetcherOptions {
mirrors: Vec::new(),
headers: Vec::new(),
basic_auth: None,
bearer_token: None,
allow_cleartext_credentials: false,
tls: TlsOptions::default(),
proxy: Proxy::default(),
http2: true,
max_retries: 5,
max_redirects: 10,
max_outstanding: 8,
connect_timeout: Duration::from_secs(30),
progress_timeout: Duration::from_secs(60),
low_speed: None,
fetch_timeout: Some(Duration::from_secs(300)),
}
}
}
impl std::fmt::Debug for FetcherOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let FetcherOptions {
mirrors,
headers,
basic_auth,
bearer_token,
allow_cleartext_credentials,
tls,
proxy,
http2,
max_retries,
max_redirects,
max_outstanding,
connect_timeout,
progress_timeout,
low_speed,
fetch_timeout,
} = self;
let headers = RedactedHeaders {
names: || headers.iter().map(|(name, _)| name.as_str()),
};
f.debug_struct("FetcherOptions")
.field("mirrors", &RedactedUrls { urls: mirrors })
.field("headers", &headers)
.field("basic_auth", basic_auth)
.field("bearer_token", bearer_token)
.field("allow_cleartext_credentials", allow_cleartext_credentials)
.field("tls", tls)
.field("proxy", proxy)
.field("http2", http2)
.field("max_retries", max_retries)
.field("max_redirects", max_redirects)
.field("max_outstanding", max_outstanding)
.field("connect_timeout", connect_timeout)
.field("progress_timeout", progress_timeout)
.field("low_speed", low_speed)
.field("fetch_timeout", fetch_timeout)
.finish()
}
}
impl FetcherOptions {
pub fn new(url: impl Into<String>) -> FetcherOptions {
FetcherOptions {
mirrors: vec![url.into()],
..FetcherOptions::default()
}
}
}
#[derive(Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum Target<'a> {
Path(&'a str),
PathQuery {
path: &'a str,
query: &'a str,
},
Url(&'a str),
}
impl std::fmt::Debug for Target<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
Target::Path(path) => f
.debug_tuple("Path")
.field(&RedactedUrl::path(path))
.finish(),
Target::PathQuery { path, query: _ } => f
.debug_struct("PathQuery")
.field("path", &RedactedUrl::path(path))
.field("query", &"<redacted>")
.finish(),
Target::Url(url) => f.debug_tuple("Url").field(&RedactedUrl::url(url)).finish(),
}
}
}
impl<'a> Target<'a> {
fn describe(&self) -> Cow<'a, str> {
match *self {
Target::Path(path) => Cow::Borrowed(path),
Target::PathQuery { path, query } => Cow::Owned(format!("{path}?{query}")),
Target::Url(url) => Cow::Borrowed(url),
}
}
}
#[derive(Clone)]
pub struct FetchRequest<'a> {
pub target: Target<'a>,
pub priority: Priority,
pub validators: Option<&'a Validators>,
pub max_size: Option<u64>,
pub headers: &'a [(String, String)],
pub basic_auth: Option<&'a BasicAuth>,
pub allow_cleartext_credentials: bool,
}
impl std::fmt::Debug for FetchRequest<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let FetchRequest {
target,
priority,
validators,
max_size,
headers,
basic_auth,
allow_cleartext_credentials,
} = self;
let headers = RedactedHeaders {
names: || headers.iter().map(|(name, _)| name.as_str()),
};
f.debug_struct("FetchRequest")
.field("target", target)
.field("priority", priority)
.field("validators", validators)
.field("max_size", max_size)
.field("headers", &headers)
.field("basic_auth", basic_auth)
.field("allow_cleartext_credentials", allow_cleartext_credentials)
.finish()
}
}
impl<'a> FetchRequest<'a> {
pub fn path(path: &'a str) -> FetchRequest<'a> {
FetchRequest::for_target(Target::Path(path))
}
pub fn path_query(path: &'a str, query: &'a str) -> FetchRequest<'a> {
FetchRequest::for_target(Target::PathQuery { path, query })
}
pub fn url(url: &'a str) -> FetchRequest<'a> {
FetchRequest::for_target(Target::Url(url))
}
fn for_target(target: Target<'a>) -> FetchRequest<'a> {
FetchRequest {
target,
priority: Priority::default(),
validators: None,
max_size: None,
headers: &[],
basic_auth: None,
allow_cleartext_credentials: false,
}
}
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum Fetched {
Body(Body),
NotModified,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum UploadMethod {
#[default]
Post,
Delete,
}
pub struct UploadBody {
form: UploadForm,
}
enum UploadForm {
Bytes(Bytes),
Channel(BodyEnd),
}
impl UploadBody {
pub fn bytes(bytes: Vec<u8>) -> UploadBody {
UploadBody {
form: UploadForm::Bytes(Bytes::from(bytes)),
}
}
pub fn channel() -> (UploadBody, UploadWriter) {
let exchange = Arc::new(Exchange::default());
let body = UploadBody {
form: UploadForm::Channel(BodyEnd {
exchange: exchange.clone(),
}),
};
let writer = UploadWriter {
exchange,
buffer: Vec::new(),
stall: None,
failed: None,
};
(body, writer)
}
}
impl From<Vec<u8>> for UploadBody {
fn from(bytes: Vec<u8>) -> UploadBody {
UploadBody::bytes(bytes)
}
}
impl std::fmt::Debug for UploadBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.form {
UploadForm::Bytes(bytes) => f.debug_tuple("Bytes").field(&bytes.len()).finish(),
UploadForm::Channel(_) => f.write_str("Channel"),
}
}
}
pub struct UploadRequest<'a> {
pub target: Target<'a>,
pub method: UploadMethod,
pub body: UploadBody,
pub priority: Priority,
pub max_response: u64,
pub headers: &'a [(String, String)],
pub basic_auth: Option<&'a BasicAuth>,
pub bearer_token: Option<&'a BearerToken>,
pub allow_cleartext_credentials: bool,
pub response_timeout: Option<Duration>,
}
impl std::fmt::Debug for UploadRequest<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let UploadRequest {
target,
method,
body,
priority,
max_response,
headers,
basic_auth,
bearer_token,
allow_cleartext_credentials,
response_timeout,
} = self;
let headers = RedactedHeaders {
names: || headers.iter().map(|(name, _)| name.as_str()),
};
f.debug_struct("UploadRequest")
.field("target", target)
.field("method", method)
.field("body", body)
.field("priority", priority)
.field("max_response", max_response)
.field("headers", &headers)
.field("basic_auth", basic_auth)
.field("bearer_token", bearer_token)
.field("allow_cleartext_credentials", allow_cleartext_credentials)
.field("response_timeout", response_timeout)
.finish()
}
}
impl<'a> UploadRequest<'a> {
pub const DEFAULT_MAX_RESPONSE: u64 = 2 * 1024 * 1024;
pub fn path(path: &'a str, body: UploadBody) -> UploadRequest<'a> {
UploadRequest::for_target(Target::Path(path), body)
}
pub fn url(url: &'a str, body: UploadBody) -> UploadRequest<'a> {
UploadRequest::for_target(Target::Url(url), body)
}
fn for_target(target: Target<'a>, body: UploadBody) -> UploadRequest<'a> {
UploadRequest {
target,
method: UploadMethod::default(),
body,
priority: Priority::default(),
max_response: UploadRequest::DEFAULT_MAX_RESPONSE,
headers: &[],
basic_auth: None,
bearer_token: None,
allow_cleartext_credentials: false,
response_timeout: None,
}
}
}
pub struct Uploaded {
status: StatusCode,
headers: hyper::HeaderMap,
url: String,
body: Body,
}
impl std::fmt::Debug for Uploaded {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Uploaded {
status,
headers,
url,
body,
} = self;
let headers = RedactedHeaders {
names: || headers.iter().map(|(name, _)| name.as_str()),
};
f.debug_struct("Uploaded")
.field("status", status)
.field("headers", &headers)
.field("url", &RedactedUrl::url(url))
.field("body", body)
.finish()
}
}
impl Uploaded {
pub fn status(&self) -> u16 {
self.status.as_u16()
}
pub fn headers(&self) -> &hyper::HeaderMap {
&self.headers
}
pub fn url(&self) -> &str {
&self.url
}
pub fn protocol(&self) -> Protocol {
self.body.protocol()
}
pub fn into_body(self) -> Body {
self.body
}
}
#[derive(Clone, Debug)]
struct Mirror {
origin: Origin,
authority: HeaderValue,
prefix: String,
base: String,
}
impl Mirror {
fn destination(&self, path: &str, query: Option<&str>) -> Destination {
let path = path.trim_start_matches('/');
let url = match query {
None => format!("{}{}/{path}", self.prefix, self.base),
Some(query) => format!("{}{}/{path}?{query}", self.prefix, self.base),
};
Destination {
origin: self.origin.clone(),
authority: self.authority.clone(),
url,
path_at: self.prefix.len(),
}
}
}
#[derive(Clone, Debug)]
struct Destination {
origin: Origin,
authority: HeaderValue,
url: String,
path_at: usize,
}
impl Destination {
fn url(&self) -> &str {
&self.url
}
fn target(&self) -> &str {
&self.url[self.path_at..]
}
fn origin_url(&self) -> &str {
&self.url[..self.path_at]
}
}
#[derive(Debug)]
enum Route<'a> {
Mirrors {
path: &'a str,
query: Option<&'a str>,
},
One(Destination),
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct Origin {
tls: bool,
host: String,
port: u16,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct PoolKey {
origin: Origin,
identity: bool,
proxied: bool,
}
#[derive(Debug)]
struct ProxyEndpoint {
endpoint: Origin,
credential: Option<HeaderValue>,
named: String,
}
#[derive(Debug)]
struct Exemption {
host: String,
port: Option<u16>,
}
impl Exemption {
fn matches(&self, origin: &Origin) -> bool {
if self.port.is_some_and(|port| port != origin.port) {
return false;
}
let host = origin.host.as_bytes();
let entry = self.host.as_bytes();
if host.eq_ignore_ascii_case(entry) {
return true;
}
host.len() > entry.len()
&& host[host.len() - entry.len() - 1] == b'.'
&& host[host.len() - entry.len()..].eq_ignore_ascii_case(entry)
}
}
#[derive(Debug, Default)]
struct Proxies {
http: Option<Arc<ProxyEndpoint>>,
https: Option<Arc<ProxyEndpoint>>,
exempt_all: bool,
exempt: Vec<Exemption>,
}
impl Proxies {
fn via(&self, origin: &Origin) -> Via<'_> {
let proxy = if origin.tls { &self.https } else { &self.http };
let Some(proxy) = proxy.as_deref() else {
return Via::Direct;
};
if self.exempt_all || self.exempt.iter().any(|entry| entry.matches(origin)) {
return Via::Direct;
}
if origin.tls {
Via::Tunnel(proxy)
} else {
Via::Absolute(proxy)
}
}
}
#[derive(Clone, Copy, Debug)]
enum Via<'a> {
Direct,
Absolute(&'a ProxyEndpoint),
Tunnel(&'a ProxyEndpoint),
}
enum RequestBody {
Empty,
Upload(BodyEnd),
}
impl hyper::body::Body for RequestBody {
type Data = Bytes;
type Error = std::io::Error;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<std::result::Result<Frame<Bytes>, Self::Error>>> {
match self.get_mut() {
RequestBody::Empty => Poll::Ready(None),
RequestBody::Upload(end) => end.poll_frame(cx),
}
}
fn is_end_stream(&self) -> bool {
match self {
RequestBody::Empty => true,
RequestBody::Upload(end) => end.is_end_stream(),
}
}
fn size_hint(&self) -> SizeHint {
match self {
RequestBody::Empty => SizeHint::with_exact(0),
RequestBody::Upload(end) => match end.exchange.exact {
Some(length) => SizeHint::with_exact(length),
None => SizeHint::default(),
},
}
}
}
#[derive(Default)]
struct Exchange {
slot: Mutex<Slot>,
exact: Option<u64>,
}
#[derive(Default)]
struct Slot {
frame: Option<Bytes>,
closed: bool,
aborted: Option<String>,
gone: bool,
ended: bool,
polled: bool,
empty: bool,
stall: Option<Stall>,
writer: Option<Waker>,
reader: Option<Waker>,
upload: Option<Waker>,
}
#[derive(Clone, Copy)]
struct Stall {
window: Duration,
since: Instant,
}
impl Slot {
fn end(&mut self) -> [Option<Waker>; 2] {
self.ended = true;
[self.writer.take(), self.upload.take()]
}
fn abort(&mut self, reason: impl FnOnce() -> String) -> [Option<Waker>; 3] {
self.aborted.get_or_insert_with(reason);
[self.reader.take(), self.upload.take(), self.writer.take()]
}
fn at_end(&self) -> bool {
self.closed && self.frame.is_none() && self.aborted.is_none()
}
fn stall_end(&self) -> Option<Instant> {
let stall = self.stall?;
if self.frame.is_none() || self.aborted.is_some() {
return None;
}
stall.since.checked_add(stall.window)
}
fn restart_stall(&mut self) {
if let Some(stall) = &mut self.stall {
stall.since = Instant::now();
}
}
}
enum Watch {
Streaming(Option<Instant>),
Ended,
Aborted(String),
}
impl Exchange {
fn whole(bytes: &Bytes) -> Exchange {
Exchange {
slot: Mutex::new(Slot {
frame: (!bytes.is_empty()).then(|| bytes.clone()),
closed: true,
..Slot::default()
}),
exact: Some(bytes.len() as u64),
}
}
fn lock(&self) -> MutexGuard<'_, Slot> {
self.slot.lock().expect("upload body mutex")
}
fn aborted(&self) -> Option<String> {
self.lock().aborted.clone()
}
fn hand_over(&self, stall: Duration) -> std::result::Result<bool, String> {
let mut slot = self.lock();
if let Some(reason) = &slot.aborted {
return Err(reason.clone());
}
slot.stall = Some(Stall {
window: stall,
since: Instant::now(),
});
slot.empty = slot.at_end();
let empty = slot.empty;
let writer = slot.writer.take();
drop(slot);
wake(writer);
Ok(empty)
}
fn has_ended(&self) -> bool {
let slot = self.lock();
slot.ended && slot.aborted.is_none()
}
fn withdraw(&self) {
let mut slot = self.lock();
slot.stall = None;
slot.empty = false;
}
fn check_stall(&self) -> std::result::Result<String, Option<Instant>> {
let mut slot = self.lock();
let end = slot.stall_end();
let (Some(end), Some(stall)) = (end, slot.stall) else {
return Err(None);
};
if Instant::now() < end {
return Err(Some(end));
}
let message = format!("the upload body was not taken for {:?}", stall.window);
let wakers = slot.abort(|| message.clone());
drop(slot);
wakers.into_iter().for_each(wake);
Ok(message)
}
fn cut(&self) {
let mut slot = self.lock();
if slot.ended {
return;
}
let wakers = slot.abort(|| "the response to the upload ended before its body".into());
drop(slot);
wakers.into_iter().for_each(wake);
}
fn watch(&self, cx: &mut Context<'_>) -> Watch {
let mut slot = self.lock();
if let Some(reason) = &slot.aborted {
return Watch::Aborted(reason.clone());
}
if slot.ended {
return Watch::Ended;
}
park(&mut slot.upload, cx);
Watch::Streaming(self.exact.and(slot.stall_end()))
}
}
fn park(waker: &mut Option<Waker>, cx: &Context<'_>) {
if !waker
.as_ref()
.is_some_and(|held| held.will_wake(cx.waker()))
{
*waker = Some(cx.waker().clone());
}
}
fn wake(waker: Option<Waker>) {
if let Some(waker) = waker {
waker.wake();
}
}
fn poll_until(timer: &mut Option<rt::Deadline>, cx: &mut Context<'_>, end: Instant) -> Poll<()> {
loop {
let left = end.saturating_duration_since(Instant::now());
if left.is_zero() {
*timer = None;
return Poll::Ready(());
}
let deadline = timer.get_or_insert_with(|| rt::Deadline::new(left));
if deadline.poll_expired(cx).is_pending() {
return Poll::Pending;
}
*timer = None;
}
}
struct BodyEnd {
exchange: Arc<Exchange>,
}
impl BodyEnd {
fn whole(bytes: &Bytes) -> BodyEnd {
BodyEnd {
exchange: Arc::new(Exchange::whole(bytes)),
}
}
fn poll_frame(&mut self, cx: &mut Context<'_>) -> Poll<Option<std::io::Result<Frame<Bytes>>>> {
let mut slot = self.exchange.lock();
slot.polled = true;
if let Some(reason) = &slot.aborted {
return Poll::Ready(Some(Err(std::io::Error::other(reason.clone()))));
}
if let Some(held) = &mut slot.frame
&& held.len() > UPLOAD_FRAME
{
let frame = held.split_to(UPLOAD_FRAME);
slot.restart_stall();
return Poll::Ready(Some(Ok(Frame::data(frame))));
}
if let Some(frame) = slot.frame.take() {
let wakers = if slot.closed {
slot.end()
} else {
[slot.writer.take(), None]
};
drop(slot);
wakers.into_iter().for_each(wake);
return Poll::Ready(Some(Ok(Frame::data(frame))));
}
if slot.closed {
let wakers = slot.end();
drop(slot);
wakers.into_iter().for_each(wake);
return Poll::Ready(None);
}
park(&mut slot.reader, cx);
Poll::Pending
}
fn is_end_stream(&self) -> bool {
let mut slot = self.exchange.lock();
if slot.ended {
return true;
}
if !slot.at_end() || !(slot.polled || slot.empty) {
return false;
}
let wakers = slot.end();
drop(slot);
wakers.into_iter().for_each(wake);
true
}
}
impl Drop for BodyEnd {
fn drop(&mut self) {
let mut slot = self.exchange.lock();
slot.gone = true;
let writer = slot.writer.take();
drop(slot);
wake(writer);
}
}
struct RequestEnd {
exchange: Arc<Exchange>,
}
impl Drop for RequestEnd {
fn drop(&mut self) {
self.exchange.cut();
}
}
type H1Sender = hyper::client::conn::http1::SendRequest<RequestBody>;
type H2Sender = hyper::client::conn::http2::SendRequest<RequestBody>;
enum Sender {
H1(H1Sender),
H2(H2Sender),
}
#[derive(Default)]
struct PoolEntry {
h2: Option<H2Sender>,
h1: Vec<IdleH1>,
}
struct IdleH1 {
sender: H1Sender,
since: Instant,
}
struct Inner {
mirrors: Vec<Mirror>,
headers: Vec<(HeaderName, HeaderValue)>,
tls: ClientConfigs,
has_trust_anchors: bool,
client_identity: bool,
proxies: Proxies,
allow_cleartext_credentials: bool,
max_retries: u32,
max_redirects: u32,
connect_timeout: Duration,
progress_timeout: Duration,
low_speed: Option<LowSpeed>,
fetch_timeout: Option<Duration>,
max_outstanding: usize,
gate: Arc<Gate>,
h2_connection_window: u32,
pool: Mutex<HashMap<PoolKey, PoolEntry>>,
}
fn h2_connection_window(max_outstanding: usize) -> u32 {
u32::try_from(max_outstanding)
.unwrap_or(u32::MAX)
.saturating_mul(H2_STREAM_WINDOW)
.min(H2_MAX_WINDOW)
}
enum Failure {
Retry(Error),
Fatal(Error),
}
impl Failure {
fn into_error(self) -> Error {
match self {
Failure::Retry(e) | Failure::Fatal(e) => e,
}
}
}
enum UploadFailure {
Unsent(Failure),
Sent { url: String, message: String },
}
struct UploadPlan<'a> {
method: Method,
headers: &'a [(HeaderName, HeaderValue)],
bytes: Option<Bytes>,
max_response: u64,
response_timeout: Duration,
}
enum Answer<T> {
Sent(T),
Aborted(String),
Silent(Duration),
}
type UploadResponse = (Response<Incoming>, Protocol, RequestEnd, Option<H1Sender>);
#[derive(Clone)]
pub struct Fetcher {
inner: Arc<Inner>,
received: Arc<[Arc<AtomicU64>]>,
}
impl std::fmt::Debug for Fetcher {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Fetcher")
.field("mirrors", &self.inner.mirrors)
.finish_non_exhaustive()
}
}
impl Fetcher {
pub async fn new(options: FetcherOptions) -> Result<Fetcher> {
if let Some(low) = options.low_speed
&& (low.limit == 0 || low.time.is_zero())
{
return Err(Error::Fetch(format!(
"low-speed limit {} bytes per second over {:?}: neither may be zero",
low.limit, low.time
)));
}
let mirrors = options
.mirrors
.iter()
.map(|url| parse_mirror(url))
.collect::<Result<Vec<_>>>()?;
let cleartext = if options.allow_cleartext_credentials {
None
} else {
options
.mirrors
.iter()
.zip(&mirrors)
.find(|(_, mirror)| !mirror.origin.tls)
.map(|(url, _)| url.as_str())
};
let credential = match (&options.basic_auth, &options.bearer_token) {
(Some(_), Some(_)) => return Err(Error::Fetch(BASIC_AND_BEARER.into())),
(Some(_), None) => Some("basic-auth credentials"),
(None, Some(_)) => Some("the bearer token"),
(None, None) => None,
};
if let Some(credential) = credential
&& let Some(url) = cleartext
{
return Err(Error::Fetch(format!(
"{credential} would reach the http mirror {url} in the clear: \
use https mirrors, drop the credentials, or set \
FetcherOptions::allow_cleartext_credentials"
)));
}
let mut headers = vec![
(
hyper::header::USER_AGENT,
HeaderValue::from_static(USER_AGENT),
),
(
hyper::header::ACCEPT_ENCODING,
HeaderValue::from_static(IDENTITY),
),
];
let mut base = headers.len();
for (name, value) in &options.headers {
let name = HeaderName::try_from(name.as_str())
.map_err(|_| Error::Fetch(format!("invalid header name: {name}")))?;
if name == hyper::header::HOST {
return Err(Error::Fetch(HOST_COMES_FROM_THE_URL.into()));
}
if is_connection_header(&name) {
return Err(connection_header_refused(&name));
}
if name == hyper::header::AUTHORIZATION && options.basic_auth.is_some() {
return Err(Error::Fetch(AMBIGUOUS_AUTHORIZATION.into()));
}
if name == hyper::header::AUTHORIZATION && options.bearer_token.is_some() {
return Err(Error::Fetch(AMBIGUOUS_BEARER.into()));
}
if is_credential(&name)
&& let Some(url) = cleartext
{
return Err(Error::Fetch(format!(
"the {name} header carries credentials, which the http mirror {url} \
would receive in the clear: use https mirrors, drop the header, or set \
FetcherOptions::allow_cleartext_credentials"
)));
}
let mut value = HeaderValue::try_from(value.as_str())
.map_err(|_| Error::Fetch(format!("invalid value for header {name}")))?;
value.set_sensitive(is_credential(&name));
if let Some(at) = headers[..base].iter().position(|(held, _)| *held == name) {
headers.remove(at);
base -= 1;
}
headers.push((name, value));
}
if let Some(auth) = &options.basic_auth {
headers.push((hyper::header::AUTHORIZATION, basic_auth_value(auth)?));
}
if let Some(token) = &options.bearer_token {
headers.push((hyper::header::AUTHORIZATION, bearer_value(token)?));
}
let proxies = resolve_proxy(&options.proxy)?;
let max_outstanding = options.max_outstanding.max(1);
let https = mirrors.is_empty() || mirrors.iter().any(|mirror| mirror.origin.tls);
let reaches_tls = https || options.max_redirects > 0;
let tls = client_config(&options.tls, options.http2, https, reaches_tls).await?;
Ok(Fetcher {
inner: Arc::new(Inner {
mirrors,
headers,
has_trust_anchors: tls.has_trust_anchors,
client_identity: options.tls.client_identity.is_some(),
proxies,
tls,
allow_cleartext_credentials: options.allow_cleartext_credentials,
max_retries: options.max_retries,
max_redirects: options.max_redirects,
connect_timeout: options.connect_timeout,
progress_timeout: options.progress_timeout,
low_speed: options.low_speed,
fetch_timeout: options.fetch_timeout,
max_outstanding,
gate: Arc::new(Gate::new(max_outstanding)),
h2_connection_window: h2_connection_window(max_outstanding),
pool: Mutex::new(HashMap::new()),
}),
received: Arc::new([]),
})
}
pub fn counted(&self, received: Vec<Arc<AtomicU64>>) -> Fetcher {
Fetcher {
inner: Arc::clone(&self.inner),
received: self.received.iter().cloned().chain(received).collect(),
}
}
pub fn max_outstanding(&self) -> usize {
self.inner.max_outstanding
}
pub async fn fetch(&self, request: FetchRequest<'_>) -> Result<Fetched> {
let (fetched, _) = self
.fetch_budgeted(&request, self.inner.max_retries)
.await?;
Ok(fetched)
}
pub fn refetching<'r>(&self, request: FetchRequest<'r>) -> Refetch<'_, 'r> {
Refetch {
fetcher: self,
request,
left: self.inner.max_retries,
round: 0,
interrupted: Arc::new(AtomicBool::new(false)),
}
}
async fn fetch_budgeted(
&self,
request: &FetchRequest<'_>,
max_retries: u32,
) -> Result<(Fetched, u32)> {
let route = self.route(request.target)?;
let headers = merge_headers(
&self.inner.headers,
request.headers,
request.basic_auth,
None,
)?;
if !request.allow_cleartext_credentials && !self.inner.allow_cleartext_credentials {
self.check_cleartext(&route, &headers)?;
}
self.check_trust_anchors(&route)?;
let permit = self.inner.gate.acquire(request.priority).await;
let rounds = self.rounds(request, &route, &headers, permit, max_retries);
let Some(limit) = self.inner.fetch_timeout else {
return rounds.await;
};
match within(limit, rounds).await {
Some(result) => result,
None => Err(Error::Fetch(format!(
"fetch of {} timed out after {limit:?}",
request.target.describe()
))),
}
}
fn route<'a>(&self, target: Target<'a>) -> Result<Route<'a>> {
let (path, query) = match target {
Target::Url(url) => return Ok(Route::One(parse_url(url)?)),
Target::Path(path) => (path, None),
Target::PathQuery { path, query } => (path, Some(query)),
};
check_path(path)?;
if let Some(query) = query {
check_query(path, query)?;
}
if self.inner.mirrors.is_empty() {
return Err(Error::Fetch(format!(
"fetch of the path {} has nowhere to go: no mirror is configured",
target.describe()
)));
}
Ok(Route::Mirrors { path, query })
}
fn check_cleartext(
&self,
route: &Route<'_>,
headers: &[(HeaderName, HeaderValue)],
) -> Result<()> {
if !headers.iter().any(|(name, _)| is_credential(name)) {
return Ok(());
}
let Some(origin) = self.matching_origin(route, |origin| !origin.tls) else {
return Ok(());
};
Err(Error::Fetch(format!(
"the request carries credentials, which the cleartext origin {origin} would receive \
in the clear: fetch over https, drop the credentials, or set \
allow_cleartext_credentials on the request or on the fetcher"
)))
}
fn check_trust_anchors(&self, route: &Route<'_>) -> Result<()> {
if self.inner.has_trust_anchors {
return Ok(());
}
let Some(origin) = self.matching_origin(route, |origin| origin.tls) else {
return Ok(());
};
Err(no_trust_anchors(origin))
}
fn matching_origin<'a>(
&'a self,
route: &'a Route<'_>,
wanted: fn(&Origin) -> bool,
) -> Option<&'a str> {
match route {
Route::Mirrors { .. } => self
.inner
.mirrors
.iter()
.find(|mirror| wanted(&mirror.origin))
.map(|mirror| mirror.prefix.as_str()),
Route::One(destination) => {
wanted(&destination.origin).then(|| destination.origin_url())
}
}
}
async fn rounds(
&self,
request: &FetchRequest<'_>,
route: &Route<'_>,
headers: &[(HeaderName, HeaderValue)],
permit: Permit,
max_retries: u32,
) -> Result<(Fetched, u32)> {
let destination_count = match route {
Route::Mirrors { .. } => self.inner.mirrors.len(),
Route::One(_) => 1,
};
let mut settled = vec![false; destination_count];
let mut reported: Option<Error> = None;
let mut definitive = false;
let mut round = 0;
loop {
let mut retryable = false;
for (position, settled) in settled.iter_mut().enumerate() {
if *settled {
continue;
}
let destination = match route {
Route::Mirrors { path, query } => {
Cow::Owned(self.inner.mirrors[position].destination(path, *query))
}
Route::One(destination) => Cow::Borrowed(destination),
};
let failure = match self.attempt(&destination, request, headers).await {
Ok(Attempted::Body(mut body)) => {
body.permit = Some(permit);
return Ok((Fetched::Body(body), round));
}
Ok(Attempted::NotModified) => return Ok((Fetched::NotModified, round)),
Err(failure) => failure,
};
match failure {
Failure::Retry(e) => {
retryable = true;
if reported.is_none() {
reported = Some(e);
}
}
Failure::Fatal(e) => {
*settled = true;
if !definitive {
reported = Some(e);
definitive = true;
}
}
}
}
if !retryable || round >= max_retries {
return Err(reported.expect("a failed round holds a failure"));
}
round += 1;
rt::Timer::after(backoff(round)).await;
}
}
async fn attempt(
&self,
destination: &Destination,
request: &FetchRequest<'_>,
headers: &[(HeaderName, HeaderValue)],
) -> std::result::Result<Attempted, Failure> {
let named = &destination.origin;
let mut hop = Cow::Borrowed(destination);
let mut headers = Cow::Borrowed(headers);
let mut followed = 0u32;
let progress_timeout = self.inner.progress_timeout;
let drain_until = Instant::now() + progress_timeout;
let head_until = self
.inner
.low_speed
.and_then(|low| Some((Instant::now().checked_add(low.whole_seconds())?, low)));
loop {
let via = self.inner.proxies.via(&hop.origin);
let key = PoolKey {
origin: match via {
Via::Absolute(proxy) => proxy.endpoint.clone(),
Via::Direct | Via::Tunnel(_) => hop.origin.clone(),
},
identity: self.presents_identity(&hop.origin, named),
proxied: matches!(via, Via::Absolute(_)),
};
let url = hop.url();
let (response, protocol, reuse) = match head_until {
None => self.send(&hop, &key, via, request, &headers).await?,
Some((until, low)) => {
let sent = Box::pin(self.send(&hop, &key, via, request, &headers));
match within(until.saturating_duration_since(Instant::now()), sent).await {
Some(result) => result?,
None => return Err(Failure::Retry(too_slow(url, low))),
}
}
};
let status = response.status();
if status == StatusCode::NOT_MODIFIED {
if let Some(sender) = reuse {
self.inner.put_h1(&key, sender);
}
return Ok(Attempted::NotModified);
}
if is_redirect(status) && self.inner.max_redirects > 0 {
let location = response
.headers()
.get(hyper::header::LOCATION)
.and_then(|value| resolve_location(url, value));
let Some(location) = location else {
let failure = classify(status, url);
self.discard(&key, response, reuse, drain_until).await;
return Err(failure);
};
if followed >= self.inner.max_redirects {
self.discard(&key, response, reuse, drain_until).await;
return Err(Failure::Fatal(Error::RedirectLimit {
url: url.to_string(),
hops: followed,
}));
}
let next = redirect_destination(&hop, &location);
self.discard(&key, response, reuse, drain_until).await;
let next = next.map_err(Failure::Fatal)?;
if next.origin.tls && !self.inner.has_trust_anchors {
return Err(Failure::Fatal(no_trust_anchors(next.origin_url())));
}
if next.origin != *named && headers.iter().any(|(name, _)| is_credential(name)) {
let scoped = headers
.iter()
.filter(|(name, _)| !is_credential(name))
.cloned()
.collect::<Vec<_>>();
headers = Cow::Owned(scoped);
}
hop = Cow::Owned(next);
followed += 1;
continue;
}
if status != StatusCode::OK {
let failure = classify(status, url);
self.discard(&key, response, reuse, drain_until).await;
return Err(failure);
}
if let Some(encoding) = declared_coding(response.headers()) {
let url = url.to_string();
self.discard(&key, response, reuse, drain_until).await;
return Err(Failure::Fatal(Error::ContentEncoded { url, encoding }));
}
let validators = read_validators(response.headers());
let content_length = content_length(response.headers());
if let (Some(limit), Some(length)) = (request.max_size, content_length)
&& length > limit
{
self.discard(&key, response, reuse, drain_until).await;
return Err(Failure::Fatal(Error::FetchTooLarge { limit }));
}
let protocol = match response.version() {
Version::HTTP_2 => Protocol::Http2,
_ => protocol,
};
return Ok(Attempted::Body(Body {
incoming: response.into_body(),
chunk: Bytes::new(),
received: 0,
max_size: request.max_size,
validators,
content_length,
protocol,
inner: self.inner.clone(),
counters: self.received.clone(),
key,
reuse,
permit: None,
done: false,
failed: None,
deadline: rt::Deadline::new(progress_timeout),
waiting: false,
low_speed: self.inner.low_speed.map(Monitor::new),
interrupted: None,
request_body: None,
}));
}
}
async fn send(
&self,
hop: &Destination,
key: &PoolKey,
via: Via<'_>,
request: &FetchRequest<'_>,
headers: &[(HeaderName, HeaderValue)],
) -> std::result::Result<(Response<Incoming>, Protocol, Option<H1Sender>), Failure> {
let url = hop.url();
let origin = &key.origin;
let connect_timeout = self.inner.connect_timeout;
let progress_timeout = self.inner.progress_timeout;
let sender = match self.inner.take_conn(key) {
Some(sender) => sender,
None => {
let opened = within(connect_timeout, Box::pin(self.connect(key, via))).await;
match opened {
Some(result) => result?,
None => {
return Err(Failure::Retry(connect_timed_out(
origin,
via,
connect_timeout,
)));
}
}
}
};
match sender {
Sender::H1(mut sender) => {
let http_request = self
.build_request(hop, request, headers, Protocol::Http11, via)
.map_err(Failure::Fatal)?;
let sent = within(progress_timeout, async {
sender.ready().await?;
sender.send_request(http_request).await
})
.await;
let response = match sent {
Some(result) => result.map_err(|e| Failure::Retry(transport(url, e)))?,
None => return Err(Failure::Retry(stalled(url, progress_timeout))),
};
Ok((response, Protocol::Http11, Some(sender)))
}
Sender::H2(mut sender) => {
let http_request = self
.build_request(hop, request, headers, Protocol::Http2, via)
.map_err(Failure::Fatal)?;
let sent = within(progress_timeout, async {
sender.ready().await?;
sender.send_request(http_request).await
})
.await;
let response = match sent {
Some(result) => result.map_err(|e| Failure::Retry(transport(url, e)))?,
None => return Err(Failure::Retry(stalled(url, progress_timeout))),
};
Ok((response, Protocol::Http2, None))
}
}
}
fn presents_identity(&self, hop: &Origin, named: &Origin) -> bool {
self.inner.client_identity && hop.tls && hop == named
}
async fn discard(
&self,
key: &PoolKey,
response: Response<Incoming>,
reuse: Option<H1Sender>,
drain_until: Instant,
) {
let Some(sender) = reuse else { return };
if content_length(response.headers()).is_none_or(|length| length > DRAIN_LIMIT) {
return;
}
let budget = drain_until.saturating_duration_since(Instant::now());
if budget.is_zero() {
return;
}
let mut body = response.into_body();
let drained = within(budget, async {
loop {
let frame = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
match frame {
Some(Ok(_)) => continue,
Some(Err(_)) => return false,
None => return true,
}
}
})
.await;
if drained == Some(true) {
self.inner.put_h1(key, sender);
}
}
pub async fn upload(&self, request: UploadRequest<'_>) -> Result<Uploaded> {
let UploadRequest {
target,
method,
body,
priority,
max_response,
headers,
basic_auth,
bearer_token,
allow_cleartext_credentials,
response_timeout,
} = request;
let route = self.route(target)?;
let headers = merge_headers(&self.inner.headers, headers, basic_auth, bearer_token)?;
if !allow_cleartext_credentials && !self.inner.allow_cleartext_credentials {
self.check_cleartext(&route, &headers)?;
}
self.check_trust_anchors(&route)?;
let method = match method {
UploadMethod::Post => Method::POST,
UploadMethod::Delete => Method::DELETE,
};
let (end, bytes) = match body.form {
UploadForm::Bytes(bytes) => (BodyEnd::whole(&bytes), Some(bytes)),
UploadForm::Channel(end) => (end, None),
};
if method == Method::DELETE && !bytes.as_ref().is_some_and(Bytes::is_empty) {
return Err(Error::Fetch(format!(
"the delete of {} carries a body, which a delete does not send: pass an empty \
UploadBody::bytes",
target.describe()
)));
}
let plan = UploadPlan {
method,
headers: &headers,
bytes,
max_response,
response_timeout: response_timeout.unwrap_or(self.inner.progress_timeout),
};
let permit = self.inner.gate.acquire(priority).await;
let handed = AtomicBool::new(false);
let rounds = self.upload_rounds(&plan, &route, end, &handed);
let mut uploaded = match self.inner.fetch_timeout {
None => rounds.await?,
Some(limit) => match before_hand_over(limit, &handed, rounds).await {
Some(result) => result?,
None => {
return Err(Error::Fetch(format!(
"upload of {} was not sent within {limit:?}",
target.describe()
)));
}
},
};
uploaded.body.permit = Some(permit);
Ok(uploaded)
}
async fn upload_rounds(
&self,
plan: &UploadPlan<'_>,
route: &Route<'_>,
end: BodyEnd,
handed: &AtomicBool,
) -> Result<Uploaded> {
let destination_count = match route {
Route::Mirrors { .. } => self.inner.mirrors.len(),
Route::One(_) => 1,
};
let mut settled = vec![false; destination_count];
let mut reported: Option<Error> = None;
let mut definitive = false;
let mut round = 0;
let mut body = Some(end);
loop {
let mut retryable = false;
for (position, settled) in settled.iter_mut().enumerate() {
if *settled {
continue;
}
let destination = match route {
Route::Mirrors { path, query } => {
Cow::Owned(self.inner.mirrors[position].destination(path, *query))
}
Route::One(destination) => Cow::Borrowed(destination),
};
match self
.upload_attempt(&destination, plan, &mut body, handed)
.await
{
Ok(uploaded) => return Ok(uploaded),
Err(UploadFailure::Sent { url, message }) => {
return Err(Error::UploadInterrupted { url, message });
}
Err(UploadFailure::Unsent(Failure::Retry(e))) => {
retryable = true;
if reported.is_none() {
reported = Some(e);
}
}
Err(UploadFailure::Unsent(Failure::Fatal(e))) => {
*settled = true;
if !definitive {
reported = Some(e);
definitive = true;
}
}
}
}
if !retryable || round >= self.inner.max_retries {
return Err(reported.expect("a failed round holds a failure"));
}
round += 1;
rt::Timer::after(backoff(round)).await;
}
}
async fn upload_attempt(
&self,
destination: &Destination,
plan: &UploadPlan<'_>,
body: &mut Option<BodyEnd>,
handed: &AtomicBool,
) -> std::result::Result<Uploaded, UploadFailure> {
let named = &destination.origin;
let mut hop = Cow::Borrowed(destination);
let mut headers = Cow::Borrowed(plan.headers);
let mut followed = 0u32;
loop {
let via = self.inner.proxies.via(&hop.origin);
let key = PoolKey {
origin: match via {
Via::Absolute(proxy) => proxy.endpoint.clone(),
Via::Direct | Via::Tunnel(_) => hop.origin.clone(),
},
identity: self.presents_identity(&hop.origin, named),
proxied: matches!(via, Via::Absolute(_)),
};
let url = hop.url();
let sent = self
.upload_send(&hop, &key, via, plan, &headers, body, handed)
.await;
let (response, protocol, request_end, reuse) = match sent {
Ok(sent) => sent,
Err(UploadFailure::Unsent(failure)) if followed > 0 => {
return Err(interrupted(url, failure.into_error().to_string()));
}
Err(failure) => return Err(failure),
};
let status = response.status();
if let Some(bytes) = &plan.bytes
&& UPLOAD_REDIRECTS.contains(&status)
&& self.inner.max_redirects > 0
&& let Some(location) = response
.headers()
.get(hyper::header::LOCATION)
.and_then(|value| resolve_location(url, value))
{
if followed >= self.inner.max_redirects {
return Err(undelivered(
url,
Error::RedirectLimit {
url: url.to_string(),
hops: followed,
},
));
}
let next =
redirect_destination(&hop, &location).map_err(|e| undelivered(url, e))?;
if next.origin.tls && !self.inner.has_trust_anchors {
return Err(undelivered(url, no_trust_anchors(next.origin_url())));
}
if next.origin != *named && headers.iter().any(|(name, _)| is_credential(name)) {
let scoped = headers
.iter()
.filter(|(name, _)| !is_credential(name))
.cloned()
.collect::<Vec<_>>();
headers = Cow::Owned(scoped);
}
hop = Cow::Owned(next);
followed += 1;
*body = Some(BodyEnd::whole(bytes));
continue;
}
if let Some(encoding) = declared_coding(response.headers()) {
return Err(undelivered(
url,
Error::ContentEncoded {
url: url.to_string(),
encoding,
},
));
}
let content_length = content_length(response.headers());
if content_length.is_some_and(|length| length > plan.max_response) {
return Err(undelivered(
url,
Error::FetchTooLarge {
limit: plan.max_response,
},
));
}
let protocol = match response.version() {
Version::HTTP_2 => Protocol::Http2,
_ => protocol,
};
let (parts, incoming) = response.into_parts();
return Ok(Uploaded {
status: parts.status,
headers: parts.headers,
url: url.to_string(),
body: Body {
incoming,
chunk: Bytes::new(),
received: 0,
max_size: Some(plan.max_response),
validators: Validators::default(),
content_length,
protocol,
inner: self.inner.clone(),
counters: self.received.clone(),
key,
reuse,
permit: None,
done: false,
failed: None,
deadline: rt::Deadline::new(self.inner.progress_timeout),
waiting: false,
low_speed: None,
interrupted: None,
request_body: Some(request_end),
},
});
}
}
#[allow(clippy::too_many_arguments)]
async fn upload_send(
&self,
hop: &Destination,
key: &PoolKey,
via: Via<'_>,
plan: &UploadPlan<'_>,
headers: &[(HeaderName, HeaderValue)],
body: &mut Option<BodyEnd>,
handed: &AtomicBool,
) -> std::result::Result<UploadResponse, UploadFailure> {
let url = hop.url();
let unsent = |failure: Failure| -> std::result::Result<UploadResponse, UploadFailure> {
Err(UploadFailure::Unsent(failure))
};
let exchange = body
.as_ref()
.expect("an upload attempt holds its body until it sends it")
.exchange
.clone();
if let Some(reason) = exchange.aborted() {
return unsent(Failure::Fatal(not_sent(url, reason)));
}
let progress_timeout = self.inner.progress_timeout;
let mut pooled = self.inner.take_upload(key);
loop {
let stale_h1 = matches!(pooled, Some(Sender::H1(_)));
let mut sender = match pooled.take() {
Some(sender) => sender,
None => {
let connect_timeout = self.inner.connect_timeout;
match within(connect_timeout, Box::pin(self.connect(key, via))).await {
Some(Ok(sender)) => sender,
Some(Err(failure)) => return unsent(failure),
None => {
return unsent(Failure::Retry(connect_timed_out(
&key.origin,
via,
connect_timeout,
)));
}
}
}
};
let protocol = match sender {
Sender::H1(_) => Protocol::Http11,
Sender::H2(_) => Protocol::Http2,
};
let mut head = match self.upload_head(hop, plan, headers, protocol, via) {
Ok(head) => head,
Err(e) => return unsent(Failure::Fatal(e)),
};
let ready = match &mut sender {
Sender::H1(sender) => within(progress_timeout, sender.ready()).await,
Sender::H2(sender) => within(progress_timeout, sender.ready()).await,
};
match ready {
Some(Ok(())) => {}
Some(Err(_)) if stale_h1 => continue,
Some(Err(e)) => return unsent(Failure::Retry(transport(url, e))),
None => return unsent(Failure::Retry(stalled(url, progress_timeout))),
}
let empty = match exchange.hand_over(progress_timeout) {
Ok(empty) => empty,
Err(reason) => return unsent(Failure::Fatal(not_sent(url, reason))),
};
if empty && plan.method == Method::POST {
head.headers_mut()
.insert(hyper::header::CONTENT_LENGTH, HeaderValue::from_static("0"));
}
let end = body
.take()
.expect("an upload attempt holds its body until it sends it");
let request = head.map(|()| RequestBody::Upload(end));
handed.store(true, Ordering::Relaxed);
let window = plan.response_timeout;
let (answered, h1) = match sender {
Sender::H1(mut sender) => {
let answered =
answer(sender.try_send_request(request), &exchange, window).await;
(answered, Some(sender))
}
Sender::H2(mut sender) => {
let answered =
answer(sender.try_send_request(request), &exchange, window).await;
(answered, None)
}
};
let response = match answered {
Answer::Sent(Ok(response)) => response,
Answer::Sent(Err(mut e)) => {
let Some(request) = e.take_message() else {
exchange.cut();
return Err(interrupted(url, with_cause(&e.into_error())));
};
exchange.withdraw();
if let RequestBody::Upload(end) = request.into_body() {
*body = Some(end);
}
handed.store(false, Ordering::Relaxed);
if stale_h1 {
continue;
}
return unsent(Failure::Retry(transport(url, e.into_error())));
}
Answer::Aborted(reason) => return Err(interrupted(url, reason)),
Answer::Silent(window) => {
return Err(interrupted(
url,
format!("no response within {window:?} of the end of the request body"),
));
}
};
let reuse = h1.filter(|_| exchange.has_ended() && !closes(&response));
return Ok((response, protocol, RequestEnd { exchange }, reuse));
}
}
fn upload_head(
&self,
destination: &Destination,
plan: &UploadPlan<'_>,
headers: &[(HeaderName, HeaderValue)],
protocol: Protocol,
via: Via<'_>,
) -> Result<Request<()>> {
self.request_head(plan.method.clone(), destination, headers, protocol, via)?
.body(())
.map_err(|e| Error::Fetch(format!("invalid request for {}: {e}", destination.url())))
}
fn build_request(
&self,
destination: &Destination,
request: &FetchRequest<'_>,
headers: &[(HeaderName, HeaderValue)],
protocol: Protocol,
via: Via<'_>,
) -> Result<Request<RequestBody>> {
let mut builder = self.request_head(Method::GET, destination, headers, protocol, via)?;
if let Some(validators) = request.validators {
if let Some(etag) = &validators.etag {
builder = builder.header(hyper::header::IF_NONE_MATCH, etag);
}
if let Some(last_modified) = &validators.last_modified {
builder = builder.header(hyper::header::IF_MODIFIED_SINCE, last_modified);
}
}
builder
.body(RequestBody::Empty)
.map_err(|e| Error::Fetch(format!("invalid request for {}: {e}", destination.url())))
}
fn request_head(
&self,
method: Method,
destination: &Destination,
headers: &[(HeaderName, HeaderValue)],
protocol: Protocol,
via: Via<'_>,
) -> Result<hyper::http::request::Builder> {
let absolute = protocol == Protocol::Http2 || matches!(via, Via::Absolute(_));
let url = if absolute {
destination.url()
} else {
destination.target()
};
let uri =
Uri::try_from(url).map_err(|e| Error::Fetch(format!("invalid url {url}: {e}")))?;
let mut builder = Request::builder().method(method).uri(uri);
if protocol == Protocol::Http11 {
builder = builder.header(hyper::header::HOST, &destination.authority);
}
for (name, value) in headers {
builder = builder.header(name, value);
}
if let Via::Absolute(proxy) = via
&& let Some(credential) = &proxy.credential
&& !headers
.iter()
.any(|(name, _)| *name == hyper::header::PROXY_AUTHORIZATION)
{
builder = builder.header(hyper::header::PROXY_AUTHORIZATION, credential);
}
Ok(builder)
}
async fn connect(&self, key: &PoolKey, via: Via<'_>) -> std::result::Result<Sender, Failure> {
let origin = &key.origin;
let endpoint = match via {
Via::Tunnel(proxy) => &proxy.endpoint,
Via::Direct | Via::Absolute(_) => origin,
};
let tcp = rt::TcpStream::connect(&endpoint.host, endpoint.port)
.await
.map_err(|e| {
Failure::Retry(Error::Fetch(match via {
Via::Direct => {
format!("connect to {}:{} failed: {e}", endpoint.host, endpoint.port)
}
Via::Absolute(proxy) | Via::Tunnel(proxy) => {
format!("connect to the proxy {} failed: {e}", proxy.named)
}
}))
})?;
if !origin.tls {
return self
.handshake_h1(key, FuturesIo::new(tcp))
.await
.map_err(Failure::Retry);
}
let tcp = match via {
Via::Tunnel(proxy) => self.tunnel(proxy, origin, tcp).await?,
Via::Direct | Via::Absolute(_) => tcp,
};
let server_name =
rustls::pki_types::ServerName::try_from(origin.host.clone()).map_err(|e| {
Failure::Retry(Error::Fetch(format!(
"invalid server name {}: {e}",
origin.host
)))
})?;
let config = if key.identity {
&self.inner.tls.with_identity
} else {
&self.inner.tls.without_identity
};
let stream = futures_rustls::TlsConnector::from(config.clone())
.connect(server_name, tcp)
.await
.map_err(|e| {
Failure::Retry(Error::Fetch(format!(
"tls handshake with {} failed: {e}",
origin.host
)))
})?;
let h2 = stream.get_ref().1.alpn_protocol() == Some(b"h2");
let io = FuturesIo::new(stream);
if h2 {
self.handshake_h2(key, io).await.map_err(Failure::Retry)
} else {
self.handshake_h1(key, io).await.map_err(Failure::Retry)
}
}
async fn tunnel(
&self,
proxy: &ProxyEndpoint,
origin: &Origin,
tcp: rt::TcpStream,
) -> std::result::Result<rt::TcpStream, Failure> {
let refused = |what: String| Failure::Retry(Error::Fetch(what));
let authority = connect_authority(origin);
let host = HeaderValue::try_from(&authority).map_err(|_| {
Failure::Fatal(Error::Fetch(format!(
"the proxy {} cannot be asked to reach {authority}, which is not a usable host",
proxy.named
)))
})?;
let mut builder = Request::builder()
.method(Method::CONNECT)
.uri(&authority)
.header(hyper::header::HOST, host);
if let Some(credential) = &proxy.credential {
builder = builder.header(hyper::header::PROXY_AUTHORIZATION, credential);
}
let request = builder.body(RequestBody::Empty).map_err(|e| {
refused(format!(
"the connect request to the proxy {} for {authority} is invalid: {e}",
proxy.named
))
})?;
let (mut sender, connection) = hyper::client::conn::http1::handshake(FuturesIo::new(tcp))
.await
.map_err(|e| {
refused(format!(
"http/1.1 handshake with the proxy {} failed: {e}",
proxy.named
))
})?;
drop(rt::spawn(async move {
let _ = connection.with_upgrades().await;
}));
let response = async {
sender.ready().await?;
sender.send_request(request).await
}
.await
.map_err(|e| {
refused(format!(
"connect to {authority} through the proxy {} failed: {e}",
proxy.named
))
})?;
let status = response.status();
if !status.is_success() {
let message = format!(
"the proxy {} answered the connect to {authority} with {}",
proxy.named,
status.as_u16()
);
return Err(match status {
StatusCode::PROXY_AUTHENTICATION_REQUIRED => Failure::Fatal(Error::Fetch(message)),
_ => Failure::Retry(Error::Fetch(message)),
});
}
let upgraded = hyper::upgrade::on(response).await.map_err(|e| {
refused(format!(
"the proxy {} accepted the connect to {authority} without tunneling it: {e}",
proxy.named
))
})?;
let parts = upgraded
.downcast::<FuturesIo<rt::TcpStream>>()
.map_err(|_| {
refused(format!(
"the tunnel through the proxy {} to {authority} is not the socket it was \
opened over",
proxy.named
))
})?;
if !parts.read_buf.is_empty() {
return Err(refused(format!(
"the proxy {} sent {} bytes after the connect to {authority}, which nothing may \
follow",
proxy.named,
parts.read_buf.len()
)));
}
Ok(parts.io.into_inner())
}
async fn handshake_h1<S>(&self, key: &PoolKey, io: FuturesIo<S>) -> Result<Sender>
where
S: AsyncRead + AsyncWrite + WriteVectored + Send + Unpin + 'static,
{
let (sender, connection) =
hyper::client::conn::http1::handshake(io)
.await
.map_err(|e| {
Error::Fetch(format!(
"http/1.1 handshake with {} failed: {e}",
key.origin.host
))
})?;
drop(rt::spawn(async move {
let _ = connection.await;
}));
Ok(Sender::H1(sender))
}
async fn handshake_h2<S>(&self, key: &PoolKey, io: FuturesIo<S>) -> Result<Sender>
where
S: AsyncRead + AsyncWrite + WriteVectored + Send + Unpin + 'static,
{
let (sender, connection) = hyper::client::conn::http2::Builder::new(RtExecutor)
.timer(RtTimer)
.initial_stream_window_size(H2_STREAM_WINDOW)
.initial_connection_window_size(self.inner.h2_connection_window)
.keep_alive_interval(H2_KEEP_ALIVE_INTERVAL)
.keep_alive_timeout(H2_KEEP_ALIVE_TIMEOUT)
.handshake(io)
.await
.map_err(|e| {
Error::Fetch(format!(
"http/2 handshake with {} failed: {e}",
key.origin.host
))
})?;
drop(rt::spawn(async move {
let _ = connection.await;
}));
self.inner.put_h2(key, sender.clone());
Ok(Sender::H2(sender))
}
}
impl Inner {
fn take_conn(&self, key: &PoolKey) -> Option<Sender> {
let mut pool = self.pool.lock().expect("fetcher pool mutex");
let entry = pool.get_mut(key)?;
if let Some(h2) = &entry.h2 {
if h2.is_closed() {
entry.h2 = None;
} else {
return Some(Sender::H2(h2.clone()));
}
}
while let Some(h1) = entry.h1.pop() {
if !h1.sender.is_closed() {
return Some(Sender::H1(h1.sender));
}
}
None
}
fn take_upload(&self, key: &PoolKey) -> Option<Sender> {
let mut pool = self.pool.lock().expect("fetcher pool mutex");
let entry = pool.get_mut(key)?;
match &entry.h2 {
Some(h2) if h2.is_closed() => entry.h2 = None,
Some(h2) => return Some(Sender::H2(h2.clone())),
None => {}
}
while let Some(h1) = entry.h1.last() {
if h1.sender.is_closed() {
entry.h1.pop();
continue;
}
if h1.since.elapsed() >= UPLOAD_IDLE {
return None;
}
return entry.h1.pop().map(|h1| Sender::H1(h1.sender));
}
None
}
fn put_h1(&self, key: &PoolKey, sender: H1Sender) {
if sender.is_closed() {
return;
}
let idle = IdleH1 {
sender,
since: Instant::now(),
};
let mut pool = self.pool.lock().expect("fetcher pool mutex");
if let Some(entry) = pool.get_mut(key) {
entry.h1.push(idle);
return;
}
pool.entry(key.clone()).or_default().h1.push(idle);
}
fn put_h2(&self, key: &PoolKey, sender: H2Sender) {
let mut pool = self.pool.lock().expect("fetcher pool mutex");
if let Some(entry) = pool.get_mut(key) {
match &entry.h2 {
Some(pooled) if !pooled.is_closed() => {}
_ => entry.h2 = Some(sender),
}
return;
}
pool.entry(key.clone()).or_default().h2 = Some(sender);
}
}
pub struct Refetch<'f, 'r> {
fetcher: &'f Fetcher,
request: FetchRequest<'r>,
left: u32,
round: u32,
interrupted: Arc<AtomicBool>,
}
impl Refetch<'_, '_> {
pub async fn fetch(&mut self) -> Result<Fetched> {
self.interrupted.store(false, Ordering::Relaxed);
let (mut fetched, used) = self
.fetcher
.fetch_budgeted(&self.request, self.left)
.await?;
self.left -= used;
self.round += used;
if let Fetched::Body(body) = &mut fetched {
body.interrupted = Some(self.interrupted.clone());
}
Ok(fetched)
}
pub async fn retry<E>(&mut self, error: E) -> std::result::Result<(), E> {
if !self.interrupted.load(Ordering::Relaxed) || self.left == 0 {
return Err(error);
}
self.left -= 1;
self.round += 1;
rt::Timer::after(backoff(self.round)).await;
Ok(())
}
}
#[allow(clippy::large_enum_variant)]
enum Attempted {
Body(Body),
NotModified,
}
struct Failed {
kind: std::io::ErrorKind,
message: String,
}
impl Failed {
fn error(&self) -> std::io::Error {
std::io::Error::new(self.kind, self.message.clone())
}
}
pub struct Body {
incoming: Incoming,
chunk: Bytes,
received: u64,
max_size: Option<u64>,
validators: Validators,
content_length: Option<u64>,
protocol: Protocol,
inner: Arc<Inner>,
counters: Arc<[Arc<AtomicU64>]>,
key: PoolKey,
reuse: Option<H1Sender>,
permit: Option<Permit>,
done: bool,
failed: Option<Failed>,
deadline: rt::Deadline,
waiting: bool,
low_speed: Option<Monitor>,
interrupted: Option<Arc<AtomicBool>>,
request_body: Option<RequestEnd>,
}
struct Monitor {
rule: LowSpeed,
counted: u64,
samples: [u64; RATE_SPAN],
taken: u64,
below: Option<u64>,
deadline: rt::Deadline,
started: bool,
}
impl Monitor {
fn new(rule: LowSpeed) -> Monitor {
Monitor {
rule,
counted: 0,
samples: [0; RATE_SPAN],
taken: 0,
below: Some(0),
deadline: rt::Deadline::new(SAMPLE_PERIOD),
started: false,
}
}
fn below_rate(&mut self, cx: &mut Context<'_>) -> bool {
while self.deadline.poll_expired(cx).is_ready() {
if self.sample() {
return true;
}
self.deadline.restart();
}
false
}
fn sample(&mut self) -> bool {
self.taken += 1;
let slot = (self.taken % RATE_SPAN as u64) as usize;
let span = self.taken.min(RATE_SPAN as u64);
let carried = self.counted - self.samples[slot];
self.samples[slot] = self.counted;
if carried > u64::from(self.rule.limit) * span {
self.below = None;
return false;
}
let below = self.below.map_or(0, |seconds| seconds + 1);
self.below = Some(below);
Duration::from_secs(below) >= self.rule.time
}
}
impl std::fmt::Debug for Body {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Body")
.field("protocol", &self.protocol)
.field("content_length", &self.content_length)
.field("received", &self.received)
.finish_non_exhaustive()
}
}
impl Body {
pub fn validators(&self) -> &Validators {
&self.validators
}
pub fn content_length(&self) -> Option<u64> {
self.content_length
}
pub fn protocol(&self) -> Protocol {
self.protocol
}
pub fn received(&self) -> u64 {
self.received
}
fn fail(&mut self, kind: std::io::ErrorKind, message: String) -> std::io::Error {
let failed = Failed { kind, message };
let error = failed.error();
self.failed = Some(failed);
error
}
fn interrupt(&mut self, kind: std::io::ErrorKind, message: String) -> std::io::Error {
if let Some(interrupted) = &self.interrupted {
interrupted.store(true, Ordering::Relaxed);
}
self.fail(kind, message)
}
fn poll_low_speed(&mut self, cx: &mut Context<'_>) -> Option<std::io::Error> {
let monitor = self.low_speed.as_mut()?;
if !monitor.below_rate(cx) {
return None;
}
let LowSpeed { limit, time } = monitor.rule;
Some(self.interrupt(
std::io::ErrorKind::TimedOut,
format!("fetched body averaged below {limit} bytes per second for {time:?}"),
))
}
}
impl AsyncRead for Body {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
if buf.is_empty() {
return Poll::Ready(Ok(0));
}
let me = self.get_mut();
if let Some(failed) = &me.failed {
return Poll::Ready(Err(failed.error()));
}
if let Some(monitor) = &mut me.low_speed
&& !monitor.started
{
monitor.deadline.restart();
monitor.started = true;
}
loop {
if !me.chunk.is_empty() {
let n = me.chunk.len().min(buf.len());
buf[..n].copy_from_slice(&me.chunk[..n]);
me.chunk = me.chunk.slice(n..);
return Poll::Ready(Ok(n));
}
if me.done {
return Poll::Ready(Ok(0));
}
let frame = match Pin::new(&mut me.incoming).poll_frame(cx) {
Poll::Ready(frame) => frame,
Poll::Pending => {
if let Some(error) = me.poll_low_speed(cx) {
return Poll::Ready(Err(error));
}
if !me.waiting {
me.deadline.restart();
me.waiting = true;
}
return match me.deadline.poll_expired(cx) {
Poll::Ready(()) => {
let window = me.deadline.window();
Poll::Ready(Err(me.interrupt(
std::io::ErrorKind::TimedOut,
format!("fetched body delivered nothing for {window:?}"),
)))
}
Poll::Pending => Poll::Pending,
};
}
};
match frame {
Some(Ok(frame)) => {
me.waiting = false;
if let Ok(data) = frame.into_data() {
me.received += data.len() as u64;
for counter in me.counters.iter() {
counter.fetch_add(data.len() as u64, Ordering::Relaxed);
}
if let Some(limit) = me.max_size
&& me.received > limit
{
return Poll::Ready(Err(me.fail(
std::io::ErrorKind::FileTooLarge,
format!("fetched body exceeds the {limit}-byte cap"),
)));
}
if let Some(monitor) = &mut me.low_speed {
monitor.counted += data.len() as u64;
}
me.chunk = data;
if let Some(error) = me.poll_low_speed(cx) {
return Poll::Ready(Err(error));
}
}
}
Some(Err(e)) => {
let message = with_cause(&e);
return Poll::Ready(Err(me.interrupt(std::io::ErrorKind::Other, message)));
}
None => {
me.done = true;
if let Some(sender) = me.reuse.take() {
me.inner.put_h1(&me.key, sender);
}
me.request_body = None;
me.permit = None;
return Poll::Ready(Ok(0));
}
}
}
}
}
#[cfg(feature = "tokio")]
impl rt::tokio_io::AsyncRead for Body {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut rt::tokio_io::ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
let unfilled = buf.initialize_unfilled();
let n = ready!(AsyncRead::poll_read(self, cx, unfilled))?;
buf.advance(n);
Poll::Ready(Ok(()))
}
}
pub struct UploadWriter {
exchange: Arc<Exchange>,
buffer: Vec<u8>,
stall: Option<rt::Deadline>,
failed: Option<Failed>,
}
impl std::fmt::Debug for UploadWriter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UploadWriter")
.field("buffered", &self.buffer.len())
.finish_non_exhaustive()
}
}
const UPLOAD_ENDED: &str = "the upload of this body has ended";
impl UploadWriter {
pub fn is_handed_over(&self) -> bool {
self.exchange.lock().stall.is_some()
}
fn fail(&mut self, kind: std::io::ErrorKind, message: String) -> std::io::Error {
let failed = Failed { kind, message };
let error = failed.error();
self.failed = Some(failed);
error
}
fn poll_hand_over(&mut self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let mut slot = self.exchange.lock();
if slot.gone || slot.aborted.is_some() {
drop(slot);
return Poll::Ready(Err(
self.fail(std::io::ErrorKind::BrokenPipe, UPLOAD_ENDED.into())
));
}
if slot.frame.is_some() {
park(&mut slot.writer, cx);
let end = slot.stall_end();
drop(slot);
return self.poll_stall(cx, end);
}
let frame = if self.buffer.len() < SMALL_FRAME {
let frame = Bytes::copy_from_slice(&self.buffer);
self.buffer.clear();
frame
} else {
Bytes::from(std::mem::take(&mut self.buffer))
};
slot.frame = Some(frame);
slot.restart_stall();
let reader = slot.reader.take();
drop(slot);
wake(reader);
Poll::Ready(Ok(()))
}
fn poll_taken(&mut self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let mut slot = self.exchange.lock();
if slot.gone || slot.aborted.is_some() {
drop(slot);
return Poll::Ready(Err(
self.fail(std::io::ErrorKind::BrokenPipe, UPLOAD_ENDED.into())
));
}
if slot.frame.is_none() {
return Poll::Ready(Ok(()));
}
park(&mut slot.writer, cx);
let end = slot.stall_end();
drop(slot);
self.poll_stall(cx, end)
}
fn poll_stall(
&mut self,
cx: &mut Context<'_>,
mut end: Option<Instant>,
) -> Poll<std::io::Result<()>> {
while let Some(at) = end {
ready!(poll_until(&mut self.stall, cx, at));
match self.exchange.check_stall() {
Ok(message) => {
return Poll::Ready(Err(self.fail(std::io::ErrorKind::TimedOut, message)));
}
Err(later) => end = later,
}
}
Poll::Pending
}
}
impl AsyncWrite for UploadWriter {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
let me = self.get_mut();
if let Some(failed) = &me.failed {
return Poll::Ready(Err(failed.error()));
}
let slot = me.exchange.lock();
let refused = if slot.gone || slot.aborted.is_some() {
Some(UPLOAD_ENDED)
} else if slot.closed {
Some("the upload body is closed")
} else {
None
};
drop(slot);
if let Some(message) = refused {
return Poll::Ready(Err(me.fail(std::io::ErrorKind::BrokenPipe, message.into())));
}
if buf.is_empty() {
return Poll::Ready(Ok(0));
}
if me.buffer.len() == UPLOAD_FRAME {
ready!(me.poll_hand_over(cx))?;
}
if me.buffer.capacity() == 0 {
me.buffer.reserve_exact(UPLOAD_FRAME);
}
let n = (UPLOAD_FRAME - me.buffer.len()).min(buf.len());
me.buffer.extend_from_slice(&buf[..n]);
Poll::Ready(Ok(n))
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let me = self.get_mut();
if let Some(failed) = &me.failed {
return Poll::Ready(Err(failed.error()));
}
if !me.buffer.is_empty() {
ready!(me.poll_hand_over(cx))?;
}
me.poll_taken(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let me = self.get_mut();
if let Some(failed) = &me.failed {
return Poll::Ready(Err(failed.error()));
}
if !me.buffer.is_empty() {
ready!(me.poll_hand_over(cx))?;
}
let mut slot = me.exchange.lock();
let reader = if slot.closed {
None
} else {
slot.closed = true;
slot.reader.take()
};
if slot.ended {
drop(slot);
wake(reader);
return Poll::Ready(Ok(()));
}
if slot.gone || slot.aborted.is_some() {
drop(slot);
return Poll::Ready(Err(
me.fail(std::io::ErrorKind::BrokenPipe, UPLOAD_ENDED.into())
));
}
park(&mut slot.writer, cx);
let end = slot.stall_end();
drop(slot);
wake(reader);
me.poll_stall(cx, end)
}
}
#[cfg(feature = "tokio")]
impl rt::tokio_io::AsyncWrite for UploadWriter {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
AsyncWrite::poll_write(self, cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
AsyncWrite::poll_flush(self, cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
AsyncWrite::poll_close(self, cx)
}
}
impl Drop for UploadWriter {
fn drop(&mut self) {
let mut slot = self.exchange.lock();
if slot.closed {
return;
}
let wakers =
slot.abort(|| "the upload writer was dropped before it closed the body".into());
drop(slot);
wakers.into_iter().for_each(wake);
}
}
fn is_credential(name: &HeaderName) -> bool {
*name == hyper::header::AUTHORIZATION
|| *name == hyper::header::PROXY_AUTHORIZATION
|| *name == hyper::header::COOKIE
}
fn is_connection_header(name: &HeaderName) -> bool {
CONNECTION_HEADERS.contains(&name.as_str())
}
fn connection_header_refused(name: &HeaderName) -> Error {
Error::Fetch(format!(
"the {name} header is set by the connection layer, which frames the request and \
holds its connection: drop the header"
))
}
fn check_path(path: &str) -> Result<()> {
if let Some(at) = path.find(['?', '#']) {
let found = &path[at..=at];
return Err(Error::Fetch(format!(
"fetch path {path} carries {found}: a path holds no query and no fragment"
)));
}
Ok(())
}
fn check_query(path: &str, query: &str) -> Result<()> {
if query.contains('#') {
return Err(Error::Fetch(format!(
"fetch query of {path}?{query} carries #: a query holds no fragment"
)));
}
Ok(())
}
fn merge_headers<'a>(
fetcher: &'a [(HeaderName, HeaderValue)],
extra: &[(String, String)],
basic_auth: Option<&BasicAuth>,
bearer_token: Option<&BearerToken>,
) -> Result<Cow<'a, [(HeaderName, HeaderValue)]>> {
if extra.is_empty() && basic_auth.is_none() && bearer_token.is_none() {
return Ok(Cow::Borrowed(fetcher));
}
if basic_auth.is_some() && bearer_token.is_some() {
return Err(Error::Fetch(BASIC_AND_BEARER.into()));
}
let credential = usize::from(basic_auth.is_some() || bearer_token.is_some());
let mut added = Vec::with_capacity(extra.len() + credential);
for (name, value) in extra {
let name = HeaderName::try_from(name.as_str())
.map_err(|_| Error::Fetch(format!("invalid header name: {name}")))?;
if name == hyper::header::HOST {
return Err(Error::Fetch(HOST_COMES_FROM_THE_URL.into()));
}
if is_connection_header(&name) {
return Err(connection_header_refused(&name));
}
if name == hyper::header::AUTHORIZATION && basic_auth.is_some() {
return Err(Error::Fetch(AMBIGUOUS_AUTHORIZATION.into()));
}
if name == hyper::header::AUTHORIZATION && bearer_token.is_some() {
return Err(Error::Fetch(AMBIGUOUS_BEARER.into()));
}
let mut value = HeaderValue::try_from(value.as_str())
.map_err(|_| Error::Fetch(format!("invalid value for header {name}")))?;
value.set_sensitive(is_credential(&name));
added.push((name, value));
}
if let Some(auth) = basic_auth {
added.push((hyper::header::AUTHORIZATION, basic_auth_value(auth)?));
}
if let Some(token) = bearer_token {
added.push((hyper::header::AUTHORIZATION, bearer_value(token)?));
}
let mut headers = Vec::with_capacity(fetcher.len() + added.len());
headers.extend(
fetcher
.iter()
.filter(|(name, _)| !added.iter().any(|(replaced, _)| replaced == name))
.cloned(),
);
headers.extend(added);
Ok(Cow::Owned(headers))
}
fn resolve_proxy(proxy: &Proxy) -> Result<Proxies> {
match proxy {
Proxy::None => Ok(Proxies::default()),
Proxy::Environment => resolve_variables(&environment()),
Proxy::Variables(variables) => resolve_variables(variables),
Proxy::Url(url) => {
let endpoint = Arc::new(parse_proxy(url)?);
Ok(Proxies {
http: Some(endpoint.clone()),
https: Some(endpoint),
exempt_all: false,
exempt: Vec::new(),
})
}
}
}
fn environment() -> Vec<(String, String)> {
PROXY_VARIABLES
.iter()
.filter_map(|name| {
let value = std::env::var(name).ok()?;
(!value.is_empty()).then(|| ((*name).to_owned(), value))
})
.collect()
}
fn resolve_variables(variables: &[(String, String)]) -> Result<Proxies> {
let all = variable(variables, "all_proxy", Some("ALL_PROXY"));
let http = variable(variables, "http_proxy", None);
let https = variable(variables, "https_proxy", Some("HTTPS_PROXY"));
let mut endpoints: Vec<(&str, Arc<ProxyEndpoint>)> = Vec::new();
for (name, url) in [all, http, https].into_iter().flatten() {
if url.trim() != url {
return Err(Error::Unsupported(format!(
"the proxy variable {name} has white space at the start or the end of \
its value"
)));
}
if !endpoints.iter().any(|(named, _)| *named == url) {
endpoints.push((url, Arc::new(parse_proxy(url)?)));
}
}
let parsed = |held: Option<(&str, &str)>| {
held.and_then(|(_, url)| endpoints.iter().find(|(named, _)| *named == url))
.map(|(_, endpoint)| endpoint.clone())
};
let (http, https) = (parsed(http.or(all)), parsed(https.or(all)));
let mut exempt_all = false;
let mut exempt = Vec::new();
for entry in variable(variables, "no_proxy", Some("NO_PROXY"))
.map(|(_, value)| value)
.unwrap_or_default()
.split(',')
.map(str::trim)
.filter(|entry| !entry.is_empty())
{
if entry == "*" {
exempt_all = true;
continue;
}
exempt.extend(parse_exemption(entry));
}
Ok(Proxies {
http,
https,
exempt_all,
exempt,
})
}
fn variable<'a>(
variables: &'a [(String, String)],
lower: &str,
upper: Option<&str>,
) -> Option<(&'a str, &'a str)> {
let held = |name: &str| {
variables
.iter()
.find(|(held, value)| held == name && !value.is_empty())
.map(|(held, value)| (held.as_str(), value.as_str()))
};
held(lower).or_else(|| upper.and_then(held))
}
fn parse_exemption(entry: &str) -> Option<Exemption> {
let (host, port) = match entry
.strip_prefix('[')
.and_then(|rest| rest.split_once(']'))
{
Some((inside, rest)) => (inside, rest.strip_prefix(':')),
None => match entry.split_once(':') {
Some((host, port)) if !port.contains(':') => (host, Some(port)),
_ => (entry, None),
},
};
let named = |host: &str| host.strip_prefix('.').unwrap_or(host).to_ascii_lowercase();
let (host, port) = match port.map(str::parse::<u16>) {
Some(Ok(port)) => (named(host), Some(port)),
Some(Err(_)) => (named(entry), None),
None => (named(host), None),
};
(!host.is_empty()).then_some(Exemption { host, port })
}
fn parse_proxy(url: &str) -> Result<ProxyEndpoint> {
let refused = |what: &str| {
Error::Unsupported(format!(
"proxy url {}: {what}",
without_userinfo(url.trim())
))
};
let url = url.trim();
if !url
.get(..PROXY_SCHEME.len())
.is_some_and(|scheme| scheme.eq_ignore_ascii_case(PROXY_SCHEME))
{
return Err(refused("a proxy is reached over http://host[:port] alone"));
}
if url.contains('#') {
return Err(refused("a proxy url carries no fragment"));
}
let uri = Uri::try_from(url).map_err(|e| refused(&format!("invalid url: {e}")))?;
if uri.query().is_some() {
return Err(refused("a proxy url carries no query string"));
}
if !matches!(uri.path(), "" | "/") {
return Err(refused("a proxy url carries no path"));
}
let literal = uri.host().ok_or_else(|| refused("the url has no host"))?;
let authority = uri
.authority()
.expect("a url holding a host holds an authority")
.as_str();
let credential = match authority.rsplit_once('@') {
Some((userinfo, _)) => Some(proxy_credential(userinfo).ok_or_else(|| {
refused(
"the userinfo is not a percent-encoded user name and password the proxy can be \
sent",
)
})?),
None => None,
};
let host = literal
.strip_prefix('[')
.and_then(|inner| inner.strip_suffix(']'))
.unwrap_or(literal)
.to_ascii_lowercase();
let port_text = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host)
.strip_prefix(literal)
.and_then(|rest| rest.strip_prefix(':'));
let port = match (uri.port_u16(), port_text) {
(Some(port), _) => port,
(None, None) => 80,
(None, Some(text)) => {
return Err(refused(&format!(
"the port {text:?} is not a number from 0 to 65535"
)));
}
};
let named = if port == 80 {
format!("{PROXY_SCHEME}{literal}")
} else {
format!("{PROXY_SCHEME}{literal}:{port}")
};
Ok(ProxyEndpoint {
endpoint: Origin {
tls: false,
host,
port,
},
credential,
named,
})
}
fn proxy_credential(userinfo: &str) -> Option<HeaderValue> {
let (user, password) = userinfo.split_once(':').unwrap_or((userinfo, ""));
let field = |text: &str| String::from_utf8(percent_decode(text)?).ok();
basic_auth_value(&BasicAuth {
user: field(user)?,
password: field(password)?,
})
.ok()
}
fn percent_decode(field: &str) -> Option<Vec<u8>> {
let bytes = field.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut at = 0;
while at < bytes.len() {
if bytes[at] != b'%' {
decoded.push(bytes[at]);
at += 1;
continue;
}
let escape = bytes.get(at + 1..at + 3)?;
if !escape.iter().all(u8::is_ascii_hexdigit) {
return None;
}
let text = std::str::from_utf8(escape).ok()?;
decoded.push(u8::from_str_radix(text, 16).ok()?);
at += 3;
}
Some(decoded)
}
fn connect_authority(origin: &Origin) -> String {
if origin.host.contains(':') {
format!("[{}]:{}", origin.host, origin.port)
} else {
format!("{}:{}", origin.host, origin.port)
}
}
fn basic_auth_value(auth: &BasicAuth) -> Result<HeaderValue> {
let encoded =
ostrya_core::base64::encode(format!("{}:{}", auth.user, auth.password).as_bytes());
let mut value = HeaderValue::try_from(format!("Basic {encoded}"))
.map_err(|_| Error::Fetch("invalid basic-auth credentials".into()))?;
value.set_sensitive(true);
Ok(value)
}
fn bearer_value(token: &BearerToken) -> Result<HeaderValue> {
let refused = || {
Error::Fetch(
"the bearer token is not token68: it holds letters, digits, -, ., _, ~, +, or /, \
then any number of ="
.into(),
)
};
if !is_token68(&token.token) {
return Err(refused());
}
let mut value =
HeaderValue::try_from(format!("Bearer {}", token.token)).map_err(|_| refused())?;
value.set_sensitive(true);
Ok(value)
}
fn is_token68(token: &str) -> bool {
let body = token.trim_end_matches('=');
!body.is_empty()
&& body
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"-._~+/".contains(&byte))
}
fn parse_authority(url: &str, credentials: &str) -> Result<(Uri, Origin, String)> {
let scheme = url
.split_once("://")
.map(|(scheme, _)| scheme)
.ok_or_else(|| {
Error::Fetch(format!(
"url {} is not an absolute http or https url",
without_userinfo(url)
))
})?;
let tls = match scheme {
_ if scheme.eq_ignore_ascii_case(Scheme::HTTPS.as_str()) => true,
_ if scheme.eq_ignore_ascii_case(Scheme::HTTP.as_str()) => false,
other => {
return Err(Error::Unsupported(format!(
"fetch url scheme {other}: only http and https are fetched"
)));
}
};
let scheme = if tls { "https" } else { "http" };
let uri = Uri::try_from(url)
.map_err(|e| Error::Fetch(format!("invalid url {}: {e}", without_userinfo(url))))?;
let literal = uri
.host()
.ok_or_else(|| Error::Fetch(format!("url {} has no host", without_userinfo(url))))?;
if uri
.authority()
.is_some_and(|authority| authority.as_str().contains('@'))
{
return Err(Error::Fetch(format!(
"the {scheme} url for {literal} carries userinfo, which the fetcher does not send: \
pass credentials as {credentials}"
)));
}
let host = literal
.strip_prefix('[')
.and_then(|inner| inner.strip_suffix(']'))
.unwrap_or(literal)
.to_ascii_lowercase();
let port_text = uri
.authority()
.and_then(|authority| authority.as_str().strip_prefix(literal))
.and_then(|rest| rest.strip_prefix(':'));
let default_port = if tls { 443 } else { 80 };
let digits = port_text.is_none_or(|text| text.bytes().all(|b| b.is_ascii_digit()));
let port = match (uri.port_u16().filter(|_| digits), port_text) {
(Some(port), _) => port,
(None, None) => default_port,
(None, Some(text)) => {
return Err(Error::Fetch(format!(
"url {} names the port {text:?}, which is not a number from 0 to 65535",
without_userinfo(url)
)));
}
};
let authority = if port == default_port {
literal.to_string()
} else {
format!("{literal}:{port}")
};
Ok((uri, Origin { tls, host, port }, authority))
}
fn without_userinfo(url: &str) -> Cow<'_, str> {
let start = scheme_len(url);
match url[start..].rfind('@') {
Some(at) => Cow::Owned(format!("{}{}", &url[..start], &url[start + at + 1..])),
None => Cow::Borrowed(url),
}
}
fn scheme_len(url: &str) -> usize {
let Some(end) = url.find("://") else {
return 0;
};
let mut chars = url[..end].chars();
let valid = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
if valid { end + 3 } else { 0 }
}
fn host_header(url: &str, authority: &str) -> Result<HeaderValue> {
HeaderValue::try_from(authority).map_err(|_| {
Error::Fetch(format!(
"url {} has an unusable host",
without_userinfo(url)
))
})
}
pub fn check_base_url(url: &str) -> Result<()> {
if url.contains('#') {
return Err(Error::Fetch(format!(
"url {} carries a fragment, which no request sends",
without_userinfo(url)
)));
}
if url.contains('@') {
return Err(Error::Fetch(format!(
"url {} holds an '@', which can mark userinfo: a base url carries no userinfo, so \
pass the credential in the options and not in the url",
without_userinfo(url)
)));
}
let mirror = parse_mirror(url)?;
if mirror.origin.host.is_empty() {
return Err(Error::Fetch(format!(
"url {} has no host",
without_userinfo(url)
)));
}
Ok(())
}
fn parse_mirror(url: &str) -> Result<Mirror> {
let (uri, origin, authority) = parse_authority(url, "FetcherOptions::basic_auth")?;
if uri.query().is_some() {
return Err(Error::Fetch(format!(
"mirror url {} carries a query string, which the fetcher does not send",
without_userinfo(url)
)));
}
let scheme = if origin.tls { "https" } else { "http" };
Ok(Mirror {
authority: host_header(url, &authority)?,
prefix: format!("{scheme}://{authority}"),
base: uri.path().trim_end_matches('/').to_string(),
origin,
})
}
fn parse_url(url: &str) -> Result<Destination> {
if url.contains('#') {
return Err(Error::Fetch(format!(
"fetch url {} carries a fragment, which no request sends",
without_userinfo(url)
)));
}
let (uri, origin, authority) = parse_authority(url, "FetchRequest::basic_auth")?;
let scheme = if origin.tls { "https" } else { "http" };
let path_and_query = uri.path_and_query().map_or("/", |pq| pq.as_str());
let mut text =
String::with_capacity(scheme.len() + 3 + authority.len() + 1 + path_and_query.len());
text.push_str(scheme);
text.push_str("://");
text.push_str(&authority);
let path_at = text.len();
if !path_and_query.starts_with('/') {
text.push('/');
}
text.push_str(path_and_query);
Ok(Destination {
authority: host_header(url, &authority)?,
url: text,
path_at,
origin,
})
}
fn closes(response: &Response<Incoming>) -> bool {
response.version() != Version::HTTP_11
|| response
.headers()
.get_all(hyper::header::CONNECTION)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(','))
.any(|token| token.trim().eq_ignore_ascii_case("close"))
}
fn content_length(headers: &hyper::HeaderMap) -> Option<u64> {
headers
.get(hyper::header::CONTENT_LENGTH)?
.to_str()
.ok()?
.parse()
.ok()
}
fn declared_coding(headers: &hyper::HeaderMap) -> Option<String> {
coding(headers, hyper::header::CONTENT_ENCODING, &[IDENTITY]).or_else(|| {
coding(
headers,
hyper::header::TRANSFER_ENCODING,
&[IDENTITY, CHUNKED],
)
})
}
fn coding(headers: &hyper::HeaderMap, name: HeaderName, undone: &[&str]) -> Option<String> {
let declared = || {
headers
.get_all(&name)
.iter()
.map(|value| String::from_utf8_lossy(value.as_bytes()))
.filter(|value| value.split(',').any(|token| !token.trim().is_empty()))
};
if !declared().any(|value| value.split(',').any(|token| names_a_coding(token, undone))) {
return None;
}
Some(declared().collect::<Vec<_>>().join(", "))
}
fn names_a_coding(token: &str, undone: &[&str]) -> bool {
let token = token.trim();
!token.is_empty() && !undone.iter().any(|name| token.eq_ignore_ascii_case(name))
}
fn read_validators(headers: &hyper::HeaderMap) -> Validators {
let text = |name: HeaderName| {
headers
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::to_string)
};
Validators {
etag: text(hyper::header::ETAG),
last_modified: text(hyper::header::LAST_MODIFIED),
}
}
fn is_redirect(status: StatusCode) -> bool {
REDIRECTS.contains(&status)
}
fn resolve_location(from: &str, location: &HeaderValue) -> Option<String> {
let location = location.to_str().ok()?;
if location.is_empty() {
return None;
}
let mut resolved = url::Url::parse(from).ok()?.join(location).ok()?;
resolved.set_fragment(None);
Some(resolved.into())
}
fn redirect_destination(from: &Destination, to: &str) -> Result<Destination> {
let refused = |what: &str| {
Error::Fetch(format!(
"{} redirects to {}, {what}",
from.url(),
without_userinfo(to)
))
};
let tls = match to.split_once("://").map(|(scheme, _)| scheme) {
Some(scheme) if scheme.eq_ignore_ascii_case(Scheme::HTTPS.as_str()) => true,
Some(scheme) if scheme.eq_ignore_ascii_case(Scheme::HTTP.as_str()) => false,
_ => return Err(refused("which is not an absolute http or https url")),
};
if from.origin.tls && !tls {
return Err(refused(
"which is cleartext: a request made over tls is not followed onto http",
));
}
parse_url(to)
}
fn no_trust_anchors(origin: &str) -> Error {
Error::Fetch(format!(
"the certificate of the tls origin {origin} has nothing to verify against: the \
fetcher holds no trust anchors, so set TlsOptions::roots"
))
}
fn classify(status: StatusCode, url: &str) -> Failure {
let error = Error::HttpStatus {
status: status.as_u16(),
url: url.to_string(),
};
if status.is_server_error()
|| status == StatusCode::REQUEST_TIMEOUT
|| status == StatusCode::TOO_MANY_REQUESTS
{
Failure::Retry(error)
} else {
Failure::Fatal(error)
}
}
fn transport(url: &str, error: hyper::Error) -> Error {
Error::Fetch(format!("{url}: {error}"))
}
fn stalled(url: &str, limit: Duration) -> Error {
Error::Fetch(format!("{url}: no response after {limit:?}"))
}
fn connect_timed_out(origin: &Origin, via: Via<'_>, limit: Duration) -> Error {
Error::Fetch(match via {
Via::Direct => format!(
"connect to {}:{} timed out after {limit:?}",
origin.host, origin.port
),
Via::Absolute(proxy) | Via::Tunnel(proxy) => format!(
"connect to the proxy {} timed out after {limit:?}",
proxy.named
),
})
}
fn not_sent(url: &str, reason: String) -> Error {
Error::Fetch(format!("upload to {url} not sent: {reason}"))
}
fn interrupted(url: &str, message: String) -> UploadFailure {
UploadFailure::Sent {
url: url.to_string(),
message,
}
}
fn undelivered(url: &str, cause: Error) -> UploadFailure {
interrupted(url, cause.to_string())
}
fn with_cause(error: &dyn std::error::Error) -> String {
match error.source() {
Some(cause) => format!("{error}: {cause}"),
None => error.to_string(),
}
}
fn too_slow(url: &str, rule: LowSpeed) -> Error {
let LowSpeed { limit, time } = rule;
Error::Fetch(format!(
"{url}: transfer below {limit} bytes per second for {time:?}"
))
}
async fn within<F: Future>(limit: Duration, future: F) -> Option<F::Output> {
let mut future = core::pin::pin!(future);
futures_lite::future::or(async { Some(future.as_mut().await) }, async {
rt::Timer::after(limit).await;
None
})
.await
}
async fn before_hand_over<F: Future>(
limit: Duration,
handed: &AtomicBool,
future: F,
) -> Option<F::Output> {
let mut future = core::pin::pin!(future);
let end = Instant::now().checked_add(limit);
let mut deadline: Option<rt::Deadline> = None;
std::future::poll_fn(|cx| {
if let Poll::Ready(output) = future.as_mut().poll(cx) {
return Poll::Ready(Some(output));
}
if handed.load(Ordering::Relaxed) {
deadline = None;
return Poll::Pending;
}
let deadline = deadline.get_or_insert_with(|| {
rt::Deadline::new(
end.map_or(limit, |end| end.saturating_duration_since(Instant::now())),
)
});
deadline.poll_expired(cx).map(|()| None)
})
.await
}
async fn answer<F: Future>(send: F, exchange: &Exchange, window: Duration) -> Answer<F::Output> {
let mut send = core::pin::pin!(send);
let mut head: Option<rt::Deadline> = None;
let mut stall: Option<rt::Deadline> = None;
std::future::poll_fn(|cx| {
if let Poll::Ready(output) = send.as_mut().poll(cx) {
return Poll::Ready(Answer::Sent(output));
}
while head.is_none() {
match exchange.watch(cx) {
Watch::Streaming(None) => return Poll::Pending,
Watch::Streaming(Some(end)) => {
if poll_until(&mut stall, cx, end).is_pending() {
return Poll::Pending;
}
if let Ok(reason) = exchange.check_stall() {
return Poll::Ready(Answer::Aborted(reason));
}
}
Watch::Aborted(reason) => return Poll::Ready(Answer::Aborted(reason)),
Watch::Ended => {
stall = None;
head = Some(rt::Deadline::new(window));
}
}
}
head.as_mut()
.expect("the head window runs once the body has ended")
.poll_expired(cx)
.map(|()| Answer::Silent(window))
})
.await
}
fn backoff(round: u32) -> Duration {
let ms = 250u64 << (round - 1).min(3);
Duration::from_millis(ms)
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Fetcher>();
assert_send_sync::<Body>();
assert_send_sync::<Fetched>();
assert_send_sync::<BearerToken>();
assert_send_sync::<UploadBody>();
assert_send_sync::<UploadWriter>();
assert_send_sync::<UploadRequest<'static>>();
assert_send_sync::<Uploaded>();
};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_connection_window_covers_every_admitted_stream() {
assert_eq!(h2_connection_window(1), H2_STREAM_WINDOW);
assert_eq!(h2_connection_window(8), 8 * H2_STREAM_WINDOW);
assert_eq!(h2_connection_window(usize::MAX), H2_MAX_WINDOW);
}
#[test]
fn mirror_urls_join_base_and_path() {
let mirror = parse_mirror("https://example.com/repo/").unwrap();
assert_eq!(
mirror.destination("objects/ab/cd.filez", None).url(),
"https://example.com/repo/objects/ab/cd.filez"
);
assert_eq!(mirror.origin.port, 443);
assert!(mirror.origin.tls);
let root = parse_mirror("http://example.com").unwrap();
assert_eq!(
root.destination("summary", None).url(),
"http://example.com/summary"
);
assert_eq!(root.origin.port, 80);
assert!(!root.origin.tls);
let ported = parse_mirror("http://127.0.0.1:8080/r").unwrap();
let config = ported.destination("/config", None);
assert_eq!(config.url(), "http://127.0.0.1:8080/r/config");
assert_eq!(config.target(), "/r/config");
assert_eq!(ported.authority, "127.0.0.1:8080");
assert_eq!(root.authority, "example.com");
}
#[test]
fn mirror_urls_join_base_path_and_query() {
let mirror = parse_mirror("http://127.0.0.1:8080/base/").unwrap();
let destination = mirror.destination("_ostrya/refs/v1", Some("pattern=a%2Fb&pattern=c"));
assert_eq!(
destination.url(),
"http://127.0.0.1:8080/base/_ostrya/refs/v1?pattern=a%2Fb&pattern=c"
);
assert_eq!(
destination.target(),
"/base/_ostrya/refs/v1?pattern=a%2Fb&pattern=c"
);
let root = parse_mirror("https://example.com").unwrap();
assert_eq!(
root.destination("/p", Some("")).url(),
"https://example.com/p?"
);
}
#[test]
fn an_ipv6_literal_keeps_its_brackets_only_in_the_authority() {
let ported = parse_mirror("http://[::1]:8080/r").unwrap();
assert_eq!(ported.origin.host, "::1");
assert_eq!(ported.origin.port, 8080);
assert_eq!(ported.authority, "[::1]:8080");
assert_eq!(
ported.destination("summary", None).url(),
"http://[::1]:8080/r/summary"
);
let tls = parse_mirror("https://[2001:db8::1]/repo").unwrap();
assert_eq!(tls.origin.host, "2001:db8::1");
assert_eq!(tls.origin.port, 443);
assert_eq!(tls.authority, "[2001:db8::1]");
assert_eq!(
tls.destination("summary", None).url(),
"https://[2001:db8::1]/repo/summary"
);
rustls::pki_types::ServerName::try_from(tls.origin.host.clone()).unwrap();
}
#[test]
fn mirror_urls_are_validated() {
let err = parse_mirror("file:///srv/repo").unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
let err = parse_mirror("/srv/repo").unwrap_err();
assert!(err.to_string().contains("not an absolute"), "{err}");
let err = parse_mirror("http://").unwrap_err();
assert!(err.to_string().contains("invalid url"), "{err}");
let err = parse_mirror("https://host/repo?X-Amz-Signature=deadbeef").unwrap_err();
assert!(err.to_string().contains("query string"), "{err}");
let err = parse_mirror("https://user:pass@host/repo").unwrap_err();
assert!(err.to_string().contains("userinfo"), "{err}");
let err = parse_mirror("http://user@host/repo").unwrap_err();
assert!(err.to_string().contains("userinfo"), "{err}");
}
#[test]
fn a_base_url_check_refuses_what_a_mirror_cannot_carry() {
for url in [
"http://host",
"https://host/repo/",
"http://127.0.0.1:8080/r",
"https://[::1]:8443/",
"HTTPS://host/repo",
] {
check_base_url(url).unwrap();
}
let refused = |url: &str, part: &str| {
let err = check_base_url(url).unwrap_err();
let text = err.to_string();
assert!(text.contains(part), "{url}: {text}");
assert!(!text.contains("secret"), "{url}: {text}");
};
refused("https://user:secret@host/repo", "userinfo");
refused("https://host/repo?q=1", "query string");
refused("https://host/repo#part", "fragment");
refused("https://u:secret@host/repo#part", "fragment");
refused("http://", "invalid url");
refused("http:///repo", "invalid url");
refused("http://:80/repo", "has no host");
refused("http://host:99999/repo", "not a number");
refused("http://host:x/repo", "not a number");
refused("ftp://host/repo", "scheme ftp");
refused("host/repo", "not an absolute");
refused("https://user:443/pw-secret@host/repo", "userinfo");
refused("https://user:1234?pw-secret@host/", "userinfo");
refused("https://host/repo@v1", "userinfo");
refused("http://h:+80/", "not a number");
refused("http://h:-80/", "not a number");
check_base_url("http://h:080/").unwrap();
assert_eq!(parse_mirror("http://h:080/r").unwrap().prefix, "http://h");
assert_eq!(
parse_mirror("http://h:0808/r").unwrap().prefix,
"http://h:808"
);
}
#[test]
fn a_mirror_refusal_names_no_userinfo() {
let err = parse_mirror("https://user:1234?pw-secret@host/").unwrap_err();
let text = err.to_string();
assert!(text.contains("query string"), "{text}");
assert!(!text.contains("secret"), "{text}");
let err = parse_mirror("http://h:+80/x").unwrap_err();
assert!(err.to_string().contains("not a number"), "{err}");
}
#[test]
fn options_are_validated_at_construction() {
rt::block_on(async {
let mut options = direct_options("http://example.com");
options.headers = vec![("not a header".into(), "v".into())];
let err = Fetcher::new(options).await.unwrap_err();
assert!(err.to_string().contains("invalid header name"), "{err}");
let mut options = direct_options("http://example.com");
options.headers = vec![("host".into(), "elsewhere".into())];
let err = Fetcher::new(options).await.unwrap_err();
assert!(err.to_string().contains("host header"), "{err}");
let mut options = tls_options("https://example.com");
options.headers = vec![("authorization".into(), "Basic aaa".into())];
options.basic_auth = Some(BasicAuth {
user: "u".into(),
password: "p".into(),
});
let err = Fetcher::new(options).await.unwrap_err();
assert!(err.to_string().contains("pass one of them"), "{err}");
for low_speed in [
LowSpeed {
limit: 0,
time: Duration::from_secs(30),
},
LowSpeed {
limit: 1000,
time: Duration::ZERO,
},
] {
let mut options = direct_options("http://example.com");
options.low_speed = Some(low_speed);
let err = Fetcher::new(options).await.unwrap_err();
assert!(err.to_string().contains("neither may be zero"), "{err}");
}
});
}
#[test]
fn a_low_speed_time_rounds_up_to_whole_seconds() {
let rule = |time| LowSpeed { limit: 1000, time };
let secs = Duration::from_secs;
assert_eq!(rule(secs(30)).whole_seconds(), secs(30));
assert_eq!(rule(Duration::from_millis(200)).whole_seconds(), secs(1));
assert_eq!(rule(Duration::from_millis(1500)).whole_seconds(), secs(2));
assert_eq!(rule(Duration::MAX).whole_seconds(), secs(u64::MAX));
}
fn low_speed_failure(time: u64, bursts: &[(u64, u64)], seconds: u64) -> Option<u64> {
let mut monitor = Monitor::new(LowSpeed {
limit: 1000,
time: Duration::from_secs(time),
});
(1..=seconds).find(|&second| {
let arrived: u64 = bursts
.iter()
.filter(|(at, _)| *at == second - 1)
.map(|(_, bytes)| bytes)
.sum();
monitor.counted += arrived;
monitor.sample()
})
}
#[test]
fn the_low_speed_rule_fails_where_the_tool_fails() {
rt::block_on(async {
assert_eq!(low_speed_failure(2, &[], 20), Some(2));
assert_eq!(low_speed_failure(3, &[], 20), Some(3));
assert_eq!(low_speed_failure(2, &[(0, 1_000)], 20), Some(2));
assert_eq!(low_speed_failure(2, &[(0, 3_000)], 20), Some(5));
assert_eq!(low_speed_failure(2, &[(0, 5_000)], 20), Some(7));
assert_eq!(low_speed_failure(2, &[(0, 20_000)], 20), Some(8));
assert_eq!(low_speed_failure(2, &[(0, 8_000)], 20), Some(8));
assert_eq!(low_speed_failure(2, &[(0, 3_500)], 20), Some(6));
let second = |at| [(0, 6_000), (at, 6_000)];
assert_eq!(low_speed_failure(2, &second(6), 7), None);
assert_eq!(low_speed_failure(2, &second(7), 8), None);
assert_eq!(low_speed_failure(2, &second(8), 9), Some(8));
let bursts: Vec<(u64, u64)> = (0..20).step_by(2).map(|at| (at, 2_100)).collect();
assert_eq!(low_speed_failure(1, &bursts, 20), None);
});
}
#[test]
fn a_path_target_needs_a_mirror() {
rt::block_on(async {
let fetcher = Fetcher::new(mirrorless_options()).await.unwrap();
let err = fetcher.route(Target::Path("summary")).unwrap_err();
assert!(err.to_string().contains("no mirror is configured"), "{err}");
let route = fetcher
.route(Target::Url("https://example.com/summary"))
.unwrap();
let Route::One(destination) = route else {
panic!("a url target names one destination");
};
assert_eq!(destination.url(), "https://example.com/summary");
});
}
#[test]
fn a_query_or_a_fragment_in_a_path_is_rejected() {
for path in ["refs/heads/a?b=c", "refs/heads/a#frag"] {
let Err(err) = check_path(path) else {
panic!("{path} was accepted as a request path");
};
assert!(
err.to_string().contains("no query and no fragment"),
"{path}: {err}"
);
}
check_path("refs/heads/a").unwrap();
}
#[test]
fn a_path_query_target_is_checked_and_goes_to_the_mirrors() {
rt::block_on(async {
let fetcher = Fetcher::new(direct_options("http://example.com/r"))
.await
.unwrap();
let route = fetcher
.route(Target::PathQuery {
path: "_ostrya/refs/v1",
query: "pattern=a",
})
.unwrap();
let Route::Mirrors { path, query } = route else {
panic!("a path query target goes to the mirrors");
};
assert_eq!((path, query), ("_ostrya/refs/v1", Some("pattern=a")));
let refused = [
("p?x", "q", "no query and no fragment"),
("p#x", "q", "no query and no fragment"),
("p", "q#x", "a query holds no fragment"),
];
for (path, query, message) in refused {
let err = fetcher
.route(Target::PathQuery { path, query })
.unwrap_err();
assert!(matches!(err, Error::Fetch(_)), "{err:?}");
assert!(err.to_string().contains(message), "{path}?{query}: {err}");
}
let fetcher = Fetcher::new(mirrorless_options()).await.unwrap();
let err = fetcher
.route(Target::PathQuery {
path: "p",
query: "q",
})
.unwrap_err();
assert!(
err.to_string().contains("path p?q has nowhere to go"),
"{err}"
);
});
}
#[test]
fn a_request_target_appends_the_path_to_the_base() {
rt::block_on(async {
let fetcher = Fetcher::new(direct_options("http://example.com/r"))
.await
.unwrap();
let mirror = &fetcher.inner.mirrors[0];
let destination = mirror.destination("refs/heads/a", None);
let request = fetcher
.build_request(
&destination,
&FetchRequest::path("refs/heads/a"),
&fetcher.inner.headers,
Protocol::Http11,
Via::Direct,
)
.unwrap();
assert_eq!(request.uri(), "/r/refs/heads/a");
});
}
#[test]
fn a_location_resolves_against_the_response_that_carried_it() {
let resolved = |value: &str| {
resolve_location(
"https://example.com/repo/objects/summary?x=1",
&HeaderValue::try_from(value).unwrap(),
)
};
for (value, hop) in [
("http://other.example/p", "http://other.example/p"),
(
"https://other.example:8443/p?q=2",
"https://other.example:8443/p?q=2",
),
("/other/path", "https://example.com/other/path"),
("sibling", "https://example.com/repo/objects/sibling"),
("//host.example/path", "https://host.example/path"),
("/other/path#frag", "https://example.com/other/path"),
("http://other.example/p#frag", "http://other.example/p"),
("file:///srv/repo", "file:///srv/repo"),
] {
assert_eq!(resolved(value).as_deref(), Some(hop), "{value}");
}
assert_eq!(resolved("http://"), None);
assert_eq!(resolved(""), None);
assert_eq!(
resolved("#frag").as_deref(),
Some("https://example.com/repo/objects/summary?x=1")
);
for (value, hop) in [
("/deep/../root", "https://example.com/root"),
("/./p", "https://example.com/p"),
("/a\\b", "https://example.com/a/b"),
("/pa\tth", "https://example.com/path"),
("/p?q='x'", "https://example.com/p?q=%27x%27"),
("http://2130706433/p", "http://127.0.0.1/p"),
] {
assert_eq!(resolved(value).as_deref(), Some(hop), "{value}");
}
}
#[test]
fn a_redirect_hop_is_validated_against_the_url_that_redirected() {
let secure = parse_url("https://example.com/repo/summary").unwrap();
let cleartext = parse_url("http://example.com/repo/summary").unwrap();
let hop = redirect_destination(&secure, "https://other.example/p?q=1").unwrap();
assert_eq!(hop.url(), "https://other.example/p?q=1");
assert_eq!(hop.origin.host, "other.example");
let hop = redirect_destination(&secure, "https://example.com/elsewhere").unwrap();
assert_eq!(hop.origin, secure.origin);
let hop = redirect_destination(&cleartext, "https://example.com/elsewhere").unwrap();
assert!(hop.origin.tls);
redirect_destination(&cleartext, "http://other.example/p").unwrap();
let err = redirect_destination(&secure, "http://other.example/p").unwrap_err();
let message = err.to_string();
assert!(
message.contains("https://example.com/repo/summary"),
"{message}"
);
assert!(message.contains("http://other.example/p"), "{message}");
assert!(message.contains("cleartext"), "{message}");
let err = redirect_destination(&secure, "file:///srv/repo").unwrap_err();
let message = err.to_string();
assert!(
message.contains("https://example.com/repo/summary"),
"{message}"
);
assert!(message.contains("file:///srv/repo"), "{message}");
assert!(
message.contains("not an absolute http or https url"),
"{message}"
);
let err =
redirect_destination(&secure, "https://alice:sup3rs3cret@other.example/p").unwrap_err();
let message = err.to_string();
assert!(message.contains("userinfo"), "{message}");
assert!(!message.contains("sup3rs3cret"), "{message}");
}
#[test]
fn the_followed_statuses_are_the_five_redirects() {
for status in [301u16, 302, 303, 307, 308] {
assert!(
is_redirect(StatusCode::from_u16(status).unwrap()),
"{status}"
);
}
for status in [200u16, 300, 304, 305, 306, 400, 404, 500] {
assert!(
!is_redirect(StatusCode::from_u16(status).unwrap()),
"{status}"
);
}
}
#[test]
fn retryable_statuses_are_classified() {
for status in [500u16, 502, 503, 408, 429] {
let failure = classify(StatusCode::from_u16(status).unwrap(), "http://h/p");
assert!(matches!(failure, Failure::Retry(_)), "{status}");
}
for status in [400u16, 401, 403, 404, 410] {
let failure = classify(StatusCode::from_u16(status).unwrap(), "http://h/p");
assert!(matches!(failure, Failure::Fatal(_)), "{status}");
}
}
#[test]
fn backoff_doubles_and_stops_at_two_seconds() {
assert_eq!(backoff(1), Duration::from_millis(250));
assert_eq!(backoff(2), Duration::from_millis(500));
assert_eq!(backoff(3), Duration::from_secs(1));
assert_eq!(backoff(4), Duration::from_secs(2));
assert_eq!(backoff(9), Duration::from_secs(2));
}
#[test]
fn basic_auth_and_extra_headers_reach_the_header_list() {
let mut options = tls_options("https://example.com");
options.basic_auth = Some(BasicAuth {
user: "u".into(),
password: "p".into(),
});
options.headers = vec![("x-trace".into(), "abc".into())];
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
let headers = &fetcher.inner.headers;
let value = |name: HeaderName| {
headers
.iter()
.find(|(n, _)| *n == name)
.map(|(_, v)| v.to_str().unwrap().to_string())
};
assert_eq!(
value(hyper::header::USER_AGENT).as_deref(),
Some(USER_AGENT)
);
assert_eq!(
value(HeaderName::from_static("x-trace")).as_deref(),
Some("abc")
);
assert_eq!(
value(hyper::header::AUTHORIZATION).as_deref(),
Some("Basic dTpw")
);
}
fn mirrorless_options() -> FetcherOptions {
FetcherOptions {
mirrors: Vec::new(),
..tls_options("unused")
}
}
fn direct_options(url: impl Into<String>) -> FetcherOptions {
FetcherOptions {
proxy: Proxy::None,
..FetcherOptions::new(url)
}
}
fn tls_options(url: &str) -> FetcherOptions {
FetcherOptions {
tls: TlsOptions {
roots: TrustRoots::Pem(
include_bytes!("../../../tests/fixtures/tls/ca.pem").to_vec(),
),
..TlsOptions::default()
},
..direct_options(url)
}
}
#[test]
fn credentials_alongside_a_cleartext_mirror_are_refused() {
let auth = || {
Some(BasicAuth {
user: "u".into(),
password: "p".into(),
})
};
for mirrors in [
vec!["http://cleartext.example/repo".to_owned()],
vec![
"https://secure.example/repo".to_owned(),
"http://cleartext.example/repo".to_owned(),
],
] {
let options = FetcherOptions {
mirrors,
basic_auth: auth(),
..tls_options("unused")
};
let err = rt::block_on(Fetcher::new(options)).unwrap_err();
let message = err.to_string();
assert!(message.contains("basic-auth credentials"), "{message}");
assert!(
message.contains("http://cleartext.example/repo"),
"{message}"
);
}
for name in ["authorization", "proxy-authorization", "cookie"] {
let options = FetcherOptions {
headers: vec![(name.to_owned(), "secret".to_owned())],
..direct_options("http://cleartext.example/repo")
};
let err = rt::block_on(Fetcher::new(options)).unwrap_err();
let message = err.to_string();
assert!(message.contains(name), "{message}");
assert!(message.contains("carries credentials"), "{message}");
}
let options = FetcherOptions {
headers: vec![("x-trace".to_owned(), "abc".to_owned())],
..direct_options("http://cleartext.example/repo")
};
rt::block_on(Fetcher::new(options)).unwrap();
let options = FetcherOptions {
mirrors: vec![
"https://one.example/repo".to_owned(),
"https://two.example/repo".to_owned(),
],
basic_auth: auth(),
headers: vec![("cookie".to_owned(), "session=1".to_owned())],
..tls_options("unused")
};
rt::block_on(Fetcher::new(options)).unwrap();
}
#[test]
fn url_targets_are_parsed_and_validated() {
let rows = [
(
"https://example.com/repo/summary?sig=a%2Fb&x=1",
"https://example.com/repo/summary?sig=a%2Fb&x=1",
"/repo/summary?sig=a%2Fb&x=1",
"example.com",
"https://example.com",
),
("http://h", "http://h/", "/", "h", "http://h"),
("http://h/", "http://h/", "/", "h", "http://h"),
("http://h/p?", "http://h/p?", "/p?", "h", "http://h"),
(
"http://h/p?a=%2F&b=1",
"http://h/p?a=%2F&b=1",
"/p?a=%2F&b=1",
"h",
"http://h",
),
("https://h:443/p", "https://h/p", "/p", "h", "https://h"),
("HTTP://h/p", "http://h/p", "/p", "h", "http://h"),
(
"http://[2001:db8::1]:8080/r/config",
"http://[2001:db8::1]:8080/r/config",
"/r/config",
"[2001:db8::1]:8080",
"http://[2001:db8::1]:8080",
),
];
for (url, absolute, target, authority, origin) in rows {
let dest = parse_url(url).unwrap();
assert_eq!(dest.url(), absolute, "{url}");
assert_eq!(dest.target(), target, "{url}");
assert_eq!(dest.authority, authority, "{url}");
assert_eq!(dest.origin_url(), origin, "{url}");
}
let dest = parse_url("https://example.com/repo/summary?sig=a%2Fb&x=1").unwrap();
assert_eq!(dest.origin.port, 443);
assert!(dest.origin.tls);
let root = parse_url("http://example.com").unwrap();
assert_eq!(root.origin.port, 80);
assert!(!root.origin.tls);
let ported = parse_url("http://[::1]:8080/r/config").unwrap();
assert_eq!(ported.origin.host, "::1");
assert_eq!(ported.origin.port, 8080);
let err = parse_url("https://alice:sup3rs3cret@example.com/p").unwrap_err();
let message = err.to_string();
assert!(message.contains("userinfo"), "{message}");
assert!(message.contains("https url for example.com"), "{message}");
assert!(message.contains("FetchRequest::basic_auth"), "{message}");
assert!(!message.contains("sup3rs3cret"), "{message}");
let err = parse_url("https://example.com/p#frag").unwrap_err();
assert!(err.to_string().contains("fragment"), "{err}");
let err = parse_url("file:///srv/repo").unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
let err = parse_url("/srv/repo").unwrap_err();
assert!(err.to_string().contains("not an absolute"), "{err}");
}
#[test]
fn a_password_reaches_no_message() {
for url in [
"https://alice:sup3rs3cret@example.com/p",
"https://alice:sup3rs3cret@example.com/p#frag",
"http://alice:sup3rs3cret@example.com/ p",
"http://alice:sup3rs3cret@",
"alice:sup3rs3cret@example.com/p",
] {
let err = parse_url(url).unwrap_err();
let message = err.to_string();
assert!(!message.contains("sup3rs3cret"), "{url}: {message}");
}
for password in ["pa#ss", "pa?ss", "p/ss"] {
let url = format!("https://alice:{password}@example.com/p");
let message = parse_url(&url).unwrap_err().to_string();
assert!(!message.contains(password), "{password}: {message}");
}
}
#[test]
fn a_port_the_url_parser_cannot_read_is_refused() {
for (url, text) in [
("http://h:99999/x", "99999"),
("http://h:65536/x", "65536"),
("http://h:abc/x", "abc"),
("http://h:/x", ""),
("http://h:+80/x", "+80"),
] {
let err = parse_url(url).unwrap_err();
let message = err.to_string();
assert!(message.contains(url), "{url}: {message}");
assert!(message.contains(text), "{url}: {message}");
assert!(message.contains("not a number"), "{url}: {message}");
assert!(parse_mirror(url).is_err(), "{url}");
}
let default = parse_url("http://h/x").unwrap();
assert_eq!(default.origin.port, 80);
assert_eq!(default.url(), "http://h/x");
let ported = parse_url("http://h:8080/x").unwrap();
assert_eq!(ported.origin.port, 8080);
assert_eq!(ported.url(), "http://h:8080/x");
let zeros = parse_url("http://h:0080/x").unwrap();
assert_eq!(zeros.origin.port, 80);
assert_eq!(zeros.url(), "http://h/x");
}
#[test]
fn a_host_in_another_case_is_one_origin() {
let upper = parse_url("http://LOCALHOST:8080/x").unwrap();
let lower = parse_url("http://localhost:8080/x").unwrap();
assert_eq!(upper.origin, lower.origin);
assert_eq!(upper.origin.host, "localhost");
assert_eq!(upper.authority, "LOCALHOST:8080");
assert_eq!(upper.url(), "http://LOCALHOST:8080/x");
}
#[test]
fn basic_auth_debug_holds_no_password() {
let auth = BasicAuth {
user: "alice".into(),
password: "sup3rs3cret".into(),
};
let rendered = format!("{auth:?}");
assert!(rendered.contains("alice"), "{rendered}");
assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
let request = FetchRequest {
basic_auth: Some(&auth),
..FetchRequest::path("summary")
};
let rendered = format!("{request:?}");
assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
let options = FetcherOptions {
basic_auth: Some(auth),
..direct_options("https://example.com")
};
let rendered = format!("{options:?}");
assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
}
fn origin_of(url: &str) -> Origin {
parse_url(url).unwrap().origin
}
fn via_of(proxies: &Proxies, url: &str) -> Option<(String, bool)> {
match proxies.via(&origin_of(url)) {
Via::Direct => None,
Via::Absolute(proxy) => Some((proxy.named.clone(), false)),
Via::Tunnel(proxy) => Some((proxy.named.clone(), true)),
}
}
fn variables(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
.collect()
}
#[test]
fn a_proxy_url_names_an_http_endpoint() {
for (url, host, port, named) in [
(
"http://proxy.example",
"proxy.example",
80,
"http://proxy.example",
),
(
"http://proxy.example:3128",
"proxy.example",
3128,
"http://proxy.example:3128",
),
(
"http://proxy.example/",
"proxy.example",
80,
"http://proxy.example",
),
(
"HTTP://Proxy.Example:3128",
"proxy.example",
3128,
"http://Proxy.Example:3128",
),
(
" http://proxy.example:3128 ",
"proxy.example",
3128,
"http://proxy.example:3128",
),
("http://[::1]:3128", "::1", 3128, "http://[::1]:3128"),
(
"http://alice:s3cret@proxy.example:3128",
"proxy.example",
3128,
"http://proxy.example:3128",
),
] {
let proxy = parse_proxy(url).unwrap_or_else(|e| panic!("{url}: {e}"));
assert_eq!(proxy.endpoint.host, host, "{url}");
assert_eq!(proxy.endpoint.port, port, "{url}");
assert!(!proxy.endpoint.tls, "{url}");
assert_eq!(proxy.named, named, "{url}");
}
let credential = |url: &str| {
parse_proxy(url)
.unwrap()
.credential
.map(|value| value.to_str().unwrap().to_owned())
};
assert_eq!(credential("http://proxy.example"), None);
assert_eq!(
credential("http://alice:s3cret@proxy.example").as_deref(),
Some("Basic YWxpY2U6czNjcmV0")
);
assert_eq!(
credential("http://al%3Ace:p%40ss@proxy.example").as_deref(),
Some("Basic YWw6Y2U6cEBzcw==")
);
assert_eq!(
credential("http://alice@proxy.example").as_deref(),
Some("Basic YWxpY2U6")
);
for (url, says) in [
("socks5://proxy.example:1080", "http://host[:port] alone"),
("https://proxy.example:3128", "http://host[:port] alone"),
("proxy.example:3128", "http://host[:port] alone"),
("http://proxy.example/squid", "carries no path"),
("http://proxy.example/?upstream=1", "carries no query"),
("http://proxy.example/#frag", "carries no fragment"),
("http://", "invalid url"),
("http://proxy.example:99999", "not a number"),
("http://proxy.example:abc", "not a number"),
("http://alice:p%zz@proxy.example", "percent-encoded"),
("http://alice:p%4@proxy.example", "percent-encoded"),
] {
let err = parse_proxy(url).unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{url}: {err}");
let message = err.to_string();
assert!(message.contains(says), "{url}: {message}");
}
}
#[test]
fn the_proxy_variables_are_read_per_scheme() {
let cleartext = "http://origin.example/summary";
let tls = "https://origin.example/summary";
let absolute = |named: &str| Some((named.to_owned(), false));
let tunnel = |named: &str| Some((named.to_owned(), true));
let proxies = resolve_variables(&variables(&[
("http_proxy", "http://plain.example:3128"),
("https_proxy", "http://secure.example:3128"),
]))
.unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://plain.example:3128")
);
assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
let proxies =
resolve_variables(&variables(&[("http_proxy", "http://plain.example:3128")])).unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://plain.example:3128")
);
assert_eq!(via_of(&proxies, tls), None);
let proxies =
resolve_variables(&variables(&[("https_proxy", "http://secure.example:3128")]))
.unwrap();
assert_eq!(via_of(&proxies, cleartext), None);
assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
let proxies =
resolve_variables(&variables(&[("all_proxy", "http://any.example:3128")])).unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://any.example:3128")
);
assert_eq!(via_of(&proxies, tls), tunnel("http://any.example:3128"));
let proxies = resolve_variables(&variables(&[
("all_proxy", "http://any.example:3128"),
("https_proxy", "http://secure.example:3128"),
]))
.unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://any.example:3128")
);
assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
let proxies = resolve_variables(&variables(&[
("HTTP_PROXY", "http://cgi.example:3128"),
("HTTPS_PROXY", "http://secure.example:3128"),
]))
.unwrap();
assert_eq!(via_of(&proxies, cleartext), None);
assert_eq!(via_of(&proxies, tls), tunnel("http://secure.example:3128"));
let proxies =
resolve_variables(&variables(&[("ALL_PROXY", "http://any.example:3128")])).unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://any.example:3128")
);
let proxies = resolve_variables(&variables(&[
("https_proxy", "http://lower.example:3128"),
("HTTPS_PROXY", "http://upper.example:3128"),
]))
.unwrap();
assert_eq!(via_of(&proxies, tls), tunnel("http://lower.example:3128"));
let proxies = resolve_variables(&variables(&[
("https_proxy", ""),
("HTTPS_PROXY", "http://upper.example:3128"),
]))
.unwrap();
assert_eq!(via_of(&proxies, tls), tunnel("http://upper.example:3128"));
let proxies = resolve_variables(&variables(&[("http_proxy", "")])).unwrap();
assert_eq!(via_of(&proxies, cleartext), None);
for name in ["http_proxy", "https_proxy", "all_proxy"] {
let err = resolve_variables(&variables(&[(name, "socks5://proxy.example:1080")]))
.unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{name}: {err}");
}
let err = resolve_variables(&variables(&[
("all_proxy", "socks5://proxy.example:1080"),
("http_proxy", "http://plain.example:3128"),
("https_proxy", "http://secure.example:3128"),
]))
.unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
let proxies = resolve_variables(&[]).unwrap();
assert_eq!(via_of(&proxies, cleartext), None);
assert_eq!(via_of(&proxies, tls), None);
let proxies = resolve_proxy(&Proxy::None).unwrap();
assert_eq!(via_of(&proxies, cleartext), None);
let proxies = resolve_proxy(&Proxy::Url("http://any.example:3128".into())).unwrap();
assert_eq!(
via_of(&proxies, cleartext),
absolute("http://any.example:3128")
);
assert_eq!(via_of(&proxies, tls), tunnel("http://any.example:3128"));
}
#[test]
fn a_proxy_variable_with_white_space_around_it_is_refused() {
let url = "http://alice:s3cret@proxy.example:3128";
let refused = |pairs: &[(&str, &str)], name: &str| {
let err = resolve_variables(&variables(pairs)).unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{pairs:?}: {err}");
let message = err.to_string();
assert!(message.contains(name), "{pairs:?}: {message}");
assert!(!message.contains("s3cret"), "{pairs:?}: {message}");
assert!(!message.contains("proxy.example"), "{pairs:?}: {message}");
};
for name in [
"http_proxy",
"https_proxy",
"HTTPS_PROXY",
"all_proxy",
"ALL_PROXY",
] {
for value in [
format!(" {url}"),
format!("{url} "),
format!("{url}\t"),
format!("{url}\n"),
format!("{url}\u{a0}"),
" ".to_owned(),
] {
refused(&[(name, &value)], name);
}
}
refused(
&[("all_proxy", ""), ("ALL_PROXY", "http://p:1 ")],
"ALL_PROXY",
);
refused(
&[("all_proxy", "socks5://alice:s3cret@proxy.example:1080 ")],
"all_proxy",
);
refused(
&[("http_proxy", &format!("{url} ")), ("no_proxy", "*")],
"http_proxy",
);
refused(
&[
("all_proxy", &format!("{url} ")),
("http_proxy", "http://plain.example:3128"),
("https_proxy", "http://secure.example:3128"),
],
"all_proxy",
);
resolve_variables(&variables(&[
("https_proxy", "http://secure.example:3128"),
("HTTPS_PROXY", "http://upper.example:3128 "),
]))
.unwrap();
resolve_variables(&variables(&[("HTTP_PROXY", "http://cgi.example:3128 ")])).unwrap();
resolve_proxy(&Proxy::Url("http://p:3128 ".into())).unwrap();
}
#[test]
fn no_proxy_exempts_by_host_text_and_port() {
let proxied = |no_proxy: &str, url: &str| {
let proxies = resolve_variables(&variables(&[
("all_proxy", "http://any.example:3128"),
("no_proxy", no_proxy),
]))
.unwrap();
via_of(&proxies, url).is_some()
};
assert!(!proxied("origin.example", "http://origin.example/p"));
assert!(proxied("origin.example", "http://other.example/p"));
for entry in ["example.com", ".example.com"] {
assert!(!proxied(entry, "http://a.example.com/p"));
assert!(!proxied(entry, "http://deep.a.example.com/p"));
assert!(!proxied(entry, "http://example.com/p"));
assert!(proxied(entry, "http://notexample.com/p"));
}
assert!(!proxied(" a.example , b.example ", "http://b.example/p"));
assert!(!proxied("a.example,,b.example", "http://a.example/p"));
assert!(proxied(",", "http://a.example/p"));
assert!(proxied("", "http://a.example/p"));
assert!(!proxied("ORIGIN.example", "http://origin.EXAMPLE/p"));
assert!(!proxied(
"origin.example:8080",
"http://origin.example:8080/p"
));
assert!(proxied(
"origin.example:8080",
"http://origin.example:8081/p"
));
assert!(proxied("origin.example:8080", "http://origin.example/p"));
assert!(!proxied("origin.example:443", "https://origin.example/p"));
assert!(!proxied("origin.example", "http://origin.example:8080/p"));
for url in ["http://a.example/p", "https://b.example:8443/p"] {
assert!(!proxied("*", url));
assert!(!proxied("a.example,*", url));
}
assert!(!proxied("127.0.0.1", "http://127.0.0.1:8080/p"));
assert!(proxied("localhost", "http://127.0.0.1:8080/p"));
assert!(proxied("127.0.0.1", "http://localhost:8080/p"));
for entry in ["::1", "[::1]", "[::1]:8080"] {
assert!(!proxied(entry, "http://[::1]:8080/p"), "{entry}");
}
assert!(proxied("[::1]:8081", "http://[::1]:8080/p"));
assert!(proxied("127.0.0.0/8", "http://127.0.0.1:8080/p"));
assert!(proxied("origin.example:abc", "http://origin.example/p"));
for entry in [".", ":8080", ".:8080"] {
assert!(proxied(entry, "http://a.example./p"), "{entry}");
assert!(proxied(entry, "http://a.example:8080/p"), "{entry}");
}
assert!(proxied("..example.com", "http://a.example.com/p"));
assert!(proxied("*.example.com", "http://a.example.com/p"));
assert!(proxied("*.example.com", "http://example.com/p"));
}
#[test]
fn a_proxy_password_reaches_no_message() {
let url = |tail: &str| format!("http://alice:sup3rs3cret@proxy.example:3128{tail}");
for proxy in [
Proxy::Url(url("")),
Proxy::Variables(vec![("https_proxy".to_owned(), url(""))]),
] {
let rendered = format!("{proxy:?}");
assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
assert!(rendered.contains("proxy.example:3128"), "{rendered}");
let options = FetcherOptions {
proxy,
..direct_options("https://example.com")
};
let rendered = format!("{options:?}");
assert!(!rendered.contains("sup3rs3cret"), "{rendered}");
}
for tail in ["/squid", "/?upstream=1", "/#frag", ":99999"] {
let err = parse_proxy(&url(tail)).unwrap_err();
let message = err.to_string();
assert!(!message.contains("sup3rs3cret"), "{tail}: {message}");
}
let err = parse_proxy("socks5://alice:sup3rs3cret@proxy.example:1080").unwrap_err();
assert!(!err.to_string().contains("sup3rs3cret"), "{err}");
for password in ["pa#ss", "pa?ss", "p/ss"] {
let url = format!("http://alice:{password}@proxy.example:3128/squid");
let rendered = format!("{:?}", Proxy::Url(url.clone()));
assert!(!rendered.contains(password), "{password}: {rendered}");
assert!(
rendered.contains("proxy.example:3128"),
"{password}: {rendered}"
);
let message = parse_proxy(&url).unwrap_err().to_string();
assert!(!message.contains(password), "{password}: {message}");
assert!(
message.contains("proxy.example:3128"),
"{password}: {message}"
);
}
for userinfo in ["u/pw-QXZ", "tok?pw-QXZ", "u:x/pw-QXZ", "u:x?pw-QXZ"] {
let url = format!("http://{userinfo}@proxy.invalid:3128");
let message = parse_proxy(&url).unwrap_err().to_string();
assert!(!message.contains("pw-QXZ"), "{userinfo}: {message}");
}
rt::block_on(async {
let err = Fetcher::new(FetcherOptions {
proxy: Proxy::Url(url("/squid")),
..direct_options("http://origin.example/repo")
})
.await
.unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
let message = err.to_string();
assert!(!message.contains("sup3rs3cret"), "{message}");
assert!(message.contains("proxy.example:3128"), "{message}");
});
}
#[test]
fn proxy_debug_redacts_each_url() {
let url = "http://alice:pw-QXZ@proxy.example:3128/?t=QXZ#QXZ";
assert_eq!(
format!("{:?}", Proxy::Url(url.to_owned())),
r#"Url("http://proxy.example:3128/?<redacted>#<redacted>")"#
);
let variables = Proxy::Variables(vec![
("https_proxy".to_owned(), url.to_owned()),
("no_proxy".to_owned(), ".internal.example.com".to_owned()),
]);
assert_eq!(
format!("{variables:?}"),
concat!(
r#"Variables([("https_proxy", "http://proxy.example:3128/?<redacted>#<redacted>"), "#,
r#"("no_proxy", ".internal.example.com")])"#
)
);
assert_eq!(format!("{:?}", Proxy::None), "None");
assert_eq!(format!("{:?}", Proxy::Environment), "Environment");
}
#[test]
fn without_userinfo_reads_only_a_valid_scheme() {
assert_eq!(without_userinfo("u:a://b@h/p"), "h/p");
assert_eq!(without_userinfo("svn+ssh://u@h/p"), "svn+ssh://h/p");
assert_eq!(without_userinfo("https://h/p"), "https://h/p");
assert_eq!(scheme_len("1http://h"), 0);
assert_eq!(scheme_len("://h"), 0);
assert_eq!(scheme_len("h/p"), 0);
}
#[test]
fn a_connect_names_the_target_with_its_port() {
for (url, authority) in [
("https://origin.example/p", "origin.example:443"),
("https://origin.example:8443/p", "origin.example:8443"),
("http://origin.example/p", "origin.example:80"),
("https://[2001:db8::1]/p", "[2001:db8::1]:443"),
("https://[::1]:8443/p", "[::1]:8443"),
] {
assert_eq!(connect_authority(&origin_of(url)), authority, "{url}");
}
}
#[test]
fn a_proxied_cleartext_request_carries_the_absolute_form() {
rt::block_on(async {
let fetcher = Fetcher::new(FetcherOptions {
proxy: Proxy::Url("http://alice:s3cret@proxy.example:3128".into()),
..tls_options("http://origin.example/r")
})
.await
.unwrap();
let destination = fetcher.inner.mirrors[0].destination("refs/heads/a", None);
let request = FetchRequest::path("refs/heads/a");
let built = |via: Via<'_>, headers: &[(HeaderName, HeaderValue)]| {
fetcher
.build_request(&destination, &request, headers, Protocol::Http11, via)
.unwrap()
};
let proxy_credential = |request: &Request<RequestBody>| {
request
.headers()
.get(hyper::header::PROXY_AUTHORIZATION)
.map(|value| value.to_str().unwrap().to_owned())
};
let Via::Absolute(proxy) = fetcher.inner.proxies.via(&destination.origin) else {
panic!("a cleartext origin behind a proxy travels in absolute form");
};
let via = Via::Absolute(proxy);
let absolute = built(via, &fetcher.inner.headers);
assert_eq!(absolute.uri(), "http://origin.example/r/refs/heads/a");
assert_eq!(
absolute.headers().get(hyper::header::HOST).unwrap(),
"origin.example"
);
assert_eq!(
proxy_credential(&absolute).as_deref(),
Some("Basic YWxpY2U6czNjcmV0")
);
let mut headers = fetcher.inner.headers.clone();
headers.push((
hyper::header::PROXY_AUTHORIZATION,
HeaderValue::from_static("Basic Y2FsbGVy"),
));
let caller = built(via, &headers);
assert_eq!(
caller
.headers()
.get_all(hyper::header::PROXY_AUTHORIZATION)
.iter()
.count(),
1
);
assert_eq!(proxy_credential(&caller).as_deref(), Some("Basic Y2FsbGVy"));
for via in [Via::Direct, Via::Tunnel(proxy)] {
let direct = built(via, &fetcher.inner.headers);
assert_eq!(direct.uri(), "/r/refs/heads/a");
assert_eq!(proxy_credential(&direct), None);
}
});
}
#[test]
fn a_connection_header_is_refused_at_both_layers() {
let fetcher_headers = vec![(
HeaderName::from_static("x-trace"),
HeaderValue::from_static("abc"),
)];
for name in CONNECTION_HEADERS {
let options = FetcherOptions {
headers: vec![(name.to_owned(), "10".to_owned())],
..direct_options("http://example.com")
};
let err = rt::block_on(Fetcher::new(options)).unwrap_err();
let message = err.to_string();
assert!(message.contains(name), "{name}: {message}");
assert!(message.contains("connection layer"), "{name}: {message}");
let request = vec![(name.to_owned(), "10".to_owned())];
let err = merge_headers(&fetcher_headers, &request, None, None).unwrap_err();
let message = err.to_string();
assert!(message.contains(name), "{name}: {message}");
assert!(message.contains("connection layer"), "{name}: {message}");
}
let request = vec![("Content-Length".to_owned(), "10".to_owned())];
let err = merge_headers(&fetcher_headers, &request, None, None).unwrap_err();
assert!(err.to_string().contains("content-length"), "{err}");
}
#[test]
fn request_headers_merge_over_the_fetchers() {
let header = |name: &'static str, value: &'static str| {
(
HeaderName::from_static(name),
HeaderValue::from_static(value),
)
};
let fetcher = vec![
header("x-trace", "fetcher"),
header("x-only", "yes"),
header("authorization", "Basic ZmV0Y2hlcg=="),
];
let sent = |headers: &[(HeaderName, HeaderValue)]| {
headers
.iter()
.map(|(name, value)| (name.as_str().to_owned(), value.to_str().unwrap().to_owned()))
.collect::<Vec<_>>()
};
let borrowed = merge_headers(&fetcher, &[], None, None).unwrap();
assert!(matches!(borrowed, Cow::Borrowed(_)));
assert_eq!(sent(&borrowed), sent(&fetcher));
let extra = vec![
("X-Trace".to_owned(), "request".to_owned()),
("x-trace".to_owned(), "second".to_owned()),
];
let merged = merge_headers(&fetcher, &extra, None, None).unwrap();
assert_eq!(
sent(&merged),
[
("x-only".to_owned(), "yes".to_owned()),
("authorization".to_owned(), "Basic ZmV0Y2hlcg==".to_owned()),
("x-trace".to_owned(), "request".to_owned()),
("x-trace".to_owned(), "second".to_owned()),
]
);
let auth = BasicAuth {
user: "u".into(),
password: "p".into(),
};
let merged = merge_headers(&fetcher, &[], Some(&auth), None).unwrap();
assert_eq!(
sent(&merged),
[
("x-trace".to_owned(), "fetcher".to_owned()),
("x-only".to_owned(), "yes".to_owned()),
("authorization".to_owned(), "Basic dTpw".to_owned()),
]
);
let both = vec![("authorization".to_owned(), "Basic aaa".to_owned())];
let err = merge_headers(&fetcher, &both, Some(&auth), None).unwrap_err();
assert!(err.to_string().contains("pass one of them"), "{err}");
let host = vec![("host".to_owned(), "elsewhere".to_owned())];
let err = merge_headers(&fetcher, &host, None, None).unwrap_err();
assert!(err.to_string().contains("host header"), "{err}");
let invalid = vec![("not a header".to_owned(), "v".to_owned())];
let err = merge_headers(&fetcher, &invalid, None, None).unwrap_err();
assert!(err.to_string().contains("invalid header name"), "{err}");
}
#[test]
fn a_declared_content_coding_is_read_off_the_response() {
let map = |values: &[&str]| {
let mut headers = hyper::HeaderMap::new();
for value in values {
headers.append(
hyper::header::CONTENT_ENCODING,
HeaderValue::try_from(*value).unwrap(),
);
}
headers
};
for values in [
vec![],
vec![""],
vec![","],
vec!["identity"],
vec!["IDENTITY"],
vec![" identity "],
vec!["identity", "identity"],
] {
assert_eq!(declared_coding(&map(&values)), None, "{values:?}");
}
for (values, named) in [
(vec!["gzip"], "gzip"),
(vec!["GZip"], "GZip"),
(vec!["identity, gzip"], "identity, gzip"),
(vec!["gzip, identity"], "gzip, identity"),
(vec!["identity", "gzip"], "identity, gzip"),
(vec!["gzip", "br"], "gzip, br"),
(vec!["", "gzip"], "gzip"),
(vec!["gzip", ""], "gzip"),
(vec!["gzip", "", "br"], "gzip, br"),
(vec!["gzip", ",", "br"], "gzip, br"),
] {
assert_eq!(
declared_coding(&map(&values)).as_deref(),
Some(named),
"{values:?}"
);
}
}
#[test]
fn a_fetcher_header_replaces_the_entry_the_fetcher_sets() {
let sent = |fetcher: &Fetcher, name: HeaderName| {
fetcher
.inner
.headers
.iter()
.filter(|(held, _)| *held == name)
.map(|(_, value)| value.to_str().unwrap().to_owned())
.collect::<Vec<_>>()
};
let fetcher = rt::block_on(Fetcher::new(direct_options("http://example.com"))).unwrap();
assert_eq!(
sent(&fetcher, hyper::header::ACCEPT_ENCODING),
[IDENTITY.to_owned()]
);
for name in ["accept-encoding", "user-agent"] {
let options = FetcherOptions {
headers: vec![(name.to_owned(), "caller".to_owned())],
..direct_options("http://example.com")
};
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
let header = HeaderName::from_static(name);
assert_eq!(sent(&fetcher, header), ["caller".to_owned()], "{name}");
}
let options = FetcherOptions {
headers: vec![
("accept-encoding".to_owned(), "one".to_owned()),
("Accept-Encoding".to_owned(), "two".to_owned()),
],
..direct_options("http://example.com")
};
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
assert_eq!(
sent(&fetcher, hyper::header::ACCEPT_ENCODING),
["one".to_owned(), "two".to_owned()]
);
let options = FetcherOptions {
headers: vec![
("x-trace".to_owned(), "one".to_owned()),
("x-trace".to_owned(), "two".to_owned()),
],
..direct_options("http://example.com")
};
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
assert_eq!(
sent(&fetcher, HeaderName::from_static("x-trace")),
["one".to_owned(), "two".to_owned()]
);
}
#[test]
fn a_credential_refuses_a_cleartext_destination() {
let credential = vec![(hyper::header::COOKIE, HeaderValue::from_static("session=1"))];
let plain = vec![(
HeaderName::from_static("x-trace"),
HeaderValue::from_static("abc"),
)];
let options = FetcherOptions {
mirrors: vec![
"https://secure.example/repo".to_owned(),
"http://cleartext.example/repo".to_owned(),
],
..tls_options("unused")
};
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
let mirrors = fetcher.route(Target::Path("summary")).unwrap();
let err = fetcher.check_cleartext(&mirrors, &credential).unwrap_err();
assert!(
err.to_string().contains("http://cleartext.example"),
"{err}"
);
fetcher.check_cleartext(&mirrors, &plain).unwrap();
let cleartext = fetcher
.route(Target::Url("http://cleartext.example/p"))
.unwrap();
let err = fetcher
.check_cleartext(&cleartext, &credential)
.unwrap_err();
assert!(
err.to_string().contains("http://cleartext.example"),
"{err}"
);
fetcher.check_cleartext(&cleartext, &plain).unwrap();
let secure = fetcher
.route(Target::Url("https://secure.example/p"))
.unwrap();
fetcher.check_cleartext(&secure, &credential).unwrap();
}
#[test]
fn a_tls_destination_needs_a_trust_anchor() {
rt::block_on(async {
let mut fetcher = Fetcher::new(direct_options("http://cleartext.example/repo"))
.await
.unwrap();
Arc::get_mut(&mut fetcher.inner)
.expect("the one handle on this fetcher")
.has_trust_anchors = false;
let refused = within(
Duration::from_secs(1),
fetcher.fetch(FetchRequest::url("https://127.0.0.1:1/summary")),
)
.await;
let err = refused
.expect("the refusal takes no attempt")
.expect_err("a tls url is refused without anchors");
let message = err.to_string();
assert!(message.contains("https://127.0.0.1:1"), "{message}");
assert!(message.contains("no trust anchors"), "{message}");
let cleartext = fetcher
.route(Target::Url("http://cleartext.example/summary"))
.unwrap();
fetcher.check_trust_anchors(&cleartext).unwrap();
let mirrors = fetcher.route(Target::Path("summary")).unwrap();
fetcher.check_trust_anchors(&mirrors).unwrap();
});
}
#[test]
fn a_cleartext_fetcher_with_no_redirect_reads_no_trust_store() {
let reads = || tls::SYSTEM_STORE_READS.with(std::cell::Cell::get);
rt::block_on(async {
let before = reads();
let fetcher = Fetcher::new(FetcherOptions {
max_redirects: 0,
..direct_options("http://cleartext.example/repo")
})
.await
.unwrap();
assert_eq!(reads(), before, "the store was read");
assert!(!fetcher.inner.has_trust_anchors);
let refused = within(
Duration::from_secs(1),
fetcher.fetch(FetchRequest::url("https://127.0.0.1:1/summary")),
)
.await
.expect("the refusal takes no attempt")
.expect_err("a tls url is refused without anchors");
assert!(
refused.to_string().contains("no trust anchors"),
"{refused}"
);
let cases = [
direct_options("http://cleartext.example/repo"),
FetcherOptions {
max_redirects: 0,
..direct_options("https://tls.example/repo")
},
FetcherOptions {
max_redirects: 0,
proxy: Proxy::None,
..FetcherOptions::default()
},
];
for options in cases {
let before = reads();
let what = format!("{:?} {}", options.mirrors, options.max_redirects);
let _ = Fetcher::new(options).await;
assert_eq!(reads(), before + 1, "{what}");
}
});
}
#[test]
fn a_redirect_to_a_tls_origin_needs_a_trust_anchor() {
use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
use std::sync::atomic::{AtomicUsize, Ordering};
rt::block_on(async {
let tls_peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
.await
.unwrap();
let tls_port = tls_peer.local_addr().unwrap().port();
let connections = Arc::new(AtomicUsize::new(0));
let counted = connections.clone();
drop(rt::spawn(async move {
while let Ok((stream, _peer)) = tls_peer.accept().await {
counted.fetch_add(1, Ordering::SeqCst);
drop(stream);
}
}));
let cleartext_peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
.await
.unwrap();
let cleartext_port = cleartext_peer.local_addr().unwrap().port();
let requests = Arc::new(AtomicUsize::new(0));
let counted = requests.clone();
drop(rt::spawn(async move {
while let Ok((mut stream, _peer)) = cleartext_peer.accept().await {
let mut request = [0u8; 1024];
let _ = stream.read(&mut request).await;
counted.fetch_add(1, Ordering::SeqCst);
let answer = format!(
"HTTP/1.1 302 Found\r\nLocation: https://127.0.0.1:{tls_port}/hopped\r\n\
Content-Length: 0\r\n\r\n"
);
let _ = stream.write_all(answer.as_bytes()).await;
let _ = stream.flush().await;
}
}));
let mut fetcher =
Fetcher::new(direct_options(format!("http://127.0.0.1:{cleartext_port}")))
.await
.unwrap();
Arc::get_mut(&mut fetcher.inner)
.expect("the one handle on this fetcher")
.has_trust_anchors = false;
let refused = within(
Duration::from_secs(2),
fetcher.fetch(FetchRequest::path("summary")),
)
.await;
let err = refused
.expect("the refusal ends the attempt")
.expect_err("a tls hop is refused without anchors");
let message = err.to_string();
assert!(
message.contains(&format!("https://127.0.0.1:{tls_port}")),
"{message}"
);
assert!(message.contains("no trust anchors"), "{message}");
assert_eq!(requests.load(Ordering::SeqCst), 1);
assert_eq!(connections.load(Ordering::SeqCst), 0);
});
}
fn channel() -> (BodyEnd, UploadWriter) {
let (body, writer) = UploadBody::channel();
let UploadForm::Channel(end) = body.form else {
panic!("a channel body holds its reading end");
};
(end, writer)
}
async fn next_frame(end: &mut BodyEnd) -> Option<std::io::Result<Bytes>> {
let frame = std::future::poll_fn(|cx| end.poll_frame(cx)).await?;
Some(frame.map(|frame| frame.into_data().expect("an upload body yields data")))
}
#[test]
fn a_writer_hands_over_frames_of_64_kib() {
rt::block_on(async {
let (mut end, mut writer) = channel();
let data = (0..150_000u32).map(|i| i as u8).collect::<Vec<_>>();
let written = async {
futures_lite::io::AsyncWriteExt::write_all(&mut writer, &data).await?;
futures_lite::io::AsyncWriteExt::close(&mut writer).await
};
let read = async {
let mut frames = Vec::new();
while let Some(frame) = next_frame(&mut end).await {
frames.push(frame.unwrap());
}
frames
};
let (written, frames) = futures_lite::future::zip(written, read).await;
written.unwrap();
assert_eq!(
frames.iter().map(Bytes::len).collect::<Vec<_>>(),
[UPLOAD_FRAME, UPLOAD_FRAME, 150_000 - 2 * UPLOAD_FRAME]
);
assert_eq!(frames.concat(), data);
assert!(end.is_end_stream());
assert!(end.exchange.lock().ended);
assert_eq!(end.exchange.exact, None);
});
}
#[test]
fn a_flush_hands_over_a_part_filled_frame() {
rt::block_on(async {
let (mut end, mut writer) = channel();
let flushed = async {
futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"hello").await?;
futures_lite::io::AsyncWriteExt::flush(&mut writer).await
};
let (flushed, frame) = futures_lite::future::zip(flushed, next_frame(&mut end)).await;
flushed.unwrap();
assert_eq!(frame.unwrap().unwrap(), &b"hello"[..]);
assert!(!end.is_end_stream());
});
}
#[test]
fn a_writer_reports_the_hand_over() {
let (end, writer) = channel();
assert!(!writer.is_handed_over());
end.exchange.hand_over(Duration::from_secs(1)).unwrap();
assert!(writer.is_handed_over());
end.exchange.withdraw();
assert!(!writer.is_handed_over());
}
#[test]
fn a_small_flush_hands_over_a_copy_and_keeps_the_buffer() {
rt::block_on(async {
let (mut end, mut writer) = channel();
assert_eq!(writer.buffer.capacity(), 0);
futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"small")
.await
.unwrap();
assert_eq!(writer.buffer.capacity(), UPLOAD_FRAME);
let kept = writer.buffer.as_ptr();
let flushed = futures_lite::io::AsyncWriteExt::flush(&mut writer);
let (flushed, frame) = futures_lite::future::zip(flushed, next_frame(&mut end)).await;
flushed.unwrap();
assert_eq!(frame.unwrap().unwrap(), &b"small"[..]);
assert!(writer.buffer.is_empty());
assert_eq!(writer.buffer.as_ptr(), kept);
assert_eq!(writer.buffer.capacity(), UPLOAD_FRAME);
let large = vec![7u8; SMALL_FRAME];
let flushed = async {
futures_lite::io::AsyncWriteExt::write_all(&mut writer, &large).await?;
futures_lite::io::AsyncWriteExt::flush(&mut writer).await
};
let (flushed, frame) = futures_lite::future::zip(flushed, next_frame(&mut end)).await;
flushed.unwrap();
assert_eq!(frame.unwrap().unwrap(), large);
assert_eq!(writer.buffer.capacity(), 0);
futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"x")
.await
.unwrap();
assert_eq!(writer.buffer.capacity(), UPLOAD_FRAME);
});
}
#[test]
fn a_writer_dropped_unclosed_fails_the_body() {
rt::block_on(async {
let (mut end, mut writer) = channel();
futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"part")
.await
.unwrap();
drop(writer);
let err = next_frame(&mut end).await.unwrap().unwrap_err();
assert!(err.to_string().contains("dropped"), "{err}");
assert!(!end.is_end_stream());
assert!(!end.exchange.lock().ended);
assert!(next_frame(&mut end).await.unwrap().is_err());
});
}
#[test]
fn a_write_after_the_reading_end_is_gone_is_a_broken_pipe() {
rt::block_on(async {
let (end, mut writer) = channel();
drop(end);
let err = futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"late")
.await
.unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
let err = futures_lite::io::AsyncWriteExt::flush(&mut writer)
.await
.unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
});
}
#[test]
fn a_write_after_close_is_a_broken_pipe() {
rt::block_on(async {
let (mut end, mut writer) = channel();
let closed = futures_lite::io::AsyncWriteExt::close(&mut writer);
let (closed, frame) = futures_lite::future::zip(closed, next_frame(&mut end)).await;
closed.unwrap();
assert!(frame.is_none());
let err = futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"x")
.await
.unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
});
}
#[test]
fn a_frame_not_taken_within_the_window_fails_the_write() {
rt::block_on(async {
let (mut end, mut writer) = channel();
let frame = vec![0u8; UPLOAD_FRAME];
for _ in 0..2 {
futures_lite::io::AsyncWriteExt::write_all(&mut writer, &frame)
.await
.unwrap();
}
let unbounded = within(
Duration::from_millis(100),
futures_lite::io::AsyncWriteExt::write_all(&mut writer, &frame),
)
.await;
assert!(unbounded.is_none(), "a wait before the upload has no bound");
end.exchange.hand_over(Duration::from_millis(50)).unwrap();
let started = Instant::now();
let err = futures_lite::io::AsyncWriteExt::write_all(&mut writer, &frame)
.await
.unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
assert!(started.elapsed() >= Duration::from_millis(50));
let again = futures_lite::io::AsyncWriteExt::write_all(&mut writer, b"x")
.await
.unwrap_err();
assert_eq!(again.kind(), std::io::ErrorKind::TimedOut);
let failed = next_frame(&mut end).await.unwrap().unwrap_err();
assert!(failed.to_string().contains("not taken"), "{failed}");
});
}
#[test]
fn a_whole_body_travels_in_frames_of_a_declared_length() {
rt::block_on(async {
let bytes = Bytes::from((0..150_000u32).map(|i| i as u8).collect::<Vec<_>>());
let mut end = BodyEnd::whole(&bytes);
assert_eq!(end.exchange.exact, Some(150_000));
assert_eq!(end.exchange.hand_over(Duration::from_secs(60)), Ok(false));
assert!(!end.is_end_stream());
let mut at = 0;
for len in [UPLOAD_FRAME, UPLOAD_FRAME, 150_000 - 2 * UPLOAD_FRAME] {
assert!(!end.exchange.lock().ended);
let frame = next_frame(&mut end).await.unwrap().unwrap();
assert_eq!(frame.len(), len);
assert_eq!(frame.as_ptr(), bytes[at..].as_ptr());
at += len;
}
assert!(end.exchange.lock().ended);
assert!(end.is_end_stream());
assert!(next_frame(&mut end).await.is_none());
let empty = BodyEnd::whole(&Bytes::new());
assert_eq!(empty.exchange.exact, Some(0));
assert!(!empty.is_end_stream());
assert_eq!(empty.exchange.hand_over(Duration::from_secs(60)), Ok(true));
assert!(empty.is_end_stream());
assert!(empty.exchange.lock().ended);
});
}
#[test]
fn a_body_closed_after_the_hand_over_ends_at_the_first_poll() {
rt::block_on(async {
let (mut end, mut writer) = channel();
assert_eq!(end.exchange.hand_over(Duration::from_secs(60)), Ok(false));
end.exchange.lock().closed = true;
assert!(!end.is_end_stream());
assert!(next_frame(&mut end).await.is_none());
assert!(end.is_end_stream());
futures_lite::io::AsyncWriteExt::close(&mut writer)
.await
.unwrap();
});
}
#[test]
fn a_lazy_timer_fires_at_the_end_it_was_moved_to() {
rt::block_on(async {
let mut timer = None;
let started = Instant::now();
let mut end = started + Duration::from_millis(50);
std::future::poll_fn(|cx| {
if poll_until(&mut timer, cx, end).is_pending() {
end = started + Duration::from_millis(120);
return Poll::Pending;
}
Poll::Ready(())
})
.await;
assert!(started.elapsed() >= Duration::from_millis(120));
assert!(timer.is_none());
});
}
#[test]
fn a_bearer_token_is_token68_and_sensitive() {
let token = |token: &str| BearerToken {
token: token.to_owned(),
};
for good in ["abc", "a-b.c_d~e+f/g", "dGVzdA==", "x="] {
assert!(is_token68(good), "{good}");
}
for bad in ["", "=", "a b", "a=b", "tök", "a\n", "a,b"] {
assert!(!is_token68(bad), "{bad:?}");
let err = merge_headers(&[], &[], None, Some(&token(bad))).unwrap_err();
let message = err.to_string();
assert!(message.contains("token68"), "{message}");
assert!(!message.contains(" "), "{message}");
if !bad.is_empty() && bad != "=" {
assert!(!message.contains(bad), "{message}");
}
}
let authorization = |headers: &[(HeaderName, HeaderValue)]| {
headers
.iter()
.find(|(name, _)| *name == hyper::header::AUTHORIZATION)
.map(|(_, value)| value.clone())
.unwrap()
};
let merged = merge_headers(&[], &[], None, Some(&token("t0k3n"))).unwrap();
let value = authorization(&merged);
assert_eq!(value, "Bearer t0k3n");
assert!(value.is_sensitive());
let auth = BasicAuth {
user: "u".into(),
password: "p".into(),
};
let merged = merge_headers(&[], &[], Some(&auth), None).unwrap();
assert!(authorization(&merged).is_sensitive());
let header = vec![("authorization".to_owned(), "Custom x".to_owned())];
let merged = merge_headers(&[], &header, None, None).unwrap();
assert!(authorization(&merged).is_sensitive());
let err = merge_headers(&[], &[], Some(&auth), Some(&token("t"))).unwrap_err();
assert!(err.to_string().contains("pass one of them"), "{err}");
assert!(err.to_string().contains("bearer token"), "{err}");
let err = merge_headers(&[], &header, None, Some(&token("t"))).unwrap_err();
assert!(err.to_string().contains("pass one of them"), "{err}");
assert!(err.to_string().contains("bearer token"), "{err}");
}
#[test]
fn bearer_token_debug_holds_no_token() {
let token = BearerToken {
token: "s3cret".into(),
};
let rendered = format!("{token:?}");
assert!(!rendered.contains("s3cret"), "{rendered}");
assert!(rendered.contains("redacted"), "{rendered}");
}
#[test]
fn a_fetcher_bearer_token_joins_the_header_list() {
let options = FetcherOptions {
bearer_token: Some(BearerToken {
token: "t0k3n".into(),
}),
..tls_options("https://example.com")
};
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
let authorization = |headers: &[(HeaderName, HeaderValue)]| {
headers
.iter()
.filter(|(name, _)| *name == hyper::header::AUTHORIZATION)
.map(|(_, value)| value.clone())
.collect::<Vec<_>>()
};
let held = authorization(&fetcher.inner.headers);
assert_eq!(held, ["Bearer t0k3n"]);
assert!(held[0].is_sensitive());
let extra = vec![("x-trace".to_owned(), "abc".to_owned())];
let merged = merge_headers(&fetcher.inner.headers, &extra, None, None).unwrap();
assert_eq!(authorization(&merged), ["Bearer t0k3n"]);
let auth = BasicAuth {
user: "u".into(),
password: "p".into(),
};
let merged = merge_headers(&fetcher.inner.headers, &[], Some(&auth), None).unwrap();
assert_eq!(authorization(&merged), ["Basic dTpw"]);
let token = BearerToken {
token: "other".into(),
};
let merged = merge_headers(&fetcher.inner.headers, &[], None, Some(&token)).unwrap();
assert_eq!(authorization(&merged), ["Bearer other"]);
let header = vec![("authorization".to_owned(), "Custom x".to_owned())];
let merged = merge_headers(&fetcher.inner.headers, &header, None, None).unwrap();
assert_eq!(authorization(&merged), ["Custom x"]);
}
#[test]
fn a_fetcher_bearer_token_is_refused_beside_another_credential_or_out_of_syntax() {
let token = |token: &str| {
Some(BearerToken {
token: token.to_owned(),
})
};
let beside_basic = FetcherOptions {
bearer_token: token("t0k3n"),
basic_auth: Some(BasicAuth {
user: "u".into(),
password: "p".into(),
}),
..tls_options("https://example.com")
};
let beside_header = FetcherOptions {
bearer_token: token("t0k3n"),
headers: vec![("authorization".into(), "Basic aaa".into())],
..tls_options("https://example.com")
};
for options in [beside_basic, beside_header] {
let err = rt::block_on(Fetcher::new(options)).unwrap_err();
let message = err.to_string();
assert!(message.contains("bearer token"), "{message}");
assert!(message.contains("pass one of them"), "{message}");
}
let options = FetcherOptions {
bearer_token: token("not a token"),
..tls_options("https://example.com")
};
let err = rt::block_on(Fetcher::new(options)).unwrap_err();
assert!(matches!(err, Error::Fetch(_)), "{err}");
let message = err.to_string();
assert!(message.contains("token68"), "{message}");
assert!(!message.contains("not a token"), "{message}");
}
#[test]
fn the_fetcher_cleartext_permission_admits_a_cleartext_mirror() {
let cleartext = "http://cleartext.example/repo";
let token = || {
Some(BearerToken {
token: "t0k3n".into(),
})
};
let options = FetcherOptions {
bearer_token: token(),
..tls_options(cleartext)
};
let err = rt::block_on(Fetcher::new(options)).unwrap_err();
let message = err.to_string();
assert!(message.contains("bearer token"), "{message}");
assert!(message.contains(cleartext), "{message}");
assert!(
message.contains("FetcherOptions::allow_cleartext_credentials"),
"{message}"
);
assert!(!message.contains("t0k3n"), "{message}");
let options = FetcherOptions {
bearer_token: token(),
allow_cleartext_credentials: true,
..tls_options(cleartext)
};
let fetcher = rt::block_on(Fetcher::new(options)).unwrap();
assert!(
fetcher.inner.headers.iter().any(
|(name, value)| name == hyper::header::AUTHORIZATION && value == "Bearer t0k3n"
)
);
let options = FetcherOptions {
basic_auth: Some(BasicAuth {
user: "u".into(),
password: "p".into(),
}),
allow_cleartext_credentials: true,
..tls_options(cleartext)
};
rt::block_on(Fetcher::new(options)).unwrap();
let options = FetcherOptions {
headers: vec![("cookie".into(), "session=1".into())],
allow_cleartext_credentials: true,
..tls_options(cleartext)
};
rt::block_on(Fetcher::new(options)).unwrap();
}
#[test]
fn fetcher_options_debug_holds_no_bearer_token() {
let options = FetcherOptions {
bearer_token: Some(BearerToken {
token: "s3cret".into(),
}),
..FetcherOptions::default()
};
let rendered = format!("{options:?}");
assert!(!rendered.contains("s3cret"), "{rendered}");
assert!(rendered.contains("redacted"), "{rendered}");
}
fn secret_headers() -> Vec<(String, String)> {
vec![
("Authorization".into(), "Basic val-QXZ-1".into()),
("proxy-authorization".into(), "Basic val-QXZ-2".into()),
("cookie".into(), "id=val-QXZ-3".into()),
("X-Trace".into(), "val-QXZ-4".into()),
]
}
const SECRET_HEADERS_SHOWN: &str = r#"[("Authorization", "<redacted>"), ("proxy-authorization", "<redacted>"), ("cookie", "<redacted>"), ("X-Trace", "<redacted>")]"#;
fn assert_no_header_value(rendered: &str) {
assert!(!rendered.contains("QXZ"), "{rendered}");
for (name, _) in secret_headers() {
let entry = format!(r#"("{name}", "<redacted>")"#);
assert!(rendered.contains(&entry), "{rendered}");
}
}
#[test]
fn fetcher_options_debug_holds_no_header_value() {
let options = FetcherOptions {
headers: secret_headers(),
..FetcherOptions::new("https://example.com/")
};
let rendered = format!("{options:?}");
assert_no_header_value(&rendered);
assert_eq!(
rendered,
format!(
"FetcherOptions {{ mirrors: [\"https://example.com/\"], \
headers: {SECRET_HEADERS_SHOWN}, basic_auth: None, bearer_token: None, \
allow_cleartext_credentials: false, \
tls: TlsOptions {{ roots: System, client_identity: None }}, \
proxy: Environment, http2: true, max_retries: 5, max_redirects: 10, \
max_outstanding: 8, connect_timeout: 30s, progress_timeout: 60s, \
low_speed: None, fetch_timeout: Some(300s) }}"
)
);
}
#[test]
fn fetch_request_debug_holds_no_header_value() {
let headers = secret_headers();
let request = FetchRequest {
headers: &headers,
..FetchRequest::path("summary")
};
let rendered = format!("{request:?}");
assert_no_header_value(&rendered);
assert_eq!(
rendered,
format!(
"FetchRequest {{ target: Path(\"summary\"), priority: Normal, \
validators: None, max_size: None, headers: {SECRET_HEADERS_SHOWN}, \
basic_auth: None, allow_cleartext_credentials: false }}"
)
);
}
#[test]
fn upload_request_debug_holds_no_header_value() {
let headers = secret_headers();
let request = UploadRequest {
headers: &headers,
..UploadRequest::path("objects", UploadBody::bytes(Vec::new()))
};
let rendered = format!("{request:?}");
assert_no_header_value(&rendered);
assert_eq!(
rendered,
format!(
"UploadRequest {{ target: Path(\"objects\"), method: Post, body: Bytes(0), \
priority: Normal, max_response: 2097152, headers: {SECRET_HEADERS_SHOWN}, \
basic_auth: None, bearer_token: None, allow_cleartext_credentials: false, \
response_timeout: None }}"
)
);
}
async fn fixed_header_peer() -> (Fetcher, u16) {
use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
let peer = rt::TcpListener::bind("127.0.0.1:0".parse().unwrap())
.await
.unwrap();
let port = peer.local_addr().unwrap().port();
drop(rt::spawn(async move {
while let Ok((mut stream, _peer)) = peer.accept().await {
let mut request = [0u8; 1024];
let _ = stream.read(&mut request).await;
let answer = "HTTP/1.1 200 OK\r\nSet-Cookie: a=val-QXZ-5\r\n\
Set-Cookie: b=val-QXZ-6\r\nContent-Type: text/val-QXZ-7\r\n\
Content-Length: 0\r\n\r\n";
let _ = stream.write_all(answer.as_bytes()).await;
let _ = stream.flush().await;
}
}));
let fetcher = Fetcher::new(FetcherOptions {
max_redirects: 0,
..direct_options(format!("http://127.0.0.1:{port}"))
})
.await
.unwrap();
(fetcher, port)
}
#[test]
fn uploaded_debug_holds_no_header_value() {
rt::block_on(async {
let (fetcher, port) = fixed_header_peer().await;
let uploaded = within(
Duration::from_secs(5),
fetcher.upload(UploadRequest::path(
"objects",
UploadBody::bytes(Vec::new()),
)),
)
.await
.expect("the upload ends within the limit")
.unwrap();
let rendered = format!("{uploaded:?}");
assert!(!rendered.contains("QXZ"), "{rendered}");
let headers = r#"[("set-cookie", "<redacted>"), ("set-cookie", "<redacted>"), ("content-type", "<redacted>"), ("content-length", "<redacted>")]"#;
assert_eq!(
rendered,
format!(
"Uploaded {{ status: 200, headers: {headers}, \
url: \"http://127.0.0.1:{port}/objects\", body: Body {{ \
protocol: Http11, content_length: Some(0), received: 0, .. }} }}"
)
);
});
}
#[test]
fn uploaded_debug_holds_no_url_query() {
rt::block_on(async {
let (fetcher, port) = fixed_header_peer().await;
let url = format!("http://127.0.0.1:{port}/objects?X-Amz-Signature=sig-QXZ");
let uploaded = within(
Duration::from_secs(5),
fetcher.upload(UploadRequest::url(&url, UploadBody::bytes(Vec::new()))),
)
.await
.expect("the upload ends within the limit")
.unwrap();
assert_eq!(uploaded.url(), url);
let rendered = format!("{uploaded:?}");
assert!(!rendered.contains("QXZ"), "{rendered}");
assert!(
rendered.contains(&format!(
"url: \"http://127.0.0.1:{port}/objects?<redacted>\""
)),
"{rendered}"
);
});
}
#[test]
fn redacted_url_debug_quotes_as_str_debug() {
let texts = [
"https://example.com/it's",
"a\"b\\c",
"line\nnext\ttab\u{7f}",
"caf\u{e9}",
"\u{301}start",
"mid\u{301}dle",
"zero\u{200b}width",
"emoji \u{1f980}",
"",
];
for text in texts {
let expected = format!("{text:?}");
assert_eq!(format!("{:?}", RedactedUrl::url(text)), expected);
assert_eq!(format!("{:?}", RedactedUrl::path(text)), expected);
}
}
#[test]
fn redacted_url_debug_removes_userinfo_query_and_fragment() {
let urls = [
("https://example.com/repo", "https://example.com/repo"),
(
"https://user:pw@example.com/repo",
"https://example.com/repo",
),
(
"https://u:pa#ss@example.com/repo",
"https://example.com/repo",
),
(
"https://u:pa?ss@example.com/repo",
"https://example.com/repo",
),
(
"https://u:p/ss@example.com/repo",
"https://example.com/repo",
),
("https://example.com/a@b/c", "https://b/c"),
(
"https://example.com/s?a=1",
"https://example.com/s?<redacted>",
),
(
"https://example.com/s#f",
"https://example.com/s#<redacted>",
),
(
"https://u:p@example.com/s?a=1#f",
"https://example.com/s?<redacted>#<redacted>",
),
("https://example.com/s?", "https://example.com/s?<redacted>"),
("https://example.com/s#", "https://example.com/s#<redacted>"),
(
"https://example.com/s?#",
"https://example.com/s?<redacted>#<redacted>",
),
("https://example.com/s?a=x@y&b=1", "https://y&b=1"),
("example.com/s?a=1", "example.com/s?<redacted>"),
("u:p@example.com/s", "example.com/s"),
("u:a://b@h/p", "h/p"),
("https://[::1]:8/p?q", "https://[::1]:8/p?<redacted>"),
("https://h/p#a?b", "https://h/p#<redacted>"),
("é@é?é#é", "é?<redacted>#<redacted>"),
];
for (url, shown) in urls {
assert_eq!(
format!("{:?}", RedactedUrl::url(url)),
format!("\"{shown}\"")
);
}
let paths = [
("objects/ab", "objects/ab"),
("a@b/c", "a@b/c"),
("summary?sig=1", "summary?<redacted>"),
("summary#f", "summary#<redacted>"),
("summary?sig=1#f", "summary?<redacted>#<redacted>"),
];
for (path, shown) in paths {
assert_eq!(
format!("{:?}", RedactedUrl::path(path)),
format!("\"{shown}\"")
);
}
}
#[test]
fn target_debug_redacts_url_and_path() {
let url = Target::Url("https://u:pw-QXZ@h/p?t=QXZ#QXZ");
let path = Target::Path("summary?sig=QXZ#QXZ");
assert_eq!(
format!("{url:?}"),
r#"Url("https://h/p?<redacted>#<redacted>")"#
);
assert_eq!(
format!("{path:?}"),
r#"Path("summary?<redacted>#<redacted>")"#
);
assert_eq!(
format!("{url:#?}"),
"Url(\n \"https://h/p?<redacted>#<redacted>\",\n)"
);
assert_eq!(
format!("{path:#?}"),
"Path(\n \"summary?<redacted>#<redacted>\",\n)"
);
let path_query = Target::PathQuery {
path: "p?QXZ",
query: "pattern=QXZ",
};
assert_eq!(
format!("{path_query:?}"),
r#"PathQuery { path: "p?<redacted>", query: "<redacted>" }"#
);
let rendered = format!("{:?}", FetchRequest::path_query("refs/v1", "pattern=QXZ"));
assert!(!rendered.contains("QXZ"), "{rendered}");
assert!(
rendered.contains(r#"target: PathQuery { path: "refs/v1", query: "<redacted>" }"#),
"{rendered}"
);
}
const SECRET_URL: &str =
"https://user-QXZ:pw-QXZ@example.com/repo?X-Amz-Signature=sig-QXZ#frag-QXZ";
#[test]
fn fetcher_options_debug_holds_no_mirror_secret() {
let options = FetcherOptions {
mirrors: vec![SECRET_URL.into(), "https://mirror.example.com/os".into()],
..FetcherOptions::default()
};
let rendered = format!("{options:?}");
assert!(!rendered.contains("QXZ"), "{rendered}");
assert!(
rendered.contains(
r#"mirrors: ["https://example.com/repo?<redacted>#<redacted>", "https://mirror.example.com/os"]"#
),
"{rendered}"
);
}
#[test]
fn fetch_request_debug_holds_no_target_secret() {
let rendered = format!("{:?}", FetchRequest::url(SECRET_URL));
assert!(!rendered.contains("QXZ"), "{rendered}");
assert!(
rendered.contains(r#"target: Url("https://example.com/repo?<redacted>#<redacted>")"#),
"{rendered}"
);
let rendered = format!("{:?}", FetchRequest::path("summary?sig=QXZ#f"));
assert!(!rendered.contains("QXZ"), "{rendered}");
assert!(
rendered.contains(r#"target: Path("summary?<redacted>#<redacted>")"#),
"{rendered}"
);
}
#[test]
fn upload_request_debug_holds_no_target_secret() {
let request = UploadRequest::url(SECRET_URL, UploadBody::bytes(Vec::new()));
let rendered = format!("{request:?}");
assert!(!rendered.contains("QXZ"), "{rendered}");
assert!(
rendered.contains(r#"target: Url("https://example.com/repo?<redacted>#<redacted>")"#),
"{rendered}"
);
}
}