{
+ config::change_keys_code(std::env::var("CODETRIAL_CHANGE_KEYS_CODE").ok().as_deref())
+}
+
/// Writes a new file that only its owner can read, and refuses rather than
/// replacing one: the config file Setup writes and the session key a
/// `--data-dir` launch makes both hold secrets.
diff --git a/src/main.rs b/src/main.rs
index 426b4bbe4..8c6268ee0 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -284,8 +284,11 @@ fn run_web(options: CliOptions) -> Result<(), String> {
// Why that socket is carried here rather than rebound: `serve_setup`. Read
// once, so the question and the page it opens answer from the same map.
let before_config = environment_and_flags(&options);
+
+ // A child has no terminal anyone reads, so the code Change keys asks for is
+ // the one its launcher handed over, if any.
let launched_by = if codetrial::exit_when_stdin_closes() {
- LaunchedBy::Parent
+ LaunchedBy::Parent(codetrial::handed_change_keys_code())
} else {
LaunchedBy::Operator
};
diff --git a/src/web/setup.rs b/src/web/setup.rs
index 7ce16188c..7a325ef93 100644
--- a/src/web/setup.rs
+++ b/src/web/setup.rs
@@ -428,7 +428,7 @@ const SETUP_PAGE: &str = r#"
Change keys code
- Printed in the terminal this server was started from, and new every time it starts.
+ Printed in the terminal this server was started from, or shown by the desktop app that started it, and new every time it starts.
Save and continue
diff --git a/src/web/setup_edit.rs b/src/web/setup_edit.rs
index 0a6fa2b92..1b6cc67a8 100644
--- a/src/web/setup_edit.rs
+++ b/src/web/setup_edit.rs
@@ -37,10 +37,12 @@ impl SetupContext {
/// The loopback bind keeps the network out and the `Host` check keeps out
/// a page that rebinds a name to 127.0.0.1, but any account on this machine
/// reaches the port and chooses every header itself. What such an account
- /// lacks is the code: it is printed only to the terminal of whoever started
- /// the server, and is new on every start. A launcher's child, the desktop
- /// app's server, has no terminal anyone reads, and behind a proxy the
- /// requests are not only this machine's, so neither gets Change keys.
+ /// lacks is the code, new on every start: `run_web` makes it and prints it
+ /// to the terminal of whoever started the server, or takes it from the
+ /// desktop app that launched this one as its child, which has no terminal
+ /// anyone reads and shows the code in its own window instead. `code` is
+ /// `None` for a launch that has neither. Behind a proxy the requests are
+ /// not only this machine's, so that launch gets no Change keys either.
///
/// A config that is a symlink is not offered either: renaming the new file
/// over it would replace the link and leave its target unchanged.
@@ -48,25 +50,19 @@ impl SetupContext {
path: PathBuf,
values: BTreeMap,
bound: SocketAddr,
- standalone: bool,
+ code: Option,
trusted_proxy_hops: u32,
- ) -> Result, String> {
- if !standalone || !bound.ip().is_loopback() || trusted_proxy_hops != 0 {
- return Ok(None);
- }
- let Some(contents) = regular_file(&path) else {
- return Ok(None);
- };
- let code = crate::accounts::random_token(18)
- .map_err(|error| format!("could not make a Change keys code: {error}"))?;
- Ok(Some(Self {
+ ) -> Option {
+ let code = code.filter(|_| bound.ip().is_loopback() && trusted_proxy_hops == 0)?;
+ let contents = regular_file(&path)?;
+ Some(Self {
path,
contents,
values,
port: bound.port(),
code,
saving: tokio::sync::Mutex::new(()),
- }))
+ })
}
/// For `run_web` to print, and for nothing else.
@@ -93,7 +89,7 @@ impl SetupContext {
if digest(given).as_ref() != digest(&self.code).as_ref() {
return json_response(
StatusCode::FORBIDDEN,
- json!({ "error": "Enter the Change keys code this server printed when it started." }),
+ json!({ "error": "Enter the Change keys code this server printed when it started, or the one the desktop app that started it shows." }),
);
}
let _saving = self.saving.lock().await;
diff --git a/tests/cli/setup_save.rs b/tests/cli/setup_save.rs
index 680a4bafc..b4415c022 100644
--- a/tests/cli/setup_save.rs
+++ b/tests/cli/setup_save.rs
@@ -220,3 +220,76 @@ async fn change_keys_rewrites_the_config_the_launch_read() {
contents("new-key", "GOOGLE_API_KEYS=\nGOOGLE_API_KEY=new-google\n")
);
}
+
+/// Change keys for a launcher's child, as the desktop app starts it: the code
+/// comes in `CODETRIAL_CHANGE_KEYS_CODE`, a save with it rewrites the config,
+/// and the code never reaches stdout, which the app writes to a log file.
+#[test]
+fn a_child_saves_with_the_code_its_launcher_handed_over_and_never_prints_it() {
+ use std::io::{BufRead, BufReader};
+
+ const CODE: &str = "0123456789abcdef0123456789abcdef";
+ let dir = exe_temp_path("change-keys-child");
+ std::fs::create_dir_all(&dir).unwrap();
+ let exe = binary_beside(&dir);
+ let livekit = spawn_livekit_room_service("new-key", "secret");
+
+ let config = dir.join("codetrial.env.local");
+ let contents = |livekit_key: &str| {
+ format!(
+ "LIVEKIT_URL=http://{livekit}\nLIVEKIT_API_KEY={livekit_key}\n\
+ LIVEKIT_API_SECRET=secret\n"
+ )
+ };
+ std::fs::write(&config, contents("old-key")).unwrap();
+ let (addr, mut server) = spawn_server(|addr| {
+ let mut command = Command::new(&exe);
+ scrubbed(&mut command)
+ .args([
+ "web",
+ "--data-dir",
+ dir.to_str().unwrap(),
+ "--web-addr",
+ addr,
+ ])
+ .current_dir(&dir)
+ .env("CODETRIAL_EXIT_WITH_STDIN", "1")
+ .env("CODETRIAL_CHANGE_KEYS_CODE", CODE)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped());
+ command
+ });
+ let stdout = server.stdout.take().unwrap();
+ let lines = thread::spawn(move || {
+ BufReader::new(stdout)
+ .lines()
+ .map_while(Result::ok)
+ .collect::>()
+ });
+
+ let save = |code: &str| {
+ let body = format!(r#"{{"code":"{code}","livekitApiKey":"new-key"}}"#);
+ http_request(
+ &addr,
+ &format!(
+ "POST /api/setup HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\n\
+ Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ ),
+ )
+ };
+ let refused = save("ffffffffffffffffffffffffffffffff");
+ let saved = save(CODE);
+ let written = std::fs::read_to_string(&config).unwrap();
+ drop(server);
+ let printed = lines.join().unwrap();
+ let _ = std::fs::remove_dir_all(&dir);
+
+ assert!(refused.starts_with("HTTP/1.1 403"), "{refused}");
+ assert!(saved.starts_with("HTTP/1.1 200 OK"), "{saved}");
+ assert_eq!(written, contents("new-key"));
+ assert!(
+ printed.iter().all(|line| !line.contains(CODE)),
+ "{printed:?}"
+ );
+}
diff --git a/tests/config.rs b/tests/config.rs
index 709b62f17..9bea1e5ec 100644
--- a/tests/config.rs
+++ b/tests/config.rs
@@ -299,19 +299,6 @@ fn guest_mode_is_disabled_by_default_and_fails_closed() {
}
}
-/// Off unless asked for: a server whose stdin is `/dev/null`, which is every
-/// service manager's default, would otherwise exit the moment it started.
-#[test]
-fn exiting_with_stdin_is_only_on_when_a_launcher_asks() {
- let exits = codetrial::config::exit_with_stdin;
- for off in [None, Some(""), Some("0"), Some("false"), Some("maybe")] {
- assert!(!exits(off), "{off:?} should leave it off");
- }
- for on in ["1", "true", "yes"] {
- assert!(exits(Some(on)), "{on} should turn it on");
- }
-}
-
/// Asserted on the parser rather than through a config struct, because the
/// struct field it used to be read through was only ever consumed by `serve`.
///
@@ -1339,6 +1326,8 @@ fn loading_config_does_not_depend_on_the_current_directory() {
assert_eq!(config.pool.providers[0].google_api_keys, ["google"]);
}
+#[path = "config/launcher.rs"]
+mod launcher;
/// The recording block, which is off in every deployment until an operator
/// provisions the resources in `docs/recording-contract.md`. These read the
/// parser directly rather than through `load_from_pairs`, because
diff --git a/tests/config/launcher.rs b/tests/config/launcher.rs
new file mode 100644
index 000000000..c7673d2f7
--- /dev/null
+++ b/tests/config/launcher.rs
@@ -0,0 +1,39 @@
+//! What a program that starts the server as its child hands it through the
+//! environment, which a `--data-dir` launch reads no configuration from.
+
+/// Off unless asked for: a server whose stdin is `/dev/null`, which is every
+/// service manager's default, would otherwise exit the moment it started.
+#[test]
+fn exiting_with_stdin_is_only_on_when_a_launcher_asks() {
+ let exits = codetrial::config::exit_with_stdin;
+ for off in [None, Some(""), Some("0"), Some("false"), Some("maybe")] {
+ assert!(!exits(off), "{off:?} should leave it off");
+ }
+ for on in ["1", "true", "yes"] {
+ assert!(exits(Some(on)), "{on} should turn it on");
+ }
+}
+
+/// A code too short or too odd to stand in for the one `run_web` makes is no
+/// code, so a launcher that set it carelessly gets no Change keys at all.
+#[test]
+fn a_change_keys_code_is_taken_only_when_strong_enough() {
+ let code = codetrial::config::change_keys_code;
+ assert_eq!(
+ code(Some(" 0123456789abcdef0123456789abcdef\n")).as_deref(),
+ Some("0123456789abcdef0123456789abcdef")
+ );
+ assert_eq!(
+ code(Some("0123456789abcdef01234567")).as_deref(),
+ Some("0123456789abcdef01234567")
+ );
+ for weak in [
+ None,
+ Some(""),
+ Some("0123456789abcdef0123456"),
+ Some("0123456789abcdef 0123456789abcdef"),
+ Some("0123456789abcdef0123456789abcde'"),
+ ] {
+ assert_eq!(code(weak), None, "{weak:?} should give no code");
+ }
+}
diff --git a/tests/unit/bin.rs b/tests/unit/bin.rs
index 7a72f378f..de0d54a71 100644
--- a/tests/unit/bin.rs
+++ b/tests/unit/bin.rs
@@ -997,24 +997,32 @@ fn finish_refuses_the_published_secret_on_a_public_address() {
}
#[test]
-fn finish_offers_a_launchers_child_no_setup_page_and_no_task_mode() {
+fn finish_offers_a_launchers_child_change_keys_only_on_the_code_it_was_handed() {
let (dir, options) = launch_fixture("finish-child");
let mut values = livekit_values(&dir);
values.insert(
"SESSION_SECRET".into(),
"a-real-secret-for-this-test-only-0123".into(),
);
- let prepared = super::prepare(&values, &options).unwrap();
- let (config, setup) = super::finish(
- prepared.config,
- &values,
- &options,
- addr("127.0.0.1:3000"),
- super::LaunchedBy::Parent,
- )
- .unwrap();
+ let finish = |launched_by| {
+ let prepared = super::prepare(&values, &options).unwrap();
+ super::finish(
+ prepared.config,
+ &values,
+ &options,
+ addr("127.0.0.1:3000"),
+ launched_by,
+ )
+ .unwrap()
+ };
+
+ let (config, setup) = finish(super::LaunchedBy::Parent(None));
assert!(setup.is_none(), "a child has no terminal anyone reads");
assert!(config.tasks.is_none(), "task mode was not asked for");
+
+ let code = "0123456789abcdef0123456789abcdef";
+ let (_, setup) = finish(super::LaunchedBy::Parent(Some(code.to_string())));
+ assert_eq!(setup.as_ref().map(|setup| setup.code()), Some(code));
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1076,7 +1084,7 @@ fn run_stopped(
&values,
&options,
bound,
- super::LaunchedBy::Parent,
+ super::LaunchedBy::Parent(None),
)
.unwrap();
let dispatcher = std::sync::Arc::new(Busy {
diff --git a/tests/unit/livekit/probe/serving.rs b/tests/unit/livekit/probe/serving.rs
index 83e2f0c95..3852c6918 100644
--- a/tests/unit/livekit/probe/serving.rs
+++ b/tests/unit/livekit/probe/serving.rs
@@ -142,7 +142,7 @@ fn serve(
&values,
&options,
bound,
- LaunchedBy::Parent,
+ LaunchedBy::Parent(None),
)?;
config.probe_provider_quota &= !settings.offline;
let agent = local_agent_config(values)?
diff --git a/tests/unit/web/setup_edit.rs b/tests/unit/web/setup_edit.rs
index 957e61301..a09fa6c82 100644
--- a/tests/unit/web/setup_edit.rs
+++ b/tests/unit/web/setup_edit.rs
@@ -111,18 +111,17 @@ fn a_tab_after_export_names_the_same_key() {
}
#[test]
-fn only_a_standalone_loopback_launch_without_a_proxy_may_change_keys() {
+fn only_a_loopback_launch_with_a_code_and_without_a_proxy_may_change_keys() {
let scratch = Scratch::new();
let path = scratch.config("LIVEKIT_API_KEY=old\n");
- let context = |path: &Path, bound: &str, standalone, hops| {
+ let context = |path: &Path, bound: &str, standalone: bool, hops| {
SetupContext::new(
path.to_path_buf(),
BTreeMap::new(),
bound.parse().unwrap(),
- standalone,
+ standalone.then(|| "code".to_string()),
hops,
)
- .unwrap()
};
assert!(context(&path, "127.0.0.1:3000", true, 0).is_some());
assert!(context(&path, "[::1]:3000", true, 0).is_some());
@@ -237,9 +236,8 @@ impl Server {
.unwrap()
.into_iter()
.collect();
- let context = SetupContext::new(path.clone(), values, bound, true, 0)
- .unwrap()
- .unwrap();
+ let context =
+ SetupContext::new(path.clone(), values, bound, Some("code".to_string()), 0).unwrap();
let code = context.code().to_string();
let config = super::super::WebServerConfig {
web_dir: PathBuf::new(),