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
+29 -2
View File
@@ -30,7 +30,11 @@ src/
cache/ версионированный кэш истории + lock на страницу
metrics/ /internal/metrics и /internal/metrics/reset
health/ liveness/readiness с проверкой зависимостей
common/ guard, exception filter, request-id, cursor, errors
common/
http/ cursor (формат+календарь), page (конверт {items,next_cursor}), request-id
errors/ exception filter и тип тела ошибки ApiErrorBody
validation/ декоратор CodePointLength (длины в Unicode code points)
auth/ guard и декоратор текущего пользователя
test/
app.e2e-spec.ts black-box набор против запущенного API (PG + Redis)
scripts/
@@ -40,7 +44,9 @@ scripts/
Принципы: raw `pg.Pool` без ORM, параметризованные запросы, никаких in-memory
хранилищ в боевых путях; кэш — производное состояние и всегда допускает
восстановление из PostgreSQL; отказ зависимости даёт ограниченную ошибку
(`503`), а не аварийное завершение процесса.
(`503`), а не аварийное завершение процесса; длины строк проверяются в Unicode
code points (свой декоратор `@CodePointLength`), как в JSON Schema, а не в
UTF-16-единицах.
## Быстрый старт
@@ -132,6 +138,7 @@ npm run start:dev # или npm run start:prod после
| `npm run start:prod` | запуск собранного приложения (`node dist/main`) |
| `npm test` / `npm run test:unit` | unit-тесты (vitest) |
| `npm run test:e2e` | black-box набор против запущенного API (см. ниже) |
| `npm run test:dependencies` | автоматическая проверка отказов Redis/PostgreSQL: останавливает и поднимает контейнеры Compose-стенда |
| `npm run lint` | oxlint по `src/` и `test/` |
| `npm run format` | prettier |
| `npm run graph` | граф модулей и провайдеров через nestjs-spelunker (пишет `../docs/architecture/`) |
@@ -158,6 +165,26 @@ npm run test:e2e
устанавливает `process.env.BASE_URL` в значение Vite base. Кейс истечения сессии
включается переменной `SESSION_TTL_SECONDS=2` и у запущенного API, и у набора.
## Отказы зависимостей
Отдельный набор останавливает и поднимает контейнеры Compose-стенда и проверяет
ограниченные ошибки вместо 500:
```sh
cd .. # из корня репозитория, стенд поднят через docker compose
make test-dependencies
```
Он включён по флагу `E2E_DEPENDENCY_FAULTS=1` (им же управляет цель Makefile),
потому что требует прав на управление Docker Compose-проектом; остальные
переменные — `E2E_COMPOSE_DIR`, `E2E_COMPOSE_ENV_FILE`, `E2E_REDIS_SERVICE`,
`E2E_POSTGRES_SERVICE`. Проверяется для Redis и PostgreSQL: `/health/live`
остаётся `200`, `/health/ready` и бизнес-запросы возвращают `503 unavailable`
с `request_id` из `X-Request-Id` и без деталей драйвера, запрос без сессии —
по-прежнему `401`, а после старта зависимости живы прежняя сессия,
подтверждённое сообщение и новая запись. Каждый запрос к остановленной БД ждёт
`DATABASE_CONNECTION_TIMEOUT_MS`, поэтому набор идёт около 40 секунд.
## Метрики
`GET /internal/metrics` возвращает `{counters, latency_ms}`: именованные SQL-метки,
+11
View File
@@ -17,6 +17,7 @@
"argon2": "^0.45.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"date-fns": "^4.4.0",
"fastify": "^5.12.5",
"pg": "^8.23.1",
"redis": "^6.3.0",
@@ -3526,6 +3527,16 @@
"node": ">= 8"
}
},
"node_modules/date-fns": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz",
"integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/kossnocorp"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+3 -1
View File
@@ -21,7 +21,8 @@
"test:cov": "vitest run --coverage",
"test:debug": "vitest --inspect-brk --no-file-parallelism",
"graph": "npm run build && DATABASE_URL=postgresql://graph-only.invalid/messenger REDIS_URL=redis://graph-only.invalid:6379 tsx scripts/graph-modules.ts",
"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
"test:e2e": "vitest run --config ./vitest.config.e2e.ts",
"test:dependencies": "E2E_DEPENDENCY_FAULTS=1 vitest run --config ./vitest.config.e2e.ts dependency-failures"
},
"dependencies": {
"@nestjs/common": "^12.0.1",
@@ -32,6 +33,7 @@
"argon2": "^0.45.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"date-fns": "^4.4.0",
"fastify": "^5.12.5",
"pg": "^8.23.1",
"redis": "^6.3.0",
+1 -5
View File
@@ -1,8 +1,4 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { BadRequestException, Injectable } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { DatabaseClient } from '../database/database.client.js';
import type { Cursor } from '../common/http/cursor.js';
+2 -1
View File
@@ -4,6 +4,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import { encodeCursor, decodeCursor } from '../common/http/cursor.js';
import type { Page } from '../common/http/page.js';
import type { User } from '../users/user.js';
import type { CreateChatDto } from './dto/create-chat.dto.js';
import type { Chat } from './chat.js';
@@ -34,7 +35,7 @@ export class ChatsService {
currentUser: User,
limit: number,
cursorValue?: string,
): Promise<{ items: Chat[]; next_cursor: string | null }> {
): Promise<Page<Chat>> {
const scope = `chats:${currentUser.id}`;
const cursor = cursorValue
? decodeCursor(cursorValue, scope)
+2 -2
View File
@@ -5,13 +5,13 @@ import {
IsArray,
IsString,
IsUUID,
Length,
Matches,
} from 'class-validator';
import { CodePointLength } from '../../common/validation/code-point-length.js';
export class CreateChatDto {
@IsString()
@Length(1, 100)
@CodePointLength(1, 100)
@Matches(/\S/, {
message: 'title must contain a non-whitespace character',
})
+7
View File
@@ -0,0 +1,7 @@
export type ApiErrorBody = {
error: {
code: string;
message: string;
request_id: string;
};
};
+57 -27
View File
@@ -4,35 +4,56 @@ import {
ExceptionFilter,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { randomUUID } from 'node:crypto';
import type { ApiErrorBody } from './api-error.js';
type RequestWithId = { requestId?: string; method?: string; url?: string };
type ExceptionBody = { message?: unknown; challenge?: unknown };
// Connection/session loss codes reported by node-postgres and the network layer.
const UNAVAILABLE_ERROR_CODES = new Set([
'ECONNREFUSED',
'ECONNRESET',
'ENOTFOUND',
'ETIMEDOUT',
'EPIPE',
'08000',
'08001',
'08003',
'08004',
'08006',
'57P01',
'57P02',
'57P03',
'53300',
]);
const UNAVAILABLE_ERROR_CODES: Record<string, true> = {
ECONNREFUSED: true,
ECONNRESET: true,
ENOTFOUND: true,
ETIMEDOUT: true,
EPIPE: true,
'08000': true,
'08001': true,
'08003': true,
'08004': true,
'08006': true,
'57P01': true,
'57P02': true,
'57P03': true,
'53300': true,
};
// Some driver failures carry no `code` at all: node-postgres raises plain errors
// when a connection dies or its pool attempt times out, and node-redis reports a
// closed socket the same way. Without these patterns a stopped database would
// surface as an internal fault instead of a bounded outage.
const UNAVAILABLE_ERROR_MESSAGES = [
'Connection terminated unexpectedly',
'Connection terminated due to connection timeout',
'timeout exceeded when trying to connect',
'Client has encountered a connection error and is not queryable',
'Socket closed unexpectedly',
'Connection is closed',
];
function isDependencyOutage(exception: unknown): boolean {
if (typeof exception !== 'object' || exception === null) return false;
const code = (exception as { code?: unknown }).code;
return typeof code === 'string' && UNAVAILABLE_ERROR_CODES.has(code);
if (typeof code === 'string' && UNAVAILABLE_ERROR_CODES[code] === true)
return true;
const message = (exception as { message?: unknown }).message;
return (
typeof message === 'string' &&
UNAVAILABLE_ERROR_MESSAGES.some((pattern) => message.includes(pattern))
);
}
function errorCodeForStatus(status: number): string {
@@ -51,6 +72,8 @@ function errorCodeForStatus(status: number): string {
@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger(ApiExceptionFilter.name);
constructor(private readonly adapterHost: HttpAdapterHost) {}
catch(exception: unknown, host: ArgumentsHost): void {
@@ -92,6 +115,16 @@ export class ApiExceptionFilter implements ExceptionFilter {
// A dropped dependency is a bounded outage, not an internal fault.
status = HttpStatus.SERVICE_UNAVAILABLE;
message = 'Service unavailable';
this.logger.warn(
`Dependency outage on ${request.method ?? ''} ${request.url ?? ''}: ${exception instanceof Error ? exception.message : 'unknown error'}`,
);
} else {
this.logger.error(
`Unhandled exception on ${request.method ?? ''} ${request.url ?? ''}`,
exception instanceof Error
? exception.stack
: String(exception),
);
}
if (status === HttpStatus.UNAUTHORIZED) {
const authChallenge =
@@ -103,16 +136,13 @@ export class ApiExceptionFilter implements ExceptionFilter {
adapter.setHeader(response, 'WWW-Authenticate', authChallenge);
}
adapter.setHeader(response, 'X-Request-Id', requestId);
adapter.reply(
response,
{
error: {
code: errorCodeForStatus(status),
message,
request_id: requestId,
},
const payload: ApiErrorBody = {
error: {
code: errorCodeForStatus(status),
message,
request_id: requestId,
},
status,
);
};
adapter.reply(response, payload, status);
}
}
+85
View File
@@ -0,0 +1,85 @@
import { BadRequestException } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import { decodeCursor, encodeCursor } from './cursor.js';
const scope = 'messages:6f1c2a3e-1111-4222-8333-444455556666';
function encode(createdAt: string, cursorScope = scope): string {
return encodeCursor({
scope: cursorScope,
created_at: createdAt,
id: randomUUID(),
});
}
describe('decodeCursor', () => {
it('accepts valid instants and normalizes them to canonical milliseconds', () => {
const accepted: Array<[string, string]> = [
['2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'],
['2026-01-01T00:00:00Z', '2026-01-01T00:00:00.000Z'],
['2026-01-01T00:00:00.999999Z', '2026-01-01T00:00:00.999Z'],
['2024-02-29T23:59:59.000Z', '2024-02-29T23:59:59.000Z'],
['2026-12-31T23:59:59.999Z', '2026-12-31T23:59:59.999Z'],
];
for (const [createdAt, expected] of accepted) {
const decoded = decodeCursor(encode(createdAt), scope);
expect(decoded.created_at).toBe(expected);
expect(decoded.scope).toBe(scope);
}
});
it('rejects calendar dates that the platform parser rolls over', () => {
// 2026-02-31 would silently become 2026-03-03 and then fail inside SQL.
for (const createdAt of [
'2026-02-31T00:00:00.000Z',
'2025-02-29T00:00:00.000Z',
'2026-04-31T00:00:00.000Z',
'2026-06-31T12:00:00.000Z',
]) {
expect(() => decodeCursor(encode(createdAt), scope)).toThrow(
BadRequestException,
);
}
});
it('rejects out-of-range and malformed timestamps', () => {
for (const createdAt of [
'2026-01-01T24:00:00.000Z',
'2026-01-01T00:00:60.000Z',
'2026-13-01T00:00:00.000Z',
'2026-00-01T00:00:00.000Z',
'2026-01-01T00:00:00',
'2026-01-01T00:00:00+02:00',
'2026-1-1T00:00:00.000Z',
'2026-01-01',
'not-a-timestamp',
]) {
expect(() => decodeCursor(encode(createdAt), scope)).toThrow(
BadRequestException,
);
}
});
it('rejects a cursor from another scope, a malformed id, and non-cursor input', () => {
expect(() =>
decodeCursor(
encode('2026-01-01T00:00:00.000Z', 'messages:other'),
scope,
),
).toThrow(BadRequestException);
expect(() =>
decodeCursor(
encodeCursor({
scope,
created_at: '2026-01-01T00:00:00.000Z',
id: 'not-a-uuid',
}),
scope,
),
).toThrow(BadRequestException);
expect(() => decodeCursor('not-a-cursor', scope)).toThrow(
BadRequestException,
);
});
});
+14 -17
View File
@@ -1,4 +1,5 @@
import { BadRequestException } from '@nestjs/common';
import { isValid, parseISO } from 'date-fns';
export type Cursor = {
scope: string;
@@ -6,6 +7,14 @@ export type Cursor = {
id: string;
};
// Format check for the canonical API shape: `Date.prototype.toISOString()` with
// optional fractional seconds. Explicit ranges reject values such as 24:00:00.
// Calendar validity (2026-02-31, 2025-02-29, 2026-04-31) is checked by
// date-fns `parseISO`, which refuses impossible dates that the platform parser
// would silently roll over into another day.
const CURSOR_TIMESTAMP =
/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?Z$/u;
export function encodeCursor(cursor: Cursor): string {
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
}
@@ -28,30 +37,18 @@ export function decodeCursor(value: string, expectedScope: string): Cursor {
!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(
parsed.id,
) ||
!/^(?:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)$/u.test(
parsed.created_at,
)
!CURSOR_TIMESTAMP.test(parsed.created_at)
)
throw new Error('invalid cursor');
const timestamp = Date.parse(parsed.created_at);
if (!Number.isFinite(timestamp)) throw new Error('invalid cursor');
const instant = parseISO(parsed.created_at);
if (!isValid(instant)) throw new Error('invalid cursor');
return {
scope: parsed.scope,
created_at: parsed.created_at,
created_at: instant.toISOString(),
id: parsed.id,
};
} catch {
throw new BadRequestException('Invalid cursor');
}
}
export function isAfter(
createdAt: string,
id: string,
cursor: Cursor,
): boolean {
return (
createdAt > cursor.created_at ||
(createdAt === cursor.created_at && id > cursor.id)
);
}
+4
View File
@@ -0,0 +1,4 @@
export type Page<T> = {
items: T[];
next_cursor: string | null;
};
@@ -0,0 +1,43 @@
import { validate } from 'class-validator';
import { describe, expect, it } from 'vitest';
import { CodePointLength } from './code-point-length.js';
class Sample {
@CodePointLength(3, 5)
value!: string;
}
async function fails(value: unknown): Promise<boolean> {
const sample = new Sample();
(sample as { value: unknown }).value = value;
const errors = await validate(sample);
return errors.length > 0;
}
describe('CodePointLength', () => {
it('counts Unicode code points instead of UTF-16 units', async () => {
// '🔐' is one code point but two UTF-16 units.
expect(await fails('🔐🔐')).toBe(true);
expect(await fails('🔐🔐🔐')).toBe(false);
expect(await fails('🔐🔐🔐🔐🔐')).toBe(false);
expect(await fails('🔐🔐🔐🔐🔐🔐')).toBe(true);
// Combining marks are separate code points, not grapheme clusters:
// three 'é' sequences are six code points and exceed the maximum.
expect(await fails('e\u0301e\u0301')).toBe(false);
expect(await fails('e\u0301e\u0301e\u0301')).toBe(true);
});
it('applies to BMP text boundaries', async () => {
expect(await fails('ab')).toBe(true);
expect(await fails('abc')).toBe(false);
expect(await fails('abcde')).toBe(false);
expect(await fails('abcdef')).toBe(true);
});
it('rejects empty and non-string values', async () => {
expect(await fails('')).toBe(true);
expect(await fails(undefined)).toBe(true);
expect(await fails(12345)).toBe(true);
expect(await fails(['a', 'b', 'c'])).toBe(true);
});
});
@@ -0,0 +1,38 @@
import {
registerDecorator,
ValidatorConstraint,
type ValidationArguments,
type ValidatorConstraintInterface,
} from 'class-validator';
// JSON Schema (and the course contract) measure string lengths in Unicode code
// points, while String.prototype.length counts UTF-16 units: one emoji outside
// the BMP is two units. `@Length` therefore accepted an 11-emoji password
// (22 units) and rejected 4000 emoji (8000 units), so these fields use an
// explicit code-point validator instead.
@ValidatorConstraint({ name: 'codePointLength', async: false })
class CodePointLengthConstraint implements ValidatorConstraintInterface {
validate(value: unknown, args: ValidationArguments): boolean {
const [min, max] = args.constraints as [number, number];
if (typeof value !== 'string') return false;
const length = [...value].length;
return length >= min && length <= max;
}
defaultMessage(args: ValidationArguments): string {
const [min, max] = args.constraints as [number, number];
return `${args.property} must be between ${min} and ${max} code points`;
}
}
export function CodePointLength(min: number, max: number): PropertyDecorator {
return (target, propertyKey) => {
registerDecorator({
name: 'codePointLength',
target: target.constructor,
propertyName: String(propertyKey),
constraints: [min, max],
validator: CodePointLengthConstraint,
});
};
}
+2 -4
View File
@@ -3,15 +3,13 @@ import { ConfigService } from '@nestjs/config';
import { setTimeout as delay } from 'node:timers/promises';
import type { AppConfig } from '../../config/app-config.schema.js';
import { RedisClient } from '../../redis/redis.client.js';
import type { Page } from '../../common/http/page.js';
import { MetricsService } from '../../metrics/metrics.service.js';
const LOCK_RETRY_COUNT = 4;
const LOCK_RETRY_DELAY_MS = 25;
export type CachePage = {
items: unknown[];
next_cursor: string | null;
};
export type CachePage = Page<unknown>;
@Injectable()
export class MessagesCacheService {
+3 -2
View File
@@ -1,7 +1,8 @@
import { IsString, Length } from 'class-validator';
import { IsString } from 'class-validator';
import { CodePointLength } from '../../common/validation/code-point-length.js';
export class CreateMessageDto {
@IsString()
@Length(1, 4000)
@CodePointLength(1, 4000)
text!: string;
}
-2
View File
@@ -1,12 +1,10 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { DatabaseClient } from '../database/database.client.js';
import type { Cursor } from '../common/http/cursor.js';
import type { User } from '../users/user.js';
import type { Message } from './message.js';
type MessageRow = {
+3 -2
View File
@@ -1,5 +1,6 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
import type { Page } from '../common/http/page.js';
import type { User } from '../users/user.js';
import { ChatsService } from '../chats/chats.service.js';
import type { CreateMessageDto } from './dto/create-message.dto.js';
@@ -35,7 +36,7 @@ export class MessagesService {
currentUser: User,
limit: number,
cursorValue?: string,
): Promise<{ items: Message[]; next_cursor: string | null }> {
): Promise<Page<Message>> {
await this.chatsService.getForUser(chatId, currentUser);
const scope = `messages:${chatId}`;
const cursor = cursorValue
@@ -70,6 +71,6 @@ export class MessagesService {
};
},
);
return page as { items: Message[]; next_cursor: string | null };
return page as Page<Message>;
}
}
+7 -3
View File
@@ -1,4 +1,5 @@
import { IsString, Length, Matches } from 'class-validator';
import { IsString, Matches } from 'class-validator';
import { CodePointLength } from '../../common/validation/code-point-length.js';
export class CreateUserDTO {
@IsString()
@@ -6,13 +7,16 @@ export class CreateUserDTO {
username!: string;
@IsString()
@Length(1, 100)
@CodePointLength(1, 100)
@Matches(/\S/u, {
message: 'display_name must contain a non-whitespace character',
})
display_name!: string;
@IsString()
@Length(12, 128)
@CodePointLength(12, 128)
@Matches(/\S/u, {
message: 'password must contain a non-whitespace character',
})
password!: string;
}
+1 -8
View File
@@ -1,4 +1,4 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import argon2 from 'argon2';
import { randomUUID } from 'node:crypto';
import { CreateUserDTO } from './dto/create-user.dto.js';
@@ -10,13 +10,6 @@ export class UsersService {
constructor(private readonly usersRepository: UsersRepository) {}
async create(input: CreateUserDTO): Promise<User> {
if (
[...input.display_name].length < 1 ||
[...input.display_name].length > 100 ||
input.display_name.trim().length === 0
) {
throw new BadRequestException('Invalid display name');
}
const passwordHash = await argon2.hash(input.password, {
type: argon2.argon2id,
});
+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,
);
});
+1 -1
View File
@@ -6,7 +6,7 @@ export default defineConfig({
test: {
globals: true,
root: './',
include: ['test/app.e2e-spec.ts'],
include: ['test/*.e2e-spec.ts'],
testTimeout: 30_000,
hookTimeout: 30_000,
sequence: { concurrent: false },