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

+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(