|
|
|
@@ -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);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|