diff --git a/crates/mctx/src/env.rs b/crates/mctx/src/env.rs index 2119da79ec..d665f5b37c 100644 --- a/crates/mctx/src/env.rs +++ b/crates/mctx/src/env.rs @@ -929,6 +929,179 @@ fn declared_by(packages: &BTreeMap, declared: &str, task: &str) } } +/// A patch path in the session home that passes through a symbolic link. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct SymlinkedPatch { + /// The link, relative to the home: the patch path itself or a parent. + pub(crate) link: PathBuf, + /// Where the link points, when it could be read. + pub(crate) target: Option, +} + +/// Why a patch path in the session home is refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum UnsafePatch { + /// The path has a `..` component. + ParentDir, + /// The path passes through a symbolic link. + Symlink(SymlinkedPatch), +} + +/// Finds why the patch at `path` cannot be mounted from the session `home`, +/// or `None` when nothing on it is unsafe. +/// +/// A path with a `..` component is refused wherever it points. The link walk +/// in [`find_symlinked_patch`] checks the path as written and stops at the +/// first missing component, while the sandbox creates that component and the +/// kernel then resolves the `..` after it, and any link beyond, itself. +pub(crate) fn find_unsafe_patch(home: &Path, path: &Path) -> std::io::Result> { + if path + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + { + return Ok(Some(UnsafePatch::ParentDir)); + } + Ok(find_symlinked_patch(home, path)?.map(UnsafePatch::Symlink)) +} + +/// Finds the first symbolic link on `path` below `home`, walking one +/// component at a time without following any link (inbox#1129). `path` has +/// no `..` component; [`find_unsafe_patch`] refuses one first. +/// +/// The rule is no links at all, not no escapes: a link that stays inside the +/// home is refused too, because the sandbox resolves the mount point through +/// it against a different root than the bind source. A path outside `home` +/// is not the box's to change and is not checked. The walk stops at the first +/// component that does not exist: a read-write patch creates the rest, and +/// nothing below a missing directory can be a link yet. It stops too at a +/// component below a regular file, which cannot be a link either; the sandbox +/// then fails that patch with an error that names who declared it. +/// +/// The check runs before the sandbox mounts, so it catches a link that is in +/// place when the task is set up, and not one that the box makes between this +/// walk and the mount. +pub(crate) fn find_symlinked_patch( + home: &Path, + path: &Path, +) -> std::io::Result> { + let Ok(rel) = path.strip_prefix(home) else { + return Ok(None); + }; + let mut at = home.to_path_buf(); + let mut link = PathBuf::new(); + for component in rel.components() { + at.push(component); + link.push(component); + match std::fs::symlink_metadata(&at) { + Ok(meta) if meta.file_type().is_symlink() => { + return Ok(Some(SymlinkedPatch { + link, + target: std::fs::read_link(&at).ok(), + })); + } + Ok(_) => {} + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory + ) => + { + break; + } + Err(e) => return Err(e), + } + } + Ok(None) +} + +/// The refusal for a patch through a symbolic link: the patch as declared, +/// who declared it, the link and its target, and the one way out. The box +/// chose the target, so its control characters are escaped. +pub(crate) fn symlinked_patch_refusal(found: &SymlinkedPatch, declared: &str, by: &str) -> String { + let link = found.link.display(); + let target = found + .target + .as_ref() + .map(|t| format!(" to `{}`", printable(&t.to_string_lossy()))) + .unwrap_or_default(); + format!( + "refused the patch `{declared}` from {by}: `~/{link}` in the session's home is a \ + symbolic link{target}. A patch is never mounted through a symbolic link. Replace \ + `~/{link}` in the session with a real directory or file." + ) +} + +/// The refusal for a patch path with a `..` component: the patch as +/// declared, who declared it, and the one way out. +pub(crate) fn parent_dir_patch_refusal(declared: &str, by: &str) -> String { + format!( + "refused the patch `{declared}` from {by}: the path contains `..`. A patch path \ + cannot contain `..`. Declare the patch without `..`." + ) +} + +/// `text` with each control character escaped (`\n`, `\u{1b}`), so a link +/// target the box chose cannot move the cursor or fake a line in the error. +fn printable(text: &str) -> std::borrow::Cow<'_, str> { + if !text.chars().any(char::is_control) { + return text.into(); + } + let mut out = String::with_capacity(text.len() + 8); + for c in text.chars() { + if c.is_control() { + out.extend(c.escape_debug()); + } else { + out.push(c); + } + } + out.into() +} + +/// Refuses the first patch whose path in the session home has a `..` +/// component or passes through a symbolic link, naming the patch as it was +/// declared (inbox#1129). +fn refuse_unsafe_patches( + home: &Path, + fs_mappings: &[common::FsMapping], + declarations: &BTreeMap>>, + packages: &BTreeMap, + task: &str, +) -> Result<(), Error> { + for mapping in fs_mappings { + let path = Path::new(&mapping.host_path); + let found = find_unsafe_patch(home, path).map_err(|e| { + Error::IO( + "checking a patch path for symbolic links", + path.to_path_buf(), + e, + ) + })?; + let Some(found) = found else { continue }; + let declared = declarations + .get(&mapping.host_path) + .and_then(|d| d.first()) + .map_or(mapping.host_path.as_str(), |d| d.declared.as_str()); + let by = declared_by(packages, declared, task); + let refusal = match &found { + UnsafePatch::ParentDir => { + tracing::warn!(task, patch = declared, "refusing a patch path with `..`"); + parent_dir_patch_refusal(declared, &by) + } + UnsafePatch::Symlink(link) => { + tracing::warn!( + task, + patch = declared, + link = %link.link.display(), + "refusing a patch through a symbolic link in the session home" + ); + symlinked_patch_refusal(link, declared, &by) + } + }; + return Err(Error::Other(anyhow::anyhow!("{refusal}"))); + } + Ok(()) +} + /// One declared patch entry that shares an expanded host path with /// possibly other entries. A directory mapping and a file mapping can /// expand to the same path — `Config::validate` processes directories @@ -1133,6 +1306,25 @@ impl<'a> Env<'a> { declarations }); + // A box owns its home, so code it runs can turn any path there into a + // symbolic link. The sandbox follows such a link for the bind source + // and resolves the mount point through it as well, so a patch through + // a link is mounted somewhere other than where it was declared, or the + // task fails to start with nothing said (inbox#1129). A `..` in a + // patch path is refused too, since the walk cannot see past it. Only a + // session home is the box's; an ambient home is the invoking user's own. + if matches!(args.home, PatchHome::Session(_)) + && let Some(home) = home.as_deref() + { + refuse_unsafe_patches( + home, + &fs_mappings, + &declarations, + &fs_mapping_packages, + args.name, + )?; + } + let mut config = apply_wd_layout( sandbox::config::Config::new(args.name), &args.wd_layout, @@ -1434,6 +1626,211 @@ mod tests { ); } + /// A home with a plain directory, a final link, a link through a parent + /// and a link that stays inside the home (inbox#1129). + fn linked_home() -> TempDir { + let home = tempdir().unwrap(); + let h = home.path(); + std::fs::create_dir_all(h.join("plain/inner")).unwrap(); + std::os::unix::fs::symlink("/etc", h.join("e810")).unwrap(); + std::os::unix::fs::symlink("/tmp", h.join("l810")).unwrap(); + std::fs::create_dir(h.join("real")).unwrap(); + std::os::unix::fs::symlink(h.join("real"), h.join("h810")).unwrap(); + home + } + + #[test] + fn a_plain_directory_patch_is_not_refused() { + let home = linked_home(); + let h = home.path(); + assert_eq!(find_symlinked_patch(h, &h.join("plain")).unwrap(), None); + assert_eq!( + find_symlinked_patch(h, &h.join("plain/inner")).unwrap(), + None + ); + assert_eq!( + find_symlinked_patch(h, &h.join("plain/missing/deeper")).unwrap(), + None, + "a path that does not exist yet has no link on it" + ); + assert_eq!( + find_symlinked_patch(h, Path::new("/etc/hostname")).unwrap(), + None, + "a path outside the home is not the box's and is not checked" + ); + } + + #[test] + fn a_final_component_symlink_is_refused() { + let home = linked_home(); + let h = home.path(); + assert_eq!( + find_symlinked_patch(h, &h.join("e810")).unwrap(), + Some(SymlinkedPatch { + link: "e810".into(), + target: Some("/etc".into()) + }) + ); + } + + #[test] + fn a_symlinked_parent_is_refused() { + let home = linked_home(); + let h = home.path(); + let found = find_symlinked_patch(h, &h.join("l810/out810p-1")).unwrap(); + assert_eq!( + found, + Some(SymlinkedPatch { + link: "l810".into(), + target: Some("/tmp".into()) + }), + "the link named is the parent, not the patch path" + ); + } + + #[test] + fn a_symlink_inside_the_home_is_still_refused() { + let home = linked_home(); + let h = home.path(); + let found = find_symlinked_patch(h, &h.join("h810")).unwrap(); + assert_eq!( + found.map(|f| f.link), + Some(PathBuf::from("h810")), + "the rule is no links, not no escapes" + ); + } + + #[test] + fn a_parent_dir_component_is_refused_before_the_walk() { + let home = linked_home(); + let h = home.path(); + assert_eq!( + find_unsafe_patch(h, &h.join("new810/../l810/out810p-2")).unwrap(), + Some(UnsafePatch::ParentDir), + "`new810` is missing, so the walk alone would stop before `l810`" + ); + assert!(!h.join("new810").exists(), "the check creates nothing"); + assert_eq!( + find_unsafe_patch(h, &h.join("plain/../plain")).unwrap(), + Some(UnsafePatch::ParentDir), + "`..` is refused even where it resolves to a plain directory" + ); + assert_eq!( + find_unsafe_patch(h, &h.join("l810/out")).unwrap(), + Some(UnsafePatch::Symlink(SymlinkedPatch { + link: "l810".into(), + target: Some("/tmp".into()) + })) + ); + assert_eq!(find_unsafe_patch(h, &h.join("plain")).unwrap(), None); + } + + #[test] + fn the_refusal_names_the_patch_and_the_link() { + let found = SymlinkedPatch { + link: "l810".into(), + target: Some("/tmp".into()), + }; + assert_eq!( + symlinked_patch_refusal(&found, "~/l810/out810p-1", "task `parent`"), + "refused the patch `~/l810/out810p-1` from task `parent`: `~/l810` in the session's \ + home is a symbolic link to `/tmp`. A patch is never mounted through a symbolic \ + link. Replace `~/l810` in the session with a real directory or file." + ); + } + + #[test] + fn refuse_unsafe_patches_names_the_declaration() { + let home = linked_home(); + let h = home.path(); + let patches = EnvPatches { + dir: [ + ("~/plain".to_string(), mfile::PatchSetting::ReadOnly), + ( + "~/l810/out810p-1".to_string(), + mfile::PatchSetting::ReadWrite, + ), + ] + .into(), + ..Default::default() + }; + let mappings = patches.to_fs_mappings(Some(h)).unwrap(); + let declared = "~/l810/out810p-1".to_string(); + let declarations = BTreeMap::from([( + format!("{}/l810/out810p-1", h.display()), + vec![DeclaredMapping { + declared: &declared, + is_file: false, + read_only: false, + }], + )]); + let err = refuse_unsafe_patches(h, &mappings, &declarations, &BTreeMap::new(), "parent") + .unwrap_err() + .to_string(); + assert!( + err.contains("refused the patch `~/l810/out810p-1` from task `parent`") + && err.contains("`~/l810`") + && err.contains("symbolic link"), + "got: {err}" + ); + } + + #[test] + fn the_refusal_escapes_control_characters_in_the_link_target() { + let found = SymlinkedPatch { + link: "l810".into(), + target: Some("/tmp/\u{1b}[2J\nfake".into()), + }; + let refusal = symlinked_patch_refusal(&found, "~/l810/out", "task `parent`"); + assert!( + refusal.contains("to `/tmp/\\u{1b}[2J\\nfake`"), + "got: {refusal}" + ); + assert!(!refusal.chars().any(char::is_control), "got: {refusal:?}"); + } + + /// A patch below a regular file is left to the sandbox, whose error + /// names who declared it, rather than failing the walk unattributed. + #[test] + fn a_patch_below_a_regular_file_is_not_a_walk_error() { + let home = linked_home(); + let h = home.path(); + std::fs::write(h.join("file810"), "").unwrap(); + assert_eq!( + find_symlinked_patch(h, &h.join("file810/sub")).unwrap(), + None + ); + let patches = EnvPatches { + dir: [("~/file810/sub".to_string(), mfile::PatchSetting::ReadWrite)].into(), + ..Default::default() + }; + let mappings = patches.to_fs_mappings(Some(h)).unwrap(); + refuse_unsafe_patches(h, &mappings, &BTreeMap::new(), &BTreeMap::new(), "parent").unwrap(); + } + + #[test] + fn refuse_unsafe_patches_refuses_a_parent_dir() { + let home = linked_home(); + let h = home.path(); + let patches = EnvPatches { + dir: [( + "~/new810/../l810/out810p-2".to_string(), + mfile::PatchSetting::ReadWrite, + )] + .into(), + ..Default::default() + }; + let mappings = patches.to_fs_mappings(Some(h)).unwrap(); + let err = refuse_unsafe_patches(h, &mappings, &BTreeMap::new(), &BTreeMap::new(), "parent") + .unwrap_err() + .to_string(); + assert!( + err.contains("from task `parent`: the path contains `..`"), + "got: {err}" + ); + assert!(!h.join("new810").exists(), "the refusal creates nothing"); + } + /// A patch path a package declared is attributed to that package; one /// that only the task's own `patch` table names falls back to the task. /// The attribution is what makes a failure to map `~/.claude.json` diff --git a/crates/minimald/src/env.rs b/crates/minimald/src/env.rs index 5737beed8d..67633f4b14 100644 --- a/crates/minimald/src/env.rs +++ b/crates/minimald/src/env.rs @@ -3129,7 +3129,7 @@ fn unescape_run_item(item: &str) -> String { /// `text` with each control character escaped (`\n`, `\r`, `\u{1b}`), for /// a name or a path that the channel echoes. A newline in it would start a /// protocol line of its own, such as `exit:0`. -fn one_line(text: &str) -> std::borrow::Cow<'_, str> { +pub(crate) fn one_line(text: &str) -> std::borrow::Cow<'_, str> { if !text.chars().any(char::is_control) { return text.into(); } diff --git a/crates/minimald/src/exec.rs b/crates/minimald/src/exec.rs index add028ab61..b406be796d 100644 --- a/crates/minimald/src/exec.rs +++ b/crates/minimald/src/exec.rs @@ -114,6 +114,13 @@ pub trait Process: Send + 'static { /// Request termination. Idempotent. Returns immediately — the /// caller is expected to follow up with `wait` for the actual exit. fn start_kill(&mut self) -> io::Result<()>; + + /// A line for the client's stderr about why the process ended, once + /// `wait` has returned. `None` (the default) when the process's own + /// output says all there is: it ran and exited, or was signalled. + fn exit_notice(&mut self) -> Option { + None + } } /// Handles a request to run a program on an SSH channel. diff --git a/crates/minimald/src/exec/bridge.rs b/crates/minimald/src/exec/bridge.rs index 4dbda0bed4..7b41859ecd 100644 --- a/crates/minimald/src/exec/bridge.rs +++ b/crates/minimald/src/exec/bridge.rs @@ -212,6 +212,10 @@ impl Process for StoppedOnDestroy

