codex icon indicating copy to clipboard operation
codex copied to clipboard

Exec-policy approval response can persist a prefix different from the offered amendment

Open TheOutlandsDev opened this issue 1 month ago • 3 comments

The command approval request offered the reusable prefix ["touch", "proposed-only.txt"]. In an isolated local test, I returned an approval response containing the broader prefix ["touch"]. Codex app-server 0.166.0 saved prefix_rule(pattern=["touch"], decision="allow"); a later touch unrelated.txt command then ran without another approval prompt.

Expected behavior

An amendment approval should apply only a prefix offered in that approval request. A response containing a different prefix should not save a rule or approve the command.

Reproduction and scope

  1. Start Codex app-server 0.166.0 with a temporary home and workspace, plus a loopback mock model. No account or external service is involved.
  2. Have the mock model request touch proposed-only.txt with a proposed reusable prefix of ["touch", "proposed-only.txt"].
  3. Return acceptWithExecpolicyAmendment with execpolicy_amendment: ["touch"].
  4. Observe that the temporary rules/default.rules contains prefix_rule(pattern=["touch"], decision="allow").
  5. Have the mock model request touch unrelated.txt. The turn completes and the file exists without a second approval request.

This tests a deliberately altered approval response. The normal terminal UI sends the offered prefix. I have not established that an untrusted actor can alter the response, so I am reporting a response-validation mismatch, not claiming an exploitable vulnerability.

In the traced workflow, the approval response comes from the app-server client over its request/response channel. The terminal UI constructs its choice from the offered decision and copies that exact prefix. The app server accepts the prefix from the client response. The mock probe acted as a custom client; it did not show that model output, a tool result, or a webpage can supply the altered response.

Source observation

request_command_approval sends available decisions but the pending approval stores no offered amendment. exec_approval persists the amendment supplied in the response before resolving that pending approval. PendingApproval::validate restricts managed human-command decisions but does not compare an exec-policy amendment with the offered prefix.

Relevant source: approval request, approval handler, pending approval validation.

I prepared a local regression test and narrow fix that record the offered amendment, reject a different response prefix, and persist only after validation. The new regression test and five existing amendment tests pass in an isolated Rust 1.98 build. The repository specifies Rust 1.95, which was not installed locally. I can provide the patch and test details if useful.

Related: #52286 discusses risks of persisted prefix rules generally. This report concerns the different prefix supplied in an approval response.

TheOutlandsDev avatar Oct 30 '26 01:10 TheOutlandsDev

Follow-up with the exact proposed fix and regression test for this issue. The patch below is against local commit e9854c0 (2026-10-29). I checked the three changed production-file blob SHAs against upstream main f2ac998 on 2026-10-30; they still match. I have not rebuilt the entire patch against that newer main commit.

The change records the amendments actually offered in the pending approval, validates the returned decision before saving any rule, and refuses a changed prefix. The regression proposes ["touch", "proposed-only.txt"], returns ["touch"], and asserts that no command runs and no broad rule is saved. The new regression and five existing amendment tests passed in an isolated Rust 1.98 build. The repo specifies Rust 1.95, which was unavailable locally. git diff --check passes.

This remains a client-response validation bug report. I have not found a lower-trust path that can alter the response, so this is not a claim of an exploitable vulnerability.

