SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Control: name the token file and spot a stale one when a call is unauthorized (#4664) (#4670)
raykholo0520910bfd4f
diff --git a/apps/solidcraft-cli/src/bench_assistant.rs b/apps/solidcraft-cli/src/bench_assistant.rsindex d6f0740b93..9ec3b1b316 100644--- a/apps/solidcraft-cli/src/bench_assistant.rs+++ b/apps/solidcraft-cli/src/bench_assistant.rs@@ -69,6 +69,7 @@ impl Control {return Err("--connect requires a loopback address and a nonzero port (the app listens on 127.0.0.1)".into());}let token = solidcraft_engine::control_auth::client_token(addr.port(), token)+ .map(|t| t.token).ok_or("no control token: pass --token, set SOLIDCRAFT_CONTROL_TOKEN, or run on the app's computer (its token file)")?;if token.len() > 4096 {return Err("the control token is longer than 4096 bytes".into());diff --git a/apps/solidcraft/src/control_server.rs b/apps/solidcraft/src/control_server.rsindex ea4a65d4dc..3cb96e3326 100644--- a/apps/solidcraft/src/control_server.rs+++ b/apps/solidcraft/src/control_server.rs@@ -35,7 +35,7 @@ fn new_token() -> Option<String> {pub fn remove_token_file() {if let Ok(files) = TOKEN_FILES.lock() {for p in files.iter() {- let _ = std::fs::remove_file(p);+ control_auth::remove_token_file(p);}}if let Some(port) = APP_PORT.lock().ok().and_then(|p| *p) {diff --git a/crates/engine/src/control_auth.rs b/crates/engine/src/control_auth.rsindex b6162e9059..125fca8eda 100644--- a/crates/engine/src/control_auth.rs+++ b/crates/engine/src/control_auth.rs@@ -2,10 +2,12 @@//! makes a random token, writes it to a file only the user can read//! ([`token_path`]) and refuses every connection whose first request doesn't carry it, so other//! users on the same machine (loopback is shared, on Windows across remote-desktop sessions too)-//! can't drive the app. Clients find it with [`client_token`].+//! can't drive the app. Clients find it with [`client_token`]. Next to it, `<port>.pid` names+//! the process that wrote it, so a client refused with a leftover token can say the file is stale.-use std::io::{Error, ErrorKind, Result, Write};+use std::io::{Error, ErrorKind, Read, Result, Write};use std::path::{Path, PathBuf};+use std::time::{SystemTime, UNIX_EPOCH};/// Shortest token accepted from `SOLIDCRAFT_CONTROL_TOKEN` (hex characters).pub const MIN_TOKEN_LEN: usize = 32;@@ -106,16 +108,151 @@ pub fn env_token() -> Option<String> {/// The token a client sends to the app on `port`: `explicit` (`--token`), else/// `SOLIDCRAFT_CONTROL_TOKEN`, else the app's token file.-pub fn client_token(port: u16, explicit: Option<&str>) -> Option<String> {+pub fn client_token(port: u16, explicit: Option<&str>) -> Option<ClientToken> {if let Some(t) = explicit.map(str::trim).filter(|t| !t.is_empty()) {- return Some(t.to_string());+ return Some(ClientToken { token: t.to_string(), file: None });}if let Some(t) = env_token() {- return Some(t);+ return Some(ClientToken { token: t, file: None });}// Read directly, not through `vfs`: the app's own file, outside any agent's folders.- let text = std::fs::read_to_string(token_path(port)?).ok().filter(|t| t.len() <= 4096)?;- Some(text.trim().to_string()).filter(|t| !t.is_empty())+ read_token_file(&token_path(port)?)+}++/// A client token and, when it came from a token file, where that file is.+pub struct ClientToken {+ pub token: String,+ pub file: Option<TokenSource>,+}++/// The token file a client read: its path, when it was written and the process that wrote it.+pub struct TokenSource {+ pub path: PathBuf,+ pub modified: Option<SystemTime>,+ /// From `<port>.pid`: the writer's process id and, on Linux, its start time.+ pub writer: Option<(u32, Option<u64>)>,+}++impl ClientToken {+ /// The app's `error`, and for a refused token read from a file, which file it was, when it+ /// was written and whether the instance that wrote it has exited. Never the token itself.+ pub fn explain_error(&self, error: &str) -> String {+ let Some(src) = &self.file else { return error.to_string() };+ if !error.starts_with("unauthorized") {+ return error.to_string();+ }+ let written = src+ .modified+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())+ .map(|t| crate::crash::utc(t.as_secs()))+ .unwrap_or_else(|| "at an unknown time".into());+ let age = src.modified.and_then(|t| t.elapsed().ok()).map(|d| format!(" ({} s ago)", d.as_secs())).unwrap_or_default();+ let path = src.path.display();+ match src.writer.filter(|(pid, start)| writer_exited(*pid, *start)) {+ Some((pid, _)) => format!(+ "{error}; stale token file from an instance that exited (process {pid}): {path}, written {written}{age}; delete that file or restart SolidCraft"+ ),+ None => format!("{error}; token from {path}, written {written}{age}; if SolidCraft was force-quit, restart it or delete that file"),+ }+ }+}++/// Files bigger than this are not token files.+const MAX_TOKEN_FILE: u64 = 4096;++fn read_token_file(path: &Path) -> Option<ClientToken> {+ let f = std::fs::File::open(path).ok()?;+ let modified = f.metadata().ok().and_then(|m| m.modified().ok());+ let mut text = String::new();+ f.take(MAX_TOKEN_FILE + 1).read_to_string(&mut text).ok()?;+ if text.len() as u64 > MAX_TOKEN_FILE {+ return None;+ }+ let token = text.trim();+ if token.is_empty() {+ return None;+ }+ let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());+ let writer = read_pid_file(&pid_path(&path));+ Some(ClientToken { token: token.to_string(), file: Some(TokenSource { path, modified, writer }) })+}++/// The process file beside the token file `path`: `7878.token` → `7878.pid`.+pub fn pid_path(path: &Path) -> PathBuf {+ path.with_extension("pid")+}++/// `<pid> [<start time>]`; anything else (or no file) is no information.+fn read_pid_file(path: &Path) -> Option<(u32, Option<u64>)> {+ let mut text = String::new();+ std::fs::File::open(path).ok()?.take(256).read_to_string(&mut text).ok()?;+ let mut fields = text.split_whitespace();+ let pid = fields.next()?.parse::<u32>().ok().filter(|&pid| pid > 0)?;+ Some((pid, fields.next().and_then(|s| s.parse().ok())))+}++/// Whether the process that wrote a token file is known to be gone: not running, or its id now+/// belongs to a process that started at another time. Unknown counts as running.+fn writer_exited(pid: u32, start: Option<u64>) -> bool {+ process_running(pid) == Some(false) || start.zip(process_start(pid)).is_some_and(|(saved, now)| saved != now)+}++/// Whether process `pid` runs; `None` when that can't be found out.+fn process_running(pid: u32) -> Option<bool> {+ #[cfg(target_os = "linux")]+ {+ if !Path::new("/proc/self").exists() {+ return None;+ }+ match std::fs::metadata(format!("/proc/{pid}")) {+ Ok(_) => Some(true),+ Err(e) if e.kind() == ErrorKind::NotFound => Some(false),+ Err(_) => None,+ }+ }+ #[cfg(all(unix, not(target_os = "linux")))]+ {+ let output = std::process::Command::new("ps").args(["-p", &pid.to_string(), "-o", "pid="]).output().ok()?;+ if output.status.success() {+ return Some(true);+ }+ (output.status.code() == Some(1) && output.stdout.iter().all(u8::is_ascii_whitespace)).then_some(false)+ }+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ let output = std::process::Command::new("tasklist")+ .args(["/FI", &format!("PID eq {pid}"), "/FO", "CSV", "/NH"])+ .creation_flags(0x0800_0000)+ .output()+ .ok()?;+ if !output.status.success() || output.stdout.is_empty() {+ return None;+ }+ // `"image","pid",…` per process; with no match, a message line without a pid.+ let text = String::from_utf8_lossy(&output.stdout);+ Some(text.lines().any(|line| line.split("\",\"").nth(1).and_then(|s| s.trim_matches('"').parse::<u32>().ok()) == Some(pid)))+ }+ #[cfg(not(any(unix, windows)))]+ {+ let _ = pid;+ None+ }+}++/// Linux: the process's start time (clock ticks after boot), which tells a reused id apart.+fn process_start(pid: u32) -> Option<u64> {+ #[cfg(target_os = "linux")]+ {+ let mut stat = String::new();+ std::fs::File::open(format!("/proc/{pid}/stat")).ok()?.take(4096).read_to_string(&mut stat).ok()?;+ stat.rsplit_once(')')?.1.split_whitespace().nth(19)?.parse().ok()+ }+ #[cfg(not(target_os = "linux"))]+ {+ let _ = pid;+ None+ }}/// `a == b`, taking the same time wherever they differ.@@ -127,7 +264,7 @@ pub fn tokens_match(a: &str, b: &str) -> bool {/// Write `token` to `path`, readable and writable only by the user: the folder is made `0700`/// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one/// entry for the user (`icacls`) before the token goes in. A file left by an earlier launch is-/// replaced.+/// replaced. The process file beside it ([`pid_path`]) records this process, best effort.pub fn write_token_file(path: &Path, token: &str) -> Result<()> {let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?;std::fs::create_dir_all(dir)?;@@ -145,7 +282,17 @@ pub fn write_token_file(path: &Path, token: &str) -> Result<()> {restrict_to_user(path)?;f.write_all(token.as_bytes())?;f.write_all(b"\n")?;- f.sync_all()+ f.sync_all()?;+ let pid = std::process::id();+ let line = process_start(pid).map_or_else(|| format!("{pid}\n"), |start| format!("{pid} {start}\n"));+ let _ = std::fs::write(pid_path(path), line);+ Ok(())+}++/// Remove a token file this launch wrote, and its process file.+pub fn remove_token_file(path: &Path) {+ let _ = std::fs::remove_file(path);+ let _ = std::fs::remove_file(pid_path(path));}/// Windows: drop inherited entries and grant only the current user full access.@@ -170,7 +317,7 @@ pub struct TokenFile(pub PathBuf);impl Drop for TokenFile {fn drop(&mut self) {- let _ = std::fs::remove_file(&self.0);+ remove_token_file(&self.0);}}@@ -221,6 +368,66 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}+ /// A one-line token file (and one with no process file) still reads.+ #[test]+ fn a_token_file_reads_with_and_without_its_process_file() {+ let dir = std::env::temp_dir().join(format!("solidcraft-control-read-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("7879.token");+ std::fs::write(&path, "legacy-token\n").unwrap();+ let client = read_token_file(&path).unwrap();+ assert_eq!(client.token, "legacy-token");+ let src = client.file.as_ref().unwrap();+ assert_eq!(src.path, std::fs::canonicalize(&path).unwrap());+ assert!(src.modified.is_some() && src.writer.is_none());+ std::fs::write(pid_path(&path), "not a pid\n").unwrap();+ assert!(read_token_file(&path).unwrap().file.unwrap().writer.is_none());+ std::fs::write(&path, "x".repeat(4097)).unwrap();+ assert!(read_token_file(&path).is_none());+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A refused token names its file and when it was written, never the token.+ #[test]+ fn unauthorized_error_names_the_token_file() {+ let path = PathBuf::from("control/7878.token");+ let modified = Some(UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000));+ let client = ClientToken { token: "secret-token".into(), file: Some(TokenSource { path: path.clone(), modified, writer: None }) };+ let error = client.explain_error("unauthorized: send the control token");+ assert!(error.contains(&format!("token from {}, written 2023-11-14T22:13:20Z (", path.display())), "{error}");+ assert!(error.contains("restart it or delete that file") && !error.contains("secret-token"), "{error}");+ assert_eq!(client.explain_error("unknown method"), "unknown method");+ let explicit = client_token(0, Some("explicit-token")).unwrap();+ assert!(explicit.token == "explicit-token" && explicit.file.is_none());+ assert_eq!(explicit.explain_error("unauthorized"), "unauthorized");+ }++ /// A process file naming a process that has exited marks the token file stale.+ #[cfg(any(unix, windows))]+ #[test]+ fn a_token_file_from_an_exited_process_is_stale() {+ let mut child = std::process::Command::new(std::env::current_exe().unwrap())+ .args(["--exact", "control_auth::tests::tokens_compare_whole"])+ .stdout(std::process::Stdio::null())+ .spawn()+ .unwrap();+ let pid = child.id();+ assert!(child.wait().unwrap().success());+ let source = |writer| Some(TokenSource { path: PathBuf::from("7878.token"), modified: None, writer });+ let stale = ClientToken { token: "secret-token".into(), file: source(Some((pid, None))) };+ let error = stale.explain_error("unauthorized");+ assert!(error.contains(&format!("stale token file from an instance that exited (process {pid}): 7878.token")), "{error}");+ assert!(!error.contains("secret-token"));+ let live = ClientToken { token: "t".into(), file: source(Some((std::process::id(), process_start(std::process::id())))) };+ assert!(!live.explain_error("unauthorized").contains("stale"));+ #[cfg(target_os = "linux")]+ {+ let reused = process_start(std::process::id()).map(|s| s + 1);+ let reused = ClientToken { token: "t".into(), file: source(Some((std::process::id(), reused))) };+ assert!(reused.explain_error("unauthorized").contains("stale token file"));+ }+ }+/// The token file is the user's alone, and a client reads it back.#[cfg(unix)]#[test]@@ -237,8 +444,10 @@ mod tests {assert_eq!(mode(&path), 0o600);assert_eq!(mode(path.parent().unwrap()), 0o700);assert_eq!(std::fs::read_to_string(&path).unwrap().trim(), "0123456789abcdef0123456789abcdef");+ let writer = read_token_file(&path).unwrap().file.unwrap().writer;+ assert_eq!(writer.map(|(pid, _)| pid), Some(std::process::id()));drop(TokenFile(path.clone()));- assert!(!path.exists());+ assert!(!path.exists() && !pid_path(&path).exists());let _ = std::fs::remove_dir_all(&dir);}}diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rsindex 1e168ca41a..e2e71cf0f6 100644--- a/crates/mcp/src/backend.rs+++ b/crates/mcp/src/backend.rs@@ -267,8 +267,9 @@ impl Remote {}let mut msg = json!({"id": id, "method": method, "params": params});// The token goes with every request (an app restarted mid-session has a new one).- if let Some(t) = solidcraft_engine::control_auth::client_token(self.port, self.explicit_token.as_deref()) {- msg["token"] = json!(t);+ let token = solidcraft_engine::control_auth::client_token(self.port, self.explicit_token.as_deref());+ if let Some(t) = &token {+ msg["token"] = json!(t.token);}msg.to_string()}@@ -422,7 +423,11 @@ impl Remote {self.settle_earlier()?;return self.call_once(method, params, false);}- outcome(&v)+ // A refused token: say which token file it came from (and whether it is stale).+ outcome(&v).map_err(|error| {+ solidcraft_engine::control_auth::client_token(self.port, self.explicit_token.as_deref())+ .map_or_else(|| error.clone(), |t| t.explain_error(&error))+ })}}diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 25dc503f90..63800ba8f2 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -44,7 +44,15 @@ launch and writes it, as one line of hex, to a file only the user can read:On Unix the folder is `0700` and the file `0600`; on Windows the file's inherited permissions arereplaced by a single entry for the user. `SOLIDCRAFT_CONTROL_DIR` moves the folder. The file isremoved when the app exits, and the next launch writes a new token. The token file's path is-printed to stderr at start-up.+printed to stderr at start-up. Beside it, `<port>.pid` holds the app's process id (and, on Linux,+its start time).++An app that is force-quit can't remove its files, so a later client may send that launch's token.+When the app refuses it, `solidcraft-cli mcp` names the token file it read and when it was+written, and says the file is stale when the process in `<port>.pid` has exited. Delete the file+or restart SolidCraft. On Windows, an app or client started from inside an MSIX-packaged app (and+the tools it launches) has its AppData redirected: it writes and reads+`%LOCALAPPDATA%\Packages\<package>\LocalCache\Local\SolidCraft\control\` before the folder above.The first request on a connection must carry the token as a top-level `"token"` member(`{"id": 1, "method": "ui.inspect", "params": {}, "token": "…"}`); later requests on the same