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:
viyatb-oai
2026-11-18 05:13:56 +00:00
committed by copyberry
parent b78fa4af86
commit 89feadf3cc
16 changed files with 756 additions and 150 deletions
+65
View File
@@ -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);
}