Skip to content

Commit 1353fab

Browse files
committed
fix(sandbox): address review — PTY shell, command provenance, portable tests
- Interactive PTY SSH sessions now use the detected shell instead of a hardcoded /bin/bash. Extract build_ssh_shell_command, shared by the PTY and non-PTY paths, and add a deterministic sh-only regression test. - Track command provenance with MainProcessConfig::default_command instead of comparing the decoded spec against scratch(), so an explicit command matching the default shape is never rewritten. Add coverage. - Gate the Unix-only shell tests with cfg(unix) so the Windows workspace lane passes, and make the SHELL env test assert the detected shell rather than a hardcoded path. - Document the default-shell resolution in docs/sandboxes/manage-sandboxes. Refs NVIDIA#3146 Signed-off-by: Akram <[email protected]>
1 parent c37f287 commit 1353fab

6 files changed

Lines changed: 125 additions & 50 deletions

File tree

‎crates/openshell-core/src/sandbox_env.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ pub struct MainProcessConfig {
4242
pub tty: bool,
4343
#[serde(default)]
4444
pub await_main_process_attachment: bool,
45+
/// True when `command` is the built-in default rather than a user- or
46+
/// driver-supplied command. Only the default is eligible for shell
47+
/// remapping in the supervisor; an explicit command is never rewritten.
48+
#[serde(default)]
49+
pub default_command: bool,
4550
}
4651

4752
impl MainProcessConfig {
@@ -54,6 +59,7 @@ impl MainProcessConfig {
5459
command: vec!["/bin/bash".to_string(), "-l".to_string()],
5560
tty: true,
5661
await_main_process_attachment: false,
62+
default_command: true,
5763
}
5864
}
5965

@@ -65,6 +71,7 @@ impl MainProcessConfig {
6571
command: spec.command.clone(),
6672
tty: spec.tty,
6773
await_main_process_attachment: spec.await_main_process_attachment,
74+
default_command: false,
6875
},
6976
None | Some(_) => Self::scratch(),
7077
}
@@ -283,4 +290,30 @@ mod tests {
283290
let encoded = serde_json::to_string(&config).unwrap();
284291
assert_eq!(MainProcessConfig::decode(&encoded).unwrap(), config);
285292
}
293+
294+
#[test]
295+
fn default_command_flag_distinguishes_default_from_explicit() {
296+
// No user command → built-in default; eligible for shell remapping.
297+
let empty = crate::proto::compute::v1::DriverSandboxSpec::default();
298+
assert!(MainProcessConfig::from_driver_spec(Some(&empty)).default_command);
299+
assert!(MainProcessConfig::from_driver_spec(None).default_command);
300+
301+
// Explicit command that happens to match the default shape must NOT be
302+
// treated as the default, so it is never rewritten in the supervisor.
303+
let explicit = crate::proto::compute::v1::DriverSandboxSpec {
304+
command: vec!["/bin/bash".into(), "-l".into()],
305+
tty: true,
306+
..Default::default()
307+
};
308+
let config = MainProcessConfig::from_driver_spec(Some(&explicit));
309+
assert!(!config.default_command);
310+
let decoded = MainProcessConfig::decode(&serde_json::to_string(&config).unwrap()).unwrap();
311+
assert!(!decoded.default_command);
312+
313+
// A legacy spec without the field decodes as not-default (safe: no
314+
// surprising rewrite of an unknown command).
315+
let legacy =
316+
MainProcessConfig::decode(r#"{"version":1,"command":["/x"],"tty":false}"#).unwrap();
317+
assert!(!legacy.default_command);
318+
}
286319
}

