fix(plugin): bound worker capability calls per invocation (H3-A)

- enforce at most 64 capability requests and 64 KiB per serialized request
  in both the worker handler and the host bridge
- return structured capability.budget_exceeded / request_too_large errors and
  kill the worker on a host-side violation
- add a real C loop fixture and CLI test proving a runaway plugin is stopped
  without producing file contents
- update ADR-0018, plugin-abi and STATUS
This commit is contained in:
cflmy committed 2026-11-20 13:11:24 +08:00
1 parent ea41256671
commit f69c563afd
7 files changed
+101 -10

No files matched your search

+19 -2
View File
@@ -155,12 +155,13 @@ fn worker_crash_is_isolated_from_the_host() {
assert_eq!(survivor.status.code(), Some(0));
}
fn compile_capability(dir: &Path) -> PathBuf {
fn compile_capability(dir: &Path, extra: &[&str]) -> PathBuf {
let output = dir.join("capability.so");
let status = Command::new("cc")
.args(["-std=c11", "-O2", "-shared", "-fPIC"])
.arg("-I")
.arg(repo().join("include"))
.args(extra)
.arg(repo().join("tests/abi/capability_plugin.c"))
.arg("-o")
.arg(&output)
@@ -226,7 +227,7 @@ fn worker_capability_bridge_reads_granted_file_and_denies_without_grant() {
return;
}
let dir = TempDir::new("capability");
let artifact = compile_capability(dir.path());
let artifact = compile_capability(dir.path(), &[]);
write_capability_manifest(dir.path(), &sha256_file(&artifact).unwrap());
let output = run_capability(dir.path(), true);
@@ -247,3 +248,19 @@ fn worker_capability_bridge_reads_granted_file_and_denies_without_grant() {
);
assert!(!String::from_utf8_lossy(&denied.stdout).contains("hello-worker"));
}
#[test]
fn worker_capability_request_budget_stops_a_runaway_plugin() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("capability-budget");
let artifact = compile_capability(dir.path(), &["-DMQ_CAPABILITY_LOOP"]);
write_capability_manifest(dir.path(), &sha256_file(&artifact).unwrap());
let output = run_capability(dir.path(), true);
assert_eq!(output.status.code(), Some(1));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("capability.budget_exceeded"), "{stderr}");
assert!(!String::from_utf8_lossy(&output.stdout).contains("hello-worker"));
}
+23 -1
View File
@@ -12,7 +12,9 @@ use std::sync::mpsc::{self, Receiver};
use std::thread;
use std::time::Duration;
use marqdo_plugin_abi::worker::{read_frame, write_frame, WORKER_COMMAND};
use marqdo_plugin_abi::worker::{
read_frame, write_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, WORKER_COMMAND,
};
use marqdo_plugin_abi::{
CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse,
};
@@ -214,6 +216,7 @@ impl WorkerPlugin {
return Err(error);
}
let deadline = std::time::Instant::now() + CALL_TIMEOUT;
let mut capability_requests = 0usize;
loop {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
if remaining.is_zero() {
@@ -239,6 +242,16 @@ impl WorkerPlugin {
};
match frame.get("kind").and_then(serde_json::Value::as_str) {
Some("capability_request") => {
capability_requests += 1;
if capability_requests > MAX_CAPABILITY_REQUESTS {
self.mark_dead();
return Err(PluginError::capability(
"capability.budget_exceeded",
format!(
"plugin exceeded the limit of {MAX_CAPABILITY_REQUESTS} capability requests per invocation"
),
));
}
if let Err(error) = self.handle_capability_request(&frame) {
self.mark_dead();
return Err(error);
@@ -286,6 +299,15 @@ impl WorkerPlugin {
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()))?;
if request_bytes.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_bytes.len()
),
));
}
let result = match &mut self.capability_handler {
Some(handler) => handler(capability, &request_bytes),
None => Err(PluginError::capability(
+29 -4
View File
@@ -8,7 +8,7 @@
use std::io::{Read, Write};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use serde_json::{json, Value};
@@ -22,6 +22,10 @@ use crate::wire::{WireRequest, WireResponse};
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).
///
@@ -123,12 +127,31 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
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 capability_handler: crate::loader::CapabilityHandler =
Box::new(move |capability, request| {
let handler_calls = Arc::clone(&capability_calls);
let capability_handler: crate::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(
@@ -201,7 +224,8 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
)),
}
}
});
},
);
let options = LoadOptions {
host_target: crate::artifact::HostTarget::current(),
capability_handler: Some(capability_handler),
@@ -259,6 +283,7 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
continue;
}
};
capability_calls.store(0, Ordering::SeqCst);
match plugin.invoke(&request) {
Ok(response) => {
let body = response
+3 -2
View File
@@ -212,8 +212,9 @@ Foreign provider integrity and environment metadata:
return `capability.unavailable` rather than empty success. Worker
request/reply frames are request-scoped and carry no trusted identity
(ADR-0018).
* H3-A remains open for live ABI session identity, resource budgets per
capability call, and broader executing services. H3-B (OS isolation) remains
* Per-invocation capability budgets are enforced in both the worker handler
and the host: 64 requests and 64 KiB per request. H3-A remains open for live
ABI session identity and broader executing services. H3-B (OS isolation) remains
open; `strict` is refused on every platform and no G-C claim is made.
### M0.6 implementation progress
@@ -54,6 +54,11 @@ Rules:
single deadline for the whole `invoke`, including capability round-trips.
* Only the broker's executing capabilities are reachable. In this build that
means `fs.read`; everything else returns `capability.unavailable`.
* Budgets: at most 64 capability requests per invocation and 64 KiB per
serialized request. Exceeding either returns
`capability.budget_exceeded`/`capability.request_too_large`; the worker-side
handler and the host both enforce the limits, and a host violation kills the
worker.
* The frames do not change the C ABI or `MqHostApi`. They are an internal IPC
protocol between the host and its own worker binary.
+4 -1
View File
@@ -390,7 +390,10 @@ The id must match and is request-scoped; requests carry no trusted identity
unknown/mismatched ids, non-text replies and other frame kinds are protocol
errors. The invoke deadline covers the whole exchange. In this build only
granted `fs.read` executes; other capabilities return `capability.unavailable`.
These frames do not change the C ABI.
At most 64 capability requests per invocation and 64 KiB per serialized
request; exceeding either is `capability.budget_exceeded`/`request_too_large`.
Both the worker handler and the host enforce the limits (the host kills the
worker on a violation). These frames do not change the C ABI.
## 10. SDK usage (`crates/marqdo-plugin-sdk`)
+18
View File
@@ -51,6 +51,24 @@ static int32_t capability_read(MqCallContext *ctx, MqBytes args_wire,
name.len = sizeof("fs.read") - 1;
request.data = (const uint8_t *)PATH_REQUEST;
request.len = strlen(PATH_REQUEST);
#ifdef MQ_CAPABILITY_LOOP
for (int i = 0; i < 100; i++) {
MqOwnedBytes loop_reply = {NULL, 0};
code = g_host->request_capability(ctx, name, request, &loop_reply);
if (loop_reply.data != NULL) {
g_host->free(g_host->host_data, loop_reply.data);
}
if (code != MQ_OK) {
static const char BUDGET_JSON[] =
"{\"wire_version\":1,\"kind\":\"response\",\"error\":"
"{\"kind\":\"capability\",\"code\":\"capability.budget_exceeded\","
"\"message\":\"capability request budget exceeded\"}}";
return emit(BUDGET_JSON, sizeof(BUDGET_JSON) - 1, error_wire) == MQ_OK
? code
: MQ_ERR_OUT_OF_MEMORY;
}
}
#endif
code = g_host->request_capability(ctx, name, request, &reply);
if (code != MQ_OK) {
static const char ERROR_JSON[] =