Skip to content

fix(plugin-sdk): bound Copilot token exchange JSON response reads - #97579

Merged
sallyom merged 3 commits into
openclaw:mainfrom
hugenshen:fix/bound-copilot-token-json-responses
Jul 6, 2026
Merged

sallyom merged 3 commits into
openclaw:mainfrom
hugenshen:fix/bound-copilot-token-json-responses

Conversation

@hugenshen

@hugenshen hugenshen commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where the GitHub Copilot API token exchange success response
was read with an unbounded await res.json(), meaning a misbehaving,
compromised, or proxied Copilot token endpoint could stream an arbitrarily
large JSON body into the Node.js heap before parsing began — causing memory
pressure or OOM during openclaw onboard and every Copilot auth refresh.

The failure path at provider-auth.ts:309 already calls
cancelUnreadResponseBody(res) to release the stream, but the success path
immediately below had no size cap — a clear asymmetric gap.

This is a SDK-level path (src/plugin-sdk/): every consumer of
resolveCopilotApiToken (agent startup, onboarding, live Copilot inference
sessions) is affected. Sibling paths in the same campaign that have already
been fixed include github-copilot/usage.ts and github-copilot/embeddings.ts
(merged #96607), and github-copilot/login.ts device-flow exchange (merged
#97583).

Why This Change Was Made

readProviderJsonResponse (from ../agents/provider-http-errors.js, the same
module re-exported via openclaw/plugin-sdk/provider-http) wraps
readResponseWithLimit with a 16 MiB cap, cancels the ReadableStream on
overflow, and wraps JSON parse errors in a consistent
"<label>: malformed JSON response" message.

// Before
const json = parseCopilotTokenResponse(await res.json());

// After
const json = parseCopilotTokenResponse(
  await readProviderJsonResponse(res, "github-copilot.token"),
);

The parseCopilotTokenResponse wrapper is unchanged — it still validates the
token and expires_at fields after the bounded read. Net diff: +1 import,
+2 production lines
(wrapping the existing single-line call).

User Impact

No user-visible behavior change for well-behaved GitHub Copilot endpoints.
Operators or users whose Copilot token endpoint returns an oversized JSON
payload (e.g., a misconfigured proxy, a MITM relay, or a future protocol
change) will now see a bounded error
(github-copilot.token: JSON response exceeds 16777216 bytes) instead of
unbounded heap growth.

Changes

  • src/plugin-sdk/provider-auth.ts:

    • imports readProviderJsonResponse from ../agents/provider-http-errors.js
    • replaces unbounded await res.json() with
      readProviderJsonResponse(res, "github-copilot.token") on the Copilot token
      exchange success path
  • src/plugin-sdk/provider-auth.test.ts:

    • adds bounds oversized Copilot token success body and cancels the stream
      (injected ReadableStream regression)
    • adds bounds oversized Copilot token success body over HTTP transport
      (node:http server + real fetch/undici through resolveCopilotApiToken)
    • adds accepts a normal Copilot token success body over HTTP transport
      (happy-path HTTP proof)

Rebased onto current main.

Real behavior proof

Behavior addressed: Prevents unbounded JSON parse allocation on the Copilot
token exchange success path. Oversized streamed bodies fail closed with a
labeled error before JSON.parse runs.

Real environment tested: Node v22, macOS 24.3.0, node:http streaming
server on 127.0.0.1, built resolveCopilotApiToken from
dist/plugin-sdk/provider-auth.js, real fetch/undici transport (not injected
Response objects for path-level cases).

Exact steps:

  1. Stream an ~18 MiB Copilot token JSON body from a local HTTP server (no
    Content-Length).
  2. Drive resolveCopilotApiToken with fetchImpl pointing at the local server
    → assert labeled rejection.
  3. Serve a normal Copilot token JSON body over HTTP → assert exchange + cache
    write succeeds.
  4. Drive readProviderJsonResponse on the same streamed HTTP body → assert
    parse cap fires.
  5. Negative control: unbounded response.json() drains 64 MiB without
    cancelling the stream.
  6. Bounded helper cancels injected stream after ~17 MiB read.
  7. Run provider-auth HTTP transport regression tests.

Observed result:

  • Path-level HTTP: github-copilot.token: JSON response exceeds 16777216 bytes
  • Normal HTTP token body parses; proxy-ep= metadata intact; cache write once
  • Negative control: unbounded .json() read all 64 chunks; no cancel()
  • Bounded helper: readCount=17, cancel() invoked
  • ALL PROOF ASSERTIONS PASSED

What was not tested: live api.github.com/copilot_internal/v2/token calls.

Evidence

=== Copilot token exchange bound proof (path-level) ===
--- Case 1: oversized streamed body through resolveCopilotApiToken + fetch ---
  ok: resolveCopilotApiToken rejects oversized HTTP token body
  ok: labeled parse cap error (got: github-copilot.token: JSON response exceeds 16777216 bytes)

--- Case 2: normal Copilot token body over HTTP transport ---
  ok: normal HTTP token body parses
  ok: proxy-ep metadata intact
  ok: token cached once

--- Case 3: oversized streamed HTTP body rejected at JSON parse helper ---
  ok: readProviderJsonResponse rejects oversized streamed body
  ok: helper label present (got: github-copilot.token: JSON response exceeds 16777216 bytes)

--- Case 4: negative control — unbounded response.json() ---
  ok: unbounded .json() consumed all 64 chunks (readCount=64)
  ok: stream NOT cancelled via .cancel()

--- Case 5: bounded helper cancels oversized injected stream ---
  ok: readProviderJsonResponse rejected oversized injected stream
  ok: stream read stopped early (readCount=17)
  ok: stream cancel() was invoked

ALL PROOF ASSERTIONS PASSED
OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs src/plugin-sdk/provider-auth.test.ts \
  -t "HTTP transport|bounds oversized Copilot token success body"
# Tests  3 passed | 8 skipped (11)

New bound regression tests (3 added):

  • bounds oversized Copilot token success body and cancels the stream ✓
  • bounds oversized Copilot token success body over HTTP transport ✓
  • accepts a normal Copilot token success body over HTTP transport ✓

@clawsweeper

clawsweeper Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 3, 2026, 12:43 PM ET / 16:43 UTC.

Summary
The PR replaces the GitHub Copilot token exchange success-path res.json() with the shared bounded provider JSON reader and adds oversized and normal-response regression tests.

PR surface: Source +3, Tests +164. Total +167 across 2 files.

Reproducibility: yes. Source inspection shows current main still calls unbounded res.json() on the Copilot token exchange success path, and the PR body supplies a concrete local node:http oversized-body proof path; I did not run tests during this read-only review.

Review metrics: 1 noteworthy metric.

  • Auth success body cap: 1 success-path JSON read capped at 16 MiB. This is the key merge decision because existing Copilot token exchange behavior changes from unbounded parsing to fail-closed size enforcement.

Root-cause cluster
Relationship: canonical
Canonical: #97579
Summary: This PR is the canonical remaining patch for the plugin-SDK Copilot token success-body read; merged siblings cover the same unbounded-response class on adjacent Copilot paths.

Members:

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

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Risk before merge

  • [P1] A legitimate, future, or enterprise-proxied Copilot token success response larger than the shared 16 MiB provider JSON cap will now fail token exchange instead of being parsed or fully drained.

Maintainer options:

  1. Accept The Shared Auth Cap (recommended)
    Merge after normal required checks if maintainers agree that oversized Copilot token success bodies should fail at the existing 16 MiB provider JSON limit.
  2. Adjust Cap Or Policy First
    If legitimate Copilot token exchange responses may exceed 16 MiB, change the cap or behavior and refresh the oversized and normal-response proof before merge.
  3. Pause For Provider-Owner Review
    Leave the PR open if Copilot token endpoint compatibility expectations need explicit auth-provider owner confirmation first.

Next step before merge

  • No automated repair is needed; maintainers need to accept the auth-provider compatibility tradeoff and let required merge checks gate the exact head.

Security
Cleared: The diff narrows an existing unbounded external auth response read and adds no dependencies, permissions, scripts, secret exposure, or new code execution surface.

Review details

Best possible solution:

Land the bounded-read hardening after maintainers accept the shared 16 MiB Copilot auth cap and required checks pass on the exact head.

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

Yes. Source inspection shows current main still calls unbounded res.json() on the Copilot token exchange success path, and the PR body supplies a concrete local node:http oversized-body proof path; I did not run tests during this read-only review.

Is this the best way to solve the issue?

Yes. Reusing readProviderJsonResponse at the single success parse is the narrow maintainable fix because it preserves existing token validation/cache behavior and matches merged sibling Copilot bounded-read work.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 0ad58848b399.

Label changes

Label justifications:

  • P2: The PR fixes a bounded-memory/auth hardening gap with limited blast radius and no new product surface.
  • merge-risk: 🚨 compatibility: A previously accepted oversized Copilot token success body now fails closed at the shared 16 MiB JSON cap.
  • merge-risk: 🚨 auth-provider: The changed code runs during GitHub Copilot token exchange and refresh, so failures affect Copilot credentials and runtime auth setup.
  • 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): The PR body includes after-fix terminal proof from a local HTTP streaming server using real fetch/undici transport for oversized and normal Copilot token responses, plus a negative unbounded-read control.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes after-fix terminal proof from a local HTTP streaming server using real fetch/undici transport for oversized and normal Copilot token responses, plus a negative unbounded-read control.
