From 0a6f661a61f420bcce1530cec471a207367b5e8f Mon Sep 17 00:00:00 2001 From: Blake Kostner Date: Fri, 2 Oct 2026 07:30:21 -0700 Subject: [PATCH 1/4] Add durable_object Container exec() and per-call image/instance sizing worker-sys: extend the Container extern block with exec()/ExecProcess/ ExecOutput, binding Cloudflare's exec() API for running an additional process inside an already-running container and reading its exit code and buffered stdout/stderr. worker: extend ContainerStartupOptions with image/instance/ container_snapshot/labels (the durable_object scheduling policy's additional ctx.container.start() fields, previously unavailable; the default policy's image/instance come from Wrangler config instead) and add idiomatic Container::exec()/ExecProcess/ExecOutput wrappers. Source: https://developers.cloudflare.com/containers/api/durable-object-container/ and https://developers.cloudflare.com/containers/configuration/scheduling-policy/, checked 2026-10-02. --- ...urable-object-container-exec-and-sizing.md | 29 ++ .../src/types/durable_object/container.rs | 61 ++++- worker/src/container.rs | 256 +++++++++++++++++- 3 files changed, 344 insertions(+), 2 deletions(-) create mode 100644 .changeset/durable-object-container-exec-and-sizing.md diff --git a/.changeset/durable-object-container-exec-and-sizing.md b/.changeset/durable-object-container-exec-and-sizing.md new file mode 100644 index 000000000..6f4121f08 --- /dev/null +++ b/.changeset/durable-object-container-exec-and-sizing.md @@ -0,0 +1,29 @@ +--- +"workers-rs": minor +--- + +Add `durable_object`-scheduling-policy `Container::start` options +(`image`, `instance`, `container_snapshot`, `labels`) and a +`Container::exec`/`ExecProcess`/`ExecOutput` binding for running and reading +the exit status of a process inside an already-running container. + +`ContainerStartupOptions` previously exposed only `entrypoint`, +`enable_internet`, and `env`, which are the fields the `default` scheduling +policy's `start()` call accepts. The `durable_object` scheduling policy's +`ctx.container.start()` additionally accepts `image` (required unless +`containerSnapshot` is set), `instance` (named size or custom +`{ vcpu, memoryMib, diskMb}`), `containerSnapshot`, and `labels`. These are +now available via `ContainerStartupOptions::set_image`, +`set_instance`/`set_custom_instance`, `set_container_snapshot`, and +`add_label`. + +`Container` previously had no binding for `exec()`, so a Rust Worker could +start a container and `wait_for_exit()` but could not run an additional +process inside it or read a granular exit code without destroying the whole +container. `Container::exec(cmd, options)` now returns an `ExecProcess` with +`pid()`, `exit_code()`, `output()` (an `ExecOutput` with `exit_code()`, +`stdout()`, `stderr()`), and `kill()`. + +Source: +and , +checked 2026-10-02. diff --git a/worker-sys/src/types/durable_object/container.rs b/worker-sys/src/types/durable_object/container.rs index 7446aed36..35a77a88b 100644 --- a/worker-sys/src/types/durable_object/container.rs +++ b/worker-sys/src/types/durable_object/container.rs @@ -1,4 +1,4 @@ -use js_sys::{Object, Promise}; +use js_sys::{ArrayBuffer, Object, Promise}; use wasm_bindgen::prelude::*; use crate::Fetcher; @@ -11,12 +11,30 @@ use crate::Fetcher; /// destroy(error?: any): Promise; /// signal(signo: number): void; /// getTcpPort(port: number): Fetcher; +/// exec(cmd: string[], options?: ContainerExecOptions): Promise; /// } /// /// interface ContainerStartupOptions { /// entrypoint?: string[]; /// enableInternet: boolean; /// env?: Record; +/// // `durable_object` scheduling policy only. +/// image?: string; +/// instance?: string | { vcpu: number; memoryMib: number; diskMb: number }; +/// containerSnapshot?: ContainerSnapshotRestoreParams; +/// labels?: Record; +/// } +/// +/// interface ExecProcess { +/// readonly pid: number; +/// readonly exitCode: Promise; +/// output(): Promise; +/// } +/// +/// interface ExecOutput { +/// readonly exitCode: number; +/// readonly stdout: ArrayBuffer; +/// readonly stderr: ArrayBuffer; /// } /// ``` @@ -43,4 +61,45 @@ extern "C" { #[wasm_bindgen(method, catch, js_name=getTcpPort)] pub fn get_tcp_port(this: &Container, port: u16) -> Result; + + /// Starts another process inside an already-running container. `cmd` is the + /// executable followed by its arguments; `options` is a `ContainerExecOptions` + /// object (or `undefined`). + #[wasm_bindgen(method, catch)] + pub fn exec(this: &Container, cmd: Vec, options: &JsValue) + -> Result; + + #[wasm_bindgen(extends=Object)] + #[derive(Debug, Clone, PartialEq, Eq)] + pub type ExecProcess; + + #[wasm_bindgen(method, getter, js_name=pid)] + pub fn pid(this: &ExecProcess) -> u32; + + /// Resolves with the process's exit code when it exits. Nonzero codes + /// resolve normally instead of rejecting. + #[wasm_bindgen(method, getter, js_name=exitCode)] + pub fn exit_code(this: &ExecProcess) -> Promise; + + /// Reads buffered output once. Throws (via the rejected `Promise`) when + /// called more than once or after a readable stream has been consumed. + #[wasm_bindgen(method, catch)] + pub fn output(this: &ExecProcess) -> Result; + + /// Queues a signal for the process; default is `SIGTERM` (15). + #[wasm_bindgen(method, catch)] + pub fn kill(this: &ExecProcess, signal: Option) -> Result<(), JsValue>; + + #[wasm_bindgen(extends=Object)] + #[derive(Debug, Clone, PartialEq, Eq)] + pub type ExecOutput; + + #[wasm_bindgen(method, getter, js_name=exitCode)] + pub fn exit_code(this: &ExecOutput) -> u32; + + #[wasm_bindgen(method, getter, js_name=stdout)] + pub fn stdout(this: &ExecOutput) -> ArrayBuffer; + + #[wasm_bindgen(method, getter, js_name=stderr)] + pub fn stderr(this: &ExecOutput) -> ArrayBuffer; } diff --git a/worker/src/container.rs b/worker/src/container.rs index 8c69c6675..dc50a3680 100644 --- a/worker/src/container.rs +++ b/worker/src/container.rs @@ -1,5 +1,5 @@ use js_sys::futures::JsFuture; -use js_sys::{Map, Object, Reflect}; +use js_sys::{Map, Object, Reflect, Uint8Array}; use wasm_bindgen::prelude::*; use crate::{Fetcher, Result}; @@ -44,6 +44,28 @@ impl Container { .map(|f| f.into()) .map_err(|e| e.into()) } + + /// Starts another process inside an already-running container. `cmd` is + /// the executable followed by its arguments; it does not start a shell, + /// so shell syntax (pipes, redirects, expansion) is not interpreted. + /// Does not start a stopped container: call this only after confirming + /// [`Container::running`]. + pub async fn exec( + &self, + cmd: &[&str], + options: Option, + ) -> Result { + let cmd: Vec = cmd.iter().map(|s| JsValue::from_str(s)).collect(); + let options = match options { + Some(o) => o.into(), + None => JsValue::undefined(), + }; + let promise = self.inner.exec(cmd, &options)?; + let process = JsFuture::from(promise).await?; + Ok(ExecProcess { + inner: process.unchecked_into(), + }) + } } unsafe impl Sync for Container {} @@ -88,6 +110,29 @@ pub struct ContainerStartupOptions { #[wasm_bindgen(js_name = "enableInternet")] pub enable_internet: Option, pub env: Map, + /// Image reference to start, e.g. a value from `ctx.container.images` or + /// the `cloudflare/debian-trixie` managed image. `durable_object` + /// scheduling policy only; required unless `container_snapshot` is set. + /// Setting both `image` and `container_snapshot` makes `start()` throw a + /// `TypeError`. + pub image: Option, + /// Named instance size (`"lite"`, `"standard-1"`, `"standard-2"`, + /// `"standard-3"`, or `"standard-4"`) or a custom size object. Defaults + /// to `"lite"` when unset. `durable_object` scheduling policy only. + /// + /// The runtime rejects `"basic"` and the legacy `"dev"`/`"standard"` + /// aliases here: those names are only valid as a `default`-policy + /// Wrangler `instance_type`, not as a per-call `durable_object` size. + /// Source: , + /// checked 2026-10-02. + pub instance: Option, + /// Snapshot handle to restore before startup, in place of `image`. + /// `durable_object` scheduling policy only. + #[wasm_bindgen(js_name = "containerSnapshot")] + pub container_snapshot: Option, + /// Up to 10 labels that `inspect()` returns. Label names must contain 1 + /// to 16 bytes; values up to 64 bytes. + pub labels: Map, } impl ContainerStartupOptions { @@ -96,6 +141,10 @@ impl ContainerStartupOptions { entrypoint: Vec::new(), enable_internet: None, env: Map::new(), + image: None, + instance: None, + container_snapshot: None, + labels: Map::new(), } } @@ -111,6 +160,57 @@ impl ContainerStartupOptions { self.env .set(&JsValue::from_str(key), &JsValue::from_str(value)); } + + /// Sets the image reference to start (`durable_object` scheduling + /// policy only). Mutually exclusive with `set_container_snapshot`. + pub fn set_image(&mut self, image: &str) { + self.image = Some(image.to_string()); + } + + /// Sets a named instance size. See the `instance` field docs for the + /// accepted names and the `basic`/`default`-policy caveat. + pub fn set_instance(&mut self, instance: &str) { + self.instance = Some(JsValue::from_str(instance)); + } + + /// Sets a custom instance size. `memory_mib` is in mebibytes and + /// `disk_mb` is in megabytes; both must be positive integers within the + /// platform's custom-instance limits. + pub fn set_custom_instance(&mut self, vcpu: u32, memory_mib: u32, disk_mb: u32) { + let obj = Object::new(); + Reflect::set( + &obj, + &JsValue::from_str("vcpu"), + &JsValue::from_f64(vcpu as f64), + ) + .unwrap(); + Reflect::set( + &obj, + &JsValue::from_str("memoryMib"), + &JsValue::from_f64(memory_mib as f64), + ) + .unwrap(); + Reflect::set( + &obj, + &JsValue::from_str("diskMb"), + &JsValue::from_f64(disk_mb as f64), + ) + .unwrap(); + self.instance = Some(obj.into()); + } + + /// Sets the snapshot to restore before startup, by the id returned from + /// `snapshotContainer()`. Mutually exclusive with `set_image`. + pub fn set_container_snapshot(&mut self, id: &str) { + let obj = Object::new(); + Reflect::set(&obj, &JsValue::from_str("id"), &JsValue::from_str(id)).unwrap(); + self.container_snapshot = Some(obj.into()); + } + + pub fn add_label(&mut self, key: &str, value: &str) { + self.labels + .set(&JsValue::from_str(key), &JsValue::from_str(value)); + } } impl From for Object { @@ -125,6 +225,160 @@ impl From for Object { if options.env.size() != 0 { Reflect::delete_property(&obj, &JsValue::from_str("env")).unwrap(); } + if options.image.is_none() { + Reflect::delete_property(&obj, &JsValue::from_str("image")).unwrap(); + } + if options.instance.is_none() { + Reflect::delete_property(&obj, &JsValue::from_str("instance")).unwrap(); + } + if options.container_snapshot.is_none() { + Reflect::delete_property(&obj, &JsValue::from_str("containerSnapshot")).unwrap(); + } + if options.labels.size() == 0 { + Reflect::delete_property(&obj, &JsValue::from_str("labels")).unwrap(); + } obj } } + +impl Default for ContainerStartupOptions { + fn default() -> Self { + Self::new() + } +} + +/// Options for [`Container::exec`]. Streaming `stdin` is not exposed by this +/// wrapper; omitting it closes standard input and sends EOF immediately, +/// matching the JS default. +#[wasm_bindgen(getter_with_clone)] +#[derive(Debug, Clone)] +pub struct ContainerExecOptions { + pub cwd: Option, + pub env: Map, + pub user: Option, + /// `"pipe"` (default) or `"ignore"`. + pub stdout: Option, + /// `"pipe"` (default), `"ignore"`, or `"combined"`. + pub stderr: Option, +} + +impl ContainerExecOptions { + pub fn new() -> ContainerExecOptions { + ContainerExecOptions { + cwd: None, + env: Map::new(), + user: None, + stdout: None, + stderr: None, + } + } + + pub fn set_cwd(&mut self, cwd: &str) { + self.cwd = Some(cwd.to_string()); + } + + pub fn add_env(&mut self, key: &str, value: &str) { + self.env + .set(&JsValue::from_str(key), &JsValue::from_str(value)); + } + + /// Sets the Linux user and group id the process runs as. + pub fn set_user(&mut self, uid: u32, gid: u32) { + self.user = Some(format!("{uid}:{gid}")); + } + + /// `"pipe"` (default) or `"ignore"`. + pub fn set_stdout(&mut self, mode: &str) { + self.stdout = Some(mode.to_string()); + } + + /// `"pipe"` (default), `"ignore"`, or `"combined"`. + pub fn set_stderr(&mut self, mode: &str) { + self.stderr = Some(mode.to_string()); + } +} + +impl From for Object { + fn from(options: ContainerExecOptions) -> Self { + let obj = options.clone().into(); + if options.cwd.is_none() { + Reflect::delete_property(&obj, &JsValue::from_str("cwd")).unwrap(); + } + if options.env.size() == 0 { + Reflect::delete_property(&obj, &JsValue::from_str("env")).unwrap(); + } + if options.user.is_none() { + Reflect::delete_property(&obj, &JsValue::from_str("user")).unwrap(); + } + if options.stdout.is_none() { + Reflect::delete_property(&obj, &JsValue::from_str("stdout")).unwrap(); + } + if options.stderr.is_none() { + Reflect::delete_property(&obj, &JsValue::from_str("stderr")).unwrap(); + } + obj + } +} + +impl Default for ContainerExecOptions { + fn default() -> Self { + Self::new() + } +} + +/// A process started inside a running container via [`Container::exec`]. +#[derive(Debug)] +pub struct ExecProcess { + inner: worker_sys::ExecProcess, +} + +impl ExecProcess { + pub fn pid(&self) -> u32 { + self.inner.pid() + } + + /// Resolves when the process exits. Nonzero exit codes resolve + /// normally; they do not produce an `Err`. + pub async fn exit_code(&self) -> Result { + let promise = self.inner.exit_code(); + let value = JsFuture::from(promise).await?; + Ok(value.as_f64().unwrap_or_default() as u32) + } + + /// Reads buffered standard output/error and the exit code once. Throws + /// when called more than once or after a readable stream has started + /// being consumed. + pub async fn output(&self) -> Result { + let promise = self.inner.output()?; + let value = JsFuture::from(promise).await?; + Ok(ExecOutput { + inner: value.unchecked_into(), + }) + } + + /// Queues a signal for the process; `None` sends the default + /// `SIGTERM` (15). + pub fn kill(&self, signal: Option) -> Result<()> { + self.inner.kill(signal).map_err(|e| e.into()) + } +} + +/// The buffered result of [`ExecProcess::output`]. +#[derive(Debug)] +pub struct ExecOutput { + inner: worker_sys::ExecOutput, +} + +impl ExecOutput { + pub fn exit_code(&self) -> u32 { + self.inner.exit_code() + } + + pub fn stdout(&self) -> Vec { + Uint8Array::new(&self.inner.stdout()).to_vec() + } + + pub fn stderr(&self) -> Vec { + Uint8Array::new(&self.inner.stderr()).to_vec() + } +} From df96700ab45b9e5dc400c48946f5c57951dcfd11 Mon Sep 17 00:00:00 2001 From: Blake Kostner Date: Fri, 2 Oct 2026 07:49:44 -0700 Subject: [PATCH 2/4] Propagate Reflect::set errors instead of unwrap() in container startup builders set_custom_instance and set_container_snapshot built their JS object with Reflect::set(...).unwrap(). Reflect::set can fail per the ECMAScript spec (js-sys surfaces that as a Result), and this code runs inside a Worker request handler, so an avoidable unwrap() is an avoidable panic there. Both methods now return Result<(), JsValue> and propagate with ?, matching Container::exec's existing ?-based error propagation in this same file. --- worker/src/container.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/worker/src/container.rs b/worker/src/container.rs index dc50a3680..c016ead4d 100644 --- a/worker/src/container.rs +++ b/worker/src/container.rs @@ -176,35 +176,39 @@ impl ContainerStartupOptions { /// Sets a custom instance size. `memory_mib` is in mebibytes and /// `disk_mb` is in megabytes; both must be positive integers within the /// platform's custom-instance limits. - pub fn set_custom_instance(&mut self, vcpu: u32, memory_mib: u32, disk_mb: u32) { + pub fn set_custom_instance( + &mut self, + vcpu: u32, + memory_mib: u32, + disk_mb: u32, + ) -> std::result::Result<(), JsValue> { let obj = Object::new(); Reflect::set( &obj, &JsValue::from_str("vcpu"), &JsValue::from_f64(vcpu as f64), - ) - .unwrap(); + )?; Reflect::set( &obj, &JsValue::from_str("memoryMib"), &JsValue::from_f64(memory_mib as f64), - ) - .unwrap(); + )?; Reflect::set( &obj, &JsValue::from_str("diskMb"), &JsValue::from_f64(disk_mb as f64), - ) - .unwrap(); + )?; self.instance = Some(obj.into()); + Ok(()) } /// Sets the snapshot to restore before startup, by the id returned from /// `snapshotContainer()`. Mutually exclusive with `set_image`. - pub fn set_container_snapshot(&mut self, id: &str) { + pub fn set_container_snapshot(&mut self, id: &str) -> std::result::Result<(), JsValue> { let obj = Object::new(); - Reflect::set(&obj, &JsValue::from_str("id"), &JsValue::from_str(id)).unwrap(); + Reflect::set(&obj, &JsValue::from_str("id"), &JsValue::from_str(id))?; self.container_snapshot = Some(obj.into()); + Ok(()) } pub fn add_label(&mut self, key: &str, value: &str) { From 0924da9a4e5dc5c4ad9d27f1d54a11fef601625a Mon Sep 17 00:00:00 2001 From: Blake Kostner Date: Thu, 12 Nov 2026 22:15:44 -0700 Subject: [PATCH 3/4] fix: serialize native container environments as records --- .changeset/container-environment-records.md | 28 +++ Cargo.lock | 8 + examples/container-env/Cargo.toml | 12 ++ examples/container-env/src/lib.rs | 98 +++++++++++ examples/container-env/verify.mjs | 38 +++++ examples/container-env/wrangler.toml | 25 +++ worker/src/container.rs | 178 +++++++++++++++++--- 7 files changed, 361 insertions(+), 26 deletions(-) create mode 100644 .changeset/container-environment-records.md create mode 100644 examples/container-env/Cargo.toml create mode 100644 examples/container-env/src/lib.rs create mode 100644 examples/container-env/verify.mjs create mode 100644 examples/container-env/wrangler.toml diff --git a/.changeset/container-environment-records.md b/.changeset/container-environment-records.md new file mode 100644 index 000000000..aca8b030a --- /dev/null +++ b/.changeset/container-environment-records.md @@ -0,0 +1,28 @@ +--- +"workers-rs": patch +--- + +Serialize `Container::start` and `Container::exec` options as plain JavaScript +objects, converting their environment maps to `Record` at the +binding boundary without changing the Rust options API. Preserve explicitly +set startup fields and serialize startup labels as a record as well. + +Previously the calls passed wasm-bindgen-exported Rust option classes whose +`env` getters returned JavaScript `Map` instances. The native Container API +expects record properties and did not pass those entries to the process. +The unused startup object conversion also incorrectly removed populated +entrypoint, Internet, and environment fields. + +Add WASM record-shape tests and an authenticated `examples/container-env` +runtime regression. Deploy that example with `worker-build` and Wrangler, +set its `REGRESSION_TOKEN` secret, then run +`REGRESSION_TOKEN=... node examples/container-env/verify.mjs `. +The regression reads the actual initial process's `/proc/1/environ` and a +separate exec process's `process.env`, checking independent startup/exec +values, empty strings, Unicode, newlines, `__proto__`, and PATH inheritance. +It destroys the container before returning the result. + +Source: +and , +checked 2026-11-12. Both environment options are `Record`; +exec inherits only PATH from startup, not the other startup variables. diff --git a/Cargo.lock b/Cargo.lock index 7ab18fa75..8632a5f31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -505,6 +505,14 @@ dependencies = [ "tokio", ] +[[package]] +name = "container-env-on-workers" +version = "0.1.0" +dependencies = [ + "serde_json", + "worker", +] + [[package]] name = "convert_case" version = "0.11.0" diff --git a/examples/container-env/Cargo.toml b/examples/container-env/Cargo.toml new file mode 100644 index 000000000..b26a5e7df --- /dev/null +++ b/examples/container-env/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "container-env-on-workers" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +crate-type = ["cdylib"] + +[dependencies] +worker.workspace = true +serde_json.workspace = true diff --git a/examples/container-env/src/lib.rs b/examples/container-env/src/lib.rs new file mode 100644 index 000000000..ee86d3bf4 --- /dev/null +++ b/examples/container-env/src/lib.rs @@ -0,0 +1,98 @@ +use serde_json::{json, Value}; +use worker::*; + +const PROCESS_ENV: &str = r#" +const fs = require('node:fs'); +const keys = ['BINDING_ALPHA', 'BINDING_EMPTY', '__proto__', 'BINDING_EXEC', 'PATH']; +const select = env => Object.fromEntries(keys.map(key => [key, + Object.hasOwn(env, key) ? env[key] : null])); +const startup = Object.fromEntries(fs.readFileSync('/proc/1/environ', 'utf8') + .split('\0').filter(Boolean).map(pair => { + const index = pair.indexOf('='); + return [pair.slice(0, index), pair.slice(index + 1)]; + })); +console.log(JSON.stringify({startup: select(startup), exec: select(process.env), cwd: process.cwd()})); +"#; + +#[event(fetch)] +async fn fetch(req: Request, env: Env, _ctx: Context) -> Result { + let token = env.secret("REGRESSION_TOKEN")?.to_string(); + if req.method() != Method::Post + || req.headers().get("Authorization")? != Some(format!("Bearer {token}")) + { + return Response::error("Unauthorized", 401); + } + let namespace = env.durable_object("CONTAINER_ENV")?; + namespace + .unique_id()? + .get_stub()? + .fetch_with_request(req) + .await +} + +#[durable_object] +pub struct ContainerEnvRegression { + state: State, +} + +impl DurableObject for ContainerEnvRegression { + fn new(state: State, _env: Env) -> Self { + Self { state } + } + + async fn fetch(&self, _req: Request) -> Result { + let container = self + .state + .container() + .ok_or_else(|| Error::RustError("Container binding missing".into()))?; + let mut startup = ContainerStartupOptions::new(); + startup.set_image("cloudflare/debian-trixie"); + startup.enable_internet(false); + startup.set_entrypoint(&["/bin/sleep", "300"]); + startup.add_env("BINDING_ALPHA", "startup spaces = quotes \" and λ\nnext"); + startup.add_env("BINDING_EMPTY", ""); + startup.add_env("__proto__", "startup ordinary key"); + startup.add_env( + "PATH", + "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/binding-path-marker", + ); + container.start(Some(startup))?; + let result = probe(&container).await; + container.destroy(None).await?; + Response::from_json(&result?) + } +} + +async fn process_env( + container: &Container, + options: Option, +) -> Result { + let output = container + .exec(&["node", "-e", PROCESS_ENV], options) + .await? + .output() + .await?; + if output.exit_code() != 0 || !output.stderr().is_empty() { + return Err(Error::RustError(format!( + "Environment reader failed: exit {}, stderr {}", + output.exit_code(), + String::from_utf8_lossy(&output.stderr()) + ))); + } + Ok(serde_json::from_slice(&output.stdout())?) +} + +async fn probe(container: &Container) -> Result { + let baseline = process_env(container, None).await?; + let mut options = ContainerExecOptions::new(); + options.add_env("BINDING_ALPHA", "exec override"); + options.add_env("BINDING_EXEC", "exec spaces = quotes \" and λ\nnext"); + options.add_env("BINDING_EMPTY", ""); + options.add_env("__proto__", "exec ordinary key"); + options.set_cwd("/tmp"); + options.set_user(0, 0); + options.set_stdout("pipe"); + options.set_stderr("pipe"); + let overridden = process_env(container, Some(options)).await?; + Ok(json!({"baseline": baseline, "overridden": overridden})) +} diff --git a/examples/container-env/verify.mjs b/examples/container-env/verify.mjs new file mode 100644 index 000000000..a7d300b9d --- /dev/null +++ b/examples/container-env/verify.mjs @@ -0,0 +1,38 @@ +import assert from "node:assert/strict"; + +const url = process.argv[2]; +assert.ok(url, "usage: node verify.mjs "); +assert.ok(process.env.REGRESSION_TOKEN, "REGRESSION_TOKEN is required"); +const response = await fetch(url, { + method: "POST", + headers: { authorization: `Bearer ${process.env.REGRESSION_TOKEN}` }, + signal: AbortSignal.timeout(120_000), +}); +assert.equal(response.status, 200, await response.clone().text()); +const result = await response.json(); +const path = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/binding-path-marker"; +const startup = { + BINDING_ALPHA: 'startup spaces = quotes " and λ\nnext', + BINDING_EMPTY: "", + ["__proto__"]: "startup ordinary key", + BINDING_EXEC: null, + PATH: path, +}; +assert.deepEqual(result.baseline.startup, startup); +assert.deepEqual(result.overridden.startup, startup); +assert.deepEqual(result.baseline.exec, { + BINDING_ALPHA: null, + BINDING_EMPTY: null, + ["__proto__"]: null, + BINDING_EXEC: null, + PATH: path, +}); +assert.deepEqual(result.overridden.exec, { + BINDING_ALPHA: "exec override", + BINDING_EMPTY: "", + ["__proto__"]: "exec ordinary key", + BINDING_EXEC: 'exec spaces = quotes " and λ\nnext', + PATH: path, +}); +assert.equal(result.overridden.cwd, "/tmp"); +console.log(JSON.stringify({ observed_at: new Date().toISOString(), passed: true, ...result }, null, 2)); diff --git a/examples/container-env/wrangler.toml b/examples/container-env/wrangler.toml new file mode 100644 index 000000000..a7c352b89 --- /dev/null +++ b/examples/container-env/wrangler.toml @@ -0,0 +1,25 @@ +name = "workers-rs-container-env-regression" +main = "build/worker/shim.mjs" +compatibility_date = "2026-11-12" +workers_dev = true + +[build] +command = "worker-build --release" + +[observability] +enabled = true + +[observability.traces] +enabled = true + +[[containers]] +class_name = "ContainerEnvRegression" +scheduling_policy = "durable_object" + +[[durable_objects.bindings]] +name = "CONTAINER_ENV" +class_name = "ContainerEnvRegression" + +[[migrations]] +tag = "v1" +new_sqlite_classes = ["ContainerEnvRegression"] diff --git a/worker/src/container.rs b/worker/src/container.rs index c016ead4d..5e90d7955 100644 --- a/worker/src/container.rs +++ b/worker/src/container.rs @@ -16,7 +16,7 @@ impl Container { pub fn start(&self, options: Option) -> Result<()> { let options = match options { - Some(o) => o.into(), + Some(o) => Object::from(o).into(), None => JsValue::undefined(), }; self.inner.start(&options).map_err(|e| e.into()) @@ -57,7 +57,7 @@ impl Container { ) -> Result { let cmd: Vec = cmd.iter().map(|s| JsValue::from_str(s)).collect(); let options = match options { - Some(o) => o.into(), + Some(o) => Object::from(o).into(), None => JsValue::undefined(), }; let promise = self.inner.exec(cmd, &options)?; @@ -219,27 +219,34 @@ impl ContainerStartupOptions { impl From for Object { fn from(options: ContainerStartupOptions) -> Self { - let obj = options.clone().into(); + let obj = Object::new(); if !options.entrypoint.is_empty() { - Reflect::delete_property(&obj, &JsValue::from_str("entrypoint")).unwrap(); + let entrypoint = options + .entrypoint + .into_iter() + .map(JsValue::from) + .collect::(); + Reflect::set(&obj, &"entrypoint".into(), &entrypoint).unwrap(); } - if options.enable_internet.is_some() { - Reflect::delete_property(&obj, &JsValue::from_str("enableInternet")).unwrap(); + if let Some(enable_internet) = options.enable_internet { + Reflect::set(&obj, &"enableInternet".into(), &enable_internet.into()).unwrap(); } if options.env.size() != 0 { - Reflect::delete_property(&obj, &JsValue::from_str("env")).unwrap(); + let env = Object::from_entries(&options.env).unwrap(); + Reflect::set(&obj, &"env".into(), &env).unwrap(); } - if options.image.is_none() { - Reflect::delete_property(&obj, &JsValue::from_str("image")).unwrap(); + if let Some(image) = options.image { + Reflect::set(&obj, &"image".into(), &image.into()).unwrap(); } - if options.instance.is_none() { - Reflect::delete_property(&obj, &JsValue::from_str("instance")).unwrap(); + if let Some(instance) = options.instance { + Reflect::set(&obj, &"instance".into(), &instance).unwrap(); } - if options.container_snapshot.is_none() { - Reflect::delete_property(&obj, &JsValue::from_str("containerSnapshot")).unwrap(); + if let Some(snapshot) = options.container_snapshot { + Reflect::set(&obj, &"containerSnapshot".into(), &snapshot).unwrap(); } - if options.labels.size() == 0 { - Reflect::delete_property(&obj, &JsValue::from_str("labels")).unwrap(); + if options.labels.size() != 0 { + let labels = Object::from_entries(&options.labels).unwrap(); + Reflect::set(&obj, &"labels".into(), &labels).unwrap(); } obj } @@ -304,21 +311,22 @@ impl ContainerExecOptions { impl From for Object { fn from(options: ContainerExecOptions) -> Self { - let obj = options.clone().into(); - if options.cwd.is_none() { - Reflect::delete_property(&obj, &JsValue::from_str("cwd")).unwrap(); + let obj = Object::new(); + if let Some(cwd) = options.cwd { + Reflect::set(&obj, &"cwd".into(), &cwd.into()).unwrap(); } - if options.env.size() == 0 { - Reflect::delete_property(&obj, &JsValue::from_str("env")).unwrap(); + if options.env.size() != 0 { + let env = Object::from_entries(&options.env).unwrap(); + Reflect::set(&obj, &"env".into(), &env).unwrap(); } - if options.user.is_none() { - Reflect::delete_property(&obj, &JsValue::from_str("user")).unwrap(); + if let Some(user) = options.user { + Reflect::set(&obj, &"user".into(), &user.into()).unwrap(); } - if options.stdout.is_none() { - Reflect::delete_property(&obj, &JsValue::from_str("stdout")).unwrap(); + if let Some(stdout) = options.stdout { + Reflect::set(&obj, &"stdout".into(), &stdout.into()).unwrap(); } - if options.stderr.is_none() { - Reflect::delete_property(&obj, &JsValue::from_str("stderr")).unwrap(); + if let Some(stderr) = options.stderr { + Reflect::set(&obj, &"stderr".into(), &stderr.into()).unwrap(); } obj } @@ -386,3 +394,121 @@ impl ExecOutput { Uint8Array::new(&self.inner.stderr()).to_vec() } } + +#[cfg(all(test, target_arch = "wasm32"))] +mod tests { + use super::*; + use wasm_bindgen_test::wasm_bindgen_test; + + fn property(object: &JsValue, name: &str) -> JsValue { + Reflect::get(object, &name.into()).unwrap() + } + + fn assert_record(value: &JsValue, expected: &[(&str, &str)]) { + assert!(!value.is_instance_of::()); + let object: &Object = value.unchecked_ref(); + assert_eq!( + Object::get_prototype_of(object), + Object::get_prototype_of(&Object::new()) + ); + assert_eq!(Object::keys(object).length() as usize, expected.len()); + for (key, value) in expected { + assert_eq!(property(object, key), JsValue::from_str(value)); + } + } + + #[wasm_bindgen_test] + fn startup_options_serialize_records_and_preserve_fields() { + let mut options = ContainerStartupOptions::new(); + options.set_entrypoint(&["node", "-e", "process.exit(0)"]); + options.enable_internet(false); + options.add_env("BINDING_ALPHA", "spaces = quotes \" and λ\nnext"); + options.add_env("BINDING_EMPTY", ""); + options.add_env("__proto__", "ordinary environment key"); + options.add_env("BINDING_ALPHA", "replacement"); + options.add_label("fixture", "synthetic"); + options.set_image("cloudflare/debian-trixie"); + options.set_custom_instance(1, 4096, 8000).unwrap(); + let object = Object::from(options); + + assert_eq!(Object::keys(&object).length(), 6); + assert_eq!(property(&object, "enableInternet"), JsValue::FALSE); + assert_eq!( + property(&object, "image"), + JsValue::from_str("cloudflare/debian-trixie") + ); + let entrypoint = js_sys::Array::from(&property(&object, "entrypoint")); + assert_eq!(entrypoint.length(), 3); + assert_eq!(entrypoint.get(2), JsValue::from_str("process.exit(0)")); + assert_record( + &property(&object, "env"), + &[ + ("BINDING_ALPHA", "replacement"), + ("BINDING_EMPTY", ""), + ("__proto__", "ordinary environment key"), + ], + ); + assert_record(&property(&object, "labels"), &[("fixture", "synthetic")]); + let instance = property(&object, "instance"); + assert_eq!(property(&instance, "vcpu"), JsValue::from_f64(1.0)); + assert_eq!(property(&instance, "memoryMib"), JsValue::from_f64(4096.0)); + assert_eq!(property(&instance, "diskMb"), JsValue::from_f64(8000.0)); + assert!(property(&object, "containerSnapshot").is_undefined()); + } + + #[wasm_bindgen_test] + fn exec_options_serialize_records_and_preserve_fields() { + let mut options = ContainerExecOptions::new(); + options.add_env("BINDING_EXEC", "spaces = quotes \" and λ\nnext"); + options.add_env("BINDING_EMPTY", ""); + options.add_env("__proto__", "ordinary environment key"); + options.set_cwd("/tmp"); + options.set_user(1000, 1000); + options.set_stdout("pipe"); + options.set_stderr("combined"); + let object = Object::from(options); + + assert_eq!(Object::keys(&object).length(), 5); + assert_record( + &property(&object, "env"), + &[ + ("BINDING_EXEC", "spaces = quotes \" and λ\nnext"), + ("BINDING_EMPTY", ""), + ("__proto__", "ordinary environment key"), + ], + ); + assert_eq!(property(&object, "cwd"), JsValue::from_str("/tmp")); + assert_eq!(property(&object, "user"), JsValue::from_str("1000:1000")); + assert_eq!(property(&object, "stdout"), JsValue::from_str("pipe")); + assert_eq!(property(&object, "stderr"), JsValue::from_str("combined")); + } + + #[wasm_bindgen_test] + fn empty_options_omit_unset_fields() { + assert_eq!( + Object::keys(&Object::from(ContainerStartupOptions::new())).length(), + 0 + ); + assert_eq!( + Object::keys(&Object::from(ContainerExecOptions::new())).length(), + 0 + ); + } + + #[wasm_bindgen_test] + fn startup_snapshot_and_explicit_internet_are_preserved() { + let mut options = ContainerStartupOptions::new(); + options.enable_internet(true); + options + .set_container_snapshot("synthetic-snapshot") + .unwrap(); + let object = Object::from(options); + assert_eq!(Object::keys(&object).length(), 2); + assert_eq!(property(&object, "enableInternet"), JsValue::TRUE); + assert_eq!( + property(&property(&object, "containerSnapshot"), "id"), + JsValue::from_str("synthetic-snapshot") + ); + assert!(property(&object, "image").is_undefined()); + } +} From 683fba705c569fd818a7c2f588b71743371ee561 Mon Sep 17 00:00:00 2001 From: Blake Kostner Date: Fri, 13 Nov 2026 14:35:13 -0700 Subject: [PATCH 4/4] test: remove container env verification example --- .changeset/container-environment-records.md | 9 +- Cargo.lock | 8 -- examples/container-env/Cargo.toml | 12 --- examples/container-env/src/lib.rs | 98 --------------------- examples/container-env/verify.mjs | 38 -------- examples/container-env/wrangler.toml | 25 ------ 6 files changed, 1 insertion(+), 189 deletions(-) delete mode 100644 examples/container-env/Cargo.toml delete mode 100644 examples/container-env/src/lib.rs delete mode 100644 examples/container-env/verify.mjs delete mode 100644 examples/container-env/wrangler.toml diff --git a/.changeset/container-environment-records.md b/.changeset/container-environment-records.md index aca8b030a..b2ea5c921 100644 --- a/.changeset/container-environment-records.md +++ b/.changeset/container-environment-records.md @@ -13,14 +13,7 @@ expects record properties and did not pass those entries to the process. The unused startup object conversion also incorrectly removed populated entrypoint, Internet, and environment fields. -Add WASM record-shape tests and an authenticated `examples/container-env` -runtime regression. Deploy that example with `worker-build` and Wrangler, -set its `REGRESSION_TOKEN` secret, then run -`REGRESSION_TOKEN=... node examples/container-env/verify.mjs `. -The regression reads the actual initial process's `/proc/1/environ` and a -separate exec process's `process.env`, checking independent startup/exec -values, empty strings, Unicode, newlines, `__proto__`, and PATH inheritance. -It destroys the container before returning the result. +Add WASM record-shape tests for startup and exec options. Source: and , diff --git a/Cargo.lock b/Cargo.lock index 8632a5f31..7ab18fa75 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -505,14 +505,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "container-env-on-workers" -version = "0.1.0" -dependencies = [ - "serde_json", - "worker", -] - [[package]] name = "convert_case" version = "0.11.0" diff --git a/examples/container-env/Cargo.toml b/examples/container-env/Cargo.toml deleted file mode 100644 index b26a5e7df..000000000 --- a/examples/container-env/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "container-env-on-workers" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] -crate-type = ["cdylib"] - -[dependencies] -worker.workspace = true -serde_json.workspace = true diff --git a/examples/container-env/src/lib.rs b/examples/container-env/src/lib.rs deleted file mode 100644 index ee86d3bf4..000000000 --- a/examples/container-env/src/lib.rs +++ /dev/null @@ -1,98 +0,0 @@ -use serde_json::{json, Value}; -use worker::*; - -const PROCESS_ENV: &str = r#" -const fs = require('node:fs'); -const keys = ['BINDING_ALPHA', 'BINDING_EMPTY', '__proto__', 'BINDING_EXEC', 'PATH']; -const select = env => Object.fromEntries(keys.map(key => [key, - Object.hasOwn(env, key) ? env[key] : null])); -const startup = Object.fromEntries(fs.readFileSync('/proc/1/environ', 'utf8') - .split('\0').filter(Boolean).map(pair => { - const index = pair.indexOf('='); - return [pair.slice(0, index), pair.slice(index + 1)]; - })); -console.log(JSON.stringify({startup: select(startup), exec: select(process.env), cwd: process.cwd()})); -"#; - -#[event(fetch)] -async fn fetch(req: Request, env: Env, _ctx: Context) -> Result { - let token = env.secret("REGRESSION_TOKEN")?.to_string(); - if req.method() != Method::Post - || req.headers().get("Authorization")? != Some(format!("Bearer {token}")) - { - return Response::error("Unauthorized", 401); - } - let namespace = env.durable_object("CONTAINER_ENV")?; - namespace - .unique_id()? - .get_stub()? - .fetch_with_request(req) - .await -} - -#[durable_object] -pub struct ContainerEnvRegression { - state: State, -} - -impl DurableObject for ContainerEnvRegression { - fn new(state: State, _env: Env) -> Self { - Self { state } - } - - async fn fetch(&self, _req: Request) -> Result { - let container = self - .state - .container() - .ok_or_else(|| Error::RustError("Container binding missing".into()))?; - let mut startup = ContainerStartupOptions::new(); - startup.set_image("cloudflare/debian-trixie"); - startup.enable_internet(false); - startup.set_entrypoint(&["/bin/sleep", "300"]); - startup.add_env("BINDING_ALPHA", "startup spaces = quotes \" and λ\nnext"); - startup.add_env("BINDING_EMPTY", ""); - startup.add_env("__proto__", "startup ordinary key"); - startup.add_env( - "PATH", - "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/binding-path-marker", - ); - container.start(Some(startup))?; - let result = probe(&container).await; - container.destroy(None).await?; - Response::from_json(&result?) - } -} - -async fn process_env( - container: &Container, - options: Option, -) -> Result { - let output = container - .exec(&["node", "-e", PROCESS_ENV], options) - .await? - .output() - .await?; - if output.exit_code() != 0 || !output.stderr().is_empty() { - return Err(Error::RustError(format!( - "Environment reader failed: exit {}, stderr {}", - output.exit_code(), - String::from_utf8_lossy(&output.stderr()) - ))); - } - Ok(serde_json::from_slice(&output.stdout())?) -} - -async fn probe(container: &Container) -> Result { - let baseline = process_env(container, None).await?; - let mut options = ContainerExecOptions::new(); - options.add_env("BINDING_ALPHA", "exec override"); - options.add_env("BINDING_EXEC", "exec spaces = quotes \" and λ\nnext"); - options.add_env("BINDING_EMPTY", ""); - options.add_env("__proto__", "exec ordinary key"); - options.set_cwd("/tmp"); - options.set_user(0, 0); - options.set_stdout("pipe"); - options.set_stderr("pipe"); - let overridden = process_env(container, Some(options)).await?; - Ok(json!({"baseline": baseline, "overridden": overridden})) -} diff --git a/examples/container-env/verify.mjs b/examples/container-env/verify.mjs deleted file mode 100644 index a7d300b9d..000000000 --- a/examples/container-env/verify.mjs +++ /dev/null @@ -1,38 +0,0 @@ -import assert from "node:assert/strict"; - -const url = process.argv[2]; -assert.ok(url, "usage: node verify.mjs "); -assert.ok(process.env.REGRESSION_TOKEN, "REGRESSION_TOKEN is required"); -const response = await fetch(url, { - method: "POST", - headers: { authorization: `Bearer ${process.env.REGRESSION_TOKEN}` }, - signal: AbortSignal.timeout(120_000), -}); -assert.equal(response.status, 200, await response.clone().text()); -const result = await response.json(); -const path = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/binding-path-marker"; -const startup = { - BINDING_ALPHA: 'startup spaces = quotes " and λ\nnext', - BINDING_EMPTY: "", - ["__proto__"]: "startup ordinary key", - BINDING_EXEC: null, - PATH: path, -}; -assert.deepEqual(result.baseline.startup, startup); -assert.deepEqual(result.overridden.startup, startup); -assert.deepEqual(result.baseline.exec, { - BINDING_ALPHA: null, - BINDING_EMPTY: null, - ["__proto__"]: null, - BINDING_EXEC: null, - PATH: path, -}); -assert.deepEqual(result.overridden.exec, { - BINDING_ALPHA: "exec override", - BINDING_EMPTY: "", - ["__proto__"]: "exec ordinary key", - BINDING_EXEC: 'exec spaces = quotes " and λ\nnext', - PATH: path, -}); -assert.equal(result.overridden.cwd, "/tmp"); -console.log(JSON.stringify({ observed_at: new Date().toISOString(), passed: true, ...result }, null, 2)); diff --git a/examples/container-env/wrangler.toml b/examples/container-env/wrangler.toml deleted file mode 100644 index a7c352b89..000000000 --- a/examples/container-env/wrangler.toml +++ /dev/null @@ -1,25 +0,0 @@ -name = "workers-rs-container-env-regression" -main = "build/worker/shim.mjs" -compatibility_date = "2026-11-12" -workers_dev = true - -[build] -command = "worker-build --release" - -[observability] -enabled = true - -[observability.traces] -enabled = true - -[[containers]] -class_name = "ContainerEnvRegression" -scheduling_policy = "durable_object" - -[[durable_objects.bindings]] -name = "CONTAINER_ENV" -class_name = "ContainerEnvRegression" - -[[migrations]] -tag = "v1" -new_sqlite_classes = ["ContainerEnvRegression"]