forked from mtusi2026/mtusi2026lab3
fix: accept empty attachment_ids, normalize member uuid case, reject repeated query params
This commit is contained in:
Executable
+143
@@ -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'
|
||||||
Regular → Executable
+3
-2
@@ -1,9 +1,10 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -eu
|
set -eu
|
||||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
: "${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")
|
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
|
if [ "$labels" != "$project/api" ]; then
|
||||||
echo "refusing to stop $TARGET_INSTANCE_ID: not an api replica of messenger-lab3 ($labels)" >&2
|
echo "refusing to stop $TARGET_INSTANCE_ID: not an api replica of $project ($labels)" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
docker stop -t 8 "$TARGET_INSTANCE_ID" >/dev/null
|
docker stop -t 8 "$TARGET_INSTANCE_ID" >/dev/null
|
||||||
|
|||||||
@@ -20,19 +20,26 @@ export class ChatsService {
|
|||||||
|
|
||||||
async create(
|
async create(
|
||||||
title: string,
|
title: string,
|
||||||
memberIds: string[],
|
rawMemberIds: string[],
|
||||||
callerId: string,
|
callerId: string,
|
||||||
): Promise<Chat> {
|
): Promise<Chat> {
|
||||||
|
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)) {
|
if (!memberIds.includes(callerId)) {
|
||||||
throw new ApiError(
|
throw new ApiError(
|
||||||
'invalid_request',
|
'invalid_request',
|
||||||
'member_ids must include the caller',
|
'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 {
|
try {
|
||||||
const chat = await this.prisma.$transaction(async (tx) => {
|
const chat = await this.prisma.$transaction(async (tx) => {
|
||||||
const created = await tx.chat.create({
|
const created = await tx.chat.create({
|
||||||
|
|||||||
@@ -8,11 +8,10 @@ export function parseLimit(raw: unknown): number {
|
|||||||
if (raw === undefined) {
|
if (raw === undefined) {
|
||||||
return DEFAULT_LIMIT;
|
return DEFAULT_LIMIT;
|
||||||
}
|
}
|
||||||
const value = Array.isArray(raw) ? raw[0] : raw;
|
if (typeof raw !== 'string' || !/^\d+$/.test(raw)) {
|
||||||
if (typeof value !== 'string' || !/^\d+$/.test(value)) {
|
|
||||||
throw new ApiError('invalid_request', 'limit must be an integer');
|
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) {
|
if (limit < MIN_LIMIT || limit > MAX_LIMIT) {
|
||||||
throw new ApiError(
|
throw new ApiError(
|
||||||
'invalid_request',
|
'invalid_request',
|
||||||
@@ -26,12 +25,11 @@ export function rawCursorParam(raw: unknown): string | null {
|
|||||||
if (raw === undefined) {
|
if (raw === undefined) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const value = Array.isArray(raw) ? raw[0] : raw;
|
if (typeof raw !== 'string' || raw.length === 0) {
|
||||||
if (typeof value !== 'string' || value.length === 0) {
|
|
||||||
throw new ApiError(
|
throw new ApiError(
|
||||||
'invalid_request',
|
'invalid_request',
|
||||||
'cursor must be a non-empty string',
|
'cursor must be a non-empty string',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return value;
|
return raw;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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';
|
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||||
|
|
||||||
export class CreateMessageDto {
|
export class CreateMessageDto {
|
||||||
@IsString()
|
@IsString()
|
||||||
@CodePointLength(0, 4000)
|
@CodePointLength(0, 4000)
|
||||||
text!: string;
|
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[];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -209,6 +209,21 @@ describe('API мессенджера (e2e) — граничные случаи
|
|||||||
.expect(400);
|
.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 () => {
|
it('принимает ровно 100 участников и отклоняет 101', async () => {
|
||||||
const alice = await createUser('max');
|
const alice = await createUser('max');
|
||||||
const ids = Array.from({ length: 100 }, () => randomUUID());
|
const ids = Array.from({ length: 100 }, () => randomUUID());
|
||||||
@@ -304,6 +319,16 @@ describe('API мессенджера (e2e) — граничные случаи
|
|||||||
.expect(400);
|
.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 () => {
|
it('отклоняет cursor, не являющийся корректным base64url JSON', async () => {
|
||||||
const alice = await createUser('pgalice4');
|
const alice = await createUser('pgalice4');
|
||||||
await request(server)
|
await request(server)
|
||||||
@@ -380,6 +405,35 @@ describe('API мессенджера (e2e) — граничные случаи
|
|||||||
expect(res.body.error.code).toBe('invalid_request');
|
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 () => {
|
it('отклоняет пустое сообщение', async () => {
|
||||||
const alice = await createUser('alice6');
|
const alice = await createUser('alice6');
|
||||||
const bob = await createUser('bob6');
|
const bob = await createUser('bob6');
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import request from 'supertest';
|
|||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
import Redis from 'ioredis';
|
import Redis from 'ioredis';
|
||||||
import { CacheService } from '../src/cache/cache.service';
|
import { CacheService } from '../src/cache/cache.service';
|
||||||
|
import { ChatsService } from '../src/chats/chats.service';
|
||||||
import { PrismaService } from '../src/db/prisma.service';
|
import { PrismaService } from '../src/db/prisma.service';
|
||||||
import { bearer, createTestApp, registerUser } from './helpers';
|
import { bearer, createTestApp, registerUser } from './helpers';
|
||||||
|
|
||||||
@@ -130,6 +131,22 @@ describe('Уровень 4: expiry, отказы зависимостей, rollb
|
|||||||
.expect(503);
|
.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 () => {
|
it('откатывает создание чата целиком, если один из участников не существует', async () => {
|
||||||
const { app, server } = await start();
|
const { app, server } = await start();
|
||||||
const alice = await registerUser(server, 'rollback');
|
const alice = await registerUser(server, 'rollback');
|
||||||
|
|||||||
Reference in New Issue
Block a user