Skip to content

Commit d59938a

Browse files
solodmdclaude
andcommitted
fix(openai): bound Codex OAuth JSON and error response reads
exchangeAuthorizationCode and refreshAccessToken called response.json() and response.text() without size limits on the token endpoint response. Replace with readProviderJsonResponse (16 MiB capped JSON parse) and readResponseTextLimited (16 MiB capped text read). Co-Authored-By: Claude <[email protected]>
1 parent 738b2be commit d59938a

2 files changed

Lines changed: 146 additions & 6 deletions

File tree

‎extensions/openai/openai-chatgpt-oauth-flow.runtime.test.ts‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,4 +174,111 @@ describe("OpenAI Codex OAuth flow", () => {
174174
message: "OpenAI Codex token refresh response missing fields: expires_in",
175175
});
176176
});
177+
178+
describe("bounded OAuth JSON and text reads", () => {
179+
function makeOversizedResponse(): Response {
180+
const chunkSize = 1024 * 1024;
181+
const maxChunks = 20; // 20 MiB — over 16 MiB cap
182+
let chunksSent = 0;
183+
return new Response(
184+
new ReadableStream<Uint8Array>({
185+
pull(controller) {
186+
if (chunksSent >= maxChunks) {
187+
controller.close();
188+
return;
189+
}
190+
chunksSent += 1;
191+
controller.enqueue(new Uint8Array(chunkSize));
192+
},
193+
cancel() {
194+
// stream canceled — bounding fired
195+
},
196+
}),
197+
);
198+
}
199+
200+
it("caps oversized token exchange response at postTokenForm level", async () => {
201+
ssrfMocks.fetchWithSsrFGuard.mockResolvedValueOnce({
202+
response: makeOversizedResponse(),
203+
release: vi.fn(async () => undefined),
204+
});
205+
206+
// readResponseWithLimit throws in postTokenForm; exchangeAuthorizationCode
207+
// catches it and returns a failed result.
208+
const result = await testing.exchangeAuthorizationCode(
209+
"code",
210+
"verifier",
211+
testing.resolveRedirectUri("localhost"),
212+
);
213+
214+
expect(result).toMatchObject({
215+
type: "failed",
216+
});
217+
});
218+
219+
it("caps oversized token refresh response at postTokenForm level", async () => {
220+
ssrfMocks.fetchWithSsrFGuard.mockResolvedValueOnce({
221+
response: makeOversizedResponse(),
222+
release: vi.fn(async () => undefined),
223+
});
224+
225+
// readResponseWithLimit throws in postTokenForm; refreshAccessToken's
226+
// outer catch handler returns a failed result.
227+
const result = await testing.refreshAccessToken("old-refresh-token");
228+
229+
expect(result).toMatchObject({
230+
type: "failed",
231+
});
232+
});
233+
234+
it("rejects malformed token exchange JSON response", async () => {
235+
mockTokenResponseText("not-json");
236+
237+
await expect(
238+
testing.exchangeAuthorizationCode(
239+
"code",
240+
"verifier",
241+
testing.resolveRedirectUri("localhost"),
242+
),
243+
).rejects.toThrow(/openai-codex-token-exchange: malformed JSON response/);
244+
});
245+
246+
it("caps oversized error body on failed token exchange", async () => {
247+
const errorBody = "x".repeat(8 * 1024); // 8 KB — over 4 KB diagnostic cap
248+
ssrfMocks.fetchWithSsrFGuard.mockResolvedValueOnce({
249+
response: new Response(errorBody, { status: 400 }),
250+
release: vi.fn(async () => undefined),
251+
});
252+
253+
const result = await testing.exchangeAuthorizationCode(
254+
"code",
255+
"verifier",
256+
testing.resolveRedirectUri("localhost"),
257+
);
258+
259+
expect(result).toMatchObject({
260+
type: "failed",
261+
status: 400,
262+
});
263+
// The message should include the truncated text (up to diagnostic cap)
264+
// and not the full 8 KB body.
265+
expect((result as { message?: string }).message?.length).toBeLessThan(6 * 1024);
266+
});
267+
268+
it("caps oversized error body on failed token refresh", async () => {
269+
const errorBody = "y".repeat(8 * 1024); // 8 KB — over 4 KB diagnostic cap
270+
ssrfMocks.fetchWithSsrFGuard.mockResolvedValueOnce({
271+
response: new Response(errorBody, { status: 400 }),
272+
release: vi.fn(async () => undefined),
273+
});
274+
275+
const result = await testing.refreshAccessToken("old-refresh-token");
276+
277+
expect(result).toMatchObject({
278+
type: "failed",
279+
status: 400,
280+
});
281+
expect((result as { message?: string }).message?.length).toBeLessThan(6 * 1024);
282+
});
283+
});
177284
});

