feat(plugin): bridge worker capability requests to the host broker (H3-A)
- add request-scoped capability_request/capability_reply/capability_error frames to the worker transport (ADR-0018); no C ABI change - worker routes its capability handler through stdin/stdout, the host serves requests inside the existing invoke deadline and binds identity from the spawned worker, never from frame text - both native and worker plugins now execute a granted fs.read through ProjectFs with audit; unsupported capabilities return capability.unavailable - add a real C capability plugin and CLI test for granted read and denial - document the bridge and that strict OS isolation (H3-B) is still refused
This commit is contained in:
1 parent
47a2e1883f
commit
0f01a69048
11 files changed
+720
-64
No files matched your search
@@ -284,9 +284,25 @@ impl StdHost {
|
||||
.map_err(map_plugin_error)?,
|
||||
)
|
||||
}
|
||||
PluginKind::Worker => PluginTransport::Worker(
|
||||
WorkerPlugin::spawn(manifest, base_dir).map_err(map_plugin_error)?,
|
||||
),
|
||||
PluginKind::Worker => {
|
||||
let mut broker = CapabilityBroker::with_audit(
|
||||
self.capabilities.clone(),
|
||||
Arc::clone(&self.broker_audit),
|
||||
)
|
||||
.with_fs(self.fs.clone());
|
||||
for capability in &self.vendor_capabilities {
|
||||
broker.allow_vendor(capability.clone());
|
||||
}
|
||||
let package = manifest.plugin.name.clone();
|
||||
let handler: marqdo_plugin_abi::CapabilityHandler =
|
||||
Box::new(move |capability, request| {
|
||||
broker.execute(&package, capability, request)
|
||||
});
|
||||
PluginTransport::Worker(
|
||||
WorkerPlugin::spawn(manifest, base_dir, Some(handler))
|
||||
.map_err(map_plugin_error)?,
|
||||
)
|
||||
}
|
||||
PluginKind::Wasm => {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::KernelUnavailable,
|
||||
|
||||
@@ -13,7 +13,9 @@ use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use marqdo_plugin_abi::worker::{read_frame, write_frame, WORKER_COMMAND};
|
||||
use marqdo_plugin_abi::{PluginError, PluginManifest, WireRequest, WireResponse};
|
||||
use marqdo_plugin_abi::{
|
||||
CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
/// A native plugin running in an isolated worker process.
|
||||
@@ -23,6 +25,7 @@ pub struct WorkerPlugin {
|
||||
frames: Receiver<Result<serde_json::Value, PluginError>>,
|
||||
exports: BTreeMap<String, String>,
|
||||
dead: bool,
|
||||
capability_handler: Option<CapabilityHandler>,
|
||||
}
|
||||
|
||||
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
@@ -39,7 +42,11 @@ impl std::fmt::Debug for WorkerPlugin {
|
||||
|
||||
impl WorkerPlugin {
|
||||
/// Spawn a worker for `manifest` and wait for its ready frame.
|
||||
pub fn spawn(manifest: &PluginManifest, base_dir: &Path) -> Result<Self, PluginError> {
|
||||
pub fn spawn(
|
||||
manifest: &PluginManifest,
|
||||
base_dir: &Path,
|
||||
capability_handler: Option<CapabilityHandler>,
|
||||
) -> Result<Self, PluginError> {
|
||||
// The worker receives an explicit serialized manifest, so it does not
|
||||
// depend on the manifest file being named `plugin.yaml`.
|
||||
let manifest_path = std::env::temp_dir().join(format!(
|
||||
@@ -185,6 +192,7 @@ impl WorkerPlugin {
|
||||
frames,
|
||||
exports,
|
||||
dead: false,
|
||||
capability_handler,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -205,42 +213,110 @@ impl WorkerPlugin {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
}
|
||||
let frame = match self.frames.recv_timeout(CALL_TIMEOUT) {
|
||||
Ok(Ok(frame)) => frame,
|
||||
Ok(Err(error)) => {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
}
|
||||
Err(_) => {
|
||||
let deadline = std::time::Instant::now() + CALL_TIMEOUT;
|
||||
loop {
|
||||
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
|
||||
if remaining.is_zero() {
|
||||
self.mark_dead();
|
||||
return Err(PluginError::invoke(
|
||||
"plugin.timeout",
|
||||
"plugin worker exceeded its invocation timeout",
|
||||
));
|
||||
}
|
||||
};
|
||||
match frame.get("kind").and_then(serde_json::Value::as_str) {
|
||||
Some("response") => marqdo_plugin_abi::worker::response_from_frame(&frame),
|
||||
Some("error") => Err(PluginError::invoke(
|
||||
frame
|
||||
.get("code")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("plugin_call_failed"),
|
||||
frame
|
||||
.get("message")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("worker reported an error"),
|
||||
)),
|
||||
_ => {
|
||||
self.mark_dead();
|
||||
Err(PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
"plugin worker closed or violated the frame protocol",
|
||||
))
|
||||
let frame = match self.frames.recv_timeout(remaining) {
|
||||
Ok(Ok(frame)) => frame,
|
||||
Ok(Err(error)) => {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
}
|
||||
Err(_) => {
|
||||
self.mark_dead();
|
||||
return Err(PluginError::invoke(
|
||||
"plugin.timeout",
|
||||
"plugin worker exceeded its invocation timeout",
|
||||
));
|
||||
}
|
||||
};
|
||||
match frame.get("kind").and_then(serde_json::Value::as_str) {
|
||||
Some("capability_request") => {
|
||||
if let Err(error) = self.handle_capability_request(&frame) {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Some("response") => {
|
||||
return marqdo_plugin_abi::worker::response_from_frame(&frame);
|
||||
}
|
||||
Some("error") => {
|
||||
return Err(PluginError::invoke(
|
||||
frame
|
||||
.get("code")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("plugin_call_failed"),
|
||||
frame
|
||||
.get("message")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("worker reported an error"),
|
||||
))
|
||||
}
|
||||
_ => {
|
||||
self.mark_dead();
|
||||
return Err(PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
"plugin worker closed or violated the frame protocol",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_capability_request(&mut self, frame: &serde_json::Value) -> Result<(), PluginError> {
|
||||
let id = frame
|
||||
.get("id")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.ok_or_else(|| {
|
||||
PluginError::wire("worker_frame_invalid", "capability request has no id")
|
||||
})?;
|
||||
let capability = frame
|
||||
.get("capability")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.ok_or_else(|| {
|
||||
PluginError::wire("worker_frame_invalid", "capability request has no name")
|
||||
})?;
|
||||
let request_value = frame.get("request").cloned().unwrap_or_else(|| json!({}));
|
||||
let request_bytes = serde_json::to_vec(&request_value)
|
||||
.map_err(|error| PluginError::wire("worker_encode_failed", error.to_string()))?;
|
||||
let result = match &mut self.capability_handler {
|
||||
Some(handler) => handler(capability, &request_bytes),
|
||||
None => Err(PluginError::capability(
|
||||
"capability.unavailable",
|
||||
"this worker has no host capability bridge",
|
||||
)),
|
||||
};
|
||||
let reply = match result {
|
||||
Ok(data) => match String::from_utf8(data) {
|
||||
Ok(data) => json!({"kind":"capability_reply","id":id,"data":data}),
|
||||
Err(_) => json!({
|
||||
"kind":"capability_error",
|
||||
"id":id,
|
||||
"code":"capability.reply_invalid",
|
||||
"message":"capability reply is not UTF-8 text",
|
||||
}),
|
||||
},
|
||||
Err(error) => json!({
|
||||
"kind":"capability_error",
|
||||
"id":id,
|
||||
"code":error.code,
|
||||
"message":error.message,
|
||||
}),
|
||||
};
|
||||
if let Err(error) = write_frame(&mut self.stdin, &reply) {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mark_dead(&mut self) {
|
||||
self.dead = true;
|
||||
let _ = self.child.kill();
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! End-to-end native plugin capability execution (H3-A).
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use marqdo_host::{Capabilities, Host, HostOp, StdHost};
|
||||
use marqdo_plugin_abi::{sha256_file, HostTarget, PluginManifest};
|
||||
use marqdo_sandbox::SandboxMode;
|
||||
use marqdo_value::{ErrorCategory, Value};
|
||||
|
||||
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new() -> Self {
|
||||
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"marqdo-host-capability-{}-{id}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn repo_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
fn have_cc() -> bool {
|
||||
Command::new("cc")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.map(|output| output.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn build_plugin(dir: &Path) -> PathBuf {
|
||||
let output = dir.join("capability.so");
|
||||
let status = Command::new("cc")
|
||||
.args(["-std=c11", "-O2", "-shared", "-fPIC"])
|
||||
.arg("-I")
|
||||
.arg(repo_root().join("include"))
|
||||
.arg(repo_root().join("tests/abi/capability_plugin.c"))
|
||||
.arg("-o")
|
||||
.arg(&output)
|
||||
.status()
|
||||
.expect("spawn cc");
|
||||
assert!(status.success(), "cc failed");
|
||||
output
|
||||
}
|
||||
|
||||
fn write_manifest(dir: &Path, sha: &str) {
|
||||
let yaml = format!(
|
||||
r#"plugin:
|
||||
name: demo.capability
|
||||
version: 0.1.0
|
||||
abi: "^1.0"
|
||||
kind: native
|
||||
exports:
|
||||
- name: capability.read
|
||||
signature: "() -> Text"
|
||||
requires:
|
||||
- fs.read
|
||||
artifacts:
|
||||
- target: {}
|
||||
file: capability.so
|
||||
sha256: "{}"
|
||||
"#,
|
||||
HostTarget::current().triple(),
|
||||
sha
|
||||
);
|
||||
std::fs::write(dir.join("plugin.yaml"), yaml).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn granted_fs_read_returns_real_bytes_and_denial_is_audited() {
|
||||
if !have_cc() {
|
||||
eprintln!("skipping: cc is unavailable");
|
||||
return;
|
||||
}
|
||||
let dir = TempDir::new();
|
||||
std::fs::create_dir_all(dir.path().join("data")).unwrap();
|
||||
std::fs::write(dir.path().join("data/allowed.txt"), "hello-from-project").unwrap();
|
||||
let artifact = build_plugin(dir.path());
|
||||
write_manifest(dir.path(), &sha256_file(&artifact).unwrap());
|
||||
let manifest = PluginManifest::load(&dir.path().join("plugin.yaml")).unwrap();
|
||||
|
||||
let capabilities = Capabilities::project()
|
||||
.allow_plugin("demo.capability")
|
||||
.allow_read("data/**");
|
||||
let mut host = StdHost::new(SandboxMode::Project, capabilities, dir.path());
|
||||
host.load_plugin(&manifest, dir.path(), true).unwrap();
|
||||
let ctx = host.context("root:default::test.mq.md", None);
|
||||
let value = host
|
||||
.invoke(
|
||||
HostOp::PluginInvoke,
|
||||
vec![
|
||||
Value::Text("capability.read".into()),
|
||||
Value::Map(Default::default()),
|
||||
],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap_or_else(|error| panic!("{error:?} audit={:?}", host.capability_audit()));
|
||||
assert_eq!(value, Value::Text("hello-from-project".into()));
|
||||
|
||||
let audit = host.capability_audit();
|
||||
assert!(
|
||||
audit
|
||||
.iter()
|
||||
.any(|entry| entry.capability == "fs.read" && entry.decision == "granted"),
|
||||
"{audit:?}"
|
||||
);
|
||||
assert!(
|
||||
!format!("{audit:?}").contains("hello-from-project"),
|
||||
"audit must not record file contents"
|
||||
);
|
||||
|
||||
// Same load, but no read grant: the broker must not return bytes.
|
||||
let capabilities = Capabilities::project().allow_plugin("demo.capability");
|
||||
let mut denied_host = StdHost::new(SandboxMode::Project, capabilities, dir.path());
|
||||
denied_host
|
||||
.load_plugin(&manifest, dir.path(), true)
|
||||
.unwrap();
|
||||
let ctx = denied_host.context("root:default::test.mq.md", None);
|
||||
let error = denied_host
|
||||
.invoke(
|
||||
HostOp::PluginInvoke,
|
||||
vec![
|
||||
Value::Text("capability.read".into()),
|
||||
Value::Map(Default::default()),
|
||||
],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
let audit = denied_host.capability_audit();
|
||||
assert!(
|
||||
audit
|
||||
.iter()
|
||||
.any(|entry| entry.capability == "fs.read" && entry.decision == "denied"),
|
||||
"{audit:?}"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user