Skip to main content

vector_core/xdc/
package.rs

1//! Reading a `.xdc` package's `manifest.toml`, and nothing else from it.
2
3use std::io::{Cursor, Read};
4
5use serde::Deserialize;
6
7/// More than any real manifest; bounds what one read inflates.
8const MANIFEST_CAP: u64 = 64 * 1024;
9
10#[derive(Debug, Clone, Default, Deserialize)]
11pub struct Manifest {
12    /// Empty when the package names none; the file name stands in (see [`Manifest::or_named`]).
13    #[serde(default)]
14    pub name: String,
15    /// A stable app id, when the author set one (`id = "3d-tic-tac-toe"`).
16    #[serde(default)]
17    pub id: Option<String>,
18    #[serde(default)]
19    pub description: String,
20    #[serde(default)]
21    pub icon: String,
22    #[serde(default)]
23    pub version: String,
24    #[serde(default)]
25    pub source_code_url: Option<String>,
26}
27
28impl Manifest {
29    /// The manifest with `file_name` standing in for a name the package doesn't
30    /// set, as the WebXDC spec has it. Kept apart from reading, since the same
31    /// bytes can be shared under any file name.
32    pub fn or_named(mut self, file_name: &str) -> Self {
33        if self.name.trim().is_empty() {
34            self.name = file_name.trim_end_matches(".xdc").to_string();
35        }
36        self
37    }
38}
39
40/// What the package's own bytes say: its `manifest.toml`, or an empty one when
41/// it has none. Reads one capped entry; the rest of the archive is never
42/// inflated. CPU-bound: call from a blocking thread.
43pub fn read_manifest(bytes: &[u8]) -> Result<Manifest, String> {
44    let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("Invalid mini app: {e}"))?;
45    let stored = archive
46        .file_names()
47        .find(|n| n.eq_ignore_ascii_case("manifest.toml"))
48        .map(str::to_string);
49    let Some(stored) = stored else {
50        return Ok(Manifest::default());
51    };
52    let mut entry = archive.by_name(&stored).map_err(|e| format!("Invalid mini app: {e}"))?;
53    // Entry headers can't be trusted; bound the bytes actually inflated.
54    let mut raw = Vec::new();
55    (&mut entry).take(MANIFEST_CAP + 1).read_to_end(&mut raw).map_err(|e| e.to_string())?;
56    if raw.len() as u64 > MANIFEST_CAP {
57        return Err("Invalid manifest: too large".into());
58    }
59    let text = String::from_utf8(raw).map_err(|e| format!("Invalid manifest: {e}"))?;
60    toml::from_str(&text).map_err(|e| format!("Invalid manifest: {e}"))
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use std::io::Write;
67
68    fn zip_of(files: &[(&str, &[u8])]) -> Vec<u8> {
69        let mut out = Cursor::new(Vec::new());
70        {
71            let mut z = zip::ZipWriter::new(&mut out);
72            let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
73            for (name, body) in files {
74                z.start_file(*name, opts).unwrap();
75                z.write_all(body).unwrap();
76            }
77            z.finish().unwrap();
78        }
79        out.into_inner()
80    }
81
82    #[test]
83    fn it_reads_the_manifest_id_and_name() {
84        let pkg = zip_of(&[("index.html", b"<html>"), ("manifest.toml", b"name = \"Chess\"\nid = \"chess\"\n")]);
85        let m = read_manifest(&pkg).unwrap().or_named("fallback.xdc");
86        assert_eq!((m.name.as_str(), m.id.as_deref()), ("Chess", Some("chess")));
87    }
88
89    #[test]
90    fn a_package_without_a_name_takes_the_file_name() {
91        let bare = read_manifest(&zip_of(&[("index.html", b"<html>")])).unwrap();
92        assert_eq!((bare.name.as_str(), bare.id.as_deref()), ("", None), "the bytes alone name nothing");
93        assert_eq!(bare.clone().or_named("chess.xdc").name, "chess");
94        assert_eq!(bare.or_named("notchess.xdc").name, "notchess", "one package, two names");
95        let unnamed = read_manifest(&zip_of(&[("manifest.toml", b"id = \"chess\"\n")])).unwrap().or_named("c.xdc");
96        assert_eq!((unnamed.name.as_str(), unnamed.id.as_deref()), ("c", Some("chess")));
97    }
98
99    #[test]
100    fn an_inflating_manifest_is_refused_without_reading_it_all() {
101        let bomb = vec![b'#'; 8 * 1024 * 1024];
102        let pkg = zip_of(&[("manifest.toml", &bomb)]);
103        assert!(pkg.len() < 64 * 1024, "the bomb is small on the wire");
104        assert!(read_manifest(&pkg).is_err());
105    }
106
107    #[test]
108    fn garbage_is_an_error_not_a_panic() {
109        assert!(read_manifest(b"not a zip").is_err());
110    }
111}