Skip to main content

zlayer_registry/
wasm.rs

1//! WASM artifact detection for OCI images
2//!
3//! This module provides types and utilities for detecting whether an OCI image
4//! is a WASM artifact (WebAssembly module) vs a traditional container image.
5//!
6//! ## Detection Strategy
7//!
8//! WASM artifacts can be identified through multiple signals:
9//! 1. The `artifact_type` field on the manifest (OCI 1.1+)
10//! 2. The `config.media_type` field
11//! 3. The layer media types
12//!
13//! The detection is performed in order of specificity:
14//! - If `artifact_type` is set and matches WASM patterns, use that
15//! - Otherwise check `config.media_type` for WASM config media type
16//! - Finally check layer media types for WASM binary layers
17
18use oci_client::manifest::{OciImageManifest, WASM_CONFIG_MEDIA_TYPE, WASM_LAYER_MEDIA_TYPE};
19use thiserror::Error;
20
21/// Media type for WASM component (wasip2) artifacts
22pub const WASM_COMPONENT_ARTIFACT_TYPE: &str = "application/vnd.wasm.component.v1+wasm";
23
24/// Media type for WASM module (wasip1) artifacts
25pub const WASM_MODULE_ARTIFACT_TYPE: &str = "application/vnd.wasm.module.v1+wasm";
26
27/// Alternative config media type used by some WASM tooling
28pub const WASM_CONFIG_MEDIA_TYPE_V0: &str = "application/vnd.wasm.config.v0+json";
29
30/// Alternative layer media type (generic application/wasm)
31pub const WASM_LAYER_MEDIA_TYPE_GENERIC: &str = "application/wasm";
32
33/// WASM binary magic bytes: `\0asm` (0x00, 0x61, 0x73, 0x6d)
34pub const WASM_MAGIC_BYTES: [u8; 4] = [0x00, 0x61, 0x73, 0x6d];
35
36/// Minimum size of a valid WASM binary (magic + version = 8 bytes)
37pub const WASM_MIN_SIZE: usize = 8;
38
39/// Error types for WASM binary analysis
40#[derive(Error, Debug, Clone, PartialEq, Eq)]
41pub enum WasmError {
42    /// Binary does not start with WASM magic bytes
43    #[error("invalid WASM magic bytes: expected \\0asm (0x00, 0x61, 0x73, 0x6d)")]
44    InvalidMagic,
45
46    /// Binary is too short to be a valid WASM module
47    #[error("WASM binary too short: expected at least {WASM_MIN_SIZE} bytes")]
48    TooShort,
49
50    /// Invalid or malformed WASM structure
51    #[error("invalid WASM structure: {reason}")]
52    InvalidStructure { reason: String },
53}
54
55/// Information extracted from a WASM binary
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct WasmBinaryInfo {
58    /// Detected WASI version based on binary analysis
59    pub wasi_version: WasiVersion,
60    /// Whether this is a component (`WASIp2`) vs a core module (`WASIp1`)
61    pub is_component: bool,
62    /// WASM binary format version (typically 1)
63    pub binary_version: u32,
64    /// Size of the binary in bytes
65    pub size: usize,
66}
67
68/// Artifact type detected from OCI manifest
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum ArtifactType {
71    /// Traditional container image (Linux containers, etc.)
72    Container,
73    /// WebAssembly artifact
74    Wasm {
75        /// WASI version detected from the artifact
76        wasi_version: WasiVersion,
77    },
78}
79
80impl ArtifactType {
81    /// Returns true if this is a WASM artifact
82    #[inline]
83    #[must_use]
84    pub fn is_wasm(&self) -> bool {
85        matches!(self, ArtifactType::Wasm { .. })
86    }
87
88    /// Returns true if this is a container image
89    #[inline]
90    #[must_use]
91    pub fn is_container(&self) -> bool {
92        matches!(self, ArtifactType::Container)
93    }
94
95    /// Returns the WASI version if this is a WASM artifact
96    #[must_use]
97    pub fn wasi_version(&self) -> Option<&WasiVersion> {
98        match self {
99            ArtifactType::Wasm { wasi_version } => Some(wasi_version),
100            ArtifactType::Container => None,
101        }
102    }
103}
104
105impl std::fmt::Display for ArtifactType {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        match self {
108            ArtifactType::Container => write!(f, "container"),
109            ArtifactType::Wasm { wasi_version } => write!(f, "wasm ({wasi_version})"),
110        }
111    }
112}
113
114/// WASI version detected from the artifact
115#[derive(Debug, Clone, PartialEq, Eq, Default)]
116pub enum WasiVersion {
117    /// WASI Preview 1 (wasip1) - core module
118    Preview1,
119    /// WASI Preview 2 (wasip2) - component model
120    Preview2,
121    /// Unable to determine WASI version
122    #[default]
123    Unknown,
124}
125
126impl WasiVersion {
127    /// Returns true if this is wasip1
128    #[inline]
129    #[must_use]
130    pub fn is_preview1(&self) -> bool {
131        matches!(self, WasiVersion::Preview1)
132    }
133
134    /// Returns true if this is wasip2 (component model)
135    #[inline]
136    #[must_use]
137    pub fn is_preview2(&self) -> bool {
138        matches!(self, WasiVersion::Preview2)
139    }
140
141    /// Returns the expected target triple suffix for this WASI version
142    #[must_use]
143    pub fn target_triple_suffix(&self) -> &'static str {
144        match self {
145            WasiVersion::Preview1 => "wasm32-wasip1",
146            WasiVersion::Preview2 => "wasm32-wasip2",
147            WasiVersion::Unknown => "wasm32-wasi",
148        }
149    }
150
151    /// Returns the OCI artifact type for this WASI version
152    ///
153    /// - `WASIp1` modules use `application/vnd.wasm.module.v1+wasm`
154    /// - `WASIp2` components use `application/vnd.wasm.component.v1+wasm`
155    #[must_use]
156    pub fn artifact_type(&self) -> &'static str {
157        match self {
158            WasiVersion::Preview1 | WasiVersion::Unknown => WASM_MODULE_ARTIFACT_TYPE,
159            WasiVersion::Preview2 => WASM_COMPONENT_ARTIFACT_TYPE,
160        }
161    }
162}
163
164impl std::fmt::Display for WasiVersion {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        match self {
167            WasiVersion::Preview1 => write!(f, "wasip1"),
168            WasiVersion::Preview2 => write!(f, "wasip2"),
169            WasiVersion::Unknown => write!(f, "unknown"),
170        }
171    }
172}
173
174// =============================================================================
175// WASM Binary Analysis Functions
176// =============================================================================
177
178/// Validate that a byte slice starts with the WASM magic bytes
179///
180/// WASM binaries must start with the magic bytes `\0asm` (0x00, 0x61, 0x73, 0x6d).
181///
182/// # Arguments
183///
184/// * `bytes` - The binary data to validate
185///
186/// # Returns
187///
188/// `true` if the bytes start with valid WASM magic, `false` otherwise.
189///
190/// # Examples
191///
192/// ```
193/// use zlayer_registry::wasm::validate_wasm_magic;
194///
195/// // Valid WASM magic
196/// let wasm_bytes = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
197/// assert!(validate_wasm_magic(&wasm_bytes));
198///
199/// // Invalid magic
200/// let invalid_bytes = [0x7f, 0x45, 0x4c, 0x46]; // ELF header
201/// assert!(!validate_wasm_magic(&invalid_bytes));
202///
203/// // Too short
204/// let short_bytes = [0x00, 0x61];
205/// assert!(!validate_wasm_magic(&short_bytes));
206/// ```
207#[inline]
208#[must_use]
209pub fn validate_wasm_magic(bytes: &[u8]) -> bool {
210    bytes.len() >= 4 && bytes[0..4] == WASM_MAGIC_BYTES
211}
212
213/// Detect WASI version by analyzing the WASM binary structure
214///
215/// This function examines the binary to determine if it's a:
216/// - **`WASIp2` Component**: Uses the component model with a component section (layer type 0x00
217///   after the 8-byte preamble indicates a component)
218/// - **`WASIp1` Module**: A core WebAssembly module with standard section types (0x01-0x0c)
219///
220/// # Binary Format Reference
221///
222/// Both modules and components start with:
223/// - Bytes 0-3: Magic bytes `\0asm`
224/// - Bytes 4-7: Version (little-endian u32, typically 1 for modules, varies for components)
225///
226/// After the preamble:
227/// - **Components (`WASIp2`)**: First section has type 0x00 (component section)
228/// - **Modules (`WASIp1`)**: Sections have types 0x01-0x0c (custom, type, import, etc.)
229///
230/// # Arguments
231///
232/// * `bytes` - The WASM binary data
233///
234/// # Returns
235///
236/// The detected `WasiVersion`:
237/// - `Preview2` for component model binaries
238/// - `Preview1` for core module binaries
239/// - `Unknown` if the binary is too short or structure is unclear
240///
241/// # Examples
242///
243/// ```
244/// use zlayer_registry::wasm::{detect_wasm_version_from_binary, WasiVersion};
245///
246/// // Core module with type section (0x01)
247/// let module_bytes = [
248///     0x00, 0x61, 0x73, 0x6d, // magic
249///     0x01, 0x00, 0x00, 0x00, // version 1
250///     0x01,                   // type section
251/// ];
252/// assert_eq!(detect_wasm_version_from_binary(&module_bytes), WasiVersion::Preview1);
253/// ```
254#[must_use]
255pub fn detect_wasm_version_from_binary(bytes: &[u8]) -> WasiVersion {
256    // Need at least magic (4) + version (4) + section type (1) = 9 bytes
257    if bytes.len() < 9 {
258        return WasiVersion::Unknown;
259    }
260
261    // Validate magic bytes first
262    if !validate_wasm_magic(bytes) {
263        return WasiVersion::Unknown;
264    }
265
266    // The section type byte comes after the 8-byte preamble
267    let first_section_type = bytes[8];
268
269    // Component model binaries have a component section with type 0x00
270    // Core modules have section types 0x01-0x0c:
271    //   0x00 = custom section (also valid in modules, but components use it differently)
272    //   0x01 = type section
273    //   0x02 = import section
274    //   0x03 = function section
275    //   0x04 = table section
276    //   0x05 = memory section
277    //   0x06 = global section
278    //   0x07 = export section
279    //   0x08 = start section
280    //   0x09 = element section
281    //   0x0a = code section
282    //   0x0b = data section
283    //   0x0c = data count section
284
285    // Check the binary version field to help distinguish
286    // Components typically use version 0x0d (13) or higher in the layer byte
287    // But the more reliable check is the section structure
288
289    // For a component, the first byte after preamble is typically 0x00 followed by
290    // component-specific encoding. For modules, first section is usually 0x01 (type)
291    // or 0x00 (custom section like name section).
292
293    // A more robust heuristic: check version bytes
294    // Core modules use version 1 (0x01, 0x00, 0x00, 0x00)
295    // Components use different version encoding
296    let version = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
297
298    // Component model uses version 0x0d000000 or similar high values
299    // Core WASM modules use version 0x00000001
300    if version == 1 {
301        // This is a core module (WASIp1)
302        // Additional validation: check that section type is valid for core module
303        if first_section_type <= 0x0c {
304            return WasiVersion::Preview1;
305        }
306    } else if version >= 0x0d {
307        // High version number indicates component model
308        return WasiVersion::Preview2;
309    }
310
311    // Fallback heuristic: if first section type is 0x00 and version != 1, likely component
312    if first_section_type == 0x00 && version != 1 {
313        return WasiVersion::Preview2;
314    }
315
316    WasiVersion::Unknown
317}
318
319/// Extract comprehensive information from a WASM binary
320///
321/// This function validates the binary structure and extracts metadata including
322/// the WASI version, whether it's a component, the binary format version, and size.
323///
324/// # Arguments
325///
326/// * `bytes` - The WASM binary data
327///
328/// # Returns
329///
330/// `Ok(WasmBinaryInfo)` with extracted information, or `Err(WasmError)` if the binary
331/// is invalid.
332///
333/// # Errors
334///
335/// - `WasmError::TooShort` - Binary is less than 8 bytes
336/// - `WasmError::InvalidMagic` - Binary doesn't start with WASM magic bytes
337/// - `WasmError::InvalidStructure` - Binary has invalid version or structure
338///
339/// # Examples
340///
341/// ```
342/// use zlayer_registry::wasm::{extract_wasm_binary_info, WasiVersion};
343///
344/// let module_bytes = [
345///     0x00, 0x61, 0x73, 0x6d, // magic
346///     0x01, 0x00, 0x00, 0x00, // version 1
347///     0x01,                   // type section
348/// ];
349///
350/// let info = extract_wasm_binary_info(&module_bytes).unwrap();
351/// assert_eq!(info.wasi_version, WasiVersion::Preview1);
352/// assert!(!info.is_component);
353/// assert_eq!(info.binary_version, 1);
354/// assert_eq!(info.size, 9);
355/// ```
356pub fn extract_wasm_binary_info(bytes: &[u8]) -> Result<WasmBinaryInfo, WasmError> {
357    // Check minimum size
358    if bytes.len() < WASM_MIN_SIZE {
359        return Err(WasmError::TooShort);
360    }
361
362    // Validate magic bytes
363    if !validate_wasm_magic(bytes) {
364        return Err(WasmError::InvalidMagic);
365    }
366
367    // Extract version (bytes 4-7, little-endian u32)
368    let binary_version = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
369
370    // Validate version is reasonable (known versions are 1 for modules, higher for components)
371    // Version 0 is invalid
372    if binary_version == 0 {
373        return Err(WasmError::InvalidStructure {
374            reason: "WASM version cannot be 0".to_string(),
375        });
376    }
377
378    // Detect WASI version
379    let wasi_version = detect_wasm_version_from_binary(bytes);
380
381    // Determine if this is a component based on version and detected WASI version
382    let is_component = wasi_version == WasiVersion::Preview2;
383
384    Ok(WasmBinaryInfo {
385        wasi_version,
386        is_component,
387        binary_version,
388        size: bytes.len(),
389    })
390}
391
392// =============================================================================
393// OCI Manifest Detection Functions
394// =============================================================================
395
396/// Detect artifact type from an OCI image manifest
397///
398/// Uses multiple detection strategies in order of specificity:
399/// 1. Check `artifact_type` field for WASM patterns (OCI 1.1+)
400/// 2. Check `config.media_type` for WASM config media type
401/// 3. Check layer media types for WASM binary layers
402///
403/// # Examples
404///
405/// ```
406/// use zlayer_registry::wasm::{detect_artifact_type, ArtifactType, WasiVersion};
407/// use oci_client::manifest::OciImageManifest;
408///
409/// // For a container image
410/// let manifest = OciImageManifest::default();
411/// let artifact_type = detect_artifact_type(&manifest);
412/// assert!(artifact_type.is_container());
413/// ```
414#[must_use]
415pub fn detect_artifact_type(manifest: &OciImageManifest) -> ArtifactType {
416    // Strategy 1: Check artifact_type field (most explicit)
417    if let Some(artifact_type) = &manifest.artifact_type {
418        if let Some(wasi_version) = detect_wasi_version_from_artifact_type(artifact_type) {
419            return ArtifactType::Wasm { wasi_version };
420        }
421    }
422
423    // Strategy 2: Check config media type
424    let config_media_type = &manifest.config.media_type;
425    if is_wasm_config_media_type(config_media_type) {
426        // Config indicates WASM, try to determine version from layers
427        let wasi_version = detect_wasi_version_from_layers(&manifest.layers);
428        return ArtifactType::Wasm { wasi_version };
429    }
430
431    // Strategy 3: Check layer media types
432    if has_wasm_layers(&manifest.layers) {
433        let wasi_version = detect_wasi_version_from_layers(&manifest.layers);
434        return ArtifactType::Wasm { wasi_version };
435    }
436
437    ArtifactType::Container
438}
439
440/// Check if a media type indicates a WASM config
441fn is_wasm_config_media_type(media_type: &str) -> bool {
442    media_type == WASM_CONFIG_MEDIA_TYPE
443        || media_type == WASM_CONFIG_MEDIA_TYPE_V0
444        || media_type.starts_with("application/vnd.wasm.config.")
445}
446
447/// Check if a media type indicates a WASM layer
448fn is_wasm_layer_media_type(media_type: &str) -> bool {
449    media_type == WASM_LAYER_MEDIA_TYPE
450        || media_type == WASM_LAYER_MEDIA_TYPE_GENERIC
451        || media_type.starts_with("application/vnd.wasm.content.layer.")
452        || media_type.ends_with("+wasm")
453}
454
455/// Detect WASI version from artifact type string
456fn detect_wasi_version_from_artifact_type(artifact_type: &str) -> Option<WasiVersion> {
457    match artifact_type {
458        WASM_COMPONENT_ARTIFACT_TYPE => Some(WasiVersion::Preview2),
459        WASM_MODULE_ARTIFACT_TYPE => Some(WasiVersion::Preview1),
460        // Generic WASM patterns
461        s if s.contains("component") && s.contains("wasm") => Some(WasiVersion::Preview2),
462        s if s.contains("module") && s.contains("wasm") => Some(WasiVersion::Preview1),
463        s if s.contains("wasm") => Some(WasiVersion::Unknown),
464        _ => None,
465    }
466}
467
468/// Check if any layers are WASM layers
469fn has_wasm_layers(layers: &[oci_client::manifest::OciDescriptor]) -> bool {
470    layers
471        .iter()
472        .any(|l| is_wasm_layer_media_type(&l.media_type))
473}
474
475/// Detect WASI version from layer media types and annotations
476fn detect_wasi_version_from_layers(layers: &[oci_client::manifest::OciDescriptor]) -> WasiVersion {
477    for layer in layers {
478        // Check media type for hints
479        let media_type = &layer.media_type;
480        if media_type.contains("component") {
481            return WasiVersion::Preview2;
482        }
483        if media_type.contains("module") {
484            return WasiVersion::Preview1;
485        }
486
487        // Check annotations for additional hints
488        if let Some(annotations) = &layer.annotations {
489            // Check for component model indicator
490            if annotations
491                .get("org.opencontainers.image.title")
492                .is_some_and(|t| t.contains("component"))
493            {
494                return WasiVersion::Preview2;
495            }
496
497            // Check for wit-component annotation
498            if annotations.contains_key("org.bytecodealliance.wit-component.version") {
499                return WasiVersion::Preview2;
500            }
501        }
502    }
503
504    WasiVersion::Unknown
505}
506
507/// Information about a WASM artifact extracted from manifest
508#[derive(Debug, Clone)]
509pub struct WasmArtifactInfo {
510    /// The detected WASI version
511    pub wasi_version: WasiVersion,
512    /// Digest of the WASM binary layer (if found)
513    pub wasm_layer_digest: Option<String>,
514    /// Size of the WASM binary in bytes
515    pub wasm_size: Option<i64>,
516    /// Title/name of the WASM module from annotations
517    pub module_name: Option<String>,
518}
519
520/// Extract detailed WASM artifact information from a manifest
521///
522/// Returns `None` if this is not a WASM artifact.
523#[must_use]
524pub fn extract_wasm_info(manifest: &OciImageManifest) -> Option<WasmArtifactInfo> {
525    let artifact_type = detect_artifact_type(manifest);
526    let wasi_version = artifact_type.wasi_version()?.clone();
527
528    // Find the WASM layer
529    let wasm_layer = manifest
530        .layers
531        .iter()
532        .find(|l| is_wasm_layer_media_type(&l.media_type));
533
534    let wasm_layer_digest = wasm_layer.map(|l| l.digest.clone());
535    let wasm_size = wasm_layer.map(|l| l.size);
536
537    // Extract module name from annotations
538    let module_name = wasm_layer.and_then(|l| {
539        l.annotations
540            .as_ref()?
541            .get("org.opencontainers.image.title")
542            .cloned()
543    });
544
545    Some(WasmArtifactInfo {
546        wasi_version,
547        wasm_layer_digest,
548        wasm_size,
549        module_name,
550    })
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556    use oci_client::manifest::{OciDescriptor, OciImageManifest};
557    use std::collections::BTreeMap;
558
559    fn make_container_manifest() -> OciImageManifest {
560        OciImageManifest {
561            schema_version: 2,
562            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
563            config: OciDescriptor {
564                media_type: "application/vnd.oci.image.config.v1+json".to_string(),
565                digest: "sha256:abc123".to_string(),
566                size: 1234,
567                urls: None,
568                annotations: None,
569            },
570            layers: vec![OciDescriptor {
571                media_type: "application/vnd.oci.image.layer.v1.tar+gzip".to_string(),
572                digest: "sha256:def456".to_string(),
573                size: 5678,
574                urls: None,
575                annotations: None,
576            }],
577            subject: None,
578            artifact_type: None,
579            annotations: None,
580        }
581    }
582
583    fn make_wasm_manifest_with_artifact_type() -> OciImageManifest {
584        OciImageManifest {
585            schema_version: 2,
586            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
587            config: OciDescriptor {
588                media_type: WASM_CONFIG_MEDIA_TYPE.to_string(),
589                digest: "sha256:abc123".to_string(),
590                size: 100,
591                urls: None,
592                annotations: None,
593            },
594            layers: vec![OciDescriptor {
595                media_type: WASM_LAYER_MEDIA_TYPE.to_string(),
596                digest: "sha256:wasm789".to_string(),
597                size: 1_615_998,
598                urls: None,
599                annotations: Some(BTreeMap::from([(
600                    "org.opencontainers.image.title".to_string(),
601                    "module.wasm".to_string(),
602                )])),
603            }],
604            subject: None,
605            artifact_type: Some(WASM_COMPONENT_ARTIFACT_TYPE.to_string()),
606            annotations: None,
607        }
608    }
609
610    fn make_wasm_manifest_config_only() -> OciImageManifest {
611        OciImageManifest {
612            schema_version: 2,
613            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
614            config: OciDescriptor {
615                media_type: WASM_CONFIG_MEDIA_TYPE.to_string(),
616                digest: "sha256:abc123".to_string(),
617                size: 100,
618                urls: None,
619                annotations: None,
620            },
621            layers: vec![OciDescriptor {
622                media_type: "application/wasm".to_string(),
623                digest: "sha256:wasm456".to_string(),
624                size: 500_000,
625                urls: None,
626                annotations: None,
627            }],
628            subject: None,
629            artifact_type: None,
630            annotations: None,
631        }
632    }
633
634    #[test]
635    fn test_detect_container() {
636        let manifest = make_container_manifest();
637        let artifact_type = detect_artifact_type(&manifest);
638        assert!(artifact_type.is_container());
639        assert!(!artifact_type.is_wasm());
640        assert_eq!(artifact_type.to_string(), "container");
641    }
642
643    #[test]
644    fn test_detect_wasm_with_artifact_type() {
645        let manifest = make_wasm_manifest_with_artifact_type();
646        let artifact_type = detect_artifact_type(&manifest);
647        assert!(artifact_type.is_wasm());
648        assert!(!artifact_type.is_container());
649        assert_eq!(artifact_type.wasi_version(), Some(&WasiVersion::Preview2));
650        assert_eq!(artifact_type.to_string(), "wasm (wasip2)");
651    }
652
653    #[test]
654    fn test_detect_wasm_config_only() {
655        let manifest = make_wasm_manifest_config_only();
656        let artifact_type = detect_artifact_type(&manifest);
657        assert!(artifact_type.is_wasm());
658        // Without artifact_type hint, falls back to Unknown
659        assert_eq!(artifact_type.wasi_version(), Some(&WasiVersion::Unknown));
660    }
661
662    #[test]
663    fn test_extract_wasm_info() {
664        let manifest = make_wasm_manifest_with_artifact_type();
665        let info = extract_wasm_info(&manifest);
666        assert!(info.is_some());
667
668        let info = info.unwrap();
669        assert_eq!(info.wasi_version, WasiVersion::Preview2);
670        assert_eq!(info.wasm_layer_digest, Some("sha256:wasm789".to_string()));
671        assert_eq!(info.wasm_size, Some(1_615_998));
672        assert_eq!(info.module_name, Some("module.wasm".to_string()));
673    }
674
675    #[test]
676    fn test_extract_wasm_info_container() {
677        let manifest = make_container_manifest();
678        let info = extract_wasm_info(&manifest);
679        assert!(info.is_none());
680    }
681
682    #[test]
683    fn test_wasi_version_display() {
684        assert_eq!(WasiVersion::Preview1.to_string(), "wasip1");
685        assert_eq!(WasiVersion::Preview2.to_string(), "wasip2");
686        assert_eq!(WasiVersion::Unknown.to_string(), "unknown");
687    }
688
689    #[test]
690    fn test_wasi_version_target_triple() {
691        assert_eq!(
692            WasiVersion::Preview1.target_triple_suffix(),
693            "wasm32-wasip1"
694        );
695        assert_eq!(
696            WasiVersion::Preview2.target_triple_suffix(),
697            "wasm32-wasip2"
698        );
699        assert_eq!(WasiVersion::Unknown.target_triple_suffix(), "wasm32-wasi");
700    }
701
702    #[test]
703    fn test_is_wasm_config_media_type() {
704        assert!(is_wasm_config_media_type(WASM_CONFIG_MEDIA_TYPE));
705        assert!(is_wasm_config_media_type(WASM_CONFIG_MEDIA_TYPE_V0));
706        assert!(is_wasm_config_media_type(
707            "application/vnd.wasm.config.v2+json"
708        ));
709        assert!(!is_wasm_config_media_type(
710            "application/vnd.oci.image.config.v1+json"
711        ));
712    }
713
714    #[test]
715    fn test_is_wasm_layer_media_type() {
716        assert!(is_wasm_layer_media_type(WASM_LAYER_MEDIA_TYPE));
717        assert!(is_wasm_layer_media_type(WASM_LAYER_MEDIA_TYPE_GENERIC));
718        assert!(is_wasm_layer_media_type(
719            "application/vnd.wasm.content.layer.v2+wasm"
720        ));
721        assert!(is_wasm_layer_media_type("application/vnd.custom.type+wasm"));
722        assert!(!is_wasm_layer_media_type(
723            "application/vnd.oci.image.layer.v1.tar+gzip"
724        ));
725    }
726
727    #[test]
728    fn test_detect_wasi_version_from_artifact_type() {
729        assert_eq!(
730            detect_wasi_version_from_artifact_type(WASM_COMPONENT_ARTIFACT_TYPE),
731            Some(WasiVersion::Preview2)
732        );
733        assert_eq!(
734            detect_wasi_version_from_artifact_type(WASM_MODULE_ARTIFACT_TYPE),
735            Some(WasiVersion::Preview1)
736        );
737        assert_eq!(
738            detect_wasi_version_from_artifact_type("application/vnd.custom.wasm"),
739            Some(WasiVersion::Unknown)
740        );
741        assert_eq!(
742            detect_wasi_version_from_artifact_type("application/json"),
743            None
744        );
745    }
746
747    // =========================================================================
748    // WASM Binary Analysis Tests
749    // =========================================================================
750
751    /// Helper to create a valid WASM module header (version 1)
752    fn make_wasm_module_bytes() -> Vec<u8> {
753        vec![
754            0x00, 0x61, 0x73, 0x6d, // magic: \0asm
755            0x01, 0x00, 0x00, 0x00, // version: 1 (little-endian)
756            0x01, // type section (0x01)
757            0x04, // section size: 4 bytes
758            0x01, // 1 type
759            0x60, // func type
760            0x00, // 0 params
761            0x00, // 0 results
762        ]
763    }
764
765    /// Helper to create a WASM component header (higher version)
766    fn make_wasm_component_bytes() -> Vec<u8> {
767        vec![
768            0x00, 0x61, 0x73, 0x6d, // magic: \0asm
769            0x0d, 0x00, 0x00, 0x00, // version: 13 (component model)
770            0x00, // component section type
771            0x08, // section size
772            0x00, 0x01, 0x02, 0x03, // some component data
773            0x04, 0x05, 0x06, 0x07,
774        ]
775    }
776
777    #[test]
778    fn test_validate_wasm_magic_valid() {
779        let bytes = make_wasm_module_bytes();
780        assert!(validate_wasm_magic(&bytes));
781    }
782
783    #[test]
784    fn test_validate_wasm_magic_component() {
785        let bytes = make_wasm_component_bytes();
786        assert!(validate_wasm_magic(&bytes));
787    }
788
789    #[test]
790    fn test_validate_wasm_magic_invalid() {
791        // ELF header
792        let elf_bytes = [0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00];
793        assert!(!validate_wasm_magic(&elf_bytes));
794
795        // Random garbage
796        let garbage = [0xde, 0xad, 0xbe, 0xef];
797        assert!(!validate_wasm_magic(&garbage));
798
799        // Almost correct (wrong first byte)
800        let almost = [0x01, 0x61, 0x73, 0x6d];
801        assert!(!validate_wasm_magic(&almost));
802    }
803
804    #[test]
805    fn test_validate_wasm_magic_too_short() {
806        let short = [0x00, 0x61, 0x73];
807        assert!(!validate_wasm_magic(&short));
808
809        let empty: [u8; 0] = [];
810        assert!(!validate_wasm_magic(&empty));
811    }
812
813    #[test]
814    fn test_validate_wasm_magic_exact_length() {
815        // Exactly 4 bytes with valid magic should pass
816        let exact = [0x00, 0x61, 0x73, 0x6d];
817        assert!(validate_wasm_magic(&exact));
818    }
819
820    #[test]
821    fn test_detect_wasm_version_from_binary_module() {
822        let bytes = make_wasm_module_bytes();
823        let version = detect_wasm_version_from_binary(&bytes);
824        assert_eq!(version, WasiVersion::Preview1);
825    }
826
827    #[test]
828    fn test_detect_wasm_version_from_binary_component() {
829        let bytes = make_wasm_component_bytes();
830        let version = detect_wasm_version_from_binary(&bytes);
831        assert_eq!(version, WasiVersion::Preview2);
832    }
833
834    #[test]
835    fn test_detect_wasm_version_from_binary_too_short() {
836        // Only 8 bytes (no section type byte)
837        let bytes = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
838        let version = detect_wasm_version_from_binary(&bytes);
839        assert_eq!(version, WasiVersion::Unknown);
840    }
841
842    #[test]
843    fn test_detect_wasm_version_from_binary_invalid_magic() {
844        let bytes = [0x7f, 0x45, 0x4c, 0x46, 0x01, 0x00, 0x00, 0x00, 0x01];
845        let version = detect_wasm_version_from_binary(&bytes);
846        assert_eq!(version, WasiVersion::Unknown);
847    }
848
849    #[test]
850    fn test_detect_wasm_version_custom_section() {
851        // Module with custom section (0x00) but version 1 should still detect as module
852        let bytes = vec![
853            0x00, 0x61, 0x73, 0x6d, // magic
854            0x01, 0x00, 0x00, 0x00, // version 1
855            0x00, // custom section (valid in both, but version disambiguates)
856            0x04, 0x6e, 0x61, 0x6d, 0x65, // "name" section
857        ];
858        let version = detect_wasm_version_from_binary(&bytes);
859        // Version 1 with section type <= 0x0c should be Preview1
860        assert_eq!(version, WasiVersion::Preview1);
861    }
862
863    #[test]
864    fn test_extract_wasm_binary_info_module() {
865        let bytes = make_wasm_module_bytes();
866        let info = extract_wasm_binary_info(&bytes).unwrap();
867
868        assert_eq!(info.wasi_version, WasiVersion::Preview1);
869        assert!(!info.is_component);
870        assert_eq!(info.binary_version, 1);
871        assert_eq!(info.size, bytes.len());
872    }
873
874    #[test]
875    fn test_extract_wasm_binary_info_component() {
876        let bytes = make_wasm_component_bytes();
877        let info = extract_wasm_binary_info(&bytes).unwrap();
878
879        assert_eq!(info.wasi_version, WasiVersion::Preview2);
880        assert!(info.is_component);
881        assert_eq!(info.binary_version, 13);
882        assert_eq!(info.size, bytes.len());
883    }
884
885    #[test]
886    fn test_extract_wasm_binary_info_too_short() {
887        let bytes = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00]; // 7 bytes
888        let result = extract_wasm_binary_info(&bytes);
889
890        assert!(result.is_err());
891        assert_eq!(result.unwrap_err(), WasmError::TooShort);
892    }
893
894    #[test]
895    fn test_extract_wasm_binary_info_invalid_magic() {
896        let bytes = [0x7f, 0x45, 0x4c, 0x46, 0x01, 0x00, 0x00, 0x00];
897        let result = extract_wasm_binary_info(&bytes);
898
899        assert!(result.is_err());
900        assert_eq!(result.unwrap_err(), WasmError::InvalidMagic);
901    }
902
903    #[test]
904    fn test_extract_wasm_binary_info_version_zero() {
905        let bytes = [
906            0x00, 0x61, 0x73, 0x6d, // magic
907            0x00, 0x00, 0x00, 0x00, // version 0 (invalid)
908        ];
909        let result = extract_wasm_binary_info(&bytes);
910
911        assert!(result.is_err());
912        match result.unwrap_err() {
913            WasmError::InvalidStructure { reason } => {
914                assert!(reason.contains("version"));
915            }
916            other => panic!("Expected InvalidStructure, got {other:?}"),
917        }
918    }
919
920    #[test]
921    fn test_wasm_error_display() {
922        assert_eq!(
923            WasmError::InvalidMagic.to_string(),
924            "invalid WASM magic bytes: expected \\0asm (0x00, 0x61, 0x73, 0x6d)"
925        );
926
927        assert_eq!(
928            WasmError::TooShort.to_string(),
929            "WASM binary too short: expected at least 8 bytes"
930        );
931
932        let structure_error = WasmError::InvalidStructure {
933            reason: "test reason".to_string(),
934        };
935        assert_eq!(
936            structure_error.to_string(),
937            "invalid WASM structure: test reason"
938        );
939    }
940
941    #[test]
942    fn test_wasm_binary_info_equality() {
943        let info1 = WasmBinaryInfo {
944            wasi_version: WasiVersion::Preview1,
945            is_component: false,
946            binary_version: 1,
947            size: 100,
948        };
949
950        let info2 = WasmBinaryInfo {
951            wasi_version: WasiVersion::Preview1,
952            is_component: false,
953            binary_version: 1,
954            size: 100,
955        };
956
957        let info3 = WasmBinaryInfo {
958            wasi_version: WasiVersion::Preview2,
959            is_component: true,
960            binary_version: 13,
961            size: 200,
962        };
963
964        assert_eq!(info1, info2);
965        assert_ne!(info1, info3);
966    }
967
968    #[test]
969    fn test_wasm_error_equality() {
970        assert_eq!(WasmError::InvalidMagic, WasmError::InvalidMagic);
971        assert_eq!(WasmError::TooShort, WasmError::TooShort);
972        assert_ne!(WasmError::InvalidMagic, WasmError::TooShort);
973
974        let err1 = WasmError::InvalidStructure {
975            reason: "test".to_string(),
976        };
977        let err2 = WasmError::InvalidStructure {
978            reason: "test".to_string(),
979        };
980        let err3 = WasmError::InvalidStructure {
981            reason: "other".to_string(),
982        };
983
984        assert_eq!(err1, err2);
985        assert_ne!(err1, err3);
986    }
987
988    #[test]
989    fn test_wasm_constants() {
990        // Verify magic bytes are correct
991        assert_eq!(WASM_MAGIC_BYTES, [0x00, 0x61, 0x73, 0x6d]);
992        assert_eq!(&WASM_MAGIC_BYTES, b"\0asm");
993
994        // Verify minimum size
995        assert_eq!(WASM_MIN_SIZE, 8);
996    }
997
998    // =========================================================================
999    // Additional validate_wasm_magic tests
1000    // =========================================================================
1001
1002    #[test]
1003    fn test_validate_wasm_magic_empty_bytes() {
1004        let empty: &[u8] = &[];
1005        assert!(!validate_wasm_magic(empty));
1006    }
1007
1008    #[test]
1009    fn test_validate_wasm_magic_single_byte() {
1010        let single = [0x00];
1011        assert!(!validate_wasm_magic(&single));
1012    }
1013
1014    #[test]
1015    fn test_validate_wasm_magic_two_bytes() {
1016        let two = [0x00, 0x61];
1017        assert!(!validate_wasm_magic(&two));
1018    }
1019
1020    #[test]
1021    fn test_validate_wasm_magic_three_bytes() {
1022        let three = [0x00, 0x61, 0x73];
1023        assert!(!validate_wasm_magic(&three));
1024    }
1025
1026    #[test]
1027    fn test_validate_wasm_magic_with_trailing_garbage() {
1028        // Valid magic followed by garbage should still pass (we only check first 4 bytes)
1029        let bytes = [0x00, 0x61, 0x73, 0x6d, 0xff, 0xff, 0xff, 0xff];
1030        assert!(validate_wasm_magic(&bytes));
1031    }
1032
1033    #[test]
1034    fn test_validate_wasm_magic_all_zeros() {
1035        let zeros = [0x00, 0x00, 0x00, 0x00];
1036        assert!(!validate_wasm_magic(&zeros));
1037    }
1038
1039    #[test]
1040    fn test_validate_wasm_magic_off_by_one_each_byte() {
1041        // Test each magic byte being wrong
1042        let wrong_byte_0 = [0x01, 0x61, 0x73, 0x6d];
1043        assert!(!validate_wasm_magic(&wrong_byte_0));
1044
1045        let wrong_byte_1 = [0x00, 0x62, 0x73, 0x6d];
1046        assert!(!validate_wasm_magic(&wrong_byte_1));
1047
1048        let wrong_byte_2 = [0x00, 0x61, 0x74, 0x6d];
1049        assert!(!validate_wasm_magic(&wrong_byte_2));
1050
1051        let wrong_byte_3 = [0x00, 0x61, 0x73, 0x6e];
1052        assert!(!validate_wasm_magic(&wrong_byte_3));
1053    }
1054
1055    // =========================================================================
1056    // Additional detect_wasm_version_from_binary tests
1057    // =========================================================================
1058
1059    #[test]
1060    fn test_detect_wasm_version_minimal_valid_module() {
1061        // Minimal valid module: magic + version + type section
1062        let bytes = [
1063            0x00, 0x61, 0x73, 0x6d, // magic
1064            0x01, 0x00, 0x00, 0x00, // version 1
1065            0x01, // type section marker
1066        ];
1067        let version = detect_wasm_version_from_binary(&bytes);
1068        assert_eq!(version, WasiVersion::Preview1);
1069    }
1070
1071    #[test]
1072    fn test_detect_wasm_version_minimal_valid_component() {
1073        // Minimal valid component: magic + version 13 + component section
1074        let bytes = [
1075            0x00, 0x61, 0x73, 0x6d, // magic
1076            0x0d, 0x00, 0x00, 0x00, // version 13
1077            0x00, // component section type
1078        ];
1079        let version = detect_wasm_version_from_binary(&bytes);
1080        assert_eq!(version, WasiVersion::Preview2);
1081    }
1082
1083    #[test]
1084    fn test_detect_wasm_version_module_with_import_section() {
1085        // Module with import section (0x02)
1086        let bytes = [
1087            0x00, 0x61, 0x73, 0x6d, // magic
1088            0x01, 0x00, 0x00, 0x00, // version 1
1089            0x02, // import section
1090        ];
1091        let version = detect_wasm_version_from_binary(&bytes);
1092        assert_eq!(version, WasiVersion::Preview1);
1093    }
1094
1095    #[test]
1096    fn test_detect_wasm_version_module_with_memory_section() {
1097        // Module with memory section (0x05)
1098        let bytes = [
1099            0x00, 0x61, 0x73, 0x6d, // magic
1100            0x01, 0x00, 0x00, 0x00, // version 1
1101            0x05, // memory section
1102        ];
1103        let version = detect_wasm_version_from_binary(&bytes);
1104        assert_eq!(version, WasiVersion::Preview1);
1105    }
1106
1107    #[test]
1108    fn test_detect_wasm_version_module_with_code_section() {
1109        // Module with code section (0x0a)
1110        let bytes = [
1111            0x00, 0x61, 0x73, 0x6d, // magic
1112            0x01, 0x00, 0x00, 0x00, // version 1
1113            0x0a, // code section
1114        ];
1115        let version = detect_wasm_version_from_binary(&bytes);
1116        assert_eq!(version, WasiVersion::Preview1);
1117    }
1118
1119    #[test]
1120    fn test_detect_wasm_version_module_with_data_count_section() {
1121        // Module with data count section (0x0c) - highest valid core module section
1122        let bytes = [
1123            0x00, 0x61, 0x73, 0x6d, // magic
1124            0x01, 0x00, 0x00, 0x00, // version 1
1125            0x0c, // data count section
1126        ];
1127        let version = detect_wasm_version_from_binary(&bytes);
1128        assert_eq!(version, WasiVersion::Preview1);
1129    }
1130
1131    #[test]
1132    fn test_detect_wasm_version_corrupt_section_type() {
1133        // Version 1 with invalid section type (> 0x0c)
1134        let bytes = [
1135            0x00, 0x61, 0x73, 0x6d, // magic
1136            0x01, 0x00, 0x00, 0x00, // version 1
1137            0x0f, // invalid section type for core module
1138        ];
1139        let version = detect_wasm_version_from_binary(&bytes);
1140        // Section type > 0x0c with version 1 should return Unknown
1141        assert_eq!(version, WasiVersion::Unknown);
1142    }
1143
1144    #[test]
1145    fn test_detect_wasm_version_version_2() {
1146        // Hypothetical version 2 module (should return Unknown as we don't recognize it)
1147        let bytes = [
1148            0x00, 0x61, 0x73, 0x6d, // magic
1149            0x02, 0x00, 0x00, 0x00, // version 2
1150            0x01, // type section
1151        ];
1152        let version = detect_wasm_version_from_binary(&bytes);
1153        // Version 2 is not recognized
1154        assert_eq!(version, WasiVersion::Unknown);
1155    }
1156
1157    #[test]
1158    fn test_detect_wasm_version_high_version_numbers() {
1159        // Test various high version numbers that indicate components
1160        for v in [0x0d, 0x0e, 0x0f, 0x10, 0x20, 0xff] {
1161            let bytes = [
1162                0x00, 0x61, 0x73, 0x6d, // magic
1163                v, 0x00, 0x00, 0x00, // high version
1164                0x00, // some section
1165            ];
1166            let version = detect_wasm_version_from_binary(&bytes);
1167            assert_eq!(
1168                version,
1169                WasiVersion::Preview2,
1170                "Expected Preview2 for version {v}",
1171            );
1172        }
1173    }
1174
1175    #[test]
1176    fn test_detect_wasm_version_exactly_8_bytes() {
1177        // Exactly 8 bytes (no section type) should return Unknown
1178        let bytes = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
1179        let version = detect_wasm_version_from_binary(&bytes);
1180        assert_eq!(version, WasiVersion::Unknown);
1181    }
1182
1183    #[test]
1184    fn test_detect_wasm_version_empty() {
1185        let empty: &[u8] = &[];
1186        let version = detect_wasm_version_from_binary(empty);
1187        assert_eq!(version, WasiVersion::Unknown);
1188    }
1189
1190    // =========================================================================
1191    // Additional extract_wasm_binary_info tests
1192    // =========================================================================
1193
1194    #[test]
1195    fn test_extract_wasm_binary_info_minimal_valid() {
1196        // Exactly 8 bytes with valid magic and version 1
1197        let bytes = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
1198        let info = extract_wasm_binary_info(&bytes).unwrap();
1199
1200        assert_eq!(info.binary_version, 1);
1201        assert_eq!(info.size, 8);
1202        // Without section type byte, version detection returns Unknown
1203        assert_eq!(info.wasi_version, WasiVersion::Unknown);
1204        assert!(!info.is_component);
1205    }
1206
1207    #[test]
1208    fn test_extract_wasm_binary_info_large_binary() {
1209        // Simulate a larger binary
1210        let mut bytes = vec![
1211            0x00, 0x61, 0x73, 0x6d, // magic
1212            0x01, 0x00, 0x00, 0x00, // version 1
1213            0x01, // type section
1214        ];
1215        // Add some padding to simulate a larger file
1216        bytes.extend(vec![0x00; 10000]);
1217
1218        let info = extract_wasm_binary_info(&bytes).unwrap();
1219        assert_eq!(info.size, 10009);
1220        assert_eq!(info.wasi_version, WasiVersion::Preview1);
1221    }
1222
1223    #[test]
1224    fn test_extract_wasm_binary_info_empty() {
1225        let empty: &[u8] = &[];
1226        let result = extract_wasm_binary_info(empty);
1227        assert!(result.is_err());
1228        assert_eq!(result.unwrap_err(), WasmError::TooShort);
1229    }
1230
1231    #[test]
1232    fn test_extract_wasm_binary_info_truncated_at_various_lengths() {
1233        // Test truncation at each byte position up to 7
1234        for len in 0..WASM_MIN_SIZE {
1235            let bytes = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
1236            let truncated = &bytes[..len];
1237            let result = extract_wasm_binary_info(truncated);
1238            assert!(
1239                result.is_err(),
1240                "Expected error for {len} bytes, got {result:?}",
1241            );
1242            assert_eq!(
1243                result.unwrap_err(),
1244                WasmError::TooShort,
1245                "Expected TooShort for {len} bytes",
1246            );
1247        }
1248    }
1249
1250    #[test]
1251    fn test_extract_wasm_binary_info_high_binary_version() {
1252        // High binary version should work and indicate component
1253        // Little-endian: 0x0d, 0x00, 0x01, 0x00 = 0x00_01_00_0d = 65549
1254        let bytes = [
1255            0x00, 0x61, 0x73, 0x6d, // magic
1256            0x0d, 0x00, 0x01, 0x00, // version 65549 in little-endian
1257            0x00, // section
1258        ];
1259        let info = extract_wasm_binary_info(&bytes).unwrap();
1260        assert_eq!(info.binary_version, 65549);
1261        assert!(info.is_component);
1262    }
1263
1264    #[test]
1265    fn test_extract_wasm_binary_info_fields_correct_for_module() {
1266        let bytes = make_wasm_module_bytes();
1267        let info = extract_wasm_binary_info(&bytes).unwrap();
1268
1269        // Verify all fields
1270        assert_eq!(info.wasi_version, WasiVersion::Preview1);
1271        assert!(!info.is_component);
1272        assert_eq!(info.binary_version, 1);
1273        assert_eq!(info.size, bytes.len());
1274
1275        // Verify is_component matches wasi_version
1276        assert_eq!(
1277            info.is_component,
1278            info.wasi_version == WasiVersion::Preview2
1279        );
1280    }
1281
1282    #[test]
1283    fn test_extract_wasm_binary_info_fields_correct_for_component() {
1284        let bytes = make_wasm_component_bytes();
1285        let info = extract_wasm_binary_info(&bytes).unwrap();
1286
1287        // Verify all fields
1288        assert_eq!(info.wasi_version, WasiVersion::Preview2);
1289        assert!(info.is_component);
1290        assert_eq!(info.binary_version, 13);
1291        assert_eq!(info.size, bytes.len());
1292
1293        // Verify is_component matches wasi_version
1294        assert_eq!(
1295            info.is_component,
1296            info.wasi_version == WasiVersion::Preview2
1297        );
1298    }
1299
1300    // =========================================================================
1301    // Additional WasmError tests
1302    // =========================================================================
1303
1304    #[test]
1305    fn test_wasm_error_debug_formatting() {
1306        let magic_err = WasmError::InvalidMagic;
1307        let debug_str = format!("{magic_err:?}");
1308        assert!(debug_str.contains("InvalidMagic"));
1309
1310        let short_err = WasmError::TooShort;
1311        let debug_str = format!("{short_err:?}");
1312        assert!(debug_str.contains("TooShort"));
1313
1314        let struct_err = WasmError::InvalidStructure {
1315            reason: "custom reason".to_string(),
1316        };
1317        let debug_str = format!("{struct_err:?}");
1318        assert!(debug_str.contains("InvalidStructure"));
1319        assert!(debug_str.contains("custom reason"));
1320    }
1321
1322    #[test]
1323    fn test_wasm_error_clone() {
1324        let err1 = WasmError::InvalidMagic;
1325        let err2 = err1.clone();
1326        assert_eq!(err1, err2);
1327
1328        let err3 = WasmError::InvalidStructure {
1329            reason: "test".to_string(),
1330        };
1331        let err4 = err3.clone();
1332        assert_eq!(err3, err4);
1333    }
1334
1335    #[test]
1336    fn test_wasm_error_invalid_structure_empty_reason() {
1337        let err = WasmError::InvalidStructure {
1338            reason: String::new(),
1339        };
1340        assert_eq!(err.to_string(), "invalid WASM structure: ");
1341    }
1342
1343    #[test]
1344    fn test_wasm_error_invalid_structure_long_reason() {
1345        let long_reason = "a".repeat(1000);
1346        let err = WasmError::InvalidStructure {
1347            reason: long_reason.clone(),
1348        };
1349        assert!(err.to_string().contains(&long_reason));
1350    }
1351
1352    // =========================================================================
1353    // Additional WasmBinaryInfo tests
1354    // =========================================================================
1355
1356    #[test]
1357    fn test_wasm_binary_info_debug_formatting() {
1358        let info = WasmBinaryInfo {
1359            wasi_version: WasiVersion::Preview1,
1360            is_component: false,
1361            binary_version: 1,
1362            size: 1024,
1363        };
1364
1365        let debug_str = format!("{info:?}");
1366        assert!(debug_str.contains("WasmBinaryInfo"));
1367        assert!(debug_str.contains("Preview1"));
1368        assert!(debug_str.contains("is_component"));
1369        assert!(debug_str.contains("binary_version"));
1370        assert!(debug_str.contains("size"));
1371    }
1372
1373    #[test]
1374    fn test_wasm_binary_info_clone() {
1375        let info1 = WasmBinaryInfo {
1376            wasi_version: WasiVersion::Preview2,
1377            is_component: true,
1378            binary_version: 13,
1379            size: 2048,
1380        };
1381
1382        let info2 = info1.clone();
1383        assert_eq!(info1, info2);
1384        assert_eq!(info2.wasi_version, WasiVersion::Preview2);
1385        assert!(info2.is_component);
1386        assert_eq!(info2.binary_version, 13);
1387        assert_eq!(info2.size, 2048);
1388    }
1389
1390    #[test]
1391    fn test_wasm_binary_info_inequality_each_field() {
1392        let base = WasmBinaryInfo {
1393            wasi_version: WasiVersion::Preview1,
1394            is_component: false,
1395            binary_version: 1,
1396            size: 100,
1397        };
1398
1399        // Different wasi_version
1400        let diff_version = WasmBinaryInfo {
1401            wasi_version: WasiVersion::Preview2,
1402            ..base.clone()
1403        };
1404        assert_ne!(base, diff_version);
1405
1406        // Different is_component
1407        let diff_component = WasmBinaryInfo {
1408            is_component: true,
1409            ..base.clone()
1410        };
1411        assert_ne!(base, diff_component);
1412
1413        // Different binary_version
1414        let diff_binary = WasmBinaryInfo {
1415            binary_version: 2,
1416            ..base.clone()
1417        };
1418        assert_ne!(base, diff_binary);
1419
1420        // Different size
1421        let diff_size = WasmBinaryInfo {
1422            size: 200,
1423            ..base.clone()
1424        };
1425        assert_ne!(base, diff_size);
1426    }
1427
1428    // =========================================================================
1429    // WasiVersion additional tests
1430    // =========================================================================
1431
1432    #[test]
1433    fn test_wasi_version_default() {
1434        let default: WasiVersion = WasiVersion::default();
1435        assert_eq!(default, WasiVersion::Unknown);
1436    }
1437
1438    #[test]
1439    fn test_wasi_version_clone() {
1440        let v1 = WasiVersion::Preview1;
1441        let v2 = v1.clone();
1442        assert_eq!(v1, v2);
1443
1444        let v3 = WasiVersion::Preview2;
1445        let v4 = v3.clone();
1446        assert_eq!(v3, v4);
1447    }
1448
1449    #[test]
1450    fn test_wasi_version_debug_formatting() {
1451        assert!(format!("{:?}", WasiVersion::Preview1).contains("Preview1"));
1452        assert!(format!("{:?}", WasiVersion::Preview2).contains("Preview2"));
1453        assert!(format!("{:?}", WasiVersion::Unknown).contains("Unknown"));
1454    }
1455
1456    #[test]
1457    fn test_wasi_version_is_methods() {
1458        let p1 = WasiVersion::Preview1;
1459        assert!(p1.is_preview1());
1460        assert!(!p1.is_preview2());
1461
1462        let p2 = WasiVersion::Preview2;
1463        assert!(!p2.is_preview1());
1464        assert!(p2.is_preview2());
1465
1466        let unknown = WasiVersion::Unknown;
1467        assert!(!unknown.is_preview1());
1468        assert!(!unknown.is_preview2());
1469    }
1470
1471    // =========================================================================
1472    // ArtifactType additional tests
1473    // =========================================================================
1474
1475    #[test]
1476    fn test_artifact_type_debug_formatting() {
1477        let container = ArtifactType::Container;
1478        assert!(format!("{container:?}").contains("Container"));
1479
1480        let wasm = ArtifactType::Wasm {
1481            wasi_version: WasiVersion::Preview1,
1482        };
1483        assert!(format!("{wasm:?}").contains("Wasm"));
1484        assert!(format!("{wasm:?}").contains("Preview1"));
1485    }
1486
1487    #[test]
1488    fn test_artifact_type_clone() {
1489        let container = ArtifactType::Container;
1490        let container_clone = container.clone();
1491        assert_eq!(container, container_clone);
1492
1493        let wasm = ArtifactType::Wasm {
1494            wasi_version: WasiVersion::Preview2,
1495        };
1496        let wasm_clone = wasm.clone();
1497        assert_eq!(wasm, wasm_clone);
1498    }
1499
1500    #[test]
1501    fn test_artifact_type_display_all_versions() {
1502        let p1 = ArtifactType::Wasm {
1503            wasi_version: WasiVersion::Preview1,
1504        };
1505        assert_eq!(p1.to_string(), "wasm (wasip1)");
1506
1507        let p2 = ArtifactType::Wasm {
1508            wasi_version: WasiVersion::Preview2,
1509        };
1510        assert_eq!(p2.to_string(), "wasm (wasip2)");
1511
1512        let unknown = ArtifactType::Wasm {
1513            wasi_version: WasiVersion::Unknown,
1514        };
1515        assert_eq!(unknown.to_string(), "wasm (unknown)");
1516    }
1517}