Add security headers middleware and tests; improve user model schema

- Added security headers middleware to enforce best practices (e.g., XSS and clickjacking prevention, CSP, HSTS in production).
- Updated `User` model schema: refined field constraints and switched `preferences` to `JSONB` for PostgreSQL compatibility.
- Introduced tests to validate security headers across endpoints and error responses.
- Ensured headers like `X-Frame-Options`, `X-Content-Type-Options`, and `Permissions-Policy` are correctly configured.
This commit is contained in:
Felipe Cardoso
2025-10-30 08:30:21 +01:00
parent 5bed14b6b0
commit d83959963b
3 changed files with 135 additions and 9 deletions

View File

@@ -43,6 +43,37 @@ app.add_middleware(
)
# Add security headers middleware
@app.middleware("http")
async def add_security_headers(request: Request, call_next):
"""Add security headers to all responses"""
response = await call_next(request)
# Prevent clickjacking
response.headers["X-Frame-Options"] = "DENY"
# Prevent MIME type sniffing
response.headers["X-Content-Type-Options"] = "nosniff"
# Enable XSS protection
response.headers["X-XSS-Protection"] = "1; mode=block"
# Enforce HTTPS in production
if settings.ENVIRONMENT == "production":
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
# Content Security Policy
response.headers["Content-Security-Policy"] = "default-src 'self'; frame-ancestors 'none'"
# Permissions Policy (formerly Feature Policy)
response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()"
# Referrer Policy
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
return response
@app.get("/", response_class=HTMLResponse)
async def root():
return """