Evidence reviewed

PR surface:

Source +3, Tests +164. Total +167 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 4 1 +3
Tests 1 164 0 +164
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 168 1 +167

What I checked:

Likely related people:

  • vincentkoc: Recent history added Copilot token exchange error-body cancellation coverage and touched the same SDK auth helper/tests. (role: recent area contributor; confidence: high; commits: 5b3d652c058e, e69cfc3e3bca; files: src/plugin-sdk/provider-auth.ts, src/plugin-sdk/provider-auth.test.ts)
  • Alix-007: Authored the shared provider JSON bounded-reader change and a merged GitHub Copilot usage bounded-read sibling using the same pattern. (role: bounded-reader contributor; confidence: high; commits: 2592f8a51a4e, 646e54ae3578; files: src/agents/provider-http-errors.ts, packages/media-core/src/read-response-with-limit.ts, extensions/github-copilot/usage.ts)
  • steipete: History shows provider-auth and plugin-SDK seam refactors on the files owning this public helper boundary. (role: SDK auth seam contributor; confidence: medium; commits: 9183081bf1aa, 62ddc9d9e0d9, 4ca07559abe4; files: src/plugin-sdk/provider-auth.ts, src/plugin-sdk/provider-auth.test.ts)
  • hugenshen: Beyond this PR, authored merged sibling Copilot bounded-read changes for model/embedding and device-flow paths. (role: adjacent bounded-read contributor; confidence: medium; commits: 1aa7cafc35a1, 748bea343416; files: extensions/github-copilot/embeddings.ts, extensions/github-copilot/login.ts, extensions/github-copilot/login.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.

@clawsweeper clawsweeper Bot added 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. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Jun 28, 2026
@hugenshen
hugenshen force-pushed the fix/bound-copilot-token-json-responses branch from 464a901 to 9b050b2 Compare July 2, 2026 15:30
@hugenshen

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 2, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 2, 2026
@hugenshen
hugenshen force-pushed the fix/bound-copilot-token-json-responses branch from a8df049 to a45e6d3 Compare July 3, 2026 12:31
@hugenshen
hugenshen force-pushed the fix/bound-copilot-token-json-responses branch from a45e6d3 to 5b20f0b Compare July 3, 2026 16:33
@sallyom sallyom self-assigned this Jul 6, 2026
@sallyom

sallyom commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Merge-ready from local maintainer review. Autoreview is clean at head SHA 5b20f0b, CI is green, and I found no compatibility concerns or breaking changes. This is the best narrow fix for the Copilot token exchange JSON parse-boundary gap: it applies the existing 16 MiB provider JSON cap to the owning token response read path while preserving normal Copilot auth behavior.

@sallyom
sallyom merged commit 2f510a0 into openclaw:main Jul 6, 2026
99 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 7, 2026
…enclaw#97579)

* fix(plugin-sdk): bound Copilot token exchange JSON response reads

* test(plugin-sdk): add HTTP transport proof for Copilot token bounds

* fix(test): cast HTTP transport fetch mocks to typeof fetch

---------

Co-authored-by: NIO <[email protected]>
wheakerd pushed a commit to wheakerd/clawdbot that referenced this pull request Jul 15, 2026
…enclaw#97579)

* fix(plugin-sdk): bound Copilot token exchange JSON response reads

* test(plugin-sdk): add HTTP transport proof for Copilot token bounds

* fix(test): cast HTTP transport fetch mocks to typeof fetch

---------

Co-authored-by: NIO <[email protected]>
(cherry picked from commit 2f510a0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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.

2 participants