Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions worker/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,16 @@ export function bearerToken(request: Request): string | undefined {
return apiKey?.trim() || undefined;
}

export function parseJsonBody<T = unknown>(request: Request): Promise<T> {
export async function parseJsonBody<T = unknown>(request: Request): Promise<T> {
const contentType = request.headers.get("content-type") || "";
if (contentType && !contentType.toLowerCase().includes("application/json")) {
throw new HttpError("Content-Type must be application/json", 415);
}
return request.json() as Promise<T>;
try {
return (await request.json()) as T;
} catch {
throw new HttpError("Invalid JSON in request body", 400, "invalid_request_error");
}
}

export class HttpError extends Error {
Expand Down
23 changes: 23 additions & 0 deletions worker/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,29 @@ describe("Worker", () => {
// An invalid cmp_ token is never forwarded to Cursor as a Cursor key.
expect(exchangeAuthHeaders).toHaveLength(0);
});

it("returns 400 for malformed JSON body instead of 500", async () => {
const db = new FakeD1();
const env = makeEnv(db);
const { deps } = fakeDeps();

const response = await handleRequest(
new Request("https://composer.test/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer cursor_direct_key"
},
body: "{ invalid json }"
}),
env,
fakeCtx(),
deps
);
expect(response.status).toBe(400);
const body = (await response.json()) as { error: { code: string } };
expect(body.error.code).toBe("invalid_request_error");
});
});

function fakeDeps(): {
Expand Down