Enable remote Bash snapshot reuse

This commit is contained in:
Vaibhav Srivastav
2026-06-24 19:31:57 +01:00
parent e351f974f6
commit 4989218088
8 changed files with 775 additions and 33 deletions
+1
View File
@@ -40,6 +40,7 @@ pub(crate) struct ExecOptions {
pub(crate) struct ExecServerEnvConfig {
pub(crate) policy: codex_exec_server::ExecEnvPolicy,
pub(crate) local_policy_env: HashMap<String, String>,
pub(crate) bash_env_snapshot: Option<codex_exec_server::BashEnvSnapshotParams>,
}
#[derive(Debug)]
@@ -65,7 +65,8 @@ fn test_get_command_uses_default_shell_when_unspecified() -> anyhow::Result<()>
}
#[test]
fn test_get_command_respects_explicit_bash_shell() -> anyhow::Result<()> {
#[cfg(unix)]
fn test_get_command_uses_non_login_bash_when_login_shell_is_disabled() -> anyhow::Result<()> {
let json = r#"{"cmd": "echo hello", "shell": "/bin/bash"}"#;
let args: ExecCommandArgs = parse_arguments(json)?;
@@ -76,18 +77,12 @@ fn test_get_command_respects_explicit_bash_shell() -> anyhow::Result<()> {
&args,
Arc::new(default_user_shell()),
&UnifiedExecShellMode::Direct,
/*allow_login_shell*/ true,
/*allow_login_shell*/ false,
)
.map_err(anyhow::Error::msg)?;
let command = resolved.command;
assert_eq!(command.last(), Some(&"echo hello".to_string()));
if command
.iter()
.any(|arg| arg.eq_ignore_ascii_case("-Command"))
{
assert!(command.contains(&"-NoProfile".to_string()));
}
assert_eq!(command, ["/bin/bash", "-c", "echo hello"]);
Ok(())
}
@@ -23,6 +23,7 @@ use crate::tools::runtimes::RuntimePathPrepends;
use crate::tools::runtimes::apply_zsh_fork_path_prepend;
use crate::tools::runtimes::disable_powershell_profile_for_elevated_windows_sandbox;
use crate::tools::runtimes::exec_env_for_sandbox_permissions;
use crate::tools::runtimes::is_managed_proxy_env_var;
use crate::tools::runtimes::maybe_wrap_shell_lc_with_snapshot;
use crate::tools::runtimes::shell::zsh_fork_backend;
use crate::tools::sandboxing::Approvable;
@@ -43,6 +44,7 @@ use crate::unified_exec::UnifiedExecProcess;
use crate::unified_exec::UnifiedExecProcessManager;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxy;
use codex_network_proxy::PROXY_ACTIVE_ENV_KEY;
use codex_protocol::error::CodexErr;
use codex_protocol::error::SandboxErr;
use codex_protocol::models::AdditionalPermissionProfile;
@@ -134,6 +136,38 @@ fn build_unified_exec_sandbox_command(
})
}
fn remote_bash_env_snapshot_params(
req: &UnifiedExecRequest,
command: &SandboxCommand,
) -> Option<codex_exec_server::BashEnvSnapshotParams> {
if !req.turn_environment.environment.is_remote() || req.shell_type != ShellType::Bash {
return None;
}
if command.args.first().map(String::as_str) != Some("-c") {
return None;
}
let mut preserve_env_keys = req
.explicit_env_overrides
.keys()
.cloned()
.collect::<Vec<_>>();
if command.env.contains_key(PROXY_ACTIVE_ENV_KEY) {
preserve_env_keys.extend(
command
.env
.iter()
.filter(|(key, value)| is_managed_proxy_env_var(key, value))
.map(|(key, _)| key.clone()),
);
}
preserve_env_keys.sort_unstable();
preserve_env_keys.dedup();
Some(codex_exec_server::BashEnvSnapshotParams {
workspace_root: req.turn_environment.cwd().clone(),
preserve_env_keys,
})
}
impl<'a> UnifiedExecRuntime<'a> {
/// Creates a runtime bound to the shared unified-exec process manager.
pub fn new(manager: &'a UnifiedExecProcessManager, shell_mode: UnifiedExecShellMode) -> Self {
@@ -469,6 +503,10 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
}
error @ ToolError::Codex(_) => error,
})?;
let mut exec_server_env_config = req.exec_server_env_config.clone();
if let Some(config) = exec_server_env_config.as_mut() {
config.bash_env_snapshot = remote_bash_env_snapshot_params(req, &command);
}
let options = unified_exec_options(attempt.network_denial_cancellation_token.clone());
self.manager
.open_session_with_exec_env(
@@ -478,7 +516,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
attempt,
managed_network,
/*environment_id*/ Some(&req.turn_environment.environment_id),
req.exec_server_env_config.clone(),
exec_server_env_config,
req.tty,
Box::new(NoopSpawnLifecycle),
req.turn_environment.environment.as_ref(),
@@ -551,6 +589,62 @@ mod tests {
assert_ne!(original_key, other_key);
}
#[tokio::test]
async fn remote_bash_c_requests_workspace_snapshot_reuse() {
let mut request = test_request(
SandboxPermissions::UseDefault,
ExecApprovalRequirement::Skip {
bypass_sandbox: false,
proposed_execpolicy_amendment: None,
},
);
request.shell_type = ShellType::Bash;
request.turn_environment = TurnEnvironment::new(
"remote".to_string(),
Arc::new(
Environment::create_for_tests(Some("ws://127.0.0.1:1".to_string()))
.expect("remote environment"),
),
request.cwd.clone(),
/*shell*/ None,
);
request.explicit_env_overrides =
HashMap::from([("OVERRIDE".to_string(), "explicit".to_string())]);
let mut command = SandboxCommand {
program: "bash".into(),
args: vec!["-c".to_string(), "echo ok".to_string()],
cwd: request.cwd.clone(),
env: HashMap::from([
(PROXY_ACTIVE_ENV_KEY.to_string(), "1".to_string()),
(
"HTTPS_PROXY".to_string(),
"http://127.0.0.1:1234".to_string(),
),
]),
managed_network: None,
additional_permissions: None,
};
assert_eq!(
remote_bash_env_snapshot_params(&request, &command),
Some(codex_exec_server::BashEnvSnapshotParams {
workspace_root: request.cwd.clone(),
preserve_env_keys: vec![
PROXY_ACTIVE_ENV_KEY.to_string(),
"HTTPS_PROXY".to_string(),
"OVERRIDE".to_string(),
],
})
);
command.args[0] = "-lc".to_string();
assert_eq!(remote_bash_env_snapshot_params(&request, &command), None);
command.args[0] = "-c".to_string();
request.shell_type = ShellType::Zsh;
assert_eq!(remote_bash_env_snapshot_params(&request, &command), None);
}
#[tokio::test]
async fn unified_exec_uses_the_trusted_sandbox_cwd() {
let cwd_dir = tempdir().expect("create process temp dir");
@@ -183,7 +183,10 @@ fn exec_server_params_for_request(
sandbox: request.exec_server_sandbox.clone(),
enforce_managed_network: request.exec_server_enforce_managed_network,
managed_network: request.exec_server_managed_network.clone(),
bash_env_snapshot: None,
bash_env_snapshot: request
.exec_server_env_config
.as_ref()
.and_then(|config| config.bash_env_snapshot.clone()),
}
}
@@ -1117,6 +1120,7 @@ impl UnifiedExecProcessManager {
&context.turn.config.permissions.shell_environment_policy,
),
local_policy_env,
bash_env_snapshot: None,
};
let mut orchestrator = ToolOrchestrator::new();
let mut runtime = UnifiedExecRuntime::new(self, request.shell_mode.clone());
@@ -81,6 +81,10 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
loopback_ports: vec![43123],
allow_local_binding: false,
};
let bash_env_snapshot = codex_exec_server::BashEnvSnapshotParams {
workspace_root: cwd.clone().into(),
preserve_env_keys: vec!["PATH".to_string()],
};
let mut request = ExecRequest {
command: vec!["bash".to_string(), "-lc".to_string(), "true".to_string()],
cwd: cwd.clone().into(),
@@ -119,6 +123,7 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
"/client/custom-ca.pem".to_string(),
),
]),
bash_env_snapshot: Some(bash_env_snapshot.clone()),
}),
network: None,
network_environment_id: None,
@@ -146,6 +151,7 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
assert_eq!(params.cwd, request.cwd);
assert!(params.enforce_managed_network);
assert_eq!(params.managed_network, Some(managed_network));
assert_eq!(params.bash_env_snapshot, Some(bash_env_snapshot));
assert!(params.env_policy.is_some());
assert_eq!(
params.env,
+192 -22
View File
@@ -5,11 +5,20 @@ use codex_core::compact::SUMMARIZATION_PROMPT;
use codex_core::config::Constrained;
use codex_exec_server::CopyOptions;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::ExecParams;
use codex_exec_server::FileSystemSandboxContext;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_exec_server::REMOTE_ENVIRONMENT_ID;
use codex_exec_server::RemoveOptions;
use codex_features::Feature;
#[cfg(target_os = "macos")]
use codex_network_proxy::CODEX_PROXY_GIT_SSH_COMMAND_MARKER;
use codex_network_proxy::CUSTOM_CA_ENV_KEYS;
use codex_network_proxy::PROXY_ENV_KEYS;
#[cfg(target_os = "macos")]
use codex_network_proxy::PROXY_GIT_SSH_COMMAND_ENV_KEY;
use codex_network_proxy::is_managed_mitm_ca_trust_bundle_path;
use codex_protocol::config_types::ShellEnvironmentPolicyInherit;
use codex_protocol::models::FileSystemPermissions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
@@ -315,6 +324,102 @@ async fn explicit_remote_shell_runs_in_remote_cwd() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_bash_c_forwards_workspace_snapshot_request() -> Result<()> {
const CALL_ID: &str = "remote-bash-snapshot";
let listener = TcpListener::bind("127.0.0.1:0").await?;
let exec_server_url = format!("ws://{}", listener.local_addr()?);
let captured = tokio::spawn(serve_captured_exec(listener));
let server = start_mock_server().await;
let arguments = serde_json::to_string(&json!({
"cmd": "printf ok",
"yield_time_ms": 1_000,
}))?;
let _response_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call(CALL_ID, "exec_command", &arguments),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
let mut builder = test_codex()
.with_exec_server_url(exec_server_url)
.with_config(|config| {
config.use_experimental_unified_exec_tool = true;
config.permissions.allow_login_shell = false;
config.permissions.shell_environment_policy.inherit =
ShellEnvironmentPolicyInherit::None;
config
.permissions
.shell_environment_policy
.r#set
.insert("OVERRIDE".to_string(), "explicit".to_string());
assert!(config.features.enable(Feature::UnifiedExec).is_ok());
});
let test = builder.build(&server).await?;
test.submit_turn("run the remote bash command").await?;
let params = timeout(Duration::from_secs(5), captured)
.await
.context("exec-server should receive process/start")??;
let cwd = PathUri::from_abs_path(&test.config.cwd);
assert_eq!(params.argv, ["/bin/bash", "-c", "printf ok"]);
assert_eq!(params.cwd, cwd);
assert!(!params.tty);
let policy = params.env_policy.as_ref().context("env policy")?;
assert_eq!(policy.inherit, ShellEnvironmentPolicyInherit::None);
assert!(policy.ignore_default_excludes);
assert!(policy.exclude.is_empty());
assert!(policy.include_only.is_empty());
assert_eq!(
policy.r#set,
HashMap::from([("OVERRIDE".to_string(), "explicit".to_string())])
);
let snapshot = params
.bash_env_snapshot
.as_ref()
.context("workspace Bash snapshot request")?;
assert_eq!(snapshot.workspace_root, cwd);
assert!(
snapshot
.preserve_env_keys
.iter()
.any(|key| key == "OVERRIDE")
);
for key in snapshot
.preserve_env_keys
.iter()
.filter(|key| key.as_str() != "OVERRIDE")
{
let value = params.env.get(key).context("preserved env value")?;
let mac_managed = {
#[cfg(target_os = "macos")]
{
key == PROXY_GIT_SSH_COMMAND_ENV_KEY
&& value.starts_with(CODEX_PROXY_GIT_SSH_COMMAND_MARKER)
}
#[cfg(not(target_os = "macos"))]
false
};
let managed = PROXY_ENV_KEYS.contains(&key.as_str())
|| (CUSTOM_CA_ENV_KEYS.contains(&key.as_str())
&& is_managed_mitm_ca_trust_bundle_path(value))
|| mac_managed;
assert!(managed, "unexpected preserved env key: {key}");
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deferred_executor_does_not_duplicate_initial_environment_context() -> Result<()> {
let server = start_mock_server().await;
@@ -366,39 +471,104 @@ async fn read_exec_server_json(websocket: &mut WebSocketStream<TcpStream>) -> Va
}
}
async fn serve_environment_info(listener: TcpListener) {
async fn send_exec_server_result(
websocket: &mut WebSocketStream<TcpStream>,
id: &Value,
result: Value,
) {
websocket
.send(Message::Text(
json!({ "id": id, "result": result }).to_string().into(),
))
.await
.expect("exec-server response");
}
async fn send_exec_server_not_found(websocket: &mut WebSocketStream<TcpStream>, id: &Value) {
websocket
.send(Message::Text(
json!({
"id": id,
"error": { "code": -32004, "message": "not found" }
})
.to_string()
.into(),
))
.await
.expect("exec-server not-found response");
}
async fn initialize_exec_server(listener: TcpListener, shell: &str) -> WebSocketStream<TcpStream> {
let (stream, _) = listener.accept().await.expect("connection");
let mut websocket = accept_async(stream).await.expect("websocket handshake");
let initialize = read_exec_server_json(&mut websocket).await;
assert_eq!(initialize["method"], "initialize");
websocket
.send(Message::Text(
json!({
"id": initialize["id"],
"result": { "sessionId": "test-session" }
})
.to_string()
.into(),
))
.await
.expect("initialize response");
send_exec_server_result(
&mut websocket,
&initialize["id"],
json!({ "sessionId": "test-session" }),
)
.await;
let initialized = read_exec_server_json(&mut websocket).await;
assert_eq!(initialized["method"], "initialized");
let info = read_exec_server_json(&mut websocket).await;
assert_eq!(info["method"], "environment/info");
send_exec_server_result(
&mut websocket,
&info["id"],
json!({ "shell": { "name": shell, "path": format!("/bin/{shell}") } }),
)
.await;
websocket
.send(Message::Text(
json!({
"id": info["id"],
"result": { "shell": { "name": "zsh", "path": "/bin/zsh" } }
})
.to_string()
.into(),
))
.await
.expect("environment info response");
}
async fn serve_environment_info(listener: TcpListener) {
let _websocket = initialize_exec_server(listener, "zsh").await;
}
async fn serve_captured_exec(listener: TcpListener) -> ExecParams {
let mut websocket = initialize_exec_server(listener, "bash").await;
let start = loop {
let request = read_exec_server_json(&mut websocket).await;
match request["method"].as_str() {
Some("fs/canonicalize") => {
send_exec_server_result(
&mut websocket,
&request["id"],
json!({ "path": request["params"]["path"] }),
)
.await;
}
Some("fs/getMetadata") => {
send_exec_server_not_found(&mut websocket, &request["id"]).await;
}
Some("process/start") => break request,
other => panic!("unexpected exec-server request: {other:?}"),
}
};
let params: ExecParams =
serde_json::from_value(start["params"].clone()).expect("process/start params");
send_exec_server_result(
&mut websocket,
&start["id"],
json!({ "processId": params.process_id.as_str() }),
)
.await;
let read = read_exec_server_json(&mut websocket).await;
assert_eq!(read["method"], "process/read");
send_exec_server_result(
&mut websocket,
&read["id"],
json!({
"chunks": [], "nextSeq": 1, "exited": true, "exitCode": 0,
"closed": true, "failure": null, "sandboxDenied": false
}),
)
.await;
params
}
fn tool_names(body: &Value) -> Vec<String> {
@@ -0,0 +1,468 @@
use codex_protocol::config_types::ShellEnvironmentPolicyInherit;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::fs;
use std::os::unix::fs::MetadataExt;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::fs::symlink;
use std::path::Path;
use std::sync::Arc;
use super::*;
use crate::ProcessId;
use crate::protocol::BashEnvSnapshotParams;
use crate::protocol::ExecEnvPolicy;
struct Fixture {
_temp: tempfile::TempDir,
workspace: PathBuf,
bash_env: PathBuf,
counter: PathBuf,
}
fn fixture() -> Fixture {
let temp = tempfile::tempdir().expect("tempdir");
let workspace = temp.path().join("workspace");
fs::create_dir(&workspace).expect("create workspace");
Fixture {
bash_env: workspace.join("bash_env.sh"),
counter: temp.path().join("counter"),
workspace,
_temp: temp,
}
}
fn startup(fixture: &Fixture, sleep: bool) -> String {
format!(
"printf 'x\\n' >> '{counter}'\n\
TOKEN=ready; SNAPSHOT_ARRAY=(zero one); INTEGER_ARRAY=(0012); declare -airx INTEGER_ARRAY; if (( BASH_VERSINFO[0] >= 4 )); then declare -A ASSOCIATIVE_ARRAY=([key]=assoc); fi; READONLY_TOKEN=locked; readonly READONLY_TOKEN\n\
export SNAPSHOT_SENTINEL=ready OVERRIDE=from-startup\n\
export PATH='{workspace}/bin':\"$PATH\"\n\
snapshot_func() {{ printf %s \"$TOKEN\"; }}; export -f snapshot_func; readonly -f snapshot_func\n{sleep}\n",
counter = fixture.counter.display(),
workspace = fixture.workspace.display(),
sleep = if sleep { "sleep 0.1" } else { ":" },
)
}
fn capture_count(fixture: &Fixture) -> usize {
fs::read_to_string(&fixture.counter)
.expect("counter")
.lines()
.count()
}
fn params(fixture: &Fixture, script: &str) -> ExecParams {
let workspace = PathUri::from_host_native_path(&fixture.workspace).expect("workspace URI");
ExecParams {
process_id: ProcessId::from("snapshot-test"),
argv: vec![
"/bin/bash".to_string(),
"-c".to_string(),
script.to_string(),
],
cwd: workspace.clone(),
env_policy: None,
env: HashMap::from([
(
"BASH_ENV".to_string(),
fixture.bash_env.to_string_lossy().into_owned(),
),
(
"PATH".to_string(),
std::env::var("PATH").unwrap_or_default() + ":/usr/bin:/bin",
),
("BASH_FUNC_return%%".to_string(), "() { :; }".to_string()),
("OVERRIDE".to_string(), "explicit".to_string()),
]),
tty: false,
pipe_stdin: false,
arg0: None,
sandbox: None,
enforce_managed_network: false,
managed_network: None,
bash_env_snapshot: Some(BashEnvSnapshotParams {
workspace_root: workspace,
preserve_env_keys: vec!["OVERRIDE".to_string()],
}),
}
}
async fn prepare(
cache: &BashEnvSnapshotCache,
params: &ExecParams,
) -> (Vec<String>, HashMap<String, String>) {
cache
.prepare_launch(params, &params.env, /*runtime_paths*/ None)
.await
}
async fn assert_fallback(cache: &BashEnvSnapshotCache, params: ExecParams) {
let prepared = prepare(cache, &params).await;
assert_eq!(prepared, (params.argv, params.env));
}
async fn run(argv: &[String], env: &HashMap<String, String>, cwd: &Path) -> std::process::Output {
tokio::process::Command::new(&argv[0])
.args(&argv[1..])
.current_dir(cwd)
.env_clear()
.envs(env)
.output()
.await
.expect("run command")
}
fn snapshot_path(cache: &BashEnvSnapshotCache) -> PathBuf {
fs::read_dir(cache.root.as_ref().expect("snapshot root").path())
.expect("snapshot directory")
.map(|entry| entry.expect("entry").path())
.find(|path| path.extension().is_some_and(|ext| ext == "sh"))
.expect("snapshot")
}
#[tokio::test]
async fn scopes_and_invalidates_cache_across_workspace_config_and_reconnect() {
let fixture = fixture();
fs::write(&fixture.bash_env, startup(&fixture, /*sleep*/ false)).expect("write BASH_ENV");
let cache = BashEnvSnapshotCache::default();
let base = params(&fixture, "true");
prepare(&cache, &base).await;
prepare(&cache, &base).await;
assert_eq!(capture_count(&fixture), 1);
let root = cache.root.as_ref().expect("snapshot root").path();
assert_eq!(
fs::metadata(root).expect("root metadata").mode() & 0o777,
0o700
);
assert_eq!(
fs::metadata(snapshot_path(&cache))
.expect("metadata")
.mode()
& 0o777,
0o600
);
let mut changed = base.clone();
changed.env_policy = Some(ExecEnvPolicy {
inherit: ShellEnvironmentPolicyInherit::All,
ignore_default_excludes: false,
exclude: Vec::new(),
r#set: HashMap::from([
("SECOND".to_string(), "2".to_string()),
("FIRST".to_string(), "1".to_string()),
]),
include_only: Vec::new(),
});
let mut equivalent = changed.clone();
equivalent.env_policy.as_mut().expect("policy").r#set = HashMap::from([
("FIRST".to_string(), "1".to_string()),
("SECOND".to_string(), "2".to_string()),
]);
assert_eq!(
BashEnvSnapshotRequest::new(&changed, &changed.env)
.expect("scope")
.key,
BashEnvSnapshotRequest::new(&equivalent, &equivalent.env)
.expect("equivalent scope")
.key,
);
prepare(&cache, &changed).await;
fs::write(
&fixture.bash_env,
format!("{}# setup changed\n", startup(&fixture, /*sleep*/ false)),
)
.expect("change BASH_ENV");
prepare(&cache, &base).await;
let shell_dir = fixture._temp.path().join("shell");
fs::create_dir(&shell_dir).expect("create shell dir");
let alternate_shell = shell_dir.join("bash");
symlink("/bin/bash", &alternate_shell).expect("link bash");
changed = base.clone();
changed.argv[0] = alternate_shell.to_string_lossy().into_owned();
prepare(&cache, &changed).await;
let second_workspace = fixture._temp.path().join("second");
fs::create_dir(&second_workspace).expect("create second workspace");
changed.cwd = PathUri::from_host_native_path(&second_workspace).expect("second URI");
changed
.bash_env_snapshot
.as_mut()
.expect("snapshot params")
.workspace_root = changed.cwd.clone();
prepare(&cache, &changed).await;
cache.clear();
prepare(&cache, &changed).await;
assert_eq!(capture_count(&fixture), 6);
let mut descendant = base.clone();
let nested = fixture.workspace.join("nested");
fs::create_dir(&nested).expect("create nested cwd");
descendant.cwd = PathUri::from_host_native_path(&nested).expect("nested URI");
prepare(&cache, &descendant).await;
assert_eq!(capture_count(&fixture), 7);
let mut outside = base;
outside.cwd = PathUri::from_host_native_path(fixture._temp.path()).expect("outside URI");
assert_fallback(&cache, outside).await;
assert_eq!(capture_count(&fixture), 7);
}
#[tokio::test]
async fn failures_oversize_and_corruption_fall_back_to_bash_env() {
let fixture = fixture();
let cache = BashEnvSnapshotCache::default();
fs::write(&fixture.bash_env, "exit 17\n").expect("write failure");
let failure = params(&fixture, "true");
assert_fallback(&cache, failure.clone()).await;
let mut unsupported = failure.clone();
unsupported.argv[0] = "/bin/sh".to_string();
assert_fallback(&cache, unsupported).await;
let mut oversized_env = failure.clone();
oversized_env
.env
.insert("LARGE".to_string(), "x".repeat(MAX_ENV_BYTES + 1));
assert_fallback(&cache, oversized_env).await;
fs::write(
&fixture.bash_env,
format!("export HUGE='{}'\n", "x".repeat(MAX_SNAPSHOT_BYTES + 1024)),
)
.expect("write oversized BASH_ENV");
let oversized = params(&fixture, "true");
assert_fallback(&cache, oversized).await;
let next_bash_env = fixture.workspace.join("next_bash_env.sh");
fs::write(&next_bash_env, "").expect("write nested BASH_ENV");
fs::write(
&fixture.bash_env,
format!(
"{}set -a\nshopt -s expand_aliases\nalias snapshot_alias='printf alias-ok'\n\
export BASH_ENV='{}'\n\
declare() {{ return 91; }}; set() {{ return 91; }}; shopt() {{ return 91; }}; alias() {{ return 91; }}\n\
unset() {{ return 91; }}; export() {{ return 91; }}; command() {{ return 91; }}\n\
function [ {{ return 91; }}; read() {{ return 91; }}; true() {{ return 91; }}\n",
startup(&fixture, /*sleep*/ false),
next_bash_env.display(),
),
)
.expect("write valid BASH_ENV");
let cache = BashEnvSnapshotCache::default();
let mut no_checksum = params(&fixture, "true");
no_checksum.env.extend([
("PATH".into(), fixture.workspace.display().to_string()),
("BASH_FUNC_sha256sum%%".into(), "() { :; }".into()),
]);
assert_fallback(&cache, no_checksum).await;
assert!(!fixture.counter.exists());
let tools = fixture._temp.path().join("tools");
fs::create_dir(&tools).expect("create tools");
let digest_file = tools.join("digest");
fs::write(
tools.join("sha256sum"),
format!(
"#!/bin/sh\nIFS=' ' read -r digest remove < '{}'\nprintf '%s %s\\n' \"$digest\" \"$1\"\ncase \"$remove\" in true) rm -f \"$1\";; esac\n",
digest_file.display()
),
)
.expect("write fake sha256sum");
fs::set_permissions(tools.join("sha256sum"), fs::Permissions::from_mode(0o755))
.expect("make executable");
let checksum_path = format!("{}:/usr/bin:/bin", tools.display());
let write_digest = |path: &Path, remove: bool| {
let digest = Sha256::digest(fs::read(path).expect("read snapshot"));
fs::write(&digest_file, format!("{digest:x} {remove}\n")).expect("write digest");
};
let mut replay = params(
&fixture,
"printf '%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s' \"$SNAPSHOT_SENTINEL\" \"$(snapshot_func)\" \"${SNAPSHOT_ARRAY[1]}\" \"${INTEGER_ARRAY[0]}\" \"$(d=$(builtin declare -p INTEGER_ARRAY); f=${d#declare }; f=${f%% *}; [[ $f == *a* && $f == *i* && $f == *r* && $f == *x* ]] && builtin printf attrs)\" \"$(if (( BASH_VERSINFO[0] >= 4 )); then d=$(builtin declare -p ASSOCIATIVE_ARRAY); [[ ${ASSOCIATIVE_ARRAY[key]} == assoc && $d == declare\\ -A* ]] && builtin printf assoc; else builtin printf assoc; fi)\" \"$(builtin declare -p READONLY_TOKEN)\" \"$OVERRIDE\" \"${PATH%%:*}\" \"$(snapshot_alias)\" \"$(/bin/bash -c 'printf %s \"${TOKEN+x}\"')\" \"$(builtin compgen -e | grep -c '^__CODEX_SNAPSHOT_' || true)\" \"$(/bin/bash -c 'type -t snapshot_func')\" \"$(builtin declare -F | grep ' snapshot_func$')\"",
);
replay.env.insert("PATH".into(), checksum_path.clone());
let (argv, env) = prepare(&cache, &replay).await;
assert!(
!fs::read_to_string(snapshot_path(&cache))
.expect("read snapshot")
.contains("__CODEX_SNAPSHOT_")
);
let path = snapshot_path(&cache);
write_digest(&path, /*remove*/ false);
let expected = format!(
"ready|ready|one|0012|attrs|assoc|declare -r READONLY_TOKEN=\"locked\"|explicit|{}/bin|alias-ok||0|function|declare -frx snapshot_func",
fixture.workspace.display()
);
let output = run(&argv, &env, &fixture.workspace).await;
assert_eq!(String::from_utf8(output.stdout).expect("utf8"), expected);
let mut corrupt = fs::read_to_string(&path).expect("read snapshot");
let marker_end = corrupt.find('\n').expect("opening marker") + 1;
corrupt.insert_str(marker_end, "builtin exit 0\n");
fs::write(&path, corrupt).expect("corrupt snapshot while retaining markers");
fs::write(&digest_file, "bad false\n").expect("write bad digest");
let output = run(&argv, &env, &fixture.workspace).await;
assert_eq!(String::from_utf8(output.stdout).expect("utf8"), expected);
assert_eq!(capture_count(&fixture), 2);
fs::write(&path, "").expect("truncate snapshot");
let output = run(&argv, &env, &fixture.workspace).await;
assert_eq!(String::from_utf8(output.stdout).expect("utf8"), expected);
assert_eq!(capture_count(&fixture), 3);
fs::write(&fixture.bash_env, startup(&fixture, /*sleep*/ false)).expect("write race BASH_ENV");
let cache = BashEnvSnapshotCache::default();
let mut race_params = params(&fixture, "builtin printf %s \"$SNAPSHOT_SENTINEL\"");
race_params.env.insert("PATH".into(), checksum_path.clone());
let (argv, env) = prepare(&cache, &race_params).await;
let path = snapshot_path(&cache);
write_digest(&path, /*remove*/ true);
let output = run(&argv, &env, &fixture.workspace).await;
assert_eq!(String::from_utf8(output.stdout).expect("utf8"), "ready");
assert!(!path.exists());
fs::write(
&fixture.bash_env,
format!("{}unset BASH_ENV\n", startup(&fixture, /*sleep*/ false)),
)
.expect("write unsetting BASH_ENV");
let cache = BashEnvSnapshotCache::default();
let mut unset_params = params(
&fixture,
"printf '%s|%s|%s' \"${BASH_ENV+x}\" \"$SNAPSHOT_SENTINEL\" \"$(/bin/bash -c 'printf %s \"${BASH_ENV+x}\"')\"",
);
unset_params.env.insert("PATH".into(), checksum_path);
let (argv, env) = prepare(&cache, &unset_params).await;
let path = snapshot_path(&cache);
write_digest(&path, /*remove*/ false);
assert_eq!(
String::from_utf8(run(&argv, &env, &fixture.workspace).await.stdout).expect("utf8"),
"|ready|"
);
fs::write(&path, "").expect("truncate snapshot");
fs::write(&digest_file, "bad false\n").expect("write bad digest");
assert_eq!(
String::from_utf8(run(&argv, &env, &fixture.workspace).await.stdout).expect("utf8"),
"|ready|"
);
}
#[tokio::test]
async fn command_dependent_bash_env_falls_back_with_original_execution_string() {
let fixture = fixture();
fs::write(
&fixture.bash_env,
format!(
"printf 'x\\n' >> '{}'; SEEN=$BASH_EXECUTION_STRING\n",
fixture.counter.display()
),
)
.expect("write command-dependent BASH_ENV");
let cache = BashEnvSnapshotCache::default();
let command_params = params(&fixture, "printf '%s' \"$SEEN\"");
for _ in 0..2 {
let (argv, env) = prepare(&cache, &command_params).await;
assert_eq!((&argv, &env), (&command_params.argv, &command_params.env));
let output = run(&argv, &env, &fixture.workspace).await;
assert_eq!(
String::from_utf8(output.stdout).expect("utf8"),
command_params.argv[2]
);
}
assert_eq!(capture_count(&fixture), 2);
fs::write(
&fixture.bash_env,
format!(
"trap 'printf \"x\\n\" >> \"{}\"; builtin printf trapped' EXIT\n",
fixture.counter.display()
),
)
.expect("write trap BASH_ENV");
let trap_params = params(&fixture, "builtin printf command");
let (argv, env) = prepare(&cache, &trap_params).await;
assert_eq!((&argv, &env), (&trap_params.argv, &trap_params.env));
let output = run(&argv, &env, &fixture.workspace).await;
assert_eq!(
String::from_utf8(output.stdout).expect("utf8"),
"commandtrapped"
);
assert_eq!(capture_count(&fixture), 3);
for option in ["x", "v"] {
fs::write(&fixture.bash_env, format!("set -{option}\n")).expect("write traced BASH_ENV");
let mut traced = params(&fixture, "true");
traced
.env
.insert("OVERRIDE".into(), "explicit-secret".into());
let (argv, env) = prepare(&cache, &traced).await;
assert_eq!((&argv, &env), (&traced.argv, &traced.env));
let stderr = String::from_utf8(run(&argv, &env, &fixture.workspace).await.stderr)
.expect("utf8 stderr");
assert!(!stderr.contains("__CODEX") && !stderr.contains("explicit-secret"));
}
fs::write(&fixture.bash_env, "function builtin { :; }\n").expect("write shadow BASH_ENV");
let direct = params(&fixture, "true");
assert_eq!(prepare(&cache, &direct).await, (direct.argv, direct.env));
fs::write(&fixture.bash_env, ":\n").expect("write plain BASH_ENV");
for key in ["BASH_FUNC_builtin%%", "builtin"] {
let mut inherited = params(&fixture, "true");
inherited
.env
.insert(key.to_string(), "() { :; }".to_string());
assert_eq!(
prepare(&cache, &inherited).await,
(inherited.argv, inherited.env)
);
}
}
#[tokio::test]
async fn replays_observable_startup_state() {
let fixture = fixture();
let nested = fixture.workspace.join("nested");
fs::create_dir(&nested).expect("create nested cwd");
fs::write(
&fixture.bash_env,
format!(
"printf 'x\\n' >> '{counter}'; printf startup-out; printf startup-err >&2\n\
if [[ ${{CWD_GUARD+x}} ]]; then export CWD_DIRTY=yes; else CWD_GUARD=fresh; readonly CWD_GUARD; fi\n\
umask 077; cd -L -- '{nested}' 2>/dev/null; set +B\n",
counter = fixture.counter.display(),
nested = nested.display(),
),
)
.expect("write BASH_ENV");
let script = "builtin printf '|%s|%s|<%s>|%s|%s|%s' \"$(builtin umask)\" \"$PWD\" {a,b} \"$CWD_GUARD\" \"${CWD_DIRTY-}\" \"$BASH_EXECUTION_STRING\"";
let params = params(&fixture, script);
let cache = BashEnvSnapshotCache::default();
let expected = |cwd: &Path| {
format!(
"startup-out|0077|{}|<{{a,b}}>|fresh||{script}",
cwd.display()
)
};
for _ in 0..2 {
let (argv, env) = prepare(&cache, &params).await;
let output = run(&argv, &env, &fixture.workspace).await;
assert_eq!(
String::from_utf8(output.stdout).expect("utf8"),
expected(&nested)
);
assert_eq!(output.stderr, b"startup-err");
}
assert_eq!(capture_count(&fixture), 1);
fs::remove_dir(&nested).expect("remove nested cwd");
let (argv, env) = prepare(&cache, &params).await;
let output = run(&argv, &env, &fixture.workspace).await;
let fallback_cwd = fs::canonicalize(&fixture.workspace).expect("canonical cwd");
assert_eq!(
String::from_utf8(output.stdout).expect("utf8"),
expected(&fallback_cwd)
);
assert_eq!(output.stderr, b"startup-err");
assert_eq!(capture_count(&fixture), 2);
}
#[tokio::test]
async fn concurrent_requests_capture_once() {
let fixture = fixture();
fs::write(&fixture.bash_env, startup(&fixture, /*sleep*/ true)).expect("write BASH_ENV");
let cache = Arc::new(BashEnvSnapshotCache::default());
let params = params(&fixture, "true");
let tasks = (0..8).map(|_| {
let (cache, params) = (Arc::clone(&cache), params.clone());
tokio::spawn(async move { prepare(&cache, &params).await })
});
for result in futures::future::join_all(tasks).await {
result.expect("capture task");
}
assert_eq!(capture_count(&fixture), 1);
prepare(&BashEnvSnapshotCache::default(), &params).await;
assert_eq!(capture_count(&fixture), 2);
}
@@ -493,3 +493,7 @@ fn fallback(
) -> (Vec<String>, HashMap<String, String>) {
(params.argv.clone(), environment.clone())
}
#[cfg(test)]
#[path = "bash_env_snapshot_tests.rs"]
mod tests;