From f79550470f45b1a327f62957c20a785fc3dd30b8 Mon Sep 17 00:00:00 2001 From: johannayang-amd Date: Thu, 12 Nov 2026 12:22:11 +0100 Subject: [PATCH 1/3] fix(sandbox): recover the workspace tmpdir after a killed run AXIS creates {tmpdir} (/.axis-tmp) exclusively and removes it when the sandbox stops. A non-interactive `axis run` that gets SIGTERM, as a caller's timeout sends, ended without that cleanup, and so does one that gets SIGKILL. The tmpdir stayed, and every later run in that workspace failed with "cannot create exclusive tmpdir ... File exists" until someone removed it by hand. `axis run` now stops its sandbox on SIGTERM in every mode, as it already did on a terminal: the command is killed, the tmpdir removed, and AXIS exits 143. The handler is registered before the sandbox starts. Each Linux sandbox that uses {tmpdir} also holds an exclusive flock on its workspace directory from before the tmpdir is created until after it is removed. The kernel releases it when that AXIS process ends, however it ends. A run that gets the lock and still finds a tmpdir knows no live sandbox owns it, and removes it when it is a real directory owned by the uid the tmpdir is created for; a link or another owner's directory is left, and the exclusive create still refuses it. A run that does not get the lock fails as before: two sandboxes in one workspace still cannot share a tmpdir. Where flock is unsupported nothing is removed. Co-authored-by: Cursor --- crates/axis-cli/src/main.rs | 58 ++++++--- crates/axis-sandbox/src/linux/landlock.rs | 137 ++++++++++++++++++++++ crates/axis-sandbox/src/linux/mod.rs | 25 +++- crates/axis-sandbox/src/linux/mxc.rs | 24 +++- 4 files changed, 220 insertions(+), 24 deletions(-) diff --git a/crates/axis-cli/src/main.rs b/crates/axis-cli/src/main.rs index a7410bd7..cb8064d8 100644 --- a/crates/axis-cli/src/main.rs +++ b/crates/axis-cli/src/main.rs @@ -800,8 +800,12 @@ async fn run_command( eprintln!("AXIS: sandbox {id} running"); eprintln!("AXIS: press Ctrl+C to stop"); - // Wait for Ctrl+C, then destroy. - tokio::signal::ctrl_c().await.ok(); + // Wait for Ctrl+C or SIGTERM, then destroy. + let terminated = terminate_signal()?; + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + () = terminated => {} + } eprintln!("\nAXIS: shutting down sandbox {id}..."); let destroy_req = serde_json::json!({ @@ -901,6 +905,9 @@ async fn run_command( let mut sandbox = axis_sandbox::Sandbox::create(config).map_err(|e| anyhow::anyhow!("{e}"))?; + // Registered before the start, so a SIGTERM from then on stops + // the sandbox instead of ending AXIS without its cleanup. + let terminated = terminate_signal()?; sandbox.start().map_err(|e| anyhow::anyhow!("{e}"))?; if !quiet { @@ -915,14 +922,18 @@ async fn run_command( // Don't install a Ctrl+C handler, because it steals the // TTY from the child process and breaks TUI apps like // Claude Code (setRawMode fails). - let code = wait_for_interactive_standalone_sandbox(&mut sandbox).await?; + let code = + wait_for_interactive_standalone_sandbox(&mut sandbox, terminated).await?; sandbox.destroy().ok(); std::process::exit(code); } else { - // Non-interactive: wait for process or Ctrl+C. destroy() - // MUST run after the wait too: wait() only kills the local - // frontend (e.g. on timeout), so without an explicit - // destroy() the backend's VM/DomU would be orphaned. + // Non-interactive: wait for process, Ctrl+C or SIGTERM. + // destroy() MUST run after the wait too: wait() only kills + // the local frontend (e.g. on timeout), so without an + // explicit destroy() the backend's VM/DomU would be orphaned. + // A caller's timeout sends SIGTERM: destroy() then stops the + // command and removes the sandbox's tmpdir, which the next + // run in this workspace needs gone. tokio::select! { code = sandbox.wait() => { let code = code.map_err(|e| anyhow::anyhow!("{e}"))?; @@ -932,6 +943,10 @@ async fn run_command( _ = tokio::signal::ctrl_c() => { sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; } + () = terminated => { + sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; + std::process::exit(TERMINATED_EXIT_CODE); + } } } } @@ -984,25 +999,38 @@ fn resolve_policy_yaml(policy: &std::path::Path) -> anyhow::Result { Ok(yaml.to_string()) } -#[cfg(unix)] async fn wait_for_interactive_standalone_sandbox( sandbox: &mut axis_sandbox::Sandbox, + terminated: impl std::future::Future, ) -> Result { - let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; tokio::select! { code = sandbox.wait() => Ok(code.map_err(|e| anyhow::anyhow!("{e}"))?), - _ = terminate.recv() => { + () = terminated => { sandbox.destroy().map_err(|e| anyhow::anyhow!("{e}"))?; - Ok(128 + libc::SIGTERM) + Ok(TERMINATED_EXIT_CODE) } } } +/// The status `axis run` exits with when SIGTERM stopped its sandbox. +#[cfg(unix)] +const TERMINATED_EXIT_CODE: i32 = 128 + libc::SIGTERM; #[cfg(not(unix))] -async fn wait_for_interactive_standalone_sandbox( - sandbox: &mut axis_sandbox::Sandbox, -) -> Result { - sandbox.wait().await.map_err(|e| anyhow::anyhow!("{e}")) +const TERMINATED_EXIT_CODE: i32 = 1; + +/// Settles when this process gets SIGTERM, from the call on; never where +/// there is no SIGTERM. +#[cfg(unix)] +fn terminate_signal() -> Result> { + let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; + Ok(async move { + terminate.recv().await; + }) +} + +#[cfg(not(unix))] +fn terminate_signal() -> Result> { + Ok(std::future::pending()) } /// Git-style subcommand extension. diff --git a/crates/axis-sandbox/src/linux/landlock.rs b/crates/axis-sandbox/src/linux/landlock.rs index 2ae0de76..4017e816 100644 --- a/crates/axis-sandbox/src/linux/landlock.rs +++ b/crates/axis-sandbox/src/linux/landlock.rs @@ -247,6 +247,74 @@ pub(crate) fn policy_uses_tmpdir(policy: &FilesystemPolicy) -> bool { .any(|path| path.contains(TMPDIR_PLACEHOLDER)) } +/// One sandbox's hold on its workspace's `{tmpdir}`, from before the tmpdir +/// is created until after it is removed: an exclusive `flock` on the +/// workspace directory, which the kernel releases when the AXIS process that +/// holds it ends, however it ends. The descriptor is close-on-exec, so the +/// sandboxed command never holds it. +#[derive(Debug)] +pub(crate) struct TmpdirClaim { + _lock: Option, +} + +/// Takes the workspace's tmpdir for one sandbox. Another sandbox holding it +/// fails the launch. A tmpdir already there while this holds it was left by a +/// sandbox whose AXIS ended without removing it (killed), and every later +/// launch would fail on it, so it is removed when it is a directory, not a +/// link, owned by `owner`, the uid the sandbox's tmpdir is created for. +/// Anything else there is left, and the exclusive create still refuses it. +/// Where the workspace cannot be locked (`flock` unsupported), nothing is +/// removed. +pub(crate) fn claim_tmpdir(workspace: &Path, owner: libc::uid_t) -> Result { + use std::os::unix::io::AsRawFd; + + let tmpdir = sandbox_tmpdir(workspace); + let dir = std::fs::File::open(workspace).map_err(|e| { + format!( + "cannot open workspace {} to lock its tmpdir: {e}", + workspace.display() + ) + })?; + if unsafe { libc::flock(dir.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { + let error = std::io::Error::last_os_error(); + if error.raw_os_error() == Some(libc::EWOULDBLOCK) { + return Err(format!( + "cannot create exclusive tmpdir {}: another sandbox in this workspace holds it", + tmpdir.display() + )); + } + tracing::debug!( + "workspace {} cannot be locked ({error}); a tmpdir left there is not removed", + workspace.display() + ); + return Ok(TmpdirClaim { _lock: None }); + } + remove_stale_tmpdir(&tmpdir, owner); + Ok(TmpdirClaim { _lock: Some(dir) }) +} + +fn remove_stale_tmpdir(tmpdir: &Path, owner: libc::uid_t) { + use std::os::unix::fs::MetadataExt; + + let Ok(metadata) = std::fs::symlink_metadata(tmpdir) else { + return; + }; + if !metadata.file_type().is_dir() || metadata.uid() != owner { + tracing::warn!( + "tmpdir {} is not a directory owned by uid {owner}; it is not removed", + tmpdir.display() + ); + return; + } + match std::fs::remove_dir_all(tmpdir) { + Ok(()) => tracing::warn!( + "removed tmpdir {} left by a sandbox that did not stop cleanly", + tmpdir.display() + ), + Err(e) => tracing::warn!("cannot remove leftover tmpdir {}: {e}", tmpdir.display()), + } +} + pub(crate) fn create_tmpdir(workspace: &Path) -> Result<(), String> { let tmpdir = sandbox_tmpdir(workspace); let mut builder = std::fs::DirBuilder::new(); @@ -1740,6 +1808,75 @@ mod tests { assert!(err.contains("cannot create exclusive tmpdir")); } + #[test] + fn claim_tmpdir_removes_a_leftover_only_while_no_other_sandbox_holds_it() { + let dir = tempfile::tempdir().unwrap(); + let tmpdir = sandbox_tmpdir(dir.path()); + let owner = unsafe { libc::geteuid() }; + + let held = claim_tmpdir(dir.path(), owner).unwrap(); + create_tmpdir(dir.path()).unwrap(); + std::fs::write(tmpdir.join("scratch"), b"scratch").unwrap(); + let err = claim_tmpdir(dir.path(), owner).unwrap_err(); + assert!( + err.contains("another sandbox in this workspace holds it"), + "{err}" + ); + assert!(tmpdir.join("scratch").exists()); + + // The holder ended without removing it, as a killed AXIS does. + drop(held); + let _claim = claim_tmpdir(dir.path(), owner).unwrap(); + assert!(!tmpdir.exists()); + create_tmpdir(dir.path()).unwrap(); + } + + #[test] + fn claim_tmpdir_leaves_a_link_or_another_owners_directory_for_the_create_to_refuse() { + let dir = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("keep"), b"keep").unwrap(); + let tmpdir = sandbox_tmpdir(dir.path()); + let owner = unsafe { libc::geteuid() }; + + std::os::unix::fs::symlink(outside.path(), &tmpdir).unwrap(); + let claim = claim_tmpdir(dir.path(), owner).unwrap(); + assert!( + std::fs::symlink_metadata(&tmpdir) + .unwrap() + .file_type() + .is_symlink() + ); + assert!(outside.path().join("keep").exists()); + assert!( + create_tmpdir(dir.path()) + .unwrap_err() + .contains("cannot create exclusive tmpdir") + ); + drop(claim); + + std::fs::remove_file(&tmpdir).unwrap(); + std::fs::create_dir(&tmpdir).unwrap(); + let _claim = claim_tmpdir(dir.path(), owner.wrapping_add(1)).unwrap(); + assert!(tmpdir.is_dir()); + assert!( + create_tmpdir(dir.path()) + .unwrap_err() + .contains("cannot create exclusive tmpdir") + ); + } + + #[test] + fn claim_tmpdir_is_not_inherited_by_the_sandboxed_command() { + use std::os::unix::io::AsRawFd; + + let dir = tempfile::tempdir().unwrap(); + let claim = claim_tmpdir(dir.path(), unsafe { libc::geteuid() }).unwrap(); + let fd = claim._lock.as_ref().unwrap().as_raw_fd(); + let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; + assert_ne!(flags & libc::FD_CLOEXEC, 0); + } + #[test] fn policy_uses_tmpdir_detects_all_filesystem_sections() { for policy in [ diff --git a/crates/axis-sandbox/src/linux/mod.rs b/crates/axis-sandbox/src/linux/mod.rs index 3dcb890c..bc04be5b 100644 --- a/crates/axis-sandbox/src/linux/mod.rs +++ b/crates/axis-sandbox/src/linux/mod.rs @@ -366,6 +366,7 @@ pub(crate) struct LinuxSandbox { cgroup: Option, connect_supervisor: Option, tmpdir_active: bool, + tmpdir_claim: Option, } impl LinuxSandbox { @@ -393,6 +394,7 @@ impl LinuxSandbox { cgroup: None, connect_supervisor: None, tmpdir_active: false, + tmpdir_claim: None, }) } @@ -679,6 +681,7 @@ impl LinuxSandbox { let sandbox_id = self.config.id; let tmpdir_required = landlock::policy_uses_tmpdir(&self.config.policy.filesystem); if tmpdir_required { + self.claim_tmpdir(unsafe { libc::geteuid() })?; match landlock::create_tmpdir(&self.config.workspace_dir) { Ok(()) => self.tmpdir_active = true, Err(e) => return Err(SandboxError::IsolationFailed(e)), @@ -1204,12 +1207,19 @@ impl LinuxSandbox { self.cleanup_tmpdir().err() } + fn claim_tmpdir(&mut self, owner: libc::uid_t) -> Result<(), SandboxError> { + let claim = landlock::claim_tmpdir(&self.config.workspace_dir, owner) + .map_err(SandboxError::IsolationFailed)?; + self.tmpdir_claim = Some(claim); + Ok(()) + } + fn cleanup_tmpdir(&mut self) -> Result<(), String> { - if !self.tmpdir_active { - return Ok(()); + if self.tmpdir_active { + landlock::cleanup_tmpdir(&self.config.workspace_dir)?; + self.tmpdir_active = false; } - landlock::cleanup_tmpdir(&self.config.workspace_dir)?; - self.tmpdir_active = false; + self.tmpdir_claim = None; Ok(()) } @@ -1754,6 +1764,12 @@ impl SandboxImpl for LinuxSandbox { self.resolve_identity() })?; let tmpdir_required = landlock::policy_uses_tmpdir(&self.config.policy.filesystem); + if tmpdir_required { + let owner = resolved_identity + .as_ref() + .map_or_else(|| unsafe { libc::geteuid() }, |identity| identity.uid); + self.claim_tmpdir(owner)?; + } if let Some(identity) = &resolved_identity { if tmpdir_required { crate::sandbox::record_startup_result(&trace, "support_files.tmpdir", || { @@ -4153,6 +4169,7 @@ mod tests { cgroup: None, connect_supervisor: None, tmpdir_active: false, + tmpdir_claim: None, } } diff --git a/crates/axis-sandbox/src/linux/mxc.rs b/crates/axis-sandbox/src/linux/mxc.rs index b61e652b..a3e8a1d2 100644 --- a/crates/axis-sandbox/src/linux/mxc.rs +++ b/crates/axis-sandbox/src/linux/mxc.rs @@ -460,6 +460,7 @@ pub(crate) struct MxcLinuxSandbox { capture_output: bool, timeout_sec: Option, tmpdir_active: bool, + tmpdir_claim: Option, startup_trace: Option, } @@ -941,6 +942,17 @@ impl MxcLinuxSandbox { })?; let mut tmpdir_active = false; let tmpdir_required = super::landlock::policy_uses_tmpdir(&config.policy.filesystem); + let tmpdir_claim = if tmpdir_required { + let owner = resolved_identity + .as_ref() + .map_or_else(|| unsafe { libc::geteuid() }, |identity| identity.uid); + Some( + super::landlock::claim_tmpdir(&config.workspace_dir, owner) + .map_err(|err| SandboxError::IsolationFailed(format!("MXC tmpdir: {err}")))?, + ) + } else { + None + }; if let Some(identity) = &resolved_identity { if tmpdir_required { crate::sandbox::record_startup_result(&trace, "support_files.tmpdir", || { @@ -1079,6 +1091,7 @@ impl MxcLinuxSandbox { capture_output: config.capture_output, timeout_sec: config.timeout_sec, tmpdir_active, + tmpdir_claim, startup_trace: config.startup_trace.clone(), }) } @@ -1114,12 +1127,13 @@ impl MxcLinuxSandbox { } fn cleanup_tmpdir(&mut self) -> Result<(), SandboxError> { - if !self.tmpdir_active { - return Ok(()); + if self.tmpdir_active { + super::landlock::cleanup_tmpdir(&self.workspace_dir).map_err(|err| { + SandboxError::IsolationFailed(format!("MXC tmpdir cleanup: {err}")) + })?; + self.tmpdir_active = false; } - super::landlock::cleanup_tmpdir(&self.workspace_dir) - .map_err(|err| SandboxError::IsolationFailed(format!("MXC tmpdir cleanup: {err}")))?; - self.tmpdir_active = false; + self.tmpdir_claim = None; Ok(()) } From ad1b9899fd8c68a4cfc082c3fb0f9230ff67298f Mon Sep 17 00:00:00 2001 From: johannayang-amd Date: Thu, 12 Nov 2026 18:16:13 +0100 Subject: [PATCH 2/3] fix(sandbox): stop the whole sandbox on SIGTERM and free the claim at once Review of the tmpdir claim found that SIGTERM left the command's children running and that a run killed with SIGKILL blocked an immediate retry. - wait() takes the child, so after the SIGTERM handler dropped a pending wait(), destroy() found no child and only disarmed the parent-death monitor. Native and MXC sandboxes now remember the process group while wait() holds the child, and destroy() kills it. - The parent-death monitor inherited the workspace lock and outlives a killed AXIS for up to about a second. It now closes every inherited descriptor except its pipe. - A flock error other than "held" or "unsupported" now fails the launch instead of starting without the claim. - MXC claims the tmpdir after the run_as_user workspace checks, as the native path does, so it never removes a leftover through a workspace it then refuses. - The daemon path of `axis run` is left as on main; #108 removes it. --- crates/axis-cli/src/main.rs | 8 +- crates/axis-sandbox/src/linux/landlock.rs | 35 ++++--- crates/axis-sandbox/src/linux/mod.rs | 120 +++++++++++++++++++++- crates/axis-sandbox/src/linux/mxc.rs | 11 +- 4 files changed, 153 insertions(+), 21 deletions(-) diff --git a/crates/axis-cli/src/main.rs b/crates/axis-cli/src/main.rs index cb8064d8..fc6e1b1a 100644 --- a/crates/axis-cli/src/main.rs +++ b/crates/axis-cli/src/main.rs @@ -800,12 +800,8 @@ async fn run_command( eprintln!("AXIS: sandbox {id} running"); eprintln!("AXIS: press Ctrl+C to stop"); - // Wait for Ctrl+C or SIGTERM, then destroy. - let terminated = terminate_signal()?; - tokio::select! { - _ = tokio::signal::ctrl_c() => {} - () = terminated => {} - } + // Wait for Ctrl+C, then destroy. + tokio::signal::ctrl_c().await.ok(); eprintln!("\nAXIS: shutting down sandbox {id}..."); let destroy_req = serde_json::json!({ diff --git a/crates/axis-sandbox/src/linux/landlock.rs b/crates/axis-sandbox/src/linux/landlock.rs index 4017e816..964066db 100644 --- a/crates/axis-sandbox/src/linux/landlock.rs +++ b/crates/axis-sandbox/src/linux/landlock.rs @@ -263,8 +263,9 @@ pub(crate) struct TmpdirClaim { /// launch would fail on it, so it is removed when it is a directory, not a /// link, owned by `owner`, the uid the sandbox's tmpdir is created for. /// Anything else there is left, and the exclusive create still refuses it. -/// Where the workspace cannot be locked (`flock` unsupported), nothing is -/// removed. +/// On a filesystem without `flock` no launch there can hold the claim, so +/// none removes anything; any other locking error fails the launch, since a +/// later launch that does get the lock could remove this one's tmpdir. pub(crate) fn claim_tmpdir(workspace: &Path, owner: libc::uid_t) -> Result { use std::os::unix::io::AsRawFd; @@ -277,17 +278,27 @@ pub(crate) fn claim_tmpdir(workspace: &Path, owner: libc::uid_t) -> Result { + return Err(format!( + "cannot create exclusive tmpdir {}: another sandbox in this workspace holds it", + tmpdir.display() + )); + } + Some(libc::EOPNOTSUPP | libc::EINVAL) => { + tracing::debug!( + "workspace {} does not support flock ({error}); a tmpdir left there is not removed", + workspace.display() + ); + return Ok(TmpdirClaim { _lock: None }); + } + _ => { + return Err(format!( + "cannot lock workspace {} for its tmpdir: {error}", + workspace.display() + )); + } } - tracing::debug!( - "workspace {} cannot be locked ({error}); a tmpdir left there is not removed", - workspace.display() - ); - return Ok(TmpdirClaim { _lock: None }); } remove_stale_tmpdir(&tmpdir, owner); Ok(TmpdirClaim { _lock: Some(dir) }) diff --git a/crates/axis-sandbox/src/linux/mod.rs b/crates/axis-sandbox/src/linux/mod.rs index bc04be5b..ba87a617 100644 --- a/crates/axis-sandbox/src/linux/mod.rs +++ b/crates/axis-sandbox/src/linux/mod.rs @@ -231,7 +231,7 @@ impl ParentDeathGuard { } if monitor_pid == 0 { unsafe { - libc::close(pipe.write_fd); + close_inherited_fds_except(pipe.read_fd); libc::setpgid(0, 0); run_parent_death_monitor(pipe.read_fd, process_group); } @@ -359,6 +359,9 @@ pub(crate) struct LinuxSandbox { config: SandboxConfig, plan: strategy::LinuxIsolationPlan, child: Option, + /// Process group of a child that `wait()` took and has not reaped yet. + /// A cancelled `wait()` leaves it set, so `destroy()` can still stop it. + waited_process_group: Option, parent_death_guard: Option, exit_code: Option, netns_name: Option, @@ -387,6 +390,7 @@ impl LinuxSandbox { config, plan, child: None, + waited_process_group: None, parent_death_guard: None, exit_code: None, netns_name: None, @@ -1666,6 +1670,37 @@ fn current_errno() -> i32 { unsafe { *libc::__errno_location() } } +/// The monitor outlives a killed AXIS by up to about a second, so it must not +/// keep descriptors AXIS opened, such as the lock on a workspace tmpdir. +/// Runs in a forked child: only async-signal-safe calls. +unsafe fn close_inherited_fds_except(keep: i32) { + let close_range = |first: u32, last: u32| unsafe { + libc::syscall(libc::SYS_close_range, first, last, 0) == 0 + }; + let keep = keep as u32; + let closed = (keep <= 3 || close_range(3, keep - 1)) && close_range(keep + 1, u32::MAX); + if closed { + return; + } + // close_range needs Linux 5.9. + let mut limit = libc::rlimit { + rlim_cur: 0, + rlim_max: 0, + }; + let max = if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } == 0 { + limit.rlim_cur.min(1 << 20) as i32 + } else { + 1024 + }; + for fd in 3..max { + if fd != keep as i32 { + unsafe { + libc::close(fd); + } + } + } +} + fn run_parent_death_monitor(read_fd: i32, process_group: libc::pid_t) -> ! { let mut byte = 0u8; let mut disarmed = false; @@ -2338,8 +2373,11 @@ impl SandboxImpl for LinuxSandbox { .take() .ok_or_else(|| SandboxError::SpawnFailed("no child process".into()))?; let pid = child.id() as i32; + self.waited_process_group = Some(pid); - let status = match wait_child_with_timeout(child, self.config.timeout_sec).await { + let status = wait_child_with_timeout(child, self.config.timeout_sec).await; + self.waited_process_group = None; + let status = match status { Ok(status) => status, Err(e) => { self.exit_code = Some(-1); @@ -2406,6 +2444,8 @@ impl SandboxImpl for LinuxSandbox { } self.exit_code = Some(wait_for_killed_child(&mut child, pid)); kill_process_group(pid); + } else if let Some(process_group) = self.waited_process_group.take() { + kill_process_group(process_group); } self.finish_parent_death_guard(); self.stop_connect_supervisor(); @@ -2835,6 +2875,81 @@ mod tests { sandbox.destroy().unwrap(); } + #[tokio::test(flavor = "multi_thread")] + async fn destroy_after_cancelled_wait_kills_the_process_group() { + if !Path::new("/bin/sh").exists() { + eprintln!("/bin/sh unavailable (test skipped)"); + return; + } + + let workspace = tempfile::tempdir().unwrap(); + let pid_path = workspace.path().join("background.pid"); + let mut cmd = Command::new("/bin/sh"); + cmd.arg("-c") + .arg("sleep 30 & echo $! > \"$PID_PATH\"; wait") + .env("PID_PATH", &pid_path); + unsafe { + cmd.pre_exec(|| { + if libc::setpgid(0, 0) < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let mut child = cmd.spawn().unwrap(); + let process_group = child.id() as libc::pid_t; + let background_pid = wait_for_recorded_test_pid(&pid_path, &mut child, process_group); + let mut sandbox = test_sandbox(SandboxId::new(), workspace.path(), Some(child)); + + // What `axis run` does on SIGTERM: the select drops the pending wait(). + let waited = tokio::time::timeout( + std::time::Duration::from_millis(200), + SandboxImpl::wait(&mut sandbox), + ) + .await; + assert!(waited.is_err(), "the sandbox command exited early"); + assert!(sandbox.child.is_none()); + sandbox.destroy().unwrap(); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while process_exists(background_pid) { + if std::time::Instant::now() >= deadline { + kill_process_group(process_group); + panic!( + "background process {background_pid} survived destroy after a cancelled wait" + ); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + } + + #[test] + fn parent_death_monitor_does_not_keep_the_tmpdir_claim() { + let workspace = tempfile::tempdir().unwrap(); + let owner = unsafe { libc::geteuid() }; + let claim = landlock::claim_tmpdir(workspace.path(), owner).unwrap(); + let mut child = Command::new("/bin/sleep").arg("30").spawn().unwrap(); + let process_group = child.id() as libc::pid_t; + let pipe = ParentDeathGuardPipe::new().unwrap(); + let mut guard = ParentDeathGuard::spawn_for_process_group(process_group, pipe).unwrap(); + drop(claim); + + // The monitor is still running; only its inherited descriptor could + // keep the workspace locked. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1); + let reclaimed = loop { + match landlock::claim_tmpdir(workspace.path(), owner) { + Ok(claim) => break Ok(claim), + Err(err) if std::time::Instant::now() >= deadline => break Err(err), + Err(_) => std::thread::sleep(std::time::Duration::from_millis(10)), + } + }; + guard.finish(); + let _ = child.kill(); + let _ = child.wait(); + assert!(reclaimed.is_ok(), "{reclaimed:?}"); + } + #[test] fn parent_death_guard_kills_process_group_descendants_on_owner_close() { if !Path::new("/bin/sh").exists() { @@ -4162,6 +4277,7 @@ mod tests { }, plan: test_plan(id, workspace), child, + waited_process_group: None, parent_death_guard: None, exit_code: None, netns_name: None, diff --git a/crates/axis-sandbox/src/linux/mxc.rs b/crates/axis-sandbox/src/linux/mxc.rs index a3e8a1d2..b70c30e6 100644 --- a/crates/axis-sandbox/src/linux/mxc.rs +++ b/crates/axis-sandbox/src/linux/mxc.rs @@ -443,6 +443,9 @@ pub(crate) struct MxcLinuxSandbox { proxy_strategy: super::strategy::ProxyStrategy, resource_strategy: super::strategy::ResourceStrategy, child: Option, + /// Process group of a child that `wait()` took and has not reaped yet. + /// A cancelled `wait()` leaves it set, so `destroy()` can still stop it. + waited_process_group: Option, parent_death_guard: Option, exit_code: Option, config_file: Option, @@ -1074,6 +1077,7 @@ impl MxcLinuxSandbox { proxy_strategy, resource_strategy, child: None, + waited_process_group: None, parent_death_guard: None, exit_code: None, config_file: None, @@ -2168,7 +2172,10 @@ impl SandboxImpl for MxcLinuxSandbox { .take() .ok_or_else(|| SandboxError::SpawnFailed("no MXC child process".into()))?; let pid = child.id() as i32; - let status = match wait_runtime_child_with_timeout(child, self.timeout_sec).await { + self.waited_process_group = Some(pid); + let status = wait_runtime_child_with_timeout(child, self.timeout_sec).await; + self.waited_process_group = None; + let status = match status { Ok(status) => status, Err(err) => { self.exit_code = Some(-1); @@ -2224,6 +2231,8 @@ impl SandboxImpl for MxcLinuxSandbox { } self.exit_code = Some(wait_for_killed_child(&mut child, pid)); kill_process_group(pid); + } else if let Some(process_group) = self.waited_process_group.take() { + kill_process_group(process_group); } self.cleanup_after_stop()?; tracing::info!("sandbox {} destroyed via MXC Linux backend", self.id); From 47ced773a327676102f0d27ded12b6d1b47d6520 Mon Sep 17 00:00:00 2001 From: johannayang-amd Date: Fri, 20 Nov 2026 12:21:21 +0100 Subject: [PATCH 3/3] fix(sandbox): reclaim the tmpdir through the locked workspace descriptor Review found three ways the leftover removal could reach the wrong directory. After #95 the claim runs before the run_as_user workspace checks, and it removed the leftover by path, so a workspace about to be refused could already have lost a .axis-tmp behind a link. On a network filesystem the lock may be local to one host, so another host's live tmpdir looked like a leftover. The claim now opens the workspace once and does everything through that descriptor: the lock, the filesystem check, and the removal, which follows no link. For run_as_user the open refuses a symlink in any component, as the run_as_user setup does. On NFS, SMB, FUSE, 9P and similar filesystems, or when the type is unknown, a leftover is left in place and the exclusive create refuses it, as before this change. axis run now registers its SIGTERM handler before creating the sandbox, since MXC creates the tmpdir there. The parent-death monitor reuses close_child_fd_range. A native-backend test covers the leftover and a second sandbox, and the close-on-exec test now checks that a spawned command does not keep the lock. The isolation contract describes the tmpdir's lifecycle. Co-authored-by: Cursor --- crates/axis-cli/src/main.rs | 7 +- crates/axis-sandbox/src/linux/identity.rs | 11 ++ crates/axis-sandbox/src/linux/landlock.rs | 189 +++++++++++++++++++--- crates/axis-sandbox/src/linux/mod.rs | 76 +++++++-- crates/axis-sandbox/src/linux/mxc.rs | 15 +- docs/axis-isolation-contract.md | 14 ++ 6 files changed, 266 insertions(+), 46 deletions(-) diff --git a/crates/axis-cli/src/main.rs b/crates/axis-cli/src/main.rs index fc6e1b1a..67bb4142 100644 --- a/crates/axis-cli/src/main.rs +++ b/crates/axis-cli/src/main.rs @@ -899,11 +899,12 @@ async fn run_command( startup_trace: None, }; + // Registered before the create, which already makes the tmpdir on + // some backends, so a SIGTERM from then on stops the sandbox + // instead of ending AXIS without its cleanup. + let terminated = terminate_signal()?; let mut sandbox = axis_sandbox::Sandbox::create(config).map_err(|e| anyhow::anyhow!("{e}"))?; - // Registered before the start, so a SIGTERM from then on stops - // the sandbox instead of ending AXIS without its cleanup. - let terminated = terminate_signal()?; sandbox.start().map_err(|e| anyhow::anyhow!("{e}"))?; if !quiet { diff --git a/crates/axis-sandbox/src/linux/identity.rs b/crates/axis-sandbox/src/linux/identity.rs index b09a462c..a8119b98 100644 --- a/crates/axis-sandbox/src/linux/identity.rs +++ b/crates/axis-sandbox/src/linux/identity.rs @@ -308,6 +308,17 @@ fn ensure_owned_private_directory_fd( Ok(()) } +/// Opens `path` as a directory without following a symlink in any component. +pub(crate) fn open_directory_no_symlinks(path: &Path) -> Result { + use std::os::fd::FromRawFd; + + let fd = open_directory_tree_no_symlinks(path)?; + let raw = fd.raw(); + std::mem::forget(fd); + // SAFETY: `raw` is an open descriptor that `fd` owned and no longer closes. + Ok(unsafe { std::fs::File::from_raw_fd(raw) }) +} + struct DirectoryFd(RawFd); impl DirectoryFd { diff --git a/crates/axis-sandbox/src/linux/landlock.rs b/crates/axis-sandbox/src/linux/landlock.rs index 964066db..2990748f 100644 --- a/crates/axis-sandbox/src/linux/landlock.rs +++ b/crates/axis-sandbox/src/linux/landlock.rs @@ -261,16 +261,43 @@ pub(crate) struct TmpdirClaim { /// fails the launch. A tmpdir already there while this holds it was left by a /// sandbox whose AXIS ended without removing it (killed), and every later /// launch would fail on it, so it is removed when it is a directory, not a -/// link, owned by `owner`, the uid the sandbox's tmpdir is created for. -/// Anything else there is left, and the exclusive create still refuses it. +/// link, owned by the uid the sandbox's tmpdir is created for: `identity`'s +/// for `run_as_user`, otherwise this process's. Anything else there is left, +/// and the exclusive create still refuses it. +/// +/// With `identity` the workspace is opened without following a symlink in any +/// component, as the `run_as_user` setup requires, so a workspace it would +/// refuse is refused before anything is removed. Everything after the open +/// goes through that descriptor: the lock, the filesystem check, and the +/// removal, which follows no symlink. +/// /// On a filesystem without `flock` no launch there can hold the claim, so /// none removes anything; any other locking error fails the launch, since a /// later launch that does get the lock could remove this one's tmpdir. -pub(crate) fn claim_tmpdir(workspace: &Path, owner: libc::uid_t) -> Result { +pub(crate) fn claim_tmpdir( + workspace: &Path, + identity: Option<&super::identity::ResolvedIdentity>, +) -> Result { + match identity { + Some(identity) => claim_tmpdir_for(workspace, identity.uid, true), + None => claim_tmpdir_for(workspace, unsafe { libc::geteuid() }, false), + } +} + +fn claim_tmpdir_for( + workspace: &Path, + owner: libc::uid_t, + refuse_symlinks: bool, +) -> Result { use std::os::unix::io::AsRawFd; let tmpdir = sandbox_tmpdir(workspace); - let dir = std::fs::File::open(workspace).map_err(|e| { + let dir = if refuse_symlinks { + super::identity::open_directory_no_symlinks(workspace) + } else { + std::fs::File::open(workspace).map_err(|e| e.to_string()) + } + .map_err(|e| { format!( "cannot open workspace {} to lock its tmpdir: {e}", workspace.display() @@ -300,24 +327,86 @@ pub(crate) fn claim_tmpdir(workspace: &Path, owner: libc::uid_t) -> Result Option { + use std::os::unix::io::AsRawFd; + + let mut stat = std::mem::MaybeUninit::::uninit(); + if unsafe { libc::fstatfs(dir.as_raw_fd(), stat.as_mut_ptr()) } != 0 { + return None; + } + // Filesystem magic numbers are 32-bit; f_type is wider on some targets. + Some(unsafe { stat.assume_init() }.f_type as u32) +} + +/// Removes a leftover tmpdir in the locked workspace `dir`. `tmpdir` names it +/// for messages only; every lookup is relative to `dir` and follows no link. +fn remove_leftover_tmpdir( + dir: &std::fs::File, + tmpdir: &Path, + owner: libc::uid_t, + filesystem: Option, +) { + use std::os::unix::io::AsRawFd; - let Ok(metadata) = std::fs::symlink_metadata(tmpdir) else { + let name = std::ffi::CString::new(SANDBOX_TMPDIR_NAME).expect("static tmpdir name has no NUL"); + let mut stat = std::mem::MaybeUninit::::uninit(); + if unsafe { + libc::fstatat( + dir.as_raw_fd(), + name.as_ptr(), + stat.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } != 0 + { return; - }; - if !metadata.file_type().is_dir() || metadata.uid() != owner { + } + let stat = unsafe { stat.assume_init() }; + match filesystem { + Some(magic) if !NETWORK_FILESYSTEM_MAGIC.contains(&magic) => {} + _ => { + tracing::warn!( + "tmpdir {} is on a network or unknown filesystem, where another host may be using it; it is not removed", + tmpdir.display() + ); + return; + } + } + if stat.st_mode & libc::S_IFMT != libc::S_IFDIR || stat.st_uid != owner { tracing::warn!( "tmpdir {} is not a directory owned by uid {owner}; it is not removed", tmpdir.display() ); return; } - match std::fs::remove_dir_all(tmpdir) { + // The magic link resolves to the locked directory itself, not to the + // workspace path, and remove_dir_all neither follows nor descends into + // a symlink below it. + let anchored = Path::new("/proc/self/fd") + .join(dir.as_raw_fd().to_string()) + .join(SANDBOX_TMPDIR_NAME); + match std::fs::remove_dir_all(&anchored) { Ok(()) => tracing::warn!( "removed tmpdir {} left by a sandbox that did not stop cleanly", tmpdir.display() @@ -1823,12 +1912,11 @@ mod tests { fn claim_tmpdir_removes_a_leftover_only_while_no_other_sandbox_holds_it() { let dir = tempfile::tempdir().unwrap(); let tmpdir = sandbox_tmpdir(dir.path()); - let owner = unsafe { libc::geteuid() }; - let held = claim_tmpdir(dir.path(), owner).unwrap(); + let held = claim_tmpdir(dir.path(), None).unwrap(); create_tmpdir(dir.path()).unwrap(); std::fs::write(tmpdir.join("scratch"), b"scratch").unwrap(); - let err = claim_tmpdir(dir.path(), owner).unwrap_err(); + let err = claim_tmpdir(dir.path(), None).unwrap_err(); assert!( err.contains("another sandbox in this workspace holds it"), "{err}" @@ -1837,7 +1925,7 @@ mod tests { // The holder ended without removing it, as a killed AXIS does. drop(held); - let _claim = claim_tmpdir(dir.path(), owner).unwrap(); + let _claim = claim_tmpdir(dir.path(), None).unwrap(); assert!(!tmpdir.exists()); create_tmpdir(dir.path()).unwrap(); } @@ -1851,7 +1939,7 @@ mod tests { let owner = unsafe { libc::geteuid() }; std::os::unix::fs::symlink(outside.path(), &tmpdir).unwrap(); - let claim = claim_tmpdir(dir.path(), owner).unwrap(); + let claim = claim_tmpdir(dir.path(), None).unwrap(); assert!( std::fs::symlink_metadata(&tmpdir) .unwrap() @@ -1868,7 +1956,7 @@ mod tests { std::fs::remove_file(&tmpdir).unwrap(); std::fs::create_dir(&tmpdir).unwrap(); - let _claim = claim_tmpdir(dir.path(), owner.wrapping_add(1)).unwrap(); + let _claim = claim_tmpdir_for(dir.path(), owner.wrapping_add(1), false).unwrap(); assert!(tmpdir.is_dir()); assert!( create_tmpdir(dir.path()) @@ -1878,14 +1966,69 @@ mod tests { } #[test] - fn claim_tmpdir_is_not_inherited_by_the_sandboxed_command() { - use std::os::unix::io::AsRawFd; + fn claim_tmpdir_removes_nothing_below_a_link_inside_the_leftover() { + let dir = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("keep"), b"keep").unwrap(); + let tmpdir = sandbox_tmpdir(dir.path()); + std::fs::create_dir(&tmpdir).unwrap(); + std::os::unix::fs::symlink(outside.path(), tmpdir.join("link")).unwrap(); + + let _claim = claim_tmpdir(dir.path(), None).unwrap(); + assert!(!tmpdir.exists()); + assert!(outside.path().join("keep").exists()); + } + + #[test] + fn claim_tmpdir_for_run_as_user_refuses_a_linked_workspace_before_removing_anything() { + let parent = tempfile::tempdir().unwrap(); + let real = parent.path().join("real"); + let link = parent.path().join("link"); + std::fs::create_dir(&real).unwrap(); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let leftover = sandbox_tmpdir(&real); + std::fs::create_dir(&leftover).unwrap(); + + let err = claim_tmpdir_for(&link, unsafe { libc::geteuid() }, true).unwrap_err(); + assert!(err.contains("cannot open workspace"), "{err}"); + assert!(leftover.is_dir()); + // Without run_as_user a linked workspace is still the workspace. + let _claim = claim_tmpdir(&link, None).unwrap(); + assert!(!leftover.exists()); + } + #[test] + fn claim_tmpdir_leaves_a_leftover_on_a_network_or_unknown_filesystem() { + let dir = tempfile::tempdir().unwrap(); + let tmpdir = sandbox_tmpdir(dir.path()); + std::fs::create_dir(&tmpdir).unwrap(); + let workspace = std::fs::File::open(dir.path()).unwrap(); + let owner = unsafe { libc::geteuid() }; + + for filesystem in [Some(0x6969), Some(0xff53_4d42), Some(0x6573_5546), None] { + remove_leftover_tmpdir(&workspace, &tmpdir, owner, filesystem); + assert!(tmpdir.is_dir(), "{filesystem:?}"); + } + remove_leftover_tmpdir(&workspace, &tmpdir, owner, Some(0x0102_1994)); // tmpfs + assert!(!tmpdir.exists()); + } + + #[test] + fn claim_tmpdir_is_free_once_only_a_spawned_command_has_descriptors() { let dir = tempfile::tempdir().unwrap(); - let claim = claim_tmpdir(dir.path(), unsafe { libc::geteuid() }).unwrap(); - let fd = claim._lock.as_ref().unwrap().as_raw_fd(); - let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; - assert_ne!(flags & libc::FD_CLOEXEC, 0); + for identity in [false, true] { + let claim = claim_tmpdir_for(dir.path(), unsafe { libc::geteuid() }, identity).unwrap(); + let mut command = std::process::Command::new("/bin/sleep") + .arg("30") + .spawn() + .unwrap(); + drop(claim); + // Only an inherited lock descriptor could keep the workspace locked. + let reclaimed = claim_tmpdir(dir.path(), None); + let _ = command.kill(); + let _ = command.wait(); + assert!(reclaimed.is_ok(), "{identity}: {reclaimed:?}"); + } } #[test] diff --git a/crates/axis-sandbox/src/linux/mod.rs b/crates/axis-sandbox/src/linux/mod.rs index ba87a617..e9bbed4c 100644 --- a/crates/axis-sandbox/src/linux/mod.rs +++ b/crates/axis-sandbox/src/linux/mod.rs @@ -685,7 +685,7 @@ impl LinuxSandbox { let sandbox_id = self.config.id; let tmpdir_required = landlock::policy_uses_tmpdir(&self.config.policy.filesystem); if tmpdir_required { - self.claim_tmpdir(unsafe { libc::geteuid() })?; + self.claim_tmpdir(None)?; match landlock::create_tmpdir(&self.config.workspace_dir) { Ok(()) => self.tmpdir_active = true, Err(e) => return Err(SandboxError::IsolationFailed(e)), @@ -1211,8 +1211,8 @@ impl LinuxSandbox { self.cleanup_tmpdir().err() } - fn claim_tmpdir(&mut self, owner: libc::uid_t) -> Result<(), SandboxError> { - let claim = landlock::claim_tmpdir(&self.config.workspace_dir, owner) + fn claim_tmpdir(&mut self, identity: Option<&ResolvedIdentity>) -> Result<(), SandboxError> { + let claim = landlock::claim_tmpdir(&self.config.workspace_dir, identity) .map_err(SandboxError::IsolationFailed)?; self.tmpdir_claim = Some(claim); Ok(()) @@ -1674,9 +1674,7 @@ fn current_errno() -> i32 { /// keep descriptors AXIS opened, such as the lock on a workspace tmpdir. /// Runs in a forked child: only async-signal-safe calls. unsafe fn close_inherited_fds_except(keep: i32) { - let close_range = |first: u32, last: u32| unsafe { - libc::syscall(libc::SYS_close_range, first, last, 0) == 0 - }; + let close_range = |first: u32, last: u32| close_child_fd_range(first, last, 0).is_ok(); let keep = keep as u32; let closed = (keep <= 3 || close_range(3, keep - 1)) && close_range(keep + 1, u32::MAX); if closed { @@ -1800,10 +1798,9 @@ impl SandboxImpl for LinuxSandbox { })?; let tmpdir_required = landlock::policy_uses_tmpdir(&self.config.policy.filesystem); if tmpdir_required { - let owner = resolved_identity - .as_ref() - .map_or_else(|| unsafe { libc::geteuid() }, |identity| identity.uid); - self.claim_tmpdir(owner)?; + crate::sandbox::record_startup_result(&trace, "support_files.tmpdir_claim", || { + self.claim_tmpdir(resolved_identity.as_ref()) + })?; } if let Some(identity) = &resolved_identity { if tmpdir_required { @@ -2926,8 +2923,7 @@ mod tests { #[test] fn parent_death_monitor_does_not_keep_the_tmpdir_claim() { let workspace = tempfile::tempdir().unwrap(); - let owner = unsafe { libc::geteuid() }; - let claim = landlock::claim_tmpdir(workspace.path(), owner).unwrap(); + let claim = landlock::claim_tmpdir(workspace.path(), None).unwrap(); let mut child = Command::new("/bin/sleep").arg("30").spawn().unwrap(); let process_group = child.id() as libc::pid_t; let pipe = ParentDeathGuardPipe::new().unwrap(); @@ -2938,7 +2934,7 @@ mod tests { // keep the workspace locked. let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1); let reclaimed = loop { - match landlock::claim_tmpdir(workspace.path(), owner) { + match landlock::claim_tmpdir(workspace.path(), None) { Ok(claim) => break Ok(claim), Err(err) if std::time::Instant::now() >= deadline => break Err(err), Err(_) => std::thread::sleep(std::time::Duration::from_millis(10)), @@ -3772,6 +3768,60 @@ mod tests { sandbox.destroy().unwrap(); } + #[tokio::test(flavor = "multi_thread")] + async fn native_sandbox_reclaims_a_leftover_tmpdir_and_refuses_a_second_sandbox() { + if !contract_landlock_available() { + return; + } + let Some(sh) = find_on_path("sh").and_then(|path| std::fs::canonicalize(path).ok()) else { + eprintln!("sh unavailable (test skipped)"); + return; + }; + let workspace = tempfile::tempdir().unwrap(); + let tmpdir = landlock::sandbox_tmpdir(workspace.path()); + // What a killed run leaves behind. + std::fs::create_dir(&tmpdir).unwrap(); + std::fs::write(tmpdir.join("stale"), b"stale").unwrap(); + let tmpdir_sandbox = |script: String| { + let mut sandbox = test_sandbox(SandboxId::new(), workspace.path(), None); + sandbox.config.command = sh.to_string_lossy().into_owned(); + sandbox.config.args = vec!["-c".into(), script]; + sandbox.config.capture_output = true; + sandbox.config.policy.network.mode = NetworkMode::Block; + sandbox.config.policy.filesystem = FilesystemPolicy { + read_only: runtime_read_only_paths_for(&sh), + read_write: vec!["{tmpdir}".into()], + ..Default::default() + }; + sandbox.plan.network = strategy::NetworkStrategy::BlockedBySeccomp; + sandbox.plan.proxy = strategy::ProxyStrategy::None; + sandbox + }; + + let mut first = tmpdir_sandbox(format!( + "test -d '{0}' && test ! -e '{0}/stale' && sleep 2", + tmpdir.display() + )); + SandboxImpl::start(&mut first).unwrap(); + let mut second = tmpdir_sandbox("true".into()); + let err = SandboxImpl::start(&mut second).unwrap_err().to_string(); + assert!( + err.contains("another sandbox in this workspace holds it"), + "{err}" + ); + let code = SandboxImpl::wait(&mut first).await.unwrap(); + let stderr = + std::fs::read_to_string(workspace.path().join("stderr.log")).unwrap_or_default(); + first.destroy().unwrap(); + assert_eq!(code, 0, "the leftover was not replaced; stderr:\n{stderr}"); + assert!(!tmpdir.exists()); + + let mut third = tmpdir_sandbox("true".into()); + SandboxImpl::start(&mut third).unwrap(); + assert_eq!(SandboxImpl::wait(&mut third).await.unwrap(), 0); + third.destroy().unwrap(); + } + async fn run_shell_with_deny_paths(sh: &Path, script: &str, deny: &[&str]) -> (i32, String) { let workspace = tempfile::tempdir().unwrap(); let mut sandbox = test_sandbox(SandboxId::new(), workspace.path(), None); diff --git a/crates/axis-sandbox/src/linux/mxc.rs b/crates/axis-sandbox/src/linux/mxc.rs index b70c30e6..29521362 100644 --- a/crates/axis-sandbox/src/linux/mxc.rs +++ b/crates/axis-sandbox/src/linux/mxc.rs @@ -946,13 +946,14 @@ impl MxcLinuxSandbox { let mut tmpdir_active = false; let tmpdir_required = super::landlock::policy_uses_tmpdir(&config.policy.filesystem); let tmpdir_claim = if tmpdir_required { - let owner = resolved_identity - .as_ref() - .map_or_else(|| unsafe { libc::geteuid() }, |identity| identity.uid); - Some( - super::landlock::claim_tmpdir(&config.workspace_dir, owner) - .map_err(|err| SandboxError::IsolationFailed(format!("MXC tmpdir: {err}")))?, - ) + Some(crate::sandbox::record_startup_result( + &trace, + "support_files.tmpdir_claim", + || { + super::landlock::claim_tmpdir(&config.workspace_dir, resolved_identity.as_ref()) + .map_err(|err| SandboxError::IsolationFailed(format!("MXC tmpdir: {err}"))) + }, + )?) } else { None }; diff --git a/docs/axis-isolation-contract.md b/docs/axis-isolation-contract.md index 8c4e5b91..511c6c67 100644 --- a/docs/axis-isolation-contract.md +++ b/docs/axis-isolation-contract.md @@ -391,6 +391,20 @@ Required behavior: failure. - Stateful backends must make persisted state explicit in policy or launch options. Hidden state reuse is not allowed. +- `{tmpdir}` is `/.axis-tmp`. AXIS creates it empty for one + sandbox and removes it when the sandbox stops; `axis run` also stops its + sandbox on SIGTERM and exits 143. On Linux the sandbox holds a lock on the + workspace for as long as the tmpdir exists, so: + - a second sandbox in the same workspace is refused while the first runs; + - a `.axis-tmp` left by a run that was killed is deleted by the next run in + that workspace when it is a directory owned by the user the tmpdir is + for. A link or another user's directory is left, and the launch fails; + - on a network filesystem (NFS, SMB, FUSE, 9P and similar), where another + host's lock may not be visible, a leftover is never deleted, and the + launch fails until it is removed. + + On Windows a leftover `.axis-tmp` still fails the launch until it is + removed. - axisd accepts IPC and gateway requests only with the per-user token in `axisd.token`, so a sandboxed process cannot ask it for a less restricted sandbox. axisd replaces the token on every start and deletes it on clean