feat: add authentication and RBAC

- packages/database: schema Prisma (users/sessions/roles/permissions/
  user_roles/role_permissions/audit_logs/password_reset_tokens), migration
  inicial e seed (permissoes+perfis+bootstrap super_admin com senha
  aleatoria em FIRST_LOGIN.txt). Decisao de ORM (Prisma) documentada em
  docs/ARCHITECTURE.md
- packages/shared: catalogo de permissoes (fonte unica usada por seed e API)
- apps/api: NestJS 11 + Fastify
  - autenticacao: Argon2id, access JWT + refresh token opaco com rotacao,
    cookies HttpOnly/SameSite=Lax, change/forgot/reset password
  - rate limiting progressivo de login via Redis (bloqueio crescente por IP)
  - RBAC reforcado no backend (PermissionsGuard), protecao contra
    auto-elevacao de privilegio
  - auditoria (audit_logs) nas acoes sensiveis, com redacao de segredos
  - health checks reais (postgres+redis), swagger desabilitavel, logs
    estruturados JSON com request_id de correlacao, filtro global de
    excecoes sem vazar erro cru
- infrastructure/docker/api.Dockerfile: build multi-stage do monorepo pnpm
- docker-compose.yml: servico api na rede interna, sem porta publicada

Testado via containers reais: login, /me, refresh, change-password,
rate limit (7 tentativas -> 429), RBAC (nega/permite), bloqueio de
auto-elevacao (403), audit log populado, health checks, lint e testes
unitarios passando.
This commit is contained in:
2026-08-27 12:23:02 -03:00
parent eee6d7aece
commit a2898fa566
69 changed files with 10161 additions and 7 deletions

View File

