Security Overview
This document outlines the standard security philosophy and defense-in-depth layers for backend applications.
Security Philosophy
Implement defense-in-depth security with multiple layers of protection:
- Input Validation - Pydantic schemas with strict validation
- Input Sanitization - HTML sanitization only for fields intended to store/render HTML (rich text)
- Authentication - JWT tokens with OAuth2
- Authorization - Role-based access control (RBAC)
- Rate Limiting - IP and user-based rate limits
- Automated Monitoring - Security scanners running periodically
- API Protection - HTTP Basic Auth on documentation endpoints
Key Security Features
1. XSS Prevention
XSS prevention is primarily about preventing unsafe rendering of untrusted input. Our baseline:
- Validate all user-controlled strings (length + format).
- Sanitize only rich-text/HTML fields (allowlist).
- Never render normal text via HTML sinks (
innerHTML/dangerouslySetInnerHTML/|safe).
Implementation:
sanitize_html()function inutils/security.py- Max length enforcement on every field
- Preserves safe HTML while removing scripts
See XSS Prevention for details.
2. Authentication & Authorization
JWT Tokens:
- OAuth2 with JWT tokens
- Token expiration and refresh
- Secure token storage
Role-Based Access:
- Roles: e.g.,
admin,owner,member - Resource-level isolation (e.g., per-tenant or per-company)
- System-wide admin roles
See Authentication for details.
3. Rate Limiting
Intelligent rate limiting with automatic detection:
- IP-based for public endpoints
- User-based for authenticated endpoints
- Per-endpoint limits
- Environment-aware (disabled in local/test)
See Rate Limiting for details.
4. Automated Security Monitoring
Background workers scan database periodically:
- XSS pattern detection
- Anomaly detection (large payloads, rapid growth)
- Auto-sanitization of infected records
- Alerts/Reports
5. Reporting
Security reporting standards are defined in reporting.md (cadence, recipients, contents, templates) with the HTML example at Security Report Example.
6. API Documentation Protection
Interactive API documentation protected with HTTP Basic Auth:
/docs- Swagger UI/redoc- ReDoc/openapi.json- Schema
Credentials via environment variables (e.g., DOCS_USERNAME, DOCS_PASSWORD).
7. Data handling & secrets
Baseline rules for .env usage, production environment variables, and PII/logging safety:
See Data Handling & Secrets.
8. Security automation
Baseline security tooling (Dependabot, pip-audit, bandit, gitleaks) and policy: See Security Automation.
Protected Attack Vectors
✅ Cross-Site Scripting (XSS) - Rich text sanitized + safe rendering practices
✅ SQL Injection - SQLAlchemy ORM with parameterized queries
✅ Injection via IDs - ID fields allowlist-validated (reject invalid)
✅ Password Attacks - Bcrypt hashing + min/max length (passwords never mutated)
✅ Memory Exhaustion - Max length on all fields
✅ Database Overflow - Field length limits
✅ Unauthorized Access - OAuth2 + role checks
✅ Rate Limit Abuse - Comprehensive rate limiting
✅ API Documentation Exposure - HTTP Basic Auth
Security Best Practices
Input Validation
Every input schema includes:
from pydantic import BaseModel, Field
class EntityCreate(BaseModel):
name: str = Field(..., max_length=100)
description: str = Field(..., max_length=500)
If a field intentionally accepts HTML (rich text), sanitize that specific field (see the XSS Prevention page).
Authentication
All protected endpoints use dependency injection:
from database.dependencies import get_current_user, require_admin_role
@router.post("/admin-endpoint")
async def admin_endpoint(
token: dict = Depends(get_current_user),
_: None = Depends(require_admin_role)
):
# Endpoint implementation
Rate Limiting
Applied to all endpoints:
from slowapi import Limiter
from utils.rate_limiter import get_rate_limit_key
limiter = Limiter(key_func=get_rate_limit_key)
@router.post("/endpoint")
@limiter.limit("100/minute")
async def endpoint(token: dict = Depends(get_current_user)):
# Auto-detects: IP-based for public, user-based for authenticated
Security Layers
Layer 1: Input Validation (Pydantic)
- Type checking
- Format validation
- Range validation
- Required field enforcement
Layer 2: Input Sanitization
- HTML sanitization (allowlist) for rich-text fields only
Layer 3: Authentication
- JWT token verification
- Token expiration checks
- Signature validation
Layer 4: Authorization
- Role verification
- Resource access checks
- Ownership validation
Layer 5: Rate Limiting
- Request throttling
- Abuse prevention
- DDoS mitigation
Layer 6: Monitoring
- Automated scanning
- Anomaly detection
- Alert generation