Files
mtusi2026lab2/test/auth.e2e-spec.ts
T
2026-10-21 10:31:23 +03:00

168 lines
5.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
});
});
});