feat(m0.6-r2): complete-name plugin exports and capability broker
- register every plugin export by its complete dotted name; reject conflicting loads atomically instead of overwriting the first namespace - route plugin calls by full export name and expose loaded descriptors to the runtime - add CapabilityBroker for core grants and vendor policy, with audit records - accept syntactically valid vendor capability requests in manifests while still denying them until a trusted policy exists - add check --plugin static signature validation without dlopen - test multi-export C plugin routing, conflict rollback, broker decisions and static arity rejection
This commit is contained in:
1 parent
21c1e50617
commit
d940013f35
13 files changed
+826
-94
No files matched your search
@@ -5,10 +5,214 @@
|
||||
//! with what the operator/CLI explicitly granted. Every host operation checks
|
||||
//! against this set at the point of execution.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use glob::Pattern;
|
||||
use marqdo_plugin_abi::PluginError;
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{ErrorCategory, RuntimeError};
|
||||
|
||||
/// One audited capability request from a plugin.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CapabilityAudit {
|
||||
/// Plugin package that asked.
|
||||
pub package: String,
|
||||
/// Capability name.
|
||||
pub capability: String,
|
||||
/// `granted`, `denied` or `unavailable`.
|
||||
pub decision: &'static str,
|
||||
/// Human-readable reason.
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
/// Broker for plugin host-capability requests (ADR-0011).
|
||||
///
|
||||
/// Core capabilities are checked against the effective grant set. Vendor
|
||||
/// capabilities are accepted only when a trusted host policy registered the
|
||||
/// exact name; a declaration in a manifest is never enough.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CapabilityBroker {
|
||||
capabilities: Capabilities,
|
||||
vendor_policy: BTreeSet<String>,
|
||||
audit: Arc<Mutex<Vec<CapabilityAudit>>>,
|
||||
}
|
||||
|
||||
impl CapabilityBroker {
|
||||
/// Construct a broker over an effective grant set.
|
||||
pub fn new(capabilities: Capabilities) -> Self {
|
||||
Self::with_audit(capabilities, Arc::new(Mutex::new(Vec::new())))
|
||||
}
|
||||
|
||||
/// Construct a broker sharing an existing audit log.
|
||||
pub fn with_audit(capabilities: Capabilities, audit: Arc<Mutex<Vec<CapabilityAudit>>>) -> Self {
|
||||
Self {
|
||||
capabilities,
|
||||
vendor_policy: BTreeSet::new(),
|
||||
audit,
|
||||
}
|
||||
}
|
||||
|
||||
/// Register a trusted vendor capability policy entry.
|
||||
pub fn allow_vendor(&mut self, capability: impl Into<String>) {
|
||||
self.vendor_policy.insert(capability.into());
|
||||
}
|
||||
|
||||
/// Shared audit log.
|
||||
pub fn audit(&self) -> Arc<Mutex<Vec<CapabilityAudit>>> {
|
||||
Arc::clone(&self.audit)
|
||||
}
|
||||
|
||||
/// Authorize one request, returning reply bytes on success.
|
||||
pub fn authorize(
|
||||
&mut self,
|
||||
package: &str,
|
||||
capability: &str,
|
||||
request: &[u8],
|
||||
) -> Result<Vec<u8>, PluginError> {
|
||||
let result = self.decide(package, capability, request);
|
||||
let (decision, reason) = match &result {
|
||||
Ok(()) => ("granted", String::new()),
|
||||
Err(error) => ("denied", format!("{}: {}", error.code, error.message)),
|
||||
};
|
||||
if let Ok(mut audit) = self.audit.lock() {
|
||||
audit.push(CapabilityAudit {
|
||||
package: package.to_string(),
|
||||
capability: capability.to_string(),
|
||||
decision,
|
||||
reason,
|
||||
});
|
||||
}
|
||||
result.map(|()| Vec::new())
|
||||
}
|
||||
|
||||
fn decide(&self, package: &str, capability: &str, request: &[u8]) -> Result<(), PluginError> {
|
||||
match capability {
|
||||
"console" => self
|
||||
.capabilities
|
||||
.console
|
||||
.then_some(())
|
||||
.ok_or_else(|| plugin_denied("console capability was not granted")),
|
||||
"math.compute" => self
|
||||
.capabilities
|
||||
.math
|
||||
.then_some(())
|
||||
.ok_or_else(|| plugin_denied("math capability was not granted")),
|
||||
"log" | "clock" | "random" | "artifact.record" => Ok(()),
|
||||
"fs.read" | "fs.write" => {
|
||||
let path = request_path(request)?;
|
||||
if capability == "fs.read" {
|
||||
self.capabilities
|
||||
.check_read(&path, None)
|
||||
.map_err(map_runtime)
|
||||
} else {
|
||||
self.capabilities
|
||||
.check_write(&path, None)
|
||||
.map_err(map_runtime)
|
||||
}
|
||||
}
|
||||
"net.request" => {
|
||||
let host = request_host(request)?;
|
||||
self.capabilities
|
||||
.check_net(&host, None)
|
||||
.map_err(map_runtime)
|
||||
}
|
||||
"process" => self
|
||||
.capabilities
|
||||
.process
|
||||
.then_some(())
|
||||
.ok_or_else(|| plugin_denied("process capability was not granted")),
|
||||
other => {
|
||||
if is_vendor_capability(other)
|
||||
&& (self.vendor_policy.contains(other) || self.vendor_policy.contains("*"))
|
||||
{
|
||||
Ok(())
|
||||
} else if is_vendor_capability(other) {
|
||||
Err(PluginError::capability(
|
||||
"capability.unavailable",
|
||||
format!(
|
||||
"vendor capability `{other}` has no trusted handler for package `{package}`"
|
||||
),
|
||||
))
|
||||
} else {
|
||||
Err(PluginError::capability(
|
||||
"capability.unknown",
|
||||
format!("unknown core capability `{other}`"),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_denied(message: &str) -> PluginError {
|
||||
PluginError::capability("permission.denied", message.to_string())
|
||||
}
|
||||
|
||||
fn map_runtime(error: RuntimeError) -> PluginError {
|
||||
PluginError::capability(error.code(), error.message)
|
||||
}
|
||||
|
||||
fn request_json(request: &[u8]) -> Result<serde_json::Value, PluginError> {
|
||||
if request.is_empty() {
|
||||
return Ok(serde_json::Value::Null);
|
||||
}
|
||||
serde_json::from_slice(request).map_err(|error| {
|
||||
PluginError::capability(
|
||||
"capability.request_invalid",
|
||||
format!("capability request is not valid JSON: {error}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn request_path(request: &[u8]) -> Result<String, PluginError> {
|
||||
let value = request_json(request)?;
|
||||
value
|
||||
.get("path")
|
||||
.and_then(|path| path.as_str())
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| {
|
||||
PluginError::capability(
|
||||
"capability.request_invalid",
|
||||
"fs capability requests must include a `path` string",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn request_host(request: &[u8]) -> Result<String, PluginError> {
|
||||
let value = request_json(request)?;
|
||||
value
|
||||
.get("host")
|
||||
.and_then(|host| host.as_str())
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| {
|
||||
PluginError::capability(
|
||||
"capability.request_invalid",
|
||||
"net capability requests must include a `host` string",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `name` is a syntactically valid vendor-namespaced capability.
|
||||
pub 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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Effective capability grants for one run.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Capabilities {
|
||||
@@ -182,6 +386,33 @@ mod tests {
|
||||
assert!(capabilities.check_foreign(None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_enforces_core_grants_and_vendor_policy() {
|
||||
let mut broker = CapabilityBroker::new(Capabilities::project().allow_read("data/**"));
|
||||
assert!(broker
|
||||
.authorize("demo.solver", "fs.read", br#"{"path":"data/a.csv"}"#)
|
||||
.is_ok());
|
||||
let denied = broker
|
||||
.authorize("demo.solver", "fs.read", br#"{"path":"secrets/key"}"#)
|
||||
.unwrap_err();
|
||||
assert_eq!(denied.code, "permission.denied");
|
||||
assert!(broker.authorize("demo.solver", "fs.read", b"{}").is_err());
|
||||
let unavailable = broker
|
||||
.authorize("demo.solver", "vendor.device.read", b"{}")
|
||||
.unwrap_err();
|
||||
assert_eq!(unavailable.code, "capability.unavailable");
|
||||
broker.allow_vendor("vendor.device.read");
|
||||
assert!(broker
|
||||
.authorize("demo.solver", "vendor.device.read", b"{}")
|
||||
.is_ok());
|
||||
assert!(!is_vendor_capability("vendor"));
|
||||
assert!(!is_vendor_capability("fs.read.extra"));
|
||||
let audit = broker.audit();
|
||||
let audit = audit.lock().unwrap();
|
||||
assert_eq!(audit.len(), 5);
|
||||
assert!(audit.iter().any(|entry| entry.decision == "denied"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_grants_are_glob_scoped() {
|
||||
let capabilities = Capabilities::project()
|
||||
|
||||
+115
-57
@@ -4,6 +4,8 @@
|
||||
//! calls [`Host::invoke`]. Authorization is checked here, at the point of
|
||||
//! execution, not at parse/compile time.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use marqdo_plugin_abi::{ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginManifest};
|
||||
@@ -11,7 +13,7 @@ use marqdo_span::Span;
|
||||
use marqdo_value::{ErrorCategory, RuntimeError, Value};
|
||||
|
||||
use crate::budget::Budget;
|
||||
use crate::capability::Capabilities;
|
||||
use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker};
|
||||
use crate::context::ExecutionContext;
|
||||
use crate::fs::ProjectFs;
|
||||
use crate::trace::{EffectTrace, TraceEntry};
|
||||
@@ -111,15 +113,23 @@ pub struct StdHost {
|
||||
pub kernel_registry: marqdo_foreign::KernelRegistry,
|
||||
output: Vec<u8>,
|
||||
trace_id: u64,
|
||||
/// Explicitly trusted, in-process native plugins keyed by namespace.
|
||||
/// Explicitly trusted, in-process native plugins.
|
||||
plugins: Vec<PluginSlot>,
|
||||
/// Complete export name -> index into `plugins` (ADR-0010).
|
||||
plugin_exports: BTreeMap<String, usize>,
|
||||
/// Trusted vendor capability policy entries for the broker.
|
||||
vendor_capabilities: BTreeSet<String>,
|
||||
/// Shared audit log for plugin capability requests.
|
||||
broker_audit: Arc<Mutex<Vec<CapabilityAudit>>>,
|
||||
}
|
||||
|
||||
struct PluginSlot {
|
||||
/// Call namespace (prefix of the export name, e.g. `solver`).
|
||||
namespace: String,
|
||||
/// Package name used for capability grants.
|
||||
package: String,
|
||||
/// Artifact/manifest digest that produced this registration.
|
||||
manifest_digest: String,
|
||||
/// Complete export name -> declared signature.
|
||||
exports: BTreeMap<String, String>,
|
||||
plugin: LoadedPlugin,
|
||||
}
|
||||
|
||||
@@ -147,6 +157,9 @@ impl StdHost {
|
||||
output: Vec::new(),
|
||||
trace_id,
|
||||
plugins: Vec::new(),
|
||||
plugin_exports: BTreeMap::new(),
|
||||
vendor_capabilities: BTreeSet::new(),
|
||||
broker_audit: Arc::new(Mutex::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,14 +167,15 @@ impl StdHost {
|
||||
///
|
||||
/// In-process native code shares the host address space and is **not**
|
||||
/// sandboxed; this build has no isolated worker transport. The caller must
|
||||
/// pass `trusted = true` and grant the plugin capability. Returns the call
|
||||
/// namespace derived from the plugin's export names.
|
||||
/// pass `trusted = true` and grant the plugin capability. Every export is
|
||||
/// registered by its complete dotted name (ADR-0010); the whole load is
|
||||
/// rejected atomically if any name conflicts.
|
||||
pub fn load_plugin(
|
||||
&mut self,
|
||||
manifest: &PluginManifest,
|
||||
base_dir: &std::path::Path,
|
||||
trusted: bool,
|
||||
) -> Result<String, RuntimeError> {
|
||||
) -> Result<Vec<String>, RuntimeError> {
|
||||
if !trusted {
|
||||
let mut error = RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
@@ -177,35 +191,87 @@ impl StdHost {
|
||||
self.capabilities
|
||||
.check_plugin(&manifest.plugin.name, None)?;
|
||||
manifest.validate().map_err(map_plugin_error)?;
|
||||
let namespace = manifest
|
||||
.plugin
|
||||
.exports
|
||||
.first()
|
||||
.and_then(|export| {
|
||||
export
|
||||
.name
|
||||
.split_once('.')
|
||||
.map(|(namespace, _)| namespace.to_string())
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
RuntimeError::new(
|
||||
let mut exports = BTreeMap::new();
|
||||
for export in &manifest.plugin.exports {
|
||||
if !export.name.contains('.') {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PluginAbi,
|
||||
None,
|
||||
"plugin manifest declares no namespaced exports",
|
||||
)
|
||||
})?;
|
||||
let loaded = LoadedPlugin::open_with(
|
||||
manifest,
|
||||
base_dir,
|
||||
marqdo_plugin_abi::LoadOptions::default(),
|
||||
)
|
||||
.map_err(map_plugin_error)?;
|
||||
format!("plugin export `{}` must be namespaced", export.name),
|
||||
));
|
||||
}
|
||||
if self.plugin_exports.contains_key(&export.name) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PluginFailure,
|
||||
None,
|
||||
format!(
|
||||
"plugin export `{}` is already registered by another plugin",
|
||||
export.name
|
||||
),
|
||||
));
|
||||
}
|
||||
exports.insert(export.name.clone(), export.signature.clone());
|
||||
}
|
||||
let artifact = manifest
|
||||
.resolve_artifact(&marqdo_plugin_abi::HostTarget::current())
|
||||
.map_err(map_plugin_error)?;
|
||||
let manifest_digest = artifact.sha256.clone();
|
||||
let mut broker =
|
||||
CapabilityBroker::with_audit(self.capabilities.clone(), Arc::clone(&self.broker_audit));
|
||||
for capability in &self.vendor_capabilities {
|
||||
broker.allow_vendor(capability.clone());
|
||||
}
|
||||
let package = manifest.plugin.name.clone();
|
||||
let options = marqdo_plugin_abi::LoadOptions {
|
||||
host_target: marqdo_plugin_abi::HostTarget::current(),
|
||||
capability_handler: Some(Box::new(move |capability, request| {
|
||||
broker.authorize(&package, capability, request)
|
||||
})),
|
||||
};
|
||||
let loaded =
|
||||
LoadedPlugin::open_with(manifest, base_dir, options).map_err(map_plugin_error)?;
|
||||
let index = self.plugins.len();
|
||||
self.plugins.push(PluginSlot {
|
||||
namespace: namespace.clone(),
|
||||
package: manifest.plugin.name.clone(),
|
||||
manifest_digest,
|
||||
exports: exports.clone(),
|
||||
plugin: loaded,
|
||||
});
|
||||
Ok(namespace)
|
||||
let names: Vec<String> = exports.keys().cloned().collect();
|
||||
for name in &names {
|
||||
self.plugin_exports.insert(name.clone(), index);
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// Trust a vendor capability for future plugin loads.
|
||||
pub fn allow_vendor_capability(&mut self, capability: impl Into<String>) {
|
||||
self.vendor_capabilities.insert(capability.into());
|
||||
}
|
||||
|
||||
/// Registered plugin exports as `(complete name, signature, digest, package)`.
|
||||
pub fn plugin_exports(&self) -> Vec<(String, String, String, String)> {
|
||||
let mut exports = Vec::new();
|
||||
for slot in &self.plugins {
|
||||
for (name, signature) in &slot.exports {
|
||||
exports.push((
|
||||
name.clone(),
|
||||
signature.clone(),
|
||||
slot.manifest_digest.clone(),
|
||||
slot.package.clone(),
|
||||
));
|
||||
}
|
||||
}
|
||||
exports.sort();
|
||||
exports
|
||||
}
|
||||
|
||||
/// Audited plugin capability decisions.
|
||||
pub fn capability_audit(&self) -> Vec<CapabilityAudit> {
|
||||
self.broker_audit
|
||||
.lock()
|
||||
.map(|audit| audit.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Register an explicit external foreign-kernel provider.
|
||||
@@ -300,46 +366,38 @@ impl StdHost {
|
||||
args: Vec<Value>,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
if args.len() != 3 {
|
||||
return Err(arity(ctx.span, "plugin.invoke", 3, args.len()));
|
||||
if args.len() != 2 {
|
||||
return Err(arity(ctx.span, "plugin.invoke", 2, args.len()));
|
||||
}
|
||||
let Value::Text(namespace) = &args[0] else {
|
||||
let Value::Text(export_name) = &args[0] else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
"plugin namespace must be Text",
|
||||
"plugin export name must be Text",
|
||||
));
|
||||
};
|
||||
let Value::Text(export) = &args[1] else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
"plugin export must be Text",
|
||||
));
|
||||
};
|
||||
let Value::Map(named_args) = &args[2] else {
|
||||
let Value::Map(named_args) = &args[1] else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
"plugin call arguments must be named",
|
||||
));
|
||||
};
|
||||
let slot = self
|
||||
.plugins
|
||||
.iter_mut()
|
||||
.find(|slot| &slot.namespace == namespace)
|
||||
.ok_or_else(|| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
ctx.span,
|
||||
format!("no plugin namespace `{namespace}` is loaded"),
|
||||
)
|
||||
})?;
|
||||
self.capabilities
|
||||
.check_plugin(&slot.package.clone(), ctx.span)?;
|
||||
let function = format!("{namespace}.{export}");
|
||||
let mut request = marqdo_plugin_abi::WireRequest::new(function.clone());
|
||||
let Some(index) = self.plugin_exports.get(export_name).copied() else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::UnknownSymbol,
|
||||
ctx.span,
|
||||
format!("no plugin export `{export_name}` is loaded"),
|
||||
));
|
||||
};
|
||||
let package = self.plugins[index].package.clone();
|
||||
self.capabilities.check_plugin(&package, ctx.span)?;
|
||||
let mut request = marqdo_plugin_abi::WireRequest::new(export_name.clone());
|
||||
for (name, value) in named_args {
|
||||
request = request.with_arg(name.clone(), value);
|
||||
}
|
||||
let response = slot.plugin.invoke(&request).map_err(map_plugin_error)?;
|
||||
let response = self.plugins[index]
|
||||
.plugin
|
||||
.invoke(&request)
|
||||
.map_err(map_plugin_error)?;
|
||||
let value = response.typed_value().map_err(map_plugin_error)?;
|
||||
Ok(value.unwrap_or(Value::Unit))
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user