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 adapter ceilings.
90    ///
91    /// These are ceilings, not defaults: the effective deadline for one fetch
92    /// is `min(request, adapter ceiling)` (see [`FetchLimits::effective`]).
93    /// A stricter adapter tightens a deadline; it never extends one.
94    /// Invalid values (zero or `connect > total`) fail closed in
95    /// [`EggfetchTransport::strict`].
96    pub fn timeouts(mut self, connect: Duration, total: Duration) -> Self {
97        self.connect_timeout = connect;
98        self.total_timeout = total;
99        self
100    }
101
102    /// Sets the redirect bound.
103    pub fn max_redirects(mut self, max: usize) -> Self {
104        self.max_redirects = max;
105        self
106    }
107
108    /// Sets the proxy decision.
109    pub fn proxy(mut self, proxy: ProxyDecision) -> Self {
110        self.proxy = proxy;
111        self
112    }
113
114    /// Derives the authoritative effective deadlines for one fetch.
115    ///
116    /// A stricter adapter ceiling wins; the adapter never extends a caller
117    /// deadline. Both metadata and artifact operations use this derivation,
118    /// and the effective total covers headers plus body streaming. This
119    /// helper assumes `limits.validate()` has succeeded; transport entry
120    /// points perform that validation before calling it.
121    pub fn effective_timeouts(&self, limits: FetchLimits) -> (Duration, Duration) {
122        limits.effective(self.connect_timeout, self.total_timeout)
123    }
124
125    fn timeout(&self) -> Timeout {
126        Timeout::builder()
127            .connect(self.connect_timeout)
128            .total(self.total_timeout)
129            .build()
130    }
131
132    fn effective_request_timeout(&self, limits: FetchLimits) -> Timeout {
133        let (connect, total) = self.effective_timeouts(limits);
134        Timeout::builder().connect(connect).total(total).build()
135    }
136
137    fn validate_timeouts(&self) -> Result<(), AcquisitionError> {
138        if self.connect_timeout.is_zero() || self.total_timeout.is_zero() {
139            return Err(AcquisitionError::InvalidInput(bound(
140                "adapter timeouts must be positive".to_string(),
141            )));
142        }
143        if self.connect_timeout > self.total_timeout {
144            return Err(AcquisitionError::InvalidInput(bound(
145                "adapter connect timeout must not exceed total timeout".to_string(),
146            )));
147        }
148        Ok(())
149    }
150
151    fn redirect_policy(&self) -> RedirectPolicy {
152        RedirectPolicy::strict(self.max_redirects)
153    }
154
155    fn build_client(&self) -> Result<Client, AcquisitionError> {
156        self.validate_timeouts()?;
157        let env = self
158            .proxy
159            .environment()
160            // ProxyEnvironment construction is infallible for our decisions;
161            // never echo environment content on failure.
162            .map_err(|_| {
163                AcquisitionError::Transport(bound(
164                    "proxy configuration/routing failure".to_string(),
165                ))
166            })?;
167        let builder = Client::builder()
168            .user_agent(&self.user_agent)
169            .http_version_policy(HttpVersionPolicy::Http1Only)
170            .redirect_policy(self.redirect_policy())
171            .timeout(self.timeout())
172            .automatic_decompression(false);
173        builder
174            .proxy_environment(&env)
175            .map(|b| b.build())
176            .map_err(|_| {
177                // Never embed upstream proxy error display: it may contain
178                // proxy URLs with credentials. Use category-only diagnostics.
179                AcquisitionError::Transport(bound(
180                    "proxy configuration/routing failure".to_string(),
181                ))
182            })
183    }
184}
185
186/// Native Eggfetch adapter implementing the acquisition seam.
187///
188/// No release, version, fallback, destination, or service policy lives here.
189/// Checksum mismatch, TLS errors, malformed metadata, timeouts, 5xx, and
190/// redirect violations are hard failures; only exact 404 becomes `NotFound`.
191pub struct EggfetchTransport {
192    client: Client,
193    config: EggfetchConfig,
194}
195
196impl EggfetchTransport {
197    /// Builds a strict adapter. Invalid proxy configuration fails closed here,
198    /// never silently direct.
199    pub fn strict(config: EggfetchConfig) -> Result<Self, AcquisitionError> {
200        let client = config.build_client()?;
201        Ok(Self { client, config })
202    }
203
204    /// Returns the transport configuration.
205    pub fn config(&self) -> &EggfetchConfig {
206        &self.config
207    }
208
209    /// Returns the exact Eggfetch dependency version used.
210    pub fn eggfetch_version() -> &'static str {
211        // Recorded at qualification time; updated when the dependency changes.
212        "eggfetch-core 0.2.0 (http1,tls-rustls,tls-native-roots,proxy; no compression/cookies/retry/json)"
213    }
214
215    fn block_on<F, T>(&self, fut: F) -> T
216    where
217        F: std::future::Future<Output = T>,
218    {
219        // Private current-thread runtime so the sync seam never forces an
220        // async runtime into eggup-core or lightweight consumers. Async
221        // consumers should call the sync seam via spawn_blocking per their
222        // own policy.
223        let rt = tokio::runtime::Builder::new_current_thread()
224            .enable_all()
225            .build()
226            .expect("eggfetch current-thread runtime");
227        rt.block_on(fut)
228    }
229}
230
231impl AcquisitionTransport for EggfetchTransport {
232    fn fetch_metadata(
233        &self,
234        request: &AcquisitionRequest,
235        limits: FetchLimits,
236        cancel: &CancelFlag,
237    ) -> Result<FetchOutcome<MetadataBytes>, AcquisitionError> {
238        limits.validate()?;
239        if cancel.is_cancelled() {
240            return Err(AcquisitionError::Cancelled);
241        }
242        // Per-fetch byte bound is authoritative; Content-Length is advisory only.
243        // Effective time bounds are min(request, adapter ceiling) and enforced
244        // via a real Eggfetch request-level timeout override, never a
245        // post-hoc elapsed check.
246        let max = limits.max_metadata_bytes;
247        let url = request.url().to_string();
248        let effective = self.config.effective_request_timeout(limits);
249        let result = self.block_on(async {
250            let mut response = self
251                .client
252                .get(&url)
253                .map_err(|e| map_request_error(&e, request))?
254                .timeout(effective)
255                .max_decoded_body_size(max)
256                .send()
257                .await
258                .map_err(|e| map_fetch_error(&e, request, Some(max)))?;
259            let status = response.status().as_u16();
260            match classify(status) {
261                StatusClass::NotFound => Ok(FetchOutcome::NotFound),
262                StatusClass::HardFailure => Err(AcquisitionError::Transport(bound(format!(
263                    "HTTP {status} from {} while fetching metadata",
264                    request.redacted()
265                )))),
266                StatusClass::Success => {
267                    if cancel.is_cancelled() {
268                        return Err(AcquisitionError::Cancelled);
269                    }
270                    if let Some(declared) = response.content_length() {
271                        if declared > max as u64 {
272                            return Err(AcquisitionError::TooLarge { limit: max as u64 });
273                        }
274                    }
275                    let bytes = response
276                        .bytes()
277                        .await
278                        .map_err(|e| map_fetch_error(&e, request, Some(max)))?;
279                    if bytes.len() > max {
280                        return Err(AcquisitionError::TooLarge { limit: max as u64 });
281                    }
282                    Ok(FetchOutcome::Success(
283                        eggup_acquisition::__adapter_metadata(bytes.to_vec()),
284                    ))
285                }
286            }
287        });
288        // Enforce caller total timeout even if the inner client policy drifts:
289        // the inner Timeout already covers connect/total, so a Timeout error
290        // here is authoritative. No extra wall-clock wrapper is needed for the
291        // sync bridge because block_on inherits the client deadlines.
292        result
293    }
294
295    fn fetch_artifact(
296        &self,
297        request: &AcquisitionRequest,
298        dest: &Path,
299        limits: FetchLimits,
300        cancel: &CancelFlag,
301    ) -> Result<FetchOutcome<ArtifactEvidence>, AcquisitionError> {
302        limits.validate()?;
303        if cancel.is_cancelled() {
304            return Err(AcquisitionError::Cancelled);
305        }
306        let parent = dest.parent().ok_or_else(|| {
307            AcquisitionError::InvalidInput(bound("destination has no parent".into()))
308        })?;
309        let parent_meta = fs::symlink_metadata(parent)
310            .map_err(|e| AcquisitionError::Io(bound(format!("reading artifact parent: {e}"))))?;
311        if !parent_meta.is_dir() || parent_meta.file_type().is_symlink() {
312            return Err(AcquisitionError::InvalidInput(bound(
313                "artifact parent must be an existing real directory".into(),
314            )));
315        }
316        // Fast-fail when the destination already exists. The race-safe
317        // guarantee comes from `__promote_no_clobber` after streaming.
318        if fs::symlink_metadata(dest).is_ok() {
319            return Err(AcquisitionError::InvalidInput(bound(
320                "artifact destination already exists; refusing to overwrite".into(),
321            )));
322        }
323        let url = request.url().to_string();
324        let max_artifact = limits.max_artifact_bytes;
325        let redacted = request.redacted();
326        let effective = self.config.effective_request_timeout(limits);
327        let parent_owned = parent.to_path_buf();
328        let dest_owned = dest.to_path_buf();
329        let result: Result<FetchOutcome<ArtifactEvidence>, AcquisitionError> =
330            self.block_on(async {
331                use futures_util::StreamExt;
332                use tokio::io::AsyncWriteExt;
333                let mut response = self
334                    .client
335                    .get(&url)
336                    .map_err(|e| map_request_error(&e, request))?
337                    .timeout(effective)
338                    .send()
339                    .await
340                    .map_err(|e| map_fetch_error(&e, request, None))?;
341                let status = response.status().as_u16();
342                match classify(status) {
343                    StatusClass::NotFound => return Ok(FetchOutcome::NotFound),
344                    StatusClass::HardFailure => {
345                        return Err(AcquisitionError::Transport(bound(format!(
346                            "HTTP {status} from {redacted} while fetching artifact"
347                        ))));
348                    }
349                    StatusClass::Success => {}
350                }
351                // Exclusive owner-private temp plus race-safe no-clobber
352                // promotion. The temp lives in the exact destination parent
353                // so promotion stays on the same filesystem.
354                let (std_file, tmp) =
355                    eggup_acquisition::__acquire_exclusive_temp(&parent_owned, "eggup-eggfetch")?;
356                struct Guard {
357                    path: std::path::PathBuf,
358                    disarm: bool,
359                }
360                impl Drop for Guard {
361                    fn drop(&mut self) {
362                        if !self.disarm {
363                            eggup_acquisition::__remove_owned_temp(&self.path);
364                        }
365                    }
366                }
367                let mut guard = Guard {
368                    path: tmp.clone(),
369                    disarm: false,
370                };
371                let mut file = tokio::fs::File::from_std(std_file);
372                let mut stream = response
373                    .bytes_stream()
374                    .map_err(|e| map_fetch_error(&e, request, None))?;
375                let mut written: u64 = 0;
376                while let Some(chunk) = stream.next().await {
377                    if cancel.is_cancelled() {
378                        return Err(AcquisitionError::Cancelled);
379                    }
380                    let chunk = chunk.map_err(|e| map_fetch_error(&e, request, None))?;
381                    if chunk.is_empty() {
382                        continue;
383                    }
384                    written = written.saturating_add(chunk.len() as u64);
385                    if written > max_artifact {
386                        return Err(AcquisitionError::TooLarge {
387                            limit: max_artifact,
388                        });
389                    }
390                    file.write_all(&chunk).await.map_err(|e| {
391                        AcquisitionError::Io(bound(format!("writing part file: {e}")))
392                    })?;
393                }
394                file.flush()
395                    .await
396                    .map_err(|e| AcquisitionError::Io(bound(format!("flushing part file: {e}"))))?;
397                drop(file);
398                if cancel.is_cancelled() {
399                    return Err(AcquisitionError::Cancelled);
400                }
401                match eggup_acquisition::__promote_no_clobber(&tmp, &dest_owned) {
402                    Ok(()) => {
403                        guard.disarm = true;
404                        Ok(FetchOutcome::Success(
405                            eggup_acquisition::__adapter_artifact(written),
406                        ))
407                    }
408                    Err(e) => {
409                        eggup_acquisition::__remove_owned_temp(&tmp);
410                        guard.disarm = true;
411                        Err(e)
412                    }
413                }
414            });
415        result
416    }
417}
418
419fn bound(s: String) -> String {
420    let mut s = s;
421    if s.len() > 512 {
422        let mut end = 512;
423        while !s.is_char_boundary(end) {
424            end -= 1;
425        }
426        s.truncate(end);
427    }
428    s
429}
430
431#[derive(Debug, Clone, Copy, PartialEq, Eq)]
432enum StatusClass {
433    Success,
434    NotFound,
435    HardFailure,
436}
437
438fn classify(status: u16) -> StatusClass {
439    match status {
440        200..=299 => StatusClass::Success,
441        404 => StatusClass::NotFound,
442        _ => StatusClass::HardFailure,
443    }
444}
445
446fn map_request_error(e: &eggfetch_core::Error, request: &AcquisitionRequest) -> AcquisitionError {
447    use eggfetch_core::Error as E;
448    match e {
449        // Never embed upstream proxy/detail display: it may contain proxy
450        // URLs with credentials. Use category-only diagnostics.
451        E::InvalidProxyUrl(_) => {
452            AcquisitionError::Transport(bound("proxy configuration/routing failure".to_string()))
453        }
454        E::Timeout { phase, .. } => AcquisitionError::Timeout {
455            phase: match phase {
456                eggfetch_core::TimeoutPhase::Connect => "connect",
457                eggfetch_core::TimeoutPhase::Total => "total",
458                _ => "total",
459            },
460        },
461        _ => AcquisitionError::Transport(bound(format!(
462            "request build failed for {}: {}",
463            request.redacted(),
464            e.kind()
465        ))),
466    }
467}
468
469fn map_fetch_error(
470    e: &eggfetch_core::Error,
471    request: &AcquisitionRequest,
472    max: Option<usize>,
473) -> AcquisitionError {
474    use eggfetch_core::Error as E;
475    match e {
476        E::DecodedBodyTooLarge => AcquisitionError::TooLarge {
477            limit: max.unwrap_or(0) as u64,
478        },
479        E::Timeout { phase, .. } => AcquisitionError::Timeout {
480            phase: match phase {
481                eggfetch_core::TimeoutPhase::Connect => "connect",
482                eggfetch_core::TimeoutPhase::Total => "total",
483                _ => "total",
484            },
485        },
486        // TransportIoTimeout is an inactivity timeout on an established
487        // connection; classify as Timeout so caller deadlines stay truthful.
488        E::TransportIoTimeout { .. } => AcquisitionError::Timeout { phase: "total" },
489        // Never embed upstream error display or proxy detail: it may contain
490        // credential-bearing URLs. Use structured category text only.
491        E::InvalidProxyUrl(_) => {
492            AcquisitionError::Transport(bound("proxy configuration/routing failure".to_string()))
493        }
494        _ => AcquisitionError::Transport(bound(format!(
495            "fetch failed for {}: {}",
496            request.redacted(),
497            e.kind()
498        ))),
499    }
500}
501
502#[cfg(test)]
503mod tests {
504    use super::*;
505
506    #[test]
507    fn diagnostic_bound_never_splits_multibyte_code_points() {
508        for (limit, ch) in [(512, "é"), (512, "€"), (512, "🦀")] {
509            let prefix = "x".repeat(limit - 1);
510            let bounded = bound(format!("{prefix}{ch}tail"));
511            assert_eq!(bounded, prefix);
512            assert!(bounded.len() <= limit);
513        }
514    }
515    use eggup_acquisition::{AcquisitionRequest, FixtureResponse, FixtureTransport};
516    use std::io::{Read, Write};
517    use std::net::TcpListener;
518    use std::sync::OnceLock;
519    use std::thread;
520
521    fn strict_transport() -> EggfetchTransport {
522        EggfetchTransport::strict(EggfetchConfig::strict()).expect("strict transport")
523    }
524
525    fn req(url: &str) -> AcquisitionRequest {
526        AcquisitionRequest::new(url).unwrap()
527    }
528
529    fn limits() -> FetchLimits {
530        FetchLimits {
531            max_metadata_bytes: 64 * 1024,
532            max_artifact_bytes: 256 * 1024,
533            connect_timeout: Duration::from_secs(2),
534            total_timeout: Duration::from_secs(10),
535        }
536    }
537
538    fn temp_dir(prefix: &str) -> std::path::PathBuf {
539        let nanos = std::time::SystemTime::now()
540            .duration_since(std::time::UNIX_EPOCH)
541            .map(|d| d.as_nanos())
542            .unwrap_or(0);
543        let p = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()));
544        let _ = fs::create_dir_all(&p);
545        p
546    }
547
548    /// Minimal single-response HTTP/1.1 server on 127.0.0.1.
549    fn serve_once(
550        status: u16,
551        headers: Vec<(String, String)>,
552        body: Vec<u8>,
553        split_body: bool,
554        stall_before_body_ms: u64,
555        abort_after_headers: bool,
556    ) -> String {
557        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
558        let addr = listener.local_addr().unwrap();
559        thread::spawn(move || {
560            if let Ok((mut stream, _)) = listener.accept() {
561                stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
562                stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
563                let mut buf = [0u8; 8192];
564                let _ = stream.read(&mut buf);
565                let reason = match status {
566                    200 => "OK",
567                    404 => "Not Found",
568                    500 => "Internal Server Error",
569                    302 => "Found",
570                    _ => "OK",
571                };
572                let mut head = format!("HTTP/1.1 {status} {reason}\r\n");
573                for (k, v) in headers {
574                    head.push_str(&format!("{k}: {v}\r\n"));
575                }
576                head.push_str("Connection: close\r\n\r\n");
577                let _ = stream.write_all(head.as_bytes());
578                if abort_after_headers {
579                    return;
580                }
581                if stall_before_body_ms > 0 {
582                    thread::sleep(Duration::from_millis(stall_before_body_ms));
583                }
584                if split_body {
585                    let mid = body.len() / 2;
586                    let _ = stream.write_all(&body[..mid]);
587                    thread::sleep(Duration::from_millis(20));
588                    let _ = stream.write_all(&body[mid..]);
589                } else {
590                    let _ = stream.write_all(&body);
591                }
592            }
593        });
594        format!("http://{addr}")
595    }
596
597    fn ok_server(body: Vec<u8>) -> String {
598        serve_once(
599            200,
600            vec![
601                ("Content-Length".into(), body.len().to_string()),
602                ("Content-Type".into(), "application/octet-stream".into()),
603            ],
604            body,
605            false,
606            0,
607            false,
608        )
609    }
610
611    #[test]
612    fn strict_config_uses_expected_policy() {
613        let t = strict_transport();
614        assert_eq!(t.config().max_redirects, DEFAULT_MAX_REDIRECTS);
615        assert_eq!(t.config().connect_timeout, DEFAULT_CONNECT_TIMEOUT);
616        assert_eq!(t.config().total_timeout, DEFAULT_TOTAL_TIMEOUT);
617        assert_eq!(
618            EggfetchTransport::eggfetch_version(),
619            "eggfetch-core 0.2.0 (http1,tls-rustls,tls-native-roots,proxy; no compression/cookies/retry/json)"
620        );
621    }
622
623    #[test]
624    fn downgrade_policy_denies_https_to_http() {
625        use eggfetch_core::RedirectDowngradePolicy;
626        let strict = RedirectPolicy::strict(10);
627        assert_eq!(strict.max_redirects, 10);
628        assert!(strict.follow);
629        let from: url::Url = "https://example.com/a".parse().unwrap();
630        let same: url::Url = "https://example.com/b".parse().unwrap();
631        let down: url::Url = "http://example.com/b".parse().unwrap();
632        assert!(strict.check_downgrade(&from, &same).is_ok());
633        assert!(strict.check_downgrade(&from, &down).is_err());
634        let _ = RedirectDowngradePolicy::Deny;
635    }
636
637    #[test]
638    fn metadata_200_is_success() {
639        let base = ok_server(b"hello-metadata".to_vec());
640        let t = strict_transport();
641        let out = t
642            .fetch_metadata(&req(&format!("{base}/meta")), limits(), &CancelFlag::new())
643            .unwrap();
644        assert_eq!(out.success().unwrap().bytes(), b"hello-metadata");
645    }
646
647    #[test]
648    fn invalid_public_limits_fail_before_eggfetch_io() {
649        let transport = strict_transport();
650        let request = req("http://127.0.0.1:1/never-contact");
651        let invalid = [
652            FetchLimits {
653                max_metadata_bytes: 0,
654                ..limits()
655            },
656            FetchLimits {
657                max_metadata_bytes: 16 * 1024 * 1024 + 1,
658                ..limits()
659            },
660            FetchLimits {
661                connect_timeout: Duration::ZERO,
662                ..limits()
663            },
664            FetchLimits {
665                total_timeout: Duration::ZERO,
666                ..limits()
667            },
668            FetchLimits {
669                connect_timeout: Duration::from_secs(11),
670                total_timeout: Duration::from_secs(10),
671                ..limits()
672            },
673        ];
674        let dir = temp_dir("eggfetch-invalid-limits");
675        let dest = dir.join("app");
676        for limits in invalid {
677            assert!(matches!(
678                transport.fetch_metadata(&request, limits, &CancelFlag::new()),
679                Err(AcquisitionError::InvalidInput(_))
680            ));
681            assert!(matches!(
682                transport.fetch_artifact(&request, &dest, limits, &CancelFlag::new()),
683                Err(AcquisitionError::InvalidInput(_))
684            ));
685            assert!(!dest.exists());
686            assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
687        }
688        assert!(limits().validate().is_ok());
689        let _ = fs::remove_dir_all(&dir);
690    }
691
692    #[test]
693    fn oversized_metadata_is_too_large() {
694        let big = vec![9u8; 128 * 1024];
695        let base = ok_server(big);
696        let t = strict_transport();
697        let err = t
698            .fetch_metadata(&req(&format!("{base}/big")), limits(), &CancelFlag::new())
699            .unwrap_err();
700        assert!(matches!(err, AcquisitionError::TooLarge { .. }));
701    }
702
703    #[test]
704    fn streaming_download_writes_exact_bytes() {
705        let body: Vec<u8> = (0..8192).map(|i| (i % 251) as u8).collect();
706        let base = ok_server(body.clone());
707        let t = strict_transport();
708        let dir = temp_dir("eggfetch-stream");
709        let dest = dir.join("app");
710        let out = t
711            .fetch_artifact(
712                &req(&format!("{base}/app")),
713                &dest,
714                limits(),
715                &CancelFlag::new(),
716            )
717            .unwrap();
718        assert_eq!(out.success().unwrap().bytes_written, 8192);
719        assert_eq!(fs::read(&dest).unwrap(), body);
720        let _ = fs::remove_dir_all(&dir);
721    }
722
723    #[test]
724    fn truncation_is_a_hard_failure_without_promotion() {
725        let body = vec![5u8; 4096];
726        let base = serve_once(
727            200,
728            vec![("Content-Length".into(), "4096".into())],
729            body,
730            false,
731            0,
732            true,
733        );
734        let t = strict_transport();
735        let dir = temp_dir("eggfetch-trunc");
736        let dest = dir.join("app");
737        let err = t
738            .fetch_artifact(
739                &req(&format!("{base}/app")),
740                &dest,
741                limits(),
742                &CancelFlag::new(),
743            )
744            .unwrap_err();
745        assert!(matches!(err, AcquisitionError::Transport(_)));
746        assert!(!dest.exists());
747        let _ = fs::remove_dir_all(&dir);
748    }
749
750    #[test]
751    fn not_found_is_typed_distinctly() {
752        let t = strict_transport();
753        let base = serve_once(404, vec![], b"nope".to_vec(), false, 0, false);
754        let out = t
755            .fetch_metadata(
756                &req(&format!("{base}/missing")),
757                limits(),
758                &CancelFlag::new(),
759            )
760            .unwrap();
761        assert!(out.is_not_found());
762        let base = serve_once(404, vec![], b"nope".to_vec(), false, 0, false);
763        let dir = temp_dir("eggfetch-404");
764        let dest = dir.join("app");
765        let out = t
766            .fetch_artifact(
767                &req(&format!("{base}/missing")),
768                &dest,
769                limits(),
770                &CancelFlag::new(),
771            )
772            .unwrap();
773        assert!(out.is_not_found());
774        assert!(!dest.exists());
775        let _ = fs::remove_dir_all(&dir);
776    }
777
778    #[test]
779    fn server_error_never_becomes_not_found() {
780        let base = serve_once(500, vec![], b"boom".to_vec(), false, 0, false);
781        let t = strict_transport();
782        let err = t
783            .fetch_metadata(&req(&format!("{base}/boom")), limits(), &CancelFlag::new())
784            .unwrap_err();
785        assert!(matches!(err, AcquisitionError::Transport(_)));
786    }
787
788    #[test]
789    fn redirect_limit_is_enforced() {
790        // Self-redirect loop; client follows up to the bound then hard-fails.
791        static ADDR: OnceLock<String> = OnceLock::new();
792        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
793        let addr = listener.local_addr().unwrap().to_string();
794        ADDR.set(format!("http://{addr}")).ok();
795        let target = format!("http://{addr}/loop");
796        thread::spawn(move || {
797            for mut s in listener.incoming().take(12).flatten() {
798                s.set_read_timeout(Some(Duration::from_secs(2))).ok();
799                s.set_write_timeout(Some(Duration::from_secs(2))).ok();
800                let mut buf = [0u8; 4096];
801                let _ = s.read(&mut buf);
802                let resp = format!(
803                    "HTTP/1.1 302 Found\r\nLocation: {target}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
804                );
805                let _ = s.write_all(resp.as_bytes());
806            }
807        });
808        let mut cfg = EggfetchConfig::strict();
809        cfg.max_redirects = 2;
810        let t = EggfetchTransport::strict(cfg).unwrap();
811        let err = t
812            .fetch_metadata(
813                &req(&format!("http://{addr}/loop")),
814                limits(),
815                &CancelFlag::new(),
816            )
817            .unwrap_err();
818        assert!(matches!(err, AcquisitionError::Transport(_)));
819    }
820
821    #[test]
822    fn total_timeout_is_a_hard_failure() {
823        let body = b"too-late".to_vec();
824        let base = serve_once(
825            200,
826            vec![("Content-Length".into(), body.len().to_string())],
827            body,
828            false,
829            3000,
830            false,
831        );
832        let mut cfg = EggfetchConfig::strict();
833        cfg.total_timeout = Duration::from_millis(300);
834        cfg.connect_timeout = Duration::from_millis(300);
835        let t = EggfetchTransport::strict(cfg).unwrap();
836        let err = t
837            .fetch_metadata(
838                &req(&format!("{base}/slow")),
839                FetchLimits {
840                    max_metadata_bytes: 64 * 1024,
841                    max_artifact_bytes: 256 * 1024,
842                    connect_timeout: Duration::from_millis(300),
843                    total_timeout: Duration::from_millis(300),
844                },
845                &CancelFlag::new(),
846            )
847            .unwrap_err();
848        assert!(matches!(
849            err,
850            AcquisitionError::Timeout { .. } | AcquisitionError::Transport(_)
851        ));
852    }
853
854    #[test]
855    fn invalid_proxy_fails_closed() {
856        let cfg = EggfetchConfig::strict().proxy(ProxyDecision::Custom(vec![(
857            "HTTPS_PROXY".into(),
858            "http://user:bogus@[::1".into(),
859        )]));
860        assert!(EggfetchTransport::strict(cfg).is_err());
861    }
862
863    #[test]
864    fn output_file_is_cleaned_on_failure() {
865        let base = serve_once(500, vec![], b"boom".to_vec(), false, 0, false);
866        let t = strict_transport();
867        let dir = temp_dir("eggfetch-cleanup");
868        let dest = dir.join("app");
869        let _ = t.fetch_artifact(
870            &req(&format!("{base}/boom")),
871            &dest,
872            limits(),
873            &CancelFlag::new(),
874        );
875        assert!(!dest.exists());
876        let leftovers: Vec<_> = fs::read_dir(&dir)
877            .unwrap()
878            .filter_map(|e| e.ok())
879            .filter(|e| {
880                e.file_name()
881                    .to_string_lossy()
882                    .starts_with(".eggup-eggfetch-")
883            })
884            .collect();
885        assert!(leftovers.is_empty());
886        let _ = fs::remove_dir_all(&dir);
887    }
888
889    #[test]
890    fn seam_fixture_and_adapter_agree_on_not_found() {
891        // Cross-check: both transports type 404 as NotFound, never fallback.
892        let fixture = FixtureTransport::new();
893        fixture.route("https://example.com/missing", FixtureResponse::not_found());
894        let out = fixture
895            .fetch_metadata(
896                &AcquisitionRequest::new("https://example.com/missing").unwrap(),
897                eggup_acquisition::FetchLimits::default(),
898                &eggup_acquisition::CancelFlag::new(),
899            )
900            .unwrap();
901        assert!(out.is_not_found());
902    }
903
904    // ---- M003 corrective: authoritative effective timeouts ----
905
906    fn request_limits(connect: Duration, total: Duration) -> FetchLimits {
907        FetchLimits {
908            max_metadata_bytes: 64 * 1024,
909            max_artifact_bytes: 256 * 1024,
910            connect_timeout: connect,
911            total_timeout: total,
912        }
913    }
914
915    #[test]
916    fn request_stricter_than_adapter_wins() {
917        // Adapter allows 5 s; request allows 50 ms. The request bound must win
918        // via a real Eggfetch per-request override, not a post-hoc check.
919        let body = b"too-late".to_vec();
920        let base = serve_once(
921            200,
922            vec![("Content-Length".into(), body.len().to_string())],
923            body,
924            false,
925            3000,
926            false,
927        );
928        let cfg = EggfetchConfig::strict().timeouts(Duration::from_secs(5), Duration::from_secs(5));
929        let t = EggfetchTransport::strict(cfg).unwrap();
930        let err = t
931            .fetch_metadata(
932                &req(&format!("{base}/slow")),
933                request_limits(Duration::from_millis(50), Duration::from_millis(50)),
934                &CancelFlag::new(),
935            )
936            .unwrap_err();
937        assert!(
938            matches!(err, AcquisitionError::Timeout { .. }),
939            "request-stricter must time out, got {err:?}"
940        );
941    }
942
943    #[test]
944    fn adapter_stricter_than_request_wins() {
945        // Request allows 5 s; adapter allows 50 ms. The adapter ceiling must
946        // win, proving min(request, adapter) enforcement in both directions.
947        let body = b"too-late".to_vec();
948        let base = serve_once(
949            200,
950            vec![("Content-Length".into(), body.len().to_string())],
951            body,
952            false,
953            3000,
954            false,
955        );
956        let cfg =
957            EggfetchConfig::strict().timeouts(Duration::from_millis(50), Duration::from_millis(50));
958        let t = EggfetchTransport::strict(cfg).unwrap();
959        let err = t
960            .fetch_metadata(
961                &req(&format!("{base}/slow")),
962                request_limits(Duration::from_secs(5), Duration::from_secs(5)),
963                &CancelFlag::new(),
964            )
965            .unwrap_err();
966        assert!(
967            matches!(err, AcquisitionError::Timeout { .. }),
968            "adapter-stricter must time out, got {err:?}"
969        );
970    }
971
972    #[test]
973    fn connect_exceeding_total_is_rejected_in_both_layers() {
974        // Seam layer.
975        assert!(
976            FetchLimits::new(1024, 1024, Duration::from_secs(5), Duration::from_secs(1),).is_err()
977        );
978        // Adapter layer fails closed at construction.
979        let cfg = EggfetchConfig::strict().timeouts(Duration::from_secs(5), Duration::from_secs(1));
980        assert!(EggfetchTransport::strict(cfg).is_err());
981        // Zero deadlines also fail closed.
982        let zero = EggfetchConfig::strict().timeouts(Duration::ZERO, Duration::from_secs(1));
983        assert!(EggfetchTransport::strict(zero).is_err());
984    }
985
986    #[test]
987    fn metadata_body_stall_times_out_without_fallback() {
988        let body = b"stalled-metadata".to_vec();
989        let base = serve_once(
990            200,
991            vec![("Content-Length".into(), body.len().to_string())],
992            body,
993            false,
994            2000,
995            false,
996        );
997        let t = strict_transport();
998        let err = t
999            .fetch_metadata(
1000                &req(&format!("{base}/stall")),
1001                request_limits(Duration::from_millis(300), Duration::from_millis(300)),
1002                &CancelFlag::new(),
1003            )
1004            .unwrap_err();
1005        assert!(matches!(err, AcquisitionError::Timeout { .. }));
1006    }
1007
1008    /// Server that sends headers + partial body, then stalls past the deadline.
1009    fn serve_partial_then_stall(partial: Vec<u8>, total_len: usize, stall_ms: u64) -> String {
1010        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
1011        let addr = listener.local_addr().unwrap();
1012        thread::spawn(move || {
1013            if let Ok((mut stream, _)) = listener.accept() {
1014                stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
1015                stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
1016                let mut buf = [0u8; 8192];
1017                let _ = stream.read(&mut buf);
1018                let head = format!(
1019                    "HTTP/1.1 200 OK\r\nContent-Length: {total_len}\r\nContent-Type: application/octet-stream\r\nConnection: close\r\n\r\n"
1020                );
1021                let _ = stream.write_all(head.as_bytes());
1022                let _ = stream.write_all(&partial);
1023                thread::sleep(Duration::from_millis(stall_ms));
1024                // Close without sending the remainder: client must time out,
1025                // not promote a partial artifact.
1026            }
1027        });
1028        format!("http://{addr}")
1029    }
1030
1031    #[test]
1032    fn artifact_body_stall_after_partial_data_times_out() {
1033        let partial = vec![7u8; 1024];
1034        let base = serve_partial_then_stall(partial, 8192, 3000);
1035        let t = strict_transport();
1036        let dir = temp_dir("eggfetch-artifact-stall");
1037        let dest = dir.join("app");
1038        let err = t
1039            .fetch_artifact(
1040                &req(&format!("{base}/app")),
1041                &dest,
1042                request_limits(Duration::from_millis(300), Duration::from_millis(300)),
1043                &CancelFlag::new(),
1044            )
1045            .unwrap_err();
1046        assert!(
1047            matches!(err, AcquisitionError::Timeout { .. }),
1048            "artifact stall must be Timeout, got {err:?}"
1049        );
1050        assert!(!dest.exists(), "partial artifact must not promote");
1051        let leftovers: Vec<_> = fs::read_dir(&dir)
1052            .unwrap()
1053            .filter_map(|e| e.ok())
1054            .filter(|e| e.file_name().to_string_lossy().ends_with(".part"))
1055            .collect();
1056        assert!(leftovers.is_empty());
1057        let _ = fs::remove_dir_all(&dir);
1058    }
1059
1060    #[test]
1061    fn timeout_never_becomes_not_found() {
1062        let body = b"late".to_vec();
1063        let base = serve_once(
1064            200,
1065            vec![("Content-Length".into(), body.len().to_string())],
1066            body,
1067            false,
1068            2000,
1069            false,
1070        );
1071        let t = strict_transport();
1072        let err = t
1073            .fetch_metadata(
1074                &req(&format!("{base}/x")),
1075                request_limits(Duration::from_millis(100), Duration::from_millis(100)),
1076                &CancelFlag::new(),
1077            )
1078            .unwrap_err();
1079        assert!(matches!(err, AcquisitionError::Timeout { .. }));
1080        assert!(!matches!(err, AcquisitionError::InvalidInput(_)));
1081    }
1082
1083    // ---- M003 corrective: exclusive temp + no-clobber ----
1084
1085    #[test]
1086    fn artifact_refuses_existing_destination_without_overwrite() {
1087        let body: Vec<u8> = (0..256).map(|i| i as u8).collect();
1088        let base = ok_server(body);
1089        let t = strict_transport();
1090        let dir = temp_dir("eggfetch-noclobber");
1091        let dest = dir.join("app");
1092        fs::write(&dest, b"FOREIGN-EGGFETCH").unwrap();
1093        let err = t
1094            .fetch_artifact(
1095                &req(&format!("{base}/app")),
1096                &dest,
1097                limits(),
1098                &CancelFlag::new(),
1099            )
1100            .unwrap_err();
1101        assert!(matches!(
1102            err,
1103            AcquisitionError::InvalidInput(_) | AcquisitionError::Io(_)
1104        ));
1105        assert_eq!(fs::read(&dest).unwrap(), b"FOREIGN-EGGFETCH");
1106        let leftovers: Vec<_> = fs::read_dir(&dir)
1107            .unwrap()
1108            .filter_map(|e| e.ok())
1109            .filter(|e| e.file_name().to_string_lossy().ends_with(".part"))
1110            .collect();
1111        assert!(leftovers.is_empty());
1112        let _ = fs::remove_dir_all(&dir);
1113    }
1114
1115    #[cfg(unix)]
1116    #[test]
1117    fn exclusive_temp_helper_is_owner_private_for_eggfetch_prefix() {
1118        use std::os::unix::fs::PermissionsExt;
1119        let dir = temp_dir("eggfetch-mode");
1120        let (f, tmp) = eggup_acquisition::__acquire_exclusive_temp(&dir, "eggup-eggfetch").unwrap();
1121        let mode = f.metadata().unwrap().permissions().mode() & 0o777;
1122        assert_eq!(mode, 0o600);
1123        drop(f);
1124        eggup_acquisition::__remove_owned_temp(&tmp);
1125        let _ = fs::remove_dir_all(&dir);
1126    }
1127
1128    // ---- M003 corrective: redaction ----
1129
1130    #[test]
1131    fn error_diagnostics_never_expose_credential_sentinels() {
1132        let userinfo = "S3CR3T-USERINFO-8841";
1133        let query = "TOKEN-QUERY-7734";
1134        let proxy_pw = "HUNTER2-PROXY-9902";
1135        // Request URL with sentinels: any error must embed only the redacted URL.
1136        let url = format!("https://alice:{userinfo}@127.0.0.1:9/app?token={query}");
1137        let t = strict_transport();
1138        // Unroutable port gives a fast transport failure without network wait.
1139        // Use a short deadline so the test stays fast even if it dials.
1140        let err = t
1141            .fetch_metadata(
1142                &req(&url),
1143                request_limits(Duration::from_millis(300), Duration::from_millis(300)),
1144                &CancelFlag::new(),
1145            )
1146            .unwrap_err();
1147        let msg = format!("{err}");
1148        let dbg = format!("{err:?}");
1149        assert!(!msg.contains(userinfo), "userinfo leaked: {msg}");
1150        assert!(!msg.contains(query), "query leaked: {msg}");
1151        assert!(!dbg.contains(userinfo));
1152        assert!(!dbg.contains(query));
1153        // Upstream error strings must map to category-only text.
1154        let fake = eggfetch_core::Error::InvalidProxyUrl(format!(
1155            "http://proxy:{proxy_pw}@example.com:8080"
1156        ));
1157        assert!(fake.to_string().contains(proxy_pw));
1158        // Our mapper must not echo that detail.
1159        let req2 = req("https://example.com/x");
1160        let mapped = super::map_fetch_error(&fake, &req2, None);
1161        let mapped_msg = format!("{mapped}");
1162        assert!(
1163            !mapped_msg.contains(proxy_pw),
1164            "proxy pw leaked: {mapped_msg}"
1165        );
1166        // Invalid proxy construction also stays generic.
1167        let bad_cfg = EggfetchConfig::strict().proxy(ProxyDecision::Custom(vec![(
1168            "HTTPS_PROXY".into(),
1169            format!("http://user:{proxy_pw}@example.com:8080"),
1170        )]));
1171        // Either construction fails closed with a generic message, or a later
1172        // fetch fails without echoing the password. Both are acceptable as
1173        // long as the password never appears.
1174        if let Err(e) = EggfetchTransport::strict(bad_cfg) {
1175            assert!(!format!("{e}").contains(proxy_pw));
1176        }
1177    }
1178
1179    #[test]
1180    fn effective_formula_is_minimum_per_phase() {
1181        let cfg =
1182            EggfetchConfig::strict().timeouts(Duration::from_secs(1), Duration::from_secs(10));
1183        let req_limits = request_limits(Duration::from_secs(5), Duration::from_secs(5));
1184        let (c, t) = cfg.effective_timeouts(req_limits);
1185        assert_eq!(c, Duration::from_secs(1));
1186        assert_eq!(t, Duration::from_secs(5));
1187    }
1188}