Skip to content

fix(agents): detect codex sandbox-denied runs that exit 0 as failures - #39460

Closed
mvanhorn wants to merge 5 commits into
openclaw:mainfrom
mvanhorn:fix/codex-sandbox-denied-exit0
Closed

mvanhorn wants to merge 5 commits into
openclaw:mainfrom
mvanhorn:fix/codex-sandbox-denied-exit0

Conversation

@mvanhorn

@mvanhorn mvanhorn commented Mar 8, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes #39317.

Codex may exit 0 even when a sandbox policy prevented the requested file write. OpenClaw only checked exitCode === 0 and treated these runs as successful, passing the agent's internal failure reasoning as normal output. This causes subagent orchestration to record work as completed when nothing actually happened.

Changes:

  • Add detectSandboxDenied() to scan structured JSONL records for sandbox denial signals (error items, tool-call outputs, status fields) without false-positiving on agents that merely discuss sandboxing
  • Wire into parseCliJsonl() to set sandboxDenied flag on CliOutput
  • CLI runner throws FailoverError with reason "sandbox_denied" when exit-0 JSONL contains sandbox denial
  • Add "sandbox_denied" to FailoverReason and AuthProfileFailureReason types
  • Exclude sandbox_denied from auth profile failure tracking (local config issue, not an auth health signal)
  • Map sandbox_denied to HTTP 403 in resolveFailoverStatus

Design decisions

  • Structured field detection over keyword matching: detectSandboxDenied() scans item.type === "error", tool/command/action item types, item.status, and top-level error fields. It does NOT scan item.type === "message" text, preventing false positives when agents discuss sandbox concepts.
  • Auth profile exclusion: Sandbox denial is a local configuration issue, not a provider auth health signal. Excluded alongside "timeout" in resolveAuthProfileFailureReason().

Testing

  • 11 new regression tests in cli-runner.sandbox-denied.test.ts:
    • detectSandboxDenied: top-level error string, nested error.message, error-typed items, tool-call outputs, command actions, status fields, and three false-positive prevention cases
    • parseCliJsonl integration: sandbox error + exit 0 sets flag, normal output does not

Files changed

File Change
src/agents/cli-runner/helpers.ts Add detectSandboxDenied(), sandboxDenied flag on CliOutput
src/agents/cli-runner.ts Check sandboxDenied after exit-0 JSONL parse, throw FailoverError
src/agents/failover-error.ts Map sandbox_denied to 403
src/agents/pi-embedded-helpers/types.ts Add "sandbox_denied" to FailoverReason
src/agents/auth-profiles/types.ts Add "sandbox_denied" to AuthProfileFailureReason
src/agents/pi-embedded-runner/run.ts Exclude sandbox_denied from auth profile failure state
src/agents/cli-runner.sandbox-denied.test.ts 11 regression tests

Post-Deploy Monitoring & Validation

  • What to monitor: grep gateway logs for sandbox_denied failover reason after deploying
  • Expected healthy behavior: Codex runs with sandbox denials now surface as failures instead of silent false-success
  • Failure signal: existing Codex runs that previously "succeeded" now throw FailoverError. This is the correct behavior but operators should verify sandbox config (--sandbox workspace-write vs read-only) if they see unexpected failures

Codex may exit 0 even when a sandbox policy prevented the requested
operation. The failure is only visible in the JSONL event stream.
Previously OpenClaw checked only exitCode === 0 and treated these
runs as successful, passing the agent's failure reasoning as output.

- Add detectSandboxDenied() to scan JSONL records for structured
  sandbox denial signals (error items, tool outputs, status fields)
- Wire into parseCliJsonl() to set sandboxDenied flag on CliOutput
- CLI runner throws FailoverError with reason "sandbox_denied" when
  exit-0 JSONL contains sandbox denial
- Add "sandbox_denied" to FailoverReason and AuthProfileFailureReason
- Exclude sandbox_denied from auth profile failure tracking (local
  config issue, not an auth health signal)
- 11 regression tests covering detection, false-positive prevention,
  and JSONL integration

Closes openclaw#39317

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 15b25584b0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/agents/cli-runner/helpers.ts Outdated
Comment on lines +306 to +309
if (!text) {
return null;
}
return { text, sessionId, usage };
const sandboxDenied = detectSandboxDenied(records);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Run sandbox detection before empty-text JSONL early return