{ fn start_kill(&mut self) -> io::Result<()> { self.inner.start_kill() } + + fn exit_notice(&mut self) -> Option { + self.inner.exit_notice() + } } /// Runs [`bridge`] and writes the notice for why the command ended to `e` @@ -1528,6 +1532,22 @@ where } } }; + // A task whose sandbox failed may have written nothing, so the reason + // goes on stderr ahead of the status. A client that stops reading holds + // the write, so the wait for it is bounded and the status still returns. + if let Some(notice) = process.exit_notice() { + match tokio::time::timeout(EXIT_NOTICE_BOUND, e.write_all(notice.as_bytes())).await { + Ok(Ok(())) => {} + Ok(Err(_)) => { + tracing::debug!(%channel_id, "exec: the exit notice was not written; the client is gone"); + } + Err(_) => tracing::debug!( + %channel_id, + bound = ?EXIT_NOTICE_BOUND, + "exec: the exit notice was not written; the client did not take it in time", + ), + } + } match status { Ok(code) => code.unwrap_or(1) as u32, Err(err) => { @@ -1540,6 +1560,10 @@ where } } +/// How long [`bridge_one`] waits to write a process's exit notice to a +/// client that is not reading, before it returns the status without it. +pub(super) const EXIT_NOTICE_BOUND: Duration = Duration::from_secs(5); + /// How long [`drain_ready`] waits for a pipe to produce something after /// the child has been reaped, before concluding that whatever still /// holds the write end is a grandchild whose output we do not owe the diff --git a/crates/minimald/src/exec/process.rs b/crates/minimald/src/exec/process.rs index b9b2bd5f43..ebc35b0d6d 100644 --- a/crates/minimald/src/exec/process.rs +++ b/crates/minimald/src/exec/process.rs @@ -543,6 +543,12 @@ pub struct HakoniwaProcess { /// A line the daemon shows ahead of the child's own stderr, such as the /// `inherit_cwd` fallback notice (see [`task_start_dir`]). pub(super) stderr_notice: Option, + /// hakoniwa's account of a sandbox that failed, for the client's + /// stderr ([`Process::exit_notice`]). + pub(super) failure: Option, + /// Set by [`Process::start_kill`]: the daemon ended this task, so its + /// status is not read as a sandbox failure. + pub(super) killed: bool, } /// The release of a task's network, owed once its process is gone. @@ -618,6 +624,8 @@ impl HakoniwaProcess { state: WaitState::Spawned(Box::new(child)), net: NetRelease::new(net_guard), stderr_notice: None, + failure: None, + killed: false, } } } @@ -659,7 +667,13 @@ impl Process for HakoniwaProcess { // signal death), so a SIGKILL reports 137 rather than 1. The // `exit_code` field is `None` for signals and would collapse // to 1 downstream; `code` is what the session path reports too. - Ok(Ok(status)) => WaitState::Exited(Some(status.code)), + Ok(Ok(status)) => { + self.failure = sandbox_failure(&status, self.killed); + if let Some(reason) = &self.failure { + tracing::warn!(pid = self.pid, %reason, "task: the sandbox failed"); + } + WaitState::Exited(Some(status.code)) + } Ok(Err(_)) | Err(_) => WaitState::Failed, }; } @@ -685,8 +699,49 @@ impl Process for HakoniwaProcess { // invariants beyond the pid being a valid `pid_t`, which we // captured from `Child::id()` at construction time. unsafe { libc::kill(self.pid, libc::SIGKILL) }; + self.killed = true; Ok(()) } + + fn exit_notice(&mut self) -> Option { + self.failure + .take() + .map(|reason| sandbox_failure_notice(&reason)) + } +} + +/// hakoniwa's exit code for a container that failed itself, rather than a +/// command that ran (`ExitStatus::FAILURE`). +pub(super) const SANDBOX_FAILURE_CODE: i32 = 125; + +/// hakoniwa's reason for a container that a SIGKILL ended. It reports that +/// as [`SANDBOX_FAILURE_CODE`] with no inner exit code, the same shape as a +/// sandbox failure, whether or not the command had started. +pub(super) const CONTAINER_SIGKILL_REASON: &str = "container received signal SIGKILL"; + +/// The reason a task's sandbox failed, or `None` for any other end of the +/// task. hakoniwa reports a sandbox failure as code 125 with no inner +/// exit code. A command that itself exits 125 carries its own exit code, and +/// a signalled one reports `128 + signo`, so neither is taken for it. A +/// container that was killed, by the daemon (`killed`) or by anything else, +/// is not a sandbox failure either. +pub(super) fn sandbox_failure(status: &hakoniwa::ExitStatus, killed: bool) -> Option { + (!killed + && status.code == SANDBOX_FAILURE_CODE + && status.exit_code.is_none() + && status.reason != CONTAINER_SIGKILL_REASON) + .then(|| status.reason.clone()) +} + +/// The line on the client's stderr for a task whose sandbox failed: the +/// command's own output may be empty, so this is the only account of why the +/// task ended with 125. The reason can quote a path the box chose, so its +/// control characters are escaped and it stays one line. +pub(super) fn sandbox_failure_notice(reason: &str) -> String { + format!( + "the task's sandbox failed: {}\n", + crate::env::one_line(reason) + ) } /// The [`Process`] produced by a [`TaskExec`]: either a real sandboxed child @@ -737,6 +792,15 @@ impl Process for TaskProcess { TaskProcess::Refused(p) => p.start_kill(), } } + + fn exit_notice(&mut self) -> Option { + match self { + TaskProcess::Sandbox(p) => p.exit_notice(), + TaskProcess::Echo(p) => p.exit_notice(), + TaskProcess::Entrypoint(p) => p.exit_notice(), + TaskProcess::Refused(p) => p.exit_notice(), + } + } } /// A task box whose entrypoint a task run relays (T43), as @@ -2247,6 +2311,9 @@ impl Process for TimedProcess

