Skip to content
Open
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 @@ -1267,6 +1267,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 @@ -1373,6 +1377,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 @@ -2549,6 +2557,7 @@ async fn main() -> Result<()> {
auto_providers,
no_auto_providers,
labels,
envs,
approval_mode,
command,
} => {
Expand Down Expand Up @@ -2583,6 +2592,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 spec into (local_path, sandbox_path, git_ignore).
let upload_spec = upload.as_deref().map(|s| {
let (local, remote) = parse_upload_spec(s);
Expand Down Expand Up @@ -2618,6 +2630,7 @@ async fn main() -> Result<()> {
tty_override,
auto_providers_override,
&labels_map,
&env_map,
&approval_mode,
&tls,
))
Expand Down Expand Up @@ -2730,6 +2743,7 @@ async fn main() -> Result<()> {
timeout,
tty,
no_tty,
envs,
command,
} => {
let name = resolve_sandbox_name(name, &ctx.name)?;
Expand All @@ -2741,13 +2755,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
34 changes: 29 additions & 5 deletions crates/openshell-cli/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1689,6 +1689,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 @@ -1765,6 +1766,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 @@ -2557,13 +2559,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 @@ -2618,8 +2622,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 @@ -2628,7 +2639,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 @@ -2974,6 +2985,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 @@ -2989,7 +3001,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 @@ -3807,7 +3819,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 @@ -3826,6 +3838,18 @@ 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 key.starts_with("OPENSHELL_") {
return Err(miette::miette!(
"--env keys starting with OPENSHELL_ are reserved; got '{key}'"
));
}
}
Ok(map)
}

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,7 @@ async fn sandbox_create_keeps_command_sessions_by_default() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand Down Expand Up @@ -836,6 +837,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 @@ -913,6 +915,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 @@ -970,6 +973,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 @@ -1023,6 +1027,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 @@ -1068,6 +1073,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 @@ -1109,6 +1115,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 @@ -1154,6 +1161,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 @@ -1199,6 +1207,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 @@ -1244,6 +1253,7 @@ async fn sandbox_create_keeps_sandbox_with_forwarding() {
Some(false),
Some(false),
&HashMap::new(),
&HashMap::new(),
"manual",
&tls,
)
Expand All @@ -1252,3 +1262,81 @@ 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",
None,
true,
false,
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}"
);
}
7 changes: 7 additions & 0 deletions crates/openshell-core/src/sandbox_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ pub const SANDBOX_TOKEN: &str = "OPENSHELL_SANDBOX_TOKEN";
/// the token is held in process memory thereafter.
pub const SANDBOX_TOKEN_FILE: &str = "OPENSHELL_SANDBOX_TOKEN_FILE";

/// JSON-serialized map of user-specified environment variables.
///
/// Set by compute drivers from `SandboxSpec.environment`. The sandbox
/// supervisor deserializes this at startup and injects the variables into
/// SSH child processes (which use `env_clear()` for security isolation).
pub const USER_ENVIRONMENT: &str = "OPENSHELL_USER_ENVIRONMENT";
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agent analysis: In docker/podman/vm the trailing environment.extend(user_env) runs after inserting the sidecar, so a user var literally named OPENSHELL_USER_ENVIRONMENT clobbers the JSON sidecar → supervisor deserialization fails → all user env silently dropped. Edge case, but cheap to defend (reserve/reject the key, or
insert
the sidecar


/// Path to the projected `ServiceAccount` JWT (Kubernetes driver).
///
/// Used to bootstrap a gateway-minted JWT via `IssueSandboxToken`. Kubelet
Expand Down
1 change: 1 addition & 0 deletions crates/openshell-driver-docker/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ tokio-stream = { workspace = true }
tracing = { workspace = true }
bytes = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
bollard = { version = "0.20" }
tar = "0.4"
tempfile = "3"
Expand Down
14 changes: 12 additions & 2 deletions crates/openshell-driver-docker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1643,10 +1643,20 @@ fn build_environment(sandbox: &DriverSandbox, config: &DockerDriverRuntimeConfig
]);

if let Some(spec) = sandbox.spec.as_ref() {
let mut user_env = HashMap::new();
if let Some(template) = spec.template.as_ref() {
environment.extend(template.environment.clone());
user_env.extend(template.environment.clone());
}
user_env.extend(spec.environment.clone());
environment.extend(user_env.clone());
if !user_env.is_empty()
&& let Ok(json) = serde_json::to_string(&user_env)
{
environment.insert(
openshell_core::sandbox_env::USER_ENVIRONMENT.to_string(),
json,
);
}
environment.extend(spec.environment.clone());
}

environment.insert(
Expand Down
Loading
Loading