feat(random): add explicitly granted OS entropy API

This commit is contained in:
Marqdo Agent committed 2026-11-21 10:25:11 +08:00
1 parent 6338fa10e9
commit ee0c6cc80a
20 files changed
+309 -15

No files matched your search

+9 -2
View File
@@ -23,6 +23,8 @@ pub struct SandboxSettings {
pub allow_env: Vec<String>,
/// Process program grants (ADR-0044).
pub allow_process: Vec<String>,
/// OS entropy grant (ADR-0046).
pub allow_random: bool,
/// Foreign execution grant.
pub allow_foreign: bool,
/// Plugin grants.
@@ -75,6 +77,7 @@ impl SandboxSettings {
|| !self.allow_write.is_empty()
|| !self.allow_env.is_empty()
|| !self.allow_process.is_empty()
|| self.allow_random
|| !self.allow_plugin.is_empty()
|| !self.plugins.is_empty()
|| self.trust_native_plugin
@@ -83,8 +86,8 @@ impl SandboxSettings {
if requested {
return Err(
"strict mode currently supports pure Marqdo and native Math only; \
--allow-read/--allow-write/--allow-env/--allow-process/--allow-foreign/\
--allow-plugin/--plugin/--trust-native-plugin/--kernel/--trace-file are
--allow-read/--allow-write/--allow-env/--allow-process/--allow-random/\
--allow-foreign/--allow-plugin/--plugin/--trust-native-plugin/--kernel/--trace-file are
rejected. Use --mode project for those capabilities."
.to_string(),
);
@@ -102,6 +105,7 @@ impl SandboxSettings {
|| !self.allow_write.is_empty()
|| !self.allow_env.is_empty()
|| !self.allow_process.is_empty()
|| self.allow_random
|| self.allow_foreign
|| !self.allow_plugin.is_empty()
{
@@ -128,6 +132,9 @@ impl SandboxSettings {
for program in &self.allow_process {
capabilities = capabilities.allow_process(program.clone());
}
if self.allow_random {
capabilities = capabilities.allow_random();
}
if self.allow_foreign {
capabilities = capabilities.allow_foreign();
}
+4
View File
@@ -98,6 +98,9 @@ struct SandboxArgs {
/// Grant execution of an exact program path (repeatable, ADR-0044).
#[arg(long = "allow-process", value_name = "PROGRAM")]
allow_process: Vec<String>,
/// Grant OS entropy reads (ADR-0046).
#[arg(long = "allow-random")]
allow_random: bool,
/// Grant explicit foreign kernel execution.
#[arg(long = "allow-foreign")]
allow_foreign: bool,
@@ -151,6 +154,7 @@ impl SandboxArgs {
allow_write: self.allow_write.clone(),
allow_env: self.allow_env.clone(),
allow_process: self.allow_process.clone(),
allow_random: self.allow_random,
allow_foreign: self.allow_foreign,
allow_plugin: self.allow_plugin.clone(),
fuel: self.fuel,
+19
View File
@@ -83,6 +83,8 @@ fn product_tests() -> Vec<TestFile> {
][..]
} else if name == "process.mq.md" {
&["--allow-process", "/bin/echo"][..]
} else if name == "random.mq.md" {
&["--allow-random"][..]
} else {
&[][..]
};
@@ -158,6 +160,7 @@ fn every_public_stdlib_module_has_a_product_test() {
"json.mq.md",
"path.mq.md",
"process.mq.md",
"random.mq.md",
"regex.mq.md",
"stream.mq.md",
"table.mq.md",
@@ -365,6 +368,22 @@ fn process_test_runs_an_explicitly_granted_program() {
assert_eq!(items[3]["value"], "");
}
#[test]
fn random_test_reads_bounded_entropy() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "random.mq.md")
.expect("random test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "16");
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], true);
assert_eq!(items[4]["value"], true);
}
#[test]
fn format_test_pins_value_semantics_and_handle_observation() {
let report = run_product_test(
+1
View File
@@ -11,6 +11,7 @@ authors.workspace = true
[dependencies]
libloading = { workspace = true }
marqdo-plugin-abi = { workspace = true }
getrandom = { workspace = true }
glob = { workspace = true }
marqdo-span = { workspace = true }
marqdo-value = { workspace = true }
+22
View File
@@ -321,6 +321,8 @@ pub struct Capabilities {
pub env: Vec<String>,
/// Allowed process program paths (empty = no process execution).
pub process_programs: Vec<String>,
/// Whether OS entropy may be read (ADR-0046).
pub random: bool,
/// May spawn processes (foreign kernels).
pub process: bool,
/// May run foreign kernels (Python/Node).
@@ -342,6 +344,7 @@ impl Capabilities {
net_hosts: Vec::new(),
env: Vec::new(),
process_programs: Vec::new(),
random: false,
process: false,
foreign: false,
plugins: Vec::new(),
@@ -409,6 +412,25 @@ impl Capabilities {
}
}
/// Grant OS entropy reads (ADR-0046).
pub fn allow_random(mut self) -> Self {
self.random = true;
self
}
/// Check the entropy grant.
pub fn check_random(&self, span: Option<Span>) -> Result<(), RuntimeError> {
if self.random {
Ok(())
} else {
Err(denied(
span,
"OS entropy was not granted",
"grant it with --allow-random",
))
}
}
/// Grant foreign kernel execution.
pub fn allow_foreign(mut self) -> Self {
self.foreign = true;
+52
View File
@@ -785,6 +785,58 @@ impl Host for StdHost {
self.record_resource_effect("resource.request", ctx, started, "process.run");
return Ok(result);
}
if operation == "random.bytes" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `random.bytes` expects 1 argument, got {}",
args.len()
),
));
}
let count = match &args[0] {
Value::Int(value) => value
.to_string()
.parse::<usize>()
.ok()
.filter(|count| (1..=65536).contains(count)),
_ => None,
};
let Some(count) = count else {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
"random.bytes requires an Int in 1..=65536",
));
};
self.capabilities.check_random(ctx.span)?;
let mut bytes = vec![0u8; count];
getrandom::fill(&mut bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("OS entropy is unavailable: {error}"),
)
})?;
let values = bytes
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=random.bytes"),
);
self.record_resource_effect("resource.request", ctx, started, "random.bytes");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
return Ok(Value::Map(map));
}
if operation == "env.get" {
if args.len() != 1 {
return Err(RuntimeError::new(
@@ -795,3 +795,51 @@ fn fs_append_read_at_and_walk_are_bounded() {
.unwrap_err();
assert_eq!(error.category, ErrorCategory::Type);
}
#[test]
fn random_bytes_require_the_entropy_grant() {
let dir = tempfile::tempdir().unwrap();
let ctx = context();
let mut denied = StdHost::new(SandboxMode::Project, Capabilities::project(), dir.path());
let error = denied
.resource_request("random.bytes", vec![Value::int(8)], &ctx)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::PermissionDenied);
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_random(),
dir.path(),
);
let value = host
.resource_request("random.bytes", vec![Value::int(16)], &ctx)
.unwrap();
assert_eq!(field(&value, "ok"), &Value::Bool(true));
let bytes = field(&value, "value").clone();
let Value::List(bytes) = bytes else {
panic!("random.bytes did not return a List");
};
assert_eq!(bytes.len(), 16);
for byte in bytes {
let Value::Int(byte) = byte else {
panic!("random byte is not an Int");
};
let byte = byte.to_string().parse::<i64>().unwrap();
assert!((0..=255).contains(&byte));
}
let error = host
.resource_request("random.bytes", vec![Value::int(0)], &ctx)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::Type);
let mut pure = StdHost::new(
SandboxMode::Pure,
Capabilities::pure().allow_random(),
dir.path(),
);
let error = pure
.resource_request("random.bytes", vec![Value::int(8)], &ctx)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::PermissionDenied);
}