Skip to main content

alpha2_engine/extract/
manifest.rs

1//! A plugin's manifest, naming its identity, artifacts, resources and extractor descriptor.
2
3use std::collections::HashSet;
4use std::fmt;
5
6use serde::{Deserialize, Serialize};
7
8use super::Descriptor;
9
10/// The longest manifest text accepted.
11pub const MAX_MANIFEST_BYTES: usize = 1024 * 1024;
12/// Most artifacts one manifest lists.
13pub const MAX_PLUGIN_ARTIFACTS: usize = 64;
14/// Most resources one manifest lists.
15pub const MAX_PLUGIN_RESOURCES: usize = 64;
16/// The longest artifact a manifest may pin, in bytes.
17pub const MAX_PLUGIN_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024;
18/// The longest resource a manifest may pin, in bytes: what a wasm module's memory can address.
19pub const MAX_PLUGIN_RESOURCE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
20/// The most bytes a manifest's resources may pin together.
21pub const MAX_PLUGIN_RESOURCES_TOTAL_BYTES: u64 = 4 * 1024 * 1024 * 1024;
22
23/// A plugin's manifest.
24#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
25#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
26#[serde(deny_unknown_fields)]
27pub struct PluginManifest {
28    /// Reverse-DNS id, equal to the descriptor's.
29    pub id: String,
30    /// The package's semantic version.
31    pub version: String,
32    /// The plugin ABI, `alpha2-plugin/1`.
33    #[cfg_attr(feature = "schema", schemars(extend("const" = alpha2_plugin_abi::ABI)))]
34    pub abi: String,
35    /// The contract the plugin implements.
36    pub kind: PluginKind,
37    /// The code, one artifact per target.
38    #[cfg_attr(feature = "schema", schemars(length(min = 1)))]
39    pub artifacts: Vec<PluginArtifact>,
40    /// Files the plugin reads through `resource()`.
41    #[serde(default, skip_serializing_if = "Vec::is_empty")]
42    pub resources: Vec<PluginResource>,
43    /// The descriptor `describe()` returns.
44    pub descriptor: Descriptor,
45}
46
47/// The contract a plugin implements.
48#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
49#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
50#[serde(rename_all = "snake_case")]
51pub enum PluginKind {
52    /// An extractor.
53    Extractor,
54}
55
56/// One build of a plugin.
57#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
58#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
59#[serde(deny_unknown_fields)]
60pub struct PluginArtifact {
61    /// `wasm32`, or the Rust target triple a native artifact is built for.
62    pub target: String,
63    /// What kind of code it is.
64    #[serde(rename = "type")]
65    pub kind: ArtifactKind,
66    /// Where it is: a path under the manifest's own directory, or an absolute `https:` URL.
67    pub url: String,
68    /// SHA-256 of its bytes, 64 lowercase hexadecimal digits.
69    #[cfg_attr(feature = "schema", schemars(regex(pattern = r"^[0-9a-f]{64}$")))]
70    pub sha256: String,
71    /// Its length in bytes.
72    #[cfg_attr(feature = "schema", schemars(range(max = MAX_PLUGIN_ARTIFACT_BYTES)))]
73    pub bytes: u64,
74}
75
76/// What kind of code an artifact is.
77#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
78#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
79#[serde(rename_all = "snake_case")]
80pub enum ArtifactKind {
81    /// A core wasm module.
82    Wasm,
83    /// A C-ABI dynamic library.
84    Cdylib,
85    /// A static library an app links at build time.
86    Staticlib,
87}
88
89/// A file a plugin reads.
90#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
91#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
92#[serde(deny_unknown_fields)]
93pub struct PluginResource {
94    /// The name the plugin asks for.
95    pub name: String,
96    /// Where it is: a path under the manifest's own directory, or an absolute `https:` URL.
97    pub url: String,
98    /// SHA-256 of its bytes, 64 lowercase hexadecimal digits.
99    #[cfg_attr(feature = "schema", schemars(regex(pattern = r"^[0-9a-f]{64}$")))]
100    pub sha256: String,
101    /// Its length in bytes.
102    #[cfg_attr(feature = "schema", schemars(range(max = MAX_PLUGIN_RESOURCE_BYTES)))]
103    pub bytes: u64,
104}
105
106/// Why a manifest was refused.
107#[derive(Clone, Debug, Eq, PartialEq)]
108#[non_exhaustive]
109pub enum ManifestError {
110    /// The manifest names an ABI this build does not implement.
111    UnsupportedAbi(String),
112    /// The manifest is not one: bad JSON, a missing or malformed field, or a broken rule.
113    Invalid(String),
114}
115
116impl fmt::Display for ManifestError {
117    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
118        match self {
119            Self::UnsupportedAbi(abi) => write!(
120                formatter,
121                "the plugin needs ABI {abi}; this build implements {}",
122                alpha2_plugin_abi::ABI
123            ),
124            Self::Invalid(why) => write!(formatter, "invalid plugin manifest: {why}"),
125        }
126    }
127}
128
129impl std::error::Error for ManifestError {}
130
131impl PluginManifest {
132    /// Reads and checks a manifest.
133    ///
134    /// # Errors
135    /// [`ManifestError::UnsupportedAbi`] for another ABI, checked before the rest so that a
136    /// manifest of a later ABI is reported as such; [`ManifestError::Invalid`] otherwise.
137    pub fn from_json(text: &str) -> Result<Self, ManifestError> {
138        if text.len() > MAX_MANIFEST_BYTES {
139            return Err(ManifestError::Invalid(format!(
140                "longer than {MAX_MANIFEST_BYTES} bytes"
141            )));
142        }
143        let value: serde_json::Value = serde_json::from_str(text)
144            .map_err(|error| ManifestError::Invalid(error.to_string()))?;
145        match value.get("abi").and_then(serde_json::Value::as_str) {
146            Some(abi) if abi != alpha2_plugin_abi::ABI => {
147                return Err(ManifestError::UnsupportedAbi(abi.to_owned()));
148            }
149            _ => {}
150        }
151        let manifest: Self = serde_json::from_value(value)
152            .map_err(|error| ManifestError::Invalid(error.to_string()))?;
153        manifest.validate().map_err(ManifestError::Invalid)?;
154        Ok(manifest)
155    }
156
157    fn validate(&self) -> Result<(), String> {
158        if self.id != self.descriptor.id {
159            return Err(format!(
160                "id {} differs from the descriptor's {}",
161                self.id, self.descriptor.id
162            ));
163        }
164        if !semver(&self.version) {
165            return Err(format!(
166                "version {} is not a semantic version",
167                self.version
168            ));
169        }
170        super::session::validate_descriptor(&self.descriptor).map_err(|error| error.to_string())?;
171        if self.artifacts.is_empty() || self.artifacts.len() > MAX_PLUGIN_ARTIFACTS {
172            return Err(format!("needs 1 to {MAX_PLUGIN_ARTIFACTS} artifacts"));
173        }
174        if self.resources.len() > MAX_PLUGIN_RESOURCES {
175            return Err(format!("lists more than {MAX_PLUGIN_RESOURCES} resources"));
176        }
177        let mut targets = HashSet::new();
178        for artifact in &self.artifacts {
179            if artifact.target.is_empty() || !targets.insert((&artifact.target, artifact.kind)) {
180                return Err(format!(
181                    "artifact target {:?} is empty or listed twice for one type",
182                    artifact.target
183                ));
184            }
185            if (artifact.target == WASM_TARGET) != (artifact.kind == ArtifactKind::Wasm) {
186                return Err(format!(
187                    "artifact {}: only the wasm32 target is a wasm module",
188                    artifact.url
189                ));
190            }
191            check_file(&artifact.url, &artifact.sha256)?;
192            if artifact.bytes > MAX_PLUGIN_ARTIFACT_BYTES {
193                return Err(format!(
194                    "artifact {} is longer than {MAX_PLUGIN_ARTIFACT_BYTES} bytes",
195                    artifact.url
196                ));
197            }
198        }
199        let mut names = HashSet::new();
200        for resource in &self.resources {
201            if resource.name.is_empty() || !names.insert(&resource.name) {
202                return Err(format!(
203                    "resource name {:?} is empty or repeated",
204                    resource.name
205                ));
206            }
207            check_file(&resource.url, &resource.sha256)?;
208            if resource.bytes > MAX_PLUGIN_RESOURCE_BYTES {
209                return Err(format!(
210                    "resource {} is longer than {MAX_PLUGIN_RESOURCE_BYTES} bytes",
211                    resource.name
212                ));
213            }
214        }
215        let total = self.resources.iter().fold(0_u64, |total, resource| {
216            total.saturating_add(resource.bytes)
217        });
218        if total > MAX_PLUGIN_RESOURCES_TOTAL_BYTES {
219            return Err(format!(
220                "the resources are longer than {MAX_PLUGIN_RESOURCES_TOTAL_BYTES} bytes together"
221            ));
222        }
223        Ok(())
224    }
225
226    /// The artifact for `target`, by kind.
227    #[must_use]
228    pub fn artifact(&self, target: &str, kind: ArtifactKind) -> Option<&PluginArtifact> {
229        self.artifacts
230            .iter()
231            .find(|artifact| artifact.target == target && artifact.kind == kind)
232    }
233}
234
235/// The target of a wasm artifact.
236pub const WASM_TARGET: &str = "wasm32";
237
238/// What a manifest's `url` names.
239#[derive(Clone, Copy, Debug, Eq, PartialEq)]
240pub enum Reference<'a> {
241    /// A path under the manifest's own directory, `/`-separated.
242    Relative(&'a str),
243    /// An absolute `https:` URL.
244    Https(&'a str),
245}
246
247/// The scheme of `url`, when it starts with one (RFC 3986).
248fn scheme(url: &str) -> Option<&str> {
249    let (scheme, _) = url.split_once(':')?;
250    let valid = scheme.starts_with(|c: char| c.is_ascii_alphabetic())
251        && scheme
252            .chars()
253            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
254    valid.then_some(scheme)
255}
256
257/// Reads a manifest's `url` as a path under the manifest's directory or an `https:` URL.
258///
259/// # Errors
260/// For any other scheme, an absolute or drive-prefixed path, a backslash or NUL, and a path whose
261/// `..` segments climb above the manifest's directory.
262pub fn reference(url: &str) -> Result<Reference<'_>, String> {
263    let refused = |why: &str| Err(format!("{url}: {why}"));
264    if url.is_empty() {
265        return Err("a URL is empty".to_owned());
266    }
267    match scheme(url) {
268        Some("https") => return Ok(Reference::Https(url)),
269        Some(scheme) if scheme.len() == 1 => {
270            return refused("a drive-prefixed path is not under the manifest");
271        }
272        Some(_) => return refused("only https: URLs and paths under the manifest are allowed"),
273        None => {}
274    }
275    if url.contains(['\\', '\0']) {
276        return refused("a path takes neither backslashes nor NUL");
277    }
278    if url.starts_with('/') {
279        return refused("an absolute path is not under the manifest");
280    }
281    let path = url.split(['?', '#']).next().unwrap_or_default();
282    let mut depth = 0_usize;
283    for segment in path.split('/') {
284        match segment {
285            "" | "." => {}
286            ".." => {
287                depth = depth
288                    .checked_sub(1)
289                    .ok_or_else(|| format!("{url}: the path climbs above the manifest"))?;
290            }
291            _ => depth += 1,
292        }
293    }
294    Ok(Reference::Relative(url))
295}
296
297fn check_file(url: &str, sha256: &str) -> Result<(), String> {
298    reference(url)?;
299    if sha256.len() != 64
300        || !sha256
301            .bytes()
302            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
303    {
304        return Err(format!(
305            "{url}: sha256 is not 64 lowercase hexadecimal digits"
306        ));
307    }
308    Ok(())
309}
310
311/// `MAJOR.MINOR.PATCH` with an optional `-prerelease` and `+build`, as semver 2.0 spells them.
312fn semver(version: &str) -> bool {
313    let (rest, build) = version
314        .split_once('+')
315        .map_or((version, None), |(a, b)| (a, Some(b)));
316    let (core, pre) = rest
317        .split_once('-')
318        .map_or((rest, None), |(a, b)| (a, Some(b)));
319    let identifiers = |text: &str| {
320        text.split('.').all(|part| {
321            !part.is_empty()
322                && part
323                    .bytes()
324                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
325        })
326    };
327    let numbers = core.split('.').collect::<Vec<_>>();
328    numbers.len() == 3
329        && numbers.iter().all(|part| {
330            !part.is_empty()
331                && part.bytes().all(|byte| byte.is_ascii_digit())
332                && (part.len() == 1 || !part.starts_with('0'))
333        })
334        && pre.is_none_or(identifiers)
335        && build.is_none_or(identifiers)
336}
337
338/// The JSON Schema of a plugin manifest.
339#[cfg(feature = "schema")]
340#[must_use]
341pub fn plugin_manifest_json_schema() -> serde_json::Value {
342    let mut schema = schemars::generate::SchemaSettings::draft2020_12()
343        .for_deserialize()
344        .into_generator()
345        .into_root_schema_for::<PluginManifest>();
346    schema.insert(
347        "$id".to_owned(),
348        serde_json::Value::String(PLUGIN_MANIFEST_SCHEMA_ID.to_owned()),
349    );
350    schema.insert(
351        "title".to_owned(),
352        serde_json::Value::String(format!(
353            "alpha2 plugin manifest, ABI {}",
354            alpha2_plugin_abi::ABI
355        )),
356    );
357    let mut value = schema.to_value();
358    alpha2_model::finish_json_schema(&mut value);
359    value
360}
361
362/// Where the plugin manifest schema is published.
363pub const PLUGIN_MANIFEST_SCHEMA_ID: &str = "https://alpha2.sh/schema/plugin-manifest.v1.json";