Skip to content

fix(secrets): preserve protected egress for non-ASCII attachment filenames - #156166

Merged
obviyus merged 6 commits into
openclaw:mainfrom
siri1410:fix/egress-proxy-non-ascii-filename
Sep 23, 2026
Merged

obviyus merged 6 commits into
openclaw:mainfrom
siri1410:fix/egress-proxy-non-ascii-filename

Conversation

@siri1410

@siri1410 siri1410 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Closes #154685

What Problem This Solves

Fixes: downloading a forwarded attachment with a non-ASCII filename stops the secret egress proxy Worker and leaves protected egress unavailable until the Gateway restarts. Before #156354 moved forwarding off the main thread, the same defect crashed the Gateway itself.

User Impact

User impact: attachments with non-ASCII filenames download with their original name preserved in filename*, and one bad upstream response head no longer stops protected egress. A rejected ordinary response gets a request-local 502 (or a closed connection for an already-bodyless response), while the proxy keeps serving.

Why This Change Was Made

The secret egress proxy passes upstream response headers straight into writeHead. Node exposes received header bytes as latin1 strings and forwards them byte-for-byte, with one exception. Once Content-Length is stored, Node revalidates Content-Disposition as UTF-8, and a raw UTF-8 filename throws ERR_INVALID_CHAR. The throw happens in the upstream response callback, outside any try. On current main it terminates the proxy Worker: the Gateway remains live, but protected egress stops until restart.

This change:

  • Rewrites only Content-Disposition, and only when it contains non-ASCII bytes. The legacy filename= becomes an ASCII fallback. An upstream filename* is kept verbatim; otherwise one is generated as filename*=UTF-8''… from the decoded name, so the original name survives. Other ASCII parameters (for example size=) are kept.
  • Leaves every other header untouched. I checked this on Node 26.8.1: after Content-Length, the same raw UTF-8 bytes in ETag, Link, Content-Type, or a custom header forward fine, and only Content-Disposition throws. So opaque values such as ETag still work with If-Match/If-None-Match.
  • Contains any remaining writeHead failure to the one request. The upstream response is destroyed and the client gets a 502. For 1xx/204/304 heads, where Node may already have marked the response bodyless, the socket is closed instead of framing a 502 body.
  • Applies the same Content-Disposition handling to the forwarded 101 upgrade head.

There is no global ServerResponse patch, and request-side behavior is unchanged. #155121 took a similar approach and was closed by its author while awaiting review; this is an independent implementation that doesn't touch Node's private _hasBody flag.

