Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/plugins.rs

Raw
//! Plugin package manifest parsing (`SMH-SPEC-WASM0001`, identity and
//! installation).
//!
//! This module bounds and validates the manifest's identity, artifact, world,
//! and requested capabilities.

use smith::error::{ProviderFault, Result, SmithError};
use std::io::Read;
use std::path::{Path, PathBuf};

/// Persisted installed package records and development links.
pub mod registry;
/// Deterministic guest fixtures through mocked host capabilities.
pub mod test;
/// Persisted project trust decisions and capability grants.
pub mod trust;

/// Decode the supported provider setting from bounded KDL source.
pub(crate) fn parse_provider_settings(input: &str, source: &Path) -> Result<Option<bool>> {
    let document: kdl::KdlDocument = input.parse().map_err(|error| SmithError::Config {
        field: format!("{}:provider-settings", source.display()),
        message: format!("invalid provider settings KDL: {error:?}"),
    })?;
    let mut include_usage = None;
    for node in document.nodes() {
        let name = node.name().value();
        let field = format!("{}:{name}", source.display());
        if name != "include-usage" {
            return Err(SmithError::Config {
                field,
                message: format!("unknown provider setting {name}"),
            });
        }
        if include_usage.is_some() {
            return Err(SmithError::Config {
                field,
                message: "duplicate provider setting include-usage".into(),
            });
        }
        if node.entries().len() != 1
            || node.entries()[0].name().is_some()
            || node.children().is_some()
        {
            return Err(SmithError::Config {
                field,
                message:
                    "include-usage requires one boolean argument without properties or children"
                        .into(),
            });
        }
        let Some(value) = node.entry(0).and_then(|entry| entry.value().as_bool()) else {
            return Err(SmithError::Config {
                field,
                message: "include-usage requires one boolean argument".into(),
            });
        };
        include_usage = Some(value);
    }
    Ok(include_usage)
}

/// Maximum encoded size of a plugin manifest.
pub const MANIFEST_BYTE_LIMIT: usize = 64 * 1024;

/// A host effect requested by a plugin package.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Capability {
    /// Scoped network HTTP effect.
    NetScope,
    /// Credential exchange effect.
    SecretProxy,
    /// Bounded diagnostic logging effect.
    Log,
    /// Scoped workspace filesystem effects.
    Workspace,
    /// Supervised external process effect.
    Process,
}

/// One explicit HTTP origin granted at trust or install time.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NetScope(String);

impl NetScope {
    /// Parse and canonicalize one HTTP origin.
    ///
    /// HTTPS origins may name production hosts.
    /// HTTP origins are limited to literal loopback for local testing.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault for an unscoped scheme, authority, path, query, or port.
    pub fn parse(origin: &str) -> Result<Self> {
        let (scheme, authority) = origin
            .split_once("://")
            .ok_or_else(|| manifest_fault("net-scope origin requires an HTTP scheme"))?;
        if !matches!(scheme, "https" | "http")
            || authority.is_empty()
            || authority.contains(['/', '?', '#', '@'])
            || authority.bytes().any(|byte| byte.is_ascii_whitespace())
        {
            return Err(manifest_fault(
                "net-scope origin must be HTTPS or literal-loopback HTTP without path, query, fragment, or credentials",
            ));
        }
        let host = authority
            .split_once(':')
            .map_or(authority, |(host, _)| host);
        if scheme == "http" && host != "127.0.0.1" {
            return Err(manifest_fault(
                "net-scope HTTP origin must use literal loopback 127.0.0.1",
            ));
        }
        if let Some((_, port)) = authority.split_once(':')
            && (port.is_empty() || port.parse::<u16>().is_err())
        {
            return Err(manifest_fault("net-scope origin has an invalid port"));
        }
        Ok(Self(origin.to_string()))
    }

    /// Canonical origin text supplied to the host effect boundary.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Capability {
    /// Manifest spelling used in capability diagnostics.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::NetScope => "net-scope",
            Self::SecretProxy => "secret-proxy",
            Self::Log => "log",
            Self::Workspace => "workspace",
            Self::Process => "process",
        }
    }

    pub(crate) fn parse(value: &str) -> Result<Self> {
        match value {
            "net-scope" => Ok(Self::NetScope),
            "secret-proxy" => Ok(Self::SecretProxy),
            "log" => Ok(Self::Log),
            "workspace" => Ok(Self::Workspace),
            "process" => Ok(Self::Process),
            _ => Err(manifest_fault(format!("unknown capability {value}"))),
        }
    }
}

