Skip to content

: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.

fix(toolbar): use ? separator for SPA hash route OAuth callback (#57811)

Matt Brooker125ab1ea0b8b
diff --git a/frontend/src/toolbar/toolbarConfigLogic.test.ts b/frontend/src/toolbar/toolbarConfigLogic.test.ts
index 68c904061a9d..1dbfc61b7270 100644
--- a/frontend/src/toolbar/toolbarConfigLogic.test.ts
+++ b/frontend/src/toolbar/toolbarConfigLogic.test.ts
@@ -927,6 +927,16 @@ describe('toolbar toolbarConfigLogic', () => {
'/#/dashboard&tab=1',
],
['handles percent-encoded delimiters', '#__posthog_toolbar=code%3Aabc%2Cclient_id%3Axyz', '/'],
+ [
+ 'restores ? when toolbar param was the first hash query on a SPA route',
+ '#/login?__posthog_toolbar=code:abc,client_id:xyz&foo=bar',
+ '/#/login?foo=bar',
+ ],
+ [
+ 'preserves trailing hash query when toolbar param was last',
+ '#/login?foo=bar&__posthog_toolbar=code:abc,client_id:xyz',
+ '/#/login?foo=bar',
+ ],
])('%s', (_label, hash, expectedUrl) => {
jest.useFakeTimers()
window.history.pushState({}, '', `/${hash}`)
diff --git a/frontend/src/toolbar/toolbarConfigLogic.ts b/frontend/src/toolbar/toolbarConfigLogic.ts
index 9f78dc9fda34..2a1cb6e95f6f 100644
--- a/frontend/src/toolbar/toolbarConfigLogic.ts
+++ b/frontend/src/toolbar/toolbarConfigLogic.ts
@@ -260,9 +260,9 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([
// posthog-js reads these at load time but never cleans them from the URL.
// Including them would cause a re-initialization loop after OAuth callback.
const hash = window.location.hash
- .replace(/[#&]__posthog=[^&]*/g, '')
- .replace(/[#&]__posthog_toolbar=[^&]*/g, '')
- .replace(/^&/, '#')
+ .replace(/[#?&]__posthog=[^&]*/g, '')
+ .replace(/[#?&]__posthog_toolbar=[^&]*/g, '')
+ .replace(/^[?&]/, '#')
.replace(/^#$/, '')
const redirect = encodeURIComponent(
window.location.origin + window.location.pathname + window.location.search + hash
diff --git a/frontend/src/toolbar/utils.ts b/frontend/src/toolbar/utils.ts
index 32385ff210ee..cce89f7c1a98 100644
--- a/frontend/src/toolbar/utils.ts
+++ b/frontend/src/toolbar/utils.ts
@@ -70,12 +70,26 @@ export function cleanToolbarAuthHash(): void {
return
}
- const cleanHash = hash
- .replace(/__posthog_toolbar=[^&]*/g, '')
+ // When the toolbar param was the first hash-query on a SPA route
+ // (e.g. `#/login?__posthog_toolbar=X&foo=bar`), removing it leaves
+ // `#/login&foo=bar` where the `&` should be `?`. Detect that case so we
+ // can restore the `?` after stripping. Only fires when the original hash
+ // contained `?__posthog_toolbar=` literally — fragments that join the
+ // toolbar param with `&` (e.g. `#/dashboard&tab=1&__posthog_toolbar=X`)
+ // are left untouched because that `&` was the customer's separator.
+ const toolbarWasFirstHashQuery = hash.includes('?__posthog_toolbar=')
+
+ let cleanHash = hash
+ .replace(/[?&]?__posthog_toolbar=[^&]*/g, '')
.replace(/&&+/g, '&')
- .replace(/&$/, '')
+ .replace(/[?&]$/, '')
.replace(/^#&/, '#')
.replace(/^#$/, '')
+
+ if (toolbarWasFirstHashQuery) {
+ cleanHash = cleanHash.replace(/(^#\/[^?]*)&/, '$1?')
+ }
+
history.replaceState(null, '', location.pathname + location.search + (cleanHash || ''))
}
diff --git a/posthog/api/oauth/toolbar_service.py b/posthog/api/oauth/toolbar_service.py
index 26351d990339..16f1c74929ea 100644
--- a/posthog/api/oauth/toolbar_service.py
+++ b/posthog/api/oauth/toolbar_service.py
@@ -129,8 +129,10 @@ def normalize_and_validate_app_url(team: Team, app_url: str) -> str:
# re-initialization loop, and leftover __posthog_toolbar params cause
# duplicate params on re-authentication.
if parsed.fragment and "__posthog" in parsed.fragment:
- clean_fragment = re.sub(r"&?__posthog_toolbar=[^&]*", "", parsed.fragment)
- clean_fragment = re.sub(r"&?__posthog=[^&]*", "", clean_fragment).strip("&")
+ # `?` separator covers SPA hash routes (#/login?__posthog_toolbar=...);
+ # `&` covers traditional fragment params (#section1&__posthog_toolbar=...).
+ clean_fragment = re.sub(r"[?&]?__posthog_toolbar=[^&]*", "", parsed.fragment)
+ clean_fragment = re.sub(r"[?&]?__posthog=[^&]*", "", clean_fragment).strip("?&")
return urlunparse(parsed._replace(fragment=clean_fragment))
return app_url
diff --git a/posthog/api/test/test_toolbar_hash_routing_repro.py b/posthog/api/test/test_toolbar_hash_routing_repro.py
new file mode 100644
index 000000000000..c3fa53bd43b3
--- /dev/null
+++ b/posthog/api/test/test_toolbar_hash_routing_repro.py
@@ -0,0 +1,59 @@
+"""
+Repro: hash-routed SPAs (e.g. /#/login) get a 404 after toolbar OAuth because
+the backend redirects to {base}#{original_fragment}&{toolbar_param}, and the
+SPA router sees /login&__posthog_toolbar=... as one path segment.
+
+Run: pytest posthog/api/test/test_toolbar_hash_routing_repro.py -v
+"""
+
+from urllib.parse import urlparse
+
+from posthog.test.base import APIBaseTest
+
+from django.conf import settings
+from django.test.utils import override_settings
+
+from parameterized import parameterized
+
+from posthog.api.oauth.test_dcr import generate_rsa_key
+from posthog.api.test.test_toolbar_oauth_primitives import ToolbarOAuthAuthorizeMixin
+
+
+@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
+class TestToolbarHashRoutingRepro(ToolbarOAuthAuthorizeMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.team.app_urls = ["https://app.example.com"]
+ self.team.save()
+
+ @parameterized.expand(
+ [
+ (
+ "hash_route_uses_question_mark_separator",
+ "https://app.example.com/#/login",
+ "/login?__posthog_toolbar=",
+ ),
+ (
+ "plain_fragment_still_uses_ampersand",
+ "https://app.example.com/page#section1",
+ "section1&__posthog_toolbar=",
+ ),
+ (
+ "hash_route_with_existing_query_uses_ampersand",
+ "https://app.example.com/#/login?foo=bar",
+ "/login?foo=bar&__posthog_toolbar=",
+ ),
+ ]
+ )
+ def test_hash_routing_separator(self, _name, redirect_url, expected_fragment_prefix):
+ state = self._authorize_and_get_state(redirect_url=redirect_url)
+ response = self.client.get(f"/toolbar_oauth/callback?code=AUTH_CODE_X&state={state}")
+
+ assert response.status_code == 302
+ parsed = urlparse(response["Location"])
+ assert parsed.fragment.startswith(expected_fragment_prefix), (
+ f"expected fragment to start with {expected_fragment_prefix!r}, got {parsed.fragment!r}"
+ )
+ assert parsed.fragment.count("?") == expected_fragment_prefix.count("?"), (
+ f"fragment must have exactly {expected_fragment_prefix.count('?')} `?`, got {parsed.fragment!r}"
+ )
diff --git a/posthog/api/test/test_toolbar_oauth_primitives.py b/posthog/api/test/test_toolbar_oauth_primitives.py
index c2f323855ab2..8ab3fd8ff7d6 100644
--- a/posthog/api/test/test_toolbar_oauth_primitives.py
+++ b/posthog/api/test/test_toolbar_oauth_primitives.py
@@ -1,4 +1,5 @@
import json
+from typing import Any
from urllib.parse import parse_qs, urlparse
from posthog.test.base import APIBaseTest
@@ -303,24 +304,29 @@ class TestTokenEndpointStatusRemapping(APIBaseTest):
assert cm.exception.status_code == expected_status
-@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
-class TestToolbarOAuthCallbackExchange(APIBaseTest):
- def setUp(self):
- super().setUp()
- self.team.app_urls = ["https://example.com"]
- self.team.save()
+class ToolbarOAuthAuthorizeMixin:
+ # Mixin assumes the concrete TestCase subclass provides a Django test `client`.
+ client: Any
def _authorize_and_get_state(self, redirect_url: str = "https://example.com/page") -> str:
response = self.client.get(
"/toolbar_oauth/authorize/",
{"redirect": redirect_url, "code_challenge": "test_challenge_value"},
)
- assert response.status_code == 302
+ assert response.status_code == 302, response.content
auth_url = response["Location"]
qs = parse_qs(urlparse(auth_url).query)
return qs["state"][0]
+
+@override_settings(OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": generate_rsa_key()})
+class TestToolbarOAuthCallbackExchange(ToolbarOAuthAuthorizeMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.team.app_urls = ["https://example.com"]
+ self.team.save()
+
def test_callback_redirects_with_code_in_redirect_flow(self):
state = self._authorize_and_get_state()
response = self.client.get(f"/toolbar_oauth/callback?code=auth_code_123&state={state}")
@@ -507,12 +513,16 @@ class TestToolbarOAuthCallbackExchange(APIBaseTest):
assert "__posthog_toolbar=code:auth_code_123" in location
def test_callback_preserves_spa_hash_route(self):
+ # SPA hash routes (fragment starts with `/`) must use `?` as the
+ # separator so hash routers split route from auth params instead of
+ # treating the whole substring as one path and 404ing.
state = self._authorize_and_get_state(redirect_url="https://example.com/#/dashboard/settings")
response = self.client.get(f"/toolbar_oauth/callback?code=abc&state={state}")
assert response.status_code == 302
location = response["Location"]
- assert "/dashboard/settings&__posthog_toolbar=code:abc" in location
+ assert "/dashboard/settings?__posthog_toolbar=code:abc" in location
+ assert "/dashboard/settings&__posthog_toolbar" not in location
def test_callback_preserves_fragment_params_after_stripping_toolbar(self):
state = self._authorize_and_get_state(
diff --git a/posthog/api/user.py b/posthog/api/user.py
index ee42858fdc13..1da2e03436e2 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -1404,7 +1404,16 @@ def toolbar_oauth_callback(request):
quoted_client_id = urllib.parse.quote(oauth_app.client_id, safe="")
toolbar_param = f"__posthog_toolbar=code:{quoted_code},client_id:{quoted_client_id}"
if original_fragment:
- fragment = f"{original_fragment}&{toolbar_param}"
+ # SPA hash routes (e.g. `#/login`) treat the entire post-`#` substring
+ # as the path, so `&` would make the auth params part of the route and
+ # 404. `?` is the standard hash-query separator that React Router,
+ # Vue Router, etc. split on. If the fragment already has a `?` (e.g.
+ # `#/login?foo=bar`), keep using `&` to extend the existing hash query.
+ if original_fragment.startswith("/") and "?" not in original_fragment:
+ separator = "?"
+ else:
+ separator = "&"
+ fragment = f"{original_fragment}{separator}{toolbar_param}"
else:
fragment = toolbar_param
return redirect(f"{base_url}#{fragment}")