feat(host): add in-process ResourceProvider v1 (CM-A09 slice)

- Add ResourceProvider v1 trait with name/protocol/kinds/open/read/write/close;
  host still issues the opaque language Resource handle, provider tokens stay
  private.
- Add StdHost::register_resource_provider with protocol/version, reserved-name
  and duplicate-kind checks; add Capabilities.allow_resource_provider grants.
- Provider kinds are project-mode only; pure/strict refuse them; in-process
  providers are trusted and not a sandbox (ADR-0033).
- Reuse resource.* and Result shapes; no parser/Value/runtime/HostOp changes.
- Add mock read/write provider and rejection tests, docs/spec/status/evidence.

Gate: fmt, clippy -D warnings, 423 tests passed.
This commit is contained in:
cflmy committed 2026-11-20 22:38:16 +08:00
1 parent a8e62a5ba9
commit 1be4662049
13 files changed
+640 -18

No files matched your search

+30
View File
@@ -323,6 +323,8 @@ pub struct Capabilities {
pub foreign: bool,
/// Allowed plugin names.
pub plugins: Vec<String>,
/// Allowed resource-provider names (ADR-0033).
pub resource_providers: Vec<String>,
}
impl Capabilities {
@@ -337,6 +339,7 @@ impl Capabilities {
process: false,
foreign: false,
plugins: Vec::new(),
resource_providers: Vec::new(),
}
}
@@ -371,6 +374,33 @@ impl Capabilities {
self
}
/// Grant a registered resource provider by its stable name (ADR-0033).
pub fn allow_resource_provider(mut self, name: impl Into<String>) -> Self {
self.resource_providers.push(name.into());
self
}
/// Check a resource-provider grant.
pub fn check_resource_provider(
&self,
name: &str,
span: Option<Span>,
) -> Result<(), RuntimeError> {
if self
.resource_providers
.iter()
.any(|allowed| allowed == name)
{
Ok(())
} else {
Err(denied(
span,
format!("resource provider `{name}` was not granted"),
format!("grant it with Capabilities::allow_resource_provider({name:?})"),
))
}
}
/// Whether a project-relative path matches a granted pattern.
///
/// Patterns and paths are normalised by stripping a leading `./` so that
+101 -6
View File
@@ -20,7 +20,7 @@ use crate::context::ExecutionContext;
use crate::fs::ProjectFs;
use crate::handles::{contains_plugin_handle, PluginHandleTable};
use crate::plugin_worker::WorkerPlugin;
use crate::resource::{ResourceRead, ResourceTable};
use crate::resource::{ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider};
use crate::trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState};
use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
@@ -202,6 +202,8 @@ pub struct StdHost {
pub handles: PluginHandleTable,
/// Host-owned resource/stream table (ADR-0025).
resources: ResourceTable,
/// Registered in-process providers keyed by resource kind (ADR-0033).
resource_providers: BTreeMap<String, (String, SharedResourceProvider)>,
semantic_events: Vec<SemanticEvent>,
next_event_seq: u64,
trace_state: TraceState,
@@ -263,6 +265,7 @@ impl StdHost {
broker_audit: Arc::new(Mutex::new(Vec::new())),
handles: PluginHandleTable::default(),
resources: ResourceTable::new(),
resource_providers: BTreeMap::new(),
semantic_events: Vec::new(),
next_event_seq: 0,
trace_state: TraceState::default(),
@@ -565,6 +568,72 @@ impl StdHost {
Ok(Value::Unit)
}
/// Register an explicitly trusted in-process provider (ADR-0033).
///
/// In-process providers share the host address space and are not a
/// sandbox; only trusted adapters may be registered. Registration is not a
/// language operation and does not grant access by itself.
pub fn register_resource_provider(
&mut self,
provider: Box<dyn ResourceProvider>,
) -> Result<(), RuntimeError> {
if provider.protocol_version() != 1 {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!(
"resource provider `{}` uses unsupported protocol version {}",
provider.name(),
provider.protocol_version()
),
));
}
let name = provider.name().to_string();
if name.is_empty() || name == "stdio" || name == "file" {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!("resource provider name `{name}` is reserved or empty"),
));
}
let kinds = provider
.kinds()
.iter()
.map(|kind| kind.to_string())
.collect::<Vec<_>>();
if kinds.is_empty() {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!("resource provider `{name}` declares no kinds"),
));
}
for kind in &kinds {
if kind.is_empty() || kind == "stdio" || kind == "file" {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!("resource provider `{name}` declares reserved kind `{kind}`"),
));
}
if let Some((existing, _)) = self.resource_providers.get(kind) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!(
"resource kind `{kind}` is already registered by provider `{existing}`"
),
));
}
}
let provider: SharedResourceProvider = std::sync::Arc::new(std::sync::Mutex::new(provider));
for kind in kinds {
self.resource_providers
.insert(kind, (name.clone(), std::sync::Arc::clone(&provider)));
}
Ok(())
}
fn record_resource_effect(
&mut self,
op: &str,
@@ -686,11 +755,37 @@ impl StdHost {
"project file streams support exactly [read] or [write] in this build",
))
}
other => Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
format!("resource kind `{other}` is not implemented in this build"),
)),
other => {
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"resource providers are available only in project mode",
));
}
let Some((provider_name, provider)) = self.resource_providers.get(other).cloned()
else {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
format!("resource kind `{other}` is not registered"),
));
};
self.capabilities
.check_resource_provider(&provider_name, ctx.span)?;
let handle = self
.resources
.open_provider(provider, other, descriptor, rights, ctx.span)?;
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind={other} provider={provider_name}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle))
}
}
}
}
+1 -1
View File
@@ -22,5 +22,5 @@ pub use fs::ProjectFs;
pub use handles::{contains_plugin_handle, PluginHandleTable};
pub use host::{arity, expect_text, Host, HostOp, StdHost};
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
pub use resource::{ResourceRead, ResourceTable};
pub use resource::{ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider};
pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation};
+106 -8
View File
@@ -6,12 +6,55 @@
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError};
static NEXT_RUN_ID: AtomicU64 = AtomicU64::new(1);
/// A versioned trusted provider of additional resource kinds (ADR-0033).
///
/// In-process providers share the host address space and are **not** a
/// sandbox; only explicitly trusted code may be registered.
pub trait ResourceProvider: Send {
/// Stable grant name.
fn name(&self) -> &str;
/// Protocol version; must be 1 in this build.
fn protocol_version(&self) -> u32 {
1
}
/// Resource kinds served by this provider.
fn kinds(&self) -> &[&str];
/// Open one descriptor, returning a provider-private token.
fn open(
&mut self,
kind: &str,
descriptor: &str,
rights: &[String],
span: Option<Span>,
) -> Result<u64, RuntimeError>;
/// Read up to `max_bytes` from a token.
fn read(
&mut self,
token: u64,
max_bytes: usize,
span: Option<Span>,
) -> Result<ResourceRead, RuntimeError>;
/// Write bytes to a token; return the accepted count.
fn write(
&mut self,
token: u64,
bytes: &[u8],
span: Option<Span>,
) -> Result<usize, RuntimeError>;
/// Close a token.
fn close(&mut self, token: u64, span: Option<Span>) -> Result<(), RuntimeError>;
}
/// Shared provider handle registered on the host.
pub type SharedResourceProvider = Arc<Mutex<Box<dyn ResourceProvider>>>;
/// Bytes returned by one stream read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceRead {
@@ -36,6 +79,12 @@ enum Stream {
bytes: Vec<u8>,
closed: bool,
},
Provider {
kind: String,
provider: SharedResourceProvider,
token: u64,
closed: bool,
},
}
struct Slot {
@@ -49,6 +98,7 @@ impl Slot {
Stream::Stdout { closed } => *closed,
Stream::File { closed, .. } => *closed,
Stream::FileWriter { closed, .. } => *closed,
Stream::Provider { closed, .. } => *closed,
}
}
}
@@ -105,6 +155,27 @@ impl ResourceTable {
})
}
/// Open a provider token and wrap it in a host-issued handle.
pub fn open_provider(
&mut self,
provider: SharedResourceProvider,
kind: &str,
descriptor: &str,
rights: &[String],
span: Option<Span>,
) -> Result<ResourceHandle, RuntimeError> {
let token = {
let mut provider = provider.lock().map_err(|_| provider_lock_error(span))?;
provider.open(kind, descriptor, rights, span)?
};
Ok(self.insert(Stream::Provider {
kind: kind.to_string(),
provider,
token,
closed: false,
}))
}
fn insert(&mut self, stream: Stream) -> ResourceHandle {
let id = self.next_resource;
self.next_resource += 1;
@@ -195,6 +266,12 @@ impl ResourceTable {
span,
"a file write stream does not support resource.read",
)),
Stream::Provider {
provider, token, ..
} => {
let mut provider = provider.lock().map_err(|_| provider_lock_error(span))?;
provider.read(*token, max_bytes, span)
}
}
}
@@ -249,6 +326,12 @@ impl ResourceTable {
buffer.extend_from_slice(bytes);
Ok(bytes.len())
}
Stream::Provider {
provider, token, ..
} => {
let mut provider = provider.lock().map_err(|_| provider_lock_error(span))?;
provider.write(*token, bytes, span)
}
}
}
@@ -270,6 +353,16 @@ impl ResourceTable {
Stream::Stdout { closed } => *closed = true,
Stream::File { closed, .. } => *closed = true,
Stream::FileWriter { closed, .. } => *closed = true,
Stream::Provider {
provider,
token,
closed,
..
} => {
let mut provider = provider.lock().map_err(|_| provider_lock_error(span))?;
provider.close(*token, span)?;
*closed = true;
}
}
Ok(())
}
@@ -301,19 +394,24 @@ impl ResourceTable {
}
/// Descriptor kind for diagnostics/trace, if the handle is valid.
pub fn kind(
&self,
handle: ResourceHandle,
span: Option<Span>,
) -> Result<&'static str, RuntimeError> {
pub fn kind(&self, handle: ResourceHandle, span: Option<Span>) -> Result<String, RuntimeError> {
let slot = self.slot(handle, span)?;
Ok(match slot.stream {
Stream::Stdout { .. } => "stdio",
Stream::File { .. } | Stream::FileWriter { .. } => "file",
Ok(match &slot.stream {
Stream::Stdout { .. } => "stdio".to_string(),
Stream::File { .. } | Stream::FileWriter { .. } => "file".to_string(),
Stream::Provider { kind, .. } => kind.clone(),
})
}
}
fn provider_lock_error(span: Option<Span>) -> RuntimeError {
RuntimeError::new(
ErrorCategory::HostError,
span,
"resource provider lock is poisoned",
)
}
fn unknown_handle(span: Option<Span>) -> RuntimeError {
RuntimeError::new(
ErrorCategory::ResourceFault,
@@ -215,3 +215,163 @@ fn traversal_and_unsupported_rights_are_refused() {
.unwrap_err();
assert_eq!(unknown_kind.category, ErrorCategory::ResourceUnsupported);
}
struct MockProvider {
data: Vec<u8>,
position: usize,
written: Vec<u8>,
version: u32,
kinds: Vec<&'static str>,
}
impl MockProvider {
fn new(data: &[u8], version: u32, kinds: Vec<&'static str>) -> Self {
Self {
data: data.to_vec(),
position: 0,
written: Vec::new(),
version,
kinds,
}
}
}
impl marqdo_host::ResourceProvider for MockProvider {
fn name(&self) -> &str {
"mock"
}
fn protocol_version(&self) -> u32 {
self.version
}
fn kinds(&self) -> &[&str] {
&self.kinds
}
fn open(
&mut self,
_kind: &str,
_descriptor: &str,
_rights: &[String],
_span: Option<marqdo_span::Span>,
) -> Result<u64, marqdo_value::RuntimeError> {
self.position = 0;
Ok(7)
}
fn read(
&mut self,
token: u64,
max_bytes: usize,
_span: Option<marqdo_span::Span>,
) -> Result<marqdo_host::ResourceRead, marqdo_value::RuntimeError> {
assert_eq!(token, 7);
let start = self.position;
let end = start.saturating_add(max_bytes).min(self.data.len());
self.position = end;
Ok(marqdo_host::ResourceRead {
bytes: self.data[start..end].to_vec(),
eof: end >= self.data.len(),
})
}
fn write(
&mut self,
token: u64,
bytes: &[u8],
_span: Option<marqdo_span::Span>,
) -> Result<usize, marqdo_value::RuntimeError> {
assert_eq!(token, 7);
self.written.extend_from_slice(bytes);
Ok(bytes.len())
}
fn close(
&mut self,
token: u64,
_span: Option<marqdo_span::Span>,
) -> Result<(), marqdo_value::RuntimeError> {
assert_eq!(token, 7);
Ok(())
}
}
#[test]
fn registered_provider_streams_work_with_a_grant_in_project_mode() {
let dir = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("mock"),
dir.path(),
);
host.register_resource_provider(Box::new(MockProvider::new(
b"abcdef",
1,
vec!["mock.sensor"],
)))
.unwrap();
let ctx = context();
let handle = handle(
host.resource_open("mock.sensor", "sensor-1", &["read".to_string()], &ctx)
.unwrap(),
);
let first = host.resource_read(handle, 2, &ctx).unwrap();
assert_eq!(first.bytes, b"ab");
assert!(!first.eof);
let rest = host.resource_read(handle, 16, &ctx).unwrap();
assert_eq!(rest.bytes, b"cdef");
assert!(rest.eof);
assert_eq!(host.resource_write(handle, b"x", &ctx).unwrap(), 1);
host.resource_close(handle, &ctx).unwrap();
assert_eq!(
host.resource_close(handle, &ctx).unwrap_err().code(),
"resource.closed"
);
}
#[test]
fn provider_requires_a_name_grant_and_project_mode() {
let dir = tempfile::tempdir().unwrap();
let ctx = context();
let mut denied = StdHost::new(SandboxMode::Project, Capabilities::project(), dir.path());
denied
.register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec!["mock.sensor"])))
.unwrap();
let error = denied
.resource_open("mock.sensor", "s", &["read".to_string()], &ctx)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::PermissionDenied);
for mode in [SandboxMode::Pure, SandboxMode::Strict] {
let mut host = StdHost::new(
mode,
Capabilities::pure().allow_resource_provider("mock"),
dir.path(),
);
host.register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec!["mock.sensor"])))
.unwrap();
let error = host
.resource_open("mock.sensor", "s", &["read".to_string()], &ctx)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::PermissionDenied);
}
}
#[test]
fn provider_registration_rejects_versions_reserved_names_and_conflicts() {
let dir = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("mock"),
dir.path(),
);
let bad_version = host
.register_resource_provider(Box::new(MockProvider::new(b"x", 2, vec!["mock.sensor"])))
.unwrap_err();
assert_eq!(bad_version.category, ErrorCategory::ResourceUnsupported);
let reserved = host
.register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec!["stdio"])))
.unwrap_err();
assert_eq!(reserved.category, ErrorCategory::ResourceUnsupported);
host.register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec!["mock.sensor"])))
.unwrap();
let conflict = host
.register_resource_provider(Box::new(MockProvider::new(b"y", 1, vec!["mock.sensor"])))
.unwrap_err();
assert_eq!(conflict.category, ErrorCategory::ResourceUnsupported);
}