Skip to content

Commit

Permalink
security(api): Add http security headers to server-side calls (#727)
Browse files Browse the repository at this point in the history
  • Loading branch information
topher-lo authored Jan 10, 2025
1 parent 05bcd7f commit 4adae47
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions tracecat/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from tracecat.editor.router import router as editor_router
from tracecat.logger import logger
from tracecat.middleware import RequestLoggingMiddleware
from tracecat.middleware.security import SecurityHeadersMiddleware
from tracecat.organization.router import router as org_router
from tracecat.registry.actions.router import router as registry_actions_router
from tracecat.registry.common import reload_registry
Expand Down Expand Up @@ -233,6 +234,7 @@ def create_app(**kwargs) -> FastAPI:

# Middleware
app.add_middleware(RequestLoggingMiddleware)
app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=allow_origins,
Expand Down
40 changes: 40 additions & 0 deletions tracecat/middleware/security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import os

from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware


class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
if os.getenv("POSTHOG_KEY"):
csp_directives = [
"connect-src 'self' https://*.posthog.com",
"default-src 'self'",
"worker-src 'self' blob:",
"frame-ancestors 'none'",
"img-src 'self' data:",
"object-src 'none'",
"script-src 'self' 'unsafe-inline' https://*.posthog.com",
"style-src 'self' 'unsafe-inline'",
]
else:
csp_directives = [
"connect-src 'self'",
"default-src 'self'",
"worker-src 'self' blob:",
"frame-ancestors 'none'",
"img-src 'self' data:",
"object-src 'none'",
"script-src 'self' 'unsafe-inline'",
"style-src 'self' 'unsafe-inline'",
]
headers = {
"Strict-Transport-Security": "max-age=7776000; includeSubDomains",
"Content-Security-Policy": "; ".join(csp_directives),
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "document-domain=()",
}
response.headers.update(headers)
return response

0 comments on commit 4adae47

Please sign in to comment.