forked from mtusi2026/mtusi2026lab5
lab5: базовый коммит из lab4 (abba248)
Перенесено дерево lab4 целиком: NestJS-приложение с вложениями и S3,
Dockerfile, compose.yaml, infra/{haproxy,minio}, стендовые скрипты,
scripts/lab4, evidence/lab4 и contracts/extensions.openapi.json.
Задание lab5 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,examples},
tests, compose.example.yaml, .github/pull_request_template.md.
Адаптации при переносе:
- docker-проект mtusi-lab4 -> mtusi-lab5 и тег образа mtusi-messenger:lab5,
чтобы тома и контейнеры не пересекались с lab4 (scripts/stop-one.sh:
LAB_PROJECT вместо LAB4_PROJECT);
- Makefile: цели lab5 сохранены, добавлены стендовые (stand-up/down,
wait-ready, init-env, test-e2e, test-dependencies, s3-security,
consistency, bench);
- .env.example: реальные переменные приложения и стенда lab4 (без них
compose.yaml не поднимается) + блок lab5 (BROKER_URL_FILE, WORKER_*).
This commit is contained in:
@@ -0,0 +1,674 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { Pool } from 'pg';
|
||||
import { createClient } from 'redis';
|
||||
import type { SessionResponse } from '../src/auth/auth.service.js';
|
||||
import type { Chat } from '../src/chats/chat.js';
|
||||
import type { ApiErrorBody } from '../src/common/errors/api-error.js';
|
||||
import type { Page } from '../src/common/http/page.js';
|
||||
import type { Message } from '../src/messages/message.js';
|
||||
import type { User } from '../src/users/user.js';
|
||||
|
||||
// The suite is black-box: run it against the compiled application process.
|
||||
// Vitest sets process.env.BASE_URL itself (Vite base), so the API URL uses its own name.
|
||||
const baseUrl = (process.env.API_BASE_URL ?? 'http://localhost:8080').replace(
|
||||
/\/+$/u,
|
||||
'',
|
||||
);
|
||||
const basicChallenge = 'Basic realm="messenger", charset="UTF-8"';
|
||||
const bearerChallenge = 'Bearer realm="messenger"';
|
||||
const password = 'integration:пароль🔐';
|
||||
const runId = randomUUID().replaceAll('-', '').slice(0, 12);
|
||||
const usernames: string[] = [];
|
||||
const tokens: string[] = [];
|
||||
let sequence = 0;
|
||||
let database: Pool;
|
||||
let redis: ReturnType<typeof createClient>;
|
||||
|
||||
type Actor = { user: User; password: string; token: string };
|
||||
type HttpResult<T> = { body: T; response: Response };
|
||||
|
||||
async function http<T = unknown>(
|
||||
path: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<HttpResult<T>> {
|
||||
const response = await fetch(`${baseUrl}${path}`, init);
|
||||
const text = await response.text();
|
||||
let body: unknown = undefined;
|
||||
if (text) {
|
||||
try {
|
||||
body = JSON.parse(text);
|
||||
} catch {
|
||||
body = text;
|
||||
}
|
||||
}
|
||||
return { body: body as T, response };
|
||||
}
|
||||
|
||||
function json(
|
||||
body: unknown,
|
||||
headers: Record<string, string> = {},
|
||||
): RequestInit {
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
};
|
||||
}
|
||||
|
||||
function basic(username: string, secret: string): string {
|
||||
return `Basic ${Buffer.from(`${username}:${secret}`, 'utf8').toString('base64')}`;
|
||||
}
|
||||
|
||||
function bearer(token: string): Record<string, string> {
|
||||
return { authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
function idempotencyKey(): Record<string, string> {
|
||||
return { 'idempotency-key': randomUUID().replaceAll('-', '') };
|
||||
}
|
||||
|
||||
function messageHeaders(token: string): Record<string, string> {
|
||||
return { ...bearer(token), ...idempotencyKey() };
|
||||
}
|
||||
|
||||
async function register(
|
||||
displayName = 'Интеграционный пользователь',
|
||||
secret = password,
|
||||
): Promise<User> {
|
||||
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
|
||||
usernames.push(username);
|
||||
const result = await http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: displayName, password: secret }),
|
||||
);
|
||||
expect(result.response.status).toBe(201);
|
||||
return result.body;
|
||||
}
|
||||
|
||||
async function login(user: User, secret = password): Promise<SessionResponse> {
|
||||
const result = await http<SessionResponse>('/api/v1/auth/sessions', {
|
||||
method: 'POST',
|
||||
headers: { authorization: basic(user.username, secret) },
|
||||
});
|
||||
expect(result.response.status).toBe(201);
|
||||
tokens.push(result.body.token);
|
||||
return result.body;
|
||||
}
|
||||
|
||||
async function actor(displayName?: string): Promise<Actor> {
|
||||
const user = await register(displayName);
|
||||
const session = await login(user);
|
||||
return { user, password, token: session.token };
|
||||
}
|
||||
|
||||
function expectError(
|
||||
result: HttpResult<ApiErrorBody>,
|
||||
status: number,
|
||||
code: string,
|
||||
): void {
|
||||
expect(result.response.status).toBe(status);
|
||||
expect(result.body.error.code).toBe(code);
|
||||
expect(result.body.error.request_id).toBe(
|
||||
result.response.headers.get('x-request-id'),
|
||||
);
|
||||
}
|
||||
|
||||
describe('HTTP integration contract', () => {
|
||||
beforeAll(async () => {
|
||||
database = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
connectionTimeoutMillis: 5000,
|
||||
});
|
||||
redis = createClient({
|
||||
url: process.env.REDIS_URL,
|
||||
socket: { reconnectStrategy: false },
|
||||
});
|
||||
redis.on('error', () => {});
|
||||
await redis.connect();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (usernames.length) {
|
||||
await database.query('BEGIN');
|
||||
try {
|
||||
await database.query(
|
||||
`DELETE FROM messages WHERE sender_id IN (SELECT id FROM users WHERE username = ANY($1::text[]))`,
|
||||
[usernames],
|
||||
);
|
||||
await database.query(
|
||||
`DELETE FROM chats WHERE id IN (SELECT chat_id FROM chat_members WHERE user_id IN (SELECT id FROM users WHERE username = ANY($1::text[])))`,
|
||||
[usernames],
|
||||
);
|
||||
await database.query(
|
||||
'DELETE FROM users WHERE username = ANY($1::text[])',
|
||||
[usernames],
|
||||
);
|
||||
await database.query('COMMIT');
|
||||
} catch (error) {
|
||||
await database.query('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (redis.isOpen) redis.destroy();
|
||||
await database.end();
|
||||
});
|
||||
|
||||
it('serves liveness and requires real session authentication', async () => {
|
||||
const live = await http<{ status: string }>('/health/live');
|
||||
expect(live.response.status).toBe(200);
|
||||
expect(live.body).toEqual({ status: 'ok' });
|
||||
const denied = await http<ApiErrorBody>('/api/v1/users/me');
|
||||
expectError(denied, 401, 'unauthorized');
|
||||
expect(denied.response.headers.get('www-authenticate')).toBe(
|
||||
bearerChallenge,
|
||||
);
|
||||
});
|
||||
|
||||
it('measures string lengths in Unicode code points', async () => {
|
||||
const emoji = '🔐';
|
||||
const username = (suffix: string) =>
|
||||
`e2e_${runId}_${suffix}`.slice(0, 32);
|
||||
const rejected = await http<ApiErrorBody>(
|
||||
'/api/v1/users',
|
||||
json({
|
||||
username: username('cp_short'),
|
||||
display_name: 'Code points',
|
||||
password: emoji.repeat(11),
|
||||
}),
|
||||
);
|
||||
expectError(rejected, 400, 'invalid_request');
|
||||
const tooLongPassword = await http<ApiErrorBody>(
|
||||
'/api/v1/users',
|
||||
json({
|
||||
username: username('cp_long'),
|
||||
display_name: 'Code points',
|
||||
password: emoji.repeat(129),
|
||||
}),
|
||||
);
|
||||
expectError(tooLongPassword, 400, 'invalid_request');
|
||||
const tooLongName = await http<ApiErrorBody>(
|
||||
'/api/v1/users',
|
||||
json({
|
||||
username: username('cp_name'),
|
||||
display_name: emoji.repeat(101),
|
||||
password,
|
||||
}),
|
||||
);
|
||||
expectError(tooLongName, 400, 'invalid_request');
|
||||
|
||||
const shortUsername = username('cp_ok');
|
||||
usernames.push(shortUsername);
|
||||
const boundaryPassword = emoji.repeat(12);
|
||||
const created = await http<User>(
|
||||
'/api/v1/users',
|
||||
json({
|
||||
username: shortUsername,
|
||||
display_name: emoji.repeat(100),
|
||||
password: boundaryPassword,
|
||||
}),
|
||||
);
|
||||
expect(created.response.status).toBe(201);
|
||||
expect([...created.body.display_name].length).toBe(100);
|
||||
// The stored password keeps all 12 code points: authentication works.
|
||||
const session = await http<SessionResponse>('/api/v1/auth/sessions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: basic(shortUsername, boundaryPassword),
|
||||
},
|
||||
});
|
||||
expect(session.response.status).toBe(201);
|
||||
tokens.push(session.body.token);
|
||||
|
||||
const longTitleRejected = await http<ApiErrorBody>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: emoji.repeat(101), member_ids: [created.body.id] },
|
||||
bearer(session.body.token),
|
||||
),
|
||||
);
|
||||
expectError(longTitleRejected, 400, 'invalid_request');
|
||||
const longTitle = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: emoji.repeat(100), member_ids: [created.body.id] },
|
||||
bearer(session.body.token),
|
||||
),
|
||||
);
|
||||
expect(longTitle.response.status).toBe(201);
|
||||
const tooLongText = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${longTitle.body.id}/messages`,
|
||||
json({ text: emoji.repeat(4001) }, messageHeaders(session.body.token)),
|
||||
);
|
||||
expectError(tooLongText, 400, 'invalid_request');
|
||||
const boundaryText = await http<Message>(
|
||||
`/api/v1/chats/${longTitle.body.id}/messages`,
|
||||
json({ text: emoji.repeat(4000) }, messageHeaders(session.body.token)),
|
||||
);
|
||||
expect(boundaryText.response.status).toBe(201);
|
||||
expect([...boundaryText.body.text].length).toBe(4000);
|
||||
});
|
||||
|
||||
it('rejects whitespace-only and too-short credentials', async () => {
|
||||
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
|
||||
usernames.push(username);
|
||||
const cases = [
|
||||
{ password: ' '.repeat(12), display_name: 'Пользователь' },
|
||||
{ password: '\t'.repeat(16), display_name: 'Пользователь' },
|
||||
{ password: 'short-pass', display_name: 'Пользователь' },
|
||||
{ password, display_name: ' ' },
|
||||
];
|
||||
for (const body of cases) {
|
||||
const result = await http<ApiErrorBody>(
|
||||
'/api/v1/users',
|
||||
json({ username, ...body }),
|
||||
);
|
||||
expectError(result, 400, 'invalid_request');
|
||||
}
|
||||
const accepted = await http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: 'Пользователь', password }),
|
||||
);
|
||||
expect(accepted.response.status).toBe(201);
|
||||
});
|
||||
|
||||
it('registers, logs in with Unicode/colon password, and challenges malformed Basic', async () => {
|
||||
const user = await register();
|
||||
const session = await login(user);
|
||||
expect(session.user.id).toBe(user.id);
|
||||
expect(session.token_type).toBe('Bearer');
|
||||
const me = await http<User>('/api/v1/users/me', {
|
||||
headers: bearer(session.token),
|
||||
});
|
||||
expect(me.response.status).toBe(200);
|
||||
expect(me.body.id).toBe(user.id);
|
||||
for (const authorization of [
|
||||
'Basic !!!',
|
||||
'Basic YWJj',
|
||||
'Bearer nope',
|
||||
]) {
|
||||
const result = await http<ApiErrorBody>('/api/v1/auth/sessions', {
|
||||
method: 'POST',
|
||||
headers: { authorization },
|
||||
});
|
||||
expectError(result, 401, 'unauthorized');
|
||||
expect(result.response.headers.get('www-authenticate')).toBe(
|
||||
basicChallenge,
|
||||
);
|
||||
}
|
||||
const bodyResult = await http<ApiErrorBody>('/api/v1/auth/sessions', {
|
||||
...json({ unexpected: true }),
|
||||
headers: { authorization: basic(user.username, password) },
|
||||
});
|
||||
expectError(bodyResult, 400, 'invalid_request');
|
||||
});
|
||||
|
||||
it('returns conflict for concurrent duplicate registration', async () => {
|
||||
const username = `e2e_${runId}_race`.slice(0, 32);
|
||||
usernames.push(username);
|
||||
const results = await Promise.all([
|
||||
http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: 'Race A', password }),
|
||||
),
|
||||
http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: 'Race B', password }),
|
||||
),
|
||||
]);
|
||||
expect(
|
||||
results.filter((item) => item.response.status === 201),
|
||||
'duplicate registration must create exactly one user',
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
results.filter((item) => item.response.status === 409),
|
||||
'loser of the race must receive 409, not 500',
|
||||
).toHaveLength(1);
|
||||
// The database unique index is the race-proof guard, so verify its effect.
|
||||
const persisted = await database.query<{ count: string }>(
|
||||
'SELECT count(*)::text AS count FROM users WHERE username = $1',
|
||||
[username],
|
||||
);
|
||||
expect(persisted.rows[0]?.count).toBe('1');
|
||||
});
|
||||
|
||||
it('uses Bearer only, ignores X-User-Id spoofing, and prevents logout replay', async () => {
|
||||
const alice = await actor('Алиса');
|
||||
const bob = await actor('Боб');
|
||||
const spoof = await http<ApiErrorBody>('/api/v1/users/me', {
|
||||
headers: { ...bearer(alice.token), 'x-user-id': bob.user.id },
|
||||
});
|
||||
expect(spoof.response.status).toBe(200);
|
||||
expect((spoof.body as unknown as User).id).toBe(alice.user.id);
|
||||
const basicBusiness = await http<ApiErrorBody>('/api/v1/users/me', {
|
||||
headers: { authorization: basic(alice.user.username, password) },
|
||||
});
|
||||
expectError(basicBusiness, 401, 'unauthorized');
|
||||
expect(basicBusiness.response.headers.get('www-authenticate')).toBe(
|
||||
bearerChallenge,
|
||||
);
|
||||
const logout = await http('/api/v1/auth/sessions/current', {
|
||||
method: 'DELETE',
|
||||
headers: bearer(alice.token),
|
||||
});
|
||||
expect(logout.response.status).toBe(204);
|
||||
const replay = await http<ApiErrorBody>('/api/v1/users/me', {
|
||||
headers: bearer(alice.token),
|
||||
});
|
||||
expectError(replay, 401, 'unauthorized');
|
||||
});
|
||||
|
||||
it('rejects unknown and duplicate chat members and hides chats from outsiders', async () => {
|
||||
const alice = await actor();
|
||||
const bob = await actor();
|
||||
const outsider = await actor();
|
||||
const unknown = await http<ApiErrorBody>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: 'unknown', member_ids: [alice.user.id, randomUUID()] },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(unknown, 400, 'invalid_request');
|
||||
const leaked = await http<ApiErrorBody>(`/api/v1/chats?limit=100`, {
|
||||
headers: bearer(alice.token),
|
||||
});
|
||||
expect(leaked.response.status).toBe(200);
|
||||
expect(
|
||||
(leaked.body as unknown as Page<Chat>).items.some(
|
||||
(item) => item.title === 'unknown',
|
||||
),
|
||||
).toBe(false);
|
||||
const duplicate = await http<ApiErrorBody>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{
|
||||
title: 'duplicate',
|
||||
member_ids: [alice.user.id, alice.user.id],
|
||||
},
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(duplicate, 400, 'invalid_request');
|
||||
const created = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{
|
||||
title: `chat-${runId}`,
|
||||
member_ids: [alice.user.id, bob.user.id],
|
||||
},
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expect(created.response.status).toBe(201);
|
||||
const hidden = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${created.body.id}`,
|
||||
{ headers: bearer(outsider.token) },
|
||||
);
|
||||
expectError(hidden, 404, 'not_found');
|
||||
});
|
||||
|
||||
it('keeps sender server-owned and makes writes visible to a second session', async () => {
|
||||
const alice = await actor();
|
||||
const secondSession = (await login(alice.user)).token;
|
||||
const chat = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: `messages-${runId}`, member_ids: [alice.user.id] },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expect(chat.response.status).toBe(201);
|
||||
const blank = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json(
|
||||
{ text: ' \n\t', sender_id: randomUUID() },
|
||||
messageHeaders(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(blank, 400, 'invalid_request');
|
||||
const spoof = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json(
|
||||
{ text: 'hello', sender_id: randomUUID() },
|
||||
messageHeaders(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(spoof, 400, 'invalid_request');
|
||||
await http(`/api/v1/chats/${chat.body.id}/messages?limit=50`, {
|
||||
headers: bearer(secondSession),
|
||||
});
|
||||
const sent = await http<Message>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json({ text: 'hello' }, messageHeaders(alice.token)),
|
||||
);
|
||||
expect(sent.response.status).toBe(201);
|
||||
expect(sent.body.sender_id).toBe(alice.user.id);
|
||||
const page = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=50`,
|
||||
{ headers: bearer(secondSession) },
|
||||
);
|
||||
expect(page.response.status).toBe(200);
|
||||
expect(page.body.items.map((item) => item.id)).toContain(sent.body.id);
|
||||
});
|
||||
|
||||
it('validates cursor, limits, malformed JSON, and paginates without repeats', async () => {
|
||||
const alice = await actor();
|
||||
const chat = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: `pages-${runId}`, member_ids: [alice.user.id] },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
for (const text of ['one', 'two', 'three']) {
|
||||
const sent = await http(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json({ text }, messageHeaders(alice.token)),
|
||||
);
|
||||
expect(sent.response.status).toBe(201);
|
||||
}
|
||||
const invalidLimit = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=101`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expectError(invalidLimit, 400, 'invalid_request');
|
||||
const invalidCursor = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?cursor=not-a-cursor`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expectError(invalidCursor, 400, 'invalid_request');
|
||||
const rolledOver = http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?cursor=${encodeURIComponent(
|
||||
Buffer.from(
|
||||
JSON.stringify({
|
||||
scope: `messages:${chat.body.id}`,
|
||||
created_at: '2026-02-31T00:00:00.000Z',
|
||||
id: randomUUID(),
|
||||
}),
|
||||
'utf8',
|
||||
).toString('base64url'),
|
||||
)}`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expectError(await rolledOver, 400, 'invalid_request');
|
||||
const malformed = await http<ApiErrorBody>('/api/v1/users', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: '{',
|
||||
});
|
||||
expectError(malformed, 400, 'invalid_request');
|
||||
const first = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=2`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expect(first.body.items).toHaveLength(2);
|
||||
const second = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=2&cursor=${encodeURIComponent(first.body.next_cursor!)}`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expect(second.body.items).toHaveLength(1);
|
||||
expect(
|
||||
new Set(
|
||||
[...first.body.items, ...second.body.items].map(
|
||||
(item) => item.id,
|
||||
),
|
||||
).size,
|
||||
).toBe(3);
|
||||
});
|
||||
|
||||
it.skipIf(process.env.SESSION_TTL_SECONDS !== '2')(
|
||||
'expires sessions with TTL=2',
|
||||
async () => {
|
||||
const user = await register();
|
||||
const session = await login(user);
|
||||
await sleep(2300);
|
||||
const expired = await http<ApiErrorBody>('/api/v1/users/me', {
|
||||
headers: bearer(session.token),
|
||||
});
|
||||
expectError(expired, 401, 'unauthorized');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// lab3: the Idempotency-Key contract of POST /chats/{id}/messages. The suite is
|
||||
// black-box, so these assertions hold for one replica and for a load-balanced
|
||||
// fleet alike.
|
||||
describe('message idempotency', () => {
|
||||
async function chatFor(token: string, memberIds: string[]): Promise<string> {
|
||||
const created = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json({ title: `idempotency-${runId}`, member_ids: memberIds }, bearer(token)),
|
||||
);
|
||||
expect(created.response.status).toBe(201);
|
||||
return created.body.id;
|
||||
}
|
||||
|
||||
async function textsIn(chatId: string, token: string): Promise<string[]> {
|
||||
const page = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chatId}/messages?limit=100`,
|
||||
{ headers: bearer(token) },
|
||||
);
|
||||
expect(page.response.status).toBe(200);
|
||||
return page.body.items.map((item) => item.text);
|
||||
}
|
||||
|
||||
it('requires a well-formed Idempotency-Key', async () => {
|
||||
const alice = await actor();
|
||||
const chatId = await chatFor(alice.token, [alice.user.id]);
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
const missing = await http<ApiErrorBody>(
|
||||
path,
|
||||
json({ text: 'без ключа' }, bearer(alice.token)),
|
||||
);
|
||||
expectError(missing, 400, 'invalid_request');
|
||||
for (const key of ['has space', 'comma,separated', 'x'.repeat(129)]) {
|
||||
const malformed = await http<ApiErrorBody>(
|
||||
path,
|
||||
json({ text: 'плохой ключ' }, { ...bearer(alice.token), 'idempotency-key': key }),
|
||||
);
|
||||
expectError(malformed, 400, 'invalid_request');
|
||||
}
|
||||
});
|
||||
|
||||
it('replays the stored response and conflicts on a different body', async () => {
|
||||
const alice = await actor();
|
||||
const chatId = await chatFor(alice.token, [alice.user.id]);
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
const key = randomUUID().replaceAll('-', '');
|
||||
const headers = { ...bearer(alice.token), 'idempotency-key': key };
|
||||
const text = `повтор ${runId}`;
|
||||
|
||||
const first = await http<Message>(path, json({ text }, headers));
|
||||
expect(first.response.status).toBe(201);
|
||||
const replayed = await http<Message>(path, json({ text }, headers));
|
||||
expect(replayed.response.status).toBe(201);
|
||||
expect(replayed.body).toEqual(first.body);
|
||||
|
||||
const conflict = await http<ApiErrorBody>(
|
||||
path,
|
||||
json({ text: 'другой body' }, headers),
|
||||
);
|
||||
expectError(conflict, 409, 'conflict');
|
||||
|
||||
expect(await textsIn(chatId, alice.token)).toEqual([text]);
|
||||
});
|
||||
|
||||
it('creates exactly one message for concurrent requests with one key', async () => {
|
||||
const alice = await actor();
|
||||
const chatId = await chatFor(alice.token, [alice.user.id]);
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
const headers = { ...bearer(alice.token), ...idempotencyKey() };
|
||||
const text = `конкурентный повтор ${runId}`;
|
||||
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 8 }, () => http<Message>(path, json({ text }, headers))),
|
||||
);
|
||||
for (const result of results) expect(result.response.status).toBe(201);
|
||||
const ids = new Set(results.map((result) => result.body.id));
|
||||
expect(
|
||||
ids.size,
|
||||
'one key must resolve to exactly one message across replicas',
|
||||
).toBe(1);
|
||||
expect(await textsIn(chatId, alice.token)).toEqual([text]);
|
||||
});
|
||||
|
||||
it('replays a key created by another replica', async () => {
|
||||
// lab3: повтор с тем же ключом может прийти на любую реплику, поэтому
|
||||
// проверяем не только сам повтор, но и то, что его обслужила другая реплика
|
||||
// (иначе тест не отличал бы общий журнал от локального состояния процесса).
|
||||
const alice = await actor();
|
||||
const chatId = await chatFor(alice.token, [alice.user.id]);
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
const key = randomUUID().replaceAll('-', '');
|
||||
const headers = { ...bearer(alice.token), 'idempotency-key': key };
|
||||
|
||||
const first = await http<Message>(path, json({ text: 'переключение реплики' }, headers));
|
||||
expect(first.response.status).toBe(201);
|
||||
const firstInstance = first.response.headers.get('x-instance-id');
|
||||
expect(firstInstance).toBeTruthy();
|
||||
|
||||
let replay = first;
|
||||
let replayInstance = firstInstance;
|
||||
for (let attempt = 0; attempt < 12 && replayInstance === firstInstance; attempt += 1) {
|
||||
replay = await http<Message>(path, json({ text: 'переключение реплики' }, headers));
|
||||
expect(replay.response.status).toBe(201);
|
||||
replayInstance = replay.response.headers.get('x-instance-id');
|
||||
}
|
||||
expect(
|
||||
replayInstance,
|
||||
'повтор должен был прийти на другую реплику (round-robin за LB)',
|
||||
).not.toBe(firstInstance);
|
||||
expect(replay.body).toEqual(first.body);
|
||||
expect(await textsIn(chatId, alice.token)).toEqual(['переключение реплики']);
|
||||
});
|
||||
|
||||
it('scopes the key per user and per chat path', async () => {
|
||||
const alice = await actor();
|
||||
const bob = await actor();
|
||||
const outsider = await actor();
|
||||
const chatId = await chatFor(alice.token, [alice.user.id, bob.user.id]);
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
const key = randomUUID().replaceAll('-', '');
|
||||
const foreignChatId = await chatFor(outsider.token, [outsider.user.id]);
|
||||
|
||||
const denied = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${foreignChatId}/messages`,
|
||||
json({ text: 'чужое' }, { ...bearer(alice.token), 'idempotency-key': key }),
|
||||
);
|
||||
expectError(denied, 404, 'not_found');
|
||||
|
||||
const mine = await http<Message>(
|
||||
path,
|
||||
json({ text: 'своё' }, { ...bearer(alice.token), 'idempotency-key': key }),
|
||||
);
|
||||
expect(mine.response.status).toBe(201);
|
||||
const other = await http<Message>(
|
||||
path,
|
||||
json({ text: 'своё' }, { ...bearer(bob.token), 'idempotency-key': key }),
|
||||
);
|
||||
expect(other.response.status).toBe(201);
|
||||
expect(other.body.id).not.toBe(mine.body.id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,509 @@
|
||||
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import net from 'node:net';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import type { Pool } from 'pg';
|
||||
import type { ApiErrorBody } from '../src/common/errors/api-error.js';
|
||||
import type { Page } from '../src/common/http/page.js';
|
||||
import type { Message } from '../src/messages/message.js';
|
||||
import {
|
||||
Actor,
|
||||
actor,
|
||||
baseUrl,
|
||||
bearer,
|
||||
createChat,
|
||||
database,
|
||||
download,
|
||||
expectError,
|
||||
http,
|
||||
postMessage,
|
||||
upload,
|
||||
uploadRaw,
|
||||
} from './support/e2e.js';
|
||||
import sharp from 'sharp';
|
||||
import { jpegWithMetadata, jpegWithoutScanData } from './support/jpeg.js';
|
||||
import {
|
||||
maxPixelsRgba16Png,
|
||||
noisePng,
|
||||
padPngTo,
|
||||
pixelBombPng,
|
||||
pngWithGarbageIdat,
|
||||
} from './support/png.js';
|
||||
|
||||
const png = readFileSync(
|
||||
new URL('../../tests/fixtures/sample.png', import.meta.url),
|
||||
);
|
||||
const jpeg = readFileSync(new URL('./fixtures/sample.jpg', import.meta.url));
|
||||
const progressive = readFileSync(
|
||||
new URL('./fixtures/sample-progressive.jpg', import.meta.url),
|
||||
);
|
||||
const MAX = 10_485_760;
|
||||
|
||||
let db: Pool;
|
||||
let alice: Actor;
|
||||
let bob: Actor;
|
||||
let eve: Actor;
|
||||
let chatId: string;
|
||||
let eveChatId: string;
|
||||
let leftoverChatId: string;
|
||||
|
||||
const sha256 = (data: Uint8Array) =>
|
||||
createHash('sha256').update(data).digest('hex');
|
||||
|
||||
async function ready(data: Buffer, type = 'image/png', chat = chatId) {
|
||||
const result = await upload(alice.token, chat, data, {
|
||||
contentType: type,
|
||||
});
|
||||
expect(result.response.status).toBe(201);
|
||||
return result.body;
|
||||
}
|
||||
|
||||
describe('attachments (proxy upload)', () => {
|
||||
beforeAll(async () => {
|
||||
db = database();
|
||||
alice = await actor();
|
||||
bob = await actor();
|
||||
eve = await actor();
|
||||
chatId = (await createChat(alice, [bob])).id;
|
||||
eveChatId = (await createChat(eve, [])).id;
|
||||
// Chat for rejected uploads: it must end up without any row.
|
||||
leftoverChatId = (await createChat(alice, [])).id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await db.end();
|
||||
});
|
||||
|
||||
it('stores a PNG and serves it only to chat members', async () => {
|
||||
const created = await upload(alice.token, chatId, png, {
|
||||
filename: 'Снимок.png',
|
||||
});
|
||||
expect(created.response.status).toBe(201);
|
||||
expect(created.body).toMatchObject({
|
||||
chat_id: chatId,
|
||||
owner_id: alice.user.id,
|
||||
filename: 'Снимок.png',
|
||||
content_type: 'image/png',
|
||||
size_bytes: png.length,
|
||||
sha256: sha256(png),
|
||||
status: 'ready',
|
||||
variants: [],
|
||||
error_code: null,
|
||||
});
|
||||
const id = created.body.id;
|
||||
|
||||
const metadata = await http<typeof created.body>(
|
||||
`/api/v1/attachments/${id}`,
|
||||
{ headers: bearer(bob.token) },
|
||||
);
|
||||
expect(metadata.response.status).toBe(200);
|
||||
expect(metadata.body.sha256).toBe(sha256(png));
|
||||
|
||||
const content = await download(bob.token, id);
|
||||
expect(content.response.status).toBe(200);
|
||||
expect(content.response.headers.get('content-type')).toBe('image/png');
|
||||
expect(content.response.headers.get('x-content-type-options')).toBe(
|
||||
'nosniff',
|
||||
);
|
||||
expect(content.response.headers.get('content-length')).toBe(
|
||||
String(png.length),
|
||||
);
|
||||
expect(content.response.headers.get('content-disposition')).toContain(
|
||||
"filename*=UTF-8''%D0%A1",
|
||||
);
|
||||
expect(content.bytes.equals(png)).toBe(true);
|
||||
|
||||
for (const path of [`/${id}`, `/${id}/content`]) {
|
||||
expectError(
|
||||
await http(`/api/v1/attachments${path}`, {
|
||||
headers: bearer(eve.token),
|
||||
}),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
}
|
||||
expectError(
|
||||
await http(`/api/v1/attachments/${id}/content`),
|
||||
401,
|
||||
'unauthorized',
|
||||
);
|
||||
expectError(await upload(eve.token, chatId, png), 404, 'not_found');
|
||||
expectError(
|
||||
await http(`/api/v1/attachments/${randomUUID()}`, {
|
||||
headers: bearer(bob.token),
|
||||
}),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['JPEG', jpeg],
|
||||
['progressive JPEG', progressive],
|
||||
])('accepts a %s', async (_name, data) => {
|
||||
const created = await ready(data, 'image/jpeg');
|
||||
expect(created.content_type).toBe('image/jpeg');
|
||||
const content = await download(alice.token, created.id);
|
||||
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);
|
||||
expect(created.size_bytes).toBe(MAX);
|
||||
expectError(
|
||||
await upload(alice.token, leftoverChatId, padPngTo(png, MAX + 1)),
|
||||
413,
|
||||
'payload_too_large',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a pixel bomb before storing anything', async () => {
|
||||
expectError(
|
||||
await upload(alice.token, leftoverChatId, pixelBombPng()),
|
||||
413,
|
||||
'payload_too_large',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects damaged images', async () => {
|
||||
const flipped = Buffer.from(png);
|
||||
flipped[Math.floor(png.length / 2)] ^= 0xff;
|
||||
const cases: Buffer[] = [
|
||||
png.subarray(0, png.length - 100),
|
||||
flipped,
|
||||
Buffer.concat([png.subarray(0, 8), randomBytes(2048)]),
|
||||
Buffer.alloc(0),
|
||||
// Structure and CRCs are fine; the pixel data does not decode.
|
||||
pngWithGarbageIdat(),
|
||||
];
|
||||
for (const data of cases)
|
||||
expectError(
|
||||
await upload(alice.token, leftoverChatId, data),
|
||||
415,
|
||||
'unsupported_media_type',
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['baseline', jpeg],
|
||||
['progressive', progressive],
|
||||
])('rejects a %s JPEG without scan data', async (_name, data) => {
|
||||
expectError(
|
||||
await upload(
|
||||
alice.token,
|
||||
leftoverChatId,
|
||||
jpegWithoutScanData(data),
|
||||
{
|
||||
contentType: 'image/jpeg',
|
||||
},
|
||||
),
|
||||
415,
|
||||
'unsupported_media_type',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a content type that does not match the bytes', async () => {
|
||||
const gif = Buffer.from('GIF89a' + 'x'.repeat(64));
|
||||
const cases: [Buffer, string][] = [
|
||||
[png, 'image/jpeg'],
|
||||
[jpeg, 'image/png'],
|
||||
[gif, 'image/png'],
|
||||
[png, 'text/plain'],
|
||||
[png, 'application/octet-stream'],
|
||||
];
|
||||
for (const [data, type] of cases)
|
||||
expectError(
|
||||
await upload(alice.token, leftoverChatId, data, {
|
||||
contentType: type,
|
||||
}),
|
||||
415,
|
||||
'unsupported_media_type',
|
||||
);
|
||||
});
|
||||
|
||||
it('validates filenames by code points and forbidden characters', async () => {
|
||||
const bad = [
|
||||
'?filename=a%2Fb.png',
|
||||
'?filename=a%5Cb.png',
|
||||
'?filename=a%00b.png',
|
||||
'?filename=a%07b.png',
|
||||
'?filename=%E2%80%AEgnp.exe',
|
||||
'?filename=%20',
|
||||
'?filename=',
|
||||
`?filename=${'a'.repeat(256)}`,
|
||||
'',
|
||||
'?filename=a.png&filename=b.png',
|
||||
];
|
||||
for (const query of bad)
|
||||
expectError(
|
||||
await uploadRaw(alice.token, leftoverChatId, query, png),
|
||||
400,
|
||||
'invalid_request',
|
||||
);
|
||||
const long = '😀'.repeat(255);
|
||||
const created = await upload(alice.token, chatId, png, {
|
||||
filename: long,
|
||||
});
|
||||
expect(created.response.status).toBe(201);
|
||||
expect(created.body.filename).toBe(long);
|
||||
});
|
||||
|
||||
it('links attachments to messages in the given order', async () => {
|
||||
const first = await ready(png);
|
||||
const second = await ready(jpeg, 'image/jpeg');
|
||||
const order = [second.id, first.id];
|
||||
const key = randomUUID().replaceAll('-', '');
|
||||
const sent = await postMessage(
|
||||
alice.token,
|
||||
chatId,
|
||||
{ text: '', attachment_ids: order },
|
||||
key,
|
||||
);
|
||||
expect(sent.response.status).toBe(201);
|
||||
expect(sent.body.attachment_ids).toEqual(order);
|
||||
|
||||
const history = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chatId}/messages?limit=100`,
|
||||
{ headers: bearer(bob.token) },
|
||||
);
|
||||
const stored = history.body.items.find((m) => m.id === sent.body.id);
|
||||
expect(stored?.attachment_ids).toEqual(order);
|
||||
|
||||
const replay = await postMessage(
|
||||
alice.token,
|
||||
chatId,
|
||||
{ text: '', attachment_ids: order },
|
||||
key,
|
||||
);
|
||||
expect(replay.response.status).toBe(201);
|
||||
expect(replay.body).toEqual(sent.body);
|
||||
expectError(
|
||||
await postMessage(
|
||||
alice.token,
|
||||
chatId,
|
||||
{ text: '', attachment_ids: [first.id] },
|
||||
key,
|
||||
),
|
||||
409,
|
||||
'conflict',
|
||||
);
|
||||
|
||||
const textOnly = await postMessage(alice.token, chatId, {
|
||||
text: 'hello',
|
||||
});
|
||||
expect(textOnly.response.status).toBe(201);
|
||||
expect(textOnly.body.attachment_ids).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects invalid attachment references', async () => {
|
||||
const mine = await ready(png);
|
||||
const foreign = await upload(eve.token, eveChatId, png);
|
||||
expect(foreign.response.status).toBe(201);
|
||||
expectError(
|
||||
await postMessage(alice.token, chatId, { text: '' }),
|
||||
400,
|
||||
'invalid_request',
|
||||
);
|
||||
expectError(
|
||||
await postMessage(alice.token, chatId, {
|
||||
text: '',
|
||||
attachment_ids: [foreign.body.id],
|
||||
}),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
expectError(
|
||||
await postMessage(alice.token, chatId, {
|
||||
text: 'x',
|
||||
attachment_ids: [randomUUID()],
|
||||
}),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
for (const ids of [
|
||||
[mine.id, mine.id],
|
||||
[mine.id, mine.id.toUpperCase()],
|
||||
Array.from({ length: 11 }, () => randomUUID()),
|
||||
null,
|
||||
['not-a-uuid'],
|
||||
])
|
||||
expectError(
|
||||
await postMessage(alice.token, chatId, {
|
||||
text: 'x',
|
||||
attachment_ids: ids,
|
||||
}),
|
||||
400,
|
||||
'invalid_request',
|
||||
);
|
||||
});
|
||||
|
||||
it('serves unknown content variants as errors, not bytes', async () => {
|
||||
const created = await ready(png);
|
||||
const variant = (name: string) =>
|
||||
http<ApiErrorBody>(
|
||||
`/api/v1/attachments/${created.id}/content?variant=${name}`,
|
||||
{
|
||||
headers: bearer(alice.token),
|
||||
},
|
||||
);
|
||||
expect((await variant('original')).response.status).toBe(200);
|
||||
expectError(await variant('thumbnail'), 404, 'not_found');
|
||||
expectError(await variant('bogus'), 400, 'invalid_request');
|
||||
});
|
||||
|
||||
it('answers 4xx, not 500, for raw image or text bodies on JSON routes', async () => {
|
||||
for (const [type, status, code] of [
|
||||
['image/png', 415, 'unsupported_media_type'],
|
||||
['image/jpeg', 415, 'unsupported_media_type'],
|
||||
['text/plain', 400, 'invalid_request'],
|
||||
] as const) {
|
||||
const result = await http<ApiErrorBody>('/api/v1/users', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': type },
|
||||
body: 'x',
|
||||
});
|
||||
expectError(result, status, code);
|
||||
}
|
||||
});
|
||||
|
||||
it('removes the pending row when the client drops the connection', async () => {
|
||||
const data = noisePng(2 * 1024 * 1024);
|
||||
const url = new URL(baseUrl);
|
||||
const socket = net.connect(Number(url.port || 80), url.hostname);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.once('connect', resolve);
|
||||
socket.once('error', reject);
|
||||
});
|
||||
socket.on('error', () => {});
|
||||
socket.write(
|
||||
`POST /api/v1/chats/${leftoverChatId}/attachments?filename=cut.png HTTP/1.1\r\n` +
|
||||
`Host: ${url.host}\r\nAuthorization: Bearer ${alice.token}\r\n` +
|
||||
`Content-Type: image/png\r\nContent-Length: ${data.length}\r\n\r\n`,
|
||||
);
|
||||
socket.write(data.subarray(0, 512 * 1024));
|
||||
await sleep(500);
|
||||
socket.destroy();
|
||||
await settled(leftoverChatId);
|
||||
});
|
||||
|
||||
it('leaves no rows behind after rejected uploads', async () => {
|
||||
await settled(leftoverChatId);
|
||||
});
|
||||
});
|
||||
|
||||
async function settled(chat: string): Promise<void> {
|
||||
const deadline = Date.now() + 10_000;
|
||||
let count = -1;
|
||||
while (Date.now() < deadline) {
|
||||
const result = await db.query<{ count: string }>(
|
||||
'SELECT count(*) FROM attachments WHERE chat_id = $1',
|
||||
[chat],
|
||||
);
|
||||
count = Number(result.rows[0].count);
|
||||
if (count === 0) return;
|
||||
await sleep(250);
|
||||
}
|
||||
expect(count).toBe(0);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,344 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import type { Pool } from 'pg';
|
||||
import type { Attachment } from '../src/attachments/attachment.js';
|
||||
import type { DirectUpload } from '../src/attachments/direct-uploads.service.js';
|
||||
import type { ApiErrorBody } from '../src/common/errors/api-error.js';
|
||||
import {
|
||||
Actor,
|
||||
actor,
|
||||
bearer,
|
||||
createChat,
|
||||
database,
|
||||
download,
|
||||
expectError,
|
||||
http,
|
||||
json,
|
||||
postMessage,
|
||||
} from './support/e2e.js';
|
||||
import { noisePng, pixelBombPng } from './support/png.js';
|
||||
|
||||
const png = readFileSync(
|
||||
new URL('../../tests/fixtures/sample.png', import.meta.url),
|
||||
);
|
||||
const jpeg = readFileSync(new URL('./fixtures/sample.jpg', import.meta.url));
|
||||
const MAX = 10_485_760;
|
||||
const shortTtl = process.env.E2E_DIRECT_TTL_SHORT === '1';
|
||||
|
||||
let db: Pool;
|
||||
let alice: Actor;
|
||||
let bob: Actor;
|
||||
let eve: Actor;
|
||||
let chatId: string;
|
||||
|
||||
const sha256 = (data: Uint8Array) =>
|
||||
createHash('sha256').update(data).digest('hex');
|
||||
|
||||
function init(token: string, chat: string, body: Record<string, unknown>) {
|
||||
return http<DirectUpload & ApiErrorBody>(
|
||||
`/api/v1/chats/${chat}/attachments/direct-uploads`,
|
||||
json(body, bearer(token)),
|
||||
);
|
||||
}
|
||||
|
||||
function declaration(data: Buffer, contentType = 'image/png') {
|
||||
return {
|
||||
filename: 'direct.png',
|
||||
content_type: contentType,
|
||||
size_bytes: data.length,
|
||||
sha256: sha256(data),
|
||||
};
|
||||
}
|
||||
|
||||
async function initOk(data: Buffer, contentType = 'image/png') {
|
||||
const result = await init(
|
||||
alice.token,
|
||||
chatId,
|
||||
declaration(data, contentType),
|
||||
);
|
||||
expect(result.response.status).toBe(201);
|
||||
return result.body;
|
||||
}
|
||||
|
||||
// The PUT goes straight to the public S3 endpoint, not through the API.
|
||||
async function put(ticket: DirectUpload, data: Buffer): Promise<Response> {
|
||||
return fetch(ticket.url, {
|
||||
method: ticket.method,
|
||||
headers: ticket.headers,
|
||||
body: data as unknown as BodyInit,
|
||||
});
|
||||
}
|
||||
|
||||
function complete(token: string, id: string) {
|
||||
return http<Attachment & ApiErrorBody>(
|
||||
`/api/v1/attachments/${id}/complete`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: bearer(token),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
describe('direct upload (presigned PUT)', () => {
|
||||
beforeAll(async () => {
|
||||
db = database();
|
||||
alice = await actor();
|
||||
bob = await actor();
|
||||
eve = await actor();
|
||||
chatId = (await createChat(alice, [bob])).id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await db.end();
|
||||
});
|
||||
|
||||
it('uploads around the API and exposes the attachment after complete', async () => {
|
||||
const ticket = await initOk(png);
|
||||
expect(ticket.method).toBe('PUT');
|
||||
expect(ticket.headers['x-amz-checksum-sha256']).toBe(
|
||||
Buffer.from(sha256(png), 'hex').toString('base64'),
|
||||
);
|
||||
expect(Date.parse(ticket.expires_at)).toBeGreaterThan(Date.now());
|
||||
expect(new URL(ticket.url).pathname).toBe(
|
||||
`/messenger-attachments/attachments/${ticket.attachment_id}/original`,
|
||||
);
|
||||
|
||||
const hidden = await http<ApiErrorBody>(
|
||||
`/api/v1/attachments/${ticket.attachment_id}`,
|
||||
{ headers: bearer(bob.token) },
|
||||
);
|
||||
expectError(hidden, 404, 'not_found');
|
||||
expectError(
|
||||
await postMessage(alice.token, chatId, {
|
||||
text: '',
|
||||
attachment_ids: [ticket.attachment_id],
|
||||
}),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
expectError(
|
||||
await complete(alice.token, ticket.attachment_id),
|
||||
409,
|
||||
'conflict',
|
||||
);
|
||||
|
||||
expect((await put(ticket, png)).status).toBe(200);
|
||||
expectError(
|
||||
await complete(bob.token, ticket.attachment_id),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
expectError(
|
||||
await complete(eve.token, ticket.attachment_id),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
const done = await complete(alice.token, ticket.attachment_id);
|
||||
expect(done.response.status).toBe(200);
|
||||
expect(done.body).toMatchObject({
|
||||
id: ticket.attachment_id,
|
||||
owner_id: alice.user.id,
|
||||
content_type: 'image/png',
|
||||
size_bytes: png.length,
|
||||
sha256: sha256(png),
|
||||
status: 'ready',
|
||||
});
|
||||
const again = await complete(alice.token, ticket.attachment_id);
|
||||
expect(again.response.status).toBe(200);
|
||||
expect(again.body).toEqual(done.body);
|
||||
|
||||
const content = await download(bob.token, ticket.attachment_id);
|
||||
expect(content.response.status).toBe(200);
|
||||
expect(content.bytes.equals(png)).toBe(true);
|
||||
const sent = await postMessage(alice.token, chatId, {
|
||||
text: '',
|
||||
attachment_ids: [ticket.attachment_id],
|
||||
});
|
||||
expect(sent.response.status).toBe(201);
|
||||
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');
|
||||
expectError(
|
||||
await init(alice.token, chatId, { ...base, size_bytes: MAX + 1 }),
|
||||
413,
|
||||
'payload_too_large',
|
||||
);
|
||||
expectError(
|
||||
await init(alice.token, chatId, {
|
||||
...base,
|
||||
content_type: 'image/gif',
|
||||
}),
|
||||
415,
|
||||
'unsupported_media_type',
|
||||
);
|
||||
for (const bad of [
|
||||
{ ...base, extra: true },
|
||||
{ ...base, sha256: 'ABC' },
|
||||
{ ...base, size_bytes: 0 },
|
||||
{ ...base, filename: 'a/b.png' },
|
||||
])
|
||||
expectError(
|
||||
await init(alice.token, chatId, bad),
|
||||
400,
|
||||
'invalid_request',
|
||||
);
|
||||
});
|
||||
|
||||
it('lets the storage refuse bytes that differ from the declaration', async () => {
|
||||
const ticket = await initOk(png);
|
||||
const tampered = Buffer.from(png);
|
||||
tampered[1000] ^= 1;
|
||||
const refused = await put(ticket, tampered);
|
||||
expect(refused.status).toBe(400);
|
||||
expect(await refused.text()).toContain('XAmzContentChecksumMismatch');
|
||||
// No object was created, so the upload can still be finished.
|
||||
expectError(
|
||||
await complete(alice.token, ticket.attachment_id),
|
||||
409,
|
||||
'conflict',
|
||||
);
|
||||
expect((await put(ticket, png)).status).toBe(200);
|
||||
expect(
|
||||
(await complete(alice.token, ticket.attachment_id)).response.status,
|
||||
).toBe(200);
|
||||
|
||||
const longer = await initOk(png);
|
||||
const wrongLength = await put(
|
||||
longer,
|
||||
Buffer.concat([png, Buffer.from('x')]),
|
||||
);
|
||||
expect(wrongLength.status).toBe(403);
|
||||
});
|
||||
|
||||
it('rejects a declared PNG that is really a JPEG, then forgets the claim', async () => {
|
||||
const ticket = await initOk(jpeg, 'image/png');
|
||||
expect((await put(ticket, jpeg)).status).toBe(200);
|
||||
expectError(
|
||||
await complete(alice.token, ticket.attachment_id),
|
||||
415,
|
||||
'unsupported_media_type',
|
||||
);
|
||||
expectError(
|
||||
await complete(alice.token, ticket.attachment_id),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
// The URL is still valid: a re-PUT must stay tracked so the sweeper
|
||||
// removes the new object too.
|
||||
expect((await put(ticket, jpeg)).status).toBe(200);
|
||||
const row = await db.query<{ status: string }>(
|
||||
'SELECT status FROM attachments WHERE id = $1',
|
||||
[ticket.attachment_id],
|
||||
);
|
||||
expect(row.rows[0]?.status).toBe('rejected');
|
||||
expectError(
|
||||
await complete(alice.token, ticket.attachment_id),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['truncated PNG', () => png.subarray(0, png.length - 100)],
|
||||
[
|
||||
'PNG damaged after the first 64 KiB',
|
||||
() => {
|
||||
const data = noisePng(1_048_576);
|
||||
data[700_000] ^= 0xff;
|
||||
return data;
|
||||
},
|
||||
],
|
||||
])('rejects a %s even with a matching checksum', async (_name, make) => {
|
||||
// The declaration and the signed checksum match the bytes exactly:
|
||||
// only a check of the whole image can tell they are not an image.
|
||||
const data = make();
|
||||
const ticket = await initOk(data);
|
||||
expect((await put(ticket, data)).status).toBe(200);
|
||||
expectError(
|
||||
await complete(alice.token, ticket.attachment_id),
|
||||
415,
|
||||
'unsupported_media_type',
|
||||
);
|
||||
expectError(
|
||||
await complete(alice.token, ticket.attachment_id),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a pixel bomb on complete', async () => {
|
||||
const bomb = pixelBombPng();
|
||||
const ticket = await initOk(bomb);
|
||||
expect((await put(ticket, bomb)).status).toBe(200);
|
||||
expectError(
|
||||
await complete(alice.token, ticket.attachment_id),
|
||||
413,
|
||||
'payload_too_large',
|
||||
);
|
||||
expectError(
|
||||
await complete(alice.token, ticket.attachment_id),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
});
|
||||
|
||||
it('limits unfinished direct uploads per user', async () => {
|
||||
const spammer = await actor();
|
||||
const chat = (await createChat(spammer, [])).id;
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
const ok = await init(spammer.token, chat, declaration(png));
|
||||
expect(ok.response.status).toBe(201);
|
||||
}
|
||||
const limited = await init(spammer.token, chat, declaration(png));
|
||||
expectError(limited, 429, 'rate_limited');
|
||||
expect(
|
||||
Number(limited.response.headers.get('retry-after')),
|
||||
).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it.runIf(shortTtl)(
|
||||
'refuses an expired URL and removes the claim',
|
||||
async () => {
|
||||
const ticket = await initOk(png);
|
||||
const expiresAt = Date.parse(ticket.expires_at);
|
||||
await sleep(Math.max(0, expiresAt - Date.now()) + 2000);
|
||||
expect((await put(ticket, png)).status).toBe(403);
|
||||
const deadline = Date.now() + 15_000;
|
||||
for (;;) {
|
||||
const rows = await db.query(
|
||||
'SELECT 1 FROM attachments WHERE id = $1',
|
||||
[ticket.attachment_id],
|
||||
);
|
||||
if (rows.rowCount === 0) break;
|
||||
expect(Date.now()).toBeLessThan(deadline);
|
||||
await sleep(250);
|
||||
}
|
||||
expectError(
|
||||
await complete(alice.token, ticket.attachment_id),
|
||||
404,
|
||||
'not_found',
|
||||
);
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
});
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 4.8 KiB |
Vendored
BIN
Binary file not shown.
|
After Width: | Height: | Size: 4.6 KiB |
@@ -0,0 +1,158 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { Pool } from 'pg';
|
||||
import { expect } from 'vitest';
|
||||
import type { Chat } from '../../src/chats/chat.js';
|
||||
import type { ApiErrorBody } from '../../src/common/errors/api-error.js';
|
||||
import type { Message } from '../../src/messages/message.js';
|
||||
import type { Attachment } from '../../src/attachments/attachment.js';
|
||||
import type { User } from '../../src/users/user.js';
|
||||
|
||||
export const baseUrl = (
|
||||
process.env.API_BASE_URL ?? 'http://localhost:8080'
|
||||
).replace(/\/+$/u, '');
|
||||
export const password = 'integration:пароль🔐';
|
||||
const runId = randomUUID().replaceAll('-', '').slice(0, 10);
|
||||
let sequence = 0;
|
||||
|
||||
export type Actor = { user: User; token: string };
|
||||
export type HttpResult<T> = { body: T; response: Response };
|
||||
|
||||
export function database(): Pool {
|
||||
return new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
connectionTimeoutMillis: 5000,
|
||||
});
|
||||
}
|
||||
|
||||
export async function http<T = unknown>(
|
||||
path: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<HttpResult<T>> {
|
||||
const response = await fetch(`${baseUrl}${path}`, init);
|
||||
const text = await response.text();
|
||||
let body: unknown = undefined;
|
||||
if (text) {
|
||||
try {
|
||||
body = JSON.parse(text);
|
||||
} catch {
|
||||
body = text;
|
||||
}
|
||||
}
|
||||
return { body: body as T, response };
|
||||
}
|
||||
|
||||
export function json(
|
||||
body: unknown,
|
||||
headers: Record<string, string> = {},
|
||||
): RequestInit {
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
};
|
||||
}
|
||||
|
||||
export function bearer(token: string): Record<string, string> {
|
||||
return { authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
export function expectError(
|
||||
result: HttpResult<ApiErrorBody>,
|
||||
status: number,
|
||||
code: string,
|
||||
): void {
|
||||
expect(result.response.status).toBe(status);
|
||||
expect(result.body.error.code).toBe(code);
|
||||
expect(result.body.error.request_id).toBe(
|
||||
result.response.headers.get('x-request-id'),
|
||||
);
|
||||
}
|
||||
|
||||
export async function actor(): Promise<Actor> {
|
||||
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
|
||||
const created = await http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: 'Attachments e2e', password }),
|
||||
);
|
||||
expect(created.response.status).toBe(201);
|
||||
const basic = Buffer.from(`${username}:${password}`, 'utf8').toString(
|
||||
'base64',
|
||||
);
|
||||
const session = await http<{ token: string }>('/api/v1/auth/sessions', {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Basic ${basic}` },
|
||||
});
|
||||
expect(session.response.status).toBe(201);
|
||||
return { user: created.body, token: session.body.token };
|
||||
}
|
||||
|
||||
export async function createChat(
|
||||
owner: Actor,
|
||||
members: Actor[],
|
||||
): Promise<Chat> {
|
||||
const result = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{
|
||||
title: 'attachments',
|
||||
member_ids: [owner.user.id, ...members.map((m) => m.user.id)],
|
||||
},
|
||||
bearer(owner.token),
|
||||
),
|
||||
);
|
||||
expect(result.response.status).toBe(201);
|
||||
return result.body;
|
||||
}
|
||||
|
||||
/** `query` is sent verbatim so tests can craft malformed filename parameters. */
|
||||
export function uploadRaw(
|
||||
token: string,
|
||||
chatId: string,
|
||||
query: string,
|
||||
body: Buffer | undefined,
|
||||
contentType = 'image/png',
|
||||
): Promise<HttpResult<Attachment & ApiErrorBody>> {
|
||||
return http(`/api/v1/chats/${chatId}/attachments${query}`, {
|
||||
method: 'POST',
|
||||
headers: { ...bearer(token), 'content-type': contentType },
|
||||
body: body as BodyInit | undefined,
|
||||
});
|
||||
}
|
||||
|
||||
export function upload(
|
||||
token: string,
|
||||
chatId: string,
|
||||
body: Buffer | undefined,
|
||||
options: { filename?: string; contentType?: string } = {},
|
||||
) {
|
||||
return uploadRaw(
|
||||
token,
|
||||
chatId,
|
||||
`?filename=${encodeURIComponent(options.filename ?? 'picture.png')}`,
|
||||
body,
|
||||
options.contentType ?? 'image/png',
|
||||
);
|
||||
}
|
||||
|
||||
export async function download(
|
||||
token: string,
|
||||
attachmentId: string,
|
||||
): Promise<{ response: Response; bytes: Buffer }> {
|
||||
const response = await fetch(
|
||||
`${baseUrl}/api/v1/attachments/${attachmentId}/content`,
|
||||
{ headers: bearer(token) },
|
||||
);
|
||||
return { response, bytes: Buffer.from(await response.arrayBuffer()) };
|
||||
}
|
||||
|
||||
export function postMessage(
|
||||
token: string,
|
||||
chatId: string,
|
||||
body: unknown,
|
||||
key = randomUUID().replaceAll('-', ''),
|
||||
) {
|
||||
return http<Message & ApiErrorBody>(
|
||||
`/api/v1/chats/${chatId}/messages`,
|
||||
json(body, { ...bearer(token), 'idempotency-key': key }),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/** Keeps every segment through the SOS header and drops the scan data. */
|
||||
export function jpegWithoutScanData(jpeg: Buffer): Buffer {
|
||||
let offset = 2;
|
||||
for (;;) {
|
||||
const marker = jpeg[offset + 1];
|
||||
offset += 2 + jpeg.readUInt16BE(offset + 2);
|
||||
if (marker === 0xda) break;
|
||||
}
|
||||
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),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { once } from 'node:events';
|
||||
import { crc32, createDeflate, deflateSync } from 'node:zlib';
|
||||
|
||||
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
|
||||
function chunk(type: string, data: Buffer): Buffer {
|
||||
const head = Buffer.alloc(8);
|
||||
head.writeUInt32BE(data.length, 0);
|
||||
head.write(type, 4, 'latin1');
|
||||
const crc = Buffer.alloc(4);
|
||||
crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])) >>> 0, 0);
|
||||
return Buffer.concat([head, data, crc]);
|
||||
}
|
||||
|
||||
export function buildPng(options: {
|
||||
width: number;
|
||||
height: number;
|
||||
colorType: number;
|
||||
bitDepth: number;
|
||||
idat: Buffer;
|
||||
}): Buffer {
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(options.width, 0);
|
||||
ihdr.writeUInt32BE(options.height, 4);
|
||||
ihdr[8] = options.bitDepth;
|
||||
ihdr[9] = options.colorType;
|
||||
return Buffer.concat([
|
||||
SIGNATURE,
|
||||
chunk('IHDR', ihdr),
|
||||
chunk('IDAT', options.idat),
|
||||
chunk('IEND', Buffer.alloc(0)),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Inserts a private ancillary chunk before IEND to reach exactly `size` bytes. */
|
||||
export function padPngTo(png: Buffer, size: number): Buffer {
|
||||
const extra = size - png.length;
|
||||
if (extra === 0) return png;
|
||||
if (extra < 12) throw new Error('PNG padding needs at least 12 bytes');
|
||||
const iend = png.length - 12;
|
||||
return Buffer.concat([
|
||||
png.subarray(0, iend),
|
||||
chunk('prVt', Buffer.alloc(extra - 12)),
|
||||
png.subarray(iend),
|
||||
]);
|
||||
}
|
||||
|
||||
/** 8000x5001 grayscale 1-bit, all-zero rows: tiny file, 40 008 000 pixels. */
|
||||
export function pixelBombPng(): Buffer {
|
||||
const width = 8000;
|
||||
const height = 5001;
|
||||
const row = Buffer.alloc(1 + Math.ceil(width / 8));
|
||||
const raw = Buffer.alloc(row.length * height);
|
||||
return buildPng({
|
||||
width,
|
||||
height,
|
||||
colorType: 0,
|
||||
bitDepth: 1,
|
||||
idat: deflateSync(raw, { level: 9 }),
|
||||
});
|
||||
}
|
||||
|
||||
const NOISE_WIDTH = 1024;
|
||||
const NOISE_ROW = 1 + NOISE_WIDTH * 3;
|
||||
|
||||
function noiseOfHeight(height: number): Buffer {
|
||||
const raw = randomBytes(NOISE_ROW * height);
|
||||
for (let row = 0; row < height; row += 1) raw[row * NOISE_ROW] = 0;
|
||||
return buildPng({
|
||||
width: NOISE_WIDTH,
|
||||
height,
|
||||
colorType: 2,
|
||||
bitDepth: 8,
|
||||
idat: deflateSync(raw, { level: 0 }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Incompressible, structurally valid PNG of exactly `size` bytes. */
|
||||
export function noisePng(size: number): Buffer {
|
||||
let height = Math.max(1, Math.floor(size / NOISE_ROW));
|
||||
for (;;) {
|
||||
const png = noiseOfHeight(height);
|
||||
if (png.length > size) {
|
||||
height -= 1;
|
||||
if (height < 1) throw new Error('size is too small for noisePng');
|
||||
continue;
|
||||
}
|
||||
const extra = size - png.length;
|
||||
if (extra > 0 && extra < 12) {
|
||||
height -= 1;
|
||||
continue;
|
||||
}
|
||||
return padPngTo(png, size);
|
||||
}
|
||||
}
|
||||
|
||||
/** Valid signature, IHDR, CRCs and IEND around a zlib stream of random bytes. */
|
||||
export function pngWithGarbageIdat(): Buffer {
|
||||
return buildPng({
|
||||
width: 320,
|
||||
height: 200,
|
||||
colorType: 2,
|
||||
bitDepth: 8,
|
||||
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