Security Guide
This guide covers security best practices and features in the FastAPI boilerplate.
Table of Contents
- Security Features
- Authentication and Authorization
- Input Validation
- File Security
- Configuration Security
- Production Deployment
- Security Testing
Security Features
The boilerplate includes comprehensive security features:
Authentication and Authorization
- JWT-based authentication with timezone-aware tokens
- Password strength requirements (8+ chars, uppercase, lowercase, digit)
- Policy and Gate-based authorization
- Secure password hashing with bcrypt
Input Validation
- Pydantic schema validation for all requests
- File upload validation (type, size, content)
- Path traversal prevention
- Command injection prevention
Security Headers
| Header | Value/Description |
|---|---|
X-Content-Type-Options | nosniff |
X-Frame-Options | DENY |
X-XSS-Protection | 1; mode=block |
Content-Security-Policy | Restricts resources |
Strict-Transport-Security | Enabled in production (HSTS) |
Referrer-Policy | Controls referrer information |
Permissions-Policy | Controls browser features |
Rate Limiting
- Redis-based distributed rate limiting
- In-memory fallback for single-server deployments
- Configurable limits per endpoint
Error Handling
- Secure error messages (no information disclosure)
- Request ID tracking
- Proper logging without sensitive data
Authentication and Authorization
Password Requirements
Passwords must meet the following requirements: | Requirement | Value | | :--- | :--- | | Minimum Length | 8 characters | | Maximum Length | 128 characters | | Characters | At least one uppercase letter | | Characters | At least one lowercase letter | | Characters | At least one digit |
# Example: Creating a user with password validation
from app.schemas.user import UserCreate
user_data = UserCreate(
email="user@example.com",
password="SecurePass123" # Must meet requirements
)
JWT Tokens
JWT tokens are timezone-aware and include: - Expiration time - User ID (subject) - Secure signing with HS256
from app.core.security import create_access_token
# Create token
token = create_access_token(user_id, expires_delta=timedelta(hours=1))
Input Validation
Request Validation
Always use Pydantic schemas for request validation:
from pydantic import BaseModel, EmailStr, validator
class UserCreate(BaseModel):
email: EmailStr
password: str
@validator('password')
def validate_password(cls, v):
if len(v) < 8:
raise ValueError('Password too short')
return v
File Upload Validation
File uploads are automatically validated:
from app.api.v1.controllers.files import upload_file
# Automatic validation includes:
# - File type (extension and MIME type)
# - File size (max 10MB)
# - Filename sanitization
# - Path traversal prevention
File Security
Path Traversal Prevention
All file operations use path validation:
from app.core.file_security import validate_file_path
# Safe file path validation
safe_path = validate_file_path(user_path, base_directory)
File Upload Security
File uploads are secured with: - Type validation (extension and MIME type) - Size limits (10MB default) - Filename sanitization - Content validation (magic bytes)
# Allowed file types
ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.pdf', ...}
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
Configuration Security
Environment Variables
Critical: Never commit .env files to version control.
Required secrets for production:
Generate secure keys:
Production Configuration
APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com
# CORS - Never use wildcard in production
BACKEND_CORS_ORIGINS=["https://yourdomain.com","https://app.yourdomain.com"]
# Cache - Use JSON only (no pickle)
CACHE_SERIALIZER=json
Production Deployment
Pre-Deployment Checklist
-
Generate Secure Secrets
-
Update Environment Variables
- Set
APP_ENV=production - Set
APP_DEBUG=false - Configure secure
APP_KEYandJWT_SECRET - Set proper CORS origins
-
Use strong database passwords
-
Configure HTTPS
- Set up SSL/TLS certificates
- Configure reverse proxy (nginx/Apache)
-
Enable HSTS header
-
Set Up Redis
- Configure Redis password
- Set up firewall rules
-
Use for distributed rate limiting
-
Security Headers
- Verify all security headers are present
- Configure CSP for your application
-
Enable HSTS
-
Database Security
- Use strong passwords
- Enable SSL connections
-
Restrict network access
-
File Storage
- Set appropriate permissions
- Use secure storage (S3 with encryption)
- Validate all file operations
Deployment Security
# 1. Generate secrets
python -c "import secrets; print(secrets.token_urlsafe(32))"
# 2. Update .env
APP_ENV=production
APP_DEBUG=false
APP_KEY=<generated-key>
JWT_SECRET=<generated-key>
# 3. Check for vulnerabilities
pip install safety
safety check
# 4. Run security linter
pip install bandit
bandit -r app/
# 5. Test application
pytest
Security Testing
Dependency Scanning
# Check for known vulnerabilities
pip install safety
safety check
# Or use pip-audit
pip install pip-audit
pip-audit
Code Security Scanning
# Run Bandit security linter
pip install bandit
bandit -r app/
# Check for common issues
bandit -r app/ -f json -o security-report.json
Manual Security Testing
-
Test Path Traversal
-
Test File Upload
-
Test Authentication
-
Test Rate Limiting
-
Check Security Headers
Common Security Issues
1. Hardcoded Secrets
Problem: Secrets in code or default values Solution: Always use environment variables
2. SQL Injection
Problem: Raw SQL queries with user input Solution: Use SQLAlchemy ORM (already implemented)
3. XSS Attacks
Problem: Unescaped user input in responses Solution: FastAPI automatically escapes JSON responses
4. CSRF Attacks
Problem: No CSRF protection Solution: Consider implementing CSRF tokens for state-changing operations
5. Information Disclosure
Problem: Detailed error messages in production Solution: Use secure error handler (already implemented)
Security Best Practices
- Never trust user input - Always validate
- Use parameterized queries - SQLAlchemy does this
- Implement defense in depth - Multiple security layers
- Keep dependencies updated - Regular security updates
- Use HTTPS everywhere - Especially in production
- Implement proper logging - But don't log sensitive data
- Regular security audits - Review code regularly
- Use security headers - Protect against common attacks
- Monitor for vulnerabilities - Use automated tools
- Regular penetration testing - Test your security measures