Skip to content

Commit

Permalink
fix: CORS requests when Origin is invalid or null (#20343)
Browse files Browse the repository at this point in the history
* Fix CORS requests when Origin is invalid or null

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

* Fix mypi issue

* Fix test
  • Loading branch information
frankh authored Feb 15, 2024
1 parent 04b5a9e commit 856d495
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", "*"),
("", None),
]

FakeRequest = namedtuple("FakeRequest", "META")
for origin, expected in valid_origin_test_cases:
with self.subTest():
request = FakeRequest(META={"HTTP_ORIGIN": origin})
self.assertEqual(
expected,
cors_response(request, {}).get("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 856d495

Please sign in to comment.