Skip to main content

vtcode_skills/
bundle.rs

1//! Skill bundle import/export
2//!
3//! Supports zip-based packaging of skills for distribution, version management,
4//! and inline bundle injection. Follows OpenAI Skills API packaging patterns:
5//! - Safe zip extraction with path traversal protection
6//! - Size limits (50MB compressed, 25MB per file, 200MB total uncompressed, 500 files max)
7//! - Manifest validation after extraction
8//! - Versioned storage layout
9
10use anyhow::{Context, Result, bail};
11use hashbrown::HashMap;
12use std::fs;
13use std::io::{Read, Write};
14use std::path::{Path, PathBuf};
15use tracing::{debug, info, warn};
16use vtcode_commons::canonicalize;
17use vtcode_commons::safe_archive_relative_path;
18
19/// Maximum compressed bundle size (50 MB)
20const MAX_BUNDLE_SIZE: usize = 50 * 1024 * 1024;
21/// Maximum uncompressed file size (25 MB)
22const MAX_FILE_SIZE: usize = 25 * 1024 * 1024;
23/// Maximum total uncompressed size (200 MB)
24///
25/// `MAX_BUNDLE_SIZE` bounds the *compressed* input, but DEFLATE can expand by
26/// ~1000x, so an uncompressed budget must be enforced while writing. Without it
27/// a single small bundle can fill the disk (zip bomb).
28const MAX_TOTAL_UNCOMPRESSED_SIZE: u64 = 200 * 1024 * 1024;
29/// Maximum file count per bundle
30const MAX_FILE_COUNT: usize = 500;
31
32/// Whether `total` uncompressed bytes fit within the bundle budget.
33///
34/// Shared by extraction (incremental, per entry) and post-extraction
35/// validation so the two enforcement points cannot drift.
36fn within_total_budget(total: u64) -> bool {
37    total <= MAX_TOTAL_UNCOMPRESSED_SIZE
38}
39
40/// Result of importing a skill bundle
41#[derive(Debug, Clone)]
42pub struct ImportedSkillInfo {
43    name: String,
44    version: Option<String>,
45    description: String,
46    path: PathBuf,
47    file_count: usize,
48    total_size: u64,
49}
50
51/// Export a skill directory to a zip bundle (bytes)
52///
53/// Walks the skill directory and creates a zip archive.
54/// The archive preserves the directory structure with the skill name as root.
55pub fn export_skill_bundle(skill_root: &Path) -> Result<Vec<u8>> {
56    let skill_md = skill_root.join("SKILL.md");
57    if !skill_md.exists() {
58        bail!("No SKILL.md found at {}", skill_root.display());
59    }
60
61    let mut buf = Vec::new();
62    {
63        let cursor = std::io::Cursor::new(&mut buf);
64        let mut zip_writer = zip::ZipWriter::new(cursor);
65        let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
66
67        add_dir_to_zip(&mut zip_writer, skill_root, skill_root, options)?;
68        zip_writer.finish().context("Failed to finalize zip archive")?;
69    }
70
71    info!("Exported skill bundle from {}: {} bytes", skill_root.display(), buf.len());
72    Ok(buf)
73}
74
75fn add_dir_to_zip<W: Write + std::io::Seek>(
76    zip_writer: &mut zip::ZipWriter<W>,
77    root: &Path,
78    dir: &Path,
79    options: zip::write::SimpleFileOptions,
80) -> Result<()> {
81    for entry in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
82        let entry = entry?;
83        let path = entry.path();
84        let rel = path
85            .strip_prefix(root)
86            .with_context(|| format!("stripping prefix from {}", path.display()))?;
87
88        // Trust the dirent type rather than stat-ing each entry again.
89        if vtcode_commons::walk::entry_is_dir(&entry) {
90            let dir_name = format!("{}/", rel.to_string_lossy());
91            zip_writer
92                .add_directory(&dir_name, options)
93                .with_context(|| format!("adding directory {dir_name}"))?;
94            add_dir_to_zip(zip_writer, root, &path, options)?;
95        } else {
96            let name = rel.to_string_lossy().to_string();
97            zip_writer
98                .start_file(&name, options)
99                .with_context(|| format!("starting file {name}"))?;
100            let data = fs::read(&path).with_context(|| format!("reading file {}", path.display()))?;
101            zip_writer.write_all(&data)?;
102        }
103    }
104    Ok(())
105}
106
107/// Import a skill bundle (zip bytes) into the skill store
108///
109/// Extracts the zip, validates SKILL.md, and moves to versioned storage.
110/// Storage layout: `<dest_store>/<skill-name>/<version>/...`
111pub fn import_skill_bundle(zip_bytes: &[u8], dest_store: &Path) -> Result<ImportedSkillInfo> {
112    if zip_bytes.len() > MAX_BUNDLE_SIZE {
113        bail!("Bundle size {} bytes exceeds maximum {} bytes", zip_bytes.len(), MAX_BUNDLE_SIZE);
114    }
115
116    let temp_dir = tempfile::tempdir().context("Failed to create temp directory")?;
117    let temp_path = temp_dir.path();
118
119    extract_zip_safely(zip_bytes, temp_path)?;
120
121    let skill_md_path = find_skill_md(temp_path)?;
122    let skill_root = skill_md_path.parent().unwrap_or(temp_path);
123
124    validate_extracted_bundle(skill_root)?;
125
126    let (manifest, _instructions) = crate::manifest::parse_skill_content(
127        &fs::read_to_string(&skill_md_path).context("Failed to read extracted SKILL.md")?,
128    )?;
129
130    let version = manifest.version.clone().unwrap_or_else(|| "0.0.0".to_string());
131
132    let dest_dir = dest_store.join(&manifest.name).join(&version);
133    if dest_dir.exists() {
134        warn!("Overwriting existing skill version at {}", dest_dir.display());
135        fs::remove_dir_all(&dest_dir).context("Failed to remove existing version")?;
136    }
137    fs::create_dir_all(&dest_dir).context("Failed to create destination directory")?;
138
139    let (file_count, total_size) = copy_dir_recursive(skill_root, &dest_dir)?;
140
141    info!(
142        "Imported skill '{}' v{} ({} files, {} bytes) to {}",
143        manifest.name,
144        version,
145        file_count,
146        total_size,
147        dest_dir.display()
148    );
149
150    update_skill_index(dest_store, &manifest.name, &version)?;
151
152    Ok(ImportedSkillInfo {
153        name: manifest.name,
154        version: Some(version),
155        description: manifest.description,
156        path: dest_dir,
157        file_count,
158        total_size,
159    })
160}
161
162/// Import a skill from base64-encoded zip (inline bundle)
163pub fn import_inline_bundle(base64_data: &str, dest_store: &Path) -> Result<ImportedSkillInfo> {
164    use base64::Engine;
165    let bytes = base64::engine::general_purpose::STANDARD
166        .decode(base64_data)
167        .context("Failed to decode base64 bundle")?;
168    import_skill_bundle(&bytes, dest_store)
169}
170
171/// Safely extract a zip archive with path-traversal and size protections
172fn extract_zip_safely(zip_bytes: &[u8], dest: &Path) -> Result<()> {
173    let cursor = std::io::Cursor::new(zip_bytes);
174    let mut archive = zip::ZipArchive::new(cursor).context("Failed to open zip archive")?;
175
176    if archive.len() > MAX_FILE_COUNT {
177        bail!("Zip contains {} entries, exceeds maximum {}", archive.len(), MAX_FILE_COUNT);
178    }
179
180    let mut total_uncompressed: u64 = 0;
181
182    for i in 0..archive.len() {
183        let mut file = archive.by_index(i).with_context(|| format!("reading zip entry {i}"))?;
184        let raw_name = file
185            .name()
186            .with_context(|| format!("zip entry {i} has a non-UTF-8 name"))?
187            .into_owned();
188
189        let safe_name = safe_archive_relative_path(Path::new(&raw_name))
190            .with_context(|| format!("Path traversal detected in zip entry: {raw_name}"))?;
191        if safe_name.as_os_str().is_empty() {
192            continue;
193        }
194
195        let out_path = dest.join(safe_name);
196
197        if file.is_dir() {
198            fs::create_dir_all(&out_path).with_context(|| format!("creating dir {}", out_path.display()))?;
199        } else {
200            if file.size() > MAX_FILE_SIZE as u64 {
201                bail!("Zip entry '{}' ({} bytes) exceeds maximum {} bytes", raw_name, file.size(), MAX_FILE_SIZE);
202            }
203
204            if let Some(parent) = out_path.parent() {
205                fs::create_dir_all(parent)?;
206            }
207
208            let mut out_file =
209                fs::File::create(&out_path).with_context(|| format!("creating file {}", out_path.display()))?;
210            // Bound by bytes actually written: the archive's declared `file.size()`
211            // cannot be trusted, and the cumulative budget stops zip bombs.
212            let written = copy_bounded(&mut file, &mut out_file, MAX_FILE_SIZE as u64)
213                .with_context(|| format!("writing file {}", out_path.display()))?;
214            total_uncompressed += written;
215            if !within_total_budget(total_uncompressed) {
216                bail!(
217                    "Zip uncompressed size {total_uncompressed} bytes exceeds maximum {MAX_TOTAL_UNCOMPRESSED_SIZE} bytes"
218                );
219            }
220        }
221    }
222
223    Ok(())
224}
225
226/// Copy at most `limit` bytes from `reader` into `writer`.
227///
228/// Fails rather than silently truncating when the reader yields more than
229/// `limit`, so untrusted input whose declared size lies is still capped by the
230/// bytes actually written.
231fn copy_bounded<R: Read, W: Write>(reader: &mut R, writer: &mut W, limit: u64) -> Result<u64> {
232    let mut bounded = reader.take(limit.saturating_add(1));
233    let written = std::io::copy(&mut bounded, writer)?;
234    if written > limit {
235        bail!("entry exceeds maximum {limit} bytes");
236    }
237    Ok(written)
238}
239
240/// Find SKILL.md in extracted directory (handles nested structures)
241fn find_skill_md(dir: &Path) -> Result<PathBuf> {
242    let direct = dir.join("SKILL.md");
243    if direct.exists() {
244        return Ok(direct);
245    }
246    let direct_lower = dir.join("skill.md");
247    if direct_lower.exists() {
248        return Ok(direct_lower);
249    }
250
251    for entry in fs::read_dir(dir).context("Failed to read extracted directory")? {
252        let entry = entry?;
253        if vtcode_commons::walk::entry_is_dir(&entry) {
254            let nested = entry.path().join("SKILL.md");
255            if nested.exists() {
256                return Ok(nested);
257            }
258            let nested_lower = entry.path().join("skill.md");
259            if nested_lower.exists() {
260                return Ok(nested_lower);
261            }
262        }
263    }
264
265    bail!("No SKILL.md found in extracted bundle")
266}
267
268/// Validate extracted bundle for security
269fn validate_extracted_bundle(skill_root: &Path) -> Result<()> {
270    let mut file_count = 0u64;
271    let mut total_size = 0u64;
272
273    validate_dir_recursive(skill_root, skill_root, &mut file_count, &mut total_size)?;
274
275    if file_count > MAX_FILE_COUNT as u64 {
276        bail!("Bundle contains {file_count} files, exceeds maximum {MAX_FILE_COUNT}");
277    }
278
279    if !within_total_budget(total_size) {
280        bail!("Bundle uncompressed size {total_size} bytes exceeds maximum {MAX_TOTAL_UNCOMPRESSED_SIZE} bytes");
281    }
282
283    Ok(())
284}
285
286fn validate_dir_recursive(root: &Path, dir: &Path, file_count: &mut u64, total_size: &mut u64) -> Result<()> {
287    for entry in fs::read_dir(dir)? {
288        let entry = entry?;
289        let path = entry.path();
290
291        if path.is_symlink() {
292            bail!("Symlinks not allowed in skill bundles: {}", path.display());
293        }
294
295        let canonical = canonicalize(&path).unwrap_or_else(|_| path.clone());
296        let root_canonical = canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
297        if !canonical.starts_with(&root_canonical) {
298            bail!("Path traversal detected: {} escapes bundle root", path.display());
299        }
300
301        if path.is_dir() {
302            validate_dir_recursive(root, &path, file_count, total_size)?;
303        } else {
304            *file_count += 1;
305            let size = entry.metadata()?.len();
306            if size > MAX_FILE_SIZE as u64 {
307                bail!("File {} ({size} bytes) exceeds maximum {MAX_FILE_SIZE} bytes", path.display(),);
308            }
309            *total_size += size;
310        }
311    }
312    Ok(())
313}
314
315/// Copy directory recursively, returning (file_count, total_bytes)
316fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(usize, u64)> {
317    let mut count = 0usize;
318    let mut size = 0u64;
319
320    for entry in fs::read_dir(src)? {
321        let entry = entry?;
322        let src_path = entry.path();
323        let file_name = entry.file_name();
324        let dst_path = dst.join(&file_name);
325
326        if vtcode_commons::walk::entry_is_dir(&entry) {
327            fs::create_dir_all(&dst_path)?;
328            let (c, s) = copy_dir_recursive(&src_path, &dst_path)?;
329            count += c;
330            size += s;
331        } else {
332            fs::copy(&src_path, &dst_path)
333                .with_context(|| format!("failed to copy {} to {}", src_path.display(), dst_path.display()))?;
334            count += 1;
335            size += entry
336                .metadata()
337                .with_context(|| format!("failed to stat {}", src_path.display()))?
338                .len();
339        }
340    }
341
342    Ok((count, size))
343}
344
345/// Skill store index for tracking versions
346#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
347pub struct SkillStoreIndex {
348    skills: HashMap<String, SkillVersionIndex>,
349}
350
351#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
352pub struct SkillVersionIndex {
353    latest_version: String,
354    #[serde(skip_serializing_if = "Option::is_none")]
355    default_version: Option<String>,
356    versions: Vec<String>,
357}
358
359/// Update the skill index after import
360fn update_skill_index(store_path: &Path, skill_name: &str, version: &str) -> Result<()> {
361    let index_path = store_path.join("index.json");
362
363    let mut index: SkillStoreIndex = if index_path.exists() {
364        let content = fs::read_to_string(&index_path)?;
365        serde_json::from_str(&content).unwrap_or_default()
366    } else {
367        SkillStoreIndex::default()
368    };
369
370    let entry = index.skills.entry(skill_name.to_string()).or_insert_with(|| SkillVersionIndex {
371        latest_version: version.to_string(),
372        default_version: None,
373        versions: Vec::new(),
374    });
375
376    if !entry.versions.contains(&version.to_string()) {
377        entry.versions.push(version.to_string());
378    }
379    entry.latest_version = version.to_string();
380
381    fs::create_dir_all(store_path)
382        .with_context(|| format!("failed to create store dir at {}", store_path.display()))?;
383    let index_json =
384        serde_json::to_vec_pretty(&index).with_context(|| format!("failed to serialize index for {skill_name}"))?;
385    fs::write(&index_path, index_json).with_context(|| format!("failed to write index at {}", index_path.display()))?;
386
387    debug!("Updated skill index at {}", index_path.display());
388    Ok(())
389}
390
391/// Load the skill store index
392pub fn load_skill_index(store_path: &Path) -> Result<SkillStoreIndex> {
393    let index_path = store_path.join("index.json");
394    if !index_path.exists() {
395        return Ok(SkillStoreIndex::default());
396    }
397    let content = fs::read_to_string(&index_path)?;
398    serde_json::from_str(&content).context("Failed to parse skill store index")
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    #[test]
406    fn test_skill_store_index_default() {
407        let index = SkillStoreIndex::default();
408        assert!(index.skills.is_empty());
409    }
410
411    #[test]
412    fn test_skill_store_index_roundtrip() {
413        let mut index = SkillStoreIndex::default();
414        index.skills.insert(
415            "test-skill".to_string(),
416            SkillVersionIndex {
417                latest_version: "1.0.0".to_string(),
418                default_version: Some("1.0.0".to_string()),
419                versions: vec!["0.9.0".to_string(), "1.0.0".to_string()],
420            },
421        );
422        let json = serde_json::to_string(&index).expect("serialize");
423        let parsed: SkillStoreIndex = serde_json::from_str(&json).expect("deserialize");
424        assert_eq!(parsed.skills["test-skill"].latest_version, "1.0.0");
425        assert_eq!(parsed.skills["test-skill"].versions.len(), 2);
426    }
427
428    #[test]
429    fn test_bundle_size_limit() {
430        let oversized = vec![0u8; MAX_BUNDLE_SIZE + 1];
431        let temp = tempfile::tempdir().expect("tempdir");
432        let result = import_skill_bundle(&oversized, temp.path());
433        assert!(result.is_err());
434        assert!(result.expect_err("should fail").to_string().contains("exceeds maximum"));
435    }
436
437    /// Build an uncompressed zip archive from `(name, contents)` entries.
438    fn zip_bytes(entries: &[(&str, &[u8])]) -> Vec<u8> {
439        let mut buf = Vec::new();
440        {
441            let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
442            let options = zip::write::SimpleFileOptions::default();
443            for (name, data) in entries {
444                writer.start_file(*name, options).expect("start_file");
445                writer.write_all(data).expect("write_all");
446            }
447            writer.finish().expect("finish");
448        }
449        buf
450    }
451
452    #[test]
453    fn copy_bounded_accepts_exactly_the_limit() {
454        let data = vec![7u8; 10];
455        let mut out = Vec::new();
456        let written = copy_bounded(&mut data.as_slice(), &mut out, 10).expect("exact limit is allowed");
457        assert_eq!(written, 10);
458        assert_eq!(out.len(), 10);
459    }
460
461    #[test]
462    fn copy_bounded_rejects_one_byte_over_the_limit() {
463        let data = vec![7u8; 11];
464        let mut out = Vec::new();
465        let err = copy_bounded(&mut data.as_slice(), &mut out, 10).expect_err("over limit must fail");
466        assert!(err.to_string().contains("exceeds maximum"), "unexpected error: {err}");
467    }
468
469    #[test]
470    fn within_total_budget_boundaries() {
471        assert!(within_total_budget(0));
472        assert!(within_total_budget(MAX_TOTAL_UNCOMPRESSED_SIZE));
473        assert!(!within_total_budget(MAX_TOTAL_UNCOMPRESSED_SIZE + 1));
474    }
475
476    #[test]
477    fn extract_rejects_parent_directory_traversal() {
478        let bytes = zip_bytes(&[("../evil.txt", b"pwned")]);
479        let temp = tempfile::tempdir().expect("tempdir");
480        let err = extract_zip_safely(&bytes, temp.path()).expect_err("traversal must fail");
481        assert!(err.to_string().contains("Path traversal"), "unexpected error: {err}");
482        assert!(!temp.path().join("../evil.txt").exists());
483    }
484
485    #[test]
486    fn extract_rejects_absolute_path_entries() {
487        let bytes = zip_bytes(&[("/abs.txt", b"pwned")]);
488        let temp = tempfile::tempdir().expect("tempdir");
489        let err = extract_zip_safely(&bytes, temp.path()).expect_err("absolute path must fail");
490        assert!(err.to_string().contains("Path traversal"), "unexpected error: {err}");
491    }
492
493    #[test]
494    fn extract_rejects_mid_path_traversal() {
495        let bytes = zip_bytes(&[("skills/../../evil.txt", b"pwned")]);
496        let temp = tempfile::tempdir().expect("tempdir");
497        let err = extract_zip_safely(&bytes, temp.path()).expect_err("mid-path traversal must fail");
498        assert!(err.to_string().contains("Path traversal"), "unexpected error: {err}");
499        assert!(!temp.path().join("evil.txt").exists());
500    }
501
502    #[test]
503    fn extract_accepts_dot_dot_inside_a_single_component() {
504        // `..` inside one component is a legitimate file name, not traversal;
505        // the substring check this replaced used to reject it.
506        let bytes = zip_bytes(&[("v1..2/README.md", b"body")]);
507        let temp = tempfile::tempdir().expect("tempdir");
508        extract_zip_safely(&bytes, temp.path()).expect("dot-dot component must extract");
509
510        assert_eq!(fs::read(temp.path().join("v1..2/README.md")).expect("read"), b"body");
511    }
512
513    #[test]
514    fn import_round_trips_an_exported_bundle() {
515        let source = tempfile::tempdir().expect("source tempdir");
516        let skill_dir = source.path().join("roundtrip-skill");
517        fs::create_dir_all(&skill_dir).expect("create skill dir");
518        fs::write(
519            skill_dir.join("SKILL.md"),
520            "---\nname: roundtrip-skill\ndescription: Round trip test skill\nversion: 1.2.3\n---\n# Body\n",
521        )
522        .expect("write SKILL.md");
523
524        let bytes = export_skill_bundle(&skill_dir).expect("export");
525
526        let store = tempfile::tempdir().expect("store tempdir");
527        let imported = import_skill_bundle(&bytes, store.path()).expect("import");
528        assert_eq!(imported.name, "roundtrip-skill");
529        assert!(imported.file_count >= 1, "expected at least SKILL.md to be copied");
530        assert!(imported.path.join("SKILL.md").exists(), "SKILL.md must land in the versioned store");
531    }
532}