Skip to content

Commit 603e90d

Browse files
committed
WIP: feat: redirect uri wildcards
1 parent b48fd8b commit 603e90d

File tree

5 files changed

+131
-23
lines changed

5 files changed

+131
-23
lines changed

docs/settings.rst

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,39 @@ 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+
95+
96+
This feature is useful for working with CI service such as cloudflare, netlify, and vercel that offer branch
97+
deployments for development previews and user acceptance testing.
98+
6699
ALLOWED_SCHEMES
67100
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68101

oauth2_provider/models.py

Lines changed: 38 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,11 @@ 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,
217221
)
218222
for uri in redirect_uris:
219223
validator(uri)
@@ -227,7 +231,11 @@ def clean(self):
227231
allowed_origins = self.allowed_origins.strip().split()
228232
if allowed_origins:
229233
# oauthlib allows only https scheme for CORS
230-
validator = AllowedURIValidator(oauth2_settings.ALLOWED_SCHEMES, "allowed origin")
234+
validator = AllowedURIValidator(
235+
oauth2_settings.ALLOWED_SCHEMES,
236+
"allowed origin",
237+
allow_hostname_wildcard=oauth2_settings.ALLOW_REDIRECT_URI_WILDCARDS,
238+
)
231239
for uri in allowed_origins:
232240
validator(uri)
233241

@@ -782,35 +790,43 @@ def redirect_to_uri_allowed(uri, allowed_uris):
782790
for allowed_uri in allowed_uris:
783791
parsed_allowed_uri = urlparse(allowed_uri)
784792

793+
if parsed_allowed_uri.scheme != parsed_uri.scheme:
794+
# match failed, continue
795+
continue
796+
797+
""" check hostname """
798+
if oauth2_settings.ALLOW_REDIRECT_URI_WILDCARDS and parsed_allowed_uri.hostname.startswith("*"):
799+
""" wildcard hostname """
800+
if not parsed_uri.hostname.endswith(parsed_allowed_uri.hostname[1:]):
801+
continue
802+
elif parsed_allowed_uri.hostname != parsed_uri.hostname:
803+
continue
804+
785805
# From RFC 8252 (Section 7.3)
806+
# https://datatracker.ietf.org/doc/html/rfc8252#section-7.3
786807
#
787808
# Loopback redirect URIs use the "http" scheme
788809
# [...]
789810
# The authorization server MUST allow any port to be specified at the
790811
# time of the request for loopback IP redirect URIs, to accommodate
791812
# clients that obtain an available ephemeral port from the operating
792813
# system at the time of the request.
814+
allowed_uri_is_loopback = parsed_allowed_uri.scheme == "http" and parsed_allowed_uri.hostname in [
815+
"127.0.0.1",
816+
"::1",
817+
]
818+
""" check port """
819+
if not allowed_uri_is_loopback and parsed_allowed_uri.port != parsed_uri.port:
820+
continue
793821

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
822+
""" check path """
823+
if parsed_allowed_uri.path != parsed_uri.path:
824+
continue
812825

813-
return False
826+
""" check querystring """
827+
aqs_set = set(parse_qsl(parsed_allowed_uri.query))
828+
if not aqs_set.issubset(uqs_set):
829+
continue # circuit break
814830

815831

816832
def is_origin_allowed(origin, allowed_origins):
@@ -833,4 +849,5 @@ def is_origin_allowed(origin, allowed_origins):
833849
and parsed_allowed_origin.netloc == parsed_origin.netloc
834850
):
835851
return True
852+
836853
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: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
from django.core.validators import URLValidator
66
from django.utils.encoding import force_str
77

8+
from .settings import oauth2_settings
9+
810

911
class URIValidator(URLValidator):
1012
scheme_re = r"^(?:[a-z][a-z0-9\.\-\+]*)://"
@@ -21,7 +23,15 @@ class URIValidator(URLValidator):
2123
class AllowedURIValidator(URIValidator):
2224
# TODO: find a way to get these associated with their form fields in place of passing name
2325
# 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):
26+
def __init__(
27+
self,
28+
schemes,
29+
name,
30+
allow_path=False,
31+
allow_query=False,
32+
allow_fragments=False,
33+
allow_hostname_wildcard=False,
34+
):
2535
"""
2636
:param schemes: List of allowed schemes. E.g.: ["https"]
2737
:param name: Name of the validated URI. It is required for validation message. E.g.: "Origin"
@@ -34,6 +44,7 @@ def __init__(self, schemes, name, allow_path=False, allow_query=False, allow_fra
3444
self.allow_path = allow_path
3545
self.allow_query = allow_query
3646
self.allow_fragments = allow_fragments
47+
self.allow_hostname_wildcard = allow_hostname_wildcard
3748

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

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

tests/test_oidc_views.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,8 @@ def test_validate_logout_request(oidc_tokens, public_application, rp_settings):
299299
post_logout_redirect_uri="http://other.org",
300300
)
301301

302+
# TODO: test wildcards
303+
302304

303305
@pytest.mark.django_db(databases=retrieve_current_databases())
304306
@pytest.mark.parametrize("ALWAYS_PROMPT", [True, False])

0 commit comments

Comments
 (0)