‎crates/openshell-core/src/shell.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,12 @@ pub fn detect_login_shell() -> String {
7474
mod tests {
7575
use super::*;
7676

77+
// These assume a Unix root filesystem (`/bin/sh`, POSIX permission bits) and
78+
// are skipped on the Windows workspace lane where openshell-core also builds.
79+
#[cfg(unix)]
7780
#[test]
7881
fn posix_sh_exists_on_test_host() {
79-
// /bin/sh is present on all supported CI hosts (Linux and macOS).
82+
// /bin/sh is present on all supported Unix CI hosts (Linux and macOS).
8083
assert!(is_executable(POSIX_SH));
8184
}
8285

@@ -85,12 +88,14 @@ mod tests {
8588
assert!(!is_executable("/nonexistent/definitely/not/here"));
8689
}
8790

91+
#[cfg(unix)]
8892
#[test]
8993
fn non_file_is_not_executable() {
9094
// A directory is not an executable shell.
9195
assert!(!is_executable("/"));
9296
}
9397

98+
#[cfg(unix)]
9499
#[test]
95100
fn detect_returns_an_executable_shell() {
96101
let shell = detect_login_shell();

‎crates/openshell-sandbox/src/main.rs‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -667,24 +667,22 @@ fn main() -> Result<()> {
667667
} else if let Ok(json) = std::env::var(openshell_core::sandbox_env::MAIN_PROCESS_SPEC) {
668668
let config = openshell_core::sandbox_env::MainProcessConfig::decode(&json)
669669
.map_err(|error| miette::miette!("{error}"))?;
670-
// The driver bakes the built-in default (`scratch`) into the spec
671-
// when the user supplies no command. Detect that case so the
672-
// default shell can be resolved against the sandbox image below.
673-
let is_default =
674-
config == openshell_core::sandbox_env::MainProcessConfig::scratch();
670+
// `default_command` is set by the driver only when it baked the
671+
// built-in default (the user supplied no command); an explicit
672+
// command carries `false` and is never remapped below.
675673
(
676674
config.command,
677675
config.tty,
678676
config.await_main_process_attachment,
679-
is_default,
677+
config.default_command,
680678
)
681679
} else {
682680
let config = openshell_core::sandbox_env::MainProcessConfig::scratch();
683681
(
684682
config.command,
685683
config.tty,
686684
config.await_main_process_attachment,
687-
true,
685+
config.default_command,
688686
)
689687
};
690688

‎crates/openshell-supervisor-process/src/process.rs‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -910,16 +910,12 @@ impl ProcessHandle {
910910
#[cfg(target_os = "linux")]
911911
let mut child = spawn_command_with_supervisor_identity_namespace(cmd)
912912
.into_diagnostic()
913-
.wrap_err_with(|| {
914-
format!("failed to spawn sandbox entrypoint process '{program}'")
915-
})?;
913+
.wrap_err_with(|| format!("failed to spawn sandbox entrypoint process '{program}'"))?;
916914
#[cfg(not(target_os = "linux"))]
917915
let mut child = cmd
918916
.spawn()
919917
.into_diagnostic()
920-
.wrap_err_with(|| {
921-
format!("failed to spawn sandbox entrypoint process '{program}'")
922-
})?;
918+
.wrap_err_with(|| format!("failed to spawn sandbox entrypoint process '{program}'"))?;
923919
let pid = child.id().unwrap_or(0);
924920
managed_children::register(pid);
925921

@@ -2486,7 +2482,10 @@ mod tests {
24862482
Some(&current_user.dir.to_string_lossy().as_ref())
24872483
);
24882484
assert_eq!(variables.get("USER"), Some(&current_user.name.as_str()));
2489-
assert_eq!(variables.get("SHELL"), Some(&"/bin/bash"));
2485+
// SHELL is the shell detected in the current root filesystem, not a
2486+
// hardcoded path (bash-less images resolve to /bin/sh).
2487+
let expected_shell = openshell_core::shell::detect_login_shell();
2488+
assert_eq!(variables.get("SHELL"), Some(&expected_shell.as_str()));
24902489
assert_eq!(variables.get("TERM"), Some(&"xterm-256color"));
24912490
}
24922491

‎crates/openshell-supervisor-process/src/ssh.rs‎

Lines changed: 70 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1242,6 +1242,33 @@ const fn login_shell_flag(no_login_shell: bool) -> &'static str {
12421242
if no_login_shell { "-c" } else { "-lc" }
12431243
}
12441244

1245+
/// Build the shell command for an SSH session using a shell that exists in the
1246+
/// sandbox image (minimal images such as Alpine ship only `/bin/sh`, not bash).
1247+
///
1248+
/// `no_command_arg` is appended only when no explicit command is given: `-i`
1249+
/// for an interactive PTY session, or `None` for the non-PTY stdin path (a
1250+
/// bare shell already reads piped stdin line-by-line). With an explicit
1251+
/// command the login-shell flag is used per `no_login_shell`.
1252+
fn build_ssh_shell_command(
1253+
shell: &str,
1254+
command: Option<String>,
1255+
no_login_shell: bool,
1256+
no_command_arg: Option<&str>,
1257+
) -> Command {
1258+
let mut cmd = Command::new(shell);
1259+
match command {
1260+
None => {
1261+
if let Some(arg) = no_command_arg {
1262+
cmd.arg(arg);
1263+
}
1264+
}
1265+
Some(command) => {
1266+
cmd.arg(login_shell_flag(no_login_shell)).arg(command);
1267+
}
1268+
}
1269+
cmd
1270+
}
1271+
12451272
#[allow(clippy::too_many_arguments)]
12461273
fn spawn_pty_shell(
12471274
policy: &SandboxPolicy,
@@ -1276,18 +1303,11 @@ fn spawn_pty_shell(
12761303
let mut reader = master.try_clone()?;
12771304
let mut writer = master.try_clone()?;
12781305

1279-
let mut cmd = command.map_or_else(
1280-
|| {
1281-
let mut c = Command::new("/bin/bash");
1282-
c.arg("-i");
1283-
c
1284-
},
1285-
|command| {
1286-
let mut c = Command::new("/bin/bash");
1287-
c.arg(login_shell_flag(no_login_shell)).arg(command);
1288-
c
1289-
},
1290-
);
1306+
// Resolve a shell present in the sandbox image; interactive PTY sessions
1307+
// pass `-i` when no command is given. Runs in the supervisor, so it
1308+
// inspects the sandbox filesystem.
1309+
let shell = openshell_core::shell::detect_login_shell();
1310+
let mut cmd = build_ssh_shell_command(&shell, command, no_login_shell, Some("-i"));
12911311

12921312
let term = if pty.term.is_empty() {
12931313
"xterm-256color"
@@ -1437,27 +1457,13 @@ fn spawn_pipe_exec(
14371457
) -> anyhow::Result<mpsc::Sender<Vec<u8>>> {
14381458
// Resolve a shell present in the sandbox image; minimal images (e.g. Alpine)
14391459
// don't ship bash, only `/bin/sh`. Runs in the supervisor, so it inspects
1440-
// the sandbox filesystem.
1460+
// the sandbox filesystem. No command → read from stdin with no `-i`:
1461+
// interactive mode reads .bashrc, writes prompts to stderr, and can add
1462+
// just enough latency for VS Code Remote-SSH's platform detection to time
1463+
// out and fall back to "windows". A plain shell with piped stdin already
1464+
// reads commands line-by-line (script mode), which is what VS Code expects.
14411465
let shell = openshell_core::shell::detect_login_shell();
1442-
let mut cmd = command.map_or_else(
1443-
|| {
1444-
// No command — read from stdin. Do *not* pass `-i`; interactive
1445-
// mode reads .bashrc, writes prompts to stderr, and can introduce
1446-
// just enough latency for VS Code Remote-SSH's platform detection
1447-
// to time out and fall back to "windows". Plain shell with piped
1448-
// stdin already reads commands line-by-line (script mode), which is
1449-
// exactly what VS Code's local server expects.
1450-
Command::new(&shell)
1451-
},
1452-
|command| {
1453-
let mut c = Command::new(&shell);
1454-
// Login shell (-l) sources .profile/.bashrc so tool env vars
1455-
// (VIRTUAL_ENV, etc.) are available. Callers that need a predictable
1456-
// environment opt out via OPENSHELL_NO_LOGIN_SHELL → plain -c.
1457-
c.arg(login_shell_flag(no_login_shell)).arg(command);
1458-
c
1459-
},
1460-
);
1466+
let mut cmd = build_ssh_shell_command(&shell, command, no_login_shell, None);
14611467

14621468
let (session_user, session_home) = session_user_and_home(policy, workspace.home());
14631469
apply_child_env(
@@ -1801,8 +1807,40 @@ fn is_loopback_host(host: &str) -> bool {
18011807
)]
18021808
mod tests {
18031809
use super::*;
1810+
use std::ffi::OsStr;
18041811
use std::process::Stdio;
18051812

1813+
/// Regression test: SSH sessions run the shell they are given, never a
1814+
/// hardcoded bash, so sh-only images (e.g. Alpine) work. Covers both the
1815+
/// interactive PTY path (`-i` when no command) and the non-PTY path.
1816+
#[test]
1817+
fn build_ssh_shell_command_uses_given_shell() {
1818+
// PTY, no command → given shell + interactive flag.
1819+
let cmd = build_ssh_shell_command("/bin/sh", None, false, Some("-i"));
1820+
assert_eq!(cmd.get_program(), OsStr::new("/bin/sh"));
1821+
assert_eq!(cmd.get_args().collect::<Vec<_>>(), vec![OsStr::new("-i")]);
1822+
1823+
// Non-PTY, no command → bare shell, no args (reads piped stdin).
1824+
let cmd = build_ssh_shell_command("/bin/sh", None, false, None);
1825+
assert_eq!(cmd.get_program(), OsStr::new("/bin/sh"));
1826+
assert_eq!(cmd.get_args().count(), 0);
1827+
1828+
// Explicit command → login-shell flag + command, still on the given shell.
1829+
let cmd = build_ssh_shell_command("/bin/sh", Some("echo hi".into()), false, Some("-i"));
1830+
assert_eq!(cmd.get_program(), OsStr::new("/bin/sh"));
1831+
assert_eq!(
1832+
cmd.get_args().collect::<Vec<_>>(),
1833+
vec![OsStr::new("-lc"), OsStr::new("echo hi")]
1834+
);
1835+
1836+
// OPENSHELL_NO_LOGIN_SHELL → plain -c.
1837+
let cmd = build_ssh_shell_command("/bin/sh", Some("echo hi".into()), true, None);
1838+
assert_eq!(
1839+
cmd.get_args().collect::<Vec<_>>(),
1840+
vec![OsStr::new("-c"), OsStr::new("echo hi")]
1841+
);
1842+
}
1843+
18061844
/// Regression test: the direct-tcpip connect path sets `TCP_NODELAY`.
18071845
#[tokio::test]
18081846
async fn connect_in_netns_sets_tcp_nodelay() {

‎docs/sandboxes/manage-sandboxes.mdx‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,11 @@ openshell sandbox create -- claude
2323
The trailing command is the sandbox's canonical main process. OpenShell starts
2424
it once, streams its output, and returns its exit status. Exit code 0 leaves a
2525
retained sandbox in `Completed`; a nonzero exit leaves it in `Error` with a
26-
`MainProcessFailed` condition. With no trailing command, OpenShell
27-
starts `/bin/bash -l` in a retained pseudo-terminal. Add `--detach` to create
28-
the sandbox without attaching:
26+
`MainProcessFailed` condition. With no trailing command, OpenShell starts a
27+
login shell in a retained pseudo-terminal: `/bin/bash -l` when the image
28+
provides bash, otherwise a shell detected in the image such as `/bin/sh` on
29+
minimal bases like Alpine. Add `--detach` to create the sandbox without
30+
attaching:
2931

3032
```shell
3133
openshell sandbox create --name worker --detach -- ./worker

0 commit comments

Comments
 (0)