Skip to main content

eggup_curl/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3#![doc = "External curl acquisition adapter with explicit bounded policy."]
4#![doc = ""]
5#![doc = "Implements `eggup-acquisition::AcquisitionTransport` without an embedded"]
6#![doc = "HTTP/TLS stack. See `README.md` for the single policy configuration point."]
7#![doc = ""]
8#![doc = "Transport fallback (curl <-> Eggfetch for the same exact URL) lives in"]
9#![doc = "`eggup-acquisition::ComposedTransport` and is never release/source fallback."]
10
11use eggup_acquisition::{
12    AcquisitionError, AcquisitionRequest, AcquisitionTransport, CancelFlag, FetchLimits,
13    FetchOutcome,
14};
15use std::fs::{self, File};
16use std::io::Write;
17use std::path::{Path, PathBuf};
18use std::process::{Command, Stdio};
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::Arc;
21use std::time::{Duration, Instant};
22
23/// Default connect deadline ceiling.
24pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
25/// Default total wall-clock deadline ceiling.
26pub const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(120);
27/// Default redirect bound when following is enabled.
28pub const DEFAULT_MAX_REDIRECTS: usize = 10;
29/// Maximum accepted outbound `User-Agent` length, in bytes.
30///
31/// The bound keeps the outbound header value a bounded HTTP field value. It
32/// matches the 512-byte magnitude this adapter already uses for bounded
33/// diagnostics. A longer value is rejected with
34/// [`AcquisitionError::InvalidInput`]; see
35/// [`CurlTransport::with_executable_and_user_agent`] for the full accepted
36/// grammar.
37pub const MAX_USER_AGENT_BYTES: usize = 512;
38/// Bound for captured curl stdout (`-w "%{http_code}"` plus slack).
39const MAX_WRITE_OUT_BYTES: u64 = 64;
40/// Parent polling granularity while waiting for the owned child.
41const POLL_INTERVAL: Duration = Duration::from_millis(5);
42
43/// Explicit proxy decision. Routing is never inherited accidentally.
44#[derive(Debug, Clone, Default)]
45pub enum CurlProxy {
46    /// No proxy is used. The child environment is cleared and
47    /// `--noproxy "*"` is passed as defense-in-depth.
48    #[default]
49    Disabled,
50    /// Use an explicit snapshot of the current process proxy environment.
51    FromEnvironment,
52    /// Use explicit `KEY=value` pairs (e.g. `HTTPS_PROXY`, `NO_PROXY`).
53    Custom(Vec<(String, String)>),
54}
55
56/// Strict transport configuration. All policy lives here.
57#[derive(Debug, Clone)]
58pub struct CurlConfig {
59    /// Connect deadline ceiling.
60    pub connect_timeout: Duration,
61    /// Total deadline ceiling.
62    pub total_timeout: Duration,
63    /// Redirect bound when following is enabled.
64    pub max_redirects: usize,
65    /// Whether HTTP redirects are followed.
66    pub follow_redirects: bool,
67    /// Allowed URL protocols (default `http`, `https`).
68    ///
69    /// This list bounds the *initial* request. The redirect target set is
70    /// narrowed further: an `https` request never follows a redirect down to
71    /// `http`, so a `302 Location: http://...` is refused rather than followed
72    /// in cleartext.
73    pub allowed_protocols: Vec<String>,
74    /// Proxy routing decision.
75    pub proxy: CurlProxy,
76}
77
78impl Default for CurlConfig {
79    fn default() -> Self {
80        Self {
81            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
82            total_timeout: DEFAULT_TOTAL_TIMEOUT,
83            max_redirects: DEFAULT_MAX_REDIRECTS,
84            follow_redirects: true,
85            allowed_protocols: vec!["http".to_string(), "https".to_string()],
86            proxy: CurlProxy::Disabled,
87        }
88    }
89}
90
91impl CurlConfig {
92    /// Strict default: bounded timeouts, redirect bound, explicit proxy.
93    pub fn strict() -> Self {
94        Self::default()
95    }
96
97    /// Sets connect/total adapter ceilings.
98    ///
99    /// These are ceilings, not defaults: the effective deadline for one fetch
100    /// is `min(request, adapter ceiling)` (see [`FetchLimits::effective`]).
101    pub fn timeouts(mut self, connect: Duration, total: Duration) -> Self {
102        self.connect_timeout = connect;
103        self.total_timeout = total;
104        self
105    }
106
107    /// Sets the redirect bound.
108    pub fn max_redirects(mut self, max: usize) -> Self {
109        self.max_redirects = max;
110        self
111    }
112
113    /// Sets whether redirects are followed.
114    pub fn follow_redirects(mut self, follow: bool) -> Self {
115        self.follow_redirects = follow;
116        self
117    }
118
119    /// Sets the allowed protocols.
120    pub fn allowed_protocols(mut self, protocols: Vec<String>) -> Self {
121        self.allowed_protocols = protocols;
122        self
123    }
124
125    /// Sets the proxy decision.
126    pub fn proxy(mut self, proxy: CurlProxy) -> Self {
127        self.proxy = proxy;
128        self
129    }
130
131    /// Derives the authoritative effective deadlines for one fetch.
132    pub fn effective_timeouts(&self, limits: FetchLimits) -> (Duration, Duration) {
133        limits.effective(self.connect_timeout, self.total_timeout)
134    }
135
136    fn validate(&self) -> Result<(), AcquisitionError> {
137        if self.connect_timeout.is_zero() || self.total_timeout.is_zero() {
138            return Err(AcquisitionError::InvalidInput(bound(
139                "adapter timeouts must be positive".to_string(),
140            )));
141        }
142        if self.connect_timeout > self.total_timeout {
143            return Err(AcquisitionError::InvalidInput(bound(
144                "adapter connect timeout must not exceed total timeout".to_string(),
145            )));
146        }
147        if self.max_redirects > 50 {
148            return Err(AcquisitionError::InvalidInput(bound(
149                "adapter redirect bound out of range".to_string(),
150            )));
151        }
152        if self.allowed_protocols.is_empty() || self.allowed_protocols.len() > 8 {
153            return Err(AcquisitionError::InvalidInput(bound(
154                "adapter protocol list out of range".to_string(),
155            )));
156        }
157        for p in &self.allowed_protocols {
158            if p.is_empty() || p.len() > 16 || !p.chars().all(|c| c.is_ascii_alphanumeric()) {
159                return Err(AcquisitionError::InvalidInput(bound(
160                    "adapter protocol names must be alphanumeric".to_string(),
161                )));
162            }
163        }
164        Ok(())
165    }
166}
167
168/// External curl adapter implementing the acquisition seam.
169///
170/// No release, version, fallback, destination, or service policy lives here.
171/// Only exact 404 becomes `NotFound`; TLS/5xx/timeout are hard failures and
172/// missing/spawn failures become `Unavailable` for safe composition.
173#[derive(Debug)]
174pub struct CurlTransport {
175    executable: PathBuf,
176    config: CurlConfig,
177    user_agent: Option<String>,
178}
179
180impl CurlTransport {
181    /// Builds an adapter from an explicit executable path plus config.
182    ///
183    /// The path is the strongest selection; discovery via
184    /// [`discover_curl_executable`] is opt-in only. Config validation happens
185    /// here; executable existence/spawn is classified per-request as
186    /// `Unavailable` so composition can fall back.
187    ///
188    /// The constructed adapter sends **no** `User-Agent`: no `--user-agent`
189    /// element reaches `curl`, so `curl` applies its own default. Use
190    /// [`CurlTransport::with_executable_and_user_agent`] to set one.
191    pub fn with_executable(
192        executable: impl Into<PathBuf>,
193        config: CurlConfig,
194    ) -> Result<Self, AcquisitionError> {
195        config.validate()?;
196        let executable = executable.into();
197        if executable.as_os_str().is_empty() {
198            return Err(AcquisitionError::InvalidInput(bound(
199                "curl executable path must not be empty".to_string(),
200            )));
201        }
202        Ok(Self {
203            executable,
204            config,
205            user_agent: None,
206        })
207    }
208
209    /// Builds an adapter from an explicit executable path plus config and a
210    /// caller-supplied outbound `User-Agent` value.
211    ///
212    /// The value is validated here and is used for **every** request this
213    /// adapter makes. It reaches `curl` as the literal argv element following
214    /// `--user-agent`, positioned before the `--` separator and the URL. No
215    /// shell is involved, so the value is never re-parsed or interpolated.
216    ///
217    /// # Accepted grammar
218    ///
219    /// ```text
220    /// user-agent = 1*( VCHAR / SP / obs-text )
221    /// VCHAR      = %x21-7E          ; printable ASCII, excluding SP
222    /// SP         = %x20            ; permitted inside the value; a run of SP is
223    ///                              ; permitted, but a leading or trailing SP is not
224    /// obs-text   = %xA0-10FFFF     ; any non-ASCII scalar value (C1 excluded)
225    /// ```
226    ///
227    /// A run of interior `SP` is permitted because the HTTP field-value grammar
228    /// permits it: RFC 7230 §3.2 defines `field-content` as
229    /// `field-vchar [ 1*( SP / HTAB ) field-vchar ]`, whose interior run is
230    /// `1*`. The accepted set is therefore a subset of a well-formed HTTP field
231    /// value, and the rules that actually protect the request head — no C0 or
232    /// C1 control character, no `DEL`, no leading or trailing `SP` — are
233    /// enforced exactly.
234    ///
235    /// The value is rejected with [`AcquisitionError::InvalidInput`] when it is
236    /// empty, when its UTF-8 length exceeds [`MAX_USER_AGENT_BYTES`], when it
237    /// contains any C0 control character (including `CR`, `LF`, `NUL`, and
238    /// `HTAB`), `DEL` (`U+007F`), or any C1 control character
239    /// (`U+0080`-`U+009F`), or when it begins or ends with a space.
240    ///
241    /// `InvalidInput` is terminal: unlike `Unavailable` it never causes a
242    /// composed transport to fall back to another adapter.
243    ///
244    /// The control characters are refused because `curl` does not sanitize
245    /// `--user-agent`: a value containing `CR LF` would be written into the
246    /// request head verbatim and inject an additional header.
247    pub fn with_executable_and_user_agent(
248        executable: impl Into<PathBuf>,
249        config: CurlConfig,
250        user_agent: impl Into<String>,
251    ) -> Result<Self, AcquisitionError> {
252        config.validate()?;
253        let executable = executable.into();
254        if executable.as_os_str().is_empty() {
255            return Err(AcquisitionError::InvalidInput(bound(
256                "curl executable path must not be empty".to_string(),
257            )));
258        }
259        let user_agent = user_agent.into();
260        validate_user_agent(&user_agent)?;
261        Ok(Self {
262            executable,
263            config,
264            user_agent: Some(user_agent),
265        })
266    }
267
268    /// Returns the configured executable path.
269    pub fn executable(&self) -> &Path {
270        &self.executable
271    }
272
273    /// Returns the transport configuration.
274    pub fn config(&self) -> &CurlConfig {
275        &self.config
276    }
277
278    /// Returns the outbound `User-Agent` value this adapter will send.
279    ///
280    /// `None` means no `--user-agent` element is emitted and `curl` applies
281    /// its own default. See
282    /// [`CurlTransport::with_executable_and_user_agent`] for the accepted
283    /// grammar.
284    pub fn user_agent(&self) -> Option<&str> {
285        self.user_agent.as_deref()
286    }
287}
288
289/// Validates a caller-supplied outbound `User-Agent` value.
290///
291/// The accepted grammar is the one documented on
292/// [`CurlTransport::with_executable_and_user_agent`]. Every rejection is
293/// `InvalidInput`, which is terminal: it never lets a composed transport fall
294/// back to another adapter because of a malformed caller input.
295fn validate_user_agent(user_agent: &str) -> Result<(), AcquisitionError> {
296    if user_agent.is_empty() {
297        return Err(AcquisitionError::InvalidInput(bound(
298            "user agent must not be empty".to_string(),
299        )));
300    }
301    if user_agent.len() > MAX_USER_AGENT_BYTES {
302        return Err(AcquisitionError::InvalidInput(bound(
303            "user agent exceeds the maximum length".to_string(),
304        )));
305    }
306    let mut chars = user_agent.chars();
307    let first = chars.next();
308    let last = user_agent.chars().next_back();
309    // An HTTP field value is delimited by optional whitespace that a recipient
310    // may strip, so a value with surrounding spaces would not be transmitted
311    // faithfully.
312    if first == Some(' ') || last == Some(' ') {
313        return Err(AcquisitionError::InvalidInput(bound(
314            "user agent must not begin or end with a space".to_string(),
315        )));
316    }
317    for ch in user_agent.chars() {
318        let permitted = match ch {
319            // VCHAR: printable ASCII, excluding SP.
320            '\u{21}'..='\u{7E}' => true,
321            // SP: interior only; the surrounding-space case is refused above.
322            '\u{20}' => true,
323            // obs-text: any non-ASCII scalar value, C1 controls excluded.
324            '\u{A0}'..='\u{10FFFF}' => true,
325            // Everything else is a C0 control (CR, LF, NUL, HTAB, ...), DEL, or
326            // a C1 control.
327            _ => false,
328        };
329        if !permitted {
330            return Err(AcquisitionError::InvalidInput(bound(
331                "user agent must not contain control characters".to_string(),
332            )));
333        }
334    }
335    Ok(())
336}
337
338impl AcquisitionTransport for CurlTransport {
339    fn fetch_metadata(
340        &self,
341        request: &AcquisitionRequest,
342        limits: FetchLimits,
343        cancel: &CancelFlag,
344    ) -> Result<FetchOutcome<eggup_acquisition::MetadataBytes>, AcquisitionError> {
345        limits.validate()?;
346        self.config.validate()?;
347        if cancel.is_cancelled() {
348            return Err(AcquisitionError::Cancelled);
349        }
350        let (eff_connect, eff_total) = self.config.effective_timeouts(limits);
351        let max = limits.max_metadata_bytes;
352        // Owned private temp in the system temp dir; same exclusive/0600
353        // machinery as artifact staging, cleaned unconditionally.
354        let parent = std::env::temp_dir();
355        let _ = fs::create_dir_all(&parent);
356        let (mut file, tmp) =
357            eggup_acquisition::__acquire_exclusive_temp(&parent, "eggup-curl-meta")?;
358        struct Guard {
359            path: PathBuf,
360            disarm: bool,
361        }
362        impl Drop for Guard {
363            fn drop(&mut self) {
364                if !self.disarm {
365                    eggup_acquisition::__remove_owned_temp(&self.path);
366                }
367            }
368        }
369        let mut guard = Guard {
370            path: tmp.clone(),
371            disarm: false,
372        };
373        let outcome = run_curl_to_file(
374            &self.executable,
375            &self.config,
376            self.user_agent.as_deref(),
377            request,
378            &tmp,
379            &mut file,
380            max as u64,
381            eff_connect,
382            eff_total,
383            cancel,
384        )?;
385        match outcome {
386            CurlOutcome::Success => {
387                if cancel.is_cancelled() {
388                    return Err(AcquisitionError::Cancelled);
389                }
390                let bytes = fs::read(&tmp)
391                    .map_err(|e| AcquisitionError::__adapter_io("reading part file", e))?;
392                eggup_acquisition::__remove_owned_temp(&tmp);
393                guard.disarm = true;
394                if bytes.len() > max {
395                    return Err(AcquisitionError::TooLarge { limit: max as u64 });
396                }
397                Ok(FetchOutcome::Success(
398                    eggup_acquisition::__adapter_metadata(bytes),
399                ))
400            }
401            CurlOutcome::NotFound => {
402                eggup_acquisition::__remove_owned_temp(&tmp);
403                guard.disarm = true;
404                Ok(FetchOutcome::NotFound)
405            }
406        }
407    }
408
409    fn fetch_artifact(
410        &self,
411        request: &AcquisitionRequest,
412        dest: &Path,
413        limits: FetchLimits,
414        cancel: &CancelFlag,
415    ) -> Result<FetchOutcome<eggup_acquisition::ArtifactEvidence>, AcquisitionError> {
416        limits.validate()?;
417        self.config.validate()?;
418        if cancel.is_cancelled() {
419            return Err(AcquisitionError::Cancelled);
420        }
421        let parent = dest.parent().ok_or_else(|| {
422            AcquisitionError::InvalidInput(bound("destination has no parent".into()))
423        })?;
424        let parent_meta = fs::symlink_metadata(parent)
425            .map_err(|e| AcquisitionError::__adapter_io("reading artifact parent", e))?;
426        if !parent_meta.is_dir() || parent_meta.file_type().is_symlink() {
427            return Err(AcquisitionError::InvalidInput(bound(
428                "artifact parent must be an existing real directory".into(),
429            )));
430        }
431        if fs::symlink_metadata(dest).is_ok() {
432            return Err(AcquisitionError::InvalidInput(bound(
433                "artifact destination already exists; refusing to overwrite".into(),
434            )));
435        }
436        let (eff_connect, eff_total) = self.config.effective_timeouts(limits);
437        let max_artifact = limits.max_artifact_bytes;
438        let (mut file, tmp) = eggup_acquisition::__acquire_exclusive_temp(parent, "eggup-curl")?;
439        struct Guard {
440            path: PathBuf,
441            disarm: bool,
442        }
443        impl Drop for Guard {
444            fn drop(&mut self) {
445                if !self.disarm {
446                    eggup_acquisition::__remove_owned_temp(&self.path);
447                }
448            }
449        }
450        let mut guard = Guard {
451            path: tmp.clone(),
452            disarm: false,
453        };
454        let outcome = run_curl_to_file(
455            &self.executable,
456            &self.config,
457            self.user_agent.as_deref(),
458            request,
459            &tmp,
460            &mut file,
461            max_artifact,
462            eff_connect,
463            eff_total,
464            cancel,
465        )?;
466        match outcome {
467            CurlOutcome::NotFound => {
468                eggup_acquisition::__remove_owned_temp(&tmp);
469                guard.disarm = true;
470                Ok(FetchOutcome::NotFound)
471            }
472            CurlOutcome::Success => {
473                if cancel.is_cancelled() {
474                    return Err(AcquisitionError::Cancelled);
475                }
476                let size = fs::metadata(&tmp)
477                    .map_err(|e| AcquisitionError::__adapter_io("reading part file", e))?
478                    .len();
479                if size > max_artifact {
480                    eggup_acquisition::__remove_owned_temp(&tmp);
481                    guard.disarm = true;
482                    return Err(AcquisitionError::TooLarge {
483                        limit: max_artifact,
484                    });
485                }
486                match eggup_acquisition::__promote_no_clobber(&tmp, dest) {
487                    Ok(()) => {
488                        guard.disarm = true;
489                        Ok(FetchOutcome::Success(
490                            eggup_acquisition::__adapter_artifact(size),
491                        ))
492                    }
493                    Err(e) => {
494                        eggup_acquisition::__remove_owned_temp(&tmp);
495                        guard.disarm = true;
496                        Err(e)
497                    }
498                }
499            }
500        }
501    }
502}
503
504#[derive(Debug, Clone, Copy, PartialEq, Eq)]
505enum CurlOutcome {
506    Success,
507    NotFound,
508}
509
510/// Opt-in discovery of a `curl` executable via `PATH`.
511///
512/// Searches `PATH` for `curl` (plus `curl.exe` on Windows) and returns the
513/// first existing regular file. Returns `Unavailable` when nothing is found.
514/// Callers that require an explicit path should use
515/// [`CurlTransport::with_executable`] directly instead.
516pub fn discover_curl_executable() -> Result<PathBuf, AcquisitionError> {
517    discover_in(std::env::var_os("PATH"))
518}
519
520fn discover_in(path_var: Option<std::ffi::OsString>) -> Result<PathBuf, AcquisitionError> {
521    let path_var = path_var
522        .ok_or_else(|| AcquisitionError::__adapter_unavailable("curl not found: PATH is unset"))?;
523    #[cfg(windows)]
524    let names = vec!["curl", "curl.exe"];
525    #[cfg(not(windows))]
526    let names = vec!["curl"];
527    for dir in std::env::split_paths(&path_var) {
528        if dir.as_os_str().is_empty() {
529            continue;
530        }
531        for name in &names {
532            let candidate = dir.join(name);
533            if let Ok(meta) = fs::symlink_metadata(&candidate) {
534                if meta.is_file() {
535                    return Ok(candidate);
536                }
537            }
538        }
539    }
540    Err(AcquisitionError::__adapter_unavailable(
541        "curl not found on PATH",
542    ))
543}
544
545/// Bounds a diagnostic detail to 512 bytes, truncating only at a UTF-8
546/// character boundary.
547///
548/// The implementation lives in the seam (`eggup-acquisition`), which owns the
549/// bounded-detail rule. This adapter deliberately keeps no local copy of the
550/// truncation logic; it only delegates.
551fn bound(s: String) -> String {
552    eggup_acquisition::__adapter_bound_detail(s)
553}
554
555/// Renders the diagnostic detail for a failed `spawn()`.
556///
557/// The cause segment is derived **only** from the [`std::io::ErrorKind`]
558/// discriminant and the numeric raw OS code. The OS-provided message text is
559/// deliberately **not** rendered: it is free-form, platform-specific, and can
560/// echo a path, so rendering it would risk carrying caller-supplied material
561/// into a diagnostic that this crate's redaction rule governs.
562///
563/// Exact format:
564///
565/// ```text
566/// curl spawn failed for {redacted}: {kind}[ (os error {code})]
567/// ```
568///
569/// `{redacted}` is the **already redacted** URL; this helper must never be
570/// given the raw URL. `{kind}` is the `ErrorKind` in its `Debug` form (for
571/// example `NotFound`, `PermissionDenied`, `WouldBlock`). The ` (os error
572/// {code})` suffix is present only when the error carries a raw OS code.
573///
574/// The caller keeps the `Unavailable` classification: the cause is evidence in
575/// the detail, never a change of variant, because `Unavailable` is the only
576/// hard failure that falls back under `CompositionPolicy::UnavailableOnly`.
577fn spawn_failure_detail(redacted: &str, error: &std::io::Error) -> String {
578    let kind = format!("{:?}", error.kind());
579    match error.raw_os_error() {
580        Some(code) => format!("curl spawn failed for {redacted}: {kind} (os error {code})"),
581        None => format!("curl spawn failed for {redacted}: {kind}"),
582    }
583}
584
585/// Serializes a positive Rust `Duration` as locale-independent decimal seconds
586/// suitable for curl `--connect-timeout` and `--max-time`.
587///
588/// Curl accepts decimal seconds with a dot separator. We format at
589/// microsecond resolution and strip trailing fractional zeros, so
590/// `100 ms -> "0.1"`, `250 ms -> "0.25"`, `1.5 s -> "1.5"`, and
591/// `2 s -> "2"`. Whole-second callers observe exact equality.
592///
593/// Sub-second values never round upward: truncation to whole microseconds
594/// always produces a value `<=` the input. A positive Rust `Duration` whose
595/// precision truncates below one microsecond cannot be expressed without
596/// widening; we reject it rather than silently extending the caller's
597/// ceiling.
598fn duration_decimal_seconds(d: Duration) -> Result<String, AcquisitionError> {
599    if d.is_zero() {
600        return Err(AcquisitionError::InvalidInput(bound(
601            "duration must be positive".to_string(),
602        )));
603    }
604    let total_micros = d.as_micros();
605    if total_micros == 0 {
606        return Err(AcquisitionError::InvalidInput(bound(
607            "duration below microsecond precision cannot be represented without widening"
608                .to_string(),
609        )));
610    }
611    let secs = total_micros / 1_000_000;
612    let micros = total_micros % 1_000_000;
613    if micros == 0 {
614        Ok(secs.to_string())
615    } else {
616        let mut frac = format!("{:06}", micros);
617        while frac.ends_with('0') {
618            frac.pop();
619        }
620        Ok(format!("{secs}.{frac}"))
621    }
622}
623
624fn proxy_env_snapshot(proxy: &CurlProxy) -> Vec<(String, String)> {
625    const KEYS: &[&str] = &[
626        "HTTP_PROXY",
627        "http_proxy",
628        "HTTPS_PROXY",
629        "https_proxy",
630        "ALL_PROXY",
631        "all_proxy",
632        "NO_PROXY",
633        "no_proxy",
634    ];
635    match proxy {
636        CurlProxy::Disabled => Vec::new(),
637        CurlProxy::FromEnvironment => KEYS
638            .iter()
639            .filter_map(|k| {
640                std::env::var_os(k).map(|v| ((*k).to_string(), v.to_string_lossy().into_owned()))
641            })
642            .collect(),
643        CurlProxy::Custom(pairs) => pairs.clone(),
644    }
645}
646
647/// Protocols a redirect may target.
648///
649/// The initial request's own scheme bounds the redirect target set: an `https`
650/// request never follows a redirect down to `http`. Without this, a
651/// `302 Location: http://attacker/...` would be followed in cleartext with no
652/// error and no diagnostic, and the cleartext body would be promoted to the
653/// destination as a normal success. This matches the strict downgrade denial
654/// the native eggfetch adapter already enforces.
655fn redirect_protocols(config: &CurlConfig, url: &str) -> Vec<String> {
656    let starts_https = url
657        .split_once("://")
658        .is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("https"));
659    if !starts_https {
660        return config.allowed_protocols.clone();
661    }
662    let narrowed: Vec<String> = config
663        .allowed_protocols
664        .iter()
665        .filter(|proto| !proto.eq_ignore_ascii_case("http"))
666        .cloned()
667        .collect();
668    if narrowed.is_empty() {
669        // An https request with no non-http protocol allowed cannot succeed at
670        // all; `--proto` already rejects the initial scheme. Emit a well-formed
671        // list rather than an empty `--proto-redir`.
672        return config.allowed_protocols.clone();
673    }
674    narrowed
675}
676
677#[allow(clippy::too_many_arguments)]
678fn build_curl_args(
679    config: &CurlConfig,
680    user_agent: Option<&str>,
681    url: &str,
682    max_bytes: u64,
683    eff_connect: Duration,
684    eff_total: Duration,
685) -> Result<Vec<String>, AcquisitionError> {
686    // The caller-supplied value is re-validated here, before a single element
687    // is pushed, so an invalid value can never produce an argv and can never
688    // reach the wire.
689    if let Some(agent) = user_agent {
690        validate_user_agent(agent)?;
691    }
692    // Ignore ~/.curlrc so ambient config cannot smuggle proxy/auth policy.
693    let mut args: Vec<String> = vec![
694        "--disable".to_string(),
695        "--silent".to_string(),
696        "--show-error".to_string(),
697        "--no-progress-meter".to_string(),
698    ];
699    if config.follow_redirects {
700        args.push("--location".to_string());
701        args.push("--max-redirs".to_string());
702        args.push(config.max_redirects.to_string());
703    }
704    let connect_arg = duration_decimal_seconds(eff_connect)?;
705    let total_arg = duration_decimal_seconds(eff_total)?;
706    args.push("--connect-timeout".to_string());
707    args.push(connect_arg);
708    args.push("--max-time".to_string());
709    args.push(total_arg);
710    args.push("--max-filesize".to_string());
711    args.push(max_bytes.to_string());
712    if !config.allowed_protocols.is_empty() {
713        let list = format!("={}", config.allowed_protocols.join(","));
714        args.push("--proto".to_string());
715        args.push(list);
716        args.push("--proto-redir".to_string());
717        args.push(format!("={}", redirect_protocols(config, url).join(",")));
718    }
719    if matches!(proxy_kind(config), ProxyKind::Disabled) {
720        args.push("--noproxy".to_string());
721        args.push("*".to_string());
722    }
723    if let Some(agent) = user_agent {
724        // A literal argv element: the child is spawned without a shell, so the
725        // value is transmitted exactly as given and cannot be re-parsed as an
726        // option (curl takes the element after `--user-agent` as the value).
727        args.push("--user-agent".to_string());
728        args.push(agent.to_string());
729    }
730    args.push("--output".to_string());
731    args.push("-".to_string());
732    args.push("--write-out".to_string());
733    args.push("%{stderr}%{http_code}".to_string());
734    args.push("--".to_string());
735    args.push(url.to_string());
736    Ok(args)
737}
738
739#[derive(Debug, Clone, Copy, PartialEq, Eq)]
740enum ProxyKind {
741    Disabled,
742    Enabled,
743}
744
745fn proxy_kind(config: &CurlConfig) -> ProxyKind {
746    match &config.proxy {
747        CurlProxy::Disabled => ProxyKind::Disabled,
748        CurlProxy::FromEnvironment | CurlProxy::Custom(_) => ProxyKind::Enabled,
749    }
750}
751
752#[allow(clippy::too_many_arguments)]
753fn run_curl_to_file(
754    executable: &Path,
755    config: &CurlConfig,
756    user_agent: Option<&str>,
757    request: &AcquisitionRequest,
758    output: &Path,
759    output_file: &mut File,
760    max_bytes: u64,
761    eff_connect: Duration,
762    eff_total: Duration,
763    cancel: &CancelFlag,
764) -> Result<CurlOutcome, AcquisitionError> {
765    let url = request.url().to_string();
766    let redacted = request.redacted();
767    let args = build_curl_args(config, user_agent, &url, max_bytes, eff_connect, eff_total)?;
768    let proxy_env = proxy_env_snapshot(&config.proxy);
769    let start = Instant::now();
770    let deadline = start + eff_total;
771    let owned_file = output_file
772        .try_clone()
773        .map_err(|e| AcquisitionError::__adapter_io("cloning owned output handle", e))?;
774
775    let mut cmd = Command::new(executable);
776    cmd.args(&args)
777        .stdin(Stdio::null())
778        .stdout(Stdio::piped())
779        .stderr(Stdio::piped())
780        .env_clear();
781    for (k, v) in &proxy_env {
782        cmd.env(k, v);
783    }
784    let mut child = cmd.spawn().map_err(|e| {
785        AcquisitionError::__adapter_unavailable(spawn_failure_detail(&redacted, &e))
786    })?;
787    // Curl streams the body on stdout. A duplicate of Eggup's exclusive open
788    // file handle is moved to the reader thread; no pathname is reopened.
789    let stdout = child.stdout.take().expect("piped stdout");
790    let mut owned_file = owned_file;
791    let overflow = Arc::new(AtomicBool::new(false));
792    let overflow_reader = Arc::clone(&overflow);
793    let body_reader = std::thread::spawn(move || {
794        use std::io::{Read, Write};
795        let mut reader = stdout.take(max_bytes.saturating_add(1));
796        let mut written = 0u64;
797        let mut buf = [0u8; 16 * 1024];
798        loop {
799            let n = reader.read(&mut buf).map_err(|_| ())?;
800            if n == 0 {
801                break;
802            }
803            written = written.saturating_add(n as u64);
804            if written > max_bytes {
805                overflow_reader.store(true, Ordering::Release);
806            }
807            owned_file.write_all(&buf[..n]).map_err(|_| ())?;
808        }
809        owned_file.flush().map_err(|_| ())?;
810        Ok::<u64, ()>(written)
811    });
812    let stderr = child.stderr.take().expect("piped stderr");
813    let status_reader = std::thread::spawn(move || {
814        use std::io::Read;
815        let mut reader = stderr;
816        let mut kept = Vec::with_capacity(MAX_WRITE_OUT_BYTES as usize);
817        let mut buf = [0u8; 128];
818        loop {
819            let n = reader.read(&mut buf).map_err(|_| ())?;
820            if n == 0 {
821                break;
822            }
823            let room = (MAX_WRITE_OUT_BYTES as usize).saturating_sub(kept.len());
824            kept.extend_from_slice(&buf[..n.min(room)]);
825        }
826        Ok::<Vec<u8>, ()>(kept)
827    });
828
829    let exit_code: Option<i32> = loop {
830        if overflow.load(Ordering::Acquire) {
831            let _ = child.kill();
832            let _ = child.wait();
833            let _ = body_reader.join();
834            let _ = status_reader.join();
835            eggup_acquisition::__remove_owned_temp(output);
836            return Err(AcquisitionError::TooLarge { limit: max_bytes });
837        }
838        if cancel.is_cancelled() {
839            let _ = child.kill();
840            let _ = child.wait();
841            let _ = body_reader.join();
842            let _ = status_reader.join();
843            eggup_acquisition::__remove_owned_temp(output);
844            return Err(AcquisitionError::Cancelled);
845        }
846        match child.try_wait() {
847            Ok(Some(status)) => break status.code(),
848            Ok(None) => {
849                if Instant::now() >= deadline {
850                    let _ = child.kill();
851                    let _ = child.wait();
852                    let _ = body_reader.join();
853                    let _ = status_reader.join();
854                    eggup_acquisition::__remove_owned_temp(output);
855                    return Err(AcquisitionError::Timeout { phase: "total" });
856                }
857                std::thread::sleep(POLL_INTERVAL);
858            }
859            Err(e) => {
860                let _ = child.kill();
861                let _ = child.wait();
862                let _ = body_reader.join();
863                let _ = status_reader.join();
864                eggup_acquisition::__remove_owned_temp(output);
865                return Err(AcquisitionError::__adapter_io("waiting for curl", e));
866            }
867        }
868    };
869    let _ = child.wait();
870    let bytes_written = body_reader
871        .join()
872        .map_err(|_| {
873            AcquisitionError::__adapter_io(
874                "joining curl body reader",
875                std::io::Error::other("curl body reader failed"),
876            )
877        })?
878        .map_err(|_| {
879            AcquisitionError::__adapter_io(
880                "writing curl body",
881                std::io::Error::other("writing curl body failed"),
882            )
883        })?;
884    if bytes_written > max_bytes {
885        eggup_acquisition::__remove_owned_temp(output);
886        return Err(AcquisitionError::TooLarge { limit: max_bytes });
887    }
888    output_file
889        .flush()
890        .map_err(|e| AcquisitionError::__adapter_io("flushing owned output", e))?;
891    let code_bytes = status_reader
892        .join()
893        .map_err(|_| {
894            AcquisitionError::__adapter_io(
895                "joining curl status reader",
896                std::io::Error::other("curl status reader failed"),
897            )
898        })?
899        .map_err(|_| {
900            AcquisitionError::__adapter_io(
901                "reading curl status",
902                std::io::Error::other("reading curl status failed"),
903            )
904        })?;
905    classify_curl_result(
906        exit_code,
907        &code_bytes,
908        output,
909        &redacted,
910        start,
911        eff_connect,
912        eff_total,
913        max_bytes,
914    )
915}
916
917#[allow(clippy::too_many_arguments)]
918fn classify_curl_result(
919    exit_code: Option<i32>,
920    code_bytes: &[u8],
921    output: &Path,
922    redacted: &str,
923    start: Instant,
924    eff_connect: Duration,
925    eff_total: Duration,
926    max_bytes: u64,
927) -> Result<CurlOutcome, AcquisitionError> {
928    let elapsed = start.elapsed();
929    let code_text = String::from_utf8_lossy(code_bytes).trim().to_string();
930    let http_code: Option<u16> = code_text.parse().ok();
931    // Tolerance covers one parent polling interval plus a small scheduling
932    // margin for kill/reap latency. It must never extend the caller's
933    // deadline; it only labels an already-enforced timeout.
934    let tolerance = POLL_INTERVAL + Duration::from_millis(5);
935    match exit_code {
936        // curl operation timeout (connect or total). Distinguish by elapsed
937        // against the effective connect ceiling using only the parent
938        // scheduling tolerance, not whole-second slack.
939        Some(28) => {
940            // When the effective connect and total ceilings are equal the two
941            // are indistinguishable, and `elapsed <= eff_connect + tolerance`
942            // would hold for every exit 28 — including one caused by the total
943            // deadline. Claim only the weaker fact in that case rather than
944            // misattributing a total timeout to connection setup.
945            let phase = if eff_connect < eff_total && elapsed <= eff_connect + tolerance {
946                "connect"
947            } else {
948                "total"
949            };
950            return Err(AcquisitionError::Timeout { phase });
951        }
952        // curl --max-filesize exceeded.
953        Some(63) => {
954            eggup_acquisition::__remove_owned_temp(output);
955            return Err(AcquisitionError::TooLarge { limit: max_bytes });
956        }
957        Some(0) => {}
958        failure @ (Some(_) | None) => {
959            // Any non-zero curl exit means the transfer did not complete
960            // (partial body, TLS, connect, resolve). Even when curl still
961            // prints an HTTP code, the body is incomplete and must not be
962            // promoted. Report an ordinary transport failure.
963            eggup_acquisition::__remove_owned_temp(output);
964            return Err(AcquisitionError::Transport(bound(format!(
965                "curl transfer failed (exit {}) for {redacted}",
966                failure.map_or_else(|| "unknown".to_string(), |code| code.to_string())
967            ))));
968        }
969    }
970    match http_code {
971        Some(200..=299) => Ok(CurlOutcome::Success),
972        Some(404) => Ok(CurlOutcome::NotFound),
973        Some(status) => {
974            eggup_acquisition::__remove_owned_temp(output);
975            Err(AcquisitionError::Transport(bound(format!(
976                "HTTP {status} from {redacted}"
977            ))))
978        }
979        None => {
980            eggup_acquisition::__remove_owned_temp(output);
981            Err(AcquisitionError::Transport(bound(format!(
982                "curl status capture failed for {redacted}"
983            ))))
984        }
985    }
986}
987
988#[cfg(test)]
989mod tests {
990    use super::*;
991    use eggup_acquisition::{FixtureResponse, FixtureTransport};
992    #[cfg(not(windows))]
993    use std::io::{Read, Write};
994    #[cfg(not(windows))]
995    use std::net::TcpListener;
996    #[cfg(unix)]
997    use std::os::unix::fs::PermissionsExt;
998    #[cfg(not(windows))]
999    use std::thread;
1000
1001    // Platform gate note (M013, Defect A): the `#[cfg(not(windows))]` gate on
1002    // the loopback-server tests below is a **known, deliberate** platform
1003    // difference, not a silent coverage gap. Those tests drive a real `curl`
1004    // subprocess against an in-process loopback HTTP server; the Windows lane
1005    // exercises the same transport paths through the real `curl.exe`
1006    // integration tests instead. The gate is recorded here, at the point of
1007    // use, so a reader sees the exclusion and its reason.
1008
1009    #[test]
1010    fn exit_28_is_labelled_total_when_connect_and_total_ceilings_coincide() {
1011        let dir = temp_dir("curl-phase");
1012        let output = dir.join("body");
1013        std::fs::write(&output, b"partial").unwrap();
1014
1015        let timed_out = |eff_connect: Duration, elapsed: Duration| {
1016            let start = Instant::now() - elapsed;
1017            match classify_curl_result(
1018                Some(28),
1019                b"",
1020                &output,
1021                "https://example.com/app",
1022                start,
1023                eff_connect,
1024                Duration::from_secs(5),
1025                1024,
1026            ) {
1027                Err(AcquisitionError::Timeout { phase }) => phase,
1028                other => panic!("expected a timeout, got {other:?}"),
1029            }
1030        };
1031
1032        // Equal ceilings: a timeout past the total deadline is not a connect
1033        // timeout, and must not be reported as one.
1034        let equal = Duration::from_secs(1);
1035        assert_eq!(
1036            timed_out(equal, Duration::from_secs(5)),
1037            "total",
1038            "coincident ceilings must not label a total timeout as connect"
1039        );
1040
1041        // Genuinely tighter connect ceiling, expired: still a connect timeout.
1042        assert_eq!(
1043            timed_out(Duration::from_secs(1), Duration::from_millis(1)),
1044            "connect"
1045        );
1046
1047        // Connect ceiling not expired: the total deadline is what expired.
1048        assert_eq!(
1049            timed_out(Duration::from_secs(1), Duration::from_secs(5)),
1050            "total"
1051        );
1052    }
1053
1054    #[test]
1055    fn diagnostic_bound_never_splits_multibyte_code_points() {
1056        for ch in ["é", "€", "🦀"] {
1057            let prefix = "x".repeat(511);
1058            let bounded = bound(format!("{prefix}{ch}tail"));
1059            assert_eq!(bounded, prefix);
1060            assert!(bounded.len() <= 512);
1061        }
1062    }
1063
1064    fn req(url: &str) -> AcquisitionRequest {
1065        AcquisitionRequest::new(url).unwrap()
1066    }
1067
1068    fn limits() -> FetchLimits {
1069        FetchLimits {
1070            max_metadata_bytes: 64 * 1024,
1071            max_artifact_bytes: 256 * 1024,
1072            connect_timeout: Duration::from_secs(2),
1073            total_timeout: Duration::from_secs(10),
1074        }
1075    }
1076
1077    fn temp_dir(prefix: &str) -> PathBuf {
1078        let nanos = std::time::SystemTime::now()
1079            .duration_since(std::time::UNIX_EPOCH)
1080            .map(|d| d.as_nanos())
1081            .unwrap_or(0);
1082        let p = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()));
1083        let _ = fs::create_dir_all(&p);
1084        p
1085    }
1086
1087    fn real_curl() -> Option<PathBuf> {
1088        discover_curl_executable().ok()
1089    }
1090
1091    /// Requires a discoverable system `curl` executable.
1092    ///
1093    /// M013, Defect A, treatment (a): the tests that use this helper drive the
1094    /// **real** curl subprocess. There is no fixture or stub that can stand in
1095    /// for it, so when no `curl` is discoverable the test must fail loudly with
1096    /// the missing prerequisite and the remedy. It must never report a pass
1097    /// while asserting nothing.
1098    fn require_curl_executable() -> PathBuf {
1099        match real_curl() {
1100            Some(exe) => exe,
1101            None => panic!(
1102                "no `curl` executable was discoverable on PATH. This test drives the real curl \
1103                 subprocess and has nothing to assert without one. Install curl (for example \
1104                 `brew install curl`) or put a curl executable on PATH, then re-run \
1105                 `cargo test -p eggup-curl`."
1106            ),
1107        }
1108    }
1109
1110    /// Builds a strict transport over the discovered system `curl`, failing
1111    /// loudly when no `curl` is discoverable (M013, Defect A, treatment (a)).
1112    fn require_transport() -> CurlTransport {
1113        let exe = require_curl_executable();
1114        CurlTransport::with_executable(exe, CurlConfig::strict())
1115            .expect("strict curl transport must build from a discovered curl executable")
1116    }
1117
1118    #[cfg(not(windows))]
1119    fn serve_once(
1120        status: u16,
1121        headers: Vec<(String, String)>,
1122        body: Vec<u8>,
1123        stall_before_body_ms: u64,
1124        abort_after_headers: bool,
1125    ) -> String {
1126        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
1127        let addr = listener.local_addr().unwrap();
1128        thread::spawn(move || {
1129            if let Ok((mut stream, _)) = listener.accept() {
1130                stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
1131                stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
1132                let mut buf = [0u8; 8192];
1133                let _ = stream.read(&mut buf);
1134                let reason = match status {
1135                    200 => "OK",
1136                    302 => "Found",
1137                    404 => "Not Found",
1138                    500 => "Internal Server Error",
1139                    _ => "OK",
1140                };
1141                let mut head = format!("HTTP/1.1 {status} {reason}\r\n");
1142                for (k, v) in headers {
1143                    head.push_str(&format!("{k}: {v}\r\n"));
1144                }
1145                head.push_str("Connection: close\r\n\r\n");
1146                let _ = stream.write_all(head.as_bytes());
1147                if abort_after_headers {
1148                    return;
1149                }
1150                if stall_before_body_ms > 0 {
1151                    thread::sleep(Duration::from_millis(stall_before_body_ms));
1152                }
1153                let _ = stream.write_all(&body);
1154            }
1155        });
1156        format!("http://{addr}")
1157    }
1158
1159    #[cfg(not(windows))]
1160    fn ok_server(body: Vec<u8>) -> String {
1161        serve_once(
1162            200,
1163            vec![
1164                ("Content-Length".into(), body.len().to_string()),
1165                ("Content-Type".into(), "application/octet-stream".into()),
1166            ],
1167            body,
1168            0,
1169            false,
1170        )
1171    }
1172
1173    /// Serves one request and records the raw request head the client sent.
1174    ///
1175    /// `serve_once` proves the adapter's behavior; this variant additionally
1176    /// captures what the peer actually received, so a header the adapter sets
1177    /// can be asserted on the wire rather than only in the child's argv.
1178    /// The head is written before the response is sent, so a client that has
1179    /// received the response is guaranteed to find the record on disk.
1180    #[cfg(not(windows))]
1181    fn serve_once_recording_head(status: u16, body: Vec<u8>, record: &Path) -> String {
1182        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
1183        let addr = listener.local_addr().unwrap();
1184        let record = record.to_path_buf();
1185        thread::spawn(move || {
1186            if let Ok((mut stream, _)) = listener.accept() {
1187                stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
1188                stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
1189                let mut buf = [0u8; 8192];
1190                let read = stream.read(&mut buf).unwrap_or(0);
1191                let _ = fs::write(&record, &buf[..read]);
1192                let reason = match status {
1193                    200 => "OK",
1194                    404 => "Not Found",
1195                    500 => "Internal Server Error",
1196                    _ => "OK",
1197                };
1198                let mut head = format!("HTTP/1.1 {status} {reason}\r\n");
1199                head.push_str(&format!("Content-Length: {}\r\n", body.len()));
1200                head.push_str("Content-Type: application/octet-stream\r\n");
1201                head.push_str("Connection: close\r\n\r\n");
1202                let _ = stream.write_all(head.as_bytes());
1203                let _ = stream.write_all(&body);
1204            }
1205        });
1206        format!("http://{addr}")
1207    }
1208
1209    /// Minimal fake curl executable (Unix-only): writes a fixed body to stdout
1210    /// and a fixed HTTP code to stderr. Records
1211    /// argv/env for policy assertions.
1212    ///
1213    /// Unix-only because it relies on `sh` + `xxd` and Unix executable-mode
1214    /// setup. Windows exercises the same transport paths through the real
1215    /// `curl.exe` integration tests and the platform-neutral unit tests below;
1216    /// shell-dependent fake-child tests are `#[cfg(unix)]`-gated, never the
1217    /// whole module.
1218    #[cfg(unix)]
1219    fn fake_curl_script(body: &[u8], code: &str, exit: i32, record_dir: &Path) -> PathBuf {
1220        let dir = record_dir.to_path_buf();
1221        let script = dir.join(format!(
1222            "fake-curl-{}-{}.sh",
1223            std::process::id(),
1224            std::time::SystemTime::now()
1225                .duration_since(std::time::UNIX_EPOCH)
1226                .map(|d| d.as_nanos())
1227                .unwrap_or(0)
1228        ));
1229        let body_hex: String = body.iter().map(|b| format!("{b:02x}")).collect();
1230        let content = format!(
1231            "#!/bin/sh\n\
1232             echo \"$@\" > \"{rec}/argv\"\n\
1233             env > \"{rec}/env\"\n\
1234             printf '{hex}' | xxd -r -p\n\\
1235             printf '{code}' >&2\n\\
1236             exit {exit}\n",
1237            rec = dir.display(),
1238            hex = body_hex,
1239            code = code,
1240            exit = exit,
1241        );
1242        fs::write(&script, content).unwrap();
1243        let mut perms = fs::metadata(&script).unwrap().permissions();
1244        perms.set_mode(0o700);
1245        fs::set_permissions(&script, perms).unwrap();
1246        script
1247    }
1248
1249    #[test]
1250    fn executable_selection_and_discovery_are_explicit() {
1251        // Empty path is invalid input, not unavailable.
1252        let err = CurlTransport::with_executable("", CurlConfig::strict()).unwrap_err();
1253        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
1254        // Invalid config fails closed at construction.
1255        let bad = CurlConfig::strict().timeouts(Duration::ZERO, Duration::from_secs(1));
1256        let err = CurlTransport::with_executable("/usr/bin/curl", bad).unwrap_err();
1257        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
1258        // Discovery is opt-in and returns a real file when curl exists.
1259        if let Ok(path) = discover_curl_executable() {
1260            assert!(fs::symlink_metadata(&path).unwrap().is_file());
1261        }
1262        // Absent PATH entry yields typed Unavailable, never Transport.
1263        // Uses the injectable helper so parallel tests never mutate process PATH.
1264        let err = discover_in(Some("/nonexistent-eggup-curl-path-xyz".into())).unwrap_err();
1265        assert!(matches!(err, AcquisitionError::Unavailable(_)));
1266        assert!(err.is_unavailable());
1267        let err = discover_in(None).unwrap_err();
1268        assert!(matches!(err, AcquisitionError::Unavailable(_)));
1269    }
1270
1271    #[test]
1272    fn missing_executable_and_spawn_failure_are_unavailable() {
1273        let t = CurlTransport::with_executable(
1274            "/nonexistent-eggup-curl-binary-xyz",
1275            CurlConfig::strict(),
1276        )
1277        .unwrap();
1278        let err = t
1279            .fetch_metadata(&req("http://127.0.0.1:1/x"), limits(), &CancelFlag::new())
1280            .unwrap_err();
1281        assert!(matches!(err, AcquisitionError::Unavailable(_)));
1282        let dir = temp_dir("curl-unavail");
1283        let dest = dir.join("app");
1284        let err = t
1285            .fetch_artifact(
1286                &req("http://127.0.0.1:1/x"),
1287                &dest,
1288                limits(),
1289                &CancelFlag::new(),
1290            )
1291            .unwrap_err();
1292        assert!(matches!(err, AcquisitionError::Unavailable(_)));
1293        assert!(!dest.exists());
1294        let _ = fs::remove_dir_all(&dir);
1295    }
1296
1297    /// M015 (§6.1, §10): a spawn failure keeps the `Unavailable`
1298    /// classification **and** now carries the OS cause.
1299    ///
1300    /// Before this milestone the `io::Error` returned by `Command::spawn()` was
1301    /// discarded by a `map_err(|_| …)`, so a missing executable (`ENOENT`), a
1302    /// non-executable file (`EACCES`), and a transient resource failure
1303    /// (`EAGAIN`) all rendered the identical, cause-free string
1304    /// `curl spawn failed for {redacted}`. A hosted CI run failed with exactly
1305    /// that message and could not be attributed, because the diagnostic carried
1306    /// no way to tell the causes apart.
1307    ///
1308    /// The expected cause is observed **independently** here — this test
1309    /// performs its own spawn of the same missing path and reads the platform's
1310    /// own error — so the assertion is not circular with the adapter's
1311    /// rendering and does not hard-code a platform-specific errno.
1312    ///
1313    /// Deterministic by construction: no network, no wall-clock budget, no
1314    /// `PATH` dependency, and no real `curl` required.
1315    #[test]
1316    fn spawn_failure_detail_names_the_os_cause_and_stays_unavailable() {
1317        const MISSING: &str = "/nonexistent-eggup-curl-binary-m015";
1318        const USERINFO: &str = "S3CR3T-USERINFO-9917";
1319        const QUERY: &str = "TOKEN-QUERY-5523";
1320        const FRAGMENT: &str = "FRAG-SENTINEL-7788";
1321        let url = format!("https://user:{USERINFO}@example.com/x?token={QUERY}#{FRAGMENT}");
1322
1323        // The platform's own error for this spawn, observed independently.
1324        let observed = std::process::Command::new(MISSING)
1325            .spawn()
1326            .expect_err("spawning a missing executable must fail");
1327        let expected_kind = format!("{:?}", observed.kind());
1328
1329        let t = CurlTransport::with_executable(MISSING, CurlConfig::strict()).unwrap();
1330        let err = t
1331            .fetch_metadata(&req(&url), limits(), &CancelFlag::new())
1332            .unwrap_err();
1333
1334        // (a) The classification is unchanged: still `Unavailable`, still
1335        // eligible for fallback under `CompositionPolicy::UnavailableOnly`.
1336        assert!(matches!(err, AcquisitionError::Unavailable(_)));
1337        assert!(err.is_unavailable());
1338
1339        let detail = match &err {
1340            AcquisitionError::Unavailable(detail) => detail.clone(),
1341            other => panic!("expected Unavailable, got {other:?}"),
1342        };
1343
1344        // (b) The detail now names the OS cause.
1345        assert!(
1346            detail.contains(&expected_kind),
1347            "detail does not name the ErrorKind {expected_kind}: {detail}"
1348        );
1349        match observed.raw_os_error() {
1350            Some(code) => assert!(
1351                detail.contains(&format!("os error {code}")),
1352                "detail does not carry the raw OS code {code}: {detail}"
1353            ),
1354            None => assert!(
1355                !detail.contains("os error"),
1356                "detail carries an OS code the platform did not produce: {detail}"
1357            ),
1358        }
1359        assert!(
1360            detail.starts_with("curl spawn failed for "),
1361            "detail lost the established prefix: {detail}"
1362        );
1363
1364        // (b') The exact documented format is pinned, so it cannot drift
1365        // silently: `curl spawn failed for {redacted}: {kind}[ (os error {code})]`.
1366        let redacted = eggup_acquisition::redact_url(&url);
1367        let expected_detail = match observed.raw_os_error() {
1368            Some(code) => {
1369                format!("curl spawn failed for {redacted}: {expected_kind} (os error {code})")
1370            }
1371            None => format!("curl spawn failed for {redacted}: {expected_kind}"),
1372        };
1373        assert_eq!(detail, expected_detail);
1374
1375        // (c) The detail carries no URL or credential material, and the
1376        // redaction of the URL is preserved.
1377        assert!(!detail.contains(USERINFO), "userinfo leaked: {detail}");
1378        assert!(!detail.contains(QUERY), "query leaked: {detail}");
1379        assert!(!detail.contains(FRAGMENT), "fragment leaked: {detail}");
1380        assert!(detail.contains("<redacted>"), "redaction lost: {detail}");
1381
1382        // (d) The detail stays bounded by the seam's shared rule.
1383        assert!(detail.len() <= 512, "detail is not bounded: {detail}");
1384    }
1385
1386    #[test]
1387    #[cfg(not(windows))]
1388    fn metadata_success_not_found_and_server_error() {
1389        let t = require_transport();
1390        let base = ok_server(b"hello-curl-meta".to_vec());
1391        let out = t
1392            .fetch_metadata(&req(&format!("{base}/meta")), limits(), &CancelFlag::new())
1393            .unwrap();
1394        assert_eq!(out.success().unwrap().bytes(), b"hello-curl-meta");
1395
1396        let base = serve_once(404, vec![], b"nope".to_vec(), 0, false);
1397        let out = t
1398            .fetch_metadata(&req(&format!("{base}/m")), limits(), &CancelFlag::new())
1399            .unwrap();
1400        assert!(out.is_not_found());
1401
1402        let base = serve_once(500, vec![], b"boom".to_vec(), 0, false);
1403        let err = t
1404            .fetch_metadata(&req(&format!("{base}/e")), limits(), &CancelFlag::new())
1405            .unwrap_err();
1406        assert!(matches!(err, AcquisitionError::Transport(_)));
1407        assert!(!matches!(err, AcquisitionError::Unavailable(_)));
1408    }
1409
1410    #[test]
1411    #[cfg(not(windows))]
1412    fn artifact_success_not_found_and_server_error() {
1413        let t = require_transport();
1414        let body: Vec<u8> = (0..4096).map(|i| (i % 251) as u8).collect();
1415        let base = ok_server(body.clone());
1416        let dir = temp_dir("curl-artifact");
1417        let dest = dir.join("app");
1418        let out = t
1419            .fetch_artifact(
1420                &req(&format!("{base}/app")),
1421                &dest,
1422                limits(),
1423                &CancelFlag::new(),
1424            )
1425            .unwrap();
1426        assert_eq!(out.success().unwrap().bytes_written, 4096);
1427        assert_eq!(fs::read(&dest).unwrap(), body);
1428
1429        let base = serve_once(404, vec![], b"no".to_vec(), 0, false);
1430        let dest2 = dir.join("missing");
1431        let out = t
1432            .fetch_artifact(
1433                &req(&format!("{base}/m")),
1434                &dest2,
1435                limits(),
1436                &CancelFlag::new(),
1437            )
1438            .unwrap();
1439        assert!(out.is_not_found());
1440        assert!(!dest2.exists());
1441
1442        let base = serve_once(500, vec![], b"boom".to_vec(), 0, false);
1443        let dest3 = dir.join("err");
1444        let err = t
1445            .fetch_artifact(
1446                &req(&format!("{base}/e")),
1447                &dest3,
1448                limits(),
1449                &CancelFlag::new(),
1450            )
1451            .unwrap_err();
1452        assert!(matches!(err, AcquisitionError::Transport(_)));
1453        assert!(!dest3.exists());
1454        let _ = fs::remove_dir_all(&dir);
1455    }
1456
1457    #[cfg(unix)]
1458    #[test]
1459    fn tls_like_process_failure_is_transport_not_unavailable() {
1460        let dir = temp_dir("curl-tls");
1461        let script = fake_curl_script(b"", "", 35, &dir);
1462        let t =
1463            CurlTransport::with_executable(&script, CurlConfig::strict()).expect("fake transport");
1464        let err = t
1465            .fetch_metadata(&req("https://example.com/x"), limits(), &CancelFlag::new())
1466            .unwrap_err();
1467        assert!(matches!(err, AcquisitionError::Transport(_)));
1468        assert!(!err.is_unavailable());
1469        let _ = fs::remove_dir_all(&dir);
1470    }
1471
1472    #[test]
1473    #[cfg(not(windows))]
1474    fn truncated_transfer_is_hard_failure_without_promotion() {
1475        let t = require_transport();
1476        let body = vec![5u8; 4096];
1477        let base = serve_once(
1478            200,
1479            vec![("Content-Length".into(), "4096".into())],
1480            body,
1481            0,
1482            true,
1483        );
1484        let dir = temp_dir("curl-trunc");
1485        let dest = dir.join("app");
1486        let err = t
1487            .fetch_artifact(
1488                &req(&format!("{base}/app")),
1489                &dest,
1490                limits(),
1491                &CancelFlag::new(),
1492            )
1493            .unwrap_err();
1494        assert!(matches!(err, AcquisitionError::Transport(_)));
1495        assert!(!dest.exists());
1496        let _ = fs::remove_dir_all(&dir);
1497    }
1498
1499    #[test]
1500    #[cfg(not(windows))]
1501    fn metadata_and_artifact_size_overflow() {
1502        let t = require_transport();
1503        let big = vec![9u8; 128 * 1024];
1504        let base = ok_server(big);
1505        let err = t
1506            .fetch_metadata(&req(&format!("{base}/big")), limits(), &CancelFlag::new())
1507            .unwrap_err();
1508        assert!(matches!(err, AcquisitionError::TooLarge { .. }));
1509
1510        let body = vec![1u8; 8192];
1511        let base = ok_server(body);
1512        let dir = temp_dir("curl-overflow");
1513        let dest = dir.join("app");
1514        let small = FetchLimits {
1515            max_metadata_bytes: 64 * 1024,
1516            max_artifact_bytes: 1024,
1517            connect_timeout: Duration::from_secs(2),
1518            total_timeout: Duration::from_secs(10),
1519        };
1520        let err = t
1521            .fetch_artifact(
1522                &req(&format!("{base}/app")),
1523                &dest,
1524                small,
1525                &CancelFlag::new(),
1526            )
1527            .unwrap_err();
1528        assert!(matches!(err, AcquisitionError::TooLarge { .. }));
1529        assert!(!dest.exists());
1530        let _ = fs::remove_dir_all(&dir);
1531    }
1532
1533    /// Total-phase timeout, proven end to end against a real `curl`.
1534    ///
1535    /// M013, Defect A, treatment (a): the fixture must exist, so a missing
1536    /// `curl` fails loudly instead of reporting a vacuous pass.
1537    #[test]
1538    #[cfg(not(windows))]
1539    fn total_phase_timeout_is_typed_end_to_end() {
1540        let t = require_transport();
1541        // Slow body with a short total ceiling.
1542        let body = vec![2u8; 1024];
1543        let base = serve_once(
1544            200,
1545            vec![("Content-Length".into(), body.len().to_string())],
1546            body,
1547            5000,
1548            false,
1549        );
1550        let short_total = FetchLimits {
1551            max_metadata_bytes: 64 * 1024,
1552            max_artifact_bytes: 256 * 1024,
1553            connect_timeout: Duration::from_millis(500),
1554            total_timeout: Duration::from_secs(2),
1555        };
1556        let err = t
1557            .fetch_metadata(
1558                &req(&format!("{base}/slow")),
1559                short_total,
1560                &CancelFlag::new(),
1561            )
1562            .unwrap_err();
1563        assert!(
1564            matches!(err, AcquisitionError::Timeout { phase: "total" }),
1565            "expected a total-phase timeout, got {err}"
1566        );
1567    }
1568
1569    /// Connect-phase timeout, proven end to end — **environment-conditional**.
1570    ///
1571    /// M013, Defect A, treatment (b): this proof needs a host that blackholes
1572    /// the route to the probe address so the connect ceiling expires. Most
1573    /// hosts and CI runners reject the connection immediately with
1574    /// `ENETUNREACH`/`EHOSTUNREACH`, which is an ordinary transport failure,
1575    /// not a timeout. The test is therefore marked as ignored with a recorded
1576    /// reason and is reported as *ignored*, never as *passed*, and it never
1577    /// exits silently: when it is run explicitly it asserts the exact
1578    /// connect-phase label. The connect/total **label** is proven
1579    /// deterministically, with no subprocess and no network, by
1580    /// `classify_curl_result_labels_connect_and_total_without_a_subprocess`.
1581    #[test]
1582    #[cfg(not(windows))]
1583    #[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"]
1584    fn connect_phase_timeout_is_typed_end_to_end() {
1585        let t = require_transport();
1586        // Unroutable connect with a short connect ceiling.
1587        let short_connect = FetchLimits {
1588            max_metadata_bytes: 64 * 1024,
1589            max_artifact_bytes: 256 * 1024,
1590            connect_timeout: Duration::from_millis(500),
1591            total_timeout: Duration::from_secs(10),
1592        };
1593        let err = t
1594            .fetch_metadata(
1595                &req("http://10.255.255.1:81/unreachable"),
1596                short_connect,
1597                &CancelFlag::new(),
1598            )
1599            .unwrap_err();
1600        assert!(
1601            matches!(err, AcquisitionError::Timeout { phase: "connect" }),
1602            "expected a connect-phase timeout, got {err}"
1603        );
1604    }
1605
1606    /// The connect/total timeout label, proven without a subprocess and
1607    /// without a network.
1608    ///
1609    /// M013, Defect A: because the end-to-end connect-phase proof is
1610    /// environment-conditional, the *label* is pinned here at the
1611    /// `classify_curl_result` layer by injecting `start`. The injected
1612    /// elapsed times are whole seconds, so the assertion never depends on a
1613    /// sub-second wall-clock budget.
1614    #[test]
1615    fn classify_curl_result_labels_connect_and_total_without_a_subprocess() {
1616        let dir = temp_dir("curl-phase-label");
1617        let output = dir.join("body");
1618        fs::write(&output, b"partial").unwrap();
1619
1620        let phase_for = |eff_connect: Duration, eff_total: Duration, elapsed: Duration| {
1621            let start = Instant::now() - elapsed;
1622            match classify_curl_result(
1623                Some(28),
1624                b"",
1625                &output,
1626                "https://example.com/app",
1627                start,
1628                eff_connect,
1629                eff_total,
1630                1024,
1631            ) {
1632                Err(AcquisitionError::Timeout { phase }) => phase,
1633                other => panic!("expected a timeout, got {other:?}"),
1634            }
1635        };
1636
1637        // A strictly tighter connect ceiling that has expired labels the
1638        // failure as a connect timeout.
1639        assert_eq!(
1640            phase_for(
1641                Duration::from_secs(2),
1642                Duration::from_secs(20),
1643                Duration::from_secs(2),
1644            ),
1645            "connect",
1646            "an expired, strictly tighter connect ceiling must label a connect timeout"
1647        );
1648        // The same ceilings with the elapsed time past the connect ceiling
1649        // label the failure as a total timeout.
1650        assert_eq!(
1651            phase_for(
1652                Duration::from_secs(2),
1653                Duration::from_secs(20),
1654                Duration::from_secs(5),
1655            ),
1656            "total",
1657            "an elapsed time past the connect ceiling must label a total timeout"
1658        );
1659        // Coincident ceilings are indistinguishable, so the weaker total
1660        // claim is the only honest one.
1661        assert_eq!(
1662            phase_for(
1663                Duration::from_secs(2),
1664                Duration::from_secs(2),
1665                Duration::from_secs(5),
1666            ),
1667            "total",
1668            "coincident ceilings must not label a total timeout as connect"
1669        );
1670        let _ = fs::remove_dir_all(&dir);
1671    }
1672
1673    #[test]
1674    fn duration_decimal_seconds_serializes_sub_second_inputs_truthfully() {
1675        // Sub-second positive durations produce decimal-second text that
1676        // never exceeds the input when curl parses it back.
1677        let cases = [
1678            (Duration::from_micros(1), "0.000001"),
1679            (Duration::from_micros(500), "0.0005"),
1680            (Duration::from_millis(1), "0.001"),
1681            (Duration::from_millis(100), "0.1"),
1682            (Duration::from_millis(250), "0.25"),
1683            (Duration::from_millis(500), "0.5"),
1684            (Duration::from_millis(1500), "1.5"),
1685            (Duration::from_secs(2), "2"),
1686            (Duration::from_secs(120), "120"),
1687        ];
1688        for (input, expected) in cases {
1689            let rendered = duration_decimal_seconds(input).expect("serializes");
1690            assert_eq!(rendered, expected, "input {input:?}");
1691        }
1692        // Whole-second values never gain a spurious fractional part.
1693        let rendered = duration_decimal_seconds(Duration::from_secs(7)).unwrap();
1694        assert_eq!(rendered, "7");
1695        // Zero is rejected.
1696        assert!(duration_decimal_seconds(Duration::ZERO).is_err());
1697        // Positive durations that truncate below one microsecond cannot be
1698        // represented without widening and must be rejected.
1699        let sub_micros = Duration::from_nanos(500);
1700        assert!(duration_decimal_seconds(sub_micros).is_err());
1701    }
1702
1703    #[test]
1704    fn https_request_never_allows_a_cleartext_redirect_target() {
1705        let cfg = CurlConfig::strict();
1706        let value_after = |args: &[String], flag: &str| -> String {
1707            let idx = args.iter().position(|a| a == flag).expect("flag present");
1708            args[idx + 1].clone()
1709        };
1710
1711        // The initial request may still use http; only the redirect target set
1712        // is narrowed.
1713        let https = build_curl_args(
1714            &cfg,
1715            None,
1716            "https://example.com/artifact",
1717            1024,
1718            Duration::from_secs(1),
1719            Duration::from_secs(5),
1720        )
1721        .expect("builds");
1722        assert_eq!(value_after(&https, "--proto"), "=http,https");
1723        assert_eq!(value_after(&https, "--proto-redir"), "=https");
1724
1725        // A cleartext request may still be redirected to either scheme.
1726        let http = build_curl_args(
1727            &cfg,
1728            None,
1729            "http://example.com/artifact",
1730            1024,
1731            Duration::from_secs(1),
1732            Duration::from_secs(5),
1733        )
1734        .expect("builds");
1735        assert_eq!(value_after(&http, "--proto"), "=http,https");
1736        assert_eq!(value_after(&http, "--proto-redir"), "=http,https");
1737
1738        // Scheme comparison is case-insensitive, as URLs are.
1739        let upper = build_curl_args(
1740            &cfg,
1741            None,
1742            "HTTPS://example.com/artifact",
1743            1024,
1744            Duration::from_secs(1),
1745            Duration::from_secs(5),
1746        )
1747        .expect("builds");
1748        assert_eq!(value_after(&upper, "--proto-redir"), "=https");
1749
1750        // A configuration that allows only http cannot fetch https at all; the
1751        // list stays well-formed rather than becoming empty.
1752        let http_only = CurlConfig::strict().allowed_protocols(vec!["http".to_string()]);
1753        let denied = build_curl_args(
1754            &http_only,
1755            None,
1756            "https://example.com/artifact",
1757            1024,
1758            Duration::from_secs(1),
1759            Duration::from_secs(5),
1760        )
1761        .expect("builds");
1762        assert_eq!(value_after(&denied, "--proto-redir"), "=http");
1763    }
1764
1765    #[test]
1766    fn build_curl_args_passes_decimal_deadlines_never_above_ceiling() {
1767        let cfg = CurlConfig::strict();
1768        let cases = [
1769            (
1770                Duration::from_millis(100),
1771                Duration::from_secs(1),
1772                "0.1",
1773                "1",
1774            ),
1775            (
1776                Duration::from_millis(250),
1777                Duration::from_millis(1500),
1778                "0.25",
1779                "1.5",
1780            ),
1781            (Duration::from_secs(2), Duration::from_secs(5), "2", "5"),
1782            (
1783                Duration::from_micros(500),
1784                Duration::from_micros(750),
1785                "0.0005",
1786                "0.00075",
1787            ),
1788        ];
1789        for (connect, total, expected_connect, expected_total) in cases {
1790            let args = build_curl_args(&cfg, None, "https://example.com/x", 1024, connect, total)
1791                .expect("builds");
1792            let connect_idx = args
1793                .iter()
1794                .position(|a| a == "--connect-timeout")
1795                .expect("connect-timeout present");
1796            let total_idx = args
1797                .iter()
1798                .position(|a| a == "--max-time")
1799                .expect("max-time present");
1800            assert_eq!(args[connect_idx + 1], expected_connect);
1801            assert_eq!(args[total_idx + 1], expected_total);
1802        }
1803        // Sub-microsecond positive durations must fail validation rather
1804        // than widen to a second.
1805        let err = build_curl_args(
1806            &cfg,
1807            None,
1808            "https://example.com/x",
1809            1024,
1810            Duration::from_nanos(500),
1811            Duration::from_millis(500),
1812        );
1813        assert!(matches!(err, Err(AcquisitionError::InvalidInput(_))));
1814    }
1815
1816    /// M012 (§6.2): the deterministic half of the sub-second serialization
1817    /// proof.
1818    ///
1819    /// A sub-second `--max-time` cannot be proven end-to-end, because the
1820    /// parent's deadline *is* the effective total ceiling — proving it would
1821    /// need a sub-second wall-clock budget. It is proven here instead, at the
1822    /// layer where the rule lives: `build_curl_args`, with no subprocess, no
1823    /// network, and no wall clock at all. This retains the coverage that
1824    /// `build_curl_args_passes_sub_second_deadlines_to_fake_curl` had to give
1825    /// up in order to become deterministic.
1826    #[test]
1827    fn sub_second_deadlines_serialize_truthfully_without_a_subprocess() {
1828        let cfg = CurlConfig::strict();
1829        let value_after = |args: &[String], flag: &str| -> String {
1830            let idx = args.iter().position(|a| a == flag).expect("flag present");
1831            args[idx + 1].clone()
1832        };
1833        let sub_second_pair = FetchLimits {
1834            max_metadata_bytes: 64 * 1024,
1835            max_artifact_bytes: 256 * 1024,
1836            connect_timeout: Duration::from_millis(250),
1837            total_timeout: Duration::from_millis(750),
1838        };
1839
1840        // A sub-second connect *and* sub-second total pair serializes to
1841        // truthful decimal seconds.
1842        let (eff_connect, eff_total) = cfg.effective_timeouts(sub_second_pair);
1843        assert_eq!(eff_connect, Duration::from_millis(250));
1844        assert_eq!(eff_total, Duration::from_millis(750));
1845        let args = build_curl_args(
1846            &cfg,
1847            None,
1848            "https://example.com/x",
1849            1024,
1850            eff_connect,
1851            eff_total,
1852        )
1853        .expect("builds");
1854        assert_eq!(value_after(&args, "--connect-timeout"), "0.25");
1855        assert_eq!(value_after(&args, "--max-time"), "0.75");
1856
1857        // `--max-time` is the *effective* total ceiling, never the raw
1858        // request, when the adapter ceiling is the lower of the two.
1859        let capped =
1860            CurlConfig::strict().timeouts(Duration::from_millis(100), Duration::from_millis(400));
1861        let (capped_connect, capped_total) = capped.effective_timeouts(sub_second_pair);
1862        assert_eq!(capped_connect, Duration::from_millis(100));
1863        assert_eq!(capped_total, Duration::from_millis(400));
1864        let capped_args = build_curl_args(
1865            &capped,
1866            None,
1867            "https://example.com/x",
1868            1024,
1869            capped_connect,
1870            capped_total,
1871        )
1872        .expect("builds");
1873        assert_eq!(value_after(&capped_args, "--connect-timeout"), "0.1");
1874        assert_eq!(value_after(&capped_args, "--max-time"), "0.4");
1875        assert_ne!(
1876            value_after(&capped_args, "--max-time"),
1877            "0.75",
1878            "--max-time must be the effective ceiling, never the raw request"
1879        );
1880
1881        // Sub-microsecond positive durations still fail validation rather
1882        // than widen to a second.
1883        let err = build_curl_args(
1884            &cfg,
1885            None,
1886            "https://example.com/x",
1887            1024,
1888            Duration::from_nanos(500),
1889            Duration::from_millis(500),
1890        );
1891        assert!(matches!(err, Err(AcquisitionError::InvalidInput(_))));
1892    }
1893
1894    /// M012 (§6.1): the *asserted* serialization is decoupled from the
1895    /// *enforced* wall-clock budget.
1896    ///
1897    /// The invariant under test is that a sub-second `FetchLimits` deadline is
1898    /// serialized truthfully into the spawned child's argv. The former
1899    /// version also made those same sub-second values the live parent
1900    /// deadline, so the assertion doubled as a claim about host scheduling
1901    /// and failed whenever the host was loaded: the parent deadline was the
1902    /// only enforcement (the fake child ignores `--connect-timeout` and
1903    /// `--max-time`), so a busy host expired the deadline the test was
1904    /// trying to succeed inside.
1905    ///
1906    /// Here the connect deadline stays sub-second and is still proven
1907    /// end-to-end through a real spawn, while the total budget is generous,
1908    /// so no host scheduling decision can expire it.
1909    ///
1910    /// A sub-second `--max-time` cannot be proven end-to-end at all: the
1911    /// parent's deadline *is* the effective total ceiling, so proving it
1912    /// would require a sub-second wall-clock budget. That half is proven
1913    /// deterministically, with no subprocess and no wall clock, by
1914    /// `sub_second_deadlines_serialize_truthfully_without_a_subprocess`.
1915    #[cfg(unix)]
1916    #[test]
1917    fn build_curl_args_passes_sub_second_deadlines_to_fake_curl() {
1918        let dir = temp_dir("curl-decode-args");
1919        let script = fake_curl_script(b"", "200", 0, &dir);
1920        let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
1921        let cfg = FetchLimits {
1922            max_metadata_bytes: 64 * 1024,
1923            max_artifact_bytes: 256 * 1024,
1924            connect_timeout: Duration::from_millis(250),
1925            // Generous on purpose: the total budget is not the thing under
1926            // test, and a sub-second value here would re-couple the
1927            // assertion to the host's scheduler.
1928            total_timeout: Duration::from_secs(30),
1929        };
1930        t.fetch_metadata(&req("https://example.com/x"), cfg, &CancelFlag::new())
1931            .expect("fake curl completes well inside the 30s budget");
1932        let argv = fs::read_to_string(dir.join("argv")).unwrap();
1933        assert!(
1934            argv.contains("--connect-timeout 0.25"),
1935            "argv missing 0.25: {argv}"
1936        );
1937        assert!(argv.contains("--max-time 30"), "argv missing 30: {argv}");
1938        let _ = fs::remove_dir_all(&dir);
1939    }
1940
1941    #[test]
1942    #[cfg(not(windows))]
1943    fn sub_second_total_timeout_kills_child_promptly() {
1944        let t = require_transport();
1945        let body = vec![7u8; 8192];
1946        let base = serve_once(
1947            200,
1948            vec![("Content-Length".into(), body.len().to_string())],
1949            body,
1950            4000,
1951            false,
1952        );
1953        let short_total = FetchLimits {
1954            max_metadata_bytes: 64 * 1024,
1955            max_artifact_bytes: 256 * 1024,
1956            connect_timeout: Duration::from_millis(100),
1957            total_timeout: Duration::from_millis(250),
1958        };
1959        let dir = temp_dir("curl-subsec-total");
1960        let dest = dir.join("app");
1961        let started = Instant::now();
1962        let err = t
1963            .fetch_artifact(
1964                &req(&format!("{base}/app")),
1965                &dest,
1966                short_total,
1967                &CancelFlag::new(),
1968            )
1969            .unwrap_err();
1970        let elapsed = started.elapsed();
1971        assert!(matches!(err, AcquisitionError::Timeout { phase: "total" }));
1972
1973        // M012 (§6.3): promptness is proven against the deadline and against
1974        // the server's stall, not against an absolute wall-clock constant.
1975        //
1976        // The deadline was actually reached: the fetch did not succeed early.
1977        // Without this half, an upper bound alone would also pass if the
1978        // fetch failed immediately.
1979        assert!(
1980            elapsed >= short_total.total_timeout,
1981            "elapsed {elapsed:?} is below the {:?} total deadline",
1982            short_total.total_timeout
1983        );
1984
1985        // The child was killed rather than left to stall: comfortably inside
1986        // the server's 4000 ms body stall. This proves the deadline fired; it
1987        // does not claim the OS reaped within a fixed number of
1988        // milliseconds, and the headroom absorbs the kill/reap/join latency
1989        // that the transport's deadline contract does not govern.
1990        assert!(
1991            elapsed < Duration::from_secs(2),
1992            "elapsed {elapsed:?} is not below the 2 s bound"
1993        );
1994        assert!(!dest.exists());
1995        assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
1996        let _ = fs::remove_dir_all(&dir);
1997    }
1998
1999    #[test]
2000    fn cancellation_before_spawn_cleans_temp() {
2001        let t = require_transport();
2002        let dir = temp_dir("curl-cancel");
2003        let dest = dir.join("app");
2004        let cancel = CancelFlag::new();
2005        cancel.cancel();
2006        let err = t
2007            .fetch_artifact(&req("http://127.0.0.1:1/app"), &dest, limits(), &cancel)
2008            .unwrap_err();
2009        assert!(matches!(err, AcquisitionError::Cancelled));
2010        assert!(!dest.exists());
2011        let leftovers: Vec<_> = fs::read_dir(&dir)
2012            .unwrap()
2013            .filter_map(|e| e.ok())
2014            .filter(|e| e.file_name().to_string_lossy().ends_with(".part"))
2015            .collect();
2016        assert!(leftovers.is_empty());
2017        let _ = fs::remove_dir_all(&dir);
2018    }
2019
2020    #[test]
2021    #[cfg(not(windows))]
2022    fn cancellation_during_body_stream_kills_and_reaps_child() {
2023        let t = require_transport();
2024        let base = serve_once(
2025            200,
2026            vec![("Content-Length".into(), "65536".into())],
2027            vec![3u8; 65536],
2028            5000,
2029            false,
2030        );
2031        let dir = temp_dir("curl-cancel-stream");
2032        let dest = dir.join("app");
2033        let cancel = Arc::new(CancelFlag::new());
2034        let child_cancel = Arc::clone(&cancel);
2035        let child_transport = t;
2036        let url = format!("{base}/app");
2037        let child = thread::spawn(move || {
2038            child_transport.fetch_artifact(&req(&url), &dest, limits(), &child_cancel)
2039        });
2040        thread::sleep(Duration::from_millis(150));
2041        cancel.cancel();
2042        assert!(matches!(
2043            child.join().unwrap(),
2044            Err(AcquisitionError::Cancelled)
2045        ));
2046        assert!(!dir.join("app").exists());
2047        assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
2048        let _ = fs::remove_dir_all(&dir);
2049    }
2050
2051    #[test]
2052    #[cfg(not(windows))]
2053    fn redirect_follow_and_reject() {
2054        let curl_exe = require_curl_executable();
2055        let target_body = b"redirect-target".to_vec();
2056        let target = ok_server(target_body.clone());
2057        let redirect = serve_once(
2058            302,
2059            vec![("Location".into(), format!("{target}/final"))],
2060            b"".to_vec(),
2061            0,
2062            false,
2063        );
2064        let follow = CurlTransport::with_executable(
2065            curl_exe.clone(),
2066            CurlConfig::strict()
2067                .follow_redirects(true)
2068                .max_redirects(10),
2069        )
2070        .unwrap();
2071        let out = follow
2072            .fetch_metadata(&req(&format!("{redirect}/r")), limits(), &CancelFlag::new())
2073            .unwrap();
2074        assert_eq!(out.success().unwrap().bytes(), b"redirect-target");
2075
2076        let nofollow =
2077            CurlTransport::with_executable(curl_exe, CurlConfig::strict().follow_redirects(false))
2078                .unwrap();
2079        let err = nofollow
2080            .fetch_metadata(&req(&format!("{redirect}/r")), limits(), &CancelFlag::new())
2081            .unwrap_err();
2082        assert!(matches!(err, AcquisitionError::Transport(_)));
2083    }
2084
2085    #[cfg(unix)]
2086    #[test]
2087    fn proxy_disabled_uses_noproxy_and_cleared_env() {
2088        let dir = temp_dir("curl-proxy");
2089        let script = fake_curl_script(b"ok", "200", 0, &dir);
2090        let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
2091        let out = t
2092            .fetch_metadata(&req("http://example.com/x"), limits(), &CancelFlag::new())
2093            .unwrap();
2094        assert_eq!(out.success().unwrap().bytes(), b"ok");
2095        let argv = fs::read_to_string(dir.join("argv")).unwrap();
2096        assert!(argv.contains("--noproxy"));
2097        assert!(argv.contains("--disable"));
2098        assert!(argv.contains("--output -"));
2099        assert!(!argv.contains("eggup-curl-meta"));
2100        let env = fs::read_to_string(dir.join("env")).unwrap();
2101        assert!(!env.contains("HTTP_PROXY=hunter"));
2102        let _ = fs::remove_dir_all(&dir);
2103    }
2104
2105    #[cfg(unix)]
2106    #[test]
2107    fn proxy_custom_env_is_explicit() {
2108        let dir = temp_dir("curl-proxy-custom");
2109        let script = fake_curl_script(b"ok", "200", 0, &dir);
2110        let t = CurlTransport::with_executable(
2111            &script,
2112            CurlConfig::strict().proxy(CurlProxy::Custom(vec![(
2113                "HTTPS_PROXY".to_string(),
2114                "http://proxy.example:8080".to_string(),
2115            )])),
2116        )
2117        .unwrap();
2118        t.fetch_metadata(&req("http://example.com/x"), limits(), &CancelFlag::new())
2119            .unwrap();
2120        let argv = fs::read_to_string(dir.join("argv")).unwrap();
2121        assert!(!argv.contains("--noproxy"));
2122        let env = fs::read_to_string(dir.join("env")).unwrap();
2123        assert!(env.contains("HTTPS_PROXY=http://proxy.example:8080"));
2124        let _ = fs::remove_dir_all(&dir);
2125    }
2126
2127    #[cfg(unix)]
2128    #[test]
2129    fn artifact_temp_is_owner_private_and_no_clobber() {
2130        let dir = temp_dir("curl-perms");
2131        let script = fake_curl_script(b"owned-bytes", "200", 0, &dir);
2132        // Use a separate work dir for the destination so the fake script dir
2133        // (which holds argv/env records) does not interfere.
2134        let work = temp_dir("curl-perms-work");
2135        // Fake curl writes directly to the Eggup-owned temp; verify promotion
2136        // preserves foreign destinations and cleans only owned temps.
2137        let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
2138        let dest = work.join("app");
2139        let out = t
2140            .fetch_artifact(
2141                &req("http://example.com/app"),
2142                &dest,
2143                limits(),
2144                &CancelFlag::new(),
2145            )
2146            .unwrap();
2147        assert_eq!(
2148            out.success().unwrap().bytes_written,
2149            b"owned-bytes".len() as u64
2150        );
2151        #[cfg(unix)]
2152        {
2153            let mode = fs::metadata(&dest).unwrap().permissions().mode() & 0o777;
2154            // Promoted artifact inherits the owner-private temp mode via
2155            // hard-link promotion (0600), never a world-readable default.
2156            assert_eq!(mode, 0o600);
2157        }
2158        // Existing destination is never overwritten.
2159        fs::write(&dest, b"FOREIGN").unwrap();
2160        let dest2 = work.join("app");
2161        let err = t
2162            .fetch_artifact(
2163                &req("http://example.com/app"),
2164                &dest2,
2165                limits(),
2166                &CancelFlag::new(),
2167            )
2168            .unwrap_err();
2169        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
2170        assert_eq!(fs::read(&dest2).unwrap(), b"FOREIGN");
2171        let _ = fs::remove_dir_all(&dir);
2172        let _ = fs::remove_dir_all(&work);
2173    }
2174
2175    #[cfg(unix)]
2176    #[test]
2177    fn credential_material_is_redacted() {
2178        let dir = temp_dir("curl-redact");
2179        let script = fake_curl_script(b"", "", 7, &dir);
2180        let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
2181        let url = "https://user:S3CR3T-USERINFO-9917@example.com/app?token=TOKEN-QUERY-5523#FRAG-SENTINEL-7788";
2182        let err = t
2183            .fetch_metadata(&req(url), limits(), &CancelFlag::new())
2184            .unwrap_err();
2185        let msg = format!("{err}");
2186        assert!(!msg.contains("S3CR3T-USERINFO-9917"));
2187        assert!(!msg.contains("TOKEN-QUERY-5523"));
2188        assert!(!msg.contains("FRAG-SENTINEL-7788"));
2189        let _ = fs::remove_dir_all(&dir);
2190    }
2191
2192    #[cfg(unix)]
2193    #[test]
2194    fn invalid_limits_fail_before_spawn() {
2195        let dir = temp_dir("curl-invalid");
2196        let script = fake_curl_script(b"ok", "200", 0, &dir);
2197        let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
2198        let bad = FetchLimits {
2199            max_metadata_bytes: 0,
2200            ..limits()
2201        };
2202        let err = t
2203            .fetch_metadata(&req("http://example.com/x"), bad, &CancelFlag::new())
2204            .unwrap_err();
2205        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
2206        // Fake was never invoked (no argv record beyond setup is acceptable;
2207        // assert no artifact side effects).
2208        let dest = dir.join("app");
2209        let err = t
2210            .fetch_artifact(&req("http://example.com/x"), &dest, bad, &CancelFlag::new())
2211            .unwrap_err();
2212        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
2213        assert!(!dest.exists());
2214        let _ = fs::remove_dir_all(&dir);
2215    }
2216
2217    #[test]
2218    fn composition_with_fixture_falls_back_from_unavailable_curl() {
2219        use eggup_acquisition::{ComposedTransport, CompositionPolicy};
2220        let dir = temp_dir("curl-composed");
2221        let script = dir.join("missing-curl");
2222        let curl = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
2223        let fixture = FixtureTransport::new();
2224        fixture.route(
2225            "https://example.com/meta",
2226            FixtureResponse::body(b"via-fixture".to_vec()),
2227        );
2228        let composed = ComposedTransport::new(&curl, &fixture, CompositionPolicy::UnavailableOnly);
2229        let out = composed
2230            .fetch_metadata(
2231                &req("https://example.com/meta"),
2232                limits(),
2233                &CancelFlag::new(),
2234            )
2235            .unwrap();
2236        assert_eq!(out.success().unwrap().bytes(), b"via-fixture");
2237        let _ = fs::remove_dir_all(&dir);
2238    }
2239
2240    /// M014 (§6.2, §6.4): a configured `User-Agent` reaches `curl` as a
2241    /// literal argv element, positioned before the `--` separator and the URL.
2242    ///
2243    /// The position matters: `--` is what isolates the URL from the options,
2244    /// so an option emitted after it would be read as part of the URL rather
2245    /// than as an option.
2246    #[test]
2247    fn user_agent_is_emitted_as_a_literal_argv_element_before_the_url() {
2248        let cfg = CurlConfig::strict();
2249        let agent = "eggup-curl-test/1.0 (Macintosh; x86_64)";
2250        let args = build_curl_args(
2251            &cfg,
2252            Some(agent),
2253            "https://example.com/x",
2254            1024,
2255            Duration::from_secs(1),
2256            Duration::from_secs(2),
2257        )
2258        .expect("builds");
2259        let flag = args
2260            .iter()
2261            .position(|a| a == "--user-agent")
2262            .expect("the user agent flag is present");
2263        assert_eq!(
2264            args[flag + 1],
2265            agent,
2266            "the value must be the exact element following the flag"
2267        );
2268        assert_eq!(
2269            args.iter().filter(|a| *a == "--user-agent").count(),
2270            1,
2271            "the flag must appear exactly once"
2272        );
2273        let separator = args.iter().position(|a| a == "--").expect("separator");
2274        let url = args
2275            .iter()
2276            .position(|a| a == "https://example.com/x")
2277            .expect("url");
2278        assert!(
2279            flag < separator,
2280            "--user-agent must be emitted before the -- separator"
2281        );
2282        assert!(separator < url, "the -- separator must precede the URL");
2283        assert_eq!(url, args.len() - 1, "the URL stays the last element");
2284    }
2285
2286    /// M014 (§6.3, R3-R5): a value carrying a control character is rejected
2287    /// as `InvalidInput`, and no argv is produced for it.
2288    ///
2289    /// `curl` does not sanitize `--user-agent`: a `CR LF` inside the value is
2290    /// written into the request head verbatim and injects a second header.
2291    /// The adapter therefore refuses the value before it can reach the wire.
2292    #[test]
2293    fn user_agent_rejects_control_characters_without_producing_argv() {
2294        let cfg = CurlConfig::strict();
2295        let rejected = [
2296            "eggup\r\nX-Injected: 1",
2297            "eggup\rvalue",
2298            "eggup\nvalue",
2299            "eggup\u{0}value",
2300            "eggup\tvalue",
2301            "eggup\u{7F}value",
2302            "eggup\u{85}value",
2303            "eggup\u{9F}value",
2304        ];
2305        for bad in rejected {
2306            let err = build_curl_args(
2307                &cfg,
2308                Some(bad),
2309                "https://example.com/x",
2310                1024,
2311                Duration::from_secs(1),
2312                Duration::from_secs(2),
2313            )
2314            .expect_err("a control character must be rejected");
2315            assert!(
2316                matches!(err, AcquisitionError::InvalidInput(_)),
2317                "expected InvalidInput for {bad:?}, got {err:?}"
2318            );
2319            // The constructor refuses it too, so no transport can carry it.
2320            let ctor = CurlTransport::with_executable_and_user_agent(
2321                "/usr/bin/curl",
2322                CurlConfig::strict(),
2323                bad,
2324            )
2325            .expect_err("a control character must be refused at construction");
2326            assert!(
2327                matches!(ctor, AcquisitionError::InvalidInput(_)),
2328                "expected InvalidInput for {bad:?}, got {ctor:?}"
2329            );
2330        }
2331    }
2332
2333    /// M014 (§6.3, R1-R2): the empty value and an over-bound value are
2334    /// rejected, and a value exactly at the bound is accepted.
2335    #[test]
2336    fn user_agent_rejects_empty_and_over_bound_values() {
2337        let cfg = CurlConfig::strict();
2338        let empty = build_curl_args(
2339            &cfg,
2340            Some(""),
2341            "https://example.com/x",
2342            1024,
2343            Duration::from_secs(1),
2344            Duration::from_secs(2),
2345        )
2346        .expect_err("an empty value must be rejected");
2347        assert!(matches!(empty, AcquisitionError::InvalidInput(_)));
2348
2349        let at_bound = "a".repeat(MAX_USER_AGENT_BYTES);
2350        let ok = build_curl_args(
2351            &cfg,
2352            Some(&at_bound),
2353            "https://example.com/x",
2354            1024,
2355            Duration::from_secs(1),
2356            Duration::from_secs(2),
2357        )
2358        .expect("a value exactly at the bound must be accepted");
2359        let flag = ok
2360            .iter()
2361            .position(|a| a == "--user-agent")
2362            .expect("the user agent flag is present");
2363        assert_eq!(ok[flag + 1], at_bound);
2364
2365        let over_bound = "a".repeat(MAX_USER_AGENT_BYTES + 1);
2366        let err = build_curl_args(
2367            &cfg,
2368            Some(&over_bound),
2369            "https://example.com/x",
2370            1024,
2371            Duration::from_secs(1),
2372            Duration::from_secs(2),
2373        )
2374        .expect_err("an over-bound value must be rejected");
2375        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
2376
2377        // The constructor applies the same bound.
2378        let ctor = CurlTransport::with_executable_and_user_agent(
2379            "/usr/bin/curl",
2380            CurlConfig::strict(),
2381            over_bound.clone(),
2382        )
2383        .expect_err("an over-bound value must be refused at construction");
2384        assert!(matches!(ctor, AcquisitionError::InvalidInput(_)));
2385    }
2386
2387    /// M014 (§6.5): the default transport sends no `User-Agent`, and its argv
2388    /// is element-for-element what it was before the control existed.
2389    ///
2390    /// The published `eggup-curl 0.1.2` behavior is what a consumer already
2391    /// observes on the wire, so the default path must not change silently.
2392    #[test]
2393    fn default_transport_emits_no_user_agent_and_keeps_the_previous_argv() {
2394        let cfg = CurlConfig::strict();
2395        let transport = CurlTransport::with_executable("/usr/bin/curl", cfg.clone())
2396            .expect("the transport builds");
2397        assert_eq!(
2398            transport.user_agent(),
2399            None,
2400            "the default transport must not carry a user agent"
2401        );
2402
2403        let args = build_curl_args(
2404            &cfg,
2405            None,
2406            "https://example.com/x",
2407            1024,
2408            Duration::from_secs(1),
2409            Duration::from_secs(2),
2410        )
2411        .expect("builds");
2412        assert!(
2413            !args.iter().any(|a| a == "--user-agent"),
2414            "the default argv must not carry --user-agent"
2415        );
2416        assert_eq!(
2417            args,
2418            vec![
2419                "--disable",
2420                "--silent",
2421                "--show-error",
2422                "--no-progress-meter",
2423                "--location",
2424                "--max-redirs",
2425                "10",
2426                "--connect-timeout",
2427                "1",
2428                "--max-time",
2429                "2",
2430                "--max-filesize",
2431                "1024",
2432                "--proto",
2433                "=http,https",
2434                "--proto-redir",
2435                "=https",
2436                "--noproxy",
2437                "*",
2438                "--output",
2439                "-",
2440                "--write-out",
2441                "%{stderr}%{http_code}",
2442                "--",
2443                "https://example.com/x",
2444            ],
2445            "the default argv must be unchanged"
2446        );
2447    }
2448
2449    /// M014 (§6.3): a rejected caller value is a terminal `InvalidInput`, and
2450    /// a composed transport does not fall back on it.
2451    ///
2452    /// `Unavailable` is the only outcome the seam falls back on. A malformed
2453    /// caller input must therefore never be classified as `Unavailable`, or a
2454    /// composed transport would silently serve the request from another
2455    /// adapter.
2456    #[test]
2457    fn rejected_user_agent_is_a_terminal_invalid_input_not_unavailable() {
2458        use eggup_acquisition::{ComposedTransport, CompositionPolicy};
2459        let err = CurlTransport::with_executable_and_user_agent(
2460            "/usr/bin/curl",
2461            CurlConfig::strict(),
2462            "bad\rvalue",
2463        )
2464        .expect_err("a control character must be refused at construction");
2465        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
2466        assert!(
2467            !err.is_unavailable(),
2468            "a rejected caller value must never be classified as unavailable"
2469        );
2470
2471        // The same terminality at the composition layer: a curl adapter that
2472        // fails with `InvalidInput` is not retried on the secondary transport.
2473        let curl = CurlTransport::with_executable_and_user_agent(
2474            "/usr/bin/curl",
2475            CurlConfig::strict(),
2476            "eggup-curl-test/1.0",
2477        )
2478        .expect("builds");
2479        let fixture = FixtureTransport::new();
2480        fixture.route(
2481            "https://example.com/meta",
2482            FixtureResponse::body(b"via-fixture".to_vec()),
2483        );
2484        let composed = ComposedTransport::new(&curl, &fixture, CompositionPolicy::UnavailableOnly);
2485        let bad_limits = FetchLimits {
2486            max_metadata_bytes: 0,
2487            ..limits()
2488        };
2489        let composed_err = composed
2490            .fetch_metadata(
2491                &req("https://example.com/meta"),
2492                bad_limits,
2493                &CancelFlag::new(),
2494            )
2495            .expect_err("a terminal failure must not fall back to the fixture");
2496        assert!(
2497            matches!(composed_err, AcquisitionError::InvalidInput(_)),
2498            "the composed transport must surface the terminal failure, got {composed_err:?}"
2499        );
2500    }
2501
2502    /// M014 (§6.1): the configured value reaches the wire as the outbound
2503    /// `User-Agent` header.
2504    ///
2505    /// The argv assertions prove what the adapter asks `curl` to do; this
2506    /// proves what the peer actually receives.
2507    #[cfg(not(windows))]
2508    #[test]
2509    fn user_agent_reaches_the_wire_as_the_configured_header() {
2510        let dir = temp_dir("curl-ua-wire");
2511        let record = dir.join("request-head");
2512        let base = serve_once_recording_head(200, b"ok".to_vec(), &record);
2513        let curl_exe = require_curl_executable();
2514        let transport = CurlTransport::with_executable_and_user_agent(
2515            curl_exe,
2516            CurlConfig::strict(),
2517            "eggup-curl-test/1.0",
2518        )
2519        .expect("builds");
2520        assert_eq!(transport.user_agent(), Some("eggup-curl-test/1.0"));
2521        let out = transport
2522            .fetch_metadata(&req(&format!("{base}/x")), limits(), &CancelFlag::new())
2523            .expect("the loopback fetch must succeed");
2524        assert_eq!(out.success().unwrap().bytes(), b"ok");
2525        let head = fs::read_to_string(&record).expect("the request head was recorded");
2526        assert!(
2527            head.contains("User-Agent: eggup-curl-test/1.0\r\n"),
2528            "the configured user agent must reach the wire; the head was {head:?}"
2529        );
2530        let _ = fs::remove_dir_all(&dir);
2531    }
2532}