[GH-ISSUE #3061] [Issue]: Chat-gallery and global-gallery uploads accept arbitrary file content (extension-only validation, no magic-byte check) #1631

Closed
opened 2026-10-21 05:41:06 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @kolacheee on GitHub (Jun 29, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3061

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong

POST /api/gallery/:chatId/upload and POST /api/global-gallery/upload validate the upload ONLY by the client-supplied filename extension and then stream the raw bytes to disk. They never inspect file content, so any bytes — HTML, a script, an arbitrary binary — can be stored as long as the filename ends in .png/.jpg/.gif/.webp/.avif. The stored file is later served back with a content type derived from its extension. By contrast, backgrounds and avatars verify magic bytes via isAllowedImageBuffer before persisting.

The direct-load XSS vector is mitigated because the global security-headers hook sets X-Content-Type-Options: nosniff, so a fake-PNG HTML file will not be sniffed as HTML. But the content-validation invariant is still bypassed: non-image data is accepted into the gallery and served under an image MIME type — exactly what the magic-byte check on the other routes exists to prevent.

How to reproduce (try it yourself)

  1. POST /api/gallery/<chatId>/upload with a file part named evil.png whose body is <html><script>...</script></html> (or any non-image bytes).
  2. GET the returned url /api/gallery/file/<chatId>/<id>.png.

You'll see: the upload succeeds (200), a chat_images record is created, and the GET returns the non-image bytes with Content-Type: image/png. The same works for /api/global-gallery/upload.

Expected: backgrounds (/api/backgrounds/upload) and NPC avatars reject the identical payload with 'Unsupported or invalid image file' because they magic-byte-check the buffer; the gallery routes should too.

Where it is

  • packages/server/src/routes/gallery.routes.ts:382-396 (upload handler 372-420) — const ext = extname(data.filename); if (!ALLOWED_EXTS.has(ext)) {...} then await pipeline(data.file, createWriteStream(filePath)); no content inspection.
  • packages/server/src/routes/global-gallery.routes.ts:89-112 (upload handler 83-142) — identical pattern.
  • Contrast: backgrounds.routes.ts:143 (isAllowedImageBuffer(buffer, ext)), avatars.routes.ts:109. Validator: packages/server/src/utils/security.ts:82-121.
  • Serving derives Content-Type from extension: gallery.routes.ts:434, global-gallery.routes.ts:155.

What's happening

Upload validation relies solely on the attacker-controlled filename extension; isAllowedImageBuffer (or any content sniff) is never called on the uploaded bytes for these two routes.

Suggested fix

Mirror backgrounds.routes.ts:118-146 in both gallery upload handlers: take the file with an explicit per-call size limit, buffer it with size-limit handling, magic-byte validate, then write. Add const GALLERY_UPLOAD_MAX_BYTES = 20 * 1024 * 1024; and import isAllowedImageBuffer from ../utils/security.js and writeFile from fs/promises. In each handler:

const data = await req.file({ limits: { fileSize: GALLERY_UPLOAD_MAX_BYTES } });
// keep the ext/ALLOWED_EXTS guard and assertInsideDir(...) -> filePath
let buffer: Buffer;
try {
  buffer = await data.toBuffer();
} catch (err) {
  if ((err as { code?: string }).code === "FST_REQ_FILE_TOO_LARGE") {
    return reply.status(413).send({ error: "Gallery image is too large" });
  }
  throw err;
}
if (!isAllowedImageBuffer(buffer, ext)) {
  return reply.status(400).send({ error: "Unsupported or invalid image file" });
}
await writeFile(filePath, buffer);

data.fields stays readable afterward, so the prompt/provider/model/width/height block and the storage create are unchanged. For global-gallery, validating before the write means no orphan can be stranded by a rejected upload; leave the existing DB-rollback try/catch (lines 121-141) as-is.

Regression avoided: the current code uses a streaming write that never holds the whole file in memory, but the global multipart fileSize cap is 256 MB. A naive data.toBuffer() with no per-call limit would buffer up to 256 MB per upload, and both gallery clients fan out with Promise.allSettled over a file array, so several such buffers could be held at once — a memory-exhaustion regression. Passing the tight per-call GALLERY_UPLOAD_MAX_BYTES limit and catching FST_REQ_FILE_TOO_LARGE (exactly as backgrounds does) avoids it. The dot-prefixed lowercased ext is the form isAllowedImageBuffer expects (its AVIF branch gates on expectedExt === ".avif").


AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.

Originally created by @kolacheee on GitHub (Jun 29, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3061 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** `POST /api/gallery/:chatId/upload` and `POST /api/global-gallery/upload` validate the upload ONLY by the client-supplied filename extension and then stream the raw bytes to disk. They never inspect file content, so any bytes — HTML, a script, an arbitrary binary — can be stored as long as the filename ends in .png/.jpg/.gif/.webp/.avif. The stored file is later served back with a content type derived from its extension. By contrast, backgrounds and avatars verify magic bytes via `isAllowedImageBuffer` before persisting. The direct-load XSS vector is mitigated because the global security-headers hook sets `X-Content-Type-Options: nosniff`, so a fake-PNG HTML file will not be sniffed as HTML. But the content-validation invariant is still bypassed: non-image data is accepted into the gallery and served under an image MIME type — exactly what the magic-byte check on the other routes exists to prevent. **How to reproduce (try it yourself)** 1. `POST /api/gallery/<chatId>/upload` with a file part named `evil.png` whose body is `<html><script>...</script></html>` (or any non-image bytes). 2. `GET` the returned url `/api/gallery/file/<chatId>/<id>.png`. You'll see: the upload succeeds (200), a `chat_images` record is created, and the GET returns the non-image bytes with `Content-Type: image/png`. The same works for `/api/global-gallery/upload`. Expected: backgrounds (`/api/backgrounds/upload`) and NPC avatars reject the identical payload with 'Unsupported or invalid image file' because they magic-byte-check the buffer; the gallery routes should too. **Where it is** - `packages/server/src/routes/gallery.routes.ts:382-396` (upload handler 372-420) — `const ext = extname(data.filename); if (!ALLOWED_EXTS.has(ext)) {...}` then `await pipeline(data.file, createWriteStream(filePath))`; no content inspection. - `packages/server/src/routes/global-gallery.routes.ts:89-112` (upload handler 83-142) — identical pattern. - Contrast: `backgrounds.routes.ts:143` (`isAllowedImageBuffer(buffer, ext)`), `avatars.routes.ts:109`. Validator: `packages/server/src/utils/security.ts:82-121`. - Serving derives Content-Type from extension: `gallery.routes.ts:434`, `global-gallery.routes.ts:155`. **What's happening** Upload validation relies solely on the attacker-controlled filename extension; `isAllowedImageBuffer` (or any content sniff) is never called on the uploaded bytes for these two routes. **Suggested fix** Mirror `backgrounds.routes.ts:118-146` in both gallery upload handlers: take the file with an explicit per-call size limit, buffer it with size-limit handling, magic-byte validate, then write. Add `const GALLERY_UPLOAD_MAX_BYTES = 20 * 1024 * 1024;` and import `isAllowedImageBuffer` from `../utils/security.js` and `writeFile` from `fs/promises`. In each handler: ```ts const data = await req.file({ limits: { fileSize: GALLERY_UPLOAD_MAX_BYTES } }); // keep the ext/ALLOWED_EXTS guard and assertInsideDir(...) -> filePath let buffer: Buffer; try { buffer = await data.toBuffer(); } catch (err) { if ((err as { code?: string }).code === "FST_REQ_FILE_TOO_LARGE") { return reply.status(413).send({ error: "Gallery image is too large" }); } throw err; } if (!isAllowedImageBuffer(buffer, ext)) { return reply.status(400).send({ error: "Unsupported or invalid image file" }); } await writeFile(filePath, buffer); ``` `data.fields` stays readable afterward, so the prompt/provider/model/width/height block and the storage create are unchanged. For global-gallery, validating before the write means no orphan can be stranded by a rejected upload; leave the existing DB-rollback try/catch (lines 121-141) as-is. Regression avoided: the current code uses a streaming write that never holds the whole file in memory, but the global multipart `fileSize` cap is 256 MB. A naive `data.toBuffer()` with no per-call limit would buffer up to 256 MB per upload, and both gallery clients fan out with `Promise.allSettled` over a file array, so several such buffers could be held at once — a memory-exhaustion regression. Passing the tight per-call `GALLERY_UPLOAD_MAX_BYTES` limit and catching `FST_REQ_FILE_TOO_LARGE` (exactly as backgrounds does) avoids it. The dot-prefixed lowercased `ext` is the form `isAllowedImageBuffer` expects (its AVIF branch gates on `expectedExt === ".avif"`). --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Claiming this for the current staging sweep in draft PR #3064: https://github.com/Pasta-Devs/Marinara-Engine/pull/3064

<!-- gh-comment-id:4835429748 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Claiming this for the current staging sweep in draft PR #3064: https://github.com/Pasta-Devs/Marinara-Engine/pull/3064
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Fixed in PR #3064 on branch codex/issue-sweep-3054-3063 (commit 3ae8ca37). Closing this issue as addressed; the PR remains open for staging review/merge.

<!-- gh-comment-id:4835579623 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Fixed in PR #3064 on branch `codex/issue-sweep-3054-3063` (commit 3ae8ca37). Closing this issue as addressed; the PR remains open for staging review/merge.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1631
No description provided.