Skip to content

Commit

Permalink
Fix CORS requests when Origin is invalid or null
Browse files Browse the repository at this point in the history
In some situations (such as calling posthog from within an iframe)
the Origin header can be "null" or otherwise invalid

In these situations we can't echo back the requested origin so we need
to send * instead
  • Loading branch information
frankh committed Feb 14, 2024
1 parent 856a12c commit 59bb8dc
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
29 changes: 29 additions & 0 deletions posthog/test/test_utils_cors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from collections import namedtuple
from django.test import TestCase

from posthog.utils_cors import cors_response


class TestCorsResponse(TestCase):
def test_origin(self) -> None:
valid_origin_test_cases = [
("https://my-amazing.site", "https://my-amazing.site"),
("https://my-amazing.site/", "https://my-amazing.site"),
("https://my-amazing.site/my/path", "https://my-amazing.site"),
("http://my-amazing.site/my/path", "http://my-amazing.site"),
("https://us.posthog.com/decide", "https://us.posthog.com"),
("my-amazing.site", "*"),
("my-amazing.site/path", "*"),
("null", "*"),
("", "*"),
]

FakeRequest = namedtuple("Request", "META")

Check failure on line 21 in posthog/test/test_utils_cors.py

View workflow job for this annotation

GitHub Actions / Python code quality checks

First argument to namedtuple() should be "FakeRequest", not "Request"
for origin, expected in valid_origin_test_cases:
with self.subTest():
request = FakeRequest(META={"HTTP_ORIGIN": origin})
self.assertEqual(
expected,
cors_response(request, {})["Access-Control-Allow-Origin"],
msg=f"with origin='{origin}', actual did not equal {expected}",
)
5 changes: 4 additions & 1 deletion posthog/utils_cors.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ def cors_response(request, response):
if not request.META.get("HTTP_ORIGIN"):
return response
url = urlparse(request.META["HTTP_ORIGIN"])
response["Access-Control-Allow-Origin"] = f"{url.scheme}://{url.netloc}"
if url.netloc == "":
response["Access-Control-Allow-Origin"] = "*"
else:
response["Access-Control-Allow-Origin"] = f"{url.scheme}://{url.netloc}"
response["Access-Control-Allow-Credentials"] = "true"
response["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"

Expand Down

0 comments on commit 59bb8dc

Please sign in to comment.