Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

fix(auth): preserve DNS resolver order when deduplicating resolved IP addresses (#5151) (#5157)

Tarek Mohamed779eb44737de
diff --git a/fastmcp_slim/fastmcp/server/auth/ssrf.py b/fastmcp_slim/fastmcp/server/auth/ssrf.py
index 4519e74f9..40da15a47 100644
--- a/fastmcp_slim/fastmcp/server/auth/ssrf.py
+++ b/fastmcp_slim/fastmcp/server/auth/ssrf.py
@@ -193,7 +193,7 @@ async def resolve_hostname(hostname: str, port: int = 443) -> list[str]:
hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM
),
)
- ips = list({info[4][0] for info in infos})
+ ips = list(dict.fromkeys(info[4][0] for info in infos))
if not ips:
raise SSRFError(f"DNS resolution returned no addresses for {hostname}")
return ips # ty: ignore[invalid-return-type]
diff --git a/tests/server/auth/test_ssrf_protection.py b/tests/server/auth/test_ssrf_protection.py
index 8d23ae501..a7271cf88 100644
--- a/tests/server/auth/test_ssrf_protection.py
+++ b/tests/server/auth/test_ssrf_protection.py
@@ -14,6 +14,7 @@ from fastmcp.server.auth.ssrf import (
SSRFError,
SSRFFetchError,
is_ip_allowed,
+ resolve_hostname,
ssrf_safe_fetch,
validate_url,
)
@@ -139,6 +140,26 @@ class TestValidateURL:
with pytest.raises(SSRFError, match="must use HTTPS"):
await validate_url("http://example.com/path")
+ async def test_resolve_hostname_preserves_resolver_order(self):
+ """Resolved addresses should keep getaddrinfo order after deduplication."""
+ infos = [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443)),
+ (
+ socket.AF_INET6,
+ socket.SOCK_STREAM,
+ 6,
+ "",
+ ("2001:4860:4860::8888", 443, 0, 0),
+ ),
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443)),
+ ]
+
+ with patch("socket.getaddrinfo", return_value=infos):
+ assert await resolve_hostname("example.com") == [
+ "93.184.216.34",
+ "2001:4860:4860::8888",
+ ]
+
async def test_missing_host_rejected(self):
"""URLs without host should be rejected."""
with pytest.raises(SSRFError, match="must have a host"):