NestJS course · Module 9: Deployment and Infrastructure

Security Best Practices - protection against barbarians

6 min read ·
In this lesson6

Guardian of the tributes! On the Empire's frontiers barbarians rarely storm the walls. They try keys: passwords stolen from other services, forged tokens, secrets someone left in a repository. Consul Caesar.js wants you to know the best methods of defending against such attacks.

Authentication & Authorization

Authentication checks who the legionary is, and authorization what he is allowed to do. A Passport strategy verifies the JWT token:

// JWT Strategy
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(config: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: config.getOrThrow<string>('JWT_SECRET'),
      algorithms: ['HS256'], // accept only the algorithm you sign with
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}

ExtractJwt.fromAuthHeaderAsBearerToken() reads the token from the Authorization header, and ignoreExpiration: false rejects expired ones. getOrThrow() stops the application from starting when the secret is missing, instead of running with an empty key. The algorithms list blocks algorithm substitution: in the test a token signed with HS512 got a 401. Whatever validate() returns lands in req.user.

We store passwords only as hashes:

// Password hashing
import { BadRequestException, Injectable } from '@nestjs/common';
import * as bcrypt from 'bcrypt';

@Injectable()
export class CryptoService {
  async hashPassword(password: string): Promise<string> {
    // bcrypt reads only 72 bytes - reject a longer password instead of silently truncating it
    if (Buffer.byteLength(password, 'utf8') > 72) {
      throw new BadRequestException('Password exceeds 72 bytes');
    }
    const saltRounds = 12;
    return bcrypt.hash(password, saltRounds);
  }

  async validatePassword(password: string, hash: string): Promise<boolean> {
    return bcrypt.compare(password, hash);
  }
}

bcrypt with a cost of 12 is deliberately slow, which makes cracking hashes harder. It reads only the first 72 bytes of UTF-8, though: in a test a password that differed only after the 72nd byte passed verification, hence the length guard. For a new project I recommend Argon2id (the argon2 package), which OWASP puts first and which has no such limit.

Input Validation

Input data is validated by a DTO with class-validator decorators:

// DTO with validation
import { IsEmail, IsString, Length, Matches, MaxLength, MinLength } from 'class-validator';

export class CreateLegionaryDto {
  @IsString()
  @Length(2, 50)
  @Matches(/^[\p{L}\s'-]+$/u, { message: 'Name can only contain letters' })
  name: string;

  @IsEmail()
  email: string;

  @IsString()
  @MinLength(15) // NIST SP 800-63B-4: length instead of composition rules
  @MaxLength(64)
  password: string;
}

The \p{L} class with the u flag accepts letters of every alphabet, so "Łukasz Żółtowski" passes - the first version with [a-zA-Z] rejected Polish names. The password rules come from NIST SP 800-63B-4: at least 15 characters when the password is the only login factor (8 with MFA), allowing at least 64 characters, and checking against a list of leaked passwords. With bcrypt, remember that 64 Polish characters may exceed 72 bytes.

The previous version of the lesson enforced password composition:

// The old password composition rule - discouraged today
@Matches(/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/, {
  message: 'Password must contain uppercase, lowercase, number and special character'
})

NIST now explicitly forbids such rules. People answer them with a predictable "Password123!", while a long, ordinary sentence is harder to crack.

Secrets - keys to the treasury

Secrets management in production rests on three principles: secrets are encrypted, rotated regularly, and access to them is audited. Keep them in a secrets manager, e.g. HashiCorp Vault or a cloud service; environment variables are only a way of delivering them to the process. A secret never goes into code, the repository or a Docker image.

A missing secret is best detected at startup. ConfigModule.forRoot() accepts a validationSchema, e.g. from the Joi library, and checks the variables before the application comes up:

// app.module.ts - validating the configuration at startup
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import Joi from 'joi';

@Module({
  imports: [
    ConfigModule.forRoot({
      validationSchema: Joi.object({
        NODE_ENV: Joi.string()
          .valid('development', 'production', 'test')
          .default('development'),
        PORT: Joi.number().port().default(3000),
        DATABASE_URL: Joi.string().uri().required(),
        JWT_SECRET: Joi.string().min(32).required(),
      }),
    }),
  ],
})
export class AppModule {}

A missing DATABASE_URL and a too short JWT_SECRET end the startup with a Config validation error listing all problems at once, and PORT already arrives as a number. In an ES module project use import Joi from 'joi': the import * as Joi form compiles, but in the test it failed with Joi.string is not a function. The NestJS documentation now recommends the Zod library for new projects, and supports Joi from version 18.

Walls around the application

You harden containers as in the Docker lesson: a user other than root, a minimal base image and vulnerability scanning. Also pin image versions instead of the :latest tag, which changes without warning and makes it impossible to reproduce exactly what runs in production. Rate limiting from the TLS lesson protects against too many requests from a single client.

The guard's chronicle

Without logs you will not detect a break-in. Production logs are written by Winston through the nest-winston module:

// app.module.ts - the guard's chronicle in production
import { Module } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';

@Module({
  imports: [
    WinstonModule.forRoot({
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.json(),
      ),
      transports: [
        new DailyRotateFile({
          filename: 'logs/app-%DATE%.log',
          datePattern: 'YYYY-MM-DD',
          maxFiles: '30d',
        }),
        new DailyRotateFile({
          filename: 'logs/error-%DATE%.log',
          datePattern: 'YYYY-MM-DD',
          level: 'error',
          maxFiles: '90d',
        }),
      ],
    }),
  ],
})
export class AppModule {}

WinstonModule.forRoot() accepts the same options as winston.createLogger(). The logs are JSON, the files rotate daily, and errors have a separate file with longer retention. To make NestJS log through it as well, call app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER)) in main.ts. Never log passwords or tokens.

