diff --git a/crates/test-programs/src/bin/p3_cli_random_limits.rs b/crates/test-programs/src/bin/p3_cli_random_limits.rs new file mode 100644 index 000000000000..b4212dceee87 --- /dev/null +++ b/crates/test-programs/src/bin/p3_cli_random_limits.rs @@ -0,0 +1,26 @@ +use test_programs::p3::wasi::random; + +struct Component; + +test_programs::p3::export!(Component); + +impl test_programs::p3::exports::wasi::cli::run::Guest for Component { + async fn run() -> Result<(), ()> { + let args = std::env::args().collect::>(); + let args = args.iter().map(|s| s.as_str()).collect::>(); + match &args[1..] { + ["random", n] => { + random::random::get_random_bytes(n.parse().unwrap()); + } + ["insecure", n] => { + random::insecure::get_insecure_random_bytes(n.parse().unwrap()); + } + other => { + panic!("unexpected args: {other:?}"); + } + } + Ok(()) + } +} + +fn main() {} diff --git a/crates/wasi/src/p3/random/host.rs b/crates/wasi/src/p3/random/host.rs index 03f106a078ff..163248fcd5fd 100644 --- a/crates/wasi/src/p3/random/host.rs +++ b/crates/wasi/src/p3/random/host.rs @@ -1,11 +1,14 @@ -use cap_rand::Rng; -use cap_rand::distributions::Standard; - use crate::p3::bindings::random::{insecure, insecure_seed, random}; use crate::random::WasiRandomCtx; +use cap_rand::Rng; +use cap_rand::distributions::Standard; +use wasmtime::bail; impl random::Host for WasiRandomCtx { fn get_random_bytes(&mut self, len: u64) -> wasmtime::Result> { + if len > self.max_size { + bail!("requested len {len:?} exceeds limit {}", self.max_size); + } Ok((&mut self.random) .sample_iter(Standard) .take(len as usize) @@ -19,6 +22,9 @@ impl random::Host for WasiRandomCtx { impl insecure::Host for WasiRandomCtx { fn get_insecure_random_bytes(&mut self, len: u64) -> wasmtime::Result> { + if len > self.max_size { + bail!("requested len {len:?} exceeds limit {}", self.max_size); + } Ok((&mut self.insecure_random) .sample_iter(Standard) .take(len as usize) diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rs index 122181e2883c..4aaa0d692f1b 100644 --- a/tests/all/cli_tests.rs +++ b/tests/all/cli_tests.rs @@ -2757,6 +2757,29 @@ start a print 1234 } Ok(()) } + + #[test] + fn p3_cli_random_limits() -> Result<()> { + let c = P3_CLI_RANDOM_LIMITS_COMPONENT; + + for rand in ["random", "insecure"] { + run_wasmtime(&["run", "-Sp3", "-Wcomponent-model-async", c, rand, "256"])?; + assert!( + run_wasmtime(&[ + "run", + "-Sp3", + "-Wcomponent-model-async", + "-Smax-random-size=255", + c, + rand, + "256" + ]) + .is_err() + ); + } + + Ok(()) + } } #[test]