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
17pub const DEFAULT_USER_AGENT: &str = "eggup-eggfetch";
19pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
21pub const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(120);
23pub const DEFAULT_MAX_REDIRECTS: usize = 10;
25
26#[derive(Debug, Clone, Default)]
28pub enum ProxyDecision {
29 #[default]
31 Disabled,
32 FromEnvironment,
34 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#[derive(Debug, Clone)]
52pub struct EggfetchConfig {
53 pub user_agent: String,
55 pub connect_timeout: Duration,
57 pub total_timeout: Duration,
59 pub max_redirects: usize,
61 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 pub fn strict() -> Self {
80 Self::default()
81 }
82
83 pub fn user_agent(mut self, agent: impl Into<String>) -> Self {
85 self.user_agent = agent.into();
86 self
87 }
88
89 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 pub fn max_redirects(mut self, max: usize) -> Self {
104 self.max_redirects = max;
105 self
106 }
107
108 pub fn proxy(mut self, proxy: ProxyDecision) -> Self {
110 self.proxy = proxy;
111 self
112 }
113
114 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 .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 AcquisitionError::Transport(bound(
180 "proxy configuration/routing failure".to_string(),
181 ))
182 })
183 }
184}
185
186pub struct EggfetchTransport {
192 client: Client,
193 config: EggfetchConfig,
194}
195
196thread_local! {
197 static RUNTIME: std::cell::RefCell<Option<tokio::runtime::Runtime>> =
199 const { std::cell::RefCell::new(None) };
200}
201
202impl EggfetchTransport {
203 pub fn strict(config: EggfetchConfig) -> Result<Self, AcquisitionError> {
206 let client = config.build_client()?;
207 Ok(Self { client, config })
208 }
209
210 pub fn config(&self) -> &EggfetchConfig {
212 &self.config
213 }
214
215 pub fn eggfetch_version() -> &'static str {
217 "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 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 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 None => Err(AcquisitionError::__adapter_unavailable(
260 "eggfetch runtime unavailable",
261 )),
262 }
263 })
264 .unwrap_or_else(|_| {
265 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 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 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::__adapter_io("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 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 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::__adapter_io("writing part file", e))?;
434 }
435 file.flush()
436 .await
437 .map_err(|e| AcquisitionError::__adapter_io("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 {
467 eggup_acquisition::__adapter_bound_detail(s)
468}
469
470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
471enum StatusClass {
472 Success,
473 NotFound,
474 HardFailure,
475}
476
477fn classify(status: u16) -> StatusClass {
478 match status {
479 200..=299 => StatusClass::Success,
480 404 => StatusClass::NotFound,
481 _ => StatusClass::HardFailure,
482 }
483}
484
485fn map_request_error(e: &eggfetch_core::Error, request: &AcquisitionRequest) -> AcquisitionError {
486 use eggfetch_core::Error as E;
487 match e {
488 E::InvalidProxyUrl(_) => {
491 AcquisitionError::Transport(bound("proxy configuration/routing failure".to_string()))
492 }
493 E::Timeout { phase, .. } => AcquisitionError::Timeout {
494 phase: match phase {
495 eggfetch_core::TimeoutPhase::Connect => "connect",
496 eggfetch_core::TimeoutPhase::Total => "total",
497 _ => "total",
498 },
499 },
500 _ => AcquisitionError::Transport(bound(format!(
501 "request build failed for {}: {}",
502 request.redacted(),
503 e.kind()
504 ))),
505 }
506}
507
508fn map_fetch_error(
513 e: &eggfetch_core::Error,
514 request: &AcquisitionRequest,
515 byte_bound: u64,
516) -> AcquisitionError {
517 use eggfetch_core::Error as E;
518 match e {
519 E::DecodedBodyTooLarge => AcquisitionError::TooLarge { limit: byte_bound },
520 E::Timeout { phase, .. } => AcquisitionError::Timeout {
521 phase: match phase {
522 eggfetch_core::TimeoutPhase::Connect => "connect",
523 eggfetch_core::TimeoutPhase::Total => "total",
524 _ => "total",
525 },
526 },
527 E::TransportIoTimeout { .. } => AcquisitionError::Timeout { phase: "total" },
530 E::InvalidProxyUrl(_) => {
533 AcquisitionError::Transport(bound("proxy configuration/routing failure".to_string()))
534 }
535 _ => AcquisitionError::Transport(bound(format!(
536 "fetch failed for {}: {}",
537 request.redacted(),
538 e.kind()
539 ))),
540 }
541}
542
543#[cfg(test)]
544mod tests {
545 use super::*;
546
547 #[test]
548 fn diagnostic_bound_never_splits_multibyte_code_points() {
549 for (limit, ch) in [(512, "é"), (512, "€"), (512, "🦀")] {
550 let prefix = "x".repeat(limit - 1);
551 let bounded = bound(format!("{prefix}{ch}tail"));
552 assert_eq!(bounded, prefix);
553 assert!(bounded.len() <= limit);
554 }
555 }
556 use eggup_acquisition::{AcquisitionRequest, FixtureResponse, FixtureTransport};
557 use std::io::{Read, Write};
558 use std::net::TcpListener;
559 use std::sync::OnceLock;
560 use std::thread;
561
562 fn strict_transport() -> EggfetchTransport {
563 EggfetchTransport::strict(EggfetchConfig::strict()).expect("strict transport")
564 }
565
566 fn req(url: &str) -> AcquisitionRequest {
567 AcquisitionRequest::new(url).unwrap()
568 }
569
570 fn limits() -> FetchLimits {
571 FetchLimits {
572 max_metadata_bytes: 64 * 1024,
573 max_artifact_bytes: 256 * 1024,
574 connect_timeout: Duration::from_secs(2),
575 total_timeout: Duration::from_secs(10),
576 }
577 }
578
579 fn temp_dir(prefix: &str) -> std::path::PathBuf {
580 let nanos = std::time::SystemTime::now()
581 .duration_since(std::time::UNIX_EPOCH)
582 .map(|d| d.as_nanos())
583 .unwrap_or(0);
584 let p = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()));
585 let _ = fs::create_dir_all(&p);
586 p
587 }
588
589 fn serve_once(
591 status: u16,
592 headers: Vec<(String, String)>,
593 body: Vec<u8>,
594 split_body: bool,
595 stall_before_body_ms: u64,
596 abort_after_headers: bool,
597 ) -> String {
598 let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
599 let addr = listener.local_addr().unwrap();
600 thread::spawn(move || {
601 if let Ok((mut stream, _)) = listener.accept() {
602 stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
603 stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
604 let mut buf = [0u8; 8192];
605 let _ = stream.read(&mut buf);
606 let reason = match status {
607 200 => "OK",
608 404 => "Not Found",
609 500 => "Internal Server Error",
610 302 => "Found",
611 _ => "OK",
612 };
613 let mut head = format!("HTTP/1.1 {status} {reason}\r\n");
614 for (k, v) in headers {
615 head.push_str(&format!("{k}: {v}\r\n"));
616 }
617 head.push_str("Connection: close\r\n\r\n");
618 let _ = stream.write_all(head.as_bytes());
619 if abort_after_headers {
620 return;
621 }
622 if stall_before_body_ms > 0 {
623 thread::sleep(Duration::from_millis(stall_before_body_ms));
624 }
625 if split_body {
626 let mid = body.len() / 2;
627 let _ = stream.write_all(&body[..mid]);
628 thread::sleep(Duration::from_millis(20));
629 let _ = stream.write_all(&body[mid..]);
630 } else {
631 let _ = stream.write_all(&body);
632 }
633 }
634 });
635 format!("http://{addr}")
636 }
637
638 fn ok_server(body: Vec<u8>) -> String {
639 serve_once(
640 200,
641 vec![
642 ("Content-Length".into(), body.len().to_string()),
643 ("Content-Type".into(), "application/octet-stream".into()),
644 ],
645 body,
646 false,
647 0,
648 false,
649 )
650 }
651
652 #[test]
653 fn strict_config_uses_expected_policy() {
654 let t = strict_transport();
655 assert_eq!(t.config().max_redirects, DEFAULT_MAX_REDIRECTS);
656 assert_eq!(t.config().connect_timeout, DEFAULT_CONNECT_TIMEOUT);
657 assert_eq!(t.config().total_timeout, DEFAULT_TOTAL_TIMEOUT);
658 assert_eq!(
659 EggfetchTransport::eggfetch_version(),
660 "eggfetch-core 0.2.0 (http1,tls-rustls,tls-native-roots,proxy; no compression/cookies/retry/json)"
661 );
662 }
663
664 #[test]
665 fn downgrade_policy_denies_https_to_http() {
666 use eggfetch_core::RedirectDowngradePolicy;
667 let strict = RedirectPolicy::strict(10);
668 assert_eq!(strict.max_redirects, 10);
669 assert!(strict.follow);
670 let from: url::Url = "https://example.com/a".parse().unwrap();
671 let same: url::Url = "https://example.com/b".parse().unwrap();
672 let down: url::Url = "http://example.com/b".parse().unwrap();
673 assert!(strict.check_downgrade(&from, &same).is_ok());
674 assert!(strict.check_downgrade(&from, &down).is_err());
675 let _ = RedirectDowngradePolicy::Deny;
676 }
677
678 #[test]
679 fn metadata_200_is_success() {
680 let base = ok_server(b"hello-metadata".to_vec());
681 let t = strict_transport();
682 let out = t
683 .fetch_metadata(&req(&format!("{base}/meta")), limits(), &CancelFlag::new())
684 .unwrap();
685 assert_eq!(out.success().unwrap().bytes(), b"hello-metadata");
686 }
687
688 #[test]
689 fn invalid_public_limits_fail_before_eggfetch_io() {
690 let transport = strict_transport();
691 let request = req("http://127.0.0.1:1/never-contact");
692 let invalid = [
693 FetchLimits {
694 max_metadata_bytes: 0,
695 ..limits()
696 },
697 FetchLimits {
698 max_metadata_bytes: 16 * 1024 * 1024 + 1,
699 ..limits()
700 },
701 FetchLimits {
702 connect_timeout: Duration::ZERO,
703 ..limits()
704 },
705 FetchLimits {
706 total_timeout: Duration::ZERO,
707 ..limits()
708 },
709 FetchLimits {
710 connect_timeout: Duration::from_secs(11),
711 total_timeout: Duration::from_secs(10),
712 ..limits()
713 },
714 ];
715 let dir = temp_dir("eggfetch-invalid-limits");
716 let dest = dir.join("app");
717 for limits in invalid {
718 assert!(matches!(
719 transport.fetch_metadata(&request, limits, &CancelFlag::new()),
720 Err(AcquisitionError::InvalidInput(_))
721 ));
722 assert!(matches!(
723 transport.fetch_artifact(&request, &dest, limits, &CancelFlag::new()),
724 Err(AcquisitionError::InvalidInput(_))
725 ));
726 assert!(!dest.exists());
727 assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
728 }
729 assert!(limits().validate().is_ok());
730 let _ = fs::remove_dir_all(&dir);
731 }
732
733 #[test]
734 fn oversized_metadata_is_too_large() {
735 let big = vec![9u8; 128 * 1024];
736 let base = ok_server(big);
737 let t = strict_transport();
738 let err = t
739 .fetch_metadata(&req(&format!("{base}/big")), limits(), &CancelFlag::new())
740 .unwrap_err();
741 assert!(matches!(err, AcquisitionError::TooLarge { .. }));
742 }
743
744 #[test]
745 fn streaming_download_writes_exact_bytes() {
746 let body: Vec<u8> = (0..8192).map(|i| (i % 251) as u8).collect();
747 let base = ok_server(body.clone());
748 let t = strict_transport();
749 let dir = temp_dir("eggfetch-stream");
750 let dest = dir.join("app");
751 let out = t
752 .fetch_artifact(
753 &req(&format!("{base}/app")),
754 &dest,
755 limits(),
756 &CancelFlag::new(),
757 )
758 .unwrap();
759 assert_eq!(out.success().unwrap().bytes_written, 8192);
760 assert_eq!(fs::read(&dest).unwrap(), body);
761 let _ = fs::remove_dir_all(&dir);
762 }
763
764 #[test]
765 fn truncation_is_a_hard_failure_without_promotion() {
766 let body = vec![5u8; 4096];
767 let base = serve_once(
768 200,
769 vec![("Content-Length".into(), "4096".into())],
770 body,
771 false,
772 0,
773 true,
774 );
775 let t = strict_transport();
776 let dir = temp_dir("eggfetch-trunc");
777 let dest = dir.join("app");
778 let err = t
779 .fetch_artifact(
780 &req(&format!("{base}/app")),
781 &dest,
782 limits(),
783 &CancelFlag::new(),
784 )
785 .unwrap_err();
786 assert!(matches!(err, AcquisitionError::Transport(_)));
787 assert!(!dest.exists());
788 let _ = fs::remove_dir_all(&dir);
789 }
790
791 #[test]
792 fn not_found_is_typed_distinctly() {
793 let t = strict_transport();
794 let base = serve_once(404, vec![], b"nope".to_vec(), false, 0, false);
795 let out = t
796 .fetch_metadata(
797 &req(&format!("{base}/missing")),
798 limits(),
799 &CancelFlag::new(),
800 )
801 .unwrap();
802 assert!(out.is_not_found());
803 let base = serve_once(404, vec![], b"nope".to_vec(), false, 0, false);
804 let dir = temp_dir("eggfetch-404");
805 let dest = dir.join("app");
806 let out = t
807 .fetch_artifact(
808 &req(&format!("{base}/missing")),
809 &dest,
810 limits(),
811 &CancelFlag::new(),
812 )
813 .unwrap();
814 assert!(out.is_not_found());
815 assert!(!dest.exists());
816 let _ = fs::remove_dir_all(&dir);
817 }
818
819 #[test]
820 fn server_error_never_becomes_not_found() {
821 let base = serve_once(500, vec![], b"boom".to_vec(), false, 0, false);
822 let t = strict_transport();
823 let err = t
824 .fetch_metadata(&req(&format!("{base}/boom")), limits(), &CancelFlag::new())
825 .unwrap_err();
826 assert!(matches!(err, AcquisitionError::Transport(_)));
827 }
828
829 #[test]
830 fn redirect_limit_is_enforced() {
831 static ADDR: OnceLock<String> = OnceLock::new();
833 let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
834 let addr = listener.local_addr().unwrap().to_string();
835 ADDR.set(format!("http://{addr}")).ok();
836 let target = format!("http://{addr}/loop");
837 thread::spawn(move || {
838 for mut s in listener.incoming().take(12).flatten() {
839 s.set_read_timeout(Some(Duration::from_secs(2))).ok();
840 s.set_write_timeout(Some(Duration::from_secs(2))).ok();
841 let mut buf = [0u8; 4096];
842 let _ = s.read(&mut buf);
843 let resp = format!(
844 "HTTP/1.1 302 Found\r\nLocation: {target}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
845 );
846 let _ = s.write_all(resp.as_bytes());
847 }
848 });
849 let mut cfg = EggfetchConfig::strict();
850 cfg.max_redirects = 2;
851 let t = EggfetchTransport::strict(cfg).unwrap();
852 let err = t
853 .fetch_metadata(
854 &req(&format!("http://{addr}/loop")),
855 limits(),
856 &CancelFlag::new(),
857 )
858 .unwrap_err();
859 assert!(matches!(err, AcquisitionError::Transport(_)));
860 }
861
862 #[test]
863 fn total_timeout_is_a_hard_failure() {
864 let body = b"too-late".to_vec();
865 let base = serve_once(
866 200,
867 vec![("Content-Length".into(), body.len().to_string())],
868 body,
869 false,
870 3000,
871 false,
872 );
873 let mut cfg = EggfetchConfig::strict();
874 cfg.total_timeout = Duration::from_millis(300);
875 cfg.connect_timeout = Duration::from_millis(300);
876 let t = EggfetchTransport::strict(cfg).unwrap();
877 let err = t
878 .fetch_metadata(
879 &req(&format!("{base}/slow")),
880 FetchLimits {
881 max_metadata_bytes: 64 * 1024,
882 max_artifact_bytes: 256 * 1024,
883 connect_timeout: Duration::from_millis(300),
884 total_timeout: Duration::from_millis(300),
885 },
886 &CancelFlag::new(),
887 )
888 .unwrap_err();
889 assert!(matches!(
890 err,
891 AcquisitionError::Timeout { .. } | AcquisitionError::Transport(_)
892 ));
893 }
894
895 #[test]
896 fn invalid_proxy_fails_closed() {
897 let cfg = EggfetchConfig::strict().proxy(ProxyDecision::Custom(vec![(
898 "HTTPS_PROXY".into(),
899 "http://user:bogus@[::1".into(),
900 )]));
901 assert!(EggfetchTransport::strict(cfg).is_err());
902 }
903
904 #[test]
905 fn output_file_is_cleaned_on_failure() {
906 let base = serve_once(500, vec![], b"boom".to_vec(), false, 0, false);
907 let t = strict_transport();
908 let dir = temp_dir("eggfetch-cleanup");
909 let dest = dir.join("app");
910 let _ = t.fetch_artifact(
911 &req(&format!("{base}/boom")),
912 &dest,
913 limits(),
914 &CancelFlag::new(),
915 );
916 assert!(!dest.exists());
917 let leftovers: Vec<_> = fs::read_dir(&dir)
918 .unwrap()
919 .filter_map(|e| e.ok())
920 .filter(|e| {
921 e.file_name()
922 .to_string_lossy()
923 .starts_with(".eggup-eggfetch-")
924 })
925 .collect();
926 assert!(leftovers.is_empty());
927 let _ = fs::remove_dir_all(&dir);
928 }
929
930 #[test]
931 fn seam_fixture_and_adapter_agree_on_not_found() {
932 let fixture = FixtureTransport::new();
934 fixture.route("https://example.com/missing", FixtureResponse::not_found());
935 let out = fixture
936 .fetch_metadata(
937 &AcquisitionRequest::new("https://example.com/missing").unwrap(),
938 eggup_acquisition::FetchLimits::default(),
939 &eggup_acquisition::CancelFlag::new(),
940 )
941 .unwrap();
942 assert!(out.is_not_found());
943 }
944
945 fn request_limits(connect: Duration, total: Duration) -> FetchLimits {
948 FetchLimits {
949 max_metadata_bytes: 64 * 1024,
950 max_artifact_bytes: 256 * 1024,
951 connect_timeout: connect,
952 total_timeout: total,
953 }
954 }
955
956 #[test]
957 fn request_stricter_than_adapter_wins() {
958 let body = b"too-late".to_vec();
961 let base = serve_once(
962 200,
963 vec![("Content-Length".into(), body.len().to_string())],
964 body,
965 false,
966 3000,
967 false,
968 );
969 let cfg = EggfetchConfig::strict().timeouts(Duration::from_secs(5), Duration::from_secs(5));
970 let t = EggfetchTransport::strict(cfg).unwrap();
971 let err = t
972 .fetch_metadata(
973 &req(&format!("{base}/slow")),
974 request_limits(Duration::from_millis(50), Duration::from_millis(50)),
975 &CancelFlag::new(),
976 )
977 .unwrap_err();
978 assert!(
979 matches!(err, AcquisitionError::Timeout { .. }),
980 "request-stricter must time out, got {err:?}"
981 );
982 }
983
984 #[test]
985 fn adapter_stricter_than_request_wins() {
986 let body = b"too-late".to_vec();
989 let base = serve_once(
990 200,
991 vec![("Content-Length".into(), body.len().to_string())],
992 body,
993 false,
994 3000,
995 false,
996 );
997 let cfg =
998 EggfetchConfig::strict().timeouts(Duration::from_millis(50), Duration::from_millis(50));
999 let t = EggfetchTransport::strict(cfg).unwrap();
1000 let err = t
1001 .fetch_metadata(
1002 &req(&format!("{base}/slow")),
1003 request_limits(Duration::from_secs(5), Duration::from_secs(5)),
1004 &CancelFlag::new(),
1005 )
1006 .unwrap_err();
1007 assert!(
1008 matches!(err, AcquisitionError::Timeout { .. }),
1009 "adapter-stricter must time out, got {err:?}"
1010 );
1011 }
1012
1013 #[test]
1014 fn connect_exceeding_total_is_rejected_in_both_layers() {
1015 assert!(
1017 FetchLimits::new(1024, 1024, Duration::from_secs(5), Duration::from_secs(1),).is_err()
1018 );
1019 let cfg = EggfetchConfig::strict().timeouts(Duration::from_secs(5), Duration::from_secs(1));
1021 assert!(EggfetchTransport::strict(cfg).is_err());
1022 let zero = EggfetchConfig::strict().timeouts(Duration::ZERO, Duration::from_secs(1));
1024 assert!(EggfetchTransport::strict(zero).is_err());
1025 }
1026
1027 #[test]
1028 fn metadata_body_stall_times_out_without_fallback() {
1029 let body = b"stalled-metadata".to_vec();
1030 let base = serve_once(
1031 200,
1032 vec![("Content-Length".into(), body.len().to_string())],
1033 body,
1034 false,
1035 2000,
1036 false,
1037 );
1038 let t = strict_transport();
1039 let err = t
1040 .fetch_metadata(
1041 &req(&format!("{base}/stall")),
1042 request_limits(Duration::from_millis(300), Duration::from_millis(300)),
1043 &CancelFlag::new(),
1044 )
1045 .unwrap_err();
1046 assert!(matches!(err, AcquisitionError::Timeout { .. }));
1047 }
1048
1049 fn serve_partial_then_stall(partial: Vec<u8>, total_len: usize, stall_ms: u64) -> String {
1051 let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
1052 let addr = listener.local_addr().unwrap();
1053 thread::spawn(move || {
1054 if let Ok((mut stream, _)) = listener.accept() {
1055 stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
1056 stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
1057 let mut buf = [0u8; 8192];
1058 let _ = stream.read(&mut buf);
1059 let head = format!(
1060 "HTTP/1.1 200 OK\r\nContent-Length: {total_len}\r\nContent-Type: application/octet-stream\r\nConnection: close\r\n\r\n"
1061 );
1062 let _ = stream.write_all(head.as_bytes());
1063 let _ = stream.write_all(&partial);
1064 thread::sleep(Duration::from_millis(stall_ms));
1065 }
1068 });
1069 format!("http://{addr}")
1070 }
1071
1072 #[test]
1073 fn artifact_body_stall_after_partial_data_times_out() {
1074 let partial = vec![7u8; 1024];
1075 let base = serve_partial_then_stall(partial, 8192, 3000);
1076 let t = strict_transport();
1077 let dir = temp_dir("eggfetch-artifact-stall");
1078 let dest = dir.join("app");
1079 let err = t
1080 .fetch_artifact(
1081 &req(&format!("{base}/app")),
1082 &dest,
1083 request_limits(Duration::from_millis(300), Duration::from_millis(300)),
1084 &CancelFlag::new(),
1085 )
1086 .unwrap_err();
1087 assert!(
1088 matches!(err, AcquisitionError::Timeout { .. }),
1089 "artifact stall must be Timeout, got {err:?}"
1090 );
1091 assert!(!dest.exists(), "partial artifact must not promote");
1092 let leftovers: Vec<_> = fs::read_dir(&dir)
1093 .unwrap()
1094 .filter_map(|e| e.ok())
1095 .filter(|e| e.file_name().to_string_lossy().ends_with(".part"))
1096 .collect();
1097 assert!(leftovers.is_empty());
1098 let _ = fs::remove_dir_all(&dir);
1099 }
1100
1101 #[test]
1102 fn timeout_never_becomes_not_found() {
1103 let body = b"late".to_vec();
1104 let base = serve_once(
1105 200,
1106 vec![("Content-Length".into(), body.len().to_string())],
1107 body,
1108 false,
1109 2000,
1110 false,
1111 );
1112 let t = strict_transport();
1113 let err = t
1114 .fetch_metadata(
1115 &req(&format!("{base}/x")),
1116 request_limits(Duration::from_millis(100), Duration::from_millis(100)),
1117 &CancelFlag::new(),
1118 )
1119 .unwrap_err();
1120 assert!(matches!(err, AcquisitionError::Timeout { .. }));
1121 assert!(!matches!(err, AcquisitionError::InvalidInput(_)));
1122 }
1123
1124 #[test]
1127 fn artifact_refuses_existing_destination_without_overwrite() {
1128 let body: Vec<u8> = (0..256).map(|i| i as u8).collect();
1129 let base = ok_server(body);
1130 let t = strict_transport();
1131 let dir = temp_dir("eggfetch-noclobber");
1132 let dest = dir.join("app");
1133 fs::write(&dest, b"FOREIGN-EGGFETCH").unwrap();
1134 let err = t
1135 .fetch_artifact(
1136 &req(&format!("{base}/app")),
1137 &dest,
1138 limits(),
1139 &CancelFlag::new(),
1140 )
1141 .unwrap_err();
1142 assert!(matches!(
1143 err,
1144 AcquisitionError::InvalidInput(_) | AcquisitionError::Io { .. }
1145 ));
1146 assert_eq!(fs::read(&dest).unwrap(), b"FOREIGN-EGGFETCH");
1147 let leftovers: Vec<_> = fs::read_dir(&dir)
1148 .unwrap()
1149 .filter_map(|e| e.ok())
1150 .filter(|e| e.file_name().to_string_lossy().ends_with(".part"))
1151 .collect();
1152 assert!(leftovers.is_empty());
1153 let _ = fs::remove_dir_all(&dir);
1154 }
1155
1156 #[cfg(unix)]
1157 #[test]
1158 fn exclusive_temp_helper_is_owner_private_for_eggfetch_prefix() {
1159 use std::os::unix::fs::PermissionsExt;
1160 let dir = temp_dir("eggfetch-mode");
1161 let (f, tmp) = eggup_acquisition::__acquire_exclusive_temp(&dir, "eggup-eggfetch").unwrap();
1162 let mode = f.metadata().unwrap().permissions().mode() & 0o777;
1163 assert_eq!(mode, 0o600);
1164 drop(f);
1165 eggup_acquisition::__remove_owned_temp(&tmp);
1166 let _ = fs::remove_dir_all(&dir);
1167 }
1168
1169 #[test]
1172 fn error_diagnostics_never_expose_credential_sentinels() {
1173 let userinfo = "S3CR3T-USERINFO-8841";
1174 let query = "TOKEN-QUERY-7734";
1175 let proxy_pw = "HUNTER2-PROXY-9902";
1176 let url = format!("https://alice:{userinfo}@127.0.0.1:9/app?token={query}");
1178 let t = strict_transport();
1179 let err = t
1182 .fetch_metadata(
1183 &req(&url),
1184 request_limits(Duration::from_millis(300), Duration::from_millis(300)),
1185 &CancelFlag::new(),
1186 )
1187 .unwrap_err();
1188 let msg = format!("{err}");
1189 let dbg = format!("{err:?}");
1190 assert!(!msg.contains(userinfo), "userinfo leaked: {msg}");
1191 assert!(!msg.contains(query), "query leaked: {msg}");
1192 assert!(!dbg.contains(userinfo));
1193 assert!(!dbg.contains(query));
1194 let fake = eggfetch_core::Error::InvalidProxyUrl(format!(
1196 "http://proxy:{proxy_pw}@example.com:8080"
1197 ));
1198 assert!(fake.to_string().contains(proxy_pw));
1199 let req2 = req("https://example.com/x");
1201 let mapped = super::map_fetch_error(&fake, &req2, 1024);
1202 let mapped_msg = format!("{mapped}");
1203 assert!(
1204 !mapped_msg.contains(proxy_pw),
1205 "proxy pw leaked: {mapped_msg}"
1206 );
1207 let bad_cfg = EggfetchConfig::strict().proxy(ProxyDecision::Custom(vec![(
1209 "HTTPS_PROXY".into(),
1210 format!("http://user:{proxy_pw}@example.com:8080"),
1211 )]));
1212 if let Err(e) = EggfetchTransport::strict(bad_cfg) {
1216 assert!(!format!("{e}").contains(proxy_pw));
1217 }
1218 }
1219
1220 #[test]
1221 fn effective_formula_is_minimum_per_phase() {
1222 let cfg =
1223 EggfetchConfig::strict().timeouts(Duration::from_secs(1), Duration::from_secs(10));
1224 let req_limits = request_limits(Duration::from_secs(5), Duration::from_secs(5));
1225 let (c, t) = cfg.effective_timeouts(req_limits);
1226 assert_eq!(c, Duration::from_secs(1));
1227 assert_eq!(t, Duration::from_secs(5));
1228 }
1229}