parseCliJsonl returns null whenever no message text is collected, and only runs detectSandboxDenied(records) after that early return. In Codex runs that emit only structured error/tool events (sandbox denial) without a message item, this path drops the new sandboxDenied signal, so runCliAgent sees parsed as null and treats an exit-0 sandbox failure as success. This reintroduces the false-success behavior for a common denial shape and defeats the fix for those cases.

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Mar 8, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a real bug where Codex can exit 0 even when a sandbox policy denies a requested operation. The approach is architecturally sound — scanning structured JSONL fields to avoid false positives from agents merely discussing sandboxing — and the plumbing across FailoverReason, AuthProfileFailureReason, HTTP status mapping, and auth-profile exclusion is all correct.

Critical logic gap to address before merging:

The sandbox detection in parseCliJsonl is placed after the if (!text) { return null } early-return guard. If a sandbox denial produces JSONL with only error/tool records and no type: "message" items, texts is empty, the function returns null, and the sandbox denial is completely missed. The existing integration tests all include a message item alongside the error item, masking this bug from CI.

To fix:

  1. Move detectSandboxDenied() call before the early-return guard
  2. Return { text: text || stdout, sessionId, usage, sandboxDenied: true } even when text is empty
  3. Add regression test for denial-only JSONL (no message items)

Confidence Score: 2/5

  • The core fix is sound, but there is a critical logic gap where sandbox denials without message text are silently missed — the exact scenario this PR aims to catch.
  • The PR correctly identifies the root bug (Codex exit 0 with sandbox denial), uses the right detection strategy (structured field scanning), and implements supporting type changes and routing correctly. However, the parseCliJsonl() function has an early-return guard that prevents sandbox detection from ever executing when JSONL contains only error/tool items with no message text. This means a class of denials (those without accompanying message output) will be completely missed — defeating the purpose of the PR for those edge cases. The test suite does not cover this gap, so it would not be caught by CI.
  • src/agents/cli-runner/helpers.ts (lines 305–310: move sandbox detection before early-return guard); src/agents/cli-runner.sandbox-denied.test.ts (add denial-only JSONL test case)

Comments Outside Diff (1)

  1. src/agents/cli-runner/helpers.ts, line 305-310 (link)

    Sandbox denial detection is placed after the early-return guard. If Codex produces JSONL with only error/tool items and no type: "message" records, texts will be empty, the function returns null before detectSandboxDenied() is called, and the caller's check parsed?.sandboxDenied is never reached — the denial is silently swallowed.

    Consider moving sandbox detection before the early return:

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/agents/cli-runner/helpers.ts
    Line: 305-310
    
    Comment:
    Sandbox denial detection is placed *after* the early-return guard. If Codex produces JSONL with only error/tool items and no `type: "message"` records, `texts` will be empty, the function returns `null` before `detectSandboxDenied()` is called, and the caller's check `parsed?.sandboxDenied` is never reached — the denial is silently swallowed.
    
    Consider moving sandbox detection before the early return:
    
    
    
    How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: 15b2558

Comment on lines +92 to +130
});