Proposed patch (four files, 143 additions and 41 deletions)
diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs
index 2564c56..0d6fd15 100644
--- a/codex-rs/core/src/session/handlers.rs
+++ b/codex-rs/core/src/session/handlers.rs
@@ -187,7 +187,7 @@ pub async fn exec_approval(
     turn_id: Option<String>,
     decision: ReviewDecision,
 ) {
-    let human_approval = {
+    let validated_approval = {
         let active = sess.active_turn.lock().await;
         let Some(turn) = active.as_ref() else {
             return;
@@ -196,15 +196,40 @@ pub async fn exec_approval(
         let Some(pending) = state.pending_approval(&approval_id) else {
             return;
         };
-        if pending.kind == codex_protocol::approvals::ExecApprovalKind::HumanCommand {
+        if pending.kind == codex_protocol::approvals::ExecApprovalKind::HumanCommand
+            || matches!(
+                &decision,
+                ReviewDecision::ApprovedExecpolicyAmendment { .. }
+            )
+        {
             state.remove_pending_approval(&approval_id)
         } else {
             None
         }
     };
-    if let Some(pending) = human_approval {
+    if let Some(pending) = validated_approval {
+        if pending.sender.is_closed() {
+            return;
+        }
+        let human_command =
+            pending.kind == codex_protocol::approvals::ExecApprovalKind::HumanCommand;
         let decision = pending.validate(decision);
-        if decision == ReviewDecision::Abort {
+        if let ReviewDecision::ApprovedExecpolicyAmendment {
+            proposed_execpolicy_amendment,
+        } = &decision
+            && let Err(err) = sess
+                .persist_execpolicy_amendment(proposed_execpolicy_amendment)
+                .await
+        {
+            let message = format!("Failed to apply execpolicy amendment: {err}");
+            tracing::warn!("{message}");
+            sess.send_event_raw(Event {
+                id: turn_id.unwrap_or_else(|| approval_id.clone()),
+                msg: EventMsg::Warning(WarningEvent { message }),
+            })
+            .await;
+        }
+        if human_command && decision == ReviewDecision::Abort {
             sess.abort_turn_if_active(
                 &pending.turn_id,
                 TurnAbortReason::Interrupted,
@@ -215,23 +240,6 @@ pub async fn exec_approval(
         pending.sender.send(decision).ok();
         return;
     }
-    let event_turn_id = turn_id.unwrap_or_else(|| approval_id.clone());
-    if let ReviewDecision::ApprovedExecpolicyAmendment {
-        proposed_execpolicy_amendment,
-    } = &decision
-        && let Err(err) = sess
-            .persist_execpolicy_amendment(proposed_execpolicy_amendment)
-            .await
-    {
-        let message = format!("Failed to apply execpolicy amendment: {err}");
-        tracing::warn!("{message}");
-        let warning = EventMsg::Warning(WarningEvent { message });
-        sess.send_event_raw(Event {
-            id: event_turn_id.clone(),
-            msg: warning,
-        })
-        .await;
-    }
     match decision {
         ReviewDecision::Abort => {
             sess.interrupt_task().await;
diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs
index f43f767..ccecc78 100644
--- a/codex-rs/core/src/session/mod.rs
+++ b/codex-rs/core/src/session/mod.rs
@@ -3100,6 +3100,35 @@ impl Session {
         //  command-level approvals use `call_id`.
         // `approval_id` identifies subcommand callbacks and stdin writes.
         let effective_approval_id = approval_id.clone().unwrap_or_else(|| call_id.clone());
+        let proposed_network_policy_amendments = network_approval_context.as_ref().map(|context| {
+            vec![
+                NetworkPolicyAmendment {
+                    host: context.host.clone(),
+                    action: NetworkPolicyRuleAction::Allow,
+                },
+                NetworkPolicyAmendment {
+                    host: context.host.clone(),
+                    action: NetworkPolicyRuleAction::Deny,
+                },
+            ]
+        });
+        let available_decisions = available_decisions.unwrap_or_else(|| {
+            ExecApprovalRequestEvent::default_available_decisions(
+                network_approval_context.as_ref(),
+                proposed_execpolicy_amendment.as_ref(),
+                proposed_network_policy_amendments.as_deref(),
+                additional_permissions.as_ref(),
+            )
+        });
+        let offered_execpolicy_amendments = available_decisions
+            .iter()
+            .filter_map(|decision| match decision {
+                ReviewDecision::ApprovedExecpolicyAmendment {
+                    proposed_execpolicy_amendment,
+                } => Some(proposed_execpolicy_amendment.clone()),
+                _ => None,
+            })
+            .collect();
         // Add the tx_approve callback to the map before sending the request.
         let (tx_approve, rx_approve) = oneshot::channel();
         let prev_entry = {
@@ -3112,6 +3141,7 @@ impl Session {
                         tx_approve,
                         kind,
                         turn_context.sub_id.clone(),
+                        offered_execpolicy_amendments,
                     )
                 }
                 None => None,
@@ -3122,26 +3152,6 @@ impl Session {
         }
 
         let parsed_cmd = parse_command(&command);
-        let proposed_network_policy_amendments = network_approval_context.as_ref().map(|context| {
-            vec![
-                NetworkPolicyAmendment {
-                    host: context.host.clone(),
-                    action: NetworkPolicyRuleAction::Allow,
-                },
-                NetworkPolicyAmendment {
-                    host: context.host.clone(),
-                    action: NetworkPolicyRuleAction::Deny,
-                },
-            ]
-        });
-        let available_decisions = available_decisions.unwrap_or_else(|| {
-            ExecApprovalRequestEvent::default_available_decisions(
-                network_approval_context.as_ref(),
-                proposed_execpolicy_amendment.as_ref(),
-                proposed_network_policy_amendments.as_deref(),
-                additional_permissions.as_ref(),
-            )
-        });
         let plugin_attribution = plugin_attribution_override.or_else(|| {
             cwd.to_abs_path()
                 .ok()
@@ -3203,6 +3213,7 @@ impl Session {
                         tx_approve,
                         ExecApprovalKind::Command,
                         turn_context.sub_id.clone(),
+                        Vec::new(),
                     )
                 }
                 None => None,
diff --git a/codex-rs/core/src/state/turn.rs b/codex-rs/core/src/state/turn.rs
index 0eba857..b204dd5 100644
--- a/codex-rs/core/src/state/turn.rs
+++ b/codex-rs/core/src/state/turn.rs
@@ -8,6 +8,7 @@ use tokio_util::sync::CancellationToken;
 use tokio_util::task::AbortOnDropHandle;
 
 use codex_diagnostics::GaugeGuard;
+use codex_protocol::approvals::ExecPolicyAmendment;
 use codex_protocol::dynamic_tools::DynamicToolResponse;
 use codex_protocol::request_permissions::RequestPermissionProfile;
 use codex_protocol::request_permissions::RequestPermissionsResponse;
@@ -108,6 +109,7 @@ pub(crate) struct PendingApproval {
     pub(crate) sender: oneshot::Sender<ReviewDecision>,
     pub(crate) kind: codex_protocol::approvals::ExecApprovalKind,
     pub(crate) turn_id: String,
+    pub(crate) offered_execpolicy_amendments: Vec<ExecPolicyAmendment>,
 }
 
 impl PendingApproval {
@@ -119,6 +121,14 @@ impl PendingApproval {
             )
         {
             ReviewDecision::denied("Managed command policy requires a one-time human approval.")
+        } else if let ReviewDecision::ApprovedExecpolicyAmendment {
+            proposed_execpolicy_amendment,
+        } = &decision
+            && !self
+                .offered_execpolicy_amendments
+                .contains(proposed_execpolicy_amendment)
+        {
+            ReviewDecision::denied("The execpolicy amendment was not offered for this approval.")
         } else {
             decision
         }
@@ -147,6 +157,7 @@ impl TurnState {
         tx: oneshot::Sender<ReviewDecision>,
         kind: codex_protocol::approvals::ExecApprovalKind,
         turn_id: String,
+        offered_execpolicy_amendments: Vec<ExecPolicyAmendment>,
     ) -> Option<PendingApproval> {
         self.pending_approvals.insert(
             key,
@@ -154,6 +165,7 @@ impl TurnState {
                 sender: tx,
                 kind,
                 turn_id,
+                offered_execpolicy_amendments,
             },
         )
     }
diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs
index 699d881..e8e17d1 100644
--- a/codex-rs/core/tests/suite/approvals.rs
+++ b/codex-rs/core/tests/suite/approvals.rs
@@ -2401,6 +2401,77 @@ async fn approving_execpolicy_amendment_emits_one_saved_prefix_notice(
     Ok(())
 }
 
+#[tokio::test(flavor = "current_thread")]
+#[cfg(unix)]
+async fn mismatched_execpolicy_amendment_is_denied_without_persisting_policy() -> Result<()> {
+    let server = start_mock_server().await;
+    let approval_policy = AskForApproval::UnlessTrusted;
+    let sandbox_policy = SandboxPolicy::new_workspace_write_policy();
+    let sandbox_policy_for_config = sandbox_policy.clone();
+    let mut builder = test_codex().with_config(move |config| {
+        config.permissions.approval_policy = Constrained::allow_any(approval_policy);
+        config
+            .set_legacy_sandbox_policy(sandbox_policy_for_config)
+            .expect("set sandbox policy");
+    });
+    let test = builder.build(&server).await?;
+    let call_id = "mismatched-prefix";
+    let (event, command) = ActionKind::RunCommand {
+        command: "touch proposed-only.txt",
+    }
+    .prepare(&test, &server, call_id, SandboxPermissions::UseDefault)
+    .await?;
+    let command = command.expect("shell command");
+    let _ = mount_sse_once(
+        &server,
+        sse(vec![
+            ev_response_created("mismatched-prefix-1"),
+            event,
+            ev_completed("mismatched-prefix-1"),
+        ]),
+    )
+    .await;
+    let _ = mount_sse_once(
+        &server,
+        sse(vec![
+            ev_assistant_message("mismatched-prefix-2", "done"),
+            ev_completed("mismatched-prefix-2"),
+        ]),
+    )
+    .await;
+    submit_turn(&test, "probe", approval_policy, sandbox_policy).await?;
+    let approval = expect_exec_approval(&test, &command).await;
+    assert_eq!(
+        approval.proposed_execpolicy_amendment,
+        Some(ExecPolicyAmendment::new(vec![
+            "touch".to_string(),
+            "proposed-only.txt".to_string(),
+        ]))
+    );
+
+    test.codex
+        .submit(Op::ExecApproval {
+            id: approval.effective_approval_id(),
+            turn_id: None,
+            decision: ReviewDecision::ApprovedExecpolicyAmendment {
+                proposed_execpolicy_amendment: ExecPolicyAmendment::new(vec!["touch".to_string()]),
+            },
+        })
+        .await?;
+    wait_for_completion(&test).await;
+
+    assert!(!test.cwd.path().join("proposed-only.txt").exists());
+    let policy_path = test.home.path().join("rules").join("default.rules");
+    if policy_path.exists() {
+        let policy_contents = fs::read_to_string(policy_path)?;
+        assert!(
+            !policy_contents.contains(r#"prefix_rule(pattern=["touch"], decision="allow")"#),
+            "mismatched prefix was saved: {policy_contents}"
+        );
+    }
+    Ok(())
+}
+
 #[tokio::test(flavor = "current_thread")]
 #[cfg(unix)]
 async fn approving_execpolicy_amendment_persists_policy_and_skips_future_prompts() -> Result<()> {

TheOutlandsDev avatar Oct 30 '26 12:10 TheOutlandsDev

Current-main follow-up for this ordinary client-response validation bug: I rebased the proposed fix onto e7f32cf1928a35a9232a633a51c2a03b5a7e2c72. The current approval handler already validates before persisting, so this version changes three files: it records the exec-policy amendments actually offered in the pending approval, rejects a different returned amendment, and adds an integration regression.

In a network-disabled container with the repository's pinned Rust 1.95 toolchain, the new test passed. It offers ["touch", "proposed-only.txt"], returns ["touch"], and asserts the explicit denial message, no command-created file, and no saved prefix rule. Four existing offered-prefix notice variants also passed. The patch applies cleanly to that commit and passed formatting and whitespace checks.

Two other existing amendment tests could not verify shell execution in this container: a minimal bubblewrap launch fails with No permissions to create new namespace. One test did save the offered rule before its shell command exited 1. I am not counting those two as passes or product regressions. The local patch is available if maintainers want it; I have not found a lower-trust route that can alter the approval response, so this remains an ordinary bug report rather than an exploit claim.

Runner follow-up (2026-11-05): The existing approving_execpolicy_amendment_persists_policy_and_skips_future_prompts test genuinely passed when run with the already-built binary in a local user/PID namespace and loopback mock. The spawned_subagent_execpolicy_amendment_propagates_to_parent_session test reported ok only because its skip_if_no_network! guard skipped it in this Codex sandbox; it remains unverified. A minimal network-disabled Docker retry with CAP_SYS_ADMIN still could not launch bubblewrap. The verified set is now the new regression, four notice variants, and the persistence/future-prompt control. No code was uploaded.

Owner-terminal completion (2026-11-05): The remaining spawned_subagent_execpolicy_amendment_propagates_to_parent_session control ran from a normal server-01 terminal against the same built current-main test binary. I read back the private log and matched the binary hash: 1 passed; 0 failed, 1.60 seconds, exit 0, with no skip message. Across separate local runs, the new mismatched-prefix regression and six existing focused amendment controls have now passed. The earlier container failures and Codex-sandbox skip remain recorded as setup-limited attempts; this is not a full suite, CI, or cross-platform result. No code or private log was uploaded.

TheOutlandsDev avatar Nov 05 '26 12:11 TheOutlandsDev

Confirming this still reproduces on the current production release, 0.172.0 (rust-v0.172.0, npm @openai/[email protected]) — the report above was filed against 0.166.0.

End-to-end dynamic test on the release binary, scratch CODEX_HOME:

  • codex app-server --listen ws://127.0.0.1:18999 (no --ws-auth)
  • an unauthenticated raw WebSocket client drove a turn that ran systemctl restart frobnicate-xyz
  • core's approval request proposed the amendment ["systemctl", "restart", "frobnicate-xyz"]
  • the client answered acceptWithExecpolicyAmendment with ["systemctl"]
  • resulting rules/default.rules:
prefix_rule(pattern=["systemctl"], decision="allow")

The broadened amendment was persisted verbatim — no comparison against the proposal, no clamping, no warning.

One supporting data point for the proposed fix direction: the sibling network amendment path in the same codebase already binds the client's answer to the approval context — validated_network_policy_amendment_host (core/src/session/mod.rs) rejects a network amendment whose host does not match the context. The execpolicy path is the only amendment path without that check, so recording offered_execpolicy_amendments on the pending approval (as in the patch above) matches the codebase's own existing pattern.

I agree with the reporter's framing that this is a response-validation bug; noting the ws listener only because it is a convenient way to exercise the path with a non-first-party client — the missing check itself is in Session::resolve_exec_approval (core/src/session/handlers.rs) and is transport-independent.

yuhe6969 avatar Nov 26 '26 13:11 yuhe6969