feat: add basic auth

This commit is contained in:
2026-10-21 10:31:23 +03:00
parent ef2bc6f8b6
commit 0563ebfb10
28 changed files with 633 additions and 176 deletions
+63 -74
View File
@@ -1,45 +1,28 @@
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';
import {
bearer,
createTestApp,
PASSWORD,
registerUser,
TestUser,
} from './helpers';
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();
({ app, server } = await createTestApp());
});
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 };
function createUser(label: string): Promise<TestUser> {
return registerUser(server, label);
}
describe('POST /api/v1/users', () => {
@@ -59,6 +42,7 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: 'validname1',
display_name: 'Valid',
password: PASSWORD,
extra: 'nope',
})
.expect(400);
@@ -68,14 +52,14 @@ describe('API мессенджера (e2e) — граничные случаи
it('отклоняет username с заглавными буквами', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'InvalidName', display_name: 'X' })
.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: ' ' })
.send({ username: 'wsonlyname1', display_name: ' ', password: PASSWORD })
.expect(400);
});
@@ -83,7 +67,7 @@ describe('API мессенджера (e2e) — граничные случаи
const user = await createUser('dup');
const res = await request(server)
.post('/api/v1/users')
.send({ username: user.username, display_name: 'Someone else' })
.send({ username: user.username, display_name: 'Someone else', password: PASSWORD })
.expect(409);
expect(res.body.error.code).toBe('conflict');
});
@@ -94,6 +78,7 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: `nopass_${randomUUID().slice(0, 8)}`,
display_name: 'X',
password: PASSWORD,
})
.expect(201);
expect(res.body).not.toHaveProperty('password');
@@ -103,21 +88,21 @@ describe('API мессенджера (e2e) — граничные случаи
it('отклоняет username короче 3 символов', async () => {
await request(server)
.post('/api/v1/users')
.send({ username: 'ab', display_name: 'X' })
.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' })
.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' })
.send({ username: 'has-hyphen', display_name: 'X', password: PASSWORD })
.expect(400);
});
@@ -127,12 +112,13 @@ describe('API мессенджера (e2e) — граничные случаи
.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' })
.send({ username: longest, display_name: 'X', password: PASSWORD })
.expect(201);
});
@@ -142,6 +128,7 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: `toolongname_${randomUUID().slice(0, 6)}`,
display_name: 'x'.repeat(101),
password: PASSWORD,
})
.expect(400);
});
@@ -154,6 +141,7 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: `emojiname_${randomUUID().slice(0, 6)}`,
display_name: displayName,
password: PASSWORD,
})
.expect(201);
});
@@ -166,6 +154,7 @@ describe('API мессенджера (e2e) — граничные случаи
.send({
username: `emojitoolong_${randomUUID().slice(0, 6)}`,
display_name: displayName,
password: PASSWORD,
})
.expect(400);
});
@@ -175,7 +164,7 @@ describe('API мессенджера (e2e) — граничные случаи
it('возвращает 401 раньше 404, если и актор, и ресурс невалидны', async () => {
const res = await request(server)
.get(`/api/v1/chats/${randomUUID()}`)
.set('X-User-Id', 'not-a-uuid')
.set('Authorization', 'Bearer not-a-token')
.expect(401);
expect(res.body.error.code).toBe('unauthorized');
});
@@ -186,13 +175,13 @@ describe('API мессенджера (e2e) — граничные случаи
const eve = await createUser('eve');
const chat = await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.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('X-User-Id', eve.id)
.set('Authorization', bearer(eve))
.expect(404);
expect(res.body.error.code).toBe('not_found');
});
@@ -202,7 +191,7 @@ describe('API мессенджера (e2e) — граничные случаи
const bob = await createUser('bob2');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ title: 'Missing caller', member_ids: [bob.id] })
.expect(400);
});
@@ -211,7 +200,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice3');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({
title: 'Dup members',
member_ids: [alice.id, alice.id],
@@ -223,7 +212,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice4');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({
title: 'Unknown member',
member_ids: [alice.id, randomUUID()],
@@ -235,7 +224,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice4b');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ title: ' ', member_ids: [alice.id] })
.expect(400);
});
@@ -244,7 +233,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice4c');
const res = await request(server)
.get('/api/v1/chats/not-a-uuid')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
@@ -253,7 +242,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice4d');
await request(server)
.get(`/api/v1/chats/${randomUUID()}`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(404);
});
});
@@ -263,12 +252,12 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('pgalice1');
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.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)
.set('Authorization', bearer(alice))
.expect(200);
expect(res.body.items.length).toBeGreaterThanOrEqual(1);
expect(res.body.items.length).toBeLessThanOrEqual(50);
@@ -278,7 +267,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('pgalice2');
await request(server)
.get('/api/v1/chats?limit=abc')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -286,7 +275,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('pgalice3');
await request(server)
.get('/api/v1/chats?limit=0')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -295,7 +284,7 @@ describe('API мессенджера (e2e) — граничные случаи
await request(server)
.get('/api/v1/chats')
.query({ cursor: 'not-a-real-cursor!!!' })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -308,7 +297,7 @@ describe('API мессенджера (e2e) — граничные случаи
const res = await request(server)
.get('/api/v1/chats')
.query({ cursor: bogusCursor })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
@@ -319,7 +308,7 @@ describe('API мессенджера (e2e) — граничные случаи
for (const title of titles) {
await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ title, member_ids: [alice.id] })
.expect(201);
}
@@ -330,7 +319,7 @@ describe('API мессенджера (e2e) — граничные случаи
const res: request.Response = await request(server)
.get('/api/v1/chats')
.query({ limit: 2, ...(cursor ? { cursor } : {}) })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(200);
seen.push(
...res.body.items.map((c: { title: string }) => c.title),
@@ -343,10 +332,10 @@ describe('API мессенджера (e2e) — граничные случаи
});
describe('сообщения', () => {
async function createChat(alice: { id: string }, bob: { id: string }) {
async function createChat(alice: TestUser, bob: TestUser) {
const res = await request(server)
.post('/api/v1/chats')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ title: 'Chat', member_ids: [alice.id, bob.id] })
.expect(201);
return res.body as { id: string };
@@ -359,7 +348,7 @@ describe('API мессенджера (e2e) — граничные случаи
const res = await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'hi', sender_id: bob.id })
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
@@ -371,7 +360,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: '' })
.expect(400);
});
@@ -382,7 +371,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: ' \n\t ' })
.expect(400);
});
@@ -394,7 +383,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', eve.id)
.set('Authorization', bearer(eve))
.send({ text: 'intrusion' })
.expect(404);
});
@@ -405,7 +394,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.get(`/api/v1/chats/${chat.id}/messages?limit=0`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -415,7 +404,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.get(`/api/v1/chats/${chat.id}/messages?limit=101`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -425,7 +414,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.get(`/api/v1/chats/${chat.id}/messages?limit=abc`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -435,7 +424,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'x'.repeat(4001) })
.expect(400);
});
@@ -446,7 +435,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'x'.repeat(4000) })
.expect(201);
});
@@ -459,7 +448,7 @@ describe('API мессенджера (e2e) — граничные случаи
expect([...text].length).toBe(4001);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text })
.expect(400);
});
@@ -471,7 +460,7 @@ describe('API мессенджера (e2e) — граничные случаи
await request(server)
.get(`/api/v1/chats/${chat.id}/messages`)
.query({ cursor: '!!!not-valid!!!' })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
});
@@ -481,7 +470,7 @@ describe('API мессенджера (e2e) — граничные случаи
const chat = await createChat(alice, bob);
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'only message' })
.expect(201);
@@ -492,7 +481,7 @@ describe('API мессенджера (e2e) — граничные случаи
const res = await request(server)
.get(`/api/v1/chats/${chat.id}/messages`)
.query({ cursor: bogusCursor })
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
@@ -501,7 +490,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice10g');
const res = await request(server)
.post('/api/v1/chats/not-a-uuid/messages')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'hi' })
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
@@ -511,7 +500,7 @@ describe('API мессенджера (e2e) — граничные случаи
const alice = await createUser('alice10h');
const res = await request(server)
.get('/api/v1/chats/not-a-uuid/messages')
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
@@ -524,25 +513,25 @@ describe('API мессенджера (e2e) — граничные случаи
await request(server)
.post(`/api/v1/chats/${chatA.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text: 'first' })
.expect(201);
await request(server)
.post(`/api/v1/chats/${chatA.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.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)
.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('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
});
@@ -555,7 +544,7 @@ describe('API мессенджера (e2e) — граничные случаи
for (const text of sentTexts) {
await request(server)
.post(`/api/v1/chats/${chat.id}/messages`)
.set('X-User-Id', alice.id)
.set('Authorization', bearer(alice))
.send({ text })
.expect(201);
}
@@ -566,7 +555,7 @@ describe('API мессенджера (e2e) — граничные случаи
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)
.set('Authorization', bearer(alice))
.expect(200);
seen.push(
...res.body.items.map((m: { text: string }) => m.text),