Files
mtusi2026lab3/app/src/auth/auth.controller.ts
T
ilya.tyunin e9cd28d6ba lab3: идентичность реплики, LB-проверка и общая идемпотентность отправки
Этот коммит впервые фиксирует порт lab2 (приложение NestJS+Fastify, Dockerfile,
одноservice-стенд compose, restart hook) и добавляет уровень 3/4 по lab3:

- X-Instance-Id = INSTANCE_ID либо hostname контейнера (стабилен для процесса),
  добавляется и в ответах об ошибках, которые формируются до интерсептора.
- /internal/lb-check: проба LB, намеренно не зависящая от PostgreSQL и Redis
  (отказ общей БД нельзя лечить выводом реплик из ротации); /health/ready
  остаётся операторским сигналом. /internal/metrics отдаёт instance_id и build_id.
- Общая идемпотентность POST сообщения: таблица idempotency_keys, область
  (user, method, path, key), канонический отпечаток тела, заявка+результат в
  одной транзакции, повтор возвращает сохранённый ответ, другое тело — 409,
  отсутствие/неверный ключ — 400, просрочка по IDEMPOTENCY_TTL_SECONDS.
- Транзиентные коды PostgreSQL (57014/40001/40P01) отображаются в 503, чтобы
  прерывание не фиксировалось идемпотентной записью как окончательный результат.
- Миграции 003 (идемпотентность) и 004 (pg_stat_statements для трека 1),
  операторский прогон GC: npm run idempotency:gc.
2026-10-15 21:09:23 +03:00

80 lines
2.2 KiB
TypeScript

import {
BadRequestException,
Body,
Controller,
Delete,
Headers,
HttpCode,
HttpStatus,
Post,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { TextDecoder } from 'node:util';
import { AuthService } from './auth.service.js';
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
const BASE64 =
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"';
function basicUnauthorized(): UnauthorizedException {
return new UnauthorizedException({
message: 'Unauthorized',
challenge: BASIC_CHALLENGE,
});
}
function bearerUnauthorized(): UnauthorizedException {
return new UnauthorizedException({
message: 'Unauthorized',
challenge: 'Bearer realm="messenger"',
});
}
function parseBasic(value: string | undefined): [string, string] {
if (typeof value !== 'string') throw basicUnauthorized();
const match = /^Basic[ \t]+([^ \t]+)$/iu.exec(value);
if (!match || !BASE64.test(match[1])) throw basicUnauthorized();
const bytes = Buffer.from(match[1], 'base64');
if (bytes.toString('base64') !== match[1]) throw basicUnauthorized();
let decoded: string;
try {
decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
} catch {
throw basicUnauthorized();
}
const separator = decoded.indexOf(':');
if (separator < 1) throw basicUnauthorized();
return [decoded.slice(0, separator), decoded.slice(separator + 1)];
}
@Controller('api/v1/auth/sessions')
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post()
create(
@Headers('authorization') authorization: string | undefined,
@Body() body: unknown,
) {
const [username, password] = parseBasic(authorization);
if (body !== undefined)
throw new BadRequestException(
'Session creation does not accept a body',
);
return this.auth.createSession(username, password);
}
@Delete('current')
@UseGuards(CurrentUserGuard)
@HttpCode(HttpStatus.NO_CONTENT)
async delete(
@Headers('authorization') authorization: string | undefined,
): Promise<void> {
if (!authorization || !/^Bearer\s+[^\s]+$/iu.test(authorization))
throw bearerUnauthorized();
await this.auth.deleteSession(authorization.slice(7).trim());
}
}