: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): persist DCR-minted client secrets for confidential clients (#58881)
Peter Kirkham7a75447f9070
diff --git a/products/mcp_store/backend/oauth.py b/products/mcp_store/backend/oauth.pyindex 81d4d2f6ff68..8f57f3f6f9f8 100644--- a/products/mcp_store/backend/oauth.py+++ b/products/mcp_store/backend/oauth.py@@ -76,6 +76,38 @@ def _resolve_issuer(metadata: dict, expected_issuer: str) -> dict:return metadata+def _validate_endpoints_bound_to_issuer(metadata: dict) -> None:+ """Reject metadata where OAuth endpoints don't share the issuer's origin.++ Without this, a malicious metadata source can mix endpoints from a real+ provider with an attacker-controlled token_endpoint, exfiltrating+ authorization codes, PKCE verifiers, and DCR-minted client_secrets while+ the user authorizes against the legitimate provider.+ """+ issuer = (metadata.get("issuer") or "").rstrip("/")+ if not issuer:+ raise ValueError("OAuth metadata is missing issuer")++ parsed_issuer = urlparse(issuer)+ if not parsed_issuer.scheme or not parsed_issuer.netloc:+ raise ValueError("OAuth metadata issuer is not an absolute URL")+ issuer_origin = (parsed_issuer.scheme, parsed_issuer.netloc)++ for field in ("authorization_endpoint", "token_endpoint", "registration_endpoint"):+ url = metadata.get(field)+ if not url:+ continue+ parsed = urlparse(url)+ if (parsed.scheme, parsed.netloc) != issuer_origin:+ logger.warning(+ "OAuth endpoint origin does not match issuer",+ issuer=issuer,+ field=field,+ endpoint=url,+ )+ raise ValueError(f"OAuth endpoint '{field}' origin does not match issuer")++def discover_oauth_metadata(server_url: str) -> dict:parsed_server = urlparse(server_url)origin = f"{parsed_server.scheme}://{parsed_server.netloc}"@@ -100,6 +132,7 @@ def discover_oauth_metadata(server_url: str) -> dict:# server metadata doesn't declare them (e.g. Asana).if "scopes_supported" not in metadata and "scopes_supported" in resource_data:metadata["scopes_supported"] = resource_data["scopes_supported"]+ _validate_endpoints_bound_to_issuer(metadata)return metadata# Step 2: Fall back to fetching authorization server metadata directly from the origin.@@ -108,10 +141,19 @@ def discover_oauth_metadata(server_url: str) -> dict:logger.info("RFC 9728 protected resource metadata not available, falling back to direct discovery", server_url=server_url)- return _resolve_issuer(_fetch_auth_server_metadata(origin), origin)+ metadata = _resolve_issuer(_fetch_auth_server_metadata(origin), origin)+ _validate_endpoints_bound_to_issuer(metadata)+ return metadata++def register_dcr_client(metadata: dict, redirect_uri: str) -> tuple[str, str | None]:+ """Run RFC 7591 Dynamic Client Registration.-def register_dcr_client(metadata: dict, redirect_uri: str) -> str:+ Returns ``(client_id, client_secret)``. Some servers (e.g. Supabase) ignore+ our ``token_endpoint_auth_method: "none"`` request and register a+ confidential client — in which case we must keep the returned secret or+ token exchange fails with ``Required parameter: client_secret``.+ """registration_endpoint = metadata.get("registration_endpoint")if not registration_endpoint:raise ValueError("Authorization server does not support Dynamic Client Registration")@@ -137,13 +179,15 @@ def register_dcr_client(metadata: dict, redirect_uri: str) -> str:)resp.raise_for_status()data = resp.json()- data.pop("client_secret", None) # Not used for public clients; don't store in plaintextclient_id = data.get("client_id")if not client_id:raise ValueError("No client_id in DCR response")- return client_id+ returned_secret = data.get("client_secret")+ client_secret = returned_secret if returned_secret and data.get("token_endpoint_auth_method") != "none" else None++ return client_id, client_secretdef generate_pkce() -> tuple[str, str]:@@ -333,7 +377,8 @@ def exchange_oauth_token(token_response = requests.post(token_endpoint, data=form, timeout=TIMEOUT)- if token_response.status_code != 200:+ # RFC 6749 specifies 200, but some providers (e.g. Supabase) return 201.+ if not token_response.ok:logger.error("OAuth token exchange failed",status_code=token_response.status_code,diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.pyindex 8f077277f354..d930963ef058 100644--- a/products/mcp_store/backend/presentation/views.py+++ b/products/mcp_store/backend/presentation/views.py@@ -405,7 +405,9 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetreturn Response({"detail": "Server URL blocked by security policy"}, status=status.HTTP_400_BAD_REQUEST)return None- def _register_dcr_client_or_raise(self, metadata: dict, redirect_uri: str, *, server_url: str = "") -> str:+ def _register_dcr_client_or_raise(+ self, metadata: dict, redirect_uri: str, *, server_url: str = ""+ ) -> tuple[str, str | None]:log_context = {"error": ""} if not server_url else {"server_url": server_url, "error": ""}try:return register_dcr_client(metadata, redirect_uri)@@ -584,7 +586,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetreturn Response({"detail": "OAuth discovery failed."}, status=status.HTTP_400_BAD_REQUEST)try:- client_id = self._register_dcr_client_or_raise(+ client_id, dcr_client_secret = self._register_dcr_client_or_raise(metadata,redirect_uri,server_url=template.url,@@ -607,6 +609,10 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetsensitive = dict(installation.sensitive_configuration or {})sensitive["dcr_client_id"] = client_idsensitive["dcr_is_user_provided"] = False+ if dcr_client_secret:+ sensitive["dcr_client_secret"] = dcr_client_secret+ else:+ sensitive.pop("dcr_client_secret", None)installation.oauth_metadata = metadatainstallation.sensitive_configuration = sensitiveinstallation.save(update_fields=["oauth_metadata", "sensitive_configuration", "updated_at"])@@ -809,12 +815,15 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetreturn Response({"detail": "Could not determine OAuth issuer"}, status=status.HTTP_400_BAD_REQUEST)# Resolve per-installation client credentials: either user-supplied or fresh DCR.+ dcr_client_secret: str | None = Noneif user_client_id:client_id = user_client_iddcr_is_user_provided = Trueelse:try:- client_id = self._register_dcr_client_or_raise(metadata, redirect_uri, server_url=mcp_url)+ client_id, dcr_client_secret = self._register_dcr_client_or_raise(+ metadata, redirect_uri, server_url=mcp_url+ )except DCRNotSupportedError:if created:installation.delete()@@ -844,11 +853,11 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetsensitive["needs_reauth"] = Truesensitive["dcr_client_id"] = client_idsensitive["dcr_is_user_provided"] = dcr_is_user_provided- # Only persist a client_secret if we also trusted the user-supplied- # client_id. A stray client_secret paired with a DCR-minted client_id- # would never validate, so discard it.- if dcr_is_user_provided and user_client_secret:- sensitive["dcr_client_secret"] = user_client_secret+ # A user-supplied secret without a user-supplied client_id is discarded;+ # it would never pair with the DCR-minted client_id.+ effective_secret = user_client_secret if dcr_is_user_provided else dcr_client_secret+ if effective_secret:+ sensitive["dcr_client_secret"] = effective_secretelse:sensitive.pop("dcr_client_secret", None)installation.sensitive_configuration = sensitivediff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex 2467783b205b..547cc890fdc9 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -713,7 +713,7 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):@ALLOW_URL@patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")- @patch("products.mcp_store.backend.presentation.views.register_dcr_client", return_value="dcr-client-id")+ @patch("products.mcp_store.backend.presentation.views.register_dcr_client", return_value=("dcr-client-id", None))def test_install_custom_populates_created_by(self, _mock_dcr, mock_discover, _allow):"""install_custom path must stamp created_by on the MCPOAuthState row."""mock_discover.return_value = {@@ -784,7 +784,7 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryM"token_endpoint": "https://auth.legit.com/token","registration_endpoint": "https://auth.legit.com/register",}- mock_dcr.return_value = "per-user-dcr-client"+ mock_dcr.return_value = ("per-user-dcr-client", None)response = self.client.post(f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",@@ -800,6 +800,38 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryM# EncryptedJSONField stringifies leaf values on round-trip; accept either bool or str.assert installation.sensitive_configuration["dcr_is_user_provided"] in (False, "False")+ @ALLOW_URL+ @patch("products.mcp_store.backend.presentation.views.register_dcr_client")+ @patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")+ def test_install_custom_persists_dcr_minted_client_secret(self, mock_discover, mock_dcr, _allow):+ """When the auth server registers a confidential client during DCR, persist the secret.++ Some providers (e.g. Supabase) ignore ``token_endpoint_auth_method=none``+ and register a confidential client anyway, returning a ``client_secret``+ that the token endpoint then requires. Dropping it makes the subsequent+ token exchange fail with 422 ``Required parameter: client_secret``.+ """+ mock_discover.return_value = {+ "issuer": "https://auth.legit.com",+ "authorization_endpoint": "https://auth.legit.com/authorize",+ "token_endpoint": "https://auth.legit.com/token",+ "registration_endpoint": "https://auth.legit.com/register",+ }+ mock_dcr.return_value = ("dcr-minted-client", "dcr-minted-secret")++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",+ data={"name": "Legit", "url": "https://mcp.legit.com/mcp", "auth_type": "oauth"},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK++ installation = MCPServerInstallation.objects.get(url="https://mcp.legit.com/mcp", user=self.user)+ sensitive = installation.sensitive_configuration+ assert sensitive["dcr_client_id"] == "dcr-minted-client"+ assert sensitive["dcr_client_secret"] == "dcr-minted-secret"+ assert sensitive["dcr_is_user_provided"] in (False, "False")+@ALLOW_URL@patch("products.mcp_store.backend.presentation.views.register_dcr_client")@patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")@@ -851,7 +883,7 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryM"token_endpoint": "https://auth.legit.com/token","registration_endpoint": "https://auth.legit.com/register",}- mock_dcr.return_value = "dcr-minted-client"+ mock_dcr.return_value = ("dcr-minted-client", None)response = self.client.post(f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",@@ -873,7 +905,10 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMassert sensitive["dcr_is_user_provided"] in (False, "False")@ALLOW_URL- @patch("products.mcp_store.backend.presentation.views.register_dcr_client", return_value="new-dcr-client")+ @patch(+ "products.mcp_store.backend.presentation.views.register_dcr_client",+ return_value=("new-dcr-client", None),+ )@patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")def test_reinstall_clears_stale_tokens_and_flags_reauth(self, mock_discover, _mock_dcr, _allow):"""Re-running install_custom swaps the DCR client; stale tokens from the old client must be cleared.@@ -1099,7 +1134,7 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest@patch("products.mcp_store.backend.presentation.views.register_dcr_client",- return_value="minted-per-user-client",+ return_value=("minted-per-user-client", None),)@patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata",diff --git a/products/mcp_store/backend/test/test_oauth.py b/products/mcp_store/backend/test/test_oauth.pyindex 621ac658c83c..18741f77b028 100644--- a/products/mcp_store/backend/test/test_oauth.py+++ b/products/mcp_store/backend/test/test_oauth.py@@ -15,6 +15,7 @@ from products.mcp_store.backend.oauth import (SSRFBlockedError,TokenRefreshError,_resolve_issuer,+ _validate_endpoints_bound_to_issuer,discover_oauth_metadata,exchange_oauth_token,refresh_oauth_token,@@ -452,6 +453,44 @@ class TestIssuerValidation(TestCase):assert mock_get.call_args_list[index].args[0] == expected_urlassert mock_get.call_args_list[index].kwargs["timeout"] == TIMEOUT+ @parameterized.expand(+ [+ (+ "token_endpoint_redirected_to_attacker",+ {+ "issuer": "https://auth.legit.com",+ "authorization_endpoint": "https://auth.legit.com/authorize",+ "token_endpoint": "https://attacker.com/token",+ "registration_endpoint": "https://auth.legit.com/register",+ },+ ),+ (+ "registration_endpoint_redirected_to_attacker",+ {+ "issuer": "https://auth.legit.com",+ "authorization_endpoint": "https://auth.legit.com/authorize",+ "token_endpoint": "https://auth.legit.com/token",+ "registration_endpoint": "https://attacker.com/register",+ },+ ),+ ]+ )+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.oauth.requests.get")+ def test_rejects_metadata_with_endpoints_off_issuer_origin(self, _name, auth_metadata, mock_get, _allow):+ """A malicious MCP server cannot mix a legitimate issuer with an attacker-controlled endpoint.++ Otherwise, after the user authorizes against the real provider, the+ token exchange would ship the code, PKCE verifier, and any DCR-minted+ client_secret to the attacker.+ """+ resource_resp = self._make_response(json_data={"authorization_servers": ["https://auth.legit.com"]})+ auth_resp = self._make_response(json_data=auth_metadata)+ mock_get.side_effect = [resource_resp, auth_resp]++ with self.assertRaises(ValueError):+ discover_oauth_metadata("https://mcp.legit.com/mcp")+class TestSSRFProtection(TestCase):@parameterized.expand(@@ -481,6 +520,162 @@ class TestSSRFProtection(TestCase):func(**kwargs) # type: ignore[operator]+class TestValidateEndpointsBoundToIssuer(TestCase):+ @parameterized.expand(+ [+ (+ "all_endpoints_match_issuer_origin",+ {+ "issuer": "https://auth.example.com",+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "https://auth.example.com/token",+ "registration_endpoint": "https://auth.example.com/register",+ },+ ),+ (+ "missing_registration_endpoint_is_ok",+ {+ "issuer": "https://auth.example.com",+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "https://auth.example.com/token",+ },+ ),+ (+ "trailing_slash_on_issuer_tolerated",+ {+ "issuer": "https://auth.example.com/",+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "https://auth.example.com/token",+ },+ ),+ ]+ )+ def test_accepts_aligned_metadata(self, _name, metadata):+ _validate_endpoints_bound_to_issuer(metadata)++ @parameterized.expand(+ [+ (+ "token_endpoint_on_attacker_origin",+ {+ "issuer": "https://auth.example.com",+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "https://attacker.com/token",+ },+ "token_endpoint",+ ),+ (+ "authorization_endpoint_on_attacker_origin",+ {+ "issuer": "https://auth.example.com",+ "authorization_endpoint": "https://attacker.com/authorize",+ "token_endpoint": "https://auth.example.com/token",+ },+ "authorization_endpoint",+ ),+ (+ "registration_endpoint_on_attacker_origin",+ {+ "issuer": "https://auth.example.com",+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "https://auth.example.com/token",+ "registration_endpoint": "https://attacker.com/register",+ },+ "registration_endpoint",+ ),+ (+ "scheme_downgrade_to_http",+ {+ "issuer": "https://auth.example.com",+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "http://auth.example.com/token",+ },+ "token_endpoint",+ ),+ (+ "subdomain_mismatch",+ {+ "issuer": "https://auth.example.com",+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "https://token.example.com/token",+ },+ "token_endpoint",+ ),+ ]+ )+ def test_rejects_mismatched_endpoints(self, _name, metadata, offending_field):+ with self.assertRaises(ValueError) as ctx:+ _validate_endpoints_bound_to_issuer(metadata)+ self.assertIn(offending_field, str(ctx.exception))++ @parameterized.expand(+ [+ ("missing_issuer", {"authorization_endpoint": "https://auth.example.com/authorize"}),+ ("empty_issuer", {"issuer": "", "authorization_endpoint": "https://auth.example.com/authorize"}),+ ("relative_issuer", {"issuer": "/auth", "authorization_endpoint": "https://auth.example.com/authorize"}),+ ]+ )+ def test_rejects_invalid_issuer(self, _name, metadata):+ with self.assertRaises(ValueError):+ _validate_endpoints_bound_to_issuer(metadata)+++class TestRegisterDCRClient(TestCase):+ @parameterized.expand(+ [+ (+ "drops_secret_when_server_honors_public_client",+ {"client_id": "abc", "token_endpoint_auth_method": "none"},+ ("abc", None),+ ),+ (+ "drops_secret_when_server_omits_it",+ {"client_id": "abc", "token_endpoint_auth_method": "none", "client_secret": ""},+ ("abc", None),+ ),+ (+ "keeps_secret_when_server_registered_confidential_client_post",+ {+ "client_id": "abc",+ "client_secret": "minted-secret",+ "token_endpoint_auth_method": "client_secret_post",+ },+ ("abc", "minted-secret"),+ ),+ (+ "keeps_secret_when_server_registered_confidential_client_basic",+ {+ "client_id": "abc",+ "client_secret": "minted-secret",+ "token_endpoint_auth_method": "client_secret_basic",+ },+ ("abc", "minted-secret"),+ ),+ (+ "keeps_secret_when_auth_method_unspecified",+ {"client_id": "abc", "client_secret": "minted-secret"},+ ("abc", "minted-secret"),+ ),+ ]+ )+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, ""))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_returns_client_secret_only_when_server_requires_it(+ self, _name, response_body, expected, mock_post, _allow+ ):+ mock_response = MagicMock()+ mock_response.ok = True+ mock_response.json.return_value = response_body+ mock_post.return_value = mock_response++ result = register_dcr_client(+ {"registration_endpoint": "https://auth.example.com/register"},+ "https://app.posthog.com/callback",+ )++ assert result == expected++class TestResolveInstallationOauthContext(BaseTest):def test_template_backed_install_returns_template_creds(self):template = MCPServerTemplate.objects.create(@@ -653,3 +848,48 @@ class TestExchangeOauthToken(BaseTest):redirect_uri="https://app.posthog.com/callback",is_https=lambda url: url.startswith("https://"),)++ @parameterized.expand(+ [+ ("ok_200", 200, True, False),+ ("created_201", 201, True, False),+ ("accepted_202", 202, True, False),+ ("bad_request_400", 400, False, True),+ ("unauthorized_401", 401, False, True),+ ("unprocessable_422", 422, False, True),+ ("server_error_500", 500, False, True),+ ]+ )+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_accepts_any_2xx_status(self, _name, status_code, ok, should_raise, mock_post, _allow):+ """Some providers (e.g. Supabase) return 201 on token issue — we must accept it."""+ mock_resp = MagicMock()+ mock_resp.status_code = status_code+ mock_resp.ok = ok+ mock_resp.json.return_value = {"access_token": "abc", "refresh_token": "def"}+ mock_resp.text = "{}"+ mock_post.return_value = mock_resp++ installation = self._make_installation(+ sensitive_configuration={"dcr_client_id": "client"},+ )++ if should_raise:+ with self.assertRaises(OAuthTokenExchangeError):+ exchange_oauth_token(+ installation=installation,+ code="auth-code",+ pkce_verifier="pkce-verifier",+ redirect_uri="https://app.posthog.com/callback",+ is_https=lambda url: url.startswith("https://"),+ )+ else:+ result = exchange_oauth_token(+ installation=installation,+ code="auth-code",+ pkce_verifier="pkce-verifier",+ redirect_uri="https://app.posthog.com/callback",+ is_https=lambda url: url.startswith("https://"),+ )+ assert result["access_token"] == "abc"