Skip to content

fix(codex): sanitize approval preview text - #70569

Merged
steipete merged 2 commits into
openclaw:mainfrom
Lucenx9:codex/fix-codex-approval-text-sanitization
Apr 24, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
Lucenx9:codex/fix-codex-approval-text-sanitization

Conversation

@Lucenx9

@Lucenx9 Lucenx9 commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Problem: Codex app-server approval previews forward command and reason text nearly raw into plugin.approval.request descriptions and approval events.
  • Why it matters: embedded newlines, ANSI escapes, and control characters can degrade forwarded approval UX and make event/chat previews harder to trust or scan.
  • What changed: command/reason previews are now sanitized before they are used in approval descriptions or emitted in approval events, and regression tests lock in the sanitized output.
  • What did NOT change (scope boundary): permission approval summaries, approval policy, session scoping, and the plugin approval roundtrip contract.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #
  • Related #
  • This PR fixes a bug or regression

Root Cause (if applicable)

  • Root cause: the bridge treated app-server command / reason fields as display-ready strings and reused them directly in human-facing approval payloads.
  • Missing detection / guardrail: there was no regression test covering multiline/control-character approval previews.
  • Contributing context (if known): permission approvals already had dedicated sanitization, but command/file approval previews did not.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: extensions/codex/src/app-server/approval-bridge.test.ts
  • Scenario the test should lock in: command/reason values with newlines, ANSI escapes, and control characters are compacted before they reach approval descriptions and approval events.
  • Why this is the smallest reliable guardrail: the bug is entirely inside the approval bridge formatting path.
  • Existing test that already covers this (if any): none.
  • If no new test is added, why not: N/A.

User-visible / Behavior Changes

  • Codex command/file approval previews now collapse multiline/control-character text into compact single-line summaries before forwarding them to the gateway approval UI/events.

Diagram (if applicable)

Before:
[app-server command/reason with ANSI/newlines] -> [approval bridge] -> [raw preview/event text]

After:
[app-server command/reason with ANSI/newlines] -> [approval bridge sanitization] -> [compact preview/event text]

Security Impact (required)

  • New permissions/capabilities? (No)
  • Secrets/tokens handling changed? (No)
  • New/changed network calls? (No)
  • Command/tool execution surface changed? (No)
  • Data access scope changed? (No)
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS: Linux
  • Runtime/container: local Node/pnpm checkout
  • Model/provider: N/A
  • Integration/channel (if any): Codex app-server bridge
  • Relevant config (redacted): default local dev config

Steps

  1. Trigger handleCodexAppServerApprovalRequest with a command approval containing newlines / ANSI escapes in requestParams.command.
  2. Trigger handleCodexAppServerApprovalRequest with a file approval containing newlines / ANSI escapes in requestParams.reason.
  3. Inspect the forwarded plugin.approval.request payload and emitted approval events.

Expected

  • Approval descriptions and event payloads contain compact sanitized preview text.

Actual

  • Before this change, raw formatting/control characters were forwarded.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

  • Verified scenarios: targeted Codex approval bridge tests for command approval, unavailable file approval, and the new command/reason sanitization cases.
  • Edge cases checked: ANSI escape stripping, multiline compaction, control-character stripping, unchanged permission approval behavior.
  • What you did not verify: full GitHub CI and live chat-forwarded approval UX on a running gateway.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? (Yes)
  • Config/env changes? (No)
  • Migration needed? (No)
  • If yes, exact upgrade steps:

Risks and Mitigations

  • Risk: over-sanitizing could remove legitimate formatting from previews.
    • Mitigation: only ANSI/control characters are stripped; printable content is preserved and regression-tested.

@aisle-research-bot

aisle-research-bot Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

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

# Severity Title
1 🟠 High Approval decision context uses truncated/sanitized command/reason previews, enabling policy/approval bypass
2 🟡 Medium Approval preview sanitization does not flag omitted/modified content unless clipped or empty
3 🟡 Medium Approval prompt can omit command/reason for exec approvals, enabling misleading approvals
1. 🟠 Approval decision context uses truncated/sanitized command/reason previews, enabling policy/approval bypass
Property Value
Severity High
CWE CWE-863
Location extensions/codex/src/app-server/approval-bridge.ts:193-203

