feat(host): execute granted fs.read through the capability broker (H3-A partial)

- CapabilityBroker::execute separates authorization from execution; native
  plugins requesting fs.read get real project file bytes through ProjectFs
- unsupported capabilities (fs.write/net/process/console/vendor without a
  handler) return capability.unavailable instead of empty success
- keep audit decisions for granted/denied/unavailable without logging contents
- document that worker capability bridging, live ABI session identity and OS
  isolation (H3-B) remain open; no G-C claim is made
This commit is contained in:
cflmy committed 2026-11-20 13:05:53 +08:00
1 parent b37026b79d
commit 47a2e1883f
4 files changed
+164 -11

No files matched your search

+142
View File
@@ -9,10 +9,13 @@ use std::collections::BTreeSet;
use std::sync::{Arc, Mutex};
use glob::Pattern;
use marqdo_plugin_abi::abi::MAX_CAPABILITY_REPLY_BYTES;
use marqdo_plugin_abi::PluginError;
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError};
use crate::fs::ProjectFs;
/// One audited capability request from a plugin.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CapabilityAudit {
@@ -36,6 +39,7 @@ pub struct CapabilityBroker {
capabilities: Capabilities,
vendor_policy: BTreeSet<String>,
audit: Arc<Mutex<Vec<CapabilityAudit>>>,
fs: Option<ProjectFs>,
}
impl CapabilityBroker {
@@ -50,9 +54,17 @@ impl CapabilityBroker {
capabilities,
vendor_policy: BTreeSet::new(),
audit,
fs: None,
}
}
/// Attach the project filesystem used to execute granted `fs.read`
/// requests. Without it, `fs.read` is authorized but unavailable.
pub fn with_fs(mut self, fs: ProjectFs) -> Self {
self.fs = Some(fs);
self
}
/// Register a trusted vendor capability policy entry.
pub fn allow_vendor(&mut self, capability: impl Into<String>) {
self.vendor_policy.insert(capability.into());
@@ -86,6 +98,85 @@ impl CapabilityBroker {
result.map(|()| Vec::new())
}
/// Authorize and execute one capability request.
///
/// 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).
pub fn execute(
&mut self,
package: &str,
capability: &str,
request: &[u8],
) -> Result<Vec<u8>, PluginError> {
if let Err(error) = self.decide(package, capability, request) {
let reason = format!("{}: {}", error.code, error.message);
self.record(package, capability, "denied", &reason);
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)
}
}
}
_ => self.unavailable(
package,
capability,
"this capability has no executing handler in this build",
),
};
if result.is_ok() {
self.record(package, capability, "granted", "");
}
result
}
fn unavailable<T>(
&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) {
if let Ok(mut audit) = self.audit.lock() {
audit.push(CapabilityAudit {
package: package.to_string(),
capability: capability.to_string(),
decision,
reason: reason.to_string(),
});
}
}
fn decide(&self, package: &str, capability: &str, request: &[u8]) -> Result<(), PluginError> {
match capability {
"console" => self
@@ -424,3 +515,54 @@ mod tests {
assert!(capabilities.check_write("data/a.csv", None).is_err());
}
}
#[cfg(test)]
mod execute_tests {
use super::*;
#[test]
fn broker_executes_fs_read_and_reports_unavailable_for_other_capabilities() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("data")).unwrap();
std::fs::write(dir.path().join("data/allowed.txt"), "hello").unwrap();
std::fs::create_dir_all(dir.path().join("private")).unwrap();
std::fs::write(dir.path().join("private/secret.txt"), "secret").unwrap();
let fs = ProjectFs::new(dir.path());
let capabilities = Capabilities::project()
.allow_read("data/**")
.allow_write("data/**");
let mut broker = CapabilityBroker::new(capabilities).with_fs(fs);
let contents = broker
.execute("demo.solver", "fs.read", br#"{"path":"data/allowed.txt"}"#)
.unwrap();
assert_eq!(String::from_utf8(contents).unwrap(), "hello");
let denied = broker
.execute(
"demo.solver",
"fs.read",
br#"{"path":"private/secret.txt"}"#,
)
.unwrap_err();
assert_eq!(denied.code, "permission.denied");
let console = broker.execute("demo.solver", "console", b"{}").unwrap_err();
assert_eq!(console.code, "capability.unavailable");
let write = broker
.execute(
"demo.solver",
"fs.write",
br#"{"path":"data/x","contents":"x"}"#,
)
.unwrap_err();
assert_eq!(write.code, "capability.unavailable");
let audit = broker.audit();
let audit = audit.lock().unwrap();
assert!(audit.iter().any(|entry| entry.decision == "granted"));
assert!(audit.iter().any(|entry| entry.decision == "denied"));
assert!(audit.iter().any(|entry| entry.decision == "unavailable"));
assert!(!format!("{audit:?}").contains("hello"));
}
}
+3 -2
View File
@@ -267,7 +267,8 @@ impl StdHost {
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());
}
@@ -275,7 +276,7 @@ impl StdHost {
let options = marqdo_plugin_abi::LoadOptions {
host_target: marqdo_plugin_abi::HostTarget::current(),
capability_handler: Some(Box::new(move |capability, request| {
broker.authorize(&package, capability, request)
broker.execute(&package, capability, request)
})),
};
PluginTransport::Native(
+8 -4
View File
@@ -203,10 +203,13 @@ Foreign provider integrity and environment metadata:
* The environment fields are metadata only. uv/npm environment materialization,
environment-directory hashing and lock-v3 integration are **not**
implemented.
* H3-A (capability broker executing real operations) and H3-B (OS isolation)
remain open. `CapabilityBroker::authorize` is still policy/audit-only, Worker
capability requests are still denied, and `strict` is refused on every
platform. No G-C claim is made.
* H3-A is **partially implemented**: the native plugin broker now executes a
granted `fs.read` through `ProjectFs` and returns real bytes, with audit;
unsupported capabilities return `capability.unavailable` rather than empty
success. H3-A remains open for the worker capability bridge, live session
identity in the ABI callback and broader service operations. H3-B (OS
isolation) remains open; Worker capability requests are still denied and
`strict` is refused on every platform. No G-C claim is made.
### M0.6 implementation progress
@@ -220,6 +223,7 @@ Foreign provider integrity and environment metadata:
| S3-A/H2-C Tool protocol | **Done** | SemVer negotiation at install+dispatch, whole-bundle manifest/digest verification, atomic install/remove, reserved record file (see §S3-A/H2-C) |
| S4-A/B-13 B-14 quality gates | **Partial** | real schema instance validation + negative mutations in CI; Windows/macOS runtime tests for core/Analysis/Trace and strict refusal. Tool/C-ABI/worker runtime evidence remains Unix-only (see §S4-A) |
| S5-A/B-12 foreign integrity | **Done for metadata/integrity** | provider digest verified at registration and before spawn; environment descriptor fields; full uv/npm materialization and H3-A/B remain open (see §S5-A/B-12) |
| S5-B/H3-A broker execution | **Partial** | native `fs.read` executes through `ProjectFs` with audit; unsupported capabilities fail unavailable. Worker bridge/session identity/H3-B OS isolation remain open and are not claimed |
| R0 baseline + ADRs | **Done** | this section; `docs/adr/0008`–`0012`; full workspace gate |
| R1 package-aware identity + callable registry | **Done for statics; superseded by S1 lock v3** | `ModuleId { instance, relative_path }`; `PackageResolver` path sources; lock v3 transitive graph (ADR-0016) replaces the flat v2 lock; `CallableRegistry` for builtins/marqdo/declared ABI exports; external manifest wiring is R2 |
| R2 ABI/Kernel/Broker | **Done (worker = crash isolation)** | `KernelRegistry` external providers; complete-name export routing; `CapabilityBroker`; static `check --plugin`; multi-export C test; isolated worker with timeout/crash tests; host handle table. Native/worker are not an OS sandbox |
+11 -5
View File
@@ -121,8 +121,12 @@ before reading. Full symlink/race hardening is an open P4 item.
`capabilities.check_plugin(package)` on **every call**; loading also checks
the same grant once;
* plugin host-capability requests → `CapabilityBroker` checks the package and
effective grants; unknown/vendor capabilities without a trusted policy entry
become `capability.unavailable`/`permission.denied`;
effective grants and **executes** granted `fs.read` through `ProjectFs`,
returning the real file bytes. Other core capabilities (`fs.write`,
`net.request`, `process`, console/math/log/...), and vendor capabilities
without a trusted executing handler, return `capability.unavailable`; they
never pretend an empty reply is success. Unknown/vendor names without a
trusted policy entry become `capability.unavailable`/`permission.denied`;
* print → output budget only.
Static analysis may warn, but it never replaces these runtime checks. There is
@@ -272,9 +276,11 @@ Neither command executes project code. Specifically:
3. Network capability exists in the model but no host operation uses it; there
is no `--allow-net` flag.
4. Write-path symlink TOCTOU (see §2.1).
5. Plugin worker isolation is unimplemented; only trusted in-process native
plugins are possible. The capability broker exists, but no vendor handler is
shipped.
5. Plugin **worker crash isolation** is implemented, but the worker capability
bridge is not: worker capability requests are still denied. Only trusted
in-process native plugins can use the broker's `fs.read` execution. No
vendor-executing handler is shipped, and broker execution is a cooperative
API contract, not an OS sandbox.
6. `plugin_handle` wire values are structurally reconstructable, but host
authority comes only from the `PluginHandleTable` owner/run/generation
check; untrusted plugin/foreign output containing a handle is rejected