Skip to main content

rustbridge_bundle/
builder.rs

1//! Bundle creation utilities.
2//!
3//! The [`BundleBuilder`] provides a fluent API for creating `.rbp` bundle archives.
4
5use crate::{BundleError, BundleResult, MANIFEST_FILE, Manifest, Platform};
6use minisign::SecretKey;
7use sha2::{Digest, Sha256};
8use std::fs::{self, File};
9use std::io::Write;
10use std::path::Path;
11use zip::ZipWriter;
12use zip::write::SimpleFileOptions;
13
14/// Builder for creating plugin bundles.
15///
16/// # Example
17///
18/// ```no_run
19/// use rustbridge_bundle::{BundleBuilder, Manifest, Platform};
20///
21/// let manifest = Manifest::new("my-plugin", "1.0.0");
22/// let builder = BundleBuilder::new(manifest)
23///     .add_library(Platform::LinuxX86_64, "target/release/libmyplugin.so")?
24///     .add_schema_file("schema/messages.h", "include/messages.h")?;
25///
26/// builder.write("my-plugin-1.0.0.rbp")?;
27/// # Ok::<(), rustbridge_bundle::BundleError>(())
28/// ```
29#[derive(Debug)]
30pub struct BundleBuilder {
31    manifest: Manifest,
32    files: Vec<BundleFile>,
33    signing_key: Option<(String, SecretKey)>, // (public_key_base64, secret_key)
34}
35
36/// A file to include in the bundle.
37#[derive(Debug)]
38struct BundleFile {
39    /// Path within the bundle archive.
40    archive_path: String,
41    /// File contents.
42    contents: Vec<u8>,
43}
44
45impl BundleBuilder {
46    /// Create a new bundle builder with the given manifest.
47    #[must_use]
48    pub fn new(manifest: Manifest) -> Self {
49        Self {
50            manifest,
51            files: Vec::new(),
52            signing_key: None,
53        }
54    }
55
56    /// Set the signing key for bundle signing.
57    ///
58    /// The secret key will be used to sign all library files and the manifest.
59    /// The corresponding public key will be embedded in the manifest.
60    ///
61    /// # Arguments
62    /// * `public_key_base64` - The public key in base64 format (from the .pub file)
63    /// * `secret_key` - The secret key for signing
64    pub fn with_signing_key(mut self, public_key_base64: String, secret_key: SecretKey) -> Self {
65        self.manifest.set_public_key(public_key_base64.clone());
66        self.signing_key = Some((public_key_base64, secret_key));
67        self
68    }
69
70    /// Add a platform-specific library to the bundle as the release variant.
71    ///
72    /// This reads the library file, computes its SHA256 checksum,
73    /// and updates the manifest with the platform information.
74    ///
75    /// This is a convenience method that adds the library as the `release` variant.
76    /// For other variants, use `add_library_variant` instead.
77    pub fn add_library<P: AsRef<Path>>(
78        self,
79        platform: Platform,
80        library_path: P,
81    ) -> BundleResult<Self> {
82        self.add_library_variant(platform, "release", library_path)
83    }
84
85    /// Add a variant-specific library to the bundle.
86    ///
87    /// This reads the library file, computes its SHA256 checksum,
88    /// and updates the manifest with the platform and variant information.
89    ///
90    /// # Arguments
91    /// * `platform` - Target platform
92    /// * `variant` - Variant name (e.g., "release", "debug")
93    /// * `library_path` - Path to the library file
94    pub fn add_library_variant<P: AsRef<Path>>(
95        mut self,
96        platform: Platform,
97        variant: &str,
98        library_path: P,
99    ) -> BundleResult<Self> {
100        let library_path = library_path.as_ref();
101
102        // Read the library file
103        let contents = fs::read(library_path).map_err(|e| {
104            BundleError::LibraryNotFound(format!("{}: {}", library_path.display(), e))
105        })?;
106
107        // Compute SHA256 checksum
108        let checksum = compute_sha256(&contents);
109
110        // Determine the archive path (now includes variant)
111        let file_name = library_path
112            .file_name()
113            .ok_or_else(|| {
114                BundleError::InvalidManifest(format!(
115                    "Invalid library path: {}",
116                    library_path.display()
117                ))
118            })?
119            .to_string_lossy();
120        let archive_path = format!("lib/{}/{}/{}", platform.as_str(), variant, file_name);
121
122        // Update manifest
123        self.manifest
124            .add_platform_variant(platform, variant, &archive_path, &checksum, None);
125
126        // Add to files list
127        self.files.push(BundleFile {
128            archive_path,
129            contents,
130        });
131
132        Ok(self)
133    }
134
135    /// Add a variant-specific library with build metadata.
136    ///
137    /// Similar to `add_library_variant` but also attaches build metadata
138    /// to the variant (e.g., compiler flags, features, etc.).
139    pub fn add_library_variant_with_build<P: AsRef<Path>>(
140        mut self,
141        platform: Platform,
142        variant: &str,
143        library_path: P,
144        build: serde_json::Value,
145    ) -> BundleResult<Self> {
146        let library_path = library_path.as_ref();
147
148        // Read the library file
149        let contents = fs::read(library_path).map_err(|e| {
150            BundleError::LibraryNotFound(format!("{}: {}", library_path.display(), e))
151        })?;
152
153        // Compute SHA256 checksum
154        let checksum = compute_sha256(&contents);
155
156        // Determine the archive path
157        let file_name = library_path
158            .file_name()
159            .ok_or_else(|| {
160                BundleError::InvalidManifest(format!(
161                    "Invalid library path: {}",
162                    library_path.display()
163                ))
164            })?
165            .to_string_lossy();
166        let archive_path = format!("lib/{}/{}/{}", platform.as_str(), variant, file_name);
167
168        // Update manifest with build metadata
169        self.manifest.add_platform_variant(
170            platform,
171            variant,
172            &archive_path,
173            &checksum,
174            Some(build),
175        );
176
177        // Add to files list
178        self.files.push(BundleFile {
179            archive_path,
180            contents,
181        });
182
183        Ok(self)
184    }
185
186    /// Add a schema file to the bundle.
187    ///
188    /// Schema files are stored in the `schema/` directory within the bundle.
189    ///
190    /// The schema format is automatically detected from the file extension:
191    /// - `.h` -> "c-header"
192    /// - `.json` -> "json-schema"
193    /// - Others -> "unknown"
194    pub fn add_schema_file<P: AsRef<Path>>(
195        mut self,
196        source_path: P,
197        archive_name: &str,
198    ) -> BundleResult<Self> {
199        let source_path = source_path.as_ref();
200
201        let contents = fs::read(source_path).map_err(|e| {
202            BundleError::Io(std::io::Error::new(
203                e.kind(),
204                format!(
205                    "Failed to read schema file {}: {}",
206                    source_path.display(),
207                    e
208                ),
209            ))
210        })?;
211
212        // Compute checksum
213        let checksum = compute_sha256(&contents);
214
215        // Detect format from extension
216        let format = detect_schema_format(archive_name);
217
218        let archive_path = format!("schema/{archive_name}");
219
220        // Add to manifest
221        self.manifest.add_schema(
222            archive_name.to_string(),
223            archive_path.clone(),
224            format,
225            checksum,
226            None, // No description by default
227        );
228
229        self.files.push(BundleFile {
230            archive_path,
231            contents,
232        });
233
234        Ok(self)
235    }
236
237    /// Add a documentation file to the bundle.
238    ///
239    /// Documentation files are stored in the `docs/` directory within the bundle.
240    pub fn add_doc_file<P: AsRef<Path>>(
241        mut self,
242        source_path: P,
243        archive_name: &str,
244    ) -> BundleResult<Self> {
245        let source_path = source_path.as_ref();
246
247        let contents = fs::read(source_path).map_err(|e| {
248            BundleError::Io(std::io::Error::new(
249                e.kind(),
250                format!("Failed to read doc file {}: {}", source_path.display(), e),
251            ))
252        })?;
253
254        let archive_path = format!("docs/{archive_name}");
255
256        self.files.push(BundleFile {
257            archive_path,
258            contents,
259        });
260
261        Ok(self)
262    }
263
264    /// Add raw bytes as a file in the bundle.
265    pub fn add_bytes(mut self, archive_path: &str, contents: Vec<u8>) -> Self {
266        self.files.push(BundleFile {
267            archive_path: archive_path.to_string(),
268            contents,
269        });
270        self
271    }
272
273    /// Set the build information for the bundle.
274    pub fn with_build_info(mut self, build_info: crate::BuildInfo) -> Self {
275        self.manifest.set_build_info(build_info);
276        self
277    }
278
279    /// Set the SBOM paths.
280    pub fn with_sbom(mut self, sbom: crate::Sbom) -> Self {
281        self.manifest.set_sbom(sbom);
282        self
283    }
284
285    /// Add a notices file to the bundle.
286    ///
287    /// The file will be stored in the `docs/` directory.
288    pub fn add_notices_file<P: AsRef<Path>>(mut self, source_path: P) -> BundleResult<Self> {
289        let source_path = source_path.as_ref();
290
291        let contents = fs::read(source_path).map_err(|e| {
292            BundleError::Io(std::io::Error::new(
293                e.kind(),
294                format!(
295                    "Failed to read notices file {}: {}",
296                    source_path.display(),
297                    e
298                ),
299            ))
300        })?;
301
302        let archive_path = "docs/NOTICES.txt".to_string();
303        self.manifest.set_notices(archive_path.clone());
304
305        self.files.push(BundleFile {
306            archive_path,
307            contents,
308        });
309
310        Ok(self)
311    }
312
313    /// Add the plugin's license file to the bundle.
314    ///
315    /// The file will be stored in the `legal/` directory as `LICENSE`.
316    /// This is for the plugin's own license, not third-party notices.
317    pub fn add_license_file<P: AsRef<Path>>(mut self, source_path: P) -> BundleResult<Self> {
318        let source_path = source_path.as_ref();
319
320        let contents = fs::read(source_path).map_err(|e| {
321            BundleError::Io(std::io::Error::new(
322                e.kind(),
323                format!(
324                    "Failed to read license file {}: {}",
325                    source_path.display(),
326                    e
327                ),
328            ))
329        })?;
330
331        let archive_path = "legal/LICENSE".to_string();
332        self.manifest.set_license_file(archive_path.clone());
333
334        self.files.push(BundleFile {
335            archive_path,
336            contents,
337        });
338
339        Ok(self)
340    }
341
342    /// Add an SBOM file to the bundle.
343    ///
344    /// The file will be stored in the `sbom/` directory.
345    pub fn add_sbom_file<P: AsRef<Path>>(
346        mut self,
347        source_path: P,
348        archive_name: &str,
349    ) -> BundleResult<Self> {
350        let source_path = source_path.as_ref();
351
352        let contents = fs::read(source_path).map_err(|e| {
353            BundleError::Io(std::io::Error::new(
354                e.kind(),
355                format!("Failed to read SBOM file {}: {}", source_path.display(), e),
356            ))
357        })?;
358
359        let archive_path = format!("sbom/{archive_name}");
360
361        self.files.push(BundleFile {
362            archive_path,
363            contents,
364        });
365
366        Ok(self)
367    }
368
369    /// Write the bundle to a file.
370    pub fn write<P: AsRef<Path>>(self, output_path: P) -> BundleResult<()> {
371        let output_path = output_path.as_ref();
372
373        // Validate the manifest
374        self.manifest.validate()?;
375
376        // Create the ZIP file
377        let file = File::create(output_path)?;
378        let mut zip = ZipWriter::new(file);
379        let options =
380            SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
381
382        // Write manifest.json
383        let manifest_json = self.manifest.to_json()?;
384        zip.start_file(MANIFEST_FILE, options)?;
385        zip.write_all(manifest_json.as_bytes())?;
386
387        // Sign and write manifest.json.minisig if signing is enabled
388        if let Some((ref _public_key, ref secret_key)) = self.signing_key {
389            let signature = sign_data(secret_key, manifest_json.as_bytes())?;
390            zip.start_file(format!("{MANIFEST_FILE}.minisig"), options)?;
391            zip.write_all(signature.as_bytes())?;
392        }
393
394        // Write all other files
395        for bundle_file in &self.files {
396            zip.start_file(&bundle_file.archive_path, options)?;
397            zip.write_all(&bundle_file.contents)?;
398
399            // Sign library files if signing is enabled
400            if let Some((ref _public_key, ref secret_key)) = self.signing_key {
401                // Sign library files (in lib/ or bridge/ directory)
402                if bundle_file.archive_path.starts_with("lib/")
403                    || bundle_file.archive_path.starts_with("bridge/")
404                {
405                    let signature = sign_data(secret_key, &bundle_file.contents)?;
406                    let sig_path = format!("{}.minisig", bundle_file.archive_path);
407                    zip.start_file(&sig_path, options)?;
408                    zip.write_all(signature.as_bytes())?;
409                }
410            }
411        }
412
413        zip.finish()?;
414
415        Ok(())
416    }
417
418    /// Get the current manifest (for inspection).
419    #[must_use]
420    pub fn manifest(&self) -> &Manifest {
421        &self.manifest
422    }
423
424    /// Get a mutable reference to the manifest (for modification).
425    pub fn manifest_mut(&mut self) -> &mut Manifest {
426        &mut self.manifest
427    }
428}
429
430/// Compute SHA256 hash of data and return as hex string.
431pub fn compute_sha256(data: &[u8]) -> String {
432    let mut hasher = Sha256::new();
433    hasher.update(data);
434    let result = hasher.finalize();
435    hex::encode(result)
436}
437
438/// Verify SHA256 checksum of data.
439pub fn verify_sha256(data: &[u8], expected: &str) -> bool {
440    let actual = compute_sha256(data);
441
442    // Handle both "sha256:xxx" and raw "xxx" formats
443    let expected_hex = expected.strip_prefix("sha256:").unwrap_or(expected);
444
445    actual == expected_hex
446}
447
448/// Detect schema format from file extension.
449fn detect_schema_format(filename: &str) -> String {
450    if filename.ends_with(".h") || filename.ends_with(".hpp") {
451        "c-header".to_string()
452    } else if filename.ends_with(".json") {
453        "json-schema".to_string()
454    } else {
455        "unknown".to_string()
456    }
457}
458
459/// Sign data using a minisign secret key.
460///
461/// Returns the signature in minisign format (base64-encoded).
462fn sign_data(secret_key: &SecretKey, data: &[u8]) -> BundleResult<String> {
463    let signature_box = minisign::sign(
464        None, // No public key needed for signing
465        secret_key, data, None, // No trusted comment
466        None, // No untrusted comment
467    )
468    .map_err(|e| BundleError::Io(std::io::Error::other(format!("Failed to sign data: {e}"))))?;
469
470    Ok(signature_box.to_string())
471}
472
473#[cfg(test)]
474mod tests {
475    #![allow(non_snake_case)]
476
477    use super::*;
478    use tempfile::TempDir;
479
480    #[test]
481    fn compute_sha256___returns_consistent_hash() {
482        let data = b"hello world";
483        let hash1 = compute_sha256(data);
484        let hash2 = compute_sha256(data);
485
486        assert_eq!(hash1, hash2);
487        assert_eq!(hash1.len(), 64); // SHA256 is 32 bytes = 64 hex chars
488    }
489
490    #[test]
491    fn compute_sha256___different_data___different_hash() {
492        let hash1 = compute_sha256(b"hello");
493        let hash2 = compute_sha256(b"world");
494
495        assert_ne!(hash1, hash2);
496    }
497
498    #[test]
499    fn compute_sha256___empty_data___returns_valid_hash() {
500        let hash = compute_sha256(b"");
501
502        assert_eq!(hash.len(), 64);
503        // Known SHA256 of empty string
504        assert_eq!(
505            hash,
506            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
507        );
508    }
509
510    #[test]
511    fn verify_sha256___accepts_valid_checksum() {
512        let data = b"hello world";
513        let checksum = compute_sha256(data);
514
515        assert!(verify_sha256(data, &checksum));
516        assert!(verify_sha256(data, &format!("sha256:{checksum}")));
517    }
518
519    #[test]
520    fn verify_sha256___rejects_invalid_checksum() {
521        let data = b"hello world";
522
523        assert!(!verify_sha256(data, "invalid"));
524        assert!(!verify_sha256(data, "sha256:invalid"));
525    }
526
527    #[test]
528    fn verify_sha256___case_sensitive___rejects_uppercase() {
529        let data = b"hello world";
530        let checksum = compute_sha256(data).to_uppercase();
531
532        assert!(!verify_sha256(data, &checksum));
533    }
534
535    #[test]
536    fn BundleBuilder___add_bytes___adds_file() {
537        let manifest = Manifest::new("test", "1.0.0");
538        let builder = BundleBuilder::new(manifest).add_bytes("test.txt", b"hello".to_vec());
539
540        assert_eq!(builder.files.len(), 1);
541        assert_eq!(builder.files[0].archive_path, "test.txt");
542        assert_eq!(builder.files[0].contents, b"hello");
543    }
544
545    #[test]
546    fn BundleBuilder___add_bytes___multiple_files() {
547        let manifest = Manifest::new("test", "1.0.0");
548        let builder = BundleBuilder::new(manifest)
549            .add_bytes("file1.txt", b"content1".to_vec())
550            .add_bytes("file2.txt", b"content2".to_vec())
551            .add_bytes("dir/file3.txt", b"content3".to_vec());
552
553        assert_eq!(builder.files.len(), 3);
554    }
555
556    #[test]
557    fn BundleBuilder___add_library___nonexistent_file___returns_error() {
558        let manifest = Manifest::new("test", "1.0.0");
559        let result = BundleBuilder::new(manifest)
560            .add_library(Platform::LinuxX86_64, "/nonexistent/path/libtest.so");
561
562        assert!(result.is_err());
563        let err = result.unwrap_err();
564        assert!(matches!(err, BundleError::LibraryNotFound(_)));
565        assert!(err.to_string().contains("/nonexistent/path/libtest.so"));
566    }
567
568    #[test]
569    fn BundleBuilder___add_library___valid_file___computes_checksum() {
570        let temp_dir = TempDir::new().unwrap();
571        let lib_path = temp_dir.path().join("libtest.so");
572        fs::write(&lib_path, b"fake library").unwrap();
573
574        let manifest = Manifest::new("test", "1.0.0");
575        let builder = BundleBuilder::new(manifest)
576            .add_library(Platform::LinuxX86_64, &lib_path)
577            .unwrap();
578
579        let platform_info = builder
580            .manifest
581            .get_platform(Platform::LinuxX86_64)
582            .unwrap();
583        let release = platform_info.release().unwrap();
584        assert!(release.checksum.starts_with("sha256:"));
585        assert_eq!(release.library, "lib/linux-x86_64/release/libtest.so");
586    }
587
588    #[test]
589    fn BundleBuilder___add_library_variant___adds_multiple_variants() {
590        let temp_dir = TempDir::new().unwrap();
591        let release_lib = temp_dir.path().join("libtest_release.so");
592        let debug_lib = temp_dir.path().join("libtest_debug.so");
593        fs::write(&release_lib, b"release library").unwrap();
594        fs::write(&debug_lib, b"debug library").unwrap();
595
596        let manifest = Manifest::new("test", "1.0.0");
597        let builder = BundleBuilder::new(manifest)
598            .add_library_variant(Platform::LinuxX86_64, "release", &release_lib)
599            .unwrap()
600            .add_library_variant(Platform::LinuxX86_64, "debug", &debug_lib)
601            .unwrap();
602
603        let platform_info = builder
604            .manifest
605            .get_platform(Platform::LinuxX86_64)
606            .unwrap();
607
608        assert!(platform_info.has_variant("release"));
609        assert!(platform_info.has_variant("debug"));
610
611        let release = platform_info.variant("release").unwrap();
612        let debug = platform_info.variant("debug").unwrap();
613
614        assert_eq!(
615            release.library,
616            "lib/linux-x86_64/release/libtest_release.so"
617        );
618        assert_eq!(debug.library, "lib/linux-x86_64/debug/libtest_debug.so");
619    }
620
621    #[test]
622    fn BundleBuilder___add_library___multiple_platforms() {
623        let temp_dir = TempDir::new().unwrap();
624
625        let linux_lib = temp_dir.path().join("libtest.so");
626        let macos_lib = temp_dir.path().join("libtest.dylib");
627        fs::write(&linux_lib, b"linux lib").unwrap();
628        fs::write(&macos_lib, b"macos lib").unwrap();
629
630        let manifest = Manifest::new("test", "1.0.0");
631        let builder = BundleBuilder::new(manifest)
632            .add_library(Platform::LinuxX86_64, &linux_lib)
633            .unwrap()
634            .add_library(Platform::DarwinAarch64, &macos_lib)
635            .unwrap();
636
637        assert!(builder.manifest.supports_platform(Platform::LinuxX86_64));
638        assert!(builder.manifest.supports_platform(Platform::DarwinAarch64));
639        assert!(!builder.manifest.supports_platform(Platform::WindowsX86_64));
640    }
641
642    #[test]
643    fn BundleBuilder___add_schema_file___nonexistent___returns_error() {
644        let manifest = Manifest::new("test", "1.0.0");
645        let result =
646            BundleBuilder::new(manifest).add_schema_file("/nonexistent/schema.h", "schema.h");
647
648        assert!(result.is_err());
649    }
650
651    #[test]
652    fn BundleBuilder___add_schema_file___detects_c_header_format() {
653        let temp_dir = TempDir::new().unwrap();
654        let schema_path = temp_dir.path().join("messages.h");
655        fs::write(&schema_path, b"#include <stdint.h>").unwrap();
656
657        let manifest = Manifest::new("test", "1.0.0");
658        let builder = BundleBuilder::new(manifest)
659            .add_schema_file(&schema_path, "messages.h")
660            .unwrap();
661
662        let schema_info = builder.manifest.schemas.get("messages.h").unwrap();
663        assert_eq!(schema_info.format, "c-header");
664    }
665
666    #[test]
667    fn BundleBuilder___add_schema_file___detects_json_schema_format() {
668        let temp_dir = TempDir::new().unwrap();
669        let schema_path = temp_dir.path().join("schema.json");
670        fs::write(&schema_path, b"{}").unwrap();
671
672        let manifest = Manifest::new("test", "1.0.0");
673        let builder = BundleBuilder::new(manifest)
674            .add_schema_file(&schema_path, "schema.json")
675            .unwrap();
676
677        let schema_info = builder.manifest.schemas.get("schema.json").unwrap();
678        assert_eq!(schema_info.format, "json-schema");
679    }
680
681    #[test]
682    fn BundleBuilder___add_schema_file___unknown_format() {
683        let temp_dir = TempDir::new().unwrap();
684        let schema_path = temp_dir.path().join("schema.xyz");
685        fs::write(&schema_path, b"content").unwrap();
686
687        let manifest = Manifest::new("test", "1.0.0");
688        let builder = BundleBuilder::new(manifest)
689            .add_schema_file(&schema_path, "schema.xyz")
690            .unwrap();
691
692        let schema_info = builder.manifest.schemas.get("schema.xyz").unwrap();
693        assert_eq!(schema_info.format, "unknown");
694    }
695
696    #[test]
697    fn BundleBuilder___write___invalid_manifest___returns_error() {
698        let temp_dir = TempDir::new().unwrap();
699        let output_path = temp_dir.path().join("test.rbp");
700
701        // Manifest without any platforms is invalid
702        let manifest = Manifest::new("test", "1.0.0");
703        let result = BundleBuilder::new(manifest).write(&output_path);
704
705        assert!(result.is_err());
706        let err = result.unwrap_err();
707        assert!(matches!(err, BundleError::InvalidManifest(_)));
708    }
709
710    #[test]
711    fn BundleBuilder___write___creates_valid_bundle() {
712        let temp_dir = TempDir::new().unwrap();
713        let lib_path = temp_dir.path().join("libtest.so");
714        let output_path = temp_dir.path().join("test.rbp");
715        fs::write(&lib_path, b"fake library").unwrap();
716
717        let manifest = Manifest::new("test", "1.0.0");
718        BundleBuilder::new(manifest)
719            .add_library(Platform::LinuxX86_64, &lib_path)
720            .unwrap()
721            .write(&output_path)
722            .unwrap();
723
724        assert!(output_path.exists());
725
726        // Verify it's a valid ZIP
727        let file = File::open(&output_path).unwrap();
728        let archive = zip::ZipArchive::new(file).unwrap();
729        assert!(archive.len() >= 2); // manifest + library
730    }
731
732    #[test]
733    fn BundleBuilder___manifest_mut___allows_modification() {
734        let manifest = Manifest::new("test", "1.0.0");
735        let mut builder = BundleBuilder::new(manifest);
736
737        builder.manifest_mut().plugin.description = Some("Modified".to_string());
738
739        assert_eq!(
740            builder.manifest().plugin.description,
741            Some("Modified".to_string())
742        );
743    }
744
745    #[test]
746    fn detect_schema_format___hpp_extension___returns_c_header() {
747        assert_eq!(detect_schema_format("types.hpp"), "c-header");
748    }
749
750    // ========================================================================
751    // Minisign Signature Tests
752    // ========================================================================
753    // These tests verify that minisign signature generation and verification
754    // work correctly. The test vectors are used as reference for consumer
755    // language implementations (Java, C#, Python).
756
757    #[test]
758    fn sign_data___generates_verifiable_signature() {
759        use minisign::{KeyPair, PublicKey};
760        use std::io::Cursor;
761
762        // Generate a test keypair
763        let keypair = KeyPair::generate_unencrypted_keypair().unwrap();
764
765        // Test data
766        let test_data = b"Hello, rustbridge!";
767
768        // Sign the data
769        let mut reader = Cursor::new(test_data.as_slice());
770        let signature_box = minisign::sign(
771            Some(&keypair.pk),
772            &keypair.sk,
773            &mut reader,
774            Some("trusted comment"),
775            Some("untrusted comment"),
776        )
777        .unwrap();
778
779        // Verify the signature
780        let pk = PublicKey::from_base64(&keypair.pk.to_base64()).unwrap();
781        let mut verify_reader = Cursor::new(test_data.as_slice());
782        let result = minisign::verify(&pk, &signature_box, &mut verify_reader, true, false, false);
783
784        assert!(result.is_ok(), "Signature verification should succeed");
785    }
786
787    #[test]
788    fn sign_data___wrong_data___verification_fails() {
789        use minisign::{KeyPair, PublicKey};
790        use std::io::Cursor;
791
792        let keypair = KeyPair::generate_unencrypted_keypair().unwrap();
793        let test_data = b"Hello, rustbridge!";
794        let wrong_data = b"Hello, rustbridge?"; // Changed ! to ?
795
796        // Sign the original data
797        let mut reader = Cursor::new(test_data.as_slice());
798        let signature_box =
799            minisign::sign(Some(&keypair.pk), &keypair.sk, &mut reader, None, None).unwrap();
800
801        // Try to verify with wrong data
802        let pk = PublicKey::from_base64(&keypair.pk.to_base64()).unwrap();
803        let mut verify_reader = Cursor::new(wrong_data.as_slice());
804        let result = minisign::verify(&pk, &signature_box, &mut verify_reader, true, false, false);
805
806        assert!(result.is_err(), "Verification should fail with wrong data");
807    }
808
809    #[test]
810    fn sign_data___signature_format___has_prehash_algorithm_id() {
811        use base64::Engine;
812        use minisign::KeyPair;
813        use std::io::Cursor;
814
815        let keypair = KeyPair::generate_unencrypted_keypair().unwrap();
816        let test_data = b"test";
817
818        let mut reader = Cursor::new(test_data.as_slice());
819        let signature_box = minisign::sign(
820            Some(&keypair.pk),
821            &keypair.sk,
822            &mut reader,
823            Some("trusted"),
824            Some("untrusted"),
825        )
826        .unwrap();
827
828        let sig_string = signature_box.into_string();
829        let lines: Vec<&str> = sig_string.lines().collect();
830
831        // The signature line is the second line
832        let sig_base64 = lines[1];
833        let sig_bytes = base64::engine::general_purpose::STANDARD
834            .decode(sig_base64)
835            .unwrap();
836
837        // First two bytes should be "ED" (0x45, 0x44) for prehashed signatures
838        assert_eq!(sig_bytes[0], 0x45, "First byte should be 'E'");
839        assert_eq!(
840            sig_bytes[1], 0x44,
841            "Second byte should be 'D' for prehashed"
842        );
843        assert_eq!(sig_bytes.len(), 74, "Signature should be 74 bytes");
844    }
845
846    #[test]
847    fn sign_data___public_key_format___has_ed_algorithm_id() {
848        use base64::Engine;
849        use minisign::KeyPair;
850
851        let keypair = KeyPair::generate_unencrypted_keypair().unwrap();
852        let pk_base64 = keypair.pk.to_base64();
853        let pk_bytes = base64::engine::general_purpose::STANDARD
854            .decode(&pk_base64)
855            .unwrap();
856
857        // First two bytes should be "Ed" (0x45, 0x64) for public keys
858        assert_eq!(pk_bytes[0], 0x45, "First byte should be 'E'");
859        assert_eq!(
860            pk_bytes[1], 0x64,
861            "Second byte should be 'd' for public key"
862        );
863        assert_eq!(pk_bytes.len(), 42, "Public key should be 42 bytes");
864    }
865
866    #[test]
867    fn BundleBuilder___add_license_file___adds_file_to_legal_dir() {
868        let temp_dir = TempDir::new().unwrap();
869        let license_path = temp_dir.path().join("LICENSE");
870        fs::write(&license_path, b"MIT License\n\nCopyright...").unwrap();
871
872        let manifest = Manifest::new("test", "1.0.0");
873        let builder = BundleBuilder::new(manifest)
874            .add_license_file(&license_path)
875            .unwrap();
876
877        // Check file was added
878        assert_eq!(builder.files.len(), 1);
879        assert_eq!(builder.files[0].archive_path, "legal/LICENSE");
880
881        // Check manifest was updated
882        assert_eq!(builder.manifest.get_license_file(), Some("legal/LICENSE"));
883    }
884
885    #[test]
886    fn BundleBuilder___add_license_file___nonexistent___returns_error() {
887        let manifest = Manifest::new("test", "1.0.0");
888        let result = BundleBuilder::new(manifest).add_license_file("/nonexistent/LICENSE");
889
890        assert!(result.is_err());
891    }
892}