/// A trusted package's manifest and confined component artifact.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PluginPackage {
    root: PathBuf,
    manifest_path: PathBuf,
    manifest: PluginManifest,
    manifest_bytes: Vec<u8>,
    artifact_bytes: Vec<u8>,
}

impl PluginPackage {
    /// Discover a package only after its project trust decision is positive.
    ///
    /// `project_trusted` is supplied by the trust resolver; rejection happens
    /// before resolving or reading any package path.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when trust is absent, package files are invalid,
    /// the manifest exceeds its bound, or its artifact escapes the package.
    pub fn discover(package_root: &Path, project_trusted: bool) -> Result<Self> {
        if !project_trusted {
            return Err(manifest_fault(
                "project plugin is untrusted; trust the project before loading its package",
            ));
        }
        let package_root = std::fs::canonicalize(package_root)
            .map_err(|error| manifest_fault(format!("package discovery failed: {error}")))?;
        let manifest_path =
            std::fs::canonicalize(package_root.join("plugin.kdl")).map_err(|error| {
                manifest_fault(format!("package manifest is missing or invalid: {error}"))
            })?;
        if !manifest_path.starts_with(&package_root) {
            return Err(manifest_fault("manifest escapes the declared package root"));
        }
        let manifest_bytes = read_bounded(&manifest_path, MANIFEST_BYTE_LIMIT, "manifest")?;
        let source = std::str::from_utf8(&manifest_bytes)
            .map_err(|error| manifest_fault(format!("manifest is not UTF-8: {error}")))?;
        let manifest = PluginManifest::parse(source)?;
        let artifact_path =
            std::fs::canonicalize(package_root.join(manifest.artifact())).map_err(|error| {
                manifest_fault(format!("package artifact is missing or invalid: {error}"))
            })?;
        if !artifact_path.starts_with(&package_root) {
            return Err(manifest_fault(
                "package artifact escapes the declared package root",
            ));
        }
        let artifact_bytes =
            read_bounded(&artifact_path, crate::wasm::ARTIFACT_BYTES_MAX, "artifact")?;
        Ok(Self {
            root: package_root,
            manifest_path,
            manifest,
            manifest_bytes,
            artifact_bytes,
        })
    }

    /// Canonical package root containing its manifest and artifact.
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Canonical manifest path confined to the package root.
    #[must_use]
    pub fn manifest_path(&self) -> &Path {
        &self.manifest_path
    }

    /// Validated package manifest.
    #[must_use]
    pub const fn manifest(&self) -> &PluginManifest {
        &self.manifest
    }

    /// Exact manifest bytes parsed during discovery.
    #[must_use]
    pub fn manifest_bytes(&self) -> &[u8] {
        &self.manifest_bytes
    }

    /// Exact component bytes read during discovery.
    #[must_use]
    pub fn artifact_bytes(&self) -> &[u8] {
        &self.artifact_bytes
    }

    pub(crate) fn into_parts(self) -> (PluginManifest, Vec<u8>) {
        (self.manifest, self.artifact_bytes)
    }
}

/// Validated identity and requested effects for one plugin artifact.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PluginManifest {
    id: String,
    version: String,
    world_version: String,
    artifact: String,
    capabilities: Vec<Capability>,
    source: Option<String>,
}

