Skip to content

Commit

Permalink
Add Content-Security-Policy frame-ancestors header
Browse files Browse the repository at this point in the history
  • Loading branch information
aliu39 committed Sep 21, 2024
1 parent 8b20e90 commit 33d488a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/sentry/toolbar/views/iframe_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,20 @@

@region_silo_view
class IframeView(OrganizationView):
def __init__(self):
super().__init__()
self.active_project: Project | None = None

def respond(self, template: str, context: dict[str, Any] | None = None, status: int = 200):
response = super().respond(template, context=context, status=status)
response["X-Frame-Options"] = "ALLOWALL" # allows response to be embedded in an iframe.
allowed_origins = (
self.active_project.get_option("sentry:toolbar_allowed_origins")
if self.active_project
else []
)
if allowed_origins:
response["Content-Security-Policy"] = "frame-ancestors " + " ".join(allowed_origins)
return response

def handle_auth_required(self, request: HttpRequest, *args, **kwargs):
Expand All @@ -37,6 +48,7 @@ def convert_args(self, request: HttpRequest, organization_slug: str, project_id_
else None
)
kwargs["project"] = active_project
self.active_project = active_project
return args, kwargs

def get(
Expand Down
10 changes: 10 additions & 0 deletions tests/sentry/toolbar/views/test_iframe_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,13 @@ def test_calls_url_matches(self):
for (i, (args, _)) in enumerate(mock_url_matches.call_args_list):
assert args[0] == referrer
assert args[1] == allowed_origins[i]

def test_security_headers(self):
allowed_origins = ["sentry.io", "abc.com"]
self.project.update_option("sentry:toolbar_allowed_origins", allowed_origins)
res = self.client.get(self.url, **{REFERRER_HEADER: "https://sentry.io"})

assert res.headers.get("X-Frame-Options") == "ALLOWALL"
csp = res.headers.get("Content-Security-Policy")
frame_ancestors = csp[len("frame-ancestors ") :].split() if csp else []
assert set(frame_ancestors) == set(allowed_origins)

0 comments on commit 33d488a

Please sign in to comment.