feat(stdlib): add explicitly granted env API
This commit is contained in:
1 parent
ae69391bc0
commit
9922bfae98
17 files changed
+322
-15
No files matched your search
@@ -24,6 +24,8 @@ pub struct SandboxSettings {
|
||||
pub allow_write: Vec<String>,
|
||||
/// Network grants (IP literals, ADR-0034).
|
||||
pub allow_net: Vec<String>,
|
||||
/// Environment variable grants (ADR-0043).
|
||||
pub allow_env: Vec<String>,
|
||||
/// Foreign execution grant.
|
||||
pub allow_foreign: bool,
|
||||
/// Plugin grants.
|
||||
@@ -74,6 +76,7 @@ impl SandboxSettings {
|
||||
|| !self.allow_read.is_empty()
|
||||
|| !self.allow_net.is_empty()
|
||||
|| !self.allow_write.is_empty()
|
||||
|| !self.allow_env.is_empty()
|
||||
|| !self.allow_plugin.is_empty()
|
||||
|| !self.plugins.is_empty()
|
||||
|| self.trust_native_plugin
|
||||
@@ -82,8 +85,8 @@ impl SandboxSettings {
|
||||
if requested {
|
||||
return Err(
|
||||
"strict mode currently supports pure Marqdo and native Math only; \
|
||||
--allow-read/--allow-write/--allow-foreign/--allow-plugin/--plugin/\
|
||||
--trust-native-plugin/--kernel/--trace-file are rejected. Use \
|
||||
--allow-read/--allow-write/--allow-env/--allow-foreign/--allow-plugin/\
|
||||
--plugin/--trust-native-plugin/--kernel/--trace-file are rejected. Use \
|
||||
--mode project for those capabilities."
|
||||
.to_string(),
|
||||
);
|
||||
@@ -99,6 +102,7 @@ impl SandboxSettings {
|
||||
if !self.allow_read.is_empty()
|
||||
|| !self.allow_net.is_empty()
|
||||
|| !self.allow_write.is_empty()
|
||||
|| !self.allow_env.is_empty()
|
||||
|| self.allow_foreign
|
||||
|| !self.allow_plugin.is_empty()
|
||||
{
|
||||
@@ -119,6 +123,9 @@ impl SandboxSettings {
|
||||
for host in &self.allow_net {
|
||||
capabilities = capabilities.allow_net(host.clone());
|
||||
}
|
||||
for name in &self.allow_env {
|
||||
capabilities = capabilities.allow_env(name.clone());
|
||||
}
|
||||
if self.allow_foreign {
|
||||
capabilities = capabilities.allow_foreign();
|
||||
}
|
||||
|
||||
@@ -92,6 +92,9 @@ struct SandboxArgs {
|
||||
/// Grant write access to a project-relative glob (repeatable).
|
||||
#[arg(long = "allow-write", value_name = "GLOB")]
|
||||
allow_write: Vec<String>,
|
||||
/// Grant read access to an environment variable (repeatable, ADR-0043).
|
||||
#[arg(long = "allow-env", value_name = "NAME")]
|
||||
allow_env: Vec<String>,
|
||||
/// Grant explicit foreign kernel execution.
|
||||
#[arg(long = "allow-foreign")]
|
||||
allow_foreign: bool,
|
||||
@@ -143,6 +146,7 @@ impl SandboxArgs {
|
||||
allow_read: self.allow_read.clone(),
|
||||
allow_net: self.allow_net.clone(),
|
||||
allow_write: self.allow_write.clone(),
|
||||
allow_env: self.allow_env.clone(),
|
||||
allow_foreign: self.allow_foreign,
|
||||
allow_plugin: self.allow_plugin.clone(),
|
||||
fuel: self.fuel,
|
||||
|
||||
@@ -38,6 +38,7 @@ struct TestFile {
|
||||
stdin: &'static str,
|
||||
stdout: &'static str,
|
||||
args: &'static [&'static str],
|
||||
env: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
fn product_tests() -> Vec<TestFile> {
|
||||
@@ -52,6 +53,7 @@ fn product_tests() -> Vec<TestFile> {
|
||||
stdin: "",
|
||||
stdout: "",
|
||||
args: &[],
|
||||
env: &[],
|
||||
};
|
||||
}
|
||||
let name = path.file_name().unwrap().to_string_lossy().to_string();
|
||||
@@ -72,6 +74,18 @@ fn product_tests() -> Vec<TestFile> {
|
||||
"--allow-write",
|
||||
"out/**",
|
||||
][..]
|
||||
} else if name == "env.mq.md" {
|
||||
&[
|
||||
"--allow-env",
|
||||
"MARQDO_TEST_ENV",
|
||||
"--allow-env",
|
||||
"MARQDO_MISSING_ENV",
|
||||
][..]
|
||||
} else {
|
||||
&[][..]
|
||||
};
|
||||
let env = if name == "env.mq.md" {
|
||||
&[("MARQDO_TEST_ENV", "env-value")][..]
|
||||
} else {
|
||||
&[][..]
|
||||
};
|
||||
@@ -80,6 +94,7 @@ fn product_tests() -> Vec<TestFile> {
|
||||
stdin,
|
||||
stdout,
|
||||
args,
|
||||
env,
|
||||
}
|
||||
})
|
||||
.filter(|file| !file.name.is_empty())
|
||||
@@ -99,6 +114,7 @@ fn run_product_test(file: &TestFile) -> serde_json::Value {
|
||||
.args(["--json"])
|
||||
.current_dir(stdlib_dir())
|
||||
.env("MARQDO_STDLIB_DIR", stdlib_dir())
|
||||
.envs(file.env.iter().copied())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -132,6 +148,7 @@ fn every_public_stdlib_module_has_a_product_test() {
|
||||
"csv.mq.md",
|
||||
"datetime.mq.md",
|
||||
"demo.mq.md",
|
||||
"env.mq.md",
|
||||
"format.mq.md",
|
||||
"fs.mq.md",
|
||||
"http.mq.md",
|
||||
@@ -310,6 +327,23 @@ fn clock_test_reports_project_mode_unix_millis() {
|
||||
assert_eq!(items[2]["value"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_test_reads_only_granted_names() {
|
||||
let report = run_product_test(
|
||||
product_tests()
|
||||
.iter()
|
||||
.find(|file| file.name == "env.mq.md")
|
||||
.expect("env test"),
|
||||
);
|
||||
let items = report["value"]["items"].as_array().expect("list");
|
||||
assert_eq!(items[0]["value"], true);
|
||||
assert_eq!(items[1]["value"], true);
|
||||
assert_eq!(items[2]["value"], true);
|
||||
assert_eq!(items[3]["value"], "env-value");
|
||||
assert_eq!(items[4]["value"], false);
|
||||
assert_eq!(items[5]["value"], "env.not_found");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_test_pins_value_semantics_and_handle_observation() {
|
||||
let report = run_product_test(
|
||||
|
||||
@@ -317,6 +317,8 @@ pub struct Capabilities {
|
||||
pub fs_write: Vec<String>,
|
||||
/// Allowed network hosts (empty = no network).
|
||||
pub net_hosts: Vec<String>,
|
||||
/// Allowed environment variable names (empty = no environment).
|
||||
pub env: Vec<String>,
|
||||
/// May spawn processes (foreign kernels).
|
||||
pub process: bool,
|
||||
/// May run foreign kernels (Python/Node).
|
||||
@@ -336,6 +338,7 @@ impl Capabilities {
|
||||
fs_read: Vec::new(),
|
||||
fs_write: Vec::new(),
|
||||
net_hosts: Vec::new(),
|
||||
env: Vec::new(),
|
||||
process: false,
|
||||
foreign: false,
|
||||
plugins: Vec::new(),
|
||||
@@ -361,6 +364,25 @@ impl Capabilities {
|
||||
self
|
||||
}
|
||||
|
||||
/// Grant read access to one environment variable name (ADR-0043).
|
||||
pub fn allow_env(mut self, name: impl Into<String>) -> Self {
|
||||
self.env.push(name.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Check an environment variable grant. Names are exact, not globs.
|
||||
pub fn check_env(&self, name: &str, span: Option<Span>) -> Result<(), RuntimeError> {
|
||||
if self.env.iter().any(|allowed| allowed == name) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(denied(
|
||||
span,
|
||||
format!("environment variable `{name}` was not granted"),
|
||||
format!("grant it with --allow-env {name}"),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Grant foreign kernel execution.
|
||||
pub fn allow_foreign(mut self) -> Self {
|
||||
self.foreign = true;
|
||||
|
||||
@@ -1127,6 +1127,58 @@ impl Host for StdHost {
|
||||
"resource operations accept only Text path arguments",
|
||||
));
|
||||
}
|
||||
if operation == "env.get" {
|
||||
if args.len() != 1 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `env.get` expects 1 argument, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let value_type = args[0].type_name();
|
||||
let Value::Text(name) = args[0].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("resource operation `env.get` expects a Text name, got {value_type}"),
|
||||
));
|
||||
};
|
||||
self.capabilities.check_env(&name, ctx.span)?;
|
||||
let mut map = BTreeMap::new();
|
||||
match std::env::var(&name) {
|
||||
Ok(value) => {
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::text(value));
|
||||
}
|
||||
Err(std::env::VarError::NotPresent) => {
|
||||
map.insert("ok".to_string(), Value::Bool(false));
|
||||
map.insert("code".to_string(), Value::text("env.not_found"));
|
||||
map.insert(
|
||||
"message".to_string(),
|
||||
Value::text(format!("environment variable `{name}` is not set")),
|
||||
);
|
||||
}
|
||||
Err(std::env::VarError::NotUnicode(_)) => {
|
||||
map.insert("ok".to_string(), Value::Bool(false));
|
||||
map.insert("code".to_string(), Value::text("env.not_unicode"));
|
||||
map.insert(
|
||||
"message".to_string(),
|
||||
Value::text(format!("environment variable `{name}` is not valid UTF-8")),
|
||||
);
|
||||
}
|
||||
}
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=env.get"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "env.get");
|
||||
return Ok(Value::Map(map));
|
||||
}
|
||||
if operation == "clock.now" {
|
||||
if !args.is_empty() {
|
||||
return Err(RuntimeError::new(
|
||||
|
||||
@@ -641,3 +641,44 @@ fn clock_now_is_project_only_and_returns_unix_millis() {
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::Arity);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_get_requires_an_exact_grant_and_reports_missing_names() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ctx = context();
|
||||
let mut denied = StdHost::new(SandboxMode::Project, Capabilities::project(), dir.path());
|
||||
let error = denied
|
||||
.resource_request("env.get", vec![Value::text("PATH")], &ctx)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
|
||||
let mut pure = StdHost::new(SandboxMode::Pure, Capabilities::pure(), dir.path());
|
||||
let error = pure
|
||||
.resource_request("env.get", vec![Value::text("PATH")], &ctx)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
|
||||
let capabilities = Capabilities::project()
|
||||
.allow_env("PATH")
|
||||
.allow_env("MARQDO_TEST_MISSING_ENV");
|
||||
let mut host = StdHost::new(SandboxMode::Project, capabilities, dir.path());
|
||||
let present = host
|
||||
.resource_request("env.get", vec![Value::text("PATH")], &ctx)
|
||||
.unwrap();
|
||||
assert_eq!(field(&present, "ok"), &Value::Bool(true));
|
||||
|
||||
let missing = host
|
||||
.resource_request(
|
||||
"env.get",
|
||||
vec![Value::text("MARQDO_TEST_MISSING_ENV")],
|
||||
&ctx,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(field(&missing, "ok"), &Value::Bool(false));
|
||||
assert_eq!(field(&missing, "code"), &Value::text("env.not_found"));
|
||||
|
||||
let error = host
|
||||
.resource_request("env.get", Vec::new(), &ctx)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::Arity);
|
||||
}
|
||||
Reference in new issue
Block a user