mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Require approval for input to escalated terminals (#40978)
## What changed - Add the `write_stdin_approval` feature flag, disabled by default, to require a fresh approval before sending non-empty input to an escalated unified-exec terminal. - Route these reviews through hooks, Guardian, app-server, and the TUI as `writeStdin` approvals while keeping the parent command item unchanged. - Preserve the terminal environment, launch directory, and escalation state across turns, and revalidate the process identity after approval before writing input. ## Testing - Cover approval routing, policy decisions, process reuse, terminal identity preservation, app-server events, analytics, and TUI rendering. GitOrigin-RevId: 4ba29eaae6208e934737ba078c96e589c7c2164d
This commit is contained in:
1 parent
21ff2e802c
commit
a57b398351
41 files changed
+861
-169
No files matched your search
@@ -12,6 +12,8 @@ pub(crate) enum UnifiedExecError {
|
||||
// The model is trained on `session_id`, but internally we track a `process_id`.
|
||||
#[error("Unknown process id {process_id}")]
|
||||
UnknownProcessId { process_id: i32 },
|
||||
#[error("stdin approval failed: {0:?}")]
|
||||
StdinApproval(crate::tools::sandboxing::ToolError),
|
||||
#[error("failed to write to stdin")]
|
||||
WriteToStdin,
|
||||
#[error(
|
||||
|
||||
@@ -184,6 +184,10 @@ struct ProcessEntry {
|
||||
initial_exec_command_active: Arc<std::sync::atomic::AtomicBool>,
|
||||
hook_command: String,
|
||||
tty: bool,
|
||||
environment_id: String,
|
||||
// The successful launch bypassed sandboxing required by its ambient policy.
|
||||
// Preserve this across turns so subsequent stdin writes can require approval.
|
||||
escalated: bool,
|
||||
network_approval: Option<DeferredNetworkApproval>,
|
||||
session: Weak<Session>,
|
||||
last_used: tokio::time::Instant,
|
||||
|
||||
@@ -141,6 +141,8 @@ async fn exec_command_with_tty(
|
||||
initial_exec_command_active: Arc::new(std::sync::atomic::AtomicBool::new(true)),
|
||||
hook_command: cmd.to_string(),
|
||||
tty,
|
||||
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
escalated: false,
|
||||
network_approval: None,
|
||||
session: Arc::downgrade(session),
|
||||
last_used: started_at,
|
||||
@@ -304,6 +306,7 @@ async fn blocking_terminate_unified_process(
|
||||
|
||||
async fn write_stdin(
|
||||
session: &Arc<Session>,
|
||||
turn: &Arc<TurnContext>,
|
||||
process_id: i32,
|
||||
input: &str,
|
||||
yield_time_ms: u64,
|
||||
@@ -311,14 +314,22 @@ async fn write_stdin(
|
||||
session
|
||||
.services
|
||||
.unified_exec_manager
|
||||
.write_stdin(WriteStdinRequest {
|
||||
process_id,
|
||||
input,
|
||||
yield_time_ms,
|
||||
max_output_tokens: None,
|
||||
truncation_policy: TruncationPolicy::Tokens(10_000),
|
||||
interaction_event: None,
|
||||
})
|
||||
.write_stdin(
|
||||
&UnifiedExecContext::new(
|
||||
Arc::clone(session),
|
||||
crate::session::step_context::StepContext::for_test(Arc::clone(turn)),
|
||||
tokio_util::sync::CancellationToken::new(),
|
||||
"write".to_string(),
|
||||
),
|
||||
WriteStdinRequest {
|
||||
process_id,
|
||||
input,
|
||||
yield_time_ms,
|
||||
max_output_tokens: None,
|
||||
truncation_policy: TruncationPolicy::Tokens(10_000),
|
||||
interaction_event: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -347,6 +358,7 @@ async fn unified_exec_persists_across_requests() -> anyhow::Result<()> {
|
||||
|
||||
write_stdin(
|
||||
&session,
|
||||
&turn,
|
||||
process_id,
|
||||
"export CODEX_INTERACTIVE_SHELL_VAR=codex\n",
|
||||
/*yield_time_ms*/ 2_500,
|
||||
@@ -355,6 +367,7 @@ async fn unified_exec_persists_across_requests() -> anyhow::Result<()> {
|
||||
|
||||
let out_2 = write_stdin(
|
||||
&session,
|
||||
&turn,
|
||||
process_id,
|
||||
"echo $CODEX_INTERACTIVE_SHELL_VAR\n",
|
||||
/*yield_time_ms*/ 2_500,
|
||||
@@ -388,6 +401,7 @@ async fn multi_unified_exec_sessions() -> anyhow::Result<()> {
|
||||
|
||||
write_stdin(
|
||||
&session,
|
||||
&turn,
|
||||
session_a,
|
||||
"export CODEX_INTERACTIVE_SHELL_VAR=codex\n",
|
||||
/*yield_time_ms*/ 2_500,
|
||||
@@ -416,6 +430,7 @@ async fn multi_unified_exec_sessions() -> anyhow::Result<()> {
|
||||
|
||||
let out_3 = write_stdin(
|
||||
&session,
|
||||
&turn,
|
||||
shell_a.process_id.expect("expected process id"),
|
||||
"echo $CODEX_INTERACTIVE_SHELL_VAR\n",
|
||||
/*yield_time_ms*/ 2_500,
|
||||
@@ -447,6 +462,7 @@ async fn unified_exec_timeouts() -> anyhow::Result<()> {
|
||||
|
||||
write_stdin(
|
||||
&session,
|
||||
&turn,
|
||||
process_id,
|
||||
format!("export CODEX_INTERACTIVE_SHELL_VAR={TEST_VAR_VALUE}\n").as_str(),
|
||||
/*yield_time_ms*/ 2_500,
|
||||
@@ -455,6 +471,7 @@ async fn unified_exec_timeouts() -> anyhow::Result<()> {
|
||||
|
||||
let out_2 = write_stdin(
|
||||
&session,
|
||||
&turn,
|
||||
process_id,
|
||||
"sleep 5 && echo $CODEX_INTERACTIVE_SHELL_VAR\n",
|
||||
/*yield_time_ms*/ 10,
|
||||
@@ -469,7 +486,7 @@ async fn unified_exec_timeouts() -> anyhow::Result<()> {
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(7)).await;
|
||||
|
||||
let out_3 = write_stdin(&session, process_id, "", /*yield_time_ms*/ 100).await?;
|
||||
let out_3 = write_stdin(&session, &turn, process_id, "", /*yield_time_ms*/ 100).await?;
|
||||
|
||||
assert!(
|
||||
out_3
|
||||
@@ -533,11 +550,14 @@ async fn reusing_completed_process_returns_unknown_process() -> anyhow::Result<(
|
||||
.await?;
|
||||
let process_id = open_shell.process_id.expect("expected process id");
|
||||
|
||||
write_stdin(&session, process_id, "exit\n", /*yield_time_ms*/ 2_500).await?;
|
||||
write_stdin(
|
||||
&session, &turn, process_id, "exit\n", /*yield_time_ms*/ 2_500,
|
||||
)
|
||||
.await?;
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
|
||||
let err = write_stdin(&session, process_id, "", /*yield_time_ms*/ 100)
|
||||
let err = write_stdin(&session, &turn, process_id, "", /*yield_time_ms*/ 100)
|
||||
.await
|
||||
.expect_err("expected unknown process error");
|
||||
|
||||
@@ -588,6 +608,8 @@ async fn terminating_initial_exec_command_rechecks_initial_response_state() -> a
|
||||
initial_exec_command_active: Arc::new(std::sync::atomic::AtomicBool::new(true)),
|
||||
hook_command: "sleep 60".to_string(),
|
||||
tty: true,
|
||||
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
escalated: false,
|
||||
network_approval: None,
|
||||
session: Arc::downgrade(&session),
|
||||
last_used: Instant::now(),
|
||||
@@ -662,6 +684,8 @@ async fn terminating_during_stdin_poll_returns_exited_response() -> anyhow::Resu
|
||||
initial_exec_command_active: Arc::new(std::sync::atomic::AtomicBool::new(false)),
|
||||
hook_command: "sleep 60".to_string(),
|
||||
tty: true,
|
||||
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
escalated: false,
|
||||
network_approval: None,
|
||||
session: Arc::downgrade(&session),
|
||||
last_used,
|
||||
@@ -670,8 +694,12 @@ async fn terminating_during_stdin_poll_returns_exited_response() -> anyhow::Resu
|
||||
|
||||
let poll_task = tokio::spawn({
|
||||
let session = Arc::clone(&session);
|
||||
let turn = Arc::clone(&turn);
|
||||
async move {
|
||||
write_stdin(&session, process_id, "", /*yield_time_ms*/ 60_000).await
|
||||
write_stdin(
|
||||
&session, &turn, process_id, "", /*yield_time_ms*/ 60_000,
|
||||
)
|
||||
.await
|
||||
}
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
@@ -835,3 +863,121 @@ async fn remote_exec_server_rejects_inherited_fd_launches() -> anyhow::Result<()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stdin_approval_preserves_the_reviewed_terminal() -> anyhow::Result<()> {
|
||||
use crate::session::tests::make_session_and_context_with_auth_and_config_and_rx;
|
||||
use crate::state::ActiveTurn;
|
||||
use crate::tools::sandboxing::ToolError;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::ReviewDecision;
|
||||
|
||||
skip_if_sandbox!(Ok(()));
|
||||
let (session, mut turn, events) = make_session_and_context_with_auth_and_config_and_rx(
|
||||
codex_login::CodexAuth::from_api_key("Test API Key"),
|
||||
Vec::new(),
|
||||
|config| {
|
||||
config.features.enable(Feature::WriteStdinApproval).unwrap();
|
||||
config.permissions.approval_policy =
|
||||
crate::config::Constrained::allow_any(AskForApproval::OnRequest);
|
||||
config.approvals_reviewer = ApprovalsReviewer::AutoReview;
|
||||
},
|
||||
)
|
||||
.await;
|
||||
*session.active_turn.lock().await = Some(ActiveTurn::default());
|
||||
let manager = &session.services.unified_exec_manager;
|
||||
let command = "while IFS= read -r line; do printf 'received:%s\\n' \"$line\"; done";
|
||||
let opened = exec_command(
|
||||
&session, &turn, command, /*yield_time_ms*/ 250, /*workdir*/ None,
|
||||
)
|
||||
.await?;
|
||||
let process_id = opened.process_id.expect("running terminal");
|
||||
let cwd = PathUri::parse("file:///C:/workspace")?;
|
||||
let original = {
|
||||
let mut store = manager.process_store.lock().await;
|
||||
let entry = store.processes.get_mut(&process_id).unwrap();
|
||||
entry.escalated = true;
|
||||
entry.environment_id = "unselected-executor".to_string();
|
||||
entry.cwd = cwd.clone();
|
||||
Arc::clone(&entry.process)
|
||||
};
|
||||
// Empty polling must complete without an approval response.
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 5),
|
||||
write_stdin(&session, &turn, process_id, "", /*yield_time_ms*/ 250),
|
||||
)
|
||||
.await??;
|
||||
let input = "rejected\n";
|
||||
let denied = write_stdin(
|
||||
&session, &turn, process_id, input, /*yield_time_ms*/ 250,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
matches!(denied, Err(UnifiedExecError::StdinApproval(ToolError::Rejected(reason)))
|
||||
if reason.contains("select it before retrying"))
|
||||
);
|
||||
Arc::make_mut(&mut Arc::get_mut(&mut turn).unwrap().config).approvals_reviewer =
|
||||
ApprovalsReviewer::User;
|
||||
for (input, decision) in [
|
||||
("rejected\n", ReviewDecision::denied("test denial")),
|
||||
("accepted\n", ReviewDecision::Approved),
|
||||
("replace\n", ReviewDecision::Approved),
|
||||
] {
|
||||
let review = async {
|
||||
loop {
|
||||
let EventMsg::ExecApprovalRequest(approval) = events.recv().await?.msg else {
|
||||
continue;
|
||||
};
|
||||
assert_eq!(
|
||||
(
|
||||
approval.call_id.as_str(),
|
||||
approval.approval_id.as_deref(),
|
||||
approval.cwd
|
||||
),
|
||||
("call", Some("write"), cwd.clone().into())
|
||||
);
|
||||
assert!(original.interaction_lock().try_lock_owned().is_err());
|
||||
if input == "replace\n" {
|
||||
let replacement = super::process_tests::remote_process(
|
||||
WriteStatus::Accepted,
|
||||
/*terminate_error*/ None,
|
||||
SandboxType::None,
|
||||
)
|
||||
.await;
|
||||
let mut store = manager.process_store.lock().await;
|
||||
store.processes.get_mut(&process_id).unwrap().process = Arc::new(replacement);
|
||||
}
|
||||
session.notify_approval("write", decision).await;
|
||||
return anyhow::Ok(());
|
||||
}
|
||||
};
|
||||
let (result, reviewed) = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
|
||||
tokio::join!(
|
||||
write_stdin(
|
||||
&session, &turn, process_id, input, /*yield_time_ms*/ 250
|
||||
),
|
||||
review
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
reviewed?;
|
||||
match input {
|
||||
"rejected\n" => assert!(matches!(result, Err(UnifiedExecError::StdinApproval(_)))),
|
||||
"accepted\n" => {
|
||||
let output = result?.truncated_output(DEFAULT_MAX_OUTPUT_TOKENS);
|
||||
assert!(output.contains("received:accepted"), "{output}");
|
||||
assert!(!output.contains("received:rejected"), "{output}");
|
||||
}
|
||||
_ => assert!(
|
||||
matches!(result, Err(UnifiedExecError::UnknownProcessId { process_id: id }) if id == process_id)
|
||||
),
|
||||
}
|
||||
assert!(original.interaction_lock().try_lock_owned().is_ok());
|
||||
}
|
||||
original.terminate();
|
||||
assert!(session.terminate_background_terminal(process_id).await);
|
||||
Ok(())
|
||||
}
|
||||
@@ -20,10 +20,12 @@ use crate::exec_env::inject_apply_patch_env;
|
||||
use crate::exec_env::inject_permission_profile_env;
|
||||
use crate::exec_env::inject_session_id_env;
|
||||
use crate::exec_policy::ExecApprovalRequest;
|
||||
use crate::guardian::GuardianReviewContext;
|
||||
use crate::plugins::metrics::finish_and_track_measurements;
|
||||
use crate::sandboxing::ExecOptions;
|
||||
use crate::sandboxing::ExecRequest;
|
||||
use crate::sandboxing::ExecServerEnvConfig;
|
||||
use crate::tools::ApprovalContext;
|
||||
use crate::tools::context::ExecCommandToolOutput;
|
||||
use crate::tools::events::ToolEmitter;
|
||||
use crate::tools::events::ToolEventCtx;
|
||||
@@ -35,6 +37,7 @@ use crate::tools::runtimes::is_managed_proxy_env_var;
|
||||
use crate::tools::runtimes::unified_exec::UnifiedExecAttempt;
|
||||
use crate::tools::runtimes::unified_exec::UnifiedExecRequest as UnifiedExecToolRequest;
|
||||
use crate::tools::runtimes::unified_exec::UnifiedExecRuntime;
|
||||
use crate::tools::sandboxing::ApprovalAction;
|
||||
use crate::tools::sandboxing::SandboxAttempt;
|
||||
use crate::tools::sandboxing::ToolCtx;
|
||||
use crate::tools::sandboxing::ToolError;
|
||||
@@ -66,6 +69,7 @@ use codex_core_plugins::PLUGIN_METRICS_OUTPUT_ENV_VAR;
|
||||
use codex_core_plugins::PluginCommandAttribution;
|
||||
use codex_core_plugins::PluginMetricsSidecar;
|
||||
use codex_core_plugins::strip_output_env;
|
||||
use codex_features::Feature;
|
||||
use codex_network_proxy::NetworkPolicyDecider;
|
||||
use codex_network_proxy::NetworkProxy;
|
||||
use codex_protocol::config_types::ShellEnvironmentPolicy;
|
||||
@@ -485,6 +489,7 @@ impl UnifiedExecProcessManager {
|
||||
let UnifiedExecAttempt {
|
||||
process,
|
||||
metrics_sidecar,
|
||||
escalated,
|
||||
} = attempt;
|
||||
let process = Arc::new(process);
|
||||
let network_denial_monitor = deferred_network_approval.as_ref().map(|deferred| {
|
||||
@@ -543,6 +548,8 @@ impl UnifiedExecProcessManager {
|
||||
&request.command,
|
||||
request.hook_command.clone(),
|
||||
cwd.clone(),
|
||||
request.turn_environment.selection.environment_id.clone(),
|
||||
escalated,
|
||||
plugin_attribution.clone(),
|
||||
start,
|
||||
request.process_id,
|
||||
@@ -757,6 +764,7 @@ impl UnifiedExecProcessManager {
|
||||
|
||||
pub(crate) async fn write_stdin(
|
||||
&self,
|
||||
context: &UnifiedExecContext,
|
||||
request: WriteStdinRequest<'_>,
|
||||
) -> Result<ExecCommandToolOutput, UnifiedExecError> {
|
||||
let process_id = request.process_id;
|
||||
@@ -764,16 +772,55 @@ impl UnifiedExecProcessManager {
|
||||
// Different terminal sessions can be polled concurrently, but reads and
|
||||
// writes against one terminal must not overlap because they share a
|
||||
// draining output buffer and process lifecycle.
|
||||
let locked_process = {
|
||||
let (locked_process, approval) = {
|
||||
let store = self.process_store.lock().await;
|
||||
let entry = store
|
||||
.processes
|
||||
.get(&process_id)
|
||||
.ok_or(UnifiedExecError::UnknownProcessId { process_id })?;
|
||||
Arc::clone(&entry.process)
|
||||
let approval = (!request.input.is_empty()
|
||||
&& (entry.tty || request.input != INTERRUPT)
|
||||
&& entry.escalated
|
||||
&& context
|
||||
.session
|
||||
.features()
|
||||
.enabled(Feature::WriteStdinApproval))
|
||||
.then(|| ApprovalAction::WriteStdin {
|
||||
id: entry.call_id.clone(),
|
||||
approval_id: context.call_id.clone(),
|
||||
environment_id: entry.environment_id.clone(),
|
||||
process_id,
|
||||
input: request.input.to_string(),
|
||||
cwd: entry.cwd.clone(),
|
||||
tty: entry.tty,
|
||||
});
|
||||
(Arc::clone(&entry.process), approval)
|
||||
};
|
||||
let _interaction_guard = locked_process.interaction_lock().lock_owned().await;
|
||||
if let Some(approval) = approval {
|
||||
let strict_auto_review = context
|
||||
.session
|
||||
.active_turn_context_and_strict_auto_review()
|
||||
.await
|
||||
.is_some_and(|(_, _, strict)| strict);
|
||||
let approval_context = ApprovalContext {
|
||||
review_context: GuardianReviewContext::from(&context.step_context),
|
||||
cancellation_token: Some(context.cancellation_token.clone()),
|
||||
call_id: context.call_id.clone(),
|
||||
tool_name: ToolName::plain("write_stdin"),
|
||||
strict_auto_review,
|
||||
approval_reason: Some("Send input to an existing escalated terminal. The cwd is its launch directory; the terminal's current directory and state may have changed.".to_string()),
|
||||
retry_reason: None,
|
||||
network_approval_context: None,
|
||||
};
|
||||
context
|
||||
.session
|
||||
.request_approval(approval, approval_context)
|
||||
.await
|
||||
.map_err(UnifiedExecError::StdinApproval)?;
|
||||
}
|
||||
|
||||
// Revalidate the identity after approval: a removed process ID can be reused.
|
||||
let PreparedProcessHandles {
|
||||
process,
|
||||
output,
|
||||
@@ -1003,6 +1050,8 @@ impl UnifiedExecProcessManager {
|
||||
command: &[String],
|
||||
hook_command: String,
|
||||
cwd: PathUri,
|
||||
environment_id: String,
|
||||
escalated: bool,
|
||||
plugin_attribution: Option<PluginCommandAttribution>,
|
||||
started_at: Instant,
|
||||
process_id: i32,
|
||||
@@ -1024,6 +1073,8 @@ impl UnifiedExecProcessManager {
|
||||
initial_exec_command_active,
|
||||
hook_command,
|
||||
tty,
|
||||
environment_id,
|
||||
escalated,
|
||||
network_approval,
|
||||
session: Arc::downgrade(&context.session),
|
||||
last_used: started_at,
|
||||
|
||||
@@ -589,6 +589,8 @@ async fn pruning_does_not_evict_live_process_while_exited_process_is_finalizing(
|
||||
initial_exec_command_active: Arc::new(AtomicBool::new(false)),
|
||||
hook_command: format!("command-{process_id}"),
|
||||
tty: false,
|
||||
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
escalated: false,
|
||||
network_approval: None,
|
||||
session: std::sync::Weak::new(),
|
||||
last_used: if is_exited {
|
||||
|
||||
Reference in new issue
Block a user