mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Honor configured and saved approvals in codex exec (#63515)
## Why `codex exec` could force the approval policy to `never`, overriding configured approvals on new threads and saved approvals when continuing a thread. ## What changed New local and remote threads use their configured approval settings. Resumed and forked threads inherit the source thread's approval policy and reviewer independently. An explicit local CLI or profile override changes the supplied setting and saves it on the resulting thread. Before an interactive approval can be requested, `codex exec` warns on stderr when the effective settings call for a human reviewer. Exec rejects those requests immediately because it runs non-interactively. ## Testing Regression tests cover approval outcomes, warnings, and saved settings across local and remote runs. They also cover managed sandbox validation against an inherited approval policy. GitOrigin-RevId: 5d3499f7a59ce16b8d909e669e9f74682f6c3b69
This commit is contained in:
committed by
copyberry
parent
5716c2e228
commit
6b776372fd
@@ -262,6 +262,235 @@ async fn run_remote_queue_command(response: QueueResponse) -> Result<(Output, Va
|
||||
Ok((output, server.await??))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn wait_for_socket(socket_path: &Path) -> Result<()> {
|
||||
use std::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
timeout(Duration::from_secs(30), async {
|
||||
while !socket_path.try_exists()? {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn exec_keeps_saved_approval_settings_for_local_and_remote() -> Result<()> {
|
||||
use app_test_support::MockResponsesConfig;
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::create_escalated_command_execution_sse_response;
|
||||
use app_test_support::create_final_assistant_message_sse_response;
|
||||
use codex_app_server_protocol::ApprovalsReviewer::AutoReview;
|
||||
use codex_app_server_protocol::ApprovalsReviewer::User;
|
||||
use codex_app_server_protocol::AskForApproval::Never;
|
||||
use codex_app_server_protocol::AskForApproval::OnRequest;
|
||||
use codex_app_server_protocol::ThreadResumeParams;
|
||||
use codex_app_server_protocol::ThreadResumeResponse;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::UserInput;
|
||||
use core_test_support::responses;
|
||||
use tokio::process::Command;
|
||||
|
||||
let home = socket_test_home()?;
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let model = responses::start_mock_server().await;
|
||||
let server_config = || {
|
||||
MockResponsesConfig::new(&model.uri())
|
||||
.with_root_config("features.plugins = false\nanalytics.enabled = false")
|
||||
};
|
||||
let human_review = r#"approvals_reviewer="user""#;
|
||||
server_config()
|
||||
.with_root_config(human_review)
|
||||
.with_approval_policy("never")
|
||||
.write(home.path())?;
|
||||
let config = core_test_support::load_default_config_for_test(&home).await;
|
||||
let mut model_info =
|
||||
codex_core::test_support::construct_model_info_offline("mock-model", &config);
|
||||
model_info.auto_review_model_override = Some("mock-model".into());
|
||||
app_test_support::write_models_cache_with_models(home.path(), vec![model_info]).await?;
|
||||
let server = || {
|
||||
TestAppServer::builder()
|
||||
.with_program(&codex)
|
||||
.with_codex_home(home.path())
|
||||
.with_plugin_startup_tasks()
|
||||
.without_managed_config()
|
||||
.with_args(&["app-server"])
|
||||
};
|
||||
let done = create_final_assistant_message_sse_response("done")?;
|
||||
let mut seed = server().build_initialized().await?;
|
||||
let mut seed_thread = async |reviewer| -> Result<String> {
|
||||
let id = seed
|
||||
.start_thread(ThreadStartParams {
|
||||
approval_policy: Some(OnRequest),
|
||||
approvals_reviewer: Some(reviewer),
|
||||
..Default::default()
|
||||
})
|
||||
.await?
|
||||
.thread
|
||||
.id;
|
||||
let _mock = responses::mount_sse_once(&model, done.clone()).await;
|
||||
seed.start_turn_and_wait_for_completion(TurnStartParams {
|
||||
thread_id: id.clone(),
|
||||
input: vec![UserInput::Text {
|
||||
text: "seed saved settings".into(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
Ok(id)
|
||||
};
|
||||
let human = seed_thread(User).await?;
|
||||
let auto = seed_thread(AutoReview).await?;
|
||||
drop(seed);
|
||||
|
||||
let deny = create_final_assistant_message_sse_response(
|
||||
r#"{"risk_level":"high","user_authorization":"low","outcome":"deny","rationale":"Test reviewer denied this action."}"#,
|
||||
)?;
|
||||
let auto_review = r#"approvals_reviewer="auto_review""#;
|
||||
let never = r#"approval_policy="never""#;
|
||||
// Check warning counts on every turn. Only request escalation when checking the denial.
|
||||
let human_denial = (1, Some("approval request failed"));
|
||||
let auto_denial = (0, Some("test reviewer denied this action"));
|
||||
let never_denial = (0, Some("approval policy is never"));
|
||||
let human_warning = (1, None);
|
||||
let mut count = 0;
|
||||
let mut run = async |args: &[&str], expected| -> Result<(String, String)> {
|
||||
let (expected_warnings, denial): (usize, Option<&str>) = expected;
|
||||
count += 1;
|
||||
let call_id = format!("action_{count}");
|
||||
let mut bodies = Vec::new();
|
||||
if denial.is_some() {
|
||||
bodies.push(create_escalated_command_execution_sse_response(
|
||||
vec!["echo".into(), call_id.clone()],
|
||||
/*workdir*/ None,
|
||||
/*timeout_ms*/ Some(500),
|
||||
&call_id,
|
||||
)?);
|
||||
if expected == auto_denial {
|
||||
bodies.push(deny.clone());
|
||||
}
|
||||
}
|
||||
bodies.push(done.clone());
|
||||
let mock = responses::mount_sse_sequence(&model, bodies).await;
|
||||
let output = Command::new(&codex)
|
||||
.env("CODEX_HOME", home.path())
|
||||
.current_dir(home.path())
|
||||
.arg("exec")
|
||||
.args(args)
|
||||
.args(["--skip-git-repo-check", "--json", "test approval"])
|
||||
.output()
|
||||
.await?;
|
||||
let stderr = String::from_utf8(output.stderr)?;
|
||||
assert!(output.status.success(), "{args:?}: {stderr}");
|
||||
let header = "WARNING: This thread is configured to ask a human";
|
||||
let warnings = stderr.matches(header).count();
|
||||
assert_eq!(warnings, expected_warnings, "{args:?}: {stderr}");
|
||||
if let Some(expected) = denial {
|
||||
let denied = mock
|
||||
.function_call_output_text(&call_id)
|
||||
.context("missing denied tool output")?
|
||||
.to_lowercase();
|
||||
assert!(denied.contains(expected), "{args:?}: {denied}");
|
||||
}
|
||||
let events = std::str::from_utf8(&output.stdout)?
|
||||
.lines()
|
||||
.map(serde_json::from_str::<Value>)
|
||||
.collect::<serde_json::Result<Vec<_>>>()?;
|
||||
let id = serde_json::from_value(events[0]["thread_id"].clone())?;
|
||||
let warning = stderr
|
||||
.lines()
|
||||
.skip_while(|line| !line.starts_with(header))
|
||||
.take_while(|line| line.starts_with(header) || line.starts_with("- "))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
Ok((id, warning))
|
||||
};
|
||||
let (_, warning) = run(&["resume", &human], human_denial).await?;
|
||||
insta::assert_snapshot!(warning, @r#"
|
||||
WARNING: This thread is configured to ask a human for approval. `codex exec` runs non-interactively and immediately rejects approval requests it receives.
|
||||
- To review requests yourself, run this turn from the TUI.
|
||||
- To change the thread's saved reviewer, pass `--config 'approvals_reviewer="auto_review"'` to `codex exec resume`.
|
||||
- To disable approval prompts for this and future turns, pass `--config 'approval_policy="never"'` to `codex exec resume`.
|
||||
"#);
|
||||
run(&["resume", &auto], auto_denial).await?;
|
||||
|
||||
// An explicit change persists. Each resume inherits the field left unspecified.
|
||||
let on_request = r#"approval_policy="on-request""#;
|
||||
let (explicit_fresh, _) = run(&["-c", on_request], human_denial).await?;
|
||||
let (fresh, _) = run(&[], never_denial).await?;
|
||||
run(&["-c", on_request, "resume", &fresh], human_warning).await?;
|
||||
run(&["-c", auto_review, "resume", &fresh], auto_denial).await?;
|
||||
std::fs::write(home.path().join("bot.config.toml"), never)?;
|
||||
run(&["--profile", "bot", "resume", &fresh], never_denial).await?;
|
||||
|
||||
// Forks inherit each field independently. The source threads must stay unchanged.
|
||||
let (inherited_fork, _) = run(&["fork", &auto], auto_denial).await?;
|
||||
let (human_fork, _) = run(&["fork", &human], human_warning).await?;
|
||||
let (reviewer_fork, _) = run(&["-c", auto_review, "fork", &human], auto_denial).await?;
|
||||
let (never_fork, _) = run(&["-c", never, "fork", &auto], never_denial).await?;
|
||||
|
||||
let socket = codex_app_server::app_server_control_socket_path(home.path())?;
|
||||
let endpoint = format!("unix://{}", socket.as_path().display());
|
||||
let remote = server().with_args(&["--listen", "unix://"]).build().await?;
|
||||
wait_for_socket(socket.as_path()).await?;
|
||||
let (remote_fresh, _) = run(&["--remote", &endpoint], never_denial).await?;
|
||||
let (_, warning) = run(&["--remote", &endpoint, "resume", &human], human_denial).await?;
|
||||
insta::assert_snapshot!(warning, @r#"
|
||||
WARNING: This thread is configured to ask a human for approval. `codex exec` runs non-interactively and immediately rejects approval requests it receives.
|
||||
- To review requests yourself, run this turn from the TUI.
|
||||
"#);
|
||||
run(&["--remote", &endpoint, "resume", &auto], auto_denial).await?;
|
||||
|
||||
// Fresh threads use the configured policy and reviewer on the first turn.
|
||||
server_config()
|
||||
.with_root_config(human_review)
|
||||
.with_approval_policy("on-request")
|
||||
.write(home.path())?;
|
||||
let (local_human, _) = run(&[], human_denial).await?;
|
||||
let (remote_human, _) = run(&["--remote", &endpoint], human_denial).await?;
|
||||
server_config()
|
||||
.with_approval_policy("on-request")
|
||||
.with_root_config(auto_review)
|
||||
.write(home.path())?;
|
||||
let (remote_auto, _) = run(&["--remote", &endpoint], auto_denial).await?;
|
||||
drop(remote);
|
||||
|
||||
let automatic = (OnRequest, AutoReview);
|
||||
let manual = (OnRequest, User);
|
||||
let default = (Never, User);
|
||||
let mut cold = server().build_initialized().await?;
|
||||
for (id, saved) in [
|
||||
(human, manual),
|
||||
(auto, automatic),
|
||||
(explicit_fresh, manual),
|
||||
(fresh, (Never, AutoReview)),
|
||||
(remote_fresh, default),
|
||||
(local_human, manual),
|
||||
(remote_human, manual),
|
||||
(remote_auto, automatic),
|
||||
(inherited_fork, automatic),
|
||||
(human_fork, manual),
|
||||
(reviewer_fork, automatic),
|
||||
(never_fork, (Never, AutoReview)),
|
||||
] {
|
||||
let request = cold
|
||||
.send_thread_resume_request(ThreadResumeParams {
|
||||
thread_id: id,
|
||||
exclude_turns: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let resumed: ThreadResumeResponse = cold.read_response(request).await?;
|
||||
assert_eq!((resumed.approval_policy, resumed.approvals_reviewer), saved);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn remote_session_commands_with_workload_identity_use_server_auth() -> Result<()> {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Explain how exec handles approvals when the effective settings call for a human.
|
||||
|
||||
use codex_app_server_protocol::ApprovalsReviewer;
|
||||
use codex_app_server_protocol::AskForApproval;
|
||||
|
||||
pub(super) fn warn_if_human_approval(
|
||||
policy: AskForApproval,
|
||||
reviewer: ApprovalsReviewer,
|
||||
flags_supported: bool,
|
||||
) {
|
||||
// Even with every granular category disabled, a dangerous command can
|
||||
// require approval to run within the existing sandbox.
|
||||
if reviewer != ApprovalsReviewer::User || policy == AskForApproval::Never {
|
||||
return;
|
||||
}
|
||||
eprintln!(
|
||||
"WARNING: This thread is configured to ask a human for approval. \
|
||||
`codex exec` runs non-interactively and immediately rejects approval requests it receives.\n\
|
||||
- To review requests yourself, run this turn from the TUI."
|
||||
);
|
||||
// Switching an untrusted project to Never would also allow ordinary
|
||||
// sandboxed commands that currently require approval.
|
||||
if flags_supported && policy != AskForApproval::UnlessTrusted {
|
||||
eprintln!(
|
||||
"- To change the thread's saved reviewer, pass `--config 'approvals_reviewer=\"auto_review\"'` to `codex exec resume`.\n\
|
||||
- To disable approval prompts for this and future turns, pass `--config 'approval_policy=\"never\"'` to `codex exec resume`."
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -462,7 +462,7 @@ fn config_summary_entries(
|
||||
),
|
||||
(
|
||||
"approval",
|
||||
config.permissions.approval_policy.value().to_string(),
|
||||
session_configured_event.approval_policy.to_string(),
|
||||
),
|
||||
(
|
||||
"sandbox",
|
||||
|
||||
+98
-93
@@ -5,6 +5,7 @@
|
||||
#![recursion_limit = "256"]
|
||||
#![deny(clippy::print_stdout)]
|
||||
|
||||
mod approval_warning;
|
||||
mod cli;
|
||||
mod daybreak;
|
||||
mod event_processor;
|
||||
@@ -103,7 +104,6 @@ use codex_otel::set_parent_from_context;
|
||||
use codex_otel::traceparent_context_from_env;
|
||||
use codex_protocol::SessionId;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::config_types::SandboxMode;
|
||||
use codex_protocol::config_types::TrustLevel;
|
||||
use codex_protocol::mcp_approval_meta::APPROVAL_KIND_KEY;
|
||||
@@ -167,7 +167,6 @@ pub use exec_events::WebSearchItem;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::future::Future;
|
||||
use std::io::IsTerminal;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
@@ -236,7 +235,6 @@ struct ExecRunArgs {
|
||||
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,
|
||||
exec_span: tracing::Span,
|
||||
@@ -650,9 +648,7 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result
|
||||
let overrides = ConfigOverrides {
|
||||
model,
|
||||
review_model: None,
|
||||
// Default to never ask for approvals in headless mode. Rebuild below if
|
||||
// the fully resolved reviewer is AutoReview.
|
||||
approval_policy: Some(AskForApproval::Never),
|
||||
approval_policy: dangerously_bypass_approvals_and_sandbox.then_some(AskForApproval::Never),
|
||||
approvals_reviewer: None,
|
||||
sandbox_mode,
|
||||
permission_profile: None,
|
||||
@@ -677,22 +673,15 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result
|
||||
additional_writable_roots: add_dir,
|
||||
};
|
||||
|
||||
let build_config = |overrides| {
|
||||
ConfigBuilder::default()
|
||||
.codex_home(codex_home.to_path_buf())
|
||||
.cli_overrides(cli_kv_overrides.clone())
|
||||
.harness_overrides(overrides)
|
||||
.loader_overrides(loader_overrides.clone())
|
||||
.strict_config(strict_config)
|
||||
.cloud_config_bundle(cloud_config_bundle.clone())
|
||||
.build()
|
||||
};
|
||||
let mut config = build_exec_config(
|
||||
overrides.clone(),
|
||||
dangerously_bypass_approvals_and_sandbox,
|
||||
build_config,
|
||||
)
|
||||
.await?;
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.to_path_buf())
|
||||
.cli_overrides(cli_kv_overrides.clone())
|
||||
.harness_overrides(overrides.clone())
|
||||
.loader_overrides(loader_overrides.clone())
|
||||
.strict_config(strict_config)
|
||||
.cloud_config_bundle(cloud_config_bundle.clone())
|
||||
.build()
|
||||
.await?;
|
||||
embedded_network_policy.activate(&mut config);
|
||||
#[allow(clippy::print_stderr)]
|
||||
if config
|
||||
@@ -711,10 +700,6 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result
|
||||
.iter()
|
||||
.any(|(key, _)| key == "daybreak")
|
||||
.then_some(config.daybreak_enabled);
|
||||
let resume_approvals_reviewer_override = cli_kv_overrides
|
||||
.iter()
|
||||
.any(|(key, _)| key == "approvals_reviewer")
|
||||
.then(|| config.approvals_reviewer.into());
|
||||
|
||||
#[allow(clippy::print_stderr)]
|
||||
match check_execpolicy_for_warnings(&config.config_layer_stack).await {
|
||||
@@ -844,7 +829,6 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result
|
||||
command,
|
||||
config,
|
||||
overrides,
|
||||
resume_approvals_reviewer_override,
|
||||
daybreak_override,
|
||||
dangerously_bypass_approvals_and_sandbox,
|
||||
exec_span: exec_span.clone(),
|
||||
@@ -865,41 +849,6 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result
|
||||
.await
|
||||
}
|
||||
|
||||
async fn build_exec_config<BuildConfig, BuildFuture>(
|
||||
overrides: ConfigOverrides,
|
||||
preserve_headless_approval_policy: bool,
|
||||
build_config: BuildConfig,
|
||||
) -> std::io::Result<Config>
|
||||
where
|
||||
BuildConfig: Fn(ConfigOverrides) -> BuildFuture,
|
||||
BuildFuture: Future<Output = std::io::Result<Config>>,
|
||||
{
|
||||
let build_without_headless_approval_policy = || {
|
||||
build_config(ConfigOverrides {
|
||||
approval_policy: None,
|
||||
..overrides.clone()
|
||||
})
|
||||
};
|
||||
match build_config(overrides.clone()).await {
|
||||
Ok(config)
|
||||
if config.approvals_reviewer == ApprovalsReviewer::AutoReview
|
||||
&& !preserve_headless_approval_policy =>
|
||||
{
|
||||
build_without_headless_approval_policy().await
|
||||
}
|
||||
Ok(config) => Ok(config),
|
||||
Err(headless_error) if !preserve_headless_approval_policy => {
|
||||
match build_without_headless_approval_policy().await {
|
||||
Ok(config) if config.approvals_reviewer == ApprovalsReviewer::AutoReview => {
|
||||
Ok(config)
|
||||
}
|
||||
Ok(_) | Err(_) => Err(headless_error),
|
||||
}
|
||||
}
|
||||
Err(headless_error) => Err(headless_error),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::print_stderr)]
|
||||
async fn load_bootstrap_config_or_exit(
|
||||
codex_home: &Path,
|
||||
@@ -947,7 +896,6 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
command,
|
||||
config,
|
||||
overrides,
|
||||
resume_approvals_reviewer_override,
|
||||
daybreak_override,
|
||||
dangerously_bypass_approvals_and_sandbox,
|
||||
exec_span,
|
||||
@@ -1004,7 +952,6 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
}
|
||||
|
||||
let default_cwd = config.cwd.to_path_buf();
|
||||
let default_approval_policy = config.permissions.approval_policy.value();
|
||||
let default_effort = config.model_reasoning_effort.clone();
|
||||
|
||||
let (initial_operation, prompt_summary) = match (command.as_ref(), prompt, images) {
|
||||
@@ -1142,12 +1089,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
&client,
|
||||
ClientRequest::ThreadResume {
|
||||
request_id: request_ids.next(),
|
||||
params: thread_resume_params_from_config(
|
||||
&config,
|
||||
thread_id,
|
||||
&overrides,
|
||||
resume_approvals_reviewer_override,
|
||||
),
|
||||
params: thread_resume_params_from_config(&config, thread_id, &overrides)?,
|
||||
},
|
||||
"thread/resume",
|
||||
)
|
||||
@@ -1219,13 +1161,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let permissions = permissions_selection_from_config(&config);
|
||||
let sandbox = permissions.is_none().then(|| {
|
||||
sandbox_mode_from_permission_profile(
|
||||
&config.permissions.effective_permission_profile(),
|
||||
config.cwd.as_path(),
|
||||
)
|
||||
});
|
||||
let settings = inherited_thread_permissions(&config, &overrides)?;
|
||||
let response: ThreadForkResponse = send_request_with_response(
|
||||
&client,
|
||||
ClientRequest::ThreadFork {
|
||||
@@ -1238,10 +1174,10 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
runtime_workspace_roots: Some(LegacyAppPathString::from_abs_paths(
|
||||
&config.workspace_roots,
|
||||
)),
|
||||
approval_policy: Some(config.permissions.approval_policy.value().into()),
|
||||
approvals_reviewer: resume_approvals_reviewer_override,
|
||||
sandbox: sandbox.flatten(),
|
||||
permissions,
|
||||
approval_policy: settings.approval_policy,
|
||||
approvals_reviewer: settings.approvals_reviewer,
|
||||
sandbox: settings.sandbox,
|
||||
permissions: settings.permissions,
|
||||
config: thread_config_overrides_from_config(&config),
|
||||
ephemeral: config.ephemeral,
|
||||
thread_source: Some(thread_source.clone()),
|
||||
@@ -1299,6 +1235,13 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
// Waiting for a later streamed `SessionConfigured` event adds up to 10s of
|
||||
// avoidable startup latency on the in-process path.
|
||||
let mut session_configured = fallback_session_configured;
|
||||
if matches!(initial_operation, InitialOperation::UserTurn { .. }) {
|
||||
approval_warning::warn_if_human_approval(
|
||||
session_configured.approval_policy.into(),
|
||||
session_configured.approvals_reviewer.into(),
|
||||
/*flags_supported*/ true,
|
||||
);
|
||||
}
|
||||
|
||||
exec_span.record("thread.id", primary_thread_id_for_span.as_str());
|
||||
|
||||
@@ -1388,7 +1331,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
environments: None,
|
||||
cwd: first_turn_cwd,
|
||||
runtime_workspace_roots: first_turn_workspace_roots,
|
||||
approval_policy: Some(default_approval_policy.into()),
|
||||
approval_policy: None,
|
||||
approvals_reviewer: None,
|
||||
sandbox_policy: None,
|
||||
permissions: None,
|
||||
@@ -1672,14 +1615,23 @@ fn thread_start_params_from_config(
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_resume_params_from_config(
|
||||
struct InheritedThreadPermissions {
|
||||
approval_policy: Option<codex_app_server_protocol::AskForApproval>,
|
||||
approvals_reviewer: Option<codex_app_server_protocol::ApprovalsReviewer>,
|
||||
sandbox: Option<codex_app_server_protocol::SandboxMode>,
|
||||
permissions: Option<String>,
|
||||
explicit_permissions: bool,
|
||||
runtime_workspace_roots: Option<Vec<LegacyAppPathString>>,
|
||||
}
|
||||
|
||||
// Fork and resume both inherit approvals. Fork keeps the launch sandbox and
|
||||
// workspace roots, while resume changes those only when explicitly requested.
|
||||
fn inherited_thread_permissions(
|
||||
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 = if permissions.is_none() {
|
||||
) -> std::io::Result<InheritedThreadPermissions> {
|
||||
let mut permissions = permissions_selection_from_config(config);
|
||||
let mut sandbox = if permissions.is_none() {
|
||||
sandbox_mode_from_permission_profile(
|
||||
&config.permissions.effective_permission_profile(),
|
||||
config.cwd.as_path(),
|
||||
@@ -1687,7 +1639,9 @@ fn thread_resume_params_from_config(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// A process default is not a new choice for an existing thread.
|
||||
// Only explicit approval choices should override the source thread.
|
||||
let mut explicit_approval_policy = overrides.approval_policy.is_some();
|
||||
let mut explicit_reviewer = overrides.approvals_reviewer.is_some();
|
||||
let mut explicit_permissions = overrides.sandbox_mode.is_some();
|
||||
let mut runtime_workspace_roots = None;
|
||||
for layer in config
|
||||
@@ -1704,6 +1658,8 @@ fn thread_resume_params_from_config(
|
||||
)
|
||||
})
|
||||
{
|
||||
explicit_approval_policy |= layer.config.get("approval_policy").is_some();
|
||||
explicit_reviewer |= layer.config.get("approvals_reviewer").is_some();
|
||||
let legacy_workspace = layer
|
||||
.config
|
||||
.get("sandbox_workspace_write")
|
||||
@@ -1719,21 +1675,70 @@ fn thread_resume_params_from_config(
|
||||
Some(LegacyAppPathString::from_abs_paths(&config.workspace_roots));
|
||||
}
|
||||
}
|
||||
ThreadResumeParams {
|
||||
// If requirements downgraded an explicit sandbox to read-only, the server
|
||||
// must validate the original selector with the saved approval policy. Sending
|
||||
// the fallback would hide a disallowed full-access request paired with Never.
|
||||
if explicit_permissions && sandbox == Some(codex_app_server_protocol::SandboxMode::ReadOnly) {
|
||||
let layers = &config.config_layer_stack;
|
||||
let toml = codex_core::config::deserialize_config_toml_with_base(
|
||||
layers.effective_config(),
|
||||
config.codex_home.as_path(),
|
||||
)?;
|
||||
match codex_config::resolve_permission_config(layers, &toml, overrides.sandbox_mode) {
|
||||
Some(codex_config::PermissionConfig::Legacy { mode, .. }) => {
|
||||
sandbox = Some(mode.into())
|
||||
}
|
||||
Some(codex_config::PermissionConfig::Named { id }) => {
|
||||
permissions = Some(id.to_owned());
|
||||
sandbox = None;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Ok(InheritedThreadPermissions {
|
||||
approval_policy: explicit_approval_policy
|
||||
.then(|| config.permissions.approval_policy.value().into()),
|
||||
approvals_reviewer: explicit_reviewer.then(|| {
|
||||
config
|
||||
.requested_approvals_reviewer
|
||||
.unwrap_or(config.approvals_reviewer)
|
||||
.into()
|
||||
}),
|
||||
sandbox,
|
||||
permissions,
|
||||
explicit_permissions,
|
||||
runtime_workspace_roots,
|
||||
})
|
||||
}
|
||||
|
||||
fn thread_resume_params_from_config(
|
||||
config: &Config,
|
||||
thread_id: String,
|
||||
overrides: &ConfigOverrides,
|
||||
) -> std::io::Result<ThreadResumeParams> {
|
||||
let InheritedThreadPermissions {
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
sandbox,
|
||||
permissions,
|
||||
explicit_permissions,
|
||||
runtime_workspace_roots,
|
||||
} = inherited_thread_permissions(config, overrides)?;
|
||||
Ok(ThreadResumeParams {
|
||||
thread_id,
|
||||
model: config.model.clone(),
|
||||
model_provider: Some(config.model_provider_id.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,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
sandbox: sandbox.filter(|_| explicit_permissions),
|
||||
permissions: permissions.filter(|_| explicit_permissions),
|
||||
config: thread_config_overrides_from_config(config),
|
||||
exclude_turns: true,
|
||||
..ThreadResumeParams::default()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn thread_config_overrides_from_config(config: &Config) -> Option<HashMap<String, Value>> {
|
||||
|
||||
@@ -549,12 +549,14 @@ async fn thread_start_params_include_review_policy_when_auto_review_is_enabled()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_resume_params_only_include_explicit_review_policy_override() {
|
||||
async fn thread_resume_params_only_include_explicit_approval_overrides() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
approval_policy: Some(AskForApproval::Never),
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
..Default::default()
|
||||
})
|
||||
@@ -567,15 +569,24 @@ async fn thread_resume_params_only_include_explicit_review_policy_override() {
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
&ConfigOverrides::default(),
|
||||
/*approvals_reviewer_override*/ None,
|
||||
);
|
||||
)
|
||||
.expect("build resume params");
|
||||
let params_with_override = thread_resume_params_from_config(
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
&ConfigOverrides::default(),
|
||||
Some(codex_app_server_protocol::ApprovalsReviewer::AutoReview),
|
||||
);
|
||||
&ConfigOverrides {
|
||||
approval_policy: Some(AskForApproval::Never),
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("build resume params");
|
||||
|
||||
assert_eq!(params_without_override.approval_policy, None);
|
||||
assert_eq!(
|
||||
params_with_override.approval_policy,
|
||||
Some(codex_app_server_protocol::AskForApproval::Never)
|
||||
);
|
||||
assert_eq!(params_without_override.approvals_reviewer, None);
|
||||
assert_eq!(
|
||||
params_with_override.approvals_reviewer,
|
||||
@@ -584,7 +595,7 @@ async fn thread_resume_params_only_include_explicit_review_policy_override() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_exec_config_retries_without_invalid_headless_policy_for_auto_review() {
|
||||
async fn inherited_permissions_preserve_managed_validation_with_saved_never() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
std::fs::write(
|
||||
@@ -606,67 +617,61 @@ allowed_sandbox_modes = ["read-only", "workspace-write"]
|
||||
.expect("write requirements");
|
||||
let mut loader_overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
loader_overrides.system_requirements_path = Some(requirements_path);
|
||||
let overrides = ConfigOverrides {
|
||||
let resume_overrides = ConfigOverrides {
|
||||
cwd: Some(cwd.path().to_path_buf()),
|
||||
approval_policy: Some(AskForApproval::Never),
|
||||
sandbox_mode: Some(SandboxMode::DangerFullAccess),
|
||||
..Default::default()
|
||||
};
|
||||
let build_config = |overrides| {
|
||||
let builder = |overrides| {
|
||||
ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.loader_overrides(loader_overrides.clone())
|
||||
.harness_overrides(overrides)
|
||||
.build()
|
||||
};
|
||||
|
||||
let error = build_config(overrides.clone())
|
||||
let config = builder(resume_overrides.clone())
|
||||
.build()
|
||||
.await
|
||||
.expect_err("synthetic headless approval policy should fail");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("`approval_policy = \"never\"` cannot be used")
|
||||
);
|
||||
.expect("preflight with on-request allows managed downgrade");
|
||||
let legacy = thread_resume_params_from_config(&config, "thread-id".into(), &resume_overrides)
|
||||
.expect("build legacy resume params");
|
||||
|
||||
let config = build_exec_config(
|
||||
overrides,
|
||||
/*preserve_headless_approval_policy*/ false,
|
||||
build_config,
|
||||
)
|
||||
.await
|
||||
.expect("auto-review config should retry without the synthetic approval policy");
|
||||
|
||||
assert_eq!(
|
||||
config.permissions.approval_policy.value(),
|
||||
AskForApproval::OnRequest
|
||||
);
|
||||
assert_eq!(config.approvals_reviewer, ApprovalsReviewer::AutoReview);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_exec_config_preserves_headless_error_when_retry_fails() {
|
||||
let overrides = ConfigOverrides {
|
||||
approval_policy: Some(AskForApproval::Never),
|
||||
..Default::default()
|
||||
let resume_overrides = ConfigOverrides {
|
||||
sandbox_mode: None,
|
||||
..resume_overrides
|
||||
};
|
||||
let named_config = builder(resume_overrides.clone())
|
||||
.cli_overrides(vec![(
|
||||
"default_permissions".into(),
|
||||
":danger-full-access".into(),
|
||||
)])
|
||||
.build()
|
||||
.await
|
||||
.expect("preflight with on-request allows managed downgrade");
|
||||
let named =
|
||||
thread_resume_params_from_config(&named_config, "thread-id".into(), &resume_overrides)
|
||||
.expect("build named resume params");
|
||||
assert_eq!(named.permissions.as_deref(), Some(":danger-full-access"));
|
||||
|
||||
let error = build_exec_config(
|
||||
overrides,
|
||||
/*preserve_headless_approval_policy*/ false,
|
||||
|overrides| async move {
|
||||
let message = if overrides.approval_policy == Some(AskForApproval::Never) {
|
||||
"headless error"
|
||||
} else {
|
||||
"retry error"
|
||||
};
|
||||
Err(std::io::Error::other(message))
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("failed speculative retry should preserve the original error");
|
||||
|
||||
assert_eq!(error.to_string(), "headless error");
|
||||
// As on cold resume, validate the transmitted selector against the saved policy.
|
||||
for params in [legacy, named] {
|
||||
assert_eq!(params.approval_policy, None);
|
||||
let error = builder(ConfigOverrides {
|
||||
approval_policy: Some(AskForApproval::Never),
|
||||
sandbox_mode: params
|
||||
.sandbox
|
||||
.map(codex_app_server_protocol::SandboxMode::to_core),
|
||||
default_permissions: params.permissions,
|
||||
..resume_overrides.clone()
|
||||
})
|
||||
.build()
|
||||
.await
|
||||
.expect_err("saved Never must reject a managed downgrade of full access");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("`approval_policy = \"never\"` cannot be used")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -723,8 +728,8 @@ async fn thread_lifecycle_params_preserve_hook_trust_bypass() {
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
&ConfigOverrides::default(),
|
||||
/*approvals_reviewer_override*/ None,
|
||||
);
|
||||
)
|
||||
.expect("build resume params");
|
||||
|
||||
assert_eq!(start_params.config, expected_config);
|
||||
assert_eq!(resume_params.config, expected_config);
|
||||
@@ -763,8 +768,8 @@ async fn thread_lifecycle_params_include_legacy_sandbox_when_no_active_profile()
|
||||
sandbox_mode: Some(SandboxMode::DangerFullAccess),
|
||||
..Default::default()
|
||||
},
|
||||
/*approvals_reviewer_override*/ None,
|
||||
);
|
||||
)
|
||||
.expect("build resume params");
|
||||
|
||||
assert_eq!(config.permissions.active_permission_profile(), None);
|
||||
assert_eq!(
|
||||
|
||||
@@ -106,8 +106,8 @@ pub(super) async fn run(cli: Cli, endpoint: RemoteAppServerEndpoint) -> anyhow::
|
||||
.await?,
|
||||
);
|
||||
let mut ids = RequestIdSequencer::new();
|
||||
let thread = if let Some(thread_id) = session_id {
|
||||
client
|
||||
let (thread, policy, reviewer) = if let Some(thread_id) = session_id {
|
||||
let response = client
|
||||
.request_typed::<ThreadResumeResponse>(ClientRequest::ThreadResume {
|
||||
request_id: ids.next(),
|
||||
params: ThreadResumeParams {
|
||||
@@ -116,20 +116,27 @@ pub(super) async fn run(cli: Cli, endpoint: RemoteAppServerEndpoint) -> anyhow::
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?
|
||||
.thread
|
||||
.await?;
|
||||
(
|
||||
response.thread,
|
||||
response.approval_policy,
|
||||
response.approvals_reviewer,
|
||||
)
|
||||
} else {
|
||||
client
|
||||
let response = client
|
||||
.request_typed::<ThreadStartResponse>(ClientRequest::ThreadStart {
|
||||
request_id: ids.next(),
|
||||
params: ThreadStartParams {
|
||||
model: model.clone(),
|
||||
approval_policy: Some(codex_app_server_protocol::AskForApproval::Never),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?
|
||||
.thread
|
||||
.await?;
|
||||
(
|
||||
response.thread,
|
||||
response.approval_policy,
|
||||
response.approvals_reviewer,
|
||||
)
|
||||
};
|
||||
anyhow::ensure!(
|
||||
!matches!(
|
||||
@@ -139,6 +146,7 @@ pub(super) async fn run(cli: Cli, endpoint: RemoteAppServerEndpoint) -> anyhow::
|
||||
"remote thread already has an active turn"
|
||||
);
|
||||
processor.print_thread_started(&thread.id);
|
||||
approval_warning::warn_if_human_approval(policy, reviewer, /*flags_supported*/ false);
|
||||
let (interrupt_tx, interrupt_rx) = mpsc::unbounded_channel();
|
||||
tokio::spawn(async move {
|
||||
if tokio::signal::ctrl_c().await.is_ok() {
|
||||
@@ -155,7 +163,6 @@ pub(super) async fn run(cli: Cli, endpoint: RemoteAppServerEndpoint) -> anyhow::
|
||||
text: prompt,
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
approval_policy: Some(codex_app_server_protocol::AskForApproval::Never),
|
||||
// Like other app-server clients, explicit overrides apply to this
|
||||
// turn and subsequent turns. Omission preserves the thread settings.
|
||||
model,
|
||||
|
||||
@@ -4,7 +4,10 @@
|
||||
use core_test_support::responses;
|
||||
use core_test_support::test_codex_exec::test_codex_exec;
|
||||
|
||||
async fn run_exec_with_config(config_toml: &str, extra_args: &[&str]) -> anyhow::Result<String> {
|
||||
async fn run_exec_with_config(
|
||||
config_toml: &str,
|
||||
extra_args: &[&str],
|
||||
) -> anyhow::Result<(String, responses::ResponseMock)> {
|
||||
let test = test_codex_exec();
|
||||
std::fs::write(test.home_path().join("config.toml"), config_toml)?;
|
||||
|
||||
@@ -14,7 +17,7 @@ async fn run_exec_with_config(config_toml: &str, extra_args: &[&str]) -> anyhow:
|
||||
responses::ev_assistant_message("response_1", "done"),
|
||||
responses::ev_completed("response_1"),
|
||||
]);
|
||||
responses::mount_sse_once(&server, body).await;
|
||||
let mock = responses::mount_sse_once(&server, body).await;
|
||||
|
||||
let mut cmd = test.cmd_with_server(&server);
|
||||
let output = cmd
|
||||
@@ -25,18 +28,42 @@ async fn run_exec_with_config(config_toml: &str, extra_args: &[&str]) -> anyhow:
|
||||
|
||||
assert!(output.status.success(), "exec run failed: {output:?}");
|
||||
|
||||
Ok(String::from_utf8(output.stderr)?)
|
||||
Ok((String::from_utf8(output.stderr)?, mock))
|
||||
}
|
||||
|
||||
async fn run_exec_with_auto_review_config(extra_args: &[&str]) -> anyhow::Result<String> {
|
||||
run_exec_with_config(
|
||||
let (stderr, _) = run_exec_with_config(
|
||||
r#"
|
||||
approval_policy = "on-request"
|
||||
approvals_reviewer = "auto_review"
|
||||
"#,
|
||||
extra_args,
|
||||
)
|
||||
.await
|
||||
.await?;
|
||||
Ok(stderr)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_resume_last_without_a_thread_uses_fresh_exec_policy() -> anyhow::Result<()> {
|
||||
let (stderr, _) =
|
||||
run_exec_with_config("approval_policy = 'on-request'", &["resume", "--last"]).await?;
|
||||
assert!(stderr.contains("approval: on-request"), "{stderr}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_warns_about_human_approval_for_granular_policy() -> anyhow::Result<()> {
|
||||
for request_permissions in [true, false] {
|
||||
let policy = format!(
|
||||
"approval_policy={{granular={{sandbox_approval=false,rules=false,request_permissions={request_permissions},mcp_elicitations=false}}}}"
|
||||
);
|
||||
let (stderr, _) = run_exec_with_config("", &["-c", &policy]).await?;
|
||||
assert!(
|
||||
stderr.contains("WARNING: This thread is configured to ask a human"),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
@@ -52,7 +79,7 @@ async fn exec_preserves_on_request_for_auto_review_config() -> anyhow::Result<()
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_approve_for_me_flag_sets_approval_mode_and_sandbox() -> anyhow::Result<()> {
|
||||
let stderr = run_exec_with_config("", &["--approve-for-me"]).await?;
|
||||
let (stderr, _) = run_exec_with_config("", &["--approve-for-me"]).await?;
|
||||
assert!(
|
||||
stderr.contains("approval: on-request"),
|
||||
"stderr missing --approve-for-me approval mode: {stderr}"
|
||||
@@ -76,3 +103,18 @@ async fn exec_bypass_preserves_never_for_auto_review_config() -> anyhow::Result<
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn exec_review_keeps_parent_approval_policy_and_disables_delegate_approvals()
|
||||
-> anyhow::Result<()> {
|
||||
let (stderr, mock) =
|
||||
run_exec_with_config("approval_policy = 'on-request'", &["review"]).await?;
|
||||
assert!(stderr.contains("approval: on-request"), "{stderr}");
|
||||
assert!(
|
||||
mock.single_request()
|
||||
.message_input_texts("developer")
|
||||
.iter()
|
||||
.any(|text| text.contains("Approval policy is currently never"))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1226,6 +1226,12 @@ async fn exec_fork_creates_distinct_threads_with_and_without_a_prompt() -> anyho
|
||||
|
||||
test.cmd_with_server(&server)
|
||||
.arg("--skip-git-repo-check")
|
||||
.args([
|
||||
"-c",
|
||||
"approval_policy='on-request'",
|
||||
"-c",
|
||||
"approvals_reviewer='user'",
|
||||
])
|
||||
.arg("--thread-source")
|
||||
.arg("source_feature")
|
||||
.arg(format!("echo {source_marker}"))
|
||||
@@ -1274,6 +1280,11 @@ async fn exec_fork_creates_distinct_threads_with_and_without_a_prompt() -> anyho
|
||||
"promptless fork failed: {}",
|
||||
String::from_utf8_lossy(&promptless_output.stderr)
|
||||
);
|
||||
let stderr = String::from_utf8(promptless_output.stderr)?;
|
||||
assert!(
|
||||
!stderr.contains("WARNING: This thread is configured to ask a human"),
|
||||
"{stderr}"
|
||||
);
|
||||
let promptless_events = String::from_utf8(promptless_output.stdout)?
|
||||
.lines()
|
||||
.map(serde_json::from_str::<Value>)
|
||||
|
||||
Reference in New Issue
Block a user