import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
_setDownloadFetchForTests,
downloadToTemp,
type UrlDownloadTelemetry,
} from "./urlDownloader.js";
const dirs: string[] = [];
afterEach(() => {
_setDownloadFetchForTests();
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
const PATH_PART = "private-customer-clip";
const QUERY_VALUE = "c2lnbmF0dXJlLXZhbHVl";
const KEY_ID = "KEXAMPLEKEYPAIR01";
const URL_ASKED = `https://media.example/${PATH_PART}.mp4?Expires=1999999999&Signature=${QUERY_VALUE}&Key-Pair-Id=${KEY_ID}`;
async function refused(response: Response): Promise<{ event: UrlDownloadTelemetry; line: string }> {
_setDownloadFetchForTests(vi.fn(async () => response) as never);
const dir = mkdtempSync(join(tmpdir(), "hf-url-refusal-"));
dirs.push(dir);
const events: UrlDownloadTelemetry[] = [];
await expect(
downloadToTemp(URL_ASKED, dir, 5_000, undefined, undefined, {
onTelemetry: (event) => events.push(event),
}),
).rejects.toMatchObject({ kind: "http_rejected", status: 403 });
expect(events).toHaveLength(1);
return { event: events[0]!, line: JSON.stringify(events) };
}
const xml = (code: string, message = "Access denied"): string =>
`${code}${message}`;
// fails without the fix: a refused download's line named only the status
describe("a refused download's line", () => {
it("names the server that answered and the error code of an XML body", async () => {
const { event } = await refused(
new Response(xml("AccessDenied"), { status: 403, headers: { server: "CloudFront" } }),
);
expect(event).toMatchObject({
outcome: "attempt_failed",
failureKind: "http_rejected",
status: 403,
refusedBy: "CloudFront",
refusalCode: "AccessDenied",
});
});
it("names the error code of a JSON body and only the product of a longer server header", async () => {
const { event } = await refused(
new Response(JSON.stringify({ code: "SignatureDoesNotMatch", message: "no" }), {
status: 403,
headers: { server: "nginx/1.25.3 (Ubuntu)" },
}),
);
expect(event).toMatchObject({ refusedBy: "nginx", refusalCode: "SignatureDoesNotMatch" });
});
it("names neither when the response has no server header and no body", async () => {
const { event } = await refused(new Response(null, { status: 403 }));
expect(event).not.toHaveProperty("refusedBy");
expect(event).not.toHaveProperty("refusalCode");
});
it("carries nothing of the requested link when the response repeats the link", async () => {
const { event, line } = await refused(
new Response(xml("AccessDenied", `Denied: ${URL_ASKED}`), {
status: 403,
headers: { server: URL_ASKED },
}),
);
expect(event.refusalCode).toBe("AccessDenied");
expect(event).not.toHaveProperty("refusedBy");
for (const part of [PATH_PART, QUERY_VALUE, KEY_ID, "Expires", "Signature", "1999999999"]) {
expect(line).not.toContain(part);
}
});
it.each([
["the signature", QUERY_VALUE],
["the key id", KEY_ID],
["a part of the path", PATH_PART],
["the key id in another case", KEY_ID.toLowerCase()],
])("leaves out a server name and a code that are %s", async (_name, value) => {
const { event, line } = await refused(
new Response(xml(value), { status: 403, headers: { server: value } }),
);
expect(event).not.toHaveProperty("refusedBy");
expect(event).not.toHaveProperty("refusalCode");
expect(line.toLowerCase()).not.toContain(value.toLowerCase());
});
it("leaves out a code or a server name longer than its limit", async () => {
const { event } = await refused(
new Response(xml("A".repeat(49)), { status: 403, headers: { server: "s".repeat(33) } }),
);
expect(event).not.toHaveProperty("refusedBy");
expect(event).not.toHaveProperty("refusalCode");
});
it("reads no more than the first 2048 bytes of the body", async () => {
const pulls: number[] = [];
const chunk = new TextEncoder().encode(" ".repeat(1024));
const body = new ReadableStream(
{
pull(controller) {
pulls.push(pulls.length);
controller.enqueue(pulls.length === 4 ? new TextEncoder().encode(xml("Late")) : chunk);
},
},
{ highWaterMark: 0 },
);
const { event } = await refused(new Response(body, { status: 403 }));
expect(event).not.toHaveProperty("refusalCode");
expect(pulls.length).toBeLessThanOrEqual(3);
});
it("waits no more than half a second for a body that stops, and lets go of it", async () => {
let cancelled = false;
const body = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode("Acc"));
},
cancel() {
cancelled = true;
},
});
const started = Date.now();
const { event } = await refused(
new Response(body, { status: 403, headers: { server: "AmazonS3" } }),
);
expect(Date.now() - started).toBeLessThan(2_500);
expect(event.refusedBy).toBe("AmazonS3");
expect(event).not.toHaveProperty("refusalCode");
expect(cancelled).toBe(true);
});
it("stays a refusal, not retried, when the attempt's time limit ends while the body is read", async () => {
const fetchMock = vi.fn(
async () =>
new Response(new ReadableStream({}), {
status: 403,
headers: { server: "AmazonS3" },
}),
);
_setDownloadFetchForTests(fetchMock as never);
const dir = mkdtempSync(join(tmpdir(), "hf-url-refusal-"));
dirs.push(dir);
const events: UrlDownloadTelemetry[] = [];
await expect(
downloadToTemp(URL_ASKED, dir, 100, undefined, undefined, {
onTelemetry: (event) => events.push(event),
}),
).rejects.toMatchObject({ kind: "http_rejected", retryable: false, status: 403 });
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(events).toEqual([
expect.objectContaining({ failureKind: "http_rejected", status: 403, refusedBy: "AmazonS3" }),
]);
});
it("leaves out a value the link carries percent-encoded", async () => {
_setDownloadFetchForTests(
vi.fn(
async () =>
new Response(xml("SecretPart"), { status: 403, headers: { server: "SecretPart" } }),
) as never,
);
const dir = mkdtempSync(join(tmpdir(), "hf-url-refusal-"));
dirs.push(dir);
const events: UrlDownloadTelemetry[] = [];
await expect(
downloadToTemp(
"https://media.example/a.mp4?k=%53ecretPart",
dir,
5_000,
undefined,
undefined,
{
onTelemetry: (event) => events.push(event),
},
),
).rejects.toMatchObject({ status: 403 });
expect(JSON.stringify(events)).not.toContain("SecretPart");
});
it("does not read the body of a response it asks for again", async () => {
let pulled = false;
const body = new ReadableStream(
{
pull() {
pulled = true;
},
},
{ highWaterMark: 0 },
);
_setDownloadFetchForTests(
vi
.fn()
.mockResolvedValueOnce(new Response(body, { status: 503, headers: { server: "nginx" } }))
.mockResolvedValueOnce(new Response("media")) as never,
);
const dir = mkdtempSync(join(tmpdir(), "hf-url-refusal-"));
dirs.push(dir);
const events: UrlDownloadTelemetry[] = [];
await downloadToTemp(URL_ASKED, dir, 1_000, undefined, undefined, {
onTelemetry: (event) => events.push(event),
});
expect(pulled).toBe(false);
expect(events[0]).toMatchObject({ status: 503, refusedBy: "nginx" });
expect(events[0]).not.toHaveProperty("refusalCode");
});
});