Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(zip): complete partial metadata reads before parsing

Afloat587c4beb6fe3
diff --git a/docs/verification/README.md b/docs/verification/README.md
index f3a7fe1043..d56c231b70 100644
--- a/docs/verification/README.md
+++ b/docs/verification/README.md
@@ -244,6 +244,10 @@ The [rich tables fixture](rich-tables.md) checks Markdown tables and message-sco
CSV/TSV previews, large-file virtualization, sorting, search, export and keyboard
interaction in a disposable workspace.
+The [ZIP import fixture](zip-short-reads.md) checks XMind attachment uploads over
+the real HTTP route when filesystem reads return partial ZIP metadata, including
+the saved outline, rejection of a truncated archive and temporary-file cleanup.
+
The [recent files fixture](computer-files.md) mounts the Files panel with synthetic
digest rows and real message-scoped downloads from a disposable workspace.
diff --git a/docs/verification/zip-short-reads.md b/docs/verification/zip-short-reads.md
new file mode 100644
index 0000000000..0c612b5b7c
--- /dev/null
+++ b/docs/verification/zip-short-reads.md
@@ -0,0 +1,29 @@
+# ZIP metadata reads and XMind imports
+
+Run the focused checks:
+
+```sh
+pnpm exec vitest run server/zip-short-reads.test.ts server/zip-archive.test.ts server/xmind.test.ts
+OMB_VITEST_E2E=1 pnpm exec vitest run server/zip-short-reads.e2e.test.ts
+```
+
+The unit fixture reads a real ZIP from disk, limiting each metadata read while
+preserving its returned bytes. It covers the end record, central directory,
+local header and member name separately, repeated short reads for stored and
+deflated content, a UTF-8 filename, and an EOF after a partial read. Existing
+archive tests cover unsafe paths, links, entry limits and inflated-size limits.
+
+The HTTP fixture starts an isolated server with `launchVerificationServer`,
+then restarts that owned process with the `short-zip-reads.mjs` test hook. The
+hook limits reads of the temporary `map.xmind` to seven bytes and records the
+actual read sizes inside the fixture's data directory. It does not change the
+archive bytes or replace the ZIP parser, decompressor or upload route.
+
+The fixture posts a valid XMind archive to `/api/files`, checks the 201 response
+and the saved Markdown outline, then posts a truncated archive and checks the
+400 response. Both paths must remove their temporary import directories.
+The fixture stops its child and removes its temporary home when it finishes.
+
+This is deterministic filesystem fault injection, not a measurement of how
+frequently a particular local or network filesystem returns short reads. It
+does not exercise the composer UI or download an engine binary.
diff --git a/server/testing/short-zip-reads.mjs b/server/testing/short-zip-reads.mjs
new file mode 100644
index 0000000000..0e78ae47bd
--- /dev/null
+++ b/server/testing/short-zip-reads.mjs
@@ -0,0 +1,22 @@
+import { appendFileSync } from "node:fs";
+import fs from "node:fs/promises";
+import { syncBuiltinESMExports } from "node:module";
+import { basename, join } from "node:path";
+
+const open = fs.open;
+fs.open = async (path, ...args) => {
+ const handle = await open(path, ...args);
+ if (basename(String(path)) === "map.xmind") {
+ const read = handle.read.bind(handle);
+ handle.read = async (buffer, offset, length, position) => {
+ const result = await read(buffer, offset, Math.min(length, 7), position);
+ if (result.bytesRead < length) {
+ appendFileSync(join(process.env.OMB_DATA_DIR, "zip-short-reads.jsonl"),
+ JSON.stringify({ requested: length, returned: result.bytesRead }) + "\n");
+ }
+ return result;
+ };
+ }
+ return handle;
+};
+syncBuiltinESMExports();
diff --git a/server/zip-archive.ts b/server/zip-archive.ts
index 166298ccef..78dac9340d 100644
--- a/server/zip-archive.ts
+++ b/server/zip-archive.ts
@@ -2,7 +2,7 @@
// is parsed from the end of the file, and each member is inflated straight to disk, never past the size it declares.
// No ZIP64, no encryption, no links: a pinned vendor archive needs none of them.
import { createReadStream, createWriteStream } from "node:fs";
-import { mkdir, open, writeFile } from "node:fs/promises";
+import { mkdir, open, writeFile, type FileHandle } from "node:fs/promises";
import { join } from "node:path";
import { Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
@@ -25,6 +25,16 @@ const UNIX_TYPE_MASK = 0o170000;
const UNIX_FILE = 0o100000;
const UNIX_DIRECTORY = 0o040000;
+async function fillBuffer(handle: FileHandle, buffer: Buffer, position: number): Promise<boolean> {
+ let filled = 0;
+ while (filled < buffer.length) {
+ const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, position + filled);
+ if (bytesRead === 0) return false;
+ filled += bytesRead;
+ }
+ return true;
+}
+
/** The members a ZIP's central directory lists; more than `maxEntries` is refused. */
export async function readZipDirectory(path: string, maxEntries: number): Promise<ZipMember[]> {
const handle = await open(path, "r");
@@ -33,7 +43,7 @@ export async function readZipDirectory(path: string, maxEntries: number): Promis
const tailBytes = Math.min(info.size, MAX_EOCD_BYTES);
const tail = Buffer.alloc(tailBytes);
const tailOffset = info.size - tailBytes;
- if ((await handle.read(tail, 0, tailBytes, tailOffset)).bytesRead !== tailBytes) {
+ if (!await fillBuffer(handle, tail, tailOffset)) {
throw new Error("The verified archive was truncated.");
}
let eocd = -1;
@@ -61,7 +71,7 @@ export async function readZipDirectory(path: string, maxEntries: number): Promis
) throw new Error("The verified archive uses an unsupported ZIP layout.");
const directory = Buffer.alloc(directoryBytes);
- if ((await handle.read(directory, 0, directoryBytes, directoryOffset)).bytesRead !== directoryBytes) {
+ if (!await fillBuffer(handle, directory, directoryOffset)) {
throw new Error("The verified archive directory was truncated.");
}
const entries: ZipMember[] = [];
@@ -108,7 +118,7 @@ async function memberDataOffset(path: string, entry: ZipMember): Promise<number>
const handle = await open(path, "r");
try {
const header = Buffer.alloc(30);
- if ((await handle.read(header, 0, header.length, entry.localHeaderOffset)).bytesRead !== header.length) {
+ if (!await fillBuffer(handle, header, entry.localHeaderOffset)) {
throw new Error("A verified archive member header was truncated.");
}
const nameBytes = header.readUInt16LE(26);
@@ -119,7 +129,7 @@ async function memberDataOffset(path: string, entry: ZipMember): Promise<number>
|| (header.readUInt16LE(6) & 1) !== 0
) throw new Error("A verified archive member header is invalid.");
const name = Buffer.alloc(nameBytes);
- if ((await handle.read(name, 0, nameBytes, entry.localHeaderOffset + 30)).bytesRead !== nameBytes) {
+ if (!await fillBuffer(handle, name, entry.localHeaderOffset + 30)) {
throw new Error("A verified archive member name was truncated.");
}
if (name.toString("utf8") !== entry.name) throw new Error("A verified archive member name did not match its directory.");
diff --git a/server/zip-short-reads.e2e.test.ts b/server/zip-short-reads.e2e.test.ts
new file mode 100644
index 0000000000..e0c0771a49
--- /dev/null
+++ b/server/zip-short-reads.e2e.test.ts
@@ -0,0 +1,54 @@
+import { spawn } from "node:child_process";
+import { closeSync, openSync, readFileSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { expect, it } from "vitest";
+import { launchVerificationServer, verificationServerArgs, verificationServerEnvironment } from "../scripts/control-omb.ts";
+import { waitForExit } from "./testing/cleanup.ts";
+import { buildZip } from "./testing/zip-fixture.ts";
+
+it("imports an XMind attachment over HTTP when disk reads return partial metadata", async () => {
+ const fixture = await launchVerificationServer();
+ const { dataDir, logPath, url } = fixture.info;
+ let server = fixture.child;
+ try {
+ await waitForExit(server, { signal: "SIGTERM" });
+ const env = verificationServerEnvironment({}, dataDir, Number(new URL(url).port));
+ const args = verificationServerArgs(env);
+ const log = openSync(logPath, "a", 0o600);
+ try {
+ server = spawn(process.execPath, [
+ ...args.slice(0, -1), "--import", new URL("./testing/short-zip-reads.mjs", import.meta.url).href, args.at(-1)!,
+ ], { cwd: fileURLToPath(new URL("..", import.meta.url)), env, stdio: ["ignore", log, log] });
+ } finally {
+ closeSync(log);
+ }
+ await expect.poll(async () => {
+ try { return (await fetch(`${url}/api/health`)).ok; } catch { return false; }
+ }, { timeout: 30_000 }).toBe(true);
+
+ const bytes = buildZip([{ name: "content.json", data: JSON.stringify([
+ { title: "Plan", rootTopic: { title: "Ship", children: { attached: [{ title: "Verify" }] } } },
+ ]) }]);
+ const upload = async (body: Buffer) => fetch(`${url}/api/files?name=Plan.xmind`, {
+ method: "POST", headers: { "content-type": "application/vnd.xmind.workbook" }, body,
+ });
+ const response = await upload(bytes);
+ const saved = await response.json() as { path: string; name: string; mime: string; error?: string };
+ expect(response.status, JSON.stringify(saved)).toBe(201);
+ expect(saved).toMatchObject({ name: "Plan.xmind.md", mime: "text/markdown" });
+ expect(readFileSync(saved.path, "utf8")).toBe("# Plan\n\n- Ship\n - Verify\n");
+ const shortReads = readFileSync(join(dataDir, "zip-short-reads.jsonl"), "utf8").trim().split("\n");
+ expect(shortReads.length).toBeGreaterThan(4);
+ expect(shortReads.map((line) => JSON.parse(line))).toEqual(
+ expect.arrayContaining([expect.objectContaining({ returned: 7 })]),
+ );
+ const broken = await upload(bytes.subarray(0, bytes.length - 8));
+ expect(broken.status).toBe(400);
+ expect(await broken.json()).toMatchObject({ error: "not a readable XMind file" });
+ expect(readdirSync(join(dataDir, "tmp")).filter((name) => name.startsWith("omb-xmind-"))).toEqual([]);
+ } finally {
+ await waitForExit(server, { signal: "SIGTERM" });
+ await fixture.close();
+ }
+}, 60_000);
diff --git a/server/zip-short-reads.test.ts b/server/zip-short-reads.test.ts
new file mode 100644
index 0000000000..388cdcfa6d
--- /dev/null
+++ b/server/zip-short-reads.test.ts
@@ -0,0 +1,68 @@
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, it, vi } from "vitest";
+import { extractZip } from "./zip-archive.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+import { buildZip } from "./testing/zip-fixture.ts";
+
+const reads = vi.hoisted(() => ({ calls: 0, shortAt: 0, zeroAt: 0, maxBytes: Infinity, shortened: 0 }));
+vi.mock("node:fs/promises", async (importOriginal) => {
+ const fs = await importOriginal<typeof import("node:fs/promises")>();
+ return { ...fs, open: async (...args: Parameters<typeof fs.open>) => {
+ const handle = await fs.open(...args);
+ if (String(args[0]).endsWith("fixture.zip")) {
+ const read = handle.read.bind(handle);
+ handle.read = (async (buffer: Buffer, offset: number, length: number, position: number) => {
+ reads.calls += 1;
+ if (reads.calls === reads.zeroAt) return { bytesRead: 0, buffer };
+ const limit = reads.calls === reads.shortAt ? 3 : reads.maxBytes;
+ if (length > limit) reads.shortened += 1;
+ return read(buffer, offset, Math.min(length, limit), position);
+ }) as typeof handle.read;
+ }
+ return handle;
+ } };
+});
+
+let scratch = "";
+afterEach(async () => {
+ Object.assign(reads, { calls: 0, shortAt: 0, zeroAt: 0, maxBytes: Infinity, shortened: 0 });
+ if (scratch) await removeTempDir(scratch);
+ scratch = "";
+});
+
+function archive(method: 0 | 8 = 8): { file: string; out: string } {
+ scratch = mkdtempSync(join(tmpdir(), "omb-zip-short-"));
+ const file = join(scratch, "fixture.zip"), out = join(scratch, "out");
+ writeFileSync(file, buildZip([{ name: "nested/世界.txt", data: "complete contents\n", method }]));
+ mkdirSync(out);
+ return { file, out };
+}
+
+it.each(["end record", "central directory", "local header", "member name"])(
+ "finishes a short %s read before parsing the ZIP",
+ async (stage) => {
+ const { file, out } = archive();
+ reads.shortAt = ["end record", "central directory", "local header", "member name"].indexOf(stage) + 1;
+ await extractZip(file, out, { maxEntries: 10 });
+ expect(reads.shortened).toBe(1);
+ expect(readFileSync(join(out, "nested", "世界.txt"), "utf8")).toBe("complete contents\n");
+ },
+);
+
+it.each([0, 8] as const)("extracts compression method %s when every metadata read stops after seven bytes", async (method) => {
+ const { file, out } = archive(method);
+ reads.maxBytes = 7;
+ await extractZip(file, out, { maxEntries: 10 });
+ expect(reads.shortened).toBeGreaterThan(4);
+ expect(readFileSync(join(out, "nested", "世界.txt"), "utf8")).toBe("complete contents\n");
+});
+
+it("rejects EOF after a partial metadata read without retrying forever", async () => {
+ const { file, out } = archive();
+ reads.shortAt = 1;
+ reads.zeroAt = 2;
+ await expect(extractZip(file, out, { maxEntries: 10 })).rejects.toThrow("The verified archive was truncated.");
+ expect(reads.calls).toBeLessThanOrEqual(2);
+});