mirror of
https://github.com/openai/codex.git
synced 2026-11-18 22:20:48 +00:00
Preserve saved sandbox permissions when resuming codex exec (#62194)
## Why `codex exec resume` sends the current process's sandbox defaults as overrides. A session started with `:read-only` can therefore resume with workspace write access when the configured default is `:workspace`. ## What changed - Restore the saved permission selection, working directory, and workspace roots by default. Honor explicit overrides and append directories requested with `--add-dir` to the resumed workspace roots. - Recover built-in read-only permissions from older history without widening current read access. Require an explicit permission selection when a saved named profile cannot be loaded or saved read-only access cannot be restored. - Report sandbox permissions and writable roots from the running thread. ## Testing Add regression coverage for a denied write on the first resumed shell call, legacy read-only history, explicit permission overrides, and workspace root preservation with and without `--add-dir`. GitOrigin-RevId: ed2cf3132f9ce34570661f801c9534a55696e3a5
This commit is contained in:
@@ -5,6 +5,7 @@ use codex_app_server_protocol::ServerNotification;
|
||||
use codex_core::config::Config;
|
||||
use codex_exec_server::BoundOutput;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CodexStatus {
|
||||
@@ -19,6 +20,7 @@ pub(crate) trait EventProcessor {
|
||||
config: &Config,
|
||||
prompt: &str,
|
||||
session_configured: &SessionConfiguredEvent,
|
||||
workspace_roots: &[PathUri],
|
||||
);
|
||||
|
||||
fn print_thread_started(&mut self, thread_id: &str);
|
||||
|
||||
@@ -217,10 +217,13 @@ impl EventProcessor for EventProcessorWithHumanOutput {
|
||||
config: &Config,
|
||||
prompt: &str,
|
||||
session_configured_event: &SessionConfiguredEvent,
|
||||
workspace_roots: &[PathUri],
|
||||
) {
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
eprintln!("OpenAI Codex v{VERSION}\n--------");
|
||||
for (key, value) in config_summary_entries(config, session_configured_event) {
|
||||
for (key, value) in
|
||||
config_summary_entries(config, session_configured_event, workspace_roots)
|
||||
{
|
||||
eprintln!("{} {}", format!("{key}:").style(self.bold), value);
|
||||
}
|
||||
eprintln!("--------");
|
||||
@@ -445,10 +448,13 @@ impl EventProcessor for EventProcessorWithHumanOutput {
|
||||
fn config_summary_entries(
|
||||
config: &Config,
|
||||
session_configured_event: &SessionConfiguredEvent,
|
||||
workspace_roots: &[PathUri],
|
||||
) -> Vec<(&'static str, String)> {
|
||||
let permission_profile = config.permissions.effective_permission_profile();
|
||||
let mut entries = vec![
|
||||
("workdir", config.cwd.display().to_string()),
|
||||
(
|
||||
"workdir",
|
||||
session_configured_event.cwd.display().to_string(),
|
||||
),
|
||||
("model", session_configured_event.model.clone()),
|
||||
(
|
||||
"provider",
|
||||
@@ -461,9 +467,9 @@ fn config_summary_entries(
|
||||
(
|
||||
"sandbox",
|
||||
summarize_permission_profile(
|
||||
&permission_profile,
|
||||
&PathUri::from_abs_path(&config.cwd),
|
||||
&config.effective_workspace_roots(),
|
||||
&session_configured_event.permission_profile,
|
||||
&PathUri::from_abs_path(&session_configured_event.cwd),
|
||||
workspace_roots,
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
@@ -286,10 +286,11 @@ fn summarizes_managed_read_only_permission_profile() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn config_summary_entries_include_runtime_workspace_roots() {
|
||||
async fn config_summary_entries_include_only_writable_workspace_roots() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let cwd = tempfile::tempdir().expect("create cwd");
|
||||
let extra_root = tempfile::tempdir().expect("create extra root");
|
||||
let read_only_root = tempfile::tempdir().expect("create read-only root");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
@@ -298,23 +299,21 @@ async fn config_summary_entries_include_runtime_workspace_roots() {
|
||||
.expect("build default config");
|
||||
let cwd = cwd.path().to_path_buf().abs();
|
||||
let extra_root = extra_root.path().to_path_buf().abs();
|
||||
let expected_extra_root_name = extra_root
|
||||
.file_name()
|
||||
.expect("extra root should have file name")
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
let read_only_root = read_only_root.path().to_path_buf().abs();
|
||||
config.cwd = cwd.clone();
|
||||
config.workspace_roots = vec![cwd.clone(), extra_root];
|
||||
config.workspace_roots = vec![cwd.clone(), read_only_root.clone(), extra_root.clone()];
|
||||
config
|
||||
.permissions
|
||||
.set_workspace_roots(config.workspace_roots.clone());
|
||||
config
|
||||
.permissions
|
||||
.set_permission_profile(PermissionProfile::workspace_write_with(
|
||||
&[],
|
||||
.set_permission_profile(PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry::new(cwd.clone().into(), FileSystemAccessMode::Write),
|
||||
FileSystemSandboxEntry::new(read_only_root.into(), FileSystemAccessMode::Read),
|
||||
FileSystemSandboxEntry::new(extra_root.clone().into(), FileSystemAccessMode::Write),
|
||||
]),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ true,
|
||||
))
|
||||
.expect("set permission profile");
|
||||
|
||||
@@ -338,16 +337,18 @@ async fn config_summary_entries_include_runtime_workspace_roots() {
|
||||
rollout_path: None,
|
||||
};
|
||||
|
||||
let summary_entries = config_summary_entries(&config, &session_configured_event);
|
||||
let summary_entries = config_summary_entries(
|
||||
&config,
|
||||
&session_configured_event,
|
||||
&config.effective_workspace_roots(),
|
||||
);
|
||||
let sandbox_summary = summary_entries
|
||||
.iter()
|
||||
.find_map(|(key, value)| (*key == "sandbox").then_some(value))
|
||||
.expect("sandbox summary entry");
|
||||
assert!(
|
||||
sandbox_summary.starts_with("workspace-write [workdir, ")
|
||||
&& sandbox_summary.contains(&expected_extra_root_name),
|
||||
"expected runtime workspace root in sandbox summary: {summary_entries:?}"
|
||||
);
|
||||
let sandbox_summary =
|
||||
sandbox_summary.replace(extra_root.to_string_lossy().as_ref(), "<extra root>");
|
||||
insta::assert_snapshot!(sandbox_summary, @"workspace-write [workdir, <extra root>]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -18,6 +18,7 @@ use codex_core::config::Config;
|
||||
use codex_exec_server::BoundOutput;
|
||||
use codex_protocol::models::WebSearchAction;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use serde_json::json;
|
||||
|
||||
pub use crate::event_processor::CodexStatus;
|
||||
@@ -611,6 +612,7 @@ impl EventProcessor for EventProcessorWithJsonOutput {
|
||||
_: &Config,
|
||||
_: &str,
|
||||
session_configured: &SessionConfiguredEvent,
|
||||
_: &[PathUri],
|
||||
) {
|
||||
self.emit(Self::thread_started_event(session_configured));
|
||||
}
|
||||
|
||||
+101
-16
@@ -66,6 +66,7 @@ use codex_app_server_protocol::TurnStartedNotification;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_cloud_config::managed_config_bundle_loader_for_storage;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::ConfigLayerSource;
|
||||
use codex_config::ConfigLoadError;
|
||||
use codex_config::ConfigLoadOptions;
|
||||
use codex_config::LoaderOverrides;
|
||||
@@ -231,6 +232,7 @@ struct ExecRunArgs {
|
||||
state_db: Option<StateDbHandle>,
|
||||
command: Option<ExecCommand>,
|
||||
config: Config,
|
||||
overrides: ConfigOverrides,
|
||||
resume_approvals_reviewer_override: Option<codex_app_server_protocol::ApprovalsReviewer>,
|
||||
daybreak_override: Option<bool>,
|
||||
dangerously_bypass_approvals_and_sandbox: bool,
|
||||
@@ -675,7 +677,7 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result
|
||||
.build()
|
||||
};
|
||||
let mut config = build_exec_config(
|
||||
overrides,
|
||||
overrides.clone(),
|
||||
dangerously_bypass_approvals_and_sandbox,
|
||||
build_config,
|
||||
)
|
||||
@@ -830,6 +832,7 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result
|
||||
state_db,
|
||||
command,
|
||||
config,
|
||||
overrides,
|
||||
resume_approvals_reviewer_override,
|
||||
daybreak_override,
|
||||
dangerously_bypass_approvals_and_sandbox,
|
||||
@@ -932,6 +935,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
state_db,
|
||||
command,
|
||||
config,
|
||||
overrides,
|
||||
resume_approvals_reviewer_override,
|
||||
daybreak_override,
|
||||
dangerously_bypass_approvals_and_sandbox,
|
||||
@@ -1113,6 +1117,9 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
);
|
||||
|
||||
let mut daybreak_enabled = config.daybreak_enabled;
|
||||
let mut resumed_workspace_roots = None;
|
||||
let mut first_turn_cwd = Some(default_cwd);
|
||||
let mut first_turn_workspace_roots = None;
|
||||
// Resolve resume and fork through existing app-server thread lifecycle APIs.
|
||||
let (history_mode, fallback_session_configured) = if let Some(ExecCommand::Resume(args)) =
|
||||
command.as_ref()
|
||||
@@ -1127,6 +1134,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
params: thread_resume_params_from_config(
|
||||
&config,
|
||||
thread_id,
|
||||
&overrides,
|
||||
resume_approvals_reviewer_override,
|
||||
),
|
||||
},
|
||||
@@ -1134,9 +1142,25 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let AppServerClient::InProcess(embedded_client) = &client else {
|
||||
unreachable!("local exec uses an embedded app-server");
|
||||
};
|
||||
let thread_id = ThreadId::from_string(&response.thread.id)
|
||||
.map_err(|err| anyhow::anyhow!("invalid resumed thread id: {err}"))?;
|
||||
let permissions = embedded_client.thread_permissions(thread_id).await?;
|
||||
let session_configured =
|
||||
session_configured_from_thread_resume_response(&response, &config)
|
||||
session_configured_from_thread_resume_response(&response, permissions.profile)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
// Resume already chose the cwd and environments, including any explicit -C.
|
||||
first_turn_cwd = None;
|
||||
resumed_workspace_roots = Some(permissions.workspace_roots);
|
||||
if !overrides.additional_writable_roots.is_empty() {
|
||||
let mut roots = response.runtime_workspace_roots;
|
||||
roots.extend(overrides.additional_writable_roots.into_iter().map(|path| {
|
||||
AbsolutePathBuf::resolve_path_against_base(path, config.cwd.as_path())
|
||||
}));
|
||||
first_turn_workspace_roots = Some(roots);
|
||||
}
|
||||
daybreak_enabled = daybreak_override
|
||||
.or(response.thread.daybreak_enabled)
|
||||
.unwrap_or(false);
|
||||
@@ -1257,17 +1281,28 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
// Use the start/resume response as the authoritative bootstrap payload.
|
||||
// Waiting for a later streamed `SessionConfigured` event adds up to 10s of
|
||||
// avoidable startup latency on the in-process path.
|
||||
let session_configured = fallback_session_configured;
|
||||
let mut session_configured = fallback_session_configured;
|
||||
|
||||
exec_span.record("thread.id", primary_thread_id_for_span.as_str());
|
||||
|
||||
// Print the effective configuration and initial request so users can see what Codex
|
||||
// is using.
|
||||
event_processor.print_config_summary(&config, &prompt_summary, &session_configured);
|
||||
// With --add-dir, report the host's effective grant after turn/start applies the additions.
|
||||
let summary_after_turn_start = !json_mode && first_turn_workspace_roots.is_some();
|
||||
if !summary_after_turn_start {
|
||||
let workspace_roots =
|
||||
resumed_workspace_roots.unwrap_or_else(|| config.effective_workspace_roots());
|
||||
event_processor.print_config_summary(
|
||||
&config,
|
||||
&prompt_summary,
|
||||
&session_configured,
|
||||
&workspace_roots,
|
||||
);
|
||||
}
|
||||
if !json_mode
|
||||
&& let Some(message) = codex_core::config::system_bwrap_warning(
|
||||
&config.permissions.effective_permission_profile(),
|
||||
&config.cwd,
|
||||
&session_configured.permission_profile,
|
||||
&session_configured.cwd,
|
||||
)
|
||||
{
|
||||
event_processor.process_warning(message);
|
||||
@@ -1334,8 +1369,8 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
responsesapi_client_metadata_patch: None,
|
||||
additional_context: None,
|
||||
environments: None,
|
||||
cwd: Some(default_cwd),
|
||||
runtime_workspace_roots: None,
|
||||
cwd: first_turn_cwd,
|
||||
runtime_workspace_roots: first_turn_workspace_roots,
|
||||
approval_policy: Some(default_approval_policy.into()),
|
||||
approvals_reviewer: None,
|
||||
sandbox_policy: None,
|
||||
@@ -1356,6 +1391,21 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
if summary_after_turn_start {
|
||||
let AppServerClient::InProcess(embedded_client) = &client else {
|
||||
unreachable!("local exec uses an embedded app-server");
|
||||
};
|
||||
let permissions = embedded_client
|
||||
.thread_permissions(primary_thread_id)
|
||||
.await?;
|
||||
session_configured.permission_profile = permissions.profile;
|
||||
event_processor.print_config_summary(
|
||||
&config,
|
||||
&prompt_summary,
|
||||
&session_configured,
|
||||
&permissions.workspace_roots,
|
||||
);
|
||||
}
|
||||
let task_id = response.turn.id;
|
||||
info!("Sent prompt with event ID: {task_id}");
|
||||
task_id
|
||||
@@ -1607,25 +1657,60 @@ fn thread_start_params_from_config(
|
||||
fn thread_resume_params_from_config(
|
||||
config: &Config,
|
||||
thread_id: String,
|
||||
overrides: &ConfigOverrides,
|
||||
approvals_reviewer_override: Option<codex_app_server_protocol::ApprovalsReviewer>,
|
||||
) -> ThreadResumeParams {
|
||||
let permissions = permissions_selection_from_config(config);
|
||||
let sandbox = permissions.is_none().then(|| {
|
||||
let sandbox = if permissions.is_none() {
|
||||
sandbox_mode_from_permission_profile(
|
||||
&config.permissions.effective_permission_profile(),
|
||||
config.cwd.as_path(),
|
||||
)
|
||||
});
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// A process default is not a new choice for an existing thread.
|
||||
let mut explicit_permissions = overrides.sandbox_mode.is_some();
|
||||
let mut runtime_workspace_roots = None;
|
||||
for layer in config
|
||||
.config_layer_stack
|
||||
.layers_high_to_low()
|
||||
.filter(|layer| {
|
||||
matches!(
|
||||
layer.name,
|
||||
ConfigLayerSource::SessionFlags
|
||||
| ConfigLayerSource::User {
|
||||
profile: Some(_),
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
{
|
||||
let legacy_workspace = layer
|
||||
.config
|
||||
.get("sandbox_workspace_write")
|
||||
.filter(|_| sandbox == Some(codex_app_server_protocol::SandboxMode::WorkspaceWrite));
|
||||
explicit_permissions |= layer.config.get("sandbox_mode").is_some()
|
||||
|| layer.config.get("default_permissions").is_some()
|
||||
|| legacy_workspace.is_some();
|
||||
if legacy_workspace
|
||||
.and_then(|settings| settings.get("writable_roots"))
|
||||
.is_some()
|
||||
{
|
||||
runtime_workspace_roots = Some(config.workspace_roots.clone());
|
||||
}
|
||||
}
|
||||
ThreadResumeParams {
|
||||
thread_id,
|
||||
model: config.model.clone(),
|
||||
model_provider: Some(config.model_provider_id.clone()),
|
||||
cwd: Some(config.cwd.to_string_lossy().to_string()),
|
||||
runtime_workspace_roots: Some(config.workspace_roots.clone()),
|
||||
cwd: (overrides.cwd.is_some() || runtime_workspace_roots.is_some())
|
||||
.then(|| config.cwd.to_string_lossy().into_owned()),
|
||||
runtime_workspace_roots,
|
||||
approval_policy: Some(config.permissions.approval_policy.value().into()),
|
||||
approvals_reviewer: approvals_reviewer_override,
|
||||
sandbox: sandbox.flatten(),
|
||||
permissions,
|
||||
sandbox: sandbox.filter(|_| explicit_permissions),
|
||||
permissions: permissions.filter(|_| explicit_permissions),
|
||||
config: thread_config_overrides_from_config(config),
|
||||
exclude_turns: true,
|
||||
..ThreadResumeParams::default()
|
||||
@@ -1717,7 +1802,7 @@ fn session_configured_from_thread_start_response(
|
||||
|
||||
fn session_configured_from_thread_resume_response(
|
||||
response: &ThreadResumeResponse,
|
||||
config: &Config,
|
||||
permission_profile: PermissionProfile,
|
||||
) -> Result<SessionConfiguredEvent, String> {
|
||||
session_configured_from_thread_response(
|
||||
&response.thread.session_id,
|
||||
@@ -1732,7 +1817,7 @@ fn session_configured_from_thread_resume_response(
|
||||
response.service_tier.clone(),
|
||||
response.approval_policy.to_core(),
|
||||
response.approvals_reviewer.to_core(),
|
||||
config.permissions.effective_permission_profile(),
|
||||
permission_profile,
|
||||
response.active_permission_profile.clone().map(Into::into),
|
||||
response.cwd.clone(),
|
||||
response.reasoning_effort.clone(),
|
||||
|
||||
@@ -565,11 +565,13 @@ async fn thread_resume_params_only_include_explicit_review_policy_override() {
|
||||
let params_without_override = thread_resume_params_from_config(
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
&ConfigOverrides::default(),
|
||||
/*approvals_reviewer_override*/ None,
|
||||
);
|
||||
let params_with_override = thread_resume_params_from_config(
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
&ConfigOverrides::default(),
|
||||
Some(codex_app_server_protocol::ApprovalsReviewer::AutoReview),
|
||||
);
|
||||
|
||||
@@ -719,6 +721,7 @@ async fn thread_lifecycle_params_preserve_hook_trust_bypass() {
|
||||
let resume_params = thread_resume_params_from_config(
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
&ConfigOverrides::default(),
|
||||
/*approvals_reviewer_override*/ None,
|
||||
);
|
||||
|
||||
@@ -755,6 +758,10 @@ async fn thread_lifecycle_params_include_legacy_sandbox_when_no_active_profile()
|
||||
let resume_params = thread_resume_params_from_config(
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
&ConfigOverrides {
|
||||
sandbox_mode: Some(SandboxMode::DangerFullAccess),
|
||||
..Default::default()
|
||||
},
|
||||
/*approvals_reviewer_override*/ None,
|
||||
);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user