mirror of
https://github.com/openai/codex.git
synced 2026-11-15 21:50:46 +00:00
Protect shell snapshots when credential brokerage is enabled (#43909)
## Why Shell startup files can introduce credentials or overwrite brokered dummy values. Snapshot capture and replay need to respect the command's sandbox and environment policy without persisting real credentials. ## What changed - Capture and validate brokered snapshots per command using its requested shell, working directory, login mode, sandbox, and environment policy. - Discover shell-initialized credentials and prepare snapshot exports for brokered replay. Preserve shell functions and aliases while preventing startup files from overwriting dummy credentials during replay. - Rebuild snapshots as credential broker state changes and retain each command's snapshot for the lifetime of its process. - Reject brokered POSIX shell execution when a protected snapshot cannot be created, and reject brokerage with `shell_zsh_fork`. Restore real credentials and remove brokerage markers for unsupported PowerShell and Cmd execution; escalated commands bypass protected snapshots. ## Testing Add regression coverage for credential discovery and redaction, environment filtering, readonly exports, shell function and heredoc replay, command working directories and login modes, sandbox enforcement, and missing or disabled snapshots. GitOrigin-RevId: 685356cb9e80f11cf69d053e4d239ee6ccf43a9e
This commit is contained in:
@@ -17,6 +17,7 @@ use codex_core_plugins::PLUGIN_METRICS_OUTPUT_ENV_VAR;
|
||||
use codex_install_context::InstallContext;
|
||||
#[cfg(target_os = "macos")]
|
||||
use codex_network_proxy::CODEX_PROXY_GIT_SSH_COMMAND_MARKER;
|
||||
use codex_network_proxy::CREDENTIAL_BROKER_ACTIVE_ENV_KEY;
|
||||
use codex_network_proxy::CUSTOM_CA_ENV_KEYS;
|
||||
use codex_network_proxy::PROXY_ACTIVE_ENV_KEY;
|
||||
use codex_network_proxy::PROXY_ENV_KEYS;
|
||||
@@ -200,8 +201,22 @@ fn prepare_powershell_command_for_elevated_windows_sandbox_with_fallback(
|
||||
command
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_brokered_shell_snapshot_env(
|
||||
env: &mut HashMap<String, String>,
|
||||
shell_snapshot: Option<&AbsolutePathBuf>,
|
||||
) {
|
||||
if shell_snapshot.is_some()
|
||||
&& env
|
||||
.get(CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
|
||||
.is_some_and(|active| active == "1")
|
||||
{
|
||||
env.remove("BASH_ENV");
|
||||
}
|
||||
}
|
||||
|
||||
/// POSIX-only helper: for commands produced by `Shell::derive_exec_args`
|
||||
/// for Bash/Zsh/sh of the form `[shell_path, "-lc", "<script>"]`, and
|
||||
/// for Bash/Zsh/sh of the form `[shell_path, "-lc", "<script>"]` or brokered
|
||||
/// `[shell_path, "-c", "<script>"]`, and
|
||||
/// when a snapshot is configured on the session shell, rewrite the argv
|
||||
/// to a single non-login shell that sources the snapshot before running
|
||||
/// the original script:
|
||||
@@ -209,6 +224,11 @@ fn prepare_powershell_command_for_elevated_windows_sandbox_with_fallback(
|
||||
/// shell -lc "<script>"
|
||||
/// => user_shell -c ". SNAPSHOT (best effort); exec shell -c <script>"
|
||||
///
|
||||
/// Brokered Bash and Zsh commands targeting the session shell run in that process
|
||||
/// to preserve captured shell functions and avoid asking patched Zsh to exec itself.
|
||||
/// Brokered Zsh wrappers use `-f` so startup files cannot overwrite credentials
|
||||
/// after the proxy has replaced them with dummies.
|
||||
///
|
||||
/// This wrapper script uses POSIX constructs (`if`, `.`, `exec`) so it can
|
||||
/// be run by Bash/Zsh/sh. On non-matching commands, or when command cwd does
|
||||
/// not match the snapshot cwd, this is a no-op.
|
||||
@@ -247,15 +267,31 @@ pub(crate) fn maybe_wrap_shell_lc_with_snapshot(
|
||||
return command.to_vec();
|
||||
}
|
||||
|
||||
let brokered = env
|
||||
.get(CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
|
||||
.is_some_and(|active| active == "1");
|
||||
let flag = command[1].as_str();
|
||||
if flag != "-lc" {
|
||||
if flag != "-lc" && !(brokered && flag == "-c") {
|
||||
return command.to_vec();
|
||||
}
|
||||
|
||||
let snapshot_path = snapshot.to_string_lossy();
|
||||
let shell_path = session_shell.shell_path.to_string_lossy();
|
||||
let command_uses_session_zsh =
|
||||
session_shell.shell_type == ShellType::Zsh && command[0] == shell_path.as_ref();
|
||||
let reuse_session_shell = brokered
|
||||
&& command[0] == shell_path.as_ref()
|
||||
&& matches!(session_shell.shell_type, ShellType::Bash | ShellType::Zsh);
|
||||
let original_shell_is_zsh = command_uses_session_zsh
|
||||
|| codex_shell_command::shell_detect::detect_shell_type(&command[0])
|
||||
== Some(ShellType::Zsh);
|
||||
let brokered_zsh_flag = if flag == "-lc" { "-lfc" } else { "-fc" };
|
||||
let original_shell_flag = if brokered && original_shell_is_zsh {
|
||||
brokered_zsh_flag
|
||||
} else {
|
||||
"-c"
|
||||
};
|
||||
let original_shell = shell_single_quote(&command[0]);
|
||||
let original_script = shell_single_quote(&command[2]);
|
||||
let snapshot_path = shell_single_quote(snapshot_path.as_ref());
|
||||
let trailing_args = command[3..]
|
||||
.iter()
|
||||
@@ -292,17 +328,34 @@ pub(crate) fn maybe_wrap_shell_lc_with_snapshot(
|
||||
proxy_exports,
|
||||
runtime_path_prepend_exports,
|
||||
]);
|
||||
let run_original = if reuse_session_shell {
|
||||
command[2].clone()
|
||||
} else {
|
||||
let original_script = shell_single_quote(&command[2]);
|
||||
format!("exec '{original_shell}' {original_shell_flag} '{original_script}'{trailing_args}")
|
||||
};
|
||||
let rewritten_script = if override_exports.is_empty() {
|
||||
format!(
|
||||
"if . '{snapshot_path}' >/dev/null 2>&1; then :; fi\n\nexec '{original_shell}' -c '{original_script}'{trailing_args}"
|
||||
)
|
||||
format!("if . '{snapshot_path}' >/dev/null 2>&1; then :; fi\n\n{run_original}")
|
||||
} else {
|
||||
format!(
|
||||
"{override_captures}\n\nif . '{snapshot_path}' >/dev/null 2>&1; then :; fi\n\n{override_exports}\n\nexec '{original_shell}' -c '{original_script}'{trailing_args}"
|
||||
"{override_captures}\n\nif . '{snapshot_path}' >/dev/null 2>&1; then :; fi\n\n{override_exports}\n\n{run_original}"
|
||||
)
|
||||
};
|
||||
|
||||
vec![shell_path.to_string(), "-c".to_string(), rewritten_script]
|
||||
let wrapper_flag = if brokered && session_shell.shell_type == ShellType::Zsh {
|
||||
brokered_zsh_flag
|
||||
} else {
|
||||
"-c"
|
||||
};
|
||||
let mut rewritten = vec![
|
||||
shell_path.to_string(),
|
||||
wrapper_flag.to_string(),
|
||||
rewritten_script,
|
||||
];
|
||||
if reuse_session_shell {
|
||||
rewritten.extend_from_slice(&command[3..]);
|
||||
}
|
||||
rewritten
|
||||
}
|
||||
|
||||
fn build_override_exports(
|
||||
@@ -328,6 +381,11 @@ fn build_proxy_env_exports(env: &HashMap<String, String>) -> (String, String) {
|
||||
.copied()
|
||||
.chain(codex_network_proxy::brokered_credential_env_keys(env))
|
||||
.chain(CUSTOM_CA_ENV_KEYS)
|
||||
.chain(
|
||||
env.get(CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
|
||||
.filter(|active| active.as_str() == "1")
|
||||
.map(|_| "BASH_ENV"),
|
||||
)
|
||||
.filter(|key| is_valid_shell_variable_name(key))
|
||||
.collect::<Vec<_>>();
|
||||
keys.sort_unstable();
|
||||
@@ -390,7 +448,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 export {key}=\"${{{value_var}}}\"; else 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"
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
|
||||
@@ -454,6 +454,47 @@ fn maybe_wrap_shell_lc_with_snapshot_preserves_trailing_args() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maybe_wrap_shell_lc_with_snapshot_reuses_brokered_session_zsh() {
|
||||
let dir = tempdir().expect("create temp dir");
|
||||
let snapshot_path = dir.path().join("snapshot.sh");
|
||||
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());
|
||||
for (flag, expected_flag) in [("-c", "-fc"), ("-lc", "-lfc")] {
|
||||
let command = vec![
|
||||
"/bin/zsh".to_string(),
|
||||
flag.to_string(),
|
||||
"printf '%s %s' \"$0\" \"$1\"".to_string(),
|
||||
"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,
|
||||
&session_shell,
|
||||
Some(&shell_snapshot),
|
||||
&HashMap::new(),
|
||||
&env,
|
||||
&RuntimePathPrepends::default(),
|
||||
);
|
||||
|
||||
assert_eq!(rewritten[0], "/bin/zsh");
|
||||
assert_eq!(rewritten[1], expected_flag);
|
||||
assert!(rewritten[2].contains(&format!(
|
||||
"if . '{}' >/dev/null 2>&1; then :; fi",
|
||||
shell_single_quote(&shell_snapshot.to_string_lossy())
|
||||
)));
|
||||
assert!(rewritten[2].ends_with(&command[2]));
|
||||
assert!(!rewritten[2].contains("exec '/bin/zsh'"));
|
||||
assert_eq!(rewritten[3..], command[3..]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maybe_wrap_shell_lc_with_snapshot_restores_explicit_override_precedence() {
|
||||
let dir = tempdir().expect("create temp dir");
|
||||
@@ -757,15 +798,67 @@ fn maybe_wrap_shell_lc_with_snapshot_restores_proxy_env_from_process_env() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn snapshot_wrapper_preserves_readonly_dummy_credentials() -> anyhow::Result<()> {
|
||||
let proxy = test_credential_broker_network_proxy().await?;
|
||||
let dir = tempdir()?;
|
||||
let snapshot = dir.path().join("snapshot.sh");
|
||||
std::fs::write(&snapshot, "# Snapshot file\ntypeset +x GH_TOKEN\n")?;
|
||||
let mut env = HashMap::from([(
|
||||
"GH_TOKEN".to_string(),
|
||||
"ghp_abcdefghijklmnopqrstuvwxyz0123456789".to_string(),
|
||||
)]);
|
||||
proxy.apply_to_env(&mut env);
|
||||
let dummy = env["GH_TOKEN"].clone();
|
||||
assert_ne!(dummy, "ghp_abcdefghijklmnopqrstuvwxyz0123456789");
|
||||
for (shell_type, path) in [(ShellType::Bash, "/bin/bash"), (ShellType::Zsh, "/bin/zsh")] {
|
||||
if !std::path::Path::new(path).exists() {
|
||||
continue;
|
||||
}
|
||||
let (shell, snapshot) = shell_with_snapshot(shell_type, path, snapshot.abs());
|
||||
let command = vec![
|
||||
path.to_string(),
|
||||
"-c".to_string(),
|
||||
"exec /bin/sh -c 'printf %s \"$GH_TOKEN\"'".to_string(),
|
||||
];
|
||||
let mut rewritten = maybe_wrap_shell_lc_with_snapshot(
|
||||
&command,
|
||||
&shell,
|
||||
Some(&snapshot),
|
||||
&HashMap::new(),
|
||||
&env,
|
||||
&RuntimePathPrepends::default(),
|
||||
);
|
||||
// Global startup can mark an inherited dummy readonly before the wrapper runs.
|
||||
rewritten[2].insert_str(0, "readonly GH_TOKEN\n");
|
||||
let output = Command::new(&rewritten[0])
|
||||
.args(&rewritten[1..])
|
||||
.env_clear()
|
||||
.envs(&env)
|
||||
.output()?;
|
||||
assert!(output.status.success(), "{path}: {output:?}");
|
||||
assert_eq!(String::from_utf8(output.stdout)?, dummy);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -> anyhow::Result<()>
|
||||
{
|
||||
let proxy = test_credential_broker_network_proxy().await?;
|
||||
let dir = tempdir()?;
|
||||
let snapshot = dir.path().join("snapshot.sh");
|
||||
let startup = dir.path().join("startup.sh");
|
||||
std::fs::write(&startup, "export OPENAI_API_KEY='sk-startup-secret'\n")?;
|
||||
let snapshot_dir = dir.path().join("snapshots");
|
||||
std::fs::create_dir(&snapshot_dir)?;
|
||||
let snapshot = snapshot_dir.join("snapshot.sh");
|
||||
std::fs::write(
|
||||
&snapshot,
|
||||
"# Snapshot file\nexport OPENAI_API_KEY='stale'\nexport GITHUB_TOKEN='ghp_snapshot_only'\nexport GH_HOST='github.example.com'\n",
|
||||
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",
|
||||
startup.display(),
|
||||
dir.path().display()
|
||||
),
|
||||
)?;
|
||||
let (shell, snapshot) = shell_with_snapshot(ShellType::Bash, "/bin/bash", snapshot.abs());
|
||||
let mut env = HashMap::from([
|
||||
@@ -774,14 +867,18 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
||||
"sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_".to_string(),
|
||||
),
|
||||
("GITHUB_TOKEN".to_string(), String::new()),
|
||||
("BASH_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 command = vec![
|
||||
"/bin/bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"printf '%s\\n%s\\n%s' \"$OPENAI_API_KEY\" \"${GITHUB_TOKEN-unset}\" \"$GH_HOST\""
|
||||
.to_string(),
|
||||
"-c".to_string(),
|
||||
"corp_auth \"$1\"".to_string(),
|
||||
"brokered-shell".to_string(),
|
||||
"github.example.com".to_string(),
|
||||
];
|
||||
let rewritten = maybe_wrap_shell_lc_with_snapshot(
|
||||
&command,
|
||||
@@ -794,7 +891,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
||||
let output = Command::new(&rewritten[0])
|
||||
.args(&rewritten[1..])
|
||||
.env_clear()
|
||||
.envs(env)
|
||||
.envs(&env)
|
||||
.output()?;
|
||||
|
||||
assert!(output.status.success(), "command failed: {output:?}");
|
||||
@@ -802,6 +899,42 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
format!("{dummy}\nghp_snapshot_only\ngithub.example.com")
|
||||
);
|
||||
|
||||
if std::path::Path::new("/bin/zsh").exists() {
|
||||
std::fs::write(
|
||||
dir.path().join(".zshenv"),
|
||||
"export OPENAI_API_KEY='sk-startup-secret'\n",
|
||||
)?;
|
||||
let renamed_zsh = dir.path().join("zsh.exe");
|
||||
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));
|
||||
let command = vec![
|
||||
renamed_zsh.display().to_string(),
|
||||
"-lc".to_string(),
|
||||
"printf '%s\\n%s' \"$OPENAI_API_KEY\" \"$ZDOTDIR\"".to_string(),
|
||||
];
|
||||
let rewritten = maybe_wrap_shell_lc_with_snapshot(
|
||||
&command,
|
||||
&zsh,
|
||||
Some(&snapshot),
|
||||
&HashMap::new(),
|
||||
&env,
|
||||
&RuntimePathPrepends::default(),
|
||||
);
|
||||
assert_eq!(rewritten[1], "-lfc");
|
||||
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(())
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ use crate::sandboxing::ExecServerEnvConfig;
|
||||
use crate::sandboxing::SandboxPermissions;
|
||||
use crate::session::turn_context::TurnEnvironment;
|
||||
use crate::shell::ShellType;
|
||||
use crate::shell_snapshot::ShellSnapshotSandbox;
|
||||
use crate::shell_snapshot::snapshot_read_permissions;
|
||||
use crate::tools::flat_tool_name;
|
||||
use crate::tools::network_approval::NetworkApprovalSpec;
|
||||
use crate::tools::runtimes::RuntimePathPrepends;
|
||||
@@ -54,6 +56,7 @@ use codex_tools::UnifiedExecShellMode;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -261,22 +264,11 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
let base_command = &req.command;
|
||||
let windows_sandbox_proxy_settings_mode = ctx.session.windows_sandbox_proxy_settings_mode;
|
||||
let session_shell = ctx.session.user_shell();
|
||||
let shell = req
|
||||
let environment_shell = req
|
||||
.turn_environment
|
||||
.shell
|
||||
.as_ref()
|
||||
.unwrap_or(session_shell.as_ref());
|
||||
let environment_is_remote = req.turn_environment.environment.is_remote();
|
||||
let shell_snapshot_location = if environment_is_remote {
|
||||
None
|
||||
} else {
|
||||
// TODO(anp): Make shell snapshot lookup accept PathUri.
|
||||
let native_cwd = req
|
||||
.cwd
|
||||
.to_abs_path()
|
||||
.map_err(|err| ToolError::Rejected(err.to_string()))?;
|
||||
req.turn_environment.shell_snapshot(&native_cwd)
|
||||
};
|
||||
let (file_system_sandbox_policy, _) = attempt.permissions.to_runtime_permissions();
|
||||
let launch_sandbox_permissions = sandbox_permissions_preserving_denied_reads(
|
||||
req.sandbox_permissions,
|
||||
@@ -286,7 +278,71 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
req.network.as_ref(),
|
||||
launch_sandbox_permissions,
|
||||
));
|
||||
let env = exec_env_for_sandbox_permissions(&req.env, launch_sandbox_permissions);
|
||||
let environment_is_remote = req.turn_environment.environment.is_remote();
|
||||
let credential_broker_available = !environment_is_remote
|
||||
&& req.network.is_some()
|
||||
&& ctx
|
||||
.step_context
|
||||
.turn
|
||||
.config
|
||||
.permissions
|
||||
.network
|
||||
.as_ref()
|
||||
.is_some_and(crate::config::NetworkProxySpec::credential_broker_enabled);
|
||||
if credential_broker_available
|
||||
&& managed_network.is_some()
|
||||
&& matches!(self.shell_mode, UnifiedExecShellMode::ZshFork(_))
|
||||
{
|
||||
return Err(ToolError::Rejected(
|
||||
"credential brokerage does not yet support shell_zsh_fork; disable shell_zsh_fork to use the broker".to_string(),
|
||||
));
|
||||
}
|
||||
let requested_shell = (credential_broker_available
|
||||
&& (req.shell_type != environment_shell.shell_type
|
||||
|| base_command.first().is_some_and(|path| {
|
||||
path != environment_shell.shell_path.to_string_lossy().as_ref()
|
||||
})))
|
||||
.then(|| {
|
||||
base_command.first().map(|path| crate::shell::Shell {
|
||||
shell_type: req.shell_type,
|
||||
shell_path: PathBuf::from(path),
|
||||
})
|
||||
})
|
||||
.flatten();
|
||||
let shell = requested_shell.as_ref().unwrap_or(environment_shell);
|
||||
let shell_snapshot = if environment_is_remote
|
||||
|| credential_broker_available
|
||||
&& launch_sandbox_permissions.requires_escalated_permissions()
|
||||
{
|
||||
None
|
||||
} else {
|
||||
// TODO(anp): Make shell snapshot lookup accept PathUri.
|
||||
let native_cwd = req
|
||||
.cwd
|
||||
.to_abs_path()
|
||||
.map_err(|err| ToolError::Rejected(err.to_string()))?;
|
||||
req.turn_environment
|
||||
.shell_snapshot(
|
||||
&native_cwd,
|
||||
base_command,
|
||||
shell,
|
||||
&ctx.step_context.turn.config,
|
||||
Some(ShellSnapshotSandbox::new(
|
||||
attempt,
|
||||
managed_network,
|
||||
&req.turn_environment.selection.environment_id,
|
||||
req.additional_permissions.as_ref(),
|
||||
)),
|
||||
)
|
||||
.await
|
||||
};
|
||||
let shell_snapshot_location = shell_snapshot.as_ref().map(|snapshot| snapshot.path());
|
||||
let mut env = exec_env_for_sandbox_permissions(&req.env, launch_sandbox_permissions);
|
||||
if let Some(snapshot) = shell_snapshot.as_ref()
|
||||
&& (managed_network.is_some() || base_command.get(1).is_some_and(|flag| flag == "-lc"))
|
||||
{
|
||||
snapshot.restore_credentials(&mut env, req.turn_environment.shell_environment_policy());
|
||||
}
|
||||
let (mut env, managed_network_context, network_proxy_launch) = match managed_network {
|
||||
Some(network) if environment_is_remote => {
|
||||
let mut launch = network.remote_launch_config().await.map_err(|err| {
|
||||
@@ -349,6 +405,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
}
|
||||
None => (env, None, None),
|
||||
};
|
||||
super::prepare_brokered_shell_snapshot_env(&mut env, shell_snapshot_location.as_ref());
|
||||
let explicit_env_overrides = req.explicit_env_overrides.clone();
|
||||
let metrics_sidecar = sidecar_for_command(
|
||||
ctx,
|
||||
@@ -392,6 +449,30 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
&runtime_path_prepends,
|
||||
)
|
||||
};
|
||||
let brokered_shell_snapshot_missing = !environment_is_remote
|
||||
&& managed_network.is_some()
|
||||
&& env
|
||||
.get(codex_network_proxy::CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
|
||||
.is_some_and(|active| active == "1")
|
||||
&& command
|
||||
.get(1)
|
||||
.is_some_and(|flag| matches!(flag.as_str(), "-lc" | "-c"))
|
||||
&& !shell_snapshot_location
|
||||
.as_ref()
|
||||
.is_some_and(|snapshot| snapshot.exists());
|
||||
if brokered_shell_snapshot_missing && let Some(network) = managed_network {
|
||||
if cfg!(unix)
|
||||
&& matches!(
|
||||
shell.shell_type,
|
||||
ShellType::Bash | ShellType::Zsh | ShellType::Sh
|
||||
)
|
||||
{
|
||||
return Err(ToolError::Rejected(
|
||||
"credential brokerage could not create a protected shell snapshot".to_string(),
|
||||
));
|
||||
}
|
||||
network.restore_and_disable_brokered_credentials(&mut env, &mut command);
|
||||
}
|
||||
if req.shell_snapshot.is_some() {
|
||||
let exports =
|
||||
runtime_path_prepends.shell_exports_after_snapshot(&explicit_env_overrides);
|
||||
@@ -401,6 +482,15 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
*script = format!("{exports}\n{script}");
|
||||
}
|
||||
}
|
||||
if !environment_is_remote
|
||||
&& matches!(shell.shell_type, ShellType::PowerShell | ShellType::Cmd)
|
||||
&& env
|
||||
.get(codex_network_proxy::CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
|
||||
.is_some_and(|active| active == "1")
|
||||
&& let Some(network) = managed_network
|
||||
{
|
||||
network.restore_and_disable_brokered_credentials(&mut env, &mut command);
|
||||
}
|
||||
let command = prepare_powershell_command_for_elevated_windows_sandbox(
|
||||
&command,
|
||||
Some(&req.shell_type),
|
||||
@@ -416,9 +506,25 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
let sidecar_permissions = metrics_sidecar
|
||||
.as_ref()
|
||||
.map(PluginMetricsSidecar::additional_permissions);
|
||||
let snapshot_permissions = shell_snapshot_location
|
||||
.as_ref()
|
||||
.filter(|_| {
|
||||
env.get(codex_network_proxy::CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
|
||||
.is_some_and(|active| active == "1")
|
||||
})
|
||||
.and_then(|path| {
|
||||
snapshot_read_permissions(
|
||||
path,
|
||||
&req.turn_environment
|
||||
.permission_profile_with_workspace_roots(),
|
||||
attempt.sandbox_cwd,
|
||||
)
|
||||
});
|
||||
let internal_permissions =
|
||||
merge_permission_profiles(sidecar_permissions.as_ref(), snapshot_permissions.as_ref());
|
||||
let additional_permissions = merge_permission_profiles(
|
||||
req.additional_permissions.as_ref(),
|
||||
sidecar_permissions.as_ref(),
|
||||
internal_permissions.as_ref(),
|
||||
);
|
||||
let permissions = TerminalPermissions::for_launch(
|
||||
&req.turn_environment,
|
||||
@@ -434,7 +540,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
SandboxPermissions::UseDefault
|
||||
},
|
||||
req.additional_permissions.as_ref(),
|
||||
sidecar_permissions.as_ref(),
|
||||
internal_permissions.as_ref(),
|
||||
);
|
||||
|
||||
if let UnifiedExecShellMode::ZshFork(zsh_fork_config) = &self.shell_mode {
|
||||
@@ -471,7 +577,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
let process = self
|
||||
let mut process = self
|
||||
.manager
|
||||
.open_session_with_prepared_exec_env(
|
||||
req.process_id,
|
||||
@@ -493,6 +599,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
}
|
||||
other => ToolError::Rejected(other.to_string()),
|
||||
})?;
|
||||
process._shell_snapshot = shell_snapshot;
|
||||
return Ok(UnifiedExecAttempt {
|
||||
process,
|
||||
metrics_sidecar,
|
||||
@@ -520,7 +627,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
error @ ToolError::Codex(_) => error,
|
||||
})?;
|
||||
let options = unified_exec_options(attempt.network_denial_cancellation_token.clone());
|
||||
let process = self
|
||||
let mut process = self
|
||||
.manager
|
||||
.open_session_with_exec_env(
|
||||
req.process_id,
|
||||
@@ -539,6 +646,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecAttempt> for UnifiedExecRunt
|
||||
req.turn_environment.environment.as_ref(),
|
||||
)
|
||||
.await?;
|
||||
process._shell_snapshot = shell_snapshot;
|
||||
Ok(UnifiedExecAttempt {
|
||||
process,
|
||||
metrics_sidecar,
|
||||
|
||||
Reference in New Issue
Block a user