{ fn start_kill(&mut self) -> io::Result<()> { self.inner.start_kill() } + fn exit_notice(&mut self) -> Option { + self.inner.exit_notice() + } } #[cfg(test)] diff --git a/crates/minimald/src/exec/tests.rs b/crates/minimald/src/exec/tests.rs index 72d0072532..ac5d10c08c 100644 --- a/crates/minimald/src/exec/tests.rs +++ b/crates/minimald/src/exec/tests.rs @@ -5401,3 +5401,138 @@ mod end_to_end { let _ = out; } } + +/// A task whose sandbox failed before its command started: nothing on its +/// stdio, hakoniwa's 125, and the reason kept for the client. +struct FailedSandbox; + +impl super::Process for FailedSandbox { + type Stdin = tokio::io::Sink; + type Stdout = tokio::io::Empty; + type Stderr = tokio::io::Empty; + + fn take_stdio(&mut self) -> Option<(Self::Stdin, Self::Stdout, Self::Stderr)> { + Some((tokio::io::sink(), tokio::io::empty(), tokio::io::empty())) + } + + async fn wait(&mut self) -> std::io::Result> { + Ok(Some(super::SANDBOX_FAILURE_CODE)) + } + + fn start_kill(&mut self) -> std::io::Result<()> { + Ok(()) + } + + fn exit_notice(&mut self) -> Option { + Some(super::sandbox_failure_notice("mount /home/h810: ENOENT")) + } +} + +/// A task whose sandbox failed ends with hakoniwa's 125 and nothing of its +/// own on stdout or stderr; the reason reaches the client's stderr +/// (inbox#1129). The process goes through [`bridge_noting_reason`], which +/// wraps it in `StoppedOnDestroy` as production does, so the wrapper must +/// pass the notice on. +#[tokio::test] +async fn a_sandbox_failure_reaches_the_client_stderr() { + let (mut bridge_stdout, mut client_stdout) = duplex(64 * 1024); + let (mut bridge_stderr, mut client_stderr) = duplex(64 * 1024); + let (client_stdin, mut stdin) = duplex(64); + drop(client_stdin); + let (status, _late) = bridge_noting_reason( + "test", + futures::stream::iter(vec![Ok(FailedSandbox)]), + &mut stdin, + &mut bridge_stdout, + &mut bridge_stderr, + client_lost(), + super::UnreadStdin::Keep, + None, + || false, + ) + .await; + drop(bridge_stdout); + drop(bridge_stderr); + assert_eq!(status, 125); + let mut err = String::new(); + client_stderr.read_to_string(&mut err).await.unwrap(); + assert_eq!(err, "the task's sandbox failed: mount /home/h810: ENOENT\n"); + let mut out = Vec::new(); + client_stdout.read_to_end(&mut out).await.unwrap(); + assert!(out.is_empty()); +} + +/// Only hakoniwa's own container failure counts: a command that exits 125 +/// itself, one that was signalled, a container that a SIGKILL ended, and a +/// task the daemon killed are not reported as a sandbox failure. +#[test] +fn only_a_container_failure_is_a_sandbox_failure() { + let status = |code, exit_code: Option, reason: &str| hakoniwa::ExitStatus { + code, + reason: reason.to_string(), + exit_code, + rusage: None, + proc_pid_smaps_rollup: None, + proc_pid_status: None, + }; + assert_eq!( + super::sandbox_failure(&status(125, None, "mount /home/h810: ENOENT"), false), + Some("mount /home/h810: ENOENT".to_string()) + ); + assert_eq!( + super::sandbox_failure( + &status(125, Some(125), "process(bash) exited with code 125"), + false + ), + None + ); + assert_eq!( + super::sandbox_failure( + &status(137, None, "process(bash) received signal SIGKILL"), + false + ), + None + ); + assert_eq!( + super::sandbox_failure(&status(125, None, super::CONTAINER_SIGKILL_REASON), false), + None, + "a container that a SIGKILL ended may have run its command" + ); + assert_eq!( + super::sandbox_failure(&status(125, None, "mount /home/h810: ENOENT"), true), + None, + "a task the daemon killed is not a sandbox failure" + ); +} + +/// The notice quotes hakoniwa's reason, which can name a path the box +/// chose; a control character in it is escaped, so the notice stays one line. +#[test] +fn the_sandbox_failure_notice_escapes_control_characters() { + assert_eq!( + super::sandbox_failure_notice("mount /home/x\n\u{1b}[2J: ENOENT"), + "the task's sandbox failed: mount /home/x\\n\\u{1b}[2J: ENOENT\n" + ); +} + +/// A client that stops reading does not hold the status back: the exit +/// notice write gives up after [`super::EXIT_NOTICE_BOUND`]. +#[tokio::test(start_paused = true)] +async fn an_unread_exit_notice_does_not_hold_the_status() { + let (mut bridge_stdout, _client_stdout) = duplex(64 * 1024); + // One byte of room and nobody reading: the notice write never completes. + let (mut bridge_stderr, _client_stderr) = duplex(1); + let (client_stdin, mut stdin) = duplex(64); + drop(client_stdin); + let status = bridge( + "test", + futures::stream::iter(vec![Ok(FailedSandbox)]), + &mut stdin, + &mut bridge_stdout, + &mut bridge_stderr, + client_lost(), + super::UnreadStdin::Keep, + ) + .await; + assert_eq!(status, 125); +}