From 8f8c89cb199121532e559e90fd07848a0143c4d5 Mon Sep 17 00:00:00 2001 From: aegor Date: Sun, 1 Nov 2026 17:51:37 +0300 Subject: [PATCH] fix: accept empty attachment_ids, normalize member uuid case, reject repeated query params --- scripts/collect-evidence.sh | 143 +++++++++++++++++++++++++ scripts/experiment.py | 0 scripts/stop-one.sh | 5 +- src/chats/chats.service.ts | 17 ++- src/common/dto/pagination-query.dto.ts | 10 +- src/messages/dto/create-message.dto.ts | 7 +- test/api.e2e-spec.ts | 54 ++++++++++ test/failures.e2e-spec.ts | 17 +++ 8 files changed, 239 insertions(+), 14 deletions(-) create mode 100755 scripts/collect-evidence.sh mode change 100644 => 100755 scripts/experiment.py diff --git a/scripts/collect-evidence.sh b/scripts/collect-evidence.sh new file mode 100755 index 00000000..090fbbb6 --- /dev/null +++ b/scripts/collect-evidence.sh @@ -0,0 +1,143 @@ +#!/bin/sh +set -u +cd "$(dirname "$0")/.." +mkdir -p evidence + +COMMIT="$(git rev-parse --short HEAD)$(git diff --quiet HEAD -- src prisma test scripts infra compose.yaml Dockerfile || echo ' (dirty)')" + +header() { + printf '# %s\n# date: %s\n# commit: %s\n\n' "$1" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$COMMIT" +} + +run() { + echo "\$ $*" + "$@" 2>&1 || echo "EXIT CODE $?" + echo +} + +started() { + docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -aq postgres redis api lb) +} + +api_states() { + docker inspect -f '{{.Name}} id={{slice .Id 0 12}} {{.State.Status}} exit={{.State.ExitCode}} finished={{.State.FinishedAt}}' $(docker compose ps -aq api) +} + +restore_api() { + for id in $(docker compose ps -aq --status exited api); do + docker start "$id" >/dev/null + done + python3 scripts/probe.py ready >/dev/null + sleep 3 +} + +echo 'container.txt' +{ + header 'Стенд: сервисы, порты, лимиты, секреты, миграции' + run docker compose ps -a --format 'table {{.Service}}\t{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}' + echo '## CPU/RAM-лимиты (NanoCpus: 1e9 = 1 CPU; Memory в байтах)' + run sh -c "docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}' \$(docker compose ps -q)" + echo '## container_name не задан (одно имя сервиса масштабируется)' + run sh -c "docker compose config | grep -c container_name" + echo '## Секреты: каждый сервис видит только свои файлы' + for service in postgres redis api lb; do + run docker compose exec -T "$service" ls /run/secrets + done + run docker compose exec -T lb haproxy -v + run docker compose exec -T postgres postgres --version + run docker compose exec -T redis redis-server --version + echo '## Миграции: отдельный one-shot сервис, повторный запуск ничего не применяет' + run docker compose run --rm migrate + run docker compose run --rm --no-deps migrate sh -c 'export DATABASE_URL="$(cat "$DATABASE_URL_FILE")"; npx prisma migrate diff --from-url "$DATABASE_URL" --to-schema-datamodel prisma/schema.prisma --exit-code' + run docker compose exec -T postgres psql -U messenger -d messenger -c 'SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY started_at' +} > evidence/container.txt + +echo 'tests.txt' +{ + header 'Собственные e2e-тесты (PostgreSQL + Redis из compose.test.yaml)' + docker compose -f compose.test.yaml build -q tests + run docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose + docker compose -f compose.test.yaml down >/dev/null 2>&1 +} > evidence/tests.txt + +echo 'smoke.txt' +{ + header 'Публичные проверки через LB; разные реплики обслуживают одну сессию' + run make check + run make test + run sh -c "docker compose ps -q api | cut -c1-12" + run python3 scripts/probe.py instances 6 +} > evidence/smoke.txt + +echo 'persistence.txt' +{ + header 'make test-persistence: restart.sh перезапускает postgres, redis, api, lb с сохранением volumes' + echo '## до' + started + echo + run make test-persistence ACTION_SCRIPT=scripts/restart.sh + echo '## после' + started +} > evidence/persistence.txt + +echo 'failover.txt' +{ + header 'make test-failover: stop-one.sh останавливает реплику, обслужившую тест; затем вторую' + for round in 1 2; do + echo "## Прогон $round" + echo '### до' + api_states + echo + since=$(date -u +%Y-%m-%dT%H:%M:%SZ) + run make test-failover ACTION_SCRIPT=scripts/stop-one.sh + echo '### после: остановленная реплика Exited (0) — штатное завершение по SIGTERM' + api_states + echo + echo '### журнал HAProxy' + docker compose logs --no-log-prefix --since "$since" lb 2>&1 | grep -E 'is DOWN|is UP|maintenance|READY' | grep -v '^\[WARNING\]' + echo + restore_api + python3 scripts/probe.py status GET /health/live >/dev/null + done + echo '## Проверка guard: stop-one.sh отказывается останавливать не api' + run env TARGET_INSTANCE_ID="$(docker compose ps -q postgres | cut -c1-12)" sh scripts/stop-one.sh +} > evidence/failover.txt + +echo 'experiments: idempotency, failover, failover --kill, rolling' +python3 scripts/experiment.py idempotency --output evidence/idempotency.json >/dev/null 2>&1 +python3 scripts/experiment.py failover --output evidence/failover-stop.json >/dev/null 2>&1 +python3 scripts/experiment.py failover --kill --output evidence/failover-kill.json >/dev/null 2>&1 +docker compose build -q api >/dev/null 2>&1 +python3 scripts/experiment.py rolling --output evidence/rolling.json >/dev/null 2>&1 + +echo 'failures.txt' +{ + header 'Отказы зависимостей, ошибки LB, expiry' + echo '## 1. Redis остановлен: вход и Bearer через PostgreSQL; logout — 503 без отзыва (токен остаётся действующим)' + run docker compose stop redis + run python3 scripts/probe.py logout + run docker compose start redis + sleep 3 + echo '## 2. Redis снова доступен: logout отзывает токен на всех репликах' + run python3 scripts/probe.py logout + echo '## 3. PostgreSQL остановлен: readiness реплик 503 → LB исключает их и сам отвечает 503 без внутренних деталей' + run docker compose stop postgres + run python3 scripts/probe.py status GET /health/live + run python3 scripts/probe.py status GET /api/v1/chats 'Bearer unknown-token' + run python3 scripts/probe.py status GET /api/v1/users/me + run docker compose start postgres + run python3 scripts/probe.py ready + echo '## 4. Все реплики API остановлены: LB отвечает 503 в формате ошибки контракта' + run docker compose stop api + run python3 scripts/probe.py status GET /api/v1/users/me + run docker compose start api + run python3 scripts/probe.py ready + echo '## 5. Expiry: реплики пересозданы с SESSION_TTL_SECONDS=2' + SESSION_TTL_SECONDS=2 docker compose up -d --no-deps --wait api >/dev/null 2>&1 + run sh -c "docker exec \$(docker compose ps -q api | head -1) printenv SESSION_TTL_SECONDS" + run python3 scripts/probe.py expiry 2 + docker compose up -d --no-deps --wait api >/dev/null 2>&1 + run python3 scripts/probe.py ready +} > evidence/failures.txt + +echo 'done' diff --git a/scripts/experiment.py b/scripts/experiment.py old mode 100644 new mode 100755 diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh index 7ce356ce..a0740f54 100755 --- a/scripts/stop-one.sh +++ b/scripts/stop-one.sh @@ -1,9 +1,10 @@ #!/bin/sh set -eu : "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +project="${COMPOSE_PROJECT_NAME:-messenger-lab3}" labels=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}/{{index .Config.Labels "com.docker.compose.service"}}' "$TARGET_INSTANCE_ID") -if [ "$labels" != "messenger-lab3/api" ]; then - echo "refusing to stop $TARGET_INSTANCE_ID: not an api replica of messenger-lab3 ($labels)" >&2 +if [ "$labels" != "$project/api" ]; then + echo "refusing to stop $TARGET_INSTANCE_ID: not an api replica of $project ($labels)" >&2 exit 1 fi docker stop -t 8 "$TARGET_INSTANCE_ID" >/dev/null diff --git a/src/chats/chats.service.ts b/src/chats/chats.service.ts index 8153b2ef..d16853e9 100644 --- a/src/chats/chats.service.ts +++ b/src/chats/chats.service.ts @@ -20,19 +20,26 @@ export class ChatsService { async create( title: string, - memberIds: string[], + rawMemberIds: string[], callerId: string, ): Promise { + const invalid = rawMemberIds.find((id) => !isUuid(id)); + if (invalid) { + throw new ApiError('invalid_request', `unknown member_id: ${invalid}`); + } + const memberIds = rawMemberIds.map((id) => id.toLowerCase()); + if (new Set(memberIds).size !== memberIds.length) { + throw new ApiError( + 'invalid_request', + "All member_ids's elements must be unique", + ); + } if (!memberIds.includes(callerId)) { throw new ApiError( 'invalid_request', 'member_ids must include the caller', ); } - const invalid = memberIds.find((id) => !isUuid(id)); - if (invalid) { - throw new ApiError('invalid_request', `unknown member_id: ${invalid}`); - } try { const chat = await this.prisma.$transaction(async (tx) => { const created = await tx.chat.create({ diff --git a/src/common/dto/pagination-query.dto.ts b/src/common/dto/pagination-query.dto.ts index bce8b7c0..cdeefc3c 100644 --- a/src/common/dto/pagination-query.dto.ts +++ b/src/common/dto/pagination-query.dto.ts @@ -8,11 +8,10 @@ export function parseLimit(raw: unknown): number { if (raw === undefined) { return DEFAULT_LIMIT; } - const value = Array.isArray(raw) ? raw[0] : raw; - if (typeof value !== 'string' || !/^\d+$/.test(value)) { + if (typeof raw !== 'string' || !/^\d+$/.test(raw)) { throw new ApiError('invalid_request', 'limit must be an integer'); } - const limit = Number(value); + const limit = Number(raw); if (limit < MIN_LIMIT || limit > MAX_LIMIT) { throw new ApiError( 'invalid_request', @@ -26,12 +25,11 @@ export function rawCursorParam(raw: unknown): string | null { if (raw === undefined) { return null; } - const value = Array.isArray(raw) ? raw[0] : raw; - if (typeof value !== 'string' || value.length === 0) { + if (typeof raw !== 'string' || raw.length === 0) { throw new ApiError( 'invalid_request', 'cursor must be a non-empty string', ); } - return value; + return raw; } diff --git a/src/messages/dto/create-message.dto.ts b/src/messages/dto/create-message.dto.ts index 23f17561..ed8a5083 100644 --- a/src/messages/dto/create-message.dto.ts +++ b/src/messages/dto/create-message.dto.ts @@ -1,8 +1,13 @@ -import { IsString } from 'class-validator'; +import { ArrayMaxSize, IsArray, IsString, ValidateIf } from 'class-validator'; import { CodePointLength } from '../../common/dto/code-point-length.validator'; export class CreateMessageDto { @IsString() @CodePointLength(0, 4000) text!: string; + + @ValidateIf((dto: CreateMessageDto) => dto.attachment_ids !== undefined) + @IsArray() + @ArrayMaxSize(0, { message: 'attachment_ids must be empty: attachments are not supported' }) + attachment_ids?: unknown[]; } diff --git a/test/api.e2e-spec.ts b/test/api.e2e-spec.ts index c8dcfa67..afe7c71d 100644 --- a/test/api.e2e-spec.ts +++ b/test/api.e2e-spec.ts @@ -209,6 +209,21 @@ describe('API мессенджера (e2e) — граничные случаи .expect(400); }); + it('считает один UUID в разном регистре дубликатом и узнаёт вызывающего в верхнем регистре', async () => { + const alice = await createUser('alicecase'); + await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Case', member_ids: [alice.id, alice.id.toUpperCase()] }) + .expect(400); + const res = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Upper', member_ids: [alice.id.toUpperCase()] }) + .expect(201); + expect(res.body.member_ids).toEqual([alice.id]); + }); + it('принимает ровно 100 участников и отклоняет 101', async () => { const alice = await createUser('max'); const ids = Array.from({ length: 100 }, () => randomUUID()); @@ -304,6 +319,16 @@ describe('API мессенджера (e2e) — граничные случаи .expect(400); }); + it('отклоняет повторённые limit и cursor', async () => { + const alice = await createUser('pgrepeat'); + for (const query of ['limit=1&limit=2', 'cursor=a&cursor=b']) { + await request(server) + .get(`/api/v1/chats?${query}`) + .set('Authorization', bearer(alice)) + .expect(400); + } + }); + it('отклоняет cursor, не являющийся корректным base64url JSON', async () => { const alice = await createUser('pgalice4'); await request(server) @@ -380,6 +405,35 @@ describe('API мессенджера (e2e) — граничные случаи expect(res.body.error.code).toBe('invalid_request'); }); + it('считает attachment_ids: [] равным отсутствию поля, непустой список отклоняет', async () => { + const alice = await createUser('aliceatt'); + const bob = await createUser('bobatt'); + const chat = await createChat(alice, bob); + const path = `/api/v1/chats/${chat.id}/messages`; + const key = randomUUID(); + const first = await request(server) + .post(path) + .set('Idempotency-Key', key) + .set('Authorization', bearer(alice)) + .send({ text: 'att' }) + .expect(201); + const replay = await request(server) + .post(path) + .set('Idempotency-Key', key) + .set('Authorization', bearer(alice)) + .send({ attachment_ids: [], text: 'att' }) + .expect(201); + expect(replay.body).toEqual(first.body); + for (const attachment_ids of [[randomUUID()], null, 'x']) { + await request(server) + .post(path) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: 'x', attachment_ids }) + .expect(400); + } + }); + it('отклоняет пустое сообщение', async () => { const alice = await createUser('alice6'); const bob = await createUser('bob6'); diff --git a/test/failures.e2e-spec.ts b/test/failures.e2e-spec.ts index 72d39854..41013f4e 100644 --- a/test/failures.e2e-spec.ts +++ b/test/failures.e2e-spec.ts @@ -3,6 +3,7 @@ import request from 'supertest'; import { randomUUID } from 'crypto'; import Redis from 'ioredis'; import { CacheService } from '../src/cache/cache.service'; +import { ChatsService } from '../src/chats/chats.service'; import { PrismaService } from '../src/db/prisma.service'; import { bearer, createTestApp, registerUser } from './helpers'; @@ -130,6 +131,22 @@ describe('Уровень 4: expiry, отказы зависимостей, rollb .expect(503); }); + it('неожиданное исключение — 500 internal_error без деталей, с X-Request-Id и X-Instance-Id', async () => { + const { app, server } = await start(); + const user = await registerUser(server, 'boom'); + jest + .spyOn(app.get(ChatsService), 'listForMember') + .mockRejectedValueOnce(new Error('secret internal details')); + const res = await request(server) + .get('/api/v1/chats') + .set('Authorization', bearer(user)) + .expect(500); + expect(res.body.error.code).toBe('internal_error'); + expect(JSON.stringify(res.body)).not.toMatch(/secret/); + expect(res.body.error.request_id).toBe(res.headers['x-request-id']); + expect(res.headers['x-instance-id']).toBeTruthy(); + }); + it('откатывает создание чата целиком, если один из участников не существует', async () => { const { app, server } = await start(); const alice = await registerUser(server, 'rollback');