Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222---title: redirect_validationsidebarTitle: redirect_validation---
# `fastmcp.server.auth.redirect_validation`
Utilities for validating client redirect URIs in OAuth flows.
This module provides secure redirect URI validation with wildcard support,protecting against userinfo-based bypass attacks like http://localhost@evil.com.
## Functions
### `add_query_params` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/auth/redirect_validation.py#L23" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonadd_query_params(url: str, params: dict[str, str]) -> str```
Append query parameters to a URL while preserving existing parameters.
The existing query string is appended to verbatim rather than decodedand re-serialized, since registered redirect URIs may carry opaque orsigned query strings whose exact bytes matter to the receiving client(for example, a valueless `?flag` must not become `?flag=`, andnon-UTF-8 percent-encoded sequences must not be replaced).
### `replace_query_param` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/auth/redirect_validation.py#L38" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonreplace_query_param(url: str, key: str, value: str) -> str```
Replace the first occurrence of `key` in a URL's query string in place.
Like `add_query_params`, this does not round-trip the query through`parse_qsl`/`urlencode`: every segment other than the matched one ispassed through byte-for-byte, so opaque or non-UTF-8 percent-encodedvalues elsewhere in the query are left untouched. Only the matchedsegment's encoding is replaced (with `key=value`, freshly`urlencode`d). If `key` is not present, it is appended, matching`add_query_params`'s behavior.
### `build_client_redirect` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/auth/redirect_validation.py#L68" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonbuild_client_redirect(url: str, params: dict[str, str]) -> str```
Build a client-facing authorization redirect that carries exactly one `iss`.
Every redirect this server sends back to an OAuth client from theauthorization endpoint -- success (carrying `code`) or error (carrying`error`) -- must carry the proxy's RFC 9207 issuer exactly once (RFC6749 §3.1 forbids a response parameter from appearing more than once).A registered redirect_uri can legitimately carry its own `iss` queryparameter already (e.g. `https://client.example/callback?iss=tenant`),so blindly appending the server's issuer on top of that would duplicateit -- this is what every client-facing redirect site must get right,and the reason this helper exists instead of five call sites eachreimplementing the same invariant by hand.
`params` is appended to `url` via `add_query_params` (verbatim, withoutre-encoding the existing query -- see that function's docstring), and`iss` is then set idempotently via `replace_query_param`: an existingoccurrence -- whether contributed by the registered redirect_uri oralready present in `url` -- is overwritten with the canonical value;otherwise `iss` is appended.
`iss` is keyword-only and required so a caller cannot forget to passit. `params` must not itself contain an `"iss"` key -- pass it via the`iss` keyword instead, so there is exactly one place the value can comefrom.
**Args:**- `url`: The redirect target -- normally the client's registeredredirect_uri.- `params`: The response parameters to append (e.g. `code`/`state`, or`error`/`error_description`). Must not include `"iss"`.- `iss`: The canonical RFC 9207 issuer, byte-for-byte equal to thediscovery document's `issuer` (`str(self.base_url)` /`self._issuer` -- never the rstripped `self._base_url`).
**Returns:**- `url` with `params` appended and exactly one `iss` query parameter- set to `iss`.
### `is_loopback_host` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/auth/redirect_validation.py#L174" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonis_loopback_host(host: str | None) -> bool```
Check if a host is a loopback address.
Per RFC 8252 §7.3, loopback covers the whole reserved loopback range, notjust the two familiar literals: IPv4 `127.0.0.0/8` (so `127.0.0.2` and`127.5.5.5` are loopback just as much as `127.0.0.1`) and IPv6 `::1`. IPhosts are therefore classified with `ipaddress.ip_address().is_loopback`rather than string equality — checking only `127.0.0.1` would let a webclient register `https://127.0.0.2/callback` and slip past thenon-loopback requirement.
Names are handled per RFC 6761 §6.3, which reserves the entire `localhost`namespace for the local machine: the exact name `localhost` *and* anysubdomain of it (`app.localhost`, `api.app.localhost`). `.localhost` is areserved TLD that cannot be registered, so a subdomain of it always resolvesto the loopback interface and must count as loopback in both directions —otherwise a web client could register `https://app.localhost/callback` andslip past the non-loopback requirement, while a native client using`http://app.localhost:3000/callback` would be wrongly rejected.
The suffix test is anchored on a leading dot so it cannot be spoofed by aregistrable domain: `localhost.evil.com` and `notlocalhost` are ordinarypublic names and are *not* loopback.
Hosts are also normalized before classification: bracketed IPv6 literals(`[::1]`) are unwrapped, and a single trailing dot (the absolute/FQDN form,e.g. `localhost.` or `127.0.0.1.`) is stripped, since it denotes the samehost. Non-IP hosts fall through to the name check without raising.
### `matches_allowed_pattern` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/auth/redirect_validation.py#L302" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonmatches_allowed_pattern(uri: str, pattern: str) -> bool```
Securely check if a URI matches an allowed pattern with wildcard support.
This function parses both the URI and pattern as URLs, comparing eachcomponent separately to prevent bypass attacks like userinfo injection.
Patterns support wildcards:- http://localhost:* matches any localhost port- http://127.0.0.1:* matches any 127.0.0.1 port- https://*.example.com/* matches any subdomain of example.com- https://app.example.com/auth/* matches any path under /auth/
Security: Rejects URIs with userinfo (user:pass@host) which could bypassnaive string matching (e.g., http://localhost@evil.com).
**Args:**- `uri`: The redirect URI to validate- `pattern`: The allowed pattern (may contain wildcards)
**Returns:**- True if the URI matches the pattern
### `is_redirect_uri_allowed_for_application_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/auth/redirect_validation.py#L369" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonis_redirect_uri_allowed_for_application_type(redirect_uri: str | AnyUrl, application_type: str | None) -> bool```
Check a redirect URI against RFC 7591 / SEP-837 `application_type` rules.
`application_type` governs which redirect URIs a Dynamically RegisteredClient may use (RFC 7591 §2, OpenID Connect Dynamic Client Registration §2):
- `"web"` clients must use `https` redirect URIs on a non-loopback host. Loopback `http`, `https://localhost`, and app/custom schemes are rejected. This is the restriction SEP-837 actually asks for.- `"native"` clients keep every scheme FastMCP already allowed, except that `http` is restricted to loopback hosts (RFC 8252 §7.3, any port). App and private-use schemes pass through untouched: `vscode://`, `com.example.app:/callback`, `myapp://callback`, `urn:ietf:wg:oauth:2.0:oob`.
Deliberately absent: any attempt to classify a native client's scheme as"private-use" versus "a network transport". There is no sound test. The IANAregistry cannot separate them — `vscode` is registered *because* it is anapp-dispatch scheme, alongside transports like `coap` and `smb` — andreverse-domain notation fails too, since `iris.beep` and`microsoft.windows.camera` are registered while `myapp` is not. Everyformulation either rejects schemes real MCP clients depend on or admits theones it meant to exclude, so native scheme filtering is left to theunsafe-scheme check below.
Unsafe browser schemes (`javascript:`, `data:`, `file:`, `vbscript:`) arealways rejected regardless of `application_type`. That check predates thisfunction and is unchanged by it.
The MCP SDK defaults `application_type` to `"native"` because MCP clientstypically register loopback redirect URIs, so omitting the field preservesthe behavior clients relied on before this check existed. `None` — which aregistered-client record carries when the field was never set — is treatedthe same way.
### `validate_redirect_uri` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/auth/redirect_validation.py#L427" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonvalidate_redirect_uri(redirect_uri: str | AnyUrl | None, allowed_patterns: list[str] | None) -> bool```
Validate a redirect URI against allowed patterns.
**Args:**- `redirect_uri`: The redirect URI to validate- `allowed_patterns`: List of allowed patterns. If None, ordinary URIs are allowed for DCR compatibility, while unsafe browser schemes are rejected. If empty list, no URIs are allowed. To restrict to localhost only, explicitly pass DEFAULT_LOCALHOST_PATTERNS.
**Returns:**- True if the redirect URI is allowed