Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(webv2): bound .invk expansion before it happens, not after

joshistoast557d83a19604
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts
index 6350a8d4d4..da109475a8 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts
@@ -1,6 +1,14 @@
import { describe, expect, it } from 'vitest';
-import { binaryEntry, readArchive, readEntryText, textEntry, writeArchive } from './archive';
+import {
+ binaryEntry,
+ createExpansionBudget,
+ INVK_MAX_ENTRIES,
+ readArchive,
+ readEntryText,
+ textEntry,
+ writeArchive,
+} from './archive';
import { InvkFormatError } from './format';
const toBytes = async (blob: Blob): Promise<Uint8Array> => new Uint8Array(await blob.arrayBuffer());
@@ -83,4 +91,97 @@ describe('writeArchive / readArchive', () => {
await expect(writeArchive(oversized as never)).rejects.toMatchObject({ reason: 'too-large' });
});
+
+ it('refuses to write more entries than the ceiling allows', async () => {
+ const tooMany = new Map(
+ Array.from({ length: INVK_MAX_ENTRIES + 1 }, (_, index) => [
+ `images/${index}.png`,
+ binaryEntry(new Uint8Array([1])),
+ ])
+ );
+
+ await expect(writeArchive(tooMany)).rejects.toMatchObject({ reason: 'too-large' });
+ });
+});
+
+/**
+ * The point of this guard is *when* it fires. `unzip` is fully buffered, so a
+ * total measured over its result describes a bomb that has already landed; the
+ * budget is what fflate consults per entry before inflating it. Testing it
+ * directly is how the sizes involved stay expressible — proving the same thing
+ * through `readArchive` would mean actually building a multi-gigabyte archive.
+ */
+describe('createExpansionBudget', () => {
+ const entry = (name: string, originalSize: number) => ({ name, originalSize });
+ const GIB = 1024 * 1024 * 1024;
+
+ it('accepts entries that fit and raises nothing', () => {
+ const budget = createExpansionBudget();
+
+ expect(budget.accept(entry('project.json', 1024))).toBe(true);
+ expect(budget.accept(entry('images/a.png', 4096))).toBe(true);
+ expect(budget.getRefusal()).toBeNull();
+ });
+
+ it('refuses the entry that crosses the byte ceiling, and every entry after it', () => {
+ const budget = createExpansionBudget();
+
+ expect(budget.accept(entry('images/a.png', GIB))).toBe(true);
+ // 2 GiB total is the ceiling itself, which still fits.
+ expect(budget.accept(entry('images/b.png', GIB))).toBe(true);
+ expect(budget.accept(entry('images/c.png', 1))).toBe(false);
+ expect(budget.accept(entry('images/d.png', 1))).toBe(false);
+
+ expect(budget.getRefusal()).toBeInstanceOf(InvkFormatError);
+ expect(budget.getRefusal()).toMatchObject({ reason: 'too-large' });
+ });
+
+ it('refuses past the entry ceiling before any of the excess is inflated', () => {
+ const budget = createExpansionBudget();
+
+ for (let index = 0; index < INVK_MAX_ENTRIES; index += 1) {
+ expect(budget.accept(entry(`images/${index}.png`, 1))).toBe(true);
+ }
+
+ expect(budget.accept(entry('images/one-too-many.png', 1))).toBe(false);
+ expect(budget.getRefusal()).toMatchObject({ reason: 'too-large' });
+ });
+
+ it('skips directory records without spending budget on them', () => {
+ const budget = createExpansionBudget();
+
+ for (let index = 0; index <= INVK_MAX_ENTRIES; index += 1) {
+ expect(budget.accept(entry(`images/${index}/`, 0))).toBe(false);
+ }
+
+ expect(budget.getRefusal()).toBeNull();
+ expect(budget.accept(entry('project.json', 1))).toBe(true);
+ });
+
+ it('keeps the first reason when both ceilings are crossed', () => {
+ const budget = createExpansionBudget();
+
+ budget.accept(entry('images/huge.png', 3 * GIB));
+ const first = budget.getRefusal();
+
+ budget.accept(entry('images/also-huge.png', 3 * GIB));
+
+ expect(budget.getRefusal()).toBe(first);
+ });
+});
+
+describe('readArchive with the budget in the path', () => {
+ it('round-trips an ordinary archive, so the filter is permissive at real sizes', async () => {
+ const blob = await writeArchive(
+ new Map([
+ ['project.json', textEntry('a'.repeat(4096))],
+ ['images/a.png', binaryEntry(new Uint8Array(4096))],
+ ])
+ );
+
+ const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
+
+ expect([...entries.keys()].sort()).toEqual(['images/a.png', 'project.json']);
+ expect(entries.get('images/a.png')!.byteLength).toBe(4096);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts
index dae9a55ffa..e83abcddac 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts
@@ -24,14 +24,33 @@ import { INVK_MIME_TYPE, InvkFormatError } from './format';
* Both directions are bounded. An `.invk` is a file someone was handed, and an
* unbounded `unzip` on a hostile one is a way to be handed an out-of-memory
* crash instead of an error message.
+ *
+ * Reading enforces its budget in fflate's entry filter rather than after the
+ * fact. `unzip` is fully buffered — by the time it hands back a record of
+ * entries, every one of them has already been inflated into memory, so a total
+ * measured there is a postmortem, not a guard. The filter is consulted per
+ * entry *before* inflation, with the declared uncompressed size from the
+ * central directory, which is the only place a ceiling can actually stop a zip
+ * bomb rather than describe one.
+ *
+ * A header that understates its entry's size does not get past this: fflate
+ * inflates into a buffer sized from that declaration and fails the decode when
+ * the stream overruns it, which surfaces as `not-a-project`.
*/
/**
* Ceiling for a single archive, in either direction. Large enough for a real
- * project with hundreds of full-resolution layers; small enough that a
- * malicious file fails fast rather than exhausting the tab.
+ * project with hundreds of full-resolution layers and a video or two; small
+ * enough that a malicious file fails fast rather than exhausting the tab.
+ *
+ * Deliberately well under 4 GiB. That is where ZIP32's 32-bit sizes and offsets
+ * stop being able to describe the file, and fflate writes no zip64 records — it
+ * reads them, but `zip()` has no path that emits them — so an archive at that
+ * boundary would be written structurally invalid rather than rejected. The
+ * browser gives out first anyway: `zip()` holds the entries and the packed
+ * output in memory at once.
*/
-export const INVK_MAX_ARCHIVE_BYTES = 4 * 1024 * 1024 * 1024;
+export const INVK_MAX_ARCHIVE_BYTES = 2 * 1024 * 1024 * 1024;
/** Ceiling on entry count, which bounds the cost of building the entry map. */
export const INVK_MAX_ENTRIES = 20_000;
@@ -58,6 +77,10 @@ export const readEntryText = (bytes: Uint8Array): string => new TextDecoder().de
/** Pack entries into a ZIP blob. Rejects with {@link InvkFormatError} past the size ceiling. */
export const writeArchive = async (entries: InvkArchiveEntries): Promise<Blob> => {
+ if (entries.size > INVK_MAX_ENTRIES) {
+ throw new InvkFormatError('too-large', `Project archive would hold ${entries.size} entries.`);
+ }
+
let total = 0;
for (const entry of entries.values()) {
@@ -90,6 +113,51 @@ export const writeArchive = async (entries: InvkArchiveEntries): Promise<Blob> =
return new Blob([packed as BlobPart], { type: INVK_MIME_TYPE });
};
+export interface InvkExpansionBudget {
+ /** Consulted per entry before it is inflated; `false` keeps it out of memory. */
+ accept: (file: { name: string; originalSize: number }) => boolean;
+ /** The refusal to raise once `unzip` has settled, or `null` if everything fit. */
+ getRefusal: () => InvkFormatError | null;
+}
+
+/**
+ * The read-side ceiling, as a value the ZIP walk consults rather than a total
+ * measured afterwards.
+ *
+ * The refusal is *returned* rather than thrown from `accept`, because a throw
+ * inside fflate's own walk unwinds through its decoder and arrives as a decode
+ * failure — the caller would be told the file was not a project when what
+ * actually happened is that it was too big. Refusing the entry and reporting
+ * afterwards keeps the two reasons distinct while still inflating nothing.
+ */
+export const createExpansionBudget = (): InvkExpansionBudget => {
+ let entryCount = 0;
+ let expandedBytes = 0;
+ let refusal: InvkFormatError | null = null;
+
+ return {
+ accept: (file) => {
+ // Directory records carry nothing and only inflate the count toward the
+ // guard.
+ if (file.name.endsWith('/')) {
+ return false;
+ }
+
+ entryCount += 1;
+ expandedBytes += file.originalSize;
+
+ if (entryCount > INVK_MAX_ENTRIES) {
+ refusal ??= new InvkFormatError('too-large', `Project archive holds more than ${INVK_MAX_ENTRIES} entries.`);
+ } else if (expandedBytes > INVK_MAX_ARCHIVE_BYTES) {
+ refusal ??= new InvkFormatError('too-large', `Project archive expands past ${INVK_MAX_ARCHIVE_BYTES} bytes.`);
+ }
+
+ return refusal === null;
+ },
+ getRefusal: () => refusal,
+ };
+};
+
/**
* Expand a ZIP into its entries. Anything that is not a readable ZIP surfaces as
* `not-a-project` rather than an fflate error, because from the caller's side
@@ -102,8 +170,9 @@ export const readArchive = async (bytes: Uint8Array): Promise<Map<string, Uint8A
}
const { unzip } = await import('fflate');
+ const budget = createExpansionBudget();
const expanded = await new Promise<Record<string, Uint8Array>>((resolve, reject) => {
- unzip(bytes, (error, data) => {
+ unzip(bytes, { filter: budget.accept }, (error, data) => {
if (error) {
reject(new InvkFormatError('not-a-project', error.message));
@@ -114,28 +183,11 @@ export const readArchive = async (bytes: Uint8Array): Promise<Map<string, Uint8A
});
});
- const entries = new Map<string, Uint8Array>();
- let total = 0;
-
- for (const [path, entry] of Object.entries(expanded)) {
- // Directory records come through as zero-length entries; they carry nothing
- // and only inflate the count toward the guard.
- if (path.endsWith('/')) {
- continue;
- }
-
- if (entries.size >= INVK_MAX_ENTRIES) {
- throw new InvkFormatError('too-large', `Project archive holds more than ${INVK_MAX_ENTRIES} entries.`);
- }
-
- total += entry.byteLength;
-
- if (total > INVK_MAX_ARCHIVE_BYTES) {
- throw new InvkFormatError('too-large', `Project archive expands past ${INVK_MAX_ARCHIVE_BYTES} bytes.`);
- }
+ const refusal = budget.getRefusal();
- entries.set(path, entry);
+ if (refusal) {
+ throw refusal;
}
- return entries;
+ return new Map(Object.entries(expanded));
};