feat(host): add IP-literal blocking TCP resource endpoint (P5)
- resource.open("tcp", ip:port, ["read","write"]) with exact IP grants,
project mode only, 5s connect/read/write timeouts; no DNS/TLS/UDP/server
sockets (ADR-0034).
- Add TCP stream storage/dispatch in the resource table; CLI --allow-net IP;
pure/strict preflight rejects the grant and the language endpoint.
- Host loopback echo/grant/DNS/strict tests and a .mq.md CLI echo test.
- Update specs, status, architecture, README, changelog and evidence.
Gate: fmt, clippy -D warnings, 426 tests passed.
This commit is contained in:
1 parent
1d87f98539
commit
00bdcad1ff
15 files changed
+435
-4
No files matched your search
@@ -22,6 +22,8 @@ pub struct SandboxSettings {
|
||||
pub allow_read: Vec<String>,
|
||||
/// Write grants.
|
||||
pub allow_write: Vec<String>,
|
||||
/// Network grants (IP literals, ADR-0034).
|
||||
pub allow_net: Vec<String>,
|
||||
/// Foreign execution grant.
|
||||
pub allow_foreign: bool,
|
||||
/// Plugin grants.
|
||||
@@ -70,6 +72,7 @@ impl SandboxSettings {
|
||||
pub fn strict_preflight(&self) -> Result<(), String> {
|
||||
let requested = self.allow_foreign
|
||||
|| !self.allow_read.is_empty()
|
||||
|| !self.allow_net.is_empty()
|
||||
|| !self.allow_write.is_empty()
|
||||
|| !self.allow_plugin.is_empty()
|
||||
|| !self.plugins.is_empty()
|
||||
@@ -94,6 +97,7 @@ impl SandboxSettings {
|
||||
match mode {
|
||||
SandboxMode::Pure => {
|
||||
if !self.allow_read.is_empty()
|
||||
|| !self.allow_net.is_empty()
|
||||
|| !self.allow_write.is_empty()
|
||||
|| self.allow_foreign
|
||||
|| !self.allow_plugin.is_empty()
|
||||
@@ -112,6 +116,9 @@ impl SandboxSettings {
|
||||
for pattern in &self.allow_write {
|
||||
capabilities = capabilities.allow_write(pattern.clone());
|
||||
}
|
||||
for host in &self.allow_net {
|
||||
capabilities = capabilities.allow_net(host.clone());
|
||||
}
|
||||
if self.allow_foreign {
|
||||
capabilities = capabilities.allow_foreign();
|
||||
}
|
||||
|
||||
@@ -86,6 +86,9 @@ 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")]
|
||||
allow_net: Vec<String>,
|
||||
/// Grant write access to a project-relative glob (repeatable).
|
||||
#[arg(long = "allow-write", value_name = "GLOB")]
|
||||
allow_write: Vec<String>,
|
||||
@@ -138,6 +141,7 @@ impl SandboxArgs {
|
||||
commands::SandboxSettings {
|
||||
mode: self.mode.clone(),
|
||||
allow_read: self.allow_read.clone(),
|
||||
allow_net: self.allow_net.clone(),
|
||||
allow_write: self.allow_write.clone(),
|
||||
allow_foreign: self.allow_foreign,
|
||||
allow_plugin: self.allow_plugin.clone(),
|
||||
|
||||
@@ -222,6 +222,68 @@ fn file_copy_is_written_in_mqmd_through_chunked_streams() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_stream_round_trips_through_mqmd_with_a_network_grant() {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
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 = TempDir::new("tcp");
|
||||
let program = format!(
|
||||
r#"## main
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
|
||||
**`内存[0] = 112`**
|
||||
|
||||
**`内存[1] = 105`**
|
||||
|
||||
**`内存[2] = 110`**
|
||||
|
||||
**`内存[3] = 103`**
|
||||
|
||||
**流 = resource.open("tcp", "{address}", ["read", "write"])**
|
||||
|
||||
**写入 = resource.write(流, 内存, 0, 4)**
|
||||
|
||||
**读出 = resource.read(流, 内存, 0, 4)**
|
||||
|
||||
**关闭 = resource.close(流)**
|
||||
|
||||
*[写入.value.count, 读出.value.count, 内存[0], 内存[1], 内存[2], 内存[3], 关闭.ok]*
|
||||
"#
|
||||
);
|
||||
write_file(&dir.path().join("index.mq.md"), &program);
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
&["run", "index.mq.md", "--allow-net", "127.0.0.1", "--json"],
|
||||
);
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(0),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
|
||||
assert_eq!(report["success"], true);
|
||||
let values = report["value"]["items"].as_array().expect("list");
|
||||
assert_eq!(values[0]["decimal"], "4");
|
||||
assert_eq!(values[1]["decimal"], "4");
|
||||
for (index, expected) in ["112", "105", "110", "103"].into_iter().enumerate() {
|
||||
assert_eq!(values[2 + index]["decimal"], expected);
|
||||
}
|
||||
assert_eq!(values[6]["value"], true);
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_stream_requires_a_read_grant() {
|
||||
let dir = TempDir::new("file-denied");
|
||||
|
||||
@@ -374,6 +374,12 @@ impl Capabilities {
|
||||
self
|
||||
}
|
||||
|
||||
/// Grant network access to one IP literal host (ADR-0034).
|
||||
pub fn allow_net(mut self, host: impl Into<String>) -> Self {
|
||||
self.net_hosts.push(host.into());
|
||||
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());
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! execution, not at parse/compile time.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -755,6 +756,54 @@ impl StdHost {
|
||||
"project file streams support exactly [read] or [write] in this build",
|
||||
))
|
||||
}
|
||||
"tcp" => {
|
||||
if self.mode != SandboxMode::Project {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
ctx.span,
|
||||
"tcp resources are available only in project mode",
|
||||
));
|
||||
}
|
||||
if requested != BTreeSet::from(["read", "write"]) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"tcp resources require exactly [read, write] in this build",
|
||||
));
|
||||
}
|
||||
let address: SocketAddr = descriptor.parse().map_err(|_| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
format!(
|
||||
"tcp descriptor `{descriptor}` must be an IP literal address:port (DNS names are not resolved in this build)"
|
||||
),
|
||||
)
|
||||
})?;
|
||||
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 _ = 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);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind=tcp address={address}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
other => {
|
||||
if self.mode != SandboxMode::Project {
|
||||
return Err(RuntimeError::new(
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
//! table validates run identity, slot identity and generation on every call.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -85,6 +87,10 @@ enum Stream {
|
||||
token: u64,
|
||||
closed: bool,
|
||||
},
|
||||
Tcp {
|
||||
stream: TcpStream,
|
||||
closed: bool,
|
||||
},
|
||||
}
|
||||
|
||||
struct Slot {
|
||||
@@ -99,6 +105,7 @@ impl Slot {
|
||||
Stream::File { closed, .. } => *closed,
|
||||
Stream::FileWriter { closed, .. } => *closed,
|
||||
Stream::Provider { closed, .. } => *closed,
|
||||
Stream::Tcp { closed, .. } => *closed,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,6 +162,14 @@ impl ResourceTable {
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a connected TCP stream.
|
||||
pub fn open_tcp(&mut self, stream: TcpStream) -> ResourceHandle {
|
||||
self.insert(Stream::Tcp {
|
||||
stream,
|
||||
closed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Open a provider token and wrap it in a host-issued handle.
|
||||
pub fn open_provider(
|
||||
&mut self,
|
||||
@@ -272,6 +287,21 @@ impl ResourceTable {
|
||||
let mut provider = provider.lock().map_err(|_| provider_lock_error(span))?;
|
||||
provider.read(*token, max_bytes, span)
|
||||
}
|
||||
Stream::Tcp { stream, .. } => {
|
||||
let mut buffer = vec![0u8; max_bytes];
|
||||
let count = stream.read(&mut buffer).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
span,
|
||||
format!("tcp read failed: {error}"),
|
||||
)
|
||||
})?;
|
||||
buffer.truncate(count);
|
||||
Ok(ResourceRead {
|
||||
bytes: buffer,
|
||||
eof: count == 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,6 +362,13 @@ impl ResourceTable {
|
||||
let mut provider = provider.lock().map_err(|_| provider_lock_error(span))?;
|
||||
provider.write(*token, bytes, span)
|
||||
}
|
||||
Stream::Tcp { stream, .. } => stream.write(bytes).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
span,
|
||||
format!("tcp write failed: {error}"),
|
||||
)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,6 +400,10 @@ impl ResourceTable {
|
||||
provider.close(*token, span)?;
|
||||
*closed = true;
|
||||
}
|
||||
Stream::Tcp { stream, closed } => {
|
||||
let _ = stream.shutdown(std::net::Shutdown::Both);
|
||||
*closed = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -400,6 +441,7 @@ impl ResourceTable {
|
||||
Stream::Stdout { .. } => "stdio".to_string(),
|
||||
Stream::File { .. } | Stream::FileWriter { .. } => "file".to_string(),
|
||||
Stream::Provider { kind, .. } => kind.clone(),
|
||||
Stream::Tcp { .. } => "tcp".to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,3 +375,82 @@ fn provider_registration_rejects_versions_reserved_names_and_conflicts() {
|
||||
.unwrap_err();
|
||||
assert_eq!(conflict.category, ErrorCategory::ResourceUnsupported);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_resource_round_trips_with_a_network_grant() {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
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("127.0.0.1"),
|
||||
dir.path(),
|
||||
);
|
||||
let ctx = context();
|
||||
let handle = handle(
|
||||
host.resource_open(
|
||||
"tcp",
|
||||
&address.to_string(),
|
||||
&["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, 4, &ctx).unwrap();
|
||||
assert_eq!(read.bytes, b"ping");
|
||||
host.resource_close(handle, &ctx).unwrap();
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_requires_network_grant_and_rejects_dns_names() {
|
||||
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 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(
|
||||
"tcp",
|
||||
"127.0.0.1:9",
|
||||
&["read".to_string(), "write".to_string()],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user