feat(net): add DNS, UDP, TCP listener and TLS endpoints
This commit is contained in:
1 parent
ee0c6cc80a
commit
ff3f19a2ea
20 files changed
+1327
-61
No files matched your search
@@ -86,8 +86,8 @@ struct SandboxArgs {
|
||||
/// Grant read access to a project-relative glob (repeatable).
|
||||
#[arg(long = "allow-read", value_name = "GLOB")]
|
||||
allow_read: Vec<String>,
|
||||
/// Grant network access to an IP literal host (repeatable, ADR-0034).
|
||||
#[arg(long = "allow-net", value_name = "IP")]
|
||||
/// Grant network access to a host name or IP literal (repeatable, ADR-0034/0047).
|
||||
#[arg(long = "allow-net", value_name = "HOST")]
|
||||
allow_net: Vec<String>,
|
||||
/// Grant write access to a project-relative glob (repeatable).
|
||||
#[arg(long = "allow-write", value_name = "GLOB")]
|
||||
|
||||
@@ -10,6 +10,8 @@ authors.workspace = true
|
||||
|
||||
[dependencies]
|
||||
libloading = { workspace = true }
|
||||
rustls = { workspace = true }
|
||||
rustls-native-certs = { workspace = true }
|
||||
marqdo-plugin-abi = { workspace = true }
|
||||
getrandom = { workspace = true }
|
||||
glob = { workspace = true }
|
||||
@@ -25,3 +27,5 @@ thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = { workspace = true }
|
||||
rcgen = { workspace = true }
|
||||
rustls-pemfile = { workspace = true }
|
||||
@@ -5,7 +5,7 @@
|
||||
//! execution, not at parse/compile time.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -14,6 +14,7 @@ use marqdo_plugin_abi::{
|
||||
};
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
|
||||
use rustls::pki_types::CertificateDer;
|
||||
|
||||
use crate::budget::Budget;
|
||||
use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker};
|
||||
@@ -144,6 +145,22 @@ pub trait Host {
|
||||
))
|
||||
}
|
||||
|
||||
/// Accept one inbound TCP connection from a `tcp-listener` handle.
|
||||
///
|
||||
/// Default: unavailable. The standard host returns a new `Resource` in a
|
||||
/// recoverable `{ok,value}` map or `{ok:false,code:"tcp.timeout"}`.
|
||||
fn resource_accept(
|
||||
&mut self,
|
||||
_handle: ResourceHandle,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"this host does not provide tcp listeners",
|
||||
))
|
||||
}
|
||||
|
||||
/// Execute one non-streaming resource operation (ADR-0041).
|
||||
///
|
||||
/// Default: unavailable. The standard host implements the `fs.*` group;
|
||||
@@ -221,6 +238,8 @@ pub struct StdHost {
|
||||
plugin_exports: BTreeMap<String, usize>,
|
||||
/// Trusted vendor capability policy entries for the broker.
|
||||
vendor_capabilities: BTreeSet<String>,
|
||||
/// Extra TLS roots explicitly trusted by the embedder (DER).
|
||||
tls_extra_roots: Vec<CertificateDer<'static>>,
|
||||
/// Shared audit log for plugin capability requests.
|
||||
broker_audit: Arc<Mutex<Vec<CapabilityAudit>>>,
|
||||
/// Host-issued opaque plugin handles.
|
||||
@@ -289,6 +308,7 @@ impl StdHost {
|
||||
plugins: Vec::new(),
|
||||
plugin_exports: BTreeMap::new(),
|
||||
vendor_capabilities: BTreeSet::new(),
|
||||
tls_extra_roots: Vec::new(),
|
||||
broker_audit: Arc::new(Mutex::new(Vec::new())),
|
||||
handles: PluginHandleTable::default(),
|
||||
stderr: Vec::new(),
|
||||
@@ -300,6 +320,16 @@ impl StdHost {
|
||||
}
|
||||
}
|
||||
|
||||
/// Add one explicit TLS root certificate (DER) for `resource.open("tls")`.
|
||||
///
|
||||
/// System roots are always tried first; this adds a private CA for
|
||||
/// embedders and tests. The certificate is a trust decision, not a grant:
|
||||
/// the exact host grant is still required.
|
||||
pub fn with_tls_ca(mut self, certificate: CertificateDer<'static>) -> Self {
|
||||
self.tls_extra_roots.push(certificate);
|
||||
self
|
||||
}
|
||||
|
||||
/// Load a native plugin in-process after an explicit trust decision.
|
||||
///
|
||||
/// In-process native code shares the host address space and is **not**
|
||||
@@ -712,6 +742,27 @@ impl Host for StdHost {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resource_accept(
|
||||
&mut self,
|
||||
handle: ResourceHandle,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let accepted = self.resources.accept(handle, ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.accept",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("kind=tcp-listener"),
|
||||
);
|
||||
self.record_resource_effect("resource.accept", ctx, started, "ok");
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::Resource(accepted));
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
|
||||
fn resource_request(
|
||||
&mut self,
|
||||
operation: &str,
|
||||
|
||||
@@ -5,6 +5,31 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
fn parse_host_port(descriptor: &str, span: Option<Span>) -> Result<(String, u16), RuntimeError> {
|
||||
let invalid = || {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
span,
|
||||
format!("tcp descriptor `{descriptor}` must be `host:port` or `[ipv6]:port`"),
|
||||
)
|
||||
};
|
||||
if let Some(rest) = descriptor.strip_prefix('[') {
|
||||
let (host, tail) = rest.split_once(']').ok_or_else(invalid)?;
|
||||
let port = tail.strip_prefix(':').ok_or_else(invalid)?;
|
||||
let port = port.parse::<u16>().map_err(|_| invalid())?;
|
||||
if host.is_empty() {
|
||||
return Err(invalid());
|
||||
}
|
||||
return Ok((host.to_string(), port));
|
||||
}
|
||||
let (host, port) = descriptor.rsplit_once(':').ok_or_else(invalid)?;
|
||||
if host.is_empty() {
|
||||
return Err(invalid());
|
||||
}
|
||||
let port = port.parse::<u16>().map_err(|_| invalid())?;
|
||||
Ok((host.to_string(), port))
|
||||
}
|
||||
|
||||
impl StdHost {
|
||||
pub(crate) fn open_resource_stream(
|
||||
&mut self,
|
||||
@@ -125,26 +150,37 @@ impl StdHost {
|
||||
"tcp resources require exactly [read, write] in this build",
|
||||
));
|
||||
}
|
||||
let address: SocketAddr = descriptor.parse().map_err(|_| {
|
||||
let (host, port) = parse_host_port(descriptor, ctx.span)?;
|
||||
self.capabilities.check_net(&host, ctx.span)?;
|
||||
let addresses = (host.as_str(), port).to_socket_addrs().map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!(
|
||||
"tcp descriptor `{descriptor}` must be an IP literal address:port (DNS names are not resolved in this build)"
|
||||
),
|
||||
format!("cannot resolve `{host}:{port}`: {error}"),
|
||||
)
|
||||
})?;
|
||||
self.capabilities
|
||||
.check_net(&address.ip().to_string(), ctx.span)?;
|
||||
let stream = TcpStream::connect_timeout(&address, Duration::from_secs(5)).map_err(
|
||||
|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot connect to {address}: {error}"),
|
||||
)
|
||||
},
|
||||
)?;
|
||||
let mut stream = None;
|
||||
let mut last_error = None;
|
||||
for address in addresses {
|
||||
match TcpStream::connect_timeout(&address, Duration::from_secs(5)) {
|
||||
Ok(connected) => {
|
||||
stream = Some(connected);
|
||||
break;
|
||||
}
|
||||
Err(error) => last_error = Some((address, error)),
|
||||
}
|
||||
}
|
||||
let Some(stream) = stream else {
|
||||
let detail = match last_error {
|
||||
Some((address, error)) => format!("{address}: {error}"),
|
||||
None => format!("`{host}:{port}` resolved to no addresses"),
|
||||
};
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot connect to `{host}:{port}`: {detail}"),
|
||||
));
|
||||
};
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
|
||||
let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
|
||||
let handle = self.resources.open_tcp(stream);
|
||||
@@ -153,7 +189,239 @@ impl StdHost {
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind=tcp address={address}")),
|
||||
Some(&format!("kind=tcp host={host} port={port}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
"tls" => {
|
||||
if self.mode != SandboxMode::Project {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
ctx.span,
|
||||
"tls resources are available only in project mode",
|
||||
));
|
||||
}
|
||||
if requested != BTreeSet::from(["read", "write"]) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"tls resources require exactly [read, write] in this build",
|
||||
));
|
||||
}
|
||||
let (host, port) = parse_host_port(descriptor, ctx.span)?;
|
||||
self.capabilities.check_net(&host, ctx.span)?;
|
||||
let addresses = (host.as_str(), port).to_socket_addrs().map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot resolve `{host}:{port}`: {error}"),
|
||||
)
|
||||
})?;
|
||||
let mut tcp = None;
|
||||
let mut last_error = None;
|
||||
for address in addresses {
|
||||
match TcpStream::connect_timeout(&address, Duration::from_secs(5)) {
|
||||
Ok(connected) => {
|
||||
tcp = Some(connected);
|
||||
break;
|
||||
}
|
||||
Err(error) => last_error = Some((address, error)),
|
||||
}
|
||||
}
|
||||
let Some(tcp) = tcp else {
|
||||
let detail = match last_error {
|
||||
Some((address, error)) => format!("{address}: {error}"),
|
||||
None => format!("`{host}:{port}` resolved to no addresses"),
|
||||
};
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot connect tls to `{host}:{port}`: {detail}"),
|
||||
));
|
||||
};
|
||||
let _ = tcp.set_read_timeout(Some(Duration::from_secs(5)));
|
||||
let _ = tcp.set_write_timeout(Some(Duration::from_secs(5)));
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
for certificate in rustls_native_certs::load_native_certs().certs {
|
||||
let _ = roots.add(certificate);
|
||||
}
|
||||
for certificate in &self.tls_extra_roots {
|
||||
roots.add(certificate.clone()).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot add TLS root: {error}"),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
if roots.is_empty() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
"no trusted TLS roots are available",
|
||||
));
|
||||
}
|
||||
let config = rustls::ClientConfig::builder()
|
||||
.with_root_certificates(roots)
|
||||
.with_no_client_auth();
|
||||
let server_name =
|
||||
rustls::pki_types::ServerName::try_from(host.clone()).map_err(|_| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
format!("`{host}` is not a valid TLS server name"),
|
||||
)
|
||||
})?;
|
||||
let connection =
|
||||
rustls::ClientConnection::new(std::sync::Arc::new(config), server_name)
|
||||
.map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot start TLS: {error}"),
|
||||
)
|
||||
})?;
|
||||
let stream = rustls::StreamOwned::new(connection, tcp);
|
||||
let handle = self.resources.open_tls(stream);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind=tls host={host} port={port}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
"tcp-listener" => {
|
||||
if self.mode != SandboxMode::Project {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
ctx.span,
|
||||
"tcp-listener resources are available only in project mode",
|
||||
));
|
||||
}
|
||||
if requested != BTreeSet::from(["accept"]) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"tcp-listener requires exactly [accept] in this build",
|
||||
));
|
||||
}
|
||||
let (host, port) = parse_host_port(descriptor, ctx.span)?;
|
||||
self.capabilities.check_net(&host, ctx.span)?;
|
||||
let addresses = (host.as_str(), port).to_socket_addrs().map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot resolve `{host}:{port}`: {error}"),
|
||||
)
|
||||
})?;
|
||||
let mut listener = None;
|
||||
let mut last_error = None;
|
||||
for address in addresses {
|
||||
match TcpListener::bind(address) {
|
||||
Ok(bound) => {
|
||||
listener = Some(bound);
|
||||
break;
|
||||
}
|
||||
Err(error) => last_error = Some((address, error)),
|
||||
}
|
||||
}
|
||||
let Some(listener) = listener else {
|
||||
let detail = match last_error {
|
||||
Some((address, error)) => format!("{address}: {error}"),
|
||||
None => format!("`{host}:{port}` resolved to no addresses"),
|
||||
};
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot listen on `{host}:{port}`: {detail}"),
|
||||
));
|
||||
};
|
||||
listener.set_nonblocking(true).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot configure tcp-listener: {error}"),
|
||||
)
|
||||
})?;
|
||||
let handle = self.resources.open_tcp_listener(listener);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind=tcp-listener host={host} port={port}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
"udp" => {
|
||||
if self.mode != SandboxMode::Project {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
ctx.span,
|
||||
"udp resources are available only in project mode",
|
||||
));
|
||||
}
|
||||
if requested != BTreeSet::from(["read", "write"]) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"udp resources require exactly [read, write] in this build",
|
||||
));
|
||||
}
|
||||
let (host, port) = parse_host_port(descriptor, ctx.span)?;
|
||||
self.capabilities.check_net(&host, ctx.span)?;
|
||||
let addresses = (host.as_str(), port).to_socket_addrs().map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot resolve `{host}:{port}`: {error}"),
|
||||
)
|
||||
})?;
|
||||
let mut socket = None;
|
||||
let mut last_error = None;
|
||||
for address in addresses {
|
||||
let bind = if address.is_ipv4() {
|
||||
"0.0.0.0:0"
|
||||
} else {
|
||||
"[::]:0"
|
||||
};
|
||||
let candidate = UdpSocket::bind(bind).and_then(|socket| {
|
||||
socket.connect(address)?;
|
||||
Ok(socket)
|
||||
});
|
||||
match candidate {
|
||||
Ok(connected) => {
|
||||
socket = Some(connected);
|
||||
break;
|
||||
}
|
||||
Err(error) => last_error = Some((address, error)),
|
||||
}
|
||||
}
|
||||
let Some(socket) = socket else {
|
||||
let detail = match last_error {
|
||||
Some((address, error)) => format!("{address}: {error}"),
|
||||
None => format!("`{host}:{port}` resolved to no addresses"),
|
||||
};
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("cannot connect udp to `{host}:{port}`: {detail}"),
|
||||
));
|
||||
};
|
||||
let _ = socket.set_read_timeout(Some(Duration::from_secs(5)));
|
||||
let _ = socket.set_write_timeout(Some(Duration::from_secs(5)));
|
||||
let handle = self.resources.open_udp(socket);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind=udp host={host} port={port}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
Ok(Value::Resource(handle))
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::net::{TcpListener, TcpStream, UdpSocket};
|
||||
|
||||
use rustls::{ClientConnection, StreamOwned};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -81,6 +83,7 @@ struct StdinCursor {
|
||||
position: usize,
|
||||
}
|
||||
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum Stream {
|
||||
Stdin {
|
||||
cursor: Arc<Mutex<StdinCursor>>,
|
||||
@@ -113,6 +116,18 @@ enum Stream {
|
||||
stream: TcpStream,
|
||||
closed: bool,
|
||||
},
|
||||
Udp {
|
||||
socket: UdpSocket,
|
||||
closed: bool,
|
||||
},
|
||||
TcpListener {
|
||||
listener: TcpListener,
|
||||
closed: bool,
|
||||
},
|
||||
Tls {
|
||||
stream: StreamOwned<ClientConnection, TcpStream>,
|
||||
closed: bool,
|
||||
},
|
||||
}
|
||||
|
||||
struct Slot {
|
||||
@@ -130,6 +145,9 @@ impl Slot {
|
||||
Stream::FileWriter { closed, .. } => *closed,
|
||||
Stream::Provider { closed, .. } => *closed,
|
||||
Stream::Tcp { closed, .. } => *closed,
|
||||
Stream::Udp { closed, .. } => *closed,
|
||||
Stream::TcpListener { closed, .. } => *closed,
|
||||
Stream::Tls { closed, .. } => *closed,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -205,7 +223,11 @@ impl ResourceTable {
|
||||
Stream::Stdout { .. } => Some("stdout"),
|
||||
Stream::Stderr { .. } => Some("stderr"),
|
||||
Stream::File { .. } | Stream::FileWriter { .. } => None,
|
||||
Stream::Provider { .. } | Stream::Tcp { .. } => None,
|
||||
Stream::Provider { .. }
|
||||
| Stream::Tcp { .. }
|
||||
| Stream::Udp { .. }
|
||||
| Stream::TcpListener { .. }
|
||||
| Stream::Tls { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -236,6 +258,83 @@ impl ResourceTable {
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a connected UDP socket.
|
||||
pub fn open_udp(&mut self, socket: UdpSocket) -> ResourceHandle {
|
||||
self.insert(Stream::Udp {
|
||||
socket,
|
||||
closed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a bound TCP listener.
|
||||
pub fn open_tcp_listener(&mut self, listener: TcpListener) -> ResourceHandle {
|
||||
self.insert(Stream::TcpListener {
|
||||
listener,
|
||||
closed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a TLS client stream over a TCP socket.
|
||||
pub fn open_tls(&mut self, stream: StreamOwned<ClientConnection, TcpStream>) -> ResourceHandle {
|
||||
self.insert(Stream::Tls {
|
||||
stream,
|
||||
closed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Accept one inbound TCP connection from a listener, with a 5 s deadline.
|
||||
pub fn accept(
|
||||
&mut self,
|
||||
handle: ResourceHandle,
|
||||
span: Option<Span>,
|
||||
) -> Result<ResourceHandle, RuntimeError> {
|
||||
let slot = self.slot_mut(handle, span)?;
|
||||
if slot.closed() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceClosed,
|
||||
span,
|
||||
"Resource handle is closed",
|
||||
));
|
||||
}
|
||||
let Stream::TcpListener { listener, .. } = &mut slot.stream else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
span,
|
||||
"resource.accept requires a tcp-listener handle",
|
||||
));
|
||||
};
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
loop {
|
||||
match listener.accept() {
|
||||
Ok((stream, _)) => {
|
||||
let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
|
||||
let _ = stream.set_write_timeout(Some(std::time::Duration::from_secs(5)));
|
||||
return Ok(self.insert(Stream::Tcp {
|
||||
stream,
|
||||
closed: false,
|
||||
}));
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
if std::time::Instant::now() >= deadline {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
span,
|
||||
"tcp-listener accept timed out after 5 seconds",
|
||||
));
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
Err(error) => {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
span,
|
||||
format!("tcp-listener accept failed: {error}"),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a provider token and wrap it in a host-issued handle.
|
||||
pub fn open_provider(
|
||||
&mut self,
|
||||
@@ -395,6 +494,41 @@ impl ResourceTable {
|
||||
eof: count == 0,
|
||||
})
|
||||
}
|
||||
Stream::TcpListener { .. } => Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
span,
|
||||
"a tcp-listener does not support resource.read; use resource.accept",
|
||||
)),
|
||||
Stream::Tls { stream, .. } => {
|
||||
let mut buffer = vec![0u8; max_bytes];
|
||||
let count = stream.read(&mut buffer).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
span,
|
||||
format!("tls read failed: {error}"),
|
||||
)
|
||||
})?;
|
||||
buffer.truncate(count);
|
||||
Ok(ResourceRead {
|
||||
bytes: buffer,
|
||||
eof: count == 0,
|
||||
})
|
||||
}
|
||||
Stream::Udp { socket, .. } => {
|
||||
let mut buffer = vec![0u8; max_bytes];
|
||||
let count = socket.recv(&mut buffer).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
span,
|
||||
format!("udp read failed: {error}"),
|
||||
)
|
||||
})?;
|
||||
buffer.truncate(count);
|
||||
Ok(ResourceRead {
|
||||
bytes: buffer,
|
||||
eof: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,6 +612,25 @@ impl ResourceTable {
|
||||
format!("tcp write failed: {error}"),
|
||||
)
|
||||
}),
|
||||
Stream::TcpListener { .. } => Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
span,
|
||||
"a tcp-listener does not support resource.write; use resource.accept",
|
||||
)),
|
||||
Stream::Tls { stream, .. } => stream.write(bytes).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
span,
|
||||
format!("tls write failed: {error}"),
|
||||
)
|
||||
}),
|
||||
Stream::Udp { socket, .. } => socket.send(bytes).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
span,
|
||||
format!("udp write failed: {error}"),
|
||||
)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -515,6 +668,9 @@ impl ResourceTable {
|
||||
let _ = stream.shutdown(std::net::Shutdown::Both);
|
||||
*closed = true;
|
||||
}
|
||||
Stream::Udp { closed, .. } => *closed = true,
|
||||
Stream::TcpListener { closed, .. } => *closed = true,
|
||||
Stream::Tls { closed, .. } => *closed = true,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -555,6 +711,9 @@ impl ResourceTable {
|
||||
Stream::File { .. } | Stream::FileWriter { .. } => "file".to_string(),
|
||||
Stream::Provider { kind, .. } => kind.clone(),
|
||||
Stream::Tcp { .. } => "tcp".to_string(),
|
||||
Stream::Udp { .. } => "udp".to_string(),
|
||||
Stream::TcpListener { .. } => "tcp-listener".to_string(),
|
||||
Stream::Tls { .. } => "tls".to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -471,28 +471,21 @@ fn tcp_resource_round_trips_with_a_network_grant() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_requires_network_grant_and_rejects_dns_names() {
|
||||
fn tcp_requires_a_host_grant_in_project_mode() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut host = StdHost::new(SandboxMode::Project, Capabilities::project(), dir.path());
|
||||
let ctx = context();
|
||||
let denied = host
|
||||
.resource_open(
|
||||
"tcp",
|
||||
"127.0.0.1:9",
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(denied.category, ErrorCategory::PermissionDenied);
|
||||
let dns = host
|
||||
.resource_open(
|
||||
"tcp",
|
||||
"example.test:80",
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(dns.category, ErrorCategory::ResourceUnsupported);
|
||||
for descriptor in ["127.0.0.1:9", "example.test:80"] {
|
||||
let denied = host
|
||||
.resource_open(
|
||||
"tcp",
|
||||
descriptor,
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(denied.category, ErrorCategory::PermissionDenied);
|
||||
}
|
||||
|
||||
for mode in [SandboxMode::Pure, SandboxMode::Strict] {
|
||||
let mut host = StdHost::new(
|
||||
@@ -512,6 +505,42 @@ fn tcp_requires_network_grant_and_rejects_dns_names() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_dns_name_connects_with_a_host_grant() {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut buffer = [0u8; 4];
|
||||
stream.read_exact(&mut buffer).unwrap();
|
||||
stream.write_all(&buffer).unwrap();
|
||||
});
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::project().allow_net("localhost"),
|
||||
dir.path(),
|
||||
);
|
||||
let ctx = context();
|
||||
let handle = handle(
|
||||
host.resource_open(
|
||||
"tcp",
|
||||
&format!("localhost:{port}"),
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(host.resource_write(handle, b"ping", &ctx).unwrap(), 4);
|
||||
assert_eq!(host.resource_read(handle, 4, &ctx).unwrap().bytes, b"ping");
|
||||
host.resource_close(handle, &ctx).unwrap();
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
fn field<'a>(value: &'a Value, name: &str) -> &'a Value {
|
||||
match value {
|
||||
Value::Map(map) => map.get(name).unwrap_or_else(|| panic!("missing `{name}`")),
|
||||
@@ -843,3 +872,222 @@ fn random_bytes_require_the_entropy_grant() {
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn udp_resource_round_trips_a_datagram_with_a_network_grant() {
|
||||
use std::net::UdpSocket;
|
||||
|
||||
let server = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
let port = server.local_addr().unwrap().port();
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut buffer = [0u8; 16];
|
||||
let (count, peer) = server.recv_from(&mut buffer).unwrap();
|
||||
server.send_to(&buffer[..count], peer).unwrap();
|
||||
});
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::project().allow_net("127.0.0.1"),
|
||||
dir.path(),
|
||||
);
|
||||
let ctx = context();
|
||||
let handle = handle(
|
||||
host.resource_open(
|
||||
"udp",
|
||||
&format!("127.0.0.1:{port}"),
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(host.resource_write(handle, b"ping", &ctx).unwrap(), 4);
|
||||
let read = host.resource_read(handle, 16, &ctx).unwrap();
|
||||
assert_eq!(read.bytes, b"ping");
|
||||
assert!(!read.eof);
|
||||
host.resource_close(handle, &ctx).unwrap();
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn udp_is_project_only_and_grant_checked() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ctx = context();
|
||||
for mode in [SandboxMode::Pure, SandboxMode::Strict] {
|
||||
let mut host = StdHost::new(
|
||||
mode,
|
||||
Capabilities::project().allow_net("127.0.0.1"),
|
||||
dir.path(),
|
||||
);
|
||||
let error = host
|
||||
.resource_open(
|
||||
"udp",
|
||||
"127.0.0.1:9",
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
}
|
||||
let mut project = StdHost::new(SandboxMode::Project, Capabilities::project(), dir.path());
|
||||
let error = project
|
||||
.resource_open(
|
||||
"udp",
|
||||
"127.0.0.1:9",
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_listener_accepts_an_inbound_connection() {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
|
||||
let probe = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = probe.local_addr().unwrap().port();
|
||||
drop(probe);
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::project().allow_net("127.0.0.1"),
|
||||
dir.path(),
|
||||
);
|
||||
let ctx = context();
|
||||
let listener = handle(
|
||||
host.resource_open(
|
||||
"tcp-listener",
|
||||
&format!("127.0.0.1:{port}"),
|
||||
&["accept".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let client = std::thread::spawn(move || {
|
||||
let mut stream = TcpStream::connect(format!("127.0.0.1:{port}")).unwrap();
|
||||
stream.write_all(b"ping").unwrap();
|
||||
let mut buffer = [0u8; 4];
|
||||
stream.read_exact(&mut buffer).unwrap();
|
||||
assert_eq!(&buffer, b"ping");
|
||||
});
|
||||
|
||||
let accepted = host.resource_accept(listener, &ctx).unwrap();
|
||||
let value = field(&accepted, "value");
|
||||
let Value::Resource(connection) = value else {
|
||||
panic!("resource.accept did not return a Resource");
|
||||
};
|
||||
assert_eq!(
|
||||
host.resource_read(*connection, 4, &ctx).unwrap().bytes,
|
||||
b"ping"
|
||||
);
|
||||
assert_eq!(host.resource_write(*connection, b"ping", &ctx).unwrap(), 4);
|
||||
host.resource_close(*connection, &ctx).unwrap();
|
||||
host.resource_close(listener, &ctx).unwrap();
|
||||
client.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_listener_requires_accept_rights_and_project_mode() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ctx = context();
|
||||
let mut project = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::project().allow_net("127.0.0.1"),
|
||||
dir.path(),
|
||||
);
|
||||
let error = project
|
||||
.resource_open("tcp-listener", "127.0.0.1:9", &["read".to_string()], &ctx)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::ResourceUnsupported);
|
||||
let mut strict = StdHost::new(
|
||||
SandboxMode::Strict,
|
||||
Capabilities::project().allow_net("127.0.0.1"),
|
||||
dir.path(),
|
||||
);
|
||||
let error = strict
|
||||
.resource_open("tcp-listener", "127.0.0.1:9", &["accept".to_string()], &ctx)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tls_resource_round_trips_with_an_explicit_root() {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::sync::Arc;
|
||||
|
||||
let certified = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
|
||||
let certificate = certified.cert.der().clone();
|
||||
let key = rustls::pki_types::PrivateKeyDer::Pkcs8(rustls::pki_types::PrivatePkcs8KeyDer::from(
|
||||
certified.key_pair.serialize_der(),
|
||||
));
|
||||
let config = rustls::ServerConfig::builder()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![certificate.clone()], key)
|
||||
.unwrap();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let connection = rustls::ServerConnection::new(Arc::new(config)).unwrap();
|
||||
let mut stream = rustls::StreamOwned::new(connection, stream);
|
||||
let mut buffer = [0u8; 4];
|
||||
stream.read_exact(&mut buffer).unwrap();
|
||||
stream.write_all(&buffer).unwrap();
|
||||
});
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::project().allow_net("localhost"),
|
||||
dir.path(),
|
||||
)
|
||||
.with_tls_ca(certificate);
|
||||
let ctx = context();
|
||||
let handle = handle(
|
||||
host.resource_open(
|
||||
"tls",
|
||||
&format!("localhost:{port}"),
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(host.resource_write(handle, b"ping", &ctx).unwrap(), 4);
|
||||
assert_eq!(host.resource_read(handle, 4, &ctx).unwrap().bytes, b"ping");
|
||||
host.resource_close(handle, &ctx).unwrap();
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tls_requires_project_mode_and_a_host_grant() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ctx = context();
|
||||
let mut project = StdHost::new(SandboxMode::Project, Capabilities::project(), dir.path());
|
||||
let error = project
|
||||
.resource_open(
|
||||
"tls",
|
||||
"localhost:9",
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
let mut strict = StdHost::new(
|
||||
SandboxMode::Strict,
|
||||
Capabilities::project().allow_net("localhost"),
|
||||
dir.path(),
|
||||
);
|
||||
let error = strict
|
||||
.resource_open(
|
||||
"tls",
|
||||
"localhost:9",
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
}
|
||||
@@ -305,6 +305,13 @@ const RESOURCE_REQUEST: Builtin = Builtin {
|
||||
named_only: false,
|
||||
effectful: true,
|
||||
};
|
||||
const RESOURCE_ACCEPT: Builtin = Builtin {
|
||||
name: "resource.accept",
|
||||
aliases: &[],
|
||||
params: &[req("handle")],
|
||||
named_only: false,
|
||||
effectful: true,
|
||||
};
|
||||
const TABLE_CELL: Builtin = Builtin {
|
||||
name: "table.cell",
|
||||
aliases: &[],
|
||||
@@ -353,6 +360,7 @@ pub const BUILTINS: &[Builtin] = &[
|
||||
RESOURCE_WRITE,
|
||||
RESOURCE_CLOSE,
|
||||
RESOURCE_REQUEST,
|
||||
RESOURCE_ACCEPT,
|
||||
];
|
||||
|
||||
/// Find a builtin by canonical name or alias.
|
||||
|
||||
@@ -478,6 +478,10 @@ pub(crate) fn dispatch(
|
||||
Err(error) => resource_recoverable(error),
|
||||
}
|
||||
}
|
||||
"resource.accept" => {
|
||||
let handle = resource_handle(take(&bound, "handle", builtin, span)?, span)?;
|
||||
interpreter.resource_accept(handle, &module, span)
|
||||
}
|
||||
"resource.request" => {
|
||||
let operation = expect_text_value(take(&bound, "operation", builtin, span)?, span)?;
|
||||
let value_type = bound["arguments"].type_name();
|
||||
|
||||
@@ -903,6 +903,22 @@ impl<'a> Interpreter<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Accept one inbound TCP connection from a listener handle.
|
||||
pub(crate) fn resource_accept(
|
||||
&mut self,
|
||||
handle: ResourceHandle,
|
||||
module: &ModuleId,
|
||||
span: Option<Span>,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let context = ExecutionContext::new(module.to_string(), span);
|
||||
self.host
|
||||
.resource_accept(handle, &context)
|
||||
.map_err(|mut error| {
|
||||
error.mark_callsite();
|
||||
error
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute one non-streaming resource operation.
|
||||
pub(crate) fn resource_request(
|
||||
&mut self,
|
||||
|
||||
Reference in new issue
Block a user