🚀 The fast, Pythonic way to build MCP servers and clients.
Fix loopback redirect URI port matching per RFC 8252 §7.3 (#3589)
Rushabh Doshi204e566227d0
diff --git a/src/fastmcp/server/auth/cimd.py b/src/fastmcp/server/auth/cimd.pyindex caef56f96..714de99e8 100644--- a/src/fastmcp/server/auth/cimd.py+++ b/src/fastmcp/server/auth/cimd.py@@ -16,7 +16,6 @@ This module provides:from __future__ import annotations-import fnmatchimport jsonimport timefrom collections.abc import Mapping@@ -28,6 +27,7 @@ from urllib.parse import urlparsefrom pydantic import AnyHttpUrl, BaseModel, Field, field_validator+from fastmcp.server.auth.redirect_validation import matches_allowed_patternfrom fastmcp.server.auth.ssrf import (SSRFError,SSRFFetchError,@@ -422,6 +422,9 @@ class CIMDFetcher:def validate_redirect_uri(self, doc: CIMDDocument, redirect_uri: str) -> bool:"""Validate that a redirect_uri is allowed by the CIMD document.+ Uses component-level matching (scheme, host, port, path) which correctly+ handles RFC 8252 §7.3 loopback port flexibility and wildcard patterns.+Args:doc: The CIMD documentredirect_uri: The redirect URI to validate@@ -438,14 +441,9 @@ class CIMDFetcher:for allowed in doc.redirect_uris:allowed_str = allowed.rstrip("/")- if redirect_uri == allowed_str:+ if matches_allowed_pattern(redirect_uri, allowed_str):return True- # Check for wildcard port matching (http://localhost:*/callback)- if "*" in allowed_str:- if fnmatch.fnmatch(redirect_uri, allowed_str):- return True-return Falsediff --git a/src/fastmcp/server/auth/redirect_validation.py b/src/fastmcp/server/auth/redirect_validation.pyindex 4d011416f..7e55a477b 100644--- a/src/fastmcp/server/auth/redirect_validation.py+++ b/src/fastmcp/server/auth/redirect_validation.py@@ -68,6 +68,17 @@ def _match_host(uri_host: str | None, pattern_host: str | None) -> bool:return uri_host == pattern_host+def _is_loopback_host(host: str | None) -> bool:+ """Check if a host is a loopback address.++ Per RFC 8252 §7.3, loopback addresses include localhost, 127.0.0.1, and ::1.+ """+ if not host:+ return False+ host = host.lower()+ return host in ("localhost", "127.0.0.1", "::1")++def _match_port(uri_port: str | None,pattern_port: str | None,@@ -164,9 +175,10 @@ def matches_allowed_pattern(uri: str, pattern: str) -> bool:if not _match_host(uri_host, pattern_host):return False- # Port must match (with * wildcard support)- if not _match_port(uri_port, pattern_port, uri_parsed.scheme.lower()):- return False+ # RFC 8252 §7.3: loopback patterns without an explicit port match any port+ if not (_is_loopback_host(pattern_host) and pattern_port is None):+ if not _match_port(uri_port, pattern_port, uri_parsed.scheme.lower()):+ return False# Path must match (with fnmatch wildcards)return _match_path(uri_parsed.path, pattern_parsed.path)diff --git a/tests/server/auth/test_cimd.py b/tests/server/auth/test_cimd.pyindex 3ed99857a..d9bfe1154 100644--- a/tests/server/auth/test_cimd.py+++ b/tests/server/auth/test_cimd.py@@ -179,6 +179,16 @@ class TestCIMDFetcher:assert fetcher.validate_redirect_uri(doc, "http://localhost:8080/callback")assert not fetcher.validate_redirect_uri(doc, "http://localhost:3000/other")+ def test_validate_redirect_uri_loopback_no_port(self, fetcher: CIMDFetcher):+ """RFC 8252 §7.3: loopback URI without port should match any port."""+ doc = CIMDDocument(+ client_id=AnyHttpUrl("https://example.com/client.json"),+ redirect_uris=["http://localhost/callback", "http://127.0.0.1/callback"],+ )+ assert fetcher.validate_redirect_uri(doc, "http://localhost:51353/callback")+ assert fetcher.validate_redirect_uri(doc, "http://127.0.0.1:3000/callback")+ assert not fetcher.validate_redirect_uri(doc, "http://localhost:51353/other")+class TestCIMDFetcherHTTP:"""Tests for CIMDFetcher HTTP fetching (using httpx mock).diff --git a/tests/server/auth/test_oauth_proxy_redirect_validation.py b/tests/server/auth/test_oauth_proxy_redirect_validation.pyindex 47ecfbe8d..a938488de 100644--- a/tests/server/auth/test_oauth_proxy_redirect_validation.py+++ b/tests/server/auth/test_oauth_proxy_redirect_validation.py@@ -188,6 +188,30 @@ class TestProxyDCRClient:with pytest.raises(InvalidRedirectUriError):client.validate_redirect_uri(None)+ def test_cimd_loopback_no_port_matches_dynamic_port(self):+ """RFC 8252 §7.3: CIMD redirect_uris without port match any loopback port."""+ cimd_doc = CIMDDocument(+ client_id=AnyHttpUrl("https://example.com/client.json"),+ redirect_uris=[+ "http://localhost/callback",+ "http://127.0.0.1/callback",+ ],+ )+ client = ProxyDCRClient(+ client_id="https://example.com/client.json",+ client_secret=None,+ redirect_uris=None,+ cimd_document=cimd_doc,+ )++ # Dynamic ports should be accepted per RFC 8252 §7.3+ assert client.validate_redirect_uri(AnyUrl("http://localhost:51353/callback"))+ assert client.validate_redirect_uri(AnyUrl("http://127.0.0.1:3000/callback"))++ # Wrong path should still be rejected+ with pytest.raises(InvalidRedirectUriError):+ client.validate_redirect_uri(AnyUrl("http://localhost:51353/other"))+def test_cimd_empty_proxy_allowlist_rejects_redirect_uri(self):"""An explicit empty proxy allowlist should reject all CIMD redirect URIs."""cimd_doc = CIMDDocument(diff --git a/tests/server/auth/test_redirect_validation.py b/tests/server/auth/test_redirect_validation.pyindex 10945d2fb..18d885023 100644--- a/tests/server/auth/test_redirect_validation.py+++ b/tests/server/auth/test_redirect_validation.py@@ -168,6 +168,64 @@ class TestSecurityBypass:assert not matches_allowed_pattern("http://example.com:3000/callback", pattern)+class TestLoopbackPortMatching:+ """Test RFC 8252 §7.3: loopback URIs with no port in pattern match any port."""++ def test_localhost_no_port_matches_any_port(self):+ """Pattern http://localhost/callback should match any port on localhost."""+ pattern = "http://localhost/callback"+ assert matches_allowed_pattern("http://localhost:51353/callback", pattern)+ assert matches_allowed_pattern("http://localhost:3000/callback", pattern)+ assert matches_allowed_pattern("http://localhost:80/callback", pattern)++ def test_localhost_no_port_no_path_matches_any_port(self):+ """Pattern http://localhost should match any port on localhost."""+ pattern = "http://localhost"+ assert matches_allowed_pattern("http://localhost:51353", pattern)+ assert matches_allowed_pattern("http://localhost:3000/callback", pattern)++ def test_127_0_0_1_no_port_matches_any_port(self):+ """Pattern http://127.0.0.1/callback should match any port on 127.0.0.1."""+ pattern = "http://127.0.0.1/callback"+ assert matches_allowed_pattern("http://127.0.0.1:51353/callback", pattern)+ assert matches_allowed_pattern("http://127.0.0.1:3000/callback", pattern)++ def test_ipv6_loopback_no_port_matches_any_port(self):+ """Pattern http://[::1]/callback should match any port on [::1]."""+ pattern = "http://[::1]/callback"+ assert matches_allowed_pattern("http://[::1]:51353/callback", pattern)+ assert matches_allowed_pattern("http://[::1]:3000/callback", pattern)++ def test_non_loopback_no_port_requires_default_port(self):+ """Non-loopback patterns without port should still require default port."""+ pattern = "http://example.com/callback"+ # Should only match port 80 (default for HTTP)+ assert matches_allowed_pattern("http://example.com/callback", pattern)+ assert matches_allowed_pattern("http://example.com:80/callback", pattern)+ assert not matches_allowed_pattern("http://example.com:3000/callback", pattern)++ def test_loopback_explicit_port_requires_exact_match(self):+ """Loopback patterns with an explicit port should still require exact match."""+ pattern = "http://localhost:8080/callback"+ assert matches_allowed_pattern("http://localhost:8080/callback", pattern)+ assert not matches_allowed_pattern("http://localhost:3000/callback", pattern)++ def test_loopback_no_port_still_checks_scheme(self):+ """Scheme must still match even for loopback URIs."""+ pattern = "http://localhost/callback"+ assert not matches_allowed_pattern("https://localhost:3000/callback", pattern)++ def test_loopback_no_port_still_checks_host(self):+ """Host must still match even for loopback URIs."""+ pattern = "http://localhost/callback"+ assert not matches_allowed_pattern("http://example.com:3000/callback", pattern)++ def test_loopback_no_port_still_checks_path(self):+ """Path must still match even for loopback URIs."""+ pattern = "http://localhost/callback"+ assert not matches_allowed_pattern("http://localhost:3000/other", pattern)++class TestDefaultPatterns:"""Test the default localhost patterns constant."""