forked from mtusi2026/mtusi2026lab4
lab4: исправления второго ревью (40 Мп в tmpfs, таймауты S3, параллельный complete, auth до Content-Type, лимит на пользователя, бюджет памяти декода)
This commit is contained in:
@@ -21,8 +21,10 @@ import {
|
||||
upload,
|
||||
uploadRaw,
|
||||
} from './support/e2e.js';
|
||||
import { jpegWithoutScanData } from './support/jpeg.js';
|
||||
import sharp from 'sharp';
|
||||
import { jpegWithMetadata, jpegWithoutScanData } from './support/jpeg.js';
|
||||
import {
|
||||
maxPixelsRgba16Png,
|
||||
noisePng,
|
||||
padPngTo,
|
||||
pixelBombPng,
|
||||
@@ -146,6 +148,106 @@ describe('attachments (proxy upload)', () => {
|
||||
expect(content.bytes.equals(data)).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts camera-size images up to the pixel limit', async () => {
|
||||
// 7728x5152 = 39.8 MP, like a 40 MP camera; decoded size far above the
|
||||
// replica's 16 MiB /tmp, so libvips must not spill to a temp file.
|
||||
const camera = sharp({
|
||||
create: {
|
||||
width: 7728,
|
||||
height: 5152,
|
||||
channels: 3,
|
||||
background: { r: 120, g: 80, b: 40 },
|
||||
},
|
||||
});
|
||||
const baseline = await camera.clone().jpeg({ quality: 85 }).toBuffer();
|
||||
const progressiveCamera = await camera
|
||||
.clone()
|
||||
.jpeg({ quality: 85, progressive: true })
|
||||
.toBuffer();
|
||||
for (const data of [baseline, progressiveCamera])
|
||||
expect((await ready(data, 'image/jpeg')).size_bytes).toBe(
|
||||
data.length,
|
||||
);
|
||||
const rgba16 = await maxPixelsRgba16Png();
|
||||
expect((await ready(rgba16)).size_bytes).toBe(rgba16.length);
|
||||
}, 120_000);
|
||||
|
||||
it('accepts a JPEG with megabytes of metadata before the frame header', async () => {
|
||||
const data = jpegWithMetadata(jpeg, 20);
|
||||
expect(data.length).toBeGreaterThan(1_048_576);
|
||||
expect((await ready(data, 'image/jpeg')).sha256).toBe(sha256(data));
|
||||
});
|
||||
|
||||
it('authenticates before judging the content type', async () => {
|
||||
const zip = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chatId}/attachments?filename=a.zip`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/zip' },
|
||||
body: png as unknown as BodyInit,
|
||||
},
|
||||
);
|
||||
expectError(zip, 401, 'unauthorized');
|
||||
expectError(
|
||||
await upload(alice.token, leftoverChatId, png, {
|
||||
contentType: 'application/json',
|
||||
}),
|
||||
415,
|
||||
'unsupported_media_type',
|
||||
);
|
||||
});
|
||||
|
||||
it('answers 413 with the error envelope to an oversized text body on JSON routes', async () => {
|
||||
const result = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chatId}/messages`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...bearer(alice.token),
|
||||
'content-type': 'text/plain',
|
||||
'idempotency-key': randomUUID().replaceAll('-', ''),
|
||||
},
|
||||
body: 'x'.repeat(2_100_000),
|
||||
},
|
||||
);
|
||||
expectError(result, 413, 'payload_too_large');
|
||||
});
|
||||
|
||||
it('keeps one slow client from taking every upload slot', async () => {
|
||||
const slow = await actor();
|
||||
const slowChat = (await createChat(slow, [])).id;
|
||||
const url = new URL(baseUrl);
|
||||
const sockets: net.Socket[] = [];
|
||||
try {
|
||||
for (let index = 0; index < 12; index += 1) {
|
||||
const socket = net.connect(
|
||||
Number(url.port || 80),
|
||||
url.hostname,
|
||||
);
|
||||
socket.on('error', () => {});
|
||||
socket.write(
|
||||
`POST /api/v1/chats/${slowChat}/attachments?filename=slow.png HTTP/1.1\r\n` +
|
||||
`Host: ${url.host}\r\nAuthorization: Bearer ${slow.token}\r\n` +
|
||||
`Content-Type: image/png\r\nContent-Length: ${png.length}\r\n\r\n`,
|
||||
);
|
||||
socket.write(png.subarray(0, 4));
|
||||
sockets.push(socket);
|
||||
}
|
||||
await sleep(1000);
|
||||
const extra = await upload(slow.token, slowChat, png);
|
||||
expectError(extra, 429, 'rate_limited');
|
||||
expect(extra.response.headers.get('retry-after')).toBe('1');
|
||||
// Another user is not affected by the slow client.
|
||||
for (let index = 0; index < 4; index += 1)
|
||||
expect(
|
||||
(await upload(bob.token, chatId, png)).response.status,
|
||||
).toBe(201);
|
||||
} finally {
|
||||
for (const socket of sockets) socket.destroy();
|
||||
}
|
||||
await settled(slowChat);
|
||||
});
|
||||
|
||||
it('enforces the 10 MiB limit exactly', async () => {
|
||||
const exact = padPngTo(png, MAX);
|
||||
const created = await ready(exact);
|
||||
|
||||
@@ -602,6 +602,10 @@ describe.skipIf(!enabled)('dependency outages', () => {
|
||||
await compose('start', redisService);
|
||||
await compose('start', postgresService);
|
||||
await compose('start', s3Service);
|
||||
const s3Container = (await compose('ps', '-q', s3Service)).split(
|
||||
'\n',
|
||||
)[0];
|
||||
await docker('unpause', s3Container).catch(() => undefined);
|
||||
await waitForReadiness(200);
|
||||
await restoreDatabaseAccess();
|
||||
const expected = (await apiContainers()).length;
|
||||
@@ -986,6 +990,62 @@ describe.skipIf(!enabled)('dependency outages', () => {
|
||||
outagedRequestBudgetMs,
|
||||
);
|
||||
|
||||
it(
|
||||
'bounds requests by S3_REQUEST_TIMEOUT_MS when S3 hangs instead of refusing',
|
||||
async () => {
|
||||
const created = await request<{ id: string }>(
|
||||
uploadPath(chat.id, `hang-${runId}.png`),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...bearer(token), 'content-type': 'image/png' },
|
||||
body: samplePng as unknown as BodyInit,
|
||||
},
|
||||
);
|
||||
expect(created.response.status).toBe(201);
|
||||
// A paused container keeps its TCP port open but never answers: the
|
||||
// failure mode a stopped container (connection refused) does not show.
|
||||
const container = (await compose('ps', '-q', s3Service)).split(
|
||||
'\n',
|
||||
)[0];
|
||||
await docker('pause', container);
|
||||
try {
|
||||
const started = Date.now();
|
||||
const content = await request<ApiErrorBody>(
|
||||
`/api/v1/attachments/${created.body.id}/content`,
|
||||
{ headers: bearer(token) },
|
||||
);
|
||||
const elapsed = Date.now() - started;
|
||||
expectBoundedOutage(content);
|
||||
// S3_REQUEST_TIMEOUT_MS is 15 s in the stand; HAProxy gives up at 30 s.
|
||||
expect(elapsed).toBeLessThan(20_000);
|
||||
expect(
|
||||
(
|
||||
await request(
|
||||
`/api/v1/attachments/${created.body.id}`,
|
||||
{
|
||||
headers: bearer(token),
|
||||
},
|
||||
)
|
||||
).response.status,
|
||||
).toBe(200);
|
||||
expect((await request('/health/ready')).response.status).toBe(
|
||||
200,
|
||||
);
|
||||
} finally {
|
||||
await docker('unpause', container);
|
||||
}
|
||||
const bytes = await fetch(
|
||||
`${baseUrl}/api/v1/attachments/${created.body.id}/content`,
|
||||
{ headers: bearer(token) },
|
||||
);
|
||||
expect(bytes.status).toBe(200);
|
||||
expect(
|
||||
Buffer.from(await bytes.arrayBuffer()).equals(samplePng),
|
||||
).toBe(true);
|
||||
},
|
||||
outagedRequestBudgetMs,
|
||||
);
|
||||
|
||||
it(
|
||||
'keeps the object while PostgreSQL is down before ready and sweeps it afterwards',
|
||||
async () => {
|
||||
|
||||
@@ -160,6 +160,21 @@ describe('direct upload (presigned PUT)', () => {
|
||||
expect(sent.body.attachment_ids).toEqual([ticket.attachment_id]);
|
||||
});
|
||||
|
||||
it('answers 200 to every parallel complete of one upload', async () => {
|
||||
const ticket = await initOk(png);
|
||||
expect((await put(ticket, png)).status).toBe(200);
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 4 }, () =>
|
||||
complete(alice.token, ticket.attachment_id),
|
||||
),
|
||||
);
|
||||
expect(results.map((result) => result.response.status)).toEqual([
|
||||
200, 200, 200, 200,
|
||||
]);
|
||||
for (const result of results)
|
||||
expect(result.body.id).toBe(ticket.attachment_id);
|
||||
});
|
||||
|
||||
it('rejects invalid declarations', async () => {
|
||||
const base = declaration(png);
|
||||
expectError(await init(eve.token, chatId, base), 404, 'not_found');
|
||||
|
||||
@@ -8,3 +8,17 @@ export function jpegWithoutScanData(jpeg: Buffer): Buffer {
|
||||
}
|
||||
return Buffer.concat([jpeg.subarray(0, offset), Buffer.from([0xff, 0xd9])]);
|
||||
}
|
||||
|
||||
/** Inserts `count` APP13 segments of ~64 KiB right after SOI (Photoshop-style metadata). */
|
||||
export function jpegWithMetadata(jpeg: Buffer, count: number): Buffer {
|
||||
const payload = Buffer.alloc(65_533, 0x20);
|
||||
const segment = Buffer.concat([
|
||||
Buffer.from([0xff, 0xed, 0xff, 0xff]),
|
||||
payload,
|
||||
]);
|
||||
return Buffer.concat([
|
||||
jpeg.subarray(0, 2),
|
||||
...Array.from({ length: count }, () => segment),
|
||||
jpeg.subarray(2),
|
||||
]);
|
||||
}
|
||||
|
||||
+35
-1
@@ -1,5 +1,6 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { crc32, deflateSync } from 'node:zlib';
|
||||
import { once } from 'node:events';
|
||||
import { crc32, createDeflate, deflateSync } from 'node:zlib';
|
||||
|
||||
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
|
||||
@@ -104,3 +105,36 @@ export function pngWithGarbageIdat(): Buffer {
|
||||
idat: randomBytes(5000),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 8000x5000 RGBA 16-bit (8 bytes/pixel, 40 000 000 px — the pixel limit):
|
||||
* the heaviest decode a valid upload can ask for. Rows are streamed into the
|
||||
* compressor, so the 320 MB raw image is never allocated here.
|
||||
*/
|
||||
export async function maxPixelsRgba16Png(): Promise<Buffer> {
|
||||
const width = 8000;
|
||||
const height = 5000;
|
||||
// First row: a gradient; every next row uses filter "Up" with zero
|
||||
// deltas, i.e. repeats it — a valid image that compresses well.
|
||||
const first = Buffer.alloc(1 + width * 8);
|
||||
for (let x = 0; x < width; x += 1)
|
||||
first.writeUInt16BE((x * 8) & 0xffff, 1 + x * 8);
|
||||
const repeat = Buffer.alloc(1 + width * 8);
|
||||
repeat[0] = 2;
|
||||
const deflate = createDeflate({ level: 1 });
|
||||
const chunks: Buffer[] = [];
|
||||
deflate.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
const ended = once(deflate, 'end');
|
||||
for (let y = 0; y < height; y += 1)
|
||||
if (!deflate.write(y === 0 ? first : repeat))
|
||||
await once(deflate, 'drain');
|
||||
deflate.end();
|
||||
await ended;
|
||||
return buildPng({
|
||||
width,
|
||||
height,
|
||||
colorType: 6,
|
||||
bitDepth: 16,
|
||||
idat: Buffer.concat(chunks),
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user