| 1 | import { describe, expect, it } from "vitest"; |
| 2 | import { readBoundedUrlEncodedForm } from "./bounded-form"; |
| 3 | |
| 4 | function request(body: string, headers: Record<string, string> = {}): Request { |
| 5 | return new Request("https://codewhale.net/api/admin/login", { |
| 6 | method: "POST", |
| 7 | headers: { |
| 8 | "content-type": "application/x-www-form-urlencoded", |
| 9 | ...headers, |
| 10 | }, |
| 11 | body, |
| 12 | }); |
| 13 | } |
| 14 | |
| 15 | describe("readBoundedUrlEncodedForm", () => { |
| 16 | it("parses the exact login form media type within the byte bound", async () => { |
| 17 | const form = await readBoundedUrlEncodedForm(request("token=safe%20value&locale=zh"), 64); |
| 18 | expect(form.get("token")).toBe("safe value"); |
| 19 | expect(form.get("locale")).toBe("zh"); |
| 20 | }); |
| 21 | |
| 22 | it("rejects unsupported media types before reading the body", async () => { |
| 23 | const req = request("token=value", { "content-type": "multipart/form-data; boundary=x" }); |
| 24 | await expect(readBoundedUrlEncodedForm(req, 64)).rejects.toMatchObject({ status: 415 }); |
| 25 | }); |
| 26 | |
| 27 | it("rejects oversized declared lengths before reading", async () => { |
| 28 | const req = request("token=value", { "content-length": "4097" }); |
| 29 | await expect(readBoundedUrlEncodedForm(req, 4096)).rejects.toMatchObject({ status: 413 }); |
| 30 | }); |
| 31 | |
| 32 | it("enforces the streaming byte cap when Content-Length is absent", async () => { |
| 33 | const req = request(`token=${"x".repeat(64)}`); |
| 34 | req.headers.delete("content-length"); |
| 35 | await expect(readBoundedUrlEncodedForm(req, 16)).rejects.toMatchObject({ status: 413 }); |
| 36 | }); |
| 37 | |
| 38 | it("preserves a split multibyte form value exactly at the byte limit", async () => { |
| 39 | const bytes = new TextEncoder().encode("token=鲸"); |
| 40 | const makeRequest = () => new Request("https://codewhale.net/api/admin/login", { |
| 41 | method: "POST", |
| 42 | headers: { "content-type": "application/x-www-form-urlencoded" }, |
| 43 | body: new ReadableStream<Uint8Array>({ start(controller) { |
| 44 | controller.enqueue(bytes.slice(0, 7)); |
| 45 | controller.enqueue(bytes.slice(7)); |
| 46 | controller.close(); |
| 47 | } }), |
| 48 | duplex: "half", |
| 49 | } as RequestInit); |
| 50 | expect((await readBoundedUrlEncodedForm(makeRequest(), 9)).get("token")).toBe("鲸"); |
| 51 | await expect(readBoundedUrlEncodedForm(makeRequest(), 8)).rejects.toMatchObject({ name: "FormBodyError", status: 413 }); |
| 52 | }); |
| 53 | |
| 54 | it("rejects malformed Content-Length values", async () => { |
| 55 | const req = request("token=value", { "content-length": "not-a-number" }); |
| 56 | await expect(readBoundedUrlEncodedForm(req, 64)).rejects.toMatchObject({ status: 400 }); |
| 57 | }); |
| 58 | }); |
| 59 |