Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion api/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ dependencies = [
"dockerflow",
"flask",
"flask_migrate",
"flask_talisman",
"mozilla-version~=5.0",
"python-decouple",
"sentry-sdk[flask]",
Expand Down
55 changes: 31 additions & 24 deletions api/src/backend_common/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,28 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import flask_talisman
import flask_talisman.talisman
from connexion.middleware import MiddlewarePosition
from starlette.datastructures import MutableHeaders

class CSPMiddleware:
def __init__(self, app, headers):
self.app = app
self.headers = headers

async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)

async def send_with_extra_headers(message):
if message["type"] == "http.response.start":
headers = MutableHeaders(scope=message)
for key, value in self.headers:
headers.append(key, value)

await send(message)

await self.app(scope, receive, send_with_extra_headers)


# TODO: we need to remove unsafe-inline
DEFAULT_CSP_POLICY = {
Expand All @@ -14,27 +34,14 @@
"img-src": "'self'",
"connect-src": "'self'",
}

DEFAULT_CONFIG = dict(
force_https=False,
force_https_permanent=False,
force_file_save=False,
frame_options=flask_talisman.talisman.SAMEORIGIN,
frame_options_allow_from=None,
strict_transport_security=True,
strict_transport_security_preload=False,
strict_transport_security_max_age=flask_talisman.talisman.ONE_YEAR_IN_SECS,
strict_transport_security_include_subdomains=True,
content_security_policy=DEFAULT_CSP_POLICY,
content_security_policy_report_uri=None,
content_security_policy_report_only=False,
session_cookie_secure=True,
session_cookie_http_only=True,
)

security = flask_talisman.Talisman()

CSP = "; ".join(f"{k}: {v}" for (k, v) in DEFAULT_CSP_POLICY.items())
DEFAULT_HEADERS = [
("x-frame-options", "SAMEORIGIN"),
("x-content-type-options", "nosniff"),
("strict-transport-security", f"max-age={365 * 24 * 60 * 60}; includeSubDomains"),
("content-security-policy", CSP),
("referrer-policy", "strict-origin-when-cross-origin"),
]

def init_app(app):
security.init_app(app.app, **DEFAULT_CONFIG)
return security
app.add_middleware(CSPMiddleware, MiddlewarePosition.BEFORE_EXCEPTION, headers=DEFAULT_HEADERS)
17 changes: 6 additions & 11 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.