Harden credential handling in shell snapshots and replay (#44040)

## Why

Shell quoting can hide credentials from raw-text checks, and startup files can restore real credentials after the broker replaces them with dummy values.

## What changed

- Decode shell literals without evaluating them and reject snapshots containing credentials in executable source, including aliases, functions, and heredocs.
- Preserve credential policy overrides, explicit unsets, and aliases whose source variables were removed. Support credential aliases in Zsh tied arrays while rejecting credentials that span array elements.
- Guard snapshot replay against credential restoration through shell startup files and preserve unrelated `ENV` settings.
- Apply Windows environment-key casing rules to credential overrides, suppress unredacted sandbox diagnostics during snapshot capture, and clear inherited environment variables before launching escalated commands.

## Testing

Add regression coverage for shell quoting and escaped credentials, Zsh tied arrays, startup-file replay, readonly credentials, policy overrides, and sensitive capture timeout and cancellation handling.

GitOrigin-RevId: 58274c07c715423241d26ce6dd2c2b4230cf0f64
This commit is contained in:
Winston Howes authored and copyberry committed 2026-09-09 04:00:10 +00:00
1 parent a548463b78
commit ec512d2347
21 files changed
+4215 -256

No files matched your search

+228 -6
View File
@@ -27,6 +27,7 @@ pub(crate) use codex_network_proxy::is_managed_proxy_env_var;
pub(crate) use codex_network_proxy::strip_managed_proxy_env;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::shell_environment::is_non_inheritable_env_var;
use codex_shell_command::shell_snapshot::posix_env_path_expansion_function;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashMap;
use std::path::Path;
@@ -35,6 +36,12 @@ pub(crate) mod apply_patch;
pub(crate) mod unified_exec;
pub(crate) mod zsh_fork;
const SNAPSHOT_ORIGINAL_BASH_ENV_ENV_KEY: &str = "CODEX_NETWORK_PROXY_SNAPSHOT_ORIGINAL_BASH_ENV";
const SNAPSHOT_ORIGINAL_POSIX_ENV_ENV_KEY: &str = "CODEX_NETWORK_PROXY_SNAPSHOT_ORIGINAL_POSIX_ENV";
const SNAPSHOT_ORIGINAL_ZDOTDIR_ENV_KEY: &str = "CODEX_NETWORK_PROXY_SNAPSHOT_ORIGINAL_ZDOTDIR";
const SNAPSHOT_BROKERED_VALUE_ENV_PREFIX: &str = "CODEX_NETWORK_PROXY_SNAPSHOT_BROKERED_VALUE_";
const SNAPSHOT_BROKERED_UNSET_ENV_PREFIX: &str = "CODEX_NETWORK_PROXY_SNAPSHOT_BROKERED_UNSET_";
pub(crate) fn exec_env_for_sandbox_permissions(
env: &HashMap<String, String>,
sandbox_permissions: SandboxPermissions,
@@ -204,13 +211,57 @@ fn prepare_powershell_command_for_elevated_windows_sandbox_with_fallback(
pub(crate) fn prepare_brokered_shell_snapshot_env(
env: &mut HashMap<String, String>,
shell_snapshot: Option<&AbsolutePathBuf>,
shell: &Shell,
) {
if shell_snapshot.is_some()
&& env
.get(CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
.is_some_and(|active| active == "1")
{
env.remove("BASH_ENV");
if !cfg!(windows) {
env.retain(|key, _| {
!key.starts_with(SNAPSHOT_BROKERED_VALUE_ENV_PREFIX)
&& !key.starts_with(SNAPSHOT_BROKERED_UNSET_ENV_PREFIX)
});
for key in codex_network_proxy::brokered_credential_value_env_keys(env) {
if is_valid_shell_variable_name(&key)
&& let Some(value) = env.get(&key).cloned()
{
env.insert(format!("{SNAPSHOT_BROKERED_VALUE_ENV_PREFIX}{key}"), value);
}
}
for key in codex_network_proxy::brokered_credential_marker_env_keys(env) {
if !is_valid_shell_variable_name(&key) {
continue;
}
if let Some(value) = env.get(&key).cloned() {
env.entry(format!("{SNAPSHOT_BROKERED_VALUE_ENV_PREFIX}{key}"))
.or_insert(value);
} else {
env.insert(
format!("{SNAPSHOT_BROKERED_UNSET_ENV_PREFIX}{key}"),
"1".to_string(),
);
}
}
}
let bash_env = env.remove("BASH_ENV");
if !cfg!(windows)
&& let Some(bash_env) = bash_env
&& !bash_env.is_empty()
{
env.insert(SNAPSHOT_ORIGINAL_BASH_ENV_ENV_KEY.to_string(), bash_env);
} else {
env.remove(SNAPSHOT_ORIGINAL_BASH_ENV_ENV_KEY);
}
if shell.shell_type == ShellType::Zsh {
if let Some(zdotdir) = env.remove("ZDOTDIR") {
env.insert(SNAPSHOT_ORIGINAL_ZDOTDIR_ENV_KEY.to_string(), zdotdir);
} else {
env.remove(SNAPSHOT_ORIGINAL_ZDOTDIR_ENV_KEY);
}
env.insert("ZDOTDIR".to_string(), "/dev/null".to_string());
}
}
}
@@ -320,18 +371,136 @@ pub(crate) fn maybe_wrap_shell_lc_with_snapshot(
],
);
let (proxy_captures, proxy_exports) = build_proxy_env_exports(env);
let (env_captures, replayed_startup_capture, env_exports) = if brokered {
let bash_env_key = SNAPSHOT_ORIGINAL_BASH_ENV_ENV_KEY;
let posix_env_key = SNAPSHOT_ORIGINAL_POSIX_ENV_ENV_KEY;
let startup_env_key =
if session_shell.shell_type == ShellType::Sh && env.contains_key(posix_env_key) {
posix_env_key
} else {
bash_env_key
};
let alternate_startup_env_key = if startup_env_key == posix_env_key {
bash_env_key
} else {
posix_env_key
};
let zdotdir_key = SNAPSHOT_ORIGINAL_ZDOTDIR_ENV_KEY;
let expand_env_function = posix_env_path_expansion_function();
(
format!(
r#"__CODEX_SNAPSHOT_ORIGINAL_ENV_SET="${{ENV+x}}"
__CODEX_SNAPSHOT_ORIGINAL_ENV="${{ENV-}}"
{expand_env_function}
__codex_snapshot_expand_env_with_zdotdir() (
if [ -n "${{{zdotdir_key}+x}}" ]; then
export ZDOTDIR="${{{zdotdir_key}}}"
elif [ -n "${{ZSH_VERSION-}}" ] && [ "${{ZDOTDIR-}}" = /dev/null ]; then
unset ZDOTDIR
fi
__codex_snapshot_expand_env "$1"
)
__CODEX_SNAPSHOT_PROTECTED_ENV=$(
__codex_snapshot_expand_env_with_zdotdir "${{{startup_env_key}-}}"
)
__CODEX_SNAPSHOT_ALTERNATE_PROTECTED_ENV=$(
__codex_snapshot_expand_env_with_zdotdir "${{{alternate_startup_env_key}-}}"
)"#
),
"__CODEX_SNAPSHOT_REPLAYED_BASH_ENV=\"${BASH_ENV-}\"".to_string(),
format!(
r#"__CODEX_SNAPSHOT_CURRENT_ENV=$(
__codex_snapshot_expand_env_with_zdotdir "${{ENV-}}"
)
__CODEX_SNAPSHOT_ORIGINAL_EXPANDED_ENV=$(
__codex_snapshot_expand_env_with_zdotdir "$__CODEX_SNAPSHOT_ORIGINAL_ENV"
)
__CODEX_SNAPSHOT_REPLAYED_PROTECTED_ENV=$(
__codex_snapshot_expand_env_with_zdotdir "$__CODEX_SNAPSHOT_REPLAYED_BASH_ENV"
)
unset -f __codex_snapshot_expand_env __codex_snapshot_expand_env_with_zdotdir
__codex_snapshot_env_is_protected() (
for __codex_protected_env in \
"$__CODEX_SNAPSHOT_PROTECTED_ENV" \
"$__CODEX_SNAPSHOT_ALTERNATE_PROTECTED_ENV" \
"$__CODEX_SNAPSHOT_REPLAYED_PROTECTED_ENV"; do
if [ -n "$__codex_protected_env" ] &&
{{ [ "$1" = "$__codex_protected_env" ] ||
[ "$1" -ef "$__codex_protected_env" ] 2>/dev/null; }}; then
return 0
fi
done
return 1
)
if __codex_snapshot_env_is_protected "$__CODEX_SNAPSHOT_CURRENT_ENV"; then
if [ -n "$__CODEX_SNAPSHOT_ORIGINAL_ENV_SET" ] &&
! __codex_snapshot_env_is_protected "$__CODEX_SNAPSHOT_ORIGINAL_EXPANDED_ENV"; then
builtin export ENV="$__CODEX_SNAPSHOT_ORIGINAL_ENV" 2>/dev/null ||
command export ENV="$__CODEX_SNAPSHOT_ORIGINAL_ENV" || exit 1
[ "${{ENV-}}" = "$__CODEX_SNAPSHOT_ORIGINAL_ENV" ] || exit 1
else
builtin unset ENV 2>/dev/null || command unset ENV || exit 1
[ -z "${{ENV+x}}" ] || exit 1
fi
fi
unset -f __codex_snapshot_env_is_protected
unset __CODEX_SNAPSHOT_ORIGINAL_ENV_SET __CODEX_SNAPSHOT_ORIGINAL_ENV \
__CODEX_SNAPSHOT_PROTECTED_ENV __CODEX_SNAPSHOT_ALTERNATE_PROTECTED_ENV \
__CODEX_SNAPSHOT_REPLAYED_BASH_ENV __CODEX_SNAPSHOT_REPLAYED_PROTECTED_ENV \
__CODEX_SNAPSHOT_CURRENT_ENV __CODEX_SNAPSHOT_ORIGINAL_EXPANDED_ENV \
{bash_env_key} {posix_env_key}"#
),
)
} else {
(String::new(), String::new(), String::new())
};
let zsh_startup_exports = if brokered && session_shell.shell_type == ShellType::Zsh {
let key = SNAPSHOT_ORIGINAL_ZDOTDIR_ENV_KEY;
format!(
"if [ -n \"${{{key}+x}}\" ]; then\n export ZDOTDIR=\"${{{key}}}\"\nelif [ \"${{ZDOTDIR-}}\" = /dev/null ]; then\n unset ZDOTDIR\nfi\nunset {key}"
)
} else {
String::new()
};
// Zsh always reads the global zshenv, even with `-f`. Keep private copies of child-visible
// dummy values until the command shell has finished startup, then remove the copies.
let outer_brokered_credential_exports = if brokered {
build_brokered_credential_exports(env, /*remove_copies*/ false)
} else {
String::new()
};
let inner_brokered_credential_exports = if brokered {
build_brokered_credential_exports(env, /*remove_copies*/ true)
} else {
String::new()
};
let original_script = if !inner_brokered_credential_exports.is_empty() {
format!("{inner_brokered_credential_exports}\n{}", command[2])
} else {
command[2].clone()
};
let runtime_path_prepend_exports =
runtime_path_prepends.shell_exports_after_snapshot(explicit_env_overrides);
let override_captures = join_shell_blocks([override_captures, proxy_captures]);
let override_captures = join_shell_blocks([
outer_brokered_credential_exports.clone(),
override_captures,
proxy_captures,
env_captures,
]);
let override_exports = join_shell_blocks([
outer_brokered_credential_exports.clone(),
replayed_startup_capture,
override_exports,
proxy_exports,
runtime_path_prepend_exports,
env_exports,
zsh_startup_exports,
outer_brokered_credential_exports,
]);
let run_original = if reuse_session_shell {
command[2].clone()
original_script
} else {
let original_script = shell_single_quote(&command[2]);
let original_script = shell_single_quote(&original_script);
format!("exec '{original_shell}' {original_shell_flag} '{original_script}'{trailing_args}")
};
let rewritten_script = if override_exports.is_empty() {
@@ -358,6 +527,60 @@ pub(crate) fn maybe_wrap_shell_lc_with_snapshot(
rewritten
}
fn build_brokered_credential_exports(env: &HashMap<String, String>, remove_copies: bool) -> String {
let mut value_copies = env
.keys()
.filter_map(|copy_key| {
let key = copy_key.strip_prefix(SNAPSHOT_BROKERED_VALUE_ENV_PREFIX)?;
is_valid_shell_variable_name(key).then_some((key, copy_key))
})
.collect::<Vec<_>>();
value_copies.sort_unstable();
let value_exports = value_copies
.into_iter()
.map(|(key, copy_key)| {
let restore = format!(
"if [ -z \"${{{copy_key}+x}}\" ]; then exit 1; fi\nif [ -n \"${{{key}+x}}\" ] && [ -n \"${{{key}}}\" ] && [ \"${{{key}}}\" != \"${{{copy_key}}}\" ]; then export {key}=\"${{{copy_key}}}\" || exit 1; fi\nif [ -n \"${{{key}+x}}\" ] && [ -n \"${{{key}}}\" ] && [ \"${{{key}}}\" != \"${{{copy_key}}}\" ]; then exit 1; fi"
);
if remove_copies {
format!("{restore}\nunset {copy_key} || exit 1")
} else {
restore
}
})
.collect::<Vec<_>>()
.join("\n");
let mut unset_markers = env
.keys()
.filter_map(|marker_key| {
let key = marker_key.strip_prefix(SNAPSHOT_BROKERED_UNSET_ENV_PREFIX)?;
is_valid_shell_variable_name(key).then_some((key, marker_key))
})
.collect::<Vec<_>>();
unset_markers.sort_unstable();
let unset_exports = unset_markers
.into_iter()
.map(|(key, marker_key)| {
let restore = format!(
"if [ -z \"${{{marker_key}+x}}\" ]; then exit 1; fi\nif [ -n \"${{{key}+x}}\" ] && [ -n \"${{{key}}}\" ]; then unset {key} || exit 1; fi\nif [ -n \"${{{key}+x}}\" ] && [ -n \"${{{key}}}\" ]; then exit 1; fi"
);
if remove_copies {
format!("{restore}\nunset {marker_key} || exit 1")
} else {
restore
}
})
.collect::<Vec<_>>()
.join("\n");
let exports = join_shell_blocks([value_exports, unset_exports]);
if exports.is_empty() {
return exports;
}
format!(
"case $- in\n *x*) __CODEX_SNAPSHOT_BROKER_XTRACE=1; set +x ;;\n *) __CODEX_SNAPSHOT_BROKER_XTRACE= ;;\nesac\n{exports}\nif [ -n \"$__CODEX_SNAPSHOT_BROKER_XTRACE\" ]; then\n unset __CODEX_SNAPSHOT_BROKER_XTRACE\n set -x\nelse\n unset __CODEX_SNAPSHOT_BROKER_XTRACE\nfi"
)
}
fn build_override_exports(
explicit_env_overrides: &HashMap<String, String>,
restore_even_when_absent: &[&str],
@@ -448,7 +671,7 @@ fn build_override_exports_for_keys(variable_prefix: &str, keys: &[&str]) -> (Str
let set_var = format!("{variable_prefix}_SET_{idx}");
let value_var = format!("{variable_prefix}_{idx}");
format!(
"if [ -n \"${{{set_var}}}\" ]; then\n if [ -z \"${{{key}+x}}\" ] || [ \"${{{key}-}}\" != \"${{{value_var}}}\" ]; then export {key}=\"${{{value_var}}}\"; else export {key}; fi\nelse builtin unset {key} 2>/dev/null || command unset {key}; fi"
"if [ -n \"${{{set_var}}}\" ]; then\n if [ -z \"${{{key}+x}}\" ] || [ \"${{{key}-}}\" != \"${{{value_var}}}\" ]; then export {key}=\"${{{value_var}}}\"; else export {key}; fi\nelse builtin unset {key} 2>/dev/null || command unset {key}; fi\nbuiltin unset {set_var} {value_var} 2>/dev/null || command unset {set_var} {value_var}"
)
})
.collect::<Vec<_>>()
@@ -617,7 +840,6 @@ mod prepare_powershell_command_tests {
assert_eq!(rewritten, command);
}
#[test]
fn local_elevated_powershell_uses_discovered_fallback() {
let command = vec![
+581 -8
View File
@@ -27,6 +27,7 @@ use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use core_test_support::PathBufExt;
use pretty_assertions::assert_eq;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;
@@ -461,6 +462,14 @@ fn maybe_wrap_shell_lc_with_snapshot_reuses_brokered_session_zsh() {
std::fs::write(&snapshot_path, "# Snapshot file\n").expect("write snapshot");
let (session_shell, shell_snapshot) =
shell_with_snapshot(ShellType::Zsh, "/bin/zsh", snapshot_path.abs());
let copy_key = format!("{SNAPSHOT_BROKERED_VALUE_ENV_PREFIX}OPENAI_API_KEY");
let env = HashMap::from([
(
CREDENTIAL_BROKER_ACTIVE_ENV_KEY.to_string(),
"1".to_string(),
),
(copy_key.clone(), "dummy-openai-key".to_string()),
]);
for (flag, expected_flag) in [("-c", "-fc"), ("-lc", "-lfc")] {
let command = vec![
"/bin/zsh".to_string(),
@@ -469,10 +478,6 @@ fn maybe_wrap_shell_lc_with_snapshot_reuses_brokered_session_zsh() {
"arg0".to_string(),
"arg1".to_string(),
];
let env = HashMap::from([(
CREDENTIAL_BROKER_ACTIVE_ENV_KEY.to_string(),
"1".to_string(),
)]);
let rewritten = maybe_wrap_shell_lc_with_snapshot(
&command,
@@ -490,6 +495,7 @@ fn maybe_wrap_shell_lc_with_snapshot_reuses_brokered_session_zsh() {
shell_single_quote(&shell_snapshot.to_string_lossy())
)));
assert!(rewritten[2].ends_with(&command[2]));
assert!(rewritten[2].contains(&format!("unset {copy_key} || exit 1")));
assert!(!rewritten[2].contains("exec '/bin/zsh'"));
assert_eq!(rewritten[3..], command[3..]);
}
@@ -855,7 +861,8 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
std::fs::write(
&snapshot,
format!(
"# Snapshot file\ncorp_auth() {{ printf '%s\\n%s\\n%s' \"$OPENAI_API_KEY\" \"${{GITHUB_TOKEN-unset}}\" \"$1\"; }}\nexport OPENAI_API_KEY='stale'\nexport GITHUB_TOKEN='ghp_snapshot_only'\nexport GH_HOST='github.example.com'\nexport BASH_ENV='{}'\nexport ZDOTDIR='{}'\n",
"# Snapshot file\ncorp_auth() {{ printf '%s\\n%s\\n%s' \"$OPENAI_API_KEY\" \"${{GITHUB_TOKEN-unset}}\" \"$1\"; }}\nexport OPENAI_API_KEY='stale'\nexport GITHUB_TOKEN='ghp_snapshot_only'\nexport GH_HOST='github.example.com'\nexport BASH_ENV='{}'\nexport ENV='{}'\nexport ZDOTDIR='{}'\n",
startup.display(),
startup.display(),
dir.path().display()
),
@@ -866,13 +873,27 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
"OPENAI_API_KEY".to_string(),
"sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_".to_string(),
),
(
"AUTH_HEADER".to_string(),
"Bearer sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
.to_string(),
),
("GITHUB_TOKEN".to_string(), String::new()),
("BASH_ENV".to_string(), startup.display().to_string()),
("ENV".to_string(), startup.display().to_string()),
]);
proxy.apply_to_env(&mut env);
prepare_brokered_shell_snapshot_env(&mut env, Some(&snapshot));
assert!(!env.contains_key("BASH_ENV"));
let dummy = env["OPENAI_API_KEY"].clone();
let dummy_alias = env["AUTH_HEADER"].clone();
let mut alias_only_env = env.clone();
alias_only_env.remove("OPENAI_API_KEY");
let mut empty_canonical_env = env.clone();
empty_canonical_env.insert("OPENAI_API_KEY".to_string(), String::new());
let mut absent_alias_env = env.clone();
absent_alias_env.remove("AUTH_HEADER");
prepare_brokered_shell_snapshot_env(&mut env, Some(&snapshot), &shell);
assert!(!env.contains_key("BASH_ENV"));
assert_eq!(env.get("ENV"), Some(&startup.display().to_string()));
let command = vec![
"/bin/bash".to_string(),
"-c".to_string(),
@@ -900,6 +921,341 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
format!("{dummy}\nghp_snapshot_only\ngithub.example.com")
);
let (posix_shell, _) = shell_with_snapshot(ShellType::Sh, "/bin/sh", snapshot.clone());
let no_prepends = RuntimePathPrepends::default();
let wrap_brokered_snapshot = |shell: &Shell,
snapshot: &AbsolutePathBuf,
env: &HashMap<String, String>,
prepends: &RuntimePathPrepends| {
maybe_wrap_shell_lc_with_snapshot(
&[
shell.shell_path.to_string_lossy().into_owned(),
if shell.shell_type == ShellType::Sh {
"-lc"
} else {
"-c"
}
.to_string(),
"/bin/sh -ic 'printf \"%s|%s\" \"$OPENAI_API_KEY\" \"${ENV-unset}\"'".to_string(),
],
shell,
Some(snapshot),
&HashMap::new(),
env,
prepends,
)
};
let wrap_snapshot = |snapshot: &AbsolutePathBuf, env: &HashMap<String, String>| {
wrap_brokered_snapshot(&posix_shell, snapshot, env, &no_prepends)
};
let nested = wrap_snapshot(&snapshot, &env);
let run_nested =
|command: &[String], env: &HashMap<String, String>| -> anyhow::Result<String> {
let output = Command::new(&command[0])
.args(&command[1..])
.current_dir(dir.path())
.env_clear()
.envs(env)
.output()?;
anyhow::ensure!(output.status.success(), "nested shell failed: {output:?}");
Ok(String::from_utf8(output.stdout)?)
};
let posix_startup = dir.path().join("posix-startup.sh");
std::fs::write(&posix_startup, "export OPENAI_API_KEY='sk-posix-secret'\n")?;
let posix_snapshot = dir.path().join("posix-startup-snapshot.sh").abs();
std::fs::write(
&posix_snapshot,
format!("export ENV='{}'\n", posix_startup.display()),
)?;
let mut posix_startup_env = env.clone();
posix_startup_env.insert(
SNAPSHOT_ORIGINAL_POSIX_ENV_ENV_KEY.to_string(),
posix_startup.display().to_string(),
);
let distinct = wrap_snapshot(&posix_snapshot, &posix_startup_env);
assert_eq!(
run_nested(&distinct, &posix_startup_env)?,
format!("{dummy}|unset")
);
posix_startup_env.remove(SNAPSHOT_ORIGINAL_BASH_ENV_ENV_KEY);
posix_startup_env.insert("ENV".to_string(), posix_startup.display().to_string());
let inherited = wrap_snapshot(&posix_snapshot, &posix_startup_env);
assert_eq!(
run_nested(&inherited, &posix_startup_env)?,
format!("{dummy}|unset")
);
let wrap_bash_snapshot = |snapshot: &AbsolutePathBuf, env: &HashMap<String, String>| {
wrap_brokered_snapshot(&shell, snapshot, env, &no_prepends)
};
let readonly_snapshot = dir.path().join("readonly-env-snapshot.sh").abs();
for initial_env in [None, Some("production"), Some(startup.to_str().unwrap())] {
let mut case_env = env.clone();
case_env.remove("ENV");
if let Some(value) = initial_env {
case_env.insert("ENV".to_string(), value.to_string());
}
for (value, succeeds) in [(startup.to_str().unwrap(), false), ("production", true)] {
std::fs::write(
&readonly_snapshot,
format!("export ENV='{value}'\nreadonly ENV\n"),
)?;
for command_shell in [&shell, &posix_shell] {
let command = wrap_brokered_snapshot(
command_shell,
&readonly_snapshot,
&case_env,
&no_prepends,
);
let output = Command::new(&command[0])
.args(&command[1..])
.current_dir(dir.path())
.env_clear()
.envs(&case_env)
.output()?;
assert_eq!(output.status.success(), succeeds, "{output:?}");
assert_eq!(
String::from_utf8(output.stdout)?,
if succeeds {
format!("{dummy}|production")
} else {
String::new()
}
);
}
}
}
let prepended_path_snapshot = dir.path().join("prepended-path-snapshot.sh").abs();
std::fs::write(
&prepended_path_snapshot,
"export ENV='${PATH%%:*}/startup.sh'\nexport PATH='/safe'\n",
)?;
let mut prepended_env = env.clone();
prepended_env.insert("PATH".to_string(), "/safe".to_string());
prepended_env.insert("ENV".to_string(), "${PATH%%:*}/startup.sh".to_string());
let mut prepends = RuntimePathPrepends::default();
prepends.prepend(&mut prepended_env, dir.path());
let command =
wrap_brokered_snapshot(&shell, &prepended_path_snapshot, &prepended_env, &prepends);
assert_eq!(
run_nested(&command, &prepended_env)?,
format!("{dummy}|unset")
);
let relative_startup_snapshot = dir.path().join("relative-startup-snapshot.sh").abs();
let startup_path = startup.display().to_string();
let mut expanded_startup_env = env.clone();
expanded_startup_env.extend([
("SNAPSHOT_STARTUP_FILE".to_string(), startup_path.clone()),
("ORIGINAL_STARTUP_FILE".to_string(), startup_path.clone()),
(
"SNAPSHOT_APPLICATION_FILE".to_string(),
"/safe-application.env".to_string(),
),
(
SNAPSHOT_ORIGINAL_BASH_ENV_ENV_KEY.to_string(),
"$SNAPSHOT_STARTUP_FILE".to_string(),
),
]);
let application_script =
format!("export ENV='{startup_path}'\nexport SNAPSHOT_APPLICATION_FILE='{startup_path}'\n");
let changed_startup_script = "export ENV='$ORIGINAL_STARTUP_FILE'\nexport SNAPSHOT_STARTUP_FILE='/different-startup.sh'\n";
let strict_script = format!("set -eu\nexport ENV='{startup_path}'\n");
for (original_env, script, expected_env) in [
(
startup_path.as_str(),
"export ENV='./startup.sh'\n",
"unset",
),
(
startup_path.as_str(),
"export ENV='$SNAPSHOT_STARTUP_FILE'\n",
"unset",
),
(
"$SNAPSHOT_APPLICATION_FILE",
application_script.as_str(),
"unset",
),
(
"${SNAPSHOT_APPLICATION_FILE}",
application_script.as_str(),
"unset",
),
(startup_path.as_str(), changed_startup_script, "unset"),
(
"$OPTIONAL_APPLICATION_FILE",
strict_script.as_str(),
"$OPTIONAL_APPLICATION_FILE",
),
] {
let mut case_env = expanded_startup_env.clone();
case_env.insert("ENV".to_string(), original_env.to_string());
std::fs::write(&relative_startup_snapshot, script)?;
let command = wrap_bash_snapshot(&relative_startup_snapshot, &case_env);
assert_eq!(
run_nested(&command, &case_env)?,
format!("{dummy}|{expected_env}")
);
}
for bash_env in ["", "$OPTIONAL_STARTUP"] {
let mut case_env = env.clone();
case_env.insert("BASH_ENV".to_string(), bash_env.to_string());
case_env.insert("ENV".to_string(), String::new());
prepare_brokered_shell_snapshot_env(&mut case_env, Some(&snapshot), &shell);
let command = wrap_bash_snapshot(&snapshot, &case_env);
assert_eq!(run_nested(&command, &case_env)?, format!("{dummy}|"));
}
let mut expanded_env = env.clone();
expanded_env.insert("ENV".to_string(), "$SNAPSHOT_STARTUP_FILE".to_string());
expanded_env.insert(
"SNAPSHOT_STARTUP_FILE".to_string(),
startup.display().to_string(),
);
assert_eq!(
run_nested(&nested, &expanded_env)?,
format!("{dummy}|unset")
);
expanded_env.insert("ENV".to_string(), "${SNAPSHOT_STARTUP_FILE}".to_string());
assert_eq!(
run_nested(&nested, &expanded_env)?,
format!("{dummy}|unset")
);
let injection = "\"; printf CODEX_ENV_INJECTED; __codex_env_file=\"";
expanded_env.insert("ENV".to_string(), injection.to_string());
let startup_value_snapshot = dir.path().join("startup-value-snapshot.sh").abs();
std::fs::write(
&startup_value_snapshot,
format!("export ENV='{injection}'\n"),
)?;
let expanded_command = wrap_snapshot(&startup_value_snapshot, &expanded_env);
assert_eq!(
run_nested(&expanded_command, &expanded_env)?,
format!("{dummy}|{injection}")
);
std::fs::write(&startup_value_snapshot, "export ENV='~/startup.sh'\n")?;
let bash_posix_path = dir.path().join("sh");
std::os::unix::fs::symlink("/bin/bash", &bash_posix_path)?;
let bash_posix_path = bash_posix_path.display().to_string();
let (bash_posix_shell, _) =
shell_with_snapshot(ShellType::Sh, &bash_posix_path, snapshot.clone());
let bash_posix_command = vec![
bash_posix_path.clone(),
"-c".to_string(),
format!(
"'{bash_posix_path}' -ic 'printf \"%s|%s\" \"$OPENAI_API_KEY\" \"${{ENV-unset}}\"'"
),
];
let mut tilde_env = env.clone();
tilde_env.insert("ENV".to_string(), "~/startup.sh".to_string());
tilde_env.insert("HOME".to_string(), dir.path().display().to_string());
let bash_posix_command = maybe_wrap_shell_lc_with_snapshot(
&bash_posix_command,
&bash_posix_shell,
Some(&startup_value_snapshot),
&HashMap::new(),
&tilde_env,
&RuntimePathPrepends::default(),
);
assert_eq!(
run_nested(&bash_posix_command, &tilde_env)?,
format!("{dummy}|unset")
);
#[cfg(target_os = "macos")]
{
expanded_env.insert("ENV".to_string(), "~/startup.sh".to_string());
expanded_env.insert("HOME".to_string(), dir.path().display().to_string());
assert_eq!(
run_nested(&nested, &expanded_env)?,
format!("{dummy}|unset")
);
}
std::fs::create_dir(dir.path().join("production"))?;
let mut ordinary_env = env.clone();
ordinary_env.insert("ENV".to_string(), "production".to_string());
assert_eq!(
run_nested(&nested, &ordinary_env)?,
format!("{dummy}|production")
);
let application_env_file = dir.path().join(".env");
std::fs::write(&application_env_file, "APPLICATION_SETTING=production\n")?;
ordinary_env.insert(
"ENV".to_string(),
application_env_file.display().to_string(),
);
let application_command = vec![
"/bin/bash".to_string(),
"-c".to_string(),
"printf '%s' \"$ENV\"".to_string(),
];
let application_command = maybe_wrap_shell_lc_with_snapshot(
&application_command,
&shell,
Some(&snapshot),
&HashMap::new(),
&ordinary_env,
&RuntimePathPrepends::default(),
);
assert_eq!(
run_nested(&application_command, &ordinary_env)?,
application_env_file.display().to_string()
);
for flag in ["-c", "-lc"] {
let posix_application_command = maybe_wrap_shell_lc_with_snapshot(
&[
"/bin/sh".to_string(),
flag.to_string(),
"printf '%s' \"$ENV\"".to_string(),
],
&posix_shell,
Some(&snapshot),
&HashMap::new(),
&ordinary_env,
&RuntimePathPrepends::default(),
);
assert_eq!(
run_nested(&posix_application_command, &ordinary_env)?,
application_env_file.display().to_string()
);
}
let changed_application_snapshot = dir.path().join("changed-application-snapshot.sh").abs();
std::fs::write(
&changed_application_snapshot,
format!("export ENV='{}'\n", application_env_file.display()),
)?;
let bash_nested_command = wrap_bash_snapshot(&changed_application_snapshot, &env);
assert_eq!(
run_nested(&bash_nested_command, &env)?,
format!("{dummy}|{}", application_env_file.display())
);
let posix_nested_command = wrap_snapshot(&changed_application_snapshot, &env);
assert_eq!(
run_nested(&posix_nested_command, &env)?,
format!("{dummy}|{}", application_env_file.display())
);
let application_snapshot = dir.path().join("application-snapshot.sh");
std::fs::write(&application_snapshot, "export ENV='production'\n")?;
let application_snapshot = application_snapshot.abs();
let application_command = wrap_snapshot(&application_snapshot, &env);
assert_eq!(
run_nested(&application_command, &env)?,
format!("{dummy}|production")
);
let mut snapshot_env = env.clone();
snapshot_env.remove("ENV");
let application_command = wrap_snapshot(&application_snapshot, &snapshot_env);
assert_eq!(
run_nested(&application_command, &snapshot_env)?,
format!("{dummy}|production")
);
if std::path::Path::new("/bin/zsh").exists() {
std::fs::write(
dir.path().join(".zshenv"),
@@ -909,7 +1265,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
std::os::unix::fs::symlink("/bin/zsh", &renamed_zsh)?;
env.insert("ZDOTDIR".to_string(), dir.path().display().to_string());
let (zsh, _) = shell_with_snapshot(ShellType::Zsh, "/bin/zsh", snapshot.clone());
prepare_brokered_shell_snapshot_env(&mut env, Some(&snapshot));
prepare_brokered_shell_snapshot_env(&mut env, Some(&snapshot), &zsh);
let command = vec![
renamed_zsh.display().to_string(),
"-lc".to_string(),
@@ -923,6 +1279,8 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
&env,
&RuntimePathPrepends::default(),
);
assert!(!rewritten[2].contains(&dummy));
assert!(!rewritten[2].contains(&dummy_alias));
assert_eq!(rewritten[1], "-lfc");
let output = Command::new(&rewritten[0])
.args(&rewritten[1..])
@@ -934,6 +1292,106 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
String::from_utf8_lossy(&output.stdout),
format!("{dummy}\n{}", dir.path().display())
);
let system_startup_dir = dir.path().join("system-startup");
std::fs::create_dir(&system_startup_dir)?;
let system_startup_zsh = system_startup_dir.join("zsh");
std::fs::write(
&system_startup_zsh,
"#!/bin/sh\nexport OPENAI_API_KEY='sk-system-startup-secret'\nexport AUTH_HEADER='Bearer sk-system-startup-secret'\nexec /bin/zsh -ax \"$@\"\n",
)?;
let mut permissions = std::fs::metadata(&system_startup_zsh)?.permissions();
permissions.set_mode(0o700);
std::fs::set_permissions(&system_startup_zsh, permissions)?;
let (system_zsh, _) = shell_with_snapshot(
ShellType::Zsh,
system_startup_zsh.to_string_lossy().as_ref(),
snapshot.clone(),
);
for (mut startup_env, expected_canonical, expected_alias) in [
(alias_only_env, "unset", dummy_alias.as_str()),
(empty_canonical_env, "", dummy_alias.as_str()),
(absent_alias_env, dummy.as_str(), "unset"),
] {
prepare_brokered_shell_snapshot_env(&mut startup_env, Some(&snapshot), &system_zsh);
let command = vec![
system_startup_zsh.display().to_string(),
"-c".to_string(),
format!(
"set +x\nprintf '%s\\n%s\\n%s\\n%s\\n%s\\n' \"${{OPENAI_API_KEY-unset}}\" \"${{AUTH_HEADER-unset}}\" \"${{{SNAPSHOT_BROKERED_VALUE_ENV_PREFIX}AUTH_HEADER-unset}}\" \"${{{SNAPSHOT_BROKERED_VALUE_ENV_PREFIX}OPENAI_API_KEY-unset}}\" \"${{{SNAPSHOT_BROKERED_UNSET_ENV_PREFIX}OPENAI_API_KEY-unset}}\"\nenv -0"
),
];
let system_rewritten = maybe_wrap_shell_lc_with_snapshot(
&command,
&system_zsh,
Some(&snapshot),
&HashMap::new(),
&startup_env,
&RuntimePathPrepends::default(),
);
let output = Command::new(&system_rewritten[0])
.args(&system_rewritten[1..])
.env_clear()
.envs(&startup_env)
.output()?;
assert!(
output.status.success(),
"system startup command failed: {output:?}"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let exported_env = stdout
.strip_prefix(&format!(
"{expected_canonical}\n{expected_alias}\nunset\nunset\nunset\n"
))
.unwrap_or_else(|| panic!("unexpected system startup output: {stdout}"));
assert!(!stdout.contains("sk-system-startup-secret"));
assert!(
!exported_env
.split('\0')
.any(|entry| entry.starts_with("__CODEX_SNAPSHOT_PROXY_OVERRIDE_"))
);
assert!(!String::from_utf8_lossy(&output.stderr).contains("sk-system-startup-secret"));
}
for (bash_env, posix_env, zdotdir) in [
(
"$ZDOTDIR/startup.sh",
"$ZDOTDIR/startup.sh",
Some(dir.path()),
),
("${ZDOTDIR:-$HOME}/startup.sh", "$HOME/startup.sh", None),
] {
let mut nested_zsh_env = env.clone();
nested_zsh_env.remove(SNAPSHOT_ORIGINAL_ZDOTDIR_ENV_KEY);
nested_zsh_env.insert("HOME".to_string(), dir.path().display().to_string());
nested_zsh_env.insert("BASH_ENV".to_string(), bash_env.to_string());
nested_zsh_env.insert("ENV".to_string(), posix_env.to_string());
if let Some(zdotdir) = zdotdir {
nested_zsh_env.insert("ZDOTDIR".to_string(), zdotdir.display().to_string());
} else {
nested_zsh_env.remove("ZDOTDIR");
}
prepare_brokered_shell_snapshot_env(&mut nested_zsh_env, Some(&snapshot), &zsh);
let command = wrap_brokered_snapshot(&zsh, &snapshot, &nested_zsh_env, &no_prepends);
assert_eq!(
run_nested(&command, &nested_zsh_env)?,
format!("{dummy}|unset")
);
}
env.remove("ZDOTDIR");
env.remove(SNAPSHOT_ORIGINAL_ZDOTDIR_ENV_KEY);
prepare_brokered_shell_snapshot_env(&mut env, Some(&snapshot), &zsh);
let output = Command::new(&rewritten[0])
.args(&rewritten[1..])
.env_clear()
.envs(env)
.output()?;
assert!(output.status.success(), "zsh command failed: {output:?}");
assert_eq!(
String::from_utf8_lossy(&output.stdout),
format!("{dummy}\n{}", dir.path().display())
);
}
Ok(())
}
@@ -1437,3 +1895,118 @@ fn maybe_wrap_shell_lc_with_snapshot_preserves_unset_override_variables() {
assert!(output.status.success(), "command failed: {output:?}");
assert_eq!(String::from_utf8_lossy(&output.stdout), "unset");
}
#[test]
fn brokered_credential_exports_stop_when_startup_makes_credential_readonly() {
let copy_key = format!("{SNAPSHOT_BROKERED_VALUE_ENV_PREFIX}OPENAI_API_KEY");
let env = HashMap::from([(copy_key.clone(), "dummy-openai-key".to_string())]);
let restore = build_brokered_credential_exports(&env, /*remove_copies*/ true);
let unset_output = Command::new("/bin/bash")
.args([
"-c",
&format!(
"unset OPENAI_API_KEY\n{restore}\nprintf '%s|%s' \"${{OPENAI_API_KEY-unset}}\" \"${{{copy_key}-unset}}\""
),
])
.env(&copy_key, "dummy-openai-key")
.output()
.expect("run unset credential probe");
assert!(
unset_output.status.success(),
"unset credential probe failed: {unset_output:?}"
);
assert_eq!(String::from_utf8_lossy(&unset_output.stdout), "unset|unset");
let empty_output = Command::new("/bin/bash")
.args([
"-c",
&format!(
"OPENAI_API_KEY=\n{restore}\nprintf '%s|%s' \"$OPENAI_API_KEY\" \"${{{copy_key}-unset}}\""
),
])
.env(&copy_key, "dummy-openai-key")
.output()
.expect("run empty credential probe");
assert!(
empty_output.status.success(),
"empty credential probe failed: {empty_output:?}"
);
assert_eq!(String::from_utf8_lossy(&empty_output.stdout), "|unset");
let unchanged_output = Command::new("/bin/bash")
.args([
"-c",
&format!(
"readonly OPENAI_API_KEY=dummy-openai-key\n{restore}\nprintf '%s|%s' \"$OPENAI_API_KEY\" \"${{{copy_key}-unset}}\""
),
])
.env(&copy_key, "dummy-openai-key")
.output()
.expect("run unchanged readonly credential probe");
assert!(
unchanged_output.status.success(),
"unchanged readonly credential probe failed: {unchanged_output:?}"
);
assert_eq!(
String::from_utf8_lossy(&unchanged_output.stdout),
"dummy-openai-key|unset"
);
let xtrace_output = Command::new("/bin/bash")
.args([
"-c",
&format!(
"OPENAI_API_KEY=real-openai-key\nset -x\n{restore}\nset +x\nprintf '%s|%s' \"$OPENAI_API_KEY\" \"${{{copy_key}-unset}}\""
),
])
.env(&copy_key, "dummy-openai-key")
.output()
.expect("run xtrace credential probe");
assert!(
xtrace_output.status.success(),
"xtrace credential probe failed: {xtrace_output:?}"
);
assert_eq!(
String::from_utf8_lossy(&xtrace_output.stdout),
"dummy-openai-key|unset"
);
assert!(!String::from_utf8_lossy(&xtrace_output.stderr).contains("real-openai-key"));
let unset_marker_key = format!("{SNAPSHOT_BROKERED_UNSET_ENV_PREFIX}OPENAI_API_KEY");
let unset_env = HashMap::from([(unset_marker_key.clone(), "1".to_string())]);
let unset_restore = build_brokered_credential_exports(&unset_env, /*remove_copies*/ true);
let readonly_empty_output = Command::new("/bin/bash")
.args([
"-c",
&format!(
"readonly OPENAI_API_KEY=\n{unset_restore}\nprintf '%s|%s' \"$OPENAI_API_KEY\" \"${{{unset_marker_key}-unset}}\""
),
])
.env(&unset_marker_key, "1")
.output()
.expect("run readonly empty credential probe");
assert!(
readonly_empty_output.status.success(),
"readonly empty credential probe failed: {readonly_empty_output:?}"
);
assert_eq!(
String::from_utf8_lossy(&readonly_empty_output.stdout),
"|unset"
);
let output = Command::new("/bin/bash")
.args([
"-c",
&format!("readonly OPENAI_API_KEY=real-openai-key\n{restore}\nprintf should-not-run"),
])
.env(copy_key, "dummy-openai-key")
.output()
.expect("run readonly credential probe");
assert!(!output.status.success(), "command unexpectedly succeeded");
assert!(
output.stdout.is_empty(),
"protected command unexpectedly ran"
);
}
@@ -43,6 +43,7 @@ use crate::unified_exec::UnifiedExecError;
use crate::unified_exec::UnifiedExecProcess;
use crate::unified_exec::UnifiedExecProcessManager;
use codex_core_plugins::PluginMetricsSidecar;
use codex_network_proxy::CREDENTIAL_BROKER_ACTIVE_ENV_KEY;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxy;
use codex_protocol::error::CodexErr;
@@ -405,7 +406,45 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
}
None => (env, None, None),
};
super::prepare_brokered_shell_snapshot_env(&mut env, shell_snapshot_location.as_ref());
if let Some(snapshot) = shell_snapshot.as_ref() {
snapshot.restore_fail_open_aliases(&mut env);
}
if managed_network.is_some()
&& !environment_is_remote
&& shell.shell_type == ShellType::Sh
&& env
.get(CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
.is_some_and(|active| active == "1")
&& let Some(startup_env) = shell_snapshot
.as_ref()
.and_then(|snapshot| snapshot.protected_startup_env())
{
env.insert(
super::SNAPSHOT_ORIGINAL_POSIX_ENV_ENV_KEY.to_string(),
startup_env.to_string(),
);
}
super::prepare_brokered_shell_snapshot_env(
&mut env,
shell_snapshot_location.as_ref(),
shell,
);
if env
.get(CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
.is_some_and(|active| active == "1")
&& let Some(snapshot) = shell_snapshot.as_ref()
{
for key in snapshot.startup_credential_keys() {
if !super::is_valid_shell_variable_name(key) {
continue;
}
let (prefix, value) = match env.get(key) {
Some(value) => (super::SNAPSHOT_BROKERED_VALUE_ENV_PREFIX, value.clone()),
None => (super::SNAPSHOT_BROKERED_UNSET_ENV_PREFIX, "1".to_string()),
};
env.insert(format!("{prefix}{key}"), value);
}
}
let explicit_env_overrides = req.explicit_env_overrides.clone();
let metrics_sidecar = sidecar_for_command(
ctx,
@@ -485,7 +524,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
if !environment_is_remote
&& matches!(shell.shell_type, ShellType::PowerShell | ShellType::Cmd)
&& env
.get(codex_network_proxy::CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
.get(CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
.is_some_and(|active| active == "1")
&& let Some(network) = managed_network
{