@@ -0,0 +1,173 @@
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Post,
Req,
Res,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { Public } from '../common/decorators/public.decorator';
import { CurrentUser } from '../common/decorators/current-user.decorator';
import type { AuthenticatedUser } from '../common/guards/auth.guard';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { ForgotPasswordDto } from './dto/forgot-password.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
const ACCESS_COOKIE = 'access_token';
const REFRESH_COOKIE = 'refresh_token';
@Controller('auth')
export class AuthController {
private readonly cookieSecure: boolean;
constructor(
private readonly authService: AuthService,
private readonly config: ConfigService,
) {
this.cookieSecure = this.config.get('COOKIE_SECURE', 'false') === 'true';
}
private setAuthCookies(
reply: FastifyReply,
tokens: {
accessToken: string;
accessTokenTtlMs: number;
refreshToken: string;
refreshTokenTtlMs: number;
},
) {
const domain = this.config.get<string>('COOKIE_DOMAIN') || undefined;
reply.setCookie(ACCESS_COOKIE, tokens.accessToken, {
httpOnly: true,
secure: this.cookieSecure,
sameSite: 'lax',
path: '/',
domain,
maxAge: Math.floor(tokens.accessTokenTtlMs / 1000),
});
// Cookie de refresh restrito a /auth: reduz superfície de exposição do
// token de maior duração a rotas que não precisam dele.
reply.setCookie(REFRESH_COOKIE, tokens.refreshToken, {
httpOnly: true,
secure: this.cookieSecure,
sameSite: 'lax',
path: '/auth',
domain,
maxAge: Math.floor(tokens.refreshTokenTtlMs / 1000),
});
}
private clearAuthCookies(reply: FastifyReply) {
const domain = this.config.get<string>('COOKIE_DOMAIN') || undefined;
reply.clearCookie(ACCESS_COOKIE, { path: '/', domain });
reply.clearCookie(REFRESH_COOKIE, { path: '/auth', domain });
}
@Public()
@Post('login')
@HttpCode(HttpStatus.OK)
async login(
@Body() dto: LoginDto,
@Req() request: FastifyRequest,
@Res({ passthrough: true }) reply: FastifyReply,
) {
const result = await this.authService.login(dto.email, dto.password, {
ip: request.ip,
userAgent: request.headers['user-agent'],
});
this.setAuthCookies(reply, result);
return { mustChangePassword: result.mustChangePassword };
}
@Public()
@Post('refresh')
@HttpCode(HttpStatus.OK)
async refresh(
@Req() request: FastifyRequest,
@Res({ passthrough: true }) reply: FastifyReply,
) {
const refreshToken = request.cookies?.[REFRESH_COOKIE];
if (!refreshToken)
throw new UnauthorizedException('Refresh token ausente.');
const tokens = await this.authService.refresh(refreshToken, {
ip: request.ip,
userAgent: request.headers['user-agent'],
});
this.setAuthCookies(reply, tokens);
return { ok: true };
}
@Post('logout')
@HttpCode(HttpStatus.OK)
async logout(
@CurrentUser() user: AuthenticatedUser,
@Req() request: FastifyRequest,
@Res({ passthrough: true }) reply: FastifyReply,
) {
const refreshToken = request.cookies?.[REFRESH_COOKIE];
await this.authService.logout(refreshToken, user?.id, {
ip: request.ip,
userAgent: request.headers['user-agent'],
});
this.clearAuthCookies(reply);
return { ok: true };
}
@Post('change-password')
@HttpCode(HttpStatus.OK)
async changePassword(
@CurrentUser() user: AuthenticatedUser,
@Body() dto: ChangePasswordDto,
@Req() request: FastifyRequest,
) {
await this.authService.changePassword(
user.id,
dto.currentPassword,
dto.newPassword,
{
ip: request.ip,
userAgent: request.headers['user-agent'],
},
);
return { ok: true };
}
@Public()
@Post('forgot-password')
@HttpCode(HttpStatus.OK)
async forgotPassword(@Body() dto: ForgotPasswordDto) {
await this.authService.forgotPassword(dto.email);
// Resposta genérica sempre — nunca revela se o e-mail existe.
return {
message: 'Se o e-mail existir, um link de recuperação foi enviado.',
};
}
@Public()
@Post('reset-password')
@HttpCode(HttpStatus.OK)
async resetPassword(
@Body() dto: ResetPasswordDto,
@Req() request: FastifyRequest,
) {
await this.authService.resetPassword(dto.token, dto.newPassword, {
ip: request.ip,
userAgent: request.headers['user-agent'],
});
return { ok: true };
}
@Get('me')
me(@CurrentUser() user: AuthenticatedUser) {
return user;
}
}

View File

@@ -0,0 +1,26 @@
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { LoginThrottleService } from './login-throttle.service';
import { MailerService } from './mailer.service';
@Module({
imports: [
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: config.getOrThrow<string>('JWT_ACCESS_SECRET'),
signOptions: { expiresIn: config.get<string>('JWT_ACCESS_TTL', '15m') },
}),
}),
],
controllers: [AuthController],
providers: [AuthService, LoginThrottleService, MailerService],
// Exporta o JwtModule para que o AuthGuard global (registrado em
// AppModule via APP_GUARD) consiga injetar JwtService.
exports: [AuthService, JwtModule],
})
export class AuthModule {}

View File

