Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Stems: a song's stems download and unpack within fixed limits, and an archive that repeats or misstates its files is refused

Claude1747cf437c3a
diff --git a/src/server/providers/fal.ts b/src/server/providers/fal.ts
index d0a52a02..0a1f220e 100644
--- a/src/server/providers/fal.ts
+++ b/src/server/providers/fal.ts
@@ -47,11 +47,51 @@ async function uploadSong(upload: { endpoint: string; purpose: string }, fileUrl
return res.id;
}
+/** The most a stems download may be, and how long it may take: past either, it stops and the run fails. */
+const STEMS_MAX_BYTES = 256 * 1024 * 1024;
+const STEMS_WAIT_MS = 3 * 60 * 1000;
+
+/** A download read with a byte count: past `max` bytes (declared or streamed) it stops at once, never held whole. */
+async function bytesWithin(res: Response, max: number): Promise<Buffer> {
+ const tooBig = () => new Error("The stems download is larger than Fuobe keeps from one result");
+ if (Number(res.headers.get("content-length")) > max) {
+ res.body?.cancel().catch(() => {});
+ throw tooBig();
+ }
+ const reader = res.body?.getReader();
+ if (!reader) return Buffer.alloc(0);
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > max) {
+ reader.cancel().catch(() => {});
+ throw tooBig();
+ }
+ chunks.push(value);
+ }
+ return Buffer.concat(chunks, total);
+}
+
/** The stems a song tool answers with in one zip (Mureka's zip_url), one result each, named by their file (meta.stem). */
-async function stemsFromZip(zipUrl: string): Promise<{ url: string; kind: "audio"; contentType: string; meta: { stem: string } }[]> {
- const res = await fetch(zipUrl);
- if (!res.ok) throw new Error(`The stems couldn't be downloaded (${res.status})`);
- const files = unzip(Buffer.from(await res.arrayBuffer())).filter((f) => AUDIO_FILE.test(f.name));
+export async function stemsFromZip(
+ zipUrl: string,
+ limits: { maxBytes?: number; waitMs?: number } = {},
+): Promise<{ url: string; kind: "audio"; contentType: string; meta: { stem: string } }[]> {
+ const maxBytes = limits.maxBytes ?? STEMS_MAX_BYTES;
+ let zipped: Buffer;
+ try {
+ const res = await fetch(zipUrl, { signal: AbortSignal.timeout(limits.waitMs ?? STEMS_WAIT_MS) });
+ if (!res.ok) throw new Error(`The stems couldn't be downloaded (${res.status})`);
+ zipped = await bytesWithin(res, maxBytes);
+ } catch (e) {
+ const name = (e as Error).name;
+ if (name === "TimeoutError" || name === "AbortError") throw new Error("The stems took too long to download. Try again.");
+ throw e;
+ }
+ const files = (await unzip(zipped, { maxBytes: 2 * maxBytes })).filter((f) => AUDIO_FILE.test(f.name));
if (!files.length) throw new Error("The stems archive held no audio");
return files.map((f) => {
const ext = AUDIO_FILE.exec(f.name)![1].toLowerCase();
diff --git a/src/server/unzip.ts b/src/server/unzip.ts
index 7e09c4e4..7f8e90fe 100644
--- a/src/server/unzip.ts
+++ b/src/server/unzip.ts
@@ -1,14 +1,22 @@
import "server-only";
-import { inflateRawSync } from "node:zlib";
+import { promisify } from "node:util";
+import { inflateRaw } from "node:zlib";
+
+const inflate = promisify(inflateRaw);
/**
* The files of a zip archive (stored or deflated entries), read from its central directory: what a provider answers with
* when its result is several files in one download (Mureka's stems). Directories and macOS resource forks are left out.
- * Bounded: at most `maxFiles` entries and `maxBytes` of unpacked data, else it throws.
+ * Bounded by what is actually unpacked, never by what the headers claim: at most `maxFiles` entries and `maxBytes` of
+ * unpacked data (each entry inflates into what is left of that budget, off the event loop). Entries that share or overlap
+ * their bytes, run past the archive, or unpack to a length other than the one declared are refused, so a crafted archive
+ * can't multiply one small entry into many large files.
*/
-export function unzip(buf: Buffer, o: { maxFiles?: number; maxBytes?: number } = {}): { name: string; data: Buffer }[] {
+export async function unzip(buf: Buffer, o: { maxFiles?: number; maxBytes?: number } = {}): Promise<{ name: string; data: Buffer }[]> {
const maxFiles = o.maxFiles ?? 64;
const maxBytes = o.maxBytes ?? 512 * 1024 * 1024;
+ const tooMuch = () => new Error("The archive unpacks to more than Fuobe keeps from one result");
+ const damaged = () => new Error("The archive's entries are damaged");
// The end of central directory record: its signature within the last 64 KiB + 22 bytes.
let eocd = -1;
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 0xffff); i--) {
@@ -19,12 +27,18 @@ export function unzip(buf: Buffer, o: { maxFiles?: number; maxBytes?: number } =
}
if (eocd < 0) throw new Error("Not a zip archive");
const count = buf.readUInt16LE(eocd + 10);
- let at = buf.readUInt32LE(eocd + 16);
+ const dirStart = buf.readUInt32LE(eocd + 16);
+ if (count === 0xffff || dirStart === 0xffffffff) throw new Error("The archive is in a format Fuobe can't read (ZIP64)");
if (count > maxFiles) throw new Error(`The archive holds ${count} files, more than ${maxFiles}`);
+ if (dirStart > eocd) throw new Error("The archive's directory is damaged");
const out: { name: string; data: Buffer }[] = [];
+ // Each entry's bytes (local header to the end of its data): no two may share any.
+ const spans: [number, number][] = [];
let total = 0;
+ let at = dirStart;
for (let n = 0; n < count; n++) {
- if (at + 46 > buf.length || buf.readUInt32LE(at) !== 0x02014b50) throw new Error("The archive's directory is damaged");
+ if (at + 46 > eocd || buf.readUInt32LE(at) !== 0x02014b50) throw new Error("The archive's directory is damaged");
+ const flags = buf.readUInt16LE(at + 8);
const method = buf.readUInt16LE(at + 10);
const packed = buf.readUInt32LE(at + 20);
const size = buf.readUInt32LE(at + 24);
@@ -35,13 +49,31 @@ export function unzip(buf: Buffer, o: { maxFiles?: number; maxBytes?: number } =
const name = buf.subarray(at + 46, at + 46 + nameLen).toString("utf8");
at += 46 + nameLen + extraLen + commentLen;
if (name.endsWith("/") || name.startsWith("__MACOSX/") || name.split("/").pop()!.startsWith("._")) continue;
- if (local + 30 > buf.length || buf.readUInt32LE(local) !== 0x04034b50) throw new Error("The archive's entries are damaged");
+ if (flags & 0x1) throw new Error("The archive is password-protected");
+ if (local + 30 > dirStart || buf.readUInt32LE(local) !== 0x04034b50) throw damaged();
const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
- const raw = buf.subarray(start, start + packed);
- total += size;
- if (total > maxBytes) throw new Error("The archive unpacks to more than Fuobe keeps from one result");
- const data = method === 0 ? Buffer.from(raw) : method === 8 ? inflateRawSync(raw, { maxOutputLength: maxBytes }) : null;
- if (!data) throw new Error(`The archive uses a compression Fuobe can't read (method ${method})`);
+ const end = start + packed;
+ if (end > dirStart) throw damaged();
+ if (spans.some(([a, b]) => local < b && a < end)) throw damaged();
+ spans.push([local, end]);
+ // The declared size turns an honest oversized archive away before any work; the bytes unpacked are what count.
+ if (total + size > maxBytes) throw tooMuch();
+ const raw = buf.subarray(start, end);
+ let data: Buffer;
+ if (method === 0) data = Buffer.from(raw);
+ else if (method === 8) {
+ const room = maxBytes - total;
+ try {
+ // One byte past the room left, so an entry that would overflow it is caught rather than cut short.
+ data = await inflate(raw, { maxOutputLength: room + 1 });
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === "ERR_BUFFER_TOO_LARGE") throw tooMuch();
+ throw damaged();
+ }
+ } else throw new Error(`The archive uses a compression Fuobe can't read (method ${method})`);
+ total += data.length;
+ if (total > maxBytes) throw tooMuch();
+ if (data.length !== size) throw damaged();
out.push({ name, data });
}
return out;
diff --git a/tests/music3-open.test.ts b/tests/music3-open.test.ts
index a24910e5..7ee29d3f 100644
--- a/tests/music3-open.test.ts
+++ b/tests/music3-open.test.ts
@@ -2,6 +2,7 @@ import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
+import zlib from "node:zlib";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { GenInput, ModelDef } from "@/lib/catalog/types";
import type { MediaInfo } from "@/lib/media-probe";
@@ -18,7 +19,7 @@ const { getModel } = await import("@/lib/catalog");
const { resolveWorkflowId } = await import("@/lib/comfy-variants");
const { buildLicenceList, licenceInfo, workflowLicence } = await import("@/lib/licences");
const { setSetting } = await import("@/server/settings");
-const { falProvider } = await import("@/server/providers/fal");
+const { falProvider, stemsFromZip } = await import("@/server/providers/fal");
const { zip } = await import("@/server/zip");
const { unzip } = await import("@/server/unzip");
@@ -170,10 +171,79 @@ describe("the fal provider's song tools", () => {
expect(Buffer.from(r.outputs[0].url.split(",")[1], "base64").toString()).toBe("ID3vocals");
});
- it("reads an archive's files, and refuses a damaged or oversized one", () => {
- expect(unzip(stems).map((f) => f.name)).toEqual(["stems/vocals.mp3", "stems/drums.wav", "readme.txt"]);
- expect(() => unzip(Buffer.from("not a zip at all, just words"))).toThrow("Not a zip archive");
- expect(() => unzip(stems, { maxFiles: 2 })).toThrow(/more than 2/);
- expect(() => unzip(stems, { maxBytes: 4 })).toThrow(/more than Fuobe keeps/);
+ it("reads an archive's files, and refuses a damaged or oversized one", async () => {
+ expect((await unzip(stems)).map((f) => f.name)).toEqual(["stems/vocals.mp3", "stems/drums.wav", "readme.txt"]);
+ await expect(unzip(Buffer.from("not a zip at all, just words"))).rejects.toThrow("Not a zip archive");
+ await expect(unzip(stems, { maxFiles: 2 })).rejects.toThrow(/more than 2/);
+ await expect(unzip(stems, { maxBytes: 4 })).rejects.toThrow(/more than Fuobe keeps/);
+ });
+
+ it("counts the bytes it unpacks, not the sizes a crafted archive declares", async () => {
+ const MiB = 1024 * 1024;
+ // One deflated entry (8 MiB of zeros in about 8 KB), listed `copies` times in the directory, each claiming `declared` bytes.
+ const crafted = (copies: number, declared: number, opts: { offsets?: number[] } = {}) => {
+ const data = zlib.deflateRawSync(Buffer.alloc(8 * MiB));
+ const name = Buffer.from("stems/vocals.wav");
+ const local = Buffer.alloc(30);
+ local.writeUInt32LE(0x04034b50, 0);
+ local.writeUInt16LE(8, 8);
+ local.writeUInt32LE(data.length, 18);
+ local.writeUInt32LE(declared, 22);
+ local.writeUInt16LE(name.length, 26);
+ const head = Buffer.concat([local, name, data]);
+ const dir = Array.from({ length: copies }, (_, i) => {
+ const c = Buffer.alloc(46);
+ c.writeUInt32LE(0x02014b50, 0);
+ c.writeUInt16LE(8, 10);
+ c.writeUInt32LE(data.length, 20);
+ c.writeUInt32LE(declared, 24);
+ c.writeUInt16LE(name.length, 28);
+ c.writeUInt32LE(opts.offsets?.[i] ?? 0, 42);
+ return Buffer.concat([c, name]);
+ });
+ const cd = Buffer.concat(dir);
+ const end = Buffer.alloc(22);
+ end.writeUInt32LE(0x06054b50, 0);
+ end.writeUInt16LE(copies, 8);
+ end.writeUInt16LE(copies, 10);
+ end.writeUInt32LE(cd.length, 12);
+ end.writeUInt32LE(head.length, 16);
+ return Buffer.concat([head, cd, end]);
+ };
+ // Twenty directory entries over one local entry: refused before a second inflate, not 160 MiB unpacked.
+ await expect(unzip(crafted(20, 0))).rejects.toThrow("damaged");
+ await expect(unzip(crafted(2, 8 * MiB, { offsets: [0, 4] }))).rejects.toThrow("damaged");
+ // A size declared as 0 that unpacks to 8 MiB: refused, and never past what is left of the budget.
+ await expect(unzip(crafted(1, 0))).rejects.toThrow("damaged");
+ await expect(unzip(crafted(1, 0), { maxBytes: 2 * MiB })).rejects.toThrow(/more than Fuobe keeps/);
+ // An honest entry still reads.
+ expect((await unzip(crafted(1, 8 * MiB)))[0].data.length).toBe(8 * MiB);
+ });
+
+ it("stops a stems download past its byte limit, with or without a declared length, and past its time limit", async () => {
+ const big = http.createServer((req, res) => {
+ if (req.url === "/declared") {
+ res.writeHead(200, { "Content-Length": String(4096) });
+ return res.end(Buffer.alloc(4096));
+ }
+ if (req.url === "/streamed") {
+ res.writeHead(200);
+ res.write(Buffer.alloc(3000));
+ res.write(Buffer.alloc(3000));
+ return res.end();
+ }
+ res.writeHead(200);
+ res.write(Buffer.alloc(10)); // then nothing more
+ });
+ await new Promise<void>((r) => big.listen(0, "127.0.0.1", r));
+ const at = `http://127.0.0.1:${(big.address() as { port: number }).port}`;
+ try {
+ await expect(stemsFromZip(`${at}/declared`, { maxBytes: 1024 })).rejects.toThrow(/larger than Fuobe keeps/);
+ await expect(stemsFromZip(`${at}/streamed`, { maxBytes: 4000 })).rejects.toThrow(/larger than Fuobe keeps/);
+ await expect(stemsFromZip(`${at}/stalls`, { waitMs: 300 })).rejects.toThrow(/took too long/);
+ } finally {
+ big.closeAllConnections();
+ await new Promise<void>((r) => big.close(() => r()));
+ }
});
});