|
| 1 | +import test from "node:test"; |
| 2 | +import assert from "node:assert/strict"; |
| 3 | +import { fetchWithTimeout } from "../src/providers/request.js"; |
| 4 | + |
| 5 | +function trackedRedirect(cancels, location) { |
| 6 | + const body = new ReadableStream({ cancel() { cancels.count += 1; } }); |
| 7 | + return new Response(body, { status: 302, headers: location === null ? {} : { location } }); |
| 8 | +} |
| 9 | + |
| 10 | +test("followed redirect hop bodies are discarded", async () => { |
| 11 | + const cancels = { count: 0 }; |
| 12 | + let calls = 0; |
| 13 | + const fetchImpl = async () => { |
| 14 | + calls += 1; |
| 15 | + if (calls < 3) return trackedRedirect(cancels, `/hop${calls}`); |
| 16 | + return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { "content-type": "application/json" } }); |
| 17 | + }; |
| 18 | + const response = await fetchWithTimeout(fetchImpl, "https://media.example.test/Sessions"); |
| 19 | + assert.equal(response.status, 200); |
| 20 | + assert.deepEqual(await response.json(), { ok: true }); |
| 21 | + await new Promise((resolve) => setImmediate(resolve)); |
| 22 | + assert.equal(cancels.count, 2); |
| 23 | +}); |
| 24 | + |
| 25 | +for (const [mode, expectedCalls, matcher] of [ |
| 26 | + ["loop", 4, /redirected too many times/], |
| 27 | + ["no-location", 1, /redirected without a location/], |
| 28 | + ["cross-origin", 1, /outside its origin/], |
| 29 | +]) { |
| 30 | + test(`failing redirect reply bodies are discarded (${mode})`, async () => { |
| 31 | + const cancels = { count: 0 }; |
| 32 | + let calls = 0; |
| 33 | + const fetchImpl = async () => { |
| 34 | + calls += 1; |
| 35 | + const location = mode === "no-location" ? null : mode === "cross-origin" ? "https://other.invalid/x" : "/loop"; |
| 36 | + return trackedRedirect(cancels, location); |
| 37 | + }; |
| 38 | + await assert.rejects(fetchWithTimeout(fetchImpl, "https://media.example.test/Sessions"), matcher); |
| 39 | + await new Promise((resolve) => setImmediate(resolve)); |
| 40 | + assert.equal(calls, expectedCalls); |
| 41 | + assert.equal(cancels.count, expectedCalls); |
| 42 | + }); |
| 43 | +} |
| 44 | + |
| 45 | +for (const mode of ["throw", "reject", "pending"]) { |
| 46 | + test(`redirect cleanup ignores errors and does not await its promise (${mode})`, async () => { |
| 47 | + let discarded = false; |
| 48 | + const fetchImpl = async () => ({ status: 302, headers: { get: () => "https://other.invalid/x" }, body: { cancel() { |
| 49 | + discarded = true; |
| 50 | + if (mode === "throw") throw new Error("cleanup failed"); |
| 51 | + if (mode === "reject") return Promise.reject(new Error("cleanup failed")); |
| 52 | + return new Promise(() => {}); |
| 53 | + } } }); |
| 54 | + await assert.rejects(fetchWithTimeout(fetchImpl, "https://media.example.test/Sessions"), /outside its origin/); |
| 55 | + assert.equal(discarded, true); |
| 56 | + }); |
| 57 | +} |
0 commit comments