From 9fa8c6688d196064d44edadb60732af81a6907d9 Mon Sep 17 00:00:00 2001 From: Bert Belder Date: Fri, 6 Nov 2026 22:02:55 -0800 Subject: [PATCH] Read the cluster key and bucket from the environment A cluster node's config had to hold the cluster key, so a container image built from it, or a binary from `workerd compile`, carried the secret, and one image could not serve two clusters. `serve` now fills an empty `cluster.key` from WORKERD_CLUSTER_KEY, or from the file that WORKERD_CLUSTER_KEY_FILE names, such as a mounted Kubernetes Secret, ignoring trailing whitespace in either. The file must be a regular file of at most 4096 bytes that holds UTF-8 text. An empty `cluster.bucket` falls back to WORKERD_CLUSTER_BUCKET. Values in the config win, as they do for `bucketOptions`. The fallback runs in the serve path only, for a config file and for a binary from `workerd compile`, so `compile` never embeds the environment. A key or bucket that neither the config nor the environment sets ends the process with an error that names the variables. It does so under `--watch` too, since the fix may lie outside the config files. --- src/workerd/server/AGENTS.md | 2 +- src/workerd/server/cli/config-test.rs | 267 ++++++++++++++++++ src/workerd/server/cli/config.rs | 137 +++++++++ src/workerd/server/cli/help.rs | 10 +- src/workerd/server/cli/lib.rs | 19 +- src/workerd/server/server-test.c++ | 2 +- src/workerd/server/server/config.rs | 6 +- .../server/tests/cluster/cluster-test.mjs | 155 +++++++++- .../server/tests/cluster/cluster-test.wd-test | 13 + src/workerd/server/workerd.capnp | 9 + 10 files changed, 594 insertions(+), 26 deletions(-) diff --git a/src/workerd/server/AGENTS.md b/src/workerd/server/AGENTS.md index 9723e2ab90d..1ab529f41a2 100644 --- a/src/workerd/server/AGENTS.md +++ b/src/workerd/server/AGENTS.md @@ -54,7 +54,7 @@ Bazel labels: `//src/workerd/server:workerd`, `//src/workerd/server:workerd-cli` | `lib.rs` | Crate root: `main()`, the commands, the server's `Watch` future for `--watch` | | `args.rs` | clap definitions | | `help.rs` | The help pages, written by hand; `args-test.rs` checks them against the parser | -| `config.rs` | Config sources (schema file, compiled binary, embedded) and the synthesized Python config | +| `config.rs` | Config sources (schema file, compiled binary, embedded) and the synthesized Python config; for `serve`, an empty cluster key and bucket filled from `WORKERD_CLUSTER_KEY` or `WORKERD_CLUSTER_KEY_FILE` and `WORKERD_CLUSTER_BUCKET` (`with_cluster_environment`), and an error if still empty | | `deploy.rs` | Cluster mode: `workerd deploy`, a wrangler project (`wrangler.rs`) or Cap'n Proto config checked as a deployment, then published to the bucket `--bucket` names (`cluster::deploy`), with the instances' bucket client and environment fallbacks; each instance skips it if it does not compose with its own config | | `deployments.rs` | Cluster mode: before `serve` starts the server, merges deployments from the bucket (`cluster::deploy`) into the config (`cluster::compose`), skips those that do not compose, and tells the server which services came from each deployment | | `process.rs` | Executable discovery, the compiled-binary format, `Process` (the files to watch, re-exec) | diff --git a/src/workerd/server/cli/config-test.rs b/src/workerd/server/cli/config-test.rs index 070b266e5ee..714cfcd945c 100644 --- a/src/workerd/server/cli/config-test.rs +++ b/src/workerd/server/cli/config-test.rs @@ -1,5 +1,10 @@ use super::*; +fn read(config: &Config) -> capnp::message::Reader { + capnp::serialize::read_message(bytes_from_words(&config.0).as_slice(), reader_options()) + .unwrap() +} + /// A config with one service named "main". fn one_service_config() -> Config { let mut message = capnp::message::Builder::new_default(); @@ -21,3 +26,265 @@ fn config_bytes_are_checked() { let bytes = bytes_from_words(&good.0); assert!(Config::from_message_bytes(&bytes[..bytes.len() - 8]).is_err()); } + +/// A config with a cluster whose key and bucket are `key` and `bucket`, or with no cluster. +fn cluster_config(cluster: Option<(&str, &str)>) -> Config { + let mut message = capnp::message::Builder::new_default(); + let mut root = message.init_root::(); + root.reborrow().init_services(1).get(0).set_name("main"); + if let Some((key, bucket)) = cluster { + let mut cluster = root.init_cluster(); + cluster.set_key(key); + cluster.set_bucket(bucket); + cluster.set_address("127.0.0.1:0"); + } + Config(words_from_bytes(&capnp::serialize::write_message_to_words( + &message, + ))) +} + +/// The cluster's key and bucket in `config`. +fn cluster_of(config: &Config) -> (String, String) { + let message = read(config); + let cluster = message + .get_root::() + .unwrap() + .get_cluster() + .unwrap(); + let text = |t: capnp::text::Reader<'_>| t.to_string().unwrap(); + ( + text(cluster.get_key().unwrap()), + text(cluster.get_bucket().unwrap()), + ) +} + +/// An environment of `vars`. +fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { + move |name| { + vars.iter() + .find(|(var, _)| *var == name) + .map(|(_, value)| (*value).to_owned()) + } +} + +/// A file of its own in the temporary directory, holding `contents`, removed when dropped. +struct TempFile(std::path::PathBuf); + +impl TempFile { + fn new(name: &str, contents: impl AsRef<[u8]>) -> Self { + let path = std::env::temp_dir().join(format!("{name}-{}", std::process::id())); + std::fs::write(&path, contents).unwrap(); + Self(path) + } + + fn path(&self) -> &str { + self.0.to_str().unwrap() + } +} + +impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +const KEY: &str = "0123456789abcdef0123456789abcdef"; + +#[test] +fn cluster_environment_fills_an_empty_key_and_bucket() { + let vars = [(CLUSTER_KEY, KEY), (CLUSTER_BUCKET, "s3://bucket/prefix")]; + let config = cluster_config(Some(("", ""))) + .with_cluster_environment(env(&vars)) + .unwrap(); + assert_eq!( + cluster_of(&config), + (KEY.to_owned(), "s3://bucket/prefix".to_owned()) + ); +} + +#[test] +fn cluster_environment_does_not_replace_config_values() { + let vars = [ + (CLUSTER_KEY, "from-the-environment"), + (CLUSTER_BUCKET, "s3://other/prefix"), + ]; + let config = cluster_config(Some((KEY, "s3://bucket/prefix"))); + let before = config.0.clone(); + let config = config.with_cluster_environment(env(&vars)).unwrap(); + assert_eq!(config.0, before); +} + +#[test] +fn cluster_environment_leaves_a_config_without_cluster_unchanged() { + let vars = [(CLUSTER_KEY, KEY), (CLUSTER_BUCKET, "s3://bucket/prefix")]; + let config = cluster_config(None); + let before = config.0.clone(); + let config = config.with_cluster_environment(env(&vars)).unwrap(); + assert_eq!(config.0, before); +} + +#[test] +fn cluster_environment_reads_the_key_file_without_trailing_whitespace() { + let file = TempFile::new("workerd-cluster-key-test", format!("{KEY}\n")); + let vars = [(CLUSTER_KEY_FILE, file.path())]; + let config = cluster_config(Some(("", "s3://bucket/prefix"))) + .with_cluster_environment(env(&vars)) + .unwrap(); + assert_eq!(cluster_of(&config).0, KEY); +} + +#[test] +fn cluster_environment_trims_the_key_variable() { + let key = format!("{KEY} \n"); + let vars = [(CLUSTER_KEY, key.as_str())]; + let config = cluster_config(Some(("", "s3://bucket/prefix"))) + .with_cluster_environment(env(&vars)) + .unwrap(); + assert_eq!(cluster_of(&config).0, KEY); +} + +#[test] +fn cluster_environment_trims_the_bucket_variable() { + let vars = [(CLUSTER_BUCKET, "s3://bucket/prefix\n")]; + let config = cluster_config(Some((KEY, ""))) + .with_cluster_environment(env(&vars)) + .unwrap(); + assert_eq!(cluster_of(&config).1, "s3://bucket/prefix"); +} + +#[test] +fn cluster_environment_refuses_a_short_key_naming_its_source() { + let file = TempFile::new("workerd-cluster-key-short-test", "0123456789ab\n"); + for (vars, expected) in [ + ( + vec![(CLUSTER_KEY, "0123456789ab")], + "cluster: WORKERD_CLUSTER_KEY: the key is 12 bytes, and must be at least 32." + .to_owned(), + ), + ( + vec![(CLUSTER_KEY_FILE, file.path())], + format!( + "cluster: WORKERD_CLUSTER_KEY_FILE={}: the key is 12 bytes, and must be at least \ + 32.", + file.path() + ), + ), + ] { + let Err(error) = + cluster_config(Some(("", "s3://bucket/prefix"))).with_cluster_environment(env(&vars)) + else { + panic!("expected an error for {vars:?}"); + }; + assert_eq!(error, expected); + } +} + +#[test] +fn cluster_environment_requires_a_key_and_bucket() { + let missing_key = "cluster.key is not set. Set it in the config, in WORKERD_CLUSTER_KEY, or \ + in a file named by WORKERD_CLUSTER_KEY_FILE."; + let missing_bucket = + "cluster.bucket is not set. Set it in the config or in WORKERD_CLUSTER_BUCKET."; + let blank = TempFile::new("workerd-cluster-key-blank-test", "\n"); + for (cluster, vars, expected) in [ + (("", ""), vec![], format!("{missing_key}\n{missing_bucket}")), + ( + ("", "s3://bucket/prefix"), + vec![(CLUSTER_KEY, " \n")], + missing_key.to_owned(), + ), + ( + ("", "s3://bucket/prefix"), + vec![(CLUSTER_KEY_FILE, blank.path())], + missing_key.to_owned(), + ), + ((KEY, ""), vec![], missing_bucket.to_owned()), + ( + (KEY, ""), + vec![(CLUSTER_BUCKET, " \n")], + missing_bucket.to_owned(), + ), + ] { + let Err(error) = cluster_config(Some(cluster)).with_cluster_environment(env(&vars)) else { + panic!("expected an error for {cluster:?} and {vars:?}"); + }; + assert_eq!(error, expected); + } +} + +#[test] +fn cluster_environment_refuses_a_key_file_that_is_not_text() { + let file = TempFile::new("workerd-cluster-key-binary-test", [0xff, 0xfe, 0x00, 0x80]); + let vars = [(CLUSTER_KEY_FILE, file.path())]; + let Err(error) = cluster_config(Some(("", ""))).with_cluster_environment(env(&vars)) else { + panic!("expected an error"); + }; + assert_eq!( + error, + format!( + "cluster: WORKERD_CLUSTER_KEY_FILE={}: not UTF-8 text. The key must be text.", + file.path() + ) + ); +} + +#[test] +fn cluster_environment_refuses_both_key_variables() { + let file = TempFile::new("workerd-cluster-key-both-test", KEY); + let vars = [(CLUSTER_KEY, KEY), (CLUSTER_KEY_FILE, file.path())]; + let Err(error) = cluster_config(Some(("", ""))).with_cluster_environment(env(&vars)) else { + panic!("expected an error"); + }; + assert_eq!( + error, + "cluster: set only one of WORKERD_CLUSTER_KEY and WORKERD_CLUSTER_KEY_FILE." + ); +} + +#[test] +fn cluster_environment_refuses_a_key_file_that_is_not_a_regular_file_or_too_large() { + let large = TempFile::new("workerd-cluster-key-large-test", "k".repeat(4097)); + let directory = std::env::temp_dir(); + for (path, reason) in [ + (directory.to_str().unwrap(), "not a regular file"), + (large.path(), "larger than 4096 bytes"), + ] { + let vars = [(CLUSTER_KEY_FILE, path)]; + let Err(error) = cluster_config(Some(("", ""))).with_cluster_environment(env(&vars)) else { + panic!("expected an error for {path}"); + }; + assert_eq!( + error, + format!("cluster: WORKERD_CLUSTER_KEY_FILE={path}: {reason}") + ); + } +} + +#[cfg(unix)] +#[test] +fn cluster_environment_refuses_a_fifo_as_the_key_file_without_blocking() { + let path = + std::env::temp_dir().join(format!("workerd-cluster-key-fifo-{}", std::process::id())); + let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap(); + // SAFETY: `c_path` is a valid NUL-terminated path. + assert_eq!(unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) }, 0); + let vars = [(CLUSTER_KEY_FILE, path.to_str().unwrap())]; + let result = cluster_config(Some(("", ""))).with_cluster_environment(env(&vars)); + let _ = std::fs::remove_file(&path); + let Err(error) = result else { + panic!("expected an error"); + }; + assert!(error.ends_with(": not a regular file"), "{error}"); +} + +#[test] +fn cluster_environment_reports_an_unreadable_key_file() { + let vars = [(CLUSTER_KEY_FILE, "/nonexistent/workerd-cluster-key")]; + let Err(error) = cluster_config(Some(("", ""))).with_cluster_environment(env(&vars)) else { + panic!("expected an error"); + }; + assert!( + error.starts_with("cluster: WORKERD_CLUSTER_KEY_FILE=/nonexistent/workerd-cluster-key: "), + "{error}" + ); +} diff --git a/src/workerd/server/cli/config.rs b/src/workerd/server/cli/config.rs index 897e30b6584..16794608cf3 100644 --- a/src/workerd/server/cli/config.rs +++ b/src/workerd/server/cli/config.rs @@ -78,6 +78,73 @@ impl Config { bytes_from_words(&self.0) } + /// Fills `cluster.key` and `cluster.bucket` from the environment where the config leaves them + /// empty. See `ClusterConfig` in workerd.capnp. `var` reads an environment variable and + /// returns `None` when it is unset or empty. A config without `cluster` is unchanged. A key or + /// bucket that neither the config nor the environment sets is an error. + pub fn with_cluster_environment( + self, + var: impl Fn(&str) -> Option, + ) -> Result { + let bytes = self.to_bytes(); + let message = capnp::serialize::read_message(bytes.as_slice(), reader_options()) + .map_err(|error| error.to_string())?; + let root = message + .get_root::() + .map_err(|error| error.to_string())?; + if !root.has_cluster() { + return Ok(self); + } + let cluster = root.get_cluster().map_err(|error| error.to_string())?; + let empty = |text: capnp::Result>| -> Result { + let text = text.and_then(|text| Ok(text.to_string()?)); + Ok(text.map_err(|error| error.to_string())?.is_empty()) + }; + let key = if empty(cluster.get_key())? { + cluster_key(&var)? + } else { + None + }; + let bucket = if empty(cluster.get_bucket())? { + var(CLUSTER_BUCKET).and_then(|bucket| non_blank(&bucket)) + } else { + None + }; + let mut missing = Vec::new(); + if key.is_none() && empty(cluster.get_key())? { + missing.push(format!( + "cluster.key is not set. Set it in the config, in {CLUSTER_KEY}, or in a file \ + named by {CLUSTER_KEY_FILE}." + )); + } + if bucket.is_none() && empty(cluster.get_bucket())? { + missing.push(format!( + "cluster.bucket is not set. Set it in the config or in {CLUSTER_BUCKET}." + )); + } + if !missing.is_empty() { + return Err(missing.join("\n")); + } + if key.is_none() && bucket.is_none() { + return Ok(self); + } + let mut message = capnp::message::Builder::new_default(); + message.set_root(root).map_err(|error| error.to_string())?; + let mut cluster = message + .get_root::() + .and_then(config::Builder::get_cluster) + .map_err(|error| error.to_string())?; + if let Some(key) = key { + cluster.set_key(key.as_str()); + } + if let Some(bucket) = bucket { + cluster.set_bucket(bucket.as_str()); + } + Ok(Self(words_from_bytes( + &capnp::serialize::write_message_to_words(&message), + ))) + } + /// Writes the encoded config to stdout (`compile --config-only`). pub fn write_to_stdout(&self) -> io::Result<()> { let mut out = io::stdout().lock(); @@ -88,6 +155,76 @@ impl Config { } } +/// The environment variable that holds the cluster key when the config leaves it empty. +pub const CLUSTER_KEY: &str = "WORKERD_CLUSTER_KEY"; +/// The environment variable that names a file holding the cluster key, such as a mounted secret. +pub const CLUSTER_KEY_FILE: &str = "WORKERD_CLUSTER_KEY_FILE"; +/// The environment variable that holds the cluster bucket when the config leaves it empty. +pub const CLUSTER_BUCKET: &str = "WORKERD_CLUSTER_BUCKET"; + +/// The shortest cluster key. The server refuses a shorter one in the config; one from the +/// environment is refused here, where the error can name its source. +const MIN_KEY: usize = 32; + +/// The cluster key from `CLUSTER_KEY` or the file `CLUSTER_KEY_FILE` names, without trailing +/// whitespace, such as a file's final newline. `None` when neither is set or the key is blank. +fn cluster_key(var: impl Fn(&str) -> Option) -> Result, String> { + let (key, source) = match (var(CLUSTER_KEY), var(CLUSTER_KEY_FILE)) { + (Some(_), Some(_)) => { + return Err(format!( + "cluster: set only one of {CLUSTER_KEY} and {CLUSTER_KEY_FILE}." + )); + } + (Some(key), None) => (non_blank(&key), CLUSTER_KEY.to_owned()), + (None, Some(path)) => { + let source = format!("{CLUSTER_KEY_FILE}={path}"); + let key = + read_key_file(&path).map_err(|error| format!("cluster: {source}: {error}"))?; + (non_blank(&key), source) + } + (None, None) => return Ok(None), + }; + match key { + Some(key) if key.len() < MIN_KEY => Err(format!( + "cluster: {source}: the key is {} bytes, and must be at least {MIN_KEY}.", + key.len() + )), + key => Ok(key), + } +} + +/// `value` without trailing whitespace, or `None` if nothing is left. +fn non_blank(value: &str) -> Option { + Some(value.trim_end()) + .filter(|value| !value.is_empty()) + .map(str::to_owned) +} + +/// The largest key file read. A key is a few dozen bytes; the limit keeps a mistaken path, such +/// as a device, from being read without end. +const MAX_KEY_FILE: u64 = 4096; + +/// The text in the regular file at `path`. +fn read_key_file(path: &str) -> Result { + // Checked before opening: opening a FIFO blocks, and a device may never end. The check + // follows symlinks, as Kubernetes mounts a Secret's files through them. + if !std::fs::metadata(path) + .map_err(|error| error.to_string())? + .is_file() + { + return Err("not a regular file".to_owned()); + } + let file = File::open(path).map_err(|error| error.to_string())?; + let mut key = Vec::new(); + file.take(MAX_KEY_FILE + 1) + .read_to_end(&mut key) + .map_err(|error| error.to_string())?; + if key.len() as u64 > MAX_KEY_FILE { + return Err(format!("larger than {MAX_KEY_FILE} bytes")); + } + String::from_utf8(key).map_err(|_| "not UTF-8 text. The key must be text.".to_owned()) +} + /// Configs can legitimately be very large and are not malicious, so use an effectively-infinite /// traversal limit. fn reader_options() -> ReaderOptions { diff --git a/src/workerd/server/cli/help.rs b/src/workerd/server/cli/help.rs index de65df81ec9..225ec3e275d 100644 --- a/src/workerd/server/cli/help.rs +++ b/src/workerd/server/cli/help.rs @@ -45,10 +45,12 @@ Cluster (experimental): --cluster-addr Override cluster address; keep private --cluster-advertise Address peers reach this instance at s3:// buckets read AWS_ENDPOINT_URL, AWS_ACCESS_KEY_ID and the other - AWS_* variables; gs:// buckets, GOOGLE_APPLICATION_CREDENTIALS. On - SIGTERM an instance hands its objects to its peers and exits within - stopTimeoutMs (8 s by default). GET /ready on the cluster address - answers OK once serving. + AWS_* variables; gs:// buckets, GOOGLE_APPLICATION_CREDENTIALS. An + empty cluster key comes from WORKERD_CLUSTER_KEY or the file that + WORKERD_CLUSTER_KEY_FILE names, an empty bucket from + WORKERD_CLUSTER_BUCKET. On SIGTERM an instance hands its objects to its + peers and exits within stopTimeoutMs (8 s by default). GET /ready on + the cluster address answers OK once serving. " }; } diff --git a/src/workerd/server/cli/lib.rs b/src/workerd/server/cli/lib.rs index 550bcf091e0..28126b8c2d1 100644 --- a/src/workerd/server/cli/lib.rs +++ b/src/workerd/server/cli/lib.rs @@ -465,12 +465,14 @@ fn load_config( config_errors(&compiled.errors, process) } -/// Adds cluster deployments to `config` and records their service sources in `options`. +/// Fills `config`'s cluster key and bucket from the environment, then adds cluster deployments to +/// `config` and records their service sources in `options`. /// -/// Deployments are added only with `--experimental`. A public cluster address or an error in -/// `config` found during composition is a config error. A deployment that does not compose is -/// skipped. A bucket that cannot be opened or read ends the process, even under `--watch`, because -/// the cause may lie outside the config files. See `deployments.rs`. +/// Both happen only with `--experimental`. A public cluster address or an error in `config` found +/// during composition is a config error. A deployment that does not compose is skipped. An +/// unusable cluster environment variable, or a bucket that cannot be opened or read, ends the +/// process, even under `--watch`, because the cause lies outside the config files. See +/// `deployments.rs`. fn with_deployments( config: Config, serve_or_test: &args::ServeOrTestArgs, @@ -480,6 +482,13 @@ fn with_deployments( if !serve_or_test.experimental { return (config, options); } + let var = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); + let config = config + .with_cluster_environment(var) + .unwrap_or_else(|error| { + eprintln!("{error}"); + std::process::exit(1); + }); let address = options.cluster_address.as_deref(); let advertise = options.cluster_advertise.as_deref(); match deployments::add(config, address, advertise) { diff --git a/src/workerd/server/server-test.c++ b/src/workerd/server/server-test.c++ index 2c9c6ef10bb..6a957c84e7d 100644 --- a/src/workerd/server/server-test.c++ +++ b/src/workerd/server/server-test.c++ @@ -1167,7 +1167,7 @@ KJ_TEST("Server: a short cluster key is refused") { TestServer test(clusterConfig("0123456789abcdef")); test.server.allowExperimental(); test.expectErrors(R"( - cluster.key must be at least 32 bytes. + cluster.key must be at least 32 bytes. Fix it in the config, or leave it empty and set WORKERD_CLUSTER_KEY or a file named by WORKERD_CLUSTER_KEY_FILE. )"_blockquote); } diff --git a/src/workerd/server/server/config.rs b/src/workerd/server/server/config.rs index 59aaa26a346..e97184d6a4d 100644 --- a/src/workerd/server/server/config.rs +++ b/src/workerd/server/server/config.rs @@ -2184,7 +2184,11 @@ fn make_cluster( let conf = config.get_cluster().map_err(capnp_error)?; // The MAC's other inputs cross the wire, so a short key falls to an offline search. if text(conf.get_key())?.len() < 32 { - report.error("cluster.key must be at least 32 bytes.".to_owned()); + report.error( + "cluster.key must be at least 32 bytes. Fix it in the config, or leave it empty and \ + set WORKERD_CLUSTER_KEY or a file named by WORKERD_CLUSTER_KEY_FILE." + .to_owned(), + ); return Ok(None); } Ok(Some(ClusterNode::new(Rc::clone(factory), conf, address)?)) diff --git a/src/workerd/server/tests/cluster/cluster-test.mjs b/src/workerd/server/tests/cluster/cluster-test.mjs index a57c949e954..3de2cbdf687 100644 --- a/src/workerd/server/tests/cluster/cluster-test.mjs +++ b/src/workerd/server/tests/cluster/cluster-test.mjs @@ -57,6 +57,8 @@ // over `ClusterNode::peer_service`): a write is seen at once on the // other node, named caches are apart, a large value crosses, and a // killed node's entries miss at once. +// 17. Nodes can take the cluster key and bucket from the environment, a +// binary from `workerd compile` too, and compiling embeds neither. // // A takeover waits out a dead owner's lease (`LEASE_MS`), so each one here // costs that much: one test per mechanism. The simulations in ../../cluster @@ -68,8 +70,17 @@ // - a dead owner's alarms adopted with its node record gone: only the // orphan scan finds them. alarms-test.rs. -import { spawn } from 'node:child_process'; -import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from 'node:fs/promises'; +import { execFileSync, spawn } from 'node:child_process'; +import { + mkdir, + mkdtemp, + open, + readFile, + readdir, + rm, + stat, + writeFile, +} from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { connect } from 'node:net'; import { @@ -78,7 +89,7 @@ import { generateKeyPairSync, randomBytes, } from 'node:crypto'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; import { env } from 'node:process'; import { test as nodeTest } from 'node:test'; import assert from 'node:assert'; @@ -147,6 +158,7 @@ class ClusterNode { #disk; #configName; #env; + #compiled; // `localPath` is the directory of the config's disk service `disk`. `env` // adds to the process's environment, or with `undefined` removes from it. @@ -160,9 +172,11 @@ class ClusterNode { nodeId, extraArgs = [], env = {}, + compiled = false, }) { - this.#env = env; this.#extraArgs = extraArgs; + this.#env = env; + this.#compiled = compiled; this.#disk = disk; this.#configName = configName; this.#binary = binary; @@ -223,10 +237,14 @@ class ClusterNode { async start() { assert.strictEqual(this.#child, null); - const args = [ + // A binary from `workerd compile` takes no command and no config. + const config = [ 'serve', this.#config, ...(this.#configName === undefined ? [] : [this.#configName]), + ]; + const args = [ + ...(this.#compiled ? [] : config), '--experimental', '--verbose', `--control-fd=${CONTROL_FD}`, @@ -554,19 +572,22 @@ class FakeS3 { // what owner records name // The nodes run the config constant `configName` of `config`, whose disk // service `disk` is a directory of each node's own, once `before` has prepared -// the bucket, of `dialect` ("s3" or "gcs", FakeS3.fresh). `nodeEnv` answers -// what a node adds to its environment. +// the bucket, of `dialect` ("s3" or "gcs", FakeS3.fresh). Node `i` gets the +// extra environment variables `nodeEnv(i, root, bucket)`, where `root` is the +// test's temporary directory, and runs the binary that `nodeBinary(i, root)` +// names (`compiled` when `workerd compile` built it). async function withCluster( numNodes, fn, { extraArgs = () => [], + nodeEnv = async () => ({}), + nodeBinary = async () => ({ binary: env.WORKERD_BINARY, compiled: false }), config = env.WD_TEST_CONFIG, configName = 'config', disk = 'local', before = async () => {}, dialect = 's3', - nodeEnv = () => ({}), } = {} ) { // Each test run gets its own bucket and disks, so state doesn't leak @@ -582,7 +603,7 @@ async function withCluster( await mkdir(localPath); nodes.push( new ClusterNode({ - binary: env.WORKERD_BINARY, + ...(await nodeBinary(i, root)), config, configName, localPath, @@ -590,7 +611,7 @@ async function withCluster( s3Port: bucket.port, nodeId: `node${i}`, extraArgs: await extraArgs(i), - env: nodeEnv(bucket), + env: await nodeEnv(i, root, bucket), }) ); } @@ -1526,6 +1547,105 @@ test('cluster: the nodes share one Cache API cache', async () => { ); }); +test('cluster: the key and bucket can come from the environment', async () => { + // Node 0 reads the key from WORKERD_CLUSTER_KEY, node 1 from a file named by + // WORKERD_CLUSTER_KEY_FILE, ending in a newline as secret files often do. + const key = 'test-cluster-shared-secret-of-32-bytes'; + const nodeEnv = async (i, root) => { + const env = { WORKERD_CLUSTER_BUCKET: 's3://wdtest/cluster' }; + if (i === 0) return { ...env, WORKERD_CLUSTER_KEY: key }; + const file = join(root, 'cluster-key'); + await writeFile(file, `${key}\n`); + return { ...env, WORKERD_CLUSTER_KEY_FILE: file }; + }; + await withCluster( + 2, + async ({ nodes, nodeKeys }) => { + // Node 1 forwards to node 0, so both hold the same key. + const first = await fetchJson(nodes[0].httpPort, '/increment?name=env'); + const second = await fetchJson(nodes[1].httpPort, '/increment?name=env'); + assert.strictEqual(first.status, 200, JSON.stringify(first.body)); + assert.strictEqual(second.status, 200, JSON.stringify(second.body)); + assert.strictEqual(second.body.count, 2); + assert.strictEqual(second.body.nodeId, first.body.nodeId); + // And that key is the one given. + const port = nodes[1].clusterPort; + const node = nodeKeys.get(nodes[1].nodeId); + const auth = clusterAuth(node, `127.0.0.1:${port}`); + assert.match(await clusterConnect(port, auth), / 200 /); + }, + { configName: 'fromEnvironment', nodeEnv } + ); +}); + +// LD_LIBRARY_PATH for a copy of `binary` elsewhere: on Linux, some builds +// (TSan) link shared libraries found relative to the binary's own directory, +// which a copy does not have. Empty where `ldd` does not apply. +function sharedLibraryPath(binary) { + if (process.platform !== 'linux') return {}; + const libraries = execFileSync('ldd', [binary], { encoding: 'utf8' }); + const dirs = [...libraries.matchAll(/=> (\/\S+)/g)].map((m) => dirname(m[1])); + return { LD_LIBRARY_PATH: [...new Set(dirs)].join(':') }; +} + +test('cluster: a binary from workerd compile takes the key and bucket from the environment', async () => { + const key = 'test-cluster-shared-secret-of-32-bytes'; + // `workerd compile`, run with the variables set, writes the config as it is. + const compile = async (args, file) => { + const out = await open(file, 'w', 0o755); + try { + const child = spawn( + env.WORKERD_BINARY, + ['compile', ...args, env.WD_TEST_CONFIG, 'fromEnvironment'], + { + stdio: ['ignore', out.fd, 'inherit'], + env: { + ...env, + WORKERD_CLUSTER_KEY: key, + WORKERD_CLUSTER_BUCKET: 's3://wdtest/cluster', + }, + } + ); + const code = await new Promise((resolve, reject) => { + child.once('error', reject).once('exit', resolve); + }); + assert.strictEqual(code, 0, `workerd compile ${args.join(' ')} failed`); + } finally { + await out.close(); + } + }; + const nodeBinary = async (i, root) => { + if (i === 0) return { binary: env.WORKERD_BINARY, compiled: false }; + const configOnly = join(root, 'config.bin'); + await compile(['--config-only'], configOnly); + const bytes = await readFile(configOnly); + assert(!bytes.includes(key), 'the compiled config holds the key'); + assert(!bytes.includes('s3://wdtest/cluster'), 'it holds the bucket'); + const exe = process.platform === 'win32' ? '.exe' : ''; + const binary = join(root, `compiled-workerd${exe}`); + await compile([], binary); + return { binary, compiled: true }; + }; + const nodeEnv = async (i) => ({ + WORKERD_CLUSTER_KEY: key, + WORKERD_CLUSTER_BUCKET: 's3://wdtest/cluster', + ...(i === 1 ? sharedLibraryPath(env.WORKERD_BINARY) : {}), + }); + await withCluster( + 2, + async ({ nodes }) => { + // The compiled node forwards to the other, so it joined with the key. + const first = await fetchJson(nodes[0].httpPort, '/increment?name=bin'); + const second = await fetchJson(nodes[1].httpPort, '/increment?name=bin'); + assert.strictEqual(first.status, 200, JSON.stringify(first.body)); + assert.strictEqual(second.status, 200, JSON.stringify(second.body)); + assert.strictEqual(second.body.count, 2); + assert.strictEqual(second.body.nodeId, first.body.nodeId); + }, + { configName: 'fromEnvironment', nodeEnv, nodeBinary } + ); +}); + test('cluster: a public cluster address is refused', async () => { const local = await mkdtemp(join(tmpdir(), 'workerd-cluster-')); // The unreachable bucket proves that address validation runs before @@ -1747,7 +1867,11 @@ for (const dialect of ['s3', 'gcs']) { // As `GCS`, with tokens from the fake metadata server. const options = dialect === 'gcs' - ? { configName: 'gcs', dialect, nodeEnv: (bucket) => bucket.gcsEnv } + ? { + configName: 'gcs', + dialect, + nodeEnv: (_i, _root, bucket) => bucket.gcsEnv, + } : {}; await withCluster( 1, @@ -3504,7 +3628,10 @@ async function until(check, ms, message) { } test('cluster: an owner record write answered 503 after it landed counts as written', async () => { - for (const options of [{}, { ...GCS, nodeEnv: (bucket) => bucket.gcsEnv }]) { + for (const options of [ + {}, + { ...GCS, nodeEnv: (_i, _root, bucket) => bucket.gcsEnv }, + ]) { await withCluster( 1, async ({ nodes, bucket, nodeKeys }) => { @@ -3605,7 +3732,7 @@ test('cluster: a gs:// bucket holds the cluster, with tokens from the metadata s { ...GCS, before: (bucket) => bucket.gcs({ expiresIn: 8 }), - nodeEnv: (bucket) => bucket.gcsEnv, + nodeEnv: (_i, _root, bucket) => bucket.gcsEnv, } ); }); @@ -3641,7 +3768,7 @@ test('cluster: a gs:// bucket takes a service account key', async () => { }; await writeFile(keyFile, JSON.stringify(key)); }, - nodeEnv: (bucket) => ({ + nodeEnv: (_i, _root, bucket) => ({ ...bucket.gcsEnv, GCE_METADATA_HOST: undefined, GOOGLE_APPLICATION_CREDENTIALS: keyFile, diff --git a/src/workerd/server/tests/cluster/cluster-test.wd-test b/src/workerd/server/tests/cluster/cluster-test.wd-test index 21103c84a66..85408a1e780 100644 --- a/src/workerd/server/tests/cluster/cluster-test.wd-test +++ b/src/workerd/server/tests/cluster/cluster-test.wd-test @@ -85,6 +85,19 @@ const shortLease :Workerd.Config = ( ), ); +# As `config`, with the key and bucket left to WORKERD_CLUSTER_KEY (or WORKERD_CLUSTER_KEY_FILE) and +# WORKERD_CLUSTER_BUCKET. +const fromEnvironment :Workerd.Config = ( + services = .services, + sockets = .sockets, + cluster = ( + bucketOptions = .bucketOptions, + address = "127.0.0.1:0", + stopTimeoutMs = 10000, + unsafeTimeDivisor = 4, + ), +); + const services :List(Workerd.Service) = [ ( name = "local", disk = ( diff --git a/src/workerd/server/workerd.capnp b/src/workerd/server/workerd.capnp index f5331a6edc2..e62947b74ec 100644 --- a/src/workerd/server/workerd.capnp +++ b/src/workerd/server/workerd.capnp @@ -199,6 +199,9 @@ struct ClusterConfig { # that is never completed or aborted, such as an R2 put cut off mid-stream, otherwise keeps its # parts, and their storage, forever. # + # When empty, `serve` takes it from the environment variable `WORKERD_CLUSTER_BUCKET`, ignoring + # trailing whitespace. A bucket set nowhere is an error. + # # A `gs://` bucket is reached through Cloud Storage's XML API, whose writes are conditional on # object generations. Its access tokens come from the service account key that # `GOOGLE_APPLICATION_CREDENTIALS` names (a credentials file of another type is an error); else @@ -265,6 +268,12 @@ struct ClusterConfig { # channel tokens, which pass service and Durable Object stubs over RPC. Traffic is not # encrypted: run the cluster on a private network (a VPC, WireGuard, Tailscale). # + # When empty, `serve` takes the key from the environment variable `WORKERD_CLUSTER_KEY`, or reads + # it at startup from the file that `WORKERD_CLUSTER_KEY_FILE` names, such as a mounted secret, + # ignoring trailing whitespace. Set only one of the two. The key is text, so the file must be + # UTF-8. A config, or a binary that `workerd compile` builds, then holds no key. A key set + # nowhere is an error. + # # TODO(someday): Support some way to gradually roll out a rotated key. unsafePublicAddress @5 :Bool = false;