refactor: extract neutral host contract and decouple plugin ABI (issue #13)
ci/woodpecker/pr/main Pipeline was successful
ci/woodpecker/push/main Pipeline was canceled

Implements the core M0-M3 boundary work from issue #13 / ADR-0071 without
changing language semantics or any public protocol:

- add marqdo-host-contract owning Host/HostOp/ExecutionContext/ResourceRead
  and the runtime observation facts; the engine depends on it only.
- marqdo-runtime no longer links marqdo-host; the native host implements the
  contract and has no reverse edge to runtime/frontend/IR.
- reduce marqdo-plugin-abi to the public C ABI/wire/error contract; move
  manifest/artifact/loader/worker execution into marqdo-host::plugin so the
  SDK carries no loader/worker/host dependency.
- add a real independent consumer (tests/embedding, own workspace+lock) that
  runs Markdown -> frontend -> IR -> runtime with bounded budgets and explicit
  effect refusal, plus differential CLI comparison.
- add an SDK-only third-party plugin fixture and real CLI invocation gate.
- replace the frozen-crate architecture test with a reviewed responsibility
  graph enforced from Cargo metadata, with negative unit cases.
- consolidate current docs/entry: ADR-0071, CURRENT responsibility map,
  developers/architecture indexes, historical banners, STATUS and evidence.
- record keep-in-workspace for Engine/Native Host; no empty candidate repo.

Evidence: docs/evidence/2026-11-26-issue-13-engine-host-boundary.md
Refs #13
This commit is contained in:
cflmy committed 2026-11-26 18:37:02 +08:00
1 parent 4bbefc9244
commit 9b4f0a0822
89 files changed
+3490 -545

No files matched your search

+269
View File
@@ -0,0 +1,269 @@
//! Artifact target triples and content-hash verification.
//!
//! Native plugin artifacts are target-specific: the C ABI layout depends on
//! pointer width and endianness, so the host only loads an artifact built for
//! exactly its own target triple. Installed/verified does not mean trusted or
//! authorized; see the header's "A C ABI IS NOT A SANDBOX" section.
use std::fs;
use std::io::Read;
use std::path::Path;
use sha2::{Digest, Sha256};
use marqdo_plugin_abi::PluginError;
/// Length of a lowercase hexadecimal sha256 digest.
pub const SHA256_HEX_LEN: usize = 64;
/// Compute the lowercase hexadecimal sha256 digest of `bytes`.
pub fn sha256_bytes(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
hex::encode(hasher.finalize())
}
/// Compute the lowercase hexadecimal sha256 digest of a file.
pub fn sha256_file(path: &Path) -> Result<String, PluginError> {
if !path.is_file() {
return Err(PluginError::artifact(
"missing_artifact",
format!("artifact file `{}` does not exist", path.display()),
));
}
let mut file = fs::File::open(path).map_err(|error| {
PluginError::artifact(
"artifact_unreadable",
format!("artifact file `{}` could not be opened", path.display()),
)
.with_detail(error.to_string())
})?;
let mut hasher = Sha256::new();
let mut buffer = [0u8; 64 * 1024];
loop {
let read = file.read(&mut buffer).map_err(|error| {
PluginError::artifact(
"artifact_unreadable",
format!("artifact file `{}` could not be read", path.display()),
)
.with_detail(error.to_string())
})?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
Ok(hex::encode(hasher.finalize()))
}
/// Validate that `digest` looks like a sha256 hex digest.
pub fn is_valid_sha256_hex(digest: &str) -> bool {
digest.len() == SHA256_HEX_LEN && digest.bytes().all(|byte| byte.is_ascii_hexdigit())
}
/// Verify a file's sha256 digest against `expected` (case-insensitive hex).
/// Manifests conventionally use lowercase hex.
///
/// A missing file yields `missing_artifact`; a digest mismatch yields
/// `hash_mismatch`. Verification is content-only: it proves the artifact is
/// the one described by the manifest, not that the plugin is trustworthy.
pub fn verify_sha256_file(path: &Path, expected: &str) -> Result<(), PluginError> {
if !is_valid_sha256_hex(expected) {
return Err(PluginError::artifact(
"invalid_sha256",
"manifest sha256 must be a 64-character hexadecimal digest",
));
}
let actual = sha256_file(path)?;
if !actual.eq_ignore_ascii_case(expected) {
return Err(PluginError::artifact(
"hash_mismatch",
format!(
"artifact `{}` content hash does not match the manifest",
path.display()
),
)
.with_detail(format!("expected {expected}, actual {actual}")));
}
Ok(())
}
/// A parsed target triple such as `x86_64-unknown-linux-gnu`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TargetTriple {
triple: String,
}
impl TargetTriple {
/// Parse and validate a target triple.
pub fn parse(triple: &str) -> Result<Self, PluginError> {
let parts: Vec<&str> = triple.split('-').collect();
if parts.len() < 3 || parts.len() > 4 {
return Err(PluginError::artifact(
"invalid_target_triple",
format!("`{triple}` is not a target triple"),
));
}
if parts.iter().any(|part| {
part.is_empty()
|| !part
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
}) {
return Err(PluginError::artifact(
"invalid_target_triple",
format!("`{triple}` contains an invalid target component"),
));
}
Ok(Self {
triple: triple.to_ascii_lowercase(),
})
}
/// The canonical triple string.
pub fn as_str(&self) -> &str {
&self.triple
}
/// The architecture component (`x86_64`, `aarch64`, ...).
pub fn arch(&self) -> &str {
self.triple.split('-').next().unwrap_or_default()
}
/// Pointer width in bytes implied by the architecture, if known.
pub fn word_size(&self) -> Option<u32> {
match self.arch() {
"x86_64" | "aarch64" | "arm64" | "powerpc64" | "powerpc64le" | "s390x" | "riscv64"
| "loongarch64" | "mips64" | "mips64el" | "sparc64" => Some(8),
"i386" | "i486" | "i586" | "i686" | "arm" | "armv5te" | "armv7" | "armv7a"
| "wasm32" | "mips" | "mipsel" | "riscv32" | "powerpc" | "sparc" => Some(4),
_ => None,
}
}
}
impl std::fmt::Display for TargetTriple {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.triple)
}
}
/// The host's own build target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostTarget {
triple: TargetTriple,
}
impl HostTarget {
/// Construct from an explicit triple (used by tests and cross-checking).
pub fn from_triple(triple: TargetTriple) -> Self {
Self { triple }
}
/// The target this process was compiled for.
pub fn current() -> Self {
Self {
triple: current_target_triple(),
}
}
/// The host target triple.
pub fn triple(&self) -> &TargetTriple {
&self.triple
}
/// The host pointer width in bytes.
pub fn word_size(&self) -> u32 {
usize::BITS / 8
}
}
/// Compute this process's target triple in the conventional 3/4-component
/// form used by Rust target triples.
pub fn current_target_triple() -> TargetTriple {
let arch = std::env::consts::ARCH;
let os = std::env::consts::OS;
let triple = match os {
"linux" => {
let environment = if cfg!(target_env = "musl") {
"musl"
} else if cfg!(target_env = "ohos") {
"ohos"
} else {
"gnu"
};
format!("{arch}-unknown-linux-{environment}")
}
"macos" => format!("{arch}-apple-darwin"),
"ios" => format!("{arch}-apple-ios"),
"windows" => format!("{arch}-pc-windows-msvc"),
"freebsd" => format!("{arch}-unknown-freebsd"),
"netbsd" => format!("{arch}-unknown-netbsd"),
"openbsd" => format!("{arch}-unknown-openbsd"),
"android" => format!("{arch}-linux-android"),
"wasi" => format!("{arch}-wasi-wasm"),
other => format!("{arch}-unknown-{other}"),
};
// The mapping above always yields a parseable triple.
TargetTriple::parse(&triple).unwrap_or_else(|_| TargetTriple {
triple: triple.to_ascii_lowercase(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sha256_matches_known_vector() {
assert_eq!(
sha256_bytes(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
sha256_bytes(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn hex_validation_is_strict() {
assert!(is_valid_sha256_hex(&"a".repeat(64)));
assert!(!is_valid_sha256_hex(&"a".repeat(63)));
assert!(!is_valid_sha256_hex(&"g".repeat(64)));
}
#[test]
fn target_triple_parsing_and_word_size() {
let triple = TargetTriple::parse("x86_64-unknown-linux-gnu").expect("valid");
assert_eq!(triple.arch(), "x86_64");
assert_eq!(triple.word_size(), Some(8));
assert_eq!(
TargetTriple::parse("aarch64-apple-darwin")
.expect("valid")
.word_size(),
Some(8)
);
assert_eq!(
TargetTriple::parse("i686-unknown-linux-gnu")
.expect("valid")
.word_size(),
Some(4)
);
// Syntactically valid but unknown architecture: word size unknown.
assert_eq!(
TargetTriple::parse("not-a-triple")
.expect("syntactic triple")
.word_size(),
None
);
assert!(TargetTriple::parse("x86_64").is_err());
assert!(TargetTriple::parse("x86_64--linux-gnu").is_err());
}
#[test]
fn host_triple_is_parseable_and_matches_word_size() {
let target = HostTarget::current();
assert_eq!(target.triple().word_size(), Some(target.word_size()));
}
}
+710
View File
@@ -0,0 +1,710 @@
//! Native dynamic-library loader and minimal invocation bridge.
//!
//! Lifecycle implemented here (blueprint section 10.5):
//! `validate manifest -> resolve artifact -> verify hash -> negotiate ABI ->
//! register exports -> load library -> verify metadata/exports -> invoke`.
//!
//! Capability *authorization* happens in the host layer before/around
//! [`LoadedPlugin::open`]; this module only exposes the `request_capability`
//! bridge so an already-authorized capability can be consumed.
use std::collections::BTreeMap;
use std::ffi::c_void;
use std::path::Path;
use std::ptr;
use libloading::{Library, Symbol};
use serde::Deserialize;
use super::artifact::HostTarget;
use super::manifest::{PluginKind, PluginManifest};
use marqdo_plugin_abi::abi::{
check_host_api, negotiate, result, AbiVersion, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes,
MqPluginApi, MqPluginEntryV1, MqPluginInvoke, PluginMetadata, ABI_MAJOR, ABI_MINOR,
ENTRY_SYMBOL, MAX_CAPABILITY_REPLY_BYTES, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES,
MAX_RESULT_WIRE_BYTES, MAX_SIGNATURE_WIRE_BYTES,
};
use marqdo_plugin_abi::wire::{WireRequest, WireResponse};
use marqdo_plugin_abi::PluginError;
/// A callback the host installs to answer capability requests from a plugin.
///
/// The handler is invoked on the host invocation thread, one call at a time.
/// It must consult the host's authorization layer and must not perform
/// effects that the loaded plugin was not granted.
pub type CapabilityHandler = Box<dyn FnMut(&str, &[u8]) -> Result<Vec<u8>, PluginError> + 'static>;
/// Options for loading a native plugin.
pub struct LoadOptions {
/// Host target used to select the manifest artifact.
pub host_target: HostTarget,
/// Optional capability bridge; without one every request is denied.
pub capability_handler: Option<CapabilityHandler>,
}
impl Default for LoadOptions {
fn default() -> Self {
Self {
host_target: HostTarget::current(),
capability_handler: None,
}
}
}
impl std::fmt::Debug for LoadOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LoadOptions")
.field("host_target", &self.host_target)
.field(
"capability_handler",
&self.capability_handler.as_ref().map(|_| "<handler>"),
)
.finish()
}
}
/// One export registered by a loaded plugin.
#[derive(Debug, Clone)]
pub struct RegisteredExport {
/// Fully qualified export name.
pub name: String,
/// Signature string reported through `signature_wire`.
pub signature: String,
invoke: MqPluginInvoke,
}
impl RegisteredExport {
/// The registered export name.
pub fn name(&self) -> &str {
&self.name
}
/// The registered signature string.
pub fn signature(&self) -> &str {
&self.signature
}
}
/// Host state shared with the loaded plugin through `MqHostApi::host_data`
/// and each invocation's `MqCallContext`.
struct HostState {
registrations: Vec<RegisteredExport>,
capability_handler: Option<CapabilityHandler>,
}
/// A loaded, validated native plugin instance.
///
/// # Threading and unloading
///
/// A [`LoadedPlugin`] is single-threaded: every invocation must happen on the
/// thread that loaded it, one at a time. Dropping it unloads the native
/// library, so it must only be dropped after all calls have returned (the
/// `&mut self` receiver of [`LoadedPlugin::invoke`] enforces this within Rust).
/// ABI v1 has no hot-reload and no shutdown callback; dropping is a shutdown
/// operation, not a reload mechanism.
///
/// Because ABI v1 plugins may keep the host table in a process-global (the
/// single-threaded contract), do not load the same artifact path twice in one
/// process; use one instance per artifact instead.
pub struct LoadedPlugin {
/// Keeps the dynamic library mapped for as long as the plugin is alive.
_library: Library,
host_state: Box<HostState>,
/// Heap-allocated so the pointer handed to the plugin at entry time stays
/// valid for the plugin lifetime (the plugin may retain it, see header).
host_api: Box<MqHostApi>,
exports: BTreeMap<String, RegisteredExport>,
metadata: PluginMetadata,
abi: AbiVersion,
}
impl std::fmt::Debug for LoadedPlugin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LoadedPlugin")
.field("name", &self.metadata.name)
.field("version", &self.metadata.version)
.field("abi", &self.abi)
.field("exports", &self.exports.keys().collect::<Vec<_>>())
.finish()
}
}
/// Signature wire decoded from `MqHostApi::register_function`.
#[derive(Deserialize)]
struct SignatureWire {
signature: String,
}
impl LoadedPlugin {
/// Validate a manifest and load the matching native artifact from
/// `base_dir` (the directory containing `plugin.yaml`).
///
/// This runs the full local lifecycle: manifest validation, artifact
/// resolution/hash verification, dynamic library loading, ABI
/// negotiation, export registration and metadata cross-checking.
pub fn open(manifest: &PluginManifest, base_dir: &Path) -> Result<Self, PluginError> {
Self::open_with(manifest, base_dir, LoadOptions::default())
}
/// Like [`LoadedPlugin::open`] with explicit target and capability bridge.
pub fn open_with(
manifest: &PluginManifest,
base_dir: &Path,
options: LoadOptions,
) -> Result<Self, PluginError> {
manifest.validate()?;
if manifest.plugin.kind != PluginKind::Native {
return Err(PluginError::unsupported(
"plugin_kind_not_loadable_in_process",
format!(
"plugin kind `{}` cannot be loaded natively; use the isolated worker path",
manifest.plugin.kind.as_str()
),
));
}
let (path, _artifact) = manifest.verify_artifact(base_dir, &options.host_target)?;
// SAFETY: `Library::new` runs the platform loader against a path whose
// content hash was just verified. Loading native code is a trust
// decision made by the caller, not a sandbox.
let library = unsafe { Library::new(&path) }.map_err(|error| {
PluginError::load(
"library_load_failed",
format!("dynamic library `{}` could not be loaded", path.display()),
)
.with_detail(error.to_string())
})?;
let mut plugin_api = MqPluginApi::host_initialized();
let mut host_state = Box::new(HostState {
registrations: Vec::new(),
capability_handler: options.capability_handler,
});
let host_api = Box::new(MqHostApi {
struct_size: size_of::<MqHostApi>() as u32,
abi_major: ABI_MAJOR,
abi_minor: ABI_MINOR,
// The HostState Box is heap-allocated, so this pointer survives
// moves of the LoadedPlugin value.
host_data: (&mut *host_state) as *mut HostState as *mut c_void,
alloc: host_alloc,
free: host_free,
register_function: host_register_function,
request_capability: host_request_capability,
});
let entry_code = {
// SAFETY: symbol lookup in a library we just loaded; the symbol
// type is the documented ABI v1 entry signature.
let entry: Symbol<MqPluginEntryV1> =
unsafe { library.get(ENTRY_SYMBOL) }.map_err(|error| {
PluginError::load(
"missing_entry_symbol",
"plugin does not export `mq_plugin_entry_v1`",
)
.with_detail(error.to_string())
})?;
// SAFETY: entry point contract: one call, same thread, host table
// and plugin table valid for the duration of the call.
unsafe { entry(&*host_api as *const MqHostApi, &mut plugin_api) }
};
if entry_code != result::OK {
return Err(entry_failure(entry_code));
}
let required_size = size_of::<MqPluginApi>() as u32;
if plugin_api.struct_size < required_size {
return Err(PluginError::abi(
"plugin_api_struct_size_too_small",
format!(
"plugin reported MqPluginApi struct_size {}, host requires at least {required_size}",
plugin_api.struct_size
),
));
}
let abi = negotiate(plugin_api.abi_major, plugin_api.abi_minor)?;
// SAFETY: plugin-owned metadata is documented as valid for the entry
// call only; we copy it here, immediately after the call.
let metadata_bytes = unsafe { plugin_api.plugin_metadata_wire.as_slice() }
.map_err(|error| {
PluginError::wire(
"metadata_invalid",
"plugin metadata buffer violates the pointer/length contract",
)
.with_detail(error.to_string())
})?
.to_vec();
let metadata = PluginMetadata::from_wire(&metadata_bytes)?;
if metadata.name != manifest.plugin.name {
return Err(PluginError::manifest(
"metadata_name_mismatch",
format!(
"plugin reports name `{}` but manifest declares `{}`",
metadata.name, manifest.plugin.name
),
));
}
let package_version = manifest.package_version()?;
if metadata.version != package_version.raw {
return Err(PluginError::manifest(
"metadata_version_mismatch",
format!(
"plugin reports version `{}` but manifest declares `{}`",
metadata.version, package_version.raw
),
));
}
let registrations = std::mem::take(&mut host_state.registrations);
let exports = cross_check_exports(manifest, registrations)?;
Ok(Self {
_library: library,
host_state,
host_api,
exports,
metadata,
abi,
})
}
/// Negotiated ABI version.
pub fn abi_version(&self) -> AbiVersion {
self.abi
}
/// Plugin metadata reported by the plugin and cross-checked with the
/// manifest name/version.
pub fn metadata(&self) -> &PluginMetadata {
&self.metadata
}
/// Registered exports in name order.
pub fn exports(&self) -> impl Iterator<Item = &RegisteredExport> {
self.exports.values()
}
/// Invoke `request.function` with the request envelope.
///
/// The plugin must return exactly one wire response envelope. Plugin-side
/// failures are surfaced as structured [`PluginError`]s.
pub fn invoke(&mut self, request: &WireRequest) -> Result<WireResponse, PluginError> {
request.validate()?;
let args_wire = request.to_json_bytes()?;
let response_wire = self.invoke_raw(&request.function, &args_wire)?;
WireResponse::from_json_bytes(&response_wire)?.into_result()
}
/// Raw invocation bridge: call `function` with already-encoded request
/// bytes and return the raw response bytes on success.
///
/// This is primarily for ABI conformance tests; prefer
/// [`LoadedPlugin::invoke`] for normal use.
pub fn invoke_raw(&mut self, function: &str, args_wire: &[u8]) -> Result<Vec<u8>, PluginError> {
if args_wire.len() > marqdo_plugin_abi::abi::MAX_REQUEST_WIRE_BYTES {
return Err(PluginError::wire(
"request_too_large",
format!(
"request wire is {} bytes, limit is {}",
args_wire.len(),
marqdo_plugin_abi::abi::MAX_REQUEST_WIRE_BYTES
),
));
}
let invoke = self
.exports
.get(function)
.map(|export| export.invoke)
.ok_or_else(|| {
PluginError::invoke(
"unknown_export",
format!("plugin does not export `{function}`"),
)
})?;
let mut context =
MqCallContext::new((&mut *self.host_state) as *mut HostState as *mut c_void);
let mut result_wire = MqOwnedBytes::EMPTY;
let mut error_wire = MqOwnedBytes::EMPTY;
// SAFETY: invoking the plugin callback with valid buffers for the
// duration of the call; the plugin owns output allocation via the
// host allocator, which we free below after copying.
let code = unsafe {
invoke(
&mut context as *mut MqCallContext,
MqBytes::from_slice(args_wire),
&mut result_wire,
&mut error_wire,
)
};
let host_api: &MqHostApi = &self.host_api;
// SAFETY: result/error buffers are the plugin's outputs; copy and
// release them exactly once.
let (result_bytes, error_bytes) = unsafe {
(
take_host_buffer(host_api, &mut result_wire, MAX_RESULT_WIRE_BYTES, "result")?,
take_host_buffer(host_api, &mut error_wire, MAX_ERROR_WIRE_BYTES, "error")?,
)
};
if code != result::OK {
if error_bytes.is_empty() {
return Err(PluginError::invoke(
"plugin_call_failed",
format!(
"plugin returned result code {} without an error envelope",
result::name(code)
),
));
}
return match WireResponse::from_error_json_bytes(&error_bytes) {
Ok(response) => match response.into_result() {
Err(error) => Err(error),
Ok(_) => Err(PluginError::invoke(
"plugin_call_failed",
"plugin returned a success envelope with a failure code",
)),
},
Err(error) => Err(PluginError::invoke(
"plugin_call_failed",
format!(
"plugin returned result code {} with an invalid error envelope",
result::name(code)
),
)
.with_detail(error.to_string())),
};
}
if !error_bytes.is_empty() {
return Err(PluginError::invoke(
"unexpected_error_buffer",
"plugin returned success but filled error_wire",
));
}
if result_bytes.is_empty() {
return Err(PluginError::invoke(
"missing_result_buffer",
"plugin returned success but did not fill result_wire",
));
}
Ok(result_bytes)
}
}
fn entry_failure(code: i32) -> PluginError {
if code == result::ABI_MISMATCH {
PluginError::abi(
"plugin_rejected_host_abi",
"plugin rejected the host ABI table during the entry call",
)
.with_detail(format!("plugin returned `{}`", result::name(code)))
} else {
PluginError::load(
"entry_point_failed",
"plugin entry point returned a failure code",
)
.with_detail(format!(
"returned `{}` ({code}); {}",
result::name(code),
if code == result::REGISTRATION {
"an export could not be registered"
} else {
"see the plugin SDK for result-code semantics"
}
))
}
}
fn cross_check_exports(
manifest: &PluginManifest,
registrations: Vec<RegisteredExport>,
) -> Result<BTreeMap<String, RegisteredExport>, PluginError> {
let mut registered: BTreeMap<String, RegisteredExport> = BTreeMap::new();
for export in registrations {
if registered.insert(export.name.clone(), export).is_some() {
return Err(PluginError::load(
"duplicate_registered_export",
"plugin registered the same export more than once",
));
}
}
let declared: BTreeMap<&str, &str> = manifest
.plugin
.exports
.iter()
.map(|export| (export.name.as_str(), export.signature.as_str()))
.collect();
for (name, signature) in &declared {
let Some(registered_export) = registered.get(*name) else {
return Err(PluginError::load(
"export_not_registered",
format!("plugin did not register declared export `{name}`"),
));
};
if registered_export.signature.trim() != signature.trim() {
return Err(PluginError::load(
"export_signature_mismatch",
format!("export `{name}` signature differs between manifest and registration"),
)
.with_detail(format!(
"manifest `{signature}`, registered `{}`",
registered_export.signature
)));
}
}
for name in registered.keys() {
if !declared.contains_key(name.as_str()) {
return Err(PluginError::load(
"unexpected_export",
format!("plugin registered undeclared export `{name}`"),
));
}
}
Ok(registered)
}
/// Host allocator: `malloc`-like, with an internal size header so the matching
/// `free` needs no length argument. Returns NULL for `size == 0`.
unsafe extern "C" fn host_alloc(_host_data: *mut c_void, size: usize) -> *mut c_void {
const HEADER: usize = 16;
const ALIGN: usize = 16;
if size == 0 {
return ptr::null_mut();
}
let Some(total) = size.checked_add(HEADER) else {
return ptr::null_mut();
};
let Ok(layout) = std::alloc::Layout::from_size_align(total, ALIGN) else {
return ptr::null_mut();
};
// SAFETY: layout has non-zero size (size > 0), checked for overflow.
let base = unsafe { std::alloc::alloc(layout) };
if base.is_null() {
return ptr::null_mut();
}
// SAFETY: base has at least HEADER bytes and is 16-byte aligned.
unsafe { (base as *mut usize).write(size) };
// SAFETY: offset stays within the allocation.
unsafe { base.add(HEADER) as *mut c_void }
}
/// Host deallocator paired with [`host_alloc`].
unsafe extern "C" fn host_free(_host_data: *mut c_void, pointer: *mut c_void) {
const HEADER: usize = 16;
const ALIGN: usize = 16;
if pointer.is_null() {
return;
}
// SAFETY: only pointers returned by host_alloc are freed here (ABI
// contract); the header stores the original requested size.
unsafe {
let base = (pointer as *mut u8).sub(HEADER);
let size = (base as *const usize).read();
let layout = std::alloc::Layout::from_size_align_unchecked(size + HEADER, ALIGN);
std::alloc::dealloc(base, layout);
}
}
/// Host export-registration callback.
unsafe extern "C" fn host_register_function(
host_data: *mut c_void,
export_name: MqBytes,
signature_wire: MqBytes,
invoke: MqPluginInvoke,
) -> i32 {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
// SAFETY: host_data points at the HostState owned by the loading
// LoadedPlugin for the duration of the entry call.
unsafe { register_function_impl(host_data, export_name, signature_wire, invoke) }
}));
result.unwrap_or(result::INTERNAL)
}
unsafe fn register_function_impl(
host_data: *mut c_void,
export_name: MqBytes,
signature_wire: MqBytes,
invoke: MqPluginInvoke,
) -> i32 {
if host_data.is_null() {
return result::INVALID_ARGUMENT;
}
// SAFETY: non-NULL host_data per the ABI contract.
let state = unsafe { &mut *(host_data as *mut HostState) };
// SAFETY: borrowed buffers are valid for the duration of this callback.
let name_bytes = match unsafe { export_name.as_slice() } {
Ok(bytes) => bytes,
Err(_) => return result::INVALID_ARGUMENT,
};
if name_bytes.is_empty() || name_bytes.len() > MAX_EXPORT_NAME_BYTES {
return result::INVALID_ARGUMENT;
}
let Ok(name) = std::str::from_utf8(name_bytes) else {
return result::INVALID_ARGUMENT;
};
// SAFETY: borrowed buffers are valid for the duration of this callback.
let signature_bytes = match unsafe { signature_wire.as_slice() } {
Ok(bytes) => bytes,
Err(_) => return result::INVALID_ARGUMENT,
};
if signature_bytes.len() > MAX_SIGNATURE_WIRE_BYTES {
return result::INVALID_ARGUMENT;
}
let Ok(signature) = serde_json::from_slice::<SignatureWire>(signature_bytes) else {
return result::BAD_WIRE;
};
if signature.signature.trim().is_empty() {
return result::BAD_WIRE;
}
if state
.registrations
.iter()
.any(|registered| registered.name == name)
{
return result::REGISTRATION;
}
state.registrations.push(RegisteredExport {
name: name.to_string(),
signature: signature.signature,
invoke,
});
result::OK
}
/// Host capability-request callback.
unsafe extern "C" fn host_request_capability(
ctx: *mut MqCallContext,
name: MqBytes,
request_wire: MqBytes,
reply_wire: *mut MqOwnedBytes,
) -> i32 {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
// SAFETY: pointers follow the invocation ABI contract; buffers are
// borrowed for the duration of this callback.
unsafe { request_capability_impl(ctx, name, request_wire, reply_wire) }
}));
result.unwrap_or(result::INTERNAL)
}
unsafe fn request_capability_impl(
ctx: *mut MqCallContext,
name: MqBytes,
request_wire: MqBytes,
reply_wire: *mut MqOwnedBytes,
) -> i32 {
if ctx.is_null() || reply_wire.is_null() {
return result::INVALID_ARGUMENT;
}
// SAFETY: output pointer is non-NULL and host-provided.
unsafe { *reply_wire = MqOwnedBytes::EMPTY };
// SAFETY: ctx was minted by this host for the current invocation.
let state_pointer = unsafe { (*ctx).host_data() } as *mut HostState;
if state_pointer.is_null() {
return result::INVALID_ARGUMENT;
}
// SAFETY: borrowed buffers are valid for the duration of this callback.
let name_bytes = match unsafe { name.as_slice() } {
Ok(bytes) => bytes,
Err(_) => return result::INVALID_ARGUMENT,
};
let Ok(capability) = std::str::from_utf8(name_bytes) else {
return result::INVALID_ARGUMENT;
};
// SAFETY: borrowed buffers are valid for the duration of this callback.
let request = match unsafe { request_wire.as_slice() } {
Ok(bytes) => bytes.to_vec(),
Err(_) => return result::INVALID_ARGUMENT,
};
// SAFETY: state is owned by the live LoadedPlugin whose invocation is in
// progress; no other Rust reference is held across this callback.
let state = unsafe { &mut *state_pointer };
let Some(handler) = state.capability_handler.as_mut() else {
return result::CAPABILITY;
};
let reply = match handler(capability, &request) {
Ok(reply) => reply,
Err(_) => return result::CAPABILITY,
};
if reply.len() > MAX_CAPABILITY_REPLY_BYTES {
return result::BAD_WIRE;
}
if reply.is_empty() {
return result::OK;
}
// SAFETY: host_alloc is the allocator plugin code frees with host_free.
let pointer = unsafe { host_alloc(state_pointer as *mut c_void, reply.len()) };
if pointer.is_null() {
return result::OUT_OF_MEMORY;
}
// SAFETY: pointer has reply.len() bytes; reply is a distinct allocation.
unsafe {
std::ptr::copy_nonoverlapping(reply.as_ptr(), pointer as *mut u8, reply.len());
*reply_wire = MqOwnedBytes::new(pointer as *mut u8, reply.len());
}
result::OK
}
/// Copy a plugin output buffer into a `Vec`, enforce its size limit, and release
/// the buffer with the host allocator.
///
/// # Safety
///
/// `buffer` must be a plugin output buffer whose pointer (if non-NULL) was
/// allocated by the host allocator, and it must not have been freed yet.
unsafe fn take_host_buffer(
host_api: &MqHostApi,
buffer: &mut MqOwnedBytes,
limit: usize,
what: &str,
) -> Result<Vec<u8>, PluginError> {
// SAFETY: output pointer is host-owned and non-NULL.
let copy = unsafe { buffer.to_vec() }?;
let mut taken = MqOwnedBytes::EMPTY;
std::mem::swap(&mut taken, buffer);
if taken.len > limit {
// Free the oversized buffer before reporting the protocol violation.
// SAFETY: taken.data came from the host allocator.
unsafe { free_host_buffer(host_api, &taken) };
return Err(PluginError::wire(
"output_too_large",
format!(
"plugin {what} wire is {} bytes, limit is {limit}",
taken.len
),
));
}
// SAFETY: taken.data came from the host allocator.
unsafe { free_host_buffer(host_api, &taken) };
Ok(copy)
}
/// Release a host-allocated buffer.
///
/// # Safety
///
/// `buffer.data` must be NULL or a pointer previously returned by the host
/// allocator and not yet freed.
unsafe fn free_host_buffer(host_api: &MqHostApi, buffer: &MqOwnedBytes) {
if buffer.data.is_null() {
return;
}
// SAFETY: alloc/free pair and non-NULL pointer per the caller contract.
unsafe { (host_api.free)(host_api.host_data, buffer.data as *mut c_void) };
}
/// Validate a host API table (useful for tests and SDK conformance checks).
pub fn validate_host_table(host: &MqHostApi) -> Result<AbiVersion, PluginError> {
// SAFETY: we pass a valid reference converted to a pointer.
unsafe { check_host_api(host as *const MqHostApi) }
}
+754
View File
@@ -0,0 +1,754 @@
//! `plugin.yaml` manifest parsing and validation.
//!
//! A manifest is the declarative half of a plugin package: it names the
//! plugin, pins the ABI generation it targets, declares every export and
//! capability requirement, and lists content-addressed artifacts per target
//! triple. Installing a package never grants permissions; validation never
//! executes plugin code.
use std::path::{Component, Path, PathBuf};
use serde::{Deserialize, Serialize};
use super::artifact::{is_valid_sha256_hex, TargetTriple};
use super::artifact::{verify_sha256_file, HostTarget};
use marqdo_plugin_abi::abi::{
AbiVersion, ABI_MAJOR, ABI_MINOR, MAX_EXPORT_NAME_BYTES, MAX_SIGNATURE_WIRE_BYTES,
};
use marqdo_plugin_abi::PluginError;
/// Maximum number of exports a single plugin may register.
pub const MAX_EXPORTS: usize = 256;
/// Maximum number of declared capabilities.
pub const MAX_REQUIRES: usize = 64;
/// Maximum number of artifacts.
pub const MAX_ARTIFACTS: usize = 32;
/// Capability names the host knows about (blueprint section 10.5 whitelist).
pub const KNOWN_CAPABILITIES: &[&str] = &[
"console",
"log",
"math.compute",
"fs.read",
"fs.write",
"net.request",
"process",
"clock",
"random",
"artifact.record",
];
/// Function-name prefixes reserved by the language/host; plugins may not
/// shadow built-ins or other namespaces.
pub const RESERVED_EXPORT_PREFIXES: &[&str] = &["marqdo.", "builtin.", "core.", "std.", "host."];
/// Plugin deployment kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PluginKind {
/// Native dynamic library loaded in-process. Requires explicit trust.
Native,
/// Isolated plugin worker process (same logical plugin API).
Worker,
/// Wasm component (future direction; only recognized in v1).
Wasm,
}
impl PluginKind {
/// Stable manifest name.
pub const fn as_str(self) -> &'static str {
match self {
PluginKind::Native => "native",
PluginKind::Worker => "worker",
PluginKind::Wasm => "wasm",
}
}
}
/// One declared export.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Export {
/// Dotted export name (e.g. `solver.add`).
pub name: String,
/// Marqdo-facing signature string (e.g. `($a: Int, $b: Int) -> Int`).
pub signature: String,
}
/// One target-specific artifact.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Artifact {
/// Rust-style target triple (e.g. `x86_64-unknown-linux-gnu`).
pub target: String,
/// Relative path to the artifact inside the package.
pub file: String,
/// Lowercase hexadecimal sha256 of the artifact contents.
pub sha256: String,
}
impl Artifact {
/// Parse the artifact target triple.
pub fn target_triple(&self) -> Result<TargetTriple, PluginError> {
TargetTriple::parse(&self.target)
}
/// Resolve the artifact path below `base_dir`, rejecting absolute paths
/// and `..` traversal so a manifest can never point outside its package.
pub fn resolve_path(&self, base_dir: &Path) -> Result<PathBuf, PluginError> {
validate_artifact_file(&self.file)?;
Ok(base_dir.join(&self.file))
}
}
/// The `plugin:` block of `plugin.yaml`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PluginInfo {
/// Package name (dotted, e.g. `qdqc.solver`).
pub name: String,
/// Package version (semver-ish, e.g. `1.0.0`).
pub version: String,
/// Required plugin ABI range (e.g. `^1.0`).
pub abi: String,
/// Deployment kind.
pub kind: PluginKind,
/// Declared exports.
pub exports: Vec<Export>,
/// Declared capability requirements.
#[serde(default)]
pub requires: Vec<String>,
/// Declared artifacts.
pub artifacts: Vec<Artifact>,
}
/// Parsed `plugin.yaml`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PluginManifest {
/// The single `plugin:` block.
pub plugin: PluginInfo,
}
impl PluginManifest {
/// Parse a manifest from YAML text.
pub fn parse_str(yaml: &str) -> Result<Self, PluginError> {
serde_yaml::from_str(yaml).map_err(|error| {
PluginError::manifest("manifest_parse_failed", "plugin.yaml could not be parsed")
.with_detail(error.to_string())
})
}
/// Read and parse a manifest from disk.
pub fn load(path: &Path) -> Result<Self, PluginError> {
let text = std::fs::read_to_string(path).map_err(|error| {
PluginError::manifest(
"manifest_unreadable",
format!("manifest `{}` could not be read", path.display()),
)
.with_detail(error.to_string())
})?;
Self::parse_str(&text)
}
/// Validate every declared field and cross-field invariant.
///
/// This performs no filesystem access and executes no plugin code.
pub fn validate(&self) -> Result<(), PluginError> {
let plugin = &self.plugin;
validate_dotted_name(&plugin.name, MAX_EXPORT_NAME_BYTES, "plugin name")?;
if plugin.name.starts_with("marqdo.") || plugin.name.starts_with("builtin.") {
return Err(PluginError::manifest(
"reserved_name",
format!("plugin name `{}` uses a reserved namespace", plugin.name),
));
}
PackageVersion::parse(&plugin.version)?;
let requirement = AbiRequirement::parse(&plugin.abi)?;
if !requirement.is_compatible_with(AbiVersion::current()) {
return Err(PluginError::unsupported(
"abi_requirement_unsupported",
format!(
"plugin requires ABI `{}` but the host implements {ABI_MAJOR}.{ABI_MINOR}",
plugin.abi
),
));
}
if plugin.exports.is_empty() {
return Err(PluginError::manifest(
"no_exports",
"plugin must declare at least one export",
));
}
if plugin.exports.len() > MAX_EXPORTS {
return Err(PluginError::manifest(
"too_many_exports",
format!("plugin declares more than {MAX_EXPORTS} exports"),
));
}
let mut export_names = std::collections::BTreeSet::new();
for export in &plugin.exports {
validate_dotted_name(&export.name, MAX_EXPORT_NAME_BYTES, "export name")?;
if !export.name.contains('.') {
return Err(PluginError::manifest(
"invalid_export_name",
format!(
"export `{}` must be namespaced (e.g. `solver.add`)",
export.name
),
));
}
if let Some(prefix) = RESERVED_EXPORT_PREFIXES
.iter()
.find(|prefix| export.name.starts_with(**prefix))
{
return Err(PluginError::manifest(
"reserved_export_name",
format!("export `{}` uses reserved prefix `{prefix}`", export.name),
));
}
if !export_names.insert(export.name.clone()) {
return Err(PluginError::manifest(
"duplicate_export",
format!("export `{}` is declared more than once", export.name),
));
}
validate_signature(&export.name, &export.signature)?;
}
if plugin.requires.len() > MAX_REQUIRES {
return Err(PluginError::manifest(
"too_many_capabilities",
format!("plugin requires more than {MAX_REQUIRES} capabilities"),
));
}
let mut capabilities = std::collections::BTreeSet::new();
for capability in &plugin.requires {
if !KNOWN_CAPABILITIES.contains(&capability.as_str())
&& !is_vendor_capability(capability)
{
return Err(PluginError::manifest(
"unknown_capability",
format!(
"unknown capability `{capability}`; vendor capabilities need a dotted vendor namespace"
),
));
}
if !capabilities.insert(capability.clone()) {
return Err(PluginError::manifest(
"duplicate_capability",
format!("capability `{capability}` is declared more than once"),
));
}
}
if plugin.artifacts.is_empty() {
return Err(PluginError::manifest(
"no_artifacts",
"plugin must declare at least one artifact",
));
}
if plugin.artifacts.len() > MAX_ARTIFACTS {
return Err(PluginError::manifest(
"too_many_artifacts",
format!("plugin declares more than {MAX_ARTIFACTS} artifacts"),
));
}
let mut targets = std::collections::BTreeSet::new();
for artifact in &plugin.artifacts {
let triple = artifact.target_triple()?;
if !targets.insert(triple.clone()) {
return Err(PluginError::manifest(
"duplicate_artifact_target",
format!("target `{triple}` is declared more than once"),
));
}
validate_artifact_file(&artifact.file)?;
if !is_valid_sha256_hex(&artifact.sha256) {
return Err(PluginError::manifest(
"invalid_sha256",
format!(
"artifact `{}` sha256 must be 64 hexadecimal characters",
artifact.file
),
));
}
}
Ok(())
}
/// The parsed ABI requirement.
pub fn abi_requirement(&self) -> Result<AbiRequirement, PluginError> {
AbiRequirement::parse(&self.plugin.abi)
}
/// The parsed package version.
pub fn package_version(&self) -> Result<PackageVersion, PluginError> {
PackageVersion::parse(&self.plugin.version)
}
/// Resolve the artifact for `host`, requiring an exact target-triple match
/// with matching pointer width.
pub fn resolve_artifact<'a>(&'a self, host: &HostTarget) -> Result<&'a Artifact, PluginError> {
for artifact in &self.plugin.artifacts {
let triple = artifact.target_triple()?;
if triple == *host.triple() {
return Ok(artifact);
}
}
Err(PluginError::artifact(
"no_matching_artifact",
format!(
"plugin `{}` has no artifact for target `{}`",
self.plugin.name,
host.triple()
),
)
.with_detail(format!(
"declared targets: {}",
self.plugin
.artifacts
.iter()
.map(|artifact| artifact.target.as_str())
.collect::<Vec<_>>()
.join(", ")
)))
}
/// Resolve and verify the artifact for `host`, returning its path.
///
/// Verification proves the file matches the manifest sha256; it does not
/// grant trust or capability authorization.
pub fn verify_artifact(
&self,
base_dir: &Path,
host: &HostTarget,
) -> Result<(PathBuf, &Artifact), PluginError> {
let artifact = self.resolve_artifact(host)?;
let path = artifact.resolve_path(base_dir)?;
verify_sha256_file(&path, &artifact.sha256)?;
Ok((path, artifact))
}
}
/// Semver-ish package version (major.minor.patch with optional pre-release and
/// build metadata). Manifest validation is deliberately not a full SemVer
/// range resolver.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackageVersion {
/// Original string from the manifest.
pub raw: String,
/// Major component.
pub major: u64,
/// Minor component.
pub minor: u64,
/// Patch component.
pub patch: u64,
/// Optional pre-release suffix (without the leading `-`).
pub pre_release: Option<String>,
/// Optional build metadata (without the leading `+`).
pub build: Option<String>,
}
impl PackageVersion {
/// Parse a semver-ish version string.
pub fn parse(raw: &str) -> Result<Self, PluginError> {
let invalid = |detail: String| {
PluginError::manifest("invalid_version", format!("`{raw}` is not a valid version"))
.with_detail(detail)
};
let (without_build, build) = match raw.split_once('+') {
Some((left, right)) => {
validate_identifiers(right).map_err(&invalid)?;
(left, Some(right.to_string()))
}
None => (raw, None),
};
let (core, pre_release) = match without_build.split_once('-') {
Some((left, right)) => {
validate_identifiers(right).map_err(&invalid)?;
(left, Some(right.to_string()))
}
None => (without_build, None),
};
let numbers: Vec<&str> = core.split('.').collect();
if numbers.len() != 3 {
return Err(invalid("expected `major.minor.patch`".to_string()));
}
let mut parsed = [0u64; 3];
for (index, number) in numbers.iter().enumerate() {
if number.is_empty() || !number.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(invalid(format!("component `{number}` is not numeric")));
}
if number.len() > 1 && number.starts_with('0') {
return Err(invalid(format!("component `{number}` has a leading zero")));
}
parsed[index] = number
.parse::<u64>()
.map_err(|_| invalid(format!("component `{number}` is too large")))?;
}
Ok(Self {
raw: raw.to_string(),
major: parsed[0],
minor: parsed[1],
patch: parsed[2],
pre_release,
build,
})
}
}
fn validate_identifiers(value: &str) -> Result<(), String> {
if value.is_empty() {
return Err("empty version suffix".to_string());
}
for segment in value.split('.') {
if segment.is_empty() {
return Err("empty version suffix segment".to_string());
}
if !segment
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
{
return Err(format!("invalid version suffix `{segment}`"));
}
}
Ok(())
}
/// A caret-style ABI requirement such as `^1.0`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AbiRequirement {
/// Required major.
pub major: u32,
/// Required minimum minor.
pub minor: u32,
/// Original string from the manifest.
pub raw: String,
}
impl AbiRequirement {
/// Parse `^1`, `^1.0`, `1`, or `1.0`.
pub fn parse(raw: &str) -> Result<Self, PluginError> {
let trimmed = raw.trim();
let numbers = trimmed.strip_prefix('^').unwrap_or(trimmed);
let mut parts = numbers.split('.');
let major = parts.next().unwrap_or_default();
let minor = parts.next().unwrap_or("0");
if parts.next().is_some() {
return Err(PluginError::manifest(
"invalid_abi_requirement",
format!("`{raw}` is not a supported ABI requirement"),
));
}
let parse_component = |component: &str| -> Result<u32, PluginError> {
if component.is_empty() || !component.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(PluginError::manifest(
"invalid_abi_requirement",
format!("`{raw}` is not a supported ABI requirement"),
));
}
component.parse::<u32>().map_err(|_| {
PluginError::manifest(
"invalid_abi_requirement",
format!("`{raw}` contains an out-of-range ABI component"),
)
})
};
Ok(Self {
major: parse_component(major)?,
minor: parse_component(minor)?,
raw: raw.to_string(),
})
}
/// Caret compatibility: `^M.m` means `>=M.m` and `<M+1.0`
/// (with the SemVer `0.x` special case pinning the minor).
pub fn is_compatible_with(&self, host: AbiVersion) -> bool {
if self.major == 0 {
host.major == 0 && host.minor == self.minor
} else {
host.major == self.major && host.minor >= self.minor
}
}
}
fn validate_dotted_name(name: &str, max_len: usize, what: &str) -> Result<(), PluginError> {
if name.is_empty() {
return Err(PluginError::manifest(
"invalid_name",
format!("{what} must not be empty"),
));
}
if name.len() > max_len {
return Err(PluginError::manifest(
"invalid_name",
format!("{what} `{name}` is longer than {max_len} bytes"),
));
}
for segment in name.split('.') {
if segment.is_empty() {
return Err(PluginError::manifest(
"invalid_name",
format!("{what} `{name}` contains an empty segment"),
));
}
let mut bytes = segment.bytes();
let first = bytes.next().unwrap_or(b'a');
if !first.is_ascii_lowercase() {
return Err(PluginError::manifest(
"invalid_name",
format!("{what} `{name}` must start each segment with a lowercase letter"),
));
}
if !bytes.all(|byte| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-' || byte == b'_'
}) {
return Err(PluginError::manifest(
"invalid_name",
format!("{what} `{name}` may only contain lowercase letters, digits, `-` and `_`"),
));
}
}
Ok(())
}
/// Whether a manifest capability is a syntactically valid vendor request.
///
/// This is validation only; a vendor capability remains unauthorized until a
/// trusted host policy provides a handler for this exact name.
fn is_vendor_capability(name: &str) -> bool {
let segments: Vec<&str> = name.split('.').collect();
if segments.len() < 3 {
return false;
}
if matches!(
segments[0],
"console" | "math" | "fs" | "net" | "process" | "log" | "clock" | "random"
) {
return false;
}
segments.iter().all(|segment| {
!segment.is_empty()
&& segment.bytes().enumerate().all(|(index, byte)| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || (byte == b'-' && index > 0)
})
})
}
fn validate_signature(export: &str, signature: &str) -> Result<(), PluginError> {
let trimmed = signature.trim();
if trimmed.is_empty() || trimmed.len() > MAX_SIGNATURE_WIRE_BYTES {
return Err(PluginError::manifest(
"invalid_signature",
format!("export `{export}` has an empty or oversized signature"),
));
}
if !trimmed.starts_with('(') || !trimmed.contains("->") {
return Err(PluginError::manifest(
"invalid_signature",
format!("export `{export}` signature must look like `(args) -> Return`"),
));
}
if trimmed.chars().any(char::is_control) {
return Err(PluginError::manifest(
"invalid_signature",
format!("export `{export}` signature contains control characters"),
));
}
Ok(())
}
fn validate_artifact_file(file: &str) -> Result<(), PluginError> {
if file.is_empty() || file.contains('\0') || file.len() > 256 {
return Err(PluginError::manifest(
"invalid_artifact_path",
"artifact file must be a non-empty relative path of at most 256 bytes",
));
}
let path = Path::new(file);
if path.is_absolute() {
return Err(PluginError::manifest(
"invalid_artifact_path",
format!("artifact file `{file}` must be relative"),
));
}
for component in path.components() {
match component {
Component::Normal(part) if !part.is_empty() => {}
Component::CurDir => {}
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
return Err(PluginError::manifest(
"invalid_artifact_path",
format!("artifact file `{file}` must not escape the package directory"),
));
}
Component::Normal(_) => {
return Err(PluginError::manifest(
"invalid_artifact_path",
format!("artifact file `{file}` contains an empty component"),
));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
const VALID_YAML: &str = r#"
plugin:
name: demo.solver
version: 1.0.0
abi: "^1.0"
kind: native
exports:
- name: solver.add
signature: "($a: Int, $b: Int) -> Int"
requires:
- math.compute
artifacts:
- target: x86_64-unknown-linux-gnu
file: solver.so
sha256: "0000000000000000000000000000000000000000000000000000000000000000"
"#;
fn valid_manifest() -> PluginManifest {
let manifest = PluginManifest::parse_str(VALID_YAML).expect("parse");
manifest.validate().expect("validate");
manifest
}
#[test]
fn valid_manifest_parses_and_validates() {
let manifest = valid_manifest();
assert_eq!(manifest.plugin.name, "demo.solver");
assert_eq!(manifest.plugin.kind, PluginKind::Native);
assert_eq!(manifest.abi_requirement().expect("abi").raw, "^1.0");
assert_eq!(manifest.package_version().expect("version").patch, 0);
}
#[test]
fn vendor_capabilities_are_validated_but_not_granted() {
let yaml = VALID_YAML.replace(
" requires:\n - math.compute",
" requires:\n - math.compute\n - vendor.device.read",
);
let manifest = PluginManifest::parse_str(&yaml).expect("parse");
manifest
.validate()
.expect("vendor names are valid requests");
for bad in ["vendor", "vendor..read", "vendor.Device", "fs.extra"] {
let yaml = VALID_YAML.replace(" - math.compute", &format!(" - {bad}"));
let manifest = PluginManifest::parse_str(&yaml).expect("parse");
assert!(
manifest.validate().is_err(),
"capability `{bad}` must be rejected"
);
}
}
#[test]
fn malformed_yaml_is_rejected() {
let error = PluginManifest::parse_str("plugin: [unclosed").expect_err("must fail");
assert_eq!(error.kind, marqdo_plugin_abi::ErrorKind::Manifest);
assert_eq!(error.code, "manifest_parse_failed");
assert!(PluginManifest::parse_str("not_a_plugin: 1").is_err());
}
#[test]
fn invalid_fields_are_rejected() {
let cases = [
("name", "DemoSolver"),
("version", "1.0"),
("abi", "^2.0"),
("kind", "inprocess"),
("file", "../solver.so"),
("sha256", "xyz"),
];
for (field, value) in cases {
let yaml = match field {
"name" => VALID_YAML.replace("name: demo.solver", &format!("name: {value}")),
"version" => VALID_YAML.replace("version: 1.0.0", &format!("version: {value}")),
"abi" => VALID_YAML.replace("abi: \"^1.0\"", &format!("abi: \"{value}\"")),
"kind" => VALID_YAML.replace("kind: native", &format!("kind: {value}")),
"file" => VALID_YAML.replace("file: solver.so", &format!("file: {value}")),
"sha256" => VALID_YAML.replace(
"sha256: \"0000000000000000000000000000000000000000000000000000000000000000\"",
&format!("sha256: \"{value}\""),
),
_ => unreachable!(),
};
match PluginManifest::parse_str(&yaml) {
Ok(manifest) => assert!(
manifest.validate().is_err(),
"`{field}` = `{value}` should fail validation"
),
Err(error) => assert_eq!(
error.kind,
marqdo_plugin_abi::ErrorKind::Manifest,
"`{field}` = `{value}` should fail manifest handling"
),
}
}
}
#[test]
fn duplicate_and_reserved_exports_are_rejected() {
let duplicate = VALID_YAML.replace(
" - name: solver.add\n signature: \"($a: Int, $b: Int) -> Int\"",
" - name: solver.add\n signature: \"($a: Int) -> Int\"\n - name: solver.add\n signature: \"($a: Int) -> Int\"",
);
let manifest = PluginManifest::parse_str(&duplicate).expect("parse");
assert_eq!(
manifest.validate().expect_err("duplicate").code,
"duplicate_export"
);
let reserved = VALID_YAML.replace("solver.add", "builtin.print");
let manifest = PluginManifest::parse_str(&reserved).expect("parse");
assert_eq!(
manifest.validate().expect_err("reserved").code,
"reserved_export_name"
);
}
#[test]
fn abi_requirement_caret_semantics() {
let v1 = AbiVersion::new(1, 0);
assert!(AbiRequirement::parse("^1.0")
.expect("parse")
.is_compatible_with(v1));
assert!(AbiRequirement::parse("^1")
.expect("parse")
.is_compatible_with(v1));
assert!(AbiRequirement::parse("1.0")
.expect("parse")
.is_compatible_with(v1));
assert!(!AbiRequirement::parse("^1.1")
.expect("parse")
.is_compatible_with(v1));
assert!(!AbiRequirement::parse("^2.0")
.expect("parse")
.is_compatible_with(v1));
assert!(!AbiRequirement::parse("^0.1")
.expect("parse")
.is_compatible_with(v1));
assert!(AbiRequirement::parse("nonsense").is_err());
}
#[test]
fn artifact_resolution_requires_exact_host_target() {
let manifest = valid_manifest();
let host = HostTarget::current();
if host.triple().as_str() == "x86_64-unknown-linux-gnu" {
let artifact = manifest.resolve_artifact(&host).expect("resolve");
assert_eq!(artifact.file, "solver.so");
} else {
assert_eq!(
manifest
.resolve_artifact(&host)
.expect_err("other target")
.code,
"no_matching_artifact"
);
}
}
}
+26
View File
@@ -0,0 +1,26 @@
//! Execution side of the Callable Plugin ABI: manifest/artifact validation,
//! native loading, invocation dispatch and the worker process.
//!
//! The public contract (C layout, wire envelope and protocol errors) lives in
//! `marqdo-plugin-abi`; this module owns `dlopen`, process spawning, artifact
//! file selection and trusted invocation. The CLI may consume the static
//! descriptor types for `check`/`inspect` preparation, but preparation never
//! loads a library or starts a process.
//!
//! The `include/marqdo_plugin_abi_v1.h` header and the Rust layout assertions
//! in `marqdo_plugin_abi::abi` remain the single ABI authority.
pub mod artifact;
pub mod loader;
pub mod manifest;
pub mod worker;
pub use artifact::{
current_target_triple, is_valid_sha256_hex, sha256_bytes, sha256_file, verify_sha256_file,
HostTarget, TargetTriple,
};
pub use loader::{CapabilityHandler, LoadOptions, LoadedPlugin, RegisteredExport};
pub use manifest::{
AbiRequirement, Artifact, Export, PackageVersion, PluginInfo, PluginKind, PluginManifest,
KNOWN_CAPABILITIES,
};
+345
View File
@@ -0,0 +1,345 @@
//! Isolated plugin worker transport (length-prefixed JSON frames).
//!
//! The worker is the same core binary invoked with the hidden
//! `__plugin-worker` command. It loads one native plugin in a child process and
//! serves invoke frames over stdin/stdout. This isolates crashes and provides a
//! process boundary; it is **not** an OS sandbox and does not make arbitrary
//! untrusted native code safe.
use std::io::{Read, Write};
use std::path::Path;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use serde_json::{json, Value};
use super::loader::{LoadOptions, LoadedPlugin};
use super::manifest::{PluginKind, PluginManifest};
use marqdo_plugin_abi::wire::{WireRequest, WireResponse};
use marqdo_plugin_abi::PluginError;
/// Hidden CLI command name used to start a worker.
pub const WORKER_COMMAND: &str = "__plugin-worker";
/// Maximum frame size accepted by either side.
pub const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
/// Maximum capability requests a plugin may make during one invocation.
pub const MAX_CAPABILITY_REQUESTS: usize = 64;
/// Maximum serialized bytes of one capability request.
pub const MAX_CAPABILITY_REQUEST_BYTES: usize = 64 * 1024;
/// Read one length-prefixed frame (4-byte big-endian length + JSON).
///
/// `Ok(None)` means a clean EOF at a frame boundary. A partial header or
/// truncated payload is a protocol error, never EOF. Framing itself is shared
/// with other persistent workers; the plugin vocabulary stays in this module.
pub fn read_frame<R: Read>(reader: &mut R) -> Result<Option<Value>, PluginError> {
marqdo_worker_ipc::read_frame(reader, MAX_FRAME_BYTES).map_err(frame_read_error)
}
/// Write one length-prefixed frame.
pub fn write_frame<W: Write>(writer: &mut W, value: &Value) -> Result<(), PluginError> {
marqdo_worker_ipc::write_frame(writer, value, MAX_FRAME_BYTES).map_err(frame_write_error)
}
fn frame_read_error(error: marqdo_worker_ipc::FrameError) -> PluginError {
match error {
marqdo_worker_ipc::FrameError::Io(error) => PluginError::invoke(
"plugin.crashed",
format!("worker frame read failed: {error}"),
),
other => PluginError::wire("worker_frame_invalid", other.to_string()),
}
}
fn frame_write_error(error: marqdo_worker_ipc::FrameError) -> PluginError {
match error {
marqdo_worker_ipc::FrameError::Io(error) => PluginError::invoke(
"plugin.crashed",
format!("worker frame write failed: {error}"),
),
marqdo_worker_ipc::FrameError::Encode(error) => {
PluginError::wire("worker_encode_failed", error.to_string())
}
marqdo_worker_ipc::FrameError::Length(length) => PluginError::wire(
"worker_frame_too_large",
format!("worker frame is {length} bytes"),
),
other => PluginError::wire("worker_frame_invalid", other.to_string()),
}
}
/// Run one worker until shutdown/EOF. Returns a process exit code.
pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
let manifest = match PluginManifest::load(manifest_path) {
Ok(manifest) => manifest,
Err(error) => {
eprintln!("worker: {}: {}", error.code, error.message);
return 2;
}
};
// The worker is the isolated transport; the library itself is loaded
// natively inside this child process.
let mut native_manifest = manifest.clone();
native_manifest.plugin.kind = PluginKind::Native;
let stdin = Arc::new(Mutex::new(std::io::stdin()));
let stdout = Arc::new(Mutex::new(std::io::stdout()));
let next_request_id = Arc::new(AtomicU64::new(1));
let capability_calls = Arc::new(AtomicUsize::new(0));
let handler_stdin = Arc::clone(&stdin);
let handler_stdout = Arc::clone(&stdout);
let handler_ids = Arc::clone(&next_request_id);
let handler_calls = Arc::clone(&capability_calls);
let capability_handler: super::loader::CapabilityHandler = Box::new(
move |capability, request| {
if handler_calls.fetch_add(1, Ordering::SeqCst) >= MAX_CAPABILITY_REQUESTS {
return Err(PluginError::capability(
"capability.budget_exceeded",
format!(
"plugin exceeded the limit of {MAX_CAPABILITY_REQUESTS} capability requests per invocation"
),
));
}
if request.len() > MAX_CAPABILITY_REQUEST_BYTES {
return Err(PluginError::capability(
"capability.request_too_large",
format!(
"capability request is {} bytes; limit is {MAX_CAPABILITY_REQUEST_BYTES}",
request.len()
),
));
}
let id = handler_ids.fetch_add(1, Ordering::SeqCst);
let request_value: Value = serde_json::from_slice(request).map_err(|error| {
PluginError::capability(
"capability.request_invalid",
format!("capability request is not valid JSON: {error}"),
)
})?;
{
let mut out = handler_stdout.lock().map_err(|_| {
PluginError::invoke("plugin.crashed", "worker stdout lock is poisoned")
})?;
write_frame(
&mut *out,
&json!({
"kind": "capability_request",
"id": id,
"capability": capability,
"request": request_value,
}),
)?;
}
{
let frame = {
let mut input = handler_stdin.lock().map_err(|_| {
PluginError::invoke("plugin.crashed", "worker stdin lock is poisoned")
})?;
read_frame(&mut *input).map_err(|error| {
PluginError::invoke(
error.code.as_str(),
format!("worker capability reply failed: {}", error.message),
)
})?
};
let Some(frame) = frame else {
return Err(PluginError::invoke(
"plugin.crashed",
"host closed the worker during a capability request",
));
};
if frame.get("id").and_then(Value::as_u64) != Some(id) {
return Err(PluginError::wire(
"worker_frame_invalid",
"capability reply id does not match the request",
));
}
match frame.get("kind").and_then(Value::as_str) {
Some("capability_reply") => {
let data = frame.get("data").and_then(Value::as_str).ok_or_else(|| {
PluginError::wire(
"worker_frame_invalid",
"capability reply has no text data",
)
})?;
Ok(data.as_bytes().to_vec())
}
Some("capability_error") => Err(PluginError::capability(
frame
.get("code")
.and_then(Value::as_str)
.unwrap_or("capability.unavailable"),
frame
.get("message")
.and_then(Value::as_str)
.unwrap_or("capability request failed")
.to_string(),
)),
_ => Err(PluginError::wire(
"worker_frame_invalid",
"expected a capability reply frame",
)),
}
}
},
);
let options = LoadOptions {
host_target: super::artifact::HostTarget::current(),
capability_handler: Some(capability_handler),
};
let mut plugin = match LoadedPlugin::open_with(&native_manifest, base_dir, options) {
Ok(plugin) => plugin,
Err(error) => {
eprintln!("worker: {}: {}", error.code, error.message);
return 2;
}
};
let exports: Vec<Value> = plugin
.exports()
.map(|export| json!({"name": export.name(), "signature": export.signature()}))
.collect();
if send_frame(&stdout, &json!({"kind": "ready", "exports": exports})).is_err() {
return 1;
}
loop {
let frame = match receive_frame(&stdin) {
Ok(Some(frame)) => frame,
Ok(None) => return 0,
Err(error) => {
eprintln!("worker: {}: {}", error.code, error.message);
return 1;
}
};
match frame.get("kind").and_then(Value::as_str) {
Some("shutdown") => return 0,
Some("invoke") => {
let Some(request_value) = frame.get("request") else {
let _ = send_frame(
&stdout,
&json!({"kind":"error","code":"worker_request_invalid","message":"missing request"}),
);
continue;
};
let request_bytes = match serde_json::to_vec(request_value) {
Ok(bytes) => bytes,
Err(error) => {
let _ = send_frame(
&stdout,
&json!({"kind":"error","code":"worker_request_invalid","message":error.to_string()}),
);
continue;
}
};
let request = match WireRequest::from_json_bytes(&request_bytes) {
Ok(request) => request,
Err(error) => {
let _ = send_frame(
&stdout,
&json!({"kind":"error","code":error.code,"message":error.message}),
);
continue;
}
};
capability_calls.store(0, Ordering::SeqCst);
match plugin.invoke(&request) {
Ok(response) => {
let body = response
.to_json_bytes()
.ok()
.and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
.unwrap_or_else(|| json!({"wire_version":1,"kind":"response"}));
if send_frame(&stdout, &json!({"kind":"response","response":body})).is_err() {
return 1;
}
}
Err(error) => {
if send_frame(
&stdout,
&json!({"kind":"error","code":error.code,"message":error.message,"error_kind":error.kind.as_str()}),
)
.is_err()
{
return 1;
}
}
}
}
_ => {
if send_frame(
&stdout,
&json!({"kind":"error","code":"worker_frame_invalid","message":"unknown frame kind"}),
)
.is_err()
{
return 1;
}
}
}
}
}
fn send_frame(stdout: &Arc<Mutex<std::io::Stdout>>, value: &Value) -> Result<(), PluginError> {
let mut out = stdout
.lock()
.map_err(|_| PluginError::invoke("plugin.crashed", "worker stdout lock is poisoned"))?;
write_frame(&mut *out, value)
}
fn receive_frame(stdin: &Arc<Mutex<std::io::Stdin>>) -> Result<Option<Value>, PluginError> {
let mut input = stdin
.lock()
.map_err(|_| PluginError::invoke("plugin.crashed", "worker stdin lock is poisoned"))?;
read_frame(&mut *input)
}
pub fn response_from_frame(frame: &Value) -> Result<WireResponse, PluginError> {
let body = frame
.get("response")
.ok_or_else(|| PluginError::wire("worker_response_invalid", "missing response body"))?;
let bytes = serde_json::to_vec(body)
.map_err(|error| PluginError::wire("worker_response_invalid", error.to_string()))?;
WireResponse::from_json_bytes(&bytes)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn frame_roundtrip_and_clean_eof() {
let mut bytes = Vec::new();
write_frame(&mut bytes, &json!({"kind": "shutdown"})).unwrap();
let mut cursor = Cursor::new(bytes.clone());
assert_eq!(
read_frame(&mut cursor).unwrap(),
Some(json!({"kind": "shutdown"}))
);
assert_eq!(read_frame(&mut cursor).unwrap(), None);
}
#[test]
fn partial_header_is_an_error_not_eof() {
let mut cursor = Cursor::new(vec![0_u8, 0]);
let error = read_frame(&mut cursor).unwrap_err();
assert_eq!(error.code, "worker_frame_invalid");
}
#[test]
fn oversized_and_zero_length_frames_are_rejected() {
for length in [0_u32, (MAX_FRAME_BYTES as u32) + 1] {
let mut cursor = Cursor::new(length.to_be_bytes().to_vec());
let error = read_frame(&mut cursor).unwrap_err();
assert_eq!(error.code, "worker_frame_invalid");
}
}
#[test]
fn truncated_payload_is_rejected() {
let mut bytes = 10_u32.to_be_bytes().to_vec();
bytes.extend_from_slice(b"{}");
let error = read_frame(&mut Cursor::new(bytes)).unwrap_err();
assert_eq!(error.code, "worker_frame_invalid");
}
}