591 lines
20 KiB
TypeScript
591 lines
20 KiB
TypeScript
import { INestApplication } from '@nestjs/common';
|
||
import request from 'supertest';
|
||
import { randomUUID } from 'crypto';
|
||
import {
|
||
bearer,
|
||
createTestApp,
|
||
PASSWORD,
|
||
registerUser,
|
||
TestUser,
|
||
} from './helpers';
|
||
|
||
describe('API мессенджера (e2e) — граничные случаи сверх публичного smoke', () => {
|
||
let app: INestApplication;
|
||
let server: any;
|
||
|
||
beforeAll(async () => {
|
||
({ app, server } = await createTestApp());
|
||
});
|
||
|
||
afterAll(async () => {
|
||
await app.close();
|
||
});
|
||
|
||
function createUser(label: string): Promise<TestUser> {
|
||
return registerUser(server, label);
|
||
}
|
||
|
||
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',
|
||
password: PASSWORD,
|
||
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', password: PASSWORD })
|
||
.expect(400);
|
||
});
|
||
|
||
it('отклоняет display_name из одних пробелов', async () => {
|
||
await request(server)
|
||
.post('/api/v1/users')
|
||
.send({ username: 'wsonlyname1', display_name: ' ', password: PASSWORD })
|
||
.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', password: PASSWORD })
|
||
.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',
|
||
password: PASSWORD,
|
||
})
|
||
.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', password: PASSWORD })
|
||
.expect(400);
|
||
});
|
||
|
||
it('отклоняет username длиннее 32 символов', async () => {
|
||
await request(server)
|
||
.post('/api/v1/users')
|
||
.send({ username: 'a'.repeat(33), display_name: 'X', password: PASSWORD })
|
||
.expect(400);
|
||
});
|
||
|
||
it('отклоняет username с недопустимыми символами (дефис)', async () => {
|
||
await request(server)
|
||
.post('/api/v1/users')
|
||
.send({ username: 'has-hyphen', display_name: 'X', password: PASSWORD })
|
||
.expect(400);
|
||
});
|
||
|
||
it('принимает username ровно на границах длины 3 и 32 символа', async () => {
|
||
await request(server)
|
||
.post('/api/v1/users')
|
||
.send({
|
||
username: `a${randomUUID().slice(0, 2)}`,
|
||
display_name: 'X',
|
||
password: PASSWORD,
|
||
})
|
||
.expect(201);
|
||
const longest = ('z' + randomUUID().replace(/-/g, '')).slice(0, 32);
|
||
await request(server)
|
||
.post('/api/v1/users')
|
||
.send({ username: longest, display_name: 'X', password: PASSWORD })
|
||
.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),
|
||
password: PASSWORD,
|
||
})
|
||
.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,
|
||
password: PASSWORD,
|
||
})
|
||
.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,
|
||
password: PASSWORD,
|
||
})
|
||
.expect(400);
|
||
});
|
||
});
|
||
|
||
describe('контроль доступа', () => {
|
||
it('возвращает 401 раньше 404, если и актор, и ресурс невалидны', async () => {
|
||
const res = await request(server)
|
||
.get(`/api/v1/chats/${randomUUID()}`)
|
||
.set('Authorization', 'Bearer not-a-token')
|
||
.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('Authorization', bearer(alice))
|
||
.send({ title: 'Private', member_ids: [alice.id, bob.id] })
|
||
.expect(201);
|
||
|
||
const res = await request(server)
|
||
.get(`/api/v1/chats/${chat.body.id}`)
|
||
.set('Authorization', bearer(eve))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.send({ title: 'Only chat', member_ids: [alice.id] })
|
||
.expect(201);
|
||
const res = await request(server)
|
||
.get('/api/v1/chats')
|
||
.set('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.expect(400);
|
||
});
|
||
|
||
it('отклоняет limit=0', async () => {
|
||
const alice = await createUser('pgalice3');
|
||
await request(server)
|
||
.get('/api/v1/chats?limit=0')
|
||
.set('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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: TestUser, bob: TestUser) {
|
||
const res = await request(server)
|
||
.post('/api/v1/chats')
|
||
.set('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(eve))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.send({ text: 'first' })
|
||
.expect(201);
|
||
await request(server)
|
||
.post(`/api/v1/chats/${chatA.id}/messages`)
|
||
.set('Authorization', bearer(alice))
|
||
.send({ text: 'second' })
|
||
.expect(201);
|
||
|
||
const page1 = await request(server)
|
||
.get(`/api/v1/chats/${chatA.id}/messages?limit=1`)
|
||
.set('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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('Authorization', bearer(alice))
|
||
.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']);
|
||
});
|
||
});
|
||
});
|