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