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:
@@ -55,6 +55,8 @@ pub use codex_app_server::in_process::InProcessServerEvent;
|
||||
use codex_app_server::in_process::InProcessStartArgs;
|
||||
use codex_app_server::in_process::LogDbLayer;
|
||||
pub use codex_app_server::in_process::StateDbHandle;
|
||||
pub use codex_app_server::in_process::ThreadPermissions;
|
||||
use codex_app_server::in_process::ThreadPermissionsReader;
|
||||
pub use codex_app_server::verified_local_daemon_socket;
|
||||
use codex_app_server_protocol::ClientInfo;
|
||||
use codex_app_server_protocol::ClientNotification;
|
||||
@@ -76,6 +78,7 @@ pub use codex_core::otel_init::build_provider as build_otel_provider;
|
||||
pub use codex_exec_server::EnvironmentManager;
|
||||
pub use codex_exec_server::ExecServerRuntimeOptions;
|
||||
use codex_feedback::CodexFeedback;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::de::DeserializeOwned;
|
||||
@@ -362,6 +365,7 @@ enum ClientCommand {
|
||||
/// boundary.
|
||||
pub struct InProcessAppServerClient {
|
||||
command_tx: mpsc::Sender<ClientCommand>,
|
||||
thread_permissions_reader: ThreadPermissionsReader,
|
||||
event_rx: mpsc::UnboundedReceiver<InProcessServerEvent>,
|
||||
worker_handle: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
@@ -394,6 +398,7 @@ impl InProcessAppServerClient {
|
||||
let mut handle =
|
||||
codex_app_server::in_process::start(args.into_runtime_start_args()).await?;
|
||||
let request_sender = handle.sender();
|
||||
let thread_permissions_reader = handle.thread_permissions_reader();
|
||||
let (command_tx, mut command_rx) = mpsc::channel::<ClientCommand>(channel_capacity);
|
||||
// e9996ec62a preserved transcript events by awaiting a bounded queue, but that can
|
||||
// deadlock a foreground request whose response is behind unread notifications.
|
||||
@@ -500,6 +505,7 @@ impl InProcessAppServerClient {
|
||||
|
||||
Ok(Self {
|
||||
command_tx,
|
||||
thread_permissions_reader,
|
||||
event_rx,
|
||||
worker_handle,
|
||||
})
|
||||
@@ -511,6 +517,11 @@ impl InProcessAppServerClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads effective permissions for a thread loaded in this embedded server.
|
||||
pub async fn thread_permissions(&self, thread_id: ThreadId) -> IoResult<ThreadPermissions> {
|
||||
self.thread_permissions_reader.read(thread_id).await
|
||||
}
|
||||
|
||||
/// Sends a typed client request and returns raw JSON-RPC result.
|
||||
///
|
||||
/// Callers that expect a concrete response type should usually prefer
|
||||
@@ -614,6 +625,7 @@ impl InProcessAppServerClient {
|
||||
pub async fn shutdown(self) -> IoResult<()> {
|
||||
let Self {
|
||||
command_tx,
|
||||
thread_permissions_reader: _,
|
||||
event_rx,
|
||||
worker_handle,
|
||||
} = self;
|
||||
@@ -2202,6 +2214,7 @@ mod tests {
|
||||
|
||||
let mut client = InProcessAppServerClient {
|
||||
command_tx,
|
||||
thread_permissions_reader: ThreadPermissionsReader::default(),
|
||||
event_rx,
|
||||
worker_handle,
|
||||
};
|
||||
@@ -2310,6 +2323,7 @@ mod tests {
|
||||
});
|
||||
let client = InProcessAppServerClient {
|
||||
command_tx,
|
||||
thread_permissions_reader: ThreadPermissionsReader::default(),
|
||||
event_rx,
|
||||
worker_handle,
|
||||
};
|
||||
|
||||
@@ -45,7 +45,9 @@ use std::io::Error as IoError;
|
||||
use std::io::ErrorKind;
|
||||
use std::io::Result as IoResult;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
@@ -85,14 +87,18 @@ use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::ThreadConfigLoader;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::check_execpolicy_for_warnings;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::resolve_installation_id;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_feedback::CodexFeedback;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
pub use codex_rollout::StateDbHandle;
|
||||
pub use codex_state::log_db::LogDbLayer;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::timeout;
|
||||
@@ -226,6 +232,55 @@ enum ProcessorCommand {
|
||||
},
|
||||
}
|
||||
|
||||
/// Effective permissions and workspace roots reported by a loaded embedded thread.
|
||||
pub struct ThreadPermissions {
|
||||
pub profile: PermissionProfile,
|
||||
pub workspace_roots: Vec<PathUri>,
|
||||
}
|
||||
|
||||
/// Read access to effective permissions in a single embedded app-server runtime.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ThreadPermissionsReader {
|
||||
thread_manager: Arc<OnceLock<Weak<ThreadManager>>>,
|
||||
}
|
||||
|
||||
impl ThreadPermissionsReader {
|
||||
pub async fn read(&self, thread_id: ThreadId) -> IoResult<ThreadPermissions> {
|
||||
let thread_manager = self
|
||||
.thread_manager
|
||||
.get()
|
||||
.and_then(Weak::upgrade)
|
||||
.ok_or_else(|| {
|
||||
IoError::new(
|
||||
ErrorKind::BrokenPipe,
|
||||
"in-process app-server runtime is closed",
|
||||
)
|
||||
})?;
|
||||
let thread = thread_manager
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|err| IoError::new(ErrorKind::NotFound, err))?;
|
||||
let snapshot = thread.config_snapshot().await;
|
||||
let mut seen = HashSet::new();
|
||||
let workspace_roots = snapshot
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.map(PathUri::from_abs_path)
|
||||
.chain(
|
||||
snapshot
|
||||
.profile_workspace_roots
|
||||
.iter()
|
||||
.map(|root| root.as_uri().clone()),
|
||||
)
|
||||
.filter(|root| seen.insert(root.to_string()))
|
||||
.collect();
|
||||
Ok(ThreadPermissions {
|
||||
profile: snapshot.permission_profile,
|
||||
workspace_roots,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct InProcessClientSender {
|
||||
client_tx: mpsc::Sender<InProcessClientMessage>,
|
||||
@@ -296,6 +351,7 @@ impl InProcessClientSender {
|
||||
/// request/response helpers, and surface-specific startup policy.
|
||||
pub struct InProcessClientHandle {
|
||||
client: InProcessClientSender,
|
||||
thread_permissions_reader: ThreadPermissionsReader,
|
||||
event_rx: mpsc::Receiver<InProcessServerEvent>,
|
||||
runtime_handle: tokio::task::JoinHandle<()>,
|
||||
#[cfg(test)]
|
||||
@@ -303,6 +359,10 @@ pub struct InProcessClientHandle {
|
||||
}
|
||||
|
||||
impl InProcessClientHandle {
|
||||
pub fn thread_permissions_reader(&self) -> ThreadPermissionsReader {
|
||||
self.thread_permissions_reader.clone()
|
||||
}
|
||||
|
||||
/// Sends a typed client request into the in-process runtime.
|
||||
///
|
||||
/// The returned value is a transport-level `IoResult` containing either a
|
||||
@@ -484,6 +544,8 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
||||
let installation_id = resolve_installation_id(&args.config.codex_home).await?;
|
||||
let (client_tx, mut client_rx) = mpsc::channel::<InProcessClientMessage>(channel_capacity);
|
||||
let (event_tx, event_rx) = mpsc::channel::<InProcessServerEvent>(channel_capacity);
|
||||
let thread_permissions_reader = ThreadPermissionsReader::default();
|
||||
let thread_manager = Arc::clone(&thread_permissions_reader.thread_manager);
|
||||
|
||||
let runtime_handle = tokio::spawn(async move {
|
||||
let (outgoing_tx, outgoing_rx) = mpsc::channel::<OutgoingEnvelope>(channel_capacity);
|
||||
@@ -570,6 +632,7 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
||||
remote_control_handle: None,
|
||||
plugin_startup_tasks: Some(PluginStartupConfig::Current),
|
||||
}));
|
||||
thread_manager.get_or_init(|| processor.thread_manager());
|
||||
let mut thread_created_rx = processor.thread_created_receiver();
|
||||
let session = Arc::new(ConnectionSessionState::new(
|
||||
crate::transport::ConnectionOrigin::InProcess,
|
||||
@@ -889,6 +952,7 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
||||
|
||||
Ok(InProcessClientHandle {
|
||||
client: InProcessClientSender { client_tx },
|
||||
thread_permissions_reader,
|
||||
event_rx,
|
||||
runtime_handle,
|
||||
#[cfg(test)]
|
||||
@@ -1144,6 +1208,7 @@ mod tests {
|
||||
});
|
||||
let client = InProcessClientHandle {
|
||||
client: InProcessClientSender { client_tx },
|
||||
thread_permissions_reader: ThreadPermissionsReader::default(),
|
||||
event_rx,
|
||||
runtime_handle,
|
||||
_test_codex_home: None,
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::collections::HashSet;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use crate::attestation::app_server_attestation_provider;
|
||||
@@ -827,6 +828,10 @@ impl MessageProcessor {
|
||||
self.thread_processor.thread_created_receiver()
|
||||
}
|
||||
|
||||
pub(crate) fn thread_manager(&self) -> Weak<ThreadManager> {
|
||||
Arc::downgrade(&self.thread_processor.thread_manager)
|
||||
}
|
||||
|
||||
pub(crate) async fn daemon_recovery_snapshot(
|
||||
&self,
|
||||
) -> codex_app_server_transport::daemon_recovery::RecoverySnapshot {
|
||||
|
||||
@@ -92,11 +92,12 @@ fn latest_persisted_resume_settings(history: &[RolloutItem]) -> Option<Persisted
|
||||
})
|
||||
}),
|
||||
active_permission_profile: turn_context.active_permission_profile.clone(),
|
||||
unnamed_permission_profile: None,
|
||||
unnamed_permission_profile: unattributed_read_only_profile(
|
||||
&turn_context.permission_profile,
|
||||
turn_context.active_permission_profile.as_ref(),
|
||||
),
|
||||
}),
|
||||
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) => {
|
||||
// History without an identifiable owner can supply a profile ID, but
|
||||
// its raw filesystem grants may belong to another thread or executor.
|
||||
let settings = &event.thread_settings;
|
||||
Some(PersistedResumeSettings {
|
||||
approval_policy: settings.approval_policy,
|
||||
@@ -106,13 +107,30 @@ fn latest_persisted_resume_settings(history: &[RolloutItem]) -> Option<Persisted
|
||||
.unwrap_or(settings.approvals_reviewer),
|
||||
),
|
||||
active_permission_profile: settings.active_permission_profile.clone(),
|
||||
unnamed_permission_profile: None,
|
||||
unnamed_permission_profile: if event.thread_id.is_none() {
|
||||
unattributed_read_only_profile(
|
||||
&settings.permission_profile,
|
||||
settings.active_permission_profile.as_ref(),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn unattributed_read_only_profile(
|
||||
profile: &PermissionProfile,
|
||||
active_profile: Option<&ActivePermissionProfile>,
|
||||
) -> Option<PermissionProfile> {
|
||||
// Unattributed history can preserve built-in read-only access. Other concrete
|
||||
// profiles may carry grants that belong to another thread or executor.
|
||||
let read_only = PermissionProfile::read_only();
|
||||
(active_profile.is_none() && *profile == read_only).then_some(read_only)
|
||||
}
|
||||
|
||||
pub(super) fn latest_persisted_model_settings(
|
||||
history: &InitialHistory,
|
||||
) -> Option<&ThreadSettingsSnapshot> {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::PersistedResumeSettings;
|
||||
use super::latest_persisted_resume_settings;
|
||||
use codex_protocol::ThreadId;
|
||||
@@ -223,20 +225,35 @@ fn older_reviewer_is_used_when_latest_turn_context_omits_it() {
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
active_permission_profile: None,
|
||||
unnamed_permission_profile: None,
|
||||
unnamed_permission_profile: Some(PermissionProfile::read_only()),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unattributed_snapshot_does_not_restore_unnamed_permissions() {
|
||||
let history = [settings_item(
|
||||
fn an_unattributed_snapshot_restores_only_portable_read_only_permissions() {
|
||||
let mut item = settings_item(
|
||||
/*thread_id*/ None,
|
||||
AskForApproval::OnRequest,
|
||||
ApprovalsReviewer::User,
|
||||
/*active_permission_profile*/ None,
|
||||
)];
|
||||
);
|
||||
let thread_id = ThreadId::new();
|
||||
let expected = PersistedResumeSettings {
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::User),
|
||||
active_permission_profile: None,
|
||||
unnamed_permission_profile: Some(PermissionProfile::read_only()),
|
||||
};
|
||||
assert_eq!(
|
||||
PersistedResumeSettings::from_history(std::slice::from_ref(&item), thread_id),
|
||||
Some(expected)
|
||||
);
|
||||
let RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) = &mut item else {
|
||||
unreachable!("fixture must be a settings update");
|
||||
};
|
||||
event.thread_settings.permission_profile = PermissionProfile::Disabled;
|
||||
let settings =
|
||||
PersistedResumeSettings::from_history(&history, ThreadId::new()).expect("legacy settings");
|
||||
PersistedResumeSettings::from_history(&[item], thread_id).expect("legacy settings");
|
||||
assert_eq!(settings.unnamed_permission_profile, None);
|
||||
}
|
||||
|
||||
@@ -1990,7 +1990,7 @@ async fn cold_resume_reresolves_persisted_active_permission_profile() -> Result<
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cold_resume_with_removed_permission_profile_uses_configured_default() -> Result<()> {
|
||||
async fn cold_resume_with_removed_permission_profile_requires_explicit_selection() -> Result<()> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
for history_mode in [ThreadHistoryMode::Legacy, ThreadHistoryMode::Paginated] {
|
||||
let codex_home = TempDir::new()?;
|
||||
@@ -2016,22 +2016,35 @@ async fn cold_resume_with_removed_permission_profile_uses_configured_default() -
|
||||
.await?;
|
||||
let resume_id = mcp
|
||||
.send_thread_resume_request(ThreadResumeParams {
|
||||
thread_id,
|
||||
thread_id: thread_id.clone(),
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let ThreadResumeResponse {
|
||||
sandbox,
|
||||
active_permission_profile,
|
||||
..
|
||||
} = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??;
|
||||
let error = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_error_message(RequestId::Integer(resume_id)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(error.error.code, -32600);
|
||||
assert!(
|
||||
error
|
||||
.error
|
||||
.message
|
||||
.contains("saved permission profile `dev`")
|
||||
);
|
||||
|
||||
assert!(matches!(sandbox, AppSandboxPolicy::DangerFullAccess));
|
||||
let resume_id = mcp
|
||||
.send_thread_resume_request(ThreadResumeParams {
|
||||
thread_id,
|
||||
permissions: Some(BUILT_IN_PERMISSION_PROFILE_READ_ONLY.to_string()),
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let response: ThreadResumeResponse =
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??;
|
||||
assert_eq!(
|
||||
active_permission_profile,
|
||||
Some(ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS,
|
||||
))
|
||||
response.active_permission_profile,
|
||||
Some(ActivePermissionProfile::read_only())
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -2965,6 +2965,50 @@ async fn permission_profile_override_populates_runtime_permissions() -> std::io:
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persisted_read_only_respects_read_allowlist_and_drops_default_proxy() -> anyhow::Result<()>
|
||||
{
|
||||
let codex_home = TempDir::new()?;
|
||||
let cwd = TempDir::new()?;
|
||||
let config_toml = toml::from_str(
|
||||
r#"
|
||||
default_permissions = "dev"
|
||||
|
||||
[permissions.dev.filesystem]
|
||||
":workspace_roots" = "write"
|
||||
|
||||
[permissions.dev.network]
|
||||
enabled = true
|
||||
"#,
|
||||
)?;
|
||||
let config = Config::load_from_base_config_with_overrides(
|
||||
config_toml,
|
||||
ConfigOverrides {
|
||||
cwd: Some(cwd.path().to_path_buf()),
|
||||
persisted_permission_profile: Some(PermissionProfile::read_only()),
|
||||
..Default::default()
|
||||
},
|
||||
codex_home.abs(),
|
||||
)
|
||||
.await?;
|
||||
let (file_system, network) = config
|
||||
.permissions
|
||||
.effective_permission_profile()
|
||||
.to_runtime_permissions();
|
||||
let cwd = cwd.path();
|
||||
assert_eq!(
|
||||
(
|
||||
file_system.can_read_local_path_with_cwd(cwd, cwd),
|
||||
file_system.can_write_local_path_with_cwd(cwd, cwd),
|
||||
file_system.can_read_local_path_with_cwd(codex_home.path(), cwd),
|
||||
network,
|
||||
),
|
||||
(true, false, false, NetworkSandboxPolicy::Restricted)
|
||||
);
|
||||
assert!(config.permissions.network.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persisted_permissions_initialize_proxy_with_expandable_managed_allowlist()
|
||||
-> anyhow::Result<()> {
|
||||
@@ -3072,20 +3116,20 @@ extends = ":workspace"
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_persisted_permission_profile_id_uses_configured_default() -> std::io::Result<()> {
|
||||
async fn missing_persisted_permission_profile_id_requires_explicit_selection() -> std::io::Result<()>
|
||||
{
|
||||
let codex_home = TempDir::new()?;
|
||||
let cwd = TempDir::new()?;
|
||||
let project_key = cwd.path().to_string_lossy().to_string();
|
||||
|
||||
for (configured_default, configured_sandbox, expected_active_profile) in [
|
||||
for (configured_default, configured_sandbox) in [
|
||||
(
|
||||
Some(BUILT_IN_PERMISSION_PROFILE_READ_ONLY.to_string()),
|
||||
Some(BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS.to_string()),
|
||||
None,
|
||||
Some(ActivePermissionProfile::read_only()),
|
||||
),
|
||||
(None, Some(SandboxMode::ReadOnly), None),
|
||||
(None, Some(SandboxMode::WorkspaceWrite)),
|
||||
] {
|
||||
let config = Config::load_from_base_config_with_overrides(
|
||||
let error = Config::load_from_base_config_with_overrides(
|
||||
ConfigToml {
|
||||
default_permissions: configured_default,
|
||||
sandbox_mode: configured_sandbox,
|
||||
@@ -3104,34 +3148,34 @@ async fn missing_persisted_permission_profile_id_uses_configured_default() -> st
|
||||
},
|
||||
codex_home.abs(),
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
.expect_err("a missing saved profile must require an explicit selection");
|
||||
|
||||
assert_eq!(
|
||||
config.permissions.active_permission_profile(),
|
||||
expected_active_profile
|
||||
);
|
||||
assert_eq!(
|
||||
config.permissions.effective_permission_profile(),
|
||||
PermissionProfile::read_only()
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("saved permission profile `removed-profile`")
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_persisted_permission_profile_uses_configured_default() -> std::io::Result<()> {
|
||||
async fn invalid_persisted_permission_profile_requires_explicit_selection() -> std::io::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let cwd = TempDir::new()?;
|
||||
for invalid_profile in [
|
||||
"extends = \"removed-parent\"",
|
||||
"extends = \":read-only\"\n\n[permissions.dev.filesystem]\nglob_scan_max_depth = 0",
|
||||
"extends = \"base\"\n\n[permissions.base]\nextends = \"dev\"",
|
||||
] {
|
||||
let config_toml = toml::from_str(&format!(
|
||||
"default_permissions = \":danger-full-access\"\n\n[permissions.dev]\n{invalid_profile}"
|
||||
))
|
||||
.expect("permission profile config should deserialize");
|
||||
|
||||
let config = Config::load_from_base_config_with_overrides(
|
||||
let error = Config::load_from_base_config_with_overrides(
|
||||
config_toml,
|
||||
ConfigOverrides {
|
||||
cwd: Some(cwd.path().to_path_buf()),
|
||||
@@ -3140,63 +3184,15 @@ async fn invalid_persisted_permission_profile_uses_configured_default() -> std::
|
||||
},
|
||||
codex_home.abs(),
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
.expect_err("an invalid saved profile must require an explicit selection");
|
||||
|
||||
assert_eq!(
|
||||
config.permissions.active_permission_profile(),
|
||||
Some(ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS,
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
config.permissions.effective_permission_profile(),
|
||||
PermissionProfile::Disabled
|
||||
);
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
|
||||
assert!(error.to_string().contains("saved permission profile `dev`"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persisted_profile_cycle_uses_configured_default() -> std::io::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let cwd = TempDir::new()?;
|
||||
let config_toml = toml::from_str(
|
||||
r#"
|
||||
default_permissions = ":danger-full-access"
|
||||
|
||||
[permissions.dev]
|
||||
extends = "base"
|
||||
|
||||
[permissions.base]
|
||||
extends = "dev"
|
||||
"#,
|
||||
)
|
||||
.expect("permission profile config should deserialize");
|
||||
|
||||
let config = Config::load_from_base_config_with_overrides(
|
||||
config_toml,
|
||||
ConfigOverrides {
|
||||
cwd: Some(cwd.path().to_path_buf()),
|
||||
persisted_permission_profile_id: Some("dev".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
codex_home.abs(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert_eq!(
|
||||
config.permissions.active_permission_profile(),
|
||||
Some(ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS,
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
config.permissions.effective_permission_profile(),
|
||||
PermissionProfile::Disabled
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_explicit_default_permissions_remains_an_error() -> std::io::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
@@ -2798,11 +2798,12 @@ pub struct ConfigOverrides {
|
||||
pub permission_profile: Option<PermissionProfile>,
|
||||
pub default_permissions: Option<String>,
|
||||
/// Permission profile ID recovered from persisted thread state. Explicit
|
||||
/// permission overrides take precedence, and stale profile IDs fall back
|
||||
/// to the configured default.
|
||||
/// permission overrides take precedence. An unavailable saved profile
|
||||
/// requires an explicit selection.
|
||||
pub persisted_permission_profile_id: Option<String>,
|
||||
/// Unnamed permissions from a thread-owned rollout snapshot. These are
|
||||
/// fallback state: explicit overrides and current requirements take priority.
|
||||
/// Unnamed permissions from a thread-owned rollout snapshot, or canonical
|
||||
/// read-only permissions recovered from older history. Explicit overrides
|
||||
/// and current requirements take priority.
|
||||
pub persisted_permission_profile: Option<PermissionProfile>,
|
||||
pub model_provider: Option<String>,
|
||||
pub service_tier: Option<Option<String>>,
|
||||
@@ -3739,12 +3740,29 @@ impl Config {
|
||||
sandbox_mode,
|
||||
);
|
||||
let requirements_toml = config_layer_stack.requirements_toml();
|
||||
let restore_persisted_profile = sandbox_mode.is_none()
|
||||
&& permission_profile.is_none()
|
||||
&& default_permissions_override.is_none()
|
||||
&& persisted_permission_profile_id.is_none();
|
||||
let persisted_read_only = restore_persisted_profile
|
||||
&& persisted_permission_profile
|
||||
.as_ref()
|
||||
.is_some_and(|profile| *profile == PermissionProfile::read_only());
|
||||
if persisted_read_only
|
||||
&& !permission_profile_is_allowed(
|
||||
&config_layer_stack,
|
||||
BUILT_IN_READ_ONLY_PROFILE,
|
||||
&PermissionProfile::read_only(),
|
||||
)
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"The saved read-only permission profile is disallowed by requirements. Select a permission profile explicitly to continue.",
|
||||
));
|
||||
}
|
||||
let persisted_permission_profile = persisted_permission_profile.filter(|profile| {
|
||||
sandbox_mode.is_none()
|
||||
&& permission_profile.is_none()
|
||||
&& default_permissions_override.is_none()
|
||||
&& persisted_permission_profile_id.is_none()
|
||||
&& requirements_toml.allowed_permission_profiles.is_none()
|
||||
restore_persisted_profile
|
||||
&& (persisted_read_only || requirements_toml.allowed_permission_profiles.is_none())
|
||||
// Executor-owned enforcement and materialized grants are not portable
|
||||
// thread defaults. Reject the original mode before preserving denials.
|
||||
&& !matches!(profile, PermissionProfile::External { .. })
|
||||
@@ -3881,7 +3899,7 @@ impl Config {
|
||||
};
|
||||
dedupe_absolute_paths(&mut workspace_roots);
|
||||
let (
|
||||
configured_network_proxy_config,
|
||||
mut configured_network_proxy_config,
|
||||
mut permission_profile,
|
||||
mut file_system_sandbox_policy,
|
||||
mut active_permission_profile,
|
||||
@@ -4022,6 +4040,21 @@ impl Config {
|
||||
)
|
||||
};
|
||||
if let Some(saved) = persisted_permission_profile {
|
||||
// Canonical read-only recovery can remove writes without replacing a
|
||||
// narrower read allowlist from the current configuration.
|
||||
let saved = if persisted_read_only
|
||||
&& (!file_system_sandbox_policy.has_full_disk_read_access()
|
||||
|| matches!(permission_profile, PermissionProfile::External { .. }))
|
||||
{
|
||||
permission_profile.intersect_with_read_only().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"Could not restore the saved read-only permission profile under external enforcement. Select a permission profile explicitly to continue.",
|
||||
)
|
||||
})?
|
||||
} else {
|
||||
saved
|
||||
};
|
||||
let (mut saved_file_system, saved_network) = saved.to_runtime_permissions();
|
||||
saved_file_system.preserve_deny_read_restrictions_from(&file_system_sandbox_policy);
|
||||
let restored = PermissionProfile::from_runtime_permissions_with_enforcement(
|
||||
@@ -4035,6 +4068,9 @@ impl Config {
|
||||
) {
|
||||
permission_profile = restored;
|
||||
file_system_sandbox_policy = saved_file_system;
|
||||
if persisted_read_only {
|
||||
configured_network_proxy_config = NetworkProxyConfig::default();
|
||||
}
|
||||
active_permission_profile = None;
|
||||
profile_workspace_roots.clear();
|
||||
}
|
||||
@@ -5231,7 +5267,7 @@ fn resolve_effective_permission_selection<'a>(
|
||||
let profiles = merge_managed_permission_profiles(configured_profiles, requirements_toml)?;
|
||||
validate_user_permission_profile_names(profiles.as_ref())?;
|
||||
validate_required_permission_profile_catalog(requirements_toml, profiles.as_ref())?;
|
||||
let valid_persisted_profile_id = persisted_profile_id.and_then(|(profile_id, context)| {
|
||||
if let Some((profile_id, context)) = persisted_profile_id {
|
||||
compile_permission_profile(
|
||||
profiles.as_ref(),
|
||||
profile_id,
|
||||
@@ -5239,11 +5275,17 @@ fn resolve_effective_permission_selection<'a>(
|
||||
/*workspace_write*/ None,
|
||||
&mut Vec::new(),
|
||||
)
|
||||
.is_ok()
|
||||
.then_some(profile_id)
|
||||
});
|
||||
.map_err(|err| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"Could not load saved permission profile `{profile_id}`: {err}. Select a permission profile explicitly to continue."
|
||||
),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
let selected_profile_id = resolve_default_permissions(
|
||||
default_permissions_override.or(valid_persisted_profile_id),
|
||||
default_permissions_override.or(persisted_profile_id.map(|(profile_id, _)| profile_id)),
|
||||
configured_default_profile_id,
|
||||
requirements_toml,
|
||||
startup_warnings,
|
||||
@@ -5253,7 +5295,7 @@ fn resolve_effective_permission_selection<'a>(
|
||||
profiles,
|
||||
selected_profile_id,
|
||||
persisted_profile_id_was_provided: default_permissions_override.is_none()
|
||||
&& valid_persisted_profile_id.is_some(),
|
||||
&& persisted_profile_id.is_some(),
|
||||
requirements_force_profile_selection: requirements_toml
|
||||
.allowed_permission_profiles
|
||||
.is_some(),
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
|
||||
|
||||
@@ -676,11 +676,16 @@ async fn exec_resume_by_id_appends_to_existing_file() -> anyhow::Result<()> {
|
||||
let server = responses::start_sse_server().await;
|
||||
let _response_mock = mount_exec_responses(&server, /*count*/ 2).await;
|
||||
|
||||
// 1) First run: create a session
|
||||
std::fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
"default_permissions = ':workspace'",
|
||||
)?;
|
||||
// Start read-only despite the writable process default.
|
||||
let marker = format!("resume-by-id-{}", Uuid::new_v4());
|
||||
let prompt = format!("echo {marker}");
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.args(["-c", "default_permissions=':read-only'"])
|
||||
.arg("--skip-git-repo-check")
|
||||
.arg(&prompt)
|
||||
.assert()
|
||||
@@ -699,13 +704,21 @@ async fn exec_resume_by_id_appends_to_existing_file() -> anyhow::Result<()> {
|
||||
let marker2 = format!("resume-by-id-2-{}", Uuid::new_v4());
|
||||
let prompt2 = format!("echo {marker2}");
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
let output = test
|
||||
.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.args(["--color", "never"])
|
||||
.arg(&prompt2)
|
||||
.arg("resume")
|
||||
.arg(&session_id)
|
||||
.assert()
|
||||
.success();
|
||||
.output()?;
|
||||
assert!(output.status.success(), "resume failed: {output:?}");
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
let sandbox_summary = stderr
|
||||
.lines()
|
||||
.find(|line| line.starts_with("sandbox: "))
|
||||
.context("missing sandbox startup summary")?;
|
||||
insta::assert_snapshot!(sandbox_summary, @"sandbox: read-only");
|
||||
|
||||
let resumed_path = find_session_file_containing_marker(&sessions_dir, &marker2)
|
||||
.expect("no resumed session file containing marker2");
|
||||
@@ -716,6 +729,324 @@ async fn exec_resume_by_id_appends_to_existing_file() -> anyhow::Result<()> {
|
||||
let content = std::fs::read_to_string(&resumed_path)?;
|
||||
assert!(content.contains(&marker));
|
||||
assert!(content.contains(&marker2));
|
||||
let turn_profiles = content
|
||||
.lines()
|
||||
.map(serde_json::from_str::<Value>)
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.filter(|item| item["type"] == "turn_context")
|
||||
.map(|item| item["payload"]["active_permission_profile"]["id"].clone())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(turn_profiles, [":read-only", ":read-only"]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_resume_enforces_read_only_on_first_shell_call() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
core_test_support::skip_if_sandbox!(Ok(()));
|
||||
#[cfg(target_os = "linux")]
|
||||
if super::sandbox::linux_sandbox_test_env().await.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_sse_server().await;
|
||||
std::fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
"default_permissions = ':workspace'",
|
||||
)?;
|
||||
let shell_args = serde_json::json!({
|
||||
"cmd": "printf 'shell reached\\n'; printf probe > resume-write.txt",
|
||||
"shell": "/bin/sh",
|
||||
"login": false,
|
||||
});
|
||||
let mock = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
exec_sse_response(/*index*/ 0),
|
||||
responses::sse(vec![
|
||||
responses::ev_function_call("write-probe", "exec_command", &shell_args.to_string()),
|
||||
responses::ev_completed("response-with-probe"),
|
||||
]),
|
||||
exec_sse_response(/*index*/ 2),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
let marker = format!("resume-enforcement-{}", Uuid::new_v4());
|
||||
test.cmd_with_server(&server)
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"-c",
|
||||
"default_permissions=':read-only'",
|
||||
])
|
||||
.arg(&marker)
|
||||
.assert()
|
||||
.success();
|
||||
let path = find_session_file_containing_marker(&test.home_path().join("sessions"), &marker)
|
||||
.context("missing initial session")?;
|
||||
let session_id = extract_conversation_id(&path);
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"resume",
|
||||
&session_id,
|
||||
"check workspace write access",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let tool_output = mock
|
||||
.last_request()
|
||||
.and_then(|request| request.function_call_output_text("write-probe"))
|
||||
.context("missing first-turn shell output")?;
|
||||
assert!(
|
||||
tool_output.lines().any(|line| line == "shell reached"),
|
||||
"the shell did not start: {tool_output}",
|
||||
);
|
||||
let tool_output_lower = tool_output.to_ascii_lowercase();
|
||||
assert!(
|
||||
[
|
||||
"permission denied",
|
||||
"operation not permitted",
|
||||
"read-only file system"
|
||||
]
|
||||
.iter()
|
||||
.any(|denial| tool_output_lower.contains(denial)),
|
||||
"expected the shell write to be denied: {tool_output}",
|
||||
);
|
||||
assert!(!test.cwd_path().join("resume-write.txt").try_exists()?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_resume_adds_only_requested_roots_to_saved_workspace() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_sse_server().await;
|
||||
let _mock = mount_exec_responses(&server, /*count*/ 3).await;
|
||||
let cwd =
|
||||
codex_utils_absolute_path::canonicalize_existing_preserving_symlinks(test.cwd_path())?;
|
||||
let scratch = cwd.join("scratch");
|
||||
let extra = cwd.join("extra");
|
||||
std::fs::create_dir(&scratch)?;
|
||||
std::fs::create_dir(&extra)?;
|
||||
let marker = "start with only scratch writable";
|
||||
test.cmd_with_server(&server)
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"-c",
|
||||
"default_permissions=':workspace'",
|
||||
"-C",
|
||||
])
|
||||
.arg(&scratch)
|
||||
.arg(marker)
|
||||
.assert()
|
||||
.success();
|
||||
let rollout = find_session_file_containing_marker(&test.home_path().join("sessions"), marker)
|
||||
.context("missing initial session")?;
|
||||
let id = extract_conversation_id(&rollout);
|
||||
for (args, expected_roots) in [
|
||||
(vec![], vec![&scratch]),
|
||||
(vec!["--add-dir", "extra"], vec![&scratch, &extra]),
|
||||
] {
|
||||
let output = test
|
||||
.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.args(args)
|
||||
.args(["resume", &id, "continue"])
|
||||
.output()?;
|
||||
assert!(output.status.success(), "resume failed: {output:?}");
|
||||
if expected_roots.contains(&&extra) {
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
let summary = stderr
|
||||
.lines()
|
||||
.find(|line| line.starts_with("sandbox: "))
|
||||
.context("missing sandbox summary")?;
|
||||
assert!(summary.contains(&*extra.to_string_lossy()), "{summary}");
|
||||
}
|
||||
let settings = std::fs::read_to_string(&rollout)?
|
||||
.lines()
|
||||
.rev()
|
||||
.map(serde_json::from_str::<Value>)
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.find(|item| item["payload"]["type"] == "thread_settings_applied")
|
||||
.context("missing resumed settings")?;
|
||||
let snapshot = &settings["payload"]["thread_settings"];
|
||||
assert_eq!(snapshot["cwd"], serde_json::json!(scratch));
|
||||
assert_eq!(
|
||||
snapshot["runtime_workspace_roots"],
|
||||
serde_json::json!(expected_roots)
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_resume_restores_unnamed_read_only_from_legacy_history() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_sse_server().await;
|
||||
let _mock = mount_exec_responses(&server, /*count*/ 2).await;
|
||||
std::fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
"default_permissions = ':workspace'",
|
||||
)?;
|
||||
let marker = format!("resume-legacy-{}", Uuid::new_v4());
|
||||
test.cmd_with_server(&server)
|
||||
.args(["--skip-git-repo-check", "--sandbox", "read-only"])
|
||||
.arg(&marker)
|
||||
.assert()
|
||||
.success();
|
||||
let path = find_session_file_containing_marker(&test.home_path().join("sessions"), &marker)
|
||||
.context("missing initial session")?;
|
||||
let session_id = extract_conversation_id(&path);
|
||||
let history = std::fs::read_to_string(&path)?;
|
||||
let mut legacy_history = String::new();
|
||||
for line in history.lines() {
|
||||
let item: Value = serde_json::from_str(line)?;
|
||||
if item["type"] == "event_msg" && item["payload"]["type"] == "thread_settings_applied" {
|
||||
continue;
|
||||
}
|
||||
if item["type"] == "turn_context" {
|
||||
assert!(item["payload"]["active_permission_profile"].is_null());
|
||||
}
|
||||
legacy_history.push_str(line);
|
||||
legacy_history.push('\n');
|
||||
}
|
||||
std::fs::write(&path, legacy_history)?;
|
||||
|
||||
let output = test
|
||||
.cmd_with_server(&server)
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"--color",
|
||||
"never",
|
||||
"resume",
|
||||
&session_id,
|
||||
"resume an older read-only session",
|
||||
])
|
||||
.output()?;
|
||||
assert!(output.status.success(), "resume failed: {output:?}");
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
let summary = stderr
|
||||
.lines()
|
||||
.find(|line| line.starts_with("sandbox: "))
|
||||
.context("missing startup permission summary")?;
|
||||
insta::assert_snapshot!(summary, @"sandbox: read-only");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_resume_preserves_explicit_legacy_workspace_settings() -> anyhow::Result<()> {
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let test = test_codex_exec();
|
||||
let server = responses::start_sse_server().await;
|
||||
let _mock = mount_exec_responses(&server, /*count*/ 3).await;
|
||||
std::fs::create_dir(test.cwd_path().join("scratch"))?;
|
||||
std::fs::write(
|
||||
test.home_path().join("config.toml"),
|
||||
r#"
|
||||
sandbox_mode = "workspace-write"
|
||||
|
||||
[permissions.partial]
|
||||
extends = ":read-only"
|
||||
|
||||
[permissions.partial.filesystem.":workspace_roots"]
|
||||
scratch = "write"
|
||||
"#,
|
||||
)?;
|
||||
let marker = format!("resume-legacy-{}", Uuid::new_v4());
|
||||
test.cmd_with_server(&server)
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"-c",
|
||||
"default_permissions='partial'",
|
||||
])
|
||||
.arg(&marker)
|
||||
.assert()
|
||||
.success();
|
||||
let path = find_session_file_containing_marker(&test.home_path().join("sessions"), &marker)
|
||||
.context("missing initial session")?;
|
||||
let session_id = extract_conversation_id(&path);
|
||||
|
||||
let output = test
|
||||
.cmd_with_server(&server)
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"--color",
|
||||
"never",
|
||||
"resume",
|
||||
&session_id,
|
||||
"resume with the saved profile",
|
||||
])
|
||||
.output()?;
|
||||
assert!(output.status.success(), "resume failed: {output:?}");
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
let sandbox_summary = stderr
|
||||
.lines()
|
||||
.find(|line| line.starts_with("sandbox: "))
|
||||
.context("missing sandbox startup summary")?;
|
||||
insta::assert_snapshot!(sandbox_summary, @"sandbox: custom permissions");
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.args([
|
||||
"--skip-git-repo-check",
|
||||
"-c",
|
||||
"sandbox_workspace_write.exclude_tmpdir_env_var=true",
|
||||
])
|
||||
.args([
|
||||
"resume",
|
||||
&session_id,
|
||||
"resume with explicit legacy settings",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let turns = std::fs::read_to_string(path)?
|
||||
.lines()
|
||||
.map(serde_json::from_str::<codex_rollout::RolloutItem>)
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.filter_map(|item| match item {
|
||||
codex_rollout::RolloutItem::TurnContext(turn) => Some(turn),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let [started, restored, overridden] = turns.as_slice() else {
|
||||
anyhow::bail!("expected three turns, got {}", turns.len());
|
||||
};
|
||||
assert_eq!(
|
||||
[started, restored, overridden].map(|turn| turn
|
||||
.active_permission_profile
|
||||
.as_ref()
|
||||
.map(|profile| profile.id.as_str())),
|
||||
[Some("partial"), Some("partial"), None],
|
||||
);
|
||||
let (file_system, _) = overridden.permission_profile.to_runtime_permissions();
|
||||
assert!(
|
||||
file_system
|
||||
.can_write_local_path_with_cwd(overridden.cwd.as_path(), overridden.cwd.as_path())
|
||||
);
|
||||
assert!(!file_system.entries.iter().any(|entry| {
|
||||
entry.access.can_write()
|
||||
&& matches!(
|
||||
entry.path,
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Tmpdir
|
||||
}
|
||||
)
|
||||
}));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ pub fn summarize_permission_profile(
|
||||
}
|
||||
}
|
||||
|
||||
if workspace_writable {
|
||||
if workspace_writable && (cwd.is_opaque() || policy.can_write_path(cwd, &context)) {
|
||||
let mut writable_entries = vec!["workdir".to_string()];
|
||||
if slash_tmp_writable {
|
||||
writable_entries.push("/tmp".to_string());
|
||||
@@ -77,10 +77,12 @@ pub fn summarize_permission_profile(
|
||||
workspace_roots
|
||||
.iter()
|
||||
.filter(|root| root.to_string() != cwd.to_string())
|
||||
.filter(|root| policy.can_write_path(root, &context))
|
||||
.map(PathUri::inferred_native_path_string),
|
||||
);
|
||||
format!("workspace-write [{}]", writable_entries.join(", "))
|
||||
} else if other_writes
|
||||
} else if workspace_writable
|
||||
|| other_writes
|
||||
|| tmpdir_writable
|
||||
|| (cwd.infer_path_convention() == Some(PathConvention::Posix)
|
||||
&& slash_tmp_writable)
|
||||
|
||||
Reference in New Issue
Block a user