: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(mcp-store): merge query params when building OAuth authorize URLs (#105007)
Alessandro Pogliaghi11ff2aedafbb
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.pyindex 5957bd059333..0f931bcabf7f 100644--- a/products/mcp_store/backend/presentation/views.py+++ b/products/mcp_store/backend/presentation/views.py@@ -1064,7 +1064,14 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetif not _is_https(auth_endpoint):raise OAuthAuthorizeURLError("Authorization endpoint must use HTTPS")- return f"{auth_endpoint}?{urlencode(query_params)}"+ # Some authorization servers (e.g. Railway) advertise authorization_endpoint+ # with an existing query string. Appending another "?" would bury params like+ # client_id inside the prior value, so merge instead.+ parts = urlsplit(auth_endpoint)+ existing = parse_qsl(parts.query, keep_blank_values=True)+ merged = [(key, value) for key, value in existing if key not in query_params]+ merged.extend(query_params.items())+ return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(merged), parts.fragment))@validated_request(MCPServerInstallationUpdateSerializer,diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex efff869700e7..c4c6eb18c40f 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -1,6 +1,6 @@import hashlibfrom datetime import timedelta-from urllib.parse import parse_qs, urlparse+from urllib.parse import parse_qs, urlparse, urlsplitfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTestfrom unittest.mock import patch@@ -46,7 +46,10 @@ from products.mcp_store.backend.presentation.gateway_views import (GatewayPoliciesUpsertSerializer,ServiceAccountAccessUpdateSerializer,)-from products.mcp_store.backend.presentation.views import _is_valid_posthog_code_callback_url+from products.mcp_store.backend.presentation.views import (+ MCPServerInstallationViewSet,+ _is_valid_posthog_code_callback_url,+)ALLOWED_VERDICT = PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set())ALLOW_URL = patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)@@ -3879,6 +3882,61 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMassert second_callback.status_code == status.HTTP_400_BAD_REQUEST+class TestBuildAuthorizeUrlFromMetadata(SimpleTestCase):+ def test_merges_query_params_when_authorization_endpoint_already_has_query(self) -> None:+ """Railway (and similar AS) advertise authorization_endpoint with ?resource=...++ Appending another '?' buries client_id inside the resource value, and the+ AS responds with: missing required parameter 'client_id'.+ """+ view = MCPServerInstallationViewSet()+ authorize_url = view._build_authorize_url_from_metadata(+ metadata={+ # Shape from https://backboard.railway.com/.well-known/oauth-authorization-server+ "authorization_endpoint": (+ "https://backboard.railway.com/oauth/auth?resource=https%3A%2F%2Fbackboard.railway.com"+ ),+ "scopes_supported": ["openid", "offline_access", "workspace:member"],+ # From https://mcp.railway.com/.well-known/oauth-protected-resource+ "resource": "https://mcp.railway.com",+ },+ client_id="rlwy_oaci_test_client",+ redirect_uri="https://us.posthog.com/api/mcp_store/oauth_redirect/",+ state_token="test-state",+ code_challenge="test-challenge",+ )++ parts = urlsplit(authorize_url)+ assert parts.scheme == "https"+ assert parts.netloc == "backboard.railway.com"+ assert parts.path == "/oauth/auth"+ assert authorize_url.count("?") == 1++ params = parse_qs(parts.query)+ assert params["client_id"] == ["rlwy_oaci_test_client"]+ assert params["redirect_uri"] == ["https://us.posthog.com/api/mcp_store/oauth_redirect/"]+ assert params["response_type"] == ["code"]+ assert params["state"] == ["test-state"]+ assert params["code_challenge"] == ["test-challenge"]+ assert params["code_challenge_method"] == ["S256"]+ # PostHog's PRM resource must win over the AS-baked issuer resource+ assert params["resource"] == ["https://mcp.railway.com"]++ def test_keeps_repeated_endpoint_query_params(self) -> None:+ view = MCPServerInstallationViewSet()+ authorize_url = view._build_authorize_url_from_metadata(+ metadata={"authorization_endpoint": "https://auth.example.com/authorize?tenant=a&tenant=b&state=stale"},+ client_id="test-client",+ redirect_uri="https://us.posthog.com/api/mcp_store/oauth_redirect/",+ state_token="test-state",+ code_challenge="test-challenge",+ )++ params = parse_qs(urlsplit(authorize_url).query)+ assert params["tenant"] == ["a", "b"]+ assert params["state"] == ["test-state"]++class TestMCPAuthorizePosthogCodeResponse(APIBaseTest):def _create_template(self) -> MCPServerTemplate:return MCPServerTemplate.objects.create(