Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions packages/engine/src/utils/notMediaPayload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,48 @@ describe("playlistLeavesItsFolder", () => {
expect(await isNotMediaPayload(file)).toBe(true);
});

function writeTree(files: Record<string, string>): string {
const dir = mkdtempSync(join(tmpdir(), "hf-playlist-tree-"));
for (const [name, contents] of Object.entries(files)) {
mkdirSync(join(dir, name, ".."), { recursive: true });
writeFileSync(join(dir, name), contents);
}
return join(dir, Object.keys(files)[0]!);
}

it("refuses a list whose nested list names a file outside the top folder", async () => {
const master = writeTree({
"master.m3u8": "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nsub/inner.m3u8\n",
"sub/inner.m3u8": hls("#EXTINF:1,", "/var/renders/other/out.mp4"),
});
expect(await playlistLeavesItsFolder(master)).toBe(true);
});

it("refuses a nested list that steps above the top folder from its own", async () => {
const master = writeTree({
"master.m3u8": "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nsub/inner.m3u8\n",
"sub/inner.m3u8": hls("#EXTINF:1,", "../../other/out.mp4"),
});
expect(await playlistLeavesItsFolder(master)).toBe(true);
});

it("refuses lists nested deeper than it reads", async () => {
const files: Record<string, string> = {};
for (let i = 0; i < 12; i++)
files[`l${i}.m3u8`] = `#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nl${i + 1}.m3u8\n`;
files["l12.m3u8"] = hls("#EXTINF:1,", "seg.ts");
expect(await playlistLeavesItsFolder(writeTree(files))).toBe(true);
});

it("keeps nested lists that stay in the top folder, cycles included", async () => {
const master = writeTree({
"master.m3u8": "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nsub/inner.m3u8\n",
"sub/inner.m3u8": hls("#EXTINF:1,", "../seg.ts", "#EXTINF:1,", "../master.m3u8"),
"seg.ts": "segment",
});
expect(await playlistLeavesItsFolder(master)).toBe(false);
});