When the barbarians get over the wall

Handling a production incident has fixed stages:

  1. detection and alerting of the problem,
  2. triage and initial response,
  3. mitigation and resolution of the problem,
  4. post-mortem analysis and improvements.

A post-mortem looks for causes in the process, not for culprits, because only then do people tell the truth. I recommend you write these stages down in a runbook before the first incident happens. In the next lesson we will prepare backups for the day the wall does fall.

Remember: the best guard does not trust the gate, he checks every key and records every attempt.

Code for this lesson: src/security.ts
// Security Best Practices - Protection Against Barbarians
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

// 1. JWT Authentication
// @Injectable()
// class JwtAuthGuard extends AuthGuard('jwt') {
//   canActivate(context: ExecutionContext) {
//     return super.canActivate(context);
//   }
// }

// 2. Role-based Authorization
@Injectable()
class RolesGuard implements CanActivate {
  constructor(private requiredRoles: string[]) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user = request.user;

    if (!user || !user.roles) return false;

    return this.requiredRoles.some(role =>
      user.roles.includes(role)
    );
  }
}

// 3. Input Validation (class-validator)
// class CreateLegionDto {
//   @IsString()
//   @MinLength(3)
//   @MaxLength(50)
//   name: string;
//
//   @IsNumber()
//   @Min(100)
//   @Max(10000)
//   soldiers: number;
//
//   @IsEnum(Province)
//   province: Province;
// }

// 4. Security Headers (Helmet)
const securityHeaders = {
  'X-Content-Type-Options': 'nosniff',
  'X-Frame-Options': 'DENY',
  'X-XSS-Protection': '1; mode=block',
  'Strict-Transport-Security': 'max-age=31536000',
  'Content-Security-Policy': "default-src 'self'",
};

// 5. Password Hashing (bcrypt)
// import * as bcrypt from 'bcrypt';
// const hash = await bcrypt.hash(password, 10);
// const isMatch = await bcrypt.compare(password, hash);

// 6. Rate Limiting - DDoS protection
// @UseGuards(ThrottlerGuard)
// @Throttle(100, 60)  // 100 requests / 60 seconds

// 7. CORS Configuration
const corsConfig = {
  origin: ['https://roman-empire.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
};

// 8. Environment Secrets
// NEVER hardcode:
// - Database passwords
// - API keys
// - JWT Secret
// - Encryption keys
// Use: .env, Docker secrets, Vault, AWS Secrets Manager

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Secrets management in production should:

  2. 2. Security best practices for Docker containers:

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Implement WinstonModule with transports: file, error-file, and JSON format

  • Click in order

    Arrange the production incident handling stages:

  1. QuestionSecrets Management in Infrastructure
  2. QuestionProduction Container Hardening
  3. Coding taskPractice: Production Log Aggregation with Winston
  4. QuestionInfrastructure Hardening Checklist
  5. Click in orderProduction Incident Handling Stages

Useful articles