Skip to content

Commit a0f8fa1

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

File tree

8 files changed

+419
-25
lines changed

8 files changed

+419
-25
lines changed

CHANGELOG.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,18 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
55
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66

7-
<!--
7+
88
## [unreleased]
99
### Added
10-
* Support for specifying client secret hasher via CLIENT_SECRET_HASHER setting.
10+
* Support for Wildcard Origin and Redirect URIs, https://github.com/jazzband/django-oauth-toolkit/issues/1506
11+
<!--
1112
### Changed
1213
### Deprecated
1314
### Removed
1415
### Fixed
1516
### Security
16-
-->
17+
-->
18+
1719

1820
## [3.0.1] - 2024-09-07
1921
### Fixed

docs/settings.rst

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

66+
ALLOW_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 for allowed_origins and
79+
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+
This feature is useful for working with CI service such as cloudflare, netlify, and vercel that offer branch
95+
deployments for development previews and user acceptance testing.
96+
6697
ALLOWED_SCHEMES
6798
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6899

oauth2_provider/models.py

Lines changed: 45 additions & 20 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_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_URI_WILDCARDS,
238+
)
231239
for uri in allowed_origins:
232240
validator(uri)
233241

@@ -777,39 +785,55 @@ def redirect_to_uri_allowed(uri, allowed_uris):
777785
:param allowed_uris: A list of URIs that are allowed
778786
"""
779787

788+
if not isinstance(allowed_uris, list):
789+
raise ValueError("allowed_uris must be a list")
790+
780791
parsed_uri = urlparse(uri)
781792
uqs_set = set(parse_qsl(parsed_uri.query))
782793
for allowed_uri in allowed_uris:
783794
parsed_allowed_uri = urlparse(allowed_uri)
784795

796+
if parsed_allowed_uri.scheme != parsed_uri.scheme:
797+
# match failed, continue
798+
continue
799+
800+
""" check hostname """
801+
if oauth2_settings.ALLOW_URI_WILDCARDS and parsed_allowed_uri.hostname.startswith("*"):
802+
""" wildcard hostname """
803+
if not parsed_uri.hostname.endswith(parsed_allowed_uri.hostname[1:]):
804+
continue
805+
elif parsed_allowed_uri.hostname != parsed_uri.hostname:
806+
continue
807+
785808
# From RFC 8252 (Section 7.3)
809+
# https://datatracker.ietf.org/doc/html/rfc8252#section-7.3
786810
#
787811
# Loopback redirect URIs use the "http" scheme
788812
# [...]
789813
# The authorization server MUST allow any port to be specified at the
790814
# time of the request for loopback IP redirect URIs, to accommodate
791815
# clients that obtain an available ephemeral port from the operating
792816
# system at the time of the request.
817+
allowed_uri_is_loopback = parsed_allowed_uri.scheme == "http" and parsed_allowed_uri.hostname in [
818+
"127.0.0.1",
819+
"::1",
820+
]
821+
""" check port """
822+
if not allowed_uri_is_loopback and parsed_allowed_uri.port != parsed_uri.port:
823+
continue
824+
825+
""" check path """
826+
if parsed_allowed_uri.path != parsed_uri.path:
827+
continue
828+
829+
""" check querystring """
830+
aqs_set = set(parse_qsl(parsed_allowed_uri.query))
831+
if not aqs_set.issubset(uqs_set):
832+
continue # circuit break
793833

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
834+
return True
812835

836+
# if uris matched then it's not allowed
813837
return False
814838

815839

@@ -833,4 +857,5 @@ def is_origin_allowed(origin, allowed_origins):
833857
and parsed_allowed_origin.netloc == parsed_origin.netloc
834858
):
835859
return True
860+
836861
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_URI_WILDCARDS": False,
7475
"OIDC_ENABLED": False,
7576
"OIDC_ISS_ENDPOINT": "",
7677
"OIDC_USERINFO_ENDPOINT": "",

oauth2_provider/validators.py

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,15 @@ 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+
):
2533
"""
2634
:param schemes: List of allowed schemes. E.g.: ["https"]
2735
:param name: Name of the validated URI. It is required for validation message. E.g.: "Origin"
@@ -34,6 +42,7 @@ def __init__(self, schemes, name, allow_path=False, allow_query=False, allow_fra
3442
self.allow_path = allow_path
3543
self.allow_query = allow_query
3644
self.allow_fragments = allow_fragments
45+
self.allow_hostname_wildcard = allow_hostname_wildcard
3746

3847
def __call__(self, value):
3948
value = force_str(value)
@@ -68,8 +77,57 @@ def __call__(self, value):
6877
params={"name": self.name, "value": value, "cause": "path not allowed"},
6978
)
7079

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

0 commit comments

Comments
 (0)