forked from mtusi2026/mtusi2026lab2
feat: lab2 done
This commit is contained in:
+399
-285
@@ -1,313 +1,427 @@
|
||||
import { HealthService } from './../src/health/health.service.js';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { Pool } from 'pg';
|
||||
import { createClient } from 'redis';
|
||||
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { App } from 'supertest/types';
|
||||
import { AppModule } from './../src/app.module.js';
|
||||
import { RequestIdInterceptor } from './../src/common/http/request-id.interceptor.js';
|
||||
import { ApiExceptionFilter } from './../src/common/errors/api-exception.filter.js';
|
||||
// The suite is black-box: run it against the compiled application process.
|
||||
// Vitest sets process.env.BASE_URL itself (Vite base), so the API URL uses its own name.
|
||||
const baseUrl = (process.env.API_BASE_URL ?? 'http://localhost:8080').replace(
|
||||
/\/+$/u,
|
||||
'',
|
||||
);
|
||||
const basicChallenge = 'Basic realm="messenger", charset="UTF-8"';
|
||||
const bearerChallenge = 'Bearer realm="messenger"';
|
||||
const password = 'integration:пароль🔐';
|
||||
const runId = randomUUID().replaceAll('-', '').slice(0, 12);
|
||||
const usernames: string[] = [];
|
||||
const tokens: string[] = [];
|
||||
let sequence = 0;
|
||||
let database: Pool;
|
||||
let redis: ReturnType<typeof createClient>;
|
||||
|
||||
describe('Foundation HTTP contract', () => {
|
||||
let app: INestApplication<App>;
|
||||
type User = {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
created_at: string;
|
||||
};
|
||||
type Session = {
|
||||
token: string;
|
||||
token_type: string;
|
||||
expires_at: string;
|
||||
user: User;
|
||||
};
|
||||
type Chat = {
|
||||
id: string;
|
||||
title: string;
|
||||
member_ids: string[];
|
||||
created_at: string;
|
||||
};
|
||||
type Message = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
};
|
||||
type Page<T> = { items: T[]; next_cursor: string | null };
|
||||
type ApiError = {
|
||||
error: { code: string; message: string; request_id: string };
|
||||
};
|
||||
type Actor = { user: User; password: string; token: string };
|
||||
type HttpResult<T> = { body: T; response: Response };
|
||||
|
||||
beforeEach(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
async function http<T = unknown>(
|
||||
path: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<HttpResult<T>> {
|
||||
const response = await fetch(`${baseUrl}${path}`, init);
|
||||
const text = await response.text();
|
||||
let body: unknown = undefined;
|
||||
if (text) {
|
||||
try {
|
||||
body = JSON.parse(text);
|
||||
} catch {
|
||||
body = text;
|
||||
}
|
||||
}
|
||||
return { body: body as T, response };
|
||||
}
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
function json(
|
||||
body: unknown,
|
||||
headers: Record<string, string> = {},
|
||||
): RequestInit {
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
};
|
||||
}
|
||||
|
||||
app.useGlobalInterceptors(new RequestIdInterceptor());
|
||||
app.useGlobalFilters(new ApiExceptionFilter());
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
function basic(username: string, secret: string): string {
|
||||
return `Basic ${Buffer.from(`${username}:${secret}`, 'utf8').toString('base64')}`;
|
||||
}
|
||||
|
||||
await app.init();
|
||||
function bearer(token: string): Record<string, string> {
|
||||
return { authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
async function register(
|
||||
displayName = 'Интеграционный пользователь',
|
||||
secret = password,
|
||||
): Promise<User> {
|
||||
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
|
||||
usernames.push(username);
|
||||
const result = await http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: displayName, password: secret }),
|
||||
);
|
||||
expect(result.response.status).toBe(201);
|
||||
return result.body;
|
||||
}
|
||||
|
||||
async function login(user: User, secret = password): Promise<Session> {
|
||||
const result = await http<Session>('/api/v1/auth/sessions', {
|
||||
method: 'POST',
|
||||
headers: { authorization: basic(user.username, secret) },
|
||||
});
|
||||
expect(result.response.status).toBe(201);
|
||||
tokens.push(result.body.token);
|
||||
return result.body;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
async function actor(displayName?: string): Promise<Actor> {
|
||||
const user = await register(displayName);
|
||||
const session = await login(user);
|
||||
return { user, password, token: session.token };
|
||||
}
|
||||
|
||||
it('returns liveness status with request id', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/health/live')
|
||||
.expect(200);
|
||||
function expectError(
|
||||
result: HttpResult<ApiError>,
|
||||
status: number,
|
||||
code: string,
|
||||
): void {
|
||||
expect(result.response.status).toBe(status);
|
||||
expect(result.body.error.code).toBe(code);
|
||||
expect(result.body.error.request_id).toBe(
|
||||
result.response.headers.get('x-request-id'),
|
||||
);
|
||||
}
|
||||
|
||||
expect(response.body).toEqual({ status: 'ok' });
|
||||
expect(response.headers['x-request-id']).toEqual(expect.any(String));
|
||||
expect(response.headers['x-request-id']).not.toHaveLength(0);
|
||||
});
|
||||
|
||||
it('returns readiness status with request id', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/health/ready')
|
||||
.expect(200);
|
||||
|
||||
expect(response.body).toEqual({ status: 'ok' });
|
||||
expect(response.headers['x-request-id']).toEqual(expect.any(String));
|
||||
});
|
||||
|
||||
it('keeps liveness alive while readiness is draining', async () => {
|
||||
app.get(HealthService).setDraining();
|
||||
|
||||
const liveResponse = await request(app.getHttpServer())
|
||||
.get('/health/live')
|
||||
.expect(200);
|
||||
expect(liveResponse.body).toEqual({ status: 'ok' });
|
||||
|
||||
const readyResponse = await request(app.getHttpServer())
|
||||
.get('/health/ready')
|
||||
.expect(503);
|
||||
const requestId = readyResponse.headers['x-request-id'];
|
||||
expect(requestId).toEqual(expect.any(String));
|
||||
expect(readyResponse.body).toEqual({
|
||||
error: {
|
||||
code: 'unavailable',
|
||||
message: 'Service is shutting down',
|
||||
request_id: requestId,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('returns contract error with matching request id for unknown route', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/health/unknown')
|
||||
.expect(404);
|
||||
|
||||
const requestId = response.headers['x-request-id'];
|
||||
|
||||
expect(requestId).toEqual(expect.any(String));
|
||||
expect(response.body).toEqual({
|
||||
error: {
|
||||
code: 'not_found',
|
||||
message: 'Resource not found',
|
||||
request_id: requestId,
|
||||
},
|
||||
describe('HTTP integration contract', () => {
|
||||
beforeAll(async () => {
|
||||
database = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
connectionTimeoutMillis: 5000,
|
||||
});
|
||||
redis = createClient({
|
||||
url: process.env.REDIS_URL,
|
||||
socket: { reconnectStrategy: false },
|
||||
});
|
||||
redis.on('error', () => {});
|
||||
await redis.connect();
|
||||
});
|
||||
|
||||
it('registers a user and returns it from /me', async () => {
|
||||
const created = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'alice',
|
||||
display_name: 'Алиса',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const user = created.body;
|
||||
|
||||
const current = await request(app.getHttpServer())
|
||||
.get('/api/v1/users/me')
|
||||
.set('X-User-Id', user.id)
|
||||
.expect(200);
|
||||
|
||||
expect(current.body).toEqual(user);
|
||||
afterAll(async () => {
|
||||
if (usernames.length) {
|
||||
await database.query('BEGIN');
|
||||
try {
|
||||
await database.query(
|
||||
`DELETE FROM messages WHERE sender_id IN (SELECT id FROM users WHERE username = ANY($1::text[]))`,
|
||||
[usernames],
|
||||
);
|
||||
await database.query(
|
||||
`DELETE FROM chats WHERE id IN (SELECT chat_id FROM chat_members WHERE user_id IN (SELECT id FROM users WHERE username = ANY($1::text[])))`,
|
||||
[usernames],
|
||||
);
|
||||
await database.query(
|
||||
'DELETE FROM users WHERE username = ANY($1::text[])',
|
||||
[usernames],
|
||||
);
|
||||
await database.query('COMMIT');
|
||||
} catch (error) {
|
||||
await database.query('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (redis.isOpen) redis.destroy();
|
||||
await database.end();
|
||||
});
|
||||
|
||||
it('rejects /me without X-User-Id', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/v1/users/me')
|
||||
.expect(401);
|
||||
|
||||
expect(response.body.error.code).toBe('unauthorized');
|
||||
expect(response.headers['x-request-id']).toBe(
|
||||
response.body.error.request_id,
|
||||
it('serves liveness and requires real session authentication', async () => {
|
||||
const live = await http<{ status: string }>('/health/live');
|
||||
expect(live.response.status).toBe(200);
|
||||
expect(live.body).toEqual({ status: 'ok' });
|
||||
const denied = await http<ApiError>('/api/v1/users/me');
|
||||
expectError(denied, 401, 'unauthorized');
|
||||
expect(denied.response.headers.get('www-authenticate')).toBe(
|
||||
bearerChallenge,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects duplicate usernames', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'duplicate_user',
|
||||
display_name: 'Первый',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'duplicate_user',
|
||||
display_name: 'Второй',
|
||||
})
|
||||
.expect(409);
|
||||
|
||||
expect(response.body.error.code).toBe('conflict');
|
||||
it('registers, logs in with Unicode/colon password, and challenges malformed Basic', async () => {
|
||||
const user = await register();
|
||||
const session = await login(user);
|
||||
expect(session.user.id).toBe(user.id);
|
||||
expect(session.token_type).toBe('Bearer');
|
||||
const me = await http<User>('/api/v1/users/me', {
|
||||
headers: bearer(session.token),
|
||||
});
|
||||
expect(me.response.status).toBe(200);
|
||||
expect(me.body.id).toBe(user.id);
|
||||
for (const authorization of [
|
||||
'Basic !!!',
|
||||
'Basic YWJj',
|
||||
'Bearer nope',
|
||||
]) {
|
||||
const result = await http<ApiError>('/api/v1/auth/sessions', {
|
||||
method: 'POST',
|
||||
headers: { authorization },
|
||||
});
|
||||
expectError(result, 401, 'unauthorized');
|
||||
expect(result.response.headers.get('www-authenticate')).toBe(
|
||||
basicChallenge,
|
||||
);
|
||||
}
|
||||
const bodyResult = await http<ApiError>('/api/v1/auth/sessions', {
|
||||
...json({ unexpected: true }),
|
||||
headers: { authorization: basic(user.username, password) },
|
||||
});
|
||||
expectError(bodyResult, 400, 'invalid_request');
|
||||
});
|
||||
|
||||
it('creates a chat and hides it from a non-member', async () => {
|
||||
const aliceResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'alice_chat',
|
||||
display_name: 'Алиса',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const bobResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'bob_chat',
|
||||
display_name: 'Боб',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const aliceId = aliceResponse.body.id;
|
||||
const bobId = bobResponse.body.id;
|
||||
|
||||
const chatResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', aliceId)
|
||||
.send({
|
||||
title: 'Учебный чат',
|
||||
member_ids: [aliceId, bobId],
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
expect(chatResponse.body.member_ids).toEqual([aliceId, bobId]);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/chats/${chatResponse.body.id}`)
|
||||
.set('X-User-Id', bobId)
|
||||
.expect(200);
|
||||
|
||||
const outsiderResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'charlie_chat',
|
||||
display_name: 'Чарли',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/chats/${chatResponse.body.id}`)
|
||||
.set('X-User-Id', outsiderResponse.body.id)
|
||||
.expect(404);
|
||||
it('returns conflict for concurrent duplicate registration', async () => {
|
||||
const username = `e2e_${runId}_race`.slice(0, 32);
|
||||
usernames.push(username);
|
||||
const results = await Promise.all([
|
||||
http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: 'Race A', password }),
|
||||
),
|
||||
http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: 'Race B', password }),
|
||||
),
|
||||
]);
|
||||
expect(
|
||||
results.filter((item) => item.response.status === 201),
|
||||
'duplicate registration must create exactly one user',
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
results.filter((item) => item.response.status === 409),
|
||||
'loser of the race must receive 409, not 500',
|
||||
).toHaveLength(1);
|
||||
// The database unique index is the race-proof guard, so verify its effect.
|
||||
const persisted = await database.query<{ count: string }>(
|
||||
'SELECT count(*)::text AS count FROM users WHERE username = $1',
|
||||
[username],
|
||||
);
|
||||
expect(persisted.rows[0]?.count).toBe('1');
|
||||
});
|
||||
|
||||
it('rejects chat when current user is not in member_ids', async () => {
|
||||
const aliceResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'alice_member',
|
||||
display_name: 'Алиса',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const bobResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'bob_member',
|
||||
display_name: 'Боб',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', aliceResponse.body.id)
|
||||
.send({
|
||||
title: 'Неверный чат',
|
||||
member_ids: [bobResponse.body.id],
|
||||
})
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.error.code).toBe('invalid_request');
|
||||
it('uses Bearer only, ignores X-User-Id spoofing, and prevents logout replay', async () => {
|
||||
const alice = await actor('Алиса');
|
||||
const bob = await actor('Боб');
|
||||
const spoof = await http<ApiError>('/api/v1/users/me', {
|
||||
headers: { ...bearer(alice.token), 'x-user-id': bob.user.id },
|
||||
});
|
||||
expect(spoof.response.status).toBe(200);
|
||||
expect((spoof.body as unknown as User).id).toBe(alice.user.id);
|
||||
const basicBusiness = await http<ApiError>('/api/v1/users/me', {
|
||||
headers: { authorization: basic(alice.user.username, password) },
|
||||
});
|
||||
expectError(basicBusiness, 401, 'unauthorized');
|
||||
expect(basicBusiness.response.headers.get('www-authenticate')).toBe(
|
||||
bearerChallenge,
|
||||
);
|
||||
const logout = await http('/api/v1/auth/sessions/current', {
|
||||
method: 'DELETE',
|
||||
headers: bearer(alice.token),
|
||||
});
|
||||
expect(logout.response.status).toBe(204);
|
||||
const replay = await http<ApiError>('/api/v1/users/me', {
|
||||
headers: bearer(alice.token),
|
||||
});
|
||||
expectError(replay, 401, 'unauthorized');
|
||||
});
|
||||
it('paginates chat history without repeating messages', async () => {
|
||||
const alice = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'page_alice', display_name: 'Алиса' })
|
||||
.expect(201);
|
||||
|
||||
const bob = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'page_bob', display_name: 'Боб' })
|
||||
.expect(201);
|
||||
it('rejects unknown and duplicate chat members and hides chats from outsiders', async () => {
|
||||
const alice = await actor();
|
||||
const bob = await actor();
|
||||
const outsider = await actor();
|
||||
const unknown = await http<ApiError>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: 'unknown', member_ids: [alice.user.id, randomUUID()] },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(unknown, 400, 'invalid_request');
|
||||
const leaked = await http<ApiError>(`/api/v1/chats?limit=100`, {
|
||||
headers: bearer(alice.token),
|
||||
});
|
||||
expect(leaked.response.status).toBe(200);
|
||||
expect(
|
||||
(leaked.body as unknown as Page<Chat>).items.some(
|
||||
(item) => item.title === 'unknown',
|
||||
),
|
||||
).toBe(false);
|
||||
const duplicate = await http<ApiError>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{
|
||||
title: 'duplicate',
|
||||
member_ids: [alice.user.id, alice.user.id],
|
||||
},
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(duplicate, 400, 'invalid_request');
|
||||
const created = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{
|
||||
title: `chat-${runId}`,
|
||||
member_ids: [alice.user.id, bob.user.id],
|
||||
},
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expect(created.response.status).toBe(201);
|
||||
const hidden = await http<ApiError>(
|
||||
`/api/v1/chats/${created.body.id}`,
|
||||
{ headers: bearer(outsider.token) },
|
||||
);
|
||||
expectError(hidden, 404, 'not_found');
|
||||
});
|
||||
|
||||
const aliceId = alice.body.id;
|
||||
const bobId = bob.body.id;
|
||||
const chat = await request(app.getHttpServer())
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', aliceId)
|
||||
.send({ title: 'История', member_ids: [aliceId, bobId] })
|
||||
.expect(201);
|
||||
it('keeps sender server-owned and makes writes visible to a second session', async () => {
|
||||
const alice = await actor();
|
||||
const secondSession = (await login(alice.user)).token;
|
||||
const chat = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: `messages-${runId}`, member_ids: [alice.user.id] },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expect(chat.response.status).toBe(201);
|
||||
const blank = await http<ApiError>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json(
|
||||
{ text: ' \n\t', sender_id: randomUUID() },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(blank, 400, 'invalid_request');
|
||||
const spoof = await http<ApiError>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json(
|
||||
{ text: 'hello', sender_id: randomUUID() },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(spoof, 400, 'invalid_request');
|
||||
await http(`/api/v1/chats/${chat.body.id}/messages?limit=50`, {
|
||||
headers: bearer(secondSession),
|
||||
});
|
||||
const sent = await http<Message>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json({ text: 'hello' }, bearer(alice.token)),
|
||||
);
|
||||
expect(sent.response.status).toBe(201);
|
||||
expect(sent.body.sender_id).toBe(alice.user.id);
|
||||
const page = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=50`,
|
||||
{ headers: bearer(secondSession) },
|
||||
);
|
||||
expect(page.response.status).toBe(200);
|
||||
expect(page.body.items.map((item) => item.id)).toContain(sent.body.id);
|
||||
});
|
||||
|
||||
const createdMessages: Array<{ id: string }> = [];
|
||||
for (const text of ['one', 'two', 'three']) {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.set('X-User-Id', aliceId)
|
||||
.send({ text })
|
||||
.expect(201);
|
||||
|
||||
createdMessages.push(response.body);
|
||||
}
|
||||
|
||||
const firstPage = await request(app.getHttpServer())
|
||||
.get(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.query({ limit: 2 })
|
||||
.set('X-User-Id', bobId)
|
||||
.expect(200);
|
||||
|
||||
expect(firstPage.body.items.map((item: { id: string }) => item.id)).toEqual(
|
||||
createdMessages.slice(0, 2).map((item) => item.id),
|
||||
);
|
||||
expect(firstPage.body.next_cursor).toEqual(expect.any(String));
|
||||
|
||||
const secondPage = await request(app.getHttpServer())
|
||||
.get(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.query({ limit: 2, cursor: firstPage.body.next_cursor })
|
||||
.set('X-User-Id', bobId)
|
||||
.expect(200);
|
||||
|
||||
expect(secondPage.body.items.map((item: { id: string }) => item.id)).toEqual(
|
||||
[createdMessages[2].id],
|
||||
);
|
||||
expect(secondPage.body.next_cursor).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects blank messages and sender spoofing fields', async () => {
|
||||
const alice = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'blank_alice', display_name: 'Алиса' })
|
||||
.expect(201);
|
||||
|
||||
const chat = await request(app.getHttpServer())
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', alice.body.id)
|
||||
.send({ title: 'Проверка', member_ids: [alice.body.id] })
|
||||
.expect(201);
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.set('X-User-Id', alice.body.id)
|
||||
.send({ text: ' ', sender_id: 'spoofed' })
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('rejects an invalid cursor and an invalid limit', async () => {
|
||||
const alice = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'cursor_alice', display_name: 'Алиса' })
|
||||
.expect(201);
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/v1/chats')
|
||||
.query({ limit: 101, cursor: 'not-a-cursor' })
|
||||
.set('X-User-Id', alice.body.id)
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
it('validates cursor, limits, malformed JSON, and paginates without repeats', async () => {
|
||||
const alice = await actor();
|
||||
const chat = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: `pages-${runId}`, member_ids: [alice.user.id] },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
for (const text of ['one', 'two', 'three']) {
|
||||
const sent = await http(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json({ text }, bearer(alice.token)),
|
||||
);
|
||||
expect(sent.response.status).toBe(201);
|
||||
}
|
||||
const invalidLimit = await http<ApiError>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=101`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expectError(invalidLimit, 400, 'invalid_request');
|
||||
const invalidCursor = await http<ApiError>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?cursor=not-a-cursor`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expectError(invalidCursor, 400, 'invalid_request');
|
||||
const malformed = await http<ApiError>('/api/v1/users', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: '{',
|
||||
});
|
||||
expectError(malformed, 400, 'invalid_request');
|
||||
const first = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=2`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expect(first.body.items).toHaveLength(2);
|
||||
const second = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=2&cursor=${encodeURIComponent(first.body.next_cursor!)}`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expect(second.body.items).toHaveLength(1);
|
||||
expect(
|
||||
new Set(
|
||||
[...first.body.items, ...second.body.items].map(
|
||||
(item) => item.id,
|
||||
),
|
||||
).size,
|
||||
).toBe(3);
|
||||
});
|
||||
|
||||
it.skipIf(process.env.SESSION_TTL_SECONDS !== '2')(
|
||||
'expires sessions with TTL=2',
|
||||
async () => {
|
||||
const user = await register();
|
||||
const session = await login(user);
|
||||
await sleep(2300);
|
||||
const expired = await http<ApiError>('/api/v1/users/me', {
|
||||
headers: bearer(session.token),
|
||||
});
|
||||
expectError(expired, 401, 'unauthorized');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user