describe("parseCliJsonl sandbox detection", () => {
it("sets sandboxDenied when JSONL contains sandbox error item", () => {
const jsonl = [
JSON.stringify({ thread_id: "abc123" }),
JSON.stringify({
item: {
type: "error",
text: "sandbox policy: write denied for /workspace/TEST_RO.md",
},
}),
JSON.stringify({
item: {
type: "message",
text: "I was unable to write the file due to sandbox restrictions.",
},
}),
].join("\n");

const result = parseCliJsonl(jsonl, CODEX_BACKEND);
expect(result).not.toBeNull();
expect(result!.sandboxDenied).toBe(true);
expect(result!.sessionId).toBe("abc123");
});

it("does not set sandboxDenied for normal output", () => {
const jsonl = [
JSON.stringify({ thread_id: "abc123" }),
JSON.stringify({
item: { type: "message", text: "I've created the file successfully." },
}),
].join("\n");

const result = parseCliJsonl(jsonl, CODEX_BACKEND);
expect(result).not.toBeNull();
expect(result!.sandboxDenied).toBeUndefined();
});
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both integration tests include at least one type: "message" item alongside the sandbox-denial record, so they always produce non-empty text and never exercise the code path where text is empty. Add a test for denial-only JSONL to expose the early-return gap:

Suggested change
});
describe("parseCliJsonl sandbox detection", () => {
it("sets sandboxDenied when JSONL contains sandbox error item", () => {
const jsonl = [
JSON.stringify({ thread_id: "abc123" }),
JSON.stringify({
item: {
type: "error",
text: "sandbox policy: write denied for /workspace/TEST_RO.md",
},
}),
JSON.stringify({
item: {
type: "message",
text: "I was unable to write the file due to sandbox restrictions.",
},
}),
].join("\n");
const result = parseCliJsonl(jsonl, CODEX_BACKEND);
expect(result).not.toBeNull();
expect(result!.sandboxDenied).toBe(true);
expect(result!.sessionId).toBe("abc123");
});
it("does not set sandboxDenied for normal output", () => {
const jsonl = [
JSON.stringify({ thread_id: "abc123" }),
JSON.stringify({
item: { type: "message", text: "I've created the file successfully." },
}),
].join("\n");
const result = parseCliJsonl(jsonl, CODEX_BACKEND);
expect(result).not.toBeNull();
expect(result!.sandboxDenied).toBeUndefined();
});
});
it("sets sandboxDenied when JSONL has only error items and no message text", () => {
const jsonl = [
JSON.stringify({ thread_id: "abc123" }),
JSON.stringify({
item: {
type: "error",
text: "sandbox policy: write denied for /workspace/TEST_RO.md",
},
}),
].join("\n");
const result = parseCliJsonl(jsonl, CODEX_BACKEND);
// Should NOT be null — sandbox denial must be surfaced even without message text.
expect(result).not.toBeNull();
expect(result!.sandboxDenied).toBe(true);
});

Without this fix, the test above would fail because parseCliJsonl returns null.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/cli-runner.sandbox-denied.test.ts
Line: 92-130

Comment:
Both integration tests include at least one `type: "message"` item alongside the sandbox-denial record, so they always produce non-empty `text` and never exercise the code path where `text` is empty. Add a test for denial-only JSONL to expose the early-return gap:

```suggestion
  it("sets sandboxDenied when JSONL has only error items and no message text", () => {
    const jsonl = [
      JSON.stringify({ thread_id: "abc123" }),
      JSON.stringify({
        item: {
          type: "error",
          text: "sandbox policy: write denied for /workspace/TEST_RO.md",
        },
      }),
    ].join("\n");

    const result = parseCliJsonl(jsonl, CODEX_BACKEND);
    // Should NOT be null — sandbox denial must be surfaced even without message text.
    expect(result).not.toBeNull();
    expect(result!.sandboxDenied).toBe(true);
  });
```

Without this fix, the test above would fail because `parseCliJsonl` returns `null`.

How can I resolve this? If you propose a fix, please make it concise.

Move detectSandboxDenied() before the empty-text early return in
parseCliJsonl() so sandbox denials without message-typed items are
still surfaced. Addresses Codex review P1 feedback on PR openclaw#39460.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@mvanhorn

mvanhorn commented Mar 8, 2026

Copy link
Copy Markdown
Contributor Author

Addressed both Codex review comments in 82a261c:

P1 - sandbox denial missed for text-less JSONL: Moved detectSandboxDenied() before the empty-text early return in parseCliJsonl(). Now returns { text: "", sandboxDenied: true } instead of null when sandbox denial is detected but no message-typed items exist. Added a dedicated regression test for this path.

Test coverage gap: Added a new test case (detects sandboxDenied even when JSONL has no message-typed items) that exercises the text-less denial path with only tool_call_output sandbox denial items and no message items. All 12 tests pass.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 82a261c927

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/agents/cli-runner.ts
Comment on lines 390 to +392
if (outputMode === "jsonl") {
const parsed = parseCliJsonl(stdout, backend);
if (parsed?.sandboxDenied) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Check resume text output for sandbox-denied runs

This new guard only runs in the outputMode === "jsonl" branch, but Codex’s default resume path uses text output (resumeOutput: "text" in src/agents/cli-backends.ts), so resumed sessions still return stdout as success without any sandbox-denied check. In practice, an exit-0 sandbox denial during exec resume will continue to be treated as a successful run, which leaves the false-success behavior in the common follow-up-turn flow.

Useful? React with 👍 / 👎.

Comment on lines +250 to +253
(itemType.includes("tool") || itemType.includes("command") || itemType.includes("action")) &&
typeof item.text === "string" &&
SANDBOX_DENIED_RE.test(item.text)
) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require failure markers before flagging tool output text

