#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![doc = "External curl acquisition adapter with explicit bounded policy."]
#![doc = ""]
#![doc = "Implements `eggup-acquisition::AcquisitionTransport` without an embedded"]
#![doc = "HTTP/TLS stack. See `README.md` for the single policy configuration point."]
#![doc = ""]
#![doc = "Transport fallback (curl <-> Eggfetch for the same exact URL) lives in"]
#![doc = "`eggup-acquisition::ComposedTransport` and is never release/source fallback."]
use eggup_acquisition::{
AcquisitionError, AcquisitionRequest, AcquisitionTransport, CancelFlag, FetchLimits,
FetchOutcome,
};
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(120);
pub const DEFAULT_MAX_REDIRECTS: usize = 10;
pub const MAX_USER_AGENT_BYTES: usize = 512;
const MAX_WRITE_OUT_BYTES: u64 = 64;
const POLL_INTERVAL: Duration = Duration::from_millis(5);
#[derive(Debug, Clone, Default)]
pub enum CurlProxy {
#[default]
Disabled,
FromEnvironment,
Custom(Vec<(String, String)>),
}
#[derive(Debug, Clone)]
pub struct CurlConfig {
pub connect_timeout: Duration,
pub total_timeout: Duration,
pub max_redirects: usize,
pub follow_redirects: bool,
pub allowed_protocols: Vec<String>,
pub proxy: CurlProxy,
}
impl Default for CurlConfig {
fn default() -> Self {
Self {
connect_timeout: DEFAULT_CONNECT_TIMEOUT,
total_timeout: DEFAULT_TOTAL_TIMEOUT,
max_redirects: DEFAULT_MAX_REDIRECTS,
follow_redirects: true,
allowed_protocols: vec!["http".to_string(), "https".to_string()],
proxy: CurlProxy::Disabled,
}
}
}
impl CurlConfig {
pub fn strict() -> Self {
Self::default()
}
pub fn timeouts(mut self, connect: Duration, total: Duration) -> Self {
self.connect_timeout = connect;
self.total_timeout = total;
self
}
pub fn max_redirects(mut self, max: usize) -> Self {
self.max_redirects = max;
self
}
pub fn follow_redirects(mut self, follow: bool) -> Self {
self.follow_redirects = follow;
self
}
pub fn allowed_protocols(mut self, protocols: Vec<String>) -> Self {
self.allowed_protocols = protocols;
self
}
pub fn proxy(mut self, proxy: CurlProxy) -> Self {
self.proxy = proxy;
self
}
pub fn effective_timeouts(&self, limits: FetchLimits) -> (Duration, Duration) {
limits.effective(self.connect_timeout, self.total_timeout)
}
fn validate(&self) -> Result<(), AcquisitionError> {
if self.connect_timeout.is_zero() || self.total_timeout.is_zero() {
return Err(AcquisitionError::InvalidInput(bound(
"adapter timeouts must be positive".to_string(),
)));
}
if self.connect_timeout > self.total_timeout {
return Err(AcquisitionError::InvalidInput(bound(
"adapter connect timeout must not exceed total timeout".to_string(),
)));
}
if self.max_redirects > 50 {
return Err(AcquisitionError::InvalidInput(bound(
"adapter redirect bound out of range".to_string(),
)));
}
if self.allowed_protocols.is_empty() || self.allowed_protocols.len() > 8 {
return Err(AcquisitionError::InvalidInput(bound(
"adapter protocol list out of range".to_string(),
)));
}
for p in &self.allowed_protocols {
if p.is_empty() || p.len() > 16 || !p.chars().all(|c| c.is_ascii_alphanumeric()) {
return Err(AcquisitionError::InvalidInput(bound(
"adapter protocol names must be alphanumeric".to_string(),
)));
}
}
Ok(())
}
}
#[derive(Debug)]
pub struct CurlTransport {
executable: PathBuf,
config: CurlConfig,
user_agent: Option<String>,
}
impl CurlTransport {
pub fn with_executable(
executable: impl Into<PathBuf>,
config: CurlConfig,
) -> Result<Self, AcquisitionError> {
config.validate()?;
let executable = executable.into();
if executable.as_os_str().is_empty() {
return Err(AcquisitionError::InvalidInput(bound(
"curl executable path must not be empty".to_string(),
)));
}
Ok(Self {
executable,
config,
user_agent: None,
})
}
pub fn with_executable_and_user_agent(
executable: impl Into<PathBuf>,
config: CurlConfig,
user_agent: impl Into<String>,
) -> Result<Self, AcquisitionError> {
config.validate()?;
let executable = executable.into();
if executable.as_os_str().is_empty() {
return Err(AcquisitionError::InvalidInput(bound(
"curl executable path must not be empty".to_string(),
)));
}
let user_agent = user_agent.into();
validate_user_agent(&user_agent)?;
Ok(Self {
executable,
config,
user_agent: Some(user_agent),
})
}
pub fn executable(&self) -> &Path {
&self.executable
}
pub fn config(&self) -> &CurlConfig {
&self.config
}
pub fn user_agent(&self) -> Option<&str> {
self.user_agent.as_deref()
}
}
fn validate_user_agent(user_agent: &str) -> Result<(), AcquisitionError> {
if user_agent.is_empty() {
return Err(AcquisitionError::InvalidInput(bound(
"user agent must not be empty".to_string(),
)));
}
if user_agent.len() > MAX_USER_AGENT_BYTES {
return Err(AcquisitionError::InvalidInput(bound(
"user agent exceeds the maximum length".to_string(),
)));
}
let mut chars = user_agent.chars();
let first = chars.next();
let last = user_agent.chars().next_back();
if first == Some(' ') || last == Some(' ') {
return Err(AcquisitionError::InvalidInput(bound(
"user agent must not begin or end with a space".to_string(),
)));
}
for ch in user_agent.chars() {
let permitted = match ch {
'\u{21}'..='\u{7E}' => true,
'\u{20}' => true,
'\u{A0}'..='\u{10FFFF}' => true,
_ => false,
};
if !permitted {
return Err(AcquisitionError::InvalidInput(bound(
"user agent must not contain control characters".to_string(),
)));
}
}
Ok(())
}
impl AcquisitionTransport for CurlTransport {
fn fetch_metadata(
&self,
request: &AcquisitionRequest,
limits: FetchLimits,
cancel: &CancelFlag,
) -> Result<FetchOutcome<eggup_acquisition::MetadataBytes>, AcquisitionError> {
limits.validate()?;
self.config.validate()?;
if cancel.is_cancelled() {
return Err(AcquisitionError::Cancelled);
}
let (eff_connect, eff_total) = self.config.effective_timeouts(limits);
let max = limits.max_metadata_bytes;
let parent = std::env::temp_dir();
let _ = fs::create_dir_all(&parent);
let (mut file, tmp) =
eggup_acquisition::__acquire_exclusive_temp(&parent, "eggup-curl-meta")?;
struct Guard {
path: PathBuf,
disarm: bool,
}
impl Drop for Guard {
fn drop(&mut self) {
if !self.disarm {
eggup_acquisition::__remove_owned_temp(&self.path);
}
}
}
let mut guard = Guard {
path: tmp.clone(),
disarm: false,
};
let outcome = run_curl_to_file(
&self.executable,
&self.config,
self.user_agent.as_deref(),
request,
&tmp,
&mut file,
max as u64,
eff_connect,
eff_total,
cancel,
)?;
match outcome {
CurlOutcome::Success => {
if cancel.is_cancelled() {
return Err(AcquisitionError::Cancelled);
}
let bytes = fs::read(&tmp)
.map_err(|e| AcquisitionError::__adapter_io("reading part file", e))?;
eggup_acquisition::__remove_owned_temp(&tmp);
guard.disarm = true;
if bytes.len() > max {
return Err(AcquisitionError::TooLarge { limit: max as u64 });
}
Ok(FetchOutcome::Success(
eggup_acquisition::__adapter_metadata(bytes),
))
}
CurlOutcome::NotFound => {
eggup_acquisition::__remove_owned_temp(&tmp);
guard.disarm = true;
Ok(FetchOutcome::NotFound)
}
}
}
fn fetch_artifact(
&self,
request: &AcquisitionRequest,
dest: &Path,
limits: FetchLimits,
cancel: &CancelFlag,
) -> Result<FetchOutcome<eggup_acquisition::ArtifactEvidence>, AcquisitionError> {
limits.validate()?;
self.config.validate()?;
if cancel.is_cancelled() {
return Err(AcquisitionError::Cancelled);
}
let parent = dest.parent().ok_or_else(|| {
AcquisitionError::InvalidInput(bound("destination has no parent".into()))
})?;
let parent_meta = fs::symlink_metadata(parent)
.map_err(|e| AcquisitionError::__adapter_io("reading artifact parent", e))?;
if !parent_meta.is_dir() || parent_meta.file_type().is_symlink() {
return Err(AcquisitionError::InvalidInput(bound(
"artifact parent must be an existing real directory".into(),
)));
}
if fs::symlink_metadata(dest).is_ok() {
return Err(AcquisitionError::InvalidInput(bound(
"artifact destination already exists; refusing to overwrite".into(),
)));
}
let (eff_connect, eff_total) = self.config.effective_timeouts(limits);
let max_artifact = limits.max_artifact_bytes;
let (mut file, tmp) = eggup_acquisition::__acquire_exclusive_temp(parent, "eggup-curl")?;
struct Guard {
path: PathBuf,
disarm: bool,
}
impl Drop for Guard {
fn drop(&mut self) {
if !self.disarm {
eggup_acquisition::__remove_owned_temp(&self.path);
}
}
}
let mut guard = Guard {
path: tmp.clone(),
disarm: false,
};
let outcome = run_curl_to_file(
&self.executable,
&self.config,
self.user_agent.as_deref(),
request,
&tmp,
&mut file,
max_artifact,
eff_connect,
eff_total,
cancel,
)?;
match outcome {
CurlOutcome::NotFound => {
eggup_acquisition::__remove_owned_temp(&tmp);
guard.disarm = true;
Ok(FetchOutcome::NotFound)
}
CurlOutcome::Success => {
if cancel.is_cancelled() {
return Err(AcquisitionError::Cancelled);
}
let size = fs::metadata(&tmp)
.map_err(|e| AcquisitionError::__adapter_io("reading part file", e))?
.len();
if size > max_artifact {
eggup_acquisition::__remove_owned_temp(&tmp);
guard.disarm = true;
return Err(AcquisitionError::TooLarge {
limit: max_artifact,
});
}
match eggup_acquisition::__promote_no_clobber(&tmp, dest) {
Ok(()) => {
guard.disarm = true;
Ok(FetchOutcome::Success(
eggup_acquisition::__adapter_artifact(size),
))
}
Err(e) => {
eggup_acquisition::__remove_owned_temp(&tmp);
guard.disarm = true;
Err(e)
}
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CurlOutcome {
Success,
NotFound,
}
pub fn discover_curl_executable() -> Result<PathBuf, AcquisitionError> {
discover_in(std::env::var_os("PATH"))
}
fn discover_in(path_var: Option<std::ffi::OsString>) -> Result<PathBuf, AcquisitionError> {
let path_var = path_var
.ok_or_else(|| AcquisitionError::__adapter_unavailable("curl not found: PATH is unset"))?;
#[cfg(windows)]
let names = vec!["curl", "curl.exe"];
#[cfg(not(windows))]
let names = vec!["curl"];
for dir in std::env::split_paths(&path_var) {
if dir.as_os_str().is_empty() {
continue;
}
for name in &names {
let candidate = dir.join(name);
if let Ok(meta) = fs::symlink_metadata(&candidate) {
if meta.is_file() {
return Ok(candidate);
}
}
}
}
Err(AcquisitionError::__adapter_unavailable(
"curl not found on PATH",
))
}
fn bound(s: String) -> String {
eggup_acquisition::__adapter_bound_detail(s)
}
fn spawn_failure_detail(redacted: &str, error: &std::io::Error) -> String {
let kind = format!("{:?}", error.kind());
match error.raw_os_error() {
Some(code) => format!("curl spawn failed for {redacted}: {kind} (os error {code})"),
None => format!("curl spawn failed for {redacted}: {kind}"),
}
}
fn duration_decimal_seconds(d: Duration) -> Result<String, AcquisitionError> {
if d.is_zero() {
return Err(AcquisitionError::InvalidInput(bound(
"duration must be positive".to_string(),
)));
}
let total_micros = d.as_micros();
if total_micros == 0 {
return Err(AcquisitionError::InvalidInput(bound(
"duration below microsecond precision cannot be represented without widening"
.to_string(),
)));
}
let secs = total_micros / 1_000_000;
let micros = total_micros % 1_000_000;
if micros == 0 {
Ok(secs.to_string())
} else {
let mut frac = format!("{:06}", micros);
while frac.ends_with('0') {
frac.pop();
}
Ok(format!("{secs}.{frac}"))
}
}
fn proxy_env_snapshot(proxy: &CurlProxy) -> Vec<(String, String)> {
const KEYS: &[&str] = &[
"HTTP_PROXY",
"http_proxy",
"HTTPS_PROXY",
"https_proxy",
"ALL_PROXY",
"all_proxy",
"NO_PROXY",
"no_proxy",
];
match proxy {
CurlProxy::Disabled => Vec::new(),
CurlProxy::FromEnvironment => KEYS
.iter()
.filter_map(|k| {
std::env::var_os(k).map(|v| ((*k).to_string(), v.to_string_lossy().into_owned()))
})
.collect(),
CurlProxy::Custom(pairs) => pairs.clone(),
}
}
fn redirect_protocols(config: &CurlConfig, url: &str) -> Vec<String> {
let starts_https = url
.split_once("://")
.is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("https"));
if !starts_https {
return config.allowed_protocols.clone();
}
let narrowed: Vec<String> = config
.allowed_protocols
.iter()
.filter(|proto| !proto.eq_ignore_ascii_case("http"))
.cloned()
.collect();
if narrowed.is_empty() {
return config.allowed_protocols.clone();
}
narrowed
}
#[allow(clippy::too_many_arguments)]
fn build_curl_args(
config: &CurlConfig,
user_agent: Option<&str>,
url: &str,
max_bytes: u64,
eff_connect: Duration,
eff_total: Duration,
) -> Result<Vec<String>, AcquisitionError> {
if let Some(agent) = user_agent {
validate_user_agent(agent)?;
}
let mut args: Vec<String> = vec![
"--disable".to_string(),
"--silent".to_string(),
"--show-error".to_string(),
"--no-progress-meter".to_string(),
];
if config.follow_redirects {
args.push("--location".to_string());
args.push("--max-redirs".to_string());
args.push(config.max_redirects.to_string());
}
let connect_arg = duration_decimal_seconds(eff_connect)?;
let total_arg = duration_decimal_seconds(eff_total)?;
args.push("--connect-timeout".to_string());
args.push(connect_arg);
args.push("--max-time".to_string());
args.push(total_arg);
args.push("--max-filesize".to_string());
args.push(max_bytes.to_string());
if !config.allowed_protocols.is_empty() {
let list = format!("={}", config.allowed_protocols.join(","));
args.push("--proto".to_string());
args.push(list);
args.push("--proto-redir".to_string());
args.push(format!("={}", redirect_protocols(config, url).join(",")));
}
if matches!(proxy_kind(config), ProxyKind::Disabled) {
args.push("--noproxy".to_string());
args.push("*".to_string());
}
if let Some(agent) = user_agent {
args.push("--user-agent".to_string());
args.push(agent.to_string());
}
args.push("--output".to_string());
args.push("-".to_string());
args.push("--write-out".to_string());
args.push("%{stderr}%{http_code}".to_string());
args.push("--".to_string());
args.push(url.to_string());
Ok(args)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProxyKind {
Disabled,
Enabled,
}
fn proxy_kind(config: &CurlConfig) -> ProxyKind {
match &config.proxy {
CurlProxy::Disabled => ProxyKind::Disabled,
CurlProxy::FromEnvironment | CurlProxy::Custom(_) => ProxyKind::Enabled,
}
}
#[allow(clippy::too_many_arguments)]
fn run_curl_to_file(
executable: &Path,
config: &CurlConfig,
user_agent: Option<&str>,
request: &AcquisitionRequest,
output: &Path,
output_file: &mut File,
max_bytes: u64,
eff_connect: Duration,
eff_total: Duration,
cancel: &CancelFlag,
) -> Result<CurlOutcome, AcquisitionError> {
let url = request.url().to_string();
let redacted = request.redacted();
let args = build_curl_args(config, user_agent, &url, max_bytes, eff_connect, eff_total)?;
let proxy_env = proxy_env_snapshot(&config.proxy);
let start = Instant::now();
let deadline = start + eff_total;
let owned_file = output_file
.try_clone()
.map_err(|e| AcquisitionError::__adapter_io("cloning owned output handle", e))?;
let mut cmd = Command::new(executable);
cmd.args(&args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.env_clear();
for (k, v) in &proxy_env {
cmd.env(k, v);
}
let mut child = cmd.spawn().map_err(|e| {
AcquisitionError::__adapter_unavailable(spawn_failure_detail(&redacted, &e))
})?;
let stdout = child.stdout.take().expect("piped stdout");
let mut owned_file = owned_file;
let overflow = Arc::new(AtomicBool::new(false));
let overflow_reader = Arc::clone(&overflow);
let body_reader = std::thread::spawn(move || {
use std::io::{Read, Write};
let mut reader = stdout.take(max_bytes.saturating_add(1));
let mut written = 0u64;
let mut buf = [0u8; 16 * 1024];
loop {
let n = reader.read(&mut buf).map_err(|_| ())?;
if n == 0 {
break;
}
written = written.saturating_add(n as u64);
if written > max_bytes {
overflow_reader.store(true, Ordering::Release);
}
owned_file.write_all(&buf[..n]).map_err(|_| ())?;
}
owned_file.flush().map_err(|_| ())?;
Ok::<u64, ()>(written)
});
let stderr = child.stderr.take().expect("piped stderr");
let status_reader = std::thread::spawn(move || {
use std::io::Read;
let mut reader = stderr;
let mut kept = Vec::with_capacity(MAX_WRITE_OUT_BYTES as usize);
let mut buf = [0u8; 128];
loop {
let n = reader.read(&mut buf).map_err(|_| ())?;
if n == 0 {
break;
}
let room = (MAX_WRITE_OUT_BYTES as usize).saturating_sub(kept.len());
kept.extend_from_slice(&buf[..n.min(room)]);
}
Ok::<Vec<u8>, ()>(kept)
});
let exit_code: Option<i32> = loop {
if overflow.load(Ordering::Acquire) {
let _ = child.kill();
let _ = child.wait();
let _ = body_reader.join();
let _ = status_reader.join();
eggup_acquisition::__remove_owned_temp(output);
return Err(AcquisitionError::TooLarge { limit: max_bytes });
}
if cancel.is_cancelled() {
let _ = child.kill();
let _ = child.wait();
let _ = body_reader.join();
let _ = status_reader.join();
eggup_acquisition::__remove_owned_temp(output);
return Err(AcquisitionError::Cancelled);
}
match child.try_wait() {
Ok(Some(status)) => break status.code(),
Ok(None) => {
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
let _ = body_reader.join();
let _ = status_reader.join();
eggup_acquisition::__remove_owned_temp(output);
return Err(AcquisitionError::Timeout { phase: "total" });
}
std::thread::sleep(POLL_INTERVAL);
}
Err(e) => {
let _ = child.kill();
let _ = child.wait();
let _ = body_reader.join();
let _ = status_reader.join();
eggup_acquisition::__remove_owned_temp(output);
return Err(AcquisitionError::__adapter_io("waiting for curl", e));
}
}
};
let _ = child.wait();
let bytes_written = body_reader
.join()
.map_err(|_| {
AcquisitionError::__adapter_io(
"joining curl body reader",
std::io::Error::other("curl body reader failed"),
)
})?
.map_err(|_| {
AcquisitionError::__adapter_io(
"writing curl body",
std::io::Error::other("writing curl body failed"),
)
})?;
if bytes_written > max_bytes {
eggup_acquisition::__remove_owned_temp(output);
return Err(AcquisitionError::TooLarge { limit: max_bytes });
}
output_file
.flush()
.map_err(|e| AcquisitionError::__adapter_io("flushing owned output", e))?;
let code_bytes = status_reader
.join()
.map_err(|_| {
AcquisitionError::__adapter_io(
"joining curl status reader",
std::io::Error::other("curl status reader failed"),
)
})?
.map_err(|_| {
AcquisitionError::__adapter_io(
"reading curl status",
std::io::Error::other("reading curl status failed"),
)
})?;
classify_curl_result(
exit_code,
&code_bytes,
output,
&redacted,
start,
eff_connect,
eff_total,
max_bytes,
)
}
#[allow(clippy::too_many_arguments)]
fn classify_curl_result(
exit_code: Option<i32>,
code_bytes: &[u8],
output: &Path,
redacted: &str,
start: Instant,
eff_connect: Duration,
eff_total: Duration,
max_bytes: u64,
) -> Result<CurlOutcome, AcquisitionError> {
let elapsed = start.elapsed();
let code_text = String::from_utf8_lossy(code_bytes).trim().to_string();
let http_code: Option<u16> = code_text.parse().ok();
let tolerance = POLL_INTERVAL + Duration::from_millis(5);
match exit_code {
Some(28) => {
let phase = if eff_connect < eff_total && elapsed <= eff_connect + tolerance {
"connect"
} else {
"total"
};
return Err(AcquisitionError::Timeout { phase });
}
Some(63) => {
eggup_acquisition::__remove_owned_temp(output);
return Err(AcquisitionError::TooLarge { limit: max_bytes });
}
Some(0) => {}
failure @ (Some(_) | None) => {
eggup_acquisition::__remove_owned_temp(output);
return Err(AcquisitionError::Transport(bound(format!(
"curl transfer failed (exit {}) for {redacted}",
failure.map_or_else(|| "unknown".to_string(), |code| code.to_string())
))));
}
}
match http_code {
Some(200..=299) => Ok(CurlOutcome::Success),
Some(404) => Ok(CurlOutcome::NotFound),
Some(status) => {
eggup_acquisition::__remove_owned_temp(output);
Err(AcquisitionError::Transport(bound(format!(
"HTTP {status} from {redacted}"
))))
}
None => {
eggup_acquisition::__remove_owned_temp(output);
Err(AcquisitionError::Transport(bound(format!(
"curl status capture failed for {redacted}"
))))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use eggup_acquisition::{FixtureResponse, FixtureTransport};
#[cfg(not(windows))]
use std::io::{Read, Write};
#[cfg(not(windows))]
use std::net::TcpListener;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
#[cfg(not(windows))]
use std::thread;
#[test]
fn exit_28_is_labelled_total_when_connect_and_total_ceilings_coincide() {
let dir = temp_dir("curl-phase");
let output = dir.join("body");
std::fs::write(&output, b"partial").unwrap();
let timed_out = |eff_connect: Duration, elapsed: Duration| {
let start = Instant::now() - elapsed;
match classify_curl_result(
Some(28),
b"",
&output,
"https://example.com/app",
start,
eff_connect,
Duration::from_secs(5),
1024,
) {
Err(AcquisitionError::Timeout { phase }) => phase,
other => panic!("expected a timeout, got {other:?}"),
}
};
let equal = Duration::from_secs(1);
assert_eq!(
timed_out(equal, Duration::from_secs(5)),
"total",
"coincident ceilings must not label a total timeout as connect"
);
assert_eq!(
timed_out(Duration::from_secs(1), Duration::from_millis(1)),
"connect"
);
assert_eq!(
timed_out(Duration::from_secs(1), Duration::from_secs(5)),
"total"
);
}
#[test]
fn diagnostic_bound_never_splits_multibyte_code_points() {
for ch in ["é", "€", "🦀"] {
let prefix = "x".repeat(511);
let bounded = bound(format!("{prefix}{ch}tail"));
assert_eq!(bounded, prefix);
assert!(bounded.len() <= 512);
}
}
fn req(url: &str) -> AcquisitionRequest {
AcquisitionRequest::new(url).unwrap()
}
fn limits() -> FetchLimits {
FetchLimits {
max_metadata_bytes: 64 * 1024,
max_artifact_bytes: 256 * 1024,
connect_timeout: Duration::from_secs(2),
total_timeout: Duration::from_secs(10),
}
}
fn temp_dir(prefix: &str) -> PathBuf {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let p = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()));
let _ = fs::create_dir_all(&p);
p
}
fn real_curl() -> Option<PathBuf> {
discover_curl_executable().ok()
}
fn require_curl_executable() -> PathBuf {
match real_curl() {
Some(exe) => exe,
None => panic!(
"no `curl` executable was discoverable on PATH. This test drives the real curl \
subprocess and has nothing to assert without one. Install curl (for example \
`brew install curl`) or put a curl executable on PATH, then re-run \
`cargo test -p eggup-curl`."
),
}
}
fn require_transport() -> CurlTransport {
let exe = require_curl_executable();
CurlTransport::with_executable(exe, CurlConfig::strict())
.expect("strict curl transport must build from a discovered curl executable")
}
#[cfg(not(windows))]
fn serve_once(
status: u16,
headers: Vec<(String, String)>,
body: Vec<u8>,
stall_before_body_ms: u64,
abort_after_headers: bool,
) -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let addr = listener.local_addr().unwrap();
thread::spawn(move || {
if let Ok((mut stream, _)) = listener.accept() {
stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
let mut buf = [0u8; 8192];
let _ = stream.read(&mut buf);
let reason = match status {
200 => "OK",
302 => "Found",
404 => "Not Found",
500 => "Internal Server Error",
_ => "OK",
};
let mut head = format!("HTTP/1.1 {status} {reason}\r\n");
for (k, v) in headers {
head.push_str(&format!("{k}: {v}\r\n"));
}
head.push_str("Connection: close\r\n\r\n");
let _ = stream.write_all(head.as_bytes());
if abort_after_headers {
return;
}
if stall_before_body_ms > 0 {
thread::sleep(Duration::from_millis(stall_before_body_ms));
}
let _ = stream.write_all(&body);
}
});
format!("http://{addr}")
}
#[cfg(not(windows))]
fn ok_server(body: Vec<u8>) -> String {
serve_once(
200,
vec![
("Content-Length".into(), body.len().to_string()),
("Content-Type".into(), "application/octet-stream".into()),
],
body,
0,
false,
)
}
#[cfg(not(windows))]
fn serve_once_recording_head(status: u16, body: Vec<u8>, record: &Path) -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let addr = listener.local_addr().unwrap();
let record = record.to_path_buf();
thread::spawn(move || {
if let Ok((mut stream, _)) = listener.accept() {
stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
let mut buf = [0u8; 8192];
let read = stream.read(&mut buf).unwrap_or(0);
let _ = fs::write(&record, &buf[..read]);
let reason = match status {
200 => "OK",
404 => "Not Found",
500 => "Internal Server Error",
_ => "OK",
};
let mut head = format!("HTTP/1.1 {status} {reason}\r\n");
head.push_str(&format!("Content-Length: {}\r\n", body.len()));
head.push_str("Content-Type: application/octet-stream\r\n");
head.push_str("Connection: close\r\n\r\n");
let _ = stream.write_all(head.as_bytes());
let _ = stream.write_all(&body);
}
});
format!("http://{addr}")
}
#[cfg(unix)]
fn fake_curl_script(body: &[u8], code: &str, exit: i32, record_dir: &Path) -> PathBuf {
let dir = record_dir.to_path_buf();
let script = dir.join(format!(
"fake-curl-{}-{}.sh",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
let body_hex: String = body.iter().map(|b| format!("{b:02x}")).collect();
let content = format!(
"#!/bin/sh\n\
echo \"$@\" > \"{rec}/argv\"\n\
env > \"{rec}/env\"\n\
printf '{hex}' | xxd -r -p\n\\
printf '{code}' >&2\n\\
exit {exit}\n",
rec = dir.display(),
hex = body_hex,
code = code,
exit = exit,
);
fs::write(&script, content).unwrap();
let mut perms = fs::metadata(&script).unwrap().permissions();
perms.set_mode(0o700);
fs::set_permissions(&script, perms).unwrap();
script
}
#[test]
fn executable_selection_and_discovery_are_explicit() {
let err = CurlTransport::with_executable("", CurlConfig::strict()).unwrap_err();
assert!(matches!(err, AcquisitionError::InvalidInput(_)));
let bad = CurlConfig::strict().timeouts(Duration::ZERO, Duration::from_secs(1));
let err = CurlTransport::with_executable("/usr/bin/curl", bad).unwrap_err();
assert!(matches!(err, AcquisitionError::InvalidInput(_)));
if let Ok(path) = discover_curl_executable() {
assert!(fs::symlink_metadata(&path).unwrap().is_file());
}
let err = discover_in(Some("/nonexistent-eggup-curl-path-xyz".into())).unwrap_err();
assert!(matches!(err, AcquisitionError::Unavailable(_)));
assert!(err.is_unavailable());
let err = discover_in(None).unwrap_err();
assert!(matches!(err, AcquisitionError::Unavailable(_)));
}
#[test]
fn missing_executable_and_spawn_failure_are_unavailable() {
let t = CurlTransport::with_executable(
"/nonexistent-eggup-curl-binary-xyz",
CurlConfig::strict(),
)
.unwrap();
let err = t
.fetch_metadata(&req("http://127.0.0.1:1/x"), limits(), &CancelFlag::new())
.unwrap_err();
assert!(matches!(err, AcquisitionError::Unavailable(_)));
let dir = temp_dir("curl-unavail");
let dest = dir.join("app");
let err = t
.fetch_artifact(
&req("http://127.0.0.1:1/x"),
&dest,
limits(),
&CancelFlag::new(),
)
.unwrap_err();
assert!(matches!(err, AcquisitionError::Unavailable(_)));
assert!(!dest.exists());
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn spawn_failure_detail_names_the_os_cause_and_stays_unavailable() {
const MISSING: &str = "/nonexistent-eggup-curl-binary-m015";
const USERINFO: &str = "S3CR3T-USERINFO-9917";
const QUERY: &str = "TOKEN-QUERY-5523";
const FRAGMENT: &str = "FRAG-SENTINEL-7788";
let url = format!("https://user:{USERINFO}@example.com/x?token={QUERY}#{FRAGMENT}");
let observed = std::process::Command::new(MISSING)
.spawn()
.expect_err("spawning a missing executable must fail");
let expected_kind = format!("{:?}", observed.kind());
let t = CurlTransport::with_executable(MISSING, CurlConfig::strict()).unwrap();
let err = t
.fetch_metadata(&req(&url), limits(), &CancelFlag::new())
.unwrap_err();
assert!(matches!(err, AcquisitionError::Unavailable(_)));
assert!(err.is_unavailable());
let detail = match &err {
AcquisitionError::Unavailable(detail) => detail.clone(),
other => panic!("expected Unavailable, got {other:?}"),
};
assert!(
detail.contains(&expected_kind),
"detail does not name the ErrorKind {expected_kind}: {detail}"
);
match observed.raw_os_error() {
Some(code) => assert!(
detail.contains(&format!("os error {code}")),
"detail does not carry the raw OS code {code}: {detail}"
),
None => assert!(
!detail.contains("os error"),
"detail carries an OS code the platform did not produce: {detail}"
),
}
assert!(
detail.starts_with("curl spawn failed for "),
"detail lost the established prefix: {detail}"
);
let redacted = eggup_acquisition::redact_url(&url);
let expected_detail = match observed.raw_os_error() {
Some(code) => {
format!("curl spawn failed for {redacted}: {expected_kind} (os error {code})")
}
None => format!("curl spawn failed for {redacted}: {expected_kind}"),
};
assert_eq!(detail, expected_detail);
assert!(!detail.contains(USERINFO), "userinfo leaked: {detail}");
assert!(!detail.contains(QUERY), "query leaked: {detail}");
assert!(!detail.contains(FRAGMENT), "fragment leaked: {detail}");
assert!(detail.contains("<redacted>"), "redaction lost: {detail}");
assert!(detail.len() <= 512, "detail is not bounded: {detail}");
}
#[test]
#[cfg(not(windows))]
fn metadata_success_not_found_and_server_error() {
let t = require_transport();
let base = ok_server(b"hello-curl-meta".to_vec());
let out = t
.fetch_metadata(&req(&format!("{base}/meta")), limits(), &CancelFlag::new())
.unwrap();
assert_eq!(out.success().unwrap().bytes(), b"hello-curl-meta");
let base = serve_once(404, vec![], b"nope".to_vec(), 0, false);
let out = t
.fetch_metadata(&req(&format!("{base}/m")), limits(), &CancelFlag::new())
.unwrap();
assert!(out.is_not_found());
let base = serve_once(500, vec![], b"boom".to_vec(), 0, false);
let err = t
.fetch_metadata(&req(&format!("{base}/e")), limits(), &CancelFlag::new())
.unwrap_err();
assert!(matches!(err, AcquisitionError::Transport(_)));
assert!(!matches!(err, AcquisitionError::Unavailable(_)));
}
#[test]
#[cfg(not(windows))]
fn artifact_success_not_found_and_server_error() {
let t = require_transport();
let body: Vec<u8> = (0..4096).map(|i| (i % 251) as u8).collect();
let base = ok_server(body.clone());
let dir = temp_dir("curl-artifact");
let dest = dir.join("app");
let out = t
.fetch_artifact(
&req(&format!("{base}/app")),
&dest,
limits(),
&CancelFlag::new(),
)
.unwrap();
assert_eq!(out.success().unwrap().bytes_written, 4096);
assert_eq!(fs::read(&dest).unwrap(), body);
let base = serve_once(404, vec![], b"no".to_vec(), 0, false);
let dest2 = dir.join("missing");
let out = t
.fetch_artifact(
&req(&format!("{base}/m")),
&dest2,
limits(),
&CancelFlag::new(),
)
.unwrap();
assert!(out.is_not_found());
assert!(!dest2.exists());
let base = serve_once(500, vec![], b"boom".to_vec(), 0, false);
let dest3 = dir.join("err");
let err = t
.fetch_artifact(
&req(&format!("{base}/e")),
&dest3,
limits(),
&CancelFlag::new(),
)
.unwrap_err();
assert!(matches!(err, AcquisitionError::Transport(_)));
assert!(!dest3.exists());
let _ = fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn tls_like_process_failure_is_transport_not_unavailable() {
let dir = temp_dir("curl-tls");
let script = fake_curl_script(b"", "", 35, &dir);
let t =
CurlTransport::with_executable(&script, CurlConfig::strict()).expect("fake transport");
let err = t
.fetch_metadata(&req("https://example.com/x"), limits(), &CancelFlag::new())
.unwrap_err();
assert!(matches!(err, AcquisitionError::Transport(_)));
assert!(!err.is_unavailable());
let _ = fs::remove_dir_all(&dir);
}
#[test]
#[cfg(not(windows))]
fn truncated_transfer_is_hard_failure_without_promotion() {
let t = require_transport();
let body = vec![5u8; 4096];
let base = serve_once(
200,
vec![("Content-Length".into(), "4096".into())],
body,
0,
true,
);
let dir = temp_dir("curl-trunc");
let dest = dir.join("app");
let err = t
.fetch_artifact(
&req(&format!("{base}/app")),
&dest,
limits(),
&CancelFlag::new(),
)
.unwrap_err();
assert!(matches!(err, AcquisitionError::Transport(_)));
assert!(!dest.exists());
let _ = fs::remove_dir_all(&dir);
}
#[test]
#[cfg(not(windows))]
fn metadata_and_artifact_size_overflow() {
let t = require_transport();
let big = vec![9u8; 128 * 1024];
let base = ok_server(big);
let err = t
.fetch_metadata(&req(&format!("{base}/big")), limits(), &CancelFlag::new())
.unwrap_err();
assert!(matches!(err, AcquisitionError::TooLarge { .. }));
let body = vec![1u8; 8192];
let base = ok_server(body);
let dir = temp_dir("curl-overflow");
let dest = dir.join("app");
let small = FetchLimits {
max_metadata_bytes: 64 * 1024,
max_artifact_bytes: 1024,
connect_timeout: Duration::from_secs(2),
total_timeout: Duration::from_secs(10),
};
let err = t
.fetch_artifact(
&req(&format!("{base}/app")),
&dest,
small,
&CancelFlag::new(),
)
.unwrap_err();
assert!(matches!(err, AcquisitionError::TooLarge { .. }));
assert!(!dest.exists());
let _ = fs::remove_dir_all(&dir);
}
#[test]
#[cfg(not(windows))]
fn total_phase_timeout_is_typed_end_to_end() {
let t = require_transport();
let body = vec![2u8; 1024];
let base = serve_once(
200,
vec![("Content-Length".into(), body.len().to_string())],
body,
5000,
false,
);
let short_total = FetchLimits {
max_metadata_bytes: 64 * 1024,
max_artifact_bytes: 256 * 1024,
connect_timeout: Duration::from_millis(500),
total_timeout: Duration::from_secs(2),
};
let err = t
.fetch_metadata(
&req(&format!("{base}/slow")),
short_total,
&CancelFlag::new(),
)
.unwrap_err();
assert!(
matches!(err, AcquisitionError::Timeout { phase: "total" }),
"expected a total-phase timeout, got {err}"
);
}
#[test]
#[cfg(not(windows))]
#[ignore = "environment-conditional: needs a host that blackholes the route to 10.255.255.1:81 so the connect ceiling expires instead of failing fast with ENETUNREACH/EHOSTUNREACH; the connect/total label itself is proven without a network by classify_curl_result_labels_connect_and_total_without_a_subprocess"]
fn connect_phase_timeout_is_typed_end_to_end() {
let t = require_transport();
let short_connect = FetchLimits {
max_metadata_bytes: 64 * 1024,
max_artifact_bytes: 256 * 1024,
connect_timeout: Duration::from_millis(500),
total_timeout: Duration::from_secs(10),
};
let err = t
.fetch_metadata(
&req("http://10.255.255.1:81/unreachable"),
short_connect,
&CancelFlag::new(),
)
.unwrap_err();
assert!(
matches!(err, AcquisitionError::Timeout { phase: "connect" }),
"expected a connect-phase timeout, got {err}"
);
}
#[test]
fn classify_curl_result_labels_connect_and_total_without_a_subprocess() {
let dir = temp_dir("curl-phase-label");
let output = dir.join("body");
fs::write(&output, b"partial").unwrap();
let phase_for = |eff_connect: Duration, eff_total: Duration, elapsed: Duration| {
let start = Instant::now() - elapsed;
match classify_curl_result(
Some(28),
b"",
&output,
"https://example.com/app",
start,
eff_connect,
eff_total,
1024,
) {
Err(AcquisitionError::Timeout { phase }) => phase,
other => panic!("expected a timeout, got {other:?}"),
}
};
assert_eq!(
phase_for(
Duration::from_secs(2),
Duration::from_secs(20),
Duration::from_secs(2),
),
"connect",
"an expired, strictly tighter connect ceiling must label a connect timeout"
);
assert_eq!(
phase_for(
Duration::from_secs(2),
Duration::from_secs(20),
Duration::from_secs(5),
),
"total",
"an elapsed time past the connect ceiling must label a total timeout"
);
assert_eq!(
phase_for(
Duration::from_secs(2),
Duration::from_secs(2),
Duration::from_secs(5),
),
"total",
"coincident ceilings must not label a total timeout as connect"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn duration_decimal_seconds_serializes_sub_second_inputs_truthfully() {
let cases = [
(Duration::from_micros(1), "0.000001"),
(Duration::from_micros(500), "0.0005"),
(Duration::from_millis(1), "0.001"),
(Duration::from_millis(100), "0.1"),
(Duration::from_millis(250), "0.25"),
(Duration::from_millis(500), "0.5"),
(Duration::from_millis(1500), "1.5"),
(Duration::from_secs(2), "2"),
(Duration::from_secs(120), "120"),
];
for (input, expected) in cases {
let rendered = duration_decimal_seconds(input).expect("serializes");
assert_eq!(rendered, expected, "input {input:?}");
}
let rendered = duration_decimal_seconds(Duration::from_secs(7)).unwrap();
assert_eq!(rendered, "7");
assert!(duration_decimal_seconds(Duration::ZERO).is_err());
let sub_micros = Duration::from_nanos(500);
assert!(duration_decimal_seconds(sub_micros).is_err());
}
#[test]
fn https_request_never_allows_a_cleartext_redirect_target() {
let cfg = CurlConfig::strict();
let value_after = |args: &[String], flag: &str| -> String {
let idx = args.iter().position(|a| a == flag).expect("flag present");
args[idx + 1].clone()
};
let https = build_curl_args(
&cfg,
None,
"https://example.com/artifact",
1024,
Duration::from_secs(1),
Duration::from_secs(5),
)
.expect("builds");
assert_eq!(value_after(&https, "--proto"), "=http,https");
assert_eq!(value_after(&https, "--proto-redir"), "=https");
let http = build_curl_args(
&cfg,
None,
"http://example.com/artifact",
1024,
Duration::from_secs(1),
Duration::from_secs(5),
)
.expect("builds");
assert_eq!(value_after(&http, "--proto"), "=http,https");
assert_eq!(value_after(&http, "--proto-redir"), "=http,https");
let upper = build_curl_args(
&cfg,
None,
"HTTPS://example.com/artifact",
1024,
Duration::from_secs(1),
Duration::from_secs(5),
)
.expect("builds");
assert_eq!(value_after(&upper, "--proto-redir"), "=https");
let http_only = CurlConfig::strict().allowed_protocols(vec!["http".to_string()]);
let denied = build_curl_args(
&http_only,
None,
"https://example.com/artifact",
1024,
Duration::from_secs(1),
Duration::from_secs(5),
)
.expect("builds");
assert_eq!(value_after(&denied, "--proto-redir"), "=http");
}
#[test]
fn build_curl_args_passes_decimal_deadlines_never_above_ceiling() {
let cfg = CurlConfig::strict();
let cases = [
(
Duration::from_millis(100),
Duration::from_secs(1),
"0.1",
"1",
),
(
Duration::from_millis(250),
Duration::from_millis(1500),
"0.25",
"1.5",
),
(Duration::from_secs(2), Duration::from_secs(5), "2", "5"),
(
Duration::from_micros(500),
Duration::from_micros(750),
"0.0005",
"0.00075",
),
];
for (connect, total, expected_connect, expected_total) in cases {
let args = build_curl_args(&cfg, None, "https://example.com/x", 1024, connect, total)
.expect("builds");
let connect_idx = args
.iter()
.position(|a| a == "--connect-timeout")
.expect("connect-timeout present");
let total_idx = args
.iter()
.position(|a| a == "--max-time")
.expect("max-time present");
assert_eq!(args[connect_idx + 1], expected_connect);
assert_eq!(args[total_idx + 1], expected_total);
}
let err = build_curl_args(
&cfg,
None,
"https://example.com/x",
1024,
Duration::from_nanos(500),
Duration::from_millis(500),
);
assert!(matches!(err, Err(AcquisitionError::InvalidInput(_))));
}
#[test]
fn sub_second_deadlines_serialize_truthfully_without_a_subprocess() {
let cfg = CurlConfig::strict();
let value_after = |args: &[String], flag: &str| -> String {
let idx = args.iter().position(|a| a == flag).expect("flag present");
args[idx + 1].clone()
};
let sub_second_pair = FetchLimits {
max_metadata_bytes: 64 * 1024,
max_artifact_bytes: 256 * 1024,
connect_timeout: Duration::from_millis(250),
total_timeout: Duration::from_millis(750),
};
let (eff_connect, eff_total) = cfg.effective_timeouts(sub_second_pair);
assert_eq!(eff_connect, Duration::from_millis(250));
assert_eq!(eff_total, Duration::from_millis(750));
let args = build_curl_args(
&cfg,
None,
"https://example.com/x",
1024,
eff_connect,
eff_total,
)
.expect("builds");
assert_eq!(value_after(&args, "--connect-timeout"), "0.25");
assert_eq!(value_after(&args, "--max-time"), "0.75");
let capped =
CurlConfig::strict().timeouts(Duration::from_millis(100), Duration::from_millis(400));
let (capped_connect, capped_total) = capped.effective_timeouts(sub_second_pair);
assert_eq!(capped_connect, Duration::from_millis(100));
assert_eq!(capped_total, Duration::from_millis(400));
let capped_args = build_curl_args(
&capped,
None,
"https://example.com/x",
1024,
capped_connect,
capped_total,
)
.expect("builds");
assert_eq!(value_after(&capped_args, "--connect-timeout"), "0.1");
assert_eq!(value_after(&capped_args, "--max-time"), "0.4");
assert_ne!(
value_after(&capped_args, "--max-time"),
"0.75",
"--max-time must be the effective ceiling, never the raw request"
);
let err = build_curl_args(
&cfg,
None,
"https://example.com/x",
1024,
Duration::from_nanos(500),
Duration::from_millis(500),
);
assert!(matches!(err, Err(AcquisitionError::InvalidInput(_))));
}
#[cfg(unix)]
#[test]
fn build_curl_args_passes_sub_second_deadlines_to_fake_curl() {
let dir = temp_dir("curl-decode-args");
let script = fake_curl_script(b"", "200", 0, &dir);
let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
let cfg = FetchLimits {
max_metadata_bytes: 64 * 1024,
max_artifact_bytes: 256 * 1024,
connect_timeout: Duration::from_millis(250),
total_timeout: Duration::from_secs(30),
};
t.fetch_metadata(&req("https://example.com/x"), cfg, &CancelFlag::new())
.expect("fake curl completes well inside the 30s budget");
let argv = fs::read_to_string(dir.join("argv")).unwrap();
assert!(
argv.contains("--connect-timeout 0.25"),
"argv missing 0.25: {argv}"
);
assert!(argv.contains("--max-time 30"), "argv missing 30: {argv}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
#[cfg(not(windows))]
fn sub_second_total_timeout_kills_child_promptly() {
let t = require_transport();
let body = vec![7u8; 8192];
let base = serve_once(
200,
vec![("Content-Length".into(), body.len().to_string())],
body,
4000,
false,
);
let short_total = FetchLimits {
max_metadata_bytes: 64 * 1024,
max_artifact_bytes: 256 * 1024,
connect_timeout: Duration::from_millis(100),
total_timeout: Duration::from_millis(250),
};
let dir = temp_dir("curl-subsec-total");
let dest = dir.join("app");
let started = Instant::now();
let err = t
.fetch_artifact(
&req(&format!("{base}/app")),
&dest,
short_total,
&CancelFlag::new(),
)
.unwrap_err();
let elapsed = started.elapsed();
assert!(matches!(err, AcquisitionError::Timeout { phase: "total" }));
assert!(
elapsed >= short_total.total_timeout,
"elapsed {elapsed:?} is below the {:?} total deadline",
short_total.total_timeout
);
assert!(
elapsed < Duration::from_secs(2),
"elapsed {elapsed:?} is not below the 2 s bound"
);
assert!(!dest.exists());
assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn cancellation_before_spawn_cleans_temp() {
let t = require_transport();
let dir = temp_dir("curl-cancel");
let dest = dir.join("app");
let cancel = CancelFlag::new();
cancel.cancel();
let err = t
.fetch_artifact(&req("http://127.0.0.1:1/app"), &dest, limits(), &cancel)
.unwrap_err();
assert!(matches!(err, AcquisitionError::Cancelled));
assert!(!dest.exists());
let leftovers: Vec<_> = fs::read_dir(&dir)
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().ends_with(".part"))
.collect();
assert!(leftovers.is_empty());
let _ = fs::remove_dir_all(&dir);
}
#[test]
#[cfg(not(windows))]
fn cancellation_during_body_stream_kills_and_reaps_child() {
let t = require_transport();
let base = serve_once(
200,
vec![("Content-Length".into(), "65536".into())],
vec![3u8; 65536],
5000,
false,
);
let dir = temp_dir("curl-cancel-stream");
let dest = dir.join("app");
let cancel = Arc::new(CancelFlag::new());
let child_cancel = Arc::clone(&cancel);
let child_transport = t;
let url = format!("{base}/app");
let child = thread::spawn(move || {
child_transport.fetch_artifact(&req(&url), &dest, limits(), &child_cancel)
});
thread::sleep(Duration::from_millis(150));
cancel.cancel();
assert!(matches!(
child.join().unwrap(),
Err(AcquisitionError::Cancelled)
));
assert!(!dir.join("app").exists());
assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
let _ = fs::remove_dir_all(&dir);
}
#[test]
#[cfg(not(windows))]
fn redirect_follow_and_reject() {
let curl_exe = require_curl_executable();
let target_body = b"redirect-target".to_vec();
let target = ok_server(target_body.clone());
let redirect = serve_once(
302,
vec![("Location".into(), format!("{target}/final"))],
b"".to_vec(),
0,
false,
);
let follow = CurlTransport::with_executable(
curl_exe.clone(),
CurlConfig::strict()
.follow_redirects(true)
.max_redirects(10),
)
.unwrap();
let out = follow
.fetch_metadata(&req(&format!("{redirect}/r")), limits(), &CancelFlag::new())
.unwrap();
assert_eq!(out.success().unwrap().bytes(), b"redirect-target");
let nofollow =
CurlTransport::with_executable(curl_exe, CurlConfig::strict().follow_redirects(false))
.unwrap();
let err = nofollow
.fetch_metadata(&req(&format!("{redirect}/r")), limits(), &CancelFlag::new())
.unwrap_err();
assert!(matches!(err, AcquisitionError::Transport(_)));
}
#[cfg(unix)]
#[test]
fn proxy_disabled_uses_noproxy_and_cleared_env() {
let dir = temp_dir("curl-proxy");
let script = fake_curl_script(b"ok", "200", 0, &dir);
let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
let out = t
.fetch_metadata(&req("http://example.com/x"), limits(), &CancelFlag::new())
.unwrap();
assert_eq!(out.success().unwrap().bytes(), b"ok");
let argv = fs::read_to_string(dir.join("argv")).unwrap();
assert!(argv.contains("--noproxy"));
assert!(argv.contains("--disable"));
assert!(argv.contains("--output -"));
assert!(!argv.contains("eggup-curl-meta"));
let env = fs::read_to_string(dir.join("env")).unwrap();
assert!(!env.contains("HTTP_PROXY=hunter"));
let _ = fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn proxy_custom_env_is_explicit() {
let dir = temp_dir("curl-proxy-custom");
let script = fake_curl_script(b"ok", "200", 0, &dir);
let t = CurlTransport::with_executable(
&script,
CurlConfig::strict().proxy(CurlProxy::Custom(vec![(
"HTTPS_PROXY".to_string(),
"http://proxy.example:8080".to_string(),
)])),
)
.unwrap();
t.fetch_metadata(&req("http://example.com/x"), limits(), &CancelFlag::new())
.unwrap();
let argv = fs::read_to_string(dir.join("argv")).unwrap();
assert!(!argv.contains("--noproxy"));
let env = fs::read_to_string(dir.join("env")).unwrap();
assert!(env.contains("HTTPS_PROXY=http://proxy.example:8080"));
let _ = fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn artifact_temp_is_owner_private_and_no_clobber() {
let dir = temp_dir("curl-perms");
let script = fake_curl_script(b"owned-bytes", "200", 0, &dir);
let work = temp_dir("curl-perms-work");
let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
let dest = work.join("app");
let out = t
.fetch_artifact(
&req("http://example.com/app"),
&dest,
limits(),
&CancelFlag::new(),
)
.unwrap();
assert_eq!(
out.success().unwrap().bytes_written,
b"owned-bytes".len() as u64
);
#[cfg(unix)]
{
let mode = fs::metadata(&dest).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
fs::write(&dest, b"FOREIGN").unwrap();
let dest2 = work.join("app");
let err = t
.fetch_artifact(
&req("http://example.com/app"),
&dest2,
limits(),
&CancelFlag::new(),
)
.unwrap_err();
assert!(matches!(err, AcquisitionError::InvalidInput(_)));
assert_eq!(fs::read(&dest2).unwrap(), b"FOREIGN");
let _ = fs::remove_dir_all(&dir);
let _ = fs::remove_dir_all(&work);
}
#[cfg(unix)]
#[test]
fn credential_material_is_redacted() {
let dir = temp_dir("curl-redact");
let script = fake_curl_script(b"", "", 7, &dir);
let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
let url = "https://user:S3CR3T-USERINFO-9917@example.com/app?token=TOKEN-QUERY-5523#FRAG-SENTINEL-7788";
let err = t
.fetch_metadata(&req(url), limits(), &CancelFlag::new())
.unwrap_err();
let msg = format!("{err}");
assert!(!msg.contains("S3CR3T-USERINFO-9917"));
assert!(!msg.contains("TOKEN-QUERY-5523"));
assert!(!msg.contains("FRAG-SENTINEL-7788"));
let _ = fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn invalid_limits_fail_before_spawn() {
let dir = temp_dir("curl-invalid");
let script = fake_curl_script(b"ok", "200", 0, &dir);
let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
let bad = FetchLimits {
max_metadata_bytes: 0,
..limits()
};
let err = t
.fetch_metadata(&req("http://example.com/x"), bad, &CancelFlag::new())
.unwrap_err();
assert!(matches!(err, AcquisitionError::InvalidInput(_)));
let dest = dir.join("app");
let err = t
.fetch_artifact(&req("http://example.com/x"), &dest, bad, &CancelFlag::new())
.unwrap_err();
assert!(matches!(err, AcquisitionError::InvalidInput(_)));
assert!(!dest.exists());
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn composition_with_fixture_falls_back_from_unavailable_curl() {
use eggup_acquisition::{ComposedTransport, CompositionPolicy};
let dir = temp_dir("curl-composed");
let script = dir.join("missing-curl");
let curl = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
let fixture = FixtureTransport::new();
fixture.route(
"https://example.com/meta",
FixtureResponse::body(b"via-fixture".to_vec()),
);
let composed = ComposedTransport::new(&curl, &fixture, CompositionPolicy::UnavailableOnly);
let out = composed
.fetch_metadata(
&req("https://example.com/meta"),
limits(),
&CancelFlag::new(),
)
.unwrap();
assert_eq!(out.success().unwrap().bytes(), b"via-fixture");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn user_agent_is_emitted_as_a_literal_argv_element_before_the_url() {
let cfg = CurlConfig::strict();
let agent = "eggup-curl-test/1.0 (Macintosh; x86_64)";
let args = build_curl_args(
&cfg,
Some(agent),
"https://example.com/x",
1024,
Duration::from_secs(1),
Duration::from_secs(2),
)
.expect("builds");
let flag = args
.iter()
.position(|a| a == "--user-agent")
.expect("the user agent flag is present");
assert_eq!(
args[flag + 1],
agent,
"the value must be the exact element following the flag"
);
assert_eq!(
args.iter().filter(|a| *a == "--user-agent").count(),
1,
"the flag must appear exactly once"
);
let separator = args.iter().position(|a| a == "--").expect("separator");
let url = args
.iter()
.position(|a| a == "https://example.com/x")
.expect("url");
assert!(
flag < separator,
"--user-agent must be emitted before the -- separator"
);
assert!(separator < url, "the -- separator must precede the URL");
assert_eq!(url, args.len() - 1, "the URL stays the last element");
}
#[test]
fn user_agent_rejects_control_characters_without_producing_argv() {
let cfg = CurlConfig::strict();
let rejected = [
"eggup\r\nX-Injected: 1",
"eggup\rvalue",
"eggup\nvalue",
"eggup\u{0}value",
"eggup\tvalue",
"eggup\u{7F}value",
"eggup\u{85}value",
"eggup\u{9F}value",
];
for bad in rejected {
let err = build_curl_args(
&cfg,
Some(bad),
"https://example.com/x",
1024,
Duration::from_secs(1),
Duration::from_secs(2),
)
.expect_err("a control character must be rejected");
assert!(
matches!(err, AcquisitionError::InvalidInput(_)),
"expected InvalidInput for {bad:?}, got {err:?}"
);
let ctor = CurlTransport::with_executable_and_user_agent(
"/usr/bin/curl",
CurlConfig::strict(),
bad,
)
.expect_err("a control character must be refused at construction");
assert!(
matches!(ctor, AcquisitionError::InvalidInput(_)),
"expected InvalidInput for {bad:?}, got {ctor:?}"
);
}
}
#[test]
fn user_agent_rejects_empty_and_over_bound_values() {
let cfg = CurlConfig::strict();
let empty = build_curl_args(
&cfg,
Some(""),
"https://example.com/x",
1024,
Duration::from_secs(1),
Duration::from_secs(2),
)
.expect_err("an empty value must be rejected");
assert!(matches!(empty, AcquisitionError::InvalidInput(_)));
let at_bound = "a".repeat(MAX_USER_AGENT_BYTES);
let ok = build_curl_args(
&cfg,
Some(&at_bound),
"https://example.com/x",
1024,
Duration::from_secs(1),
Duration::from_secs(2),
)
.expect("a value exactly at the bound must be accepted");
let flag = ok
.iter()
.position(|a| a == "--user-agent")
.expect("the user agent flag is present");
assert_eq!(ok[flag + 1], at_bound);
let over_bound = "a".repeat(MAX_USER_AGENT_BYTES + 1);
let err = build_curl_args(
&cfg,
Some(&over_bound),
"https://example.com/x",
1024,
Duration::from_secs(1),
Duration::from_secs(2),
)
.expect_err("an over-bound value must be rejected");
assert!(matches!(err, AcquisitionError::InvalidInput(_)));
let ctor = CurlTransport::with_executable_and_user_agent(
"/usr/bin/curl",
CurlConfig::strict(),
over_bound.clone(),
)
.expect_err("an over-bound value must be refused at construction");
assert!(matches!(ctor, AcquisitionError::InvalidInput(_)));
}
#[test]
fn default_transport_emits_no_user_agent_and_keeps_the_previous_argv() {
let cfg = CurlConfig::strict();
let transport = CurlTransport::with_executable("/usr/bin/curl", cfg.clone())
.expect("the transport builds");
assert_eq!(
transport.user_agent(),
None,
"the default transport must not carry a user agent"
);
let args = build_curl_args(
&cfg,
None,
"https://example.com/x",
1024,
Duration::from_secs(1),
Duration::from_secs(2),
)
.expect("builds");
assert!(
!args.iter().any(|a| a == "--user-agent"),
"the default argv must not carry --user-agent"
);
assert_eq!(
args,
vec![
"--disable",
"--silent",
"--show-error",
"--no-progress-meter",
"--location",
"--max-redirs",
"10",
"--connect-timeout",
"1",
"--max-time",
"2",
"--max-filesize",
"1024",
"--proto",
"=http,https",
"--proto-redir",
"=https",
"--noproxy",
"*",
"--output",
"-",
"--write-out",
"%{stderr}%{http_code}",
"--",
"https://example.com/x",
],
"the default argv must be unchanged"
);
}
#[test]
fn rejected_user_agent_is_a_terminal_invalid_input_not_unavailable() {
use eggup_acquisition::{ComposedTransport, CompositionPolicy};
let err = CurlTransport::with_executable_and_user_agent(
"/usr/bin/curl",
CurlConfig::strict(),
"bad\rvalue",
)
.expect_err("a control character must be refused at construction");
assert!(matches!(err, AcquisitionError::InvalidInput(_)));
assert!(
!err.is_unavailable(),
"a rejected caller value must never be classified as unavailable"
);
let curl = CurlTransport::with_executable_and_user_agent(
"/usr/bin/curl",
CurlConfig::strict(),
"eggup-curl-test/1.0",
)
.expect("builds");
let fixture = FixtureTransport::new();
fixture.route(
"https://example.com/meta",
FixtureResponse::body(b"via-fixture".to_vec()),
);
let composed = ComposedTransport::new(&curl, &fixture, CompositionPolicy::UnavailableOnly);
let bad_limits = FetchLimits {
max_metadata_bytes: 0,
..limits()
};
let composed_err = composed
.fetch_metadata(
&req("https://example.com/meta"),
bad_limits,
&CancelFlag::new(),
)
.expect_err("a terminal failure must not fall back to the fixture");
assert!(
matches!(composed_err, AcquisitionError::InvalidInput(_)),
"the composed transport must surface the terminal failure, got {composed_err:?}"
);
}
#[cfg(not(windows))]
#[test]
fn user_agent_reaches_the_wire_as_the_configured_header() {
let dir = temp_dir("curl-ua-wire");
let record = dir.join("request-head");
let base = serve_once_recording_head(200, b"ok".to_vec(), &record);
let curl_exe = require_curl_executable();
let transport = CurlTransport::with_executable_and_user_agent(
curl_exe,
CurlConfig::strict(),
"eggup-curl-test/1.0",
)
.expect("builds");
assert_eq!(transport.user_agent(), Some("eggup-curl-test/1.0"));
let out = transport
.fetch_metadata(&req(&format!("{base}/x")), limits(), &CancelFlag::new())
.expect("the loopback fetch must succeed");
assert_eq!(out.success().unwrap().bytes(), b"ok");
let head = fs::read_to_string(&record).expect("the request head was recorded");
assert!(
head.contains("User-Agent: eggup-curl-test/1.0\r\n"),
"the configured user agent must reach the wire; the head was {head:?}"
);
let _ = fs::remove_dir_all(&dir);
}
}