Skip to content

fix(headers): stop crashes from non-ASCII headers in proxy-capture and image responses - #156192

Closed
YangManBOBO wants to merge 1 commit into
openclaw:mainfrom
YangManBOBO:fix/forwarded-header-latin1-complement
Closed

YangManBOBO wants to merge 1 commit into
openclaw:mainfrom
YangManBOBO:fix/forwarded-header-latin1-complement

Conversation

@YangManBOBO

Copy link
Copy Markdown
Contributor

Related: #154685
Complements: #156166

What Problem This Solves

Fixes: the Gateway can crash (and crash-loop under systemd) when a response boundary forwards or builds a Content-Disposition header from a non-ASCII filename. PR #156166 fixes the primary egress-proxy site from #154685; this change closes the same class of crash at the two other write sites it does not cover.

User Impact

User impact: attachments with non-ASCII filenames served through the debug capture proxy, and image responses carrying a caller-supplied non-ASCII filename, no longer risk taking down the Gateway with an uncaught ERR_INVALID_CHAR. Filenames are preserved with an ASCII fallback plus RFC 5987 filename*=UTF-8''….

Why This Change Was Made

Node requires header values to be Latin-1 and throws ERR_INVALID_CHAR at the write boundary. Two response paths were still unguarded:

This change centralizes the encoding in a shared helper (src/shared/http-header-sanitize.ts): Content-Disposition filenames get an ASCII filename= fallback plus filename*=UTF-8''… (the same encoding the Gateway's media responses already use), and any other non-Latin-1 header value is scrubbed, covering both setHeader and writeHead. Safe headers pass through unchanged.

Evidence

  • 27 unit tests for the shared helper cover Latin-1 acceptance, RFC 5987 re-encoding (CJK, escaped quotes, bare filenames), array values, and unchanged safe headers.
  • src/gateway/http-image-response.test.ts regression: a CJK filename is re-encoded to attachment; filename="__.png"; filename*=UTF-8''%E9%99%84%E4%BB%B6.png; before the fix the test fails with ERR_INVALID_CHAR.
  • The proxy-capture site shares the same sanitizer and code path as the egress proxy, which has a direct regression test in fix(secrets): preserve protected egress for non-ASCII attachment filenames #156166. A real-socket integration test cannot reproduce the crash here because Node's HTTP parser decodes received header bytes as Latin-1 (always writable); the non-Latin-1 values arise from in-process header construction, which the unit tests exercise.
  • tsgo core typecheck, oxlint on changed files, and git diff --check all pass. 202 existing image-route consumer tests pass unchanged.

Scope boundary

This change touches only the two additional write sites and the new shared helper. The egress-proxy fix remains in #156166; no duplication of that logic is introduced here.

AI-assisted contribution

This change was authored with AI assistance.

The secret egress proxy crash (issue openclaw#154685, PR openclaw#156166) came from
forwarding an upstream Content-Disposition with a non-Latin-1 filename
into writeHead. The same unguarded pattern exists at two other response
boundaries that forward or build header values from dynamic data:

- src/proxy-capture/proxy-server.ts forwards upstream response headers
  verbatim into writeHead, same ERR_INVALID_CHAR crash risk.
- src/gateway/http-image-response.ts builds an attachment filename
  Content-Disposition and setHeader's it directly; this was the crash
  point the issue notes surfaced on 2026.9.4 before the code path moved
  to the egress proxy.

Reuse a shared helper (src/shared/http-header-sanitize.ts) that makes
header values writable: Content-Disposition filenames get an ASCII
fallback plus RFC 5987 filename*=UTF-8'' and other non-Latin-1 values
are scrubbed, matching the encoding the Gateway's media responses
already use. Covers both setHeader and writeHead.

Complements openclaw#156166; related to openclaw#154685.
@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

The PR sanitizes response headers in the debug capture proxy and encodes Unicode attachment filenames in Gateway image responses.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The useful repair remains incomplete, with unchanged correctness and security findings and only isolated test evidence.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) Security review found an item that needs attention.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 10 items remain

Useful work remains outside the merged egress-proxy fix, but all three earlier findings remain unresolved and the changed production paths lack real behavior proof.

Priority: P2
Reviewed head: 7d17e9b408770609efdc93dd22418db733ac483b

Before merge

  • Add real behavior proof - The captured body exercises sanitizer functions and a standalone image ServerResponse, not after-fix forwarding through startDebugProxyServer with a real upstream and client. Add redacted terminal output or logs demonstrating the header-order trigger, preserved filenames, unchanged legal headers, and continued serving; screenshots or recordings count when they show these diagnostics. Remove credentials, private endpoints, IP addresses, phone numbers, and user data. Update the PR body to trigger review, or ask a maintainer for @clawsweeper re-review. No stored-data contract changes.
  • [P1] Handle received filename bytes before the Latin-1 fast path (P1) - Node exposes received UTF-8 header bytes as Latin-1 characters, so this fast path returns the problematic Content-Disposition unchanged. When Content-Length precedes it, Node converts the value to a Buffer and subsequently validates its UTF-8 coercion, still throwing ERR_INVALID_CHAR outside the proxy’s error handling. This leaves the central proxy repair ineffective. Handle received non-ASCII disposition bytes before returning, following the established egress adapter.
  • [P1] Preserve legal tabs in forwarded header values (P1) - HTAB is a legal header character, but the introduced regex replaces it in every upstream response header. For example, Content-Security-Policy: default-src\t'none' becomes default-src_'none', causing the browser to ignore that directive. Preserve legal whitespace and leave unrelated headers byte-for-byte unchanged rather than applying this replacement globally.
  • [P1] Reuse the existing filename serializer (P1) - The image writer now constructs a quoted header and reparses it through a second filename encoder, although buildAssistantMediaContentDisposition already handles ASCII fallback, extended encoding, surrogate repair, and bounded filenames. The duplicate path omits the existing length bound and creates competing filename policies. Serialize the filename directly through the existing owner, preserving attachment disposition, and retain only the distinct received-header adaptation needed by the proxy.
  • Resolve security concern: Legal CSP whitespace is replaced with punctuation - The debug proxy applies a tab-excluding replacement to every response header. A valid tab between a CSP directive and its value becomes an underscore, potentially disabling the browser restriction.
  • Resolve merge risk - Merging the broad sanitizer can weaken upstream browser security policies by replacing legal tab separators with underscores.
  • Complete next step - Correct received-byte handling, preserve legal forwarded headers, and reuse the existing filename serializer.
  • Improve patch quality - Handle received filename bytes and preserve legal upstream header values.
  • Improve patch quality - Reuse the existing generated-filename serializer instead of maintaining parallel encoding policy.
  • Improve patch quality - Supply after-fix real debug-proxy transport evidence for the exact header-order trigger and unchanged security headers.

Findings

  • [P1] [P1] Handle received filename bytes before the Latin-1 fast path — src/shared/http-header-sanitize.ts:89-94
  • [P1] [P1] Preserve legal tabs in forwarded header values — src/shared/http-header-sanitize.ts:14
  • [P1] [P1] Reuse the existing filename serializer — src/gateway/http-image-response.ts:98-100
  • [medium] Legal CSP whitespace is replaced with punctuation — src/shared/http-header-sanitize.ts:14
Agent review details

How this fits together

The debug capture proxy forwards upstream HTTP responses while recording diagnostic traffic. Gateway image routes separately construct response headers for authenticated image downloads; both paths ultimately write headers through Node’s HTTP server.

flowchart TD
  A[Upstream HTTP response] --> B[Debug capture proxy]
  C[Authenticated image request] --> D[Gateway image response]
  B --> E[Response header sanitization]
  D --> E
  E --> F[Node HTTP header validation]
  F --> G[Client response]
Loading

Technical review

Best possible solution:

Use one maintained filename serializer for generated responses and a narrowly scoped received-header adapter that preserves legal upstream headers.

Do we have a high-confidence way to reproduce the issue?

Yes, source establishes the debug-proxy trigger: raw UTF-8 filename bytes following a positive Content-Length pass this sanitizer but fail Node’s later validation. No runtime reproduction was executed, and the inspected image-route callers currently use fixed ASCII names.

Is this the best way to solve the issue?

No. The proposed fast path misses received-byte behavior, mutates legal headers, and duplicates an existing filename serializer; a narrow forwarding adapter plus reuse of the existing serializer is safer.

Full review comments:

  • [P1] [P1] Handle received filename bytes before the Latin-1 fast path — src/shared/http-header-sanitize.ts:89-94
    Node exposes received UTF-8 header bytes as Latin-1 characters, so this fast path returns the problematic Content-Disposition unchanged. When Content-Length precedes it, Node converts the value to a Buffer and subsequently validates its UTF-8 coercion, still throwing ERR_INVALID_CHAR outside the proxy’s error handling. This leaves the central proxy repair ineffective. Handle received non-ASCII disposition bytes before returning, following the established egress adapter.
    Confidence: 0.99
  • [P1] [P1] Preserve legal tabs in forwarded header values — src/shared/http-header-sanitize.ts:14
    HTAB is a legal header character, but the introduced regex replaces it in every upstream response header. For example, Content-Security-Policy: default-src\t'none' becomes default-src_'none', causing the browser to ignore that directive. Preserve legal whitespace and leave unrelated headers byte-for-byte unchanged rather than applying this replacement globally.
    Confidence: 0.99
  • [P1] [P1] Reuse the existing filename serializer — src/gateway/http-image-response.ts:98-100
    The image writer now constructs a quoted header and reparses it through a second filename encoder, although buildAssistantMediaContentDisposition already handles ASCII fallback, extended encoding, surrogate repair, and bounded filenames. The duplicate path omits the existing length bound and creates competing filename policies. Serialize the filename directly through the existing owner, preserving attachment disposition, and retain only the distinct received-header adaptation needed by the proxy.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 218501fc6957.

Merge-risk options

Maintainer options:

  1. Preserve upstream security headers (recommended)
    Restrict forwarding normalization to the affected Content-Disposition contract and demonstrate that legal CSP whitespace reaches the client unchanged.

Security

Needs attention: The introduced sanitizer can weaken forwarded CSP directives; no dependency or supply-chain changes were introduced.

Evidence

Security concerns:

  • [medium] Legal CSP whitespace is replaced with punctuation — src/shared/http-header-sanitize.ts:14
    The debug proxy applies a tab-excluding replacement to every response header. A valid tab between a CSP directive and its value becomes an underscore, potentially disabling the browser restriction.
    Confidence: 0.99

What I checked:

PR surface

Source +171, Tests +162. Total +333 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 173 2 +171
Tests 2 162 0 +162
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 335 2 +333

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded response-boundary repair; the reported primary protected-egress outage already has a merged fix.
  • merge-risk: 🚨 security-boundary: The introduced all-header replacement can invalidate a valid upstream Content-Security-Policy directive.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-23T05:03:18.990Z sha 7d17e9b :: needs real behavior proof before merge. :: [P1] [P1] Handle received filename bytes before the Latin-1 fast path | [P1] [P1] Preserve legal tabs in forwarded header values | [P1] [P1] Reuse the existing filename serializer

Reviewed October 7, 2026, 8:10 PM ET / October 8, 2026, 00:10 UTC (Revision 2).

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant