mirror of
https://github.com/openai/codex.git
synced 2026-11-15 21:50:46 +00:00
Keep step settings and approval environments consistent (#46556)
## Why Background processes can outlive their launching turn. Their approval reviews need the originating environment's filesystem restrictions, even when the active turn uses a different environment. Remote restrictions must also be resolved using executor paths rather than the local filesystem. ## What changed - Capture settings and environment selections together in `StepInputs`. Preserve the captured selection during active model updates while allowing environment startup to finish. - Carry environment IDs into Guardian network and `execve` requests, and use the owning process's environment with current review settings. Refresh environment readiness for network requests that fall back to the active turn. - Resolve remote denied paths and globs using the executor's policy context. Decline automatic approval when the request's environment is unavailable or an explicitly denied temporary directory cannot be resolved. ## Testing Add regression coverage for active model updates retaining their environment while the next turn adopts a new selection, background approvals using their owning environment, newly ready network environments, and remote denied paths and globs, including Windows paths and missing temporary-directory metadata. GitOrigin-RevId: b620d4b030c597a4f430fe0500864fa5469db3d4
This commit is contained in:
@@ -42,6 +42,7 @@ pub(crate) enum GuardianApprovalRequest {
|
||||
#[cfg(unix)]
|
||||
Execve {
|
||||
id: String,
|
||||
environment_id: String,
|
||||
source: GuardianCommandSource,
|
||||
program: String,
|
||||
argv: Vec<String>,
|
||||
@@ -57,6 +58,7 @@ pub(crate) enum GuardianApprovalRequest {
|
||||
NetworkAccess {
|
||||
id: String,
|
||||
turn_id: String,
|
||||
environment_id: String,
|
||||
target: String,
|
||||
host: String,
|
||||
protocol: NetworkApprovalProtocol,
|
||||
@@ -84,6 +86,21 @@ pub(crate) enum GuardianApprovalRequest {
|
||||
},
|
||||
}
|
||||
|
||||
impl GuardianApprovalRequest {
|
||||
pub(super) fn background_environment_id(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::NetworkAccess { environment_id, .. } => Some(environment_id),
|
||||
#[cfg(unix)]
|
||||
Self::Execve { environment_id, .. } => Some(environment_id),
|
||||
Self::ExecCommand { .. }
|
||||
| Self::WriteStdin { .. }
|
||||
| Self::ApplyPatch { .. }
|
||||
| Self::McpToolCall { .. }
|
||||
| Self::RequestPermissions { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct GuardianNetworkAccessTrigger {
|
||||
@@ -289,6 +306,7 @@ pub(crate) fn guardian_approval_request_to_json(
|
||||
#[cfg(unix)]
|
||||
GuardianApprovalRequest::Execve {
|
||||
id: _,
|
||||
environment_id: _,
|
||||
source,
|
||||
program,
|
||||
argv,
|
||||
@@ -315,6 +333,7 @@ pub(crate) fn guardian_approval_request_to_json(
|
||||
GuardianApprovalRequest::NetworkAccess {
|
||||
id: _,
|
||||
turn_id: _,
|
||||
environment_id: _,
|
||||
target,
|
||||
host,
|
||||
protocol,
|
||||
@@ -416,6 +435,7 @@ pub(crate) fn guardian_assessment_action(
|
||||
GuardianApprovalRequest::NetworkAccess {
|
||||
id: _id,
|
||||
turn_id: _turn_id,
|
||||
environment_id: _,
|
||||
target,
|
||||
host,
|
||||
protocol,
|
||||
|
||||
@@ -161,7 +161,7 @@ impl From<Arc<TurnContext>> for GuardianReviewContext {
|
||||
.extension_data
|
||||
.get::<codex_api::ResponseId>()
|
||||
.map(|id| id.0.clone()),
|
||||
environments: turn.environments.clone(),
|
||||
environments: turn.initial_environments.clone(),
|
||||
model_info: Arc::clone(turn.model_info()),
|
||||
reasoning_effort: turn.reasoning_effort().cloned(),
|
||||
reasoning_summary: turn.reasoning_summary(),
|
||||
|
||||
@@ -27,6 +27,7 @@ use crate::context::NodeReplReviewEvidenceMode;
|
||||
use crate::context::node_repl_review_evidence_mode;
|
||||
use crate::event_mapping::is_contextual_user_message_content;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn_context::TurnEnvironment;
|
||||
use codex_utils_output_truncation::TruncationPolicy;
|
||||
use codex_utils_output_truncation::approx_bytes_for_tokens;
|
||||
use codex_utils_output_truncation::truncate_text;
|
||||
@@ -143,7 +144,9 @@ pub(crate) async fn build_guardian_prompt_items_with_parent_turn(
|
||||
)
|
||||
}),
|
||||
};
|
||||
let permissions = parent_context.map(parent_turn_permissions);
|
||||
let permissions = parent_context
|
||||
.map(|context| parent_turn_permissions(context, &request))
|
||||
.transpose()?;
|
||||
let node_repl_snapshot = if node_repl_transcripts_enabled {
|
||||
session
|
||||
.services
|
||||
@@ -208,25 +211,61 @@ pub(crate) async fn build_guardian_prompt_items_with_parent_turn(
|
||||
})
|
||||
}
|
||||
|
||||
fn parent_turn_permissions(context: &GuardianReviewContext) -> PermissionContext {
|
||||
fn parent_turn_permissions(
|
||||
context: &GuardianReviewContext,
|
||||
request: &GuardianApprovalRequest,
|
||||
) -> anyhow::Result<PermissionContext> {
|
||||
let turn = context.turn();
|
||||
let environment = context.environments().primary();
|
||||
#[allow(deprecated)]
|
||||
let cwd = environment
|
||||
.and_then(|environment| environment.cwd().to_abs_path().ok())
|
||||
.unwrap_or_else(|| turn.cwd.clone());
|
||||
let permission_profile = context
|
||||
.environments()
|
||||
.permission_profile_or_else(|| turn.permission_profile());
|
||||
let environment = match request.background_environment_id() {
|
||||
Some(id) => Some(
|
||||
context
|
||||
.environments()
|
||||
.turn_environments()
|
||||
.find(|environment| environment.selection.environment_id == id)
|
||||
.ok_or_else(|| anyhow::anyhow!("approval environment {id} is unavailable"))?,
|
||||
),
|
||||
None => context.environments().primary(),
|
||||
};
|
||||
let native_cwd = environment
|
||||
.filter(|environment| !environment.environment.is_remote())
|
||||
.and_then(|environment| environment.cwd().to_abs_path().ok());
|
||||
let permission_profile = environment
|
||||
.map(TurnEnvironment::permission_profile_with_workspace_roots)
|
||||
.unwrap_or_else(|| turn.permission_profile());
|
||||
let file_system_policy = permission_profile.file_system_sandbox_policy();
|
||||
PermissionContext {
|
||||
// Remote restrictions must not be interpreted using the filesystem running Guardian.
|
||||
// Older executors may not report their temp folders. If a rule explicitly denies those
|
||||
// folders, decline automatic approval rather than guess. Default rules do not deny them.
|
||||
if let Some(environment) = environment
|
||||
&& native_cwd.is_none()
|
||||
{
|
||||
let sandbox = environment.sandbox_context(/*additional_permissions*/ None);
|
||||
let paths = sandbox.policy_context();
|
||||
let mut denied_globs = file_system_policy
|
||||
.get_unreadable_globs_with_context(&paths)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
denied_globs.sort();
|
||||
denied_globs.dedup();
|
||||
return Ok(PermissionContext {
|
||||
denied_paths: file_system_policy
|
||||
.get_unreadable_roots_with_context(&paths)
|
||||
.map_err(anyhow::Error::msg)?
|
||||
.into_iter()
|
||||
.map(|path| path.inferred_native_path_string())
|
||||
.collect(),
|
||||
denied_globs,
|
||||
});
|
||||
}
|
||||
#[allow(deprecated)]
|
||||
let cwd = native_cwd.unwrap_or_else(|| turn.cwd.clone());
|
||||
Ok(PermissionContext {
|
||||
denied_paths: file_system_policy
|
||||
.get_unreadable_roots_with_cwd(&cwd)
|
||||
.into_iter()
|
||||
.map(|root| root.to_string_lossy().into_owned())
|
||||
.collect(),
|
||||
denied_globs: file_system_policy.get_unreadable_globs_with_cwd(&cwd),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Exercises the sync profile through the host's existing transcript tests.
|
||||
|
||||
@@ -58,15 +58,24 @@ impl ReviewAction {
|
||||
tracing::error!(%error, "failed to build automatic approval action");
|
||||
ReviewDecision::denied("automatic approval review could not prepare the action")
|
||||
})?;
|
||||
if let GuardianApprovalRequest::WriteStdin { environment_id, .. } = request
|
||||
let environment_id =
|
||||
if let GuardianApprovalRequest::WriteStdin { environment_id, .. } = request {
|
||||
Some(environment_id.as_str())
|
||||
} else {
|
||||
request.background_environment_id()
|
||||
};
|
||||
if let Some(environment_id) = environment_id
|
||||
&& !context
|
||||
.environments()
|
||||
.turn_environments()
|
||||
.any(|environment| environment.selection.environment_id == *environment_id)
|
||||
.any(|environment| environment.selection.environment_id == environment_id)
|
||||
{
|
||||
return Err(ReviewDecision::denied(
|
||||
"automatic approval review cannot access the terminal's environment; select it before retrying",
|
||||
));
|
||||
let message = if matches!(request, GuardianApprovalRequest::WriteStdin { .. }) {
|
||||
"automatic approval review cannot access the terminal's environment; select it before retrying"
|
||||
} else {
|
||||
"automatic approval review cannot access the request's environment"
|
||||
};
|
||||
return Err(ReviewDecision::denied(message));
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
@@ -517,7 +517,8 @@ async fn build_guardian_prompt_includes_parent_turn_denied_reads() -> anyhow::Re
|
||||
]),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
let TurnEnvironmentState::Ready(environment) = &mut turn.environments.environments[0] else {
|
||||
let TurnEnvironmentState::Ready(environment) = &mut turn.initial_environments.environments[0]
|
||||
else {
|
||||
panic!("parent environment should be ready");
|
||||
};
|
||||
environment.config_mut().permission_profile =
|
||||
@@ -565,6 +566,113 @@ async fn build_guardian_prompt_includes_parent_turn_denied_reads() -> anyhow::Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn background_approval_permissions_use_the_owning_environment() -> anyhow::Result<()> {
|
||||
let (session, mut turn) = crate::session::tests::make_session_and_context().await;
|
||||
let mut secondary = turn.initial_environments.primary().unwrap().clone();
|
||||
let cwd = test_path_buf("/guardian-secondary").abs();
|
||||
let denied = cwd.join("private");
|
||||
secondary.selection.environment_id = "secondary".to_string();
|
||||
secondary.selection.cwd = PathUri::from_abs_path(&cwd);
|
||||
secondary.config_mut().permission_profile =
|
||||
PermissionProfileSnapshot::legacy(PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Path {
|
||||
path: PathUri::from_abs_path(&denied),
|
||||
},
|
||||
access: FileSystemAccessMode::Deny,
|
||||
missing_path_behavior: None,
|
||||
}]),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
));
|
||||
let mut windows = secondary.clone();
|
||||
let windows_cwd = PathUri::parse("file:///C:/guardian-secondary")?;
|
||||
windows.environment = Arc::new(codex_exec_server::Environment::create_for_tests(Some(
|
||||
"ws://127.0.0.1:1".into(),
|
||||
))?);
|
||||
windows.selection.environment_id = "windows".into();
|
||||
windows.selection.cwd = windows_cwd.clone();
|
||||
windows.config_mut().workspace_roots = vec![windows_cwd.clone()];
|
||||
windows.config_mut().permission_profile =
|
||||
PermissionProfileSnapshot::legacy(PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry::new(
|
||||
windows_cwd.join("private")?.into(),
|
||||
FileSystemAccessMode::Deny,
|
||||
),
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: "*.secret".into(),
|
||||
},
|
||||
FileSystemAccessMode::Deny,
|
||||
),
|
||||
]),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
));
|
||||
turn.initial_environments.environments.extend([
|
||||
TurnEnvironmentState::Ready(secondary),
|
||||
TurnEnvironmentState::Ready(windows),
|
||||
]);
|
||||
let turn = Arc::new(turn);
|
||||
let context = GuardianReviewContext::from(&turn);
|
||||
let network_request = |environment_id: &str| GuardianApprovalRequest::NetworkAccess {
|
||||
id: "network".to_string(),
|
||||
turn_id: turn.sub_id.clone(),
|
||||
environment_id: environment_id.to_string(),
|
||||
target: "https://example.com:443".to_string(),
|
||||
host: "example.com".to_string(),
|
||||
protocol: NetworkApprovalProtocol::Https,
|
||||
port: 443,
|
||||
trigger: None,
|
||||
};
|
||||
let requests = [
|
||||
network_request("secondary"),
|
||||
network_request("windows"),
|
||||
#[cfg(unix)]
|
||||
GuardianApprovalRequest::Execve {
|
||||
id: "shell".to_string(),
|
||||
environment_id: "secondary".to_string(),
|
||||
source: codex_protocol::approvals::GuardianCommandSource::UnifiedExec,
|
||||
program: "cat".to_string(),
|
||||
argv: Vec::new(),
|
||||
cwd,
|
||||
additional_permissions: None,
|
||||
},
|
||||
];
|
||||
for request in requests {
|
||||
let is_windows = request.background_environment_id() == Some("windows");
|
||||
let prompt = build_guardian_prompt_items_with_parent_turn(
|
||||
&session,
|
||||
session.conversation_history_snapshot().await.as_ref(),
|
||||
Some(&context),
|
||||
ApprovalRequestReasons::default(),
|
||||
request,
|
||||
GuardianPromptMode::Full,
|
||||
/*reviewed_node_repl_evidence_sequence*/ 0,
|
||||
)
|
||||
.await?;
|
||||
let text = guardian_prompt_text(&prompt.context.into_user_inputs()?);
|
||||
if is_windows {
|
||||
assert!(
|
||||
text.contains(r"path `C:\guardian-secondary\private`"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains(r"glob `C:\guardian-secondary\*.secret`"),
|
||||
"{text}"
|
||||
);
|
||||
} else {
|
||||
assert!(text.contains(denied.to_string_lossy().as_ref()));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
runtime::ReviewAction::from(network_request("missing"))
|
||||
.validate(&context)
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn build_guardian_prompt_delta_mode_preserves_original_numbering() -> anyhow::Result<()> {
|
||||
let (session, turn) = guardian_test_session_and_turn_with_base_url("http://localhost").await;
|
||||
@@ -1091,6 +1199,7 @@ fn guardian_approval_request_to_json_renders_network_access_trigger() -> serde_j
|
||||
let action = GuardianApprovalRequest::NetworkAccess {
|
||||
id: "network-1".to_string(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
environment_id: "local".to_string(),
|
||||
target: "https://example.com:443".to_string(),
|
||||
host: "example.com".to_string(),
|
||||
protocol: NetworkApprovalProtocol::Https,
|
||||
@@ -1141,6 +1250,7 @@ async fn build_guardian_prompt_items_explains_network_access_review_scope() -> a
|
||||
GuardianApprovalRequest::NetworkAccess {
|
||||
id: "network-1".to_string(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
environment_id: "local".to_string(),
|
||||
target: "https://example.com:443".to_string(),
|
||||
host: "example.com".to_string(),
|
||||
protocol: NetworkApprovalProtocol::Https,
|
||||
@@ -1339,6 +1449,7 @@ fn guardian_request_turn_id_prefers_network_access_owner_turn() {
|
||||
let network_access = GuardianApprovalRequest::NetworkAccess {
|
||||
id: "network-1".to_string(),
|
||||
turn_id: "owner-turn".to_string(),
|
||||
environment_id: "local".to_string(),
|
||||
target: "https://example.com:443".to_string(),
|
||||
host: "example.com".to_string(),
|
||||
protocol: NetworkApprovalProtocol::Https,
|
||||
@@ -1368,6 +1479,7 @@ fn guardian_request_target_item_id_omits_network_access_trigger_call_id() {
|
||||
let network_access = GuardianApprovalRequest::NetworkAccess {
|
||||
id: "network-1".to_string(),
|
||||
turn_id: "owner-turn".to_string(),
|
||||
environment_id: "local".to_string(),
|
||||
target: "https://example.com:443".to_string(),
|
||||
host: "example.com".to_string(),
|
||||
protocol: NetworkApprovalProtocol::Https,
|
||||
|
||||
Reference in New Issue
Block a user