Skip to content

Commit 2f9173a

Browse files
committed
WIP: feat: redirect uri wildcards
1 parent 631291d commit 2f9173a

File tree

4 files changed

+135
-44
lines changed

4 files changed

+135
-44
lines changed

docs/settings.rst

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,44 @@ assigned ports.
6363
Note that you may override ``Application.get_allowed_schemes()`` to set this on
6464
a per-application basis.
6565

66+
ALLOW_REDIRECT_URI_WILDCARDS
67+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68+
69+
Default: ``False``
70+
71+
SECURITY WARNING: Enabling this setting can introduce security vulnerabilities. Only enable
72+
this setting if you understand the risks. https://datatracker.ietf.org/doc/html/rfc6749#section-3.1.2
73+
states "The redirection endpoint URI MUST be an absolute URI as defined by [RFC3986] Section 4.3." The
74+
intent of the URI restrictions is to prevent open redirects and phishing attacks. If you do enable this
75+
ensure that the wildcards restrict URIs to resources under your control. You are strongly encouragd not
76+
to use this feature in production.
77+
78+
When set to ``True``, the server will allow wildcard characters in the domains
79+
and paths for redirect_uris and post_logout_redirect_uris.
80+
81+
``*`` is the only wildcard character allowed.
82+
83+
``*`` can only be used as a prefix to a domain, must be the first character in
84+
the domain, and cannot be in the top or second level domain. Matching is done using an
85+
endsWith check.
86+
87+
For example,
88+
``https://*.example.com`` is allowed,
89+
``https://*-myproject.example.com`` is allowed,
90+
``https://*.sub.example.com`` is not allowed,
91+
``https://*.com`` is not allowed, and
92+
``https://example.*.com`` is not allowed.
93+
94+
``*`` can also be used as a suffix to a path, must be the last character in the path.
95+
Matching is done using a startsWith check.
96+
97+
For example,
98+
``https://example.com/*`` is allowed, and
99+
``https://example.com/path/*`` is allowed.
100+
101+
This feature is useful for working with CI service such as cloudflare, netlify, and vercel that offer branch
102+
deployments for development previews and user acceptance testing.
103+
66104
ALLOWED_SCHEMES
67105
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68106

oauth2_provider/models.py

Lines changed: 37 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,12 @@ def clean(self):
213213

214214
if redirect_uris:
215215
validator = AllowedURIValidator(
216-
allowed_schemes, name="redirect uri", allow_path=True, allow_query=True
216+
allowed_schemes,
217+
name="redirect uri",
218+
allow_path=True,
219+
allow_query=True,
220+
allow_hostname_wildcard=oauth2_settings.ALLOW_REDIRECT_URI_WILDCARDS,
221+
allow_path_wildcard=oauth2_settings.ALLOW_REDIRECT_URI_WILDCARDS,
217222
)
218223
for uri in redirect_uris:
219224
validator(uri)
@@ -782,55 +787,45 @@ def redirect_to_uri_allowed(uri, allowed_uris):
782787
for allowed_uri in allowed_uris:
783788
parsed_allowed_uri = urlparse(allowed_uri)
784789

790+
if parsed_allowed_uri.scheme != parsed_uri.scheme:
791+
# match failed, continue
792+
continue
793+
794+
""" check hostname """
795+
if parsed_allowed_uri.hostname.startswith("*"):
796+
""" wildcard hostname """
797+
if not parsed_uri.hostname.endswith(parsed_allowed_uri.hostname[1:]):
798+
continue
799+
elif parsed_allowed_uri.hostname != parsed_uri.hostname:
800+
continue
801+
785802
# From RFC 8252 (Section 7.3)
803+
# https://datatracker.ietf.org/doc/html/rfc8252#section-7.3
786804
#
787805
# Loopback redirect URIs use the "http" scheme
788806
# [...]
789807
# The authorization server MUST allow any port to be specified at the
790808
# time of the request for loopback IP redirect URIs, to accommodate
791809
# clients that obtain an available ephemeral port from the operating
792810
# system at the time of the request.
811+
allowed_uri_is_loopback = (parsed_allowed_uri.scheme == "http" and parsed_allowed_uri.hostname in ["127.0.0.1", "::1"])
812+
""" check port """
813+
if not allowed_uri_is_loopback and parsed_allowed_uri.port != parsed_uri.port:
814+
continue
815+
816+
""" check path """
817+
if parsed_allowed_uri.path.endswith("*"):
818+
""" wildcard path """
819+
if not parsed_uri.path.startswith(parsed_allowed_uri.path[:-1]):
820+
continue
821+
elif parsed_allowed_uri.path != parsed_uri.path:
822+
continue
823+
824+
""" check querystring """
825+
aqs_set = set(parse_qsl(parsed_allowed_uri.query))
826+
if not aqs_set.issubset(uqs_set):
827+
continue # circuit break
793828

