From 1cbe60c66c18c7e1f1dfe5f24e407127e50007fe Mon Sep 17 00:00:00 2001 From: Patriciaath999 Date: Sat, 14 Nov 2026 18:45:09 +0800 Subject: [PATCH 1/3] Take the Change keys code from the launcher A server the desktop app starts as its child gets no Change keys: the code it asks for is made in run_web and printed to a terminal the desktop user never sees, so SetupContext is left out for a child. A child now takes its code from CODETRIAL_CHANGE_KEYS_CODE, ignoring one shorter than 24 letters and digits, and does not print it. A launch from a terminal still makes and prints its own code, and a child given none still gets no Change keys. The desktop side of #687 follows. Change-Id: I1044d348f980a97067c591b093d56fae42984e55 --- README.md | 1 + src/config.rs | 10 ++++++++ src/launch.rs | 34 +++++++++++++++++++------ src/lib.rs | 9 +++++++ src/main.rs | 5 +++- src/web/setup_edit.rs | 30 ++++++++++------------ tests/config.rs | 15 ++--------- tests/config/launcher.rs | 39 +++++++++++++++++++++++++++++ tests/unit/bin.rs | 30 ++++++++++++++-------- tests/unit/livekit/probe/serving.rs | 2 +- tests/unit/web/setup_edit.rs | 12 ++++----- 11 files changed, 130 insertions(+), 57 deletions(-) create mode 100644 tests/config/launcher.rs diff --git a/README.md b/README.md index 72539796a..74629ad29 100644 --- a/README.md +++ b/README.md @@ -353,6 +353,7 @@ The common ones: | `CODETRIAL_MAX_CONCURRENT_INTERVIEWS` | `16` | Interviews one `web` process hosts agents for | | `CODETRIAL_ALLOWED_HOSTS` | empty | Comma-separated `Host` values the server answers; any other is refused with 421. Empty answers every name, but a value that names no host is refused at startup. `--allowed-hosts` sets it from the command line | | `CODETRIAL_EXIT_WITH_STDIN` | unset | For a program that starts the server as its child: exit when standard input reaches end of file, so the server does not outlive a launcher that crashed. Read from the process environment even under `--data-dir` | +| `CODETRIAL_CHANGE_KEYS_CODE` | unset | For a program that starts the server as its child: the Change keys code, at least 24 letters and digits, which the server then never prints. Read from the process environment even under `--data-dir`; ignored by a launch from a terminal, which makes and prints its own | Two more matter in production. `SESSION_SECRET` signs the session cookie, and its built-in default is a string published in this repository, so the server diff --git a/src/config.rs b/src/config.rs index 3c06dc14a..2265e0ed2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -690,6 +690,16 @@ pub fn exit_with_stdin(value: Option<&str>) -> bool { parse_bool(value, false) } +/// `CODETRIAL_CHANGE_KEYS_CODE`: the code the desktop app hands its child. +/// One too short to stand in for the code `run_web` makes is no code, so a +/// launcher that set it carelessly gets no Change keys rather than a weak one. +pub fn change_keys_code(value: Option<&str>) -> Option { + value + .map(str::trim) + .filter(|code| code.len() >= 24 && code.bytes().all(|byte| byte.is_ascii_alphanumeric())) + .map(str::to_string) +} + pub fn gemini_candidate_video_enabled(value: Option<&str>) -> bool { parse_bool(value, DEFAULT_GEMINI_CANDIDATE_VIDEO_ENABLED) } diff --git a/src/launch.rs b/src/launch.rs index bc8afc315..ae77591e3 100644 --- a/src/launch.rs +++ b/src/launch.rs @@ -859,14 +859,28 @@ pub fn prepare( }) } -/// Who started this server. A launcher that owns it (the desktop app, a test -/// fixture) offers no Setup page; an operator who started it is offered one. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// Who started this server. An operator who started it is offered Change keys +/// with a code made here; a launcher that owns it (the desktop app, a test +/// fixture) offers it only with the code it handed its child, carried here. +/// No `Debug`: `Parent` carries that code. +#[derive(Clone, PartialEq, Eq)] pub enum LaunchedBy { - Parent, + Parent(Option), Operator, } +/// The code Change keys asks for: made here for a launch from a terminal, or +/// the one the desktop app made and handed its child. A child given none gets +/// no Change keys. +fn change_keys_code(launched_by: &LaunchedBy) -> Result, String> { + if let LaunchedBy::Parent(code) = launched_by { + return Ok(code.clone()); + } + crate::accounts::random_token(18) + .map(Some) + .map_err(|error| format!("could not make a Change keys code: {error}")) +} + /// What a launch settles once its socket is bound and its address is known: /// the published-secret refusal, the Setup page and task mode, both of which /// depend on where the server is reachable. @@ -884,12 +898,18 @@ pub fn finish( primary_config_path(options)?, values.clone(), bound, - launched_by == LaunchedBy::Operator, + change_keys_code(&launched_by)?, config.trusted_proxy_hops, - )?; + ); // Same reason `serve_setup` prints this: say where to go. println!("codetrial: open http://{bound} in your browser"); - if let Some(setup) = &setup { + + // A child's code is not printed: its output goes to a log file, and the app + // that launched it already holds the code. + if let Some(setup) = setup + .as_ref() + .filter(|_| launched_by == LaunchedBy::Operator) + { println!( "codetrial: to change keys at http://{bound}/setup, enter {}", setup.code() diff --git a/src/lib.rs b/src/lib.rs index 1eaa1e0a0..6ae40f074 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -102,6 +102,15 @@ pub fn exit_when_stdin_closes() -> bool { true } +/// The Change keys code a launcher handed its child in +/// `CODETRIAL_CHANGE_KEYS_CODE`, or `None` when it handed none strong enough. +/// From the process environment for the same reason as +/// `exit_when_stdin_closes`: it is not configuration but what the launcher +/// handed over, and its child has no terminal to print a code of its own to. +pub fn handed_change_keys_code() -> Option { + 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_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/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(), From 7021c76b0195f4616efaca8cc47fb81d57e74cd1 Mon Sep 17 00:00:00 2001 From: Patriciaath999 Date: Sat, 14 Nov 2026 21:02:49 +0800 Subject: [PATCH 2/3] Test Change keys end to end for a launcher's child The desktop app starts the server as its child and hands it the Change keys code in the environment. Nothing ran that path: the unit tests pass the code into finish, and no CLI test started a child with one. The test starts the binary as the desktop app does, with CODETRIAL_EXIT_WITH_STDIN and the code set, checks that a wrong code is refused and the handed one rewrites the config, and that the code never reaches stdout, which the app writes to a log file. Change-Id: Iea6ba45fe95672c2ebcbca63ca268793b316d288 --- tests/cli/setup_save.rs | 73 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) 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:?}" + ); +} From 90af116069f899d897a2026b7f303ed4ab9c7729 Mon Sep 17 00:00:00 2001 From: Patriciaath999 Date: Sat, 14 Nov 2026 18:45:34 +0800 Subject: [PATCH 3/3] Offer Change keys in the desktop app Keys entered at the desktop app's first Setup could not be changed afterwards without editing the config file by hand, because its server had no Change keys code anyone could read. The app now makes a code on every launch and hands it to the server in CODETRIAL_CHANGE_KEYS_CODE. With the interview in its window, it fills the code into the server's own /setup page; with the interview in the default browser, where it cannot fill a field, its start page shows the code instead. The code never travels in a URL. A save takes effect at the next launch; restarting the server on it is #688. Close #687 Change-Id: If3fc34eae7782ba7a867489f52fdca74f7ee7e34 --- desktop/Cargo.lock | 1 + desktop/Cargo.toml | 2 ++ desktop/src/main.rs | 54 ++++++++++++++++++++++++++++++-- desktop/src/navigation.rs | 23 ++++++++++++++ desktop/src/server.rs | 14 +++++++++ desktop/tests/unit/navigation.rs | 44 ++++++++++++++++++++++++++ desktop/tests/unit/server.rs | 22 +++++++++++-- desktop/ui/index.html | 5 +++ docs/desktop.md | 20 +++++++++--- src/web/setup.rs | 2 +- 10 files changed, 176 insertions(+), 11 deletions(-) diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock index 8507eb850..9bf0ad789 100644 --- a/desktop/Cargo.lock +++ b/desktop/Cargo.lock @@ -476,6 +476,7 @@ dependencies = [ name = "codetrial-desktop" version = "0.1.0" dependencies = [ + "getrandom 0.3.4", "open", "tauri", "tauri-build", diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml index 39d25e7fe..fb7131cc6 100644 --- a/desktop/Cargo.toml +++ b/desktop/Cargo.toml @@ -27,6 +27,8 @@ all = "deny" tauri-build = { version = "=2.7.4", features = [] } [dependencies] +# Already in the tree through tauri; the Change keys code is read from it. +getrandom = "=0.3.4" open = { version = "=5.4.4", features = ["shellexecute-on-windows"] } tauri = { version = "=2.12.5", features = [] } tauri-plugin-dialog = "=2.8.4" diff --git a/desktop/src/main.rs b/desktop/src/main.rs index d7c532ecb..4a60a5a28 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -18,11 +18,13 @@ use std::path::Path; use std::sync::{LazyLock, Mutex, mpsc}; use std::time::Duration; -use tauri::webview::{DownloadEvent, NewWindowResponse, PermissionKind, PermissionResponse}; +use tauri::webview::{ + DownloadEvent, NewWindowResponse, PageLoadEvent, PermissionKind, PermissionResponse, +}; use tauri::{AppHandle, Manager, RunEvent, Url, WebviewUrl, WebviewWindowBuilder, WindowEvent}; use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind}; -use navigation::{Ask, Verdict}; +use navigation::{Ask, ChangeKeysCode, Verdict}; const WINDOW: &str = "main"; @@ -89,6 +91,8 @@ enum Close { struct Shell { server: Mutex>, + /// The running server's Change keys code, shown or filled in this window. + change_keys_code: Mutex>, phase: Mutex, close: Mutex, } @@ -113,6 +117,7 @@ fn main() { .plugin(tauri_plugin_dialog::init()) .manage(Shell { server: Mutex::new(None), + change_keys_code: Mutex::new(None), phase: Mutex::new(Phase::Starting { server_ready: false, webrtc: None, @@ -208,6 +213,27 @@ fn open_window(app: &AppHandle) -> tauri::Result<()> { Verdict::Refuse => false, } }) + // Change keys asks for the code the server would print to a terminal, + // and this server has none. With the interview in this window the code + // is filled into the server's own Setup page and no other; with it in + // the browser, the start page left here shows it, as a terminal would. + // Never in a URL, where history would keep it. + .on_page_load(|webview, payload| { + if payload.event() != PageLoadEvent::Finished { + return; + } + let script = + match navigation::change_keys_code_for(payload.url(), &SERVER_URL, &START_PAGE) { + Some(ChangeKeysCode::Fill) => fill_change_keys_code, + Some(ChangeKeysCode::Show) => show_change_keys_code, + None => return, + }; + let shell = webview.app_handle().state::(); + let code = shell.change_keys_code.lock().expect("code lock").clone(); + if let Some(code) = code { + let _ = webview.eval(script(&code)); + } + }) // `target="_blank"` and `window.open`. A second webview would be a // second window into the same origin with none of the rules above, so a // web page goes to the browser and nothing opens here. @@ -300,6 +326,7 @@ fn launch(app: &AppHandle) { std::fs::create_dir_all(&data_dir) .map_err(|error| format!("cannot create {}: {error}", data_dir.display()))?; Ok(server::Launch { + change_keys_code: server::change_keys_code()?, program: server::program_path()?, data_dir, addr: SERVER_ADDR.to_string(), @@ -313,6 +340,10 @@ fn launch(app: &AppHandle) { Err(message) => return show_failure(app, &message, None), }; + *app.state::() + .change_keys_code + .lock() + .expect("code lock") = Some(launch.change_keys_code.clone()); let data_dir = launch.data_dir.clone(); let reporter = app.clone(); let started = server::start(&launch, move |status| { @@ -342,6 +373,25 @@ fn launch(app: &AppHandle) { } } +/// The script that puts `code`, hex digits only, into the Setup page's code +/// field. The page shows and enables that field itself once `/api/setup` +/// answers, which keeps the value, so the field appears already filled. +fn fill_change_keys_code(code: &str) -> String { + format!( + "(() => {{ const field = document.getElementById('code'); \ + if (field) field.value = '{code}'; }})()" + ) +} + +/// The script that shows `code`, hex digits only, on the start page when the +/// interview runs in the browser, where nothing here can fill it in. +fn show_change_keys_code(code: &str) -> String { + format!( + "(() => {{ document.getElementById('change-keys-code').textContent = '{code}'; \ + document.getElementById('change-keys').hidden = false; }})()" + ) +} + /// Shows the server in this window, or in the default browser when this /// window has no WebRTC, once both halves are known: the server is ready and /// the starting page has said what it has. Called as each arrives, in either diff --git a/desktop/src/navigation.rs b/desktop/src/navigation.rs index eaf166546..7c6777fdb 100644 --- a/desktop/src/navigation.rs +++ b/desktop/src/navigation.rs @@ -54,6 +54,29 @@ pub fn judge(url: &Url, server: &Url, start_page: &Url) -> Verdict { } } +/// What a page the window finished loading is handed of the Change keys code. +#[derive(Debug, PartialEq, Eq)] +pub enum ChangeKeysCode { + /// Filled into the code field of the server's own Setup page. + Fill, + /// Shown on the start page left in the window while the interview runs in + /// the browser, where nothing here can fill a field. + Show, +} + +/// Which pages get the code, and no other: a mistake here either hides Change +/// keys or hands the code to a page that is not the server's Setup page. Built +/// on `judge`, so a page the window may not show never gets it. +pub fn change_keys_code_for(url: &Url, server: &Url, start_page: &Url) -> Option { + match judge(url, server, start_page) { + Verdict::Server if url.path() == "/setup" => Some(ChangeKeysCode::Fill), + Verdict::StartPage(Ask::Nothing) if url.query_pairs().any(|(key, _)| key == "browser") => { + Some(ChangeKeysCode::Show) + } + _ => None, + } +} + /// Where the window's start page loads, `http_scheme` being true on Windows /// and Android. Tauri serves `WebviewUrl::App("index.html")` at the root of /// its own origin, `http://tauri.localhost/` there and `tauri://localhost/` diff --git a/desktop/src/server.rs b/desktop/src/server.rs index df11e29e7..ffb655844 100644 --- a/desktop/src/server.rs +++ b/desktop/src/server.rs @@ -39,6 +39,19 @@ pub struct Launch { /// A CLI config whose keys Setup offers to use on a first launch. The /// server decides what is offered and what using it writes. pub import_config: Option, + /// What Change keys asks for, new on every launch. The server has no + /// terminal to print one to, so the app makes it, hands it over in the + /// environment, and shows or fills it in its own window. + pub change_keys_code: String, +} + +/// A code for `Launch::change_keys_code`: 32 hex digits from the operating +/// system's generator. +pub fn change_keys_code() -> Result { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes) + .map_err(|error| format!("cannot make a Change keys code: {error}"))?; + Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) } /// The CLI config in `start`: the CLI's own two places there and nowhere else. @@ -116,6 +129,7 @@ fn command(launch: &Launch) -> Command { // data folder is the one place it can sensibly mean. .current_dir(&launch.data_dir) .env("CODETRIAL_EXIT_WITH_STDIN", "1") + .env("CODETRIAL_CHANGE_KEYS_CODE", &launch.change_keys_code) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); diff --git a/desktop/tests/unit/navigation.rs b/desktop/tests/unit/navigation.rs index 9ef61c20b..e29bc3cf4 100644 --- a/desktop/tests/unit/navigation.rs +++ b/desktop/tests/unit/navigation.rs @@ -176,3 +176,47 @@ fn a_download_keeps_its_name_and_never_overwrites() { let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn only_the_servers_setup_page_and_the_browser_start_page_get_the_code() { + let server = url("http://127.0.0.1:3101/"); + for start in [ + "tauri://localhost/index.html", + "http://tauri.localhost/index.html", + ] { + let start = url(start); + let code_for = |page: &str| change_keys_code_for(&url(page), &server, &start); + assert_eq!( + code_for("http://127.0.0.1:3101/setup"), + Some(ChangeKeysCode::Fill) + ); + + // `show_start_page` loads the root with the query, which serves + // `index.html`; the named file is the same page. + for shown in ["/?browser=", "index.html?browser="] { + assert_eq!( + code_for(start.join(shown).unwrap().as_str()), + Some(ChangeKeysCode::Show), + "{shown}" + ); + } + + // The server's own `?browser` is just a server page, and only its Setup + // page has the field: not another path, not another port, not the start + // page while it is starting, failing or asking. + for nothing in [ + "http://127.0.0.1:3101/?browser=", + "http://127.0.0.1:3101/", + "http://127.0.0.1:3101/setup/x", + "http://127.0.0.1:3102/setup", + "http://localhost:3101/setup", + ] { + assert_eq!(code_for(nothing), None, "{nothing}"); + } + for query in ["", "?error=x", "?webrtc=no", "?reopen", "?browser=&reopen"] { + let page = start.join(&format!("index.html{query}")).unwrap(); + assert_eq!(code_for(page.as_str()), None, "{page}"); + } + assert_eq!(code_for(start.join("setup").unwrap().as_str()), None); + } +} diff --git a/desktop/tests/unit/server.rs b/desktop/tests/unit/server.rs index a379b1327..6ae787039 100644 --- a/desktop/tests/unit/server.rs +++ b/desktop/tests/unit/server.rs @@ -3,6 +3,8 @@ use std::sync::mpsc; use super::*; +const CODE: &str = "0123456789abcdef0123456789abcdef"; + fn temp_dir(label: &str) -> PathBuf { static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let dir = std::env::temp_dir().join(format!( @@ -22,6 +24,7 @@ fn the_server_is_started_on_the_data_dir_and_told_the_rest() { data_dir: PathBuf::from("/data"), addr: "127.0.0.1:3101".to_string(), import_config: None, + change_keys_code: CODE.to_string(), }; let command = command(&launch); let args = command @@ -43,8 +46,8 @@ fn the_server_is_started_on_the_data_dir_and_told_the_rest() { ); assert_eq!(command.get_current_dir(), Some(Path::new("/data"))); - // The pipe is the one thing it is told through the environment, which a - // `--data-dir` launch reads no configuration from. + // The pipe and the Change keys code are the two things it is told through + // the environment, which a `--data-dir` launch reads no configuration from. let env = |key: &str| { command .get_envs() @@ -52,8 +55,9 @@ fn the_server_is_started_on_the_data_dir_and_told_the_rest() { .and_then(|(_, value)| value) .map(|value| value.to_string_lossy().into_owned()) }; - assert_eq!(command.get_envs().count(), 1); + assert_eq!(command.get_envs().count(), 2); assert_eq!(env("CODETRIAL_EXIT_WITH_STDIN").as_deref(), Some("1")); + assert_eq!(env("CODETRIAL_CHANGE_KEYS_CODE").as_deref(), Some(CODE)); } #[test] @@ -63,6 +67,7 @@ fn a_cli_config_found_is_offered_to_the_server_to_import() { data_dir: PathBuf::from("/data"), addr: "127.0.0.1:3101".to_string(), import_config: Some(PathBuf::from("/checkout/config/codetrial.env.local")), + change_keys_code: CODE.to_string(), }; let args = command(&launch) .get_args() @@ -144,6 +149,7 @@ fn launch_of(dir: &Path, program: PathBuf, addr: String) -> Launch { data_dir: dir.to_path_buf(), addr, import_config: None, + change_keys_code: CODE.to_string(), } } @@ -218,3 +224,13 @@ fn a_server_is_ready_once_bound_and_stops_when_its_stdin_closes() { assert!(received.recv_timeout(Duration::from_millis(500)).is_err()); let _ = std::fs::remove_dir_all(&dir); } + +/// Strong enough for the server to take: it ignores a code shorter than 24 +/// letters and digits. +#[test] +fn a_change_keys_code_is_new_hex_on_every_launch() { + let first = change_keys_code().unwrap(); + assert_eq!(first.len(), 32); + assert!(first.bytes().all(|byte| byte.is_ascii_hexdigit())); + assert_ne!(first, change_keys_code().unwrap()); +} diff --git a/desktop/ui/index.html b/desktop/ui/index.html index 318a47594..1e647c1ea 100644 --- a/desktop/ui/index.html +++ b/desktop/ui/index.html @@ -23,6 +23,11 @@

CodeTrial

Keep this window open while you practise. Closing it stops CodeTrial.

+