1use crate::cache::BlobCacheBackend;
4use crate::error::{RegistryError, Result};
5use crate::image_config::{ImageConfig, OciImageConfigRoot};
6use crate::wasm::{detect_artifact_type, extract_wasm_info, ArtifactType, WasmArtifactInfo};
7use futures_util::stream::{StreamExt, TryStreamExt};
8use oci_client::{
9 client::{ClientConfig, ClientProtocol},
10 manifest::{ImageIndexEntry, OciImageIndex, OciImageManifest, OciManifest},
11 secrets::RegistryAuth,
12 Reference, RegistryOperation,
13};
14use std::sync::Arc;
15use thiserror::Error;
16use tokio::sync::Semaphore;
17use tracing::instrument;
18
19const LAYER_PULL_CONCURRENCY: usize = 8;
23use zlayer_spec::PullPolicy;
24
25const S3_TIER_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
40
41type WarmSlot = tokio::sync::OnceCell<std::result::Result<(OciImageManifest, String), String>>;
53
54type ConfigSlot = tokio::sync::OnceCell<std::result::Result<ImageConfig, String>>;
60
61static PULL_SINGLEFLIGHT: std::sync::OnceLock<
74 tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<WarmSlot>>>,
75> = std::sync::OnceLock::new();
76
77fn pull_singleflight(
78) -> &'static tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<WarmSlot>>> {
79 PULL_SINGLEFLIGHT.get_or_init(|| tokio::sync::Mutex::new(std::collections::HashMap::new()))
80}
81
82static CONFIG_SINGLEFLIGHT: std::sync::OnceLock<
89 tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<ConfigSlot>>>,
90> = std::sync::OnceLock::new();
91
92fn config_singleflight(
93) -> &'static tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<ConfigSlot>>> {
94 CONFIG_SINGLEFLIGHT.get_or_init(|| tokio::sync::Mutex::new(std::collections::HashMap::new()))
95}
96
97#[cfg(feature = "local")]
98use crate::wasm_export::WasmExportResult;
99
100#[must_use]
118fn canonical_manifest_ref(image: &str) -> String {
119 use std::str::FromStr;
120 match oci_client::Reference::from_str(image) {
121 Ok(reference) => reference.whole(),
122 Err(_) => image.to_string(),
123 }
124}
125
126#[must_use]
140pub fn manifest_cache_key(image: &str) -> String {
141 format!("manifest:{}", canonical_manifest_ref(image))
142}
143
144#[must_use]
153pub fn manifest_digest_cache_key(image: &str) -> String {
154 format!("manifest:digest-{}", canonical_manifest_ref(image))
155}
156
157#[must_use]
166pub fn manifest_orig_cache_key(image: &str) -> String {
167 format!("manifest-orig:{}", canonical_manifest_ref(image))
168}
169
170#[derive(Debug, Error)]
172pub enum PushError {
173 #[error("authentication failed for registry {registry}: {reason}")]
175 AuthenticationFailed {
176 registry: String,
178 reason: String,
180 },
181
182 #[error("failed to upload blob {digest}: {reason}")]
184 BlobUploadFailed {
185 digest: String,
187 reason: String,
189 },
190
191 #[error("failed to upload manifest: {reason}")]
193 ManifestUploadFailed {
194 reason: String,
196 },
197
198 #[error("network error: {0}")]
200 NetworkError(String),
201
202 #[error("invalid image reference: {reference}")]
204 InvalidReference {
205 reference: String,
207 },
208
209 #[error("OCI distribution error: {0}")]
211 OciError(#[from] oci_client::errors::OciDistributionError),
212}
213
214#[derive(Debug, Clone)]
216pub struct PushResult {
217 pub manifest_digest: String,
219 pub blobs_pushed: Vec<String>,
221 pub reference: String,
223}
224
225#[cfg(feature = "local")]
229#[derive(Debug, Clone)]
230pub struct ArtifactLayer {
231 pub data: Vec<u8>,
233 pub media_type: String,
236 pub title: Option<String>,
239}
240
241#[cfg(feature = "local")]
244#[must_use]
245pub fn oci_sha256_digest(bytes: &[u8]) -> String {
246 use sha2::{Digest, Sha256};
247 let mut hasher = Sha256::new();
248 hasher.update(bytes);
249 format!("sha256:{}", hex::encode(hasher.finalize()))
250}
251
252pub(crate) fn go_arch_name() -> &'static str {
254 match std::env::consts::ARCH {
255 "x86_64" => "amd64",
256 "x86" => "amd",
257 "aarch64" => "arm64",
258 "powerpc64" => "ppc64le",
259 other => other,
260 }
261}
262
263pub(crate) fn go_os_name() -> &'static str {
265 match std::env::consts::OS {
266 "macos" => "darwin",
267 other => other,
268 }
269}
270
271fn is_mutable_tag(image: &str) -> bool {
278 let (without_digest, had_digest) = match image.find('@') {
281 Some(idx) => (&image[..idx], true),
282 None => (image, false),
283 };
284 if had_digest {
285 return false;
286 }
287
288 let tag = match without_digest.rfind(':') {
291 Some(idx) => {
292 let candidate = &without_digest[idx + 1..];
293 if candidate.contains('/') {
294 None
296 } else {
297 Some(candidate)
298 }
299 }
300 None => None,
301 };
302
303 match tag {
304 None | Some("") => true,
307 Some(t) => matches!(t, "latest" | "dev" | "edge" | "main" | "master"),
308 }
309}
310
311#[cfg(feature = "local")]
329fn local_image_ref_candidates(image: &str) -> Vec<(String, String)> {
330 zlayer_types::image_ref_candidates(image)
334}
335
336#[cfg(all(test, feature = "local"))]
337mod local_image_ref_candidates_tests {
338 use super::local_image_ref_candidates;
339
340 fn contains(candidates: &[(String, String)], name: &str, reference: &str) -> bool {
341 candidates.iter().any(|(n, r)| n == name && r == reference)
342 }
343
344 #[test]
345 fn bare_name_with_tag_produces_library_and_self() {
346 let c = local_image_ref_candidates("zarcrunner-executor:latest");
347 assert!(
348 contains(&c, "zarcrunner-executor", "latest"),
349 "missing bare candidate in {c:?}",
350 );
351 assert!(
352 contains(&c, "library/zarcrunner-executor", "latest"),
353 "missing library/ candidate in {c:?}",
354 );
355 }
356
357 #[test]
358 fn fully_qualified_docker_hub_strips_prefixes() {
359 let c = local_image_ref_candidates("docker.io/library/zarcrunner-executor:latest");
360 assert!(
361 contains(&c, "docker.io/library/zarcrunner-executor", "latest"),
362 "missing primary in {c:?}",
363 );
364 assert!(
365 contains(&c, "library/zarcrunner-executor", "latest"),
366 "missing docker.io-stripped form in {c:?}",
367 );
368 assert!(
369 contains(&c, "zarcrunner-executor", "latest"),
370 "missing docker.io/library-stripped form in {c:?}",
371 );
372 }
373
374 #[test]
375 fn ghcr_keeps_qualified_and_bare_segment_but_no_library_prefix() {
376 let c = local_image_ref_candidates("ghcr.io/team/svc:1.2");
377 assert!(
378 contains(&c, "ghcr.io/team/svc", "1.2"),
379 "missing primary in {c:?}",
380 );
381 assert!(
382 contains(&c, "svc", "1.2"),
383 "missing bare last-segment fallback in {c:?}",
384 );
385 assert!(
388 !c.iter().any(|(n, _)| n.starts_with("library/")),
389 "unexpected library/ prefix in {c:?}",
390 );
391 }
392
393 #[test]
394 fn digest_reference_is_preserved() {
395 let digest = "sha256:0000000000000000000000000000000000000000000000000000000000000000";
396 let input = format!("foo@{digest}");
397 let c = local_image_ref_candidates(&input);
398 assert!(
399 contains(&c, "foo", digest),
400 "missing foo@digest candidate in {c:?}",
401 );
402 assert!(
403 contains(&c, "library/foo", digest),
404 "missing library/foo@digest candidate in {c:?}",
405 );
406 for (_, r) in &c {
408 assert_eq!(r, digest, "non-digest reference leaked into {c:?}");
409 }
410 }
411
412 #[test]
413 fn deterministic_input_has_no_duplicates() {
414 for input in [
415 "zarcrunner-executor:latest",
416 "docker.io/library/zarcrunner-executor:latest",
417 "ghcr.io/team/svc:1.2",
418 "foo",
419 "library/foo:1.0",
420 "foo@sha256:0000000000000000000000000000000000000000000000000000000000000000",
421 ] {
422 let c = local_image_ref_candidates(input);
423 let mut sorted: Vec<_> = c.clone();
424 sorted.sort();
425 let original_len = sorted.len();
426 sorted.dedup();
427 assert_eq!(
428 original_len,
429 sorted.len(),
430 "duplicate candidates produced for {input}: {c:?}",
431 );
432 }
433 }
434}
435
436fn build_platform_resolver(
449 target: Option<zlayer_spec::TargetPlatform>,
450) -> impl Fn(&[ImageIndexEntry]) -> Option<String> + Send + Sync + 'static {
451 let has_target = target.is_some();
463 let (target_os, target_arch, target_os_version): (String, String, Option<String>) = match target
464 {
465 Some(tp) => (
466 tp.os.as_oci_str().to_string(),
467 tp.arch.as_oci_str().to_string(),
468 tp.os_version,
469 ),
470 None => (go_os_name().to_string(), go_arch_name().to_string(), None),
471 };
472 let use_macos_fallback = !has_target && cfg!(target_os = "macos");
473
474 move |manifests: &[ImageIndexEntry]| -> Option<String> {
475 if target_os == "windows" {
478 if let Some(want_version) = target_os_version.as_deref() {
479 if let Some(entry) = manifests.iter().find(|entry| {
480 entry.platform.as_ref().is_some_and(|p| {
481 p.os == target_os
482 && p.architecture == target_arch
483 && p.os_version
484 .as_deref()
485 .is_some_and(|v| v == want_version || v.starts_with(want_version))
486 })
487 }) {
488 return Some(entry.digest.clone());
489 }
490 }
491 }
492
493 if let Some(entry) = manifests.iter().find(|entry| {
496 entry
497 .platform
498 .as_ref()
499 .is_some_and(|p| p.os == target_os && p.architecture == target_arch)
500 }) {
501 return Some(entry.digest.clone());
502 }
503
504 if use_macos_fallback {
507 return manifests
508 .iter()
509 .find(|entry| {
510 entry
511 .platform
512 .as_ref()
513 .is_some_and(|p| p.os == "linux" && p.architecture == target_arch)
514 })
515 .map(|entry| entry.digest.clone());
516 }
517
518 None
519 }
520}
521
522fn parse_image_manifest_only(data: &[u8]) -> Option<OciImageManifest> {
534 match serde_json::from_slice::<OciManifest>(data).ok()? {
535 OciManifest::Image(manifest) => Some(manifest),
536 OciManifest::ImageIndex(_) => None,
537 }
538}
539
540fn build_client_config(target: Option<zlayer_spec::TargetPlatform>) -> ClientConfig {
547 ClientConfig {
548 protocol: ClientProtocol::Https,
549 connect_timeout: Some(std::time::Duration::from_secs(30)),
550 read_timeout: Some(std::time::Duration::from_secs(300)), platform_resolver: Some(Box::new(build_platform_resolver(target))),
552 ..Default::default()
553 }
554}
555
556pub struct ImagePuller {
558 client: oci_client::Client,
559 cache: Arc<Box<dyn BlobCacheBackend>>,
560 concurrency_limit: Arc<Semaphore>,
561 network_calls: Arc<std::sync::atomic::AtomicUsize>,
570 s3_cache: Option<Arc<Box<dyn BlobCacheBackend>>>,
575 default_registry: Option<String>,
579 source_policy: zlayer_spec::SourcePolicy,
583 #[cfg(feature = "local")]
593 target: Option<zlayer_spec::TargetPlatform>,
594 #[cfg(feature = "local")]
595 local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
596}
597
598impl ImagePuller {
599 pub fn new<C: BlobCacheBackend + 'static>(cache: C) -> Self {
605 let client = oci_client::Client::new(build_client_config(None));
606
607 Self {
608 client,
609 cache: Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>),
610 concurrency_limit: Arc::new(Semaphore::new(3)),
611 network_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
612 s3_cache: None,
613 default_registry: None,
614 source_policy: zlayer_spec::SourcePolicy::LocalFirst,
615 #[cfg(feature = "local")]
616 target: None,
617 #[cfg(feature = "local")]
618 local_registry: None,
619 }
620 }
621
622 #[must_use]
628 pub fn with_cache(cache: Arc<Box<dyn BlobCacheBackend>>) -> Self {
629 let client = oci_client::Client::new(build_client_config(None));
630
631 Self {
632 client,
633 cache,
634 concurrency_limit: Arc::new(Semaphore::new(3)),
635 network_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
636 s3_cache: None,
637 default_registry: None,
638 source_policy: zlayer_spec::SourcePolicy::LocalFirst,
639 #[cfg(feature = "local")]
640 target: None,
641 #[cfg(feature = "local")]
642 local_registry: None,
643 }
644 }
645
646 #[must_use]
653 pub fn with_platform(
654 cache: Arc<Box<dyn BlobCacheBackend>>,
655 target: zlayer_spec::TargetPlatform,
656 ) -> Self {
657 #[cfg(feature = "local")]
661 let client = oci_client::Client::new(build_client_config(Some(target.clone())));
662 #[cfg(not(feature = "local"))]
663 let client = oci_client::Client::new(build_client_config(Some(target)));
664
665 Self {
666 client,
667 cache,
668 concurrency_limit: Arc::new(Semaphore::new(3)),
669 network_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
670 s3_cache: None,
671 default_registry: None,
672 source_policy: zlayer_spec::SourcePolicy::LocalFirst,
673 #[cfg(feature = "local")]
674 target: Some(target),
675 #[cfg(feature = "local")]
676 local_registry: None,
677 }
678 }
679
680 fn note_network_call(&self) {
685 self.network_calls
686 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
687 }
688
689 #[cfg(test)]
693 fn network_call_count(&self) -> usize {
694 self.network_calls
695 .load(std::sync::atomic::Ordering::Relaxed)
696 }
697
698 async fn store_auth(&self, image: &str, auth: &RegistryAuth) -> Result<()> {
702 let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
703 registry: "unknown".to_string(),
704 image: image.to_string(),
705 })?;
706
707 self.client
711 .store_auth_if_needed(reference.resolve_registry(), auth)
712 .await;
713
714 Ok(())
715 }
716
717 #[must_use]
719 pub fn with_concurrency_limit(mut self, limit: usize) -> Self {
720 self.concurrency_limit = Arc::new(Semaphore::new(limit));
721 self
722 }
723
724 #[must_use]
729 pub fn with_s3_cache(mut self, s3: Arc<Box<dyn BlobCacheBackend>>) -> Self {
730 self.s3_cache = Some(s3);
731 self
732 }
733
734 async fn s3_tier_get(&self, key: &str) -> Option<Vec<u8>> {
748 let s3 = self.s3_cache.as_ref()?;
749 match tokio::time::timeout(S3_TIER_READ_TIMEOUT, s3.get(key)).await {
750 Ok(Ok(data)) => data,
751 Ok(Err(e)) => {
752 tracing::debug!(key = %key, error = %e, "S3 tier read failed; treating as cache miss");
753 None
754 }
755 Err(_elapsed) => {
756 tracing::warn!(
757 key = %key,
758 timeout_secs = S3_TIER_READ_TIMEOUT.as_secs(),
759 "S3 tier read timed out (endpoint unreachable?); treating as cache miss and \
760 falling through to origin/local"
761 );
762 None
763 }
764 }
765 }
766
767 #[must_use]
771 pub fn with_default_registry(mut self, registry: impl Into<String>) -> Self {
772 let host = registry.into();
773 self.default_registry = if host.trim().is_empty() {
774 None
775 } else {
776 Some(host)
777 };
778 self
779 }
780
781 #[must_use]
783 pub fn with_source_policy(mut self, source: zlayer_spec::SourcePolicy) -> Self {
784 self.source_policy = source;
785 self
786 }
787
788 pub async fn from_env_for_runtime(
796 cache: Arc<Box<dyn BlobCacheBackend>>,
797 source: zlayer_spec::SourcePolicy,
798 ) -> Self {
799 let mut puller = Self::with_cache(cache).with_source_policy(source);
800 match crate::cache_config::s3_cache_from_env().await {
801 Ok(Some(s3)) => puller = puller.with_s3_cache(s3),
802 Ok(None) => {}
803 Err(e) => {
804 tracing::warn!(error = %e, "S3 cache tier configured but failed to initialize; continuing without it");
805 }
806 }
807 if let Some(default_registry) = crate::cache_config::default_registry_from_env() {
808 puller = puller.with_default_registry(default_registry);
809 }
810 puller
811 }
812
813 #[cfg(feature = "local")]
815 #[must_use]
816 pub fn with_local_registry(
817 mut self,
818 registry: std::sync::Arc<crate::local_registry::LocalRegistry>,
819 ) -> Self {
820 self.local_registry = Some(registry);
821 self
822 }
823
824 pub async fn pull_blob(
836 &self,
837 image: &str,
838 digest: &str,
839 auth: &RegistryAuth,
840 ) -> Result<Vec<u8>> {
841 self.pull_blob_with_urls(image, digest, auth, &[], None)
842 .await
843 }
844
845 pub async fn pull_blob_with_urls(
868 &self,
869 image: &str,
870 digest: &str,
871 auth: &RegistryAuth,
872 urls: &[String],
873 expected_size: Option<i64>,
874 ) -> Result<Vec<u8>> {
875 if let Some(data) = self.cache.get(digest).await? {
877 tracing::debug!(digest = %digest, "blob found in cache");
878 return Ok(data);
879 }
880
881 if let Some(data) = self.s3_tier_get(digest).await {
886 tracing::debug!(digest = %digest, "blob found in S3 tier; warming local cache");
887 let _ = self.cache.put(digest, &data).await;
888 return Ok(data);
889 }
890
891 #[cfg(feature = "local")]
898 if let Some(registry) = &self.local_registry {
899 if let Ok(data) = registry.get_blob(digest).await {
900 if !data.is_empty() {
901 tracing::debug!(
902 digest = %digest,
903 "blob found in local registry; warming local cache"
904 );
905 let _ = self.cache.put(digest, &data).await;
906 return Ok(data);
907 }
908 }
909 }
910
911 self.store_auth(image, auth).await?;
913
914 let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
915 registry: "unknown".to_string(),
916 image: image.to_string(),
917 })?;
918
919 let _permit = self.concurrency_limit.acquire().await.unwrap();
920
921 tracing::debug!(digest = %digest, image = %image, "pulling blob from registry");
922
923 let mut buffer = Vec::new();
928 let primary_result = self.client.pull_blob(&reference, digest, &mut buffer).await;
929
930 let buffer = match primary_result {
931 Ok(()) => buffer,
932 Err(err) if is_blob_not_found(&err) && !urls.is_empty() => {
933 tracing::info!(
934 digest = %digest,
935 urls_count = urls.len(),
936 "primary registry missed foreign layer; attempting urls[] redirects"
937 );
938 let mut last_err: Option<RegistryError> = None;
939 let mut recovered: Option<Vec<u8>> = None;
940 for url in urls.iter().take(MAX_FOREIGN_LAYER_REDIRECTS) {
941 match fetch_blob_from_url(url, digest, expected_size).await {
942 Ok(bytes) => {
943 tracing::info!(url = %url, "foreign layer recovered via redirect");
944 recovered = Some(bytes);
945 break;
946 }
947 Err(e) => {
948 tracing::warn!(url = %url, error = %e, "redirect attempt failed");
949 last_err = Some(e);
950 }
951 }
952 }
953 if let Some(bytes) = recovered {
954 bytes
955 } else {
956 tracing::error!(
957 digest = %digest,
958 image = %image,
959 "foreign layer redirect fallback exhausted"
960 );
961 return Err(last_err.unwrap_or(RegistryError::Oci(err)));
962 }
963 }
964 Err(err) => {
965 tracing::error!(error = %err, digest = %digest, image = %image, "failed to pull blob from registry");
966 return Err(RegistryError::Oci(err));
967 }
968 };
969
970 if buffer.is_empty() {
972 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
973 format!("blob {digest} was empty after pulling from registry"),
974 )));
975 }
976
977 self.cache.put(digest, &buffer).await?;
979
980 if let Some(s3) = &self.s3_cache {
984 if let Err(e) = s3.put(digest, &buffer).await {
985 tracing::debug!(digest = %digest, error = %e, "failed to propagate blob to S3 tier");
986 }
987 }
988
989 tracing::debug!(digest = %digest, size = buffer.len(), "blob cached successfully");
990
991 Ok(buffer)
992 }
993
994 #[allow(clippy::too_many_lines)]
1015 pub async fn pull_blob_to_file(
1016 &self,
1017 image: &str,
1018 digest: &str,
1019 auth: &RegistryAuth,
1020 urls: &[String],
1021 expected_size: Option<i64>,
1022 staging_dir: &std::path::Path,
1023 ) -> Result<std::path::PathBuf> {
1024 tokio::fs::create_dir_all(staging_dir)
1025 .await
1026 .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1027 let dest = staging_dir.join(blob_staging_filename(digest));
1028
1029 if let Some(path) = self.cache.get_path(digest).await? {
1031 tracing::debug!(digest = %digest, "blob found in cache (file-backed); linking into stage");
1032 link_or_copy(&path, &dest).await?;
1033 return Ok(dest);
1034 }
1035
1036 if let Some(data) = self.cache.get(digest).await? {
1038 tracing::debug!(digest = %digest, "blob found in cache (inline); writing into stage");
1039 tokio::fs::write(&dest, &data)
1040 .await
1041 .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1042 return Ok(dest);
1043 }
1044
1045 if let Some(data) = self.s3_tier_get(digest).await {
1049 tracing::debug!(digest = %digest, "blob found in S3 tier; staging + warming local cache");
1050 tokio::fs::write(&dest, &data)
1051 .await
1052 .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1053 let _ = self.cache.put_path(digest, &dest).await;
1054 return Ok(dest);
1055 }
1056
1057 #[cfg(feature = "local")]
1059 if let Some(registry) = &self.local_registry {
1060 if let Ok(data) = registry.get_blob(digest).await {
1061 if !data.is_empty() {
1062 tracing::debug!(digest = %digest, "blob found in local registry; staging + warming local cache");
1063 tokio::fs::write(&dest, &data)
1064 .await
1065 .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1066 let _ = self.cache.put_path(digest, &dest).await;
1067 return Ok(dest);
1068 }
1069 }
1070 }
1071
1072 self.store_auth(image, auth).await?;
1074 let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
1075 registry: "unknown".to_string(),
1076 image: image.to_string(),
1077 })?;
1078 let _permit = self.concurrency_limit.acquire().await.unwrap();
1079 tracing::debug!(digest = %digest, image = %image, "streaming blob from registry to file");
1080
1081 let seq = BLOB_PART_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1082 let tmp = staging_dir.join(format!(
1083 "{}.part.{}.{}",
1084 blob_staging_filename(digest),
1085 std::process::id(),
1086 seq
1087 ));
1088
1089 let make_writer = || async {
1090 let file = tokio::fs::File::create(&tmp)
1091 .await
1092 .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1093 Ok::<_, RegistryError>(HashingFileWriter::new(file))
1094 };
1095
1096 let mut writer = make_writer().await?;
1097 let primary = self.client.pull_blob(&reference, digest, &mut writer).await;
1098
1099 let final_writer = match primary {
1100 Ok(()) => writer,
1101 Err(err) if is_blob_not_found(&err) && !urls.is_empty() => {
1102 tracing::info!(
1103 digest = %digest,
1104 urls_count = urls.len(),
1105 "primary registry missed foreign layer; streaming urls[] redirects"
1106 );
1107 drop(writer);
1109 let mut recovered: Option<HashingFileWriter> = None;
1110 let mut last_err: Option<RegistryError> = None;
1111 for url in urls.iter().take(MAX_FOREIGN_LAYER_REDIRECTS) {
1112 let mut w = make_writer().await?;
1113 match fetch_blob_from_url_to_writer(url, expected_size, &mut w).await {
1114 Ok(()) => {
1115 tracing::info!(url = %url, "foreign layer recovered via redirect");
1116 recovered = Some(w);
1117 break;
1118 }
1119 Err(e) => {
1120 tracing::warn!(url = %url, error = %e, "redirect attempt failed");
1121 last_err = Some(e);
1122 }
1123 }
1124 }
1125 if let Some(w) = recovered {
1126 w
1127 } else {
1128 let _ = tokio::fs::remove_file(&tmp).await;
1129 tracing::error!(digest = %digest, image = %image, "foreign layer redirect fallback exhausted");
1130 return Err(last_err.unwrap_or(RegistryError::Oci(err)));
1131 }
1132 }
1133 Err(err) => {
1134 let _ = tokio::fs::remove_file(&tmp).await;
1135 tracing::error!(error = %err, digest = %digest, image = %image, "failed to stream blob from registry");
1136 return Err(RegistryError::Oci(err));
1137 }
1138 };
1139
1140 let (actual_digest, written) = final_writer.finalize().await?;
1142 if written == 0 {
1143 let _ = tokio::fs::remove_file(&tmp).await;
1144 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
1145 format!("blob {digest} was empty after pulling from registry"),
1146 )));
1147 }
1148 if !actual_digest.eq_ignore_ascii_case(digest) {
1149 let _ = tokio::fs::remove_file(&tmp).await;
1150 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
1151 format!("digest mismatch: expected {digest}, got {actual_digest}"),
1152 )));
1153 }
1154 if let Some(expected) = expected_size {
1155 if let Ok(expected_u) = u64::try_from(expected) {
1156 if written != expected_u {
1157 let _ = tokio::fs::remove_file(&tmp).await;
1158 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
1159 format!(
1160 "blob {digest}: size mismatch (expected {expected}, got {written})"
1161 ),
1162 )));
1163 }
1164 }
1165 }
1166
1167 tokio::fs::rename(&tmp, &dest)
1168 .await
1169 .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1170
1171 if let Err(e) = self.cache.put_path(digest, &dest).await {
1173 tracing::debug!(digest = %digest, error = %e, "failed to ingest streamed blob into cache");
1174 }
1175 if let Some(s3) = &self.s3_cache {
1177 if let Err(e) = s3.put_path(digest, &dest).await {
1178 tracing::debug!(digest = %digest, error = %e, "failed to propagate blob to S3 tier");
1179 }
1180 }
1181
1182 tracing::debug!(digest = %digest, size = written, "blob streamed to file successfully");
1183 Ok(dest)
1184 }
1185
1186 pub async fn pull_image_to_files(
1194 &self,
1195 image: &str,
1196 auth: &RegistryAuth,
1197 staging_dir: &std::path::Path,
1198 ) -> Result<Vec<(std::path::PathBuf, String)>> {
1199 self.pull_image_to_files_inner(image, auth, staging_dir, PullPolicy::Newer)
1200 .await
1201 }
1202
1203 pub async fn pull_image_to_files_with_policy(
1209 &self,
1210 image: &str,
1211 auth: &RegistryAuth,
1212 staging_dir: &std::path::Path,
1213 policy: PullPolicy,
1214 ) -> Result<Vec<(std::path::PathBuf, String)>> {
1215 self.pull_image_to_files_inner(image, auth, staging_dir, policy)
1216 .await
1217 }
1218
1219 fn pull_singleflight_key(&self, image: &str, policy: PullPolicy) -> String {
1230 let cache_id = Arc::as_ptr(&self.cache) as usize;
1233 format!(
1234 "{cache_id:x}|{:?}|{:?}|{}",
1235 policy,
1236 self.source_policy,
1237 canonical_manifest_ref(image),
1238 )
1239 }
1240
1241 async fn pull_image_to_files_inner(
1269 &self,
1270 image: &str,
1271 auth: &RegistryAuth,
1272 staging_dir: &std::path::Path,
1273 policy: PullPolicy,
1274 ) -> Result<Vec<(std::path::PathBuf, String)>> {
1275 let key = self.pull_singleflight_key(image, policy);
1276
1277 let (slot, is_leader) = {
1281 let mut map = pull_singleflight().lock().await;
1282 if let Some(existing) = map.get(&key).and_then(std::sync::Weak::upgrade) {
1283 (existing, false)
1284 } else {
1285 let fresh: Arc<WarmSlot> = Arc::new(tokio::sync::OnceCell::new());
1286 map.insert(key.clone(), Arc::downgrade(&fresh));
1287 (fresh, true)
1288 }
1289 };
1290
1291 let mut leader_layers: Option<Result<Vec<(std::path::PathBuf, String)>>> = None;
1304 let shared = slot
1305 .get_or_init(|| async {
1306 match self.pull_manifest_inner(image, auth, policy).await {
1307 Ok((manifest, digest)) => {
1308 leader_layers = Some(
1311 self.materialize_layers_to_files(image, auth, staging_dir, &manifest)
1312 .await,
1313 );
1314 Ok((manifest, digest))
1315 }
1316 Err(e) => Err(e.to_string()),
1317 }
1318 })
1319 .await;
1320
1321 if is_leader {
1325 pull_singleflight().lock().await.remove(&key);
1326 }
1327
1328 if let Some(result) = leader_layers {
1333 return result;
1334 }
1335
1336 match shared {
1337 Ok((manifest, _digest)) => {
1338 self.materialize_layers_to_files(image, auth, staging_dir, manifest)
1342 .await
1343 }
1344 Err(msg) => {
1345 Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
1350 format!("image warm failed for {image}: {msg}"),
1351 )))
1352 }
1353 }
1354 }
1355
1356 async fn materialize_layers_to_files(
1363 &self,
1364 image: &str,
1365 auth: &RegistryAuth,
1366 staging_dir: &std::path::Path,
1367 manifest: &OciImageManifest,
1368 ) -> Result<Vec<(std::path::PathBuf, String)>> {
1369 tracing::info!(
1370 image = %image,
1371 layer_count = manifest.layers.len(),
1372 "pulling image layers (streamed to files)"
1373 );
1374
1375 let layer_inputs: Vec<(usize, String, String, Vec<String>, i64)> = manifest
1384 .layers
1385 .iter()
1386 .enumerate()
1387 .map(|(i, l)| {
1388 (
1389 i,
1390 l.digest.clone(),
1391 l.media_type.clone(),
1392 l.urls.clone().unwrap_or_default(),
1393 l.size,
1394 )
1395 })
1396 .collect();
1397 let layers: Vec<(std::path::PathBuf, String)> =
1398 futures_util::stream::iter(layer_inputs.into_iter().map(
1399 |(i, digest, media_type, urls, size)| async move {
1400 tracing::debug!(
1401 layer = i,
1402 digest = %digest,
1403 media_type = %media_type,
1404 size,
1405 "streaming layer to file"
1406 );
1407 let path = self
1408 .pull_blob_to_file(image, &digest, auth, &urls, Some(size), staging_dir)
1409 .await?;
1410 Ok::<(std::path::PathBuf, String), RegistryError>((path, media_type))
1411 },
1412 ))
1413 .buffered(LAYER_PULL_CONCURRENCY)
1414 .try_collect()
1415 .await?;
1416
1417 tracing::info!(image = %image, layers_pulled = layers.len(), "image pull complete (streamed)");
1418 Ok(layers)
1419 }
1420
1421 pub async fn remote_manifest_digest(
1437 &self,
1438 image: &str,
1439 auth: &RegistryAuth,
1440 ) -> Result<Option<String>> {
1441 let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
1442 registry: "unknown".to_string(),
1443 image: image.to_string(),
1444 })?;
1445
1446 self.note_network_call();
1447 match self.client.fetch_manifest_digest(&reference, auth).await {
1448 Ok(digest) => Ok(Some(digest)),
1449 Err(oci_client::errors::OciDistributionError::ImageManifestNotFoundError(_)) => {
1450 tracing::debug!(image = %image, "remote manifest not found");
1451 Ok(None)
1452 }
1453 Err(e) => {
1454 tracing::warn!(error = %e, image = %image, "failed to fetch remote manifest digest");
1455 Err(RegistryError::Oci(e))
1456 }
1457 }
1458 }
1459
1460 async fn try_cached_manifest(
1471 &self,
1472 image: &str,
1473 auth: &RegistryAuth,
1474 cache_key: &str,
1475 digest_key: &str,
1476 policy: PullPolicy,
1477 ) -> Option<(OciImageManifest, String)> {
1478 let data = self.cache.get(cache_key).await.ok().flatten()?;
1479 let manifest = parse_image_manifest_only(&data)?;
1480
1481 let cached_digest = self
1482 .cache
1483 .get(digest_key)
1484 .await
1485 .ok()
1486 .flatten()
1487 .and_then(|bytes| String::from_utf8(bytes).ok());
1488
1489 if matches!(policy, PullPolicy::IfNotPresent | PullPolicy::Never) {
1491 let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
1492 tracing::debug!(image = %image, "manifest cache hit (IfNotPresent/Never, no revalidation)");
1493 return Some((manifest, digest));
1494 }
1495
1496 if !is_mutable_tag(image) {
1498 let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
1499 tracing::debug!(image = %image, "manifest cache hit (pinned ref)");
1500 return Some((manifest, digest));
1501 }
1502
1503 match self.remote_manifest_digest(image, auth).await {
1505 Ok(Some(remote_digest)) => {
1506 if let Some(cached) = cached_digest.as_deref() {
1507 if cached == remote_digest {
1508 tracing::debug!(image = %image, "manifest cache hit (revalidated)");
1509 return Some((manifest, remote_digest));
1510 }
1511 tracing::info!(
1512 image = %image,
1513 cached = %cached,
1514 remote = %remote_digest,
1515 "cached manifest is stale, refetching"
1516 );
1517 } else {
1518 tracing::info!(
1522 image = %image,
1523 remote = %remote_digest,
1524 "cached manifest has no stored digest, refetching"
1525 );
1526 }
1527 if let Err(e) = self.cache.delete(cache_key).await {
1528 tracing::warn!(
1529 image = %image,
1530 error = %e,
1531 "failed to delete stale manifest cache entry"
1532 );
1533 }
1534 if let Err(e) = self.cache.delete(digest_key).await {
1535 tracing::warn!(
1536 image = %image,
1537 error = %e,
1538 "failed to delete stale manifest digest cache entry"
1539 );
1540 }
1541 None
1542 }
1543 Ok(None) => {
1544 tracing::warn!(image = %image, "remote manifest not found, using stale cache");
1545 let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
1546 Some((manifest, digest))
1547 }
1548 Err(e) => {
1549 tracing::warn!(
1550 image = %image,
1551 error = %e,
1552 "manifest revalidation failed, using stale cache"
1553 );
1554 let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
1555 Some((manifest, digest))
1556 }
1557 }
1558 }
1559
1560 #[cfg(feature = "local")]
1577 async fn resolve_stored_manifest(
1578 &self,
1579 registry: &crate::local_registry::LocalRegistry,
1580 name: &str,
1581 data: &[u8],
1582 ) -> Option<(OciImageManifest, String)> {
1583 match serde_json::from_slice::<OciManifest>(data).ok()? {
1584 OciManifest::Image(manifest) => Some((manifest, crate::cache::compute_digest(data))),
1585 OciManifest::ImageIndex(index) => {
1586 let resolver = build_platform_resolver(self.target.clone());
1587 let selected = resolver(&index.manifests)?;
1588 let sub = registry.get_manifest(name, &selected).await.ok()?;
1589 let manifest = serde_json::from_slice::<OciImageManifest>(&sub).ok()?;
1590 tracing::debug!(
1591 name = %name,
1592 index_digest = %crate::cache::compute_digest(data),
1593 selected = %selected,
1594 "resolved stored OCI image index to its platform-specific manifest",
1595 );
1596 Some((manifest, crate::cache::compute_digest(&sub)))
1597 }
1598 }
1599 }
1600
1601 #[cfg(feature = "local")]
1610 async fn try_local_registry(&self, image: &str) -> Option<(OciImageManifest, String)> {
1611 let registry = self.local_registry.as_ref()?;
1612 let candidates = local_image_ref_candidates(image);
1613 let primary = candidates.first().map(|(n, _)| n.clone());
1614 for (name, reference) in candidates {
1615 if let Ok(data) = registry.get_manifest(&name, &reference).await {
1619 if let Some((manifest, digest)) =
1624 self.resolve_stored_manifest(registry, &name, &data).await
1625 {
1626 if primary.as_deref() == Some(name.as_str()) {
1627 tracing::debug!(
1628 image = %image,
1629 digest = %digest,
1630 "manifest found in local registry",
1631 );
1632 } else {
1633 tracing::debug!(
1634 image = %image,
1635 matched_name = %name,
1636 digest = %digest,
1637 "manifest found in local registry via name-form fallback",
1638 );
1639 }
1640 return Some((manifest, digest));
1641 }
1642 tracing::warn!(
1643 image = %image,
1644 candidate = %name,
1645 "local registry manifest parse/resolve failed",
1646 );
1647 }
1649 }
1650
1651 if zlayer_types::image_str_is_unqualified(image) {
1659 if let Some((want_name, want_ref)) =
1660 local_image_ref_candidates(image).into_iter().next()
1661 {
1662 let want_leaf = want_name
1663 .rsplit('/')
1664 .next()
1665 .unwrap_or(&want_name)
1666 .to_string();
1667 if let Ok(stored) = registry.list_images().await {
1668 for s in stored {
1669 let s_leaf = s.rsplit('/').next().unwrap_or(&s);
1670 if s_leaf != want_leaf {
1675 continue;
1676 }
1677 if let Ok(data) = registry.get_manifest(&s, &want_ref).await {
1678 if let Some((manifest, digest)) =
1679 self.resolve_stored_manifest(registry, &s, &data).await
1680 {
1681 tracing::debug!(
1682 image = %image,
1683 matched_name = %s,
1684 reference = %want_ref,
1685 digest = %digest,
1686 "manifest found in local registry via unqualified suffix-match",
1687 );
1688 return Some((manifest, digest));
1689 }
1690 }
1691 }
1692 }
1693 }
1694 }
1695
1696 None
1697 }
1698
1699 pub async fn pull_manifest(
1720 &self,
1721 image: &str,
1722 auth: &RegistryAuth,
1723 ) -> Result<(OciImageManifest, String)> {
1724 self.pull_manifest_inner(image, auth, PullPolicy::Newer)
1725 .await
1726 }
1727
1728 async fn pull_manifest_inner(
1737 &self,
1738 image: &str,
1739 auth: &RegistryAuth,
1740 policy: PullPolicy,
1741 ) -> Result<(OciImageManifest, String)> {
1742 use zlayer_spec::SourcePolicy;
1743 let cache_key = manifest_cache_key(image);
1744 let digest_key = manifest_digest_cache_key(image);
1745 let source = self.source_policy;
1746
1747 let use_local = !matches!(source, SourcePolicy::RemoteOnly);
1764 let use_s3 = matches!(source, SourcePolicy::LocalFirst | SourcePolicy::S3First);
1765 let use_origin = !matches!(source, SourcePolicy::LocalOnly);
1766
1767 #[cfg(feature = "local")]
1770 if use_local {
1771 if let Some((manifest, digest)) = self.try_local_registry(image).await {
1772 self.warm_local_cache(image, &cache_key, &digest_key, &manifest, &digest)
1775 .await;
1776
1777 let revalidate = use_origin
1781 && !matches!(policy, PullPolicy::IfNotPresent | PullPolicy::Never)
1782 && is_mutable_tag(image);
1783 if !revalidate {
1784 return Ok((manifest, digest));
1785 }
1786 match self.remote_manifest_digest(image, auth).await {
1787 Ok(Some(remote_digest)) if remote_digest != digest => {
1788 tracing::info!(
1789 image = %image,
1790 local = %digest,
1791 remote = %remote_digest,
1792 "remote has newer manifest, pulling fresh"
1793 );
1794 }
1796 Ok(Some(_) | None) => return Ok((manifest, digest)),
1797 Err(e) => {
1798 tracing::warn!(image = %image, error = %e, "remote check failed, using local manifest");
1799 return Ok((manifest, digest));
1800 }
1801 }
1802 return self
1803 .pull_from_origin(image, auth, &cache_key, &digest_key)
1804 .await;
1805 }
1806 }
1807
1808 if use_local {
1811 if matches!(source, SourcePolicy::S3First) {
1812 if let Some(hit) = self
1813 .try_s3_manifest(image, auth, &cache_key, &digest_key, policy)
1814 .await
1815 {
1816 return Ok(hit);
1817 }
1818 if let Some(hit) = self
1819 .try_cached_manifest(image, auth, &cache_key, &digest_key, policy)
1820 .await
1821 {
1822 return Ok(hit);
1823 }
1824 } else {
1825 if let Some(hit) = self
1826 .try_cached_manifest(image, auth, &cache_key, &digest_key, policy)
1827 .await
1828 {
1829 return Ok(hit);
1830 }
1831 if use_s3 {
1832 if let Some(hit) = self
1833 .try_s3_manifest(image, auth, &cache_key, &digest_key, policy)
1834 .await
1835 {
1836 return Ok(hit);
1837 }
1838 }
1839 }
1840 }
1841
1842 if !use_origin {
1845 return Err(RegistryError::NotFound {
1846 registry: "local".to_string(),
1847 image: format!(
1848 "{image} (source_policy=local_only: not present in any local source \
1849 and remote resolution is disabled for this image)"
1850 ),
1851 });
1852 }
1853 self.pull_from_origin(image, auth, &cache_key, &digest_key)
1854 .await
1855 }
1856
1857 async fn pull_from_origin(
1864 &self,
1865 image: &str,
1866 auth: &RegistryAuth,
1867 cache_key: &str,
1868 digest_key: &str,
1869 ) -> Result<(OciImageManifest, String)> {
1870 let pull_ref: Reference = if zlayer_types::image_str_is_unqualified(image) {
1871 let Some(default) = self.default_registry.as_deref() else {
1872 tracing::error!(
1879 image = %image,
1880 missing_config = "ZLAYER_DEFAULT_REGISTRY",
1881 "cannot resolve unqualified image: no default registry is configured. Set \
1882 ZLAYER_DEFAULT_REGISTRY (or run `zlayer login --default <host>`) to pick the \
1883 registry bare names resolve against, push a fully-qualified ref (e.g. \
1884 registry.example.com/{image}), or `zlayer build` it locally"
1885 );
1886 return Err(RegistryError::NotFound {
1887 registry: "local".to_string(),
1888 image: format!(
1889 "{image} (unqualified image not found locally and no default registry is \
1890 configured: set ZLAYER_DEFAULT_REGISTRY or run `zlayer login --default \
1891 <host>` to choose the registry bare names resolve against, use a full \
1892 registry URL such as registry.example.com/{image} for a remote pull, or \
1893 run `zlayer build` to produce it locally — ZLayer never silently pulls \
1894 bare names from a public registry)"
1895 ),
1896 });
1897 };
1898 let qualified = format!("{}/{}", default.trim_end_matches('/'), image);
1899 tracing::info!(
1900 image = %image,
1901 default_registry = %default,
1902 qualified = %qualified,
1903 "bare name resolved nowhere; using configured last-resort default registry"
1904 );
1905 qualified.parse().map_err(|_| RegistryError::NotFound {
1906 registry: default.to_string(),
1907 image: qualified.clone(),
1908 })?
1909 } else {
1910 image.parse().map_err(|_| RegistryError::NotFound {
1911 registry: "unknown".to_string(),
1912 image: image.to_string(),
1913 })?
1914 };
1915
1916 tracing::info!(image = %image, reference = %pull_ref, "pulling manifest from registry");
1917
1918 self.note_network_call();
1919 match self.client.pull_image_manifest(&pull_ref, auth).await {
1920 Ok((manifest, digest)) => {
1921 tracing::debug!(
1922 image = %image,
1923 digest = %digest,
1924 layers = manifest.layers.len(),
1925 "manifest pulled successfully"
1926 );
1927
1928 self.propagate_manifest_down(image, cache_key, digest_key, &manifest, &digest)
1932 .await;
1933
1934 Ok((manifest, digest))
1935 }
1936 Err(remote_err) => {
1937 #[cfg(feature = "local")]
1939 if let Some((manifest, digest)) = self.try_local_registry(image).await {
1940 tracing::warn!(
1941 image = %image,
1942 error = %remote_err,
1943 "remote pull failed, falling back to local registry"
1944 );
1945 return Ok((manifest, digest));
1946 }
1947
1948 tracing::error!(error = %remote_err, image = %image, "failed to pull manifest");
1949 Err(RegistryError::Oci(remote_err))
1950 }
1951 }
1952 }
1953
1954 async fn record_original_ref(&self, image: &str) {
1958 let _ = self
1959 .cache
1960 .put(&manifest_orig_cache_key(image), image.as_bytes())
1961 .await;
1962 }
1963
1964 async fn warm_local_cache(
1968 &self,
1969 image: &str,
1970 cache_key: &str,
1971 digest_key: &str,
1972 manifest: &OciImageManifest,
1973 digest: &str,
1974 ) {
1975 if let Ok(bytes) = serde_json::to_vec(manifest) {
1976 let _ = self.cache.put(cache_key, &bytes).await;
1977 let _ = self.cache.put(digest_key, digest.as_bytes()).await;
1978 }
1979 self.record_original_ref(image).await;
1980 }
1981
1982 async fn propagate_manifest_down(
1986 &self,
1987 image: &str,
1988 cache_key: &str,
1989 digest_key: &str,
1990 manifest: &OciImageManifest,
1991 digest: &str,
1992 ) {
1993 let Ok(bytes) = serde_json::to_vec(manifest) else {
1994 return;
1995 };
1996 let prev_digest = self
2000 .cache
2001 .get(digest_key)
2002 .await
2003 .ok()
2004 .flatten()
2005 .and_then(|b| String::from_utf8(b).ok());
2006 let tag_moved = matches!(prev_digest, Some(prev) if prev != digest);
2007
2008 let _ = self.cache.put(cache_key, &bytes).await;
2009 let _ = self.cache.put(digest_key, digest.as_bytes()).await;
2010 self.record_original_ref(image).await;
2011 if let Some(s3) = &self.s3_cache {
2012 if let Err(e) = s3.put(cache_key, &bytes).await {
2013 tracing::debug!(error = %e, "failed to propagate manifest body to S3 tier");
2014 }
2015 if let Err(e) = s3.put(digest_key, digest.as_bytes()).await {
2016 tracing::debug!(error = %e, "failed to propagate manifest digest to S3 tier");
2017 }
2018 }
2019
2020 if tag_moved {
2025 match crate::prune::prune_dangling_blobs(self.cache.as_ref().as_ref()).await {
2026 Ok((deleted, reclaimed)) if !deleted.is_empty() => {
2027 tracing::info!(
2028 image = %image,
2029 superseded = deleted.len(),
2030 reclaimed_bytes = reclaimed,
2031 "reclaimed layers from a superseded manifest after tag update"
2032 );
2033 }
2034 Ok(_) => {}
2035 Err(e) => {
2036 tracing::debug!(image = %image, error = %e, "post-tag-update blob prune failed");
2037 }
2038 }
2039 }
2040 }
2041
2042 async fn try_s3_manifest(
2047 &self,
2048 image: &str,
2049 auth: &RegistryAuth,
2050 cache_key: &str,
2051 digest_key: &str,
2052 policy: PullPolicy,
2053 ) -> Option<(OciImageManifest, String)> {
2054 self.s3_cache.as_ref()?;
2058 let data = self.s3_tier_get(cache_key).await?;
2059 let manifest = parse_image_manifest_only(&data)?;
2060 let cached_digest = self
2061 .s3_tier_get(digest_key)
2062 .await
2063 .and_then(|b| String::from_utf8(b).ok());
2064
2065 if matches!(policy, PullPolicy::IfNotPresent | PullPolicy::Never) || !is_mutable_tag(image)
2067 {
2068 let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
2069 self.warm_local_cache(image, cache_key, digest_key, &manifest, &digest)
2070 .await;
2071 tracing::debug!(image = %image, "manifest S3 tier hit");
2072 return Some((manifest, digest));
2073 }
2074
2075 match self.remote_manifest_digest(image, auth).await {
2077 Ok(Some(remote_digest)) if cached_digest.as_deref() == Some(remote_digest.as_str()) => {
2078 self.warm_local_cache(image, cache_key, digest_key, &manifest, &remote_digest)
2079 .await;
2080 tracing::debug!(image = %image, "manifest S3 tier hit (revalidated)");
2081 Some((manifest, remote_digest))
2082 }
2083 Ok(Some(_)) => {
2084 tracing::info!(image = %image, "S3 manifest stale vs origin, refetching");
2085 None
2086 }
2087 Ok(None) | Err(_) => {
2088 let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
2089 self.warm_local_cache(image, cache_key, digest_key, &manifest, &digest)
2090 .await;
2091 tracing::warn!(image = %image, "S3 manifest revalidation unavailable, serving S3 copy");
2092 Some((manifest, digest))
2093 }
2094 }
2095 }
2096
2097 async fn resolve_manifest_local_only(&self, image: &str) -> Option<(OciImageManifest, String)> {
2109 let cache_key = manifest_cache_key(image);
2110 let digest_key = manifest_digest_cache_key(image);
2111
2112 if let Some(hit) = self
2128 .try_cached_manifest(
2129 image,
2130 &RegistryAuth::Anonymous,
2131 &cache_key,
2132 &digest_key,
2133 PullPolicy::IfNotPresent,
2134 )
2135 .await
2136 {
2137 return Some(hit);
2138 }
2139
2140 #[cfg(feature = "local")]
2148 if let Some((manifest, digest)) = self.try_local_registry(image).await {
2149 if let Ok(bytes) = serde_json::to_vec(&manifest) {
2150 let _ = self.cache.put(&cache_key, &bytes).await;
2151 let _ = self.cache.put(&digest_key, digest.as_bytes()).await;
2152 }
2153 return Some((manifest, digest));
2154 }
2155
2156 None
2160 }
2161
2162 pub async fn image_os_in_cache_only(&self, image: &str) -> Result<Option<zlayer_spec::OsKind>> {
2171 let Some((manifest, _digest)) = self.resolve_manifest_local_only(image).await else {
2172 return Ok(None);
2173 };
2174
2175 let config_digest = &manifest.config.digest;
2176 let Some(config_blob) = self.cache.get(config_digest).await.ok().flatten() else {
2180 return Ok(None);
2181 };
2182
2183 let config_root: OciImageConfigRoot =
2184 serde_json::from_slice(&config_blob).map_err(|e| {
2185 tracing::error!(
2186 error = %e,
2187 image = %image,
2188 config_digest = %config_digest,
2189 "failed to parse cached image config JSON for OS inspection"
2190 );
2191 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2192 "failed to parse image config for {image}: {e}"
2193 )))
2194 })?;
2195
2196 Ok(config_root
2197 .os
2198 .as_deref()
2199 .and_then(zlayer_spec::OsKind::from_oci_str))
2200 }
2201
2202 pub async fn cache_local_image_platform(
2219 &self,
2220 image: &str,
2221 os: &str,
2222 architecture: &str,
2223 ) -> Result<()> {
2224 let config_json = serde_json::json!({
2230 "architecture": architecture,
2231 "os": os,
2232 "config": {},
2233 });
2234 let config_bytes = serde_json::to_vec(&config_json).map_err(|e| {
2235 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2236 "failed to serialize local image config for {image}: {e}"
2237 )))
2238 })?;
2239 let config_digest = crate::cache::compute_digest(&config_bytes);
2240 self.cache.put(&config_digest, &config_bytes).await?;
2241
2242 let manifest = OciImageManifest {
2246 schema_version: 2,
2247 media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
2248 artifact_type: None,
2249 config: oci_client::manifest::OciDescriptor {
2250 media_type: "application/vnd.oci.image.config.v1+json".to_string(),
2251 digest: config_digest.clone(),
2252 size: i64::try_from(config_bytes.len()).unwrap_or(0),
2253 urls: None,
2254 annotations: None,
2255 },
2256 layers: vec![],
2257 annotations: None,
2258 subject: None,
2259 };
2260 let manifest_bytes = serde_json::to_vec(&manifest).map_err(|e| {
2261 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2262 "failed to serialize local image manifest for {image}: {e}"
2263 )))
2264 })?;
2265 let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
2266
2267 self.cache
2271 .put(&manifest_cache_key(image), &manifest_bytes)
2272 .await?;
2273 self.cache
2274 .put(
2275 &manifest_digest_cache_key(image),
2276 manifest_digest.as_bytes(),
2277 )
2278 .await?;
2279 self.record_original_ref(image).await;
2280 Ok(())
2281 }
2282
2283 pub async fn image_runtime_marker_in_cache_only(&self, image: &str) -> Result<Option<String>> {
2291 let Some((manifest, _digest)) = self.resolve_manifest_local_only(image).await else {
2292 return Ok(None);
2293 };
2294 Ok(manifest
2295 .annotations
2296 .as_ref()
2297 .and_then(|a| a.get(crate::ZLAYER_RUNTIME_ANNOTATION).cloned()))
2298 }
2299
2300 pub async fn image_isolation_marker_in_cache_only(
2314 &self,
2315 image: &str,
2316 ) -> Result<Option<String>> {
2317 let Some((manifest, _digest)) = self.resolve_manifest_local_only(image).await else {
2318 return Ok(None);
2319 };
2320
2321 let config_digest = &manifest.config.digest;
2322 let Some(config_blob) = self.cache.get(config_digest).await.ok().flatten() else {
2326 return Ok(None);
2327 };
2328
2329 let config_root: OciImageConfigRoot =
2330 serde_json::from_slice(&config_blob).map_err(|e| {
2331 tracing::error!(
2332 error = %e,
2333 image = %image,
2334 config_digest = %config_digest,
2335 "failed to parse cached image config JSON for isolation inspection"
2336 );
2337 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2338 "failed to parse image config for {image}: {e}"
2339 )))
2340 })?;
2341
2342 Ok(config_root
2343 .config
2344 .and_then(|c| c.labels)
2345 .and_then(|l| l.get(crate::ZLAYER_ISOLATION_ANNOTATION).cloned()))
2346 }
2347
2348 pub async fn pull_manifest_with_policy(
2362 &self,
2363 image: &str,
2364 auth: &RegistryAuth,
2365 policy: PullPolicy,
2366 ) -> Result<(OciImageManifest, String)> {
2367 let force_refresh = matches!(policy, PullPolicy::Always);
2368 if force_refresh {
2369 let cache_key = manifest_cache_key(image);
2370 let digest_key = manifest_digest_cache_key(image);
2371 if let Err(e) = self.cache.delete(&cache_key).await {
2372 tracing::warn!(
2373 image = %image,
2374 error = %e,
2375 "failed to invalidate manifest cache for force refresh"
2376 );
2377 }
2378 if let Err(e) = self.cache.delete(&digest_key).await {
2379 tracing::warn!(
2380 image = %image,
2381 error = %e,
2382 "failed to invalidate manifest digest cache for force refresh"
2383 );
2384 }
2385 }
2386 self.pull_manifest_inner(image, auth, policy).await
2387 }
2388
2389 pub async fn pull_image_config(&self, image: &str, auth: &RegistryAuth) -> Result<ImageConfig> {
2411 self.pull_image_config_inner(image, auth, PullPolicy::Newer)
2412 .await
2413 }
2414
2415 async fn pull_image_config_inner(
2417 &self,
2418 image: &str,
2419 auth: &RegistryAuth,
2420 policy: PullPolicy,
2421 ) -> Result<ImageConfig> {
2422 let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
2423
2424 let config_digest = &manifest.config.digest;
2425
2426 tracing::debug!(
2427 image = %image,
2428 config_digest = %config_digest,
2429 config_media_type = %manifest.config.media_type,
2430 "fetching image config blob"
2431 );
2432
2433 let config_blob = self.pull_blob(image, config_digest, auth).await?;
2434
2435 let config_root: OciImageConfigRoot =
2436 serde_json::from_slice(&config_blob).map_err(|e| {
2437 tracing::error!(
2438 error = %e,
2439 image = %image,
2440 config_digest = %config_digest,
2441 "failed to parse image config JSON"
2442 );
2443 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2444 "failed to parse image config for {image}: {e}"
2445 )))
2446 })?;
2447
2448 let config = config_root.config.unwrap_or_default();
2449
2450 tracing::info!(
2451 image = %image,
2452 has_entrypoint = config.entrypoint.is_some(),
2453 has_cmd = config.cmd.is_some(),
2454 has_working_dir = config.working_dir.is_some(),
2455 has_user = config.user.is_some(),
2456 env_count = config.env.as_ref().map_or(0, std::vec::Vec::len),
2457 "image config parsed successfully"
2458 );
2459
2460 Ok(config)
2461 }
2462
2463 pub async fn pull_image_config_with_policy(
2479 &self,
2480 image: &str,
2481 auth: &RegistryAuth,
2482 policy: PullPolicy,
2483 ) -> Result<ImageConfig> {
2484 let force_refresh = matches!(policy, PullPolicy::Always);
2485 if force_refresh {
2486 let cache_key = manifest_cache_key(image);
2487 let digest_key = manifest_digest_cache_key(image);
2488 if let Err(e) = self.cache.delete(&cache_key).await {
2489 tracing::warn!(
2490 image = %image,
2491 error = %e,
2492 "failed to invalidate manifest cache for force refresh"
2493 );
2494 }
2495 if let Err(e) = self.cache.delete(&digest_key).await {
2496 tracing::warn!(
2497 image = %image,
2498 error = %e,
2499 "failed to invalidate manifest digest cache for force refresh"
2500 );
2501 }
2502 }
2503 let key = self.pull_singleflight_key(image, policy);
2512 let (slot, is_leader) = {
2513 let mut map = config_singleflight().lock().await;
2514 if let Some(existing) = map.get(&key).and_then(std::sync::Weak::upgrade) {
2515 (existing, false)
2516 } else {
2517 let fresh: Arc<ConfigSlot> = Arc::new(tokio::sync::OnceCell::new());
2518 map.insert(key.clone(), Arc::downgrade(&fresh));
2519 (fresh, true)
2520 }
2521 };
2522
2523 let outcome = slot
2524 .get_or_init(|| async {
2525 self.pull_image_config_inner(image, auth, policy)
2526 .await
2527 .map_err(|e| e.to_string())
2528 })
2529 .await
2530 .clone();
2531
2532 if is_leader {
2533 config_singleflight().lock().await.remove(&key);
2536 }
2537
2538 outcome.map_err(|msg| {
2539 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2540 "image config fetch failed for {image}: {msg}"
2541 )))
2542 })
2543 }
2544
2545 pub async fn image_os(
2565 &self,
2566 image: &str,
2567 auth: &RegistryAuth,
2568 ) -> Result<Option<zlayer_spec::OsKind>> {
2569 self.image_os_with_policy(image, auth, PullPolicy::Newer)
2570 .await
2571 }
2572
2573 pub async fn image_os_with_policy(
2589 &self,
2590 image: &str,
2591 auth: &RegistryAuth,
2592 policy: PullPolicy,
2593 ) -> Result<Option<zlayer_spec::OsKind>> {
2594 let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
2595
2596 let config_digest = &manifest.config.digest;
2597 let config_blob = self.pull_blob(image, config_digest, auth).await?;
2598
2599 let config_root: OciImageConfigRoot =
2600 serde_json::from_slice(&config_blob).map_err(|e| {
2601 tracing::error!(
2602 error = %e,
2603 image = %image,
2604 config_digest = %config_digest,
2605 "failed to parse image config JSON for OS inspection"
2606 );
2607 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2608 "failed to parse image config for {image}: {e}"
2609 )))
2610 })?;
2611
2612 Ok(config_root
2613 .os
2614 .as_deref()
2615 .and_then(zlayer_spec::OsKind::from_oci_str))
2616 }
2617
2618 pub async fn image_runtime_marker(
2626 &self,
2627 image: &str,
2628 auth: &RegistryAuth,
2629 ) -> Result<Option<String>> {
2630 self.image_runtime_marker_with_policy(image, auth, PullPolicy::Newer)
2631 .await
2632 }
2633
2634 pub async fn image_runtime_marker_with_policy(
2642 &self,
2643 image: &str,
2644 auth: &RegistryAuth,
2645 policy: PullPolicy,
2646 ) -> Result<Option<String>> {
2647 let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
2648 Ok(manifest
2649 .annotations
2650 .as_ref()
2651 .and_then(|a| a.get(crate::ZLAYER_RUNTIME_ANNOTATION).cloned()))
2652 }
2653
2654 pub async fn image_isolation_marker_with_policy(
2665 &self,
2666 image: &str,
2667 auth: &RegistryAuth,
2668 policy: PullPolicy,
2669 ) -> Result<Option<String>> {
2670 let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
2671
2672 let config_digest = &manifest.config.digest;
2673 let config_blob = self.pull_blob(image, config_digest, auth).await?;
2674
2675 let config_root: OciImageConfigRoot =
2676 serde_json::from_slice(&config_blob).map_err(|e| {
2677 tracing::error!(
2678 error = %e,
2679 image = %image,
2680 config_digest = %config_digest,
2681 "failed to parse image config JSON for isolation inspection"
2682 );
2683 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2684 "failed to parse image config for {image}: {e}"
2685 )))
2686 })?;
2687
2688 Ok(config_root
2689 .config
2690 .and_then(|c| c.labels)
2691 .and_then(|l| l.get(crate::ZLAYER_ISOLATION_ANNOTATION).cloned()))
2692 }
2693
2694 pub async fn image_os_version(
2713 &self,
2714 image: &str,
2715 auth: &RegistryAuth,
2716 ) -> Result<Option<String>> {
2717 let (manifest, _digest) = self.pull_manifest(image, auth).await?;
2718
2719 let config_digest = &manifest.config.digest;
2720 let config_blob = self.pull_blob(image, config_digest, auth).await?;
2721
2722 let config_root: OciImageConfigRoot =
2723 serde_json::from_slice(&config_blob).map_err(|e| {
2724 tracing::error!(
2725 error = %e,
2726 image = %image,
2727 config_digest = %config_digest,
2728 "failed to parse image config JSON for os.version inspection"
2729 );
2730 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2731 "failed to parse image config for {image}: {e}"
2732 )))
2733 })?;
2734
2735 Ok(config_root.os_version)
2736 }
2737
2738 pub async fn detect_artifact_type(
2756 &self,
2757 image: &str,
2758 auth: &RegistryAuth,
2759 ) -> Result<(ArtifactType, OciImageManifest, String)> {
2760 let (manifest, digest) = self.pull_manifest(image, auth).await?;
2761 let artifact_type = detect_artifact_type(&manifest);
2762
2763 tracing::info!(
2764 image = %image,
2765 artifact_type = %artifact_type,
2766 "detected artifact type"
2767 );
2768
2769 Ok((artifact_type, manifest, digest))
2770 }
2771
2772 pub async fn get_wasm_info(
2790 &self,
2791 image: &str,
2792 auth: &RegistryAuth,
2793 ) -> Result<Option<WasmArtifactInfo>> {
2794 let (manifest, _digest) = self.pull_manifest(image, auth).await?;
2795 Ok(extract_wasm_info(&manifest))
2796 }
2797
2798 pub async fn pull_wasm(
2817 &self,
2818 image: &str,
2819 auth: &RegistryAuth,
2820 ) -> Result<(Vec<u8>, WasmArtifactInfo)> {
2821 let (manifest, _digest) = self.pull_manifest(image, auth).await?;
2822
2823 let wasm_info = extract_wasm_info(&manifest).ok_or_else(|| RegistryError::NotFound {
2824 registry: "unknown".to_string(),
2825 image: format!("{image} (not a WASM artifact)"),
2826 })?;
2827
2828 let wasm_digest =
2829 wasm_info
2830 .wasm_layer_digest
2831 .as_ref()
2832 .ok_or_else(|| RegistryError::NotFound {
2833 registry: "unknown".to_string(),
2834 image: format!("{image} (no WASM layer found)"),
2835 })?;
2836
2837 tracing::info!(
2838 image = %image,
2839 wasi_version = %wasm_info.wasi_version,
2840 wasm_digest = %wasm_digest,
2841 "pulling WASM binary"
2842 );
2843
2844 let wasm_bytes = self.pull_blob(image, wasm_digest, auth).await?;
2845
2846 tracing::info!(
2847 image = %image,
2848 wasm_size = wasm_bytes.len(),
2849 "WASM binary pulled successfully"
2850 );
2851
2852 Ok((wasm_bytes, wasm_info))
2853 }
2854
2855 pub async fn pull_image(
2863 &self,
2864 image: &str,
2865 auth: &RegistryAuth,
2866 ) -> Result<Vec<(Vec<u8>, String)>> {
2867 self.pull_image_inner(image, auth, PullPolicy::Newer).await
2868 }
2869
2870 async fn pull_image_inner(
2872 &self,
2873 image: &str,
2874 auth: &RegistryAuth,
2875 policy: PullPolicy,
2876 ) -> Result<Vec<(Vec<u8>, String)>> {
2877 let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
2879
2880 tracing::info!(
2881 image = %image,
2882 layer_count = manifest.layers.len(),
2883 "pulling image layers"
2884 );
2885
2886 let layer_inputs: Vec<(usize, String, String, Vec<String>, i64)> = manifest
2893 .layers
2894 .iter()
2895 .enumerate()
2896 .map(|(i, l)| {
2897 (
2898 i,
2899 l.digest.clone(),
2900 l.media_type.clone(),
2901 l.urls.clone().unwrap_or_default(),
2902 l.size,
2903 )
2904 })
2905 .collect();
2906 let layers: Vec<(Vec<u8>, String)> =
2907 futures_util::stream::iter(layer_inputs.into_iter().map(
2908 |(i, digest, media_type, urls, size)| async move {
2909 tracing::debug!(
2910 layer = i,
2911 digest = %digest,
2912 media_type = %media_type,
2913 size,
2914 "pulling layer"
2915 );
2916
2917 let data = self
2918 .pull_blob_with_urls(image, &digest, auth, &urls, Some(size))
2919 .await?;
2920
2921 if data.is_empty() {
2923 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
2924 format!("layer {i} ({digest}) is empty after pull"),
2925 )));
2926 }
2927
2928 Ok::<(Vec<u8>, String), RegistryError>((data, media_type))
2929 },
2930 ))
2931 .buffered(LAYER_PULL_CONCURRENCY)
2932 .try_collect()
2933 .await?;
2934
2935 tracing::info!(
2936 image = %image,
2937 layers_pulled = layers.len(),
2938 "image pull complete"
2939 );
2940
2941 Ok(layers)
2942 }
2943
2944 pub async fn pull_image_with_policy(
2958 &self,
2959 image: &str,
2960 auth: &RegistryAuth,
2961 policy: PullPolicy,
2962 ) -> Result<Vec<(Vec<u8>, String)>> {
2963 let force_refresh = matches!(policy, PullPolicy::Always);
2964 if force_refresh {
2965 let cache_key = manifest_cache_key(image);
2966 let digest_key = manifest_digest_cache_key(image);
2967 if let Err(e) = self.cache.delete(&cache_key).await {
2968 tracing::warn!(
2969 image = %image,
2970 error = %e,
2971 "failed to invalidate manifest cache for force refresh"
2972 );
2973 }
2974 if let Err(e) = self.cache.delete(&digest_key).await {
2975 tracing::warn!(
2976 image = %image,
2977 error = %e,
2978 "failed to invalidate manifest digest cache for force refresh"
2979 );
2980 }
2981 }
2982 self.pull_image_inner(image, auth, policy).await
2983 }
2984
2985 #[instrument(
3006 name = "push_blob",
3007 skip(self, data, auth, _media_type),
3008 fields(
3009 reference = %reference,
3010 digest = %digest,
3011 size = data.len(),
3012 )
3013 )]
3014 pub async fn push_blob(
3015 &self,
3016 reference: &str,
3017 digest: &str,
3018 data: &[u8],
3019 _media_type: &str,
3020 auth: &RegistryAuth,
3021 ) -> std::result::Result<(), PushError> {
3022 let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3023 reference: reference.to_string(),
3024 })?;
3025
3026 tracing::debug!(
3027 reference = %reference,
3028 digest = %digest,
3029 size = data.len(),
3030 "pushing blob to registry"
3031 );
3032
3033 self.client
3035 .auth(&image_ref, auth, RegistryOperation::Push)
3036 .await
3037 .map_err(|e| PushError::AuthenticationFailed {
3038 registry: image_ref.resolve_registry().to_string(),
3039 reason: e.to_string(),
3040 })?;
3041
3042 self.client
3044 .push_blob(&image_ref, data, digest)
3045 .await
3046 .map_err(|e| PushError::BlobUploadFailed {
3047 digest: digest.to_string(),
3048 reason: e.to_string(),
3049 })?;
3050
3051 tracing::info!(
3052 reference = %reference,
3053 digest = %digest,
3054 size = data.len(),
3055 "blob pushed successfully"
3056 );
3057
3058 Ok(())
3059 }
3060
3061 #[instrument(
3083 name = "push_manifest_to_registry",
3084 skip(self, manifest, auth),
3085 fields(
3086 reference = %reference,
3087 layers = manifest.layers.len(),
3088 )
3089 )]
3090 pub async fn push_manifest_to_registry(
3091 &self,
3092 reference: &str,
3093 manifest: &OciImageManifest,
3094 auth: &RegistryAuth,
3095 ) -> std::result::Result<String, PushError> {
3096 let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3097 reference: reference.to_string(),
3098 })?;
3099
3100 tracing::debug!(
3101 reference = %reference,
3102 layers = manifest.layers.len(),
3103 config_digest = %manifest.config.digest,
3104 "pushing manifest to registry"
3105 );
3106
3107 self.client
3109 .auth(&image_ref, auth, RegistryOperation::Push)
3110 .await
3111 .map_err(|e| PushError::AuthenticationFailed {
3112 registry: image_ref.resolve_registry().to_string(),
3113 reason: e.to_string(),
3114 })?;
3115
3116 let manifest_url = self
3118 .client
3119 .push_manifest(&image_ref, &OciManifest::Image(manifest.clone()))
3120 .await
3121 .map_err(|e| PushError::ManifestUploadFailed {
3122 reason: e.to_string(),
3123 })?;
3124
3125 let digest = if let Some(digest_start) = manifest_url.rfind('@') {
3128 manifest_url[digest_start + 1..].to_string()
3129 } else {
3130 let manifest_json =
3132 serde_json::to_vec(manifest).map_err(|e| PushError::ManifestUploadFailed {
3133 reason: format!("failed to serialize manifest: {e}"),
3134 })?;
3135 crate::cache::compute_digest(&manifest_json)
3136 };
3137
3138 tracing::info!(
3139 reference = %reference,
3140 digest = %digest,
3141 manifest_url = %manifest_url,
3142 "manifest pushed successfully"
3143 );
3144
3145 Ok(digest)
3146 }
3147
3148 #[instrument(
3158 name = "push_image_index_to_registry",
3159 skip(self, index, auth),
3160 fields(
3161 reference = %reference,
3162 manifests = index.manifests.len(),
3163 )
3164 )]
3165 pub async fn push_image_index_to_registry(
3166 &self,
3167 reference: &str,
3168 index: &OciImageIndex,
3169 auth: &RegistryAuth,
3170 ) -> std::result::Result<String, PushError> {
3171 let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3172 reference: reference.to_string(),
3173 })?;
3174
3175 tracing::debug!(
3176 reference = %reference,
3177 manifests = index.manifests.len(),
3178 "pushing image index to registry"
3179 );
3180
3181 self.client
3183 .auth(&image_ref, auth, RegistryOperation::Push)
3184 .await
3185 .map_err(|e| PushError::AuthenticationFailed {
3186 registry: image_ref.resolve_registry().to_string(),
3187 reason: e.to_string(),
3188 })?;
3189
3190 let manifest_url = self
3192 .client
3193 .push_manifest(&image_ref, &OciManifest::ImageIndex(index.clone()))
3194 .await
3195 .map_err(|e| PushError::ManifestUploadFailed {
3196 reason: e.to_string(),
3197 })?;
3198
3199 let digest = if let Some(digest_start) = manifest_url.rfind('@') {
3200 manifest_url[digest_start + 1..].to_string()
3201 } else {
3202 let index_json =
3203 serde_json::to_vec(index).map_err(|e| PushError::ManifestUploadFailed {
3204 reason: format!("failed to serialize image index: {e}"),
3205 })?;
3206 crate::cache::compute_digest(&index_json)
3207 };
3208
3209 tracing::info!(
3210 reference = %reference,
3211 digest = %digest,
3212 "image index pushed successfully"
3213 );
3214
3215 Ok(digest)
3216 }
3217
3218 #[instrument(
3239 name = "push_manifest_blob",
3240 skip(self, manifest_bytes, auth),
3241 fields(
3242 reference = %reference,
3243 content_type = %content_type,
3244 size = manifest_bytes.len(),
3245 )
3246 )]
3247 pub async fn push_manifest_blob(
3248 &self,
3249 reference: &str,
3250 manifest_bytes: Vec<u8>,
3251 content_type: &str,
3252 auth: &RegistryAuth,
3253 ) -> std::result::Result<String, PushError> {
3254 let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3255 reference: reference.to_string(),
3256 })?;
3257
3258 let header_value =
3259 content_type
3260 .parse()
3261 .map_err(|e: reqwest::header::InvalidHeaderValue| {
3262 PushError::ManifestUploadFailed {
3263 reason: format!("invalid Content-Type {content_type:?}: {e}"),
3264 }
3265 })?;
3266
3267 self.client
3269 .auth(&image_ref, auth, RegistryOperation::Push)
3270 .await
3271 .map_err(|e| PushError::AuthenticationFailed {
3272 registry: image_ref.resolve_registry().to_string(),
3273 reason: e.to_string(),
3274 })?;
3275
3276 let manifest_url = self
3277 .client
3278 .push_manifest_raw(&image_ref, manifest_bytes.clone(), header_value)
3279 .await
3280 .map_err(|e| PushError::ManifestUploadFailed {
3281 reason: e.to_string(),
3282 })?;
3283
3284 let digest = if let Some(digest_start) = manifest_url.rfind('@') {
3285 manifest_url[digest_start + 1..].to_string()
3286 } else {
3287 crate::cache::compute_digest(&manifest_bytes)
3288 };
3289
3290 tracing::info!(
3291 reference = %reference,
3292 digest = %digest,
3293 "manifest blob pushed successfully"
3294 );
3295
3296 Ok(digest)
3297 }
3298
3299 #[cfg(feature = "local")]
3354 #[allow(clippy::too_many_lines)]
3355 #[instrument(
3356 name = "push_wasm",
3357 skip(self, export_result, auth),
3358 fields(
3359 reference = %reference,
3360 wasm_size = export_result.wasm_size,
3361 wasi_version = %export_result.wasi_version,
3362 )
3363 )]
3364 pub async fn push_wasm(
3365 &self,
3366 reference: &str,
3367 export_result: &WasmExportResult,
3368 auth: &RegistryAuth,
3369 ) -> std::result::Result<PushResult, PushError> {
3370 use crate::wasm::{WASM_CONFIG_MEDIA_TYPE_V0, WASM_LAYER_MEDIA_TYPE_GENERIC};
3371
3372 let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3373 reference: reference.to_string(),
3374 })?;
3375
3376 tracing::info!(
3377 reference = %reference,
3378 wasm_size = export_result.wasm_size,
3379 wasi_version = %export_result.wasi_version,
3380 artifact_type = %export_result.artifact_type,
3381 "pushing WASM artifact to registry"
3382 );
3383
3384 self.client
3386 .auth(&image_ref, auth, RegistryOperation::Push)
3387 .await
3388 .map_err(|e| PushError::AuthenticationFailed {
3389 registry: image_ref.resolve_registry().to_string(),
3390 reason: e.to_string(),
3391 })?;
3392
3393 let mut blobs_pushed = Vec::new();
3394
3395 tracing::debug!(
3397 digest = %export_result.config_digest,
3398 size = export_result.config_size,
3399 "pushing config blob"
3400 );
3401 self.client
3402 .push_blob(
3403 &image_ref,
3404 &export_result.config_blob,
3405 &export_result.config_digest,
3406 )
3407 .await
3408 .map_err(|e| PushError::BlobUploadFailed {
3409 digest: export_result.config_digest.clone(),
3410 reason: e.to_string(),
3411 })?;
3412 blobs_pushed.push(export_result.config_digest.clone());
3413
3414 tracing::debug!(
3416 digest = %export_result.wasm_layer_digest,
3417 size = export_result.wasm_size,
3418 "pushing WASM layer blob"
3419 );
3420 self.client
3421 .push_blob(
3422 &image_ref,
3423 &export_result.wasm_binary,
3424 &export_result.wasm_layer_digest,
3425 )
3426 .await
3427 .map_err(|e| PushError::BlobUploadFailed {
3428 digest: export_result.wasm_layer_digest.clone(),
3429 reason: e.to_string(),
3430 })?;
3431 blobs_pushed.push(export_result.wasm_layer_digest.clone());
3432
3433 #[allow(clippy::cast_possible_wrap)]
3435 let manifest = OciImageManifest {
3436 schema_version: 2,
3437 media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
3438 artifact_type: Some(export_result.artifact_type.clone()),
3439 config: oci_client::manifest::OciDescriptor {
3440 media_type: WASM_CONFIG_MEDIA_TYPE_V0.to_string(),
3441 digest: export_result.config_digest.clone(),
3442 size: export_result.config_size as i64,
3443 urls: None,
3444 annotations: None,
3445 },
3446 layers: vec![oci_client::manifest::OciDescriptor {
3447 media_type: WASM_LAYER_MEDIA_TYPE_GENERIC.to_string(),
3448 digest: export_result.wasm_layer_digest.clone(),
3449 size: export_result.wasm_size as i64,
3450 urls: None,
3451 annotations: None,
3452 }],
3453 annotations: None,
3454 subject: None,
3455 };
3456
3457 tracing::debug!(
3459 config_digest = %export_result.config_digest,
3460 wasm_digest = %export_result.wasm_layer_digest,
3461 "pushing manifest"
3462 );
3463 let manifest_url = self
3464 .client
3465 .push_manifest(&image_ref, &OciManifest::Image(manifest))
3466 .await
3467 .map_err(|e| PushError::ManifestUploadFailed {
3468 reason: e.to_string(),
3469 })?;
3470
3471 let manifest_digest = if let Some(digest_start) = manifest_url.rfind('@') {
3473 manifest_url[digest_start + 1..].to_string()
3474 } else {
3475 export_result.manifest_digest.clone()
3476 };
3477
3478 tracing::info!(
3479 reference = %reference,
3480 manifest_digest = %manifest_digest,
3481 blobs_pushed = blobs_pushed.len(),
3482 "WASM artifact pushed successfully"
3483 );
3484
3485 Ok(PushResult {
3486 manifest_digest,
3487 blobs_pushed,
3488 reference: reference.to_string(),
3489 })
3490 }
3491
3492 #[cfg(feature = "local")]
3511 #[allow(clippy::too_many_arguments)]
3512 #[instrument(name = "push_artifact", skip(self, config_blob, layers, annotations, auth), fields(reference = %reference, artifact_type = %artifact_type, layers = layers.len()))]
3513 pub async fn push_artifact(
3514 &self,
3515 reference: &str,
3516 artifact_type: &str,
3517 config_media_type: &str,
3518 config_blob: &[u8],
3519 layers: &[ArtifactLayer],
3520 annotations: std::collections::BTreeMap<String, String>,
3521 auth: &RegistryAuth,
3522 ) -> std::result::Result<PushResult, PushError> {
3523 let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3524 reference: reference.to_string(),
3525 })?;
3526
3527 self.client
3528 .auth(&image_ref, auth, RegistryOperation::Push)
3529 .await
3530 .map_err(|e| PushError::AuthenticationFailed {
3531 registry: image_ref.resolve_registry().to_string(),
3532 reason: e.to_string(),
3533 })?;
3534
3535 let mut blobs_pushed = Vec::new();
3536
3537 let config_digest = oci_sha256_digest(config_blob);
3539 self.client
3540 .push_blob(&image_ref, config_blob, &config_digest)
3541 .await
3542 .map_err(|e| PushError::BlobUploadFailed {
3543 digest: config_digest.clone(),
3544 reason: e.to_string(),
3545 })?;
3546 blobs_pushed.push(config_digest.clone());
3547
3548 let mut layer_descriptors = Vec::with_capacity(layers.len());
3550 for layer in layers {
3551 let digest = oci_sha256_digest(&layer.data);
3552 tracing::debug!(
3553 digest = %digest,
3554 size = layer.data.len(),
3555 media_type = %layer.media_type,
3556 "pushing artifact layer blob"
3557 );
3558 self.client
3559 .push_blob(&image_ref, &layer.data, &digest)
3560 .await
3561 .map_err(|e| PushError::BlobUploadFailed {
3562 digest: digest.clone(),
3563 reason: e.to_string(),
3564 })?;
3565 blobs_pushed.push(digest.clone());
3566
3567 let layer_annotations = layer.title.as_ref().map(|title| {
3568 let mut m = std::collections::BTreeMap::new();
3569 m.insert("org.opencontainers.image.title".to_string(), title.clone());
3570 m
3571 });
3572 #[allow(clippy::cast_possible_wrap)]
3573 layer_descriptors.push(oci_client::manifest::OciDescriptor {
3574 media_type: layer.media_type.clone(),
3575 digest,
3576 size: layer.data.len() as i64,
3577 urls: None,
3578 annotations: layer_annotations,
3579 });
3580 }
3581
3582 let manifest_annotations = if annotations.is_empty() {
3583 None
3584 } else {
3585 Some(annotations)
3586 };
3587
3588 #[allow(clippy::cast_possible_wrap)]
3589 let manifest = OciImageManifest {
3590 schema_version: 2,
3591 media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
3592 artifact_type: Some(artifact_type.to_string()),
3593 config: oci_client::manifest::OciDescriptor {
3594 media_type: config_media_type.to_string(),
3595 digest: config_digest.clone(),
3596 size: config_blob.len() as i64,
3597 urls: None,
3598 annotations: None,
3599 },
3600 layers: layer_descriptors,
3601 annotations: manifest_annotations,
3602 subject: None,
3603 };
3604
3605 let manifest_url = self
3606 .client
3607 .push_manifest(&image_ref, &OciManifest::Image(manifest))
3608 .await
3609 .map_err(|e| PushError::ManifestUploadFailed {
3610 reason: e.to_string(),
3611 })?;
3612
3613 let manifest_digest = manifest_url
3614 .rfind('@')
3615 .map(|i| manifest_url[i + 1..].to_string())
3616 .unwrap_or(manifest_url);
3617
3618 tracing::info!(
3619 reference = %reference,
3620 manifest_digest = %manifest_digest,
3621 blobs_pushed = blobs_pushed.len(),
3622 "OCI artifact pushed successfully"
3623 );
3624
3625 Ok(PushResult {
3626 manifest_digest,
3627 blobs_pushed,
3628 reference: reference.to_string(),
3629 })
3630 }
3631}
3632
3633#[derive(Debug, Clone, PartialEq, Eq)]
3635pub struct Image {
3636 pub registry: String,
3638 pub repository: String,
3640 pub tag: String,
3642}
3643
3644impl std::fmt::Display for Image {
3645 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3646 write!(f, "{}/{}:{}", self.registry, self.repository, self.tag)
3647 }
3648}
3649
3650const MAX_FOREIGN_LAYER_REDIRECTS: usize = 5;
3654
3655fn is_blob_not_found(err: &oci_client::errors::OciDistributionError) -> bool {
3659 use oci_client::errors::{OciDistributionError, OciErrorCode};
3660 match err {
3661 OciDistributionError::ImageManifestNotFoundError(_) => true,
3662 OciDistributionError::ServerError { code, .. } => *code == 404,
3663 OciDistributionError::RegistryError { envelope, .. } => envelope.errors.iter().any(|e| {
3664 matches!(
3665 e.code,
3666 OciErrorCode::BlobUnknown
3667 | OciErrorCode::ManifestBlobUnknown
3668 | OciErrorCode::ManifestUnknown
3669 | OciErrorCode::NotFound
3670 | OciErrorCode::NameUnknown
3671 )
3672 }),
3673 OciDistributionError::RequestError(req_err) => {
3674 req_err.status() == Some(reqwest::StatusCode::NOT_FOUND)
3675 }
3676 _ => false,
3677 }
3678}
3679
3680pub async fn fetch_from_url(
3700 url: &str,
3701 auth: Option<(&str, &str)>,
3702 context: &str,
3703) -> Result<Vec<u8>> {
3704 let client = reqwest::Client::builder().build().map_err(|e| {
3705 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3706 "failed to build HTTP client for {context} {url}: {e}"
3707 )))
3708 })?;
3709
3710 let mut req = client.get(url);
3711 if let Some((user, pw)) = auth {
3712 req = req.basic_auth(user, Some(pw));
3713 }
3714
3715 let response = req.send().await.map_err(|e| {
3716 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3717 "{context} GET {url} failed: {e}"
3718 )))
3719 })?;
3720
3721 if !response.status().is_success() {
3722 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3723 format!("{context} {url} returned HTTP {}", response.status()),
3724 )));
3725 }
3726
3727 let bytes = response.bytes().await.map_err(|e| {
3728 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3729 "failed to read {context} body from {url}: {e}"
3730 )))
3731 })?;
3732
3733 Ok(bytes.to_vec())
3734}
3735
3736async fn fetch_blob_from_url(
3740 url: &str,
3741 expected_digest: &str,
3742 expected_size: Option<i64>,
3743) -> Result<Vec<u8>> {
3744 use sha2::{Digest, Sha256};
3745
3746 let bytes = fetch_from_url(url, None, "foreign-layer redirect").await?;
3747
3748 if bytes.is_empty() {
3749 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3750 format!("foreign-layer redirect {url} returned empty body"),
3751 )));
3752 }
3753
3754 if let Some(expected) = expected_size {
3755 if let Ok(expected_u) = u64::try_from(expected) {
3756 if bytes.len() as u64 != expected_u {
3757 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3758 format!(
3759 "foreign-layer redirect {url}: size mismatch (expected {expected}, got {})",
3760 bytes.len()
3761 ),
3762 )));
3763 }
3764 }
3765 }
3766
3767 let mut hasher = Sha256::new();
3768 hasher.update(&bytes);
3769 let actual = hex::encode(hasher.finalize());
3770 let expected = expected_digest
3771 .strip_prefix("sha256:")
3772 .unwrap_or(expected_digest);
3773 if !actual.eq_ignore_ascii_case(expected) {
3774 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3775 format!(
3776 "foreign-layer redirect {url}: digest mismatch (expected {expected_digest}, got sha256:{actual})"
3777 ),
3778 )));
3779 }
3780
3781 Ok(bytes)
3782}
3783
3784static BLOB_PART_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3787
3788fn blob_staging_filename(digest: &str) -> String {
3791 digest.replace([':', '/'], "_")
3792}
3793
3794async fn link_or_copy(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
3797 let _ = tokio::fs::remove_file(dest).await;
3798 if tokio::fs::hard_link(src, dest).await.is_ok() {
3799 return Ok(());
3800 }
3801 tokio::fs::copy(src, dest)
3802 .await
3803 .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
3804 Ok(())
3805}
3806
3807struct HashingFileWriter {
3813 file: tokio::fs::File,
3814 hasher: sha2::Sha256,
3815 written: u64,
3816}
3817
3818impl HashingFileWriter {
3819 fn new(file: tokio::fs::File) -> Self {
3820 use sha2::Digest;
3821 Self {
3822 file,
3823 hasher: sha2::Sha256::new(),
3824 written: 0,
3825 }
3826 }
3827
3828 async fn finalize(mut self) -> Result<(String, u64)> {
3831 use sha2::Digest;
3832 use tokio::io::AsyncWriteExt as _;
3833 self.file
3834 .flush()
3835 .await
3836 .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
3837 self.file
3838 .sync_all()
3839 .await
3840 .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
3841 let digest = format!("sha256:{}", hex::encode(self.hasher.finalize()));
3842 Ok((digest, self.written))
3843 }
3844}
3845
3846impl tokio::io::AsyncWrite for HashingFileWriter {
3847 fn poll_write(
3848 self: std::pin::Pin<&mut Self>,
3849 cx: &mut std::task::Context<'_>,
3850 buf: &[u8],
3851 ) -> std::task::Poll<std::io::Result<usize>> {
3852 use sha2::Digest;
3853 let me = self.get_mut();
3854 match std::pin::Pin::new(&mut me.file).poll_write(cx, buf) {
3855 std::task::Poll::Ready(Ok(n)) => {
3856 me.hasher.update(&buf[..n]);
3857 me.written += n as u64;
3858 std::task::Poll::Ready(Ok(n))
3859 }
3860 other => other,
3861 }
3862 }
3863
3864 fn poll_flush(
3865 self: std::pin::Pin<&mut Self>,
3866 cx: &mut std::task::Context<'_>,
3867 ) -> std::task::Poll<std::io::Result<()>> {
3868 let me = self.get_mut();
3869 std::pin::Pin::new(&mut me.file).poll_flush(cx)
3870 }
3871
3872 fn poll_shutdown(
3873 self: std::pin::Pin<&mut Self>,
3874 cx: &mut std::task::Context<'_>,
3875 ) -> std::task::Poll<std::io::Result<()>> {
3876 let me = self.get_mut();
3877 std::pin::Pin::new(&mut me.file).poll_shutdown(cx)
3878 }
3879}
3880
3881async fn fetch_blob_from_url_to_writer(
3886 url: &str,
3887 expected_size: Option<i64>,
3888 writer: &mut HashingFileWriter,
3889) -> Result<()> {
3890 use tokio::io::AsyncWriteExt as _;
3891
3892 let client = reqwest::Client::builder().build().map_err(|e| {
3893 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3894 "failed to build HTTP client for foreign-layer redirect {url}: {e}"
3895 )))
3896 })?;
3897
3898 let mut response = client.get(url).send().await.map_err(|e| {
3899 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3900 "foreign-layer redirect GET {url} failed: {e}"
3901 )))
3902 })?;
3903
3904 if !response.status().is_success() {
3905 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3906 format!(
3907 "foreign-layer redirect {url} returned HTTP {}",
3908 response.status()
3909 ),
3910 )));
3911 }
3912
3913 while let Some(chunk) = response.chunk().await.map_err(|e| {
3914 RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3915 "failed to read foreign-layer body from {url}: {e}"
3916 )))
3917 })? {
3918 writer
3919 .write_all(&chunk)
3920 .await
3921 .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
3922 }
3923
3924 if let Some(expected) = expected_size {
3925 if let Ok(expected_u) = u64::try_from(expected) {
3926 if writer.written != expected_u {
3927 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3928 format!(
3929 "foreign-layer redirect {url}: size mismatch (expected {expected}, got {})",
3930 writer.written
3931 ),
3932 )));
3933 }
3934 }
3935 }
3936
3937 Ok(())
3938}
3939
3940pub async fn fetch_archive_from_url(url: &str, auth: Option<(&str, &str)>) -> Result<Vec<u8>> {
3958 let bytes = fetch_from_url(url, auth, "archive fetch").await?;
3959
3960 if bytes.is_empty() {
3961 return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3962 format!("archive fetch {url} returned empty body"),
3963 )));
3964 }
3965
3966 Ok(bytes)
3967}
3968
3969#[must_use]
3977pub fn spec_auth_to_oci(auth: Option<&zlayer_spec::RegistryAuth>) -> RegistryAuth {
3978 let Some(a) = auth else {
3979 return RegistryAuth::Anonymous;
3980 };
3981 match a.auth_type {
3982 zlayer_spec::RegistryAuthType::Basic | zlayer_spec::RegistryAuthType::Token => {
3983 RegistryAuth::Basic(a.username.clone(), a.password.clone())
3984 }
3985 }
3986}
3987
3988#[cfg(feature = "local")]
4002fn inspection_puller(
4003 cache: Arc<Box<dyn BlobCacheBackend>>,
4004 local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4005) -> ImagePuller {
4006 let puller = ImagePuller::with_cache(cache);
4007 match local_registry {
4008 Some(reg) => puller.with_local_registry(reg),
4009 None => puller,
4010 }
4011}
4012
4013pub async fn fetch_image_os(
4042 image: &str,
4043 auth: Option<&zlayer_spec::RegistryAuth>,
4044) -> Result<Option<zlayer_spec::OsKind>> {
4045 let cache = crate::cache::BlobCache::new()?;
4046 let puller = ImagePuller::new(cache);
4047
4048 let oci_auth = spec_auth_to_oci(auth);
4049 puller
4050 .image_os_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4051 .await
4052}
4053
4054#[cfg(feature = "local")]
4074pub async fn fetch_image_os_in_cache(
4075 image: &str,
4076 auth: Option<&zlayer_spec::RegistryAuth>,
4077 cache: Arc<Box<dyn BlobCacheBackend>>,
4078 local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4079) -> Result<Option<zlayer_spec::OsKind>> {
4080 let puller = inspection_puller(cache, local_registry);
4081 let oci_auth = spec_auth_to_oci(auth);
4082 puller
4083 .image_os_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4084 .await
4085}
4086
4087pub async fn fetch_image_runtime_marker(
4099 image: &str,
4100 auth: Option<&zlayer_spec::RegistryAuth>,
4101) -> Result<Option<String>> {
4102 let cache = crate::cache::BlobCache::new()?;
4103 let puller = ImagePuller::new(cache);
4104
4105 let oci_auth = spec_auth_to_oci(auth);
4106 puller
4107 .image_runtime_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4108 .await
4109}
4110
4111#[cfg(feature = "local")]
4120pub async fn fetch_image_runtime_marker_in_cache(
4121 image: &str,
4122 auth: Option<&zlayer_spec::RegistryAuth>,
4123 cache: Arc<Box<dyn BlobCacheBackend>>,
4124 local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4125) -> Result<Option<String>> {
4126 let puller = inspection_puller(cache, local_registry);
4127 let oci_auth = spec_auth_to_oci(auth);
4128 puller
4129 .image_runtime_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4130 .await
4131}
4132
4133#[cfg(feature = "local")]
4145pub async fn fetch_image_os_in_cache_only(
4146 image: &str,
4147 cache: Arc<Box<dyn BlobCacheBackend>>,
4148 local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4149) -> Result<Option<zlayer_spec::OsKind>> {
4150 let puller = inspection_puller(cache, local_registry);
4151 puller.image_os_in_cache_only(image).await
4152}
4153
4154#[cfg(feature = "local")]
4161pub async fn fetch_image_runtime_marker_in_cache_only(
4162 image: &str,
4163 cache: Arc<Box<dyn BlobCacheBackend>>,
4164 local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4165) -> Result<Option<String>> {
4166 let puller = inspection_puller(cache, local_registry);
4167 puller.image_runtime_marker_in_cache_only(image).await
4168}
4169
4170pub async fn fetch_image_isolation_marker(
4184 image: &str,
4185 auth: Option<&zlayer_spec::RegistryAuth>,
4186) -> Result<Option<String>> {
4187 let cache = crate::cache::BlobCache::new()?;
4188 let puller = ImagePuller::new(cache);
4189
4190 let oci_auth = spec_auth_to_oci(auth);
4191 puller
4192 .image_isolation_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4193 .await
4194}
4195
4196#[cfg(feature = "local")]
4205pub async fn fetch_image_isolation_marker_in_cache(
4206 image: &str,
4207 auth: Option<&zlayer_spec::RegistryAuth>,
4208 cache: Arc<Box<dyn BlobCacheBackend>>,
4209 local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4210) -> Result<Option<String>> {
4211 let puller = inspection_puller(cache, local_registry);
4212 let oci_auth = spec_auth_to_oci(auth);
4213 puller
4214 .image_isolation_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4215 .await
4216}
4217
4218#[cfg(feature = "local")]
4225pub async fn fetch_image_isolation_marker_in_cache_only(
4226 image: &str,
4227 cache: Arc<Box<dyn BlobCacheBackend>>,
4228 local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4229) -> Result<Option<String>> {
4230 let puller = inspection_puller(cache, local_registry);
4231 puller.image_isolation_marker_in_cache_only(image).await
4232}
4233
4234#[cfg(test)]
4235mod tests {
4236 use super::*;
4237
4238 #[test]
4243 fn test_image_display() {
4244 let image = Image {
4245 registry: "docker.io".to_string(),
4246 repository: "library/nginx".to_string(),
4247 tag: "latest".to_string(),
4248 };
4249 assert_eq!(image.to_string(), "docker.io/library/nginx:latest");
4250 }
4251
4252 #[test]
4253 fn test_image_display_ghcr() {
4254 let image = Image {
4255 registry: "ghcr.io".to_string(),
4256 repository: "myorg/myrepo".to_string(),
4257 tag: "v1.2.3".to_string(),
4258 };
4259 assert_eq!(image.to_string(), "ghcr.io/myorg/myrepo:v1.2.3");
4260 }
4261
4262 #[test]
4263 fn test_image_display_with_nested_repo() {
4264 let image = Image {
4265 registry: "gcr.io".to_string(),
4266 repository: "project/subdir/image".to_string(),
4267 tag: "sha-abc123".to_string(),
4268 };
4269 assert_eq!(image.to_string(), "gcr.io/project/subdir/image:sha-abc123");
4270 }
4271
4272 #[test]
4273 fn test_image_clone() {
4274 let image = Image {
4275 registry: "docker.io".to_string(),
4276 repository: "library/nginx".to_string(),
4277 tag: "latest".to_string(),
4278 };
4279 let cloned = image.clone();
4280 assert_eq!(image, cloned);
4281 assert_eq!(cloned.registry, "docker.io");
4282 assert_eq!(cloned.repository, "library/nginx");
4283 assert_eq!(cloned.tag, "latest");
4284 }
4285
4286 #[test]
4287 fn test_image_equality() {
4288 let image1 = Image {
4289 registry: "docker.io".to_string(),
4290 repository: "library/nginx".to_string(),
4291 tag: "latest".to_string(),
4292 };
4293 let image2 = Image {
4294 registry: "docker.io".to_string(),
4295 repository: "library/nginx".to_string(),
4296 tag: "latest".to_string(),
4297 };
4298 let image3 = Image {
4299 registry: "ghcr.io".to_string(),
4300 repository: "library/nginx".to_string(),
4301 tag: "latest".to_string(),
4302 };
4303
4304 assert_eq!(image1, image2);
4305 assert_ne!(image1, image3);
4306 }
4307
4308 #[test]
4309 fn test_image_debug() {
4310 let image = Image {
4311 registry: "docker.io".to_string(),
4312 repository: "test".to_string(),
4313 tag: "v1".to_string(),
4314 };
4315 let debug_str = format!("{image:?}");
4316 assert!(debug_str.contains("Image"));
4317 assert!(debug_str.contains("docker.io"));
4318 assert!(debug_str.contains("test"));
4319 assert!(debug_str.contains("v1"));
4320 }
4321
4322 #[test]
4327 fn test_push_error_display_authentication_failed() {
4328 let err = PushError::AuthenticationFailed {
4329 registry: "ghcr.io".to_string(),
4330 reason: "invalid token".to_string(),
4331 };
4332 assert_eq!(
4333 err.to_string(),
4334 "authentication failed for registry ghcr.io: invalid token"
4335 );
4336 }
4337
4338 #[test]
4339 fn test_push_error_display_authentication_failed_empty_reason() {
4340 let err = PushError::AuthenticationFailed {
4341 registry: "docker.io".to_string(),
4342 reason: String::new(),
4343 };
4344 assert_eq!(
4345 err.to_string(),
4346 "authentication failed for registry docker.io: "
4347 );
4348 }
4349
4350 #[test]
4351 fn test_push_error_display_authentication_failed_long_reason() {
4352 let long_reason = "a]".repeat(100);
4353 let err = PushError::AuthenticationFailed {
4354 registry: "ghcr.io".to_string(),
4355 reason: long_reason.clone(),
4356 };
4357 assert!(err.to_string().contains(&long_reason));
4358 }
4359
4360 #[test]
4361 fn test_push_error_display_blob_upload_failed() {
4362 let err = PushError::BlobUploadFailed {
4363 digest: "sha256:abc123".to_string(),
4364 reason: "connection reset".to_string(),
4365 };
4366 assert_eq!(
4367 err.to_string(),
4368 "failed to upload blob sha256:abc123: connection reset"
4369 );
4370 }
4371
4372 #[test]
4373 fn test_push_error_display_blob_upload_failed_with_full_digest() {
4374 let digest =
4375 "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".to_string();
4376 let err = PushError::BlobUploadFailed {
4377 digest: digest.clone(),
4378 reason: "timeout".to_string(),
4379 };
4380 assert!(err.to_string().contains(&digest));
4381 assert!(err.to_string().contains("timeout"));
4382 }
4383
4384 #[test]
4385 fn test_push_error_display_manifest_upload_failed() {
4386 let err = PushError::ManifestUploadFailed {
4387 reason: "invalid manifest".to_string(),
4388 };
4389 assert_eq!(
4390 err.to_string(),
4391 "failed to upload manifest: invalid manifest"
4392 );
4393 }
4394
4395 #[test]
4396 fn test_push_error_display_manifest_upload_failed_json_error() {
4397 let err = PushError::ManifestUploadFailed {
4398 reason: "invalid JSON: unexpected token at position 42".to_string(),
4399 };
4400 assert!(err.to_string().contains("invalid JSON"));
4401 assert!(err.to_string().contains("position 42"));
4402 }
4403
4404 #[test]
4405 fn test_push_error_display_network_error() {
4406 let err = PushError::NetworkError("timeout".to_string());
4407 assert_eq!(err.to_string(), "network error: timeout");
4408 }
4409
4410 #[test]
4411 fn test_push_error_display_network_error_connection_refused() {
4412 let err = PushError::NetworkError("connection refused: 127.0.0.1:5000".to_string());
4413 assert_eq!(
4414 err.to_string(),
4415 "network error: connection refused: 127.0.0.1:5000"
4416 );
4417 }
4418
4419 #[test]
4420 fn test_push_error_display_network_error_dns() {
4421 let err =
4422 PushError::NetworkError("DNS resolution failed for registry.example.com".to_string());
4423 assert!(err.to_string().contains("DNS resolution failed"));
4424 }
4425
4426 #[test]
4427 fn test_push_error_display_invalid_reference() {
4428 let err = PushError::InvalidReference {
4429 reference: "invalid::ref".to_string(),
4430 };
4431 assert_eq!(err.to_string(), "invalid image reference: invalid::ref");
4432 }
4433
4434 #[test]
4435 fn test_push_error_display_invalid_reference_empty() {
4436 let err = PushError::InvalidReference {
4437 reference: String::new(),
4438 };
4439 assert_eq!(err.to_string(), "invalid image reference: ");
4440 }
4441
4442 #[test]
4443 fn test_push_error_display_invalid_reference_special_chars() {
4444 let err = PushError::InvalidReference {
4445 reference: "ghcr.io/test/image:tag@sha256:abc".to_string(),
4446 };
4447 assert!(err
4448 .to_string()
4449 .contains("ghcr.io/test/image:tag@sha256:abc"));
4450 }
4451
4452 #[test]
4457 fn test_push_error_debug_authentication_failed() {
4458 let err = PushError::AuthenticationFailed {
4459 registry: "ghcr.io".to_string(),
4460 reason: "invalid token".to_string(),
4461 };
4462 let debug_str = format!("{err:?}");
4463 assert!(debug_str.contains("AuthenticationFailed"));
4464 assert!(debug_str.contains("ghcr.io"));
4465 assert!(debug_str.contains("invalid token"));
4466 }
4467
4468 #[test]
4469 fn test_push_error_debug_blob_upload_failed() {
4470 let err = PushError::BlobUploadFailed {
4471 digest: "sha256:abc123".to_string(),
4472 reason: "network error".to_string(),
4473 };
4474 let debug_str = format!("{err:?}");
4475 assert!(debug_str.contains("BlobUploadFailed"));
4476 assert!(debug_str.contains("sha256:abc123"));
4477 assert!(debug_str.contains("network error"));
4478 }
4479
4480 #[test]
4481 fn test_push_error_debug_manifest_upload_failed() {
4482 let err = PushError::ManifestUploadFailed {
4483 reason: "schema validation failed".to_string(),
4484 };
4485 let debug_str = format!("{err:?}");
4486 assert!(debug_str.contains("ManifestUploadFailed"));
4487 assert!(debug_str.contains("schema validation failed"));
4488 }
4489
4490 #[test]
4491 fn test_push_error_debug_network_error() {
4492 let err = PushError::NetworkError("connection timed out".to_string());
4493 let debug_str = format!("{err:?}");
4494 assert!(debug_str.contains("NetworkError"));
4495 assert!(debug_str.contains("connection timed out"));
4496 }
4497
4498 #[test]
4499 fn test_push_error_debug_invalid_reference() {
4500 let err = PushError::InvalidReference {
4501 reference: "bad-ref".to_string(),
4502 };
4503 let debug_str = format!("{err:?}");
4504 assert!(debug_str.contains("InvalidReference"));
4505 assert!(debug_str.contains("bad-ref"));
4506 }
4507
4508 #[test]
4509 fn test_push_error_debug_oci_error() {
4510 let oci_err =
4512 oci_client::errors::OciDistributionError::GenericError(Some("test error".to_string()));
4513 let err = PushError::OciError(oci_err);
4514 let debug_str = format!("{err:?}");
4515 assert!(debug_str.contains("OciError"));
4516 }
4517
4518 #[test]
4523 fn test_push_error_from_oci_generic_error() {
4524 let oci_err = oci_client::errors::OciDistributionError::GenericError(Some(
4525 "generic error message".to_string(),
4526 ));
4527 let push_err: PushError = oci_err.into();
4528 match push_err {
4529 PushError::OciError(inner) => {
4530 assert!(inner.to_string().contains("generic error message"));
4531 }
4532 _ => panic!("Expected OciError variant"),
4533 }
4534 }
4535
4536 #[test]
4537 fn test_push_error_from_oci_config_conversion_error() {
4538 let oci_err = oci_client::errors::OciDistributionError::ConfigConversionError(
4539 "config conversion failed".to_string(),
4540 );
4541 let push_err: PushError = oci_err.into();
4542 match push_err {
4543 PushError::OciError(inner) => {
4544 assert!(inner.to_string().contains("config conversion"));
4545 }
4546 _ => panic!("Expected OciError variant"),
4547 }
4548 }
4549
4550 #[test]
4551 fn test_push_error_from_oci_manifest_parsing_error() {
4552 let oci_err = oci_client::errors::OciDistributionError::ManifestParsingError(
4553 "invalid manifest JSON".to_string(),
4554 );
4555 let push_err: PushError = oci_err.into();
4556 match push_err {
4557 PushError::OciError(inner) => {
4558 assert!(
4559 inner.to_string().contains("manifest") || inner.to_string().contains("JSON")
4560 );
4561 }
4562 _ => panic!("Expected OciError variant"),
4563 }
4564 }
4565
4566 #[test]
4567 fn test_push_error_from_oci_image_manifest_not_found() {
4568 let oci_err = oci_client::errors::OciDistributionError::ImageManifestNotFoundError(
4569 "image:tag".to_string(),
4570 );
4571 let push_err: PushError = oci_err.into();
4572 match push_err {
4573 PushError::OciError(inner) => {
4574 assert!(inner.to_string().contains("image:tag"));
4575 }
4576 _ => panic!("Expected OciError variant"),
4577 }
4578 }
4579
4580 #[test]
4581 fn test_push_error_from_oci_url_parse_error() {
4582 let oci_err =
4583 oci_client::errors::OciDistributionError::UrlParseError("invalid URL".to_string());
4584 let push_err: PushError = oci_err.into();
4585 match push_err {
4586 PushError::OciError(inner) => {
4587 assert!(inner.to_string().contains("URL"));
4588 }
4589 _ => panic!("Expected OciError variant"),
4590 }
4591 }
4592
4593 #[test]
4594 fn test_push_error_from_oci_unsupported_schema_version() {
4595 let oci_err = oci_client::errors::OciDistributionError::UnsupportedSchemaVersionError(99);
4596 let push_err: PushError = oci_err.into();
4597 match push_err {
4598 PushError::OciError(inner) => {
4599 let _ = inner.to_string();
4601 }
4602 _ => panic!("Expected OciError variant"),
4603 }
4604 }
4605
4606 #[test]
4607 fn test_push_error_from_oci_unsupported_media_type() {
4608 let oci_err = oci_client::errors::OciDistributionError::UnsupportedMediaTypeError(
4609 "application/unknown".to_string(),
4610 );
4611 let push_err: PushError = oci_err.into();
4612 match push_err {
4613 PushError::OciError(inner) => {
4614 assert!(inner.to_string().contains("application/unknown"));
4615 }
4616 _ => panic!("Expected OciError variant"),
4617 }
4618 }
4619
4620 #[test]
4621 fn test_push_error_oci_error_display() {
4622 let oci_err = oci_client::errors::OciDistributionError::GenericError(Some(
4623 "version mismatch".to_string(),
4624 ));
4625 let push_err = PushError::OciError(oci_err);
4626 assert!(push_err.to_string().contains("OCI distribution error"));
4627 }
4628
4629 #[test]
4630 fn test_push_error_from_oci_spec_violation() {
4631 let oci_err = oci_client::errors::OciDistributionError::SpecViolationError(
4632 "OCI spec violation".to_string(),
4633 );
4634 let push_err: PushError = oci_err.into();
4635 match push_err {
4636 PushError::OciError(inner) => {
4637 assert!(
4638 inner.to_string().contains("spec") || inner.to_string().contains("violation")
4639 );
4640 }
4641 _ => panic!("Expected OciError variant"),
4642 }
4643 }
4644
4645 #[test]
4646 fn test_push_error_from_oci_versioned_parsing_error() {
4647 let oci_err = oci_client::errors::OciDistributionError::VersionedParsingError(
4648 "failed to parse versioned content".to_string(),
4649 );
4650 let push_err: PushError = oci_err.into();
4651 match push_err {
4652 PushError::OciError(inner) => {
4653 let _ = inner.to_string();
4654 }
4655 _ => panic!("Expected OciError variant"),
4656 }
4657 }
4658
4659 #[test]
4660 fn test_push_error_from_oci_registry_token_decode() {
4661 let oci_err = oci_client::errors::OciDistributionError::RegistryTokenDecodeError(
4662 "invalid token format".to_string(),
4663 );
4664 let push_err: PushError = oci_err.into();
4665 match push_err {
4666 PushError::OciError(inner) => {
4667 assert!(inner.to_string().contains("token"));
4668 }
4669 _ => panic!("Expected OciError variant"),
4670 }
4671 }
4672
4673 #[test]
4674 fn test_push_error_from_oci_incompatible_layer_media_type() {
4675 let oci_err = oci_client::errors::OciDistributionError::IncompatibleLayerMediaTypeError(
4676 "application/vnd.incompatible".to_string(),
4677 );
4678 let push_err: PushError = oci_err.into();
4679 match push_err {
4680 PushError::OciError(inner) => {
4681 assert!(
4682 inner.to_string().contains("incompatible")
4683 || inner.to_string().contains("layer")
4684 );
4685 }
4686 _ => panic!("Expected OciError variant"),
4687 }
4688 }
4689
4690 #[test]
4695 fn test_push_result_creation_all_fields() {
4696 let result = PushResult {
4697 manifest_digest: "sha256:abc123".to_string(),
4698 blobs_pushed: vec!["sha256:def456".to_string(), "sha256:ghi789".to_string()],
4699 reference: "ghcr.io/test/image:v1.0".to_string(),
4700 };
4701 assert_eq!(result.manifest_digest, "sha256:abc123");
4702 assert_eq!(result.blobs_pushed.len(), 2);
4703 assert_eq!(result.blobs_pushed[0], "sha256:def456");
4704 assert_eq!(result.blobs_pushed[1], "sha256:ghi789");
4705 assert_eq!(result.reference, "ghcr.io/test/image:v1.0");
4706 }
4707
4708 #[test]
4709 fn test_push_result_creation_empty_blobs() {
4710 let result = PushResult {
4711 manifest_digest: "sha256:empty".to_string(),
4712 blobs_pushed: vec![],
4713 reference: "docker.io/test:latest".to_string(),
4714 };
4715 assert!(result.blobs_pushed.is_empty());
4716 assert_eq!(result.manifest_digest, "sha256:empty");
4717 }
4718
4719 #[test]
4720 fn test_push_result_creation_single_blob() {
4721 let result = PushResult {
4722 manifest_digest: "sha256:single".to_string(),
4723 blobs_pushed: vec!["sha256:only_one".to_string()],
4724 reference: "registry.example.com/repo:tag".to_string(),
4725 };
4726 assert_eq!(result.blobs_pushed.len(), 1);
4727 }
4728
4729 #[test]
4730 fn test_push_result_creation_many_blobs() {
4731 let blobs: Vec<String> = (0..100).map(|i| format!("sha256:blob{i:03}")).collect();
4732 let result = PushResult {
4733 manifest_digest: "sha256:many".to_string(),
4734 blobs_pushed: blobs,
4735 reference: "test/image:v1".to_string(),
4736 };
4737 assert_eq!(result.blobs_pushed.len(), 100);
4738 assert_eq!(result.blobs_pushed[0], "sha256:blob000");
4739 assert_eq!(result.blobs_pushed[99], "sha256:blob099");
4740 }
4741
4742 #[test]
4743 fn test_push_result_clone() {
4744 let result = PushResult {
4745 manifest_digest: "sha256:abc".to_string(),
4746 blobs_pushed: vec!["sha256:def".to_string()],
4747 reference: "test:v1".to_string(),
4748 };
4749 let cloned = result.clone();
4750 assert_eq!(result.manifest_digest, cloned.manifest_digest);
4751 assert_eq!(result.blobs_pushed, cloned.blobs_pushed);
4752 assert_eq!(result.reference, cloned.reference);
4753 }
4754
4755 #[test]
4756 fn test_push_result_clone_independence() {
4757 let result = PushResult {
4758 manifest_digest: "sha256:original".to_string(),
4759 blobs_pushed: vec!["sha256:blob1".to_string()],
4760 reference: "original:v1".to_string(),
4761 };
4762 let mut cloned = result.clone();
4763 cloned.manifest_digest = "sha256:modified".to_string();
4764 cloned.blobs_pushed.push("sha256:blob2".to_string());
4765
4766 assert_eq!(result.manifest_digest, "sha256:original");
4768 assert_eq!(result.blobs_pushed.len(), 1);
4769
4770 assert_eq!(cloned.manifest_digest, "sha256:modified");
4772 assert_eq!(cloned.blobs_pushed.len(), 2);
4773 }
4774
4775 #[test]
4776 fn test_push_result_debug() {
4777 let result = PushResult {
4778 manifest_digest: "sha256:test".to_string(),
4779 blobs_pushed: vec!["sha256:blob1".to_string(), "sha256:blob2".to_string()],
4780 reference: "ghcr.io/org/repo:tag".to_string(),
4781 };
4782 let debug_str = format!("{result:?}");
4783 assert!(debug_str.contains("PushResult"));
4784 assert!(debug_str.contains("sha256:test"));
4785 assert!(debug_str.contains("sha256:blob1"));
4786 assert!(debug_str.contains("sha256:blob2"));
4787 assert!(debug_str.contains("ghcr.io/org/repo:tag"));
4788 }
4789
4790 #[test]
4791 fn test_push_result_with_full_sha256_digest() {
4792 let full_digest = "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
4793 let result = PushResult {
4794 manifest_digest: full_digest.to_string(),
4795 blobs_pushed: vec![full_digest.to_string()],
4796 reference: "test:latest".to_string(),
4797 };
4798 assert_eq!(result.manifest_digest.len(), 71); }
4800
4801 #[test]
4806 fn test_valid_reference_parsing_docker_hub() {
4807 let reference = "docker.io/library/nginx:latest";
4808 let parsed: Result<Reference, _> = reference.parse();
4809 assert!(parsed.is_ok());
4810 }
4811
4812 #[test]
4813 fn test_valid_reference_parsing_ghcr() {
4814 let reference = "ghcr.io/myorg/myrepo:v1.0.0";
4815 let parsed: Result<Reference, _> = reference.parse();
4816 assert!(parsed.is_ok());
4817 }
4818
4819 #[test]
4820 fn test_valid_reference_parsing_with_digest() {
4821 let reference = "ghcr.io/test/image@sha256:abc123def456789012345678901234567890123456789012345678901234";
4822 let parsed: Result<Reference, _> = reference.parse();
4823 let _ = parsed;
4826 }
4827
4828 #[test]
4829 fn test_valid_reference_parsing_nested_repo() {
4830 let reference = "gcr.io/project-id/subdir/image:tag";
4831 let parsed: Result<Reference, _> = reference.parse();
4832 assert!(parsed.is_ok());
4833 }
4834
4835 #[test]
4836 fn test_invalid_reference_empty() {
4837 let reference = "";
4838 let parsed: Result<Reference, _> = reference.parse();
4839 assert!(parsed.is_err());
4840 }
4841
4842 #[test]
4843 fn test_invalid_reference_double_colon() {
4844 let reference = "invalid::reference";
4845 let parsed: Result<Reference, _> = reference.parse();
4846 assert!(parsed.is_err());
4847 }
4848
4849 #[test]
4854 fn test_push_error_authentication_failed_construction() {
4855 let err = PushError::AuthenticationFailed {
4856 registry: "test.registry.io".to_string(),
4857 reason: "credentials expired".to_string(),
4858 };
4859 let display = err.to_string();
4861 assert!(display.contains("test.registry.io"));
4862 assert!(display.contains("credentials expired"));
4863 }
4864
4865 #[test]
4866 fn test_push_error_blob_upload_failed_construction() {
4867 let digest = "sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
4868 let err = PushError::BlobUploadFailed {
4869 digest: digest.to_string(),
4870 reason: "server returned 500".to_string(),
4871 };
4872 let display = err.to_string();
4873 assert!(display.contains(digest));
4874 assert!(display.contains("server returned 500"));
4875 }
4876
4877 #[test]
4878 fn test_push_error_manifest_upload_failed_construction() {
4879 let err = PushError::ManifestUploadFailed {
4880 reason: "manifest already exists with different content".to_string(),
4881 };
4882 let display = err.to_string();
4883 assert!(display.contains("manifest already exists"));
4884 }
4885
4886 #[test]
4887 fn test_push_error_network_error_construction() {
4888 let err = PushError::NetworkError("TLS handshake failed".to_string());
4889 let display = err.to_string();
4890 assert!(display.contains("TLS handshake failed"));
4891 }
4892
4893 #[test]
4894 fn test_push_error_invalid_reference_construction() {
4895 let err = PushError::InvalidReference {
4896 reference: "not/a/valid/reference!!!".to_string(),
4897 };
4898 let display = err.to_string();
4899 assert!(display.contains("not/a/valid/reference!!!"));
4900 }
4901
4902 #[test]
4907 fn test_push_error_is_authentication_failed() {
4908 let err = PushError::AuthenticationFailed {
4909 registry: "test".to_string(),
4910 reason: "test".to_string(),
4911 };
4912 assert!(matches!(err, PushError::AuthenticationFailed { .. }));
4913 assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
4914 assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
4915 assert!(!matches!(err, PushError::NetworkError(_)));
4916 assert!(!matches!(err, PushError::InvalidReference { .. }));
4917 assert!(!matches!(err, PushError::OciError(_)));
4918 }
4919
4920 #[test]
4921 fn test_push_error_is_blob_upload_failed() {
4922 let err = PushError::BlobUploadFailed {
4923 digest: "test".to_string(),
4924 reason: "test".to_string(),
4925 };
4926 assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
4927 assert!(matches!(err, PushError::BlobUploadFailed { .. }));
4928 assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
4929 assert!(!matches!(err, PushError::NetworkError(_)));
4930 assert!(!matches!(err, PushError::InvalidReference { .. }));
4931 assert!(!matches!(err, PushError::OciError(_)));
4932 }
4933
4934 #[test]
4935 fn test_push_error_is_manifest_upload_failed() {
4936 let err = PushError::ManifestUploadFailed {
4937 reason: "test".to_string(),
4938 };
4939 assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
4940 assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
4941 assert!(matches!(err, PushError::ManifestUploadFailed { .. }));
4942 assert!(!matches!(err, PushError::NetworkError(_)));
4943 assert!(!matches!(err, PushError::InvalidReference { .. }));
4944 assert!(!matches!(err, PushError::OciError(_)));
4945 }
4946
4947 #[test]
4948 fn test_push_error_is_network_error() {
4949 let err = PushError::NetworkError("test".to_string());
4950 assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
4951 assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
4952 assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
4953 assert!(matches!(err, PushError::NetworkError(_)));
4954 assert!(!matches!(err, PushError::InvalidReference { .. }));
4955 assert!(!matches!(err, PushError::OciError(_)));
4956 }
4957
4958 #[test]
4959 fn test_push_error_is_invalid_reference() {
4960 let err = PushError::InvalidReference {
4961 reference: "test".to_string(),
4962 };
4963 assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
4964 assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
4965 assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
4966 assert!(!matches!(err, PushError::NetworkError(_)));
4967 assert!(matches!(err, PushError::InvalidReference { .. }));
4968 assert!(!matches!(err, PushError::OciError(_)));
4969 }
4970
4971 #[test]
4972 fn test_push_error_is_oci_error() {
4973 let oci_err =
4974 oci_client::errors::OciDistributionError::GenericError(Some("test".to_string()));
4975 let err = PushError::OciError(oci_err);
4976 assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
4977 assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
4978 assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
4979 assert!(!matches!(err, PushError::NetworkError(_)));
4980 assert!(!matches!(err, PushError::InvalidReference { .. }));
4981 assert!(matches!(err, PushError::OciError(_)));
4982 }
4983
4984 #[test]
4989 fn test_push_error_implements_error_trait() {
4990 let err = PushError::NetworkError("test".to_string());
4991 let _: &dyn std::error::Error = &err;
4993 }
4994
4995 #[test]
4996 fn test_push_error_source_for_oci_error() {
4997 use std::error::Error;
4998 let oci_err =
4999 oci_client::errors::OciDistributionError::GenericError(Some("test".to_string()));
5000 let err = PushError::OciError(oci_err);
5001 let source = err.source();
5003 assert!(source.is_some());
5004 }
5005
5006 #[test]
5007 fn test_push_error_source_for_other_variants() {
5008 use std::error::Error;
5009
5010 let err1 = PushError::AuthenticationFailed {
5011 registry: "test".to_string(),
5012 reason: "test".to_string(),
5013 };
5014 assert!(err1.source().is_none());
5015
5016 let err2 = PushError::BlobUploadFailed {
5017 digest: "test".to_string(),
5018 reason: "test".to_string(),
5019 };
5020 assert!(err2.source().is_none());
5021
5022 let err3 = PushError::ManifestUploadFailed {
5023 reason: "test".to_string(),
5024 };
5025 assert!(err3.source().is_none());
5026
5027 let err4 = PushError::NetworkError("test".to_string());
5028 assert!(err4.source().is_none());
5029
5030 let err5 = PushError::InvalidReference {
5031 reference: "test".to_string(),
5032 };
5033 assert!(err5.source().is_none());
5034 }
5035
5036 #[test]
5041 fn test_image_puller_creation_with_blob_cache() {
5042 let cache = crate::cache::BlobCache::new().unwrap();
5043 let puller = ImagePuller::new(cache);
5044 let _ = puller;
5046 }
5047
5048 #[test]
5049 fn test_image_puller_with_concurrency_limit() {
5050 let cache = crate::cache::BlobCache::new().unwrap();
5051 let puller = ImagePuller::new(cache).with_concurrency_limit(5);
5052 let _ = puller;
5053 }
5054
5055 #[test]
5056 fn test_image_puller_with_concurrency_limit_one() {
5057 let cache = crate::cache::BlobCache::new().unwrap();
5058 let puller = ImagePuller::new(cache).with_concurrency_limit(1);
5059 let _ = puller;
5060 }
5061
5062 #[test]
5063 fn test_image_puller_with_shared_cache() {
5064 let cache = crate::cache::BlobCache::new().unwrap();
5065 let shared: Arc<Box<dyn BlobCacheBackend>> = Arc::new(Box::new(cache));
5066 let puller = ImagePuller::with_cache(shared);
5067 let _ = puller;
5068 }
5069
5070 #[tokio::test]
5075 async fn test_push_blob_invalid_reference_returns_error() {
5076 let cache = crate::cache::BlobCache::new().unwrap();
5077 let puller = ImagePuller::new(cache);
5078
5079 let result = puller
5080 .push_blob(
5081 "invalid::reference",
5082 "sha256:test",
5083 b"test data",
5084 "application/octet-stream",
5085 &RegistryAuth::Anonymous,
5086 )
5087 .await;
5088
5089 assert!(result.is_err());
5090 match result {
5091 Err(PushError::InvalidReference { reference }) => {
5092 assert_eq!(reference, "invalid::reference");
5093 }
5094 other => panic!("Expected InvalidReference error, got {other:?}"),
5095 }
5096 }
5097
5098 #[tokio::test]
5099 async fn test_push_blob_empty_reference_returns_error() {
5100 let cache = crate::cache::BlobCache::new().unwrap();
5101 let puller = ImagePuller::new(cache);
5102
5103 let result = puller
5104 .push_blob(
5105 "",
5106 "sha256:test",
5107 b"test data",
5108 "application/octet-stream",
5109 &RegistryAuth::Anonymous,
5110 )
5111 .await;
5112
5113 assert!(result.is_err());
5114 match result {
5115 Err(PushError::InvalidReference { reference }) => {
5116 assert!(reference.is_empty());
5117 }
5118 other => panic!("Expected InvalidReference error, got {other:?}"),
5119 }
5120 }
5121
5122 #[tokio::test]
5123 async fn test_push_manifest_invalid_reference_returns_error() {
5124 let cache = crate::cache::BlobCache::new().unwrap();
5125 let puller = ImagePuller::new(cache);
5126
5127 let manifest = oci_client::manifest::OciImageManifest::default();
5128
5129 let result = puller
5130 .push_manifest_to_registry("invalid::reference", &manifest, &RegistryAuth::Anonymous)
5131 .await;
5132
5133 assert!(result.is_err());
5134 match result {
5135 Err(PushError::InvalidReference { reference }) => {
5136 assert_eq!(reference, "invalid::reference");
5137 }
5138 other => panic!("Expected InvalidReference error, got {other:?}"),
5139 }
5140 }
5141
5142 #[tokio::test]
5143 async fn test_push_manifest_empty_reference_returns_error() {
5144 let cache = crate::cache::BlobCache::new().unwrap();
5145 let puller = ImagePuller::new(cache);
5146
5147 let manifest = oci_client::manifest::OciImageManifest::default();
5148
5149 let result = puller
5150 .push_manifest_to_registry("", &manifest, &RegistryAuth::Anonymous)
5151 .await;
5152
5153 assert!(result.is_err());
5154 match result {
5155 Err(PushError::InvalidReference { reference }) => {
5156 assert!(reference.is_empty());
5157 }
5158 other => panic!("Expected InvalidReference error, got {other:?}"),
5159 }
5160 }
5161
5162 #[cfg(feature = "local")]
5167 #[tokio::test]
5168 async fn test_push_wasm_invalid_reference_returns_error() {
5169 use crate::wasm::WasiVersion;
5170 use crate::wasm_export::WasmExportResult;
5171
5172 let cache = crate::cache::BlobCache::new().unwrap();
5173 let puller = ImagePuller::new(cache);
5174
5175 let export_result = WasmExportResult {
5176 manifest_digest: "sha256:test".to_string(),
5177 manifest_size: 100,
5178 wasm_layer_digest: "sha256:wasm".to_string(),
5179 wasm_size: 1000,
5180 config_digest: "sha256:config".to_string(),
5181 config_size: 2,
5182 wasi_version: WasiVersion::Preview1,
5183 artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
5184 manifest_json: b"{}".to_vec(),
5185 config_blob: b"{}".to_vec(),
5186 wasm_binary: vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00],
5187 };
5188
5189 let result = puller
5190 .push_wasm(
5191 "invalid::reference",
5192 &export_result,
5193 &RegistryAuth::Anonymous,
5194 )
5195 .await;
5196
5197 assert!(result.is_err());
5198 match result {
5199 Err(PushError::InvalidReference { reference }) => {
5200 assert_eq!(reference, "invalid::reference");
5201 }
5202 other => panic!("Expected InvalidReference error, got {other:?}"),
5203 }
5204 }
5205
5206 #[cfg(feature = "local")]
5207 #[tokio::test]
5208 async fn test_push_wasm_empty_reference_returns_error() {
5209 use crate::wasm::WasiVersion;
5210 use crate::wasm_export::WasmExportResult;
5211
5212 let cache = crate::cache::BlobCache::new().unwrap();
5213 let puller = ImagePuller::new(cache);
5214
5215 let export_result = WasmExportResult {
5216 manifest_digest: "sha256:test".to_string(),
5217 manifest_size: 100,
5218 wasm_layer_digest: "sha256:wasm".to_string(),
5219 wasm_size: 1000,
5220 config_digest: "sha256:config".to_string(),
5221 config_size: 2,
5222 wasi_version: WasiVersion::Preview2,
5223 artifact_type: "application/vnd.wasm.component.v1+wasm".to_string(),
5224 manifest_json: b"{}".to_vec(),
5225 config_blob: b"{}".to_vec(),
5226 wasm_binary: vec![0x00, 0x61, 0x73, 0x6d, 0x0d, 0x00, 0x01, 0x00],
5227 };
5228
5229 let result = puller
5230 .push_wasm("", &export_result, &RegistryAuth::Anonymous)
5231 .await;
5232
5233 assert!(result.is_err());
5234 match result {
5235 Err(PushError::InvalidReference { reference }) => {
5236 assert!(reference.is_empty());
5237 }
5238 other => panic!("Expected InvalidReference error, got {other:?}"),
5239 }
5240 }
5241
5242 #[cfg(feature = "local")]
5247 #[test]
5248 fn test_wasm_export_result_debug_formatting() {
5249 use crate::wasm::WasiVersion;
5250 use crate::wasm_export::WasmExportResult;
5251
5252 let result = WasmExportResult {
5253 manifest_digest: "sha256:manifest".to_string(),
5254 manifest_size: 500,
5255 wasm_layer_digest: "sha256:layer".to_string(),
5256 wasm_size: 10000,
5257 config_digest: "sha256:cfg".to_string(),
5258 config_size: 2,
5259 wasi_version: WasiVersion::Preview2,
5260 artifact_type: "application/vnd.wasm.component.v1+wasm".to_string(),
5261 manifest_json: vec![],
5262 config_blob: vec![],
5263 wasm_binary: vec![],
5264 };
5265
5266 let debug_str = format!("{result:?}");
5267 assert!(debug_str.contains("WasmExportResult"));
5268 assert!(debug_str.contains("sha256:manifest"));
5269 assert!(debug_str.contains("sha256:layer"));
5270 assert!(debug_str.contains("Preview2"));
5271 }
5272
5273 #[cfg(feature = "local")]
5274 #[test]
5275 fn test_wasm_export_result_clone_independence() {
5276 use crate::wasm::WasiVersion;
5277 use crate::wasm_export::WasmExportResult;
5278
5279 let result = WasmExportResult {
5280 manifest_digest: "sha256:original".to_string(),
5281 manifest_size: 100,
5282 wasm_layer_digest: "sha256:wasm".to_string(),
5283 wasm_size: 1000,
5284 config_digest: "sha256:config".to_string(),
5285 config_size: 2,
5286 wasi_version: WasiVersion::Preview1,
5287 artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
5288 manifest_json: b"{}".to_vec(),
5289 config_blob: b"{}".to_vec(),
5290 wasm_binary: vec![0x00, 0x61, 0x73, 0x6d],
5291 };
5292
5293 let mut cloned = result.clone();
5294 cloned.manifest_digest = "sha256:modified".to_string();
5295
5296 assert_eq!(result.manifest_digest, "sha256:original");
5298 assert_eq!(cloned.manifest_digest, "sha256:modified");
5299 }
5300
5301 #[cfg(feature = "local")]
5302 #[test]
5303 fn test_wasm_export_result_all_fields_populated() {
5304 use crate::wasm::WasiVersion;
5305 use crate::wasm_export::WasmExportResult;
5306
5307 let wasm_binary = vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
5308 let config_blob = b"{}".to_vec();
5309 let manifest_json = b"{\"schemaVersion\": 2}".to_vec();
5310
5311 let result = WasmExportResult {
5312 manifest_digest: "sha256:abc".to_string(),
5313 manifest_size: manifest_json.len() as u64,
5314 wasm_layer_digest: "sha256:def".to_string(),
5315 wasm_size: wasm_binary.len() as u64,
5316 config_digest: "sha256:ghi".to_string(),
5317 config_size: config_blob.len() as u64,
5318 wasi_version: WasiVersion::Preview1,
5319 artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
5320 manifest_json: manifest_json.clone(),
5321 config_blob: config_blob.clone(),
5322 wasm_binary: wasm_binary.clone(),
5323 };
5324
5325 assert!(result.manifest_digest.starts_with("sha256:"));
5327 assert_eq!(result.manifest_size, manifest_json.len() as u64);
5328 assert!(result.wasm_layer_digest.starts_with("sha256:"));
5329 assert_eq!(result.wasm_size, wasm_binary.len() as u64);
5330 assert!(result.config_digest.starts_with("sha256:"));
5331 assert_eq!(result.config_size, config_blob.len() as u64);
5332 assert_eq!(result.wasi_version, WasiVersion::Preview1);
5333 assert!(result.artifact_type.contains("wasm"));
5334 assert!(!result.manifest_json.is_empty());
5335 assert!(!result.config_blob.is_empty());
5336 assert!(!result.wasm_binary.is_empty());
5337 }
5338
5339 #[test]
5346 fn test_push_flow_documentation_blob_before_manifest() {
5347 }
5358
5359 #[test]
5360 fn test_push_flow_documentation_authentication_order() {
5361 }
5374
5375 #[test]
5376 fn test_push_result_blobs_pushed_order() {
5377 let result = PushResult {
5384 manifest_digest: "sha256:manifest".to_string(),
5385 blobs_pushed: vec!["sha256:config".to_string(), "sha256:wasm_layer".to_string()],
5386 reference: "test:v1".to_string(),
5387 };
5388
5389 assert_eq!(result.blobs_pushed.len(), 2);
5390 assert!(result.blobs_pushed[0].contains("config"));
5392 assert!(result.blobs_pushed[1].contains("layer"));
5394 }
5395
5396 #[test]
5401 fn is_mutable_tag_recognises_no_tag() {
5402 assert!(is_mutable_tag("nginx"));
5403 assert!(is_mutable_tag("zachhandley/zlayer-manager"));
5404 assert!(is_mutable_tag("registry.example.com:5000/img"));
5405 }
5406
5407 #[test]
5408 fn is_mutable_tag_recognises_empty_tag() {
5409 assert!(is_mutable_tag("nginx:"));
5410 }
5411
5412 #[test]
5413 fn is_mutable_tag_recognises_known_mutable_tags() {
5414 assert!(is_mutable_tag("nginx:latest"));
5415 assert!(is_mutable_tag("nginx:dev"));
5416 assert!(is_mutable_tag("nginx:edge"));
5417 assert!(is_mutable_tag("nginx:main"));
5418 assert!(is_mutable_tag("nginx:master"));
5419 assert!(is_mutable_tag("zachhandley/zlayer-manager:latest"));
5420 assert!(is_mutable_tag("registry.example.com:5000/img:latest"));
5421 }
5422
5423 #[test]
5424 fn is_mutable_tag_rejects_pinned_tags() {
5425 assert!(!is_mutable_tag("nginx:1.25"));
5426 assert!(!is_mutable_tag("nginx:1.25.3"));
5427 assert!(!is_mutable_tag("zachhandley/zlayer-manager:v0.10.70"));
5428 assert!(!is_mutable_tag("registry.example.com:5000/img:v1"));
5429 }
5430
5431 #[test]
5432 fn is_mutable_tag_rejects_digest_refs() {
5433 assert!(!is_mutable_tag(
5434 "img@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
5435 ));
5436 assert!(!is_mutable_tag(
5437 "nginx:latest@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
5438 ));
5439 assert!(!is_mutable_tag(
5440 "registry.example.com:5000/img@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
5441 ));
5442 }
5443
5444 #[test]
5449 fn is_blob_not_found_detects_404_server_error() {
5450 use oci_client::errors::OciDistributionError;
5451 let err = OciDistributionError::ServerError {
5452 code: 404,
5453 url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
5454 message: "not found".to_string(),
5455 };
5456 assert!(is_blob_not_found(&err));
5457 }
5458
5459 #[test]
5460 fn is_blob_not_found_detects_manifest_not_found() {
5461 use oci_client::errors::OciDistributionError;
5462 let err = OciDistributionError::ImageManifestNotFoundError("foo".to_string());
5463 assert!(is_blob_not_found(&err));
5464 }
5465
5466 #[test]
5467 fn is_blob_not_found_detects_blob_unknown_registry_error() {
5468 use oci_client::errors::{OciDistributionError, OciEnvelope, OciError, OciErrorCode};
5469 let envelope = OciEnvelope {
5470 errors: vec![OciError {
5471 code: OciErrorCode::BlobUnknown,
5472 message: "blob gone".to_string(),
5473 detail: serde_json::Value::Null,
5474 }],
5475 };
5476 let err = OciDistributionError::RegistryError {
5477 envelope,
5478 url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
5479 };
5480 assert!(is_blob_not_found(&err));
5481 }
5482
5483 #[test]
5484 fn is_blob_not_found_rejects_non_404_server_error() {
5485 use oci_client::errors::OciDistributionError;
5486 let err = OciDistributionError::ServerError {
5487 code: 500,
5488 url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
5489 message: "boom".to_string(),
5490 };
5491 assert!(!is_blob_not_found(&err));
5492 }
5493
5494 #[test]
5495 fn is_blob_not_found_rejects_auth_failure() {
5496 use oci_client::errors::OciDistributionError;
5497 let err = OciDistributionError::AuthenticationFailure("bad creds".to_string());
5498 assert!(!is_blob_not_found(&err));
5499 }
5500
5501 #[test]
5502 fn max_foreign_layer_redirects_is_capped() {
5503 assert_eq!(MAX_FOREIGN_LAYER_REDIRECTS, 5);
5506 }
5507
5508 #[tokio::test]
5509 async fn fetch_blob_from_url_rejects_invalid_url() {
5510 let result = fetch_blob_from_url(
5511 "not-a-url",
5512 "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
5513 None,
5514 )
5515 .await;
5516 assert!(result.is_err());
5517 }
5518
5519 #[tokio::test]
5520 async fn fetch_archive_from_url_rejects_invalid_url() {
5521 let result = fetch_archive_from_url("not-a-url", None).await;
5522 assert!(result.is_err());
5523 }
5524
5525 #[tokio::test]
5526 async fn fetch_archive_from_url_rejects_unreachable_host() {
5527 let result = fetch_archive_from_url("http://127.0.0.1:1/archive.tar", None).await;
5529 assert!(result.is_err());
5530 }
5531
5532 #[tokio::test]
5533 async fn fetch_archive_from_url_accepts_basic_auth_without_panic() {
5534 let result =
5538 fetch_archive_from_url("http://127.0.0.1:1/archive.tar", Some(("user", "password")))
5539 .await;
5540 assert!(result.is_err());
5541 }
5542
5543 #[tokio::test]
5544 async fn fetch_from_url_surfaces_context_in_error() {
5545 let result = fetch_from_url("http://127.0.0.1:1/thing", None, "test-context").await;
5546 let Err(err) = result else {
5547 panic!("expected connect-refused error");
5548 };
5549 let msg = err.to_string();
5550 assert!(
5551 msg.contains("test-context"),
5552 "error should include context label, got: {msg}"
5553 );
5554 }
5555
5556 #[tokio::test]
5557 async fn fetch_blob_from_url_rejects_unreachable_host() {
5558 let result = fetch_blob_from_url(
5560 "http://127.0.0.1:1/foo",
5561 "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
5562 None,
5563 )
5564 .await;
5565 assert!(result.is_err());
5566 }
5567
5568 #[test]
5573 fn parse_image_manifest_only_rejects_index() {
5574 let index_json = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json","manifests":[]}"#;
5577 assert!(parse_image_manifest_only(index_json).is_none());
5578 }
5579
5580 #[test]
5581 fn parse_image_manifest_only_accepts_image_manifest() {
5582 let image_json = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:cfg","size":1},"layers":[]}"#;
5583 assert!(parse_image_manifest_only(image_json).is_some());
5584 }
5585
5586 #[cfg(feature = "local")]
5587 #[tokio::test]
5588 async fn resolve_stored_manifest_follows_local_index() {
5589 let tmp = tempfile::TempDir::new().unwrap();
5590 let registry = std::sync::Arc::new(
5591 crate::local_registry::LocalRegistry::new(tmp.path().to_path_buf())
5592 .await
5593 .unwrap(),
5594 );
5595
5596 let image_json = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:cfg","size":1},"layers":[]}"#;
5598 let sub_digest = registry
5599 .put_manifest("test/img", "sha256:ignored", image_json)
5600 .await
5601 .unwrap();
5602
5603 let index = OciImageIndex {
5606 schema_version: 2,
5607 media_type: Some("application/vnd.oci.image.index.v1+json".to_string()),
5608 manifests: vec![mk_entry(go_os_name(), go_arch_name(), None, &sub_digest)],
5609 artifact_type: None,
5610 annotations: None,
5611 };
5612 let index_bytes = serde_json::to_vec(&index).unwrap();
5613
5614 let cache: Arc<Box<dyn BlobCacheBackend>> =
5615 Arc::new(Box::new(crate::cache::BlobCache::new().unwrap()));
5616 let puller = ImagePuller::with_cache(cache).with_local_registry(registry.clone());
5617
5618 let (_manifest, digest) = puller
5620 .resolve_stored_manifest(®istry, "test/img", &index_bytes)
5621 .await
5622 .expect("index should resolve to the host-platform manifest");
5623 assert_eq!(digest, sub_digest);
5624
5625 let (_m2, d2) = puller
5627 .resolve_stored_manifest(®istry, "test/img", image_json)
5628 .await
5629 .expect("plain image manifest should resolve as-is");
5630 assert_eq!(d2, sub_digest);
5631 }
5632
5633 fn mk_entry(os: &str, arch: &str, os_version: Option<&str>, digest: &str) -> ImageIndexEntry {
5640 ImageIndexEntry {
5641 media_type: "application/vnd.oci.image.manifest.v1+json".to_string(),
5642 digest: digest.to_string(),
5643 size: 0,
5644 platform: Some(oci_client::manifest::Platform {
5645 architecture: arch.to_string(),
5646 os: os.to_string(),
5647 os_version: os_version.map(str::to_string),
5648 os_features: None,
5649 variant: None,
5650 features: None,
5651 }),
5652 annotations: None,
5653 }
5654 }
5655
5656 #[test]
5657 fn platform_resolver_windows_os_version_prefers_prefix_match() {
5658 use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
5659 let manifests = vec![
5662 mk_entry(
5663 "windows",
5664 "amd64",
5665 Some("10.0.20348.2113"),
5666 "sha256:server2022",
5667 ),
5668 mk_entry(
5669 "windows",
5670 "amd64",
5671 Some("10.0.26100.1742"),
5672 "sha256:server2025",
5673 ),
5674 ];
5675 let target =
5676 TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).with_os_version("10.0.26100");
5677 let resolver = build_platform_resolver(Some(target));
5678 assert_eq!(resolver(&manifests).as_deref(), Some("sha256:server2025"));
5679 }
5680
5681 #[test]
5682 fn platform_resolver_windows_os_version_exact_match() {
5683 use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
5684 let manifests = vec![
5685 mk_entry(
5686 "windows",
5687 "amd64",
5688 Some("10.0.20348.2113"),
5689 "sha256:server2022",
5690 ),
5691 mk_entry(
5692 "windows",
5693 "amd64",
5694 Some("10.0.26100.1742"),
5695 "sha256:server2025",
5696 ),
5697 ];
5698 let target = TargetPlatform::new(OsKind::Windows, ArchKind::Amd64)
5699 .with_os_version("10.0.26100.1742");
5700 let resolver = build_platform_resolver(Some(target));
5701 assert_eq!(resolver(&manifests).as_deref(), Some("sha256:server2025"));
5702 }
5703
5704 #[test]
5705 fn platform_resolver_windows_no_os_version_falls_back_to_first_match() {
5706 use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
5707 let manifests = vec![
5710 mk_entry("windows", "amd64", Some("10.0.20348.2113"), "sha256:first"),
5711 mk_entry("windows", "amd64", Some("10.0.26100.1742"), "sha256:second"),
5712 ];
5713 let target = TargetPlatform::new(OsKind::Windows, ArchKind::Amd64);
5714 let resolver = build_platform_resolver(Some(target));
5715 assert_eq!(resolver(&manifests).as_deref(), Some("sha256:first"));
5716 }
5717
5718 #[test]
5719 fn platform_resolver_windows_os_version_falls_back_when_no_version_match() {
5720 use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
5721 let manifests = vec![mk_entry(
5726 "windows",
5727 "amd64",
5728 Some("10.0.20348.2113"),
5729 "sha256:only",
5730 )];
5731 let target =
5732 TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).with_os_version("10.0.26100");
5733 let resolver = build_platform_resolver(Some(target));
5734 assert_eq!(resolver(&manifests).as_deref(), Some("sha256:only"));
5735 }
5736
5737 #[test]
5738 fn platform_resolver_non_windows_ignores_os_version() {
5739 use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
5740 let manifests = vec![mk_entry("linux", "amd64", None, "sha256:linux")];
5743 let target =
5744 TargetPlatform::new(OsKind::Linux, ArchKind::Amd64).with_os_version("ignored.on.linux");
5745 let resolver = build_platform_resolver(Some(target));
5746 assert_eq!(resolver(&manifests).as_deref(), Some("sha256:linux"));
5747 }
5748
5749 #[test]
5750 fn manifest_cache_key_is_stable() {
5751 assert_eq!(
5756 manifest_cache_key("alpine:latest"),
5757 "manifest:docker.io/library/alpine:latest"
5758 );
5759 assert_eq!(
5761 manifest_cache_key("docker.io/library/alpine:latest"),
5762 "manifest:docker.io/library/alpine:latest"
5763 );
5764 assert_eq!(manifest_cache_key(""), "manifest:");
5766 }
5767
5768 #[test]
5769 fn manifest_cache_key_normalizes_bare_and_qualified_to_same_key() {
5770 assert_eq!(
5774 manifest_cache_key("alpine:latest"),
5775 manifest_cache_key("docker.io/library/alpine:latest"),
5776 );
5777 assert_eq!(
5778 manifest_digest_cache_key("alpine:latest"),
5779 manifest_digest_cache_key("docker.io/library/alpine:latest"),
5780 );
5781 }
5782
5783 #[test]
5784 fn manifest_digest_cache_key_is_stable() {
5785 assert_eq!(
5786 manifest_digest_cache_key("alpine:latest"),
5787 "manifest:digest-docker.io/library/alpine:latest"
5788 );
5789 }
5790
5791 #[test]
5792 fn manifest_and_digest_keys_never_collide() {
5793 for image in [
5797 "alpine",
5798 "alpine:latest",
5799 "library/redis:7",
5800 "ghcr.io/x/y:tag",
5801 ] {
5802 let body = manifest_cache_key(image);
5803 let digest = manifest_digest_cache_key(image);
5804 assert_ne!(body, digest, "cache-key collision for {image}");
5805 assert!(body.starts_with("manifest:"), "manifest key shape: {body}");
5806 assert!(
5807 digest.starts_with("manifest:digest-"),
5808 "digest key shape: {digest}"
5809 );
5810 }
5811 }
5812
5813 fn seed_cache_with_os(
5825 image: &str,
5826 os: &str,
5827 runtime_marker: Option<&str>,
5828 ) -> Arc<Box<dyn BlobCacheBackend>> {
5829 let cache = crate::cache::BlobCache::new().unwrap();
5830
5831 let config_json = serde_json::json!({
5833 "architecture": "arm64",
5834 "os": os,
5835 "config": {},
5836 });
5837 let config_bytes = serde_json::to_vec(&config_json).unwrap();
5838 let config_digest = crate::cache::compute_digest(&config_bytes);
5839 cache.put(&config_digest, &config_bytes).unwrap();
5840
5841 let annotations = runtime_marker.map(|m| {
5842 let mut a = std::collections::BTreeMap::new();
5843 a.insert(crate::ZLAYER_RUNTIME_ANNOTATION.to_string(), m.to_string());
5844 a
5845 });
5846
5847 let manifest = OciImageManifest {
5848 schema_version: 2,
5849 media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
5850 artifact_type: None,
5851 config: oci_client::manifest::OciDescriptor {
5852 media_type: "application/vnd.oci.image.config.v1+json".to_string(),
5853 digest: config_digest.clone(),
5854 size: i64::try_from(config_bytes.len()).unwrap(),
5855 urls: None,
5856 annotations: None,
5857 },
5858 layers: vec![],
5859 annotations,
5860 subject: None,
5861 };
5862 let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
5863 let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
5864
5865 cache
5867 .put(&manifest_cache_key(image), &manifest_bytes)
5868 .unwrap();
5869 cache
5870 .put(
5871 &manifest_digest_cache_key(image),
5872 manifest_digest.as_bytes(),
5873 )
5874 .unwrap();
5875
5876 Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>)
5877 }
5878
5879 struct CountingCache {
5900 inner: crate::cache::BlobCache,
5901 watch_key: String,
5902 in_flight: std::sync::atomic::AtomicUsize,
5903 max_in_flight: std::sync::atomic::AtomicUsize,
5904 delay: std::time::Duration,
5905 }
5906
5907 impl CountingCache {
5908 fn new(inner: crate::cache::BlobCache, watch_key: String) -> Arc<Self> {
5909 Arc::new(Self {
5910 inner,
5911 watch_key,
5912 in_flight: std::sync::atomic::AtomicUsize::new(0),
5913 max_in_flight: std::sync::atomic::AtomicUsize::new(0),
5914 delay: std::time::Duration::from_millis(50),
5915 })
5916 }
5917
5918 fn max_concurrent(&self) -> usize {
5919 self.max_in_flight.load(std::sync::atomic::Ordering::SeqCst)
5920 }
5921 }
5922
5923 #[async_trait::async_trait]
5924 impl BlobCacheBackend for CountingCache {
5925 async fn get(
5926 &self,
5927 digest: &str,
5928 ) -> std::result::Result<Option<Vec<u8>>, crate::error::CacheError> {
5929 if digest == self.watch_key {
5930 let now = self
5931 .in_flight
5932 .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
5933 + 1;
5934 self.max_in_flight
5935 .fetch_max(now, std::sync::atomic::Ordering::SeqCst);
5936 tokio::time::sleep(self.delay).await;
5937 let out = self.inner.get(digest);
5938 self.in_flight
5939 .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
5940 out
5941 } else {
5942 self.inner.get(digest)
5943 }
5944 }
5945
5946 async fn put(
5947 &self,
5948 digest: &str,
5949 data: &[u8],
5950 ) -> std::result::Result<(), crate::error::CacheError> {
5951 self.inner.put(digest, data)
5952 }
5953
5954 async fn contains(
5955 &self,
5956 digest: &str,
5957 ) -> std::result::Result<bool, crate::error::CacheError> {
5958 self.inner.contains(digest)
5959 }
5960
5961 async fn delete(&self, digest: &str) -> std::result::Result<(), crate::error::CacheError> {
5962 self.inner.delete(digest)
5963 }
5964 }
5965
5966 fn counting_cache_for(image: &str) -> Arc<CountingCache> {
5972 let inner = crate::cache::BlobCache::new().unwrap();
5973
5974 let config_json =
5975 serde_json::json!({ "architecture": "arm64", "os": "linux", "config": {} });
5976 let config_bytes = serde_json::to_vec(&config_json).unwrap();
5977 let config_digest = crate::cache::compute_digest(&config_bytes);
5978 inner.put(&config_digest, &config_bytes).unwrap();
5979
5980 let manifest = OciImageManifest {
5981 schema_version: 2,
5982 media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
5983 artifact_type: None,
5984 config: oci_client::manifest::OciDescriptor {
5985 media_type: "application/vnd.oci.image.config.v1+json".to_string(),
5986 digest: config_digest.clone(),
5987 size: i64::try_from(config_bytes.len()).unwrap(),
5988 urls: None,
5989 annotations: None,
5990 },
5991 layers: vec![],
5992 annotations: None,
5993 subject: None,
5994 };
5995 let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
5996 let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
5997 inner
5998 .put(&manifest_cache_key(image), &manifest_bytes)
5999 .unwrap();
6000 inner
6001 .put(
6002 &manifest_digest_cache_key(image),
6003 manifest_digest.as_bytes(),
6004 )
6005 .unwrap();
6006
6007 CountingCache::new(inner, manifest_cache_key(image))
6008 }
6009
6010 #[tokio::test]
6011 async fn pull_image_to_files_single_flights_concurrent_pulls_of_same_ref() {
6012 let image = "registry.example.com/team/executor@sha256:\
6017 1111111111111111111111111111111111111111111111111111111111111111";
6018 let counting = counting_cache_for(image);
6019 let cache: Arc<Box<dyn BlobCacheBackend>> =
6020 Arc::new(Box::new(CountingCacheHandle(counting.clone())) as Box<dyn BlobCacheBackend>);
6021 let puller = Arc::new(ImagePuller::with_cache(cache));
6022
6023 let tmp = tempfile::tempdir().unwrap();
6024 let n = 10usize;
6025 let mut set = tokio::task::JoinSet::new();
6026 for i in 0..n {
6027 let puller = puller.clone();
6028 let image = image.to_string();
6029 let stage = tmp.path().join(format!("stage-{i}"));
6030 set.spawn(async move {
6031 puller
6032 .pull_image_to_files_with_policy(
6033 &image,
6034 &RegistryAuth::Anonymous,
6035 &stage,
6036 PullPolicy::IfNotPresent,
6037 )
6038 .await
6039 });
6040 }
6041
6042 let mut ok = 0usize;
6043 while let Some(joined) = set.join_next().await {
6044 let layers = joined
6045 .expect("task must not panic")
6046 .expect("pull must succeed");
6047 assert!(
6048 layers.is_empty(),
6049 "zero-layer manifest yields zero layer files"
6050 );
6051 ok += 1;
6052 }
6053 assert_eq!(ok, n, "every concurrent caller must complete");
6054
6055 assert_eq!(
6056 counting.max_concurrent(),
6057 1,
6058 "single-flight must collapse the {n} concurrent pulls onto ONE in-flight \
6059 manifest fetch (the leader); followers block until it completes",
6060 );
6061 }
6062
6063 #[tokio::test]
6064 async fn pull_image_config_single_flights_concurrent_fetches_of_same_ref() {
6065 let image = "registry.example.com/team/cfg@sha256:\
6069 2222222222222222222222222222222222222222222222222222222222222222";
6070 let inner = crate::cache::BlobCache::new().unwrap();
6072 let config_json =
6073 serde_json::json!({ "architecture": "arm64", "os": "linux", "config": {} });
6074 let config_bytes = serde_json::to_vec(&config_json).unwrap();
6075 let config_digest = crate::cache::compute_digest(&config_bytes);
6076 inner.put(&config_digest, &config_bytes).unwrap();
6077 let manifest = OciImageManifest {
6078 schema_version: 2,
6079 media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
6080 artifact_type: None,
6081 config: oci_client::manifest::OciDescriptor {
6082 media_type: "application/vnd.oci.image.config.v1+json".to_string(),
6083 digest: config_digest.clone(),
6084 size: i64::try_from(config_bytes.len()).unwrap(),
6085 urls: None,
6086 annotations: None,
6087 },
6088 layers: vec![],
6089 annotations: None,
6090 subject: None,
6091 };
6092 let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
6093 let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
6094 inner
6095 .put(&manifest_cache_key(image), &manifest_bytes)
6096 .unwrap();
6097 inner
6098 .put(
6099 &manifest_digest_cache_key(image),
6100 manifest_digest.as_bytes(),
6101 )
6102 .unwrap();
6103 let counting = CountingCache::new(inner, config_digest.clone());
6104 let cache: Arc<Box<dyn BlobCacheBackend>> =
6105 Arc::new(Box::new(CountingCacheHandle(counting.clone())) as Box<dyn BlobCacheBackend>);
6106 let puller = Arc::new(ImagePuller::with_cache(cache));
6107
6108 let n = 10usize;
6109 let mut set = tokio::task::JoinSet::new();
6110 for _ in 0..n {
6111 let puller = puller.clone();
6112 let image = image.to_string();
6113 set.spawn(async move {
6114 puller
6115 .pull_image_config_with_policy(
6116 &image,
6117 &RegistryAuth::Anonymous,
6118 PullPolicy::IfNotPresent,
6119 )
6120 .await
6121 });
6122 }
6123 let mut ok = 0usize;
6124 while let Some(joined) = set.join_next().await {
6125 joined
6126 .expect("task must not panic")
6127 .expect("config fetch must succeed");
6128 ok += 1;
6129 }
6130 assert_eq!(ok, n);
6131 assert_eq!(
6132 counting.max_concurrent(),
6133 1,
6134 "single-flight must collapse the {n} concurrent config fetches onto ONE \
6135 in-flight config-blob read",
6136 );
6137 }
6138
6139 #[tokio::test]
6140 async fn pull_image_to_files_does_not_false_share_across_refs() {
6141 let image_a = "registry.example.com/team/a@sha256:\
6147 3333333333333333333333333333333333333333333333333333333333333333";
6148 let image_b = "registry.example.com/team/b@sha256:\
6149 4444444444444444444444444444444444444444444444444444444444444444";
6150 let counting_a = counting_cache_for(image_a);
6151 let counting_b = counting_cache_for(image_b);
6152 let puller_a = Arc::new(ImagePuller::with_cache(Arc::new(
6153 Box::new(CountingCacheHandle(counting_a.clone())) as Box<dyn BlobCacheBackend>,
6154 )));
6155 let puller_b = Arc::new(ImagePuller::with_cache(Arc::new(
6156 Box::new(CountingCacheHandle(counting_b.clone())) as Box<dyn BlobCacheBackend>,
6157 )));
6158
6159 let tmp = tempfile::tempdir().unwrap();
6160 let stage_a = tmp.path().join("a");
6161 let stage_b = tmp.path().join("b");
6162 let (ra, rb) = tokio::join!(
6163 puller_a.pull_image_to_files_with_policy(
6164 image_a,
6165 &RegistryAuth::Anonymous,
6166 &stage_a,
6167 PullPolicy::IfNotPresent,
6168 ),
6169 puller_b.pull_image_to_files_with_policy(
6170 image_b,
6171 &RegistryAuth::Anonymous,
6172 &stage_b,
6173 PullPolicy::IfNotPresent,
6174 ),
6175 );
6176 assert!(ra.expect("ref A pull must succeed").is_empty());
6177 assert!(rb.expect("ref B pull must succeed").is_empty());
6178 assert_eq!(counting_a.max_concurrent(), 1);
6182 assert_eq!(counting_b.max_concurrent(), 1);
6183 }
6184
6185 struct CountingCacheHandle(Arc<CountingCache>);
6190
6191 #[async_trait::async_trait]
6192 impl BlobCacheBackend for CountingCacheHandle {
6193 async fn get(
6194 &self,
6195 digest: &str,
6196 ) -> std::result::Result<Option<Vec<u8>>, crate::error::CacheError> {
6197 self.0.get(digest).await
6198 }
6199 async fn put(
6200 &self,
6201 digest: &str,
6202 data: &[u8],
6203 ) -> std::result::Result<(), crate::error::CacheError> {
6204 self.0.put(digest, data).await
6205 }
6206 async fn contains(
6207 &self,
6208 digest: &str,
6209 ) -> std::result::Result<bool, crate::error::CacheError> {
6210 self.0.contains(digest).await
6211 }
6212 async fn delete(&self, digest: &str) -> std::result::Result<(), crate::error::CacheError> {
6213 self.0.delete(digest).await
6214 }
6215 }
6216
6217 #[tokio::test]
6218 async fn image_os_with_policy_resolves_linux_from_local_cache_no_network() {
6219 let image = "docker.io/library/alpine:latest";
6225 let cache = seed_cache_with_os(image, "linux", None);
6226 let puller = ImagePuller::with_cache(cache);
6227
6228 let os = puller
6229 .image_os_with_policy(image, &RegistryAuth::Anonymous, PullPolicy::IfNotPresent)
6230 .await
6231 .expect("local-first OS inspection must not error");
6232 assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
6233 }
6234
6235 #[cfg(feature = "local")]
6236 #[tokio::test]
6237 async fn fetch_image_os_in_cache_resolves_linux_no_network() {
6238 let image = "docker.io/library/alpine:latest";
6242 let cache = seed_cache_with_os(image, "linux", None);
6243
6244 let os = fetch_image_os_in_cache(image, None, cache, None)
6245 .await
6246 .expect("local-first OS inspection must not error");
6247 assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
6248 }
6249
6250 #[cfg(feature = "local")]
6251 #[tokio::test]
6252 async fn fetch_image_runtime_marker_in_cache_resolves_marker_no_network() {
6253 let image = "ghcr.io/example/vz-base:1.0";
6254 let cache = seed_cache_with_os(image, "linux", Some("vz"));
6255
6256 let marker = fetch_image_runtime_marker_in_cache(image, None, cache, None)
6257 .await
6258 .expect("local-first marker inspection must not error");
6259 assert_eq!(marker.as_deref(), Some("vz"));
6260 }
6261
6262 #[tokio::test]
6265 async fn bare_ref_resolves_from_cache_seeded_under_qualified_ref() {
6266 let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", None);
6272 let puller = ImagePuller::with_cache(cache);
6273
6274 let os = puller
6275 .image_os_in_cache_only("alpine:latest")
6276 .await
6277 .expect("bare-ref local inspection must not error");
6278 assert_eq!(
6279 os,
6280 Some(zlayer_spec::OsKind::Linux),
6281 "bare `alpine:latest` must resolve from a cache seeded under the qualified ref",
6282 );
6283 }
6284
6285 #[cfg(feature = "local")]
6286 #[tokio::test]
6287 async fn fetch_image_os_in_cache_only_bare_ref_no_network() {
6288 let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", None);
6290 let os = fetch_image_os_in_cache_only("alpine:latest", cache, None)
6291 .await
6292 .expect("local-only inspection must not error");
6293 assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
6294 }
6295
6296 #[tokio::test]
6297 async fn image_os_in_cache_only_no_network_when_manifest_and_config_present() {
6298 let image = "docker.io/library/alpine:latest";
6305 let cache = seed_cache_with_os(image, "linux", None);
6306 let puller = ImagePuller::with_cache(cache);
6307
6308 let os = puller
6309 .image_os_in_cache_only(image)
6310 .await
6311 .expect("cached manifest+config must resolve OS with no network");
6312 assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
6313 }
6314
6315 #[tokio::test]
6316 async fn cache_local_image_platform_round_trips_darwin() {
6317 let image = "ghcr.io/owner/seatbelt-app:latest";
6324 let cache: Arc<Box<dyn BlobCacheBackend>> =
6325 Arc::new(Box::new(crate::cache::BlobCache::new().unwrap()));
6326 let puller = ImagePuller::with_cache(cache);
6327
6328 assert_eq!(
6330 puller.image_os_in_cache_only(image).await.unwrap(),
6331 None,
6332 "no stamp yet must be a clean local miss"
6333 );
6334
6335 puller
6336 .cache_local_image_platform(image, "darwin", "arm64")
6337 .await
6338 .expect("stamping a local image's platform must succeed");
6339
6340 let os = puller
6341 .image_os_in_cache_only(image)
6342 .await
6343 .expect("stamped manifest+config must resolve OS with no network");
6344 assert_eq!(os, Some(zlayer_spec::OsKind::Macos));
6345 }
6346
6347 #[tokio::test]
6348 async fn image_os_in_cache_only_returns_none_on_clean_local_miss() {
6349 let cache: Arc<Box<dyn BlobCacheBackend>> = Arc::new(Box::new(
6353 crate::cache::BlobCache::new().unwrap(),
6354 )
6355 as Box<dyn BlobCacheBackend>);
6356 let puller = ImagePuller::with_cache(cache);
6357
6358 let os = puller
6359 .image_os_in_cache_only("docker.io/library/absent:latest")
6360 .await
6361 .expect("a local miss must be Ok(None), never an error");
6362 assert_eq!(os, None);
6363 assert_eq!(
6365 puller.network_call_count(),
6366 0,
6367 "image_os_in_cache_only must never issue a network call, even on a local miss",
6368 );
6369 }
6370
6371 #[tokio::test]
6372 async fn image_os_in_cache_only_bare_ref_issues_zero_network_calls() {
6373 let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", None);
6379 let puller = ImagePuller::with_cache(cache);
6380
6381 let os = puller
6382 .image_os_in_cache_only("alpine:latest")
6383 .await
6384 .expect("bare-ref local inspection must not error");
6385
6386 assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
6387 assert_eq!(
6388 puller.network_call_count(),
6389 0,
6390 "a cached image's OS must resolve with ZERO network calls (no Docker Hub re-inspect)",
6391 );
6392 }
6393
6394 #[tokio::test]
6395 async fn image_runtime_marker_in_cache_only_bare_ref_zero_network() {
6396 let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", Some("vz"));
6399 let puller = ImagePuller::with_cache(cache);
6400
6401 let marker = puller
6402 .image_runtime_marker_in_cache_only("alpine:latest")
6403 .await
6404 .expect("bare-ref marker inspection must not error");
6405
6406 assert_eq!(marker.as_deref(), Some("vz"));
6407 assert_eq!(
6408 puller.network_call_count(),
6409 0,
6410 "runtime-marker inspection must resolve from cache with ZERO network calls",
6411 );
6412 }
6413
6414 fn seed_cache_with_isolation(image: &str, isolation: &str) -> Arc<Box<dyn BlobCacheBackend>> {
6418 let cache = crate::cache::BlobCache::new().unwrap();
6419
6420 let config_json = serde_json::json!({
6423 "architecture": "arm64",
6424 "os": "linux",
6425 "config": { "Labels": { crate::ZLAYER_ISOLATION_ANNOTATION: isolation } },
6426 });
6427 let config_bytes = serde_json::to_vec(&config_json).unwrap();
6428 let config_digest = crate::cache::compute_digest(&config_bytes);
6429 cache.put(&config_digest, &config_bytes).unwrap();
6430
6431 let manifest = OciImageManifest {
6432 schema_version: 2,
6433 media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
6434 artifact_type: None,
6435 config: oci_client::manifest::OciDescriptor {
6436 media_type: "application/vnd.oci.image.config.v1+json".to_string(),
6437 digest: config_digest.clone(),
6438 size: i64::try_from(config_bytes.len()).unwrap(),
6439 urls: None,
6440 annotations: None,
6441 },
6442 layers: vec![],
6443 annotations: None,
6444 subject: None,
6445 };
6446 let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
6447 let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
6448
6449 cache
6450 .put(&manifest_cache_key(image), &manifest_bytes)
6451 .unwrap();
6452 cache
6453 .put(
6454 &manifest_digest_cache_key(image),
6455 manifest_digest.as_bytes(),
6456 )
6457 .unwrap();
6458
6459 Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>)
6460 }
6461
6462 #[tokio::test]
6463 async fn image_isolation_marker_in_cache_only_reads_config_label_zero_network() {
6464 let image = "docker.io/library/alpine:latest";
6468 let cache = seed_cache_with_isolation(image, "vz-linux");
6469 let puller = ImagePuller::with_cache(cache);
6470
6471 let iso = puller
6472 .image_isolation_marker_in_cache_only("alpine:latest")
6473 .await
6474 .expect("isolation-label inspection must not error");
6475
6476 assert_eq!(iso.as_deref(), Some("vz-linux"));
6477 assert_eq!(
6478 puller.network_call_count(),
6479 0,
6480 "isolation inspection must resolve from cache with ZERO network calls",
6481 );
6482 }
6483
6484 #[tokio::test]
6485 async fn image_isolation_marker_in_cache_only_none_when_label_absent() {
6486 let image = "docker.io/library/alpine:latest";
6489 let cache = seed_cache_with_os(image, "linux", None);
6490 let puller = ImagePuller::with_cache(cache);
6491
6492 let iso = puller
6493 .image_isolation_marker_in_cache_only(image)
6494 .await
6495 .expect("missing isolation label must be Ok(None), never an error");
6496 assert_eq!(iso, None);
6497 }
6498
6499 #[tokio::test]
6500 async fn manifest_cache_key_collides_bare_qualified_and_literal() {
6501 assert_eq!(
6505 manifest_cache_key("alpine:latest"),
6506 "manifest:docker.io/library/alpine:latest",
6507 );
6508 assert_eq!(
6509 manifest_cache_key("docker.io/library/alpine:latest"),
6510 "manifest:docker.io/library/alpine:latest",
6511 );
6512 assert_eq!(
6513 manifest_cache_key("alpine:latest"),
6514 manifest_cache_key("docker.io/library/alpine:latest"),
6515 );
6516 }
6517
6518 struct BrokenS3;
6526
6527 use crate::error::CacheError;
6528
6529 #[async_trait::async_trait]
6530 impl BlobCacheBackend for BrokenS3 {
6531 async fn get(&self, _digest: &str) -> std::result::Result<Option<Vec<u8>>, CacheError> {
6532 Err(CacheError::Database(
6533 "simulated S3 endpoint unreachable".to_string(),
6534 ))
6535 }
6536 async fn put(&self, _digest: &str, _data: &[u8]) -> std::result::Result<(), CacheError> {
6537 Err(CacheError::Database(
6538 "simulated S3 endpoint unreachable".to_string(),
6539 ))
6540 }
6541 async fn contains(&self, _digest: &str) -> std::result::Result<bool, CacheError> {
6542 Err(CacheError::Database(
6543 "simulated S3 endpoint unreachable".to_string(),
6544 ))
6545 }
6546 }
6547
6548 fn broken_s3() -> Arc<Box<dyn BlobCacheBackend>> {
6549 Arc::new(Box::new(BrokenS3) as Box<dyn BlobCacheBackend>)
6550 }
6551
6552 #[tokio::test]
6553 async fn s3_tier_get_treats_error_as_miss() {
6554 let puller = ImagePuller::with_cache(seed_cache_with_os(
6557 "docker.io/library/alpine:latest",
6558 "linux",
6559 None,
6560 ))
6561 .with_s3_cache(broken_s3());
6562
6563 assert!(
6564 puller.s3_tier_get("any-key").await.is_none(),
6565 "an erroring S3 tier must degrade to a cache MISS, not surface the error",
6566 );
6567 }
6568
6569 #[tokio::test]
6570 async fn unreachable_s3_does_not_break_local_cache_hit() {
6571 let image = "ghcr.io/example/app:1.2.3";
6577 let puller = ImagePuller::with_cache(seed_cache_with_os(image, "linux", None))
6578 .with_s3_cache(broken_s3());
6579
6580 let (_manifest, _digest) = puller
6581 .pull_manifest_inner(image, &RegistryAuth::Anonymous, PullPolicy::IfNotPresent)
6582 .await
6583 .expect("a local cache hit must survive an unreachable S3 tier");
6584 }
6585
6586 #[tokio::test]
6587 async fn unreachable_s3_falls_through_to_origin_not_a_hard_s3_error() {
6588 let image = "registry.invalid.example.test/example/app:1.0.0";
6597 let empty_cache: Arc<Box<dyn BlobCacheBackend>> = Arc::new(Box::new(
6598 crate::cache::BlobCache::new().unwrap(),
6599 )
6600 as Box<dyn BlobCacheBackend>);
6601 let puller = ImagePuller::with_cache(empty_cache).with_s3_cache(broken_s3());
6602
6603 let err = puller
6604 .pull_manifest_inner(image, &RegistryAuth::Anonymous, PullPolicy::Newer)
6605 .await
6606 .expect_err("an unreachable origin should error (no network in test env)");
6607
6608 match err {
6611 RegistryError::NotFound { .. } | RegistryError::Oci(_) => {}
6612 other => panic!("expected an origin-class error after S3 fell through, got: {other:?}"),
6613 }
6614 }
6615}