diff --git a/pkgs/pkarr-worker/src/index.ts b/pkgs/pkarr-worker/src/index.ts index 664519ed6b..fb0b2ecbc8 100644 --- a/pkgs/pkarr-worker/src/index.ts +++ b/pkgs/pkarr-worker/src/index.ts @@ -111,14 +111,72 @@ async function rateLimited(limiter: RateLimit, key: string): Promise { const NO_STORE = { "cache-control": "no-store" } as const; +type BoundedBodyResult = + | { kind: "ok"; bytes: Uint8Array } + | { kind: "too-large" } + | { kind: "read-error" }; + +/** Read at most `maximum` bytes, cancelling the request as soon as it exceeds the cap. */ +async function readBoundedBody(request: Request, maximum: number): Promise { + const declaredLength = request.headers.get("content-length"); + if (declaredLength !== null && /^\d+$/.test(declaredLength)) { + const length = Number(declaredLength); + if (Number.isSafeInteger(length) && length > maximum) { + try { + await request.body?.cancel(); + } catch { + // The declared size is sufficient to reject; cancellation is best effort. + } + return { kind: "too-large" }; + } + } + + const reader = request.body?.getReader(); + if (reader === undefined) return { kind: "ok", bytes: new Uint8Array() }; + + const chunks: Uint8Array[] = []; + let total = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (value.byteLength === 0) continue; + total += value.byteLength; + if (total > maximum) { + try { + await reader.cancel(); + } catch { + // The over-limit condition is already decisive; cancellation is best effort. + } + return { kind: "too-large" }; + } + chunks.push(value); + } + } catch { + return { kind: "read-error" }; + } finally { + reader.releaseLock(); + } + + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return { kind: "ok", bytes }; +} + async function handlePut(request: Request, env: Env, keyText: string): Promise { const publicKey = parsePublicKey(keyText); if (publicKey === null) return new Response("invalid public key", { status: 400 }); if (await rateLimited(env.PUT_LIMITER, clientIp(request))) { return new Response("rate limited", { status: 429 }); } - const body = new Uint8Array(await request.arrayBuffer()); - if (body.length > MAX_RELAY_PAYLOAD) return new Response("payload too large", { status: 413 }); + const read = await readBoundedBody(request, MAX_RELAY_PAYLOAD); + if (read.kind === "too-large") return new Response("payload too large", { status: 413 }); + if (read.kind === "read-error") return new Response("invalid request body", { status: 400 }); + const body = read.bytes; const parsed = parseRelayPayload(body); if (typeof parsed === "string") return new Response(parsed, { status: 400 }); // The packet itself must be a well-formed DNS message within bounds. @@ -175,7 +233,12 @@ function underOrigin(name: string, origin: string): boolean { return suffix.every((label, i) => labels[labels.length - suffix.length + i] === label); } -async function handleDoh(request: Request, env: Env, queryBytes: Uint8Array): Promise { +async function handleDoh( + request: Request, + env: Env, + queryBytes: Uint8Array, + rateLimitChecked = false, +): Promise { if (queryBytes.length > MAX_DOH_BODY) return new Response("message too large", { status: 413 }); const query = parseDnsMessage(queryBytes); if (typeof query === "string") return new Response("malformed dns message", { status: 400 }); @@ -195,7 +258,7 @@ async function handleDoh(request: Request, env: Env, queryBytes: Uint8Array): Pr if (question.type !== 16 && question.type !== 255) return respond(0, []); // TXT/ANY only const publicKey = parsePublicKey(keyText); if (publicKey === null) return respond(0, []); - if (await rateLimited(env.DOH_LIMITER, clientIp(request))) { + if (!rateLimitChecked && (await rateLimited(env.DOH_LIMITER, clientIp(request)))) { return new Response("rate limited", { status: 429 }); } const payload = await storeFor(env, publicKey).getPacket(); @@ -257,7 +320,20 @@ export default { } if (path === "/dns-query") { if (request.method === "POST") { - return handleDoh(request, env, new Uint8Array(await request.arrayBuffer())); + // DoH POSTs are rate-limited before any request-body read, including + // malformed queries that cannot yet be associated with a lookup key. + if (await rateLimited(env.DOH_LIMITER, clientIp(request))) { + try { + await request.body?.cancel(); + } catch { + // The rate limit is decisive; cancellation is best effort. + } + return new Response("rate limited", { status: 429 }); + } + const read = await readBoundedBody(request, MAX_DOH_BODY); + if (read.kind === "too-large") return new Response("message too large", { status: 413 }); + if (read.kind === "read-error") return new Response("invalid request body", { status: 400 }); + return handleDoh(request, env, read.bytes, true); } if (request.method === "GET") { const dns = url.searchParams.get("dns"); diff --git a/pkgs/pkarr-worker/test/worker.test.ts b/pkgs/pkarr-worker/test/worker.test.ts index 5a0c25e6fe..c43b5f283a 100644 --- a/pkgs/pkarr-worker/test/worker.test.ts +++ b/pkgs/pkarr-worker/test/worker.test.ts @@ -63,6 +63,47 @@ function testEnv(store: ReturnType["store"], retentionSeconds: } as unknown as Env; } +function requestWithStream( + url: string, + method: string, + body: ReadableStream, + headers: Record = {}, +): Request { + return new Request(url, { + method, + headers, + body, + duplex: "half", + } as RequestInit); +} + +function endlessByteStream(chunkSize: number, onPull?: () => void) { + let pulls = 0; + let cancelled = false; + const stream = new ReadableStream( + { + pull(controller) { + pulls++; + onPull?.(); + controller.enqueue(new Uint8Array(chunkSize)); + }, + cancel() { + cancelled = true; + }, + }, + { highWaterMark: 0 }, + ); + return { + stream, + get pulls() { + return pulls; + }, + get cancelled() { + return cancelled; + }, + }; +} + describe("z32 codec", () => { it("matches hand-computed vectors", () => { expect(z32Encode(new Uint8Array([0x00]))).toBe("yy"); @@ -187,6 +228,34 @@ describe("pkarr HTTP relay", () => { expect((await put(key, payload)).status).toBe(413); }); + it("rejects an over-cap declared Content-Length before reading a PUT body", async () => { + const key = z32(keypair(26).publicKey); + const body = endlessByteStream(1); + const response = await worker.fetch( + requestWithStream(`${BASE}/pkarr/${key}`, "PUT", body.stream, { + "content-length": String(1073), + }), + testEnv(mockStore(undefined).store, undefined), + ); + + expect(response.status).toBe(413); + expect(body.pulls).toBe(0); + expect(body.cancelled).toBe(true); + }); + + it("cancels a streamed PUT as soon as its body exceeds the cap", async () => { + const key = z32(keypair(27).publicKey); + const body = endlessByteStream(600); + const response = await worker.fetch( + requestWithStream(`${BASE}/pkarr/${key}`, "PUT", body.stream), + testEnv(mockStore(undefined).store, undefined), + ); + + expect(response.status).toBe(413); + expect(body.pulls).toBe(2); + expect(body.cancelled).toBe(true); + }); + it("accepts a packet at exactly 1000 bytes", async () => { const kp = keypair(17); const key = z32(kp.publicKey); @@ -283,6 +352,54 @@ describe("DNS-over-HTTPS", () => { expect(parsed.flags & 0x000f).toBe(5); // REFUSED expect((await doh(new Uint8Array([1, 2, 3]))).status).toBe(400); }); + + it("rejects an over-cap declared Content-Length before reading a DoH POST body", async () => { + const body = endlessByteStream(1); + const response = await worker.fetch( + requestWithStream(`${BASE}/dns-query`, "POST", body.stream, { + "content-length": String(4097), + }), + testEnv(mockStore(undefined).store, undefined), + ); + + expect(response.status).toBe(413); + expect(body.pulls).toBe(0); + expect(body.cancelled).toBe(true); + }); + + it("cancels a streamed DoH POST as soon as its body exceeds the cap", async () => { + const body = endlessByteStream(2048); + const response = await worker.fetch( + requestWithStream(`${BASE}/dns-query`, "POST", body.stream), + testEnv(mockStore(undefined).store, undefined), + ); + + expect(response.status).toBe(413); + expect(body.pulls).toBe(3); + expect(body.cancelled).toBe(true); + }); + + it("checks the DoH limiter before reading a POST body", async () => { + const order: string[] = []; + const body = endlessByteStream(1, () => order.push("read")); + const env = testEnv(mockStore(undefined).store, undefined); + env.DOH_LIMITER = { + limit: async () => { + order.push("limit"); + return { success: false }; + }, + } as Env["DOH_LIMITER"]; + + const response = await worker.fetch( + requestWithStream(`${BASE}/dns-query`, "POST", body.stream), + env, + ); + + expect(response.status).toBe(429); + expect(order).toEqual(["limit"]); + expect(body.pulls).toBe(0); + expect(body.cancelled).toBe(true); + }); }); describe("scope guardrails", () => {