fix(media): bound image work before public rendition

Check avatar uploads and raster fallbacks before decoding. Limit compressed bytes, decoded dimensions, GIF frames and the combined TIFF page budget.
This commit is contained in:
Maurice
2026-12-01 11:56:22 +01:00
parent 1ff8a814ae
commit 28eea68559
7 changed files with 308 additions and 6 deletions
+11 -1
View File
@@ -6,6 +6,7 @@ import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { currentSessionId, decodeSessionClaims } from '../auth-core/jwt-verify';
import { MfaExempt } from '../auth-core/mfa-policy.guard';
import { boundedRasterHeader, readRasterFile } from '../common/bounded-raster';
import { DEMO_ACCOUNT_REFUSAL, DEMO_WRITE_ERROR, isDemoWriteBlocked, refuseForDemoAccount } from '../common/demo-write';
import { ManagedForbidden } from '../common/managed';
import { RateLimitService } from '../common/rate-limit.service';
@@ -46,17 +47,20 @@ import { FileInterceptor } from '@nestjs/platform-express';
import type { Request, Response } from 'express';
import type { Options } from 'multer';
import { rm } from 'node:fs/promises';
import path from 'path';
const WINDOW = 15 * 60 * 1000;
const ALLOWED_AVATAR_EXTS = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
const ALLOWED_AVATAR_MIME_TYPES = new Set(['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
const INVALID_AVATAR_MESSAGE = 'Only image files (jpg, png, gif, webp) are allowed';
export const MAX_AVATAR_SIZE = 5 * 1024 * 1024;
// Consumed by auth.module.ts's MulterModule factory; the storage engine (spool
// destination + UUID filename) comes from the storage upload factory.
export const AVATAR_FILE_FILTER: Options['fileFilter'] = (_req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
if (!file.mimetype.startsWith('image/') || !ALLOWED_AVATAR_EXTS.includes(ext)) {
const err: Error & { statusCode?: number } = new Error('Only image files (jpg, png, gif, webp) are allowed');
const err: Error & { statusCode?: number } = new Error(INVALID_AVATAR_MESSAGE);
err.statusCode = 400;
return cb(err);
}
@@ -225,6 +229,12 @@ export class AuthController {
if (!file) {
throw new HttpException({ error: 'No image uploaded' }, 400);
}
const bytes = await readRasterFile(file.path, MAX_AVATAR_SIZE);
const header = bytes && boundedRasterHeader(bytes);
if (!header || !ALLOWED_AVATAR_MIME_TYPES.has(header.mimeType)) {
await rm(file.path, { force: true });
throw new HttpException({ error: INVALID_AVATAR_MESSAGE }, 400);
}
// Commit the spooled upload to its final storage location (atomic
// same-volume rename) before the DB row references the final path.
await this.storage.put('avatars', file.filename, { tmpPath: file.path });
+142
View File
@@ -0,0 +1,142 @@
import { readImageHeader } from './image-header';
import { open } from 'node:fs/promises';
const MAX_EDGE = 16_384;
export const MAX_RASTER_PIXELS = 40_000_000;
const MAX_RASTER_BYTES = MAX_RASTER_PIXELS * 4;
const MAX_TIFF_PAGES = 64;
const TIFF_SIZE_TAGS = new Set([256, 257, 258, 262, 277, 322, 323]);
const TIFF_UNSUPPORTED_TAGS = new Set([330, 50885]);
type RasterInfo = { width: number; height: number; mimeType: string };
type ReadInteger = (offset: number) => number;
function fitsRaster(width: number, height: number): boolean {
return width > 0 && height > 0 && width <= MAX_EDGE && height <= MAX_EDGE && width * height <= MAX_RASTER_PIXELS;
}
function tiffValue(data: Buffer, short: ReadInteger, long: ReadInteger, entry: number, tag: number): number | null {
const type = short(entry + 2);
const count = long(entry + 4);
if ((type !== 3 && type !== 4) || count < 1 || count > (tag === 258 ? 4 : 1)) return null;
const size = type === 3 ? 2 : 4;
const offset = count * size <= 4 ? entry + 8 : long(entry + 8);
if (offset + count * size > data.length) return null;
return type === 3 ? short(offset) : long(offset);
}
function readTiffPage(data: Buffer, short: ReadInteger, long: ReadInteger, directory: number) {
if (directory < 8 || directory + 2 > data.length) return null;
const end = directory + 2 + short(directory) * 12;
if (end + 4 > data.length) return null;
const tags = new Map<number, number>();
for (let entry = directory + 2; entry < end; entry += 12) {
const tag = short(entry);
if (TIFF_UNSUPPORTED_TAGS.has(tag)) return null;
if (!TIFF_SIZE_TAGS.has(tag)) continue;
const value = tiffValue(data, short, long, entry, tag);
if (value === null) return null;
tags.set(tag, value);
}
const width = tags.get(256) ?? 0;
const height = tags.get(257) ?? 0;
if (!fitsRaster(width, height) || tags.get(262) === 32803) return null;
const samples = tags.get(277) ?? 1;
const bits = tags.get(258) ?? 1;
if (samples < 1 || samples > 4 || bits < 1 || bits > 32) return null;
const tileWidth = tags.get(322) ?? 0;
const tileHeight = tags.get(323) ?? 0;
if ((tileWidth || tileHeight) && !fitsRaster(tileWidth, tileHeight)) return null;
const bytes = (width * height + tileWidth * tileHeight) * Math.max(4, Math.ceil((samples * bits) / 8));
return { width, height, bytes, next: long(end) };
}
function readTiffHeader(data: Buffer): RasterInfo | null {
const littleEndian = data.toString('latin1', 0, 2) === 'II';
const short = littleEndian ? data.readUInt16LE.bind(data) : data.readUInt16BE.bind(data);
const long = littleEndian ? data.readUInt32LE.bind(data) : data.readUInt32BE.bind(data);
if ((!littleEndian && data.toString('latin1', 0, 2) !== 'MM') || short(2) !== 42) return null;
let directory = long(4);
let first: RasterInfo | null = null;
let decodedBytes = 0;
for (let page = 0; directory; page++) {
if (page === MAX_TIFF_PAGES) return null;
const info = readTiffPage(data, short, long, directory);
if (!info) return null;
decodedBytes += info.bytes;
if (decodedBytes > MAX_RASTER_BYTES) return null;
first ??= { width: info.width, height: info.height, mimeType: 'image/tiff' };
directory = info.next;
}
return first;
}
function skipGifBlocks(data: Buffer, offset: number): number {
while (offset < data.length) {
const blockSize = data[offset++];
if (blockSize === 0) return offset;
offset += blockSize;
}
return data.length;
}
function gifPaletteBytes(flags: number): number {
return flags & 0x80 ? 3 * (2 << (flags & 7)) : 0;
}
function readGifHeader(data: Buffer): RasterInfo | null {
const width = data.readUInt16LE(6);
const height = data.readUInt16LE(8);
if (!fitsRaster(width, height)) return null;
let offset = 13 + gifPaletteBytes(data[10]);
let frames = 0;
while (offset < data.length) {
const block = data[offset++];
if (block === 0x3b) return frames ? { width, height, mimeType: 'image/gif' } : null;
if (block === 0x21) {
offset = skipGifBlocks(data, offset + 1);
continue;
}
if (block !== 0x2c || offset + 9 > data.length || ++frames > 1_000) return null;
if (!fitsRaster(data.readUInt16LE(offset + 4), data.readUInt16LE(offset + 6))) return null;
offset = skipGifBlocks(data, offset + 10 + gifPaletteBytes(data[offset + 8]));
}
return null;
}
function readRasterHeader(data: Buffer): RasterInfo | null {
const common = readImageHeader(data);
if (common) return common;
const signature = data.toString('latin1', 0, 6);
if (data.length >= 13 && (signature === 'GIF87a' || signature === 'GIF89a')) {
return readGifHeader(data);
}
if (data.length >= 26 && signature.startsWith('BM')) {
const dibSize = data.readUInt32LE(14);
if (dibSize < 40 || 14 + dibSize > data.length) return null;
return { width: data.readInt32LE(18), height: Math.abs(data.readInt32LE(22)), mimeType: 'image/bmp' };
}
return data.length >= 8 ? readTiffHeader(data) : null;
}
export function boundedRasterHeader(data: Buffer): RasterInfo | null {
const header = readRasterHeader(data);
return header && fitsRaster(header.width, header.height) ? header : null;
}
/** Limit the compressed input independently of the decoded pixel budget. */
export async function readRasterFile(path: string, maxBytes: number): Promise<Buffer | null> {
const file = await open(path, 'r');
try {
const { size } = await file.stat();
if (size === 0 || size > maxBytes) return null;
const data = Buffer.alloc(size);
const { bytesRead } = await file.read(data);
return bytesRead === size ? data : null;
} finally {
await file.close();
}
}
@@ -3,6 +3,7 @@ import { TrekPhotos } from '../../db/entities/TrekPhotos.entity';
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
import type { TrekPhotosRepository } from '../../db/repositories/TrekPhotos.repository';
import { logWarn } from '../audit/audit-log.logger';
import { boundedRasterHeader, MAX_RASTER_PIXELS, readRasterFile } from '../common/bounded-raster';
import { StorageService } from '../storage/storage.service';
import { StorageNotFoundError, type ServedCategory } from '../storage/storage.types';
import { redactLocationInFile } from './media-redact';
@@ -23,6 +24,7 @@ const RENDITION_CATEGORIES: readonly ServedCategory[] = ['avatars', 'covers', 'j
/** Image types Jimp both decodes and writes; it writes no metadata, so a re-encoded copy carries no location. */
const REENCODABLE_EXTENSIONS = new Set(['.bmp', '.gif', '.jpeg', '.jpg', '.png', '.tif', '.tiff']);
const MAX_REENCODE_BYTES = 32 * 1024 * 1024;
/**
* How long a request waits for a copy being made: just under the 60 s a
@@ -188,7 +190,11 @@ export class PublicMediaService {
if (!REENCODABLE_EXTENSIONS.has(extension)) return false;
try {
// Jimp applies the EXIF orientation on read, so the copy shows upright without it.
const image = await this.storage.withLocalFile(category, name, (source) => Jimp.read(source));
const bytes = await this.storage.withLocalFile(category, name, (source) =>
readRasterFile(source, MAX_REENCODE_BYTES),
);
if (!bytes || !boundedRasterHeader(bytes)) return false;
const image = await Jimp.read(bytes, { 'image/jpeg': { maxResolutionInMP: MAX_RASTER_PIXELS / 1_000_000 } });
await image.write(spool as Parameters<typeof image.write>[0]);
return true;
} catch {
+11
View File
@@ -168,6 +168,17 @@ describe('Avatar', () => {
expect(res.status).toBe(400);
});
it('PROFILE-003b: checks the avatar bytes before storing it', async () => {
const { user } = await makeUser(orm);
const res = await request(app)
.post('/api/auth/avatar')
.set('Cookie', authCookie(user.id))
.attach('avatar', Buffer.from('not an image'), { filename: 'avatar.png', contentType: 'image/png' });
expect(res.status).toBe(400);
expect(await findRow(orm, Users, { id: user.id })).toMatchObject({ avatar: null });
});
it('PROFILE-005 — DELETE /api/auth/avatar clears avatar_url', async () => {
const { user } = await makeUser(orm);
// Upload first
+12 -4
View File
@@ -17,6 +17,7 @@ import { HttpException } from '@nestjs/common';
import type { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { join } from 'node:path';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('../../../src/nest/audit/client-ip', () => ({ getClientIp: vi.fn(() => '1.2.3.4') }));
@@ -32,6 +33,7 @@ vi.mock('../../../src/nest/common/demo', () => ({ isDemoEmail: vi.fn(() => false
const user = { id: 1, username: 'u', role: 'user', email: 'u@example.test' } as User;
const req = { ip: '9.9.9.9', headers: {} } as Request;
const res = {} as Response;
const avatarFixture = join(__dirname, '../../fixtures/small-image.jpg');
function asvc(o: Partial<AuthService> = {}): AuthService {
return {
@@ -468,7 +470,10 @@ describe('AuthController (authenticated)', () => {
});
const saveAvatar = vi.fn().mockResolvedValue({ avatar: '/a.jpg' });
expect(
await ac(asvc({}), rl(), {}, { saveAvatar }).avatar(user, { filename: 'a.jpg' } as Express.Multer.File),
await ac(asvc({}), rl(), {}, { saveAvatar }).avatar(user, {
filename: 'a.jpg',
path: avatarFixture,
} as Express.Multer.File),
).toEqual({ avatar: '/a.jpg' });
});
@@ -972,9 +977,12 @@ describe('AuthController (authenticated)', () => {
it('avatar saves when not in demo mode (env present but email is not a demo email)', async () => {
process.env.DEMO_MODE = 'true';
vi.mocked(isDemoEmail).mockReturnValue(false);
const saveAvatar = vi.fn().mockResolvedValue({ avatar: '/b.png' });
const saveAvatar = vi.fn().mockResolvedValue({ avatar: '/b.jpg' });
expect(
await ac(asvc({}), rl(), {}, { saveAvatar }).avatar(user, { filename: 'b.png' } as Express.Multer.File),
).toEqual({ avatar: '/b.png' });
await ac(asvc({}), rl(), {}, { saveAvatar }).avatar(user, {
filename: 'b.jpg',
path: avatarFixture,
} as Express.Multer.File),
).toEqual({ avatar: '/b.jpg' });
});
});
@@ -0,0 +1,118 @@
import { boundedRasterHeader, readRasterFile } from '../../../src/nest/common/bounded-raster';
import { Jimp } from 'jimp';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
function pngHeader(width: number, height: number): Buffer {
const buffer = Buffer.alloc(24);
buffer.writeUInt32BE(0x89504e47, 0);
buffer.write('IHDR', 12);
buffer.writeUInt32BE(width, 16);
buffer.writeUInt32BE(height, 20);
return buffer;
}
function tiffDirectories(...pages: ReadonlyArray<ReadonlyArray<readonly [number, number]>>): Buffer {
const data = Buffer.alloc(8 + pages.reduce((size, tags) => size + 6 + tags.length * 12, 0));
data.write('II');
data.writeUInt16LE(42, 2);
data.writeUInt32LE(8, 4);
let directory = 8;
for (const [page, tags] of pages.entries()) {
data.writeUInt16LE(tags.length, directory);
let entry = directory + 2;
for (const [tag, value] of tags) {
data.writeUInt16LE(tag, entry);
data.writeUInt16LE(4, entry + 2);
data.writeUInt32LE(1, entry + 4);
data.writeUInt32LE(value, entry + 8);
entry += 12;
}
directory = entry + 4;
data.writeUInt32LE(page === pages.length - 1 ? 0 : directory, entry);
}
return data;
}
function gifFrameHeader(frameWidth: number, frameHeight: number): Buffer {
const data = Buffer.alloc(26);
data.write('GIF87a');
data.writeUInt16LE(4, 6);
data.writeUInt16LE(2, 8);
data[13] = 0x2c;
data.writeUInt16LE(frameWidth, 18);
data.writeUInt16LE(frameHeight, 20);
data[25] = 0x3b;
return data;
}
describe('boundedRasterHeader', () => {
it.each(['image/png', 'image/jpeg', 'image/bmp', 'image/gif', 'image/tiff'] as const)(
'reads %s dimensions without decoding',
async (mimeType) => {
const image = new Jimp({ width: 4, height: 2, color: 0x336699ff });
expect(boundedRasterHeader(await image.getBuffer(mimeType))).toEqual({ mimeType, width: 4, height: 2 });
},
);
it.each([
[0, 20],
[20, 0],
[20_000, 20],
[20, 20_000],
[8_000, 6_000],
])('refuses dimensions %d × %d', (width, height) => {
expect(boundedRasterHeader(pngHeader(width, height))).toBeNull();
});
it('refuses unsupported and incomplete headers', () => {
expect(boundedRasterHeader(Buffer.from('not an image'))).toBeNull();
expect(boundedRasterHeader(Buffer.from('II\x2a\x00\x08\x00\x00\x00', 'latin1'))).toBeNull();
expect(boundedRasterHeader(Buffer.from('GIF89a'))).toBeNull();
});
it('checks individual GIF frames independently of the canvas', () => {
expect(boundedRasterHeader(gifFrameHeader(4, 2))).toMatchObject({ mimeType: 'image/gif', width: 4, height: 2 });
expect(boundedRasterHeader(gifFrameHeader(0, 2))).toBeNull();
expect(boundedRasterHeader(gifFrameHeader(4, 20_000))).toBeNull();
});
it('counts the decoded space used by every TIFF page', () => {
const small = [
[256, 4],
[257, 2],
] as const;
expect(boundedRasterHeader(tiffDirectories(small, small))).toMatchObject({
mimeType: 'image/tiff',
width: 4,
height: 2,
});
const large = [
[256, 5_000],
[257, 5_000],
] as const;
expect(boundedRasterHeader(tiffDirectories(large, large))).toBeNull();
});
it('refuses TIFF pages with unbounded samples or tile geometry', () => {
const size = [
[256, 4],
[257, 2],
] as const;
expect(boundedRasterHeader(tiffDirectories([...size, [277, 5]]))).toBeNull();
expect(boundedRasterHeader(tiffDirectories([...size, [322, 20_000], [323, 2]]))).toBeNull();
expect(boundedRasterHeader(tiffDirectories([...size, [330, 8]]))).toBeNull();
});
});
describe('readRasterFile', () => {
const fixture = join(__dirname, '../../fixtures/small-image.jpg');
it('reads only input within its byte limit', async () => {
expect(await readRasterFile(fixture, 4)).toBeNull();
expect(boundedRasterHeader((await readRasterFile(fixture, 5 * 1024 * 1024)) ?? Buffer.alloc(0))).toMatchObject({
mimeType: 'image/jpeg',
});
});
});
@@ -190,6 +190,13 @@ describe('renditionFor', () => {
});
describe('renditionFor re-encode fallback', () => {
it('refuses a legacy avatar whose raster dimensions cannot be read', async () => {
write('avatars', 'incomplete.bmp', Buffer.from('BM'));
expect(await service.renditionFor('avatars', 'incomplete.bmp')).toBeNull();
expect(fs.readdirSync(path.join(root, '.spool'))).toEqual([]);
});
it('PMEDIA-004: an image whose metadata cannot be cleaned is re-encoded instead of refused', async () => {
const image = new Jimp({ width: 4, height: 2, color: 0x336699ff });
const bmp = await image.getBuffer('image/bmp');