From ffab6ba030b65ae620faf80896efc6ce05eecc83 Mon Sep 17 00:00:00 2001 From: Willow Sparks Date: Thu, 5 Nov 2026 00:14:11 +0000 Subject: [PATCH] fix(daemon): keep tests off the product daemon socket A too-deep TMPDIR fell back to /tmp/prime-agent-rust-, the product default, so a test sandbox with a long worker path could bind or connect to the user's live daemon. differential_cli's TS corpus includes `shutdown --force`, which then stopped the live session. Namespace the rejected TMPDIR into a hashed /tmp fallback so distinct deep roots no longer alias the product socket. The daemon, the installed launcher, the npm bridge, and their parity fixtures all reserve the same longest-worker endpoint and hash the same TMPDIR, so every path resolves to the same directory on Linux and macOS. Require PA_TS_BINARY to exist before running the differential corpus, and scrub inherited agent and daemon environment from its fixtures. A missing reference binary now skips instead of running the corpus against ambient state. The path tests pin the hashed fallback and its separation from the default. --- crates/pa-cli/tests/differential_cli.rs | 47 +++++++++++-------- crates/pa-cli/tests/lock_compat_e2e.rs | 3 +- crates/pa-cli/tests/package_e2e.rs | 3 +- crates/pa-daemon/src/platform/paths.rs | 56 ++++++++++++++++++----- install-rust.sh | 33 +++++++++---- scripts/release/npm_bridge_assets/cli.cjs | 17 ++++--- scripts/release/test_npm_bridge.py | 35 ++++++++------ scripts/review_socket_pin_parity.py | 6 ++- 8 files changed, 137 insertions(+), 63 deletions(-) diff --git a/crates/pa-cli/tests/differential_cli.rs b/crates/pa-cli/tests/differential_cli.rs index 5164cb8f4..e6d276537 100644 --- a/crates/pa-cli/tests/differential_cli.rs +++ b/crates/pa-cli/tests/differential_cli.rs @@ -306,7 +306,8 @@ const CORPUS: &[&[&str]] = &[ fn ts_binary() -> Option { if let Ok(path) = std::env::var("PA_TS_BINARY") { - return Some(PathBuf::from(path)); + let path = PathBuf::from(path); + return path.exists().then_some(path); } let found = Command::new("which") .arg("prime-agent") @@ -323,11 +324,16 @@ struct InvocationOutput { stderr: String, } -fn run(binary: &Path, args: &[&str], sandbox: &Path) -> InvocationOutput { - let output = Command::new("timeout") - .arg("20") - .arg(binary) - .args(args) +fn isolate_child(command: &mut Command, sandbox: &Path) { + // A differential run may be launched from inside a live agent worker. + // Never let that worker's state dirs, daemon socket, or install identity + // leak into the fixture under comparison. + for (key, _) in std::env::vars_os() { + if key.to_string_lossy().starts_with("PRIME_AGENT_INTERNAL_") { + command.env_remove(key); + } + } + command .env("HOME", sandbox.join("home")) // Isolate the agent state dir: the TS binary resolves the real home // through passwd rather than $HOME, so the env override is the only @@ -338,9 +344,21 @@ fn run(binary: &Path, args: &[&str], sandbox: &Path) -> InvocationOutput { // `shutdown --force` kills unrelated sockets (containment contract). .env("TMPDIR", sandbox.join("tmp")) .env("PI_OFFLINE", "1") - .current_dir(sandbox.join("cwd")) - .output() - .expect("failed to spawn binary under test"); + .env_remove("PRIME_AGENT_AGENT_DIR") + .env_remove("PRIME_AGENT_CODING_AGENT_SESSION_DIR") + .env_remove("PRIME_AGENT_DAEMON_SOCKET") + .env_remove("PRIME_AGENT_INSTALL_MANAGED_BY") + .env_remove("PRIME_AGENT_KERNEL_OWNER_PID") + .env_remove("PRIME_AGENT_PLUGIN_SESSION_ID") + .env_remove("PRIME_AGENT_SESSION_DIR") + .current_dir(sandbox.join("cwd")); +} + +fn run(binary: &Path, args: &[&str], sandbox: &Path) -> InvocationOutput { + let mut command = Command::new("timeout"); + command.arg("20").arg(binary).args(args); + isolate_child(&mut command, sandbox); + let output = command.output().expect("failed to spawn binary under test"); InvocationOutput { exit_code: output.status.code(), stdout: String::from_utf8_lossy(&output.stdout).into_owned(), @@ -658,15 +676,8 @@ fn run_with_env( envs: &[(&str, &str)], ) -> InvocationOutput { let mut command = Command::new("timeout"); - command - .arg("20") - .arg(binary) - .args(args) - .env("HOME", sandbox.join("home")) - .env("TMPDIR", sandbox.join("tmp")) - .env("PRIME_AGENT_CODING_AGENT_DIR", sandbox.join("agent")) - .env("PI_OFFLINE", "1") - .current_dir(sandbox.join("cwd")); + command.arg("20").arg(binary).args(args); + isolate_child(&mut command, sandbox); for (key, value) in envs { command.env(key, value); } diff --git a/crates/pa-cli/tests/lock_compat_e2e.rs b/crates/pa-cli/tests/lock_compat_e2e.rs index e6d2e87ce..1ea39c53c 100644 --- a/crates/pa-cli/tests/lock_compat_e2e.rs +++ b/crates/pa-cli/tests/lock_compat_e2e.rs @@ -28,7 +28,8 @@ use pa_core::platform::LockDir; /// (`PA_TS_BINARY` or `prime-agent` on PATH; skipped when absent). fn ts_binary() -> Option { if let Ok(path) = std::env::var("PA_TS_BINARY") { - return Some(PathBuf::from(path)); + let path = PathBuf::from(path); + return path.exists().then_some(path); } let found = Command::new("which") .arg("prime-agent") diff --git a/crates/pa-cli/tests/package_e2e.rs b/crates/pa-cli/tests/package_e2e.rs index 319cb9352..a21ff32e0 100644 --- a/crates/pa-cli/tests/package_e2e.rs +++ b/crates/pa-cli/tests/package_e2e.rs @@ -443,7 +443,8 @@ fn normalize_keeps_git_fetch_ranges_for_all_hash_shapes() { fn ts_binary() -> Option { if let Ok(path) = std::env::var("PA_TS_BINARY") { - return Some(PathBuf::from(path)); + let path = PathBuf::from(path); + return path.exists().then_some(path); } let found = Command::new("which") .arg("prime-agent") diff --git a/crates/pa-daemon/src/platform/paths.rs b/crates/pa-daemon/src/platform/paths.rs index 14866900c..c53c9c608 100644 --- a/crates/pa-daemon/src/platform/paths.rs +++ b/crates/pa-daemon/src/platform/paths.rs @@ -1,6 +1,8 @@ //! Per-OS Rust daemon endpoint naming: Unix socket files under -//! `/prime-agent-rust-/`; Windows named pipes in the `\\.\\pipe\\` -//! namespace. Rust defaults stay separate from the TypeScript runtime. +//! `/prime-agent-rust-/`; a too-deep tmpdir falls back to a +//! hashed name under `/tmp` so it cannot alias the product default. Windows +//! named pipes live in the `\\.\\pipe\\` namespace. Rust defaults stay +//! separate from the TypeScript runtime. use std::path::{Path, PathBuf}; use crate::paths::hash_key; @@ -21,14 +23,19 @@ pub fn socket_dir() -> PathBuf { fn socket_dir_for(tmp: &Path, uid: u32) -> PathBuf { let name = format!("prime-agent-rust-{uid}"); let dir = tmp.join(&name); - if std::os::unix::net::SocketAddr::from_pathname( - dir.join("worker-000000000000-000000000000.sock"), - ) - .is_err() - { - return Path::new("/tmp").join(name); + // Reserve the longest generated endpoint. The byte cap is the portable + // non-Linux sun_path ceiling, and the installer and npm bridge use the + // same 103-byte probe so every launcher resolves the same directory. + let probe = dir.join("worker-000000000000-000000000000.sock"); + if probe.as_os_str().as_encoded_bytes().len() <= 103 { + return dir; } - dir + // A deep TMPDIR must not alias the product default: that path is the + // live daemon for every process whose TMPDIR is short, so a test (or a + // relocated install) with a long TMPDIR would bind or connect to it. + // Keep the fallback under /tmp but namespace it by the rejected root. + let suffix = hash_key(&tmp.to_string_lossy(), 12); + Path::new("/tmp").join(format!("{name}-{suffix}")) } /// The socket-dir half of a discovery state root on Windows. Keep Rust @@ -121,7 +128,14 @@ mod tests { let worker = dir.join("worker-000000000000-000000000000.sock"); assert!(SocketAddr::from_pathname(&worker).is_ok()); if length >= 65 { - assert_eq!(dir, Path::new("/tmp/prime-agent-rust-501")); + assert_eq!( + dir, + Path::new("/tmp").join(format!( + "prime-agent-rust-501-{}", + hash_key(&tmp.to_string_lossy(), 12) + )) + ); + assert_ne!(dir, Path::new("/tmp/prime-agent-rust-501")); } else { assert_eq!(dir, tmp.join("prime-agent-rust-501")); } @@ -134,13 +148,31 @@ mod tests { #[cfg(target_os = "linux")] #[test] fn deep_tmpdir_yields_to_a_connectable_directory() { + use std::os::unix::net::SocketAddr; + let tmp = PathBuf::from(format!("/{}", "d".repeat(120))); + let dir = socket_dir_for(&tmp, 501); assert_eq!( - socket_dir_for(&tmp, 501), - Path::new("/tmp/prime-agent-rust-501") + dir, + Path::new("/tmp").join(format!( + "prime-agent-rust-501-{}", + hash_key(&tmp.to_string_lossy(), 12) + )) + ); + assert_ne!(dir, Path::new("/tmp/prime-agent-rust-501")); + assert!( + SocketAddr::from_pathname(dir.join("worker-000000000000-000000000000.sock")).is_ok() ); } + #[cfg(unix)] + #[test] + fn deep_tmpdirs_get_distinct_socket_directories() { + let first = PathBuf::from(format!("/{}", "a".repeat(120))); + let second = PathBuf::from(format!("/{}", "b".repeat(120))); + assert_ne!(socket_dir_for(&first, 501), socket_dir_for(&second, 501)); + } + #[cfg(unix)] #[test] fn short_tmpdir_keeps_the_rust_socket_directory() { diff --git a/install-rust.sh b/install-rust.sh index edf6712e9..26b6438d0 100755 --- a/install-rust.sh +++ b/install-rust.sh @@ -90,7 +90,8 @@ # the product binary/package — the user can remove it by hand). # 3. WHY DAEMON CONFLICTS ARE GONE AFTER THIS INSTALL: the launcher # pins a rust-only daemon socket -# (${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/daemon.sock) — a +# (${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/daemon.sock, or a +# hashed /tmp fallback for a deep TMPDIR) — a # different path than the TS daemon's own — so BY DEFAULT this CLI # and the TS daemon never meet (each product's default socket is its # own), and the install-time stop-when-idle above retires a TS daemon @@ -1606,11 +1607,17 @@ ts_stop_rust_stopped="" windows_stop_summary="" ts_socket="${TMPDIR:-/tmp}/prime-agent-$(id -u)/daemon.sock" rust_socket="${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/daemon.sock" -# The launcher pins /tmp when the TMPDIR path exceeds the non-Linux -# 103-byte sun_path limit (pa-daemon socket_dir() owns the rule); the -# stop probe must look where the launcher actually pinned. -if [ "$OS" != "Linux" ] && [ "$(printf '%s' "$rust_socket" | wc -c)" -gt 103 ]; then - rust_socket="/tmp/prime-agent-rust-$(id -u)/daemon.sock" +# The launcher pins a hashed /tmp directory when the longest generated +# worker endpoint exceeds the portable 103-byte sun_path limit; the stop +# probe must look where the launcher actually pinned. +rust_worker="${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/worker-000000000000-000000000000.sock" +if [ "$(printf '%s' "$rust_worker" | wc -c)" -gt 103 ]; then + rust_hash="$(if command -v sha256sum >/dev/null 2>&1; then + printf '%s' "${TMPDIR:-/tmp}" | sha256sum + else + printf '%s' "${TMPDIR:-/tmp}" | shasum -a 256 + fi | cut -c1-12)" + rust_socket="/tmp/prime-agent-rust-$(id -u)-${rust_hash}/daemon.sock" fi env_socket="${PRIME_AGENT_DAEMON_SOCKET:-}" # THE TILDE EXPANSION (the CLI's own spelling: the products' clients @@ -2854,11 +2861,17 @@ if [ -f "$(dirname "$0")/../share/.prime-agent-npm-bridge/legacy-daemon-socket" export PRIME_AGENT_DAEMON_SOCKET="${PRIME_AGENT_DAEMON_SOCKET:-${TMPDIR:-${TMP:-${TEMP:-/tmp}}}/prime-agent-$(id -u)/daemon.sock}" else if [ -z "${PRIME_AGENT_DAEMON_SOCKET:-}" ]; then - # Same rule as pa-daemon socket_dir(): non-Linux sun_path caps a unix - # socket at 103 bytes, so a too-deep TMPDIR pins /tmp/prime-agent-rust-. + # A deep TMPDIR gets a hashed rust-only directory under /tmp, matching + # pa-daemon socket_dir(); never the product default. PRIME_AGENT_DAEMON_SOCKET="${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/daemon.sock" - if [ "$(printf '%s' "$PRIME_AGENT_DAEMON_SOCKET" | wc -c)" -gt 103 ] && [ "$(uname -s)" != "Linux" ]; then - PRIME_AGENT_DAEMON_SOCKET="/tmp/prime-agent-rust-$(id -u)/daemon.sock" + launcher_worker="${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/worker-000000000000-000000000000.sock" + if [ "$(printf '%s' "$launcher_worker" | wc -c)" -gt 103 ]; then + launcher_hash="$(if command -v sha256sum >/dev/null 2>&1; then + printf '%s' "${TMPDIR:-/tmp}" | sha256sum + else + printf '%s' "${TMPDIR:-/tmp}" | shasum -a 256 + fi | cut -c1-12)" + PRIME_AGENT_DAEMON_SOCKET="/tmp/prime-agent-rust-$(id -u)-${launcher_hash}/daemon.sock" fi export PRIME_AGENT_DAEMON_SOCKET fi diff --git a/scripts/release/npm_bridge_assets/cli.cjs b/scripts/release/npm_bridge_assets/cli.cjs index a89471a70..4b1c43750 100644 --- a/scripts/release/npm_bridge_assets/cli.cjs +++ b/scripts/release/npm_bridge_assets/cli.cjs @@ -4,7 +4,7 @@ // Ship this at dist/bundle/cli.js and cli-node.js: historical updaters relaunch // their original absolute entrypoint, including the later shim's Node fallback. const { spawn, spawnSync } = require("node:child_process"); -const { randomUUID } = require("node:crypto"); +const { createHash, randomUUID } = require("node:crypto"); const { pathToFileURL } = require("node:url"); const fs = require("node:fs"); const os = require("node:os"); @@ -47,11 +47,16 @@ const receipt = path.join(receiptDir, metadata.version); const failedReceipt = `${receipt}.failed`; const legacySocketMarker = path.join(receiptDir, "legacy-daemon-socket"); const legacySocket = path.join(os.tmpdir(), `prime-agent-${process.getuid()}`, "daemon.sock"); -const rustSocket = path.join(process.env.TMPDIR || "/tmp", `prime-agent-rust-${process.getuid()}`, "daemon.sock"); -// Same rule as pa-daemon socket_dir(): non-Linux sun_path caps a unix -// socket at 103 bytes, so a too-deep TMPDIR pins /tmp/prime-agent-rust-. -const pinnedRustSocket = process.platform !== "linux" && Buffer.byteLength(rustSocket) > 103 - ? path.join("/tmp", `prime-agent-rust-${process.getuid()}`, "daemon.sock") : rustSocket; +const rustTmp = process.env.TMPDIR || "/tmp"; +const rustSocket = path.join(rustTmp, `prime-agent-rust-${process.getuid()}`, "daemon.sock"); +// Match pa-daemon socket_dir(): reserve the longest worker endpoint. A deep +// TMPDIR gets a hashed rust-only directory under /tmp, never the product default. +const rustWorker = path.join(rustTmp, `prime-agent-rust-${process.getuid()}`, + "worker-000000000000-000000000000.sock"); +const rustSocketHash = createHash("sha256").update(rustTmp).digest("hex").slice(0, 12); +const pinnedRustSocket = Buffer.byteLength(rustWorker) > 103 + ? path.join("/tmp", `prime-agent-rust-${process.getuid()}-${rustSocketHash}`, "daemon.sock") + : rustSocket; const nativeEnvironment = { ...process.env, PRIME_AGENT_CODING_AGENT_DIR: process.env.PRIME_AGENT_CODING_AGENT_DIR || path.join(os.homedir(), ".prime/agent"), PRIME_AGENT_DAEMON_SOCKET: process.env.PRIME_AGENT_DAEMON_SOCKET || diff --git a/scripts/release/test_npm_bridge.py b/scripts/release/test_npm_bridge.py index af47dfa6e..cb7baff3d 100644 --- a/scripts/release/test_npm_bridge.py +++ b/scripts/release/test_npm_bridge.py @@ -21,6 +21,17 @@ from unittest.mock import patch import npm_bridge from npm_bridge import assemble +def rust_socket(tmp, uid=None): + """Mirror pa-daemon socket_dir(): reserve the longest worker endpoint.""" + uid = os.getuid() if uid is None else uid + tmp = str(tmp) + worker = f"{tmp}/prime-agent-rust-{uid}/worker-000000000000-000000000000.sock" + if len(worker.encode()) > 103: + suffix = hashlib.sha256(tmp.encode()).hexdigest()[:12] + return f"/tmp/prime-agent-rust-{uid}-{suffix}/daemon.sock" + return f"{tmp}/prime-agent-rust-{uid}/daemon.sock" + + @unittest.skipUnless(sys.platform in ("darwin", "linux") and shutil.which("node") and shutil.which("npm"), "requires Node and npm on a historical TypeScript platform") @@ -373,17 +384,18 @@ trap '[ -z "${launcher_tmp:-}" ] || rm -f "$launcher_tmp"' EXIT self.assertEqual(list(command.parent.glob(".prime-agent.*")), []) def test_real_launcher_pin_respects_the_sun_path_limit(self): - # The launcher pins the daemon socket env; a TMPDIR whose pin cannot - # fit the non-Linux 103-byte sun_path limit must pin /tmp instead - # (the same fallback pa-daemon socket_dir() gives the binary default). + # A TMPDIR whose longest worker endpoint cannot fit the portable + # 103-byte sun_path limit must pin a hashed /tmp directory, never the + # product default. The rule no longer varies by platform. command = self.npm_prefix / "bin/prime-agent" result = self.install_real_launcher() self.assertEqual(result.returncode, 0, result.stderr) - # The PATH shim makes both arms testable on every platform. shim_dir = self.root / "uname-shim" shim_dir.mkdir() long_tmp = self.root / ("t" * 80) - for system, root in (("Darwin", "/tmp"), ("Linux", str(long_tmp))): + expected = rust_socket(long_tmp) + self.assertTrue(expected.startswith("/tmp/prime-agent-rust-")) + for system in ("Darwin", "Linux"): with self.subTest(system=system): (shim_dir / "uname").write_text(f'#!/bin/sh\necho {system}\n') (shim_dir / "uname").chmod(0o755) @@ -393,8 +405,7 @@ trap '[ -z "${launcher_tmp:-}" ] || rm -f "$launcher_tmp"' EXIT probe = subprocess.run([str(command), "socket"], env=probe_env, text=True, capture_output=True, timeout=10) self.assertEqual(probe.returncode, 0, probe.stderr) - self.assertEqual(probe.stdout.strip(), - f"{root}/prime-agent-rust-{os.getuid()}/daemon.sock") + self.assertEqual(probe.stdout.strip(), expected) def test_utf8_socket_limit_applies_to_launcher_and_stop_probe(self): result = self.install_real_launcher() @@ -417,7 +428,7 @@ trap '[ -z "${launcher_tmp:-}" ] || rm -f "$launcher_tmp"' EXIT "LC_ALL": "en_US.UTF-8", "PATH": str(shim_dir) + os.pathsep + self.env["PATH"]} env.pop("PRIME_AGENT_DAEMON_SOCKET", None) - expected = f"/tmp/prime-agent-rust-{os.getuid()}/daemon.sock" if system == "Darwin" else pin + expected = rust_socket(tmp) for shell in ("sh", "bash"): with self.subTest(shell=shell): probe = subprocess.run([shell, str(command), "socket"], env=env, @@ -448,13 +459,11 @@ else console.log(JSON.stringify(process.argv.slice(2))); self.env["TMPDIR"] = str(self.root / "sockets") expected = str(self.root / "sockets" / f"prime-agent-rust-{os.getuid()}" / "daemon.sock") self.assertEqual(self.launch("socket").stdout.strip(), expected) - # A TMPDIR deeper than the non-Linux 103-byte sun_path limit pins - # /tmp instead (node's platform cannot be shimmed, so the expected - # value follows the host OS). + # A TMPDIR deeper than the portable 103-byte worker limit pins a + # hashed /tmp directory instead. long_tmp = str(self.root / ("t" * 80)) self.env["TMPDIR"] = long_tmp - expected = (f"/tmp/prime-agent-rust-{os.getuid()}/daemon.sock" if sys.platform == "darwin" - else f"{long_tmp}/prime-agent-rust-{os.getuid()}/daemon.sock") + expected = rust_socket(long_tmp) self.assertEqual(self.launch("socket").stdout.strip(), expected) def test_concurrent_first_launches_install_once(self): diff --git a/scripts/review_socket_pin_parity.py b/scripts/review_socket_pin_parity.py index d948fb8fc..18ca7040e 100644 --- a/scripts/review_socket_pin_parity.py +++ b/scripts/review_socket_pin_parity.py @@ -7,6 +7,7 @@ published launcher on Linux with the exact CI-built Rust payload. Both daemons run only in fixture-owned homes and socket paths. No installer downloads occur. """ import argparse +import hashlib import json import os from pathlib import Path @@ -77,7 +78,7 @@ def main(): args = parser.parse_args() receipt = {'passed': False, 'scenario': 'socket_pin', 'runs': {}, 'scope': 'Actual daemons: legacy namespace compatibility and explicit override; actual Rust launcher and installer stop probe: UTF-8 byte fallback under Darwin uname shim.', - 'intentional_difference': 'Unmarked Rust launcher uses rust-only namespace; non-Linux oversized pins fall back to /tmp. TS namespace and migration marker remain unchanged.'} + 'intentional_difference': 'Unmarked Rust launcher uses its own namespace; a deep TMPDIR with an oversized worker endpoint falls back to a hashed rust-only /tmp directory. TS namespace and migration marker remain unchanged.'} fallback_dir = None try: assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256 @@ -113,7 +114,8 @@ def main(): long_tmp = str(owned / ('é' * 25)) long_pin = f'{long_tmp}/prime-agent-rust-{fixture_uid}/daemon.sock' assert len(long_pin) <= 103 and len(long_pin.encode()) > 103, long_pin - candidate = Path(f'/tmp/prime-agent-rust-{fixture_uid}') + suffix = hashlib.sha256(long_tmp.encode()).hexdigest()[:12] + candidate = Path(f'/tmp/prime-agent-rust-{fixture_uid}-{suffix}') # Atomic reservation: a collision never authorizes cleanup. candidate.mkdir(mode=0o700, exist_ok=False) fallback_dir = candidate -- knotmirror 0.0.1