794-
allowed_uri_is_loopback = (
795-
parsed_allowed_uri.scheme == "http"
796-
and parsed_allowed_uri.hostname in ["127.0.0.1", "::1"]
797-
and parsed_allowed_uri.port is None
798-
)
799-
if (
800-
allowed_uri_is_loopback
801-
and parsed_allowed_uri.scheme == parsed_uri.scheme
802-
and parsed_allowed_uri.hostname == parsed_uri.hostname
803-
and parsed_allowed_uri.path == parsed_uri.path
804-
) or (
805-
parsed_allowed_uri.scheme == parsed_uri.scheme
806-
and parsed_allowed_uri.netloc == parsed_uri.netloc
807-
and parsed_allowed_uri.path == parsed_uri.path
808-
):
809-
aqs_set = set(parse_qsl(parsed_allowed_uri.query))
810-
if aqs_set.issubset(uqs_set):
811-
return True
812-
813-
return False
814-
815-
816-
def is_origin_allowed(origin, allowed_origins):
817-
"""
818-
Checks if a given origin uri is allowed based on the provided allowed_origins configuration.
819-
820-
:param origin: Origin URI to check
821-
:param allowed_origins: A list of Origin URIs that are allowed
822-
"""
823-
824-
parsed_origin = urlparse(origin)
825-
826-
if parsed_origin.scheme not in oauth2_settings.ALLOWED_SCHEMES:
827-
return False
829+
return True
828830

829-
for allowed_origin in allowed_origins:
830-
parsed_allowed_origin = urlparse(allowed_origin)
831-
if (
832-
parsed_allowed_origin.scheme == parsed_origin.scheme
833-
and parsed_allowed_origin.netloc == parsed_origin.netloc
834-
):
835-
return True
836831
return False

oauth2_provider/settings.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@
7171
"REQUEST_APPROVAL_PROMPT": "force",
7272
"ALLOWED_REDIRECT_URI_SCHEMES": ["http", "https"],
7373
"ALLOWED_SCHEMES": ["https"],
74+
"ALLOW_REDIRECT_URI_WILDCARDS": False,
7475
"OIDC_ENABLED": False,
7576
"OIDC_ISS_ENDPOINT": "",
7677
"OIDC_USERINFO_ENDPOINT": "",

oauth2_provider/validators.py

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,16 @@ class URIValidator(URLValidator):
2121
class AllowedURIValidator(URIValidator):
2222
# TODO: find a way to get these associated with their form fields in place of passing name
2323
# TODO: submit PR to get `cause` included in the parent class ValidationError params`
24-
def __init__(self, schemes, name, allow_path=False, allow_query=False, allow_fragments=False):
24+
def __init__(
25+
self,
26+
schemes,
27+
name,
28+
allow_path=False,
29+
allow_query=False,
30+
allow_fragments=False,
31+
allow_hostname_wildcard=False,
32+
allow_path_wildcard=False,
33+
):
2534
"""
2635
:param schemes: List of allowed schemes. E.g.: ["https"]
2736
:param name: Name of the validated URI. It is required for validation message. E.g.: "Origin"
@@ -34,6 +43,8 @@ def __init__(self, schemes, name, allow_path=False, allow_query=False, allow_fra
3443
self.allow_path = allow_path
3544
self.allow_query = allow_query
3645
self.allow_fragments = allow_fragments
46+
self.allow_hostname_wildcard = allow_hostname_wildcard or True
47+
self.allow_path_wildcard = allow_path_wildcard or True
3748

3849
def __call__(self, value):
3950
value = force_str(value)
@@ -68,8 +79,54 @@ def __call__(self, value):
6879
params={"name": self.name, "value": value, "cause": "path not allowed"},
6980
)
7081

82+
if self.allow_hostname_wildcard and "*" in netloc:
83+
domain_parts = netloc.split(".")
84+
if netloc.count("*") > 1:
85+
raise ValidationError(
86+
"%(name)s URI validation error. %(cause)s: %(value)s",
87+
params={"name": self.name, "value": value, "cause": "only one wildcard is allowed in the hostname"},
88+
)
89+
if not netloc.startswith("*"):
90+
raise ValidationError(
91+
"%(name)s URI validation error. %(cause)s: %(value)s",
92+
params={"name": self.name, "value": value, "cause": "wildcards must be at the beginning of the hostname"},
93+
)
94+
if len(domain_parts) < 3:
95+
raise ValidationError(
96+
"%(name)s URI validation error. %(cause)s: %(value)s",
97+
params={"name": self.name, "value": value, "cause": "wildcards cannot be in the top level or second level domain"},
98+
)
99+
100+
# strip the wildcard from the netloc, we'll reassamble the value later to pass to URI Validator
101+
if netloc.startswith("*."):
102+
netloc = netloc[2:]
103+
else:
104+
netloc = netloc[1:]
105+
106+
if self.allow_path_wildcard and "*" in path:
107+
if path.count("*") > 1:
108+
raise ValidationError(
109+
"%(name)s URI validation error. %(cause)s: %(value)s",
110+
params={"name": self.name, "value": value, "cause": "only one wildcard is allowed in the path"},
111+
)
112+
if not path.endswith("*"):
113+
raise ValidationError(
114+
"%(name)s URI validation error. %(cause)s: %(value)s",
115+
params={"name": self.name, "value": value, "cause": "wildcards must be at the end of the path"},
116+
)
117+
# strip the wildcard from the path, we'll reassamble the value later to pass to URI Validator
118+
path = path[:-1]
119+
120+
# we stripped the wildcard from the netloc and path if they were allowed and present since they would fail validation
121+
# we'll reassamble the URI to pass to the URIValidator
122+
reassambled_uri = f"{scheme}://{netloc}{path}"
123+
if query:
124+
reassambled_uri += f"?{query}"
125+
if fragment:
126+
reassambled_uri += f"#{fragment}"
127+
71128
try:
72-
super().__call__(value)
129+
super().__call__(reassambled_uri)
73130
except ValidationError as e:
74131
raise ValidationError(
75132
"%(name)s URI validation error. %(cause)s: %(value)s",

0 commit comments

Comments
 (0)