diff --git a/posthog/test/test_utils_cors.py b/posthog/test/test_utils_cors.py new file mode 100644 index 00000000000000..ef4a27fa0886b9 --- /dev/null +++ b/posthog/test/test_utils_cors.py @@ -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") + 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}", + ) diff --git a/posthog/utils_cors.py b/posthog/utils_cors.py index 0c4f6cb52765ac..fe866a047001a5 100644 --- a/posthog/utils_cors.py +++ b/posthog/utils_cors.py @@ -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"