-
Notifications
You must be signed in to change notification settings - Fork 85
ENG-2192: Security Headers #7134
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
Open
tvandort
wants to merge
13
commits into
main
Choose a base branch
from
ENG-2192-security-headers
base: main
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.
+208
−1
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
5ae8d54
Barebones header applier.
tvandort 6088101
Header changes.
tvandort f2fa355
Import sorting.
tvandort 1ebad12
Python 3.9 doesn't have typealias.
tvandort 3a749b2
Unit testing.
tvandort e347ec3
Sort imports.
tvandort bbeb867
Fix exact match check.
tvandort f5f9986
Tests.
tvandort 3b7acfd
Exclude header and API paths from CSP.
tvandort 26820f8
Update imports.
tvandort c87903c
More testing.
tvandort 8bd6093
Remove errant line.
tvandort 88d4a3b
Parametrize test.
tvandort 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 hidden or 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
This file contains hidden or 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,103 @@ | ||
| import re | ||
| from dataclasses import dataclass | ||
|
|
||
| from fastapi import Request, Response | ||
| from starlette.middleware.base import BaseHTTPMiddleware | ||
|
|
||
| from fides.config import CONFIG | ||
|
|
||
| apply_recommended_headers = CONFIG.security.headers_mode == "recommended" | ||
|
|
||
|
|
||
| def is_exact_match(matcher: re.Pattern[str], path_name: str) -> bool: | ||
| matched_content = re.match(matcher, path_name) | ||
| if matched_content is None: | ||
| return False | ||
| return len(matched_content.group(0)) == len(path_name) | ||
|
|
||
|
|
||
| HeaderDefinition = tuple[str, str] | ||
|
|
||
|
|
||
| @dataclass | ||
| class HeaderRule: | ||
| matcher: re.Pattern[str] | ||
| headers: list[HeaderDefinition] | ||
|
|
||
|
|
||
| recommended_csp_header_value = re.sub( | ||
| r"\s{2,}", | ||
| " ", | ||
| """" | ||
| default-src 'self'; | ||
| script-src 'self' 'unsafe-inline'; | ||
| style-src 'self' 'unsafe-inline'; | ||
| connect-src 'self'; | ||
| img-src 'self' blob: data:; | ||
| font-src 'self'; | ||
| object-src 'none'; | ||
| base-uri 'self'; | ||
| form-action 'self'; | ||
| frame-ancestors 'self'; | ||
| upgrade-insecure-requests; | ||
| """, | ||
| ) | ||
|
|
||
| recommended_headers: list[HeaderRule] = [ | ||
| HeaderRule( | ||
| matcher=re.compile(r"/.*"), | ||
| headers=[ | ||
| ("X-Content-Type-Options", "nosniff"), | ||
| ("Strict-Transport-Security", "max-age=31536000"), | ||
| ], | ||
| ), | ||
| HeaderRule( | ||
| matcher=re.compile(r"^/((?!api|health).*)"), | ||
| headers=[ | ||
| ( | ||
| "Content-Security-Policy", | ||
| recommended_csp_header_value, | ||
| ), | ||
| ("X-Frame-Options", "SAMEORIGIN"), | ||
| ], | ||
| ), | ||
| ] | ||
|
|
||
|
|
||
| def get_applicable_header_rules( | ||
| path: str, header_rules: list[HeaderRule] | ||
| ) -> list[HeaderDefinition]: | ||
| header_names: set[str] = set() | ||
| header_definitions: list[HeaderDefinition] = [] | ||
|
|
||
| for rule in header_rules: | ||
| if is_exact_match(rule.matcher, path): | ||
| for header in rule.headers: | ||
| [header_name, _] = header | ||
| if header_name not in header_names: | ||
| header_names.add(header_name) | ||
| header_definitions.append(header) | ||
|
|
||
| return header_definitions | ||
|
|
||
|
|
||
| def apply_headers_to_response( | ||
| headers: list[HeaderRule], request: Request, response: Response | ||
| ) -> None: | ||
| applicable_headers = get_applicable_header_rules(request.url.path, headers) | ||
| for [header_name, header_value] in applicable_headers: | ||
| response.headers.append(header_name, header_value) | ||
|
|
||
|
|
||
| class SecurityHeadersMiddleware(BaseHTTPMiddleware): | ||
| """ | ||
| Controls what security headers are included in Fides API responses | ||
| """ | ||
|
|
||
| async def dispatch(self, request: Request, call_next): # type: ignore | ||
| response = await call_next(request) | ||
|
|
||
| if apply_recommended_headers: | ||
| apply_headers_to_response(recommended_headers, request, response) | ||
|
|
||
| return response | ||
This file contains hidden or 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
This file contains hidden or 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,98 @@ | ||
| import re | ||
| from unittest import mock | ||
|
|
||
| import pytest | ||
| from fastapi import Request, Response | ||
|
|
||
| from fides.api.util.security_headers import ( | ||
| HeaderRule, | ||
| apply_headers_to_response, | ||
| get_applicable_header_rules, | ||
| is_exact_match, | ||
| recommended_csp_header_value, | ||
| recommended_headers, | ||
| ) | ||
|
|
||
|
|
||
| class TestSecurityHeaders: | ||
| @pytest.mark.parametrize( | ||
| "pattern,path,expected", | ||
| [ | ||
| (r"\/example-path", "/example-path", True), | ||
| (r"\/example-path", "/example-path/with-more-content", False), | ||
| (r"\/example-path/?(.*)", "/example-path/with-more-content", True), | ||
| (r"\/example-path", "/anti-example-path", False), | ||
| (r"\/example-path", "/completely-disparate-no-match", False), | ||
| ], | ||
| ) | ||
| def test_is_exact_match(self, pattern, path, expected): | ||
| assert (is_exact_match(pattern, path)) is expected | ||
|
|
||
| def test_get_applicable_header_rules_returns_first_matching_rule_for_path(self): | ||
| expected_headers: tuple[str, str] = ("header-1", "value-1") | ||
| headers: list[HeaderRule] = [ | ||
| HeaderRule(re.compile(r"\/a"), [expected_headers]), | ||
| HeaderRule(re.compile(r"\/a"), [("header-1", "value-2")]), | ||
| ] | ||
|
|
||
| assert get_applicable_header_rules("/a", headers) == [expected_headers] | ||
|
|
||
| def test_get_applicable_header_rules_returns_disparate_headers(self): | ||
| header1 = "header-1" | ||
| header2 = "header-2" | ||
| headers1: tuple[str, str] = (header1, "value-1") | ||
| headers2: tuple[str, str] = (header2, "value-2") | ||
| headers: list[HeaderRule] = [ | ||
| HeaderRule(re.compile(r"\/a-path"), [headers1]), | ||
| HeaderRule(re.compile(r"\/a-path"), [headers2]), | ||
| ] | ||
|
|
||
| assert get_applicable_header_rules("/a-path", headers) == [headers1, headers2] | ||
|
|
||
| def test_apply_headers_to_response(self): | ||
| header = ("header-1", "value-1") | ||
| header_rules: list[HeaderRule] = [HeaderRule(re.compile(r".*"), [header])] | ||
|
|
||
| mock_request = mock.Mock(spec=Request) | ||
| mock_request.url.path = "/any-path" | ||
|
|
||
| response = Response() | ||
|
|
||
| apply_headers_to_response(header_rules, mock_request, response) | ||
|
|
||
| assert header in response.headers.items() | ||
|
|
||
| @pytest.mark.parametrize( | ||
| "path,expected", | ||
| [ | ||
| ( | ||
| "/api/foo", | ||
| [ | ||
| ("X-Content-Type-Options", "nosniff"), | ||
| ("Strict-Transport-Security", "max-age=31536000"), | ||
| ], | ||
| ), | ||
| ( | ||
| "/health", | ||
| [ | ||
| ("X-Content-Type-Options", "nosniff"), | ||
| ("Strict-Transport-Security", "max-age=31536000"), | ||
| ], | ||
| ), | ||
| ( | ||
| "/privacy-requests", | ||
| [ | ||
| ("X-Content-Type-Options", "nosniff"), | ||
| ("Strict-Transport-Security", "max-age=31536000"), | ||
| ( | ||
| "Content-Security-Policy", | ||
| recommended_csp_header_value, | ||
| ), | ||
| ("X-Frame-Options", "SAMEORIGIN"), | ||
| ], | ||
| ), | ||
| ], | ||
| ) | ||
| def test_recommended_headers_api_route(self, path, expected): | ||
| applicable_rules = get_applicable_header_rules(path, recommended_headers) | ||
| assert applicable_rules == expected |
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.
Uh oh!
There was an error while loading. Please reload this page.