1use crate::cache::compute_digest;
36use crate::wasm::{
37 WasiVersion, WASM_COMPONENT_ARTIFACT_TYPE, WASM_CONFIG_MEDIA_TYPE_V0,
38 WASM_LAYER_MEDIA_TYPE_GENERIC, WASM_MODULE_ARTIFACT_TYPE,
39};
40use serde::{Deserialize, Serialize};
41use std::collections::HashMap;
42use std::path::PathBuf;
43use thiserror::Error;
44use tokio::fs;
45use tracing::instrument;
46
47const WASM_MAGIC_BYTES: [u8; 4] = [0x00, 0x61, 0x73, 0x6d];
49
50const WASM_VERSION_CORE: [u8; 4] = [0x01, 0x00, 0x00, 0x00];
52
53const COMPONENT_LAYER_ID: u8 = 0x0d;
56
57#[derive(Debug, Clone)]
59pub struct WasmExportConfig {
60 pub wasm_path: PathBuf,
62
63 pub module_name: String,
65
66 pub wasi_version: Option<WasiVersion>,
68
69 pub annotations: HashMap<String, String>,
71}
72
73#[derive(Debug, Clone)]
75pub struct WasmExportResult {
76 pub manifest_digest: String,
78
79 pub manifest_size: u64,
81
82 pub wasm_layer_digest: String,
84
85 pub wasm_size: u64,
87
88 pub config_digest: String,
90
91 pub config_size: u64,
93
94 pub wasi_version: WasiVersion,
96
97 pub artifact_type: String,
99
100 pub manifest_json: Vec<u8>,
102
103 pub config_blob: Vec<u8>,
105
106 pub wasm_binary: Vec<u8>,
108}
109
110#[derive(Debug, Error)]
112pub enum WasmExportError {
113 #[error("invalid WASM binary: {reason}")]
115 InvalidWasmBinary {
116 reason: String,
118 },
119
120 #[error("IO error: {0}")]
122 IoError(#[from] std::io::Error),
123
124 #[error("serialization error: failed to serialize manifest or config")]
126 SerializationError,
127
128 #[error("storage error: {reason}")]
130 StorageError {
131 reason: String,
133 },
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize)]
138struct OciManifest {
139 #[serde(rename = "schemaVersion")]
141 schema_version: u32,
142
143 #[serde(rename = "mediaType")]
145 media_type: String,
146
147 #[serde(rename = "artifactType", skip_serializing_if = "Option::is_none")]
149 artifact_type: Option<String>,
150
151 config: OciDescriptor,
153
154 layers: Vec<OciDescriptor>,
156
157 #[serde(skip_serializing_if = "Option::is_none")]
159 annotations: Option<HashMap<String, String>>,
160}
161
162#[derive(Debug, Clone, Serialize, Deserialize)]
164struct OciDescriptor {
165 #[serde(rename = "mediaType")]
167 media_type: String,
168
169 digest: String,
171
172 size: u64,
174
175 #[serde(skip_serializing_if = "Option::is_none")]
177 annotations: Option<HashMap<String, String>>,
178}
179
180fn validate_wasm_magic(data: &[u8]) -> Result<(), WasmExportError> {
182 if data.len() < 8 {
183 return Err(WasmExportError::InvalidWasmBinary {
184 reason: "file too small to be a valid WASM binary (less than 8 bytes)".to_string(),
185 });
186 }
187
188 if data[0..4] != WASM_MAGIC_BYTES {
189 return Err(WasmExportError::InvalidWasmBinary {
190 reason: format!(
191 "invalid magic bytes: expected {:?}, got {:?}",
192 WASM_MAGIC_BYTES,
193 &data[0..4]
194 ),
195 });
196 }
197
198 Ok(())
199}
200
201fn detect_wasi_version_from_binary(data: &[u8]) -> WasiVersion {
211 if data.len() < 8 {
212 return WasiVersion::Unknown;
213 }
214
215 let version_bytes = &data[4..8];
219
220 if version_bytes == WASM_VERSION_CORE {
221 if data.len() > 8 {
227 let first_section_id = data[8];
229 if first_section_id == COMPONENT_LAYER_ID {
230 return WasiVersion::Preview2;
231 }
232
233 if contains_component_indicator(data) {
236 return WasiVersion::Preview2;
237 }
238 }
239
240 return WasiVersion::Preview1;
241 }
242
243 if version_bytes[0] == COMPONENT_LAYER_ID {
246 return WasiVersion::Preview2;
247 }
248
249 WasiVersion::Unknown
250}
251
252fn contains_component_indicator(data: &[u8]) -> bool {
256 const COMPONENT_TYPE_MARKER: &[u8] = b"component-type";
259 const WIT_COMPONENT_MARKER: &[u8] = b"wit-component";
260
261 for window in data.windows(COMPONENT_TYPE_MARKER.len()) {
263 if window == COMPONENT_TYPE_MARKER {
264 return true;
265 }
266 }
267
268 for window in data.windows(WIT_COMPONENT_MARKER.len()) {
269 if window == WIT_COMPONENT_MARKER {
270 return true;
271 }
272 }
273
274 false
275}
276
277fn artifact_type_for_wasi_version(version: &WasiVersion) -> String {
279 match version {
280 WasiVersion::Preview1 | WasiVersion::Unknown => WASM_MODULE_ARTIFACT_TYPE.to_string(),
281 WasiVersion::Preview2 => WASM_COMPONENT_ARTIFACT_TYPE.to_string(),
282 }
283}
284
285fn create_wasm_config_blob() -> Vec<u8> {
289 b"{}".to_vec()
290}
291
292#[instrument(
338 name = "export_wasm_as_oci",
339 skip(config),
340 fields(
341 wasm_path = %config.wasm_path.display(),
342 module_name = %config.module_name,
343 )
344)]
345pub async fn export_wasm_as_oci(
346 config: &WasmExportConfig,
347) -> Result<WasmExportResult, WasmExportError> {
348 tracing::debug!("reading WASM binary from disk");
350 let wasm_binary = fs::read(&config.wasm_path).await?;
351
352 tracing::debug!("validating WASM magic bytes");
354 validate_wasm_magic(&wasm_binary)?;
355
356 let wasi_version = config.wasi_version.clone().unwrap_or_else(|| {
358 tracing::debug!("auto-detecting WASI version from binary structure");
359 detect_wasi_version_from_binary(&wasm_binary)
360 });
361
362 tracing::info!(
363 wasi_version = %wasi_version,
364 wasm_size = wasm_binary.len(),
365 "validated WASM binary"
366 );
367
368 let wasm_layer_digest = compute_digest(&wasm_binary);
370 let wasm_size = wasm_binary.len() as u64;
371
372 let config_blob = create_wasm_config_blob();
374 let config_digest = compute_digest(&config_blob);
375 let config_size = config_blob.len() as u64;
376
377 let artifact_type = artifact_type_for_wasi_version(&wasi_version);
379
380 let mut layer_annotations = HashMap::new();
382 layer_annotations.insert(
383 "org.opencontainers.image.title".to_string(),
384 format!("{}.wasm", config.module_name),
385 );
386
387 let mut manifest_annotations = config.annotations.clone();
389 if !manifest_annotations.contains_key("org.opencontainers.image.title") {
390 manifest_annotations.insert(
391 "org.opencontainers.image.title".to_string(),
392 config.module_name.clone(),
393 );
394 }
395
396 let manifest = OciManifest {
398 schema_version: 2,
399 media_type: "application/vnd.oci.image.manifest.v1+json".to_string(),
400 artifact_type: Some(artifact_type.clone()),
401 config: OciDescriptor {
402 media_type: WASM_CONFIG_MEDIA_TYPE_V0.to_string(),
403 digest: config_digest.clone(),
404 size: config_size,
405 annotations: None,
406 },
407 layers: vec![OciDescriptor {
408 media_type: WASM_LAYER_MEDIA_TYPE_GENERIC.to_string(),
409 digest: wasm_layer_digest.clone(),
410 size: wasm_size,
411 annotations: Some(layer_annotations),
412 }],
413 annotations: if manifest_annotations.is_empty() {
414 None
415 } else {
416 Some(manifest_annotations)
417 },
418 };
419
420 let manifest_json =
422 serde_json::to_vec_pretty(&manifest).map_err(|_| WasmExportError::SerializationError)?;
423
424 let manifest_digest = compute_digest(&manifest_json);
425 let manifest_size = manifest_json.len() as u64;
426
427 tracing::info!(
428 manifest_digest = %manifest_digest,
429 manifest_size = manifest_size,
430 wasm_layer_digest = %wasm_layer_digest,
431 config_digest = %config_digest,
432 artifact_type = %artifact_type,
433 "created OCI manifest for WASM artifact"
434 );
435
436 Ok(WasmExportResult {
437 manifest_digest,
438 manifest_size,
439 wasm_layer_digest,
440 wasm_size,
441 config_digest,
442 config_size,
443 wasi_version,
444 artifact_type,
445 manifest_json,
446 config_blob,
447 wasm_binary,
448 })
449}
450
451#[cfg(test)]
452mod tests {
453 use super::*;
454 use tempfile::TempDir;
455
456 fn create_minimal_wasm_module() -> Vec<u8> {
462 vec![
467 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, ]
470 }
471
472 fn create_wasm_module_with_type_section() -> Vec<u8> {
474 vec![
475 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01, 0x60, 0x00, 0x00, ]
484 }
485
486 fn create_wasm_module_with_custom_section() -> Vec<u8> {
488 vec![
489 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x00, 0x05, 0x04, 0x6e, 0x61, 0x6d, 0x65, ]
496 }
497
498 fn create_minimal_wasm_component() -> Vec<u8> {
500 let mut data = vec![
502 0x00, 0x61, 0x73, 0x6d, 0x0d, 0x00, 0x01, 0x00, ];
505 data.extend_from_slice(b"component-type");
507 data
508 }
509
510 fn create_wasm_component_with_wit_marker() -> Vec<u8> {
512 let mut data = vec![
513 0x00, 0x61, 0x73, 0x6d, 0x0d, 0x00, 0x01, 0x00, ];
516 data.extend_from_slice(b"wit-component");
518 data
519 }
520
521 fn create_invalid_bytes() -> Vec<u8> {
523 vec![0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe]
524 }
525
526 fn create_invalid_version_bytes() -> Vec<u8> {
528 vec![
529 0x00, 0x61, 0x73, 0x6d, 0xff, 0xff, 0x00, 0x00, ]
532 }
533
534 #[test]
539 fn test_wasm_export_config_creation_all_fields() {
540 let mut annotations = HashMap::new();
541 annotations.insert("key1".to_string(), "value1".to_string());
542 annotations.insert("key2".to_string(), "value2".to_string());
543
544 let config = WasmExportConfig {
545 wasm_path: PathBuf::from("/path/to/module.wasm"),
546 module_name: "my-module".to_string(),
547 wasi_version: Some(WasiVersion::Preview2),
548 annotations: annotations.clone(),
549 };
550
551 assert_eq!(config.wasm_path, PathBuf::from("/path/to/module.wasm"));
552 assert_eq!(config.module_name, "my-module");
553 assert_eq!(config.wasi_version, Some(WasiVersion::Preview2));
554 assert_eq!(config.annotations.len(), 2);
555 assert_eq!(config.annotations.get("key1"), Some(&"value1".to_string()));
556 }
557
558 #[test]
559 fn test_wasm_export_config_creation_minimal_fields() {
560 let config = WasmExportConfig {
561 wasm_path: PathBuf::from("./module.wasm"),
562 module_name: "minimal".to_string(),
563 wasi_version: None,
564 annotations: HashMap::new(),
565 };
566
567 assert_eq!(config.wasm_path, PathBuf::from("./module.wasm"));
568 assert_eq!(config.module_name, "minimal");
569 assert_eq!(config.wasi_version, None);
570 assert!(config.annotations.is_empty());
571 }
572
573 #[test]
574 fn test_wasm_export_config_clone() {
575 let mut annotations = HashMap::new();
576 annotations.insert("key".to_string(), "value".to_string());
577
578 let config = WasmExportConfig {
579 wasm_path: PathBuf::from("/test/path.wasm"),
580 module_name: "test".to_string(),
581 wasi_version: Some(WasiVersion::Preview1),
582 annotations,
583 };
584
585 let cloned = config.clone();
586
587 assert_eq!(cloned.wasm_path, config.wasm_path);
588 assert_eq!(cloned.module_name, config.module_name);
589 assert_eq!(cloned.wasi_version, config.wasi_version);
590 assert_eq!(cloned.annotations, config.annotations);
591 }
592
593 #[test]
594 fn test_wasm_export_config_debug() {
595 let config = WasmExportConfig {
596 wasm_path: PathBuf::from("/test.wasm"),
597 module_name: "test".to_string(),
598 wasi_version: None,
599 annotations: HashMap::new(),
600 };
601
602 let debug_str = format!("{config:?}");
603 assert!(debug_str.contains("WasmExportConfig"));
604 assert!(debug_str.contains("wasm_path"));
605 assert!(debug_str.contains("module_name"));
606 }
607
608 #[test]
613 fn test_validate_wasm_magic_valid_module() {
614 let valid_wasm = create_minimal_wasm_module();
615 assert!(validate_wasm_magic(&valid_wasm).is_ok());
616 }
617
618 #[test]
619 fn test_validate_wasm_magic_valid_module_with_type_section() {
620 let valid_wasm = create_wasm_module_with_type_section();
621 assert!(validate_wasm_magic(&valid_wasm).is_ok());
622 }
623
624 #[test]
625 fn test_validate_wasm_magic_valid_component() {
626 let valid_component = create_minimal_wasm_component();
627 assert!(validate_wasm_magic(&valid_component).is_ok());
628 }
629
630 #[test]
631 fn test_validate_wasm_magic_invalid_bytes() {
632 let invalid_data = create_invalid_bytes();
633 let result = validate_wasm_magic(&invalid_data);
634 assert!(result.is_err());
635 match result {
636 Err(WasmExportError::InvalidWasmBinary { reason }) => {
637 assert!(reason.contains("invalid magic bytes"));
638 }
639 _ => panic!("expected InvalidWasmBinary error"),
640 }
641 }
642
643 #[test]
644 fn test_validate_wasm_magic_wrong_first_byte() {
645 let wrong_first = vec![0x01, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
647 let result = validate_wasm_magic(&wrong_first);
648 assert!(result.is_err());
649 match result {
650 Err(WasmExportError::InvalidWasmBinary { reason }) => {
651 assert!(reason.contains("invalid magic bytes"));
652 }
653 _ => panic!("expected InvalidWasmBinary error"),
654 }
655 }
656
657 #[test]
658 fn test_validate_wasm_magic_empty_bytes() {
659 let empty: Vec<u8> = vec![];
660 let result = validate_wasm_magic(&empty);
661 assert!(result.is_err());
662 match result {
663 Err(WasmExportError::InvalidWasmBinary { reason }) => {
664 assert!(reason.contains("too small"));
665 }
666 _ => panic!("expected InvalidWasmBinary error for empty input"),
667 }
668 }
669
670 #[test]
671 fn test_validate_wasm_magic_truncated_4_bytes() {
672 let too_small = vec![0x00, 0x61, 0x73, 0x6d];
674 let result = validate_wasm_magic(&too_small);
675 assert!(result.is_err());
676 match result {
677 Err(WasmExportError::InvalidWasmBinary { reason }) => {
678 assert!(reason.contains("too small"));
679 }
680 _ => panic!("expected InvalidWasmBinary error"),
681 }
682 }
683
684 #[test]
685 fn test_validate_wasm_magic_truncated_7_bytes() {
686 let too_small = vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00];
688 let result = validate_wasm_magic(&too_small);
689 assert!(result.is_err());
690 match result {
691 Err(WasmExportError::InvalidWasmBinary { reason }) => {
692 assert!(reason.contains("too small"));
693 }
694 _ => panic!("expected InvalidWasmBinary error"),
695 }
696 }
697
698 #[test]
699 fn test_validate_wasm_magic_exact_8_bytes_valid() {
700 let exact = vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
702 let result = validate_wasm_magic(&exact);
703 assert!(result.is_ok());
704 }
705
706 #[test]
707 fn test_validate_wasm_magic_elf_header() {
708 let elf = vec![0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00];
710 let result = validate_wasm_magic(&elf);
711 assert!(result.is_err());
712 }
713
714 #[test]
715 fn test_validate_wasm_magic_pe_header() {
716 let pe = vec![0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00];
718 let result = validate_wasm_magic(&pe);
719 assert!(result.is_err());
720 }
721
722 #[test]
727 fn test_detect_wasi_version_wasip1_minimal_module() {
728 let core_module = create_minimal_wasm_module();
729 let version = detect_wasi_version_from_binary(&core_module);
730 assert_eq!(version, WasiVersion::Preview1);
731 }
732
733 #[test]
734 fn test_detect_wasi_version_wasip1_with_type_section() {
735 let module = create_wasm_module_with_type_section();
736 let version = detect_wasi_version_from_binary(&module);
737 assert_eq!(version, WasiVersion::Preview1);
738 }
739
740 #[test]
741 fn test_detect_wasi_version_wasip1_with_custom_section() {
742 let module = create_wasm_module_with_custom_section();
743 let version = detect_wasi_version_from_binary(&module);
744 assert_eq!(version, WasiVersion::Preview1);
745 }
746
747 #[test]
748 fn test_detect_wasi_version_wasip2_component_type_marker() {
749 let component = create_minimal_wasm_component();
750 let version = detect_wasi_version_from_binary(&component);
751 assert_eq!(version, WasiVersion::Preview2);
752 }
753
754 #[test]
755 fn test_detect_wasi_version_wasip2_wit_component_marker() {
756 let component = create_wasm_component_with_wit_marker();
757 let version = detect_wasi_version_from_binary(&component);
758 assert_eq!(version, WasiVersion::Preview2);
759 }
760
761 #[test]
762 fn test_detect_wasi_version_empty_returns_unknown() {
763 let empty: Vec<u8> = vec![];
764 let version = detect_wasi_version_from_binary(&empty);
765 assert_eq!(version, WasiVersion::Unknown);
766 }
767
768 #[test]
769 fn test_detect_wasi_version_too_short_returns_unknown() {
770 let short = vec![0x00, 0x61, 0x73, 0x6d, 0x01];
772 let version = detect_wasi_version_from_binary(&short);
773 assert_eq!(version, WasiVersion::Unknown);
774 }
775
776 #[test]
777 fn test_detect_wasi_version_invalid_magic_returns_unknown() {
778 let invalid = create_invalid_bytes();
779 let version = detect_wasi_version_from_binary(&invalid);
780 assert_eq!(version, WasiVersion::Unknown);
781 }
782
783 #[test]
784 fn test_detect_wasi_version_unusual_version_returns_unknown() {
785 let unusual = create_invalid_version_bytes();
787 let version = detect_wasi_version_from_binary(&unusual);
788 assert_eq!(version, WasiVersion::Unknown);
789 }
790
791 #[test]
796 fn test_create_wasm_config_blob_returns_empty_json() {
797 let config_blob = create_wasm_config_blob();
798 assert_eq!(config_blob, b"{}");
799 }
800
801 #[test]
802 fn test_create_wasm_config_blob_valid_json() {
803 let config_blob = create_wasm_config_blob();
804 let parsed: Result<serde_json::Value, _> = serde_json::from_slice(&config_blob);
805 assert!(parsed.is_ok());
806 let value = parsed.unwrap();
807 assert!(value.is_object());
808 assert!(value.as_object().unwrap().is_empty());
809 }
810
811 #[test]
812 fn test_create_wasm_config_blob_consistent_digest() {
813 let blob1 = create_wasm_config_blob();
815 let blob2 = create_wasm_config_blob();
816 assert_eq!(blob1, blob2);
817
818 let digest1 = compute_digest(&blob1);
820 let digest2 = compute_digest(&blob2);
821 assert_eq!(digest1, digest2);
822 }
823
824 #[tokio::test]
829 async fn test_layer_descriptor_wasip1_media_type() {
830 let temp_dir = TempDir::new().unwrap();
831 let wasm_path = temp_dir.path().join("module.wasm");
832 let wasm_data = create_minimal_wasm_module();
833 fs::write(&wasm_path, &wasm_data).await.unwrap();
834
835 let config = WasmExportConfig {
836 wasm_path,
837 module_name: "test-module".to_string(),
838 wasi_version: Some(WasiVersion::Preview1),
839 annotations: HashMap::new(),
840 };
841
842 let result = export_wasm_as_oci(&config).await.unwrap();
843 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
844
845 assert_eq!(manifest.layers.len(), 1);
846 assert_eq!(manifest.layers[0].media_type, WASM_LAYER_MEDIA_TYPE_GENERIC);
847 }
848
849 #[tokio::test]
850 async fn test_layer_descriptor_wasip2_media_type() {
851 let temp_dir = TempDir::new().unwrap();
852 let wasm_path = temp_dir.path().join("component.wasm");
853 let wasm_data = create_minimal_wasm_component();
854 fs::write(&wasm_path, &wasm_data).await.unwrap();
855
856 let config = WasmExportConfig {
857 wasm_path,
858 module_name: "test-component".to_string(),
859 wasi_version: Some(WasiVersion::Preview2),
860 annotations: HashMap::new(),
861 };
862
863 let result = export_wasm_as_oci(&config).await.unwrap();
864 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
865
866 assert_eq!(manifest.layers[0].media_type, WASM_LAYER_MEDIA_TYPE_GENERIC);
868 }
869
870 #[tokio::test]
871 async fn test_layer_descriptor_digest_calculation() {
872 let temp_dir = TempDir::new().unwrap();
873 let wasm_path = temp_dir.path().join("module.wasm");
874 let wasm_data = create_wasm_module_with_type_section();
875 fs::write(&wasm_path, &wasm_data).await.unwrap();
876
877 let config = WasmExportConfig {
878 wasm_path,
879 module_name: "test-module".to_string(),
880 wasi_version: None,
881 annotations: HashMap::new(),
882 };
883
884 let result = export_wasm_as_oci(&config).await.unwrap();
885 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
886
887 let expected_digest = compute_digest(&wasm_data);
889 assert_eq!(manifest.layers[0].digest, expected_digest);
890 assert_eq!(result.wasm_layer_digest, expected_digest);
891 }
892
893 #[tokio::test]
894 async fn test_layer_descriptor_size_calculation() {
895 let temp_dir = TempDir::new().unwrap();
896 let wasm_path = temp_dir.path().join("module.wasm");
897 let wasm_data = create_wasm_module_with_type_section();
898 let expected_size = wasm_data.len() as u64;
899 fs::write(&wasm_path, &wasm_data).await.unwrap();
900
901 let config = WasmExportConfig {
902 wasm_path,
903 module_name: "test-module".to_string(),
904 wasi_version: None,
905 annotations: HashMap::new(),
906 };
907
908 let result = export_wasm_as_oci(&config).await.unwrap();
909 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
910
911 assert_eq!(manifest.layers[0].size, expected_size);
912 assert_eq!(result.wasm_size, expected_size);
913 }
914
915 #[tokio::test]
916 async fn test_layer_descriptor_has_title_annotation() {
917 let temp_dir = TempDir::new().unwrap();
918 let wasm_path = temp_dir.path().join("module.wasm");
919 fs::write(&wasm_path, &create_minimal_wasm_module())
920 .await
921 .unwrap();
922
923 let config = WasmExportConfig {
924 wasm_path,
925 module_name: "my-custom-module".to_string(),
926 wasi_version: None,
927 annotations: HashMap::new(),
928 };
929
930 let result = export_wasm_as_oci(&config).await.unwrap();
931 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
932
933 let layer_annotations = manifest.layers[0].annotations.as_ref().unwrap();
934 assert_eq!(
935 layer_annotations.get("org.opencontainers.image.title"),
936 Some(&"my-custom-module.wasm".to_string())
937 );
938 }
939
940 #[tokio::test]
945 async fn test_manifest_artifact_type_wasip1() {
946 let temp_dir = TempDir::new().unwrap();
947 let wasm_path = temp_dir.path().join("module.wasm");
948 fs::write(&wasm_path, &create_minimal_wasm_module())
949 .await
950 .unwrap();
951
952 let config = WasmExportConfig {
953 wasm_path,
954 module_name: "test".to_string(),
955 wasi_version: Some(WasiVersion::Preview1),
956 annotations: HashMap::new(),
957 };
958
959 let result = export_wasm_as_oci(&config).await.unwrap();
960 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
961
962 assert_eq!(
963 manifest.artifact_type,
964 Some(WASM_MODULE_ARTIFACT_TYPE.to_string())
965 );
966 assert_eq!(result.artifact_type, WASM_MODULE_ARTIFACT_TYPE);
967 }
968
969 #[tokio::test]
970 async fn test_manifest_artifact_type_wasip2() {
971 let temp_dir = TempDir::new().unwrap();
972 let wasm_path = temp_dir.path().join("component.wasm");
973 fs::write(&wasm_path, &create_minimal_wasm_component())
974 .await
975 .unwrap();
976
977 let config = WasmExportConfig {
978 wasm_path,
979 module_name: "test".to_string(),
980 wasi_version: Some(WasiVersion::Preview2),
981 annotations: HashMap::new(),
982 };
983
984 let result = export_wasm_as_oci(&config).await.unwrap();
985 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
986
987 assert_eq!(
988 manifest.artifact_type,
989 Some(WASM_COMPONENT_ARTIFACT_TYPE.to_string())
990 );
991 assert_eq!(result.artifact_type, WASM_COMPONENT_ARTIFACT_TYPE);
992 }
993
994 #[tokio::test]
995 async fn test_manifest_config_media_type() {
996 let temp_dir = TempDir::new().unwrap();
997 let wasm_path = temp_dir.path().join("module.wasm");
998 fs::write(&wasm_path, &create_minimal_wasm_module())
999 .await
1000 .unwrap();
1001
1002 let config = WasmExportConfig {
1003 wasm_path,
1004 module_name: "test".to_string(),
1005 wasi_version: None,
1006 annotations: HashMap::new(),
1007 };
1008
1009 let result = export_wasm_as_oci(&config).await.unwrap();
1010 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1011
1012 assert_eq!(manifest.config.media_type, WASM_CONFIG_MEDIA_TYPE_V0);
1013 }
1014
1015 #[tokio::test]
1016 async fn test_manifest_config_digest_and_size() {
1017 let temp_dir = TempDir::new().unwrap();
1018 let wasm_path = temp_dir.path().join("module.wasm");
1019 fs::write(&wasm_path, &create_minimal_wasm_module())
1020 .await
1021 .unwrap();
1022
1023 let config = WasmExportConfig {
1024 wasm_path,
1025 module_name: "test".to_string(),
1026 wasi_version: None,
1027 annotations: HashMap::new(),
1028 };
1029
1030 let result = export_wasm_as_oci(&config).await.unwrap();
1031 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1032
1033 let config_blob = create_wasm_config_blob();
1034 let expected_digest = compute_digest(&config_blob);
1035 let expected_size = config_blob.len() as u64;
1036
1037 assert_eq!(manifest.config.digest, expected_digest);
1038 assert_eq!(manifest.config.size, expected_size);
1039 assert_eq!(result.config_digest, expected_digest);
1040 assert_eq!(result.config_size, expected_size);
1041 }
1042
1043 #[tokio::test]
1044 async fn test_manifest_schema_version() {
1045 let temp_dir = TempDir::new().unwrap();
1046 let wasm_path = temp_dir.path().join("module.wasm");
1047 fs::write(&wasm_path, &create_minimal_wasm_module())
1048 .await
1049 .unwrap();
1050
1051 let config = WasmExportConfig {
1052 wasm_path,
1053 module_name: "test".to_string(),
1054 wasi_version: None,
1055 annotations: HashMap::new(),
1056 };
1057
1058 let result = export_wasm_as_oci(&config).await.unwrap();
1059 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1060
1061 assert_eq!(manifest.schema_version, 2);
1062 }
1063
1064 #[tokio::test]
1065 async fn test_manifest_media_type() {
1066 let temp_dir = TempDir::new().unwrap();
1067 let wasm_path = temp_dir.path().join("module.wasm");
1068 fs::write(&wasm_path, &create_minimal_wasm_module())
1069 .await
1070 .unwrap();
1071
1072 let config = WasmExportConfig {
1073 wasm_path,
1074 module_name: "test".to_string(),
1075 wasi_version: None,
1076 annotations: HashMap::new(),
1077 };
1078
1079 let result = export_wasm_as_oci(&config).await.unwrap();
1080 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1081
1082 assert_eq!(
1083 manifest.media_type,
1084 "application/vnd.oci.image.manifest.v1+json"
1085 );
1086 }
1087
1088 #[tokio::test]
1089 async fn test_manifest_layers_count() {
1090 let temp_dir = TempDir::new().unwrap();
1091 let wasm_path = temp_dir.path().join("module.wasm");
1092 fs::write(&wasm_path, &create_minimal_wasm_module())
1093 .await
1094 .unwrap();
1095
1096 let config = WasmExportConfig {
1097 wasm_path,
1098 module_name: "test".to_string(),
1099 wasi_version: None,
1100 annotations: HashMap::new(),
1101 };
1102
1103 let result = export_wasm_as_oci(&config).await.unwrap();
1104 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1105
1106 assert_eq!(manifest.layers.len(), 1);
1108 }
1109
1110 #[tokio::test]
1111 async fn test_manifest_annotations_propagate() {
1112 let temp_dir = TempDir::new().unwrap();
1113 let wasm_path = temp_dir.path().join("module.wasm");
1114 fs::write(&wasm_path, &create_minimal_wasm_module())
1115 .await
1116 .unwrap();
1117
1118 let mut annotations = HashMap::new();
1119 annotations.insert("org.example.custom".to_string(), "custom-value".to_string());
1120 annotations.insert("org.example.version".to_string(), "2.0.0".to_string());
1121
1122 let config = WasmExportConfig {
1123 wasm_path,
1124 module_name: "annotated-test".to_string(),
1125 wasi_version: None,
1126 annotations,
1127 };
1128
1129 let result = export_wasm_as_oci(&config).await.unwrap();
1130 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1131
1132 let manifest_annotations = manifest.annotations.unwrap();
1133 assert_eq!(
1134 manifest_annotations.get("org.example.custom"),
1135 Some(&"custom-value".to_string())
1136 );
1137 assert_eq!(
1138 manifest_annotations.get("org.example.version"),
1139 Some(&"2.0.0".to_string())
1140 );
1141 }
1142
1143 #[tokio::test]
1144 async fn test_manifest_auto_adds_title_annotation() {
1145 let temp_dir = TempDir::new().unwrap();
1146 let wasm_path = temp_dir.path().join("module.wasm");
1147 fs::write(&wasm_path, &create_minimal_wasm_module())
1148 .await
1149 .unwrap();
1150
1151 let config = WasmExportConfig {
1152 wasm_path,
1153 module_name: "auto-title-module".to_string(),
1154 wasi_version: None,
1155 annotations: HashMap::new(), };
1157
1158 let result = export_wasm_as_oci(&config).await.unwrap();
1159 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1160
1161 let manifest_annotations = manifest.annotations.unwrap();
1162 assert_eq!(
1163 manifest_annotations.get("org.opencontainers.image.title"),
1164 Some(&"auto-title-module".to_string())
1165 );
1166 }
1167
1168 #[tokio::test]
1169 async fn test_manifest_does_not_override_existing_title() {
1170 let temp_dir = TempDir::new().unwrap();
1171 let wasm_path = temp_dir.path().join("module.wasm");
1172 fs::write(&wasm_path, &create_minimal_wasm_module())
1173 .await
1174 .unwrap();
1175
1176 let mut annotations = HashMap::new();
1177 annotations.insert(
1178 "org.opencontainers.image.title".to_string(),
1179 "custom-title".to_string(),
1180 );
1181
1182 let config = WasmExportConfig {
1183 wasm_path,
1184 module_name: "module-name".to_string(),
1185 wasi_version: None,
1186 annotations,
1187 };
1188
1189 let result = export_wasm_as_oci(&config).await.unwrap();
1190 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1191
1192 let manifest_annotations = manifest.annotations.unwrap();
1193 assert_eq!(
1195 manifest_annotations.get("org.opencontainers.image.title"),
1196 Some(&"custom-title".to_string())
1197 );
1198 }
1199
1200 #[tokio::test]
1201 async fn test_manifest_no_annotations_when_empty() {
1202 let temp_dir = TempDir::new().unwrap();
1203 let wasm_path = temp_dir.path().join("module.wasm");
1204 fs::write(&wasm_path, &create_minimal_wasm_module())
1205 .await
1206 .unwrap();
1207
1208 let config = WasmExportConfig {
1210 wasm_path,
1211 module_name: "test".to_string(),
1212 wasi_version: None,
1213 annotations: HashMap::new(),
1214 };
1215
1216 let result = export_wasm_as_oci(&config).await.unwrap();
1217 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1218
1219 assert!(manifest.annotations.is_some());
1221 }
1222
1223 #[tokio::test]
1228 async fn test_export_wasip1_full_flow() {
1229 let temp_dir = TempDir::new().unwrap();
1230 let wasm_path = temp_dir.path().join("wasip1_module.wasm");
1231 let wasm_data = create_wasm_module_with_type_section();
1232 fs::write(&wasm_path, &wasm_data).await.unwrap();
1233
1234 let mut annotations = HashMap::new();
1235 annotations.insert("org.example.env".to_string(), "production".to_string());
1236
1237 let config = WasmExportConfig {
1238 wasm_path: wasm_path.clone(),
1239 module_name: "wasip1-integration-test".to_string(),
1240 wasi_version: None, annotations,
1242 };
1243
1244 let result = export_wasm_as_oci(&config).await.unwrap();
1245
1246 assert!(result.manifest_digest.starts_with("sha256:"));
1248 assert!(result.wasm_layer_digest.starts_with("sha256:"));
1249 assert!(result.config_digest.starts_with("sha256:"));
1250
1251 assert_eq!(result.wasi_version, WasiVersion::Preview1);
1253 assert_eq!(result.artifact_type, WASM_MODULE_ARTIFACT_TYPE);
1254
1255 assert_eq!(result.wasm_size, wasm_data.len() as u64);
1257 assert_eq!(result.config_size, 2); assert!(result.manifest_size > 0);
1259
1260 assert_eq!(result.wasm_binary, wasm_data);
1262 assert_eq!(result.config_blob, b"{}");
1263
1264 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1266 assert_eq!(manifest.schema_version, 2);
1267 assert_eq!(
1268 manifest.artifact_type,
1269 Some(WASM_MODULE_ARTIFACT_TYPE.to_string())
1270 );
1271 assert_eq!(manifest.layers.len(), 1);
1272 assert_eq!(manifest.layers[0].digest, result.wasm_layer_digest);
1273 assert_eq!(manifest.config.digest, result.config_digest);
1274
1275 let annotations = manifest.annotations.unwrap();
1277 assert_eq!(
1278 annotations.get("org.example.env"),
1279 Some(&"production".to_string())
1280 );
1281 }
1282
1283 #[tokio::test]
1284 async fn test_export_wasip2_full_flow() {
1285 let temp_dir = TempDir::new().unwrap();
1286 let wasm_path = temp_dir.path().join("wasip2_component.wasm");
1287 let wasm_data = create_minimal_wasm_component();
1288 fs::write(&wasm_path, &wasm_data).await.unwrap();
1289
1290 let config = WasmExportConfig {
1291 wasm_path: wasm_path.clone(),
1292 module_name: "wasip2-integration-test".to_string(),
1293 wasi_version: None, annotations: HashMap::new(),
1295 };
1296
1297 let result = export_wasm_as_oci(&config).await.unwrap();
1298
1299 assert_eq!(result.wasi_version, WasiVersion::Preview2);
1301 assert_eq!(result.artifact_type, WASM_COMPONENT_ARTIFACT_TYPE);
1302
1303 let manifest: OciManifest = serde_json::from_slice(&result.manifest_json).unwrap();
1305 assert_eq!(
1306 manifest.artifact_type,
1307 Some(WASM_COMPONENT_ARTIFACT_TYPE.to_string())
1308 );
1309 }
1310
1311 #[tokio::test]
1312 async fn test_export_with_explicit_version_override() {
1313 let temp_dir = TempDir::new().unwrap();
1314 let wasm_path = temp_dir.path().join("module.wasm");
1315 let wasm_data = create_minimal_wasm_module();
1317 fs::write(&wasm_path, &wasm_data).await.unwrap();
1318
1319 let config = WasmExportConfig {
1321 wasm_path,
1322 module_name: "override-test".to_string(),
1323 wasi_version: Some(WasiVersion::Preview2),
1324 annotations: HashMap::new(),
1325 };
1326
1327 let result = export_wasm_as_oci(&config).await.unwrap();
1328
1329 assert_eq!(result.wasi_version, WasiVersion::Preview2);
1331 assert_eq!(result.artifact_type, WASM_COMPONENT_ARTIFACT_TYPE);
1332 }
1333
1334 #[tokio::test]
1335 async fn test_export_error_invalid_binary() {
1336 let temp_dir = TempDir::new().unwrap();
1337 let wasm_path = temp_dir.path().join("invalid.wasm");
1338 fs::write(&wasm_path, b"not a wasm file at all")
1339 .await
1340 .unwrap();
1341
1342 let config = WasmExportConfig {
1343 wasm_path,
1344 module_name: "invalid".to_string(),
1345 wasi_version: None,
1346 annotations: HashMap::new(),
1347 };
1348
1349 let result = export_wasm_as_oci(&config).await;
1350 assert!(result.is_err());
1351
1352 match result {
1353 Err(WasmExportError::InvalidWasmBinary { reason }) => {
1354 assert!(reason.contains("invalid magic bytes"));
1355 }
1356 other => panic!("expected InvalidWasmBinary error, got {other:?}"),
1357 }
1358 }
1359
1360 #[tokio::test]
1361 async fn test_export_error_truncated_binary() {
1362 let temp_dir = TempDir::new().unwrap();
1363 let wasm_path = temp_dir.path().join("truncated.wasm");
1364 fs::write(&wasm_path, &[0x00, 0x61, 0x73, 0x6d])
1366 .await
1367 .unwrap();
1368
1369 let config = WasmExportConfig {
1370 wasm_path,
1371 module_name: "truncated".to_string(),
1372 wasi_version: None,
1373 annotations: HashMap::new(),
1374 };
1375
1376 let result = export_wasm_as_oci(&config).await;
1377 assert!(result.is_err());
1378
1379 match result {
1380 Err(WasmExportError::InvalidWasmBinary { reason }) => {
1381 assert!(reason.contains("too small"));
1382 }
1383 other => panic!("expected InvalidWasmBinary error, got {other:?}"),
1384 }
1385 }
1386
1387 #[tokio::test]
1388 async fn test_export_error_missing_file() {
1389 let config = WasmExportConfig {
1390 wasm_path: PathBuf::from("/nonexistent/path/to/module.wasm"),
1391 module_name: "missing".to_string(),
1392 wasi_version: None,
1393 annotations: HashMap::new(),
1394 };
1395
1396 let result = export_wasm_as_oci(&config).await;
1397 assert!(result.is_err());
1398
1399 match result {
1400 Err(WasmExportError::IoError(e)) => {
1401 assert_eq!(e.kind(), std::io::ErrorKind::NotFound);
1402 }
1403 other => panic!("expected IoError, got {other:?}"),
1404 }
1405 }
1406
1407 #[tokio::test]
1408 async fn test_export_error_permission_denied() {
1409 #[cfg(unix)]
1411 {
1412 use std::os::unix::fs::PermissionsExt;
1413
1414 let temp_dir = TempDir::new().unwrap();
1415 let wasm_path = temp_dir.path().join("unreadable.wasm");
1416 fs::write(&wasm_path, &create_minimal_wasm_module())
1417 .await
1418 .unwrap();
1419
1420 let metadata = std::fs::metadata(&wasm_path).unwrap();
1422 let mut perms = metadata.permissions();
1423 perms.set_mode(0o000);
1424 std::fs::set_permissions(&wasm_path, perms).unwrap();
1425
1426 let config = WasmExportConfig {
1427 wasm_path: wasm_path.clone(),
1428 module_name: "unreadable".to_string(),
1429 wasi_version: None,
1430 annotations: HashMap::new(),
1431 };
1432
1433 let result = export_wasm_as_oci(&config).await;
1434 assert!(result.is_err());
1435
1436 match &result {
1437 Err(WasmExportError::IoError(e)) => {
1438 assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied);
1439 }
1440 other => panic!("expected IoError(PermissionDenied), got {other:?}"),
1441 }
1442
1443 let mut perms = std::fs::metadata(&wasm_path).unwrap().permissions();
1445 perms.set_mode(0o644);
1446 std::fs::set_permissions(&wasm_path, perms).unwrap();
1447 }
1448 }
1449
1450 #[test]
1455 fn test_artifact_type_for_wasi_version_preview1() {
1456 assert_eq!(
1457 artifact_type_for_wasi_version(&WasiVersion::Preview1),
1458 WASM_MODULE_ARTIFACT_TYPE
1459 );
1460 }
1461
1462 #[test]
1463 fn test_artifact_type_for_wasi_version_preview2() {
1464 assert_eq!(
1465 artifact_type_for_wasi_version(&WasiVersion::Preview2),
1466 WASM_COMPONENT_ARTIFACT_TYPE
1467 );
1468 }
1469
1470 #[test]
1471 fn test_artifact_type_for_wasi_version_unknown() {
1472 assert_eq!(
1474 artifact_type_for_wasi_version(&WasiVersion::Unknown),
1475 WASM_MODULE_ARTIFACT_TYPE
1476 );
1477 }
1478
1479 #[test]
1484 fn test_contains_component_indicator_component_type() {
1485 let mut data = vec![0x00; 100];
1486 data[50..64].copy_from_slice(b"component-type");
1487 assert!(contains_component_indicator(&data));
1488 }
1489
1490 #[test]
1491 fn test_contains_component_indicator_wit_component() {
1492 let mut data = vec![0x00; 100];
1493 data[40..53].copy_from_slice(b"wit-component");
1494 assert!(contains_component_indicator(&data));
1495 }
1496
1497 #[test]
1498 fn test_contains_component_indicator_at_start() {
1499 let mut data = vec![0x00; 100];
1500 data[0..14].copy_from_slice(b"component-type");
1501 assert!(contains_component_indicator(&data));
1502 }
1503
1504 #[test]
1505 fn test_contains_component_indicator_at_end() {
1506 let mut data = vec![0x00; 100];
1507 data[86..100].copy_from_slice(b"component-type");
1508 assert!(contains_component_indicator(&data));
1509 }
1510
1511 #[test]
1512 fn test_contains_component_indicator_none() {
1513 let data = vec![0x00; 100];
1514 assert!(!contains_component_indicator(&data));
1515 }
1516
1517 #[test]
1518 fn test_contains_component_indicator_partial_match() {
1519 let mut data = vec![0x00; 100];
1520 data[50..60].copy_from_slice(b"component-");
1522 assert!(!contains_component_indicator(&data));
1523 }
1524
1525 #[test]
1526 fn test_contains_component_indicator_empty() {
1527 let data: Vec<u8> = vec![];
1528 assert!(!contains_component_indicator(&data));
1529 }
1530
1531 #[test]
1532 fn test_contains_component_indicator_too_short() {
1533 let data = vec![0x00; 5]; assert!(!contains_component_indicator(&data));
1535 }
1536
1537 #[test]
1542 fn test_wasm_export_error_display_invalid_binary() {
1543 let err = WasmExportError::InvalidWasmBinary {
1544 reason: "test reason".to_string(),
1545 };
1546 assert_eq!(err.to_string(), "invalid WASM binary: test reason");
1547 }
1548
1549 #[test]
1550 fn test_wasm_export_error_display_io_error() {
1551 let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
1552 let err = WasmExportError::IoError(io_err);
1553 assert!(err.to_string().contains("IO error"));
1554 }
1555
1556 #[test]
1557 fn test_wasm_export_error_display_serialization() {
1558 let err = WasmExportError::SerializationError;
1559 assert_eq!(
1560 err.to_string(),
1561 "serialization error: failed to serialize manifest or config"
1562 );
1563 }
1564
1565 #[test]
1566 fn test_wasm_export_error_display_storage() {
1567 let err = WasmExportError::StorageError {
1568 reason: "storage failed".to_string(),
1569 };
1570 assert_eq!(err.to_string(), "storage error: storage failed");
1571 }
1572
1573 #[test]
1574 fn test_wasm_export_error_from_io_error() {
1575 let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
1576 let export_err: WasmExportError = io_err.into();
1577 match export_err {
1578 WasmExportError::IoError(e) => {
1579 assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied);
1580 }
1581 _ => panic!("expected IoError variant"),
1582 }
1583 }
1584
1585 #[tokio::test]
1590 async fn test_wasm_export_result_all_fields_populated() {
1591 let temp_dir = TempDir::new().unwrap();
1592 let wasm_path = temp_dir.path().join("module.wasm");
1593 let wasm_data = create_minimal_wasm_module();
1594 fs::write(&wasm_path, &wasm_data).await.unwrap();
1595
1596 let config = WasmExportConfig {
1597 wasm_path,
1598 module_name: "test".to_string(),
1599 wasi_version: None,
1600 annotations: HashMap::new(),
1601 };
1602
1603 let result = export_wasm_as_oci(&config).await.unwrap();
1604
1605 assert!(result.manifest_digest.starts_with("sha256:"));
1607 assert_eq!(result.manifest_digest.len(), 7 + 64); assert!(result.wasm_layer_digest.starts_with("sha256:"));
1610 assert_eq!(result.wasm_layer_digest.len(), 7 + 64);
1611
1612 assert!(result.config_digest.starts_with("sha256:"));
1613 assert_eq!(result.config_digest.len(), 7 + 64);
1614
1615 assert!(result.manifest_size > 0);
1617 assert!(result.wasm_size > 0);
1618 assert!(result.config_size > 0);
1619
1620 assert!(!result.manifest_json.is_empty());
1622 assert!(!result.wasm_binary.is_empty());
1623 assert!(!result.config_blob.is_empty());
1624
1625 assert!(result.artifact_type.contains("wasm"));
1627 }
1628
1629 #[test]
1630 fn test_wasm_export_result_clone() {
1631 let result = WasmExportResult {
1632 manifest_digest: "sha256:abc123".to_string(),
1633 manifest_size: 100,
1634 wasm_layer_digest: "sha256:def456".to_string(),
1635 wasm_size: 200,
1636 config_digest: "sha256:ghi789".to_string(),
1637 config_size: 2,
1638 wasi_version: WasiVersion::Preview1,
1639 artifact_type: WASM_MODULE_ARTIFACT_TYPE.to_string(),
1640 manifest_json: b"{}".to_vec(),
1641 config_blob: b"{}".to_vec(),
1642 wasm_binary: vec![0x00, 0x61, 0x73, 0x6d],
1643 };
1644
1645 let cloned = result.clone();
1646
1647 assert_eq!(cloned.manifest_digest, result.manifest_digest);
1648 assert_eq!(cloned.wasm_layer_digest, result.wasm_layer_digest);
1649 assert_eq!(cloned.config_digest, result.config_digest);
1650 assert_eq!(cloned.manifest_size, result.manifest_size);
1651 assert_eq!(cloned.wasm_size, result.wasm_size);
1652 assert_eq!(cloned.config_size, result.config_size);
1653 assert_eq!(cloned.wasi_version, result.wasi_version);
1654 assert_eq!(cloned.artifact_type, result.artifact_type);
1655 assert_eq!(cloned.manifest_json, result.manifest_json);
1656 assert_eq!(cloned.config_blob, result.config_blob);
1657 assert_eq!(cloned.wasm_binary, result.wasm_binary);
1658 }
1659
1660 #[test]
1661 fn test_wasm_export_result_debug() {
1662 let result = WasmExportResult {
1663 manifest_digest: "sha256:test".to_string(),
1664 manifest_size: 100,
1665 wasm_layer_digest: "sha256:wasm".to_string(),
1666 wasm_size: 200,
1667 config_digest: "sha256:config".to_string(),
1668 config_size: 2,
1669 wasi_version: WasiVersion::Preview2,
1670 artifact_type: WASM_COMPONENT_ARTIFACT_TYPE.to_string(),
1671 manifest_json: vec![],
1672 config_blob: vec![],
1673 wasm_binary: vec![],
1674 };
1675
1676 let debug_str = format!("{result:?}");
1677 assert!(debug_str.contains("WasmExportResult"));
1678 assert!(debug_str.contains("manifest_digest"));
1679 assert!(debug_str.contains("Preview2"));
1680 }
1681
1682 #[test]
1687 fn test_oci_manifest_serialization() {
1688 let manifest = OciManifest {
1689 schema_version: 2,
1690 media_type: "application/vnd.oci.image.manifest.v1+json".to_string(),
1691 artifact_type: Some(WASM_MODULE_ARTIFACT_TYPE.to_string()),
1692 config: OciDescriptor {
1693 media_type: WASM_CONFIG_MEDIA_TYPE_V0.to_string(),
1694 digest: "sha256:test123".to_string(),
1695 size: 2,
1696 annotations: None,
1697 },
1698 layers: vec![OciDescriptor {
1699 media_type: WASM_LAYER_MEDIA_TYPE_GENERIC.to_string(),
1700 digest: "sha256:layer456".to_string(),
1701 size: 100,
1702 annotations: Some({
1703 let mut map = HashMap::new();
1704 map.insert(
1705 "org.opencontainers.image.title".to_string(),
1706 "test.wasm".to_string(),
1707 );
1708 map
1709 }),
1710 }],
1711 annotations: None,
1712 };
1713
1714 let json = serde_json::to_string(&manifest).unwrap();
1715 assert!(json.contains("schemaVersion"));
1716 assert!(json.contains("mediaType"));
1717 assert!(json.contains("artifactType"));
1718 assert!(json.contains("config"));
1719 assert!(json.contains("layers"));
1720 }
1721
1722 #[test]
1723 fn test_oci_manifest_deserialization() {
1724 let json = r#"{
1725 "schemaVersion": 2,
1726 "mediaType": "application/vnd.oci.image.manifest.v1+json",
1727 "artifactType": "application/vnd.wasm.module.v1+wasm",
1728 "config": {
1729 "mediaType": "application/vnd.wasm.config.v0+json",
1730 "digest": "sha256:abc",
1731 "size": 2
1732 },
1733 "layers": [{
1734 "mediaType": "application/wasm",
1735 "digest": "sha256:def",
1736 "size": 100
1737 }]
1738 }"#;
1739
1740 let manifest: OciManifest = serde_json::from_str(json).unwrap();
1741 assert_eq!(manifest.schema_version, 2);
1742 assert_eq!(
1743 manifest.artifact_type,
1744 Some(WASM_MODULE_ARTIFACT_TYPE.to_string())
1745 );
1746 assert_eq!(manifest.layers.len(), 1);
1747 }
1748
1749 #[test]
1750 fn test_oci_descriptor_serialization() {
1751 let descriptor = OciDescriptor {
1752 media_type: "application/wasm".to_string(),
1753 digest: "sha256:test".to_string(),
1754 size: 12345,
1755 annotations: Some({
1756 let mut map = HashMap::new();
1757 map.insert("key".to_string(), "value".to_string());
1758 map
1759 }),
1760 };
1761
1762 let json = serde_json::to_string(&descriptor).unwrap();
1763 assert!(json.contains("mediaType"));
1764 assert!(json.contains("digest"));
1765 assert!(json.contains("size"));
1766 assert!(json.contains("annotations"));
1767 }
1768
1769 #[test]
1770 fn test_oci_manifest_skip_empty_annotations() {
1771 let manifest = OciManifest {
1772 schema_version: 2,
1773 media_type: "application/vnd.oci.image.manifest.v1+json".to_string(),
1774 artifact_type: None,
1775 config: OciDescriptor {
1776 media_type: WASM_CONFIG_MEDIA_TYPE_V0.to_string(),
1777 digest: "sha256:test".to_string(),
1778 size: 2,
1779 annotations: None,
1780 },
1781 layers: vec![],
1782 annotations: None, };
1784
1785 let json = serde_json::to_string(&manifest).unwrap();
1786 assert!(!json.contains("annotations"));
1788 }
1789
1790 #[test]
1791 fn test_oci_manifest_skip_empty_artifact_type() {
1792 let manifest = OciManifest {
1793 schema_version: 2,
1794 media_type: "application/vnd.oci.image.manifest.v1+json".to_string(),
1795 artifact_type: None, config: OciDescriptor {
1797 media_type: WASM_CONFIG_MEDIA_TYPE_V0.to_string(),
1798 digest: "sha256:test".to_string(),
1799 size: 2,
1800 annotations: None,
1801 },
1802 layers: vec![],
1803 annotations: None,
1804 };
1805
1806 let json = serde_json::to_string(&manifest).unwrap();
1807 assert!(!json.contains("artifactType"));
1809 }
1810
1811 #[tokio::test]
1816 async fn test_digest_consistency_multiple_exports() {
1817 let temp_dir = TempDir::new().unwrap();
1818 let wasm_path = temp_dir.path().join("module.wasm");
1819 let wasm_data = create_minimal_wasm_module();
1820 fs::write(&wasm_path, &wasm_data).await.unwrap();
1821
1822 let config = WasmExportConfig {
1823 wasm_path: wasm_path.clone(),
1824 module_name: "consistency-test".to_string(),
1825 wasi_version: None,
1826 annotations: HashMap::new(),
1827 };
1828
1829 let result1 = export_wasm_as_oci(&config).await.unwrap();
1830 let result2 = export_wasm_as_oci(&config).await.unwrap();
1831
1832 assert_eq!(result1.manifest_digest, result2.manifest_digest);
1834 assert_eq!(result1.wasm_layer_digest, result2.wasm_layer_digest);
1835 assert_eq!(result1.config_digest, result2.config_digest);
1836 }
1837
1838 #[tokio::test]
1839 async fn test_digest_changes_with_different_binary() {
1840 let temp_dir = TempDir::new().unwrap();
1841
1842 let wasm_path1 = temp_dir.path().join("module1.wasm");
1844 fs::write(&wasm_path1, &create_minimal_wasm_module())
1845 .await
1846 .unwrap();
1847
1848 let config1 = WasmExportConfig {
1849 wasm_path: wasm_path1,
1850 module_name: "test".to_string(),
1851 wasi_version: None,
1852 annotations: HashMap::new(),
1853 };
1854
1855 let result1 = export_wasm_as_oci(&config1).await.unwrap();
1856
1857 let wasm_path2 = temp_dir.path().join("module2.wasm");
1859 fs::write(&wasm_path2, &create_wasm_module_with_type_section())
1860 .await
1861 .unwrap();
1862
1863 let config2 = WasmExportConfig {
1864 wasm_path: wasm_path2,
1865 module_name: "test".to_string(),
1866 wasi_version: None,
1867 annotations: HashMap::new(),
1868 };
1869
1870 let result2 = export_wasm_as_oci(&config2).await.unwrap();
1871
1872 assert_ne!(result1.wasm_layer_digest, result2.wasm_layer_digest);
1874 assert_ne!(result1.manifest_digest, result2.manifest_digest);
1876 assert_eq!(result1.config_digest, result2.config_digest);
1878 }
1879}