A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
cli: reject zero timeouts (#15143)
Xia Chaod1c3c60d43c8
diff --git a/crates/cli-flags/src/lib.rs b/crates/cli-flags/src/lib.rsindex 06101fbc40..ac681f55f7 100644--- a/crates/cli-flags/src/lib.rs+++ b/crates/cli-flags/src/lib.rs@@ -11,8 +11,9 @@//! is the [`Config`] type but this additionally serves as a means of creating//! that type.+use crate::opt::NonzeroDuration;use std::num::NonZeroUsize;-use std::{fmt, num::NonZeroU32, path::PathBuf, time::Duration};+use std::{fmt, num::NonZeroU32, path::PathBuf};use wasmtime::{Config, Engine, Result, WasmBacktraceDetails, WasmFeatures, bail};pub mod opt;@@ -451,7 +452,7 @@ wasmtime_option_group! {/// Note that when this option is not set, malicious wasm code may/// cause the host process to become unresponsive to inputs including/// SIGTERM.- pub timeout: Option<Duration>,+ pub timeout: Option<NonzeroDuration>,/// Configures support for all WebAssembly proposals implemented.pub all_proposals: Option<bool>,/// Configure support for the bulk memory proposal.diff --git a/crates/cli-flags/src/opt.rs b/crates/cli-flags/src/opt.rsindex df1d3674f3..b0aad8b45c 100644--- a/crates/cli-flags/src/opt.rs+++ b/crates/cli-flags/src/opt.rs@@ -517,6 +517,46 @@ impl WasmtimeOptionValue for bool {}}+/// A duration parsed from CLI options, rejecting zero.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+#[cfg_attr(+ feature = "serde",+ derive(serde_derive::Serialize, serde_derive::Deserialize)+)]+pub struct NonzeroDuration(Duration);++impl NonzeroDuration {+ /// Returns `None` if `duration` is zero.+ pub fn new(duration: Duration) -> Option<Self> {+ if duration.is_zero() {+ None+ } else {+ Some(Self(duration))+ }+ }+}++impl std::ops::Deref for NonzeroDuration {+ type Target = Duration;++ fn deref(&self) -> &Duration {+ &self.0+ }+}++impl WasmtimeOptionValue for NonzeroDuration {+ const VAL_HELP: &'static str = "=N|Ns|Nms|..";++ fn parse(val: Option<&str>) -> Result<Self> {+ let duration = <Duration as WasmtimeOptionValue>::parse(val)?;+ Self::new(duration).ok_or_else(|| format_err!("duration must not be zero"))+ }++ fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ <Duration as WasmtimeOptionValue>::display(&self.0, f)+ }+}+impl WasmtimeOptionValue for Duration {const VAL_HELP: &'static str = "=N|Ns|Nms|..";fn parse(val: Option<&str>) -> Result<Duration> {@@ -882,11 +922,33 @@ where#[cfg(test)]mod tests {- use super::WasmtimeOptionValue;+ use super::{NonzeroDuration, WasmtimeOptionValue};+ use std::time::Duration;#[test]fn numbers_with_underscores() {assert!(<u32 as WasmtimeOptionValue>::parse(Some("123")).is_ok_and(|v| v == 123));assert!(<u32 as WasmtimeOptionValue>::parse(Some("1_2_3")).is_ok_and(|v| v == 123));}++ #[test]+ fn nonzero_durations() {+ for (input, expected) in [+ ("0", None),+ ("0s", None),+ ("0ms", None),+ ("0us", None),+ ("0ns", None),+ ("1", Some(Duration::from_secs(1))),+ ("1s", Some(Duration::from_secs(1))),+ ("1ms", Some(Duration::from_millis(1))),+ ("1us", Some(Duration::from_micros(1))),+ ("1ns", Some(Duration::from_nanos(1))),+ ] {+ let actual = <NonzeroDuration as WasmtimeOptionValue>::parse(Some(input))+ .ok()+ .map(|d| *d);+ assert_eq!(actual, expected, "input = {input}");+ }+ }}diff --git a/src/commands/run.rs b/src/commands/run.rsindex ac24819a21..92183001b2 100644--- a/src/commands/run.rs+++ b/src/commands/run.rs@@ -420,6 +420,7 @@ impl RunCommand {.common.wasm.timeout+ .map(|t| *t).unwrap_or(std::time::Duration::MAX);let result = tokio::time::timeout(dur, async {let mut profiled_modules: Vec<(String, Module)> = Vec::new();@@ -575,7 +576,7 @@ impl RunCommand {store.set_epoch_deadline(1);let engine = store.engine().clone();thread::spawn(move || {- thread::sleep(timeout);+ thread::sleep(*timeout);engine.increment_epoch();});}diff --git a/src/commands/serve.rs b/src/commands/serve.rsindex dd67e25043..b2daf5f904 100644--- a/src/commands/serve.rs+++ b/src/commands/serve.rs@@ -28,7 +28,7 @@ use wasmtime::error::Context as _;use wasmtime::{AsContextMut as _, Engine, Result, Store, StoreContextMut, StoreLimits, UpdateDeadline, bail,};-use wasmtime_cli_flags::opt::WasmtimeOptionValue;+use wasmtime_cli_flags::opt::{NonzeroDuration, WasmtimeOptionValue};use wasmtime_wasi::p2::{StreamError, StreamResult};use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};use wasmtime_wasi_http::handler::{@@ -103,6 +103,10 @@ fn parse_duration(s: &str) -> Result<Duration, String> {Duration::parse(Some(s)).map_err(|e| e.to_string())}+fn parse_nonzero_duration(s: &str) -> Result<NonzeroDuration, String> {+ NonzeroDuration::parse(Some(s)).map_err(|e| e.to_string())+}+/// Runs a WebAssembly module#[derive(Parser)]pub struct ServeCommand {@@ -182,8 +186,8 @@ pub struct ServeCommand {/// A number with no suffix or with an `s` suffix is interpreted as seconds;/// other accepted suffixes include `ms` (milliseconds), `us` or `μs`/// (microseconds), and `ns` (nanoseconds).- #[arg(long, value_parser = parse_duration)]- post_return_timeout: Option<Duration>,+ #[arg(long, value_parser = parse_nonzero_duration)]+ post_return_timeout: Option<NonzeroDuration>,/// Optional maximum idle time before exiting the process.///@@ -743,7 +747,7 @@ impl ServeCommand {.flatten().min(){- Some(EPOCH_INTERRUPT_PERIOD.min(t))+ Some(EPOCH_INTERRUPT_PERIOD.min(*t))} else if debuggee_store.is_some() {Some(Duration::from_millis(1))} else {@@ -1067,8 +1071,19 @@ impl HandlerState for HostHandlerState {.new_store(self.component.engine(), Some(instance_id))?;let proxy = self.instantiate_into(&mut store).await?;- let request_timeout = self.cmd.run.common.wasm.timeout.unwrap_or(Duration::MAX);- let post_return_timeout = self.cmd.post_return_timeout.unwrap_or(request_timeout);+ let request_timeout = self+ .cmd+ .run+ .common+ .wasm+ .timeout+ .map(|t| *t)+ .unwrap_or(Duration::MAX);+ let post_return_timeout = self+ .cmd+ .post_return_timeout+ .map(|t| *t)+ .unwrap_or(request_timeout);Ok(Instance {store,diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rsindex f9337994b3..799f3e927b 100644--- a/tests/all/cli_tests.rs+++ b/tests/all/cli_tests.rs@@ -1966,6 +1966,63 @@ mod test_programs {Ok(())}+ #[test]+ fn p2_cli_zero_idle_timeouts_still_accepted() -> Result<()> {+ // Only `-W timeout` and `--post-return-timeout` reject zero.+ let component = P2_CLI_SERVE_HELLO_WORLD_COMPONENT;+ for option in ["--idle-process-timeout=0", "--idle-instance-timeout=0"] {+ let mut cmd = super::get_wasmtime_command()?;+ cmd.args(["serve", "-Scli", option, "--addr", "127.0.0.1:0", component])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::piped());+ let mut child = cmd.spawn()?;+ thread::sleep(Duration::from_millis(800));+ assert!(+ child.try_wait()?.is_none(),+ "`{option}` should still be accepted"+ );+ child.kill()?;+ child.wait()?;+ }++ Ok(())+ }++ #[test]+ fn p2_cli_reject_zero_timeouts() -> Result<()> {+ // A zero timeout makes the epoch thread spin at 100% CPU.+ let component = P2_CLI_SERVE_HELLO_WORLD_COMPONENT;+ for args in [+ &["serve", "-Scli", "-W", "timeout=0", component][..],+ &["serve", "-Scli", "--post-return-timeout", "0", component][..],+ ] {+ let mut cmd = super::get_wasmtime_command()?;+ cmd.args(args)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::piped());+ let mut child = cmd.spawn()?;+ let deadline = std::time::Instant::now() + Duration::from_secs(10);+ while child.try_wait()?.is_none() {+ assert!(+ std::time::Instant::now() < deadline,+ "zero timeout was accepted and the server kept running"+ );+ thread::sleep(Duration::from_millis(100));+ }+ let output = child.wait_with_output()?;+ assert!(!output.status.success(), "zero timeout was accepted");+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("duration must not be zero"),+ "expected zero timeout to be rejected, got: {stderr}"+ );+ }++ Ok(())+ }+#[test]fn p2_cli_run_outgoing_body_chunk_size() -> Result<()> {// Without the option an outgoing body keeps its 1 MiB default budget.