:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(auth): redirect app.posthog.com deep links to logged-in region (#68224)
Yasen1dfc6facf225
diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 37577bf46d87..5d6cd6621e5e 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -566,7 +566,9 @@ class QueryTimeCountingMiddleware:if "api" in path and any(key in path for key in self.ALLOW_LIST_ROUTES):return Truetry:- return resolve(path).func.__name__ == "home"+ # Frontend page loads resolve to either the `home` view (unauthenticated routes)+ # or its `home_with_region_redirect` wrapper (the authenticated catch-all).+ return resolve(path).func.__name__ in ("home", "home_with_region_redirect")except Exception:return Falsediff --git a/posthog/test/test_urls.py b/posthog/test/test_urls.pyindex fbc249704445..9a20e5a8ba4a 100644--- a/posthog/test/test_urls.py+++ b/posthog/test/test_urls.py@@ -2,11 +2,14 @@ import uuidfrom posthog.test.base import APIBaseTest-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterizedfrom rest_framework import status+from posthog.models.instance_setting import override_instance_config+from posthog.urls import region_host_from_current_instance+class TestUrls(APIBaseTest):def test_logged_out_user_is_redirected_to_login(self):@@ -31,6 +34,37 @@ class TestUrls(APIBaseTest):fetch_redirect_response=False,)+ @parameterized.expand(+ [+ ("eu", "https://eu.posthog.com", "https://eu.posthog.com/organization/billing"),+ ("us", "https://us.posthog.com", "https://us.posthog.com/organization/billing"),+ ]+ )+ def test_app_host_deep_link_redirects_to_logged_in_region(self, _name, cookie_value, expected_location):+ # /organization/billing is behind login_required; the region redirect must fire first,+ # so a logged-out EU user reaches EU instead of the US login page.+ self.client.logout()+ self.client.cookies["ph_current_instance"] = cookie_value+ response = self.client.get("/organization/billing", HTTP_HOST="app.posthog.com", follow=False)+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ self.assertEqual(response["Location"], expected_location)++ def test_app_host_deep_link_without_region_cookie_falls_through_to_login(self):+ self.client.logout()+ self.client.cookies.pop("ph_current_instance", None)+ response = self.client.get("/organization/billing", HTTP_HOST="app.posthog.com", follow=False)+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ self.assertIn("/login", response["Location"])++ def test_app_host_deep_link_without_region_cookie_falls_back_to_us_when_redirect_app_to_us(self):+ # With no region cookie, REDIRECT_APP_TO_US routes app.posthog.com to US before the auth gate.+ self.client.logout()+ self.client.cookies.pop("ph_current_instance", None)+ with override_instance_config("REDIRECT_APP_TO_US", True):+ response = self.client.get("/organization/billing", HTTP_HOST="app.posthog.com", follow=False)+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ self.assertEqual(response["Location"], "https://us.posthog.com/organization/billing")+def test_integration_connect_redirect_authenticated(self):response = self.client.get(f"/integrations/connect/github/?project_id={self.team.id}&connect_from=slack", follow=False@@ -146,3 +180,21 @@ class TestUrls(APIBaseTest):# response,# "Do you want to give the PostHog Toolbar on <strong>https://domain.com/sdf</strong> access to your PostHog data?",# )+++class TestRegionHostFromCurrentInstance(SimpleTestCase):+ @parameterized.expand(+ [+ ("eu", "https://eu.posthog.com", "eu.posthog.com"),+ ("us", "https://us.posthog.com", "us.posthog.com"),+ ("with_port", "https://eu.posthog.com:8123", "eu.posthog.com"),+ ("wrapping_quotes", '"https://eu.posthog.com"', "eu.posthog.com"),+ ("app_is_not_a_region", "https://app.posthog.com", None),+ ("unknown_host_is_rejected", "https://evil.example.com", None),+ ("none", None, None),+ ("empty", "", None),+ ("not_a_url", "yo ho ho", None),+ ]+ )+ def test_region_host_from_current_instance(self, _name, cookie_value, expected):+ self.assertEqual(region_host_from_current_instance(cookie_value), expected)diff --git a/posthog/urls.py b/posthog/urls.pyindex adbe99c2a628..44911ad28fc2 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -161,15 +161,80 @@ def handler500(request):return HttpResponseServerError(template.render({"request": request}, request))+APP_POSTHOG_HOST = "app.posthog.com"+# Canonical per-region hosts a `ph_current_instance` cookie is allowed to resolve to.+# Restricting to this set keeps the cookie from being turned into an open redirect.+_REGION_HOSTS = {"us.posthog.com", "eu.posthog.com"}+++def region_host_from_current_instance(cookie_value: str | None) -> str | None:+ """Map a `ph_current_instance` cookie (an instance SITE_URL) to its canonical region+ host, or None when it isn't a recognized cloud region. Mirrors the frontend+ `cleanedCookieSubdomain` in RedirectToLoggedInInstance.tsx — the value is sometimes+ wrapped in quotes by the cookie serializer, so strip those before parsing."""+ if not cookie_value:+ return None+ hostname = urlparse(cookie_value.replace('"', "")).hostname+ return hostname if hostname in _REGION_HOSTS else None+++def app_region_redirect(request: HttpRequest) -> HttpResponseRedirect | None:+ """For `app.posthog.com` page loads, send the browser to the region the user is+ actually logged into (per the `ph_current_instance` cookie), preserving the path and+ query. Falls back to the `REDIRECT_APP_TO_US` instance setting when there's no region+ cookie. Returns None when no redirect applies so callers render normally.++ This has to run before the `login_required` auth gate: `app.posthog.com` is the US+ backend, so an EU user hitting a deep link like /organization/billing is otherwise+ bounced to /login on US first, and only the login page honors the cookie."""+ if request.method not in ("GET", "HEAD"):+ return None+ if request.get_host().split(":")[0] != APP_POSTHOG_HOST:+ return None++ target_host = region_host_from_current_instance(request.COOKIES.get("ph_current_instance"))+ if target_host is None and get_instance_setting("REDIRECT_APP_TO_US"):+ target_host = "us.posthog.com"+ if target_host is None:+ return None++ url = "https://{}{}".format(target_host, request.get_full_path())+ if url_has_allowed_host_and_scheme(url, target_host, True):+ return HttpResponseRedirect(url)+ return None++@ensure_csrf_cookie-def home(request, *args, **kwargs):- if request.get_host().split(":")[0] == "app.posthog.com" and get_instance_setting("REDIRECT_APP_TO_US"):- url = "https://us.posthog.com{}".format(request.get_full_path())- if url_has_allowed_host_and_scheme(url, "us.posthog.com", True):- return HttpResponseRedirect(url)+def _render_home(request, *args, **kwargs):return render_template("index.html", request)+# Wrapped once at import time (as `login_required(home)` used to be) so the catch-all+# authenticated route doesn't rebuild the wrapper on every request.+_login_required_render_home = login_required(_render_home)+++def home(request, *args, **kwargs):+ """Entrypoint for the unauthenticated frontend routes (login, signup, …). Runs the+ cross-region redirect before rendering so `app.posthog.com` visitors land on their+ logged-in region (see `app_region_redirect`)."""+ region_redirect = app_region_redirect(request)+ if region_redirect is not None:+ return region_redirect+ return _render_home(request, *args, **kwargs)+++def home_with_region_redirect(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:+ """Catch-all entrypoint for authenticated frontend routes. The cross-region redirect+ runs before `login_required` so `app.posthog.com` deep links reach the right region+ without a detour through the login page (see `app_region_redirect`). It wraps+ `_render_home` rather than `home` so the redirect check runs exactly once per request."""+ region_redirect = app_region_redirect(request)+ if region_redirect is not None:+ return region_redirect+ return _login_required_render_home(request, *args, **kwargs)++_CONNECT_REDIRECT_ALLOWED_KINDS = {"github", "slack", "linear"}# Surfaces allowed to start a connect flow and be returned to afterwards (see# posthog/api/github_callback/types.py APP_CONNECT_FROM_VALUES, plus Slack).@@ -568,4 +633,4 @@ frontend_unauthenticated_routes = [for route in frontend_unauthenticated_routes:urlpatterns.append(re_path(route, home))-urlpatterns.append(re_path(r"^.*", login_required(home)))+urlpatterns.append(re_path(r"^.*", home_with_region_redirect))