Description

buildApprovalContext now replaces the original command/reason values with a sanitized + truncated preview before emitting approval events and before sending the approval request to the gateway.

Security impact:

  • The downstream approval plugin is invoked via requestPluginApproval() with only a short description field (hard-truncated to 256 chars).
  • After this change, the emitted approval event details (command/reason) and the plugin/UI description are derived from sanitizeApprovalPreview(..., 180).
  • An attacker (or malicious prompt/tool output) can craft a command/reason where the dangerous portion is beyond the preview length (or removed by sanitization), causing:
    • human approvers to see an incomplete, benign-looking command/reason
    • policy engines that parse description/event details to evaluate risk to make an allow/deny decision on incomplete data

Vulnerable code:

const commandPreview = sanitizeApprovalPreview(readDisplayCommandPreview(params.requestParams), 180);
const reasonPreview = sanitizeApprovalPreview(readStringPreview(params.requestParams, "reason"), 180);
const command = commandPreview.text;
const reason = reasonPreview.text;
...
eventDetails: {
  ...(command ? { command } : {}),
  ...(reason ? { reason } : {}),
}

While commandPreviewOmitted / reasonPreviewOmitted flags are emitted, the gateway tool request (plugin.approval.request) does not include these flags, and consumers may ignore them; the policy decision is therefore at risk of being made without access to the full underlying command/reason.

Recommendation

Ensure approval/policy decisions are based on the full underlying command/reason, while still protecting the UI from terminal escape injection.

Suggested approach:

  • Keep two separate fields:
    • commandFull/reasonFull (raw/full; not rendered directly)
    • commandPreview/reasonPreview (sanitized, truncated for display)
  • Send the full values to the approval plugin in a dedicated structured field (not in a truncated description), and/or include a cryptographic hash of the full command so approvers/policy can validate what was approved.
  • If full content is too large, explicitly fail closed or require manual approval with an attached artifact.

Example:

const commandFull = readDisplayCommand(params.requestParams); // full
const commandPreview = sanitizeApprovalPreview(previewSource(commandFull ?? ""), 180);

await requestPluginApproval({
  ...,
  description: `Command: ${formatApprovalPreviewSubject(commandPreview.text ?? "", commandPreview.omitted)}`,
  ​// add non-truncated structured context for policy engines:
  context: { commandFull, reasonFull },
});

emitApprovalEvent(paramsForRun, {
  ...,
  commandPreview: commandPreview.text,
  commandPreviewOmitted: commandPreview.omitted,
  ​// do NOT overwrite `command` with the preview if consumers treat it as authoritative
});

Also update approval consumers to treat *PreviewOmitted as a hard warning / require manual inspection, rather than proceeding with automated allow rules.

2. 🟡 Approval preview sanitization does not flag omitted/modified content unless clipped or empty
Property Value
Severity Medium
CWE CWE-451
Location extensions/codex/src/app-server/approval-bridge.ts:662-675

Description

sanitizeApprovalPreview() removes potentially dangerous/ambiguous characters (ANSI/OSC sequences, control chars, bidi/invisible formatting controls) but sets the omitted indicator only when the input was clipped by length (source.clipped) or when sanitization results in an empty string.

This creates a deception risk in approval UX:

  • Input: untrusted command / reason values from requestParams.
  • Transformation: sanitizeVisibleScalar() strips terminal escape sequences and invisible formatting characters.
  • Display: the approver sees the sanitized text in subject/description.
  • Problem: if unsafe characters were removed but some visible text remains (common case), omitted remains false, so the UI/event stream does not warn that the content was modified/removed.

An attacker could craft a command/reason containing hidden or terminal-control content that is stripped for display, causing the approver to see a different (sanitized) string without any indication that sanitization occurred.

Vulnerable code:

const rawPreview = source.value.replace(DANGLING_TERMINAL_SEQUENCE_SUFFIX_RE, "");
const sanitized = sanitizeVisibleScalar(rawPreview);
...
return { text: truncate(sanitized, maxLength), omitted: source.clipped };

Recommendation

