Skip to main content

eggup_eggfetch/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3#![doc = "Native Eggfetch HTTP acquisition adapter with explicit bounded policy."]
4#![doc = ""]
5#![doc = "Implements `eggup-acquisition::AcquisitionTransport` without release or"]
6#![doc = "fallback authority. See `README.md` for the single policy configuration point."]
7
8use eggfetch_core::{Client, HttpVersionPolicy, ProxyEnvironment, RedirectPolicy, Timeout};
9use eggup_acquisition::{
10    AcquisitionError, AcquisitionRequest, AcquisitionTransport, ArtifactEvidence, CancelFlag,
11    FetchLimits, FetchOutcome, MetadataBytes,
12};
13use std::fs;
14use std::path::Path;
15use std::time::Duration;
16
17/// Default user agent for Eggup Eggfetch traffic.
18pub const DEFAULT_USER_AGENT: &str = "eggup-eggfetch";
19/// Default connect deadline (matches eggsact/stegoeggo posture).
20pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
21/// Default total wall-clock deadline.
22pub const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(120);
23/// Default redirect bound for asset chains.
24pub const DEFAULT_MAX_REDIRECTS: usize = 10;
25
26/// Explicit proxy decision. Routing is never inherited accidentally.
27#[derive(Debug, Clone, Default)]
28pub enum ProxyDecision {
29    /// No proxy is used, even if environment variables are set.
30    #[default]
31    Disabled,
32    /// Use an explicit snapshot of the process environment.
33    FromEnvironment,
34    /// Use explicit `KEY=value` pairs (e.g. `HTTPS_PROXY`, `NO_PROXY`).
35    Custom(Vec<(String, String)>),
36}
37
38impl ProxyDecision {
39    fn environment(&self) -> Result<ProxyEnvironment, String> {
40        match self {
41            Self::Disabled => Ok(ProxyEnvironment::new()),
42            Self::FromEnvironment => Ok(ProxyEnvironment::from_env()),
43            Self::Custom(pairs) => Ok(ProxyEnvironment::from_map(
44                pairs.iter().map(|(k, v)| (k.as_str(), v.as_str())),
45            )),
46        }
47    }
48}
49
50/// Strict transport configuration. All policy lives here.
51#[derive(Debug, Clone)]
52pub struct EggfetchConfig {
53    /// User agent header.
54    pub user_agent: String,
55    /// Connect deadline.
56    pub connect_timeout: Duration,
57    /// Total deadline.
58    pub total_timeout: Duration,
59    /// Redirect bound.
60    pub max_redirects: usize,
61    /// Proxy routing decision.
62    pub proxy: ProxyDecision,
63}
64
65impl Default for EggfetchConfig {
66    fn default() -> Self {
67        Self {
68            user_agent: DEFAULT_USER_AGENT.to_string(),
69            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
70            total_timeout: DEFAULT_TOTAL_TIMEOUT,
71            max_redirects: DEFAULT_MAX_REDIRECTS,
72            proxy: ProxyDecision::Disabled,
73        }
74    }
75}
76
77impl EggfetchConfig {
78    /// Strict default: HTTP/1, Rustls, redirect bound, explicit proxy.
79    pub fn strict() -> Self {
80        Self::default()
81    }
82
83    /// Sets the user agent.
84    pub fn user_agent(mut self, agent: impl Into<String>) -> Self {
85        self.user_agent = agent.into();
86        self
87    }
88
89    /// Sets connect/total timeouts.
90    pub fn timeouts(mut self, connect: Duration, total: Duration) -> Self {
91        self.connect_timeout = connect;
92        self.total_timeout = total;
93        self
94    }
95
96    /// Sets the redirect bound.
97    pub fn max_redirects(mut self, max: usize) -> Self {
98        self.max_redirects = max;
99        self
100    }
101
102    /// Sets the proxy decision.
103    pub fn proxy(mut self, proxy: ProxyDecision) -> Self {
104        self.proxy = proxy;
105        self
106    }
107
108    fn timeout(&self) -> Timeout {
109        Timeout::builder()
110            .connect(self.connect_timeout)
111            .total(self.total_timeout)
112            .build()
113    }
114
115    fn redirect_policy(&self) -> RedirectPolicy {
116        RedirectPolicy::strict(self.max_redirects)
117    }
118
119    fn build_client(&self) -> Result<Client, AcquisitionError> {
120        let env = self
121            .proxy
122            .environment()
123            .map_err(|e| AcquisitionError::Transport(bound(e)))?;
124        let builder = Client::builder()
125            .user_agent(&self.user_agent)
126            .http_version_policy(HttpVersionPolicy::Http1Only)
127            .redirect_policy(self.redirect_policy())
128            .timeout(self.timeout())
129            .automatic_decompression(false);
130        builder
131            .proxy_environment(&env)
132            .map(|b| b.build())
133            .map_err(|e| {
134                AcquisitionError::Transport(bound(format!(
135                    "proxy configuration/routing failure: {e}"
136                )))
137            })
138    }
139}
140
141/// Native Eggfetch adapter implementing the acquisition seam.
142///
143/// No release, version, fallback, destination, or service policy lives here.
144/// Checksum mismatch, TLS errors, malformed metadata, timeouts, 5xx, and
145/// redirect violations are hard failures; only exact 404 becomes `NotFound`.
146pub struct EggfetchTransport {
147    client: Client,
148    config: EggfetchConfig,
149}
150
151impl EggfetchTransport {
152    /// Builds a strict adapter. Invalid proxy configuration fails closed here,
153    /// never silently direct.
154    pub fn strict(config: EggfetchConfig) -> Result<Self, AcquisitionError> {
155        let client = config.build_client()?;
156        Ok(Self { client, config })
157    }
158
159    /// Returns the transport configuration.
160    pub fn config(&self) -> &EggfetchConfig {
161        &self.config
162    }
163
164    /// Returns the exact Eggfetch dependency version used.
165    pub fn eggfetch_version() -> &'static str {
166        // Recorded at qualification time; updated when the dependency changes.
167        "eggfetch-core 0.2.0 (http1,tls-rustls,tls-native-roots,proxy; no compression/cookies/retry/json)"
168    }
169
170    fn block_on<F, T>(&self, fut: F) -> T
171    where
172        F: std::future::Future<Output = T>,
173    {
174        // Private current-thread runtime so the sync seam never forces an
175        // async runtime into eggup-core or lightweight consumers. Async
176        // consumers should call the sync seam via spawn_blocking per their
177        // own policy.
178        let rt = tokio::runtime::Builder::new_current_thread()
179            .enable_all()
180            .build()
181            .expect("eggfetch current-thread runtime");
182        rt.block_on(fut)
183    }
184}
185
186impl AcquisitionTransport for EggfetchTransport {
187    fn fetch_metadata(
188        &self,
189        request: &AcquisitionRequest,
190        limits: FetchLimits,
191        cancel: &CancelFlag,
192    ) -> Result<FetchOutcome<MetadataBytes>, AcquisitionError> {
193        if cancel.is_cancelled() {
194            return Err(AcquisitionError::Cancelled);
195        }
196        // Per-fetch byte bound is authoritative; Content-Length is advisory only.
197        let max = limits.max_metadata_bytes;
198        let url = request.url().to_string();
199        let result = self.block_on(async {
200            let mut response = self
201                .client
202                .get(&url)
203                .map_err(|e| map_request_error(&e, request))?
204                .max_decoded_body_size(max)
205                .send()
206                .await
207                .map_err(|e| map_fetch_error(&e, request, Some(max)))?;
208            let status = response.status().as_u16();
209            match classify(status) {
210                StatusClass::NotFound => Ok(FetchOutcome::NotFound),
211                StatusClass::HardFailure => Err(AcquisitionError::Transport(bound(format!(
212                    "HTTP {status} from {} while fetching metadata",
213                    request.redacted()
214                )))),
215                StatusClass::Success => {
216                    if cancel.is_cancelled() {
217                        return Err(AcquisitionError::Cancelled);
218                    }
219                    if let Some(declared) = response.content_length() {
220                        if declared > max as u64 {
221                            return Err(AcquisitionError::TooLarge { limit: max as u64 });
222                        }
223                    }
224                    let bytes = response
225                        .bytes()
226                        .await
227                        .map_err(|e| map_fetch_error(&e, request, Some(max)))?;
228                    if bytes.len() > max {
229                        return Err(AcquisitionError::TooLarge { limit: max as u64 });
230                    }
231                    Ok(FetchOutcome::Success(
232                        eggup_acquisition::__adapter_metadata(bytes.to_vec()),
233                    ))
234                }
235            }
236        });
237        // Enforce caller total timeout even if the inner client policy drifts:
238        // the inner Timeout already covers connect/total, so a Timeout error
239        // here is authoritative. No extra wall-clock wrapper is needed for the
240        // sync bridge because block_on inherits the client deadlines.
241        result
242    }
243
244    fn fetch_artifact(
245        &self,
246        request: &AcquisitionRequest,
247        dest: &Path,
248        limits: FetchLimits,
249        cancel: &CancelFlag,
250    ) -> Result<FetchOutcome<ArtifactEvidence>, AcquisitionError> {
251        if cancel.is_cancelled() {
252            return Err(AcquisitionError::Cancelled);
253        }
254        let parent = dest.parent().ok_or_else(|| {
255            AcquisitionError::InvalidInput(bound("destination has no parent".into()))
256        })?;
257        let parent_meta = fs::symlink_metadata(parent)
258            .map_err(|e| AcquisitionError::Io(bound(format!("reading artifact parent: {e}"))))?;
259        if !parent_meta.is_dir() || parent_meta.file_type().is_symlink() {
260            return Err(AcquisitionError::InvalidInput(bound(
261                "artifact parent must be an existing real directory".into(),
262            )));
263        }
264        let url = request.url().to_string();
265        let max_artifact = limits.max_artifact_bytes;
266        let redacted = request.redacted();
267        let result: Result<FetchOutcome<ArtifactEvidence>, AcquisitionError> =
268            self.block_on(async {
269                use futures_util::StreamExt;
270                use tokio::io::AsyncWriteExt;
271                let mut response = self
272                    .client
273                    .get(&url)
274                    .map_err(|e| map_request_error(&e, request))?
275                    .send()
276                    .await
277                    .map_err(|e| map_fetch_error(&e, request, None))?;
278                let status = response.status().as_u16();
279                match classify(status) {
280                    StatusClass::NotFound => return Ok(FetchOutcome::NotFound),
281                    StatusClass::HardFailure => {
282                        return Err(AcquisitionError::Transport(bound(format!(
283                            "HTTP {status} from {redacted} while fetching artifact"
284                        ))));
285                    }
286                    StatusClass::Success => {}
287                }
288                // Atomic promotion via temp sibling; cleaned on any failure.
289                let tmp = parent.join(format!(
290                    ".eggup-eggfetch-{}-{}.part",
291                    std::process::id(),
292                    nanos()
293                ));
294                struct Guard<'a> {
295                    path: &'a Path,
296                    disarm: bool,
297                }
298                impl Drop for Guard<'_> {
299                    fn drop(&mut self) {
300                        if !self.disarm {
301                            let _ = fs::remove_file(self.path);
302                        }
303                    }
304                }
305                let mut guard = Guard {
306                    path: &tmp,
307                    disarm: false,
308                };
309                let mut file = tokio::fs::File::create(&tmp)
310                    .await
311                    .map_err(|e| AcquisitionError::Io(bound(format!("creating part file: {e}"))))?;
312                let mut stream = response
313                    .bytes_stream()
314                    .map_err(|e| map_fetch_error(&e, request, None))?;
315                let mut written: u64 = 0;
316                while let Some(chunk) = stream.next().await {
317                    if cancel.is_cancelled() {
318                        return Err(AcquisitionError::Cancelled);
319                    }
320                    let chunk = chunk.map_err(|e| map_fetch_error(&e, request, None))?;
321                    if chunk.is_empty() {
322                        continue;
323                    }
324                    if let Some(max) = max_artifact {
325                        written = written.saturating_add(chunk.len() as u64);
326                        if written > max {
327                            return Err(AcquisitionError::TooLarge { limit: max });
328                        }
329                    } else {
330                        written = written.saturating_add(chunk.len() as u64);
331                    }
332                    file.write_all(&chunk).await.map_err(|e| {
333                        AcquisitionError::Io(bound(format!("writing part file: {e}")))
334                    })?;
335                }
336                file.flush()
337                    .await
338                    .map_err(|e| AcquisitionError::Io(bound(format!("flushing part file: {e}"))))?;
339                drop(file);
340                fs::rename(&tmp, dest)
341                    .map_err(|e| AcquisitionError::Io(bound(format!("promoting artifact: {e}"))))?;
342                guard.disarm = true;
343                Ok(FetchOutcome::Success(
344                    eggup_acquisition::__adapter_artifact(written),
345                ))
346            });
347        result
348    }
349}
350
351fn nanos() -> u128 {
352    std::time::SystemTime::now()
353        .duration_since(std::time::UNIX_EPOCH)
354        .map(|d| d.as_nanos())
355        .unwrap_or(0)
356}
357
358fn bound(s: String) -> String {
359    let mut s = s;
360    if s.len() > 512 {
361        s.truncate(512);
362    }
363    s
364}
365
366#[derive(Debug, Clone, Copy, PartialEq, Eq)]
367enum StatusClass {
368    Success,
369    NotFound,
370    HardFailure,
371}
372
373fn classify(status: u16) -> StatusClass {
374    match status {
375        200..=299 => StatusClass::Success,
376        404 => StatusClass::NotFound,
377        _ => StatusClass::HardFailure,
378    }
379}
380
381fn map_request_error(e: &eggfetch_core::Error, request: &AcquisitionRequest) -> AcquisitionError {
382    use eggfetch_core::Error as E;
383    match e {
384        E::InvalidProxyUrl(detail) => AcquisitionError::Transport(bound(format!(
385            "proxy configuration/routing failure: {detail}"
386        ))),
387        _ => AcquisitionError::Transport(bound(format!(
388            "request build failed for {}: {e}",
389            request.redacted()
390        ))),
391    }
392}
393
394fn map_fetch_error(
395    e: &eggfetch_core::Error,
396    request: &AcquisitionRequest,
397    max: Option<usize>,
398) -> AcquisitionError {
399    use eggfetch_core::Error as E;
400    match e {
401        E::DecodedBodyTooLarge => AcquisitionError::TooLarge {
402            limit: max.unwrap_or(0) as u64,
403        },
404        E::Timeout { phase, .. } => AcquisitionError::Timeout {
405            phase: match phase {
406                eggfetch_core::TimeoutPhase::Connect => "connect",
407                eggfetch_core::TimeoutPhase::Total => "total",
408                _ => "total",
409            },
410        },
411        E::InvalidProxyUrl(detail) => AcquisitionError::Transport(bound(format!(
412            "proxy configuration/routing failure: {detail}"
413        ))),
414        _ => {
415            let msg = format!("{e}");
416            // Never leak credential material: only the redacted URL is embedded.
417            AcquisitionError::Transport(bound(format!(
418                "fetch failed for {}: {msg}",
419                request.redacted()
420            )))
421        }
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use eggup_acquisition::{AcquisitionRequest, FixtureResponse, FixtureTransport};
429    use std::io::{Read, Write};
430    use std::net::TcpListener;
431    use std::sync::OnceLock;
432    use std::thread;
433
434    fn strict_transport() -> EggfetchTransport {
435        EggfetchTransport::strict(EggfetchConfig::strict()).expect("strict transport")
436    }
437
438    fn req(url: &str) -> AcquisitionRequest {
439        AcquisitionRequest::new(url).unwrap()
440    }
441
442    fn limits() -> FetchLimits {
443        FetchLimits {
444            max_metadata_bytes: 64 * 1024,
445            max_artifact_bytes: Some(256 * 1024),
446            connect_timeout: Duration::from_secs(2),
447            total_timeout: Duration::from_secs(10),
448        }
449    }
450
451    fn temp_dir(prefix: &str) -> std::path::PathBuf {
452        let nanos = std::time::SystemTime::now()
453            .duration_since(std::time::UNIX_EPOCH)
454            .map(|d| d.as_nanos())
455            .unwrap_or(0);
456        let p = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()));
457        let _ = fs::create_dir_all(&p);
458        p
459    }
460
461    /// Minimal single-response HTTP/1.1 server on 127.0.0.1.
462    fn serve_once(
463        status: u16,
464        headers: Vec<(String, String)>,
465        body: Vec<u8>,
466        split_body: bool,
467        stall_before_body_ms: u64,
468        abort_after_headers: bool,
469    ) -> String {
470        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
471        let addr = listener.local_addr().unwrap();
472        thread::spawn(move || {
473            if let Ok((mut stream, _)) = listener.accept() {
474                stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
475                stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
476                let mut buf = [0u8; 8192];
477                let _ = stream.read(&mut buf);
478                let reason = match status {
479                    200 => "OK",
480                    404 => "Not Found",
481                    500 => "Internal Server Error",
482                    302 => "Found",
483                    _ => "OK",
484                };
485                let mut head = format!("HTTP/1.1 {status} {reason}\r\n");
486                for (k, v) in headers {
487                    head.push_str(&format!("{k}: {v}\r\n"));
488                }
489                head.push_str("Connection: close\r\n\r\n");
490                let _ = stream.write_all(head.as_bytes());
491                if abort_after_headers {
492                    return;
493                }
494                if stall_before_body_ms > 0 {
495                    thread::sleep(Duration::from_millis(stall_before_body_ms));
496                }
497                if split_body {
498                    let mid = body.len() / 2;
499                    let _ = stream.write_all(&body[..mid]);
500                    thread::sleep(Duration::from_millis(20));
501                    let _ = stream.write_all(&body[mid..]);
502                } else {
503                    let _ = stream.write_all(&body);
504                }
505            }
506        });
507        format!("http://{addr}")
508    }
509
510    fn ok_server(body: Vec<u8>) -> String {
511        serve_once(
512            200,
513            vec![
514                ("Content-Length".into(), body.len().to_string()),
515                ("Content-Type".into(), "application/octet-stream".into()),
516            ],
517            body,
518            false,
519            0,
520            false,
521        )
522    }
523
524    #[test]
525    fn strict_config_uses_expected_policy() {
526        let t = strict_transport();
527        assert_eq!(t.config().max_redirects, DEFAULT_MAX_REDIRECTS);
528        assert_eq!(t.config().connect_timeout, DEFAULT_CONNECT_TIMEOUT);
529        assert_eq!(t.config().total_timeout, DEFAULT_TOTAL_TIMEOUT);
530        assert_eq!(
531            EggfetchTransport::eggfetch_version(),
532            "eggfetch-core 0.2.0 (http1,tls-rustls,tls-native-roots,proxy; no compression/cookies/retry/json)"
533        );
534    }
535
536    #[test]
537    fn downgrade_policy_denies_https_to_http() {
538        use eggfetch_core::RedirectDowngradePolicy;
539        let strict = RedirectPolicy::strict(10);
540        assert_eq!(strict.max_redirects, 10);
541        assert!(strict.follow);
542        let from: url::Url = "https://example.com/a".parse().unwrap();
543        let same: url::Url = "https://example.com/b".parse().unwrap();
544        let down: url::Url = "http://example.com/b".parse().unwrap();
545        assert!(strict.check_downgrade(&from, &same).is_ok());
546        assert!(strict.check_downgrade(&from, &down).is_err());
547        let _ = RedirectDowngradePolicy::Deny;
548    }
549
550    #[test]
551    fn metadata_200_is_success() {
552        let base = ok_server(b"hello-metadata".to_vec());
553        let t = strict_transport();
554        let out = t
555            .fetch_metadata(&req(&format!("{base}/meta")), limits(), &CancelFlag::new())
556            .unwrap();
557        assert_eq!(out.success().unwrap().bytes(), b"hello-metadata");
558    }
559
560    #[test]
561    fn oversized_metadata_is_too_large() {
562        let big = vec![9u8; 128 * 1024];
563        let base = ok_server(big);
564        let t = strict_transport();
565        let err = t
566            .fetch_metadata(&req(&format!("{base}/big")), limits(), &CancelFlag::new())
567            .unwrap_err();
568        assert!(matches!(err, AcquisitionError::TooLarge { .. }));
569    }
570
571    #[test]
572    fn streaming_download_writes_exact_bytes() {
573        let body: Vec<u8> = (0..8192).map(|i| (i % 251) as u8).collect();
574        let base = ok_server(body.clone());
575        let t = strict_transport();
576        let dir = temp_dir("eggfetch-stream");
577        let dest = dir.join("app");
578        let out = t
579            .fetch_artifact(
580                &req(&format!("{base}/app")),
581                &dest,
582                limits(),
583                &CancelFlag::new(),
584            )
585            .unwrap();
586        assert_eq!(out.success().unwrap().bytes_written, 8192);
587        assert_eq!(fs::read(&dest).unwrap(), body);
588        let _ = fs::remove_dir_all(&dir);
589    }
590
591    #[test]
592    fn truncation_is_a_hard_failure_without_promotion() {
593        let body = vec![5u8; 4096];
594        let base = serve_once(
595            200,
596            vec![("Content-Length".into(), "4096".into())],
597            body,
598            false,
599            0,
600            true,
601        );
602        let t = strict_transport();
603        let dir = temp_dir("eggfetch-trunc");
604        let dest = dir.join("app");
605        let err = t
606            .fetch_artifact(
607                &req(&format!("{base}/app")),
608                &dest,
609                limits(),
610                &CancelFlag::new(),
611            )
612            .unwrap_err();
613        assert!(matches!(err, AcquisitionError::Transport(_)));
614        assert!(!dest.exists());
615        let _ = fs::remove_dir_all(&dir);
616    }
617
618    #[test]
619    fn not_found_is_typed_distinctly() {
620        let t = strict_transport();
621        let base = serve_once(404, vec![], b"nope".to_vec(), false, 0, false);
622        let out = t
623            .fetch_metadata(
624                &req(&format!("{base}/missing")),
625                limits(),
626                &CancelFlag::new(),
627            )
628            .unwrap();
629        assert!(out.is_not_found());
630        let base = serve_once(404, vec![], b"nope".to_vec(), false, 0, false);
631        let dir = temp_dir("eggfetch-404");
632        let dest = dir.join("app");
633        let out = t
634            .fetch_artifact(
635                &req(&format!("{base}/missing")),
636                &dest,
637                limits(),
638                &CancelFlag::new(),
639            )
640            .unwrap();
641        assert!(out.is_not_found());
642        assert!(!dest.exists());
643        let _ = fs::remove_dir_all(&dir);
644    }
645
646    #[test]
647    fn server_error_never_becomes_not_found() {
648        let base = serve_once(500, vec![], b"boom".to_vec(), false, 0, false);
649        let t = strict_transport();
650        let err = t
651            .fetch_metadata(&req(&format!("{base}/boom")), limits(), &CancelFlag::new())
652            .unwrap_err();
653        assert!(matches!(err, AcquisitionError::Transport(_)));
654    }
655
656    #[test]
657    fn redirect_limit_is_enforced() {
658        // Self-redirect loop; client follows up to the bound then hard-fails.
659        static ADDR: OnceLock<String> = OnceLock::new();
660        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
661        let addr = listener.local_addr().unwrap().to_string();
662        ADDR.set(format!("http://{addr}")).ok();
663        let target = format!("http://{addr}/loop");
664        thread::spawn(move || {
665            for mut s in listener.incoming().take(12).flatten() {
666                s.set_read_timeout(Some(Duration::from_secs(2))).ok();
667                s.set_write_timeout(Some(Duration::from_secs(2))).ok();
668                let mut buf = [0u8; 4096];
669                let _ = s.read(&mut buf);
670                let resp = format!(
671                    "HTTP/1.1 302 Found\r\nLocation: {target}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
672                );
673                let _ = s.write_all(resp.as_bytes());
674            }
675        });
676        let mut cfg = EggfetchConfig::strict();
677        cfg.max_redirects = 2;
678        let t = EggfetchTransport::strict(cfg).unwrap();
679        let err = t
680            .fetch_metadata(
681                &req(&format!("http://{addr}/loop")),
682                limits(),
683                &CancelFlag::new(),
684            )
685            .unwrap_err();
686        assert!(matches!(err, AcquisitionError::Transport(_)));
687    }
688
689    #[test]
690    fn total_timeout_is_a_hard_failure() {
691        let body = b"too-late".to_vec();
692        let base = serve_once(
693            200,
694            vec![("Content-Length".into(), body.len().to_string())],
695            body,
696            false,
697            3000,
698            false,
699        );
700        let mut cfg = EggfetchConfig::strict();
701        cfg.total_timeout = Duration::from_millis(300);
702        cfg.connect_timeout = Duration::from_millis(300);
703        let t = EggfetchTransport::strict(cfg).unwrap();
704        let err = t
705            .fetch_metadata(
706                &req(&format!("{base}/slow")),
707                FetchLimits {
708                    max_metadata_bytes: 64 * 1024,
709                    max_artifact_bytes: Some(256 * 1024),
710                    connect_timeout: Duration::from_millis(300),
711                    total_timeout: Duration::from_millis(300),
712                },
713                &CancelFlag::new(),
714            )
715            .unwrap_err();
716        assert!(matches!(
717            err,
718            AcquisitionError::Timeout { .. } | AcquisitionError::Transport(_)
719        ));
720    }
721
722    #[test]
723    fn invalid_proxy_fails_closed() {
724        let cfg = EggfetchConfig::strict().proxy(ProxyDecision::Custom(vec![(
725            "HTTPS_PROXY".into(),
726            "http://user:bogus@[::1".into(),
727        )]));
728        assert!(EggfetchTransport::strict(cfg).is_err());
729    }
730
731    #[test]
732    fn output_file_is_cleaned_on_failure() {
733        let base = serve_once(500, vec![], b"boom".to_vec(), false, 0, false);
734        let t = strict_transport();
735        let dir = temp_dir("eggfetch-cleanup");
736        let dest = dir.join("app");
737        let _ = t.fetch_artifact(
738            &req(&format!("{base}/boom")),
739            &dest,
740            limits(),
741            &CancelFlag::new(),
742        );
743        assert!(!dest.exists());
744        let leftovers: Vec<_> = fs::read_dir(&dir)
745            .unwrap()
746            .filter_map(|e| e.ok())
747            .filter(|e| {
748                e.file_name()
749                    .to_string_lossy()
750                    .starts_with(".eggup-eggfetch-")
751            })
752            .collect();
753        assert!(leftovers.is_empty());
754        let _ = fs::remove_dir_all(&dir);
755    }
756
757    #[test]
758    fn seam_fixture_and_adapter_agree_on_not_found() {
759        // Cross-check: both transports type 404 as NotFound, never fallback.
760        let fixture = FixtureTransport::new();
761        fixture.route("https://example.com/missing", FixtureResponse::not_found());
762        let out = fixture
763            .fetch_metadata(
764                &AcquisitionRequest::new("https://example.com/missing").unwrap(),
765                eggup_acquisition::FetchLimits::default(),
766                &eggup_acquisition::CancelFlag::new(),
767            )
768            .unwrap();
769        assert!(out.is_not_found());
770    }
771}