This branch marks sandbox denial from any tool/command/action item whose text matches the regex, even when the tool call succeeded, but those text fields can contain arbitrary command/file content. A normal run that reads logs or docs containing phrases like "sandbox policy ... denied" will now be misclassified as sandbox_denied and thrown as a FailoverError, so detection should be gated by explicit error status (for example item.type === "error" or a denied status flag) rather than raw tool output text alone.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d80cd24509

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +205 to +206
const SANDBOX_DENIED_RE =
/sandbox.policy|sandbox.denied|sandbox.*read.only|read.only.*sandbox|write.*denied.*sandbox|sandbox.*blocked|permission denied.*sandbox/i;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Tighten text-mode sandbox regex to avoid false failovers

The text-path detector currently matches any output containing sandbox policy via sandbox.policy, so a successful resumed Codex run that merely discusses sandbox behavior (for example, answering a user question about policy) is classified as sandbox_denied and thrown as a FailoverError. Because runCliAgent applies this check unconditionally in outputMode === "text", normal responses can be dropped as failures even when no operation was denied.

Useful? React with 👍 / 👎.

Comment thread src/agents/cli-runner/helpers.ts Outdated
(typeof item.exit_code === "number" && item.exit_code !== 0);
// Short tool output (<500 chars) with denial keywords is almost certainly
// a real denial, not a coincidental match in a long log.
if (hasErrorSignal || item.text.length < 500) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require explicit error signal for tool-output sandbox detection

This branch still marks sandbox denial when matching text appears in any short (<500 chars) tool/command/action output, even if the tool call succeeded (status not failed and exit_code is 0). Successful commands like rg/cat that print lines containing phrases such as sandbox policy can therefore set sandboxDenied, causing the JSONL path to throw FailoverError on a healthy run.

Useful? React with 👍 / 👎.

- Remove short-text (<500 chars) fallback in tool output detection;
  now requires explicit error signal (status=error/failed/denied or
  non-zero exit_code) to flag sandbox denial from tool/command items
- Use stricter regex for text-mode detection to avoid false positives
  when resumed Codex output merely discusses sandbox concepts
- Update tests to reflect tighter detection requirements

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@aisle-research-bot

aisle-research-bot Bot commented Mar 10, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 3 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium Memory exhaustion risk in parseCliJsonl from retaining all parsed JSONL records
2 🟡 Medium Unbounded CLI stdout scanned with backtracking regex can cause resource-exhaustion DoS
3 🟡 Medium Untrusted CLI stdout triggers sandbox_denied FailoverError and model/provider failover

1. 🟡 Memory exhaustion risk in parseCliJsonl from retaining all parsed JSONL records

Property Value
Severity Medium
CWE CWE-400
Location src/agents/cli-runner/helpers.ts:304-335

Description

The parseCliJsonl function now retains every parsed JSONL object in an in-memory records array solely to run detectSandboxDenied(records) after parsing.

This is uncontrolled resource consumption because:

  • Input raw comes from a spawned CLI process (codex exec --json ...) whose stdout is fully captured into memory as a string by the process supervisor.
  • parseCliJsonl additionally does raw.split(...) (allocating an array of all lines) and then JSON.parse on each line.
  • The change adds records.push(parsed) for every parsed line, preventing garbage collection of parsed objects/strings during the loop.

If the CLI produces many JSONL events or very large JSON objects (e.g., long tool output embedded in JSONL), this can significantly increase peak memory and can crash the Node process (DoS).

Vulnerable code:

const texts: string[] = [];
const records: Record<string, unknown>[] = [];
for (const line of lines) {
  ...
  records.push(parsed);
  ...
}
const sandboxDenied = detectSandboxDenied(records);

Recommendation

Avoid retaining the full JSONL record set. Perform sandbox-denied detection incrementally while parsing, or refactor detectSandboxDenied to accept a single record.

Example (online detection without storing records):

