1#![forbid(unsafe_code)]
11
12use std::fs;
13use std::io::Read;
14use std::path::{Path, PathBuf};
15use vanta_core::{Area, Artifact, BuildRecipe, Platform, StoreKey, VtaError, VtaResult};
16use vanta_net::Downloader;
17use vanta_security::Policy;
18use vanta_state::{GenerationRecord, State, StoreEntryMeta};
19use vanta_store::Store;
20
21pub trait Reporter {
26 fn fetch_start(&self, total: Option<u64>) {
29 let _ = total;
30 }
31 fn fetch_inc(&self, n: u64) {
33 let _ = n;
34 }
35 fn phase(&self, name: &str) {
37 let _ = name;
38 }
39}
40
41impl Reporter for () {}
43
44pub const DEFAULT_MAX_DECOMPRESSED: u64 = 2 * 1024 * 1024 * 1024; pub struct Engine {
51 store: Store,
52 state: State,
53 downloader: Downloader,
54 home: PathBuf,
55 policy: Policy,
58 max_decompressed: u64,
60}
61
62impl Engine {
63 pub fn open(home: impl AsRef<Path>) -> VtaResult<Engine> {
67 Self::open_with_policy(home, Policy::default())
68 }
69
70 pub fn open_with_policy(home: impl AsRef<Path>, policy: Policy) -> VtaResult<Engine> {
72 let home = home.as_ref().to_path_buf();
73 let store = Store::open(&home)?;
74 let state = State::open(&home.join("state.db"))?;
75 let downloader = Downloader::new()?;
76 Ok(Engine {
77 store,
78 state,
79 downloader,
80 home,
81 policy,
82 max_decompressed: DEFAULT_MAX_DECOMPRESSED,
83 })
84 }
85
86 pub fn with_max_decompressed(mut self, max: u64) -> Self {
88 self.max_decompressed = max;
89 self
90 }
91
92 pub fn store(&self) -> &Store {
94 &self.store
95 }
96 pub fn state(&self) -> &State {
97 &self.state
98 }
99
100 pub fn install_artifact(
104 &self,
105 tool: &str,
106 version: &str,
107 artifact: &Artifact,
108 ) -> VtaResult<StoreKey> {
109 self.install_artifact_reported(tool, version, artifact, &())
110 }
111
112 pub fn install_artifact_reported(
115 &self,
116 tool: &str,
117 version: &str,
118 artifact: &Artifact,
119 reporter: &dyn Reporter,
120 ) -> VtaResult<StoreKey> {
121 let has_trusted_sig = artifact.signature.is_some() && artifact.signature_key.is_some();
125 if self.policy.require_signature && !has_trusted_sig {
126 return Err(VtaError::new(
127 Area::Vrf,
128 3,
129 format!(
130 "signature required by policy but `{tool} {version}` is unsigned \
131 or its signing key is not trusted"
132 ),
133 ));
134 }
135
136 if let Some(key) = &artifact.store_key {
142 if self.store.has(key) {
143 if self.store.verify_entry(key)? {
144 self.link_bins(key, &artifact.bin)?;
145 self.record(tool, version, key, &artifact.checksum.value)?;
146 return Ok(key.clone());
147 }
148 self.store.remove_entry(key)?;
149 }
150 }
151
152 let dl = self
154 .store
155 .downloads_dir()
156 .join(format!("incoming-{tool}-{}", std::process::id()));
157 let mut urls = vec![artifact.url.clone()];
158 urls.extend(artifact.mirrors.clone());
159 reporter.fetch_start(artifact.size);
160 self.downloader.download_any_with_progress(
161 &urls,
162 &dl,
163 artifact.size,
164 Some(&|n| reporter.fetch_inc(n)),
165 )?;
166
167 reporter.phase("verifying");
169 if let Err(e) =
170 vanta_security::verify_file(&dl, &artifact.checksum.algo, &artifact.checksum.value)
171 {
172 let _ = fs::remove_file(&dl);
173 return Err(e);
174 }
175 if let (Some(sig), Some(key_text)) = (&artifact.signature, &artifact.signature_key) {
179 let key = vanta_security::parse_minisign_pubkey(key_text)?;
180 let bytes = fs::read(&dl).map_err(|e| io(&dl, e))?;
181 if let Err(e) = vanta_security::minisign_verify(&bytes, sig, &key) {
182 let _ = fs::remove_file(&dl);
183 return Err(e);
184 }
185 }
186
187 let name = artifact
189 .bin
190 .first()
191 .map(|b| basename(b))
192 .unwrap_or_else(|| tool.to_string());
193 let staging = self.store.new_staging()?;
195 if let Some(recipe) = &artifact.build {
196 reporter.phase("extracting source");
200 let src = self.store.new_staging()?;
201 extract(
202 &artifact.archive,
203 &dl,
204 &src,
205 &name,
206 artifact.strip,
207 self.max_decompressed,
208 )?;
209 let _ = fs::remove_file(&dl);
210 run_build(recipe, &src, &staging, tool, version, reporter)?;
211 let _ = fs::remove_dir_all(&src);
212 } else {
213 reporter.phase("extracting");
214 extract(
215 &artifact.archive,
216 &dl,
217 &staging,
218 &name,
219 artifact.strip,
220 self.max_decompressed,
221 )?;
222 let _ = fs::remove_file(&dl);
223 }
224
225 let key = self.store.publish_tree(&staging)?;
227
228 self.link_bins(&key, &artifact.bin)?;
230
231 self.record(tool, version, &key, &artifact.checksum.value)?;
233 Ok(key)
234 }
235
236 fn link_bins(&self, key: &StoreKey, bins: &[String]) -> VtaResult<()> {
240 let bin_dir = self.home.join("bin");
241 fs::create_dir_all(&bin_dir).map_err(|e| io(&bin_dir, e))?;
242 let entry = self.store.entry_path(key);
243 for bin in bins {
244 let src = entry.join(bin);
245 if src.exists() {
246 let dst = bin_dir.join(basename(bin));
247 vanta_store::link_best(&src, &dst)?;
248 }
249 }
250 Ok(())
251 }
252
253 fn record(&self, tool: &str, version: &str, key: &StoreKey, sha256: &str) -> VtaResult<()> {
254 let platform = Platform::current().token();
255 self.state.put_store_entry(
256 key.as_str(),
257 &StoreEntryMeta {
258 tool: tool.to_string(),
259 version: version.to_string(),
260 platform,
261 size: 0,
262 sha256: sha256.to_string(),
263 },
264 )?;
265 let parent = self.state.current()?;
266 let id = parent.map(|c| c + 1).unwrap_or(1);
267 self.state.append_generation(&GenerationRecord {
268 id,
269 parent,
270 command: format!("vanta add {tool}@{version}"),
271 reason: "add".to_string(),
272 tools: vec![(tool.to_string(), key.as_str().to_string())],
273 })?;
274 self.state.set_current(id)?;
275 Ok(())
276 }
277
278 fn active_store_keys(&self) -> VtaResult<Vec<StoreKey>> {
280 let mut keys = Vec::new();
281 if let Some(current) = self.state.current()? {
282 if let Some(gen) = self.state.get_generation(current)? {
283 for (_, k) in gen.tools {
284 if let Ok(sk) = StoreKey::new(k) {
285 keys.push(sk);
286 }
287 }
288 }
289 }
290 Ok(keys)
291 }
292
293 pub fn bundle_current(&self, out: &Path) -> VtaResult<usize> {
296 let keys = self.active_store_keys()?;
297 let file = fs::File::create(out).map_err(|e| io(out, e))?;
298 let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());
299 let mut builder = tar::Builder::new(enc);
300 let list = keys
301 .iter()
302 .map(|k| k.as_str())
303 .collect::<Vec<_>>()
304 .join("\n");
305 let mut header = tar::Header::new_gnu();
306 header.set_size(list.len() as u64);
307 header.set_mode(0o644);
308 header.set_cksum();
309 builder
310 .append_data(&mut header, "KEYS", list.as_bytes())
311 .map_err(|e| inst(format!("bundle KEYS: {e}")))?;
312 for key in &keys {
313 let dir = self.store.entry_path(key);
314 if dir.is_dir() {
315 builder
316 .append_dir_all(key.as_str(), &dir)
317 .map_err(|e| inst(format!("bundle {key}: {e}")))?;
318 }
319 }
320 let enc = builder
321 .into_inner()
322 .map_err(|e| inst(format!("bundle finalize: {e}")))?;
323 enc.finish()
324 .map_err(|e| inst(format!("bundle gzip: {e}")))?;
325 Ok(keys.len())
326 }
327
328 pub fn restore(&self, bundle: &Path) -> VtaResult<usize> {
331 let file = fs::File::open(bundle).map_err(|e| io(bundle, e))?;
332 let gz = flate2::read::GzDecoder::new(file);
333 let mut archive = tar::Archive::new(gz);
334 let staging = self.store.new_staging()?;
335 archive
336 .unpack(&staging)
337 .map_err(|e| inst(format!("restore unpack: {e}")))?;
338 let keys_txt =
339 fs::read_to_string(staging.join("KEYS")).map_err(|e| io(&staging.join("KEYS"), e))?;
340 let mut restored = 0;
341 for line in keys_txt.lines() {
342 let key = line.trim();
343 if key.is_empty() {
344 continue;
345 }
346 let sk = StoreKey::new(key)?;
349 let dst = self.store.entry_path(&sk);
350 if dst.exists() {
351 continue;
354 }
355 let src = staging.join(key);
356 if !src.is_dir() {
357 continue;
358 }
359 let actual = vanta_store::hash_tree(&src)?;
364 if actual != sk.as_str() {
365 let _ = fs::remove_dir_all(&staging);
366 return Err(VtaError::new(
367 Area::Vrf,
368 1,
369 format!("bundled entry {key} failed integrity verification (content mismatch)"),
370 ));
371 }
372 let _ = vanta_store::ensure_writable(&src);
374 fs::rename(&src, &dst).map_err(|e| io(&dst, e))?;
375 restored += 1;
376 }
377 let _ = fs::remove_dir_all(&staging);
378 Ok(restored)
379 }
380
381 pub fn remove(&self, tool: &str) -> VtaResult<bool> {
384 let current = match self.state.current()? {
385 Some(c) => c,
386 None => return Ok(false),
387 };
388 let gen = match self.state.get_generation(current)? {
389 Some(g) => g,
390 None => return Ok(false),
391 };
392 if !gen.tools.iter().any(|(t, _)| t == tool) {
393 return Ok(false);
394 }
395 let tools: Vec<(String, String)> = gen
396 .tools
397 .iter()
398 .filter(|(t, _)| t != tool)
399 .cloned()
400 .collect();
401 let id = current + 1;
402 self.state.append_generation(&GenerationRecord {
403 id,
404 parent: Some(current),
405 command: format!("vanta remove {tool}"),
406 reason: "remove".to_string(),
407 tools,
408 })?;
409 self.state.set_current(id)?;
410 let _ = fs::remove_file(self.home.join("bin").join(tool));
411 Ok(true)
412 }
413}
414
415fn inst(msg: String) -> VtaError {
416 VtaError::new(Area::Inst, 1, msg)
417}
418
419fn run_build(
430 recipe: &BuildRecipe,
431 src_dir: &Path,
432 prefix: &Path,
433 tool: &str,
434 version: &str,
435 reporter: &dyn Reporter,
436) -> VtaResult<()> {
437 fs::create_dir_all(prefix).map_err(|e| io(prefix, e))?;
439 let prefix_str = prefix.to_string_lossy().to_string();
440 let jobs = std::thread::available_parallelism()
441 .map(|n| n.get())
442 .unwrap_or(1)
443 .to_string();
444
445 for (i, step) in recipe.steps.iter().enumerate() {
446 let Some((prog, rest)) = step.split_first() else {
447 continue; };
449 let args: Vec<String> = rest
450 .iter()
451 .map(|a| a.replace("{prefix}", &prefix_str).replace("{jobs}", &jobs))
452 .collect();
453 let prog = prog
454 .replace("{prefix}", &prefix_str)
455 .replace("{jobs}", &jobs);
456
457 reporter.phase(&format!(
458 "building {tool} {version} [{}/{}]: {prog}",
459 i + 1,
460 recipe.steps.len()
461 ));
462 let status = std::process::Command::new(&prog)
463 .args(&args)
464 .current_dir(src_dir)
465 .env("PREFIX", &prefix_str)
466 .status()
467 .map_err(|e| {
468 VtaError::new(
469 Area::Inst,
470 4,
471 format!("source build of `{tool} {version}`: cannot start `{prog}`: {e}"),
472 )
473 })?;
474 if !status.success() {
475 return Err(VtaError::new(
476 Area::Inst,
477 4,
478 format!(
479 "source build of `{tool} {version}`: step `{prog}` failed ({status}); \
480 ensure the required build toolchain (C compiler, make, …) is installed"
481 ),
482 ));
483 }
484 }
485
486 let populated = fs::read_dir(prefix)
489 .map(|mut d| d.next().is_some())
490 .unwrap_or(false);
491 if !populated {
492 return Err(VtaError::new(
493 Area::Inst,
494 4,
495 format!("source build of `{tool} {version}`: recipe produced an empty install prefix"),
496 ));
497 }
498 Ok(())
499}
500
501pub fn extract(
505 archive: &str,
506 src: &Path,
507 dest: &Path,
508 raw_name: &str,
509 strip: u32,
510 max_decompressed: u64,
511) -> VtaResult<()> {
512 match archive {
513 "tar.gz" | "tgz" => extract_targz(src, dest, strip, max_decompressed),
514 "zip" => extract_zip(src, dest, strip, max_decompressed),
515 "raw" => {
516 fs::create_dir_all(dest).map_err(|e| io(dest, e))?;
517 let out = dest.join(raw_name);
518 fs::copy(src, &out).map_err(|e| io(&out, e))?;
519 set_executable(&out);
520 Ok(())
521 }
522 other => Err(VtaError::new(
523 Area::Inst,
524 3,
525 format!("unsupported archive kind `{other}` (supported: tar.gz, tgz, zip, raw)"),
526 )),
527 }
528}
529
530fn extract_zip(src: &Path, dest: &Path, strip: u32, max_decompressed: u64) -> VtaResult<()> {
535 use std::path::PathBuf;
536 let file = fs::File::open(src).map_err(|e| io(src, e))?;
537 let mut archive = zip::ZipArchive::new(file)
538 .map_err(|e| VtaError::new(Area::Inst, 1, format!("reading zip archive: {e}")))?;
539 fs::create_dir_all(dest).map_err(|e| io(dest, e))?;
540 let dest_canon = dest.canonicalize().map_err(|e| io(dest, e))?;
541 let mut budget = max_decompressed;
544
545 for i in 0..archive.len() {
546 let mut entry = archive
547 .by_index(i)
548 .map_err(|e| VtaError::new(Area::Inst, 1, format!("reading zip entry: {e}")))?;
549 let Some(path) = entry.enclosed_name() else {
551 return Err(traversal());
552 };
553 let stripped: PathBuf = path.components().skip(strip as usize).collect();
554 if stripped.as_os_str().is_empty() {
555 continue;
556 }
557 if escapes(&stripped) {
558 return Err(traversal());
559 }
560 let out = dest.join(&stripped);
561
562 if entry.is_dir() {
563 fs::create_dir_all(&out).map_err(|e| io(&out, e))?;
564 continue;
565 }
566
567 if let Some(parent) = out.parent() {
568 fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
569 let parent_canon = parent.canonicalize().map_err(|e| io(parent, e))?;
572 if !parent_canon.starts_with(&dest_canon) {
573 return Err(traversal());
574 }
575 }
576
577 let mode = entry.unix_mode();
578 if mode.is_some_and(|m| m & 0o170000 == 0o120000) {
581 let mut target = String::new();
582 LimitReader::new(&mut entry, 4096)
583 .read_to_string(&mut target)
584 .map_err(|e| VtaError::new(Area::Inst, 1, format!("zip link target: {e}")))?;
585 let target_path = Path::new(&target);
586 let base = stripped.parent().unwrap_or_else(|| Path::new(""));
587 if link_target_escapes(base, target_path) {
588 return Err(VtaError::new(
589 Area::Inst,
590 1,
591 format!(
592 "archive link entry `{}` has an unsafe target `{target}` (rejected)",
593 stripped.display()
594 ),
595 ));
596 }
597 #[cfg(unix)]
598 std::os::unix::fs::symlink(target_path, &out).map_err(|e| io(&out, e))?;
599 continue;
601 }
602
603 let mut writer = fs::File::create(&out).map_err(|e| io(&out, e))?;
604 let mut limited = LimitReader::new(&mut entry, budget);
605 let copied = std::io::copy(&mut limited, &mut writer)
606 .map_err(|e| VtaError::new(Area::Inst, 1, format!("unpacking zip entry: {e}")))?;
607 budget = budget.saturating_sub(copied);
608
609 #[cfg(unix)]
612 {
613 use std::os::unix::fs::PermissionsExt;
614 let safe = mode.map(|m| m & 0o777).unwrap_or(0o644);
615 let _ = fs::set_permissions(&out, fs::Permissions::from_mode(safe));
616 }
617 strip_special_bits(&out);
618 }
619 Ok(())
620}
621
622fn extract_targz(src: &Path, dest: &Path, strip: u32, max_decompressed: u64) -> VtaResult<()> {
623 use std::path::PathBuf;
624 let file = fs::File::open(src).map_err(|e| io(src, e))?;
625 let gz = LimitReader::new(flate2::read::GzDecoder::new(file), max_decompressed);
628 let mut archive = tar::Archive::new(gz);
629 archive.set_preserve_permissions(true);
632 let dest_canon = dest.canonicalize().map_err(|e| io(dest, e))?;
633 let entries = archive
634 .entries()
635 .map_err(|e| VtaError::new(Area::Inst, 1, format!("reading archive: {e}")))?;
636 for entry in entries {
637 let mut entry = entry
638 .map_err(|e| VtaError::new(Area::Inst, 1, format!("reading archive entry: {e}")))?;
639 let entry_type = entry.header().entry_type();
640 let path = entry
641 .path()
642 .map_err(|e| VtaError::new(Area::Inst, 1, format!("entry path: {e}")))?
643 .into_owned();
644 let stripped: PathBuf = path.components().skip(strip as usize).collect();
645 if stripped.as_os_str().is_empty() {
646 continue;
647 }
648 if escapes(&stripped) {
650 return Err(traversal());
651 }
652 if matches!(entry_type, tar::EntryType::Symlink | tar::EntryType::Link) {
661 let target = entry
662 .link_name()
663 .map_err(|e| VtaError::new(Area::Inst, 1, format!("link target: {e}")))?
664 .map(|c| c.into_owned())
665 .unwrap_or_default();
666 let base = if entry_type == tar::EntryType::Symlink {
667 stripped.parent().unwrap_or_else(|| Path::new(""))
668 } else {
669 Path::new("")
670 };
671 if link_target_escapes(base, &target) {
672 return Err(VtaError::new(
673 Area::Inst,
674 1,
675 format!(
676 "archive link entry `{}` has an unsafe target `{}` (rejected)",
677 stripped.display(),
678 target.display()
679 ),
680 ));
681 }
682 }
683 let out = dest.join(&stripped);
684 if let Some(parent) = out.parent() {
685 fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
686 let parent_canon = parent.canonicalize().map_err(|e| io(parent, e))?;
690 if !parent_canon.starts_with(&dest_canon) {
691 return Err(traversal());
692 }
693 }
694 entry
695 .unpack(&out)
696 .map_err(|e| VtaError::new(Area::Inst, 1, format!("unpacking entry: {e}")))?;
697 strip_special_bits(&out);
699 }
700 Ok(())
701}
702
703fn link_target_escapes(base_dir: &Path, target: &Path) -> bool {
710 use std::path::Component;
711 if target.is_absolute() {
712 return true;
713 }
714 let mut depth: i64 = 0;
715 for c in base_dir.components() {
716 match c {
717 Component::Normal(_) => depth += 1,
718 Component::ParentDir => depth -= 1,
719 _ => {}
720 }
721 }
722 for c in target.components() {
723 match c {
724 Component::Normal(_) => depth += 1,
725 Component::CurDir => {}
726 Component::ParentDir => {
727 depth -= 1;
728 if depth < 0 {
729 return true;
730 }
731 }
732 Component::RootDir | Component::Prefix(_) => return true,
733 }
734 }
735 depth < 0
736}
737
738fn escapes(p: &Path) -> bool {
740 use std::path::Component;
741 p.components().any(|c| {
742 matches!(
743 c,
744 Component::ParentDir | Component::RootDir | Component::Prefix(_)
745 )
746 })
747}
748
749fn traversal() -> VtaError {
750 VtaError::new(
751 Area::Inst,
752 1,
753 "archive entry escapes destination (path traversal rejected)".to_string(),
754 )
755}
756
757struct LimitReader<R> {
759 inner: R,
760 remaining: u64,
761}
762
763impl<R> LimitReader<R> {
764 fn new(inner: R, limit: u64) -> Self {
765 LimitReader {
766 inner,
767 remaining: limit,
768 }
769 }
770}
771
772impl<R: Read> Read for LimitReader<R> {
773 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
774 let n = self.inner.read(buf)?;
775 let n64 = n as u64;
776 if n64 > self.remaining {
777 return Err(std::io::Error::new(
778 std::io::ErrorKind::InvalidData,
779 "decompressed size exceeds configured maximum (possible decompression bomb)",
780 ));
781 }
782 self.remaining -= n64;
783 Ok(n)
784 }
785}
786
787#[cfg(unix)]
789fn strip_special_bits(path: &Path) {
790 use std::os::unix::fs::PermissionsExt;
791 if let Ok(meta) = fs::symlink_metadata(path) {
793 if meta.file_type().is_symlink() {
794 return;
795 }
796 let mode = meta.permissions().mode();
797 let safe = mode & 0o777; if safe != mode {
799 let mut perms = meta.permissions();
800 perms.set_mode(safe);
801 let _ = fs::set_permissions(path, perms);
802 }
803 }
804}
805
806#[cfg(not(unix))]
807fn strip_special_bits(_path: &Path) {}
808
809fn basename(p: &str) -> String {
810 p.rsplit(['/', '\\']).next().unwrap_or(p).to_string()
811}
812
813#[cfg(unix)]
814fn set_executable(path: &Path) {
815 use std::os::unix::fs::PermissionsExt;
816 if let Ok(meta) = fs::metadata(path) {
817 let mut perms = meta.permissions();
818 perms.set_mode(perms.mode() | 0o755);
819 let _ = fs::set_permissions(path, perms);
820 }
821}
822
823#[cfg(not(unix))]
824fn set_executable(_path: &Path) {}
825
826fn io(path: &Path, e: std::io::Error) -> VtaError {
827 VtaError::new(Area::Inst, 2, format!("{}: {e}", path.display()))
828}
829
830#[cfg(test)]
831mod tests {
832 use super::*;
833
834 fn home(tag: &str) -> PathBuf {
835 let p = std::env::temp_dir().join(format!("vanta-install-{}-{}", tag, std::process::id()));
836 let _ = fs::remove_dir_all(&p);
837 p
838 }
839
840 #[test]
841 fn engine_opens_and_creates_state() {
842 let h = home("open");
843 let e = Engine::open(&h).unwrap();
844 assert_eq!(
845 e.state().schema_version().unwrap(),
846 vanta_state::SCHEMA_VERSION
847 );
848 let _ = fs::remove_dir_all(&h);
849 }
850
851 #[test]
852 fn extracts_targz_then_publishes() {
853 use flate2::write::GzEncoder;
854 use flate2::Compression;
855
856 let mut builder = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default()));
858 let mut header = tar::Header::new_gnu();
859 let payload = b"#!/bin/sh\necho hi\n";
860 header.set_size(payload.len() as u64);
861 header.set_mode(0o755);
862 header.set_cksum();
863 builder
864 .append_data(&mut header, "bin/tool", &payload[..])
865 .unwrap();
866 let gz = builder.into_inner().unwrap();
867 let bytes = gz.finish().unwrap();
868
869 let h = home("targz");
870 let store = Store::open(&h).unwrap();
871 let archive_path = store.downloads_dir().join("a.tar.gz");
872 fs::write(&archive_path, &bytes).unwrap();
873
874 let staging = store.new_staging().unwrap();
875 extract(
876 "tar.gz",
877 &archive_path,
878 &staging,
879 "tool",
880 0,
881 DEFAULT_MAX_DECOMPRESSED,
882 )
883 .unwrap();
884 assert!(staging.join("bin/tool").exists());
885
886 let key = store.publish_tree(&staging).unwrap();
887 assert!(store.has(&key));
888 assert!(store.verify_entry(&key).unwrap());
889 let _ = fs::remove_dir_all(&h);
890 }
891
892 #[test]
893 fn source_build_runs_recipe_into_prefix() {
894 let src = home("bld-src");
895 fs::create_dir_all(&src).unwrap();
896 let prefix = home("bld-pfx");
897 let recipe = BuildRecipe {
899 steps: vec![
900 vec!["sh".into(), "-c".into(), "mkdir -p {prefix}/bin".into()],
901 vec![
902 "sh".into(),
903 "-c".into(),
904 "printf '#!/bin/sh\\necho hi\\n' > {prefix}/bin/tool && chmod +x {prefix}/bin/tool"
905 .into(),
906 ],
907 ],
908 };
909 run_build(&recipe, &src, &prefix, "tool", "1.0", &()).unwrap();
910 let bin = prefix.join("bin/tool");
911 assert!(bin.exists(), "recipe should install bin/tool");
912 let out = std::process::Command::new(&bin).output().unwrap();
913 assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hi");
914 let _ = fs::remove_dir_all(&src);
915 let _ = fs::remove_dir_all(&prefix);
916 }
917
918 #[test]
919 fn source_build_failing_step_aborts() {
920 let src = home("bld-fail-src");
921 fs::create_dir_all(&src).unwrap();
922 let prefix = home("bld-fail-pfx");
923 let recipe = BuildRecipe {
924 steps: vec![vec!["sh".into(), "-c".into(), "exit 3".into()]],
925 };
926 let err = run_build(&recipe, &src, &prefix, "tool", "1.0", &()).unwrap_err();
927 assert!(err.to_string().contains("failed"), "{err}");
928 let _ = fs::remove_dir_all(&src);
929 let _ = fs::remove_dir_all(&prefix);
930 }
931
932 #[test]
933 fn source_build_empty_prefix_rejected() {
934 let src = home("bld-empty-src");
935 fs::create_dir_all(&src).unwrap();
936 let prefix = home("bld-empty-pfx");
937 let recipe = BuildRecipe {
939 steps: vec![vec!["sh".into(), "-c".into(), "true".into()]],
940 };
941 let err = run_build(&recipe, &src, &prefix, "tool", "1.0", &()).unwrap_err();
942 assert!(err.to_string().contains("empty install prefix"), "{err}");
943 let _ = fs::remove_dir_all(&src);
944 let _ = fs::remove_dir_all(&prefix);
945 }
946
947 #[test]
948 fn link_target_guard_allows_internal_dotdot_rejects_escape() {
949 use std::path::Path;
950 assert!(!link_target_escapes(
952 Path::new("bin"),
953 Path::new("../lib/node_modules/corepack/dist/corepack.js")
954 ));
955 assert!(!link_target_escapes(Path::new("bin"), Path::new("node")));
957 assert!(link_target_escapes(
959 Path::new("bin"),
960 Path::new("../../etc/passwd")
961 ));
962 assert!(link_target_escapes(
964 Path::new("bin"),
965 Path::new("/etc/passwd")
966 ));
967 assert!(link_target_escapes(Path::new(""), Path::new("../x")));
969 assert!(!link_target_escapes(Path::new(""), Path::new("bin/node")));
970 }
971
972 fn make_zip(entries: &[(&str, u32, &[u8])]) -> Vec<u8> {
974 use std::io::Write;
975 let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
976 for (name, mode, payload) in entries {
977 let opts = zip::write::SimpleFileOptions::default().unix_permissions(*mode);
978 w.start_file(*name, opts).unwrap();
979 w.write_all(payload).unwrap();
980 }
981 w.finish().unwrap().into_inner()
982 }
983
984 #[test]
985 fn extracts_zip_with_strip_and_modes() {
986 let h = home("zip");
987 let store = Store::open(&h).unwrap();
988 let bytes = make_zip(&[
989 ("terraform_1.9.0/terraform", 0o755, b"#!/bin/sh\necho tf\n"),
990 ("terraform_1.9.0/README.md", 0o644, b"docs"),
991 ]);
992 let archive_path = store.downloads_dir().join("a.zip");
993 fs::write(&archive_path, &bytes).unwrap();
994
995 let staging = store.new_staging().unwrap();
996 extract(
997 "zip",
998 &archive_path,
999 &staging,
1000 "terraform",
1001 1,
1002 DEFAULT_MAX_DECOMPRESSED,
1003 )
1004 .unwrap();
1005 let bin = staging.join("terraform");
1006 assert!(bin.exists());
1007 assert!(staging.join("README.md").exists());
1008 #[cfg(unix)]
1009 {
1010 use std::os::unix::fs::PermissionsExt;
1011 let mode = fs::metadata(&bin).unwrap().permissions().mode();
1012 assert_eq!(mode & 0o777, 0o755, "exec bit preserved from zip modes");
1013 }
1014 let _ = fs::remove_dir_all(&h);
1015 }
1016
1017 #[test]
1018 fn zip_slip_rejected() {
1019 let h = home("zipslip");
1020 let store = Store::open(&h).unwrap();
1021 let bytes = make_zip(&[("../evil", 0o644, b"pwn")]);
1022 let archive_path = store.downloads_dir().join("evil.zip");
1023 fs::write(&archive_path, &bytes).unwrap();
1024
1025 let staging = store.new_staging().unwrap();
1026 let err = extract(
1027 "zip",
1028 &archive_path,
1029 &staging,
1030 "evil",
1031 0,
1032 DEFAULT_MAX_DECOMPRESSED,
1033 )
1034 .unwrap_err();
1035 assert!(err.to_string().contains("traversal"), "{err}");
1036 let _ = fs::remove_dir_all(&h);
1037 }
1038
1039 #[test]
1040 fn zip_decompression_budget_enforced() {
1041 let h = home("zipbomb");
1042 let store = Store::open(&h).unwrap();
1043 let big = vec![0u8; 64 * 1024];
1044 let bytes = make_zip(&[("big.bin", 0o644, &big[..])]);
1045 let archive_path = store.downloads_dir().join("big.zip");
1046 fs::write(&archive_path, &bytes).unwrap();
1047
1048 let staging = store.new_staging().unwrap();
1049 let err = extract("zip", &archive_path, &staging, "big", 0, 1024).unwrap_err();
1051 assert!(err.to_string().contains("decompress"), "{err}");
1052 let _ = fs::remove_dir_all(&h);
1053 }
1054
1055 #[test]
1056 fn rejects_unsupported_archive() {
1057 let err = extract(
1058 "tar.xz",
1059 Path::new("/x"),
1060 Path::new("/y"),
1061 "t",
1062 0,
1063 DEFAULT_MAX_DECOMPRESSED,
1064 )
1065 .unwrap_err();
1066 assert_eq!(err.area, Area::Inst);
1067 }
1068
1069 #[test]
1072 fn rejects_symlink_escape_archive() {
1073 use flate2::write::GzEncoder;
1074 use flate2::Compression;
1075
1076 let mut builder = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default()));
1077 let mut link = tar::Header::new_gnu();
1079 link.set_entry_type(tar::EntryType::Symlink);
1080 link.set_size(0);
1081 link.set_mode(0o777);
1082 builder
1083 .append_link(&mut link, "evil", "/tmp/vanta-escape-target")
1084 .unwrap();
1085 let payload = b"pwned";
1087 let mut f = tar::Header::new_gnu();
1088 f.set_size(payload.len() as u64);
1089 f.set_mode(0o644);
1090 f.set_cksum();
1091 builder.append_data(&mut f, "evil", &payload[..]).unwrap();
1092 let bytes = builder.into_inner().unwrap().finish().unwrap();
1093
1094 let h = home("symlink");
1095 let store = Store::open(&h).unwrap();
1096 let archive_path = store.downloads_dir().join("evil.tar.gz");
1097 fs::write(&archive_path, &bytes).unwrap();
1098 let staging = store.new_staging().unwrap();
1099 let err = extract(
1100 "tar.gz",
1101 &archive_path,
1102 &staging,
1103 "tool",
1104 0,
1105 DEFAULT_MAX_DECOMPRESSED,
1106 )
1107 .unwrap_err();
1108 assert_eq!(err.area, Area::Inst);
1109 assert!(!Path::new("/tmp/vanta-escape-target").exists());
1110 let _ = fs::remove_dir_all(&h);
1111 }
1112
1113 #[test]
1115 fn rejects_decompression_bomb() {
1116 use flate2::write::GzEncoder;
1117 use flate2::Compression;
1118
1119 let mut builder = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default()));
1120 let big = vec![0u8; 1_000_000]; let mut header = tar::Header::new_gnu();
1122 header.set_size(big.len() as u64);
1123 header.set_mode(0o644);
1124 header.set_cksum();
1125 builder.append_data(&mut header, "big", &big[..]).unwrap();
1126 let bytes = builder.into_inner().unwrap().finish().unwrap();
1127
1128 let h = home("bomb");
1129 let store = Store::open(&h).unwrap();
1130 let archive_path = store.downloads_dir().join("bomb.tar.gz");
1131 fs::write(&archive_path, &bytes).unwrap();
1132 let staging = store.new_staging().unwrap();
1133 let err = extract("tar.gz", &archive_path, &staging, "tool", 0, 4096).unwrap_err();
1135 assert_eq!(err.area, Area::Inst);
1136 let _ = fs::remove_dir_all(&h);
1137 }
1138}