forked from mtusi2026/mtusi2026lab2
347 lines
10 KiB
JavaScript
347 lines
10 KiB
JavaScript
import 'dotenv/config';
|
|
import assert from 'node:assert/strict';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { createRequire } from 'node:module';
|
|
import test from 'node:test';
|
|
|
|
const require = createRequire(import.meta.url);
|
|
const { NestFactory } = require('@nestjs/core');
|
|
const { AppModule } = require('../dist/app.module');
|
|
const { PrismaService } = require('../dist/prisma/prisma.service');
|
|
const {
|
|
createFastifyAdapter,
|
|
exposeRequestIdHeader,
|
|
} = require('../dist/common/http/fastify-adapter');
|
|
|
|
async function start() {
|
|
const app = await NestFactory.create(AppModule, createFastifyAdapter(), {
|
|
logger: false,
|
|
abortOnError: false,
|
|
});
|
|
try {
|
|
exposeRequestIdHeader(app);
|
|
await app.init();
|
|
const server = app.getHttpAdapter().getInstance();
|
|
await server.ready();
|
|
return { app, server, prisma: app.get(PrismaService) };
|
|
} catch (error) {
|
|
await app.close();
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
test('PostgreSQL storage: constraints, pagination, access and application restart', async (t) => {
|
|
assert.ok(
|
|
process.env.DATABASE_URL,
|
|
'Set DATABASE_URL and apply migrations before running this test',
|
|
);
|
|
let context = await start();
|
|
const userIds = [];
|
|
const chatIds = [];
|
|
t.after(async () => {
|
|
try {
|
|
await context.prisma.chat.deleteMany({ where: { id: { in: chatIds } } });
|
|
await context.prisma.user.deleteMany({ where: { id: { in: userIds } } });
|
|
} finally {
|
|
await context.app.close();
|
|
}
|
|
});
|
|
const suffix = randomUUID().replaceAll('-', '').slice(0, 16);
|
|
const password = '🔐'.repeat(40) + ':пароль с пробелами ';
|
|
const tokens = new Map();
|
|
const request = (method, url, payload, userId) =>
|
|
context.server.inject({
|
|
method,
|
|
url,
|
|
...(payload === undefined ? {} : { payload }),
|
|
...(userId
|
|
? { headers: { authorization: `Bearer ${tokens.get(userId)}` } }
|
|
: {}),
|
|
});
|
|
|
|
const registrations = await Promise.all(
|
|
Array.from({ length: 4 }, () =>
|
|
request('POST', '/api/v1/users', {
|
|
username: `race_${suffix}`,
|
|
display_name: 'Race',
|
|
password,
|
|
}),
|
|
),
|
|
);
|
|
for (const response of registrations) {
|
|
if (response.statusCode === 201) userIds.push(response.json().id);
|
|
}
|
|
assert.deepEqual(
|
|
registrations.map((response) => response.statusCode).sort(),
|
|
[201, 409, 409, 409],
|
|
);
|
|
const userId = userIds[0];
|
|
const outsider = await request('POST', '/api/v1/users', {
|
|
username: `other_${suffix}`,
|
|
display_name: 'Other',
|
|
password,
|
|
});
|
|
assert.equal(outsider.statusCode, 201);
|
|
userIds.push(outsider.json().id);
|
|
|
|
const login = (username, secret = password, payload) =>
|
|
context.server.inject({
|
|
method: 'POST',
|
|
url: '/api/v1/auth/sessions',
|
|
headers: {
|
|
authorization: `Basic ${Buffer.from(`${username}:${secret}`, 'utf8').toString('base64')}`,
|
|
},
|
|
...(payload === undefined ? {} : { payload }),
|
|
});
|
|
for (const user of [
|
|
registrations.find((r) => r.statusCode === 201).json(),
|
|
outsider.json(),
|
|
]) {
|
|
assert.deepEqual(Object.keys(user).sort(), [
|
|
'created_at',
|
|
'display_name',
|
|
'id',
|
|
'username',
|
|
]);
|
|
const response = await login(user.username);
|
|
assert.equal(response.statusCode, 201);
|
|
assert.equal(response.json().token_type, 'Bearer');
|
|
assert.match(response.json().token, /^[A-Za-z0-9_-]{43}$/);
|
|
assert.deepEqual(response.json().user, user);
|
|
tokens.set(user.id, response.json().token);
|
|
const stored = await context.prisma.user.findUniqueOrThrow({
|
|
where: { id: user.id },
|
|
});
|
|
assert.match(stored.passwordHash, /^\$argon2id\$v=19\$m=19456,t=2,p=1\$/);
|
|
assert.ok(!stored.passwordHash.includes(password));
|
|
}
|
|
const sessions = await context.prisma.session.findMany({ where: { userId } });
|
|
assert.equal(sessions.length, 1);
|
|
assert.match(sessions[0].tokenHash, /^[a-f0-9]{64}$/);
|
|
assert.notEqual(sessions[0].tokenHash, tokens.get(userId));
|
|
const wrong = await login(`race_${suffix}`, 'wrong-password');
|
|
const unknown = await login(`missing_${suffix}`, 'wrong-password');
|
|
assert.equal(wrong.statusCode, 401);
|
|
assert.equal(unknown.statusCode, 401);
|
|
assert.equal(wrong.json().error.message, unknown.json().error.message);
|
|
assert.equal(
|
|
wrong.headers['www-authenticate'],
|
|
'Basic realm="messenger", charset="UTF-8"',
|
|
);
|
|
assert.equal((await login(`race_${suffix}`, password, {})).statusCode, 400);
|
|
for (const invalid of [
|
|
undefined,
|
|
'short',
|
|
' '.repeat(12),
|
|
'🔐'.repeat(129),
|
|
]) {
|
|
assert.equal(
|
|
(
|
|
await request('POST', '/api/v1/users', {
|
|
username: `bad_${suffix}`,
|
|
display_name: 'Bad',
|
|
...(invalid === undefined ? {} : { password: invalid }),
|
|
})
|
|
).statusCode,
|
|
400,
|
|
);
|
|
}
|
|
for (const authorization of [
|
|
undefined,
|
|
'Bearer unknown',
|
|
`Basic ${Buffer.from(`race_${suffix}:${password}`).toString('base64')}`,
|
|
]) {
|
|
const response = await context.server.inject({
|
|
method: 'GET',
|
|
url: '/api/v1/users/me',
|
|
headers: {
|
|
'x-user-id': userId,
|
|
...(authorization ? { authorization } : {}),
|
|
},
|
|
});
|
|
assert.equal(response.statusCode, 401);
|
|
assert.equal(
|
|
response.headers['www-authenticate'],
|
|
'Bearer realm="messenger"',
|
|
);
|
|
}
|
|
const identity = await context.server.inject({
|
|
method: 'GET',
|
|
url: '/api/v1/users/me',
|
|
headers: {
|
|
authorization: `Bearer ${tokens.get(userId)}`,
|
|
'x-user-id': outsider.json().id,
|
|
},
|
|
});
|
|
assert.equal(identity.json().id, userId);
|
|
|
|
const ready = await request('GET', '/health/ready');
|
|
assert.equal(ready.statusCode, 200);
|
|
|
|
const invalidChat = await request(
|
|
'POST',
|
|
'/api/v1/chats',
|
|
{
|
|
title: `invalid_${suffix}`,
|
|
member_ids: [userId, randomUUID()],
|
|
},
|
|
userId,
|
|
);
|
|
assert.equal(invalidChat.statusCode, 400);
|
|
assert.equal(
|
|
await context.prisma.chat.count({ where: { title: `invalid_${suffix}` } }),
|
|
0,
|
|
);
|
|
|
|
const rolledBackId = randomUUID();
|
|
chatIds.push(rolledBackId);
|
|
await assert.rejects(
|
|
context.prisma.$transaction(async (tx) => {
|
|
await tx.chat.create({ data: { id: rolledBackId, title: 'Rollback' } });
|
|
await tx.chatMember.create({
|
|
data: { chatId: rolledBackId, userId: randomUUID(), position: 0 },
|
|
});
|
|
}),
|
|
{ code: 'P2003' },
|
|
);
|
|
assert.equal(
|
|
await context.prisma.chat.count({ where: { id: rolledBackId } }),
|
|
0,
|
|
);
|
|
|
|
const createdChat = await request(
|
|
'POST',
|
|
'/api/v1/chats',
|
|
{ title: 'Persisted chat', member_ids: [userId] },
|
|
userId,
|
|
);
|
|
assert.equal(createdChat.statusCode, 201);
|
|
const chatId = createdChat.json().id;
|
|
chatIds.push(chatId);
|
|
const forbidden = await request(
|
|
'GET',
|
|
`/api/v1/chats/${chatId}`,
|
|
undefined,
|
|
outsider.json().id,
|
|
);
|
|
assert.equal(forbidden.statusCode, 404);
|
|
const unauthorized = await request('GET', `/api/v1/chats/${chatId}`);
|
|
assert.equal(unauthorized.statusCode, 401);
|
|
|
|
const messageIds = [];
|
|
for (let i = 0; i < 5; i++) {
|
|
const message = await request(
|
|
'POST',
|
|
`/api/v1/chats/${chatId}/messages`,
|
|
{ text: `Message ${i}` },
|
|
userId,
|
|
);
|
|
assert.equal(message.statusCode, 201);
|
|
messageIds.push(message.json().id);
|
|
}
|
|
await context.prisma.message.updateMany({
|
|
where: { chatId },
|
|
data: { createdAt: new Date('2026-01-01T00:00:00.000Z') },
|
|
});
|
|
const first = await request(
|
|
'GET',
|
|
`/api/v1/chats/${chatId}/messages?limit=2`,
|
|
undefined,
|
|
userId,
|
|
);
|
|
assert.equal(first.statusCode, 200);
|
|
assert.equal(first.json().items.length, 2);
|
|
assert.ok(first.json().next_cursor);
|
|
|
|
await context.app.close();
|
|
context = await start();
|
|
const me = await request('GET', '/api/v1/users/me', undefined, userId);
|
|
assert.equal(me.statusCode, 200);
|
|
const chat = await request(
|
|
'GET',
|
|
`/api/v1/chats/${chatId}`,
|
|
undefined,
|
|
userId,
|
|
);
|
|
assert.equal(chat.statusCode, 200);
|
|
assert.deepEqual(chat.json().member_ids, [userId]);
|
|
const listed = await request(
|
|
'GET',
|
|
'/api/v1/chats?limit=1',
|
|
undefined,
|
|
userId,
|
|
);
|
|
assert.deepEqual(
|
|
listed.json().items.map((item) => item.id),
|
|
[chatId],
|
|
);
|
|
|
|
const seen = first.json().items.map((message) => message.id);
|
|
let cursor = first.json().next_cursor;
|
|
while (cursor) {
|
|
const page = await request(
|
|
'GET',
|
|
`/api/v1/chats/${chatId}/messages?limit=2&cursor=${cursor}`,
|
|
undefined,
|
|
userId,
|
|
);
|
|
assert.equal(page.statusCode, 200);
|
|
assert.ok(page.json().items.length <= 2);
|
|
seen.push(...page.json().items.map((message) => message.id));
|
|
cursor = page.json().next_cursor;
|
|
}
|
|
assert.deepEqual(seen, [...messageIds].sort());
|
|
assert.equal(new Set(seen).size, 5);
|
|
|
|
const logouts = await Promise.all(
|
|
Array.from({ length: 2 }, () =>
|
|
request('DELETE', '/api/v1/auth/sessions/current', undefined, userId),
|
|
),
|
|
);
|
|
assert.deepEqual(logouts.map((r) => r.statusCode).sort(), [204, 401]);
|
|
assert.equal(logouts.find((r) => r.statusCode === 204).body, '');
|
|
assert.equal(
|
|
(await request('GET', '/api/v1/users/me', undefined, userId)).statusCode,
|
|
401,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await request(
|
|
'DELETE',
|
|
'/api/v1/auth/sessions/current',
|
|
undefined,
|
|
userId,
|
|
)
|
|
).statusCode,
|
|
401,
|
|
);
|
|
await context.app.close();
|
|
const originalTtl = process.env.SESSION_TTL_SECONDS;
|
|
process.env.SESSION_TTL_SECONDS = '2';
|
|
try {
|
|
context = await start();
|
|
} finally {
|
|
if (originalTtl === undefined) delete process.env.SESSION_TTL_SECONDS;
|
|
else process.env.SESSION_TTL_SECONDS = originalTtl;
|
|
}
|
|
const short = await login(`race_${suffix}`);
|
|
assert.equal(short.statusCode, 201);
|
|
tokens.set(userId, short.json().token);
|
|
assert.equal(
|
|
(await request('GET', '/api/v1/users/me', undefined, userId)).statusCode,
|
|
200,
|
|
);
|
|
await context.app.close();
|
|
context = await start();
|
|
await new Promise((resolve) =>
|
|
setTimeout(
|
|
resolve,
|
|
Math.max(0, Date.parse(short.json().expires_at) - Date.now()) + 100,
|
|
),
|
|
);
|
|
assert.equal(
|
|
(await request('GET', '/api/v1/users/me', undefined, userId)).statusCode,
|
|
401,
|
|
);
|
|
});
|