let sandboxDenied = false;
for (const line of lines) {
  let parsed: unknown;
  try {
    parsed = JSON.parse(line);
  } catch {
    continue;
  }
  if (!isRecord(parsed)) continue;

  ​// incremental detection
  if (!sandboxDenied && detectSandboxDenied([parsed])) {
    sandboxDenied = true;
  }

  ​// existing extraction logic...
}

Better (no per-iteration array allocation):

function detectSandboxDeniedRecord(rec: Record<string, unknown>): boolean {
  ​// move the body of the loop from detectSandboxDenied here
}

let sandboxDenied = false;
...
if (!sandboxDenied && detectSandboxDeniedRecord(parsed)) sandboxDenied = true;

Additionally, consider implementing an upper bound on captured stdout/stderr (truncate after N bytes) to prevent output-based memory DoS across the whole CLI runner.


2. 🟡 Unbounded CLI stdout scanned with backtracking regex can cause resource-exhaustion DoS

Property Value
Severity Medium
CWE CWE-400
Location src/agents/cli-runner/helpers.ts:214-225

Description

The CLI runner performs sandbox-denied detection by running regular expressions containing multiple .* wildcards against the entire captured stdout.

Why this is risky:

  • stdout is accumulated with no output-size cap (process supervisor concatenates every chunk into a JS string).
  • detectSandboxDeniedInText(stdout) is executed on the raw stdout for outputMode === "text".
  • The patterns include constructs like write.*denied.*sandbox which can exhibit superlinear backtracking on some inputs (e.g., many occurrences of denied but no sandbox), and at minimum require scanning very large strings.

Vulnerable code (regex + unbounded test):

const SANDBOX_DENIED_TEXT_RE =
  ​/sandbox policy:\s*.+? denied|permission denied.*sandbox|write.*denied.*sandbox|read.only.*sandbox/i;

export function detectSandboxDeniedInText(text: string): boolean {
  return SANDBOX_DENIED_TEXT_RE.test(text);
}

This is reachable from the CLI hot path:

  • stdout (untrusted tool/LLM output) → detectSandboxDeniedInText(stdout) → regex engine work on full string.

Impact:

  • A user-controlled prompt/tool output that causes extremely large stdout (or adversarial text shaped to maximize backtracking) can drive high CPU usage in the Node process and contribute to denial of service.

Recommendation

Mitigate uncontrolled resource usage by bounding the scanned input and avoiding backtracking-heavy patterns.

Suggested hardening (combine as appropriate):

  1. Scan only a bounded window (e.g., last N KB/lines) where denial messages would appear:
const MAX_SCAN_CHARS = 64_000;
const window = text.length > MAX_SCAN_CHARS ? text.slice(-MAX_SCAN_CHARS) : text;
return SANDBOX_DENIED_TEXT_RE.test(window);
  1. Replace multi-.* regex branches with linear-time substring searches:
const lower = window.toLowerCase();
if (lower.includes("sandbox policy:") && lower.includes(" denied")) return true;
if (lower.includes("permission denied") && lower.includes("sandbox")) return true;
{
  const iWrite = lower.indexOf("write");
  if (iWrite >= 0) {
    const iDenied = lower.indexOf("denied", iWrite);
    if (iDenied >= 0 && lower.indexOf("sandbox", iDenied) >= 0) return true;
  }
}
return false;
  1. Consider bounding/streaming stdout capture (global mitigation), or at least performing detection on streaming chunks rather than the full accumulated string.

3. 🟡 Untrusted CLI stdout triggers sandbox_denied FailoverError and model/provider failover

Property Value
Severity Medium
CWE CWE-807
Location src/agents/cli-runner.ts:386-415

Description

The CLI runner treats model-controlled output text as a security signal for sandbox_denied and throws FailoverError, which is then used by the model-fallback mechanism to try alternate provider/model candidates.

In runCliAgent():

  • When outputMode === "text" (notably Codex resumeOutput: "text"), it runs detectSandboxDeniedInText(stdout).
  • stdout in text-mode is the assistant's response stream and is therefore attacker-influenceable via prompt injection/user content.
  • If the regex matches, the code throws FailoverError with reason: "sandbox_denied".
  • runWithModelFallback() will treat this as an ordinary failure and proceed to the next fallback candidate, potentially switching to a different backend with different sandbox/tooling guarantees.

