Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add security response headers #3124

Merged
merged 9 commits into from
Aug 30, 2019
31 changes: 31 additions & 0 deletions fec/fec/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings


class AddSecureHeaders(MiddlewareMixin):
"""Add secure headers to each response"""

def process_response(self, request, response):

# Report violations to the API due to CSRF issue with Django route
REPORT_URI = "{0}/report-csp-violation/?api_key={1}".format(
settings.FEC_API_URL, settings.FEC_API_KEY_PUBLIC
)
content_security_policy = {
"default-src": "'self' *.fec.gov *.app.cloud.gov https://www.google-analytics.com",
"frame-src": "'self' https://www.google.com/recaptcha/",
"img-src": "'self' data: https://*.ssl.fastly.net https://www.google-analytics.com *.app.cloud.gov",
patphongs marked this conversation as resolved.
Show resolved Hide resolved
"script-src": "'self' 'unsafe-inline' 'unsafe-eval' https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/ https://www.google-analytics.com https://polyfill.io https://dap.digitalgov.gov",
"style-src": "'self' data: 'unsafe-inline'",
"object-src": "'none'",
"report-uri": REPORT_URI,
}
if settings.FEC_CMS_ENVIRONMENT == 'LOCAL':
content_security_policy["default-src"] += " localhost:* http://127.0.0.1:*"

response["Content-Security-Policy"] = "".join(
"{0} {1}; ".format(directive, value)
for directive, value in content_security_policy.items()
)
response["cache-control"] = "max-age=600"
return response
5 changes: 5 additions & 0 deletions fec/fec/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'fec.middleware.AddSecureHeaders', # custom response headers
'uaa_client.middleware.UaaRefreshMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
Expand All @@ -122,6 +123,10 @@
'audit_log.middleware.UserLoggingMiddleware',
)

CSRF_TRUSTED_ORIGINS = ["fec.gov", "app.cloud.gov"]
if FEC_CMS_ENVIRONMENT == 'LOCAL':
CSRF_TRUSTED_ORIGINS.extend(["127.0.0.1:5000"])

ROOT_URLCONF = 'fec.urls'

from data import constants
Expand Down