Skip to content

Commit

Permalink
fix(proxy): avoid decoding request body as utf8 (#440)
Browse files Browse the repository at this point in the history
Co-authored-by: Benoit Ngo <b.ngo@thecodingmachine.com>
Co-authored-by: Pooya Parsa <pooya@pi0.io>
  • Loading branch information
3 people authored Jul 24, 2023
1 parent 57dcba8 commit ed3ae90
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/utils/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export async function proxyRequest(
// Body
let body;
if (PayloadMethods.has(method)) {
body = await readRawBody(event).catch(() => undefined);
body = await readRawBody(event, false).catch(() => undefined);
}

// Headers
Expand Down
Binary file added test/assets/dummy.pdf
Binary file not shown.
40 changes: 40 additions & 0 deletions test/proxy.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Server } from "node:http";
import { readFile } from "node:fs/promises";
import supertest, { SuperTest, Test } from "supertest";
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { fetch } from "node-fetch-native";
Expand All @@ -12,6 +13,7 @@ import {
setHeader,
readRawBody,
setCookie,
setResponseHeader,
} from "../src";
import { sendProxy, proxyRequest } from "../src/utils/proxy";

Expand Down Expand Up @@ -106,6 +108,44 @@ describe("", () => {
}
`);
});

it("can proxy binary request", async () => {
app.use(
"/debug",
eventHandler(async (event) => {
const body = await readRawBody(event, false);
return {
headers: getHeaders(event),
bytes: body!.length,
};
})
);

app.use(
"/",
eventHandler((event) => {
setResponseHeader(event, "x-res-header", "works");
return proxyRequest(event, url + "/debug", { fetch });
})
);

const dummyFile = await readFile(
new URL("assets/dummy.pdf", import.meta.url)
);

const res = await fetch(url + "/", {
method: "POST",
body: dummyFile,
headers: {
"x-req-header": "works",
},
});
const resBody = await res.json();

expect(res.headers.get("x-res-header")).toEqual("works");
expect(resBody.headers["x-req-header"]).toEqual("works");
expect(resBody.bytes).toEqual(dummyFile.length);
});
});

describe("multipleCookies", () => {
Expand Down

0 comments on commit ed3ae90

Please sign in to comment.