diff --git a/crates/automation/src/agents/link.rs b/crates/automation/src/agents/link.rs index 6296beea7..f43e37f78 100644 --- a/crates/automation/src/agents/link.rs +++ b/crates/automation/src/agents/link.rs @@ -16,7 +16,7 @@ use crate::security; use crate::server::{self, Listening}; /// How long after a failed start [`AgentLink::sync`] tries again with the same settings, so -/// freeing a taken port is enough. +/// freeing a taken port is enough. A refused token file is not tried again: see [`AgentLink::sync`]. pub const RETRY: Duration = Duration::from_secs(5); /// Why agents cannot connect, or what the app could not apply. `Display` is the English sentence @@ -123,6 +123,10 @@ pub struct AgentLink { applied: Option>, retry_at: Option, retry: Duration, + /// The token a failed start already read and checked, for its retries; cleared once a start + /// succeeds. On Windows the check starts `whoami` and PowerShell (`owner_only`), about 300 ms + /// on the UI thread, which every retry of a taken port would otherwise pay again. + checked_token: Option, status: AgentLinkStatus, } @@ -144,6 +148,7 @@ impl AgentLink { applied: None, retry_at: None, retry: RETRY, + checked_token: None, status: AgentLinkStatus::default(), } } @@ -166,7 +171,12 @@ impl AgentLink { /// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it /// on another port, stop it, or keep it while other settings change. Does nothing while `want` - /// equals the last call's and no retry of a failed start is due. + /// equals the last call's and no retry of a failed start is due. A token file refused as it is + /// (open to others, a damaged token) is replaced by a new one (`fresh_token`). One that still + /// can't be used (a folder in its place, a folder that can't be written) schedules no retry: + /// that lasts until someone changes it, and on Windows each check blocks the UI thread for + /// about 300 ms (`owner_only` starts `whoami` and PowerShell), which a retry every [`RETRY`] + /// turned into a stall every few seconds (photocraft#17006). Changing the settings tries again. pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate { let mut update = LinkUpdate::default(); if self.launch.is_some() { @@ -218,6 +228,10 @@ impl AgentLink { update.requests = Some(requests); Ok(()) } + Err(problem @ LinkProblem::TokenFile(_)) => { + log::warn!("{problem}"); + Err(problem) + } Err(problem) => { log::warn!("{problem}"); self.retry_at = Some(motion::now() + self.retry); @@ -229,13 +243,21 @@ impl AgentLink { /// The token from the settings folder (created `0600` when missing), the server, then the /// connection file. Any failure leaves nothing running. - fn start(&self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { + /// A retry of a failed start reuses the token that start checked ([`Self::checked_token`]). + /// The token file is the link's own, so one refused as it is gets a new token (see + /// [`fresh_token`]). + fn start(&mut self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { let token_file = dir.join(TOKEN_FILE); - let token = security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?; + let token = match self.checked_token.clone() { + Some(token) => token, + None => fresh_token(&token_file)?, + }; + self.checked_token = Some(token.clone()); let (requests, server) = server::listen(port, token, host.clone()).map_err(|e| LinkProblem::Listen { port, error: e.to_string() })?; let running = Running { server, dir: dir.to_path_buf(), port_pref }; let connection = Connection::new(running.server.addr.port(), token_file, self.app.clone()); write_connection(dir, &connection).map_err(|e| LinkProblem::Publish(e.to_string()))?; + self.checked_token = None; Ok((running, requests)) } @@ -250,3 +272,22 @@ impl AgentLink { self.status.problem = Some(problem); } } + +/// The token in `token_file`, created when missing. A regular file the check refuses (one an +/// older app wrote with its folder's access list on Windows, open to Administrators, or a damaged +/// token) is replaced with a new token, once: the token is only this link's secret, and a client +/// reads the new one from the file. Kept, its refusal would keep agents out until someone deleted +/// the file. Anything else in the way (a folder, a link) is reported, not removed. +fn fresh_token(token_file: &Path) -> Result { + let read = || security::server_token(None, Some(token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string())); + let problem = match read() { + Ok(token) => return Ok(token), + Err(problem) => problem, + }; + if !std::fs::symlink_metadata(token_file).is_ok_and(|meta| meta.is_file()) { + return Err(problem); + } + log::warn!("{problem}; writing a new token file"); + std::fs::remove_file(token_file).map_err(|e| LinkProblem::TokenFile(format!("{}: {e}", token_file.display())))?; + read() +} diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index 7ca7bb5f0..81b2fe5bc 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -308,6 +308,74 @@ fn a_token_file_that_cannot_be_written_keeps_agents_out() { TcpListener::bind(("127.0.0.1", port)).expect("the port was let go"); } +/// A refused token file is not tried again with the same settings: a retry can't succeed until someone changes the +/// file, and on Windows each check starts `whoami` and PowerShell on the UI thread, about 300 ms, which a retry every +/// few seconds turned into a stall that often (photocraft#17006). Changing the settings tries again. +#[trial] +fn a_refused_token_file_is_not_retried_until_the_settings_change() { + let dir = temp_dir("link-token-no-retry"); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let wanted = free_port(); + assert!(link.sync(Some(&on(u32::from(wanted))), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + + // The file is fixed, but the same settings don't look at it again. + std::fs::remove_dir(dir.path().join(TOKEN_FILE)).unwrap(); + let same = link.sync(Some(&on(u32::from(wanted))), &host); + assert!(same.requests.is_none() && !same.changed, "no retry with the same settings"); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + + let changed = link.sync(Some(&on(0)), &host); + assert!(changed.requests.is_some(), "a settings change tries again"); + assert_eq!(link.status().problem, None); +} + +/// A token file the check refuses as it is (here a damaged token; on Windows also one an older app wrote with its +/// folder's access list, open to Administrators) is the link's own: it is replaced with a new token, so agents can +/// connect instead of staying out until someone deletes the file (photocraft#17006). +#[trial] +fn a_refused_token_file_is_replaced_with_a_new_token() { + let dir = temp_dir("link-token-refresh"); + let file = dir.path().join(TOKEN_FILE); + std::fs::write(&file, "not a token\n").unwrap(); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x"); + assert!(link.sync(Some(&on(0)), &host).requests.is_some(), "{:?}", link.status()); + assert_eq!(link.status().problem, None); + let token = std::fs::read_to_string(&file).unwrap(); + assert_ne!(token.trim(), "not a token"); + assert_eq!(token.trim().len(), 64, "a new token: {token:?}"); + assert_eq!(read_connection(dir.path()).unwrap().expect("published").port, link.status().port.expect("listening")); +} + +/// A retry of a taken port reuses the token its first try checked instead of reading the token file again (on Windows +/// that check is about 300 ms on the UI thread, photocraft#17006); a start that succeeded reads it afresh next time. +#[trial] +fn a_taken_port_retry_reuses_the_checked_token() { + let dir = temp_dir("link-token-reuse"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = u32::from(taken.local_addr().unwrap().port()); + assert!(link.sync(Some(&on(port)), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status()); + + // Reading the file now fails, so a retry that read it would report a token file problem. + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + drop(taken); + let retried = link.sync(Some(&on(port)), &host); + assert!(retried.requests.is_some(), "{:?}", link.status()); + assert_eq!(link.status().problem, None); + + // Once a start succeeded, the next one reads the file again. + let moved = link.sync(Some(&on(0)), &host); + assert!(moved.requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); +} + /// Dropping the link stops its server and removes its connection file. #[trial] fn dropping_the_link_removes_its_connection_file() {