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 """

View File

@@ -1,4 +1,5 @@
from sqlalchemy import Column, String, JSON, Boolean
from sqlalchemy import Column, String, Boolean
from sqlalchemy.dialects.postgresql import JSONB
from .base import Base, TimestampMixin, UUIDMixin
@@ -6,14 +7,14 @@ from .base import Base, TimestampMixin, UUIDMixin
class User(Base, UUIDMixin, TimestampMixin):
__tablename__ = 'users'
email = Column(String, unique=True, nullable=False, index=True)
password_hash = Column(String, nullable=False)
first_name = Column(String, nullable=False, default="user")
last_name = Column(String, nullable=True)
phone_number = Column(String)
is_active = Column(Boolean, default=True, nullable=False)
is_superuser = Column(Boolean, default=False, nullable=False)
preferences = Column(JSON)
email = Column(String(255), unique=True, nullable=False, index=True)
password_hash = Column(String(255), nullable=False)
first_name = Column(String(100), nullable=False, default="user")
last_name = Column(String(100), nullable=True)
phone_number = Column(String(20))
is_active = Column(Boolean, default=True, nullable=False, index=True)
is_superuser = Column(Boolean, default=False, nullable=False, index=True)
preferences = Column(JSONB)
def __repr__(self):
return f"<User {self.email}>"