Treat sanitization changes as omission as well (not only clipping), so approvers are warned whenever unsafe/control content was removed.

For example:

function sanitizeApprovalPreview(
  source: ApprovalPreviewSource | undefined,
  maxLength: number,
): SanitizedApprovalPreview {
  if (!source || !source.value) return { omitted: false };

  const rawPreview = source.value.replace(DANGLING_TERMINAL_SEQUENCE_SUFFIX_RE, "");
  const sanitized = sanitizeVisibleScalar(rawPreview);

  ​// Flag omission if we clipped OR if sanitization altered the string.
  const sanitizedChanged = sanitized !== sanitizeVisibleScalar(source.value);
  const omitted = source.clipped || rawPreview !== source.value || sanitizedChanged;

  if (!sanitized) return { omitted: true };
  return { text: truncate(sanitized, maxLength), omitted };
}

Alternatively, explicitly detect matches of the stripping regexes (e.g., ANSI_OSC_SEQUENCE_RE.test(...)) and set omitted = true when any are present.

This ensures commandPreviewOmitted / reasonPreviewOmitted and the subject suffix ([preview truncated or unsafe content omitted]) accurately reflect any material sanitization.

3. 🟡 Approval prompt can omit command/reason for exec approvals, enabling misleading approvals
Property Value
Severity Medium
CWE CWE-1021
Location extensions/codex/src/app-server/approval-bridge.ts:603-626

Description

The approval bridge can generate an approval request without any command or reason shown to the approver, yet still return an "accept" decision for item/commandExecution/requestApproval.

  • readCommandPreview() returns undefined when requestParams.command is an array containing any non-string element.
  • readCommandActionsPreview() silently skips any non-object action or any action missing a string command.
  • When neither preview yields text, buildApprovalContext() falls back to a generic subject (Request method: ...).
  • The bridge does not fail closed in this situation; it still requests approval and, if approved, responds with decision: "accept".

This creates a confused-deputy / social-engineering risk: a malicious or compromised caller that can influence requestParams can cause approvers to approve an execution request without seeing what is actually being executed (or can cause the UI to present a much less scrutinizable prompt).

Vulnerable code (preview becomes undefined and subject falls back):

for (const part of command) {
  if (typeof part !== "string") {
    return undefined;
  }
}
...
: `Request method: ${params.method}`

Recommendation

Fail closed for exec approvals when no trustworthy preview can be produced.

Suggested change:

  • For item/commandExecution/requestApproval, if both readCommandActionsPreview() and readCommandPreview() produce no usable text (or are omitted), decline the approval request (or include a safe, structured fallback like a redacted JSON summary).
  • Additionally, enforce the protocol type at runtime: require command to be a string (since the generated type specifies command?: string | null).

Example:

if (params.method === "item/commandExecution/requestApproval") {
  const source = readDisplayCommandPreview(params.requestParams);
  const preview = sanitizeApprovalPreview(source, 180);
  if (!preview.text) {
    ​// no command displayed -> deny
    return {
      kind,
      title,
      description: "Command preview unavailable; denying approval request.",
      ​// ...
      forceDeny: true,
    };
  }
}

And when building the response, if forceDeny is set, return decline.


Analyzed PR: #70569 at commit bed8ce3

Last updated on: 2026-04-24T04:19:39Z

@greptile-apps

greptile-apps Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds sanitizeApprovalPreviewText to strip ANSI escape sequences, control characters, and collapse whitespace in command/reason fields before they are forwarded into plugin.approval.request descriptions and approval events. Two regression tests lock in the sanitized output for command and file-change approval paths. The implementation is clean and well-scoped; permission approvals are unaffected.

Confidence Score: 5/5

Safe to merge; the sanitization logic is correct, well-tested, and scoped only to command/reason preview formatting.

No P0 or P1 findings. The ANSI and control-character regex construction via String.raw + RegExp is correct, ordering of replacements is sound, truncation is properly folded into the helper, and the new tests confirm expected output for both code paths. Only a trivial style nit remains.

No files require special attention.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/codex/src/app-server/approval-bridge.ts
Line: 20-21

Comment:
**Missing blank line before export**

