use std::collections::HashSet;
use std::fmt;
use serde::{Deserialize, Serialize};
use super::Descriptor;
pub const MAX_MANIFEST_BYTES: usize = 1024 * 1024;
pub const MAX_PLUGIN_ARTIFACTS: usize = 64;
pub const MAX_PLUGIN_RESOURCES: usize = 64;
pub const MAX_PLUGIN_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024;
pub const MAX_PLUGIN_RESOURCE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
pub const MAX_PLUGIN_RESOURCES_TOTAL_BYTES: u64 = 4 * 1024 * 1024 * 1024;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct PluginManifest {
pub id: String,
pub version: String,
#[cfg_attr(feature = "schema", schemars(extend("const" = alpha2_plugin_abi::ABI)))]
pub abi: String,
pub kind: PluginKind,
#[cfg_attr(feature = "schema", schemars(length(min = 1)))]
pub artifacts: Vec<PluginArtifact>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<PluginResource>,
pub descriptor: Descriptor,
}
#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum PluginKind {
Extractor,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct PluginArtifact {
pub target: String,
#[serde(rename = "type")]
pub kind: ArtifactKind,
pub url: String,
#[cfg_attr(feature = "schema", schemars(regex(pattern = r"^[0-9a-f]{64}$")))]
pub sha256: String,
#[cfg_attr(feature = "schema", schemars(range(max = MAX_PLUGIN_ARTIFACT_BYTES)))]
pub bytes: u64,
}
#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum ArtifactKind {
Wasm,
Cdylib,
Staticlib,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct PluginResource {
pub name: String,
pub url: String,
#[cfg_attr(feature = "schema", schemars(regex(pattern = r"^[0-9a-f]{64}$")))]
pub sha256: String,
#[cfg_attr(feature = "schema", schemars(range(max = MAX_PLUGIN_RESOURCE_BYTES)))]
pub bytes: u64,
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ManifestError {
UnsupportedAbi(String),
Invalid(String),
}
impl fmt::Display for ManifestError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnsupportedAbi(abi) => write!(
formatter,
"the plugin needs ABI {abi}; this build implements {}",
alpha2_plugin_abi::ABI
),
Self::Invalid(why) => write!(formatter, "invalid plugin manifest: {why}"),
}
}
}
impl std::error::Error for ManifestError {}
impl PluginManifest {
pub fn from_json(text: &str) -> Result<Self, ManifestError> {
if text.len() > MAX_MANIFEST_BYTES {
return Err(ManifestError::Invalid(format!(
"longer than {MAX_MANIFEST_BYTES} bytes"
)));
}
let value: serde_json::Value = serde_json::from_str(text)
.map_err(|error| ManifestError::Invalid(error.to_string()))?;
match value.get("abi").and_then(serde_json::Value::as_str) {
Some(abi) if abi != alpha2_plugin_abi::ABI => {
return Err(ManifestError::UnsupportedAbi(abi.to_owned()));
}
_ => {}
}
let manifest: Self = serde_json::from_value(value)
.map_err(|error| ManifestError::Invalid(error.to_string()))?;
manifest.validate().map_err(ManifestError::Invalid)?;
Ok(manifest)
}
fn validate(&self) -> Result<(), String> {
if self.id != self.descriptor.id {
return Err(format!(
"id {} differs from the descriptor's {}",
self.id, self.descriptor.id
));
}
if !semver(&self.version) {
return Err(format!(
"version {} is not a semantic version",
self.version
));
}
super::session::validate_descriptor(&self.descriptor).map_err(|error| error.to_string())?;
if self.artifacts.is_empty() || self.artifacts.len() > MAX_PLUGIN_ARTIFACTS {
return Err(format!("needs 1 to {MAX_PLUGIN_ARTIFACTS} artifacts"));
}
if self.resources.len() > MAX_PLUGIN_RESOURCES {
return Err(format!("lists more than {MAX_PLUGIN_RESOURCES} resources"));
}
let mut targets = HashSet::new();
for artifact in &self.artifacts {
if artifact.target.is_empty() || !targets.insert((&artifact.target, artifact.kind)) {
return Err(format!(
"artifact target {:?} is empty or listed twice for one type",
artifact.target
));
}
if (artifact.target == WASM_TARGET) != (artifact.kind == ArtifactKind::Wasm) {
return Err(format!(
"artifact {}: only the wasm32 target is a wasm module",
artifact.url
));
}
check_file(&artifact.url, &artifact.sha256)?;
if artifact.bytes > MAX_PLUGIN_ARTIFACT_BYTES {
return Err(format!(
"artifact {} is longer than {MAX_PLUGIN_ARTIFACT_BYTES} bytes",
artifact.url
));
}
}
let mut names = HashSet::new();
for resource in &self.resources {
if resource.name.is_empty() || !names.insert(&resource.name) {
return Err(format!(
"resource name {:?} is empty or repeated",
resource.name
));
}
check_file(&resource.url, &resource.sha256)?;
if resource.bytes > MAX_PLUGIN_RESOURCE_BYTES {
return Err(format!(
"resource {} is longer than {MAX_PLUGIN_RESOURCE_BYTES} bytes",
resource.name
));
}
}
let total = self.resources.iter().fold(0_u64, |total, resource| {
total.saturating_add(resource.bytes)
});
if total > MAX_PLUGIN_RESOURCES_TOTAL_BYTES {
return Err(format!(
"the resources are longer than {MAX_PLUGIN_RESOURCES_TOTAL_BYTES} bytes together"
));
}
Ok(())
}
#[must_use]
pub fn artifact(&self, target: &str, kind: ArtifactKind) -> Option<&PluginArtifact> {
self.artifacts
.iter()
.find(|artifact| artifact.target == target && artifact.kind == kind)
}
}
pub const WASM_TARGET: &str = "wasm32";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Reference<'a> {
Relative(&'a str),
Https(&'a str),
}
fn scheme(url: &str) -> Option<&str> {
let (scheme, _) = url.split_once(':')?;
let valid = scheme.starts_with(|c: char| c.is_ascii_alphabetic())
&& scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
valid.then_some(scheme)
}
pub fn reference(url: &str) -> Result<Reference<'_>, String> {
let refused = |why: &str| Err(format!("{url}: {why}"));
if url.is_empty() {
return Err("a URL is empty".to_owned());
}
match scheme(url) {
Some("https") => return Ok(Reference::Https(url)),
Some(scheme) if scheme.len() == 1 => {
return refused("a drive-prefixed path is not under the manifest");
}
Some(_) => return refused("only https: URLs and paths under the manifest are allowed"),
None => {}
}
if url.contains(['\\', '\0']) {
return refused("a path takes neither backslashes nor NUL");
}
if url.starts_with('/') {
return refused("an absolute path is not under the manifest");
}
let path = url.split(['?', '#']).next().unwrap_or_default();
let mut depth = 0_usize;
for segment in path.split('/') {
match segment {
"" | "." => {}
".." => {
depth = depth
.checked_sub(1)
.ok_or_else(|| format!("{url}: the path climbs above the manifest"))?;
}
_ => depth += 1,
}
}
Ok(Reference::Relative(url))
}
fn check_file(url: &str, sha256: &str) -> Result<(), String> {
reference(url)?;
if sha256.len() != 64
|| !sha256
.bytes()
.all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
{
return Err(format!(
"{url}: sha256 is not 64 lowercase hexadecimal digits"
));
}
Ok(())
}
fn semver(version: &str) -> bool {
let (rest, build) = version
.split_once('+')
.map_or((version, None), |(a, b)| (a, Some(b)));
let (core, pre) = rest
.split_once('-')
.map_or((rest, None), |(a, b)| (a, Some(b)));
let identifiers = |text: &str| {
text.split('.').all(|part| {
!part.is_empty()
&& part
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
})
};
let numbers = core.split('.').collect::<Vec<_>>();
numbers.len() == 3
&& numbers.iter().all(|part| {
!part.is_empty()
&& part.bytes().all(|byte| byte.is_ascii_digit())
&& (part.len() == 1 || !part.starts_with('0'))
})
&& pre.is_none_or(identifiers)
&& build.is_none_or(identifiers)
}
#[cfg(feature = "schema")]
#[must_use]
pub fn plugin_manifest_json_schema() -> serde_json::Value {
let mut schema = schemars::generate::SchemaSettings::draft2020_12()
.for_deserialize()
.into_generator()
.into_root_schema_for::<PluginManifest>();
schema.insert(
"$id".to_owned(),
serde_json::Value::String(PLUGIN_MANIFEST_SCHEMA_ID.to_owned()),
);
schema.insert(
"title".to_owned(),
serde_json::Value::String(format!(
"alpha2 plugin manifest, ABI {}",
alpha2_plugin_abi::ABI
)),
);
let mut value = schema.to_value();
alpha2_model::finish_json_schema(&mut value);
value
}
pub const PLUGIN_MANIFEST_SCHEMA_ID: &str = "https://alpha2.sh/schema/plugin-manifest.v1.json";