Security note: this touches src/secrets/egress-proxy/**, so it needs /allow-security-sensitive-change from a maintainer.

Evidence

Real proxy and real upstream transport. New test in proxy-server.test.ts: forwards a CJK attachment filename from a real upstream and keeps serving. It starts the actual startSecretEgressProxyServer, sends requests through an authenticated CONNECT tunnel with TLS to the proxy, and forwards them over real HTTPS to a real TLS upstream. The upstream writes raw bytes to its socket, because Node's own server cannot emit this header order. In sequence:

  1. Content-Length: 4 followed by Content-Disposition: attachment; filename="附件_2026-09-21.log" as raw UTF-8. The client receives 200, body file, and content-disposition: attachment; filename="___2026-09-21.log"; filename*=UTF-8''%E9%99%84%E4%BB%B6_2026-09-21.log.
  2. A head that Node rejects mid-write (Trailer on a non-chunked response). The client receives 502 Secret egress proxy could not forward the upstream response.
  3. A normal request on the same proxy returns 200 ok, so the proxy is still serving. No uncaughtException is raised at any point.

On main's proxy-forward.ts, step 1 gets no HTTP response at all and the test fails.

Focused tests.

  • proxy-forward.test.ts loopback tests, with the upstream response emitted on a later tick as the real client does:
    • A CJK filename after Content-Length. Without the fix this fails with the production error, TypeError: Invalid character in header content ["content-disposition"].
    • A real mid-writeHead rejection returns a 502 on a 200 head. On a 304 head the connection closes with no status line; with an unconditional 502 instead, the client would get a 502 head and then an aborted body, and the test catches that.
  • response-headers.test.ts covers:
    • non-Content-Disposition headers, including a non-ASCII ETag, forwarded unchanged;
    • an upstream filename* and size= kept;
    • received UTF-8 bytes vs. decoded characters, and quoted vs. unquoted filenames;
    • non-UTF-8 Latin-1 input;
    • unparseable values.
✓ proxy-server.test.ts > secret egress proxy > forwards a CJK attachment filename from a real upstream and keeps serving 240ms
✓ proxy-forward.test.ts > secret egress forwarded response heads > forwards a CJK attachment filename that follows Content-Length 2ms
✓ proxy-forward.test.ts > secret egress forwarded response heads > answers 502 instead of crashing when the forwarded head is rejected 1ms
✓ proxy-forward.test.ts > secret egress forwarded response heads > answers 502 after Node rejects a forwarded head mid-write 1ms
✓ proxy-forward.test.ts > secret egress forwarded response heads > closes a rejected bodyless head instead of framing a 502 body 1ms
✓ response-headers.test.ts > toForwardableResponseHeaders > forwards non-ASCII bytes in other headers unchanged 0ms
✓ response-headers.test.ts > toForwardableResponseHeaders > keeps an upstream filename* and other ASCII parameters 1ms
… (6 more response-headers cases)
Test Files  6 passed (6)
Tests  115 passed (115)
Duration  6.70s

Checks.

  • pnpm check:changed passed on the first revision. For this revision:
    • pnpm tsgo:core and the agents-tools core test shard typecheck (which includes src/secrets/** tests) are clean.
    • The gate's scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json and oxfmt --check are clean.
  • CI note: the two failing Node shards on the first revision were unrelated to this change. They were src/gateway/session-lifecycle-state.persistence.test.ts and src/gateway/server.sessions.abort-authorization.test.ts ("Matcher did not succeed in time"), and both pass locally on this branch.

Maintainer verification

At head 2ec35def5c3fc9cb3ca4c2c9241491880b01ed49, all three focused files passed (58 tests). Each file was run separately with OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs src/secrets/egress-proxy/<file>; measured command wall time, including startup:

File Wall time
proxy-server.test.ts 7.14s
proxy-forward.test.ts 1.39s
response-headers.test.ts 1.32s

Negative control: replacing only proxy-forward.ts with merge-base 86d353b7485df33811774618af23252555e19f62 made the real authenticated CONNECT/TLS CJK-attachment test fail: no HTTP status was received (NaN, expected 200). Restoring the candidate made the complete server suite pass, including the attachment, rejected-head 502, subsequent 200, and secret destination/authentication checks.

Available CI timing: initial checks-node-compact-large-10 job ran 05:12:53–05:19:20 UTC (6m27s), with its failing owner-claim shard reporting 327.06s. The authorized failed-job rerun still failed that same unrelated owner-claim case. Current main was merged without rebasing the contributor commits; new CI is required.

Built Gateway end-to-end proof

At candidate 1261c0851e317ca70a2286f398aa05e1d01e78fe (main 0864fb6f86c9a5080f23b3125dba29d0db38427e merged, including #156354), pnpm openclaw gateway run rebuilt the CLI and started an isolated Gateway with secrets.egressProxy.enabled=true. A normal pnpm openclaw agent turn used the supported OpenClaw runtime and a synthetic local Chat Completions provider to issue an actual Gateway-hosted exec command. Curl used the process-owned authenticated proxy and TLS to download a raw-byte HTTPS attachment response with Content-Length preceding the UTF-8 Content-Disposition. Both sides used fresh isolated state.

  • Candidate: the exec tool result contained 200 OK, body file, ASCII filename="___2026-09-21.log" plus RFC 6266 filename*=UTF-8''%E9%99%84%E4%BB%B6_2026-09-21.log. A second request returned 200 OK / ok, and the agent turn completed through the still-running Gateway.
  • Current-main negative control: rebuilt the same checkout with only proxy-forward.ts replaced by its 0864fb6f86c version (the only changed production caller; the candidate helper was then unused). The identical agent flow received curl error 52 / empty reply for the attachment, then curl error 7 / connection refused for the next request. Gateway logs reported secret egress proxy Worker stopped; restart the Gateway to restore protected egress. /healthz still returned {"ok":true,"status":"live"}: perf(secrets): move egress forwarding off the main thread #156354 contains the process crash, but does not fix attachment delivery or the protected-egress outage. Candidate source was restored afterward.
  • The HTTPS fixture used localhost port 19443 because binding privileged port 443 was denied, and a certificate signed by the isolated Gateway's process CA. This proves the built Gateway/proxy/exec path, not Feishu delivery or general non-443 compatibility. No product callback or transport was mocked; only the model and upstream service responses were synthetic.

…SCII filename

The secret egress proxy passed upstream response headers straight into
writeHead. Node exposes received header bytes as latin1 strings, and once
Content-Length is stored a later non-Latin-1 Content-Disposition throws
ERR_INVALID_CHAR. That throw happened in the upstream response callback,
outside any try block, so it exited the Gateway and systemd restarted it
into the same attachment.

Forward only ASCII header values: Content-Disposition filenames become an
ASCII filename= fallback plus RFC 6266 filename*=UTF-8'' so the original
name survives, and other non-ASCII characters are replaced. Any remaining
writeHead failure now stays on that request as a 502 (or a closed socket
for bodyless 1xx/204/304 heads) instead of crashing the process.

Closes openclaw#154685
@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ Maintainer security changes approved

A maintainer approved this revision with an explicit security approval comment.

A later push requires a fresh approval comment for an external contributor's PR.

@clawsweeper clawsweeper Bot added P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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 Sep 23, 2026
@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 23, 2026, 8:55 AM ET / 12:55 UTC (Revision 7).

ClawSweeper review

What this changes

The PR preserves international attachment filenames through the secret egress proxy and contains rejected response headers to the affected request.

Merge readiness

✅ Ready for maintainer review

The fix remains necessary on current main. Prior findings are resolved, real behavior proof is sufficient, and security approval now covers the reviewed head; no blocking defect was found.

Priority: P0
Reviewed head: 1261c0851e317ca70a2286f398aa05e1d01e78fe

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused repair with strong production-path evidence, a failing baseline control, compatibility coverage, and no remaining review findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Recorded output from the reviewed built Gateway's agent/exec/curl path demonstrates successful attachment forwarding and continued service through real CONNECT/TLS transport; the production-server fault scenario additionally demonstrates request-local rejection and recovery. No stored-data contract changes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Recorded output from the reviewed built Gateway's agent/exec/curl path demonstrates successful attachment forwarding and continued service through real CONNECT/TLS transport; the production-server fault scenario additionally demonstrates request-local rejection and recovery. No stored-data contract changes.
Evidence reviewed 10 items Introduced change: The pinned base-to-head diff changes response-header normalization, ordinary response-head failure containment, and focused regression coverage. It does not change grants, destination authorization, configuration, dependencies, or persistent storage.
Current main still needs the fix: Fetched main still passes upstream headers directly to writeHead without containing exceptions in the asynchronous response callback. Worker isolation limits the failure to protected egress; it does not repair attachment forwarding.
Latest release remains affected: The supplied latest release, v2026.9.5, also contains the unguarded response-header forwarding call, consistent with the linked report's crash trace.
Findings None None.
Security None None.

How this fits together

The secret egress proxy forwards HTTPS requests from Gateway-hosted commands while protecting destination-bound credentials. Its response forwarding determines whether downloaded attachments reach those commands and whether the proxy remains available.

flowchart LR
  A[Gateway-hosted command] --> B[Authenticated secret proxy]
  B --> C[HTTPS upstream]
  C --> D[Response header normalization]
  D --> E{Header accepted?}
  E -->|Yes| F[Stream attachment to command]
  E -->|No| G[Request-local error or disconnect]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +108, Tests +274. Total +382 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 2 110 2 +108
Tests 3 278 4 +274
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 388 6 +382

Review metrics

Metric Value Why it matters
Production versus test growth production +108 net lines; tests +274 net lines Production growth implements the missing response adapter and exception containment; tests cover encoding compatibility and transport recovery.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #154685
Summary: This PR addresses the reported egress forwarding failure; related response sites and Worker isolation are distinct work.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep filename normalization and request-local failure containment at the egress response boundary while preserving unrelated header bytes and existing authorization.

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

Yes: raw UTF-8 Content-Disposition following Content-Length reaches an unguarded Node writeHead on current main. Source inspection and the supplied production-path negative control establish the trigger; this review did not execute it.

Is this the best way to solve the issue?

Yes: the repair belongs at the forwarding boundary, preserves unrelated headers and upstream filename*, and avoids modifying Node's private response state.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P0: The reported current release can enter a Gateway crash loop; current main contains the process crash but still loses protected egress until restart.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Recorded output from the reviewed built Gateway's agent/exec/curl path demonstrates successful attachment forwarding and continued service through real CONNECT/TLS transport; the production-server fault scenario additionally demonstrates request-local rejection and recovery. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded output from the reviewed built Gateway's agent/exec/curl path demonstrates successful attachment forwarding and continued service through real CONNECT/TLS transport; the production-server fault scenario additionally demonstrates request-local rejection and recovery. No stored-data contract changes.

Evidence

What I checked:

  • Introduced change: The pinned base-to-head diff changes response-header normalization, ordinary response-head failure containment, and focused regression coverage. It does not change grants, destination authorization, configuration, dependencies, or persistent storage. (src/secrets/egress-proxy/proxy-forward.ts:168, 1261c0851e31)
  • Current main still needs the fix: Fetched main still passes upstream headers directly to writeHead without containing exceptions in the asynchronous response callback. Worker isolation limits the failure to protected egress; it does not repair attachment forwarding. (src/secrets/egress-proxy/proxy-forward.ts:165, bb8aea886bfd)
  • Latest release remains affected: The supplied latest release, v2026.9.5, also contains the unguarded response-header forwarding call, consistent with the linked report's crash trace. (src/secrets/egress-proxy/proxy-forward.ts, ec9c1a13db89)
  • Verified Node response-header contract: The patch directly uses Node HTTP response APIs, and its regression depends on their behavior. Node v26.8.1 converts Content-Disposition through a Latin-1 Buffer when Content-Length is present before validating the value; it also rejects Trailer on non-chunked responses. The tag resolves to the recorded Node commit. (lib/_http_outgoing.js, 7be6d3af31a6)
  • Prior findings resolved: The helper rewrites only Content-Disposition, preserves an existing ASCII filename*, and retains other ASCII parameters. Tests explicitly protect opaque unrelated headers and authoritative extended filenames. The helper is unchanged from the previously reviewed corrected revision. (src/secrets/egress-proxy/response-headers.ts:15, 1261c0851e31)
  • Real production-path proof: The supplied body snapshot, sourceRevision aeb1f0311dd74f64a0cddc1f7058d8fd5ba7cae71c9fc4970f943a95926fff6b, records a built Gateway agent/exec/curl flow at the reviewed head: authenticated CONNECT and real TLS forwarding returned the encoded filename, 200/file, then 200/ok. Replacing the production caller with pinned main produced an empty reply, subsequent connection refusal, and the Worker-stopped diagnostic. The inspected server regression separately exercises a rejected head, request-local 502, and subsequent successful request. Synthetic model/origin responses do not replace the production transport. This review did not execute repository code. (src/secrets/egress-proxy/proxy-server.test.ts:365, 1261c0851e31)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (6 earlier review cycles)
  • reviewed 2026-09-23T04:20:37.578Z sha d247078 :: needs real behavior proof before merge. :: [P1] Preserve valid bytes in unrelated response headers | [P2] Preserve an existing authoritative filename*
  • reviewed 2026-09-23T05:07:12.443Z sha 2ec35de :: needs changes before merge. :: none
  • reviewed 2026-09-23T06:24:01.036Z sha 2ec35de :: needs maintainer review before merge. :: none
  • reviewed 2026-09-23T07:24:27.153Z sha 2e1fb4c :: needs changes before merge. :: none
  • reviewed 2026-09-23T12:29:18.761Z sha 1261c08 :: blocked before merge. :: none
  • reviewed 2026-09-23T12:35:43.075Z sha 1261c08 :: blocked before merge. :: none

@YangManBOBO

Copy link
Copy Markdown
Contributor

Thanks for the thorough egress-proxy fix — that is the primary crash site from #154685 and the loopback + containment coverage is solid.

While validating this independently I found the same unguarded write pattern in two other response paths that this PR does not cover:

  • src/proxy-capture/proxy-server.ts (~line 333): res.writeHead(upstreamRes.statusCode ?? 502, upstreamRes.headers) forwards the upstream response headers verbatim, same ERR_INVALID_CHAR risk.
  • src/gateway/http-image-response.ts (sendHttpImageResponse): builds attachment; filename=${params.filename} and calls setHeader directly — this is the crash point the issue notes surfaced on 2026.9.4 before moving to the egress proxy.

I have an independent, complementary implementation of the same RFC 6266/RFC 5987 approach (filename= ASCII fallback + filename*=UTF-8''…, other non-Latin-1 values scrubbed) as a shared helper src/shared/http-header-sanitize.ts, wired into all three sites. It lives on fix/forwarded-header-latin1-sanitize (commit 7fbfee85878) in my fork, with unit tests plus regression tests at the egress and image-response write sites (both red before the fix, green after).

Happy to either (a) open a small separate PR for the two additional sites so this one can land on its own, or (b) fold the two sites + shared helper into this PR if you prefer one change. Let me know which you'd like — no intention to race your fix.

@YangManBOBO

Copy link
Copy Markdown
Contributor

Follow-up: I've opened a small separate PR for the two additional write sites this one does not cover — #156192 (proxy-capture proxy-server writeHead + gateway http-image-response setHeader, reusing the same shared RFC 5987 sanitizer). It is scoped to those sites only, so it should not conflict with this PR. Happy to rebase or adjust if you prefer a different shape.

…ilename*

Node forwards other latin1 header values byte-for-byte after Content-Length;
only Content-Disposition is revalidated as UTF-8. Leave every other header
untouched so opaque values such as ETag keep working with If-Match and
If-None-Match. When rewriting Content-Disposition, keep an existing ASCII
filename* verbatim and preserve the other ASCII parameters.

Add an end-to-end test through the real proxy and a real TLS upstream that
sends Content-Length before a UTF-8 filename, then a rejected head, then a
normal request.
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 23, 2026
@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

/allow-security-sensitive-change

@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus obviyus changed the title fix(gateway): stop crash loop when a forwarded attachment has a non-ASCII filename fix(secrets): preserve protected egress for non-ASCII attachment filenames Sep 23, 2026
@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

/allow-security-sensitive-change

@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 23, 2026
@obviyus
obviyus merged commit b6b4524 into openclaw:main Sep 23, 2026
204 of 206 checks passed
@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

Landed in b6b4524. Thanks @siri1410 for the fix! Verified through a built Gateway and real agent/exec → CONNECT/TLS forwarding: current main lost the attachment and stopped protected egress, while this revision preserved the filename and delivered both the attachment and the next request. All 62 focused tests passed; required CI and exact-head hosted review were green.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 24, 2026
…names (openclaw#156166)

Closes openclaw#154685

## What Problem This Solves

Fixes: downloading a forwarded attachment with a non-ASCII filename stops the secret egress proxy Worker and leaves protected egress unavailable until the Gateway restarts. Before openclaw#156354 moved forwarding off the main thread, the same defect crashed the Gateway itself.

## User Impact

User impact: attachments with non-ASCII filenames download with their original name preserved in `filename*`, and one bad upstream response head no longer stops protected egress. A rejected ordinary response gets a request-local 502 (or a closed connection for an already-bodyless response), while the proxy keeps serving.

## Why This Change Was Made

The secret egress proxy passes upstream response headers straight into `writeHead`. Node exposes received header bytes as latin1 strings and forwards them byte-for-byte, with one exception. Once `Content-Length` is stored, Node revalidates `Content-Disposition` as UTF-8, and a raw UTF-8 filename throws `ERR_INVALID_CHAR`. The throw happens in the upstream response callback, outside any `try`. On current main it terminates the proxy Worker: the Gateway remains live, but protected egress stops until restart.

This change:

- **Rewrites only `Content-Disposition`, and only when it contains non-ASCII bytes.** The legacy `filename=` becomes an ASCII fallback. An upstream `filename*` is kept verbatim; otherwise one is generated as `filename*=UTF-8''…` from the decoded name, so the original name survives. Other ASCII parameters (for example `size=`) are kept.
- **Leaves every other header untouched.** I checked this on Node 26.8.1: after `Content-Length`, the same raw UTF-8 bytes in `ETag`, `Link`, `Content-Type`, or a custom header forward fine, and only `Content-Disposition` throws. So opaque values such as `ETag` still work with `If-Match`/`If-None-Match`.
- **Contains any remaining `writeHead` failure to the one request.** The upstream response is destroyed and the client gets a 502. For 1xx/204/304 heads, where Node may already have marked the response bodyless, the socket is closed instead of framing a 502 body.
- Applies the same `Content-Disposition` handling to the forwarded `101` upgrade head.

There is no global `ServerResponse` patch, and request-side behavior is unchanged. openclaw#155121 took a similar approach and was closed by its author while awaiting review; this is an independent implementation that doesn't touch Node's private `_hasBody` flag.

Security note: this touches `src/secrets/egress-proxy/**`, so it needs `/allow-security-sensitive-change` from a maintainer.

## Evidence

**Real proxy and real upstream transport.** New test in `proxy-server.test.ts`: `forwards a CJK attachment filename from a real upstream and keeps serving`. It starts the actual `startSecretEgressProxyServer`, sends requests through an authenticated CONNECT tunnel with TLS to the proxy, and forwards them over real HTTPS to a real TLS upstream. The upstream writes raw bytes to its socket, because Node's own server cannot emit this header order. In sequence:

1. `Content-Length: 4` followed by `Content-Disposition: attachment; filename="附件_2026-09-21.log"` as raw UTF-8. The client receives `200`, body `file`, and `content-disposition: attachment; filename="___2026-09-21.log"; filename*=UTF-8''%E9%99%84%E4%BB%B6_2026-09-21.log`.
2. A head that Node rejects mid-write (`Trailer` on a non-chunked response). The client receives `502 Secret egress proxy could not forward the upstream response.`
3. A normal request on the same proxy returns `200 ok`, so the proxy is still serving. No `uncaughtException` is raised at any point.

On `main`'s `proxy-forward.ts`, step 1 gets no HTTP response at all and the test fails.

**Focused tests.**
- `proxy-forward.test.ts` loopback tests, with the upstream response emitted on a later tick as the real client does:
  - A CJK filename after `Content-Length`. Without the fix this fails with the production error, `TypeError: Invalid character in header content ["content-disposition"]`.
  - A real mid-`writeHead` rejection returns a `502` on a 200 head. On a 304 head the connection closes with no status line; with an unconditional 502 instead, the client would get a `502` head and then an aborted body, and the test catches that.
- `response-headers.test.ts` covers:
  - non-`Content-Disposition` headers, including a non-ASCII `ETag`, forwarded unchanged;
  - an upstream `filename*` and `size=` kept;
  - received UTF-8 bytes vs. decoded characters, and quoted vs. unquoted filenames;
  - non-UTF-8 Latin-1 input;
  - unparseable values.

```
✓ proxy-server.test.ts > secret egress proxy > forwards a CJK attachment filename from a real upstream and keeps serving 240ms
✓ proxy-forward.test.ts > secret egress forwarded response heads > forwards a CJK attachment filename that follows Content-Length 2ms
✓ proxy-forward.test.ts > secret egress forwarded response heads > answers 502 instead of crashing when the forwarded head is rejected 1ms
✓ proxy-forward.test.ts > secret egress forwarded response heads > answers 502 after Node rejects a forwarded head mid-write 1ms
✓ proxy-forward.test.ts > secret egress forwarded response heads > closes a rejected bodyless head instead of framing a 502 body 1ms
✓ response-headers.test.ts > toForwardableResponseHeaders > forwards non-ASCII bytes in other headers unchanged 0ms
✓ response-headers.test.ts > toForwardableResponseHeaders > keeps an upstream filename* and other ASCII parameters 1ms
… (6 more response-headers cases)
Test Files  6 passed (6)
Tests  115 passed (115)
Duration  6.70s
```

**Checks.**
- `pnpm check:changed` passed on the first revision. For this revision:
  - `pnpm tsgo:core` and the `agents-tools` core test shard typecheck (which includes `src/secrets/**` tests) are clean.
  - The gate's `scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json` and `oxfmt --check` are clean.
- CI note: the two failing Node shards on the first revision were unrelated to this change. They were `src/gateway/session-lifecycle-state.persistence.test.ts` and `src/gateway/server.sessions.abort-authorization.test.ts` ("Matcher did not succeed in time"), and both pass locally on this branch.

## Maintainer verification

At head `2ec35def5c3fc9cb3ca4c2c9241491880b01ed49`, all three focused files passed (58 tests). Each file was run separately with `OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs src/secrets/egress-proxy/<file>`; measured command wall time, including startup:

| File | Wall time |
| --- | ---: |
| `proxy-server.test.ts` | 7.14s |
| `proxy-forward.test.ts` | 1.39s |
| `response-headers.test.ts` | 1.32s |

Negative control: replacing only `proxy-forward.ts` with merge-base `0bad6eeb100097e0822e1a5d49c236824d0ee8fe` made the real authenticated CONNECT/TLS CJK-attachment test fail: no HTTP status was received (`NaN`, expected `200`). Restoring the candidate made the complete server suite pass, including the attachment, rejected-head 502, subsequent 200, and secret destination/authentication checks.

Available CI timing: initial `checks-node-compact-large-10` job ran 05:12:53–05:19:20 UTC (6m27s), with its failing owner-claim shard reporting 327.06s. The authorized failed-job rerun still failed that same unrelated owner-claim case. Current main was merged without rebasing the contributor commits; new CI is required.

### Built Gateway end-to-end proof

At candidate `1261c0851e317ca70a2286f398aa05e1d01e78fe` (main `b638129b2461184c916d3318e673fae2af9fe8b3` merged, including openclaw#156354), `pnpm openclaw gateway run` rebuilt the CLI and started an isolated Gateway with `secrets.egressProxy.enabled=true`. A normal `pnpm openclaw agent` turn used the supported OpenClaw runtime and a synthetic local Chat Completions provider to issue an actual Gateway-hosted `exec` command. Curl used the process-owned authenticated proxy and TLS to download a raw-byte HTTPS attachment response with `Content-Length` preceding the UTF-8 `Content-Disposition`. Both sides used fresh isolated state.

- Candidate: the exec tool result contained `200 OK`, body `file`, ASCII `filename="___2026-09-21.log"` plus RFC 6266 `filename*=UTF-8''%E9%99%84%E4%BB%B6_2026-09-21.log`. A second request returned `200 OK` / `ok`, and the agent turn completed through the still-running Gateway.
- Current-main negative control: rebuilt the same checkout with only `proxy-forward.ts` replaced by its `b638129b246` version (the only changed production caller; the candidate helper was then unused). The identical agent flow received curl error 52 / empty reply for the attachment, then curl error 7 / connection refused for the next request. Gateway logs reported `secret egress proxy Worker stopped; restart the Gateway to restore protected egress`. `/healthz` still returned `{"ok":true,"status":"live"}`: openclaw#156354 contains the process crash, but does not fix attachment delivery or the protected-egress outage. Candidate source was restored afterward.
- The HTTPS fixture used localhost port 19443 because binding privileged port 443 was denied, and a certificate signed by the isolated Gateway's process CA. This proves the built Gateway/proxy/exec path, not Feishu delivery or general non-443 compatibility. No product callback or transport was mocked; only the model and upstream service responses were synthetic.

Co-authored-by: Ayaan Zaidi <[email protected]>
@roboclaw-bot roboclaw-bot mentioned this pull request Sep 24, 2026
2 of 8 tasks
roboclaw-bot added a commit that referenced this pull request Sep 26, 2026
Backport #156166: b6b4524
Selected backport #156207: 741a1c8

Retain request-local response-head failure handling and use the shared
stream writer for Fleet output. Remove the retired Fleet-local owner.
The unrelated Crabbox protected-credential feature is not included.

Targeted transport/registered-handler proof and independent review pass.
Full release qualification remains separate.

Co-authored-by: siri1410 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vyctorbrzezowski <[email protected]>
Co-authored-by: steipete <[email protected]>
Co-authored-by: jalehman <[email protected]>
steipete added a commit that referenced this pull request Sep 28, 2026
…ed PR (#160305)

The release-notes verifier now records exact GraphQL NOT_FOUND results and omits a reference only when it appears solely as contextual commit-body text and lies below the highest resolved number, reporting it as manifest unavailableReferences without credit. Every other unresolved reference stays fatal. Unblocks 2026.9.7 notes regeneration (#155121 mentioned in #156166).
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 29, 2026
…ed PR (openclaw#160305)

The release-notes verifier now records exact GraphQL NOT_FOUND results and omits a reference only when it appears solely as contextual commit-body text and lies below the highest resolved number, reporting it as manifest unavailableReferences without credit. Every other unresolved reference stays fatal. Unblocks 2026.9.7 notes regeneration (openclaw#155121 mentioned in openclaw#156166).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. security-sensitive-changed size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Non-ASCII (CJK) filename in a forwarded response header crashes the Gateway — uncaught TypeError [ERR_INVALID_CHAR] in writeHead → crash loop

3 participants