@@ -0,0 +1,298 @@
import { createHash, randomBytes } from 'node:crypto';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import * as argon2 from 'argon2';
import ms from 'ms';
import { PrismaService } from '../prisma/prisma.service';
import { AuditService } from '../audit/audit.service';
import { LoginThrottleService } from './login-throttle.service';
import { MailerService } from './mailer.service';
export interface RequestContext {
ip: string;
userAgent?: string;
}
export interface TokenPair {
accessToken: string;
accessTokenTtlMs: number;
refreshToken: string;
refreshTokenTtlMs: number;
}
const GENERIC_LOGIN_ERROR = 'Credenciais inválidas.';
function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
@Injectable()
export class AuthService {
private readonly accessTtl: string;
private readonly refreshTtl: string;
constructor(
private readonly prisma: PrismaService,
private readonly jwtService: JwtService,
private readonly config: ConfigService,
private readonly audit: AuditService,
private readonly loginThrottle: LoginThrottleService,
private readonly mailer: MailerService,
) {
this.accessTtl = this.config.get('JWT_ACCESS_TTL', '15m');
this.refreshTtl = this.config.get('JWT_REFRESH_TTL', '7d');
}
async getUserPermissions(userId: string): Promise<string[]> {
const roles = await this.prisma.userRole.findMany({
where: { userId },
include: {
role: { include: { permissions: { include: { permission: true } } } },
},
});
const permissions = new Set<string>();
for (const userRole of roles) {
for (const rolePermission of userRole.role.permissions) {
permissions.add(rolePermission.permission.key);
}
}
return [...permissions];
}
async login(
email: string,
password: string,
ctx: RequestContext,
): Promise<TokenPair & { mustChangePassword: boolean }> {
await this.loginThrottle.assertNotBlocked(ctx.ip);
const user = await this.prisma.user.findUnique({ where: { email } });
const passwordValid = user
? await argon2.verify(user.passwordHash, password).catch(() => false)
: false;
if (!user || !user.isActive || !passwordValid) {
await this.loginThrottle.recordFailure(ctx.ip);
await this.audit.log({
userId: user?.id ?? null,
action: 'login_failed',
entityType: 'user',
entityId: user?.id,
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
});
throw new UnauthorizedException(GENERIC_LOGIN_ERROR);
}
await this.loginThrottle.recordSuccess(ctx.ip);
await this.prisma.user.update({
where: { id: user.id },
data: { lastLoginAt: new Date() },
});
await this.audit.log({
userId: user.id,
action: 'login',
entityType: 'user',
entityId: user.id,
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
});
const permissions = await this.getUserPermissions(user.id);
const tokens = await this.issueTokenPair(
user.id,
user.email,
permissions,
ctx,
);
return { ...tokens, mustChangePassword: user.mustChangePassword };
}
private async issueTokenPair(
userId: string,
email: string,
permissions: string[],
ctx: RequestContext,
): Promise<TokenPair> {
const accessToken = await this.jwtService.signAsync(
{ sub: userId, email, permissions },
{ expiresIn: this.accessTtl },
);
const refreshTokenPlain = randomBytes(48).toString('base64url');
const refreshTokenTtlMs = ms(this.refreshTtl);
await this.prisma.session.create({
data: {
userId,
refreshTokenHash: hashToken(refreshTokenPlain),
userAgent: ctx.userAgent,
ipAddress: ctx.ip,
expiresAt: new Date(Date.now() + refreshTokenTtlMs),
},
});
return {
accessToken,
accessTokenTtlMs: ms(this.accessTtl),
refreshToken: refreshTokenPlain,
refreshTokenTtlMs,
};
}
// Rotação de refresh token: cada uso invalida o token anterior e emite um
// novo par (agente.md seção 9: "rotação de refresh token").
async refresh(
refreshTokenPlain: string,
ctx: RequestContext,
): Promise<TokenPair> {
const tokenHash = hashToken(refreshTokenPlain);
const session = await this.prisma.session.findFirst({
where: { refreshTokenHash: tokenHash },
include: { user: true },
});
if (!session || session.revokedAt || session.expiresAt < new Date()) {
throw new UnauthorizedException('Sessão inválida ou expirada.');
}
await this.prisma.session.update({
where: { id: session.id },
data: { revokedAt: new Date() },
});
if (!session.user.isActive) {
throw new UnauthorizedException('Usuário inativo.');
}
const permissions = await this.getUserPermissions(session.userId);
return this.issueTokenPair(
session.userId,
session.user.email,
permissions,
ctx,
);
}
async logout(
refreshTokenPlain: string | undefined,
userId: string | undefined,
ctx: RequestContext,
): Promise<void> {
if (refreshTokenPlain) {
const tokenHash = hashToken(refreshTokenPlain);
await this.prisma.session.updateMany({
where: { refreshTokenHash: tokenHash, revokedAt: null },
data: { revokedAt: new Date() },
});
}
await this.audit.log({
userId,
action: 'logout',
entityType: 'user',
entityId: userId,
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
});
}
async changePassword(
userId: string,
currentPassword: string,
newPassword: string,
ctx: RequestContext,
): Promise<void> {
const user = await this.prisma.user.findUniqueOrThrow({
where: { id: userId },
});
const valid = await argon2
.verify(user.passwordHash, currentPassword)
.catch(() => false);
if (!valid) throw new UnauthorizedException('Senha atual incorreta.');
const passwordHash = await argon2.hash(newPassword, {
type: argon2.argon2id,
});
await this.prisma.user.update({
where: { id: userId },
data: { passwordHash, mustChangePassword: false },
});
// Revoga todas as sessões existentes ao trocar senha (boa prática de
// segurança: um refresh token vazado antes da troca deixa de funcionar).
await this.prisma.session.updateMany({
where: { userId, revokedAt: null },
data: { revokedAt: new Date() },
});
await this.audit.log({
userId,
action: 'password_changed',
entityType: 'user',
entityId: userId,
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
});
}
// Resposta sempre genérica independente de o e-mail existir, para não
// permitir enumeração de usuários (agente.md seção 9).
async forgotPassword(email: string): Promise<void> {
const user = await this.prisma.user.findUnique({ where: { email } });
if (!user) return;
const tokenPlain = randomBytes(32).toString('base64url');
const expiresAt = new Date(Date.now() + ms('1h'));
await this.prisma.passwordResetToken.create({
data: { userId: user.id, tokenHash: hashToken(tokenPlain), expiresAt },
});
this.mailer.sendPasswordReset(user.email, tokenPlain);
}
async resetPassword(
tokenPlain: string,
newPassword: string,
ctx: RequestContext,
): Promise<void> {
const tokenHash = hashToken(tokenPlain);
const resetToken = await this.prisma.passwordResetToken.findUnique({
where: { tokenHash },
});
if (!resetToken || resetToken.usedAt || resetToken.expiresAt < new Date()) {
throw new UnauthorizedException(
'Token de recuperação inválido ou expirado.',
);
}
const passwordHash = await argon2.hash(newPassword, {
type: argon2.argon2id,
});
await this.prisma.$transaction([
this.prisma.user.update({
where: { id: resetToken.userId },
data: { passwordHash, mustChangePassword: false },
}),
this.prisma.passwordResetToken.update({
where: { id: resetToken.id },
data: { usedAt: new Date() },
}),
this.prisma.session.updateMany({
where: { userId: resetToken.userId, revokedAt: null },
data: { revokedAt: new Date() },
}),
]);
await this.audit.log({
userId: resetToken.userId,
action: 'password_reset',
entityType: 'user',
entityId: resetToken.userId,
ipAddress: ctx.ip,
userAgent: ctx.userAgent,
});
}
}

