feat(ext): single callable binding, provider v2 CLI, capability handlers, stdlib aliases

Implements RFC-EXT-0001 PR-00..PR-07 first pass:
- CallSiteKey/CallBindingTable + one frontend binding pass; runtime dispatch by identity
- prepare composition root shared by check/run/inspect/Analysis; exact plugin reconciliation
- provider.json v2 --provider/--allow-provider worker CLI with fail-closed verification
- capability handler registry with real fs.read and audit
- verified stdlib public aliases replace print_override/AST scan
- docs: specs, ADR-0054/0055/0057/0058, README, CI/release gates, evidence

PR-04 extension selection/lock v4 and final frozen-binary evidence remain.
This commit is contained in:
cflmy committed 2026-11-22 00:17:36 +08:00
1 parent 9aa536c2c9
commit 1f6fd644a0
54 files changed
+8710 -828

No files matched your search

+434 -84
View File
@@ -1,12 +1,19 @@
//! Capability model.
//! Capability model and the trusted capability-handler registry.
//!
//! A project manifest can *request* capabilities, but requests are not grants.
//! Effective permissions are the host default for the sandbox mode intersected
//! with what the operator/CLI explicitly granted. Every host operation checks
//! against this set at the point of execution.
//!
//! Executable vendor/core capabilities additionally need an explicitly
//! registered trusted [`CapabilityHandler`] (ADR-0057, RFC-EXT-0001 §7.2).
//! Being authorized is never the same as being executable: a request without a
//! handler fails with `capability.unavailable` instead of returning an empty
//! successful reply.
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use glob::Pattern;
use marqdo_plugin_abi::abi::MAX_CAPABILITY_REPLY_BYTES;
@@ -14,8 +21,33 @@ use marqdo_plugin_abi::PluginError;
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError};
use crate::budget::Budget;
use crate::fs::ProjectFs;
/// Core capability names understood by [`CapabilityBroker::decide`].
///
/// This is the closed set of host primitives (ADR-0011). A trusted embedder
/// may install a [`CapabilityHandler`] for one of these names; until it does,
/// the capability is authorized by policy but *unavailable* at execution.
pub const CORE_CAPABILITIES: [&str; 10] = [
"console",
"math.compute",
"fs.read",
"fs.write",
"net.request",
"process",
"clock",
"random",
"log",
"artifact.record",
];
/// Capability namespace prefixes reserved for the host itself.
///
/// Handler registration rejects these prefixes so a vendor package can never
/// shadow a host-internal operation.
pub const RESERVED_HANDLER_PREFIXES: [&str; 2] = ["marqdo.", "host."];
/// One audited capability request from a plugin.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CapabilityAudit {
@@ -27,19 +59,143 @@ pub struct CapabilityAudit {
pub decision: &'static str,
/// Human-readable reason.
pub reason: String,
/// Wall-clock duration of the decision/execution in microseconds.
pub duration_micros: u64,
}
/// Broker for plugin host-capability requests (ADR-0011).
/// One capability request handed to an installed [`CapabilityHandler`].
#[derive(Debug, Clone, Copy)]
pub struct CapabilityRequest<'a> {
/// Trusted package identity supplied by the host, never by plugin wire data.
pub package_instance: &'a str,
/// Capability being requested.
pub capability: &'a str,
/// Raw request payload (JSON for the predefined capabilities).
pub payload: &'a [u8],
/// Run/session trace id used to correlate audit entries with a run.
pub trace_id: &'a str,
}
/// Trusted, explicitly registered executor for one capability.
///
/// 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)]
/// RFC-EXT-0001 §7.2 names the policy parameter `EffectiveGrant` and the budget
/// `ResourceBudget`; this build deliberately reuses the existing
/// [`Capabilities`] grant set and [`Budget`] instead of introducing a second
/// permission system (the RFC explicitly allows that substitution).
///
/// A handler is only reachable after [`CapabilityBroker::decide`] authorizes
/// the request, but it must still verify its own scope (project-relative paths,
/// globs, per-file limits) and must charge work to `budget` where applicable.
/// Registration is host-only: there is no wire path from a plugin to this
/// registry.
pub trait CapabilityHandler: Send {
/// Stable capability name this handler serves.
fn name(&self) -> &str;
/// Execute one already-authorized request.
fn execute(
&mut self,
request: &CapabilityRequest<'_>,
capabilities: &Capabilities,
budget: &mut Budget,
) -> Result<Vec<u8>, PluginError>;
}
/// Built-in handler for granted `fs.read` requests.
///
/// Reads go through [`ProjectFs`] (root confinement, traversal rejection,
/// regular-file/UTF-8/8 MiB limits) and the grant is checked **again** against
/// the normalized project-relative path at the execution point, so a raw
/// payload cannot win the glob check with a path the filesystem later
/// normalizes differently.
pub struct FsReadHandler {
fs: ProjectFs,
}
impl FsReadHandler {
/// Install the built-in handler over one project filesystem view.
pub fn new(fs: ProjectFs) -> Self {
Self { fs }
}
}
impl CapabilityHandler for FsReadHandler {
fn name(&self) -> &str {
"fs.read"
}
fn execute(
&mut self,
request: &CapabilityRequest<'_>,
capabilities: &Capabilities,
_budget: &mut Budget,
) -> Result<Vec<u8>, PluginError> {
// Reply-size limits are enforced by the broker, so this handler keeps
// the historical per-read behavior and only needs the grant re-check.
let raw_path = request_path(request.payload)?;
let (_, relative) = self.fs.resolve(&raw_path, None).map_err(map_runtime)?;
capabilities
.check_read(&relative, None)
.map_err(map_runtime)?;
let contents = self.fs.read(&raw_path, None).map_err(map_runtime)?;
Ok(contents.into_bytes())
}
}
struct HandlerEntry {
handler: Box<dyn CapabilityHandler>,
/// Exact trusted package binding. `None` means the handler is authorized
/// by the capability grant alone (for example project-scoped `fs.read`).
package: Option<String>,
}
/// Broker for plugin host-capability requests (ADR-0011, ADR-0057).
///
/// The broker keeps two independent sets: trusted vendor *policy* entries and
/// installed *handlers*. Execution is
///
/// ```text
/// decide (grant + policy + payload shape)
/// -> handler installed? (else capability.unavailable)
/// -> package-bound handler owns the claimed package? (else permission.denied)
/// -> handler executes under the broker budget and reply limit
/// -> audit { package, capability, granted|denied|unavailable, reason, duration }
/// ```
///
/// A capability that is merely authorized never executes: there is no
/// empty-success path.
pub struct CapabilityBroker {
capabilities: Capabilities,
vendor_policy: BTreeSet<String>,
handlers: BTreeMap<String, HandlerEntry>,
reply_limit: usize,
budget: Budget,
trace_id: String,
audit: Arc<Mutex<Vec<CapabilityAudit>>>,
fs: Option<ProjectFs>,
}
impl std::fmt::Debug for CapabilityBroker {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let bound: Vec<(&str, &str)> = self
.handlers
.iter()
.filter_map(|(name, entry)| {
entry
.package
.as_deref()
.map(|package| (name.as_str(), package))
})
.collect();
formatter
.debug_struct("CapabilityBroker")
.field("capabilities", &self.capabilities)
.field("vendor_policy", &self.vendor_policy)
.field("handlers", &self.handlers.keys().collect::<Vec<_>>())
.field("package_bound_handlers", &bound)
.field("reply_limit", &self.reply_limit)
.field("budget", &self.budget)
.field("trace_id", &self.trace_id)
.finish()
}
}
impl CapabilityBroker {
@@ -53,19 +209,116 @@ impl CapabilityBroker {
Self {
capabilities,
vendor_policy: BTreeSet::new(),
handlers: BTreeMap::new(),
reply_limit: MAX_CAPABILITY_REPLY_BYTES,
budget: Budget::default(),
trace_id: String::new(),
audit,
fs: None,
}
}
/// Attach the project filesystem used to execute granted `fs.read`
/// requests. Without it, `fs.read` is authorized but unavailable.
/// Attach the project filesystem and install the trusted built-in
/// `fs.read` handler.
///
/// Without an attached filesystem, granted `fs.read` requests stay
/// authorized but have no handler, so execution returns
/// `capability.unavailable` (never an empty success).
///
/// # Panics
///
/// Panics if a handler for `fs.read` was already registered on this broker,
/// which would make the built-in handler ambiguous.
pub fn with_fs(mut self, fs: ProjectFs) -> Self {
self.fs = Some(fs);
self.register_handler(FsReadHandler::new(fs))
.expect("a fresh broker has no fs.read handler to conflict with");
self
}
/// Override the maximum reply size a handler may return.
pub fn with_reply_limit(mut self, bytes: usize) -> Self {
self.reply_limit = bytes;
self
}
/// Attach the per-run budget that handlers charge work to.
pub fn with_budget(mut self, budget: Budget) -> Self {
self.budget = budget;
self
}
/// Set the run/session trace id surfaced to handlers.
pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
self.trace_id = trace_id.into();
self
}
/// Remaining broker budget (diagnostics and tests).
pub fn budget(&self) -> &Budget {
&self.budget
}
/// Install a trusted handler reachable by any package that holds a grant.
///
/// Registration is a host-only operation; a plugin manifest cannot reach
/// this API. Duplicate, reserved and empty/invalid names are rejected.
pub fn register_handler<H>(&mut self, handler: H) -> Result<(), PluginError>
where
H: CapabilityHandler + 'static,
{
self.install_handler(handler, None)
}
/// Install a trusted handler bound to one exact trusted package identity.
///
/// A request that claims any other package is `permission.denied`, even
/// when the capability grant and vendor policy match.
pub fn register_package_handler<H>(
&mut self,
package: impl Into<String>,
handler: H,
) -> Result<(), PluginError>
where
H: CapabilityHandler + 'static,
{
self.install_handler(handler, Some(package.into()))
}
fn install_handler<H>(&mut self, handler: H, package: Option<String>) -> Result<(), PluginError>
where
H: CapabilityHandler + 'static,
{
let name = handler.name().to_string();
validate_handler_name(&name)?;
if self.handlers.contains_key(&name) {
return Err(PluginError::capability(
"capability.handler_conflict",
format!("a capability handler is already registered for `{name}`"),
));
}
self.handlers.insert(
name,
HandlerEntry {
handler: Box::new(handler),
package,
},
);
Ok(())
}
/// Names with an installed trusted handler, in deterministic order.
pub fn handler_names(&self) -> Vec<&str> {
self.handlers.keys().map(String::as_str).collect()
}
/// Whether a trusted executing handler is installed for `capability`.
pub fn has_handler(&self, capability: &str) -> bool {
self.handlers.contains_key(capability)
}
/// Register a trusted vendor capability policy entry.
///
/// This is policy only: execution additionally requires an installed
/// handler. Registering a vendor name does not install anything.
pub fn allow_vendor(&mut self, capability: impl Into<String>) {
self.vendor_policy.insert(capability.into());
}
@@ -76,103 +329,132 @@ impl CapabilityBroker {
}
/// Authorize one request, returning reply bytes on success.
///
/// This is the grant decision only; it does not prove that an executor is
/// installed. Call [`Self::execute`] to actually run a capability.
pub fn authorize(
&mut self,
package: &str,
capability: &str,
request: &[u8],
) -> Result<Vec<u8>, PluginError> {
let started = Instant::now();
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,
});
}
self.record(package, capability, decision, &reason, started);
result.map(|()| Vec::new())
}
/// Authorize and execute one capability request.
/// Authorize and execute one capability request through its trusted
/// handler.
///
/// Only `fs.read` has a real implementation in this build. Other
/// capabilities return `capability.unavailable` instead of pretending an
/// empty reply means success (ADR-0011, spec §12.2).
/// The chain is fixed: `decide` → handler installed → package binding →
/// handler execution under the broker budget and reply limit → audit.
/// Anything without an installed handler is `capability.unavailable`; it
/// is never reported as an empty success (ADR-0011, ADR-0057).
pub fn execute(
&mut self,
package: &str,
capability: &str,
request: &[u8],
) -> Result<Vec<u8>, PluginError> {
let started = Instant::now();
// 1. Authorization: effective grants, vendor policy, payload shape.
if let Err(error) = self.decide(package, capability, request) {
let reason = format!("{}: {}", error.code, error.message);
self.record(package, capability, "denied", &reason);
self.record(package, capability, "denied", &reason, started);
return Err(error);
}
let result = match capability {
"fs.read" => {
let path = request_path(request)?;
let Some(fs) = &self.fs else {
return self.unavailable(
package,
capability,
"no project filesystem is attached",
);
};
match fs.read(&path, None) {
Ok(contents) => {
if contents.len() > MAX_CAPABILITY_REPLY_BYTES {
return self.unavailable(
package,
capability,
"the file exceeds the capability reply limit",
);
}
Ok(contents.into_bytes())
}
Err(error) => {
let error = map_runtime(error);
let reason = format!("{}: {}", error.code, error.message);
self.record(package, capability, "denied", &reason);
Err(error)
}
}
// 2. A trusted executor must exist; a package-bound executor must own
// the trusted package identity the host is claiming.
let bound_package = match self.handlers.get(capability) {
Some(entry) => entry.package.clone(),
None => {
let message = "this capability has no executing handler in this build";
self.record(package, capability, "unavailable", message, started);
return Err(PluginError::capability(
"capability.unavailable",
message.to_string(),
));
}
_ => self.unavailable(
package,
capability,
"this capability has no executing handler in this build",
),
};
if result.is_ok() {
self.record(package, capability, "granted", "");
if let Some(bound) = bound_package {
if bound != package {
let error = plugin_denied(&format!(
"capability `{capability}` is bound to another trusted package"
));
let reason = format!("{}: {}", error.code, error.message);
self.record(package, capability, "denied", &reason, started);
return Err(error);
}
}
// 3. Execute under the broker budget and reply limit.
let broker_request = CapabilityRequest {
package_instance: package,
capability,
payload: request,
trace_id: &self.trace_id,
};
let reply_limit = self.reply_limit;
let outcome = self
.handlers
.get_mut(capability)
.expect("handler presence was checked above")
.handler
.execute(&broker_request, &self.capabilities, &mut self.budget);
match outcome {
Ok(contents) => {
if contents.len() > reply_limit {
let error = PluginError::capability(
"resource.exhausted",
format!(
"capability reply is {} bytes; the limit is {reply_limit} bytes",
contents.len()
),
);
let reason = format!("{}: {}", error.code, error.message);
self.record(package, capability, "denied", &reason, started);
return Err(error);
}
self.record(package, capability, "granted", "", started);
Ok(contents)
}
Err(error) => {
let reason = format!("{}: {}", error.code, error.message);
let decision = if error.code == "capability.unavailable" {
"unavailable"
} else {
"denied"
};
self.record(package, capability, decision, &reason, started);
Err(error)
}
}
result
}
fn unavailable<T>(
fn record(
&mut self,
package: &str,
capability: &str,
message: &str,
) -> Result<T, PluginError> {
let error = PluginError::capability("capability.unavailable", message.to_string());
self.record(package, capability, "unavailable", message);
Err(error)
}
fn record(&mut self, package: &str, capability: &str, decision: &'static str, reason: &str) {
decision: &'static str,
reason: &str,
started: Instant,
) {
let elapsed = started.elapsed();
let duration_micros = u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX);
if let Ok(mut audit) = self.audit.lock() {
audit.push(CapabilityAudit {
package: package.to_string(),
capability: capability.to_string(),
decision,
reason: reason.to_string(),
duration_micros,
});
}
}
@@ -214,17 +496,14 @@ impl CapabilityBroker {
.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}`"
),
))
if is_vendor_capability(other) {
if self.vendor_policy.contains(other) || self.vendor_policy.contains("*") {
Ok(())
} else {
Err(plugin_denied(&format!(
"vendor capability `{other}` has no trusted policy entry for package `{package}`"
)))
}
} else {
Err(PluginError::capability(
"capability.unknown",
@@ -304,6 +583,38 @@ pub fn is_vendor_capability(name: &str) -> bool {
})
}
/// Validate a trusted handler name before registration.
///
/// Registration uses [`CapabilityHandler::name`] as the registry key, so there
/// is no second name argument that could disagree with the handler's declared
/// capability (the RFC's "declared protocol mismatch" rejection).
fn validate_handler_name(name: &str) -> Result<(), PluginError> {
if name.is_empty() || name.trim() != name {
return Err(PluginError::capability(
"capability.handler_invalid",
"capability handler names must be non-empty and must not contain surrounding whitespace",
));
}
if RESERVED_HANDLER_PREFIXES
.iter()
.any(|prefix| name.starts_with(prefix))
{
return Err(PluginError::capability(
"capability.handler_reserved",
format!("capability handler name `{name}` uses a reserved host namespace"),
));
}
if !CORE_CAPABILITIES.contains(&name) && !is_vendor_capability(name) {
return Err(PluginError::capability(
"capability.handler_invalid",
format!(
"`{name}` is not a registrable capability name: expected a core capability or a vendor-namespaced name"
),
));
}
Ok(())
}
/// Effective capability grants for one run.
#[derive(Debug, Clone, Default)]
pub struct Capabilities {
@@ -594,20 +905,56 @@ mod tests {
.unwrap_err();
assert_eq!(denied.code, "permission.denied");
assert!(broker.authorize("demo.solver", "fs.read", b"{}").is_err());
let unavailable = broker
// Declaring a vendor capability is not a grant: without a trusted
// policy entry authorization is denied (RFC-EXT-0001 CAP-01).
let vendor_denied = broker
.authorize("demo.solver", "vendor.device.read", b"{}")
.unwrap_err();
assert_eq!(unavailable.code, "capability.unavailable");
assert_eq!(vendor_denied.code, "permission.denied");
broker.allow_vendor("vendor.device.read");
assert!(broker
.authorize("demo.solver", "vendor.device.read", b"{}")
.is_ok());
// Policy is not a handler: authorize() succeeds but execution still
// needs an executor and reports `capability.unavailable`.
assert!(!broker.has_handler("vendor.device.read"));
assert_eq!(
broker
.execute("demo.solver", "vendor.device.read", b"{}")
.unwrap_err()
.code,
"capability.unavailable"
);
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_eq!(audit.len(), 6);
assert!(audit.iter().any(|entry| entry.decision == "denied"));
assert!(audit.iter().any(|entry| entry.decision == "unavailable"));
assert!(audit.iter().all(|entry| entry.duration_micros <= 5_000_000));
}
#[test]
fn every_core_capability_is_understood_by_decide() {
for name in CORE_CAPABILITIES {
let broker = CapabilityBroker::new(Capabilities::project());
let payload: &[u8] = match name {
"fs.read" => br#"{"path":"data/a.csv"}"#,
"fs.write" => br#"{"path":"data/a.csv","contents":"x"}"#,
"net.request" => br#"{"host":"127.0.0.1"}"#,
_ => b"{}",
};
let error = broker
.decide("demo.solver", name, payload)
.err()
.map(|error| error.code);
assert_ne!(
error.as_deref(),
Some("capability.unknown"),
"core capability `{name}` must be handled by decide"
);
}
}
#[test]
@@ -638,6 +985,9 @@ mod execute_tests {
.allow_read("data/**")
.allow_write("data/**");
let mut broker = CapabilityBroker::new(capabilities).with_fs(fs);
assert!(broker.has_handler("fs.read"));
assert_eq!(broker.handler_names(), vec!["fs.read"]);
assert_eq!(broker.reply_limit, MAX_CAPABILITY_REPLY_BYTES);
let contents = broker
.execute("demo.solver", "fs.read", br#"{"path":"data/allowed.txt"}"#)
+4 -1
View File
@@ -19,7 +19,10 @@ pub mod resource;
pub mod trace;
pub use budget::{Budget, DEFAULT_FUEL, DEFAULT_OUTPUT_BYTES, DEFAULT_STACK_LIMIT};
pub use capability::Capabilities;
pub use capability::{
Capabilities, CapabilityAudit, CapabilityBroker, CapabilityHandler, CapabilityRequest,
FsReadHandler, CORE_CAPABILITIES, RESERVED_HANDLER_PREFIXES,
};
pub use context::ExecutionContext;
pub use fs::ProjectFs;
pub use handles::{contains_plugin_handle, PluginHandleTable};
@@ -0,0 +1,581 @@
//! Trusted capability-handler registry (RFC-EXT-0001 §7, ADR-0057).
//!
//! These are end-to-end tests over the public `marqdo-host` API. They cover the
//! CAP-01..CAP-12 checks listed in RFC-EXT-0001 §7.5: policy vs handler,
//! package binding, registration validation, real `fs.read` scope enforcement,
//! reply budgets, forged/replayed handles, audit hygiene, resource-stream
//! regression, project-vs-strict labeling and the "no handler is never a
//! silent OK" rule.
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use marqdo_host::{
contains_plugin_handle, Budget, Capabilities, CapabilityBroker, CapabilityHandler,
CapabilityRequest, PluginHandleTable, ProjectFs, ResourceTable, SandboxMode, StdHost,
CORE_CAPABILITIES,
};
use marqdo_plugin_abi::PluginError;
use marqdo_value::{RuntimeError, Value};
static COUNTER: AtomicU32 = AtomicU32::new(0);
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new() -> Self {
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"marqdo-capability-handlers-{}-{id}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A trusted test handler that returns canned bytes.
struct FixedHandler {
name: &'static str,
reply: Vec<u8>,
}
impl CapabilityHandler for FixedHandler {
fn name(&self) -> &str {
self.name
}
fn execute(
&mut self,
_request: &CapabilityRequest<'_>,
_capabilities: &Capabilities,
_budget: &mut Budget,
) -> Result<Vec<u8>, PluginError> {
Ok(self.reply.clone())
}
}
/// A trusted test handler that proves the request identity and budget reach it.
struct EchoHandler {
name: &'static str,
fuel: u64,
}
impl CapabilityHandler for EchoHandler {
fn name(&self) -> &str {
self.name
}
fn execute(
&mut self,
request: &CapabilityRequest<'_>,
_capabilities: &Capabilities,
budget: &mut Budget,
) -> Result<Vec<u8>, PluginError> {
budget
.consume_fuel(self.fuel, None)
.map_err(map_runtime_error)?;
Ok(format!(
"{}|{}|{}",
request.package_instance, request.capability, request.trace_id
)
.into_bytes())
}
}
fn map_runtime_error(error: RuntimeError) -> PluginError {
PluginError::capability(error.code(), error.message)
}
fn audit_entries(broker: &CapabilityBroker) -> Vec<marqdo_host::CapabilityAudit> {
let audit = broker.audit();
let guard = audit.lock().expect("audit lock");
guard.clone()
}
/// CAP-01: a declared vendor capability without a trusted policy entry is
/// denied, even when a handler happens to be installed.
#[test]
fn cap_01_vendor_capability_without_policy_is_denied() {
let mut broker = CapabilityBroker::new(Capabilities::project());
broker
.register_handler(FixedHandler {
name: "vendor.device.read",
reply: b"device".to_vec(),
})
.unwrap();
let error = broker
.execute("demo.solver", "vendor.device.read", b"{}")
.unwrap_err();
assert_eq!(error.code, "permission.denied", "{error:?}");
assert!(broker
.authorize("demo.solver", "vendor.device.read", b"{}")
.is_err());
let audit = audit_entries(&broker);
assert_eq!(audit.len(), 2);
assert!(audit.iter().all(|entry| entry.decision == "denied"));
assert!(audit
.iter()
.all(|entry| entry.capability == "vendor.device.read"));
}
/// CAP-02: authorized but no handler installed is `capability.unavailable`;
/// `authorize` alone does not execute and cannot fake an empty success.
#[test]
fn cap_02_authorized_capability_without_handler_is_unavailable() {
let mut broker = CapabilityBroker::new(Capabilities::project().allow_write("out/**"));
broker.allow_vendor("vendor.device.read");
let unavailable = broker
.execute("demo.solver", "vendor.device.read", b"{}")
.unwrap_err();
assert_eq!(
unavailable.code, "capability.unavailable",
"{unavailable:?}"
);
// Policy is a grant, not an executor: authorize() succeeds, execute() still
// refuses because no trusted handler was registered.
assert!(broker
.authorize(
"demo.solver",
"fs.write",
br#"{"path":"out/result.txt","contents":"x"}"#,
)
.is_ok());
let write = broker
.execute(
"demo.solver",
"fs.write",
br#"{"path":"out/result.txt","contents":"x"}"#,
)
.unwrap_err();
assert_eq!(write.code, "capability.unavailable", "{write:?}");
let audit = audit_entries(&broker);
assert!(audit
.iter()
.any(|entry| entry.decision == "unavailable" && entry.capability == "fs.write"));
assert!(audit
.iter()
.any(|entry| entry.decision == "granted" && entry.capability == "fs.write"));
}
/// CAP-03: a handler bound to one trusted package rejects cross-package
/// impersonation, while the bound package still executes and the request
/// identity/trace id reach the handler.
#[test]
fn cap_03_package_bound_handler_rejects_impersonation() {
let mut broker = CapabilityBroker::new(Capabilities::project()).with_trace_id("trace-9");
broker.allow_vendor("vendor.device.read");
broker
.register_package_handler(
"demo.solver",
EchoHandler {
name: "vendor.device.read",
fuel: 0,
},
)
.unwrap();
let spoofed = broker
.execute("attacker.solver", "vendor.device.read", b"{}")
.unwrap_err();
assert_eq!(spoofed.code, "permission.denied", "{spoofed:?}");
let reply = broker
.execute("demo.solver", "vendor.device.read", b"{}")
.unwrap();
assert_eq!(
String::from_utf8(reply).unwrap(),
"demo.solver|vendor.device.read|trace-9"
);
let audit = audit_entries(&broker);
assert!(audit
.iter()
.any(|entry| entry.decision == "denied" && entry.package == "attacker.solver"));
assert!(audit
.iter()
.any(|entry| entry.decision == "granted" && entry.package == "demo.solver"));
}
/// CAP-04: duplicate, reserved, empty and malformed handler names are rejected
/// and never installed.
#[test]
fn cap_04_registration_rejects_duplicate_reserved_and_empty_names() {
let mut broker = CapabilityBroker::new(Capabilities::project());
let rejected = |broker: &mut CapabilityBroker, name: &'static str, expected: &str| {
let error = broker
.register_handler(FixedHandler {
name,
reply: Vec::new(),
})
.unwrap_err();
assert_eq!(error.code, expected, "name `{name}`: {error:?}");
assert!(!broker.has_handler(name));
};
rejected(&mut broker, "", "capability.handler_invalid");
rejected(&mut broker, "host.terminal", "capability.handler_reserved");
rejected(
&mut broker,
"marqdo.internal.read",
"capability.handler_reserved",
);
rejected(
&mut broker,
"not a capability",
"capability.handler_invalid",
);
rejected(&mut broker, "vendor..read", "capability.handler_invalid");
broker
.register_handler(FixedHandler {
name: "vendor.device.read",
reply: b"device".to_vec(),
})
.unwrap();
let duplicate = broker
.register_handler(FixedHandler {
name: "vendor.device.read",
reply: b"other".to_vec(),
})
.unwrap_err();
assert_eq!(
duplicate.code, "capability.handler_conflict",
"{duplicate:?}"
);
// The trusted built-in fs.read handler cannot be replaced either.
let dir = TempDir::new();
let mut with_fs =
CapabilityBroker::new(Capabilities::project()).with_fs(ProjectFs::new(dir.path()));
assert!(with_fs.has_handler("fs.read"));
let conflict = with_fs
.register_handler(FixedHandler {
name: "fs.read",
reply: Vec::new(),
})
.unwrap_err();
assert_eq!(conflict.code, "capability.handler_conflict", "{conflict:?}");
}
/// CAP-05: the real `fs.read` handler enforces ProjectFs root/scope limits; a
/// permissive glob grant cannot be used to read outside the project root or to
/// traverse with `..`.
#[test]
fn cap_05_fs_read_handler_enforces_scope() {
let dir = TempDir::new();
std::fs::create_dir_all(dir.path().join("data")).unwrap();
std::fs::write(dir.path().join("data/allowed.txt"), "allowed").unwrap();
std::fs::create_dir_all(dir.path().join("private")).unwrap();
std::fs::write(dir.path().join("private/secret.txt"), "secret").unwrap();
let mut broker = CapabilityBroker::new(Capabilities::project().allow_read("data/**"))
.with_fs(ProjectFs::new(dir.path()));
let allowed = broker
.execute("demo.solver", "fs.read", br#"{"path":"data/allowed.txt"}"#)
.unwrap();
assert_eq!(String::from_utf8(allowed).unwrap(), "allowed");
for out_of_scope in [
br#"{"path":"private/secret.txt"}"#.as_slice(),
br#"{"path":"../escape.txt"}"#.as_slice(),
br#"{"path":"/etc/passwd"}"#.as_slice(),
] {
let error = broker
.execute("demo.solver", "fs.read", out_of_scope)
.unwrap_err();
assert_eq!(
error.code, "permission.denied",
"{out_of_scope:?}: {error:?}"
);
}
// Even a `**` grant only authorizes project-relative paths: traversal and
// absolute paths are rejected by ProjectFs::resolve at the handler.
let mut permissive = CapabilityBroker::new(Capabilities::project().allow_read("**"))
.with_fs(ProjectFs::new(dir.path()));
for rejected in [
br#"{"path":"data/../private/secret.txt"}"#.as_slice(),
br#"{"path":"/etc/passwd"}"#.as_slice(),
] {
let error = permissive
.execute("demo.solver", "fs.read", rejected)
.unwrap_err();
assert_eq!(error.code, "permission.denied", "{rejected:?}: {error:?}");
}
}
/// CAP-06: a handler reply over the broker budget is a resource limit, and the
/// handler receives (and charges) the broker budget.
#[test]
fn cap_06_handler_reply_over_budget_is_resource_limit() {
let mut broker = CapabilityBroker::new(Capabilities::project())
.with_reply_limit(64)
.with_budget(Budget {
fuel: 10,
..Budget::default()
});
broker.allow_vendor("vendor.device.big");
broker.allow_vendor("vendor.device.fuel");
broker
.register_handler(FixedHandler {
name: "vendor.device.big",
reply: vec![b'x'; 65],
})
.unwrap();
broker
.register_handler(EchoHandler {
name: "vendor.device.fuel",
fuel: 4,
})
.unwrap();
let oversized = broker
.execute("demo.solver", "vendor.device.big", b"{}")
.unwrap_err();
assert_eq!(oversized.code, "resource.exhausted", "{oversized:?}");
let reply = broker
.execute("demo.solver", "vendor.device.fuel", b"{}")
.unwrap();
assert_eq!(
String::from_utf8(reply).unwrap(),
"demo.solver|vendor.device.fuel|"
);
assert_eq!(broker.budget().remaining_fuel(), 6);
let audit = audit_entries(&broker);
assert!(audit.iter().all(|entry| entry.duration_micros <= 5_000_000));
assert!(audit
.iter()
.any(|entry| entry.capability == "vendor.device.big" && entry.decision == "denied"));
}
/// CAP-07: forged plugin handles are rejected by the host table, and a handle
/// hidden inside an untrusted extension value is detected.
#[test]
fn cap_07_forged_handles_are_rejected() {
let mut table = PluginHandleTable::default();
let handle = table.mint("demo.capability", "capability.read", "demo.capability", 1);
table
.validate(&handle, "demo.capability", 1)
.expect("host-minted handle is valid");
let mut forged = handle.clone();
forged.id = handle.id.wrapping_add(1000);
let error = table
.validate(&forged, "demo.capability", 1)
.expect_err("forged id must be rejected");
assert!(
error.message.contains("plugin_handle.untrusted"),
"{error:?}"
);
let wrong_owner = table
.validate(&handle, "other.package", 1)
.expect_err("cross-owner handle must be rejected");
assert!(
wrong_owner.message.contains("plugin_handle.untrusted"),
"{wrong_owner:?}"
);
let untrusted_value = Value::Map(
[("handle".to_string(), Value::PluginHandle(handle.clone()))]
.into_iter()
.collect(),
);
assert!(contains_plugin_handle(&untrusted_value));
}
/// CAP-08: a handle from an old run or a cleared (unloaded) run is rejected on
/// replay.
#[test]
fn cap_08_replayed_handle_after_run_end_is_rejected() {
let mut table = PluginHandleTable::default();
let handle = table.mint("demo.capability", "capability.read", "demo.capability", 7);
table
.validate(&handle, "demo.capability", 7)
.expect("current run accepts its own handle");
let new_run = table
.validate(&handle, "demo.capability", 8)
.expect_err("a new run must not accept the old handle");
assert!(
new_run.message.contains("plugin_handle.untrusted"),
"{new_run:?}"
);
table.clear_run(7);
assert!(table.is_empty());
let replayed = table
.validate(&handle, "demo.capability", 7)
.expect_err("a cleared run must reject the replayed handle");
assert!(
replayed.message.contains("plugin_handle.untrusted"),
"{replayed:?}"
);
}
/// CAP-09: the capability audit records decisions and durations but never file
/// contents or request secrets.
#[test]
fn cap_09_audit_contains_no_file_contents_or_secrets() {
const SECRET: &str = "TOP-SECRET-PAYLOAD";
const API_KEY: &str = "sk-live-not-audited";
let dir = TempDir::new();
std::fs::create_dir_all(dir.path().join("data")).unwrap();
std::fs::write(dir.path().join("data/secret.txt"), SECRET).unwrap();
let mut broker = CapabilityBroker::new(Capabilities::project().allow_read("data/**"))
.with_fs(ProjectFs::new(dir.path()));
let request = format!(r#"{{"path":"data/secret.txt","api_key":"{API_KEY}"}}"#);
let contents = broker
.execute("demo.solver", "fs.read", request.as_bytes())
.unwrap();
assert_eq!(String::from_utf8(contents).unwrap(), SECRET);
let denied = broker
.execute("demo.solver", "fs.read", br#"{"path":"private/key.txt"}"#)
.unwrap_err();
assert_eq!(denied.code, "permission.denied");
let audit_debug = format!("{:?}", audit_entries(&broker));
assert!(!audit_debug.contains(SECRET), "{audit_debug}");
assert!(!audit_debug.contains(API_KEY), "{audit_debug}");
let audit = audit_entries(&broker);
assert!(audit
.iter()
.any(|entry| entry.decision == "granted" && entry.capability == "fs.read"));
assert!(audit
.iter()
.any(|entry| entry.decision == "denied" && entry.capability == "fs.read"));
assert!(audit.iter().all(|entry| entry.duration_micros <= 5_000_000));
}
/// CAP-10: low-level resource open/read/write/close stays on a sane performance
/// path. This is a catastrophic-regression guard with a deliberately generous
/// bound, not a benchmark (CI timeouts remain authoritative).
#[test]
fn cap_10_resource_stream_operations_do_not_regress_catastrophically() {
const CHUNK: usize = 256 * 1024;
const ITERATIONS: usize = 32;
let payload = vec![b'x'; CHUNK];
let mut table = ResourceTable::default();
let started = Instant::now();
for _ in 0..ITERATIONS {
let reader = table.open_file("data/blob.bin", payload.clone());
let read = table.read(reader, payload.len(), None).unwrap();
assert_eq!(read.bytes.len(), CHUNK);
assert!(read.eof);
table.close(reader, None).unwrap();
let writer = table.open_file_writer("out/blob.bin");
assert_eq!(table.write(writer, &payload, None).unwrap(), CHUNK);
table.close(writer, None).unwrap();
}
let elapsed = started.elapsed();
// 32 x (256 KiB read + 256 KiB write) is ~16 MiB of in-memory copying.
assert!(
elapsed < Duration::from_secs(5),
"resource open/read/write/close took {elapsed:?} for {ITERATIONS} iterations"
);
}
/// CAP-11: the default `project` mode is not an OS-strict mode and grants
/// nothing beyond `pure` by default.
#[test]
fn cap_11_default_project_mode_is_not_os_strict() {
let dir = TempDir::new();
let host = StdHost::new(SandboxMode::Project, Capabilities::project(), dir.path());
assert_eq!(host.mode, SandboxMode::Project);
assert_ne!(host.mode, SandboxMode::Strict);
assert_eq!(host.mode.as_str(), "project");
// Project defaults equal pure defaults: no implicit fs/process/plugin grant.
assert!(host.capabilities.fs_read.is_empty());
assert!(host.capabilities.fs_write.is_empty());
assert!(!host.capabilities.process);
assert!(!host.capabilities.foreign);
assert!(host.capabilities.plugins.is_empty());
// Strict isolation availability is a property of `strict`; project mode is
// cooperative in-process checks, whether or not the platform could isolate.
assert_eq!(
SandboxMode::parse(host.mode.as_str()),
Some(SandboxMode::Project)
);
}
/// CAP-12: core capabilities without an executing handler are always
/// `capability.unavailable`, never a silent empty success.
#[test]
fn cap_12_core_capabilities_without_handler_are_unavailable() {
let dir = TempDir::new();
std::fs::create_dir_all(dir.path().join("data")).unwrap();
std::fs::write(dir.path().join("data/ok.txt"), "ok").unwrap();
let mut capabilities = Capabilities::project()
.allow_read("data/**")
.allow_write("data/**")
.allow_net("127.0.0.1")
.allow_process("/bin/true");
capabilities.process = true;
let mut broker = CapabilityBroker::new(capabilities).with_fs(ProjectFs::new(dir.path()));
// The one migrated capability has a real handler.
let read = broker
.execute("demo.solver", "fs.read", br#"{"path":"data/ok.txt"}"#)
.unwrap();
assert_eq!(String::from_utf8(read).unwrap(), "ok");
// Every other core capability is authorized by its grant but has no
// executor in this build.
for name in CORE_CAPABILITIES {
if name == "fs.read" {
continue;
}
let payload: &[u8] = match name {
"fs.write" => br#"{"path":"data/x","contents":"x"}"#,
"net.request" => br#"{"host":"127.0.0.1"}"#,
_ => b"{}",
};
let error = broker.execute("demo.solver", name, payload).unwrap_err();
assert_eq!(
error.code, "capability.unavailable",
"core capability `{name}` must not silently succeed: {error:?}"
);
assert!(!broker.has_handler(name));
}
let unknown = broker
.execute("demo.solver", "teleport", b"{}")
.unwrap_err();
assert_eq!(unknown.code, "capability.unknown", "{unknown:?}");
let audit = audit_entries(&broker);
assert!(
audit
.iter()
.filter(|entry| entry.decision == "unavailable")
.count()
>= CORE_CAPABILITIES.len() - 1,
"{audit:?}"
);
}