Skip to content

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

Normalize raw-string redirect URIs through AnyUrl before validation (#6315)

uhhgxg3f50594a4cc1
diff --git a/fastmcp_slim/fastmcp/server/auth/redirect_validation.py b/fastmcp_slim/fastmcp/server/auth/redirect_validation.py
index 6077ba91b..ee920992e 100644
--- a/fastmcp_slim/fastmcp/server/auth/redirect_validation.py
+++ b/fastmcp_slim/fastmcp/server/auth/redirect_validation.py
@@ -8,7 +8,7 @@ import fnmatch
import ipaddress
from urllib.parse import unquote, urlencode, urlparse, urlunparse
-from pydantic import AnyUrl
+from pydantic import AnyUrl, ValidationError
UNSAFE_REDIRECT_URI_SCHEMES = frozenset(
{
@@ -348,6 +348,29 @@ def _is_unsafe_redirect_uri(uri: str) -> bool:
return parsed.scheme.lower() in UNSAFE_REDIRECT_URI_SCHEMES
+def _normalize_redirect_uri(uri: str | AnyUrl) -> str:
+ """Return the canonical string form shared by both input types.
+
+ A plain string never goes through a URL parser, so attacker-controlled
+ spellings read differently through `urlparse` than through the WHATWG
+ rules browsers apply to a 302 Location: `https://evil.com\\.example.com/cb`
+ keeps its backslash, `..` segments survive, `127.1` is not expanded, and
+ trailing C0 characters are not stripped. pydantic's `AnyUrl` performs the
+ WHATWG-style normalization, so re-parsing raw strings through it gives
+ the string form the same parsed value as the `AnyUrl` form.
+
+ Strings that `AnyUrl` cannot express (rare schemes without an authority
+ that pydantic rejects outright) are passed through unchanged; they were
+ already handled by the scheme and pattern checks below.
+ """
+ if isinstance(uri, AnyUrl):
+ return str(uri)
+ try:
+ return str(AnyUrl(uri))
+ except ValidationError:
+ return uri
+
+
def matches_allowed_pattern(uri: str, pattern: str) -> bool:
"""Securely check if a URI matches an allowed pattern with wildcard support.
@@ -370,6 +393,16 @@ def matches_allowed_pattern(uri: str, pattern: str) -> bool:
Returns:
True if the URI matches the pattern
"""
+ # Capture the raw authority and path before normalization: resolving
+ # dot-segments away (which AnyUrl normalization does) must not turn a
+ # rejected traversal spelling into a matching ordinary path.
+ try:
+ raw_parsed = urlparse(uri)
+ except ValueError:
+ return False
+ raw_path = raw_parsed.path
+
+ uri = _normalize_redirect_uri(uri)
try:
uri_parsed = urlparse(uri)
pattern_parsed = urlparse(pattern)
@@ -385,13 +418,29 @@ def matches_allowed_pattern(uri: str, pattern: str) -> bool:
if uri_parsed.username is not None or uri_parsed.password is not None:
return False
+ # SECURITY: Reject URIs whose raw authority contains a backslash.
+ # WHATWG URL parsing (which pydantic's AnyUrl applies above) ends the
+ # authority at `\`, so `https://trusted.example\@attacker.example/cb`
+ # normalizes to host `trusted.example` with `@attacker.example/cb` as
+ # the path -- the userinfo check no longer sees an `@`. But the raw
+ # string round-trips through callers that do not apply WHATWG rules:
+ # `RedirectResponse` percent-encodes the backslash, and a browser then
+ # reads `trusted.example%5C` as userinfo with host `attacker.example`,
+ # leaving the allowlisted origin entirely. `\` is a forbidden host code
+ # point, so no legitimate redirect URI carries one in its authority.
+ if "\\" in raw_parsed.netloc:
+ return False
+
# SECURITY: Reject URIs with dot-segments in the path.
# fnmatch's `*` matches across `/`, so a pattern like `/oauth/callback/*`
# would accept `/oauth/callback/../../steal`; a browser receiving that in
# a 302 Location resolves the dot-segments and lands at `/steal`, outside
# the intended allowlist prefix. Reject at validation time so the stored
- # redirect_uri cannot later be emitted verbatim in a redirect.
- if _has_dot_segments(uri_parsed.path):
+ # redirect_uri cannot later be emitted verbatim in a redirect. Checked on
+ # both the raw and the normalized path: normalization resolves the
+ # segments away, so a normalized-only check would miss the raw spelling,
+ # and a raw-only check would miss encoded variants AnyUrl decodes.
+ if _has_dot_segments(uri_parsed.path) or _has_dot_segments(raw_path):
return False
# Scheme must match exactly
@@ -452,7 +501,18 @@ def is_redirect_uri_allowed_for_application_type(
registered-client record carries when the field was never set β€” is treated
the same way.
"""
- uri_str = str(redirect_uri)
+ # SECURITY: Reject URIs whose raw authority contains a backslash (same
+ # WHATWG-raw divergence as matches_allowed_pattern):
+ # `http://localhost\@attacker.example/cb` normalizes to a loopback host
+ # and passes the native-client check, but `RedirectResponse` percent-
+ # encodes the backslash and a browser then reads host `attacker.example`.
+ try:
+ if "\\" in urlparse(str(redirect_uri)).netloc:
+ return False
+ except ValueError:
+ return False
+
+ uri_str = _normalize_redirect_uri(redirect_uri)
if _is_unsafe_redirect_uri(uri_str):
return False
@@ -492,6 +552,9 @@ def validate_redirect_uri(
if redirect_uri is None:
return True # None is allowed (will use client's default)
+ # Keep the raw string form: pattern matching below re-parses it through
+ # AnyUrl normalization itself, and the dot-segment rejection there must
+ # see the caller's original spelling.
uri_str = str(redirect_uri)
if _is_unsafe_redirect_uri(uri_str):
diff --git a/tests/server/auth/test_redirect_validation.py b/tests/server/auth/test_redirect_validation.py
index 43e21a944..b0eeab8b0 100644
--- a/tests/server/auth/test_redirect_validation.py
+++ b/tests/server/auth/test_redirect_validation.py
@@ -12,6 +12,7 @@ from fastmcp.server.auth.redirect_validation import (
DEFAULT_LOCALHOST_PATTERNS,
add_query_params,
build_client_redirect,
+ is_redirect_uri_allowed_for_application_type,
matches_allowed_pattern,
replace_query_param,
validate_redirect_uri,
@@ -642,3 +643,141 @@ class TestDefaultPatterns:
assert not validate_redirect_uri(
"https://claude.ai/api/mcp/auth_callback", DEFAULT_LOCALHOST_PATTERNS
)
+
+
+class TestRawStringNormalization:
+ """Raw-string redirect URIs must validate identically to the AnyUrl form.
+
+ Browsers parse a 302 Location with WHATWG rules, and pydantic's AnyUrl
+ normalizes the same way (backslash becomes a path separator, dot-segments
+ are resolved, IPv4 shorthand is expanded, trailing C0 characters are
+ stripped). A plain string skips that parser, so attacker-controlled
+ spellings matched allowlist patterns that the parsed form would have
+ failed (#6295).
+ """
+
+ @pytest.mark.parametrize(
+ "uri,pattern",
+ [
+ (r"https://evil.com\.example.com/cb", "https://*.example.com/*"),
+ (r"https://app.example.com/cb/..\steal", "https://app.example.com/cb/*"),
+ ("https://app.example.com/cb/.. ", "https://app.example.com/cb/*"),
+ ],
+ )
+ def test_raw_string_rejects_whatwg_ambiguous_spellings(self, uri, pattern):
+ assert not matches_allowed_pattern(uri, pattern)
+ # The parsed (AnyUrl) form already failed the same pattern; the two
+ # input forms must agree.
+ assert not matches_allowed_pattern(str(AnyUrl(uri)), pattern)
+
+ def test_raw_string_rejected_by_validate_redirect_uri(self):
+ patterns = ["https://*.example.com/*"]
+ uri = r"https://evil.com\.example.com/cb"
+ assert not validate_redirect_uri(uri, patterns)
+ assert not validate_redirect_uri(AnyUrl(uri), patterns)
+
+ def test_web_application_type_rejects_ipv4_shorthand(self):
+ # `https://127.1/cb` normalizes to the loopback `127.0.0.1`, so a
+ # "web" client (which requires a non-loopback https host) must be
+ # rejected in both input forms.
+ assert not is_redirect_uri_allowed_for_application_type(
+ "https://127.1/cb", "web"
+ )
+ assert not is_redirect_uri_allowed_for_application_type(
+ AnyUrl("https://127.1/cb"), "web"
+ )
+
+ def test_native_application_type_rejects_backslash_localhost(self):
+ # `http://evil.com\.localhost/cb` keeps the loopback-suffix host only
+ # in the un-normalized form; normalized it is `evil.com`, not loopback.
+ assert not is_redirect_uri_allowed_for_application_type(
+ r"http://evil.com\.localhost/cb", "native"
+ )
+ assert not is_redirect_uri_allowed_for_application_type(
+ AnyUrl(r"http://evil.com\.localhost/cb"), "native"
+ )
+
+ def test_dot_segments_still_rejected_after_normalization(self):
+ # Normalization resolves dot-segments away, so the raw spelling must
+ # still be rejected: a normalized-only check would turn a rejected
+ # traversal into a matching ordinary path.
+ patterns = ["https://app.example.com/oauth/callback/*"]
+ assert not validate_redirect_uri(
+ "https://app.example.com/oauth/callback/./foo", patterns
+ )
+ assert not validate_redirect_uri(
+ "https://app.example.com/oauth/callback/foo/..", patterns
+ )
+ assert not matches_allowed_pattern(
+ "https://app.example.com/oauth/callback/./foo", patterns[0]
+ )
+
+ def test_legitimate_raw_strings_unchanged(self):
+ # Ordinary http(s) redirect URIs validate exactly as before.
+ assert validate_redirect_uri(
+ "http://localhost:3000/callback", ["http://localhost:*"]
+ )
+ assert validate_redirect_uri(
+ "https://app.example.com/cb", ["https://*.example.com/*"]
+ )
+ # Custom schemes that AnyUrl cannot express are passed through
+ # unchanged and keep their previous classification.
+ assert is_redirect_uri_allowed_for_application_type(
+ "com.example.app:/callback", "native"
+ )
+ assert is_redirect_uri_allowed_for_application_type(
+ "urn:ietf:wg:oauth:2.0:oob", "native"
+ )
+ assert is_redirect_uri_allowed_for_application_type(
+ "myapp://callback", "native"
+ )
+
+
+class TestBackslashAuthorityRejects:
+ r"""A backslash in the raw authority must be rejected outright.
+
+ WHATWG parsing (pydantic's AnyUrl, and any browser reading a 302
+ Location) ends the authority at a backslash, so
+ ``https://trusted.example\@attacker.example/cb`` normalizes to host
+ ``trusted.example`` with ``@attacker.example/cb`` as the path and would
+ pass the pattern check. But the raw string is what callers emit:
+ ``RedirectResponse`` percent-encodes the backslash, and a browser then
+ reads ``trusted.example%5C`` as userinfo with host ``attacker.example``
+ -- outside the allowlisted origin. Both spellings were rejected by
+ the pre-normalization implementation; keep them rejected (#6295).
+ """
+
+ @pytest.mark.parametrize(
+ "uri,pattern",
+ [
+ (
+ "https://trusted.example\\@attacker.example/cb",
+ "https://trusted.example/*",
+ ),
+ ("http://localhost\\@attacker.example/cb", "http://localhost:*"),
+ ],
+ )
+ def test_backslash_authority_pattern_rejected(self, uri, pattern):
+ assert not matches_allowed_pattern(uri, pattern)
+
+ @pytest.mark.parametrize(
+ "uri,application_type",
+ [
+ ("http://localhost\\@attacker.example/cb", "native"),
+ ("https://trusted.example\\@attacker.example/cb", "web"),
+ ],
+ )
+ def test_backslash_authority_application_type_rejected(self, uri, application_type):
+ assert not is_redirect_uri_allowed_for_application_type(uri, application_type)
+
+ def test_legitimate_uris_still_allowed(self):
+ # No backslash in the authority: ordinary behavior is intact.
+ assert matches_allowed_pattern(
+ "https://trusted.example/cb", "https://trusted.example/*"
+ )
+ assert matches_allowed_pattern(
+ "http://localhost:3000/callback", "http://localhost:*"
+ )
+ assert is_redirect_uri_allowed_for_application_type(
+ "http://localhost:8123/callback", "native"
+ )