1use 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#[derive(Debug)]
30pub struct BundleBuilder {
31 manifest: Manifest,
32 files: Vec<BundleFile>,
33 signing_key: Option<(String, SecretKey)>, }
35
36#[derive(Debug)]
38struct BundleFile {
39 archive_path: String,
41 contents: Vec<u8>,
43}
44
45impl BundleBuilder {
46 #[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 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 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 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 let contents = fs::read(library_path).map_err(|e| {
104 BundleError::LibraryNotFound(format!("{}: {}", library_path.display(), e))
105 })?;
106
107 let checksum = compute_sha256(&contents);
109
110 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 self.manifest
124 .add_platform_variant(platform, variant, &archive_path, &checksum, None);
125
126 self.files.push(BundleFile {
128 archive_path,
129 contents,
130 });
131
132 Ok(self)
133 }
134
135 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 let contents = fs::read(library_path).map_err(|e| {
150 BundleError::LibraryNotFound(format!("{}: {}", library_path.display(), e))
151 })?;
152
153 let checksum = compute_sha256(&contents);
155
156 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 self.manifest.add_platform_variant(
170 platform,
171 variant,
172 &archive_path,
173 &checksum,
174 Some(build),
175 );
176
177 self.files.push(BundleFile {
179 archive_path,
180 contents,
181 });
182
183 Ok(self)
184 }
185
186 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 let checksum = compute_sha256(&contents);
214
215 let format = detect_schema_format(archive_name);
217
218 let archive_path = format!("schema/{archive_name}");
219
220 self.manifest.add_schema(
222 archive_name.to_string(),
223 archive_path.clone(),
224 format,
225 checksum,
226 None, );
228
229 self.files.push(BundleFile {
230 archive_path,
231 contents,
232 });
233
234 Ok(self)
235 }
236
237 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 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 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 pub fn with_sbom(mut self, sbom: crate::Sbom) -> Self {
281 self.manifest.set_sbom(sbom);
282 self
283 }
284
285 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 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 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 pub fn write<P: AsRef<Path>>(self, output_path: P) -> BundleResult<()> {
371 let output_path = output_path.as_ref();
372
373 self.manifest.validate()?;
375
376 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 let manifest_json = self.manifest.to_json()?;
384 zip.start_file(MANIFEST_FILE, options)?;
385 zip.write_all(manifest_json.as_bytes())?;
386
387 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 for bundle_file in &self.files {
396 zip.start_file(&bundle_file.archive_path, options)?;
397 zip.write_all(&bundle_file.contents)?;
398
399 if let Some((ref _public_key, ref secret_key)) = self.signing_key {
401 if bundle_file.archive_path.starts_with("lib/") {
403 let signature = sign_data(secret_key, &bundle_file.contents)?;
404 let sig_path = format!("{}.minisig", bundle_file.archive_path);
405 zip.start_file(&sig_path, options)?;
406 zip.write_all(signature.as_bytes())?;
407 }
408 }
409 }
410
411 zip.finish()?;
412
413 Ok(())
414 }
415
416 #[must_use]
418 pub fn manifest(&self) -> &Manifest {
419 &self.manifest
420 }
421
422 pub fn manifest_mut(&mut self) -> &mut Manifest {
424 &mut self.manifest
425 }
426}
427
428pub fn compute_sha256(data: &[u8]) -> String {
430 let mut hasher = Sha256::new();
431 hasher.update(data);
432 let result = hasher.finalize();
433 hex::encode(result)
434}
435
436pub fn verify_sha256(data: &[u8], expected: &str) -> bool {
438 let actual = compute_sha256(data);
439
440 let expected_hex = expected.strip_prefix("sha256:").unwrap_or(expected);
442
443 actual == expected_hex
444}
445
446fn detect_schema_format(filename: &str) -> String {
448 if filename.ends_with(".h") || filename.ends_with(".hpp") {
449 "c-header".to_string()
450 } else if filename.ends_with(".json") {
451 "json-schema".to_string()
452 } else {
453 "unknown".to_string()
454 }
455}
456
457fn sign_data(secret_key: &SecretKey, data: &[u8]) -> BundleResult<String> {
461 let signature_box = minisign::sign(
462 None, secret_key, data, None, None, )
466 .map_err(|e| BundleError::Io(std::io::Error::other(format!("Failed to sign data: {e}"))))?;
467
468 Ok(signature_box.to_string())
469}
470
471#[cfg(test)]
472mod tests {
473 #![allow(non_snake_case)]
474
475 use super::*;
476 use tempfile::TempDir;
477
478 #[test]
479 fn compute_sha256___returns_consistent_hash() {
480 let data = b"hello world";
481 let hash1 = compute_sha256(data);
482 let hash2 = compute_sha256(data);
483
484 assert_eq!(hash1, hash2);
485 assert_eq!(hash1.len(), 64); }
487
488 #[test]
489 fn compute_sha256___different_data___different_hash() {
490 let hash1 = compute_sha256(b"hello");
491 let hash2 = compute_sha256(b"world");
492
493 assert_ne!(hash1, hash2);
494 }
495
496 #[test]
497 fn compute_sha256___empty_data___returns_valid_hash() {
498 let hash = compute_sha256(b"");
499
500 assert_eq!(hash.len(), 64);
501 assert_eq!(
503 hash,
504 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
505 );
506 }
507
508 #[test]
509 fn verify_sha256___accepts_valid_checksum() {
510 let data = b"hello world";
511 let checksum = compute_sha256(data);
512
513 assert!(verify_sha256(data, &checksum));
514 assert!(verify_sha256(data, &format!("sha256:{checksum}")));
515 }
516
517 #[test]
518 fn verify_sha256___rejects_invalid_checksum() {
519 let data = b"hello world";
520
521 assert!(!verify_sha256(data, "invalid"));
522 assert!(!verify_sha256(data, "sha256:invalid"));
523 }
524
525 #[test]
526 fn verify_sha256___case_sensitive___rejects_uppercase() {
527 let data = b"hello world";
528 let checksum = compute_sha256(data).to_uppercase();
529
530 assert!(!verify_sha256(data, &checksum));
531 }
532
533 #[test]
534 fn BundleBuilder___add_bytes___adds_file() {
535 let manifest = Manifest::new("test", "1.0.0");
536 let builder = BundleBuilder::new(manifest).add_bytes("test.txt", b"hello".to_vec());
537
538 assert_eq!(builder.files.len(), 1);
539 assert_eq!(builder.files[0].archive_path, "test.txt");
540 assert_eq!(builder.files[0].contents, b"hello");
541 }
542
543 #[test]
544 fn BundleBuilder___add_bytes___multiple_files() {
545 let manifest = Manifest::new("test", "1.0.0");
546 let builder = BundleBuilder::new(manifest)
547 .add_bytes("file1.txt", b"content1".to_vec())
548 .add_bytes("file2.txt", b"content2".to_vec())
549 .add_bytes("dir/file3.txt", b"content3".to_vec());
550
551 assert_eq!(builder.files.len(), 3);
552 }
553
554 #[test]
555 fn BundleBuilder___add_library___nonexistent_file___returns_error() {
556 let manifest = Manifest::new("test", "1.0.0");
557 let result = BundleBuilder::new(manifest)
558 .add_library(Platform::LinuxX86_64, "/nonexistent/path/libtest.so");
559
560 assert!(result.is_err());
561 let err = result.unwrap_err();
562 assert!(matches!(err, BundleError::LibraryNotFound(_)));
563 assert!(err.to_string().contains("/nonexistent/path/libtest.so"));
564 }
565
566 #[test]
567 fn BundleBuilder___add_library___valid_file___computes_checksum() {
568 let temp_dir = TempDir::new().unwrap();
569 let lib_path = temp_dir.path().join("libtest.so");
570 fs::write(&lib_path, b"fake library").unwrap();
571
572 let manifest = Manifest::new("test", "1.0.0");
573 let builder = BundleBuilder::new(manifest)
574 .add_library(Platform::LinuxX86_64, &lib_path)
575 .unwrap();
576
577 let platform_info = builder
578 .manifest
579 .get_platform(Platform::LinuxX86_64)
580 .unwrap();
581 let release = platform_info.release().unwrap();
582 assert!(release.checksum.starts_with("sha256:"));
583 assert_eq!(release.library, "lib/linux-x86_64/release/libtest.so");
584 }
585
586 #[test]
587 fn BundleBuilder___add_library_variant___adds_multiple_variants() {
588 let temp_dir = TempDir::new().unwrap();
589 let release_lib = temp_dir.path().join("libtest_release.so");
590 let debug_lib = temp_dir.path().join("libtest_debug.so");
591 fs::write(&release_lib, b"release library").unwrap();
592 fs::write(&debug_lib, b"debug library").unwrap();
593
594 let manifest = Manifest::new("test", "1.0.0");
595 let builder = BundleBuilder::new(manifest)
596 .add_library_variant(Platform::LinuxX86_64, "release", &release_lib)
597 .unwrap()
598 .add_library_variant(Platform::LinuxX86_64, "debug", &debug_lib)
599 .unwrap();
600
601 let platform_info = builder
602 .manifest
603 .get_platform(Platform::LinuxX86_64)
604 .unwrap();
605
606 assert!(platform_info.has_variant("release"));
607 assert!(platform_info.has_variant("debug"));
608
609 let release = platform_info.variant("release").unwrap();
610 let debug = platform_info.variant("debug").unwrap();
611
612 assert_eq!(
613 release.library,
614 "lib/linux-x86_64/release/libtest_release.so"
615 );
616 assert_eq!(debug.library, "lib/linux-x86_64/debug/libtest_debug.so");
617 }
618
619 #[test]
620 fn BundleBuilder___add_library___multiple_platforms() {
621 let temp_dir = TempDir::new().unwrap();
622
623 let linux_lib = temp_dir.path().join("libtest.so");
624 let macos_lib = temp_dir.path().join("libtest.dylib");
625 fs::write(&linux_lib, b"linux lib").unwrap();
626 fs::write(&macos_lib, b"macos lib").unwrap();
627
628 let manifest = Manifest::new("test", "1.0.0");
629 let builder = BundleBuilder::new(manifest)
630 .add_library(Platform::LinuxX86_64, &linux_lib)
631 .unwrap()
632 .add_library(Platform::DarwinAarch64, &macos_lib)
633 .unwrap();
634
635 assert!(builder.manifest.supports_platform(Platform::LinuxX86_64));
636 assert!(builder.manifest.supports_platform(Platform::DarwinAarch64));
637 assert!(!builder.manifest.supports_platform(Platform::WindowsX86_64));
638 }
639
640 #[test]
641 fn BundleBuilder___add_schema_file___nonexistent___returns_error() {
642 let manifest = Manifest::new("test", "1.0.0");
643 let result =
644 BundleBuilder::new(manifest).add_schema_file("/nonexistent/schema.h", "schema.h");
645
646 assert!(result.is_err());
647 }
648
649 #[test]
650 fn BundleBuilder___add_schema_file___detects_c_header_format() {
651 let temp_dir = TempDir::new().unwrap();
652 let schema_path = temp_dir.path().join("messages.h");
653 fs::write(&schema_path, b"#include <stdint.h>").unwrap();
654
655 let manifest = Manifest::new("test", "1.0.0");
656 let builder = BundleBuilder::new(manifest)
657 .add_schema_file(&schema_path, "messages.h")
658 .unwrap();
659
660 let schema_info = builder.manifest.schemas.get("messages.h").unwrap();
661 assert_eq!(schema_info.format, "c-header");
662 }
663
664 #[test]
665 fn BundleBuilder___add_schema_file___detects_json_schema_format() {
666 let temp_dir = TempDir::new().unwrap();
667 let schema_path = temp_dir.path().join("schema.json");
668 fs::write(&schema_path, b"{}").unwrap();
669
670 let manifest = Manifest::new("test", "1.0.0");
671 let builder = BundleBuilder::new(manifest)
672 .add_schema_file(&schema_path, "schema.json")
673 .unwrap();
674
675 let schema_info = builder.manifest.schemas.get("schema.json").unwrap();
676 assert_eq!(schema_info.format, "json-schema");
677 }
678
679 #[test]
680 fn BundleBuilder___add_schema_file___unknown_format() {
681 let temp_dir = TempDir::new().unwrap();
682 let schema_path = temp_dir.path().join("schema.xyz");
683 fs::write(&schema_path, b"content").unwrap();
684
685 let manifest = Manifest::new("test", "1.0.0");
686 let builder = BundleBuilder::new(manifest)
687 .add_schema_file(&schema_path, "schema.xyz")
688 .unwrap();
689
690 let schema_info = builder.manifest.schemas.get("schema.xyz").unwrap();
691 assert_eq!(schema_info.format, "unknown");
692 }
693
694 #[test]
695 fn BundleBuilder___write___invalid_manifest___returns_error() {
696 let temp_dir = TempDir::new().unwrap();
697 let output_path = temp_dir.path().join("test.rbp");
698
699 let manifest = Manifest::new("test", "1.0.0");
701 let result = BundleBuilder::new(manifest).write(&output_path);
702
703 assert!(result.is_err());
704 let err = result.unwrap_err();
705 assert!(matches!(err, BundleError::InvalidManifest(_)));
706 }
707
708 #[test]
709 fn BundleBuilder___write___creates_valid_bundle() {
710 let temp_dir = TempDir::new().unwrap();
711 let lib_path = temp_dir.path().join("libtest.so");
712 let output_path = temp_dir.path().join("test.rbp");
713 fs::write(&lib_path, b"fake library").unwrap();
714
715 let manifest = Manifest::new("test", "1.0.0");
716 BundleBuilder::new(manifest)
717 .add_library(Platform::LinuxX86_64, &lib_path)
718 .unwrap()
719 .write(&output_path)
720 .unwrap();
721
722 assert!(output_path.exists());
723
724 let file = File::open(&output_path).unwrap();
726 let archive = zip::ZipArchive::new(file).unwrap();
727 assert!(archive.len() >= 2); }
729
730 #[test]
731 fn BundleBuilder___manifest_mut___allows_modification() {
732 let manifest = Manifest::new("test", "1.0.0");
733 let mut builder = BundleBuilder::new(manifest);
734
735 builder.manifest_mut().plugin.description = Some("Modified".to_string());
736
737 assert_eq!(
738 builder.manifest().plugin.description,
739 Some("Modified".to_string())
740 );
741 }
742
743 #[test]
744 fn detect_schema_format___hpp_extension___returns_c_header() {
745 assert_eq!(detect_schema_format("types.hpp"), "c-header");
746 }
747
748 #[test]
749 fn BundleBuilder___add_license_file___adds_file_to_legal_dir() {
750 let temp_dir = TempDir::new().unwrap();
751 let license_path = temp_dir.path().join("LICENSE");
752 fs::write(&license_path, b"MIT License\n\nCopyright...").unwrap();
753
754 let manifest = Manifest::new("test", "1.0.0");
755 let builder = BundleBuilder::new(manifest)
756 .add_license_file(&license_path)
757 .unwrap();
758
759 assert_eq!(builder.files.len(), 1);
761 assert_eq!(builder.files[0].archive_path, "legal/LICENSE");
762
763 assert_eq!(builder.manifest.get_license_file(), Some("legal/LICENSE"));
765 }
766
767 #[test]
768 fn BundleBuilder___add_license_file___nonexistent___returns_error() {
769 let manifest = Manifest::new("test", "1.0.0");
770 let result = BundleBuilder::new(manifest).add_license_file("/nonexistent/LICENSE");
771
772 assert!(result.is_err());
773 }
774}