Skip to content

Commit 9bd50c8

Browse files
authored
fix(media): bound local reads and invalidate cleaned attachment paths (#130885)
1 parent 9b612a6 commit 9bd50c8

6 files changed

Lines changed: 213 additions & 103 deletions

File tree

‎src/media-understanding/attachments.cache.test.ts‎

Lines changed: 112 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
// Attachment cache tests cover MIME detection after local and remote bytes are available.
1+
// Attachment cache tests cover bounded reads, MIME detection, and temporary-file ownership.
22
import fs from "node:fs/promises";
33
import path from "node:path";
44
import JSZip from "jszip";
5-
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest";
66
import { withTestDir } from "../test-helpers/temp-dir.js";
77
import { MediaAttachmentCache } from "./attachments.js";
88

@@ -35,7 +35,7 @@ const PNG_1X1 = Buffer.from(
3535
);
3636
const AMBIGUOUS_WEBM = Buffer.from("1a45dfa3874282847765626d", "hex");
3737

38-
describe("media understanding attachment MIME detection", () => {
38+
describe("media understanding attachment cache", () => {
3939
afterEach(() => {
4040
vi.restoreAllMocks();
4141
buildRandomTempFilePathMock.mockReset();
@@ -79,6 +79,111 @@ describe("media understanding attachment MIME detection", () => {
7979
expect(result.mime).toBe("image/png");
8080
});
8181

82+
it("bounds bytes consumed when a local file grows after stat", async () => {
83+
await withTestDir({ prefix: "openclaw-media-cache-growth-" }, async (base) => {
84+
const attachmentPath = path.join(base, "growing.png");
85+
await fs.writeFile(attachmentPath, PNG_1X1);
86+
const maxBytes = PNG_1X1.length;
87+
const open = fs.open.bind(fs);
88+
let consumed = 0;
89+
let grew = false;
90+
const growBeforeRead = async () => {
91+
if (!grew) {
92+
grew = true;
93+
await fs.appendFile(attachmentPath, Buffer.alloc(4096));
94+
}
95+
};
96+
vi.spyOn(fs, "open").mockImplementation(async (...args) => {
97+
const handle = await open(...args);
98+
const read = handle.read.bind(handle);
99+
vi.spyOn(handle, "read").mockImplementation(async (...readArgs) => {
100+
await growBeforeRead();
101+
const result = await read(...readArgs);
102+
consumed += result.bytesRead;
103+
return result;
104+
});
105+
const readFile = handle.readFile.bind(handle);
106+
vi.spyOn(handle, "readFile").mockImplementation(async (...readArgs) => {
107+
await growBeforeRead();
108+
const result = await readFile(...readArgs);
109+
consumed += result.length;
110+
return result;
111+
});
112+
return handle;
113+
});
114+
const cache = new MediaAttachmentCache([{ index: 0, path: attachmentPath }], {
115+
localPathRoots: [base],
116+
includeDefaultLocalPathRoots: false,
117+
});
118+
119+
await expect(
120+
cache.getBuffer({ attachmentIndex: 0, maxBytes, timeoutMs: 1000 }),
121+
).rejects.toMatchObject({ reason: "maxBytes" });
122+
expect(consumed).toBeGreaterThan(0);
123+
expect(consumed).toBeLessThanOrEqual(maxBytes + 1);
124+
});
125+
});
126+
127+
it.each(["local", "staged"] as const)(
128+
"enforces a zero-byte path limit for %s files",
129+
async (source) => {
130+
expectTypeOf<Parameters<MediaAttachmentCache["getPath"]>[0]>().toEqualTypeOf<{
131+
attachmentIndex: number;
132+
maxBytes: number;
133+
timeoutMs: number;
134+
}>();
135+
await withTestDir({ prefix: "openclaw-media-cache-path-limit-" }, async (base) => {
136+
const attachmentPath = path.join(base, "photo.png");
137+
await fs.writeFile(attachmentPath, PNG_1X1);
138+
buildRandomTempFilePathMock.mockReturnValue(path.join(base, "staged.png"));
139+
readRemoteMediaBufferMock.mockResolvedValue({ buffer: PNG_1X1, fileName: "photo.png" });
140+
const attachment =
141+
source === "local"
142+
? { index: 0, path: attachmentPath }
143+
: { index: 0, url: "https://example.com/photo.png" };
144+
const cache = new MediaAttachmentCache([attachment], { localPathRoots: [base] });
145+
const request = { attachmentIndex: 0, maxBytes: PNG_1X1.length, timeoutMs: 1000 };
146+
try {
147+
await expect(cache.getPath(request)).resolves.toHaveProperty("path");
148+
await expect(cache.getPath({ ...request, maxBytes: 0 })).rejects.toMatchObject({
149+
reason: "maxBytes",
150+
});
151+
} finally {
152+
await cache.cleanup();
153+
}
154+
});
155+
},
156+
);
157+
158+
it.each(["cache", "returned"] as const)(
159+
"restages files after %s cleanup",
160+
async (cleanupOwner) => {
161+
await withTestDir({ prefix: "openclaw-media-cache-restage-" }, async (base) => {
162+
buildRandomTempFilePathMock
163+
.mockReturnValueOnce(path.join(base, "first.png"))
164+
.mockReturnValueOnce(path.join(base, "second.png"));
165+
readRemoteMediaBufferMock.mockResolvedValue({ buffer: PNG_1X1, fileName: "photo.png" });
166+
const cache = new MediaAttachmentCache([
167+
{ index: 0, url: "https://example.com/photo.png" },
168+
]);
169+
const request = { attachmentIndex: 0, maxBytes: PNG_1X1.length, timeoutMs: 1000 };
170+
try {
171+
const first = await cache.getPath(request);
172+
await (cleanupOwner === "cache" ? cache.cleanup() : first.cleanup?.());
173+
await expect(fs.stat(first.path)).rejects.toMatchObject({ code: "ENOENT" });
174+
const second = await cache.getPath(request);
175+
await expect(fs.readFile(second.path)).resolves.toEqual(PNG_1X1);
176+
await first.cleanup?.();
177+
expect((await cache.getPath(request)).path).toBe(second.path);
178+
expect(readRemoteMediaBufferMock).toHaveBeenCalledTimes(1);
179+
} finally {
180+
await cache.cleanup();
181+
}
182+
expect(await fs.readdir(base)).toEqual([]);
183+
});
184+
},
185+
);
186+
82187
it("uses fetched audio metadata when declared MIME is stale for ambiguous WebM", async () => {
83188
const url = "https://example.com/voice.webm";
84189
readRemoteMediaBufferMock.mockResolvedValue({
@@ -132,9 +237,9 @@ describe("media understanding attachment MIME detection", () => {
132237
});
133238
const cache = new MediaAttachmentCache([{ index: 0, url: "https://example.com/photo.png" }]);
134239

135-
await expect(cache.getPath({ attachmentIndex: 0, timeoutMs: 1_000 })).rejects.toBe(
136-
writeError,
137-
);
240+
await expect(
241+
cache.getPath({ attachmentIndex: 0, maxBytes: 1024, timeoutMs: 1_000 }),
242+
).rejects.toBe(writeError);
138243
await cache.cleanup();
139244

140245
expect(await fs.readdir(base)).toEqual([]);
@@ -156,7 +261,7 @@ describe("media understanding attachment MIME detection", () => {
156261
});
157262
vi.spyOn(fs, "unlink").mockRejectedValueOnce(cleanupError);
158263
const cache = new MediaAttachmentCache([{ index: 0, url: "https://example.com/photo.png" }]);
159-
const request = { attachmentIndex: 0, timeoutMs: 1_000 };
264+
const request = { attachmentIndex: 0, maxBytes: 1024, timeoutMs: 1_000 };
160265

161266
await expect(cache.getPath(request)).rejects.toBe(writeError);
162267
expect(await fs.readdir(base)).toEqual(["failed.png"]);

‎src/media-understanding/attachments.cache.ts‎

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { MediaUnderstandingSkipError } from "../../packages/media-understanding-
1515
import { resolveStateDir } from "../config/paths.js";
1616
import { logVerbose, shouldLogVerbose } from "../globals.js";
1717
import { isAbortError } from "../infra/abort-signal.js";
18+
import { readFileHandleBounded } from "../infra/fs-safe-advanced.js";
1819
import { FsSafeError, openLocalFileSafely } from "../infra/fs-safe.js";
1920
import type { SsrFPolicy } from "../infra/net/ssrf.js";
2021
import {
@@ -328,14 +329,14 @@ export class MediaAttachmentCache {
328329
/** Returns a local path for providers that cannot accept buffers, creating a temp file if needed. */
329330
async getPath(params: {
330331
attachmentIndex: number;
331-
maxBytes?: number;
332+
maxBytes: number;
332333
timeoutMs: number;
333334
}): Promise<MediaPathResult> {
334335
const entry = await this.ensureEntry(params.attachmentIndex);
335336
if (entry.resolvedPath) {
336337
try {
337338
const size = await this.ensureLocalStat(entry);
338-
if (entry.resolvedPath && params.maxBytes && size !== undefined && size > params.maxBytes) {
339+
if (entry.resolvedPath && size !== undefined && size > params.maxBytes) {
339340
throw new MediaUnderstandingSkipError(
340341
"maxBytes",
341342
`Attachment ${params.attachmentIndex + 1} exceeds maxBytes ${params.maxBytes}`,
@@ -355,7 +356,7 @@ export class MediaAttachmentCache {
355356
try {
356357
const size = await this.ensureLocalStat(entry);
357358
if (entry.resolvedPath) {
358-
if (params.maxBytes && size !== undefined && size > params.maxBytes) {
359+
if (size !== undefined && size > params.maxBytes) {
359360
throw new MediaUnderstandingSkipError(
360361
"maxBytes",
361362
`Attachment ${params.attachmentIndex + 1} exceeds maxBytes ${params.maxBytes}`,
@@ -371,7 +372,7 @@ export class MediaAttachmentCache {
371372
}
372373

373374
if (entry.tempPath) {
374-
if (params.maxBytes && entry.bufferResult && entry.bufferResult.size > params.maxBytes) {
375+
if (entry.bufferResult && entry.bufferResult.size > params.maxBytes) {
375376
throw new MediaUnderstandingSkipError(
376377
"maxBytes",
377378
`Attachment ${params.attachmentIndex + 1} exceeds maxBytes ${params.maxBytes}`,
@@ -380,12 +381,7 @@ export class MediaAttachmentCache {
380381
return { path: entry.tempPath, cleanup: entry.tempCleanup };
381382
}
382383

383-
const maxBytes = params.maxBytes ?? Number.POSITIVE_INFINITY;
384-
const bufferResult = await this.getBuffer({
385-
attachmentIndex: params.attachmentIndex,
386-
maxBytes,
387-
timeoutMs: params.timeoutMs,
388-
});
384+
const bufferResult = await this.getBuffer(params);
389385
const extension = path.extname(bufferResult.fileName || "") || "";
390386
const tmpPath = buildRandomTempFilePath({
391387
prefix: "openclaw-media",
@@ -394,6 +390,10 @@ export class MediaAttachmentCache {
394390
// Keep failed staging owned when model fallback retries the same attachment.
395391
const previousCleanup = entry.tempCleanup;
396392
entry.tempCleanup = async () => {
393+
// Returned cleanup callbacks may outlive a restaged file; invalidate only their path.
394+
if (entry.tempPath === tmpPath) {
395+
entry.tempPath = undefined;
396+
}
397397
await previousCleanup?.();
398398
await fs.unlink(tmpPath).catch(() => {});
399399
};
@@ -584,13 +584,7 @@ export class MediaAttachmentCache {
584584
`Attachment ${params.attachmentIndex + 1} path is outside allowed roots.`,
585585
);
586586
}
587-
const buffer = await opened.handle.readFile();
588-
if (buffer.length > params.maxBytes) {
589-
throw new MediaUnderstandingSkipError(
590-
"maxBytes",
591-
`Attachment ${params.attachmentIndex + 1} exceeds maxBytes ${params.maxBytes}`,
592-
);
593-
}
587+
const buffer = await readFileHandleBounded(opened.handle, params.maxBytes);
594588
return { buffer, filePath: opened.realPath };
595589
} catch (err) {
596590
if (err instanceof FsSafeError) {

‎src/media-understanding/media-understanding-misc.test.ts‎

Lines changed: 0 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -446,33 +446,6 @@ describe("media understanding attachments SSRF", () => {
446446
});
447447
});
448448

449-
it("enforces maxBytes after reading local attachments", async () => {
450-
await withLocalAttachmentCache(
451-
"openclaw-media-cache-max-bytes-",
452-
async ({ cache, canonicalAttachmentPath }) => {
453-
const originalOpen = fs.open.bind(fs);
454-
const openSpy = vi.spyOn(fs, "open");
455-
456-
openSpy.mockImplementation(async (filePath, flags) => {
457-
const handle = await originalOpen(filePath, flags);
458-
const candidatePath = await fs.realpath(String(filePath)).catch(() => String(filePath));
459-
if (candidatePath !== canonicalAttachmentPath) {
460-
return handle;
461-
}
462-
const mockedHandle = handle as typeof handle & {
463-
readFile: typeof handle.readFile;
464-
};
465-
mockedHandle.readFile = (async () => Buffer.alloc(2048, 1)) as typeof handle.readFile;
466-
return mockedHandle;
467-
});
468-
469-
await expect(
470-
cache.getBuffer({ attachmentIndex: 0, maxBytes: 1024, timeoutMs: 1000 }),
471-
).rejects.toThrow(/exceeds maxBytes 1024/i);
472-
},
473-
);
474-
});
475-
476449
it("opens local attachments with nofollow on posix", async () => {
477450
if (process.platform === "win32") {
478451
return;
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Exercise the file API with real cache, filesystem, root policy, and MIME detection.
2+
import fs from "node:fs/promises";
3+
import path from "node:path";
4+
import { describe, expect, it, vi } from "vitest";
5+
import { withTestDir } from "../test-helpers/temp-dir.js";
6+
import { DEFAULT_MAX_BYTES } from "./defaults.constants.js";
7+
import { prepareImageDescriptionInput } from "./runtime.js";
8+
9+
vi.mock("./runner.js", async () => {
10+
return {
11+
...(await import("./runner.attachments.js")),
12+
buildProviderRegistry: vi.fn(),
13+
runCapability: vi.fn(),
14+
};
15+
});
16+
17+
vi.mock("./provider-registry.js", () => ({
18+
buildMediaUnderstandingRegistry: vi.fn(),
19+
getMediaUnderstandingProvider: vi.fn(),
20+
normalizeMediaProviderId: vi.fn(),
21+
}));
22+
vi.mock("./image-runtime.js", () => ({ describeImageWithModel: vi.fn() }));
23+
24+
describe("local image preparation", () => {
25+
it("rejects oversized local images before provider preparation", async () => {
26+
await withTestDir({ prefix: "openclaw-image-input-limit-" }, async (base) => {
27+
const filePath = path.join(base, "oversized.png");
28+
await fs.writeFile(filePath, Buffer.alloc(DEFAULT_MAX_BYTES.image + 1));
29+
await expect(
30+
prepareImageDescriptionInput({ filePath, cfg: {} }).then(() => "accepted"),
31+
).rejects.toMatchObject({
32+
reason: "maxBytes",
33+
});
34+
});
35+
});
36+
37+
it.skipIf(process.platform === "win32")("keeps rejecting local image symlinks", async () => {
38+
await withTestDir({ prefix: "openclaw-image-input-roots-" }, async (base) => {
39+
const allowed = path.join(base, "allowed");
40+
const outside = path.join(base, "outside.png");
41+
const filePath = path.join(allowed, "linked.png");
42+
await fs.mkdir(allowed);
43+
await fs.writeFile(outside, "outside");
44+
await fs.symlink(outside, filePath);
45+
await expect(prepareImageDescriptionInput({ filePath, cfg: {} })).rejects.toThrow();
46+
});
47+
});
48+
49+
it("accepts an explicitly supplied local image and classifies its bytes", async () => {
50+
await withTestDir({ prefix: "openclaw-image-input-local-" }, async (base) => {
51+
const buffer = Buffer.from(
52+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGNgYAAAAAMAASsJTYQAAAAASUVORK5CYII=",
53+
"base64",
54+
);
55+
const filePath = path.join(base, "photo.jpg");
56+
await fs.writeFile(filePath, buffer);
57+
await expect(
58+
prepareImageDescriptionInput({ filePath, mime: "application/pdf", cfg: {} }),
59+
).resolves.toEqual({ buffer, fileName: "photo.jpg", mime: "image/png" });
60+
});
61+
});
62+
});

0 commit comments

Comments
 (0)