# Bungate Security Guide > **Comprehensive security hardening guide for production deployments** This guide provides detailed information about Bungate's security features, threat model, and best practices for securing your API gateway in production environments. ## Related Documentation - **[Authentication Guide](./AUTHENTICATION.md)** - JWT, API keys, OAuth2 configuration - **[TLS Configuration Guide](./TLS_CONFIGURATION.md)** - Detailed HTTPS setup - **[Quick Start](./QUICK_START.md)** - Basic security setup - **[API Reference](./API_REFERENCE.md)** - Security configuration options - **[Troubleshooting](./TROUBLESHOOTING.md)** - Security-related issues ## Table of Contents - [Threat Model](#threat-model) - [Security Features Overview](#security-features-overview) - [TLS/HTTPS Configuration](#tlshttps-configuration) - [Input Validation & Sanitization](#input-validation--sanitization) - [Secure Error Handling](#secure-error-handling) - [Session Management](#session-management) - [Trusted Proxy Configuration](#trusted-proxy-configuration) - [Security Headers](#security-headers) - [Request Size Limits](#request-size-limits) - [JWT Key Rotation](#jwt-key-rotation) - [Common Security Scenarios](#common-security-scenarios) - [Security Checklist](#security-checklist) - [Compliance & Standards](#compliance--standards) ## Threat Model Bungate is designed to protect against the following attack vectors: ### Network Layer Threats - **Man-in-the-Middle (MITM) Attacks**: Prevented through TLS/HTTPS encryption - **Eavesdropping**: All traffic encrypted with strong cipher suites - **Protocol Downgrade Attacks**: Minimum TLS version enforcement ### Application Layer Threats - **Injection Attacks**: Path traversal, SQL injection, command injection - **Cross-Site Scripting (XSS)**: Security headers and CSP - **Cross-Site Request Forgery (CSRF)**: Token-based protection - **Information Disclosure**: Secure error handling and sanitization ### Resource Exhaustion Threats - **Denial of Service (DoS)**: Request size limits and rate limiting - **Slowloris Attacks**: Timeout management and connection limits - **Resource Amplification**: Payload size monitoring ### Authentication & Authorization Threats - **Session Hijacking**: Cryptographically secure session IDs - **Token Replay**: JWT expiration and validation - **Credential Stuffing**: Rate limiting and account lockout ### Infrastructure Threats - **IP Spoofing**: Trusted proxy validation - **Header Injection**: Header validation and sanitization - **Configuration Tampering**: Secure defaults and validation ## Security Features Overview Bungate provides defense-in-depth with multiple security layers. All security features are **automatically applied** when configured in the gateway's `security` configuration object. You don't need to manually add middleware to each route - the gateway handles this for you. ### Automatic Security Application When you configure security features at the gateway level, they are automatically applied to all routes: ```typescript const gateway = new BunGateway({ security: { // These features are automatically applied to ALL routes tls: { enabled: true /* ... */ }, sizeLimits: { maxBodySize: 10 * 1024 * 1024 }, inputValidation: { blockedPatterns: [/\.\./] }, securityHeaders: { enabled: true }, }, }) // This route automatically gets all security features gateway.addRoute({ pattern: '/api/*', target: 'http://backend:3000', }) ``` ### Security Middleware Order Security features are applied in the following order: 1. **Size Limits** - Validates request sizes before processing 2. **Input Validation** - Validates paths, headers, and query parameters 3. **Security Headers** - Applied to all responses 4. **Authentication** - JWT/API key validation (if configured) 5. **Rate Limiting** - Request throttling (if configured) 6. **Route-specific middleware** - Your custom middleware ### Defense-in-Depth Architecture Bungate provides defense-in-depth with multiple security layers: ``` ┌─────────────────────────────────────────────────────────────┐ │ Client Requests │ └──────────────────────┬──────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Layer 1: TLS Termination │ │ ✓ Certificate validation │ │ ✓ Cipher suite enforcement │ │ ✓ Protocol version validation │ └──────────────────────┬──────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Layer 2: Request Validation │ │ ✓ Size limit enforcement │ │ ✓ Input validation & sanitization │ │ ✓ Header validation │ └──────────────────────┬──────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Layer 3: Security Middleware │ │ ✓ Trusted proxy validation │ │ ✓ Security headers injection │ │ ✓ Authentication & authorization │ │ ✓ Rate limiting │ └──────────────────────┬──────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Layer 4: Application Processing │ │ ✓ Routing & load balancing │ │ ✓ Circuit breaking │ │ ✓ Backend proxying │ └──────────────────────┬──────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Layer 5: Response Processing │ │ ✓ Error sanitization │ │ ✓ Security header injection │ │ ✓ Payload size monitoring │ └──────────────────────┬──────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Backend Services │ └─────────────────────────────────────────────────────────────┘ ``` ## TLS/HTTPS Configuration ### Overview TLS (Transport Layer Security) encrypts all traffic between clients and the gateway, preventing eavesdropping and man-in-the-middle attacks. ### Basic Configuration ```typescript import { BunGateway } from 'bungate' const gateway = new BunGateway({ server: { port: 443, hostname: 'example.com' }, security: { tls: { enabled: true, cert: './cert.pem', key: './key.pem', minVersion: 'TLSv1.3', redirectHTTP: true, redirectPort: 80, // Prevent open redirects via Host header redirectAllowedHosts: ['example.com', '*.example.com'], }, }, }) await gateway.listen() ``` ### Production Configuration ```typescript const gateway = new BunGateway({ server: { port: 443, hostname: 'example.com' }, security: { tls: { enabled: true, cert: process.env.TLS_CERT_PATH, key: process.env.TLS_KEY_PATH, ca: process.env.TLS_CA_PATH, // For client certificate validation minVersion: 'TLSv1.3', cipherSuites: [ 'TLS_AES_256_GCM_SHA384', 'TLS_CHACHA20_POLY1305_SHA256', 'TLS_AES_128_GCM_SHA256', ], requestCert: false, // Enable for mTLS rejectUnauthorized: true, redirectHTTP: true, redirectPort: 80, redirectAllowedHosts: ['example.com', '*.example.com'], }, }, }) ``` ### Best Practices 1. **Use TLS 1.3**: Provides better security and performance 2. **Strong Cipher Suites**: Use AEAD ciphers with forward secrecy 3. **Valid Certificates**: Obtain from trusted CAs (Let's Encrypt, DigiCert) 4. **Certificate Rotation**: Automate renewal before expiration 5. **Secure Key Storage**: Protect private keys with proper permissions (chmod 600) 6. **HTTP Redirect**: Always redirect HTTP to HTTPS in production For detailed TLS configuration, see [TLS Configuration Guide](./TLS_CONFIGURATION.md). ## Input Validation & Sanitization ### Overview Input validation prevents injection attacks by validating and sanitizing all user-provided data before processing. ### Configuration Input validation is automatically applied when configured in the gateway security settings: ```typescript import { BunGateway } from 'bungate' const gateway = new BunGateway({ server: { port: 3000 }, security: { inputValidation: { maxPathLength: 2048, maxHeaderSize: 16384, maxHeaderCount: 100, allowedPathChars: /^[a-zA-Z0-9\/_\-\.~%]+$/, blockedPatterns: [ /\.\./, // Directory traversal /%00/, // Null byte injection /