Skip to main content

zlayer_registry/
wasm_export.rs

1//! WASM export functionality for OCI registries
2//!
3//! This module provides functionality to export WebAssembly binaries as OCI artifacts,
4//! conforming to the WASM OCI artifact specification.
5//!
6//! ## OCI WASM Artifact Structure
7//!
8//! WASM artifacts in OCI registries follow a specific format:
9//! - Config blob: Empty JSON object with media type `application/vnd.wasm.config.v0+json`
10//! - Layer: The WASM binary with media type `application/wasm`
11//! - Artifact type: `application/vnd.wasm.component.v1+wasm` (`WASIp2`) or
12//!   `application/vnd.wasm.module.v1+wasm` (`WASIp1`)
13//!
14//! ## Usage
15//!
16//! ```rust,no_run
17//! use zlayer_registry::wasm_export::{WasmExportConfig, export_wasm_as_oci};
18//! use zlayer_registry::wasm::WasiVersion;
19//! use std::path::PathBuf;
20//!
21//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
22//! let config = WasmExportConfig {
23//!     wasm_path: PathBuf::from("/path/to/module.wasm"),
24//!     module_name: "my-module".to_string(),
25//!     wasi_version: Some(WasiVersion::Preview2),
26//!     annotations: Default::default(),
27//! };
28//!
29//! let result = export_wasm_as_oci(&config).await?;
30//! println!("WASM manifest digest: {}", result.manifest_digest);
31//! # Ok(())
32//! # }
33//! ```
34
35use 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
47/// WASM binary magic bytes: `\0asm`
48const WASM_MAGIC_BYTES: [u8; 4] = [0x00, 0x61, 0x73, 0x6d];
49
50/// WASM binary version for core module (wasip1)
51const WASM_VERSION_CORE: [u8; 4] = [0x01, 0x00, 0x00, 0x00];
52
53/// Component model magic/version indicator
54/// Components start with the core WASM magic followed by a component layer indicator
55const COMPONENT_LAYER_ID: u8 = 0x0d;
56
57/// Configuration for exporting a WASM binary as an OCI artifact
58#[derive(Debug, Clone)]
59pub struct WasmExportConfig {
60    /// Path to the WASM binary file
61    pub wasm_path: PathBuf,
62
63    /// Name for the WASM module (used in annotations)
64    pub module_name: String,
65
66    /// WASI version to use. If None, will be auto-detected from the binary
67    pub wasi_version: Option<WasiVersion>,
68
69    /// Additional annotations to include in the manifest
70    pub annotations: HashMap<String, String>,
71}
72
73/// Result of exporting a WASM binary as OCI artifact
74#[derive(Debug, Clone)]
75pub struct WasmExportResult {
76    /// Digest of the manifest (sha256:...)
77    pub manifest_digest: String,
78
79    /// Size of the manifest in bytes
80    pub manifest_size: u64,
81
82    /// Digest of the WASM layer (sha256:...)
83    pub wasm_layer_digest: String,
84
85    /// Size of the WASM binary in bytes
86    pub wasm_size: u64,
87
88    /// Digest of the config blob (sha256:...)
89    pub config_digest: String,
90
91    /// Size of the config blob in bytes
92    pub config_size: u64,
93
94    /// Detected or specified WASI version
95    pub wasi_version: WasiVersion,
96
97    /// The artifact type used in the manifest
98    pub artifact_type: String,
99
100    /// The serialized manifest JSON
101    pub manifest_json: Vec<u8>,
102
103    /// The config blob content
104    pub config_blob: Vec<u8>,
105
106    /// The WASM binary content
107    pub wasm_binary: Vec<u8>,
108}
109
110/// Errors that can occur during WASM export operations
111#[derive(Debug, Error)]
112pub enum WasmExportError {
113    /// The WASM binary is invalid or malformed
114    #[error("invalid WASM binary: {reason}")]
115    InvalidWasmBinary {
116        /// Description of why the binary is invalid
117        reason: String,
118    },
119
120    /// IO error reading the WASM file
121    #[error("IO error: {0}")]
122    IoError(#[from] std::io::Error),
123
124    /// JSON serialization error
125    #[error("serialization error: failed to serialize manifest or config")]
126    SerializationError,
127
128    /// Storage backend error
129    #[error("storage error: {reason}")]
130    StorageError {
131        /// Description of the storage error
132        reason: String,
133    },
134}
135
136/// OCI Image Manifest structure for WASM artifacts
137#[derive(Debug, Clone, Serialize, Deserialize)]
138struct OciManifest {
139    /// Schema version (must be 2)
140    #[serde(rename = "schemaVersion")]
141    schema_version: u32,
142
143    /// Media type of this manifest
144    #[serde(rename = "mediaType")]
145    media_type: String,
146
147    /// Artifact type indicating this is a WASM artifact
148    #[serde(rename = "artifactType", skip_serializing_if = "Option::is_none")]
149    artifact_type: Option<String>,
150
151    /// Config descriptor
152    config: OciDescriptor,
153
154    /// Layer descriptors
155    layers: Vec<OciDescriptor>,
156
157    /// Optional annotations
158    #[serde(skip_serializing_if = "Option::is_none")]
159    annotations: Option<HashMap<String, String>>,
160}
161
162/// OCI Content Descriptor
163#[derive(Debug, Clone, Serialize, Deserialize)]
164struct OciDescriptor {
165    /// MIME type of the referenced content
166    #[serde(rename = "mediaType")]
167    media_type: String,
168
169    /// Content digest (e.g., "sha256:...")
170    digest: String,
171
172    /// Size of the content in bytes
173    size: u64,
174
175    /// Optional annotations
176    #[serde(skip_serializing_if = "Option::is_none")]
177    annotations: Option<HashMap<String, String>>,
178}
179
180/// Validate WASM binary magic bytes
181fn 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
201/// Detect WASI version from WASM binary structure
202///
203/// This function analyzes the binary structure to determine if it's a
204/// `WASIp1` (core module) or `WASIp2` (component model) binary.
205///
206/// The detection is based on:
207/// - Core modules (WASIp1): Start with `\0asm` followed by version `0x01 0x00 0x00 0x00`
208/// - Components (WASIp2): Start with `\0asm` followed by version bytes, then contain
209///   a component layer indicator (0x0d) in the section IDs
210fn detect_wasi_version_from_binary(data: &[u8]) -> WasiVersion {
211    if data.len() < 8 {
212        return WasiVersion::Unknown;
213    }
214
215    // Check for component model indicator
216    // Components have a specific structure where the first section after the header
217    // contains a component layer indicator
218    let version_bytes = &data[4..8];
219
220    if version_bytes == WASM_VERSION_CORE {
221        // This is a core module format, but we need to check if it's actually
222        // a component wrapped in the new component model format
223        //
224        // Component model uses section ID 0x0d for custom sections
225        // We look for the component model layer indicator in the first few sections
226        if data.len() > 8 {
227            // Scan the first section ID to see if it's a component layer
228            let first_section_id = data[8];
229            if first_section_id == COMPONENT_LAYER_ID {
230                return WasiVersion::Preview2;
231            }
232
233            // Also check for the component model custom section pattern
234            // which can appear later in the binary
235            if contains_component_indicator(data) {
236                return WasiVersion::Preview2;
237            }
238        }
239
240        return WasiVersion::Preview1;
241    }
242
243    // Check for newer component model version format
244    // Component model version 0x0d indicates WASIp2
245    if version_bytes[0] == COMPONENT_LAYER_ID {
246        return WasiVersion::Preview2;
247    }
248
249    WasiVersion::Unknown
250}
251
252/// Check if the binary contains component model indicators
253///
254/// This scans for patterns that indicate this is a component model binary
255fn contains_component_indicator(data: &[u8]) -> bool {
256    // Component model binaries often contain specific custom sections
257    // Look for the "component-type" custom section name
258    const COMPONENT_TYPE_MARKER: &[u8] = b"component-type";
259    const WIT_COMPONENT_MARKER: &[u8] = b"wit-component";
260
261    // Simple sliding window search for markers
262    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
277/// Get the artifact type media type for a WASI version
278fn 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
285/// Create an empty config blob for WASM artifacts
286///
287/// WASM OCI artifacts use an empty JSON object as the config blob
288fn create_wasm_config_blob() -> Vec<u8> {
289    b"{}".to_vec()
290}
291
292/// Export a WASM binary as an OCI artifact
293///
294/// This function reads a WASM binary file, validates it, detects the WASI version,
295/// and creates the necessary OCI manifest and descriptors for storing it as an
296/// OCI artifact.
297///
298/// # Arguments
299///
300/// * `config` - Configuration specifying the WASM file path, module name, and options
301///
302/// # Returns
303///
304/// Returns a `WasmExportResult` containing all the generated blobs and manifest
305/// information needed to push the WASM artifact to an OCI registry.
306///
307/// # Errors
308///
309/// Returns an error if:
310/// - The WASM file cannot be read
311/// - The file is not a valid WASM binary (invalid magic bytes)
312/// - The manifest cannot be serialized
313///
314/// # Example
315///
316/// ```rust,no_run
317/// use zlayer_registry::wasm_export::{WasmExportConfig, export_wasm_as_oci};
318/// use std::path::PathBuf;
319///
320/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
321/// let config = WasmExportConfig {
322///     wasm_path: PathBuf::from("./target/wasm32-wasip2/release/my_module.wasm"),
323///     module_name: "my-module".to_string(),
324///     wasi_version: None, // Auto-detect
325///     annotations: Default::default(),
326/// };
327///
328/// let result = export_wasm_as_oci(&config).await?;
329///
330/// // The result contains all blobs ready for pushing to a registry:
331/// // - result.manifest_json: The OCI manifest
332/// // - result.config_blob: The config blob (empty JSON)
333/// // - result.wasm_binary: The WASM binary itself
334/// # Ok(())
335/// # }
336/// ```
337#[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    // Read the WASM binary
349    tracing::debug!("reading WASM binary from disk");
350    let wasm_binary = fs::read(&config.wasm_path).await?;
351
352    // Validate magic bytes
353    tracing::debug!("validating WASM magic bytes");
354    validate_wasm_magic(&wasm_binary)?;
355
356    // Determine WASI version
357    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    // Compute WASM layer digest
369    let wasm_layer_digest = compute_digest(&wasm_binary);
370    let wasm_size = wasm_binary.len() as u64;
371
372    // Create config blob (empty JSON for WASM artifacts)
373    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    // Determine artifact type based on WASI version
378    let artifact_type = artifact_type_for_wasi_version(&wasi_version);
379
380    // Build layer annotations
381    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    // Build manifest annotations
388    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    // Create the OCI manifest
397    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    // Serialize the manifest
421    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    // =========================================================================
457    // WASM Binary Helpers
458    // =========================================================================
459
460    /// Create a minimal valid `WASIp1` core module
461    fn create_minimal_wasm_module() -> Vec<u8> {
462        // Minimal valid WASM module:
463        // Magic: \0asm
464        // Version: 1.0.0.0
465        // Empty module (no sections)
466        vec![
467            0x00, 0x61, 0x73, 0x6d, // Magic: \0asm
468            0x01, 0x00, 0x00, 0x00, // Version: 1
469        ]
470    }
471
472    /// Create a minimal `WASIp1` module with a type section
473    fn create_wasm_module_with_type_section() -> Vec<u8> {
474        vec![
475            0x00, 0x61, 0x73, 0x6d, // Magic: \0asm
476            0x01, 0x00, 0x00, 0x00, // Version: 1
477            0x01, // Type section ID
478            0x04, // Section size: 4 bytes
479            0x01, // Number of types: 1
480            0x60, // Function type indicator
481            0x00, // Number of parameters: 0
482            0x00, // Number of results: 0
483        ]
484    }
485
486    /// Create a `WASIp1` module with a custom section (name section)
487    fn create_wasm_module_with_custom_section() -> Vec<u8> {
488        vec![
489            0x00, 0x61, 0x73, 0x6d, // Magic: \0asm
490            0x01, 0x00, 0x00, 0x00, // Version: 1
491            0x00, // Custom section ID (0x00)
492            0x05, // Section size: 5 bytes
493            0x04, // Name length: 4
494            0x6e, 0x61, 0x6d, 0x65, // "name"
495        ]
496    }
497
498    /// Create a minimal `WASIp2` component using component model layer version
499    fn create_minimal_wasm_component() -> Vec<u8> {
500        // Component model binaries start with the same magic but different version
501        let mut data = vec![
502            0x00, 0x61, 0x73, 0x6d, // Magic: \0asm
503            0x0d, 0x00, 0x01, 0x00, // Component layer version (0x0d = 13)
504        ];
505        // Add component-type marker for detection
506        data.extend_from_slice(b"component-type");
507        data
508    }
509
510    /// Create a `WASIp2` component with wit-component marker
511    fn create_wasm_component_with_wit_marker() -> Vec<u8> {
512        let mut data = vec![
513            0x00, 0x61, 0x73, 0x6d, // Magic: \0asm
514            0x0d, 0x00, 0x01, 0x00, // Component layer version
515        ];
516        // Add wit-component marker for detection
517        data.extend_from_slice(b"wit-component");
518        data
519    }
520
521    /// Create invalid bytes that look nothing like WASM
522    fn create_invalid_bytes() -> Vec<u8> {
523        vec![0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe]
524    }
525
526    /// Create bytes that have correct magic but wrong version structure
527    fn create_invalid_version_bytes() -> Vec<u8> {
528        vec![
529            0x00, 0x61, 0x73, 0x6d, // Magic: \0asm
530            0xff, 0xff, 0x00, 0x00, // Unusual version
531        ]
532    }
533
534    // =========================================================================
535    // WasmExportConfig Tests
536    // =========================================================================
537
538    #[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    // =========================================================================
609    // WASM Binary Validation Tests
610    // =========================================================================
611
612    #[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        // First byte is 0x01 instead of 0x00
646        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        // Only magic, no version
673        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        // Missing one byte of version
687        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        // Exactly magic + version, no sections
701        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        // ELF binary magic bytes
709        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        // Windows PE header (MZ)
717        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    // =========================================================================
723    // WASI Version Detection Tests
724    // =========================================================================
725
726    #[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        // Less than 8 bytes
771        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        // Valid magic but unusual version that doesn't match known patterns
786        let unusual = create_invalid_version_bytes();
787        let version = detect_wasi_version_from_binary(&unusual);
788        assert_eq!(version, WasiVersion::Unknown);
789    }
790
791    // =========================================================================
792    // Config Blob Creation Tests
793    // =========================================================================
794
795    #[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        // Multiple calls should produce identical blob
814        let blob1 = create_wasm_config_blob();
815        let blob2 = create_wasm_config_blob();
816        assert_eq!(blob1, blob2);
817
818        // Verify digest is consistent
819        let digest1 = compute_digest(&blob1);
820        let digest2 = compute_digest(&blob2);
821        assert_eq!(digest1, digest2);
822    }
823
824    // =========================================================================
825    // Layer Descriptor Tests
826    // =========================================================================
827
828    #[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        // Layer media type is the same for both WASIp1 and WASIp2
867        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        // Verify the digest matches what we compute directly
888        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    // =========================================================================
941    // Manifest Building Tests
942    // =========================================================================
943
944    #[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        // WASM artifacts have exactly one layer
1107        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(), // Empty - should auto-add title
1156        };
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        // Should keep the custom title, not replace with module_name
1194        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        // Even with empty annotations, title is auto-added
1209        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        // Annotations should be present because title is auto-added
1220        assert!(manifest.annotations.is_some());
1221    }
1222
1223    // =========================================================================
1224    // Export Integration Tests
1225    // =========================================================================
1226
1227    #[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, // Auto-detect
1241            annotations,
1242        };
1243
1244        let result = export_wasm_as_oci(&config).await.unwrap();
1245
1246        // Verify overall result structure
1247        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        // Verify WASI version detection
1252        assert_eq!(result.wasi_version, WasiVersion::Preview1);
1253        assert_eq!(result.artifact_type, WASM_MODULE_ARTIFACT_TYPE);
1254
1255        // Verify sizes
1256        assert_eq!(result.wasm_size, wasm_data.len() as u64);
1257        assert_eq!(result.config_size, 2); // "{}"
1258        assert!(result.manifest_size > 0);
1259
1260        // Verify binary content
1261        assert_eq!(result.wasm_binary, wasm_data);
1262        assert_eq!(result.config_blob, b"{}");
1263
1264        // Verify manifest JSON is well-formed
1265        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        // Verify custom annotations
1276        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, // Auto-detect
1294            annotations: HashMap::new(),
1295        };
1296
1297        let result = export_wasm_as_oci(&config).await.unwrap();
1298
1299        // Verify WASI version detection
1300        assert_eq!(result.wasi_version, WasiVersion::Preview2);
1301        assert_eq!(result.artifact_type, WASM_COMPONENT_ARTIFACT_TYPE);
1302
1303        // Verify manifest structure
1304        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        // Write a WASIp1 module
1316        let wasm_data = create_minimal_wasm_module();
1317        fs::write(&wasm_path, &wasm_data).await.unwrap();
1318
1319        // But specify WASIp2 explicitly
1320        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        // Should use the explicit version, not auto-detected
1330        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        // Only magic, missing version bytes
1365        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        // Skip this test on non-Unix systems where permission behavior differs
1410        #[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            // Remove read permissions
1421            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            // Restore permissions for cleanup
1444            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    // =========================================================================
1451    // Artifact Type Mapping Tests
1452    // =========================================================================
1453
1454    #[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        // Unknown defaults to module type
1473        assert_eq!(
1474            artifact_type_for_wasi_version(&WasiVersion::Unknown),
1475            WASM_MODULE_ARTIFACT_TYPE
1476        );
1477    }
1478
1479    // =========================================================================
1480    // Component Indicator Detection Tests
1481    // =========================================================================
1482
1483    #[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        // Only partial marker - should not match
1521        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]; // Shorter than marker
1534        assert!(!contains_component_indicator(&data));
1535    }
1536
1537    // =========================================================================
1538    // Error Display Tests
1539    // =========================================================================
1540
1541    #[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    // =========================================================================
1586    // Result Structure Tests
1587    // =========================================================================
1588
1589    #[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        // All digest fields should be populated and valid
1606        assert!(result.manifest_digest.starts_with("sha256:"));
1607        assert_eq!(result.manifest_digest.len(), 7 + 64); // "sha256:" + 64 hex chars
1608
1609        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        // Size fields should be non-zero (except possibly for very small inputs)
1616        assert!(result.manifest_size > 0);
1617        assert!(result.wasm_size > 0);
1618        assert!(result.config_size > 0);
1619
1620        // Binary content should be populated
1621        assert!(!result.manifest_json.is_empty());
1622        assert!(!result.wasm_binary.is_empty());
1623        assert!(!result.config_blob.is_empty());
1624
1625        // Version and artifact type should be set
1626        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    // =========================================================================
1683    // OCI Manifest Structure Tests
1684    // =========================================================================
1685
1686    #[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, // Should be skipped in serialization
1783        };
1784
1785        let json = serde_json::to_string(&manifest).unwrap();
1786        // annotations field should not appear when None
1787        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, // Should be skipped
1796            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        // artifactType should not appear when None
1808        assert!(!json.contains("artifactType"));
1809    }
1810
1811    // =========================================================================
1812    // Digest Consistency Tests
1813    // =========================================================================
1814
1815    #[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        // Same input should produce same digests
1833        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        // First export
1843        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        // Second export with different binary
1858        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        // Different binaries should produce different layer digests
1873        assert_ne!(result1.wasm_layer_digest, result2.wasm_layer_digest);
1874        // And different manifest digests (since layer digest changed)
1875        assert_ne!(result1.manifest_digest, result2.manifest_digest);
1876        // But config digest should be the same (empty JSON)
1877        assert_eq!(result1.config_digest, result2.config_digest);
1878    }
1879}