Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions crates/openshell-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1275,6 +1275,10 @@ enum SandboxCommands {
#[arg(long = "label")]
labels: Vec<String>,

/// Environment variables to inject into the sandbox (KEY=VALUE format, repeatable).
#[arg(long = "env", value_name = "KEY=VALUE")]
envs: Vec<String>,

/// Approval mode for agent-authored policy proposals.
///
/// `manual` (default): every proposal lands in the draft inbox for
Expand Down Expand Up @@ -1381,6 +1385,10 @@ enum SandboxCommands {
#[arg(long, overrides_with = "tty")]
no_tty: bool,

/// Environment variables to set for the command (KEY=VALUE format, repeatable).
#[arg(long = "env", value_name = "KEY=VALUE")]
envs: Vec<String>,

/// Command and arguments to execute.
#[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
command: Vec<String>,
Expand Down Expand Up @@ -2558,6 +2566,7 @@ async fn main() -> Result<()> {
auto_providers,
no_auto_providers,
labels,
envs,
approval_mode,
command,
} => {
Expand Down Expand Up @@ -2592,6 +2601,9 @@ async fn main() -> Result<()> {
labels_map.insert(parts[0].to_string(), parts[1].to_string());
}

// Parse --env flags into a HashMap<String, String>.
let env_map = run::parse_env_pairs(&envs)?;

// Parse --upload specs into [(local_path, sandbox_path, git_ignore)].
let upload_specs: Vec<(String, Option<String>, bool)> = upload
.iter()
Expand Down Expand Up @@ -2639,6 +2651,7 @@ async fn main() -> Result<()> {
tty_override,
auto_providers_override,
&labels_map,
&env_map,
&approval_mode,
&tls,
))
Expand Down Expand Up @@ -2751,6 +2764,7 @@ async fn main() -> Result<()> {
timeout,
tty,
no_tty,
envs,
command,
} => {
let name = resolve_sandbox_name(name, &ctx.name)?;
Expand All @@ -2762,13 +2776,15 @@ async fn main() -> Result<()> {
} else {
None // auto-detect
};
let env_map = run::parse_env_pairs(&envs)?;
let exit_code = run::sandbox_exec_grpc(
endpoint,
&name,
&command,
workdir.as_deref(),
timeout,
tty_override,
&env_map,
&tls,
)
.await?;
Expand Down
50 changes: 45 additions & 5 deletions crates/openshell-cli/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1756,6 +1756,7 @@ pub async fn sandbox_create(
tty_override: Option<bool>,
auto_providers_override: Option<bool>,
labels: &HashMap<String, String>,
environment: &HashMap<String, String>,
approval_mode: &str,
tls: &TlsOptions,
) -> Result<()> {
Expand Down Expand Up @@ -1836,6 +1837,7 @@ pub async fn sandbox_create(
spec: Some(SandboxSpec {
gpu: requested_gpu,
gpu_device: gpu_device.unwrap_or_default().to_string(),
environment: environment.clone(),
policy,
providers: configured_providers,
template,
Expand Down Expand Up @@ -2638,13 +2640,15 @@ const MAX_STDIN_PAYLOAD: usize = 4 * 1024 * 1024;
/// Execute a command in a running sandbox via gRPC, streaming output to the terminal.
///
/// Returns the remote command's exit code.
#[allow(clippy::too_many_arguments, clippy::implicit_hasher)]
pub async fn sandbox_exec_grpc(
server: &str,
name: &str,
command: &[String],
workdir: Option<&str>,
timeout_seconds: u32,
tty_override: Option<bool>,
environment: &HashMap<String, String>,
tls: &TlsOptions,
) -> Result<i32> {
let mut client = grpc_client(server, tls).await?;
Expand Down Expand Up @@ -2699,8 +2703,15 @@ pub async fn sandbox_exec_grpc(
.unwrap_or_else(|| std::io::stdin().is_terminal() && std::io::stdout().is_terminal());

if tty_override == Some(true) && std::io::stdin().is_terminal() {
return sandbox_exec_interactive_grpc(client, &sandbox, command, workdir, timeout_seconds)
.await;
return sandbox_exec_interactive_grpc(
client,
&sandbox,
command,
workdir,
timeout_seconds,
environment,
)
.await;
}

// Make the streaming gRPC call.
Expand All @@ -2709,7 +2720,7 @@ pub async fn sandbox_exec_grpc(
sandbox_id: sandbox.object_id().to_string(),
command: command.to_vec(),
workdir: workdir.unwrap_or_default().to_string(),
environment: HashMap::new(),
environment: environment.clone(),
timeout_seconds,
stdin: stdin_payload,
tty,
Expand Down Expand Up @@ -3055,6 +3066,7 @@ async fn sandbox_exec_interactive_grpc(
command: &[String],
workdir: Option<&str>,
timeout_seconds: u32,
environment: &HashMap<String, String>,
) -> Result<i32> {
use openshell_core::proto::{ExecSandboxInput, ExecSandboxWindowResize, exec_sandbox_input};
use tokio_stream::wrappers::ReceiverStream;
Expand All @@ -3070,7 +3082,7 @@ async fn sandbox_exec_interactive_grpc(
sandbox_id: sandbox.object_id().to_string(),
command: command.to_vec(),
workdir: workdir.unwrap_or_default().to_string(),
environment: HashMap::new(),
environment: environment.clone(),
timeout_seconds,
stdin: Vec::new(),
tty: true,
Expand Down Expand Up @@ -3888,7 +3900,7 @@ async fn auto_create_provider(
Ok(())
}

fn parse_key_value_pairs(items: &[String], flag: &str) -> Result<HashMap<String, String>> {
pub fn parse_key_value_pairs(items: &[String], flag: &str) -> Result<HashMap<String, String>> {
let mut map = HashMap::new();

for item in items {
Expand All @@ -3907,6 +3919,34 @@ fn parse_key_value_pairs(items: &[String], flag: &str) -> Result<HashMap<String,
Ok(map)
}

pub fn parse_env_pairs(items: &[String]) -> Result<HashMap<String, String>> {
let map = parse_key_value_pairs(items, "--env")?;
for key in map.keys() {
if !is_valid_env_name(key) {
return Err(miette::miette!(
"--env key must match [A-Za-z_][A-Za-z0-9_]*; got '{key}'"
));
}
if key.starts_with("OPENSHELL_") {
return Err(miette::miette!(
"--env keys starting with OPENSHELL_ are reserved; got '{key}'"
));
}
}
Ok(map)
}

fn is_valid_env_name(key: &str) -> bool {
let mut bytes = key.bytes();
let Some(first) = bytes.next() else {
return false;
};
if !(first == b'_' || first.is_ascii_alphabetic()) {
return false;
}
bytes.all(|b| b == b'_' || b.is_ascii_alphanumeric())
}

fn parse_credential_pairs(items: &[String]) -> Result<HashMap<String, String>> {
let mut map = HashMap::new();

Expand Down
107 changes: 107 additions & 0 deletions crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,7 @@ async fn sandbox_create_keeps_command_sessions_by_default() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -838,6 +839,7 @@ async fn sandbox_create_sends_cpu_and_memory_limits_only() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -915,6 +917,7 @@ async fn sandbox_create_sends_driver_config_json() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -989,6 +992,7 @@ async fn sandbox_create_does_not_infer_command_providers_when_v2_enabled() {
Some(true),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -1047,6 +1051,7 @@ async fn sandbox_create_returns_vm_error_without_waiting_for_timeout() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -1101,6 +1106,7 @@ async fn sandbox_create_keeps_waiting_while_vm_progress_arrives() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -1147,6 +1153,7 @@ async fn sandbox_create_times_out_when_only_logs_arrive() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -1189,6 +1196,7 @@ async fn sandbox_create_deletes_command_sessions_with_no_keep() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -1235,6 +1243,7 @@ async fn sandbox_create_deletes_shell_sessions_with_no_keep() {
Some(true),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -1281,6 +1290,7 @@ async fn sandbox_create_keeps_sandbox_with_hidden_keep_flag() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -1327,6 +1337,7 @@ async fn sandbox_create_keeps_sandbox_with_forwarding() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand All @@ -1335,3 +1346,99 @@ async fn sandbox_create_keeps_sandbox_with_forwarding() {

assert!(deleted_names(&server).await.is_empty());
}

#[tokio::test]
async fn sandbox_create_sends_environment_variables() {
let server = run_server().await;
let fake_ssh_dir = tempfile::tempdir().unwrap();
let xdg_dir = tempfile::tempdir().unwrap();
let _env = test_env(&fake_ssh_dir, &xdg_dir);
let tls = test_tls(&server);
install_fake_ssh(&fake_ssh_dir);

let mut env_map = HashMap::new();
env_map.insert("FOO".to_string(), "bar".to_string());
env_map.insert("BAZ".to_string(), "qux=with=equals".to_string());

run::sandbox_create(
&server.endpoint,
Some("env-test"),
None,
"openshell",
&[],
true,
false,
None,
None,
None,
None,
None,
&[],
None,
None,
&["echo".to_string(), "OK".to_string()],
Some(false),
Some(false),
&HashMap::new(),
&env_map,
"manual",
&tls,
)
.await
.expect("sandbox create should succeed");

let requests = create_requests(&server).await;
let environment = &requests[0]
.spec
.as_ref()
.expect("spec should be present")
.environment;
assert_eq!(environment.get("FOO").map(String::as_str), Some("bar"));
assert_eq!(
environment.get("BAZ").map(String::as_str),
Some("qux=with=equals")
);
assert_eq!(environment.len(), 2);
}

#[tokio::test]
async fn sandbox_create_env_rejects_invalid_format() {
let err = run::parse_key_value_pairs(
&["VALID=ok".to_string(), "NOEQUALSSIGN".to_string()],
"--env",
)
.unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains("--env") && msg.contains("NOEQUALSSIGN"),
"error should mention the flag and bad value, got: {msg}"
);
}

#[tokio::test]
async fn sandbox_create_env_rejects_reserved_prefix() {
let err = run::parse_env_pairs(&["VALID=ok".to_string(), "OPENSHELL_SECRET=bad".to_string()])
.unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains("OPENSHELL_") && msg.contains("reserved"),
"error should mention reserved prefix, got: {msg}"
);
}

#[tokio::test]
async fn sandbox_create_env_rejects_invalid_key_name() {
let err = run::parse_env_pairs(&["1BAD=value".to_string()]).unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains("1BAD"),
"error should mention invalid key, got: {msg}"
);

let err = run::parse_env_pairs(&["BAD-NAME=value".to_string()]).unwrap_err();
let msg = format!("{err}");
assert!(
msg.contains("BAD-NAME"),
"error should mention invalid key, got: {msg}"
);
}
Loading
Loading