Debian Codegraph @

allauth/idp/oidc/internal/clientkit.py

raw
1 from __future__ import annotations
2
3 import re
4 from re import Pattern
5 from urllib.parse import ParseResult, parse_qsl, urlparse
6
7 from django.core.exceptions import ValidationError
8 from django.forms import URLField
9 from django.utils.translation import gettext_lazy as _
10
11 from allauth.idp.oidc import app_settings
12 from allauth.idp.oidc.internal import cimd
13 from allauth.idp.oidc.models import Client
14
15
16 def is_loopback(parsed_uri: ParseResult) -> bool:
17 return parsed_uri.scheme == "http" and parsed_uri.hostname in (
18 "127.0.0.1",
19 "::1",
20 )
21
22
23 def _validate_uri_wildcard_format(uri: str, allow_uri_wildcards: bool) -> None:
24 if not allow_uri_wildcards:
25 if "*" in uri:
26 raise ValidationError(
27 _("Wildcards are not allowed unless 'Allow URI wildcards' is enabled.")
28 )
29 elif uri.count("*") > 1:
30 raise ValidationError(
31 _(
32 "URI '{}' contains more than one wildcard (*). Only one wildcard per URI is allowed."
33 ).format(uri)
34 )
35 else:
36 try:
37 parsed = urlparse(uri)
38 except ValueError as e:
39 # it's possible for this to happen with wildcards in ports
40 raise ValidationError(_(f"Invalid URI: {e}"))
41
42 if "*" in parsed.scheme or "*" in parsed.path or "*" in parsed.query:
43 raise ValidationError(
44 _("Wildcards are only allowed in the hostname portion of the URI.")
45 )
46
47
48 def _wildcard_to_regex(wildcard: str) -> Pattern[str]:
49 pattern = re.escape(wildcard).replace(r"\*", r"[^.]+")
50 return re.compile(f"^{pattern}$")
51
52
53 def _is_scheme_hostname_allowed(
54 parsed_uri: ParseResult, parsed_allowed_uri: ParseResult, allow_uri_wildcards: bool
55 ) -> bool:
56 if parsed_allowed_uri.scheme != parsed_uri.scheme:
57 return False
58
59 if (
60 allow_uri_wildcards
61 and parsed_allowed_uri.hostname
62 and "*" in parsed_allowed_uri.hostname
63 ):
64 allowed_hostname_pattern = _wildcard_to_regex(parsed_allowed_uri.hostname)
65
66 if not parsed_uri.hostname or not allowed_hostname_pattern.match(
67 parsed_uri.hostname
68 ):
69 return False
70 else:
71 if parsed_allowed_uri.hostname != parsed_uri.hostname:
72 return False
73
74 return True
75
76
77 def is_parsed_redirect_uri_allowed(
78 parsed_uri: ParseResult, allowed_uri: str, allow_uri_wildcards: bool
79 ) -> bool:
80 parsed_allowed_uri = urlparse(allowed_uri)
81
82 if not _is_scheme_hostname_allowed(
83 parsed_uri, parsed_allowed_uri, allow_uri_wildcards
84 ):
85 return False
86
87 if parsed_allowed_uri.path != parsed_uri.path:
88 return False
89
90 if not is_loopback(parsed_allowed_uri):
91 if parsed_allowed_uri.port != parsed_uri.port:
92 return False
93
94 if not set(parse_qsl(parsed_allowed_uri.query)).issubset(
95 set(parse_qsl(parsed_uri.query))
96 ):
97 return False
98
99 return True
100
101
102 def is_redirect_uri_allowed(
103 uri: str, allowed_uris: list[str], allow_uri_wildcards: bool
104 ) -> bool:
105 parsed_uri = urlparse(uri)
106 return any(
107 is_parsed_redirect_uri_allowed(parsed_uri, allowed_uri, allow_uri_wildcards)
108 for allowed_uri in allowed_uris
109 )
110
111
112 def is_origin_allowed(
113 origin: str, allowed_origins: list[str], allow_uri_wildcards: bool
114 ) -> bool:
115 parsed_origin = urlparse(origin)
116
117 for allowed_origin in allowed_origins:
118 parsed_allowed_origin = urlparse(allowed_origin)
119 if (
120 not _is_scheme_hostname_allowed(
121 parsed_origin, parsed_allowed_origin, allow_uri_wildcards
122 )
123 or parsed_origin.username != parsed_allowed_origin.username
124 or parsed_origin.password != parsed_allowed_origin.password
125 or parsed_origin.port != parsed_allowed_origin.port
126 ):
127 continue
128 else:
129 return True
130
131 return False
132
133
134 def is_post_logout_redirect_uri_allowed(
135 client: Client, post_logout_redirect_uri: str, parsed_uri: ParseResult
136 ) -> bool:
137 registered_uris = client.get_post_logout_redirect_uris()
138 if registered_uris:
139 # Logout redirect URIs were explicitly set, so only accept those.
140 return is_redirect_uri_allowed(
141 post_logout_redirect_uri, registered_uris, client.allow_uri_wildcards
142 )
143 # No explicit redirect URIs configured. Let's at least check the netloc
144 # against redirect_uris. But, we can only do so for proper http(s) urls,
145 # as app uris like 'org.allauth.app://logout' don't have that.
146 if parsed_uri.scheme in ("http", "https"):
147 return is_origin_allowed(
148 post_logout_redirect_uri,
149 client.get_redirect_uris(),
150 client.allow_uri_wildcards,
151 )
152 else:
153 # Our caller did already perform scheme validation, meaning,
154 # scheme 'org.allauth.app' would pass, and 'com.evil.app' would not.
155 return True
156
157
158 def get_used_schemes(client: Client) -> set[str]:
159 schemes = set()
160 for uri in client.get_redirect_uris() + client.get_post_logout_redirect_uris():
161 parsed = urlparse(uri)
162 if parsed.scheme:
163 schemes.add(parsed.scheme)
164 return schemes
165
166
167 def clean_post_logout_redirect_uri(
168 post_logout_redirect_uri: str | None, client: Client | None
169 ) -> str | None:
170 """
171 This URI SHOULD use the https scheme and MAY contain port, path, and
172 query parameter components; however, it MAY use the http scheme, provided
173 that the Client Type is confidential, as defined in Section 2.1 of OAuth 2.0
174 [RFC6749], and provided the OP allows the use of http RP URIs. The URI MAY
175 use an alternate scheme, such as one that is intended to identify a callback
176 into a native application. The value MUST have been previously registered
177 with the OP, either using the post_logout_redirect_uris Registration
178 parameter or via another mechanism. An id_token_hint is also RECOMMENDED
179 when this parameter is included.
180 """
181 if not client:
182 # Without a client we have no way of validating this part:
183 # "...The value MUST have been previously registered...".
184 return None
185 if not post_logout_redirect_uri:
186 return None
187 allowed_schemes = {"https"}
188 allowed_schemes.update(get_used_schemes(client))
189 if client.type == Client.Type.CONFIDENTIAL:
190 allowed_schemes.add("http")
191 parsed = urlparse(post_logout_redirect_uri)
192 if not parsed.scheme or parsed.scheme not in allowed_schemes:
193 raise ValidationError(URLField.default_error_messages["invalid"])
194 if parsed.scheme in ("http", "https"):
195 URLField().clean(post_logout_redirect_uri)
196 if not is_post_logout_redirect_uri_allowed(
197 client, post_logout_redirect_uri, parsed
198 ):
199 raise ValidationError(URLField.default_error_messages["invalid"])
200 return post_logout_redirect_uri
201
202
203 def lookup_client(client_id: str) -> Client | None:
204 client = Client.objects.filter(id=client_id).first()
205 if not app_settings.CIMD_ENABLED:
206 return client
207 return cimd.lookup_client(client_id, client)
208
209
210 def lookup_public_client(client_id: str) -> Client | None:
211 client = lookup_client(client_id)
212 if not client:
213 return None
214 if client.type != Client.Type.PUBLIC:
215 return None
216 return client