View File

@@ -0,0 +1,10 @@
import { IsString, MinLength } from 'class-validator';
export class ChangePasswordDto {
@IsString()
currentPassword!: string;
@IsString()
@MinLength(12, { message: 'A nova senha deve ter pelo menos 12 caracteres' })
newPassword!: string;
}

View File

@@ -0,0 +1,6 @@
import { IsEmail } from 'class-validator';
export class ForgotPasswordDto {
@IsEmail()
email!: string;
}

View File

@@ -0,0 +1,10 @@
import { IsEmail, IsString, MinLength } from 'class-validator';
export class LoginDto {
@IsEmail()
email!: string;
@IsString()
@MinLength(1)
password!: string;
}

View File

@@ -0,0 +1,10 @@
import { IsString, MinLength } from 'class-validator';
export class ResetPasswordDto {
@IsString()
token!: string;
@IsString()
@MinLength(12, { message: 'A nova senha deve ter pelo menos 12 caracteres' })
newPassword!: string;
}

View File

@@ -0,0 +1,76 @@
import { Inject, Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type Redis from 'ioredis';
import { REDIS_CLIENT } from '../redis/redis.module';
// Proteção contra força bruta no login (agente.md seção 10): N tentativas
// por janela por IP, com bloqueio progressivo (1min, 2min, 4min, ... até um
// teto de 1h) baseado em quantas vezes aquele IP já estourou o limite nas
// últimas 24h. Coordenado via Redis para funcionar com múltiplas réplicas
// da API no futuro.
@Injectable()
export class LoginThrottleService {
private readonly maxAttempts: number;
private readonly windowSeconds: number;
private readonly maxBlockSeconds = 3600;
private readonly violationsTtlSeconds = 86400;
constructor(
@Inject(REDIS_CLIENT) private readonly redis: Redis,
config: ConfigService,
) {
this.maxAttempts = Number(config.get('RATE_LIMIT_LOGIN_MAX', '5'));
this.windowSeconds = Number(
config.get('RATE_LIMIT_LOGIN_WINDOW_SECONDS', '60'),
);
}
private blockKey(ip: string) {
return `auth:block:${ip}`;
}
private attemptsKey(ip: string) {
return `auth:attempts:${ip}`;
}
private violationsKey(ip: string) {
return `auth:violations:${ip}`;
}
async assertNotBlocked(ip: string): Promise<void> {
const ttl = await this.redis.ttl(this.blockKey(ip));
if (ttl > 0) {
throw new HttpException(
{
message: `Muitas tentativas de login. Tente novamente em ${ttl} segundos.`,
},
HttpStatus.TOO_MANY_REQUESTS,
);
}
}
async recordFailure(ip: string): Promise<void> {
const attempts = await this.redis.incr(this.attemptsKey(ip));
if (attempts === 1) {
await this.redis.expire(this.attemptsKey(ip), this.windowSeconds);
}
if (attempts > this.maxAttempts) {
const violations = await this.redis.incr(this.violationsKey(ip));
if (violations === 1) {
await this.redis.expire(
this.violationsKey(ip),
this.violationsTtlSeconds,
);
}
const blockSeconds = Math.min(
60 * 2 ** (violations - 1),
this.maxBlockSeconds,
);
await this.redis.set(this.blockKey(ip), '1', 'EX', blockSeconds);
await this.redis.del(this.attemptsKey(ip));
}
}
async recordSuccess(ip: string): Promise<void> {
await this.redis.del(this.attemptsKey(ip), this.blockKey(ip));
}
}

View File

@@ -0,0 +1,26 @@
import { Injectable, Logger } from '@nestjs/common';
// Stub: sem credenciais SMTP fornecidas (.env SMTP_*), não dá para enviar
// e-mail de verdade — isso exige informação externa (agente.md seção 1:
// "somente pare por algo realmente impossível de resolver sem informação
// externa"). Implementação real (nodemailer) é um único arquivo a trocar
// aqui assim que as credenciais existirem; a lógica de geração/validação
// de token de recuperação já está completa em AuthService.
@Injectable()
export class MailerService {
private readonly logger = new Logger(MailerService.name);
sendPasswordReset(email: string, token: string): void {
this.logger.warn(
`SMTP não configurado — link de recuperação para ${email} (apenas log, não enviado): ` +
`/reset-password?token=${token}`,
);
}
sendNewUserCredentials(email: string, temporaryPassword: string): void {
this.logger.warn(
`SMTP não configurado — credenciais iniciais para ${email} (apenas log, não enviado): ` +
`senha temporária ${temporaryPassword} (troca obrigatória no primeiro login)`,
);
}
}