forked from mtusi2026/mtusi2026lab2
feat: add basic auth
This commit is contained in:
+63
-74
@@ -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),
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import {
|
||||
basic,
|
||||
bearer,
|
||||
createTestApp,
|
||||
login,
|
||||
PASSWORD,
|
||||
registerUser,
|
||||
} from './helpers';
|
||||
|
||||
describe('Аутентификация и сессии (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
let server: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ app, server } = await createTestApp());
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe('регистрация', () => {
|
||||
it('требует password', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: `nopw_${randomUUID().slice(0, 8)}`, display_name: 'X' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет password короче 12 code points', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `short_${randomUUID().slice(0, 8)}`,
|
||||
display_name: 'X',
|
||||
password: 'x'.repeat(11),
|
||||
})
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('хранит пароль как Argon2id-хеш, а не открытым текстом', async () => {
|
||||
const user = await registerUser(server, 'hash');
|
||||
const row = await app
|
||||
.get(PrismaService)
|
||||
.user.findUniqueOrThrow({ where: { id: user.id } });
|
||||
expect(row.passwordHash.startsWith('$argon2id$')).toBe(true);
|
||||
expect(row.passwordHash).not.toContain(PASSWORD);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/auth/sessions', () => {
|
||||
it('выдаёт непрозрачный Bearer-токен с expires_at и пользователем', async () => {
|
||||
const user = await registerUser(server, 'login');
|
||||
const res = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.set('Authorization', basic(user.username, PASSWORD))
|
||||
.expect(201);
|
||||
expect(res.body.token_type).toBe('Bearer');
|
||||
expect(res.body.token.length).toBeGreaterThanOrEqual(43);
|
||||
expect(res.body.token).not.toContain(user.id);
|
||||
expect(res.body.user.id).toBe(user.id);
|
||||
const expiresIn = Date.parse(res.body.expires_at) - Date.now();
|
||||
expect(expiresIn).toBeGreaterThan(3500 * 1000);
|
||||
expect(expiresIn).toBeLessThanOrEqual(3600 * 1000);
|
||||
});
|
||||
|
||||
it('принимает пароль с двоеточием и не-ASCII символами', async () => {
|
||||
const username = `colon_${randomUUID().slice(0, 8)}`;
|
||||
const password = 'пароль:с:двоеточием🔑';
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username, display_name: 'X', password })
|
||||
.expect(201);
|
||||
await login(server, username, password);
|
||||
});
|
||||
|
||||
it('отвечает одинаковым 401 на неверный пароль и неизвестного пользователя', async () => {
|
||||
const user = await registerUser(server, 'wrong');
|
||||
const wrong = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.set('Authorization', basic(user.username, 'wrong-password-123'))
|
||||
.expect(401);
|
||||
const unknown = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.set('Authorization', basic(`ghost_${randomUUID().slice(0, 8)}`, PASSWORD))
|
||||
.expect(401);
|
||||
for (const res of [wrong, unknown]) {
|
||||
expect(res.headers['www-authenticate']).toBe(
|
||||
'Basic realm="messenger", charset="UTF-8"',
|
||||
);
|
||||
expect(res.body.error.code).toBe('unauthorized');
|
||||
}
|
||||
expect(wrong.body.error.message).toBe(unknown.body.error.message);
|
||||
});
|
||||
|
||||
it('отвечает 401 без заголовка Authorization', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.expect(401);
|
||||
expect(res.headers['www-authenticate']).toContain('Basic');
|
||||
});
|
||||
});
|
||||
|
||||
describe('защищённые endpoint', () => {
|
||||
it('не принимают Basic', async () => {
|
||||
const user = await registerUser(server, 'basic');
|
||||
const res = await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', basic(user.username, PASSWORD))
|
||||
.expect(401);
|
||||
expect(res.headers['www-authenticate']).toBe('Bearer realm="messenger"');
|
||||
});
|
||||
|
||||
it('не принимают X-User-Id сам по себе', async () => {
|
||||
const user = await registerUser(server, 'xuid');
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('X-User-Id', user.id)
|
||||
.expect(401);
|
||||
});
|
||||
|
||||
it('игнорируют X-User-Id рядом с Bearer', async () => {
|
||||
const alice = await registerUser(server, 'alice');
|
||||
const eve = await registerUser(server, 'eve');
|
||||
const res = await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(alice))
|
||||
.set('X-User-Id', eve.id)
|
||||
.expect(200);
|
||||
expect(res.body.id).toBe(alice.id);
|
||||
});
|
||||
|
||||
it('отвечают 401 на неизвестный токен', async () => {
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', 'Bearer unknown-token-value')
|
||||
.expect(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/auth/sessions/current', () => {
|
||||
it('отзывает только текущий токен: 204, затем 401 на повтор', async () => {
|
||||
const user = await registerUser(server, 'logout');
|
||||
const other = await login(server, user.username);
|
||||
await request(server)
|
||||
.delete('/api/v1/auth/sessions/current')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(204);
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(401);
|
||||
await request(server)
|
||||
.delete('/api/v1/auth/sessions/current')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(401);
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', `Bearer ${other}`)
|
||||
.expect(200);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,30 +1,20 @@
|
||||
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,
|
||||
login,
|
||||
PASSWORD,
|
||||
registerUser,
|
||||
} from './helpers';
|
||||
|
||||
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();
|
||||
({ app, server } = await createTestApp());
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -35,30 +25,17 @@ describe('Безопасность при конкурентном доступ
|
||||
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 owner = await registerUser(server, 'owner');
|
||||
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),
|
||||
registerUser(server, `racer${i}`),
|
||||
),
|
||||
);
|
||||
const memberIds = [owner.body.id, ...clients.map((c) => c.body.id)];
|
||||
const memberIds = [owner.id, ...clients.map((c) => c.id)];
|
||||
|
||||
const chat = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', owner.body.id)
|
||||
.set('Authorization', bearer(owner))
|
||||
.send({ title: 'Race', member_ids: memberIds })
|
||||
.expect(201);
|
||||
|
||||
@@ -68,7 +45,7 @@ describe('Безопасность при конкурентном доступ
|
||||
sendTasks.push(
|
||||
request(server)
|
||||
.post(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.set('X-User-Id', clients[c].body.id)
|
||||
.set('Authorization', bearer(clients[c]))
|
||||
.send({ text: `client-${c}-message-${m}` }),
|
||||
);
|
||||
}
|
||||
@@ -88,7 +65,7 @@ describe('Безопасность при конкурентном доступ
|
||||
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)
|
||||
.set('Authorization', bearer(owner))
|
||||
.expect(200);
|
||||
collected.push(...res.body.items);
|
||||
cursor = res.body.next_cursor;
|
||||
@@ -105,7 +82,7 @@ describe('Безопасность при конкурентном доступ
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.query({ limit: 100 })
|
||||
.set('X-User-Id', owner.body.id)
|
||||
.set('Authorization', bearer(owner))
|
||||
.expect(200)
|
||||
.then((res) => res.body.items);
|
||||
const sortKeys = fullHistory.map((m) => `${m.created_at}#${m.id}`);
|
||||
@@ -121,7 +98,7 @@ describe('Безопасность при конкурентном доступ
|
||||
Array.from({ length: attempts }, () =>
|
||||
request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username, display_name: 'Racer' }),
|
||||
.send({ username, display_name: 'Racer', password: PASSWORD }),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -130,12 +107,12 @@ describe('Безопасность при конкурентном доступ
|
||||
|
||||
expect(succeeded.length).toBe(1);
|
||||
expect(conflicted.length).toBe(attempts - 1);
|
||||
expect(succeeded.length + conflicted.length).toBe(attempts);
|
||||
|
||||
const listRes = await request(server)
|
||||
const token = await login(server, username);
|
||||
const me = await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('X-User-Id', succeeded[0].body.id)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
expect(listRes.body.username).toBe(username);
|
||||
expect(me.body.id).toBe(succeeded[0].body.id);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { randomUUID } from 'crypto';
|
||||
import request from 'supertest';
|
||||
import { AppModule } from '../src/app.module';
|
||||
import { configureApp } from '../src/configure-app';
|
||||
|
||||
export const PASSWORD = 'Correct-Horse-Battery-42';
|
||||
|
||||
export interface TestUser {
|
||||
id: string;
|
||||
username: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
export async function createTestApp(): Promise<{
|
||||
app: INestApplication;
|
||||
server: any;
|
||||
}> {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
const app = moduleRef.createNestApplication<NestFastifyApplication>(
|
||||
new FastifyAdapter(),
|
||||
);
|
||||
configureApp(app);
|
||||
await app.listen(0, '127.0.0.1');
|
||||
return { app, server: app.getHttpServer() };
|
||||
}
|
||||
|
||||
export function basic(username: string, password: string): string {
|
||||
return `Basic ${Buffer.from(`${username}:${password}`, 'utf8').toString('base64')}`;
|
||||
}
|
||||
|
||||
export function bearer(user: TestUser): string {
|
||||
return `Bearer ${user.token}`;
|
||||
}
|
||||
|
||||
export async function login(
|
||||
server: any,
|
||||
username: string,
|
||||
password = PASSWORD,
|
||||
): Promise<string> {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.set('Authorization', basic(username, password))
|
||||
.expect(201);
|
||||
return res.body.token;
|
||||
}
|
||||
|
||||
export async function registerUser(
|
||||
server: any,
|
||||
label: string,
|
||||
): Promise<TestUser> {
|
||||
const username = `u_${label}_${randomUUID().slice(0, 8)}`;
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username, display_name: `User ${label}`, password: PASSWORD })
|
||||
.expect(201);
|
||||
return { id: res.body.id, username, token: await login(server, username) };
|
||||
}
|
||||
Reference in New Issue
Block a user