Files
mtusi2026lab4/app/src/attachments/image/image-decoder.spec.ts
T

71 lines
2.3 KiB
TypeScript

import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { jpegWithoutScanData } from '../../../test/support/jpeg.js';
import {
maxPixelsRgba16Png,
noisePng,
pngWithGarbageIdat,
} from '../../../test/support/png.js';
import { ImageDecoder } from './image-decoder.js';
import { ImageInspector, ImageRejectedError } from './image-inspector.js';
const here = dirname(fileURLToPath(import.meta.url));
const png = readFileSync(join(here, '../../../../tests/fixtures/sample.png'));
const jpeg = readFileSync(join(here, '../../../test/fixtures/sample.jpg'));
const progressive = readFileSync(
join(here, '../../../test/fixtures/sample-progressive.jpg'),
);
const settings: Record<string, number> = {
MAX_IMAGE_PIXELS: 40_000_000,
IMAGE_DECODE_MAX_CONCURRENT: 1,
};
const decoder = new ImageDecoder(
{ getOrThrow: (key: string) => settings[key] } as never,
{ increment: () => undefined, add: () => undefined } as never,
);
describe('ImageDecoder', () => {
it('accepts valid PNG and JPEG files, also concurrently', async () => {
await Promise.all(
[png, jpeg, progressive, noisePng(1_048_576)].map((data) =>
decoder.verify(data),
),
);
});
// These files pass the structural inspector; only a decode catches them.
it.each([
['PNG with a garbage zlib stream', pngWithGarbageIdat()],
['JPEG without scan data', jpegWithoutScanData(jpeg)],
[
'progressive JPEG without scan data',
jpegWithoutScanData(progressive),
],
])('rejects a %s', async (_name, data) => {
const inspector = new ImageInspector(40_000_000);
inspector.push(data);
expect(inspector.finish().width).toBe(320);
await expect(decoder.verify(data)).rejects.toBeInstanceOf(
ImageRejectedError,
);
});
it('accepts the heaviest valid input: 40 MP RGBA 16-bit', async () => {
await decoder.verify(await maxPixelsRgba16Png());
});
it('drops an aborted waiter from the queue without running its decode', async () => {
const busy = decoder.verify(noisePng(4_000_000));
const controller = new AbortController();
const waiting = decoder.verify(png, controller.signal);
controller.abort();
await expect(waiting).rejects.toMatchObject({ status: 503 });
await busy;
// The slot was not leaked: the next decode runs.
await decoder.verify(png);
});
});