chore: migrate minimum from lab1

This commit is contained in:
2026-10-21 09:41:45 +03:00
parent 65003b6119
commit d8fb486709
44 changed files with 11664 additions and 0 deletions
+601
View File
@@ -0,0 +1,601 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import request from 'supertest';
import { randomUUID } from 'crypto';
import { AppModule } from '../src/app.module';
import { configureApp } from '../src/configure-app';
describe('API мессенджера (e2e) — граничные случаи сверх публичного smoke', () => {
let app: INestApplication;
let server: any;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
const fastifyApp =
moduleRef.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
);
app = fastifyApp;
configureApp(fastifyApp);
await fastifyApp.listen(0, '127.0.0.1');
server = fastifyApp.getHttpServer();
});
afterAll(async () => {
await app.close();
});
async function createUser(label: string) {
const res = await request(server)
.post('/api/v1/users')
.send({
username: `u_${label}_${randomUUID().slice(0, 8)}`,
display_name: `User ${label}`,
})
.expect(201);
return res.body as { id: string; username: string };
}
describe('POST /api/v1/users', () => {
it('отклоняет некорректный JSON с кодом 400', async () => {
const res = await request(server)
.post('/api/v1/users')
.set('Content-Type', 'application/json')
.send('{not valid json')
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
expect(res.body.error.request_id).toBeTruthy();
});
it('отклоняет тело с лишними полями', async () => {
const res = await request(server)
.post('/api/v1/users')
.send({
username: 'validname1',
display_name: 'Valid',
extra: 'nope',
})
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
it('отклоняет username с заглавными буквами', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'InvalidName', display_name: 'X' })
.expect(400);
});
it('отклоняет display_name из одних пробелов', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'wsonlyname1', display_name: ' ' })
.expect(400);
});
it('отклоняет дубликат username с кодом 409', async () => {
const user = await createUser('dup');
const res = await request(server)
.post('/api/v1/users')
.send({ username: user.username, display_name: 'Someone else' })
.expect(409);
expect(res.body.error.code).toBe('conflict');
});
it('никогда не возвращает поле пароля или его хэша', async () => {
const res = await request(server)
.post('/api/v1/users')
.send({
username: `nopass_${randomUUID().slice(0, 8)}`,
display_name: 'X',
})
.expect(201);
expect(res.body).not.toHaveProperty('password');
expect(res.body).not.toHaveProperty('password_hash');
});
it('отклоняет username короче 3 символов', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'ab', display_name: 'X' })
.expect(400);
});
it('отклоняет username длиннее 32 символов', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'a'.repeat(33), display_name: 'X' })
.expect(400);
});
it('отклоняет username с недопустимыми символами (дефис)', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'has-hyphen', display_name: 'X' })
.expect(400);
});
it('принимает username ровно на границах длины 3 и 32 символа', async () => {
await request(server)
.post('/api/v1/users')
.send({
username: `a${randomUUID().slice(0, 2)}`,
display_name: 'X',
})
.expect(201);
const longest = ('z' + randomUUID().replace(/-/g, '')).slice(0, 32);
await request(server)
.post('/api/v1/users')
.send({ username: longest, display_name: 'X' })
.expect(201);
});
it('отклоняет display_name длиннее 100 Unicode code points', async () => {
await request(server)
.post('/api/v1/users')
.send({
username: `toolongname_${randomUUID().slice(0, 6)}`,
display_name: 'x'.repeat(101),
})
.expect(400);
});
it('принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ', async () => {
const displayName = '👋'.repeat(100);
expect([...displayName].length).toBe(100);
await request(server)
.post('/api/v1/users')
.send({
username: `emojiname_${randomUUID().slice(0, 6)}`,
display_name: displayName,
})
.expect(201);
});
it('отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP', async () => {
const displayName = '👋'.repeat(100) + 'x';
expect([...displayName].length).toBe(101);
await request(server)
.post('/api/v1/users')
.send({
username: `emojitoolong_${randomUUID().slice(0, 6)}`,
display_name: displayName,
})
.expect(400);
});
});
describe('контроль доступа', () => {
it('возвращает 401 раньше 404, если и актор, и ресурс невалидны', async () => {
const res = await request(server)
.get(`/api/v1/chats/${randomUUID()}`)
.set('X-User-Id', 'not-a-uuid')
.expect(401);
expect(res.body.error.code).toBe('unauthorized');
});
it('возвращает 404 (не 403), когда чат запрашивает не его участник', async () => {
const alice = await createUser('alice');
const bob = await createUser('bob');
const eve = await createUser('eve');
const chat = await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.send({ title: 'Private', member_ids: [alice.id, bob.id] })
.expect(201);
const res = await request(server)
.get(`/api/v1/chats/${chat.body.id}`)
.set('X-User-Id', eve.id)
.expect(404);
expect(res.body.error.code).toBe('not_found');
});
it('отклоняет создание чата, если вызывающий не входит в member_ids', async () => {
const alice = await createUser('alice2');
const bob = await createUser('bob2');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.send({ title: 'Missing caller', member_ids: [bob.id] })
.expect(400);
});
it('отклоняет создание чата с дублирующимися member_ids', async () => {
const alice = await createUser('alice3');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.send({
title: 'Dup members',
member_ids: [alice.id, alice.id],
})
.expect(400);
});
it('отклоняет создание чата с неизвестным участником', async () => {
const alice = await createUser('alice4');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.send({
title: 'Unknown member',
member_ids: [alice.id, randomUUID()],
})
.expect(400);
});
it('отклоняет создание чата с пустым/пробельным title', async () => {
const alice = await createUser('alice4b');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.send({ title: ' ', member_ids: [alice.id] })
.expect(400);
});
it('возвращает 400 для синтаксически некорректного chat_id (не UUID)', async () => {
const alice = await createUser('alice4c');
const res = await request(server)
.get('/api/v1/chats/not-a-uuid')
.set('X-User-Id', alice.id)
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
it('возвращает 404 для корректного по формату, но несуществующего chat_id', async () => {
const alice = await createUser('alice4d');
await request(server)
.get(`/api/v1/chats/${randomUUID()}`)
.set('X-User-Id', alice.id)
.expect(404);
});
});
describe('GET /api/v1/chats (пагинация)', () => {
it('использует limit=50 по умолчанию, если limit не передан', async () => {
const alice = await createUser('pgalice1');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.send({ title: 'Only chat', member_ids: [alice.id] })
.expect(201);
const res = await request(server)
.get('/api/v1/chats')
.set('X-User-Id', alice.id)
.expect(200);
expect(res.body.items.length).toBeGreaterThanOrEqual(1);
expect(res.body.items.length).toBeLessThanOrEqual(50);
});
it('отклоняет нечисловой limit', async () => {
const alice = await createUser('pgalice2');
await request(server)
.get('/api/v1/chats?limit=abc')
.set('X-User-Id', alice.id)
.expect(400);
});
it('отклоняет limit=0', async () => {
const alice = await createUser('pgalice3');
await request(server)
.get('/api/v1/chats?limit=0')
.set('X-User-Id', alice.id)
.expect(400);
});
it('отклоняет cursor, не являющийся корректным base64url JSON', async () => {
const alice = await createUser('pgalice4');
await request(server)
.get('/api/v1/chats')
.query({ cursor: 'not-a-real-cursor!!!' })
.set('X-User-Id', alice.id)
.expect(400);
});
it('отклоняет корректно закодированный cursor с id чата, который никогда не существовал', async () => {
const alice = await createUser('pgalice4b');
const bogusCursor = Buffer.from(
JSON.stringify({ id: randomUUID() }),
'utf8',
).toString('base64url');
const res = await request(server)
.get('/api/v1/chats')
.query({ cursor: bogusCursor })
.set('X-User-Id', alice.id)
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
it('обходит весь список чатов по страницам без пропусков и дублей', async () => {
const alice = await createUser('pgalice5');
const titles = ['c1', 'c2', 'c3', 'c4', 'c5'];
for (const title of titles) {
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.send({ title, member_ids: [alice.id] })
.expect(201);
}
const seen: string[] = [];
let cursor: string | null = null;
do {
const res: request.Response = await request(server)
.get('/api/v1/chats')
.query({ limit: 2, ...(cursor ? { cursor } : {}) })
.set('X-User-Id', alice.id)
.expect(200);
seen.push(
...res.body.items.map((c: { title: string }) => c.title),
);
cursor = res.body.next_cursor;
} while (cursor);
expect(seen).toEqual(titles);
});
});
describe('сообщения', () => {
async function createChat(alice: { id: string }, bob: { id: string }) {
const res = await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.send({ title: 'Chat', member_ids: [alice.id, bob.id] })
.expect(201);
return res.body as { id: string };
}
it('не принимает sender_id, переданный клиентом', async () => {
const alice = await createUser('alice5');
const bob = await createUser('bob5');
const chat = await createChat(alice, bob);
const res = await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.send({ text: 'hi', sender_id: bob.id })
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
it('отклоняет пустое сообщение', async () => {
const alice = await createUser('alice6');
const bob = await createUser('bob6');
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.send({ text: '' })
.expect(400);
});
it('отклоняет сообщение из одних пробелов', async () => {
const alice = await createUser('alice7');
const bob = await createUser('bob7');
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.send({ text: ' \n\t ' })
.expect(400);
});
it('отклоняет отправку в чат, где вызывающий не участник', async () => {
const alice = await createUser('alice8');
const bob = await createUser('bob8');
const eve = await createUser('eve8');
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', eve.id)
.send({ text: 'intrusion' })
.expect(404);
});
it('отклоняет limit=0 при чтении истории', async () => {
const alice = await createUser('alice9');
const bob = await createUser('bob9');
const chat = await createChat(alice, bob);
await request(server)
.get(`/api/v1/chats/${chat.id}/messages?limit=0`)
.set('X-User-Id', alice.id)
.expect(400);
});
it('отклоняет limit=101 при чтении истории', async () => {
const alice = await createUser('alice10');
const bob = await createUser('bob10');
const chat = await createChat(alice, bob);
await request(server)
.get(`/api/v1/chats/${chat.id}/messages?limit=101`)
.set('X-User-Id', alice.id)
.expect(400);
});
it('отклоняет нечисловой limit', async () => {
const alice = await createUser('alice10b');
const bob = await createUser('bob10b');
const chat = await createChat(alice, bob);
await request(server)
.get(`/api/v1/chats/${chat.id}/messages?limit=abc`)
.set('X-User-Id', alice.id)
.expect(400);
});
it('отклоняет текст сообщения длиннее 4000 Unicode code points', async () => {
const alice = await createUser('alice10c');
const bob = await createUser('bob10c');
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.send({ text: 'x'.repeat(4001) })
.expect(400);
});
it('принимает текст сообщения ровно из 4000 Unicode code points', async () => {
const alice = await createUser('alice10d');
const bob = await createUser('bob10d');
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.send({ text: 'x'.repeat(4000) })
.expect(201);
});
it('отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP', async () => {
const alice = await createUser('alice10e');
const bob = await createUser('bob10e');
const chat = await createChat(alice, bob);
const text = '👋'.repeat(4001);
expect([...text].length).toBe(4001);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.send({ text })
.expect(400);
});
it('отклоняет cursor, не являющийся корректным base64url JSON', async () => {
const alice = await createUser('alice10f');
const bob = await createUser('bob10f');
const chat = await createChat(alice, bob);
await request(server)
.get(`/api/v1/chats/${chat.id}/messages`)
.query({ cursor: '!!!not-valid!!!' })
.set('X-User-Id', alice.id)
.expect(400);
});
it('отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате', async () => {
const alice = await createUser('alice10i');
const bob = await createUser('bob10i');
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.send({ text: 'only message' })
.expect(201);
const bogusCursor = Buffer.from(
JSON.stringify({ chatId: chat.id, id: randomUUID() }),
'utf8',
).toString('base64url');
const res = await request(server)
.get(`/api/v1/chats/${chat.id}/messages`)
.query({ cursor: bogusCursor })
.set('X-User-Id', alice.id)
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
it('возвращает 400 для синтаксически некорректного chat_id при отправке сообщения', async () => {
const alice = await createUser('alice10g');
const res = await request(server)
.post('/api/v1/chats/not-a-uuid/messages')
.set('X-User-Id', alice.id)
.send({ text: 'hi' })
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
it('возвращает 400 для синтаксически некорректного chat_id при чтении истории', async () => {
const alice = await createUser('alice10h');
const res = await request(server)
.get('/api/v1/chats/not-a-uuid/messages')
.set('X-User-Id', alice.id)
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
it('отклоняет cursor, взятый из другого чата', async () => {
const alice = await createUser('alice11');
const bob = await createUser('bob11');
const chatA = await createChat(alice, bob);
const chatB = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chatA.id}/messages`)
.set('X-User-Id', alice.id)
.send({ text: 'first' })
.expect(201);
await request(server)
.post(`/api/v1/chats/${chatA.id}/messages`)
.set('X-User-Id', alice.id)
.send({ text: 'second' })
.expect(201);
const page1 = await request(server)
.get(`/api/v1/chats/${chatA.id}/messages?limit=1`)
.set('X-User-Id', alice.id)
.expect(200);
expect(page1.body.next_cursor).toBeTruthy();
const res = await request(server)
.get(`/api/v1/chats/${chatB.id}/messages`)
.query({ cursor: page1.body.next_cursor })
.set('X-User-Id', alice.id)
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
it('обходит всю историю по страницам без пропусков и дублей', async () => {
const alice = await createUser('alice12');
const bob = await createUser('bob12');
const chat = await createChat(alice, bob);
const sentTexts = ['m1', 'm2', 'm3', 'm4', 'm5'];
for (const text of sentTexts) {
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.send({ text })
.expect(201);
}
const seen: string[] = [];
let cursor: string | null = null;
do {
const res: request.Response = await request(server)
.get(`/api/v1/chats/${chat.id}/messages`)
.query({ limit: 2, ...(cursor ? { cursor } : {}) })
.set('X-User-Id', alice.id)
.expect(200);
seen.push(
...res.body.items.map((m: { text: string }) => m.text),
);
cursor = res.body.next_cursor;
} while (cursor);
expect(seen).toEqual(sentTexts);
});
});
describe('X-Request-Id', () => {
it('присутствует и уникален для независимых запросов', async () => {
const first = await request(server).get('/health/live').expect(200);
const second = await request(server)
.get('/health/live')
.expect(200);
expect(first.headers['x-request-id']).toBeTruthy();
expect(second.headers['x-request-id']).toBeTruthy();
expect(first.headers['x-request-id']).not.toBe(
second.headers['x-request-id'],
);
});
it('совпадает с request_id внутри тела ошибки', async () => {
const res = await request(server)
.get('/api/v1/users/me')
.expect(401);
expect(res.body.error.request_id).toBe(res.headers['x-request-id']);
});
});
});
+141
View File
@@ -0,0 +1,141 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import request from 'supertest';
import { randomUUID } from 'crypto';
import { AppModule } from '../src/app.module';
import { configureApp } from '../src/configure-app';
describe('Безопасность при конкурентном доступе (e2e)', () => {
let app: INestApplication;
let server: any;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
const fastifyApp =
moduleRef.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
);
app = fastifyApp;
configureApp(fastifyApp);
await fastifyApp.listen(0, '127.0.0.1');
server = fastifyApp.getHttpServer();
});
afterAll(async () => {
await app.close();
});
it('принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных', async () => {
const CLIENTS = 10;
const MESSAGES_PER_CLIENT = 10;
const owner = await request(server)
.post('/api/v1/users')
.send({
username: `owner_${randomUUID().slice(0, 8)}`,
display_name: 'Owner',
})
.expect(201);
const clients = await Promise.all(
Array.from({ length: CLIENTS }, (_, i) =>
request(server)
.post('/api/v1/users')
.send({
username: `racer${i}_${randomUUID().slice(0, 6)}`,
display_name: `Racer ${i}`,
})
.expect(201),
),
);
const memberIds = [owner.body.id, ...clients.map((c) => c.body.id)];
const chat = await request(server)
.post('/api/v1/chats')
.set('X-User-Id', owner.body.id)
.send({ title: 'Race', member_ids: memberIds })
.expect(201);
const sendTasks: Promise<request.Response>[] = [];
for (let c = 0; c < CLIENTS; c++) {
for (let m = 0; m < MESSAGES_PER_CLIENT; m++) {
sendTasks.push(
request(server)
.post(`/api/v1/chats/${chat.body.id}/messages`)
.set('X-User-Id', clients[c].body.id)
.send({ text: `client-${c}-message-${m}` }),
);
}
}
const responses = await Promise.all(sendTasks);
for (const res of responses) {
expect(res.status).toBe(201);
}
const sentIds = new Set(responses.map((r) => r.body.id));
expect(sentIds.size).toBe(CLIENTS * MESSAGES_PER_CLIENT);
const collected: { id: string; text: string }[] = [];
let cursor: string | null = null;
do {
const res: request.Response = await request(server)
.get(`/api/v1/chats/${chat.body.id}/messages`)
.query({ limit: 25, ...(cursor ? { cursor } : {}) })
.set('X-User-Id', owner.body.id)
.expect(200);
collected.push(...res.body.items);
cursor = res.body.next_cursor;
} while (cursor);
expect(collected.length).toBe(CLIENTS * MESSAGES_PER_CLIENT);
const uniqueIds = new Set(collected.map((m) => m.id));
expect(uniqueIds.size).toBe(CLIENTS * MESSAGES_PER_CLIENT);
const uniqueTexts = new Set(collected.map((m) => m.text));
expect(uniqueTexts.size).toBe(CLIENTS * MESSAGES_PER_CLIENT);
const fullHistory: { id: string; created_at: string }[] =
await request(server)
.get(`/api/v1/chats/${chat.body.id}/messages`)
.query({ limit: 100 })
.set('X-User-Id', owner.body.id)
.expect(200)
.then((res) => res.body.items);
const sortKeys = fullHistory.map((m) => `${m.created_at}#${m.id}`);
const sortedKeys = [...sortKeys].sort();
expect(sortKeys).toEqual(sortedKeys);
});
it('регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username', async () => {
const username = `racer_username_${randomUUID().slice(0, 8)}`;
const attempts = 10;
const responses = await Promise.all(
Array.from({ length: attempts }, () =>
request(server)
.post('/api/v1/users')
.send({ username, display_name: 'Racer' }),
),
);
const succeeded = responses.filter((r) => r.status === 201);
const conflicted = responses.filter((r) => r.status === 409);
expect(succeeded.length).toBe(1);
expect(conflicted.length).toBe(attempts - 1);
expect(succeeded.length + conflicted.length).toBe(attempts);
const listRes = await request(server)
.get('/api/v1/users/me')
.set('X-User-Id', succeeded[0].body.id)
.expect(200);
expect(listRes.body.username).toBe(username);
});
});
+9
View File
@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}