feat(random): add explicitly granted OS entropy API
This commit is contained in:
1 parent
6338fa10e9
commit
ee0c6cc80a
20 files changed
+309
-15
No files matched your search
Generated
+1
@@ -393,6 +393,7 @@ dependencies = [
|
||||
name = "marqdo-host"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"glob",
|
||||
"libloading",
|
||||
"marqdo-foreign",
|
||||
|
||||
@@ -53,6 +53,7 @@ semver = "1"
|
||||
hex = "0.4"
|
||||
libloading = "0.8"
|
||||
tempfile = "3"
|
||||
getrandom = "0.4"
|
||||
thiserror = "2"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
walkdir = "2"
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+7
-6
@@ -58,7 +58,7 @@ byte-identical).
|
||||
cargo fmt --all -- --check PASS
|
||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||
cargo test --workspace --locked PASS
|
||||
479 passed, 0 failed, 2 ignored; includes 7/7 Linux security tests
|
||||
481 passed, 0 failed, 2 ignored; includes 7/7 Linux security tests
|
||||
```
|
||||
|
||||
The documentation and test migration is local work; re-run this block after it
|
||||
@@ -207,11 +207,12 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
|
||||
`clock.现在` reads `clock.now` in project mode (ADR-0042); `env.读取` reads
|
||||
only exact `--allow-env NAME` grants in project mode (ADR-0043); `process.运行`
|
||||
runs an exact `--allow-process PROGRAM` grant with 5 s timeout and 1 MiB caps
|
||||
(ADR-0044, not an OS sandbox). File watch, binary offset reads, streaming
|
||||
JSON/CSV, a JSON depth bound, regex groups/alternation, secure random and
|
||||
compression remain open.
|
||||
(ADR-0044, not an OS sandbox); `random.字节` reads explicitly granted
|
||||
`random.bytes` entropy (ADR-0046). File watch, binary offset reads, streaming
|
||||
JSON/CSV, a JSON depth bound, regex groups/alternation and compression remain
|
||||
open.
|
||||
- Bundled standard library (CM-A10, ADR-0028): `stdlib/` ships
|
||||
`format`/`text`/`io`/`fs`/`data`/`path`/`regex`/`datetime`/`clock`/`env`/`process`; explicit `std:` imports resolve only inside the bundle;
|
||||
`format`/`text`/`io`/`fs`/`data`/`path`/`regex`/`datetime`/`clock`/`env`/`process`/`random`; explicit `std:` imports resolve only inside the bundle;
|
||||
a SHA-256 digest over `*.mq.md` is verified before loading; Analysis records
|
||||
`project.stdlib`; a frozen-binary test asserts the CLI hash is unchanged after
|
||||
running a `std:io` project and that tampering is rejected. `打印/print` is
|
||||
@@ -237,7 +238,7 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
|
||||
status/index links and SHA-pinned evidence; `crates/cli/tests/architecture_boundaries.rs`
|
||||
pins the workspace graph, `marqdo-runtime -> marqdo-host`, the bundled stdlib
|
||||
digest and the stdio/file/TCP endpoints; `crates/cli/tests/stdlib_product.rs`
|
||||
runs every public stdlib module (`clock/console/csv/datetime/demo/env/format/fs/http/io/json/path/process/regex/stream/table/text/utf8`)
|
||||
runs every public stdlib module (`clock/console/csv/datetime/demo/env/format/fs/http/io/json/path/process/random/regex/stream/table/text/utf8`)
|
||||
through `std:` imports over `stdlib/tests/*.mq.md`. `tools/pack-stdlib.py`
|
||||
now sorts `.mq.md` by the same relative path key as the CLI. Source/test baseline
|
||||
`0d40de7`; later docs-only commits keep code/test bytes identical. Evidence:
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# ADR-0046: Explicitly granted `random.bytes`
|
||||
|
||||
Status: **Accepted**
|
||||
Date: 2026-11-21
|
||||
Relates to: ADR-0041
|
||||
Specs: `spec/security.md`, `spec/evaluation.md`
|
||||
Evidence: `docs/evidence/2026-11-21-random-product.md`
|
||||
|
||||
## Context
|
||||
|
||||
The standard library had no product entropy API. Reading `/dev/urandom` or
|
||||
using an OS RNG inside a Rust builtin would create an unaudited side channel
|
||||
and would make `pure` mode non-deterministic without an explicit grant.
|
||||
|
||||
## Decision
|
||||
|
||||
Add one project-mode operation:
|
||||
|
||||
```text
|
||||
resource.request("random.bytes", [count]) -> {ok:true, value:List<Int>}
|
||||
```
|
||||
|
||||
* `count` is an `Int` in `1..=65536`; other values are fatal type errors.
|
||||
* A new `Capabilities::random: bool` grant is required (`--allow-random`).
|
||||
Un-granted calls are `permission.denied`; `pure`/`strict` refuse.
|
||||
* Bytes come from the `getrandom` crate's OS entropy source; a source failure
|
||||
is a fatal `host.error`.
|
||||
* The operation returns a `List<Int>` of 0–255 values. It does not expose a
|
||||
`Memory` handle or raw pointer.
|
||||
* `stdlib/random.mq.md` exposes `字节(n)` and `整数(上限)`. `整数` combines
|
||||
eight bytes and takes a modulus; it is **not** claimed to be unbiased
|
||||
rejection sampling.
|
||||
* No new builtin or `HostOp` is added.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Entropy is opt-in per run and unavailable in pure/strict.
|
||||
* The API is byte-list based, so callers can build their own distributions in
|
||||
`.mq.md`; a cryptographically audited RNG API is out of scope.
|
||||
* A future unbiased integer helper or secure token API needs its own ADR.
|
||||
@@ -18,7 +18,7 @@ platform".
|
||||
| Dimension | Current state | Source |
|
||||
|---|---|---|
|
||||
| Implemented | Rust workspace `0.1.0`: Markdown/frontend/IR, tree-walk runtime, `Memory`, capability host, Tool/Analysis/Trace, Plugin ABI, Foreign kernels, bundled stdlib, CLI composition root | `Cargo.toml`, `crates/`, `stdlib/` |
|
||||
| Tested locally | `cargo test --workspace --locked`: **478 passed, 0 failed, 2 ignored** on Linux x86_64 at the baseline | `docs/STATUS.md` §3 |
|
||||
| Tested locally | `cargo test --workspace --locked`: **481 passed, 0 failed, 2 ignored** on Linux x86_64 at the baseline | `docs/STATUS.md` §3 |
|
||||
| Bundled stdlib released | In-repo bundle `marqdo-stdlib@0.1.0`, SHA-256 digest verified before loading; it is **not** an external registry package | `stdlib/stdlib.json`, `stdlib/README.md` |
|
||||
| Multi-platform verified | Linux local gate is the only executed lane here; Windows/macOS native lanes are **UNVERIFIED**, and the GitHub security lane remains a **VM-only** gate | `docs/STATUS.md` §1, §4 |
|
||||
|
||||
@@ -100,6 +100,7 @@ review RFC, not a new crate per provider.
|
||||
| `std:clock` | `clock.现在()` -> `resource.request("clock.now", [])` | implemented (project mode; pure/strict denied) | `resource_streams`, `stdlib_product` |
|
||||
| `std:env` | `env.读取/存在` -> `resource.request("env.get", [name])`; exact `--allow-env` grant | implemented (project mode; no `env.list`) | `resource_streams`, `stdlib_product` |
|
||||
| `std:process` | `process.运行(程序, 参数列表)` -> `resource.request("process.run", ...)`; exact `--allow-process` grant, 5 s timeout, 1 MiB caps | implemented (project mode; not an OS sandbox) | `resource_streams`, `stdlib_product` |
|
||||
| `std:random` | `random.字节/整数` -> `resource.request("random.bytes", [count])`; exact `--allow-random` grant | implemented (project mode; byte-list RNG) | `resource_streams`, `stdlib_product` |
|
||||
| file metadata / directory / rename / remove / mkdir | not part of the current Resource contract | **not implemented**; needs a separate Resource Operation ADR | — |
|
||||
| TCP | `resource.open("tcp", ip:port, ["read","write"])`; exact IP grant, 5 s timeout | implemented; no DNS/TLS/server socket/UDP | `tcp_endpoint`, `http_over_tcp` |
|
||||
| HTTP/1.1 | `stdlib/net/http.mq.md`: status/header/chunked-byte parse, request build | implemented over an already-authorized TCP stream; not a DNS/TLS client | `stdlib_http`, `http_over_tcp`, `stdlib_product` |
|
||||
@@ -131,7 +132,7 @@ that a phase is complete.
|
||||
| P1 | CLI split into `commands/{sandbox,run,check,inspect,init,package,tool}.rs`; host split into `host/{resource_ops,providers,effects,dispatch}.rs` plus `process.rs`; `commands.rs` keeps shared project/runtime helpers and `host.rs` keeps the `Host` trait methods and capability checks | split; shared helpers and trait methods remain by design |
|
||||
| P2 | HTTP parsing is Unicode-codepoint oriented; a general byte body is not the only path | open; convert before a general network release |
|
||||
| P2 | No DNS, TLS, listener or UDP provider | open |
|
||||
| P2 | `std:path`, a regex subset, `std:datetime`, `std:clock`, `std:env` and `std:process` are implemented; no secure random or compression | open |
|
||||
| P2 | `std:path`, a regex subset, `std:datetime`, `std:clock`, `std:env`, `std:process` and `std:random` are implemented; no compression | open |
|
||||
| P2 | Memory limits: 16 MiB per region, 64 MiB per run | current budget, not a product limit |
|
||||
| P3 | No concurrency tasks, atomics or cancellable long-running scheduling | open; separate ADR |
|
||||
| P3 | No native optimizer/JIT or columnar numeric backend | open; benchmark-first |
|
||||
@@ -166,5 +167,6 @@ that a phase is complete.
|
||||
- [ADR-0043: `env.get` resource operation](../adr/0043-env-resource-operation.md) — accepted exact-name environment grants.
|
||||
- [ADR-0044: `process.run` resource operation](../adr/0044-process-resource-operation.md) — accepted exact-path process grant; not a sandbox.
|
||||
- [ADR-0045: fs append/read_at/walk](../adr/0045-fs-append-read-at-walk.md) — accepted bounded content and directory walk.
|
||||
- [ADR-0046: `random.bytes`](../adr/0046-random-resource-operation.md) — accepted explicitly granted OS entropy.
|
||||
- [Compute-machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) and [core/stdlib RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) — design input.
|
||||
- [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) — review input for this migration.
|
||||
@@ -50,6 +50,7 @@ The implemented first slices of these RFCs are recorded in `CURRENT.md` and
|
||||
| `env.get` resource operation | [0043](../adr/0043-env-resource-operation.md) | Accepted (exact-name project grant) |
|
||||
| `process.run` resource operation | [0044](../adr/0044-process-resource-operation.md) | Accepted (exact program grant, project only, not a sandbox) |
|
||||
| `fs.append`/`fs.read_at`/`fs.walk` | [0045](../adr/0045-fs-append-read-at-walk.md) | Accepted (bounded content, directory walk) |
|
||||
| `random.bytes` resource operation | [0046](../adr/0046-random-resource-operation.md) | Accepted (explicit `--allow-random`, project only) |
|
||||
| Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication |
|
||||
|
||||
## Evidence and status
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# Evidence: `std:random` and `random.bytes`
|
||||
|
||||
Date: 2026-11-21 (Asia/Shanghai)
|
||||
Source baseline: `6338fa10e948d9f62f8eea84c793a0c4255e8d66`
|
||||
Repository: `marqdo-cli`
|
||||
Decision record: [ADR-0046](../adr/0046-random-resource-operation.md)
|
||||
|
||||
## Implemented
|
||||
|
||||
`resource.request("random.bytes", [count])` is project-mode only:
|
||||
|
||||
- count 1..=65536; other values are fatal type errors;
|
||||
- exact `--allow-random` grant required; pure/strict refuse;
|
||||
- bytes come from `getrandom::fill` and are returned as `List<Int>` 0–255;
|
||||
- one `resource.request` trace/effect event.
|
||||
|
||||
`stdlib/random.mq.md` exposes `字节(n)` and `整数(上限)` (8 bytes modulo
|
||||
upper bound; not claimed unbiased).
|
||||
|
||||
## Tests
|
||||
|
||||
`stdlib/tests/random.mq.md` runs with `--allow-random` and checks length and
|
||||
range. `crates/marqdo-host/tests/resource_streams.rs` pins grant denial,
|
||||
pure-mode refusal, byte range and count validation (25 host tests).
|
||||
|
||||
```text
|
||||
cargo fmt --all -- --check PASS
|
||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||
cargo test --workspace 481 passed, 0 failed, 2 ignored
|
||||
cargo test -p marqdo-host --test resource_streams 25 passed
|
||||
cargo test -p marqdo-cli --test stdlib_product 15 passed
|
||||
python3 tools/pack-stdlib.py PASS
|
||||
```
|
||||
|
||||
## Not covered
|
||||
|
||||
No unbiased rejection sampling, token/secret API, deterministic seed source or
|
||||
cryptographic post-processing. The byte list is plain OS entropy.
|
||||
+4
-1
@@ -210,6 +210,7 @@ resource.request("fs.read_at", [path, offset, len]) -> {ok:true, value:Text}
|
||||
resource.request("fs.walk", [dir]) -> {ok:true, value:List<Text>}
|
||||
resource.request("clock.now", []) -> {ok:true, value:UnixMillis}
|
||||
resource.request("env.get", [name]) -> {ok:true, value:Text}
|
||||
resource.request("random.bytes", [count]) -> {ok:true, value:List<Int>}
|
||||
resource.request("process.run", [program, args])-> {ok:true, value:{status, stdout, stderr}}
|
||||
```
|
||||
|
||||
@@ -239,6 +240,8 @@ resource.request("process.run", [program, args])-> {ok:true, value:{status, stdo
|
||||
* `env.get` takes one exact variable name and requires an `--allow-env NAME`
|
||||
grant; un-granted names are `permission.denied`, missing names are recoverable
|
||||
`env.not_found` and non-UTF-8 values are `env.not_unicode` (ADR-0043).
|
||||
* `random.bytes` takes an Int count in `1..=65536`, requires
|
||||
`--allow-random`, and returns a List of 0–255 OS entropy bytes (ADR-0046).
|
||||
* `process.run` takes an exact program path and a List of Text arguments,
|
||||
requires an `--allow-process PROGRAM` grant, runs without a shell with a
|
||||
cleared environment in the project root, and enforces a 5 second timeout and
|
||||
@@ -339,7 +342,7 @@ host boundary. Names are stable; adding one requires a spec update.
|
||||
| `resource.read` | `(handle, memory: Memory, offset: Int, max_bytes: Int) -> Result` | bounded chunk read into Memory; `{count,eof}` |
|
||||
| `resource.write` | `(handle, memory: Memory, offset: Int, length: Int) -> Result` | bounded byte write; `{count}` |
|
||||
| `resource.close` | `(handle) -> Result` | releases the host slot |
|
||||
| `resource.request` | `(operation: Text, arguments: List) -> Result` | non-streaming `fs.*` operations (ADR-0041) `clock.now` (ADR-0042), `env.get` (ADR-0043) and `process.run` (ADR-0044); project-mode and grant-checked |
|
||||
| `resource.request` | `(operation: Text, arguments: List) -> Result` | non-streaming `fs.*` operations (ADR-0041) `clock.now` (ADR-0042), `env.get` (ADR-0043), `process.run` (ADR-0044) and `random.bytes` (ADR-0046); project-mode and grant-checked |
|
||||
| `math.parse/eval/substitute` | see `spec/math.md` | P5; `math.simplify`/`math.differentiate` are declared but return `math.unsupported` in this build |
|
||||
| `foreign.run/call` | see `spec/foreign.md` | P5, capability-gated |
|
||||
| `fs.read/write` | see `spec/security.md` | capability-gated |
|
||||
|
||||
+6
-2
@@ -27,8 +27,8 @@ Normative implementation:
|
||||
| Mode | Intended guarantee | Actual status in this build |
|
||||
|---|---|---|
|
||||
| `pure` | No external I/O; memory computation and budgets only. | **Enforced.** `Capabilities::pure()` = `console`, `math` only; every FS/foreign/plugin grant flag makes the CLI exit 2 with "pure mode prohibits external I/O grants". |
|
||||
| `project` | Operator-approved project resources under `CapabilityHost` + bounded resources. | **Enforced for the implemented operations.** Defaults equal `pure`; `--allow-read`, `--allow-write`, `--allow-net`, `--allow-env`, `--allow-process`, `--allow-foreign`, `--allow-plugin` add grants. `resource.open` supports stdin read, separate stdout/stderr write, granted project-file read/write (ADR-0025/0026/0040), granted in-process provider kinds (ADR-0033) and granted IP-literal TCP streams (ADR-0034); process/device remain unsupported. Sandboxing is cooperative (in-process checks), not OS isolation; in-process providers are trusted, not sandboxed. |
|
||||
| `strict` | Untrusted documents under real OS isolation. | **Linux: enforced when the runtime probe passes (ADR-0021).** `resource.open` is **refused** in strict except for the existing `stdio/stdout` console channel (console grant); stdin/stderr, file/TCP/provider/process resources remain refused until a provider passes the isolation lane (CM-A11, ADR-0030/0034/0040). `PlatformCapabilities::detect()` runs a real Bubblewrap smoke test; success reports `Available { mechanism }`, failure reports `Unavailable { reason }`. Strict L1 supports the interpreter, console, native Math and the read-only bundled stdlib (published at `/run/marqdo-stdlib` for the Compat-C print chain); `--allow-read/--allow-write/--allow-net/--allow-env/--allow-process/--allow-foreign/--allow-plugin/--plugin/--trust-native-plugin/--kernel/--trace-file` are rejected with exit 2. macOS/Windows and Linux hosts without the mechanisms remain `Unavailable`; there is **no fallback** to an unrestricted process. |
|
||||
| `project` | Operator-approved project resources under `CapabilityHost` + bounded resources. | **Enforced for the implemented operations.** Defaults equal `pure`; `--allow-read`, `--allow-write`, `--allow-net`, `--allow-env`, `--allow-process`, `--allow-random`, `--allow-foreign`, `--allow-plugin` add grants. `resource.open` supports stdin read, separate stdout/stderr write, granted project-file read/write (ADR-0025/0026/0040), granted in-process provider kinds (ADR-0033) and granted IP-literal TCP streams (ADR-0034); process/device remain unsupported. Sandboxing is cooperative (in-process checks), not OS isolation; in-process providers are trusted, not sandboxed. |
|
||||
| `strict` | Untrusted documents under real OS isolation. | **Linux: enforced when the runtime probe passes (ADR-0021).** `resource.open` is **refused** in strict except for the existing `stdio/stdout` console channel (console grant); stdin/stderr, file/TCP/provider/process resources remain refused until a provider passes the isolation lane (CM-A11, ADR-0030/0034/0040). `PlatformCapabilities::detect()` runs a real Bubblewrap smoke test; success reports `Available { mechanism }`, failure reports `Unavailable { reason }`. Strict L1 supports the interpreter, console, native Math and the read-only bundled stdlib (published at `/run/marqdo-stdlib` for the Compat-C print chain); `--allow-read/--allow-write/--allow-net/--allow-env/--allow-process/--allow-random/--allow-foreign/--allow-plugin/--plugin/--trust-native-plugin/--kernel/--trace-file` are rejected with exit 2. macOS/Windows and Linux hosts without the mechanisms remain `Unavailable`; there is **no fallback** to an unrestricted process. |
|
||||
|
||||
`marqdo inspect <file> --platform` prints the detection report, for example:
|
||||
|
||||
@@ -62,6 +62,7 @@ set for one run:
|
||||
| `net_hosts: Vec<String>` | empty | exact IP-literal grants for `resource.open("tcp", "<ip>:<port>", ["read","write"])`; DNS is not resolved; `--allow-net <IP>` adds a grant (ADR-0034) |
|
||||
| `env: Vec<String>` | empty | exact-name grants for `resource.request("env.get", [name])`; no glob and no `env.list`; `--allow-env <NAME>` adds a grant (ADR-0043) |
|
||||
| `process_programs: Vec<String>` | empty | exact program paths for `resource.request("process.run", [program, args])`; no shell, `env_clear`, project root cwd, 5 s timeout, 1 MiB stdout/stderr cap; `--allow-process <PROGRAM>` adds a grant (ADR-0044); not an OS sandbox |
|
||||
| `random: bool` | `false` | OS entropy for `resource.request("random.bytes", [count])`; `--allow-random` enables it; project mode only (ADR-0046) |
|
||||
| `process: bool` | `false` | required together with `foreign` for `foreign.run`/`foreign.call` |
|
||||
| `foreign: bool` | `false` | foreign kernels |
|
||||
| `plugins: Vec<String>` | empty | `plugin.invoke` and `StdHost::load_plugin` |
|
||||
@@ -84,6 +85,7 @@ Requests versus grants:
|
||||
mode only, ADR-0043);
|
||||
* `--allow-process <PROGRAM>` (repeatable, exact program path, project mode
|
||||
only, ADR-0044; the child is not sandboxed);
|
||||
* `--allow-random` (project mode only; OS entropy, ADR-0046);
|
||||
* `--allow-foreign` (project mode only; sets `foreign = true` and
|
||||
`process = true`);
|
||||
* `--allow-plugin <PACKAGE-NAME>` (repeatable, project mode only; matches the
|
||||
@@ -130,6 +132,8 @@ before reading. Full symlink/race hardening is an open P4 item.
|
||||
`std::env::var`;
|
||||
* `resource.request("process.run")` → `capabilities.check_process(program)`
|
||||
before `Command::spawn`;
|
||||
* `resource.request("random.bytes")` → `capabilities.check_random` before
|
||||
`getrandom::fill`;
|
||||
* `fs.write` → `check_write` then `ProjectFs::write`;
|
||||
* math ops → `capabilities.math` (in `crates/marqdo-host/src/kernels.rs`);
|
||||
* foreign ops → `capabilities.check_foreign` (requires `foreign && process`);
|
||||
|
||||
+2
-1
@@ -17,6 +17,7 @@ module; a mismatch is a hard error.
|
||||
- `data/table.mq.md` — value-returning table select/filter/sort/append/set/join/group/GFM
|
||||
- `env.mq.md` — explicitly granted `env.get` names over `resource.request`
|
||||
- `process.mq.md` — explicitly granted `process.run` with timeout/output caps
|
||||
- `random.mq.md` — explicitly granted OS entropy bytes/integers
|
||||
- `datetime.mq.md` — UTC ISO-8601 format/parse over Unix milliseconds (pure)
|
||||
- `clock.mq.md` — project-mode `clock.now` over `resource.request`
|
||||
- `path.mq.md` — lexical join/basename/dirname/extension/normalize (no I/O)
|
||||
@@ -24,7 +25,7 @@ module; a mismatch is a hard error.
|
||||
- `net/http.mq.md` — HTTP/1.1 response parsing (headers/chunked) and request builder
|
||||
- `tests/` — product self-tests for every public module
|
||||
(`clock`, `console`, `csv`, `datetime`, `demo`, `env`, `format`, `fs`, `http`,
|
||||
`io`, `json`, `path`, `process`, `regex`, `stream`, `table`, `text`, `utf8`)
|
||||
`io`, `json`, `path`, `process`, `random`, `regex`, `stream`, `table`, `text`, `utf8`)
|
||||
|
||||
The digest is a SHA-256 over sorted `*.mq.md` relative paths, a NUL, file
|
||||
bytes, and a NUL. It excludes `stdlib.json` and non-`.mq.md` files. After any
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
## 字节
|
||||
|
||||
`(数量)`
|
||||
|
||||
读取 `数量` 个 OS 熵字节,返回 `List<Int>`(每个 0–255)。仅项目模式,
|
||||
需要显式 `--allow-random`;`pure`/`strict` 拒绝。
|
||||
|
||||
*resource.request("random.bytes", [数量])*
|
||||
|
||||
## 整数
|
||||
|
||||
`(上限)`
|
||||
|
||||
返回 `0 <= 值 < 上限` 的整数。`上限` 必须大于 0;使用 8 个熵字节
|
||||
组合后取模(无偏拒绝采样尚未实现)。
|
||||
|
||||
1. `上限 <= 0`
|
||||
|
||||
*{ok: false, code: "random.invalid", message: "上限必须大于 0"}*
|
||||
|
||||
**字节结果 = 字节(8)**
|
||||
|
||||
1. `not 字节结果.ok`
|
||||
|
||||
*字节结果*
|
||||
|
||||
**值 = 0**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 8`
|
||||
|
||||
**值 = 值 * 256 + 字节结果.value[下标]**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*{ok: true, value: 值 % 上限}*
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "marqdo-stdlib",
|
||||
"version": "0.1.0",
|
||||
"digest": "sha256:6974496a9826f977189804bae0959e494bfc7443543ed4afffcea1ac390b0ce9"
|
||||
"digest": "sha256:171c0d31cab5ae70ce6b16fc4c1cf819ab5a8e1895a801d5b2286b642dee5866"
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
import:
|
||||
random: "std:random"
|
||||
---
|
||||
|
||||
## main
|
||||
|
||||
**字节结果 = random.字节(16)**
|
||||
|
||||
**整数结果 = random.整数(100)**
|
||||
|
||||
*[字节结果.ok, 长度(字节结果.value), 整数结果.ok, 整数结果.value >= 0, 整数结果.value < 100]*
|
||||
Reference in new issue
Block a user