impl PluginManifest {
    /// Parse one KDL manifest.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when input exceeds [`MANIFEST_BYTE_LIMIT`], KDL
    /// or field syntax is invalid, required data is absent or empty, fields are
    /// repeated, or a requested capability is unknown or repeated.
    pub fn parse(input: &str) -> Result<Self> {
        if input.len() > MANIFEST_BYTE_LIMIT {
            return Err(manifest_fault(format!(
                "manifest exceeds byte limit of {MANIFEST_BYTE_LIMIT}"
            )));
        }
        let document: kdl::KdlDocument = input
            .parse()
            .map_err(|error| manifest_fault(format!("invalid manifest: {error}")))?;
        let mut id = None;
        let mut version = None;
        let mut world_version = None;
        let mut artifact = None;
        let mut capabilities = Vec::new();
        let mut source = None;

        for node in document.nodes() {
            let name = node.name().value();
            match name {
                "id" => set_once(&mut id, node_string(node, name)?, name)?,
                "version" => set_once(&mut version, node_string(node, name)?, name)?,
                "world" => set_once(&mut world_version, node_string(node, name)?, name)?,
                "artifact" => set_once(&mut artifact, node_string(node, name)?, name)?,
                "capability" => {
                    let value = node_string(node, name)?;
                    let capability = Capability::parse(&value)?;
                    if capabilities.contains(&capability) {
                        return Err(manifest_fault(format!("duplicate capability {value}")));
                    }
                    capabilities.push(capability);
                }
                "source" => set_once(&mut source, node_string(node, name)?, name)?,
                _ => return Err(manifest_fault(format!("unknown manifest field {name}"))),
            }
        }

        Ok(Self {
            id: required(id, "id")?,
            version: required(version, "version")?,
            world_version: required(world_version, "world")?,
            artifact: required(artifact, "artifact")?,
            capabilities,
            source,
        })
    }

    /// Plugin identity, namespaced by publisher.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Plugin package version.
    #[must_use]
    pub fn version(&self) -> &str {
        &self.version
    }

    /// Declared Smith plugin world version.
    #[must_use]
    pub fn world_version(&self) -> &str {
        &self.world_version
    }

    /// Relative component artifact path.
    #[must_use]
    pub fn artifact(&self) -> &str {
        &self.artifact
    }

    /// Requested host capabilities in manifest order.
    #[must_use]
    pub fn capabilities(&self) -> &[Capability] {
        &self.capabilities
    }

    /// Optional source provenance.
    #[must_use]
    pub fn source(&self) -> Option<&str> {
        self.source.as_deref()
    }
}

fn canonical_grants(grants: &[Capability]) -> Vec<Capability> {
    [
        Capability::NetScope,
        Capability::SecretProxy,
        Capability::Log,
        Capability::Workspace,
        Capability::Process,
    ]
    .into_iter()
    .filter(|capability| grants.contains(capability))
    .collect()
}

fn canonical_net_scopes(scopes: &[NetScope]) -> Vec<NetScope> {
    let mut scopes = scopes.to_vec();
    scopes.sort_by(|left, right| left.as_str().cmp(right.as_str()));
    scopes.dedup_by(|left, right| left.as_str() == right.as_str());
    scopes
}

pub(crate) fn read_bounded(path: &Path, bytes_max: usize, kind: &str) -> Result<Vec<u8>> {
    let metadata = std::fs::metadata(path)
        .map_err(|error| manifest_fault(format!("{kind} read failed: {error}")))?;
    if metadata.len() > bytes_max as u64 {
        return Err(manifest_fault(format!(
            "{kind} exceeds byte limit of {bytes_max}"
        )));
    }
    let capacity = usize::try_from(metadata.len())
        .map_err(|_| manifest_fault(format!("{kind} exceeds addressable memory")))?;
    let mut bytes = Vec::new();
    bytes
        .try_reserve_exact(capacity)
        .map_err(|_| manifest_fault(format!("{kind} allocation failed")))?;
    let file = std::fs::File::open(path)
        .map_err(|error| manifest_fault(format!("{kind} read failed: {error}")))?;
    #[expect(
        clippy::disallowed_methods,
        reason = "Take caps package snapshot reads"
    )]
    file.take((bytes_max + 1) as u64)
        .read_to_end(&mut bytes)
        .map_err(|error| manifest_fault(format!("{kind} read failed: {error}")))?;
    if bytes.len() > bytes_max {
        return Err(manifest_fault(format!(
            "{kind} exceeds byte limit of {bytes_max}"
        )));
    }
    Ok(bytes)
}

fn node_string(node: &kdl::KdlNode, name: &str) -> Result<String> {
    if node.entries().len() != 1 || node.entries()[0].name().is_some() || node.children().is_some()
    {
        return Err(manifest_fault(format!(
            "manifest field {name} accepts one string value without properties or children"
        )));
    }
    let Some(value) = node.entry(0).and_then(|entry| entry.value().as_string()) else {
        return Err(manifest_fault(format!(
            "manifest field {name} requires one string value"
        )));
    };
    Ok(value.to_string())
}

