From 5f394f64fc847d36f224c16dab0ffa241020ccf6 Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 27 Oct 2026 18:19:02 -0400 Subject: [PATCH] feat(process-daemon): support a private Unix socket directory (#59697) Co-authored-by: CBEPX <458940+CBEPX@users.noreply.github.com> --- packages/process-daemon/README.md | 9 +- packages/process-daemon/src/daemon/sweep.rs | 24 ++- packages/process-daemon/src/daemon/unix.rs | 142 ++++++++++++++++-- packages/process-daemon/src/daemon/windows.rs | 5 +- 4 files changed, 153 insertions(+), 27 deletions(-) diff --git a/packages/process-daemon/README.md b/packages/process-daemon/README.md index b7ee19c3aab..92225394983 100644 --- a/packages/process-daemon/README.md +++ b/packages/process-daemon/README.md @@ -44,11 +44,18 @@ directory, `${XDG_STATE_HOME:-~/.local/state}/opencode/pty`. Names are a single path component of letters, digits, `.`, `_`, or `-`. The registration (`service.json`) and lock (`service.lock`) live in that directory. They only default to a temporary directory when no home directory exists, because macOS deletes unaccessed regular files -there after three days. The socket stays under `/tmp/opencode-pty-/` to fit +there after three days. The socket defaults to `/tmp/opencode-pty-/` to fit socket path limits; temporary cleaners skip sockets. A stopping daemon removes its own files and runtime directory, and a starting daemon removes abandoned sibling runtime directories older than ten minutes. +On Unix, set `OPENCODE_PTY_SOCKET_DIR` to use a different socket directory. The +value must be an absolute path without `..` components. Sockets go in an +`opencode-pty-` child of that directory, which gets the existing ownership +and symlink checks and mode `0700`; the directory itself is left unchanged. +Socket path length limits still apply. Registration and lock files continue to +use the runtime directory. + ### Local transport boundary `src/transport/` owns endpoint listening/connecting, byte-stream I/O, diff --git a/packages/process-daemon/src/daemon/sweep.rs b/packages/process-daemon/src/daemon/sweep.rs index 653c6ab266a..e922f02f719 100644 --- a/packages/process-daemon/src/daemon/sweep.rs +++ b/packages/process-daemon/src/daemon/sweep.rs @@ -76,22 +76,20 @@ pub(super) fn runtime(directory: &Path, now: SystemTime) -> Result<()> { } Some(lock) } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - let Some(registration) = fs::read(registration_path(directory)) - .ok() - .and_then(|data| serde_json::from_slice::(&data).ok()) - else { - return Ok(()); - }; - if platform::process_exists(registration.pid) { - return Ok(()); - } - None - } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, Err(error) => return Err(error.into()), }; + let registration = fs::read(registration_path(directory)) + .ok() + .and_then(|data| serde_json::from_slice::(&data).ok()); + if lock.is_none() { + match ®istration { + Some(registration) if !platform::process_exists(registration.pid) => {} + _ => return Ok(()), + } + } - platform::remove_stale_endpoint(&fs::canonicalize(directory)?)?; + platform::remove_stale_endpoint(&fs::canonicalize(directory)?, registration.as_ref())?; // Remove the lock last so a racing daemon cannot claim a half-removed directory. files.sort_by_key(|file| file.ends_with(LOCK_FILE)); for file in files { diff --git a/packages/process-daemon/src/daemon/unix.rs b/packages/process-daemon/src/daemon/unix.rs index 30e2a0c5cbf..78e9c857689 100644 --- a/packages/process-daemon/src/daemon/unix.rs +++ b/packages/process-daemon/src/daemon/unix.rs @@ -2,10 +2,10 @@ use std::fs::{self, File, OpenOptions}; use std::io::Write; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}; -use std::path::{Path, PathBuf}; +use std::path::{Component, Path, PathBuf}; use std::thread::{self, JoinHandle}; -use anyhow::{Context, Result, anyhow}; +use anyhow::{Context, Result, anyhow, bail}; use fs2::FileExt; use sha2::{Digest, Sha256}; @@ -135,9 +135,20 @@ pub(super) fn process_exists(pid: u32) -> bool { } /// Removes the socket of an abandoned runtime found by the shared sweep. -pub(super) fn remove_stale_endpoint(canonical_directory: &Path) -> Result<()> { - let socket = socket_file(&socket_root(), canonical_directory); - if fs::symlink_metadata(&socket).is_ok_and(|metadata| metadata.file_type().is_socket()) { +pub(super) fn remove_stale_endpoint( + canonical_directory: &Path, + registration: Option<&Registration>, +) -> Result<()> { + // The abandoned daemon may have used a different OPENCODE_PTY_SOCKET_DIR, so + // prefer the socket it registered over this daemon's socket root. + let socket = match registration { + Some(registration) => registration.socket.clone(), + None => socket_file(&socket_root()?, canonical_directory), + }; + let uid = nix::unistd::Uid::effective().as_raw(); + if fs::symlink_metadata(&socket) + .is_ok_and(|metadata| metadata.file_type().is_socket() && metadata.uid() == uid) + { fs::remove_file(&socket)?; } Ok(()) @@ -146,17 +157,37 @@ pub(super) fn remove_stale_endpoint(canonical_directory: &Path) -> Result<()> { fn socket_path(directory: &Path) -> Result { let directory = fs::canonicalize(directory).context("failed to resolve PTY runtime directory")?; - let root = socket_root(); + let root = socket_root()?; ensure_private_directory(&root)?; Ok(socket_file(&root, &directory)) } -// Sockets stay in /tmp so their paths fit sun_path; temp cleaners skip sockets. -fn socket_root() -> PathBuf { - PathBuf::from("/tmp").join(format!( - "opencode-pty-{}", - nix::unistd::Uid::effective().as_raw() - )) +// The default path stays short enough for sun_path; temp cleaners skip sockets. +fn socket_root() -> Result { + resolve_socket_root( + std::env::var_os("OPENCODE_PTY_SOCKET_DIR").map(PathBuf::from), + nix::unistd::Uid::effective().as_raw(), + ) +} + +fn resolve_socket_root(directory: Option, uid: u32) -> Result { + let base = match directory { + None => PathBuf::from("/tmp"), + Some(directory) if !directory.is_absolute() => { + bail!("OPENCODE_PTY_SOCKET_DIR must be an absolute path") + } + Some(directory) + if directory + .components() + .any(|part| part == Component::ParentDir) => + { + bail!("OPENCODE_PTY_SOCKET_DIR must not contain '..'") + } + Some(directory) => directory, + }; + // Sockets live in a dedicated child so the 0700 permission change never + // applies to a caller-chosen directory. + Ok(base.join(format!("opencode-pty-{uid}"))) } fn socket_file(root: &Path, canonical_directory: &Path) -> PathBuf { @@ -222,6 +253,62 @@ mod tests { use super::*; + #[test] + fn socket_root_preserves_default_uid_directory() { + assert_eq!( + resolve_socket_root(None, 12345).unwrap(), + PathBuf::from("/tmp/opencode-pty-12345") + ); + } + + #[test] + fn socket_root_uses_dedicated_child_of_explicit_directory() { + assert_eq!( + resolve_socket_root(Some(PathBuf::from("/private/tmp/task-owned-pty")), 12345).unwrap(), + PathBuf::from("/private/tmp/task-owned-pty/opencode-pty-12345") + ); + } + + #[test] + fn socket_root_rejects_relative_and_parent_overrides() { + for root in [ + "", + ".", + "..", + "relative", + "../socket", + "/tmp/..", + "/tmp/a/../b", + ] { + assert!(resolve_socket_root(Some(PathBuf::from(root)), 12345).is_err()); + } + } + + #[test] + fn socket_root_leaves_explicit_directory_permissions_alone() { + let base = std::env::temp_dir().join(format!("opencode-pty-root-test-{}", random_id())); + fs::create_dir_all(&base).unwrap(); + fs::set_permissions(&base, fs::Permissions::from_mode(0o755)).unwrap(); + + let root = resolve_socket_root(Some(base.clone()), 12345).unwrap(); + ensure_private_directory(&root).unwrap(); + + let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&base), 0o755); + assert_eq!(mode(&root), 0o700); + fs::remove_dir_all(base).unwrap(); + } + + #[test] + fn socket_root_rejects_symlinked_child() { + let base = std::env::temp_dir().join(format!("opencode-pty-root-test-{}", random_id())); + fs::create_dir_all(base.join("target")).unwrap(); + let root = resolve_socket_root(Some(base.clone()), 12345).unwrap(); + std::os::unix::fs::symlink(base.join("target"), &root).unwrap(); + assert!(ensure_private_directory(&root).is_err()); + fs::remove_dir_all(base).unwrap(); + } + #[test] fn socket_paths_are_short_and_runtime_specific() { let base = std::env::temp_dir().join(format!("opencode-pty-socket-test-{}", random_id())); @@ -258,4 +345,35 @@ mod tests { assert!(!socket.exists()); fs::remove_dir_all(root).unwrap(); } + + #[test] + fn sweep_removes_socket_recorded_in_registration() { + let root = std::env::temp_dir().join(format!("opencode-pty-sweep-test-{}", random_id())); + let abandoned = root.join(random_id()); + fs::create_dir_all(&abandoned).unwrap(); + fs::write(abandoned.join(LOCK_FILE), b"").unwrap(); + // macOS temp directories are too long for sun_path. + let socket = PathBuf::from(format!( + "/tmp/opencode-pty-test-{}.sock", + &random_id()[..16] + )); + drop(UnixListener::bind(&socket).unwrap()); + let registration = Registration { + instance_id: random_id(), + pid: std::process::id(), + protocol: PROTOCOL_VERSION, + socket: socket.clone(), + token: random_id(), + }; + write_registration(&abandoned, ®istration).unwrap(); + + let later = std::time::SystemTime::now() + + super::super::sweep::STALE_RUNTIME_AGE + + std::time::Duration::from_secs(1); + super::super::sweep::runtime(&abandoned, later).unwrap(); + + assert!(!abandoned.exists()); + assert!(!socket.exists()); + fs::remove_dir_all(root).unwrap(); + } } diff --git a/packages/process-daemon/src/daemon/windows.rs b/packages/process-daemon/src/daemon/windows.rs index 7bce7d9ccf1..0e2eb72d234 100644 --- a/packages/process-daemon/src/daemon/windows.rs +++ b/packages/process-daemon/src/daemon/windows.rs @@ -185,7 +185,10 @@ pub(super) fn process_exists(pid: u32) -> bool { } /// Named pipes vanish with their server process; there is no endpoint to remove. -pub(super) fn remove_stale_endpoint(_canonical_directory: &Path) -> Result<()> { +pub(super) fn remove_stale_endpoint( + _canonical_directory: &Path, + _registration: Option<&Registration>, +) -> Result<()> { Ok(()) }