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                    if let Some(max) = max_artifact {
385                        written = written.saturating_add(chunk.len() as u64);
386                        if written > max {
387                            return Err(AcquisitionError::TooLarge { limit: max });
388                        }
389                    } else {
390                        written = written.saturating_add(chunk.len() as u64);
391                    }
392                    file.write_all(&chunk).await.map_err(|e| {
393                        AcquisitionError::Io(bound(format!("writing part file: {e}")))
394                    })?;
395                }
396                file.flush()
397                    .await
398                    .map_err(|e| AcquisitionError::Io(bound(format!("flushing part file: {e}"))))?;
399                drop(file);
400                if cancel.is_cancelled() {
401                    return Err(AcquisitionError::Cancelled);
402                }
403                match eggup_acquisition::__promote_no_clobber(&tmp, &dest_owned) {
404                    Ok(()) => {
405                        guard.disarm = true;
406                        Ok(FetchOutcome::Success(
407                            eggup_acquisition::__adapter_artifact(written),
408                        ))
409                    }
410                    Err(e) => {
411                        eggup_acquisition::__remove_owned_temp(&tmp);
412                        guard.disarm = true;
413                        Err(e)
414                    }
415                }
416            });
417        result
418    }
419}
420
421fn bound(s: String) -> String {
422    let mut s = s;
423    if s.len() > 512 {
424        s.truncate(512);
425    }
426    s
427}
428
429#[derive(Debug, Clone, Copy, PartialEq, Eq)]
430enum StatusClass {
431    Success,
432    NotFound,
433    HardFailure,
434}
435
436fn classify(status: u16) -> StatusClass {
437    match status {
438        200..=299 => StatusClass::Success,
439        404 => StatusClass::NotFound,
440        _ => StatusClass::HardFailure,
441    }
442}
443
444fn map_request_error(e: &eggfetch_core::Error, request: &AcquisitionRequest) -> AcquisitionError {
445    use eggfetch_core::Error as E;
446    match e {
447        // Never embed upstream proxy/detail display: it may contain proxy
448        // URLs with credentials. Use category-only diagnostics.
449        E::InvalidProxyUrl(_) => {
450            AcquisitionError::Transport(bound("proxy configuration/routing failure".to_string()))
451        }
452        E::Timeout { phase, .. } => AcquisitionError::Timeout {
453            phase: match phase {
454                eggfetch_core::TimeoutPhase::Connect => "connect",
455                eggfetch_core::TimeoutPhase::Total => "total",
456                _ => "total",
457            },
458        },
459        _ => AcquisitionError::Transport(bound(format!(
460            "request build failed for {}: {}",
461            request.redacted(),
462            e.kind()
463        ))),
464    }
465}
466
467fn map_fetch_error(
468    e: &eggfetch_core::Error,
469    request: &AcquisitionRequest,
470    max: Option<usize>,
471) -> AcquisitionError {
472    use eggfetch_core::Error as E;
473    match e {
474        E::DecodedBodyTooLarge => AcquisitionError::TooLarge {
475            limit: max.unwrap_or(0) as u64,
476        },
477        E::Timeout { phase, .. } => AcquisitionError::Timeout {
478            phase: match phase {
479                eggfetch_core::TimeoutPhase::Connect => "connect",
480                eggfetch_core::TimeoutPhase::Total => "total",
481                _ => "total",
482            },
483        },
484        // TransportIoTimeout is an inactivity timeout on an established
485        // connection; classify as Timeout so caller deadlines stay truthful.
486        E::TransportIoTimeout { .. } => AcquisitionError::Timeout { phase: "total" },
487        // Never embed upstream error display or proxy detail: it may contain
488        // credential-bearing URLs. Use structured category text only.
489        E::InvalidProxyUrl(_) => {
490            AcquisitionError::Transport(bound("proxy configuration/routing failure".to_string()))
491        }
492        _ => AcquisitionError::Transport(bound(format!(
493            "fetch failed for {}: {}",
494            request.redacted(),
495            e.kind()
496        ))),
497    }
498}
499
500#[cfg(test)]
501mod tests {
502    use super::*;
503    use eggup_acquisition::{AcquisitionRequest, FixtureResponse, FixtureTransport};
504    use std::io::{Read, Write};
505    use std::net::TcpListener;
506    use std::sync::OnceLock;
507    use std::thread;
508
509    fn strict_transport() -> EggfetchTransport {
510        EggfetchTransport::strict(EggfetchConfig::strict()).expect("strict transport")
511    }
512
513    fn req(url: &str) -> AcquisitionRequest {
514        AcquisitionRequest::new(url).unwrap()
515    }
516
517    fn limits() -> FetchLimits {
518        FetchLimits {
519            max_metadata_bytes: 64 * 1024,
520            max_artifact_bytes: Some(256 * 1024),
521            connect_timeout: Duration::from_secs(2),
522            total_timeout: Duration::from_secs(10),
523        }
524    }
525
526    fn temp_dir(prefix: &str) -> std::path::PathBuf {
527        let nanos = std::time::SystemTime::now()
528            .duration_since(std::time::UNIX_EPOCH)
529            .map(|d| d.as_nanos())
530            .unwrap_or(0);
531        let p = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()));
532        let _ = fs::create_dir_all(&p);
533        p
534    }
535
536    /// Minimal single-response HTTP/1.1 server on 127.0.0.1.
537    fn serve_once(
538        status: u16,
539        headers: Vec<(String, String)>,
540        body: Vec<u8>,
541        split_body: bool,
542        stall_before_body_ms: u64,
543        abort_after_headers: bool,
544    ) -> String {
545        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
546        let addr = listener.local_addr().unwrap();
547        thread::spawn(move || {
548            if let Ok((mut stream, _)) = listener.accept() {
549                stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
550                stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
551                let mut buf = [0u8; 8192];
552                let _ = stream.read(&mut buf);
553                let reason = match status {
554                    200 => "OK",
555                    404 => "Not Found",
556                    500 => "Internal Server Error",
557                    302 => "Found",
558                    _ => "OK",
559                };
560                let mut head = format!("HTTP/1.1 {status} {reason}\r\n");
561                for (k, v) in headers {
562                    head.push_str(&format!("{k}: {v}\r\n"));
563                }
564                head.push_str("Connection: close\r\n\r\n");
565                let _ = stream.write_all(head.as_bytes());
566                if abort_after_headers {
567                    return;
568                }
569                if stall_before_body_ms > 0 {
570                    thread::sleep(Duration::from_millis(stall_before_body_ms));
571                }
572                if split_body {
573                    let mid = body.len() / 2;
574                    let _ = stream.write_all(&body[..mid]);
575                    thread::sleep(Duration::from_millis(20));
576                    let _ = stream.write_all(&body[mid..]);
577                } else {
578                    let _ = stream.write_all(&body);
579                }
580            }
581        });
582        format!("http://{addr}")
583    }
584
585    fn ok_server(body: Vec<u8>) -> String {
586        serve_once(
587            200,
588            vec![
589                ("Content-Length".into(), body.len().to_string()),
590                ("Content-Type".into(), "application/octet-stream".into()),
591            ],
592            body,
593            false,
594            0,
595            false,
596        )
597    }
598
599    #[test]
600    fn strict_config_uses_expected_policy() {
601        let t = strict_transport();
602        assert_eq!(t.config().max_redirects, DEFAULT_MAX_REDIRECTS);
603        assert_eq!(t.config().connect_timeout, DEFAULT_CONNECT_TIMEOUT);
604        assert_eq!(t.config().total_timeout, DEFAULT_TOTAL_TIMEOUT);
605        assert_eq!(
606            EggfetchTransport::eggfetch_version(),
607            "eggfetch-core 0.2.0 (http1,tls-rustls,tls-native-roots,proxy; no compression/cookies/retry/json)"
608        );
609    }
610
611    #[test]
612    fn downgrade_policy_denies_https_to_http() {
613        use eggfetch_core::RedirectDowngradePolicy;
614        let strict = RedirectPolicy::strict(10);
615        assert_eq!(strict.max_redirects, 10);
616        assert!(strict.follow);
617        let from: url::Url = "https://example.com/a".parse().unwrap();
618        let same: url::Url = "https://example.com/b".parse().unwrap();
619        let down: url::Url = "http://example.com/b".parse().unwrap();
620        assert!(strict.check_downgrade(&from, &same).is_ok());
621        assert!(strict.check_downgrade(&from, &down).is_err());
622        let _ = RedirectDowngradePolicy::Deny;
623    }
624
625    #[test]
626    fn metadata_200_is_success() {
627        let base = ok_server(b"hello-metadata".to_vec());
628        let t = strict_transport();
629        let out = t
630            .fetch_metadata(&req(&format!("{base}/meta")), limits(), &CancelFlag::new())
631            .unwrap();
632        assert_eq!(out.success().unwrap().bytes(), b"hello-metadata");
633    }
634
635    #[test]
636    fn invalid_public_limits_fail_before_eggfetch_io() {
637        let transport = strict_transport();
638        let request = req("http://127.0.0.1:1/never-contact");
639        let invalid = [
640            FetchLimits {
641                max_metadata_bytes: 0,
642                ..limits()
643            },
644            FetchLimits {
645                max_metadata_bytes: 16 * 1024 * 1024 + 1,
646                ..limits()
647            },
648            FetchLimits {
649                connect_timeout: Duration::ZERO,
650                ..limits()
651            },
652            FetchLimits {
653                total_timeout: Duration::ZERO,
654                ..limits()
655            },
656            FetchLimits {
657                connect_timeout: Duration::from_secs(11),
658                total_timeout: Duration::from_secs(10),
659                ..limits()
660            },
661        ];
662        let dir = temp_dir("eggfetch-invalid-limits");
663        let dest = dir.join("app");
664        for limits in invalid {
665            assert!(matches!(
666                transport.fetch_metadata(&request, limits, &CancelFlag::new()),
667                Err(AcquisitionError::InvalidInput(_))
668            ));
669            assert!(matches!(
670                transport.fetch_artifact(&request, &dest, limits, &CancelFlag::new()),
671                Err(AcquisitionError::InvalidInput(_))
672            ));
673            assert!(!dest.exists());
674            assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
675        }
676        assert!(limits().validate().is_ok());
677        let _ = fs::remove_dir_all(&dir);
678    }
679
680    #[test]
681    fn oversized_metadata_is_too_large() {
682        let big = vec![9u8; 128 * 1024];
683        let base = ok_server(big);
684        let t = strict_transport();
685        let err = t
686            .fetch_metadata(&req(&format!("{base}/big")), limits(), &CancelFlag::new())
687            .unwrap_err();
688        assert!(matches!(err, AcquisitionError::TooLarge { .. }));
689    }
690
691    #[test]
692    fn streaming_download_writes_exact_bytes() {
693        let body: Vec<u8> = (0..8192).map(|i| (i % 251) as u8).collect();
694        let base = ok_server(body.clone());
695        let t = strict_transport();
696        let dir = temp_dir("eggfetch-stream");
697        let dest = dir.join("app");
698        let out = t
699            .fetch_artifact(
700                &req(&format!("{base}/app")),
701                &dest,
702                limits(),
703                &CancelFlag::new(),
704            )
705            .unwrap();
706        assert_eq!(out.success().unwrap().bytes_written, 8192);
707        assert_eq!(fs::read(&dest).unwrap(), body);
708        let _ = fs::remove_dir_all(&dir);
709    }
710
711    #[test]
712    fn truncation_is_a_hard_failure_without_promotion() {
713        let body = vec![5u8; 4096];
714        let base = serve_once(
715            200,
716            vec![("Content-Length".into(), "4096".into())],
717            body,
718            false,
719            0,
720            true,
721        );
722        let t = strict_transport();
723        let dir = temp_dir("eggfetch-trunc");
724        let dest = dir.join("app");
725        let err = t
726            .fetch_artifact(
727                &req(&format!("{base}/app")),
728                &dest,
729                limits(),
730                &CancelFlag::new(),
731            )
732            .unwrap_err();
733        assert!(matches!(err, AcquisitionError::Transport(_)));
734        assert!(!dest.exists());
735        let _ = fs::remove_dir_all(&dir);
736    }
737
738    #[test]
739    fn not_found_is_typed_distinctly() {
740        let t = strict_transport();
741        let base = serve_once(404, vec![], b"nope".to_vec(), false, 0, false);
742        let out = t
743            .fetch_metadata(
744                &req(&format!("{base}/missing")),
745                limits(),
746                &CancelFlag::new(),
747            )
748            .unwrap();
749        assert!(out.is_not_found());
750        let base = serve_once(404, vec![], b"nope".to_vec(), false, 0, false);
751        let dir = temp_dir("eggfetch-404");
752        let dest = dir.join("app");
753        let out = t
754            .fetch_artifact(
755                &req(&format!("{base}/missing")),
756                &dest,
757                limits(),
758                &CancelFlag::new(),
759            )
760            .unwrap();
761        assert!(out.is_not_found());
762        assert!(!dest.exists());
763        let _ = fs::remove_dir_all(&dir);
764    }
765
766    #[test]
767    fn server_error_never_becomes_not_found() {
768        let base = serve_once(500, vec![], b"boom".to_vec(), false, 0, false);
769        let t = strict_transport();
770        let err = t
771            .fetch_metadata(&req(&format!("{base}/boom")), limits(), &CancelFlag::new())
772            .unwrap_err();
773        assert!(matches!(err, AcquisitionError::Transport(_)));
774    }
775
776    #[test]
777    fn redirect_limit_is_enforced() {
778        // Self-redirect loop; client follows up to the bound then hard-fails.
779        static ADDR: OnceLock<String> = OnceLock::new();
780        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
781        let addr = listener.local_addr().unwrap().to_string();
782        ADDR.set(format!("http://{addr}")).ok();
783        let target = format!("http://{addr}/loop");
784        thread::spawn(move || {
785            for mut s in listener.incoming().take(12).flatten() {
786                s.set_read_timeout(Some(Duration::from_secs(2))).ok();
787                s.set_write_timeout(Some(Duration::from_secs(2))).ok();
788                let mut buf = [0u8; 4096];
789                let _ = s.read(&mut buf);
790                let resp = format!(
791                    "HTTP/1.1 302 Found\r\nLocation: {target}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
792                );
793                let _ = s.write_all(resp.as_bytes());
794            }
795        });
796        let mut cfg = EggfetchConfig::strict();
797        cfg.max_redirects = 2;
798        let t = EggfetchTransport::strict(cfg).unwrap();
799        let err = t
800            .fetch_metadata(
801                &req(&format!("http://{addr}/loop")),
802                limits(),
803                &CancelFlag::new(),
804            )
805            .unwrap_err();
806        assert!(matches!(err, AcquisitionError::Transport(_)));
807    }
808
809    #[test]
810    fn total_timeout_is_a_hard_failure() {
811        let body = b"too-late".to_vec();
812        let base = serve_once(
813            200,
814            vec![("Content-Length".into(), body.len().to_string())],
815            body,
816            false,
817            3000,
818            false,
819        );
820        let mut cfg = EggfetchConfig::strict();
821        cfg.total_timeout = Duration::from_millis(300);
822        cfg.connect_timeout = Duration::from_millis(300);
823        let t = EggfetchTransport::strict(cfg).unwrap();
824        let err = t
825            .fetch_metadata(
826                &req(&format!("{base}/slow")),
827                FetchLimits {
828                    max_metadata_bytes: 64 * 1024,
829                    max_artifact_bytes: Some(256 * 1024),
830                    connect_timeout: Duration::from_millis(300),
831                    total_timeout: Duration::from_millis(300),
832                },
833                &CancelFlag::new(),
834            )
835            .unwrap_err();
836        assert!(matches!(
837            err,
838            AcquisitionError::Timeout { .. } | AcquisitionError::Transport(_)
839        ));
840    }
841
842    #[test]
843    fn invalid_proxy_fails_closed() {
844        let cfg = EggfetchConfig::strict().proxy(ProxyDecision::Custom(vec![(
845            "HTTPS_PROXY".into(),
846            "http://user:bogus@[::1".into(),
847        )]));
848        assert!(EggfetchTransport::strict(cfg).is_err());
849    }
850
851    #[test]
852    fn output_file_is_cleaned_on_failure() {
853        let base = serve_once(500, vec![], b"boom".to_vec(), false, 0, false);
854        let t = strict_transport();
855        let dir = temp_dir("eggfetch-cleanup");
856        let dest = dir.join("app");
857        let _ = t.fetch_artifact(
858            &req(&format!("{base}/boom")),
859            &dest,
860            limits(),
861            &CancelFlag::new(),
862        );
863        assert!(!dest.exists());
864        let leftovers: Vec<_> = fs::read_dir(&dir)
865            .unwrap()
866            .filter_map(|e| e.ok())
867            .filter(|e| {
868                e.file_name()
869                    .to_string_lossy()
870                    .starts_with(".eggup-eggfetch-")
871            })
872            .collect();
873        assert!(leftovers.is_empty());
874        let _ = fs::remove_dir_all(&dir);
875    }
876
877    #[test]
878    fn seam_fixture_and_adapter_agree_on_not_found() {
879        // Cross-check: both transports type 404 as NotFound, never fallback.
880        let fixture = FixtureTransport::new();
881        fixture.route("https://example.com/missing", FixtureResponse::not_found());
882        let out = fixture
883            .fetch_metadata(
884                &AcquisitionRequest::new("https://example.com/missing").unwrap(),
885                eggup_acquisition::FetchLimits::default(),
886                &eggup_acquisition::CancelFlag::new(),
887            )
888            .unwrap();
889        assert!(out.is_not_found());
890    }
891
892    // ---- M003 corrective: authoritative effective timeouts ----
893
894    fn request_limits(connect: Duration, total: Duration) -> FetchLimits {
895        FetchLimits {
896            max_metadata_bytes: 64 * 1024,
897            max_artifact_bytes: Some(256 * 1024),
898            connect_timeout: connect,
899            total_timeout: total,
900        }
901    }
902
903    #[test]
904    fn request_stricter_than_adapter_wins() {
905        // Adapter allows 5 s; request allows 50 ms. The request bound must win
906        // via a real Eggfetch per-request override, not a post-hoc check.
907        let body = b"too-late".to_vec();
908        let base = serve_once(
909            200,
910            vec![("Content-Length".into(), body.len().to_string())],
911            body,
912            false,
913            3000,
914            false,
915        );
916        let cfg = EggfetchConfig::strict().timeouts(Duration::from_secs(5), Duration::from_secs(5));
917        let t = EggfetchTransport::strict(cfg).unwrap();
918        let err = t
919            .fetch_metadata(
920                &req(&format!("{base}/slow")),
921                request_limits(Duration::from_millis(50), Duration::from_millis(50)),
922                &CancelFlag::new(),
923            )
924            .unwrap_err();
925        assert!(
926            matches!(err, AcquisitionError::Timeout { .. }),
927            "request-stricter must time out, got {err:?}"
928        );
929    }
930
931    #[test]
932    fn adapter_stricter_than_request_wins() {
933        // Request allows 5 s; adapter allows 50 ms. The adapter ceiling must
934        // win, proving min(request, adapter) enforcement in both directions.
935        let body = b"too-late".to_vec();
936        let base = serve_once(
937            200,
938            vec![("Content-Length".into(), body.len().to_string())],
939            body,
940            false,
941            3000,
942            false,
943        );
944        let cfg =
945            EggfetchConfig::strict().timeouts(Duration::from_millis(50), Duration::from_millis(50));
946        let t = EggfetchTransport::strict(cfg).unwrap();
947        let err = t
948            .fetch_metadata(
949                &req(&format!("{base}/slow")),
950                request_limits(Duration::from_secs(5), Duration::from_secs(5)),
951                &CancelFlag::new(),
952            )
953            .unwrap_err();
954        assert!(
955            matches!(err, AcquisitionError::Timeout { .. }),
956            "adapter-stricter must time out, got {err:?}"
957        );
958    }
959
960    #[test]
961    fn connect_exceeding_total_is_rejected_in_both_layers() {
962        // Seam layer.
963        assert!(FetchLimits::new(
964            1024,
965            Some(1024),
966            Duration::from_secs(5),
967            Duration::from_secs(1),
968        )
969        .is_err());
970        // Adapter layer fails closed at construction.
971        let cfg = EggfetchConfig::strict().timeouts(Duration::from_secs(5), Duration::from_secs(1));
972        assert!(EggfetchTransport::strict(cfg).is_err());
973        // Zero deadlines also fail closed.
974        let zero = EggfetchConfig::strict().timeouts(Duration::ZERO, Duration::from_secs(1));
975        assert!(EggfetchTransport::strict(zero).is_err());
976    }
977
978    #[test]
979    fn metadata_body_stall_times_out_without_fallback() {
980        let body = b"stalled-metadata".to_vec();
981        let base = serve_once(
982            200,
983            vec![("Content-Length".into(), body.len().to_string())],
984            body,
985            false,
986            2000,
987            false,
988        );
989        let t = strict_transport();
990        let err = t
991            .fetch_metadata(
992                &req(&format!("{base}/stall")),
993                request_limits(Duration::from_millis(300), Duration::from_millis(300)),
994                &CancelFlag::new(),
995            )
996            .unwrap_err();
997        assert!(matches!(err, AcquisitionError::Timeout { .. }));
998    }
999
1000    /// Server that sends headers + partial body, then stalls past the deadline.
1001    fn serve_partial_then_stall(partial: Vec<u8>, total_len: usize, stall_ms: u64) -> String {
1002        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
1003        let addr = listener.local_addr().unwrap();
1004        thread::spawn(move || {
1005            if let Ok((mut stream, _)) = listener.accept() {
1006                stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
1007                stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
1008                let mut buf = [0u8; 8192];
1009                let _ = stream.read(&mut buf);
1010                let head = format!(
1011                    "HTTP/1.1 200 OK\r\nContent-Length: {total_len}\r\nContent-Type: application/octet-stream\r\nConnection: close\r\n\r\n"
1012                );
1013                let _ = stream.write_all(head.as_bytes());
1014                let _ = stream.write_all(&partial);
1015                thread::sleep(Duration::from_millis(stall_ms));
1016                // Close without sending the remainder: client must time out,
1017                // not promote a partial artifact.
1018            }
1019        });
1020        format!("http://{addr}")
1021    }
1022
1023    #[test]
1024    fn artifact_body_stall_after_partial_data_times_out() {
1025        let partial = vec![7u8; 1024];
1026        let base = serve_partial_then_stall(partial, 8192, 3000);
1027        let t = strict_transport();
1028        let dir = temp_dir("eggfetch-artifact-stall");
1029        let dest = dir.join("app");
1030        let err = t
1031            .fetch_artifact(
1032                &req(&format!("{base}/app")),
1033                &dest,
1034                request_limits(Duration::from_millis(300), Duration::from_millis(300)),
1035                &CancelFlag::new(),
1036            )
1037            .unwrap_err();
1038        assert!(
1039            matches!(err, AcquisitionError::Timeout { .. }),
1040            "artifact stall must be Timeout, got {err:?}"
1041        );
1042        assert!(!dest.exists(), "partial artifact must not promote");
1043        let leftovers: Vec<_> = fs::read_dir(&dir)
1044            .unwrap()
1045            .filter_map(|e| e.ok())
1046            .filter(|e| e.file_name().to_string_lossy().ends_with(".part"))
1047            .collect();
1048        assert!(leftovers.is_empty());
1049        let _ = fs::remove_dir_all(&dir);
1050    }
1051
1052    #[test]
1053    fn timeout_never_becomes_not_found() {
1054        let body = b"late".to_vec();
1055        let base = serve_once(
1056            200,
1057            vec![("Content-Length".into(), body.len().to_string())],
1058            body,
1059            false,
1060            2000,
1061            false,
1062        );
1063        let t = strict_transport();
1064        let err = t
1065            .fetch_metadata(
1066                &req(&format!("{base}/x")),
1067                request_limits(Duration::from_millis(100), Duration::from_millis(100)),
1068                &CancelFlag::new(),
1069            )
1070            .unwrap_err();
1071        assert!(matches!(err, AcquisitionError::Timeout { .. }));
1072        assert!(!matches!(err, AcquisitionError::InvalidInput(_)));
1073    }
1074
1075    // ---- M003 corrective: exclusive temp + no-clobber ----
1076
1077    #[test]
1078    fn artifact_refuses_existing_destination_without_overwrite() {
1079        let body: Vec<u8> = (0..256).map(|i| i as u8).collect();
1080        let base = ok_server(body);
1081        let t = strict_transport();
1082        let dir = temp_dir("eggfetch-noclobber");
1083        let dest = dir.join("app");
1084        fs::write(&dest, b"FOREIGN-EGGFETCH").unwrap();
1085        let err = t
1086            .fetch_artifact(
1087                &req(&format!("{base}/app")),
1088                &dest,
1089                limits(),
1090                &CancelFlag::new(),
1091            )
1092            .unwrap_err();
1093        assert!(matches!(
1094            err,
1095            AcquisitionError::InvalidInput(_) | AcquisitionError::Io(_)
1096        ));
1097        assert_eq!(fs::read(&dest).unwrap(), b"FOREIGN-EGGFETCH");
1098        let leftovers: Vec<_> = fs::read_dir(&dir)
1099            .unwrap()
1100            .filter_map(|e| e.ok())
1101            .filter(|e| e.file_name().to_string_lossy().ends_with(".part"))
1102            .collect();
1103        assert!(leftovers.is_empty());
1104        let _ = fs::remove_dir_all(&dir);
1105    }
1106
1107    #[cfg(unix)]
1108    #[test]
1109    fn exclusive_temp_helper_is_owner_private_for_eggfetch_prefix() {
1110        use std::os::unix::fs::PermissionsExt;
1111        let dir = temp_dir("eggfetch-mode");
1112        let (f, tmp) = eggup_acquisition::__acquire_exclusive_temp(&dir, "eggup-eggfetch").unwrap();
1113        let mode = f.metadata().unwrap().permissions().mode() & 0o777;
1114        assert_eq!(mode, 0o600);
1115        drop(f);
1116        eggup_acquisition::__remove_owned_temp(&tmp);
1117        let _ = fs::remove_dir_all(&dir);
1118    }
1119
1120    // ---- M003 corrective: redaction ----
1121
1122    #[test]
1123    fn error_diagnostics_never_expose_credential_sentinels() {
1124        let userinfo = "S3CR3T-USERINFO-8841";
1125        let query = "TOKEN-QUERY-7734";
1126        let proxy_pw = "HUNTER2-PROXY-9902";
1127        // Request URL with sentinels: any error must embed only the redacted URL.
1128        let url = format!("https://alice:{userinfo}@127.0.0.1:9/app?token={query}");
1129        let t = strict_transport();
1130        // Unroutable port gives a fast transport failure without network wait.
1131        // Use a short deadline so the test stays fast even if it dials.
1132        let err = t
1133            .fetch_metadata(
1134                &req(&url),
1135                request_limits(Duration::from_millis(300), Duration::from_millis(300)),
1136                &CancelFlag::new(),
1137            )
1138            .unwrap_err();
1139        let msg = format!("{err}");
1140        let dbg = format!("{err:?}");
1141        assert!(!msg.contains(userinfo), "userinfo leaked: {msg}");
1142        assert!(!msg.contains(query), "query leaked: {msg}");
1143        assert!(!dbg.contains(userinfo));
1144        assert!(!dbg.contains(query));
1145        // Upstream error strings must map to category-only text.
1146        let fake = eggfetch_core::Error::InvalidProxyUrl(format!(
1147            "http://proxy:{proxy_pw}@example.com:8080"
1148        ));
1149        assert!(fake.to_string().contains(proxy_pw));
1150        // Our mapper must not echo that detail.
1151        let req2 = req("https://example.com/x");
1152        let mapped = super::map_fetch_error(&fake, &req2, None);
1153        let mapped_msg = format!("{mapped}");
1154        assert!(
1155            !mapped_msg.contains(proxy_pw),
1156            "proxy pw leaked: {mapped_msg}"
1157        );
1158        // Invalid proxy construction also stays generic.
1159        let bad_cfg = EggfetchConfig::strict().proxy(ProxyDecision::Custom(vec![(
1160            "HTTPS_PROXY".into(),
1161            format!("http://user:{proxy_pw}@example.com:8080"),
1162        )]));
1163        // Either construction fails closed with a generic message, or a later
1164        // fetch fails without echoing the password. Both are acceptable as
1165        // long as the password never appears.
1166        if let Err(e) = EggfetchTransport::strict(bad_cfg) {
1167            assert!(!format!("{e}").contains(proxy_pw));
1168        }
1169    }
1170
1171    #[test]
1172    fn effective_formula_is_minimum_per_phase() {
1173        let cfg =
1174            EggfetchConfig::strict().timeouts(Duration::from_secs(1), Duration::from_secs(10));
1175        let req_limits = request_limits(Duration::from_secs(5), Duration::from_secs(5));
1176        let (c, t) = cfg.effective_timeouts(req_limits);
1177        assert_eq!(c, Duration::from_secs(1));
1178        assert_eq!(t, Duration::from_secs(5));
1179    }
1180}