it.each([
["segments beside it", hls("#EXTINF:1,", "seg0.ts", "#EXTINF:1,", "parts/seg1.ts")],
["https segments", hls("#EXTINF:1,", "https://cdn.example.com/seg0.ts")],
Expand Down
69 changes: 56 additions & 13 deletions packages/engine/src/utils/notMediaPayload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ export async function assertMediaPayload(filePath: string, elementId: string): P
}

const MAX_PLAYLIST_BYTES = 8 * 1024 * 1024;
const MAX_PLAYLIST_DEPTH = 8;
const HTTP_URL = /^https?:\/\//i;
const OTHER_SCHEME = /^[a-z][a-z0-9+.-]+:/i;
const DRIVE_PATH = /^[a-z]:[\\/]/i;
Expand All @@ -179,12 +180,12 @@ function playlistEntries(text: string): string[] | undefined {
return undefined;
}

function entryLeavesFolder(entry: string, folder: string): boolean {
function entryLeavesFolder(entry: string, base: string, folder: string): boolean {
if (HTTP_URL.test(entry)) return false;
if (OTHER_SCHEME.test(entry) && !DRIVE_PATH.test(entry)) return true;
return [entry, safeDecode(entry)].some((path) => {
if (isAbsolute(path) || DRIVE_PATH.test(path) || path.startsWith("\\")) return true;
const inside = relative(folder, resolve(folder, path));
const inside = relative(folder, resolve(base, path));
return (
inside === ".." || inside.startsWith("../") || inside.startsWith("..\\") || isAbsolute(inside)
);
Expand All @@ -199,20 +200,62 @@ function safeDecode(value: string): string {
}
}

/** True for an HLS or ffconcat list naming a file outside its folder; ffmpeg would open it. Never throws. */
export async function playlistLeavesItsFolder(filePath: string): Promise<boolean> {
/**
* True for an HLS or ffconcat list naming a file outside its folder; ffmpeg would open it. Never throws.
* `placedAt` is where the file will live when it is read from elsewhere first (a download not yet published).
*/
export async function playlistLeavesItsFolder(
filePath: string,
placedAt = filePath,
): Promise<boolean> {
const placed = resolve(placedAt);
return listLeaves(resolve(filePath), placed, dirname(placed), new Set(), 0);
}

async function startsAsPlaylist(path: string): Promise<boolean> {
const head = (await readHead(path))
.toString("utf8")
.replace(/^\uFEFF/, "")
.trimStart();
return head.startsWith("#EXTM3U") || /^ffconcat\s+version/i.test(head);
}

/** Every list a list names is read too, against the top list's folder. */
async function listLeaves(
readPath: string,
path: string,
folder: string,
seen: Set<string>,
depth: number,
): Promise<boolean> {
try {
const head = (await readHead(filePath))
.toString("utf8")
.replace(/^\uFEFF/, "")
.trimStart();
if (!head.startsWith("#EXTM3U") && !/^ffconcat\s+version/i.test(head)) return false;
const body = await readHead(filePath, MAX_PLAYLIST_BYTES + 1);
if (!(await startsAsPlaylist(readPath))) return false;
if (depth >= MAX_PLAYLIST_DEPTH) return true;
if (seen.has(path)) return false;
seen.add(path);
const body = await readHead(readPath, MAX_PLAYLIST_BYTES + 1);
if (body.length > MAX_PLAYLIST_BYTES) return true;
const entries = playlistEntries(body.toString("utf8")) ?? [];
const folder = dirname(resolve(filePath));
return entries.some((entry) => entryLeavesFolder(entry, folder));
for (const entry of playlistEntries(body.toString("utf8")) ?? []) {
if (await entryLeaves(entry, dirname(path), folder, seen, depth)) return true;
}
return false;
} catch {
return false;
}
}

async function entryLeaves(
entry: string,
base: string,
folder: string,
seen: Set<string>,
depth: number,
): Promise<boolean> {
if (entryLeavesFolder(entry, base, folder)) return true;
if (HTTP_URL.test(entry)) return false;
for (const local of new Set([entry, safeDecode(entry)])) {
const nested = resolve(base, local);
if (await listLeaves(nested, nested, folder, seen, depth + 1)) return true;
}
return false;
}
40 changes: 40 additions & 0 deletions packages/engine/src/utils/urlDownloader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,46 @@ describe("downloadToTemp atomic publication and bounded retry", () => {
expect(temporaryDownloadEntries(dir)).toEqual([]);
});

it.each([
["names a file outside its folder", () => "/var/renders/other/out.mp4"],
[
"names a list beside it that leaves the folder",
(dir: string) => {
writeFileSync(
join(dir, "download_000000000000.m3u8"),
"#EXTM3U\n#EXTINF:1,\n/var/renders/other/out.mp4\n",
);
return "download_000000000000.m3u8";
},
],
])("never publishes a downloaded playlist that %s", async (_name, entry) => {
const dir = makeTempDir();
const fetchMock = vi
.fn()
.mockResolvedValue(new Response(`#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\n${entry(dir)}\n`));
stubFetch(fetchMock);

await expect(downloadToTemp("https://cdn.example/clip.m3u8", dir, 1_000)).rejects.toMatchObject(
{
kind: "invalid_payload",
retryable: false,
},
);
expect(fetchMock).toHaveBeenCalledTimes(1);
const published = `download_${createHash("md5").update("https://cdn.example/clip.m3u8").digest("hex").slice(0, 12)}.m3u8`;
expect(readdirSync(dir)).not.toContain(published);
expect(temporaryDownloadEntries(dir)).toEqual([]);
});

it("publishes a downloaded playlist whose segments sit beside it", async () => {
const dir = makeTempDir();
stubFetch(vi.fn().mockResolvedValue(new Response("#EXTM3U\n#EXTINF:1,\nseg0.ts\n")));

const path = await downloadToTemp("https://cdn.example/clip.m3u8", dir, 1_000);

expect(readFileSync(path, "utf8")).toContain("seg0.ts");
});

it("rejects a BOM-prefixed remote error document without retrying", async () => {
const payload = Buffer.from("\uFEFF <!doctype html><html><body>denied</body></html>");
const fetchMock = vi.fn().mockResolvedValue(new Response(payload));
Expand Down
10 changes: 10 additions & 0 deletions packages/engine/src/utils/urlDownloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { Readable, Transform } from "stream";
import { pipeline } from "stream/promises";
import { cannotHardLink, createStagingDir } from "@hyperframes/core/atomic-file";
import { renameWithRetry } from "@hyperframes/core/rename-retry";
import { playlistLeavesItsFolder } from "./notMediaPayload.js";

const inFlightDownloads = new Map<string, Promise<string>>();
const signalScopes = new WeakMap<AbortSignal, number>();
Expand Down Expand Up @@ -1090,6 +1091,15 @@ async function runDownloadAttempt(
throw new UrlDownloadError("cancelled", false, "Download cancelled");
}
const integrity = await fetchToPartial(url, partialPath, controller, options, extendTimeout);
if (await playlistLeavesItsFolder(partialPath, localPath)) {
throw new UrlDownloadError(
"invalid_payload",
false,
"Download is a playlist naming files outside its folder",
integrity.status,
integrity,
);
}
let outcome = await syncAndPublishPartial(partialPath, localPath, timeoutMs, signal);
let publishedIntegrity = integrity;
if (outcome === "race_reused") {
Expand Down
Loading