feat(provider): add C ABI provider worker binding v1

- Add the separate marqdo-provider-worker binary: loads one trusted c-abi-1
  shared library and serves the ADR-0035 framed-JSON resource protocol, with
  fail-closed startup and no in-process fallback (ADR-0038).
- Reuse StdHost::register_worker_resource_provider; language still sees only
  resource.* and project-mode/name grants.
- Compile a C test provider and run open/read/write/close through the helper;
  cover missing-library fail-closed. Trusted process boundary, not a sandbox;
  existing plugin-Worker ABI binding remains open.
- Add ADR/spec/status/README/changelog/evidence; workspace member and tests.

Gate: fmt, clippy -D warnings, 440 tests passed.
This commit is contained in:
cflmy committed 2026-11-20 23:30:22 +08:00
1 parent 313ac035e8
commit 757c5ed15e
13 files changed
+562 -2

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
[package]
name = "marqdo-provider-worker"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[[bin]]
name = "marqdo-provider-worker"
path = "src/main.rs"
[dependencies]
libloading = { workspace = true }
serde_json = { workspace = true }
[dev-dependencies]
marqdo-host = { path = "../marqdo-host" }
marqdo-sandbox = { path = "../marqdo-sandbox" }
marqdo-value = { path = "../marqdo-value" }
tempfile = { workspace = true }
+261
View File
@@ -0,0 +1,261 @@
//! Trusted C ABI provider worker (ADR-0038).
//!
//! This helper loads one trusted `c-abi-1` shared library and serves the
//! ADR-0035 framed-JSON resource protocol over stdin/stdout. It is a transport
//! boundary, not a sandbox: the library runs with the worker's privileges.
use std::ffi::{c_char, CString};
use std::io::{Read, Write};
use std::path::PathBuf;
use libloading::Library;
use serde_json::{json, Value as Json};
const ABI_VERSION: u32 = 1;
const MAX_FRAME_BYTES: usize = 1024 * 1024;
const ERROR_MAX: usize = 1024;
type AbiVersionFn = unsafe extern "C" fn() -> u32;
type OpenFn = unsafe extern "C" fn(*const c_char, *const c_char, *const c_char, *mut u64) -> i32;
type ReadFn = unsafe extern "C" fn(u64, *mut u8, u32, *mut u32, *mut i32) -> i32;
type WriteFn = unsafe extern "C" fn(u64, *const u8, u32, *mut u32) -> i32;
type CloseFn = unsafe extern "C" fn(u64) -> i32;
type LastErrorFn = unsafe extern "C" fn(*mut c_char, u32) -> i32;
struct Provider {
library: Library,
}
impl Provider {
fn load(path: &PathBuf) -> Result<Self, String> {
let library = unsafe { Library::new(path) }
.map_err(|error| format!("cannot load `{}`: {error}", path.display()))?;
let version: libloading::Symbol<AbiVersionFn> = unsafe {
library
.get(b"marqdo_resource_provider_abi_version\0")
.map_err(|error| format!("missing abi_version: {error}"))?
};
if unsafe { version() } != ABI_VERSION {
return Err(format!("provider ABI is not {ABI_VERSION}"));
}
Ok(Self { library })
}
fn last_error(&self) -> String {
let Ok(symbol) = (unsafe {
self.library
.get::<LastErrorFn>(b"marqdo_resource_last_error\0")
}) else {
return "C provider failed".to_string();
};
let mut buffer = vec![0i8; ERROR_MAX];
if unsafe { symbol(buffer.as_mut_ptr(), ERROR_MAX as u32) } != 0 {
return "C provider failed".to_string();
}
let bytes = buffer
.iter()
.map(|value| *value as u8)
.take_while(|value| *value != 0)
.collect::<Vec<_>>();
String::from_utf8_lossy(&bytes).into_owned()
}
fn open(&self, kind: &str, descriptor: &str, rights: &[String]) -> Result<u64, String> {
let kind = CString::new(kind).map_err(|_| "kind has NUL".to_string())?;
let descriptor = CString::new(descriptor).map_err(|_| "descriptor has NUL".to_string())?;
let rights = CString::new(rights.join(",")).map_err(|_| "rights have NUL".to_string())?;
let symbol: libloading::Symbol<OpenFn> = unsafe {
self.library
.get(b"marqdo_resource_open\0")
.map_err(|error| format!("missing open: {error}"))?
};
let mut token = 0u64;
if unsafe {
symbol(
kind.as_ptr(),
descriptor.as_ptr(),
rights.as_ptr(),
&mut token,
)
} != 0
{
return Err(self.last_error());
}
Ok(token)
}
fn read(&self, token: u64, max_bytes: usize) -> Result<(Vec<u8>, bool), String> {
let capacity = u32::try_from(max_bytes).unwrap_or(u32::MAX);
let mut buffer = vec![0u8; capacity as usize];
let mut read = 0u32;
let mut eof = 0i32;
let symbol: libloading::Symbol<ReadFn> = unsafe {
self.library
.get(b"marqdo_resource_read\0")
.map_err(|error| format!("missing read: {error}"))?
};
if unsafe { symbol(token, buffer.as_mut_ptr(), capacity, &mut read, &mut eof) } != 0 {
return Err(self.last_error());
}
buffer.truncate(read as usize);
Ok((buffer, eof != 0))
}
fn write(&self, token: u64, bytes: &[u8]) -> Result<usize, String> {
let length = u32::try_from(bytes.len()).map_err(|_| "write too large".to_string())?;
let mut written = 0u32;
let symbol: libloading::Symbol<WriteFn> = unsafe {
self.library
.get(b"marqdo_resource_write\0")
.map_err(|error| format!("missing write: {error}"))?
};
if unsafe { symbol(token, bytes.as_ptr(), length, &mut written) } != 0 {
return Err(self.last_error());
}
Ok(written as usize)
}
fn close(&self, token: u64) -> Result<(), String> {
let symbol: libloading::Symbol<CloseFn> = unsafe {
self.library
.get(b"marqdo_resource_close\0")
.map_err(|error| format!("missing close: {error}"))?
};
if unsafe { symbol(token) } != 0 {
return Err(self.last_error());
}
Ok(())
}
}
fn read_frame() -> Result<Option<Json>, String> {
let mut header = [0u8; 4];
let mut read = 0usize;
while read < header.len() {
match std::io::stdin().read(&mut header[read..]) {
Ok(0) if read == 0 => return Ok(None),
Ok(0) => return Err("stdin ended inside a frame header".to_string()),
Ok(count) => read += count,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => return Err(format!("stdin read failed: {error}")),
}
}
let length = u32::from_be_bytes(header) as usize;
if length == 0 || length > MAX_FRAME_BYTES {
return Err(format!("invalid frame length {length}"));
}
let mut payload = vec![0u8; length];
std::io::stdin()
.read_exact(&mut payload)
.map_err(|error| format!("stdin read failed: {error}"))?;
serde_json::from_slice(&payload)
.map(Some)
.map_err(|error| format!("invalid JSON frame: {error}"))
}
fn write_frame(value: &Json) -> Result<(), String> {
let bytes = serde_json::to_vec(value).map_err(|error| format!("encode failed: {error}"))?;
if bytes.len() > MAX_FRAME_BYTES {
return Err("response frame is too large".to_string());
}
let mut stdout = std::io::stdout();
stdout
.write_all(&(bytes.len() as u32).to_be_bytes())
.and_then(|()| stdout.write_all(&bytes))
.and_then(|()| stdout.flush())
.map_err(|error| format!("stdout write failed: {error}"))
}
fn fail(message: &str) -> Json {
json!({"ok": false, "code": "host.error", "message": message})
}
fn main() {
let Some(path) = std::env::args_os().nth(1) else {
eprintln!("usage: marqdo-provider-worker <c-abi-library>");
std::process::exit(2);
};
let provider = match Provider::load(&PathBuf::from(path)) {
Ok(provider) => provider,
Err(error) => {
eprintln!("provider worker: {error}");
std::process::exit(2);
}
};
loop {
let request = match read_frame() {
Ok(Some(request)) => request,
Ok(None) => break,
Err(error) => {
eprintln!("provider worker: {error}");
std::process::exit(1);
}
};
let op = request.get("op").and_then(Json::as_str).unwrap_or("");
let response = match op {
"ping" => json!({"ok": true}),
"open" => {
let kind = request.get("kind").and_then(Json::as_str).unwrap_or("");
let descriptor = request
.get("descriptor")
.and_then(Json::as_str)
.unwrap_or("");
let rights = request
.get("rights")
.and_then(Json::as_array)
.map(|values| {
values
.iter()
.filter_map(Json::as_str)
.map(str::to_string)
.collect::<Vec<_>>()
})
.unwrap_or_default();
match provider.open(kind, descriptor, &rights) {
Ok(token) => json!({"ok": true, "token": token}),
Err(error) => fail(&error),
}
}
"read" => {
let token = request.get("token").and_then(Json::as_u64).unwrap_or(0);
let max_bytes =
request.get("max_bytes").and_then(Json::as_u64).unwrap_or(0) as usize;
match provider.read(token, max_bytes) {
Ok((bytes, eof)) => json!({"ok": true, "bytes": bytes, "eof": eof}),
Err(error) => fail(&error),
}
}
"write" => {
let token = request.get("token").and_then(Json::as_u64).unwrap_or(0);
let bytes = request
.get("bytes")
.and_then(Json::as_array)
.map(|values| {
values
.iter()
.filter_map(Json::as_u64)
.filter_map(|value| u8::try_from(value).ok())
.collect::<Vec<_>>()
})
.unwrap_or_default();
match provider.write(token, &bytes) {
Ok(count) => json!({"ok": true, "count": count}),
Err(error) => fail(&error),
}
}
"close" => {
let token = request.get("token").and_then(Json::as_u64).unwrap_or(0);
match provider.close(token) {
Ok(()) => json!({"ok": true}),
Err(error) => fail(&error),
}
}
"shutdown" => break,
_ => fail("unsupported worker operation"),
};
if let Err(error) = write_frame(&response) {
eprintln!("provider worker: {error}");
std::process::exit(1);
}
}
}
@@ -0,0 +1,136 @@
#![cfg(unix)]
use std::path::Path;
use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value};
fn context() -> marqdo_host::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None)
}
fn handle(value: Value) -> marqdo_value::ResourceHandle {
match value {
Value::Resource(handle) => handle,
other => panic!("expected resource, got {other:?}"),
}
}
fn cc_available() -> bool {
Command::new("cc")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
fn build_provider(dir: &Path) -> std::path::PathBuf {
let source = dir.join("provider.c");
std::fs::write(
&source,
r#"
#include <stdint.h>
#include <stddef.h>
#include <string.h>
static const char DATA[] = "worker-abi";
static size_t position = 0;
uint32_t marqdo_resource_provider_abi_version(void) { return 1u; }
int32_t marqdo_resource_open(const char *kind, const char *descriptor,
const char *rights_csv, uint64_t *out_token) {
(void)kind; (void)descriptor; (void)rights_csv;
position = 0; *out_token = 42; return 0;
}
int32_t marqdo_resource_read(uint64_t token, uint8_t *buffer,
uint32_t capacity, uint32_t *out_read,
int32_t *out_eof) {
(void)token;
size_t remaining = sizeof(DATA) - 1 - position;
size_t count = remaining < capacity ? remaining : capacity;
memcpy(buffer, DATA + position, count);
position += count;
*out_read = (uint32_t)count;
*out_eof = position >= sizeof(DATA) - 1 ? 1 : 0;
return 0;
}
int32_t marqdo_resource_write(uint64_t token, const uint8_t *bytes,
uint32_t length, uint32_t *out_written) {
(void)token; (void)bytes; *out_written = length; return 0;
}
int32_t marqdo_resource_close(uint64_t token) { (void)token; return 0; }
int32_t marqdo_resource_last_error(char *buffer, uint32_t capacity) {
(void)capacity; buffer[0] = 0; return 0;
}
"#,
)
.unwrap();
let extension = if cfg!(target_os = "macos") {
"dylib"
} else {
"so"
};
let library = dir.join(format!("libworker_provider.{extension}"));
let status = Command::new("cc")
.args(["-shared", "-fPIC", "-O2", "-o"])
.arg(&library)
.arg(&source)
.status()
.expect("run cc");
assert!(status.success());
library
}
#[test]
fn c_abi_provider_runs_inside_the_worker_helper() {
if !cc_available() {
eprintln!("skipping worker binding test: cc is unavailable");
return;
}
let dir = tempfile::tempdir().unwrap();
let library = build_provider(dir.path());
let project = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("worker-cabi"),
project.path(),
);
host.register_worker_resource_provider(
"worker-cabi",
&["worker.sensor"],
&std::path::PathBuf::from(env!("CARGO_BIN_EXE_marqdo-provider-worker")),
&[library.to_string_lossy().to_string()],
)
.unwrap();
let ctx = context();
let handle = handle(
host.resource_open("worker.sensor", "s", &["read".to_string()], &ctx)
.unwrap(),
);
let first = host.resource_read(handle, 6, &ctx).unwrap();
assert_eq!(first.bytes, b"worker");
let rest = host.resource_read(handle, 64, &ctx).unwrap();
assert_eq!(rest.bytes, b"-abi");
assert!(rest.eof);
assert_eq!(host.resource_write(handle, b"x", &ctx).unwrap(), 1);
host.resource_close(handle, &ctx).unwrap();
}
#[test]
fn worker_helper_without_c_provider_fails_closed() {
let project = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("worker-cabi"),
project.path(),
);
let error = host
.register_worker_resource_provider(
"worker-cabi",
&["worker.sensor"],
&std::path::PathBuf::from(env!("CARGO_BIN_EXE_marqdo-provider-worker")),
&["/definitely/missing/provider.so".to_string()],
)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::HostError);
}