There is no blank line separating the new module-level constant declarations from the exported function, which is inconsistent with the surrounding style and makes the module header harder to scan at a glance.

```suggestion
const CONTROL_CHARACTER_RE = new RegExp(String.raw`[\u0000-\u001f\u007f]+`, "g");

export async function handleCodexAppServerApprovalRequest(params: {
```

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

Reviews (1): Last reviewed commit: "fix(codex): sanitize approval preview te..." | Re-trigger Greptile

@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: b047548936

ℹ️ 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".

@steipete

Copy link
Copy Markdown
Contributor

Codex maintainer deep review: useful fix, but I would not merge this yet because approval preview text is a security/UI boundary.

Please harden before landing:

  • Cap untrusted command / reason length before running multi-pass regex sanitization. The app-server payload can be large, and the current helper truncates only after scanning the whole string.
  • Strip Unicode bidi and invisible formatting controls (U+061C, U+200B-U+200F, U+202A-U+202E, U+2066-U+2069, U+FEFF) so approval text cannot render differently from what was logged or approved.
  • Cover C1/8-bit terminal controls as well as ESC-prefixed CSI/OSC, or use a proven local/helper sanitizer if we already have one in-tree.
  • Add tests for bidi spoofing, C1 controls, oversized input capping, and the existing OSC-8 visible-label preservation case.

The scope is otherwise good: sanitizing only the command/reason preview fields and leaving permission approval details alone is the right boundary.

@Lucenx9

Lucenx9 commented Apr 23, 2026

Copy link
Copy Markdown
Contributor Author

@steipete pushed a hardening follow-up in ece3862d3f.

Covered all four items from your review:

  • cap untrusted preview input before multi-pass sanitization (APPROVAL_PREVIEW_SCAN_MAX_LENGTH)
  • strip bidi / invisible formatting controls
  • cover C1 / 8-bit OSC+CSI in addition to ESC-prefixed sequences
  • add regressions for bidi spoofing, C1 controls, oversized input capping, and the OSC-8 visible-label case

Scope stays the same: only command / reason preview fields are sanitized; permission approval detail is unchanged.

Local verification:

  • pnpm test extensions/codex/src/app-server/approval-bridge.test.ts
  • oxlint
  • check:changed lane passed locally

@steipete
steipete merged commit ed6094b into openclaw:main Apr 24, 2026
64 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Codex review follow-up: landed as ed6094b301.

Rewritten to cap and sanitize approval preview text before command-array joins, strip terminal/control/invisible formatting controls, and mark omitted/truncated previews explicitly. Focused local proof before push: pnpm test extensions/codex/src/app-server/approval-bridge.test.ts (15 tests). Thanks @Lucenx9.

Angfr95 pushed a commit to Angfr95/openclaw that referenced this pull request Apr 25, 2026
Harden Codex app-server approval preview text sanitization and truncation handling.

Thanks @Lucenx9.

Co-authored-by: Lucenx9 <[email protected]>
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
Harden Codex app-server approval preview text sanitization and truncation handling.

Thanks @Lucenx9.

Co-authored-by: Lucenx9 <[email protected]>
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
Harden Codex app-server approval preview text sanitization and truncation handling.

Thanks @Lucenx9.

Co-authored-by: Lucenx9 <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
Harden Codex app-server approval preview text sanitization and truncation handling.

Thanks @Lucenx9.

Co-authored-by: Lucenx9 <[email protected]>
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
Harden Codex app-server approval preview text sanitization and truncation handling.

Thanks @Lucenx9.

Co-authored-by: Lucenx9 <[email protected]>
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
Harden Codex app-server approval preview text sanitization and truncation handling.

Thanks @Lucenx9.

Co-authored-by: Lucenx9 <[email protected]>
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
Harden Codex app-server approval preview text sanitization and truncation handling.

Thanks @Lucenx9.

Co-authored-by: Lucenx9 <[email protected]>
Heetisk pushed a commit to Heetisk/openclaw that referenced this pull request Sep 28, 2026
Harden Codex app-server approval preview text sanitization and truncation handling.

Thanks @Lucenx9.

Co-authored-by: Lucenx9 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants