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:
1 parent
ea41256671
commit
f69c563afd
7 files changed
+101
-10
No files matched your search
@@ -155,12 +155,13 @@ fn worker_crash_is_isolated_from_the_host() {
|
|||||||
assert_eq!(survivor.status.code(), Some(0));
|
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 output = dir.join("capability.so");
|
||||||
let status = Command::new("cc")
|
let status = Command::new("cc")
|
||||||
.args(["-std=c11", "-O2", "-shared", "-fPIC"])
|
.args(["-std=c11", "-O2", "-shared", "-fPIC"])
|
||||||
.arg("-I")
|
.arg("-I")
|
||||||
.arg(repo().join("include"))
|
.arg(repo().join("include"))
|
||||||
|
.args(extra)
|
||||||
.arg(repo().join("tests/abi/capability_plugin.c"))
|
.arg(repo().join("tests/abi/capability_plugin.c"))
|
||||||
.arg("-o")
|
.arg("-o")
|
||||||
.arg(&output)
|
.arg(&output)
|
||||||
@@ -226,7 +227,7 @@ fn worker_capability_bridge_reads_granted_file_and_denies_without_grant() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let dir = TempDir::new("capability");
|
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());
|
write_capability_manifest(dir.path(), &sha256_file(&artifact).unwrap());
|
||||||
|
|
||||||
let output = run_capability(dir.path(), true);
|
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"));
|
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"));
|
||||||
|
}
|
||||||
@@ -12,7 +12,9 @@ use std::sync::mpsc::{self, Receiver};
|
|||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::Duration;
|
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::{
|
use marqdo_plugin_abi::{
|
||||||
CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse,
|
CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse,
|
||||||
};
|
};
|
||||||
@@ -214,6 +216,7 @@ impl WorkerPlugin {
|
|||||||
return Err(error);
|
return Err(error);
|
||||||
}
|
}
|
||||||
let deadline = std::time::Instant::now() + CALL_TIMEOUT;
|
let deadline = std::time::Instant::now() + CALL_TIMEOUT;
|
||||||
|
let mut capability_requests = 0usize;
|
||||||
loop {
|
loop {
|
||||||
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
|
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
|
||||||
if remaining.is_zero() {
|
if remaining.is_zero() {
|
||||||
@@ -239,6 +242,16 @@ impl WorkerPlugin {
|
|||||||
};
|
};
|
||||||
match frame.get("kind").and_then(serde_json::Value::as_str) {
|
match frame.get("kind").and_then(serde_json::Value::as_str) {
|
||||||
Some("capability_request") => {
|
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) {
|
if let Err(error) = self.handle_capability_request(&frame) {
|
||||||
self.mark_dead();
|
self.mark_dead();
|
||||||
return Err(error);
|
return Err(error);
|
||||||
@@ -286,6 +299,15 @@ impl WorkerPlugin {
|
|||||||
let request_value = frame.get("request").cloned().unwrap_or_else(|| json!({}));
|
let request_value = frame.get("request").cloned().unwrap_or_else(|| json!({}));
|
||||||
let request_bytes = serde_json::to_vec(&request_value)
|
let request_bytes = serde_json::to_vec(&request_value)
|
||||||
.map_err(|error| PluginError::wire("worker_encode_failed", error.to_string()))?;
|
.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 {
|
let result = match &mut self.capability_handler {
|
||||||
Some(handler) => handler(capability, &request_bytes),
|
Some(handler) => handler(capability, &request_bytes),
|
||||||
None => Err(PluginError::capability(
|
None => Err(PluginError::capability(
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
|
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
@@ -22,6 +22,10 @@ use crate::wire::{WireRequest, WireResponse};
|
|||||||
pub const WORKER_COMMAND: &str = "__plugin-worker";
|
pub const WORKER_COMMAND: &str = "__plugin-worker";
|
||||||
/// Maximum frame size accepted by either side.
|
/// Maximum frame size accepted by either side.
|
||||||
pub const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
|
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).
|
/// 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 stdin = Arc::new(Mutex::new(std::io::stdin()));
|
||||||
let stdout = Arc::new(Mutex::new(std::io::stdout()));
|
let stdout = Arc::new(Mutex::new(std::io::stdout()));
|
||||||
let next_request_id = Arc::new(AtomicU64::new(1));
|
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_stdin = Arc::clone(&stdin);
|
||||||
let handler_stdout = Arc::clone(&stdout);
|
let handler_stdout = Arc::clone(&stdout);
|
||||||
let handler_ids = Arc::clone(&next_request_id);
|
let handler_ids = Arc::clone(&next_request_id);
|
||||||
let capability_handler: crate::loader::CapabilityHandler =
|
let handler_calls = Arc::clone(&capability_calls);
|
||||||
Box::new(move |capability, request| {
|
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 id = handler_ids.fetch_add(1, Ordering::SeqCst);
|
||||||
let request_value: Value = serde_json::from_slice(request).map_err(|error| {
|
let request_value: Value = serde_json::from_slice(request).map_err(|error| {
|
||||||
PluginError::capability(
|
PluginError::capability(
|
||||||
@@ -201,7 +224,8 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
|
|||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
},
|
||||||
|
);
|
||||||
let options = LoadOptions {
|
let options = LoadOptions {
|
||||||
host_target: crate::artifact::HostTarget::current(),
|
host_target: crate::artifact::HostTarget::current(),
|
||||||
capability_handler: Some(capability_handler),
|
capability_handler: Some(capability_handler),
|
||||||
@@ -259,6 +283,7 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
capability_calls.store(0, Ordering::SeqCst);
|
||||||
match plugin.invoke(&request) {
|
match plugin.invoke(&request) {
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
let body = response
|
let body = response
|
||||||
|
|||||||
+3
-2
@@ -212,8 +212,9 @@ Foreign provider integrity and environment metadata:
|
|||||||
return `capability.unavailable` rather than empty success. Worker
|
return `capability.unavailable` rather than empty success. Worker
|
||||||
request/reply frames are request-scoped and carry no trusted identity
|
request/reply frames are request-scoped and carry no trusted identity
|
||||||
(ADR-0018).
|
(ADR-0018).
|
||||||
* H3-A remains open for live ABI session identity, resource budgets per
|
* Per-invocation capability budgets are enforced in both the worker handler
|
||||||
capability call, and broader executing services. H3-B (OS isolation) remains
|
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.
|
open; `strict` is refused on every platform and no G-C claim is made.
|
||||||
|
|
||||||
### M0.6 implementation progress
|
### M0.6 implementation progress
|
||||||
|
|||||||
@@ -54,6 +54,11 @@ Rules:
|
|||||||
single deadline for the whole `invoke`, including capability round-trips.
|
single deadline for the whole `invoke`, including capability round-trips.
|
||||||
* Only the broker's executing capabilities are reachable. In this build that
|
* Only the broker's executing capabilities are reachable. In this build that
|
||||||
means `fs.read`; everything else returns `capability.unavailable`.
|
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
|
* The frames do not change the C ABI or `MqHostApi`. They are an internal IPC
|
||||||
protocol between the host and its own worker binary.
|
protocol between the host and its own worker binary.
|
||||||
|
|
||||||
|
|||||||
+4
-1
@@ -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
|
unknown/mismatched ids, non-text replies and other frame kinds are protocol
|
||||||
errors. The invoke deadline covers the whole exchange. In this build only
|
errors. The invoke deadline covers the whole exchange. In this build only
|
||||||
granted `fs.read` executes; other capabilities return `capability.unavailable`.
|
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`)
|
## 10. SDK usage (`crates/marqdo-plugin-sdk`)
|
||||||
|
|
||||||
|
|||||||
@@ -51,6 +51,24 @@ static int32_t capability_read(MqCallContext *ctx, MqBytes args_wire,
|
|||||||
name.len = sizeof("fs.read") - 1;
|
name.len = sizeof("fs.read") - 1;
|
||||||
request.data = (const uint8_t *)PATH_REQUEST;
|
request.data = (const uint8_t *)PATH_REQUEST;
|
||||||
request.len = strlen(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);
|
code = g_host->request_capability(ctx, name, request, &reply);
|
||||||
if (code != MQ_OK) {
|
if (code != MQ_OK) {
|
||||||
static const char ERROR_JSON[] =
|
static const char ERROR_JSON[] =
|
||||||
|
|||||||
Reference in new issue
Block a user