: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): support metadata-driven oauth registration (#65894)
Chris Volzerb0b365af8d19
diff --git a/products/mcp_store/backend/models.py b/products/mcp_store/backend/models.pyindex c4fab4ed2fff..fc8fa55b8862 100644--- a/products/mcp_store/backend/models.py+++ b/products/mcp_store/backend/models.py@@ -42,6 +42,7 @@ class SensitiveConfig(TypedDict, total=False):# the install form instead of a DCR handshake.dcr_client_id: strdcr_client_secret: str+ dcr_token_endpoint_auth_method: strdcr_is_user_provided: booldiff --git a/products/mcp_store/backend/oauth.py b/products/mcp_store/backend/oauth.pyindex 7f2e236bfd10..566705fca5b0 100644--- a/products/mcp_store/backend/oauth.py+++ b/products/mcp_store/backend/oauth.py@@ -16,6 +16,8 @@ from .models import MCPServerInstallationlogger = structlog.get_logger(__name__)TIMEOUT = 10+SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS = ("none", "client_secret_post", "client_secret_basic")+DEFAULT_CONFIDENTIAL_TOKEN_ENDPOINT_AUTH_METHOD = "client_secret_basic"class SSRFBlockedError(Exception):@@ -36,6 +38,97 @@ def _validate_url(url: str) -> None:raise SSRFBlockedError(f"URL blocked by SSRF protection: {reason} ({url})")+def _canonical_origin(url: str) -> str | None:+ try:+ parsed = urlparse(url)+ port = parsed.port+ except ValueError:+ return None++ if not parsed.scheme or not parsed.hostname or parsed.username or parsed.password:+ return None++ scheme = parsed.scheme.lower()+ hostname = parsed.hostname.lower()+ default_port = (scheme == "https" and port == 443) or (scheme == "http" and port == 80)+ netloc = hostname if port is None or default_port else f"{hostname}:{port}"+ return f"{scheme}://{netloc}"+++def _validate_resource_bound_to_server(resource: object, server_url: str) -> str:+ if not isinstance(resource, str) or not resource:+ raise ValueError("OAuth protected resource metadata resource must be a non-empty string")++ parsed_resource = urlparse(resource)+ if not parsed_resource.scheme or not parsed_resource.netloc:+ raise ValueError("OAuth protected resource metadata resource is not an absolute URL")+ if parsed_resource.fragment:+ raise ValueError("OAuth protected resource metadata resource must not include a fragment")++ resource_origin = _canonical_origin(resource)+ server_origin = _canonical_origin(server_url)+ if not resource_origin or not server_origin or resource_origin != server_origin:+ logger.warning(+ "OAuth protected resource metadata resource is not bound to MCP server",+ server_url=server_url,+ resource=resource,+ )+ raise ValueError("OAuth protected resource metadata resource is not bound to MCP server")++ return resource+++def _as_string_list(value: object) -> list[str]:+ if isinstance(value, str):+ return [value]+ if not isinstance(value, (list, tuple)):+ return []+ return [item for item in value if isinstance(item, str)]+++def requested_oauth_scopes(metadata: dict) -> list[str]:+ """Return the exact scopes we should request from this provider."""+ resource_scopes = _as_string_list(metadata.get("resource_scopes_supported"))+ if resource_scopes:+ return resource_scopes+ return _as_string_list(metadata.get("scopes_supported"))+++def requested_oauth_grant_types(metadata: dict) -> list[str]:+ grant_types = ["authorization_code"]+ supported_grants = _as_string_list(metadata.get("grant_types_supported"))+ if "refresh_token" in supported_grants:+ grant_types.append("refresh_token")+ return grant_types+++def select_token_endpoint_auth_method(metadata: dict, *, has_client_secret: bool = False) -> str:+ """Pick the token endpoint auth method we can actually use.++ Prefer public PKCE clients when the provider allows them. Otherwise use a+ client-secret method we support, keeping the registered method with the+ per-installation DCR credentials for token exchange and refresh.+ """+ supported_methods = _as_string_list(metadata.get("token_endpoint_auth_methods_supported"))+ preferred_methods = (+ ("client_secret_post", "client_secret_basic", "none")+ if has_client_secret+ else SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS+ )+ if not supported_methods:+ return DEFAULT_CONFIDENTIAL_TOKEN_ENDPOINT_AUTH_METHOD if has_client_secret else "none"+ for method in preferred_methods:+ if method in supported_methods:+ return method++ raise ValueError(f"Unsupported token_endpoint_auth_methods_supported: {', '.join(supported_methods)}")+++def oauth_resource(metadata: dict) -> str:+ resource = metadata.get("resource")+ return resource if isinstance(resource, str) else ""++def _fetch_auth_server_metadata(auth_server_url: str) -> dict:# MCP Authorization §2.3 mandates this exact ordered chain of well-known URLs.# https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#authorization-server-metadata-discovery@@ -179,10 +272,17 @@ def discover_oauth_metadata(server_url: str) -> dict:if resource_resp.ok:resource_data = resource_resp.json()+ bound_resource = None+ if "resource" in resource_data:+ bound_resource = _validate_resource_bound_to_server(resource_data["resource"], server_url)auth_servers = resource_data.get("authorization_servers", [])if auth_servers:auth_server_url = auth_servers[0]metadata = _resolve_issuer(_fetch_auth_server_metadata(auth_server_url), auth_server_url)+ if bound_resource:+ metadata["resource"] = bound_resource+ if "scopes_supported" in resource_data:+ metadata["resource_scopes_supported"] = resource_data["scopes_supported"]# Carry scopes from the protected resource metadata when the auth# server metadata doesn't declare them (e.g. Asana).if "scopes_supported" not in metadata and "scopes_supported" in resource_data:@@ -201,30 +301,32 @@ def discover_oauth_metadata(server_url: str) -> dict:return metadata-def register_dcr_client(metadata: dict, redirect_uri: str) -> tuple[str, str | None]:+def register_dcr_client(metadata: dict, redirect_uri: str) -> tuple[str, str | None, str]:"""Run RFC 7591 Dynamic Client Registration.- 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``.+ Returns ``(client_id, client_secret, token_endpoint_auth_method)``. Some+ servers (e.g. Supabase) register a confidential client even when we ask for+ a public one, so the auth method is persisted with the minted client."""registration_endpoint = metadata.get("registration_endpoint")if not registration_endpoint:raise ValueError("Authorization server does not support Dynamic Client Registration")+ token_endpoint_auth_method = select_token_endpoint_auth_method(metadata)payload: dict[str, object] = {"client_name": "MCP Store (PostHog)","redirect_uris": [redirect_uri],- "grant_types": ["authorization_code"],+ "grant_types": requested_oauth_grant_types(metadata),"response_types": ["code"],- "token_endpoint_auth_method": "none",+ "token_endpoint_auth_method": token_endpoint_auth_method,}- if scope := metadata.get("scopes_supported"):- payload["scope"] = " ".join(scope)+ if scopes := requested_oauth_scopes(metadata):+ payload["scope"] = " ".join(scopes)_validate_url(registration_endpoint)- resp = requests.post(registration_endpoint, json=payload, timeout=TIMEOUT)+ resp = requests.post(registration_endpoint, json=payload, timeout=TIMEOUT, allow_redirects=False)+ if 300 <= resp.status_code < 400:+ raise ValueError("Dynamic Client Registration endpoint redirected")if not resp.ok:logger.error("DCR registration request rejected",@@ -239,10 +341,21 @@ def register_dcr_client(metadata: dict, redirect_uri: str) -> tuple[str, str | Nif not client_id:raise ValueError("No client_id in DCR response")- returned_secret = data.get("client_secret")- client_secret = returned_secret if returned_secret and data.get("token_endpoint_auth_method") != "none" else None+ returned_secret = data.get("client_secret") or ""+ returned_auth_method_value = data.get("token_endpoint_auth_method")+ if isinstance(returned_auth_method_value, str) and returned_auth_method_value:+ returned_auth_method = returned_auth_method_value+ elif returned_secret and token_endpoint_auth_method == "none":+ returned_auth_method = DEFAULT_CONFIDENTIAL_TOKEN_ENDPOINT_AUTH_METHOD+ else:+ returned_auth_method = token_endpoint_auth_method+ if returned_auth_method not in SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS:+ raise ValueError(f"Unsupported token_endpoint_auth_method from DCR response: {returned_auth_method}")+ if returned_auth_method != "none" and not returned_secret:+ raise ValueError("DCR response registered a confidential client without client_secret")+ client_secret = returned_secret if returned_secret and returned_auth_method != "none" else None- return client_id, client_secret+ return client_id, client_secret, returned_auth_methoddef generate_pkce() -> tuple[str, str]:@@ -267,12 +380,19 @@ class TokenRefreshError(Exception):pass-def resolve_installation_oauth_context(installation: MCPServerInstallation) -> tuple[dict, str, str | None]:+def _credential_auth_method(credentials: dict, auth_method_key: str, client_secret: str | None) -> str:+ method = credentials.get(auth_method_key)+ if isinstance(method, str) and method in SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS:+ return method+ return DEFAULT_CONFIDENTIAL_TOKEN_ENDPOINT_AUTH_METHOD if client_secret else "none"+++def resolve_installation_oauth_context(installation: MCPServerInstallation) -> tuple[dict, str, str | None, str]:"""Resolve the OAuth metadata + client credentials for an installation.- Returns ``(metadata, client_id, client_secret)``. Secrets come from the- shared template when set, or from the installation's encrypted- ``sensitive_configuration`` for user-added servers.+ Returns ``(metadata, client_id, client_secret, token_endpoint_auth_method)``.+ Secrets come from the shared template when set, or from the installation's+ encrypted ``sensitive_configuration`` for user-added servers.Raises ``ValueError`` if the installation is missing required OAuth state."""@@ -290,7 +410,8 @@ def resolve_installation_oauth_context(installation: MCPServerInstallation) -> tif not metadata:raise ValueError("Template missing OAuth metadata")client_secret = credentials.get("client_secret") or None- return metadata, shared_client_id, client_secret+ auth_method = _credential_auth_method(credentials, "token_endpoint_auth_method", client_secret)+ return metadata, shared_client_id, client_secret, auth_method# DCR template: each installation ran discovery + DCR at install# time. Both the metadata and the minted client live on the# installation — the template is never written back to, so a@@ -300,14 +421,36 @@ def resolve_installation_oauth_context(installation: MCPServerInstallation) -> tclient_secret = sensitive.get("dcr_client_secret") or Noneif not metadata or not client_id:raise ValueError("DCR template installation missing OAuth metadata or dcr_client_id")- return metadata, client_id, client_secret+ auth_method = _credential_auth_method(sensitive, "dcr_token_endpoint_auth_method", client_secret)+ return metadata, client_id, client_secret, auth_methodmetadata = dict(installation.oauth_metadata or {})client_id = sensitive.get("dcr_client_id", "")client_secret = sensitive.get("dcr_client_secret") or Noneif not metadata or not client_id:raise ValueError("Installation missing OAuth metadata or client_id")- return metadata, client_id, client_secret+ auth_method = _credential_auth_method(sensitive, "dcr_token_endpoint_auth_method", client_secret)+ return metadata, client_id, client_secret, auth_method+++def _token_request_auth(+ form: dict[str, str],+ *,+ client_id: str,+ client_secret: str | None,+ token_endpoint_auth_method: str,+) -> tuple[dict[str, str], tuple[str, str] | None]:+ if token_endpoint_auth_method == "client_secret_basic":+ if not client_secret:+ raise ValueError("Missing client_secret for client_secret_basic token auth")+ return form, (client_id, client_secret)++ form["client_id"] = client_id+ if token_endpoint_auth_method == "client_secret_post":+ if not client_secret:+ raise ValueError("Missing client_secret for client_secret_post token auth")+ form["client_secret"] = client_secret+ return form, Nonedef refresh_oauth_token(@@ -316,27 +459,41 @@ def refresh_oauth_token(refresh_token: str,client_id: str,client_secret: str | None = None,+ token_endpoint_auth_method: str | None = None,+ resource: str = "",) -> dict:data: dict[str, str] = {"grant_type": "refresh_token","refresh_token": refresh_token,- "client_id": client_id,}- if client_secret:- data["client_secret"] = client_secret+ if resource:+ data["resource"] = resource++ try:+ data, auth = _token_request_auth(+ data,+ client_id=client_id,+ client_secret=client_secret,+ token_endpoint_auth_method=token_endpoint_auth_method+ or (DEFAULT_CONFIDENTIAL_TOKEN_ENDPOINT_AUTH_METHOD if client_secret else "none"),+ )+ except ValueError as exc:+ raise TokenRefreshError(str(exc))try:_validate_url(token_url)- resp = requests.post(token_url, data=data, timeout=TIMEOUT)+ resp = requests.post(token_url, data=data, auth=auth, timeout=TIMEOUT, allow_redirects=False)+ if 300 <= resp.status_code < 400:+ raise TokenRefreshError("Token refresh endpoint redirected")resp.raise_for_status()except SSRFBlockedError:raise TokenRefreshError(f"Token refresh URL blocked by SSRF protection: {token_url}")except requests.RequestException as exc:- status_code = getattr(getattr(exc, "response", None), "status_code", None)+ failed_status_code = getattr(getattr(exc, "response", None), "status_code", None)logger.warning("OAuth token refresh request failed",token_url=token_url,- status_code=status_code,+ status_code=failed_status_code,)raise TokenRefreshError("Token refresh request failed")@@ -356,7 +513,9 @@ def refresh_installation_token(installation: MCPServerInstallation) -> dict:raise TokenRefreshError("No refresh token available")try:- metadata, client_id, client_secret = resolve_installation_oauth_context(installation)+ metadata, client_id, client_secret, token_endpoint_auth_method = resolve_installation_oauth_context(+ installation+ )except ValueError as exc:raise TokenRefreshError(str(exc))@@ -369,6 +528,8 @@ def refresh_installation_token(installation: MCPServerInstallation) -> dict:refresh_token=refresh_token_value,client_id=client_id,client_secret=client_secret,+ token_endpoint_auth_method=token_endpoint_auth_method,+ resource=oauth_resource(metadata),)# Preserve non-token keys (needs_reauth, dcr_client_id, dcr_client_secret, etc.) across refresh.@@ -404,7 +565,9 @@ def exchange_oauth_token(raise OAuthTokenExchangeError("Missing PKCE verifier")try:- metadata, client_id, client_secret = resolve_installation_oauth_context(installation)+ metadata, client_id, client_secret, token_endpoint_auth_method = resolve_installation_oauth_context(+ installation+ )except ValueError as exc:raise OAuthTokenExchangeError(str(exc))@@ -421,18 +584,29 @@ def exchange_oauth_token(raise OAuthTokenExchangeError("Token endpoint must use HTTPS")form: dict[str, str] = {- "client_id": client_id,"code": code,"redirect_uri": redirect_uri,"grant_type": "authorization_code","code_verifier": pkce_verifier,}- if client_secret:- form["client_secret"] = client_secret+ if resource := oauth_resource(metadata):+ form["resource"] = resource++ try:+ form, auth = _token_request_auth(+ form,+ client_id=client_id,+ client_secret=client_secret,+ token_endpoint_auth_method=token_endpoint_auth_method,+ )+ except ValueError as exc:+ raise OAuthTokenExchangeError(str(exc))- token_response = requests.post(token_endpoint, data=form, timeout=TIMEOUT)+ token_response = requests.post(token_endpoint, data=form, auth=auth, timeout=TIMEOUT, allow_redirects=False)# RFC 6749 specifies 200, but some providers (e.g. Supabase) return 201.+ if 300 <= token_response.status_code < 400:+ raise OAuthTokenExchangeError("Token endpoint redirected")if not token_response.ok:logger.error("OAuth token exchange failed",diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.pyindex 1ea1b9f9584e..9cffcfebd574 100644--- a/products/mcp_store/backend/presentation/views.py+++ b/products/mcp_store/backend/presentation/views.py@@ -43,7 +43,10 @@ from ..oauth import (discover_oauth_metadata,exchange_oauth_token,generate_pkce,+ oauth_resource,register_dcr_client,+ requested_oauth_scopes,+ select_token_endpoint_auth_method,)from ..proxy import proxy_mcp_request, validate_installation_authfrom ..tasks import sync_installation_tools_task@@ -127,6 +130,15 @@ def _get_oauth_redirect_uri() -> str:return f"{settings.SITE_URL}/api/mcp_store/oauth_redirect/"+def _oauth_authorize_response(authorize_url: str, install_source: str) -> HttpResponse:+ if install_source == "posthog-code":+ return Response({"redirect_url": authorize_url}, status=status.HTTP_200_OK)++ response = HttpResponse(status=302)+ response["Location"] = authorize_url+ return response++def _template_uses_dcr(template: MCPServerTemplate) -> bool:"""Is this template configured for per-user Dynamic Client Registration?@@ -405,7 +417,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetdef _register_dcr_client_or_raise(self, metadata: dict, redirect_uri: str, *, server_url: str = ""- ) -> tuple[str, str | None]:+ ) -> tuple[str, str | None, str]:log_context = {"error": ""} if not server_url else {"server_url": server_url, "error": ""}try:return register_dcr_client(metadata, redirect_uri)@@ -435,8 +447,10 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet"code_challenge": code_challenge,"code_challenge_method": "S256",}- if scopes := metadata.get("scopes_supported"):+ if scopes := requested_oauth_scopes(metadata):query_params["scope"] = " ".join(scopes)+ if resource := oauth_resource(metadata):+ query_params["resource"] = resourceauth_endpoint = metadata.get("authorization_endpoint", "")if not auth_endpoint:@@ -584,7 +598,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetreturn Response({"detail": "OAuth discovery failed."}, status=status.HTTP_400_BAD_REQUEST)try:- client_id, dcr_client_secret = self._register_dcr_client_or_raise(+ client_id, dcr_client_secret, token_endpoint_auth_method = self._register_dcr_client_or_raise(metadata,redirect_uri,server_url=template.url,@@ -607,6 +621,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetsensitive = dict(installation.sensitive_configuration or {})sensitive["dcr_client_id"] = client_idsensitive["dcr_is_user_provided"] = False+ sensitive["dcr_token_endpoint_auth_method"] = token_endpoint_auth_methodif dcr_client_secret:sensitive["dcr_client_secret"] = dcr_client_secretelse:@@ -814,12 +829,25 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet# Resolve per-installation client credentials: either user-supplied or fresh DCR.dcr_client_secret: str | None = None+ token_endpoint_auth_method = "none"if user_client_id:client_id = user_client_iddcr_is_user_provided = True+ try:+ token_endpoint_auth_method = select_token_endpoint_auth_method(+ metadata, has_client_secret=bool(user_client_secret)+ )+ except ValueError as e:+ logger.warning("OAuth token endpoint auth method unsupported", server_url=mcp_url, error=str(e))+ if created:+ installation.delete()+ return Response(+ {"detail": "OAuth token endpoint auth method is not supported."},+ status=status.HTTP_400_BAD_REQUEST,+ )else:try:- client_id, dcr_client_secret = self._register_dcr_client_or_raise(+ client_id, dcr_client_secret, token_endpoint_auth_method = self._register_dcr_client_or_raise(metadata, redirect_uri, server_url=mcp_url)except DCRNotSupportedError:@@ -851,6 +879,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetsensitive["needs_reauth"] = Truesensitive["dcr_client_id"] = client_idsensitive["dcr_is_user_provided"] = dcr_is_user_provided+ sensitive["dcr_token_endpoint_auth_method"] = token_endpoint_auth_method# 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@@ -1033,9 +1062,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetteam=self.team,)- response = HttpResponse(status=302)- response["Location"] = authorize_url- return response+ return _oauth_authorize_response(authorize_url, install_source)def _authorize_for_installation(self,@@ -1101,9 +1128,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetexcept OAuthAuthorizeURLError:return Response({"detail": "Authorization endpoint must use HTTPS"}, status=status.HTTP_400_BAD_REQUEST)- response = HttpResponse(status=302)- response["Location"] = authorize_url- return response+ return _oauth_authorize_response(authorize_url, install_source)@extend_schema(responses={200: OpenApiResponse(response=MCPServerInstallationToolSerializer(many=True))})@action(detail=True, methods=["get"], url_path="tools")diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.pyindex b2e30bc4d181..73dd40ef65cc 100644--- a/products/mcp_store/backend/proxy.py+++ b/products/mcp_store/backend/proxy.py@@ -1,6 +1,7 @@import jsonfrom collections.abc import Iteratorfrom typing import Any+from urllib.parse import urljoin, urlparsefrom django.http import HttpResponse, StreamingHttpResponse@@ -19,6 +20,7 @@ logger = structlog.get_logger(__name__)UPSTREAM_TIMEOUT = 180MAX_PROXY_BODY_SIZE = 1_048_576 # 1 MB+REDIRECT_STATUS_CODES = {301, 302, 307, 308}# JSON-RPC error codes used by per-tool approval enforcement. -32000..-32099 is# the implementation-defined server-error range; we deliberately use distinct@@ -30,6 +32,83 @@ BATCH_REJECTED_CODE = -32000METHOD_NOT_FOUND_CODE = -32601+def _normalized_origin(url: str) -> tuple[str, str, int | None] | None:+ parsed = urlparse(url)+ try:+ port = parsed.port+ except ValueError:+ return None+ if port is None:+ if parsed.scheme == "https":+ port = 443+ elif parsed.scheme == "http":+ port = 80+ return parsed.scheme, (parsed.hostname or "").lower(), port+++def validated_same_origin_redirect_url(original_url: str, response: httpx.Response) -> str | None:+ """Return a safe redirect target for MCP URL canonicalization, or None.++ MCP servers commonly redirect `/mcp` to `/mcp/`. Retrying with credentials is+ only safe when the redirect stays on exactly the same origin; SSRF-safe is+ not the same as credential-safe.+ """+ if response.status_code not in REDIRECT_STATUS_CODES:+ return None++ location = response.headers.get("location")+ if not location:+ return None++ redirect_url = urljoin(original_url, location)+ original_origin = _normalized_origin(original_url)+ redirect_origin = _normalized_origin(redirect_url)+ if not original_origin or not redirect_origin or original_origin != redirect_origin:+ logger.warning(+ "Upstream MCP redirect rejected: target is cross-origin",+ original_url=original_url,+ redirect_url=redirect_url,+ )+ return None++ allowed, reason = is_url_allowed(redirect_url)+ if not allowed:+ logger.warning(+ "Upstream MCP redirect rejected by SSRF protection",+ original_url=original_url,+ redirect_url=redirect_url,+ reason=reason,+ )+ return None++ return redirect_url+++def send_mcp_request_with_same_origin_redirect(+ client: httpx.Client,+ method: str,+ url: str,+ *,+ headers: dict[str, str],+ content: bytes | None = None,+ stream: bool = False,+) -> tuple[httpx.Response, str]:+ request_kwargs: dict[str, Any] = {"headers": headers}+ if content is not None:+ request_kwargs["content"] = content++ upstream_request = client.build_request(method, url, **request_kwargs)+ upstream_response = client.send(upstream_request, stream=stream)++ redirect_url = validated_same_origin_redirect_url(url, upstream_response)+ if not redirect_url:+ return upstream_response, url++ upstream_response.close()+ redirected_request = client.build_request(method, redirect_url, **request_kwargs)+ return client.send(redirected_request, stream=stream), redirect_url++def build_upstream_auth_headers(installation: MCPServerInstallation) -> dict[str, str]:sensitive = installation.sensitive_configuration or {}@@ -293,13 +372,14 @@ def proxy_mcp_request(request: Any, installation: MCPServerInstallation) -> Httpclient = httpx.Client(timeout=UPSTREAM_TIMEOUT)try:- upstream_request = client.build_request(+ upstream_response, upstream_url = send_mcp_request_with_same_origin_redirect(+ client,"POST",installation.url,content=body,headers=headers,+ stream=True,)- upstream_response = client.send(upstream_request, stream=True)except httpx.ConnectError:client.close()logger.warning("Upstream MCP server unreachable", url=installation.url)@@ -334,7 +414,7 @@ def proxy_mcp_request(request: Any, installation: MCPServerInstallation) -> Httpif upstream_response.status_code >= 400:logger.warning("Upstream MCP server returned error",- url=installation.url,+ url=upstream_url,status_code=upstream_response.status_code,response_body=upstream_response.text[:500] if upstream_response.text else "",)diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex 547cc890fdc9..a258640a5840 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -713,7 +713,10 @@ 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", None))+ @patch(+ "products.mcp_store.backend.presentation.views.register_dcr_client",+ return_value=("dcr-client-id", None, "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 +787,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", None)+ mock_dcr.return_value = ("per-user-dcr-client", None, "none")response = self.client.post(f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",@@ -797,6 +800,7 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMinstallation = MCPServerInstallation.objects.get(url="https://mcp.legit.com/mcp", user=self.user)assert installation.oauth_metadata["authorization_endpoint"] == "https://auth.legit.com/authorize"assert installation.sensitive_configuration["dcr_client_id"] == "per-user-dcr-client"+ assert installation.sensitive_configuration["dcr_token_endpoint_auth_method"] == "none"# EncryptedJSONField stringifies leaf values on round-trip; accept either bool or str.assert installation.sensitive_configuration["dcr_is_user_provided"] in (False, "False")@@ -817,7 +821,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", "dcr-minted-secret")+ mock_dcr.return_value = ("dcr-minted-client", "dcr-minted-secret", "client_secret_post")response = self.client.post(f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",@@ -830,6 +834,7 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMsensitive = installation.sensitive_configurationassert sensitive["dcr_client_id"] == "dcr-minted-client"assert sensitive["dcr_client_secret"] == "dcr-minted-secret"+ assert sensitive["dcr_token_endpoint_auth_method"] == "client_secret_post"assert sensitive["dcr_is_user_provided"] in (False, "False")@ALLOW_URL@@ -862,12 +867,44 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMsensitive = installation.sensitive_configurationassert sensitive["dcr_client_id"] == "user-supplied-client-id"assert sensitive["dcr_client_secret"] == "user-supplied-secret"+ assert sensitive["dcr_token_endpoint_auth_method"] == "client_secret_basic"# EncryptedJSONField stringifies leaf values on round-trip; accept either bool or str.assert sensitive["dcr_is_user_provided"] in (True, "True")params = parse_qs(urlparse(response.json()["redirect_url"]).query)assert params["client_id"][0] == "user-supplied-client-id"+ @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_with_user_supplied_creds_rejects_unsupported_auth_method(+ self, mock_discover, mock_dcr, _allow+ ):+ 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",+ "token_endpoint_auth_methods_supported": ["private_key_jwt"],+ }++ 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",+ "client_id": "user-supplied-client-id",+ "client_secret": "user-supplied-secret",+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["detail"] == "OAuth token endpoint auth method is not supported."+ assert not MCPServerInstallation.objects.filter(url="https://mcp.legit.com/mcp", user=self.user).exists()+ mock_dcr.assert_not_called()+@ALLOW_URL@patch("products.mcp_store.backend.presentation.views.register_dcr_client")@patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")@@ -883,7 +920,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", None)+ mock_dcr.return_value = ("dcr-minted-client", None, "none")response = self.client.post(f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",@@ -902,12 +939,13 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMsensitive = installation.sensitive_configurationassert sensitive["dcr_client_id"] == "dcr-minted-client"assert "dcr_client_secret" not in sensitive+ assert sensitive["dcr_token_endpoint_auth_method"] == "none"assert 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", None),+ return_value=("new-dcr-client", None, "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):@@ -955,6 +993,7 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMinstallation.refresh_from_db()sensitive = installation.sensitive_configurationassert sensitive["dcr_client_id"] == "new-dcr-client"+ assert sensitive["dcr_token_endpoint_auth_method"] == "none"assert sensitive["needs_reauth"] in (True, "True")for stale_key in ("access_token", "refresh_token", "token_retrieved_at", "expires_in"):assert stale_key not in sensitive, f"{stale_key} should have been cleared on re-install"@@ -973,6 +1012,9 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMoauth_metadata={"authorization_endpoint": "https://auth.example.com/authorize","token_endpoint": "https://auth.example.com/token",+ "resource": "https://mcp.example.com/",+ "scopes_supported": ["admin", "read"],+ "resource_scopes_supported": ["read"],},sensitive_configuration={"dcr_client_id": "existing-client-id", "dcr_is_user_provided": False},)@@ -987,6 +1029,8 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMmock_discover.assert_not_called()params = parse_qs(urlparse(response["Location"]).query)assert params["client_id"][0] == "existing-client-id"+ assert params["resource"][0] == "https://mcp.example.com/"+ assert params["scope"][0] == "read"@ALLOW_URLdef test_authorize_uses_opaque_state_token(self, _allow):@@ -1048,6 +1092,82 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMassert second_callback.status_code == status.HTTP_400_BAD_REQUEST+class TestMCPAuthorizePosthogCodeResponse(APIBaseTest):+ def _create_template(self) -> MCPServerTemplate:+ return MCPServerTemplate.objects.create(+ name="Test Template",+ url="https://mcp.test.example.com/mcp",+ auth_type="oauth",+ is_active=True,+ oauth_metadata={+ "authorization_endpoint": "https://auth.test.example.com/authorize",+ "token_endpoint": "https://auth.test.example.com/token",+ },+ oauth_credentials={"client_id": "test-client-id"},+ )++ @ALLOW_URL+ @patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")+ def test_authorize_returns_redirect_url_for_custom_installation(self, mock_discover, _allow):+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ url="https://mcp.example.com",+ display_name="Test",+ auth_type="oauth",+ oauth_issuer_url="https://auth.example.com",+ oauth_metadata={+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "https://auth.example.com/token",+ },+ sensitive_configuration={"dcr_client_id": "existing-client-id", "dcr_is_user_provided": False},+ )++ response = self.client.get(+ f"/api/environments/{self.team.id}/mcp_server_installations/authorize/",+ {+ "installation_id": str(installation.id),+ "install_source": "posthog-code",+ "posthog_code_callback_url": "posthog-code://oauth/callback",+ },+ )++ assert response.status_code == status.HTTP_200_OK+ assert "Location" not in response+ redirect_url = response.json()["redirect_url"]+ assert urlparse(redirect_url).netloc == "auth.example.com"+ mock_discover.assert_not_called()+ params = parse_qs(urlparse(redirect_url).query)+ assert params["client_id"][0] == "existing-client-id"++ @ALLOW_URL+ def test_authorize_returns_redirect_url_for_template_installation(self, _allow):+ template = self._create_template()+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ template=template,+ url=template.url,+ auth_type="oauth",+ )++ response = self.client.get(+ f"/api/environments/{self.team.id}/mcp_server_installations/authorize/",+ {+ "installation_id": str(installation.id),+ "install_source": "posthog-code",+ "posthog_code_callback_url": "posthog-code://oauth/callback",+ },+ )++ assert response.status_code == status.HTTP_200_OK+ assert "Location" not in response+ redirect_url = response.json()["redirect_url"]+ assert urlparse(redirect_url).netloc == "auth.test.example.com"+ params = parse_qs(urlparse(redirect_url).query)+ assert params["client_id"][0] == "test-client-id"++class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def _template(self, **overrides) -> MCPServerTemplate:import uuid as _uuid@@ -1134,7 +1254,7 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest@patch("products.mcp_store.backend.presentation.views.register_dcr_client",- return_value=("minted-per-user-client", None),+ return_value=("minted-per-user-client", None, "none"),)@patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata",@@ -1169,6 +1289,7 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTestinstallation = MCPServerInstallation.objects.get(url=template.url, user=self.user)sensitive = installation.sensitive_configuration or {}assert sensitive["dcr_client_id"] == "minted-per-user-client"+ assert sensitive["dcr_token_endpoint_auth_method"] == "none"# Discovered metadata is cached on the installation, not written back to the template.assert installation.oauth_metadata["token_endpoint"] == "https://auth.discovered.example.com/token"template.refresh_from_db()diff --git a/products/mcp_store/backend/test/test_oauth.py b/products/mcp_store/backend/test/test_oauth.pyindex 63903dd3b858..69ab6840461e 100644--- a/products/mcp_store/backend/test/test_oauth.py+++ b/products/mcp_store/backend/test/test_oauth.py@@ -3,7 +3,7 @@ from urllib.parse import urlparsefrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch-from django.test import TestCase+from django.test import SimpleTestCase, TestCaseimport requestsfrom parameterized import parameterized@@ -18,9 +18,13 @@ from products.mcp_store.backend.oauth import (_validate_endpoints_bound_to_issuer,discover_oauth_metadata,exchange_oauth_token,+ oauth_resource,refresh_oauth_token,register_dcr_client,+ requested_oauth_grant_types,+ requested_oauth_scopes,resolve_installation_oauth_context,+ select_token_endpoint_auth_method,)@@ -119,22 +123,22 @@ class TestResolveIssuer(TestCase):_resolve_issuer(metadata, "https://origin.com")-class TestRefreshOauthToken(TestCase):+class TestRefreshOauthToken(SimpleTestCase):@parameterized.expand([("known_provider_with_secret",{"client_secret": "my-secret"},- {"client_secret": "my-secret"},+ ("my-client", "my-secret"),),("dcr_without_secret",{"client_secret": None},- {},+ None,),])- def test_client_secret_inclusion(self, _name, kwargs, expected_extra_data):+ def test_default_token_auth_method(self, _name, kwargs, expected_auth):mock_resp = MagicMock()mock_resp.status_code = 200mock_resp.json.return_value = {"access_token": "new-token", "refresh_token": "new-refresh"}@@ -148,18 +152,42 @@ class TestRefreshOauthToken(TestCase):**kwargs,)- call_data = mock_post.call_args[1]["data"]+ call_kwargs = mock_post.call_args.kwargs+ call_data = call_kwargs["data"]self.assertEqual(call_data["grant_type"], "refresh_token")self.assertEqual(call_data["refresh_token"], "old-refresh")- self.assertEqual(call_data["client_id"], "my-client")- if expected_extra_data:- self.assertEqual(call_data["client_secret"], expected_extra_data["client_secret"])+ if expected_auth:+ self.assertNotIn("client_id", call_data)+ self.assertNotIn("client_secret", call_data)else:+ self.assertEqual(call_data["client_id"], "my-client")self.assertNotIn("client_secret", call_data)+ self.assertEqual(call_kwargs["auth"], expected_auth)self.assertEqual(result["access_token"], "new-token")+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_refresh_sends_resource_and_disables_redirects(self, mock_post, _allow):+ mock_resp = MagicMock()+ mock_resp.status_code = 200+ mock_resp.json.return_value = {"access_token": "new-token"}+ mock_resp.raise_for_status = MagicMock()+ mock_post.return_value = mock_resp++ refresh_oauth_token(+ token_url="https://example.com/token",+ refresh_token="old-refresh",+ client_id="my-client",+ resource="https://mcp.example.com/",+ )++ call_kwargs = mock_post.call_args.kwargs+ assert call_kwargs["allow_redirects"] is False+ assert call_kwargs["data"]["resource"] == "https://mcp.example.com/"+def test_http_error_raises_token_refresh_error(self):mock_resp = MagicMock()+ mock_resp.status_code = 401mock_resp.raise_for_status.side_effect = requests.HTTPError("401 Unauthorized", response=mock_resp)with patch("products.mcp_store.backend.oauth.requests.post", return_value=mock_resp):@@ -197,7 +225,7 @@ class TestRefreshOauthToken(TestCase):self.assertIn("SSRF protection", str(ctx.exception))-class TestIssuerValidation(TestCase):+class TestIssuerValidation(SimpleTestCase):def _make_response(self, *, ok=True, status_code=200, json_data=None):resp = MagicMock()resp.ok = ok@@ -472,6 +500,46 @@ class TestIssuerValidation(TestCase):assert mock_get.call_args_list[index].args[0] == expected_urlassert mock_get.call_args_list[index].kwargs["timeout"] == TIMEOUT+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.oauth.requests.get")+ def test_step1_preserves_same_origin_resource(self, mock_get, _allow):+ auth_server_url = "https://auth.example.com"+ resource_resp = self._make_response(+ json_data={+ "resource": "https://mcp.example.com/mcp",+ "authorization_servers": [auth_server_url],+ }+ )+ auth_resp = self._make_response(+ json_data={+ "issuer": auth_server_url,+ "authorization_endpoint": f"{auth_server_url}/authorize",+ "token_endpoint": f"{auth_server_url}/token",+ }+ )+ mock_get.side_effect = [resource_resp, auth_resp]++ metadata = discover_oauth_metadata("https://mcp.example.com/mcp")++ assert metadata["resource"] == "https://mcp.example.com/mcp"+ assert mock_get.call_count == 2++ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.oauth.requests.get")+ def test_step1_rejects_resource_on_unrelated_origin(self, mock_get, _allow):+ resource_resp = self._make_response(+ json_data={+ "resource": "https://api.legit.com",+ "authorization_servers": ["https://auth.legit.com"],+ }+ )+ mock_get.return_value = resource_resp++ with self.assertRaisesMessage(ValueError, "not bound to MCP server"):+ discover_oauth_metadata("https://mcp.attacker.com/mcp")++ assert mock_get.call_count == 1+@parameterized.expand([(@@ -830,18 +898,56 @@ class TestValidateEndpointsBoundToIssuer(TestCase):_validate_endpoints_bound_to_issuer(metadata)-class TestRegisterDCRClient(TestCase):+class TestRegisterDCRClient(SimpleTestCase):+ @parameterized.expand(+ [+ ("public_client", False),+ ("confidential_client", True),+ ]+ )+ def test_rejects_explicit_unsupported_auth_methods(self, _name, has_client_secret):+ with self.assertRaisesMessage(ValueError, "private_key_jwt"):+ select_token_endpoint_auth_method(+ {"token_endpoint_auth_methods_supported": ["private_key_jwt"]},+ has_client_secret=has_client_secret,+ )++ def test_uses_public_auth_when_it_is_the_only_supported_method_with_secret(self):+ assert (+ select_token_endpoint_auth_method(+ {"token_endpoint_auth_methods_supported": ["none"]},+ has_client_secret=True,+ )+ == "none"+ )++ def test_omitted_supported_methods_default_to_basic_for_confidential_clients(self):+ assert select_token_endpoint_auth_method({}, has_client_secret=True) == "client_secret_basic"++ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_rejects_dcr_when_provider_only_lists_unsupported_auth_methods(self, mock_post):+ with self.assertRaisesMessage(ValueError, "private_key_jwt"):+ register_dcr_client(+ {+ "registration_endpoint": "https://auth.example.com/register",+ "token_endpoint_auth_methods_supported": ["private_key_jwt"],+ },+ "https://app.posthog.com/callback",+ )++ mock_post.assert_not_called()+@parameterized.expand([("drops_secret_when_server_honors_public_client",{"client_id": "abc", "token_endpoint_auth_method": "none"},- ("abc", None),+ ("abc", None, "none"),),("drops_secret_when_server_omits_it",{"client_id": "abc", "token_endpoint_auth_method": "none", "client_secret": ""},- ("abc", None),+ ("abc", None, "none"),),("keeps_secret_when_server_registered_confidential_client_post",@@ -850,7 +956,7 @@ class TestRegisterDCRClient(TestCase):"client_secret": "minted-secret","token_endpoint_auth_method": "client_secret_post",},- ("abc", "minted-secret"),+ ("abc", "minted-secret", "client_secret_post"),),("keeps_secret_when_server_registered_confidential_client_basic",@@ -859,12 +965,12 @@ class TestRegisterDCRClient(TestCase):"client_secret": "minted-secret","token_endpoint_auth_method": "client_secret_basic",},- ("abc", "minted-secret"),+ ("abc", "minted-secret", "client_secret_basic"),),(- "keeps_secret_when_auth_method_unspecified",+ "keeps_secret_with_basic_auth_when_auth_method_unspecified",{"client_id": "abc", "client_secret": "minted-secret"},- ("abc", "minted-secret"),+ ("abc", "minted-secret", "client_secret_basic"),),])@@ -875,6 +981,7 @@ class TestRegisterDCRClient(TestCase):):mock_response = MagicMock()mock_response.ok = True+ mock_response.status_code = 201mock_response.json.return_value = response_bodymock_post.return_value = mock_response@@ -885,6 +992,72 @@ class TestRegisterDCRClient(TestCase):assert result == expected+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, ""))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_registers_refresh_grant_without_refresh_scope(self, mock_post, _allow):+ mock_response = MagicMock()+ mock_response.ok = True+ mock_response.status_code = 201+ mock_response.json.return_value = {+ "client_id": "abc",+ "client_secret": "minted-secret",+ "token_endpoint_auth_method": "client_secret_post",+ }+ mock_post.return_value = mock_response++ result = register_dcr_client(+ {+ "registration_endpoint": "https://auth.example.com/register",+ "scopes_supported": ["read", "write"],+ "grant_types_supported": ["authorization_code", "refresh_token"],+ "token_endpoint_auth_methods_supported": ["client_secret_post", "client_secret_basic"],+ },+ "https://app.posthog.com/callback",+ )++ assert result == ("abc", "minted-secret", "client_secret_post")+ payload = mock_post.call_args.kwargs["json"]+ assert payload["grant_types"] == ["authorization_code", "refresh_token"]+ assert payload["token_endpoint_auth_method"] == "client_secret_post"+ assert payload["scope"] == "read write"+ assert "refresh_token" not in payload["scope"]+ assert mock_post.call_args.kwargs["allow_redirects"] is False++ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, ""))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_keeps_requested_basic_auth_when_dcr_response_omits_auth_method(self, mock_post, _allow):+ mock_response = MagicMock()+ mock_response.ok = True+ mock_response.status_code = 201+ mock_response.json.return_value = {+ "client_id": "abc",+ "client_secret": "minted-secret",+ }+ mock_post.return_value = mock_response++ result = register_dcr_client(+ {+ "registration_endpoint": "https://auth.example.com/register",+ "token_endpoint_auth_methods_supported": ["client_secret_basic"],+ },+ "https://app.posthog.com/callback",+ )++ assert result == ("abc", "minted-secret", "client_secret_basic")+ assert mock_post.call_args.kwargs["json"]["token_endpoint_auth_method"] == "client_secret_basic"++ def test_scope_selection_prefers_protected_resource_scopes(self):+ metadata = {+ "scopes_supported": ["admin", "read"],+ "resource_scopes_supported": ["read"],+ "grant_types_supported": ["authorization_code", "refresh_token"],+ "resource": "https://mcp.example.com/",+ }++ assert requested_oauth_scopes(metadata) == ["read"]+ assert requested_oauth_grant_types(metadata) == ["authorization_code", "refresh_token"]+ assert oauth_resource(metadata) == "https://mcp.example.com/"+class TestResolveInstallationOauthContext(BaseTest):def test_template_backed_install_returns_template_creds(self):@@ -907,11 +1080,12 @@ class TestResolveInstallationOauthContext(BaseTest):sensitive_configuration={"access_token": "tok"},)- metadata, client_id, client_secret = resolve_installation_oauth_context(installation)+ metadata, client_id, client_secret, auth_method = resolve_installation_oauth_context(installation)assert metadata["token_endpoint"] == "https://auth.template.example.com/token"assert client_id == "template-client"assert client_secret == "template-secret"+ assert auth_method == "client_secret_basic"def test_dcr_template_backed_install_returns_per_installation_metadata_and_creds(self):# DCR templates carry no shared client_id AND no trusted metadata —@@ -940,11 +1114,12 @@ class TestResolveInstallationOauthContext(BaseTest):},)- metadata, client_id, client_secret = resolve_installation_oauth_context(installation)+ metadata, client_id, client_secret, auth_method = resolve_installation_oauth_context(installation)assert metadata["token_endpoint"] == "https://auth.dcr-template.example.com/token"assert client_id == "minted-for-user"assert client_secret is None+ assert auth_method == "none"def test_custom_install_returns_per_installation_dcr_creds(self):installation = MCPServerInstallation.objects.create(@@ -959,11 +1134,12 @@ class TestResolveInstallationOauthContext(BaseTest):},)- metadata, client_id, client_secret = resolve_installation_oauth_context(installation)+ metadata, client_id, client_secret, auth_method = resolve_installation_oauth_context(installation)assert metadata["token_endpoint"] == "https://auth.custom.example.com/token"assert client_id == "per-user-client"assert client_secret == "per-user-secret"+ assert auth_method == "client_secret_basic"def test_custom_install_without_secret_returns_none(self):installation = MCPServerInstallation.objects.create(@@ -975,9 +1151,10 @@ class TestResolveInstallationOauthContext(BaseTest):sensitive_configuration={"dcr_client_id": "public-client"},)- _metadata, _client_id, client_secret = resolve_installation_oauth_context(installation)+ _metadata, _client_id, client_secret, auth_method = resolve_installation_oauth_context(installation)assert client_secret is None+ assert auth_method == "none"class TestExchangeOauthToken(BaseTest):@@ -993,10 +1170,10 @@ class TestExchangeOauthToken(BaseTest):@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))@patch("products.mcp_store.backend.oauth.requests.post")- def test_confidential_custom_install_sends_client_secret(self, mock_post, _allow):- """dcr_client_secret round-trips through resolve_installation_oauth_context into the token exchange body."""+ def test_confidential_custom_install_defaults_to_http_basic(self, mock_post, _allow):mock_resp = MagicMock()mock_resp.status_code = 200+ mock_resp.ok = Truemock_resp.json.return_value = {"access_token": "abc", "refresh_token": "def"}mock_post.return_value = mock_resp@@ -1016,11 +1193,46 @@ class TestExchangeOauthToken(BaseTest):)assert result["access_token"] == "abc"- sent_form = mock_post.call_args[1]["data"]+ sent_form = mock_post.call_args.kwargs["data"]+ assert "client_id" not in sent_form+ assert "client_secret" not in sent_form+ assert sent_form["grant_type"] == "authorization_code"+ assert sent_form["code_verifier"] == "pkce-verifier"+ assert mock_post.call_args.kwargs["auth"] == ("confidential-client", "confidential-secret")+ assert mock_post.call_args.kwargs["allow_redirects"] is False++ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_client_secret_post_custom_install_sends_secret_in_form(self, mock_post, _allow):+ mock_resp = MagicMock()+ mock_resp.status_code = 200+ mock_resp.ok = True+ mock_resp.json.return_value = {"access_token": "abc", "refresh_token": "def"}+ mock_post.return_value = mock_resp++ installation = self._make_installation(+ sensitive_configuration={+ "dcr_client_id": "confidential-client",+ "dcr_client_secret": "confidential-secret",+ "dcr_token_endpoint_auth_method": "client_secret_post",+ },+ )++ 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"+ sent_form = mock_post.call_args.kwargs["data"]assert sent_form["client_id"] == "confidential-client"assert sent_form["client_secret"] == "confidential-secret"assert sent_form["grant_type"] == "authorization_code"assert sent_form["code_verifier"] == "pkce-verifier"+ assert mock_post.call_args.kwargs["auth"] is None@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))@patch("products.mcp_store.backend.oauth.requests.post")@@ -1045,6 +1257,64 @@ class TestExchangeOauthToken(BaseTest):sent_form = mock_post.call_args[1]["data"]assert "client_secret" not in sent_form+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_client_secret_basic_custom_install_uses_http_basic(self, mock_post, _allow):+ mock_resp = MagicMock()+ mock_resp.status_code = 200+ mock_resp.ok = True+ mock_resp.json.return_value = {"access_token": "abc"}+ mock_post.return_value = mock_resp++ installation = self._make_installation(+ sensitive_configuration={+ "dcr_client_id": "basic-client",+ "dcr_client_secret": "basic-secret",+ "dcr_token_endpoint_auth_method": "client_secret_basic",+ },+ )++ 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://"),+ )++ sent_form = mock_post.call_args.kwargs["data"]+ assert "client_id" not in sent_form+ assert "client_secret" not in sent_form+ assert mock_post.call_args.kwargs["auth"] == ("basic-client", "basic-secret")++ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_token_exchange_includes_resource_indicator(self, mock_post, _allow):+ mock_resp = MagicMock()+ mock_resp.status_code = 200+ mock_resp.ok = True+ mock_resp.json.return_value = {"access_token": "abc"}+ mock_post.return_value = mock_resp++ installation = self._make_installation(+ sensitive_configuration={"dcr_client_id": "public-client"},+ )+ installation.oauth_metadata = {+ "token_endpoint": "https://auth.custom.example.com/token",+ "resource": "https://mcp.custom.example.com/",+ }+ installation.save(update_fields=["oauth_metadata"])++ 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 mock_post.call_args.kwargs["data"]["resource"] == "https://mcp.custom.example.com/"+def test_missing_pkce_verifier_raises(self):installation = self._make_installation(sensitive_configuration={"dcr_client_id": "public-client"},diff --git a/products/mcp_store/backend/test/test_proxy.py b/products/mcp_store/backend/test/test_proxy.pyindex c76a6386cd78..5c8fc383839e 100644--- a/products/mcp_store/backend/test/test_proxy.py+++ b/products/mcp_store/backend/test/test_proxy.py@@ -371,6 +371,92 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert response.status_code == 404+ @patch("products.mcp_store.backend.proxy.httpx.Client")+ def test_proxy_follows_same_origin_mcp_redirect(self, mock_client_cls):+ installation = self._create_installation(+ sensitive_configuration={"api_key": "sk-test-key"},+ url="https://mcp.example.com/mcp",+ )+ redirect_response = MagicMock()+ redirect_response.status_code = 307+ redirect_response.headers = {"location": "/mcp/", "content-type": "text/plain"}+ redirect_response.close = MagicMock()++ final_response = MagicMock()+ final_response.status_code = 200+ final_response.headers = {"content-type": "application/json"}+ final_response.content = b'{"jsonrpc":"2.0","id":1,"result":{}}'++ mock_client = MagicMock()+ mock_client.build_request.return_value = MagicMock()+ mock_client.send.side_effect = [redirect_response, final_response]+ mock_client_cls.return_value = mock_client++ response = self.client.post(+ self._proxy_url(installation.id),+ data={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},+ format="json",+ )++ assert response.status_code == 200+ assert mock_client.send.call_count == 2+ assert mock_client.build_request.call_args_list[0].args[1] == "https://mcp.example.com/mcp"+ assert mock_client.build_request.call_args_list[1].args[1] == "https://mcp.example.com/mcp/"+ assert mock_client.build_request.call_args_list[1].kwargs["headers"]["Authorization"] == "Bearer sk-test-key"+ redirect_response.close.assert_called_once()++ @patch("products.mcp_store.backend.proxy.httpx.Client")+ def test_proxy_does_not_follow_cross_origin_redirect_with_credentials(self, mock_client_cls):+ installation = self._create_installation(+ sensitive_configuration={"api_key": "sk-test-key"},+ url="https://mcp.example.com/mcp",+ )+ redirect_response = MagicMock()+ redirect_response.status_code = 307+ redirect_response.headers = {"location": "https://attacker.example/mcp", "content-type": "text/plain"}+ redirect_response.content = b""++ mock_client = MagicMock()+ mock_client.build_request.return_value = MagicMock()+ mock_client.send.return_value = redirect_response+ mock_client_cls.return_value = mock_client++ response = self.client.post(+ self._proxy_url(installation.id),+ data={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},+ format="json",+ )++ assert response.status_code == 307+ mock_client.send.assert_called_once()+ assert mock_client.build_request.call_args_list[0].kwargs["headers"]["Authorization"] == "Bearer sk-test-key"++ @patch("products.mcp_store.backend.proxy.httpx.Client")+ def test_proxy_does_not_follow_malformed_redirect_with_credentials(self, mock_client_cls):+ installation = self._create_installation(+ sensitive_configuration={"api_key": "sk-test-key"},+ url="https://mcp.example.com/mcp",+ )+ redirect_response = MagicMock()+ redirect_response.status_code = 307+ redirect_response.headers = {"location": "https://mcp.example.com:bad/mcp/", "content-type": "text/plain"}+ redirect_response.content = b""++ mock_client = MagicMock()+ mock_client.build_request.return_value = MagicMock()+ mock_client.send.return_value = redirect_response+ mock_client_cls.return_value = mock_client++ response = self.client.post(+ self._proxy_url(installation.id),+ data={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},+ format="json",+ )++ assert response.status_code == 307+ mock_client.send.assert_called_once()+ assert mock_client.build_request.call_args_list[0].kwargs["headers"]["Authorization"] == "Bearer sk-test-key"+def test_proxy_returns_401_for_oauth_without_access_token(self):installation = self._create_oauth_installation(sensitive_configuration={diff --git a/products/mcp_store/backend/test/test_tools.py b/products/mcp_store/backend/test/test_tools.pyindex 98645a8c2b8b..8dba487026b7 100644--- a/products/mcp_store/backend/test/test_tools.py+++ b/products/mcp_store/backend/test/test_tools.py@@ -120,6 +120,37 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):assert client.delete.calledassert client.delete.call_args.kwargs["headers"]["Mcp-Session-Id"] == "sess-1"+ @patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.tools.httpx.Client")+ def test_fetch_upstream_tools_follows_same_origin_initialize_redirect(+ self, mock_client_cls, _allow_tools, _allow_proxy+ ):+ installation = self._installation(url="https://mcp.example.com/mcp")+ redirect_resp = _build_response(status=307, body="")+ redirect_resp.headers["location"] = "/mcp/"+ initialize_resp = _build_response(+ body=json.dumps({"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2024-11-05"}}),+ session_id="sess-1",+ )+ notify_resp = _build_response(status=202, body="")+ tools_body = json.dumps({"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": "alpha"}]}})+ tools_resp = _build_response(body=tools_body)++ client = MagicMock()+ client.post.side_effect = [redirect_resp, initialize_resp, notify_resp, tools_resp]+ client.delete.return_value = _build_response(status=200, body="")+ mock_client_cls.return_value.__enter__.return_value = client++ tools = fetch_upstream_tools(installation)++ assert [tool["name"] for tool in tools] == ["alpha"]+ assert client.post.call_args_list[0].args[0] == "https://mcp.example.com/mcp"+ assert client.post.call_args_list[1].args[0] == "https://mcp.example.com/mcp/"+ assert client.post.call_args_list[2].args[0] == "https://mcp.example.com/mcp/"+ assert client.post.call_args_list[3].args[0] == "https://mcp.example.com/mcp/"+ assert client.delete.call_args.args[0] == "https://mcp.example.com/mcp/"+@patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))@patch("products.mcp_store.backend.tools.httpx.Client")def test_fetch_upstream_tools_parses_sse_tools_list(self, mock_client_cls, _allow):diff --git a/products/mcp_store/backend/tools.py b/products/mcp_store/backend/tools.pyindex 6ce678f83561..2ac47c529e47 100644--- a/products/mcp_store/backend/tools.py+++ b/products/mcp_store/backend/tools.py@@ -17,7 +17,7 @@ from posthog.security.url_validation import is_url_allowedfrom .models import MCPServerInstallation, MCPServerInstallationToolfrom .oauth import TokenRefreshError, is_token_expiring, refresh_installation_token-from .proxy import build_upstream_auth_headers+from .proxy import build_upstream_auth_headers, validated_same_origin_redirect_urllogger = structlog.get_logger(__name__)@@ -80,26 +80,42 @@ def fetch_upstream_tools(installation: MCPServerInstallation) -> list[dict[str,try:with httpx.Client(timeout=HANDSHAKE_TIMEOUT) as client:- session_id = _mcp_initialize(client, installation.url, base_headers)+ session_id, upstream_url = _mcp_initialize(client, installation.url, base_headers)session_headers = dict(base_headers)if session_id:session_headers["Mcp-Session-Id"] = session_id- _mcp_send_initialized(client, installation.url, session_headers)+ _mcp_send_initialized(client, upstream_url, session_headers)try:- return _mcp_list_tools(client, installation.url, session_headers)+ return _mcp_list_tools(client, upstream_url, session_headers)finally:# Best-effort cleanup so we don't leak sessions upstream. Failures# here are purely janitorial and must not mask real errors above.if session_id:- _mcp_terminate_session(client, installation.url, session_headers)+ _mcp_terminate_session(client, upstream_url, session_headers)except httpx.ConnectError as exc:raise ToolsFetchError("Upstream MCP server unreachable") from excexcept httpx.TimeoutException as exc:raise ToolsFetchError("Upstream MCP server timed out") from exc-def _mcp_initialize(client: httpx.Client, url: str, headers: dict[str, str]) -> str | None:+def _post_with_same_origin_redirect(+ client: httpx.Client,+ url: str,+ *,+ content: bytes,+ headers: dict[str, str],+) -> tuple[httpx.Response, str]:+ response = client.post(url, content=content, headers=headers)+ redirect_url = validated_same_origin_redirect_url(url, response)+ if not redirect_url:+ return response, url++ response.close()+ return client.post(redirect_url, content=content, headers=headers), redirect_url+++def _mcp_initialize(client: httpx.Client, url: str, headers: dict[str, str]) -> tuple[str | None, str]:body = json.dumps({"jsonrpc": "2.0",@@ -113,11 +129,11 @@ def _mcp_initialize(client: httpx.Client, url: str, headers: dict[str, str]) ->}).encode()- response = client.post(url, content=body, headers=headers)+ response, upstream_url = _post_with_same_origin_redirect(client, url, content=body, headers=headers)if response.status_code >= 400:logger.warning("initialize request returned error",- url=url,+ url=upstream_url,status_code=response.status_code,body=response.text[:500],)@@ -131,7 +147,7 @@ def _mcp_initialize(client: httpx.Client, url: str, headers: dict[str, str]) -># Session id is optional per the spec — servers that don't need one still# work with tools/list, so treat a missing header as "no session needed".- return response.headers.get("mcp-session-id")+ return response.headers.get("mcp-session-id"), upstream_urldef _mcp_send_initialized(client: httpx.Client, url: str, headers: dict[str, str]) -> None:@@ -143,7 +159,7 @@ def _mcp_send_initialized(client: httpx.Client, url: str, headers: dict[str, str"""body = json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}}).encode()try:- response = client.post(url, content=body, headers=headers)+ response, _upstream_url = _post_with_same_origin_redirect(client, url, content=body, headers=headers)except httpx.HTTPError as exc:logger.warning("notifications/initialized transport failed; continuing", url=url, error=str(exc))return@@ -159,11 +175,11 @@ def _mcp_send_initialized(client: httpx.Client, url: str, headers: dict[str, strdef _mcp_list_tools(client: httpx.Client, url: str, headers: dict[str, str]) -> list[dict[str, Any]]:body = json.dumps({"jsonrpc": "2.0", "id": _TOOLS_LIST_ID, "method": "tools/list", "params": {}}).encode()- response = client.post(url, content=body, headers=headers)+ response, upstream_url = _post_with_same_origin_redirect(client, url, content=body, headers=headers)if response.status_code >= 400:logger.warning("tools/list request returned error",- url=url,+ url=upstream_url,status_code=response.status_code,body=response.text[:500],)