fn set_once(slot: &mut Option<String>, value: String, name: &str) -> Result<()> {
    if slot.replace(value).is_some() {
        return Err(manifest_fault(format!("duplicate manifest field {name}")));
    }
    Ok(())
}

fn required(value: Option<String>, name: &str) -> Result<String> {
    let value = value.ok_or_else(|| manifest_fault(format!("missing manifest field {name}")))?;
    if value.is_empty() {
        return Err(manifest_fault(format!(
            "manifest field {name} must not be empty"
        )));
    }
    Ok(value)
}

pub(crate) fn native_path_identity(path: &Path) -> String {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        format!("unix:{}", hex(path.as_os_str().as_bytes()))
    }
    #[cfg(windows)]
    {
        use std::os::windows::ffi::OsStrExt;
        let mut bytes = Vec::new();
        for unit in path.as_os_str().encode_wide() {
            bytes.extend_from_slice(&unit.to_le_bytes());
        }
        format!("windows:{}", hex(&bytes))
    }
    #[cfg(not(any(unix, windows)))]
    {
        format!("other:{}", hex(path.to_string_lossy().as_bytes()))
    }
}

pub(crate) fn native_path_from_identity(identity: &str) -> Result<PathBuf> {
    let (platform, encoded) = identity
        .split_once(':')
        .ok_or_else(|| manifest_fault("invalid native path identity"))?;
    let bytes = unhex(encoded)?;
    #[cfg(unix)]
    if platform == "unix" {
        use std::os::unix::ffi::OsStringExt;
        return Ok(PathBuf::from(std::ffi::OsString::from_vec(bytes)));
    }
    #[cfg(windows)]
    if platform == "windows" {
        use std::os::windows::ffi::OsStringExt;
        let (pairs, remainder) = bytes.as_chunks::<2>();
        if !remainder.is_empty() {
            return Err(manifest_fault("invalid Windows native path identity"));
        }
        let units = pairs
            .iter()
            .map(|pair| u16::from_le_bytes(*pair))
            .collect::<Vec<_>>();
        return Ok(PathBuf::from(std::ffi::OsString::from_wide(&units)));
    }
    Err(manifest_fault(format!(
        "native path identity platform {platform} is unsupported"
    )))
}

fn hex(bytes: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut text = String::with_capacity(bytes.len().saturating_mul(2));
    for byte in bytes {
        text.push(char::from(DIGITS[usize::from(byte >> 4)]));
        text.push(char::from(DIGITS[usize::from(byte & 15)]));
    }
    text
}

fn unhex(text: &str) -> Result<Vec<u8>> {
    if !text.len().is_multiple_of(2) {
        return Err(manifest_fault("invalid native path identity"));
    }
    let (pairs, remainder) = text.as_bytes().as_chunks::<2>();
    assert!(remainder.is_empty(), "even-length input has no remainder");
    pairs
        .iter()
        .map(|pair| {
            let high = char::from(pair[0])
                .to_digit(16)
                .ok_or_else(|| manifest_fault("invalid native path identity"))?;
            let low = char::from(pair[1])
                .to_digit(16)
                .ok_or_else(|| manifest_fault("invalid native path identity"))?;
            u8::try_from((high << 4) | low)
                .map_err(|_| manifest_fault("invalid native path identity"))
        })
        .collect()
}

fn manifest_fault(message: impl Into<String>) -> SmithError {
    SmithError::Provider {
        fault: ProviderFault::Plugin {
            message: message.into(),
        },
    }
}

#[cfg(test)]
mod tests {
    //! Trust-time authority parsing (`SMH-SPEC-PLUG0001`).

    use super::NetScope;

    #[test]
    fn net_scope_accepts_explicit_production_or_loopback_origins_only() {
        assert_eq!(
            NetScope::parse("https://api.example.test:8443")
                .unwrap()
                .as_str(),
            "https://api.example.test:8443"
        );
        assert!(NetScope::parse("http://127.0.0.1:8080").is_ok());
        for origin in [
            "http://example.test",
            "https://api.example.test/path",
            "https://user@api.example.test",
            "https://api.example.test?token=secret",
            "https://api.example.test:bad",
        ] {
            assert!(NetScope::parse(origin).is_err(), "accepted {origin}");
        }
    }
}