fix: правки

This commit is contained in:
2026-10-10 02:13:35 +03:00
parent 1bef3845bc
commit ff47290919
30 changed files with 902 additions and 183 deletions
+146 -48
View File
@@ -3,6 +3,12 @@ import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
import { Pool } from 'pg';
import { createClient } from 'redis';
import type { SessionResponse } from '../src/auth/auth.service.js';
import type { Chat } from '../src/chats/chat.js';
import type { ApiErrorBody } from '../src/common/errors/api-error.js';
import type { Page } from '../src/common/http/page.js';
import type { Message } from '../src/messages/message.js';
import type { User } from '../src/users/user.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.
@@ -20,35 +26,6 @@ let sequence = 0;
let database: Pool;
let redis: ReturnType<typeof createClient>;
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 };
@@ -102,8 +79,8 @@ async function register(
return result.body;
}
async function login(user: User, secret = password): Promise<Session> {
const result = await http<Session>('/api/v1/auth/sessions', {
async function login(user: User, secret = password): Promise<SessionResponse> {
const result = await http<SessionResponse>('/api/v1/auth/sessions', {
method: 'POST',
headers: { authorization: basic(user.username, secret) },
});
@@ -119,7 +96,7 @@ async function actor(displayName?: string): Promise<Actor> {
}
function expectError(
result: HttpResult<ApiError>,
result: HttpResult<ApiErrorBody>,
status: number,
code: string,
): void {
@@ -174,13 +151,120 @@ describe('HTTP integration contract', () => {
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');
const denied = await http<ApiErrorBody>('/api/v1/users/me');
expectError(denied, 401, 'unauthorized');
expect(denied.response.headers.get('www-authenticate')).toBe(
bearerChallenge,
);
});
it('measures string lengths in Unicode code points', async () => {
const emoji = '🔐';
const username = (suffix: string) =>
`e2e_${runId}_${suffix}`.slice(0, 32);
const rejected = await http<ApiErrorBody>(
'/api/v1/users',
json({
username: username('cp_short'),
display_name: 'Code points',
password: emoji.repeat(11),
}),
);
expectError(rejected, 400, 'invalid_request');
const tooLongPassword = await http<ApiErrorBody>(
'/api/v1/users',
json({
username: username('cp_long'),
display_name: 'Code points',
password: emoji.repeat(129),
}),
);
expectError(tooLongPassword, 400, 'invalid_request');
const tooLongName = await http<ApiErrorBody>(
'/api/v1/users',
json({
username: username('cp_name'),
display_name: emoji.repeat(101),
password,
}),
);
expectError(tooLongName, 400, 'invalid_request');
const shortUsername = username('cp_ok');
usernames.push(shortUsername);
const boundaryPassword = emoji.repeat(12);
const created = await http<User>(
'/api/v1/users',
json({
username: shortUsername,
display_name: emoji.repeat(100),
password: boundaryPassword,
}),
);
expect(created.response.status).toBe(201);
expect([...created.body.display_name].length).toBe(100);
// The stored password keeps all 12 code points: authentication works.
const session = await http<SessionResponse>('/api/v1/auth/sessions', {
method: 'POST',
headers: {
authorization: basic(shortUsername, boundaryPassword),
},
});
expect(session.response.status).toBe(201);
tokens.push(session.body.token);
const longTitleRejected = await http<ApiErrorBody>(
'/api/v1/chats',
json(
{ title: emoji.repeat(101), member_ids: [created.body.id] },
bearer(session.body.token),
),
);
expectError(longTitleRejected, 400, 'invalid_request');
const longTitle = await http<Chat>(
'/api/v1/chats',
json(
{ title: emoji.repeat(100), member_ids: [created.body.id] },
bearer(session.body.token),
),
);
expect(longTitle.response.status).toBe(201);
const tooLongText = await http<ApiErrorBody>(
`/api/v1/chats/${longTitle.body.id}/messages`,
json({ text: emoji.repeat(4001) }, bearer(session.body.token)),
);
expectError(tooLongText, 400, 'invalid_request');
const boundaryText = await http<Message>(
`/api/v1/chats/${longTitle.body.id}/messages`,
json({ text: emoji.repeat(4000) }, bearer(session.body.token)),
);
expect(boundaryText.response.status).toBe(201);
expect([...boundaryText.body.text].length).toBe(4000);
});
it('rejects whitespace-only and too-short credentials', async () => {
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
usernames.push(username);
const cases = [
{ password: ' '.repeat(12), display_name: 'Пользователь' },
{ password: '\t'.repeat(16), display_name: 'Пользователь' },
{ password: 'short-pass', display_name: 'Пользователь' },
{ password, display_name: ' ' },
];
for (const body of cases) {
const result = await http<ApiErrorBody>(
'/api/v1/users',
json({ username, ...body }),
);
expectError(result, 400, 'invalid_request');
}
const accepted = await http<User>(
'/api/v1/users',
json({ username, display_name: 'Пользователь', password }),
);
expect(accepted.response.status).toBe(201);
});
it('registers, logs in with Unicode/colon password, and challenges malformed Basic', async () => {
const user = await register();
const session = await login(user);
@@ -196,7 +280,7 @@ describe('HTTP integration contract', () => {
'Basic YWJj',
'Bearer nope',
]) {
const result = await http<ApiError>('/api/v1/auth/sessions', {
const result = await http<ApiErrorBody>('/api/v1/auth/sessions', {
method: 'POST',
headers: { authorization },
});
@@ -205,7 +289,7 @@ describe('HTTP integration contract', () => {
basicChallenge,
);
}
const bodyResult = await http<ApiError>('/api/v1/auth/sessions', {
const bodyResult = await http<ApiErrorBody>('/api/v1/auth/sessions', {
...json({ unexpected: true }),
headers: { authorization: basic(user.username, password) },
});
@@ -244,12 +328,12 @@ describe('HTTP integration contract', () => {
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', {
const spoof = await http<ApiErrorBody>('/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', {
const basicBusiness = await http<ApiErrorBody>('/api/v1/users/me', {
headers: { authorization: basic(alice.user.username, password) },
});
expectError(basicBusiness, 401, 'unauthorized');
@@ -261,7 +345,7 @@ describe('HTTP integration contract', () => {
headers: bearer(alice.token),
});
expect(logout.response.status).toBe(204);
const replay = await http<ApiError>('/api/v1/users/me', {
const replay = await http<ApiErrorBody>('/api/v1/users/me', {
headers: bearer(alice.token),
});
expectError(replay, 401, 'unauthorized');
@@ -271,7 +355,7 @@ describe('HTTP integration contract', () => {
const alice = await actor();
const bob = await actor();
const outsider = await actor();
const unknown = await http<ApiError>(
const unknown = await http<ApiErrorBody>(
'/api/v1/chats',
json(
{ title: 'unknown', member_ids: [alice.user.id, randomUUID()] },
@@ -279,7 +363,7 @@ describe('HTTP integration contract', () => {
),
);
expectError(unknown, 400, 'invalid_request');
const leaked = await http<ApiError>(`/api/v1/chats?limit=100`, {
const leaked = await http<ApiErrorBody>(`/api/v1/chats?limit=100`, {
headers: bearer(alice.token),
});
expect(leaked.response.status).toBe(200);
@@ -288,7 +372,7 @@ describe('HTTP integration contract', () => {
(item) => item.title === 'unknown',
),
).toBe(false);
const duplicate = await http<ApiError>(
const duplicate = await http<ApiErrorBody>(
'/api/v1/chats',
json(
{
@@ -310,7 +394,7 @@ describe('HTTP integration contract', () => {
),
);
expect(created.response.status).toBe(201);
const hidden = await http<ApiError>(
const hidden = await http<ApiErrorBody>(
`/api/v1/chats/${created.body.id}`,
{ headers: bearer(outsider.token) },
);
@@ -328,7 +412,7 @@ describe('HTTP integration contract', () => {
),
);
expect(chat.response.status).toBe(201);
const blank = await http<ApiError>(
const blank = await http<ApiErrorBody>(
`/api/v1/chats/${chat.body.id}/messages`,
json(
{ text: ' \n\t', sender_id: randomUUID() },
@@ -336,7 +420,7 @@ describe('HTTP integration contract', () => {
),
);
expectError(blank, 400, 'invalid_request');
const spoof = await http<ApiError>(
const spoof = await http<ApiErrorBody>(
`/api/v1/chats/${chat.body.id}/messages`,
json(
{ text: 'hello', sender_id: randomUUID() },
@@ -377,17 +461,31 @@ describe('HTTP integration contract', () => {
);
expect(sent.response.status).toBe(201);
}
const invalidLimit = await http<ApiError>(
const invalidLimit = await http<ApiErrorBody>(
`/api/v1/chats/${chat.body.id}/messages?limit=101`,
{ headers: bearer(alice.token) },
);
expectError(invalidLimit, 400, 'invalid_request');
const invalidCursor = await http<ApiError>(
const invalidCursor = await http<ApiErrorBody>(
`/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', {
const rolledOver = http<ApiErrorBody>(
`/api/v1/chats/${chat.body.id}/messages?cursor=${encodeURIComponent(
Buffer.from(
JSON.stringify({
scope: `messages:${chat.body.id}`,
created_at: '2026-02-31T00:00:00.000Z',
id: randomUUID(),
}),
'utf8',
).toString('base64url'),
)}`,
{ headers: bearer(alice.token) },
);
expectError(await rolledOver, 400, 'invalid_request');
const malformed = await http<ApiErrorBody>('/api/v1/users', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{',
@@ -418,7 +516,7 @@ describe('HTTP integration contract', () => {
const user = await register();
const session = await login(user);
await sleep(2300);
const expired = await http<ApiError>('/api/v1/users/me', {
const expired = await http<ApiErrorBody>('/api/v1/users/me', {
headers: bearer(session.token),
});
expectError(expired, 401, 'unauthorized');
+290
View File
@@ -0,0 +1,290 @@
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import type { SessionResponse } from '../src/auth/auth.service.js';
import type { Chat } from '../src/chats/chat.js';
import type { ApiErrorBody } from '../src/common/errors/api-error.js';
import type { Page } from '../src/common/http/page.js';
import type { Message } from '../src/messages/message.js';
import type { User } from '../src/users/user.js';
// Automated counterpart of the manual Redis/PostgreSQL outage checks: the suite
// stops a dependency of the Compose stand, asserts a bounded 503 (never a 500,
// never a trusted anonymous request, never a leaked driver error) and then
// restarts it to prove recovery without data loss.
//
// It is opt-in because it needs control over the Docker Compose project:
// make test-dependencies
// cd app && E2E_DEPENDENCY_FAULTS=1 npm run test:dependencies
const enabled = process.env.E2E_DEPENDENCY_FAULTS === '1';
const baseUrl = (process.env.API_BASE_URL ?? 'http://localhost:8080').replace(
/\/+$/u,
'',
);
const composeDir =
process.env.E2E_COMPOSE_DIR ??
fileURLToPath(new URL('../..', import.meta.url));
const composeEnvFile = process.env.E2E_COMPOSE_ENV_FILE ?? '.env';
const redisService = process.env.E2E_REDIS_SERVICE ?? 'redis';
const postgresService = process.env.E2E_POSTGRES_SERVICE ?? 'postgres';
const password = 'outage-check:пароль🔐';
const runId = randomUUID().replaceAll('-', '').slice(0, 12);
// A request that reaches a stopped database waits for the pool connection
// timeout, so every outage step costs up to DATABASE_CONNECTION_TIMEOUT_MS.
const outagedRequestBudgetMs = 180_000;
const execFileAsync = promisify(execFile);
type Result<T> = { body: T; text: string; response: Response };
async function compose(...args: string[]): Promise<void> {
await execFileAsync(
'docker',
['compose', '--env-file', composeEnvFile, ...args],
{ cwd: composeDir, timeout: 120_000 },
);
}
async function request<T = unknown>(
path: string,
init: RequestInit = {},
): Promise<Result<T>> {
const response = await fetch(`${baseUrl}${path}`, init);
const text = await response.text();
return { body: (text ? JSON.parse(text) : undefined) as T, text, response };
}
function json(
body: unknown,
headers: Record<string, string> = {},
): RequestInit {
return {
method: 'POST',
headers: { 'content-type': 'application/json', ...headers },
body: JSON.stringify(body),
};
}
function bearer(token: string): Record<string, string> {
return { authorization: `Bearer ${token}` };
}
function basic(username: string, secret: string): string {
return `Basic ${Buffer.from(`${username}:${secret}`, 'utf8').toString('base64')}`;
}
// The dependencies recover asynchronously, so readiness is polled instead of
// asserted right after docker compose returns.
async function waitForReadiness(
expected: number,
timeoutMs = 90_000,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
let last: number | string = 'no response';
for (;;) {
try {
const probe = await request('/health/ready');
last = probe.response.status;
if (probe.response.status === expected) return;
} catch (error) {
last = error instanceof Error ? error.message : 'request failed';
}
if (Date.now() > deadline)
throw new Error(
`readiness never became ${expected} within ${timeoutMs}ms (last: ${String(last)})`,
);
await sleep(250);
}
}
function expectBoundedOutage(result: Result<ApiErrorBody>): void {
expect(result.response.status).toBe(503);
expect(result.body.error.code).toBe('unavailable');
expect(result.body.error.message).toBe('Service unavailable');
expect(result.body.error.request_id).toBe(
result.response.headers.get('x-request-id'),
);
// A bounded error must not leak driver details, SQL text or a stack trace.
expect(result.text).not.toMatch(
/ECONNREFUSED|ECONNRESET|Connection terminated|pg\.|node_modules|at .*\(.+:\d+:\d+\)/u,
);
}
async function historyOf(
chatId: string,
token: string,
): Promise<Result<Page<Message>>> {
return request<Page<Message>>(`/api/v1/chats/${chatId}/messages?limit=100`, {
headers: bearer(token),
});
}
describe.skipIf(!enabled)('dependency outages', () => {
let user: User;
let token: string;
let chat: Chat;
let message: Message;
beforeAll(async () => {
await compose('up', '-d');
await waitForReadiness(200);
const username = `outage_${runId}`;
const registered = await request<User>(
'/api/v1/users',
json({ username, display_name: 'Отказ зависимости', password }),
);
expect(registered.response.status).toBe(201);
user = registered.body;
const session = await request<SessionResponse>(
'/api/v1/auth/sessions',
{
method: 'POST',
headers: { authorization: basic(username, password) },
},
);
expect(session.response.status).toBe(201);
token = session.body.token;
const created = await request<Chat>(
'/api/v1/chats',
json(
{ title: `outage-${runId}`, member_ids: [user.id] },
bearer(token),
),
);
expect(created.response.status).toBe(201);
chat = created.body;
const sent = await request<Message>(
`/api/v1/chats/${chat.id}/messages`,
json({ text: 'Сообщение до отказа' }, bearer(token)),
);
expect(sent.response.status).toBe(201);
message = sent.body;
}, outagedRequestBudgetMs);
afterAll(async () => {
// Always restore the stand, even when an assertion failed mid-outage.
await compose('start', redisService);
await compose('start', postgresService);
await waitForReadiness(200);
}, outagedRequestBudgetMs);
it(
'serves bounded 503 for the Redis outage and recovers the session',
async () => {
await compose('stop', redisService);
const live = await request('/health/live');
expect(live.response.status).toBe(200);
await waitForReadiness(503);
expectBoundedOutage(await request<ApiErrorBody>('/health/ready'));
expectBoundedOutage(
await request<ApiErrorBody>('/api/v1/users/me', {
headers: bearer(token),
}),
);
expectBoundedOutage(
await request<ApiErrorBody>('/api/v1/auth/sessions', {
method: 'POST',
headers: { authorization: basic(user.username, password) },
}),
);
// A request without a session must stay unauthorized during an outage:
// the outage may not turn an anonymous caller into a trusted one.
const anonymous = await request<ApiErrorBody>('/api/v1/chats', {
headers: { 'x-user-id': user.id },
});
expect(anonymous.response.status).toBe(401);
expect(anonymous.body.error.code).toBe('unauthorized');
await compose('start', redisService);
await waitForReadiness(200);
// Sessions live in Redis with persistence, so the old token still works.
const recovered = await request<User>('/api/v1/users/me', {
headers: bearer(token),
});
expect(recovered.response.status).toBe(200);
expect(recovered.body.id).toBe(user.id);
const history = await historyOf(chat.id, token);
expect(history.response.status).toBe(200);
expect(history.body.items.map((item) => item.id)).toContain(
message.id,
);
},
outagedRequestBudgetMs,
);
it(
'serves bounded 503 for the PostgreSQL outage and keeps confirmed data',
async () => {
await compose('stop', postgresService);
const live = await request('/health/live');
expect(live.response.status).toBe(200);
await waitForReadiness(503);
expectBoundedOutage(await request<ApiErrorBody>('/health/ready'));
// Redis still answers, so these requests reach the database layer.
expectBoundedOutage(
await request<ApiErrorBody>('/api/v1/users/me', {
headers: bearer(token),
}),
);
expectBoundedOutage(
await request<ApiErrorBody>('/api/v1/chats', {
headers: bearer(token),
}),
);
expectBoundedOutage(
await request<ApiErrorBody>(
`/api/v1/chats/${chat.id}/messages?limit=100`,
{ headers: bearer(token) },
),
);
expectBoundedOutage(
await request<ApiErrorBody>(
'/api/v1/users',
json({
username: `outage_${runId}_late`,
display_name: 'Отказ зависимости',
password,
}),
),
);
await compose('start', postgresService);
await waitForReadiness(200);
const recovered = await request<User>('/api/v1/users/me', {
headers: bearer(token),
});
expect(recovered.response.status).toBe(200);
expect(recovered.body.id).toBe(user.id);
const history = await historyOf(chat.id, token);
expect(history.response.status).toBe(200);
expect(history.body.items.map((item) => item.id)).toContain(
message.id,
);
const sent = await request<Message>(
`/api/v1/chats/${chat.id}/messages`,
json({ text: 'Сообщение после отказа' }, bearer(token)),
);
expect(sent.response.status).toBe(201);
},
outagedRequestBudgetMs,
);
});