‎extensions/openai/openai-chatgpt-oauth-flow.runtime.ts‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,16 @@
55
* It is only intended for CLI use, not browser environments.
66
*/
77

8+
import {
9+
readProviderJsonResponse,
10+
readResponseTextLimited,
11+
} from "openclaw/plugin-sdk/provider-http";
812
import {
913
parseOAuthAuthorizationInput,
1014
resolveOAuthTokenExpiresAt,
1115
resolveOAuthTokenLifetimeMs,
1216
} from "openclaw/plugin-sdk/provider-oauth-runtime";
17+
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
1318
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
1419
import { resolveCodexAuthIdentity } from "./openai-chatgpt-auth-identity.js";
1520
import {
@@ -27,6 +32,8 @@ import type {
2732
import { generatePKCE } from "./openai-chatgpt-pkce.runtime.js";
2833

2934
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
35+
const OPENAI_OAUTH_RESPONSE_MAX_BYTES = 16 * 1024 * 1024;
36+
const OPENAI_OAUTH_DIAGNOSTIC_MAX_BYTES = 4 * 1024;
3037
const AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize";
3138
const TOKEN_URL = "https://auth.openai.com/oauth/token";
3239
const CALLBACK_PORT = 1455;
@@ -178,8 +185,24 @@ async function postTokenForm(
178185
auditContext: "openai-chatgpt-oauth-token",
179186
});
180187
try {
181-
const responseBody = await response.arrayBuffer();
182-
return new Response(responseBody, {
188+
// Read the original response body under a byte cap *before* release(),
189+
// so a hostile or buggy token endpoint cannot exhaust memory via the
190+
// unbounded arrayBuffer() path.
191+
const responseBody = await readResponseWithLimit(response, OPENAI_OAUTH_RESPONSE_MAX_BYTES, {
192+
onOverflow: ({ maxBytes }) =>
193+
new Error(`OpenAI Codex token response exceeds ${maxBytes} bytes`),
194+
});
195+
// `readResponseWithLimit` returns a `Buffer` (Node Uint8Array view). The
196+
// global `Response` constructor accepts `BufferSource` (Uint8Array /
197+
// ArrayBuffer) as a body; cast through `BodyInit` because `Buffer.buffer`
198+
// is typed as `ArrayBufferLike`. Same wrap-shape as
199+
// extensions/google/oauth.http.ts:454.
200+
const bodyBytes = new Uint8Array(
201+
responseBody.buffer,
202+
responseBody.byteOffset,
203+
responseBody.byteLength,
204+
);
205+
return new Response(bodyBytes as unknown as BodyInit, {
183206
status: response.status,
184207
statusText: response.statusText,
185208
headers: response.headers,
@@ -216,15 +239,20 @@ async function exchangeAuthorizationCode(
216239
}
217240

218241
if (!response.ok) {
219-
const text = await response.text().catch(() => "");
242+
const text = await readResponseTextLimited(response, OPENAI_OAUTH_DIAGNOSTIC_MAX_BYTES).catch(
243+
() => "",
244+
);
220245
return {
221246
type: "failed",
222247
status: response.status,
223248
message: `OpenAI Codex token exchange failed (${response.status}): ${text || response.statusText}`,
224249
};
225250
}
226251

227-
const json = (await response.json()) as TokenResponseJson;
252+
const json = await readProviderJsonResponse<TokenResponseJson>(
253+
response,
254+
"openai-codex-token-exchange",
255+
);
228256

229257
const expires = resolveOAuthTokenExpiresAt(json.expires_in);
230258
if (!json.access_token || !json.refresh_token || expires === undefined) {
@@ -258,15 +286,20 @@ async function refreshAccessToken(
258286
);
259287

260288
if (!response.ok) {
261-
const text = await response.text().catch(() => "");
289+
const text = await readResponseTextLimited(response, OPENAI_OAUTH_DIAGNOSTIC_MAX_BYTES).catch(
290+
() => "",
291+
);
262292
return {
263293
type: "failed",
264294
status: response.status,
265295
message: `OpenAI Codex token refresh failed (${response.status}): ${text || response.statusText}`,
266296
};
267297
}
268298

269-
const json = (await response.json()) as TokenResponseJson;
299+
const json = await readProviderJsonResponse<TokenResponseJson>(
300+
response,
301+
"openai-codex-token-refresh",
302+
);
270303

271304
const expires = resolveOAuthTokenExpiresAt(json.expires_in);
272305
if (!json.access_token || !json.refresh_token || expires === undefined) {

0 commit comments

Comments
 (0)