| 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("rejects malformed Content-Length values", async () => { |
| 39 | const req = request("token=value", { "content-length": "not-a-number" }); |
| 40 | await expect(readBoundedUrlEncodedForm(req, 64)).rejects.toMatchObject({ status: 400 }); |
| 41 | }); |
| 42 | }); |
| 43 |