-
Notifications
You must be signed in to change notification settings - Fork 20
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
feat: add custom middleware for x-frame-options to allow overrides #422
Draft
jesperhodge
wants to merge
7
commits into
master
Choose a base branch
from
feat--add-x-frame-options-custom-middleware
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
eb7cad0
feat: add custom middleware for x-frame-options to allow overrides
jesperhodge 389a7e9
fix: lint
jesperhodge 0f5bc7d
fix: lint
jesperhodge 77f4966
fix: lint
jesperhodge 5e3094f
fix: lint
jesperhodge db67f12
fix: lint
jesperhodge 0ce0e0f
fix: tests
jesperhodge File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
Security Utils | ||
############## | ||
|
||
Common security utilities. | ||
|
||
Deprecated - Clickjacking middleware | ||
************************************ | ||
|
||
Consider this deprecated as new projects should be using Content Security Policy headers instead. | ||
However, this won't be removed until no openedx project depends on it anymore, specifically, edx-platform. | ||
Please do not add this middleware to a project unless you have to use the ``X-Frame-Options`` header, | ||
and do not add it outside the openedx github organization, as it may be removed in the future. | ||
|
||
Clickjacking middleware | ||
*********************** | ||
|
||
The preferred way to prevent clickjacking is to use the Content Security Policy headers. | ||
In some legacy code where those headers are not used, it is required to instead use the older | ||
header ``X-Frame-Options`` set either to ``DENY`` or to ``SAMEORIGIN``. | ||
In any case, this middleware allows you both to set the ``X-Frame-Options`` header to any recognized value - | ||
``DENY``, ``SAMEORIGIN``, ``ALLOW`` per django setting - but defaults to ``DENY``. | ||
It also allows you to override the header for specific urls defined via regex. | ||
|
||
- Add the middleware ``'edx_django_utils.security.clickjacking.middleware.EdxXFrameOptionsMiddleware'`` near the end of your ``MIDDLEWARE`` list. | ||
- This will add an `X-Frame-Options` header to all responses. | ||
- Add ``X_FRAME_OPTIONS = value`` to your django settings file with "value" being ``DENY``, ``SAMEORIGIN``, or ``ALLOW``. | ||
- Optionally, add ``X_FRAME_OPTIONS_OVERRIDES = [[regex, value]]`` where ``[[regex, value]]`` is a list of | ||
pairs consisting of a regex that matches urls to override and a value that's one of ``DENY``, ``SAMEORIGIN``, and ``ALLOW``. |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
""" | ||
Middleware to add correct x-frame-options headers. | ||
|
||
The headers get set to the platform default which we assume is `DENY`. | ||
However, there's a number of paths that are set to `SAMEORIGIN` which | ||
we identify via regexes stored in a django setting in the application calling this. | ||
""" | ||
|
||
from django.conf import settings | ||
from django.http.request import HttpRequest | ||
from django.http.response import HttpResponse | ||
from django.middleware.clickjacking import XFrameOptionsMiddleware | ||
|
||
import re | ||
|
||
PERMISSIBLE_VALUES = ['DENY', 'SAMEORIGIN', 'ALLOW'] | ||
|
||
|
||
class InvalidHeaderValueError(ValueError): | ||
""" A custom error that is thrown when we try to set an invalid value for a header """ | ||
pass | ||
|
||
|
||
def _validate_header_value(value): | ||
if value not in PERMISSIBLE_VALUES: | ||
raise InvalidHeaderValueError( | ||
f'Invalid value "{value}" for header "X-Frame-Options"' | ||
) | ||
|
||
|
||
class EdxXFrameOptionsMiddleware(XFrameOptionsMiddleware): | ||
""" | ||
A class extending the django XFrameOptionsMiddleware with the ability to override | ||
the header for URLs specified in a `X_FRAME_OPTIONS_OVERRIDES` django setting. | ||
You can set this via `X_FRAME_OPTIONS_OVERRIDES = [[regex, value]]` in your django application | ||
where you specify a list of pairs of regex and value, where regex matches urls and value is | ||
one of `DENY`, `SAMEORIGIN`, `ALLOW`. The latter is not advisable unless you have a content security | ||
policy in place. | ||
""" | ||
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse: | ||
""" | ||
Process the response and set the x-frame-options header to the value specified | ||
""" | ||
response = super().process_response(request, response) | ||
headers = response.headers | ||
request_path = request.path | ||
frame_options = getattr(settings, 'X_FRAME_OPTIONS', 'DENY') | ||
_validate_header_value(frame_options) | ||
|
||
headers['X-Frame-Options'] = frame_options | ||
overrides = getattr(settings, 'X_FRAME_OPTIONS_OVERRIDES', []) | ||
for override in overrides: | ||
print('override', override) | ||
regex, value = override | ||
_validate_header_value(value) | ||
if re.search(regex, request_path): | ||
headers['X-Frame-Options'] = value | ||
response.headers = headers | ||
return response |
90 changes: 90 additions & 0 deletions
90
edx_django_utils/security/clickjacking/tests/test_middleware.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
""" | ||
Tests for Content-Security-Policy middleware. | ||
""" | ||
|
||
import ddt | ||
from edx_django_utils.security.clickjacking.middleware import EdxXFrameOptionsMiddleware | ||
|
||
from unittest import TestCase | ||
from unittest.mock import MagicMock, patch | ||
|
||
|
||
|
||
@ddt.ddt | ||
class TestEdxXFrameOptionsMiddleware(TestCase): | ||
"""Test the actual middleware.""" | ||
|
||
@patch('edx_django_utils.security.clickjacking.middleware._validate_header_value') | ||
@patch('edx_django_utils.security.clickjacking.middleware.settings') | ||
def test_x_frame_setting_must_apply_on_no_override(self, settings, validate_header): | ||
""" | ||
If the setting `X_FRAME_OPTIONS` is set but no overrides are specified, | ||
the `X-Frame-Options` header should be set to that setting. | ||
""" | ||
settings.X_FRAME_OPTIONS = 'SAMEORIGIN' | ||
validate_header.return_value = True | ||
|
||
request = MagicMock() | ||
response = MagicMock() | ||
response.headers = {} | ||
middleware = EdxXFrameOptionsMiddleware(get_response=lambda _: response) | ||
|
||
middleware.process_response(request, response) | ||
|
||
assert response.headers['X-Frame-Options'] == 'SAMEORIGIN' | ||
validate_header.assert_called_once_with('SAMEORIGIN') | ||
|
||
@patch('edx_django_utils.security.clickjacking.middleware._validate_header_value') | ||
@patch('edx_django_utils.security.clickjacking.middleware.settings') | ||
def test_on_override_with_valid_regex_is_sameorigin(self, settings, validate_header): | ||
""" | ||
If the URL matches one of the overrides, the header should be set to | ||
the correct override setting as specified in the `X_FRAME_OPTIONS_OVERRIDES` list. | ||
""" | ||
settings.X_FRAME_OPTIONS = 'DENY' | ||
settings.X_FRAME_OPTIONS_OVERRIDES = [['.*/media/scorm/.*', 'SAMEORIGIN']] | ||
validate_header.return_value = True | ||
|
||
request = MagicMock() | ||
response = MagicMock() | ||
response.headers = {} | ||
request.path = 'http://localhost:18010/media/scorm/hello/world' | ||
middleware = EdxXFrameOptionsMiddleware(get_response=lambda _: response) | ||
|
||
middleware.process_response(request, response) | ||
|
||
assert response.headers['X-Frame-Options'] == 'SAMEORIGIN' | ||
|
||
@patch('edx_django_utils.security.clickjacking.middleware._validate_header_value') | ||
@patch('edx_django_utils.security.clickjacking.middleware.settings') | ||
def test_on_override_for_non_matching_urls_is_deny(self, settings, validate_header): | ||
""" | ||
If the URL does not match any of the overrides, the header should be set to | ||
the `X_FRAME_OPTIONS` setting. | ||
""" | ||
settings.X_FRAME_OPTIONS = 'DENY' | ||
settings.X_FRAME_OPTIONS_OVERRIDES = [['.*/media/scorm/.*', 'SAMEORIGIN']] | ||
validate_header.return_value = True | ||
|
||
request = MagicMock() | ||
response = MagicMock() | ||
response.headers = {} | ||
request.path = 'http://localhost:18010/notmedia/scorm/hello/world' | ||
middleware = EdxXFrameOptionsMiddleware(get_response=lambda _: response) | ||
|
||
middleware.process_response(request, response) | ||
|
||
assert response.headers['X-Frame-Options'] == 'DENY' | ||
|
||
def test_x_frame_defaults_to_deny(self): | ||
""" | ||
The default value of the `X-Frame-Options` header should be `DENY`. | ||
""" | ||
request = MagicMock() | ||
response = MagicMock() | ||
response.headers = {} | ||
middleware = EdxXFrameOptionsMiddleware(get_response=lambda _: response) | ||
|
||
middleware.process_response(request, response) | ||
|
||
assert response.headers['X-Frame-Options'] == 'DENY' |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not clear. You are adding a deprecated middleware with a new feature? So this regex feature will not be needed in some future time?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Okay let me try to explain my intention. Probably there's a better way to do this.
From a security perspective, we prefer CSP over X-Frame-Options for new or flexible projects. That means that it's okay to use X-Frame-Options but only if the project already has them and it's more work than it's worth to change them. That would be way outside the scope of my task for edx-platform - edx-platform still using the
X-Frame-Options
header.The new middleware is important because we currently can't support SCORM xblock without setting the header to
SAMEORIGIN
, but I did not want to blindly do this for all of edx-platform. So I wrote this code to allow us to change the header for specific url patterns.I wanted to mark this as deprecated because on the one hand we need it and it's not worth the effort to change the whole security headers thing on edx-platform right now, but I want to warn people off from using this middleware together with the outdated header in new projects.
Do you have a better suggestion for this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I may have more thoughts, but a quick question is whether this is for edx-platform only, and if it should live there? That would reduce scope of introducing deprecated-from-the-start code.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm happy to move it to edx-platform.