Skip to main content

Security Best Practices

FSS includes enterprise-grade security features. This guide covers how to properly configure and maintain security in your deployment.

Overview

FSS implements security at multiple levels:

  • Transport Security - HTTPS/TLS encryption
  • Authentication - JWT with refresh tokens and MFA
  • Authorization - Role-based access control (RBAC)
  • Data Protection - Encryption at rest and in transit
  • Infrastructure - Container isolation and network security

Environment Variables

Required Security Variables

# JWT Configuration - CRITICAL FOR SECURITY
JWT_SECRET=your-256-bit-secret-key-here
JWT_EXPIRATION=15m
REFRESH_TOKEN_EXPIRATION=7d

# Encryption Keys
ENCRYPTION_KEY=your-32-byte-encryption-key
ENCRYPTION_IV=your-16-byte-iv

# Rate Limiting
THROTTLE_TTL=60
THROTTLE_LIMIT=100

Generate Secure Keys

# Generate JWT secret (at least 32 characters)
openssl rand -base64 32

# Generate encryption key (32 bytes for AES-256)
openssl rand -base64 32

# Generate encryption IV (16 bytes)
openssl rand -base64 16

HTTPS/TLS Configuration

Production SSL/TLS

For production deployments, always use HTTPS:

# nginx.conf
server {
listen 443 ssl http2;
server_name api.yourdomain.com;

ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;

# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
}

Security Headers

FSS includes security headers via middleware:

// security.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class SecurityMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
// Content Security Policy
res.setHeader('Content-Security-Policy',
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';"
);

// Prevent MIME type sniffing
res.setHeader('X-Content-Type-Options', 'nosniff');

// Clickjacking protection
res.setHeader('X-Frame-Options', 'SAMEORIGIN');

// XSS protection
res.setHeader('X-XSS-Protection', '1; mode=block');

// Referrer policy
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');

// Permissions policy
res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');

next();
}
}

Authentication Security

Password Requirements

Configure strong password policies:

// password.constants.ts
export const PASSWORD_REQUIREMENTS = {
minLength: 12,
requireUppercase: true,
requireLowercase: true,
requireNumber: true,
requireSpecial: true,
maxAge: 90, // days -强制更改密码
preventCommonPasswords: true,
preventReuse: 5, // Remember last 5 passwords
};

Account Lockout

// auth.constants.ts
export const ACCOUNT_LOCKOUT = {
maxAttempts: 5,
lockoutDuration: 15 * 60 * 1000, // 15 minutes
resetCounterAfter: 60 * 60 * 1000, // 1 hour
};

MFA Requirements

For sensitive operations, require MFA:

// Requires MFA for:
- Password changes
- Email changes
- Account deletion
- Sensitive data access
- Admin actions

Rate Limiting

FSS implements multiple layers of rate limiting:

Global Rate Limit

// throttler.config.ts
import { ThrottlerModule } from '@nestjs/throttler';

@Module({
imports: [
ThrottlerModule.forRoot([{
ttl: 60000, // 1 minute
limit: 100, // 100 requests per minute
}]),
],
})
export class AppModule {}

Endpoint-Specific Limits

// auth.controller.ts
@Controller('auth')
@Throttle({ default: { limit: 5, ttl: 900000 } }) // 5 attempts per 15 minutes
export class AuthController {
@Post('login')
@Throttle({ limit: 5, ttl: 900000 }) // Override for login
async login(@Body() loginDto: LoginDto) {
// Login logic
}
}

Input Validation

All inputs should be validated:

// login.dto.ts
import { IsEmail, IsString, MinLength, Matches } from 'class-validator';

export class LoginDto {
@IsEmail()
email: string;

@IsString()
@MinLength(8)
password: string;
}

SQL Injection Prevention

FSS uses Prisma ORM which automatically prevents SQL injection:

// ✅ SAFE - Using Prisma
const user = await prisma.user.findUnique({
where: { email: userInput.email },
});

// ❌ DANGEROUS - Never do this
await prisma.$queryRaw`SELECT * FROM users WHERE email = ${userInput.email}`;

CORS Configuration

Configure CORS properly:

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);

app.enableCors({
origin: process.env.FRONTEND_URL,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 86400, // 24 hours
});

await app.listen(3001);
}
bootstrap();

Database Security

Connection Pooling

// prisma.config.ts
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
datasources: {
db: {
url: process.env.DATABASE_URL,
},
},
log: ['query', 'info', 'warn', 'error'],
// Connection pool settings
__internalConfig: {
engine: {
adapter: undefined,
tracing: false,
},
},
});

// Set connection pool size
prisma.$connect();
// Prisma uses pg pool with default: min: 2, max: num_cpus * 2

Sensitive Data Handling

// Never log sensitive data
console.log({
email: user.email, // OK
password: user.password, // ❌ NEVER
creditCard: user.creditCard, // ❌ NEVER
});

// Use Prisma middleware to filter sensitive fields
prisma.$use((params, next) => {
if (params.model === 'User' && params.action === 'findMany') {
params.args.select = {
...params.args.select,
password: false,
refreshToken: false,
};
}
return next(params);
});

Audit Logging

FSS includes comprehensive audit logging:

// audit.service.ts
@Injectable()
export class AuditService {
async log(params: {
userId?: string;
action: string;
resource: string;
resourceId?: string;
details?: Record<string, any>;
ip?: string;
userAgent?: string;
}) {
return this.prisma.auditLog.create({
data: {
userId: params.userId,
action: params.action,
resource: params.resource,
resourceId: params.resourceId,
details: params.details,
ip: params.ip,
userAgent: params.userAgent,
timestamp: new Date(),
},
});
}
}

Security Checklist for Production

  • Use HTTPS with valid SSL/TLS certificates
  • Set strong JWT_SECRET (32+ random characters)
  • Enable rate limiting
  • Configure CORS properly
  • Set up MFA for admin accounts
  • Implement audit logging
  • Use environment variables for secrets
  • Rotate secrets regularly
  • Set up intrusion detection
  • Configure backup and disaster recovery
  • Regular security audits
  • Keep dependencies updated