1use std::collections::HashSet;
4use std::fmt;
5
6use serde::{Deserialize, Serialize};
7
8use super::Descriptor;
9
10pub const MAX_MANIFEST_BYTES: usize = 1024 * 1024;
12pub const MAX_PLUGIN_ARTIFACTS: usize = 64;
14pub const MAX_PLUGIN_RESOURCES: usize = 64;
16pub const MAX_PLUGIN_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024;
18pub const MAX_PLUGIN_RESOURCE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
20pub const MAX_PLUGIN_RESOURCES_TOTAL_BYTES: u64 = 4 * 1024 * 1024 * 1024;
22
23#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
25#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
26#[serde(deny_unknown_fields)]
27pub struct PluginManifest {
28 pub id: String,
30 pub version: String,
32 #[cfg_attr(feature = "schema", schemars(extend("const" = alpha2_plugin_abi::ABI)))]
34 pub abi: String,
35 pub kind: PluginKind,
37 #[cfg_attr(feature = "schema", schemars(length(min = 1)))]
39 pub artifacts: Vec<PluginArtifact>,
40 #[serde(default, skip_serializing_if = "Vec::is_empty")]
42 pub resources: Vec<PluginResource>,
43 pub descriptor: Descriptor,
45}
46
47#[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 Extractor,
54}
55
56#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
58#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
59#[serde(deny_unknown_fields)]
60pub struct PluginArtifact {
61 pub target: String,
63 #[serde(rename = "type")]
65 pub kind: ArtifactKind,
66 pub url: String,
68 #[cfg_attr(feature = "schema", schemars(regex(pattern = r"^[0-9a-f]{64}$")))]
70 pub sha256: String,
71 #[cfg_attr(feature = "schema", schemars(range(max = MAX_PLUGIN_ARTIFACT_BYTES)))]
73 pub bytes: u64,
74}
75
76#[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 Wasm,
83 Cdylib,
85 Staticlib,
87}
88
89#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
91#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
92#[serde(deny_unknown_fields)]
93pub struct PluginResource {
94 pub name: String,
96 pub url: String,
98 #[cfg_attr(feature = "schema", schemars(regex(pattern = r"^[0-9a-f]{64}$")))]
100 pub sha256: String,
101 #[cfg_attr(feature = "schema", schemars(range(max = MAX_PLUGIN_RESOURCE_BYTES)))]
103 pub bytes: u64,
104}
105
106#[derive(Clone, Debug, Eq, PartialEq)]
108#[non_exhaustive]
109pub enum ManifestError {
110 UnsupportedAbi(String),
112 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 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 #[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
235pub const WASM_TARGET: &str = "wasm32";
237
238#[derive(Clone, Copy, Debug, Eq, PartialEq)]
240pub enum Reference<'a> {
241 Relative(&'a str),
243 Https(&'a str),
245}
246
247fn 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
257pub 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
311fn 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#[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
362pub const PLUGIN_MANIFEST_SCHEMA_ID: &str = "https://alpha2.sh/schema/plugin-manifest.v1.json";