This creates a reliance on untrusted input for a security-relevant decision (failover/provider switching) and enables:

  • Forced provider/model switching by embedding strings like "sandbox policy: write denied ..." in the model response during resume runs.
  • Request amplification / reliability DoS: a single request can be made to consume multiple model attempts (primary + fallbacks).
  • Potential security boundary bypass if the fallback chain includes a less restricted runner (e.g., one with broader tool/FS access) than the original sandboxed CLI backend.

Vulnerable code (text-mode):

if (outputMode === "text") {
  if (detectSandboxDeniedInText(stdout)) {
    throw new FailoverError(...{ reason: "sandbox_denied", ... });
  }
  return { text: stdout, sessionId: undefined };
}

The detection is purely regex-based:

const SANDBOX_DENIED_TEXT_RE =
  ​/sandbox policy:\s*.+? denied|permission denied.*sandbox|write.*denied.*sandbox|read.only.*sandbox/i;

Because this runs on raw assistant text, the condition can be satisfied without any real sandbox policy violation.

Recommendation

Do not make failover/provider-switch decisions based on untrusted assistant text.

Recommended hardening (pick one or combine):

  1. Remove text-mode sandbox detection and require structured signals:

    • Configure Codex resume to emit structured JSONL (or JSON) and detect denial only from non-model-controlled fields.
  2. Treat sandbox_denied as terminal (no fallback) unless explicitly configured:

    • Sandbox denial is a policy enforcement signal; falling back to a different backend can bypass the intended restriction.
  3. If text-mode detection must exist, only trust a machine-authored sentinel that the CLI prints outside the model channel (e.g., a dedicated prefix/line emitted by the CLI itself), not arbitrary assistant content.

Example: stop falling back on sandbox_denied (illustrative):

​// in model-fallback runner error handling
if (isFailoverError(normalized) && normalized.reason === "sandbox_denied") {
  throw normalized; // do not attempt other candidates
}

And/or change Codex backend to avoid resumeOutput: "text" and parse JSONL for resume as well.


Analyzed PR: #39460 at commit 6ebd045

Last updated on: 2026-03-10T03:33:13Z

@mvanhorn

Copy link
Copy Markdown
Contributor Author

Addressed remaining P2 bot feedback in 3745049:

P2 - Tool output false positives: Removed the item.text.length < 500 short-text fallback from tool/command/action detection. Now requires an explicit error signal (status = error/failed/denied, or non-zero exit_code) before flagging sandbox denial from tool output. Successful rg/cat commands that print sandbox-related log content will no longer false-positive.

P2 - Text-mode regex too broad: Created a stricter SANDBOX_DENIED_TEXT_RE for text-mode detection that requires patterns matching actual error messages (e.g. sandbox policy: write denied) rather than generic sandbox.policy which could match discussions about sandbox behavior.

Updated all affected test cases to reflect the tighter detection requirements.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3745049148

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/agents/cli-runner/helpers.ts Outdated
* Codex output merely discusses sandbox behavior.
*/
const SANDBOX_DENIED_TEXT_RE =
/sandbox policy:\s*\S+ denied|permission denied.*sandbox|write.*denied.*sandbox|read.only.*sandbox/i;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Match path-bearing sandbox policy denials in text mode

The text-mode detector regex is too narrow: sandbox policy:\s*\S+ denied only matches a single token before denied, so strings like sandbox policy: write to /workspace/file denied (the same denial wording already used in your JSONL tests) are missed. Because Codex resume defaults to outputMode === "text", this leaves a real exit-0 sandbox-denied path unflagged and still treated as success.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6ebd045 - widened the text-mode regex from \S+ (single token) to .+? (multi-word match) so path-bearing denials like sandbox policy: write to /workspace/file denied are now caught. Added a test covering this case.

The \S+ pattern only matched a single token before "denied", missing
denials like "sandbox policy: write to /workspace/file denied".
Changed to .+? to match path-bearing sandbox policy denials.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@mvanhorn

Copy link
Copy Markdown
Contributor Author

Closing to reduce noise on the review queue. The fix is available on my fork if it becomes relevant. Happy to reopen or resubmit if there's interest.

@mvanhorn mvanhorn closed this Mar 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: OpenClaw treats codex exec sandbox-denied runs as success because codex exits 0

1 participant