Debian Codegraph @

allauth/idp/oidc/internal/resources.py

raw
1 import posixpath
2 from urllib.parse import urlparse
3
4 from django.core.exceptions import ValidationError
5 from django.http import HttpRequest
6
7 from oauthlib.oauth2.rfc6749.errors import OAuth2Error
8
9 from allauth.idp.oidc.adapter import get_adapter
10
11
12 class InvalidTargetError(OAuth2Error):
13 error = "invalid_target"
14 description = "The requested resource is invalid, missing, unknown, or malformed."
15
16
17 def get_resources(request: HttpRequest) -> list[str]:
18 params = request.GET if request.method == "GET" else request.POST
19 resources = params.getlist("resource")
20 validate_resources(resources)
21 return resources
22
23
24 def validate_resources(resources: list[str]) -> None:
25 for resource in resources:
26 parsed = urlparse(resource)
27 if not parsed.scheme or not parsed.netloc:
28 raise ValidationError("Resource must be an absolute URI.")
29 if parsed.fragment:
30 raise ValidationError("Resource must not include a fragment component.")
31 if parsed.path and posixpath.normpath(parsed.path) != parsed.path:
32 raise ValidationError("Resource path is not normalized.")
33 if "//" in parsed.path:
34 raise ValidationError("Resource path is not normalized.")
35 adapter = get_adapter()
36 adapter.validate_resource_uris(uris=resources)
37
38
39 def is_resources_subset(requested: list[str] | None, granted: list[str] | None) -> bool:
40 if not granted or not requested:
41 return True
42 for resource in requested:
43 if not any(_is_contained_by(resource, g) for g in granted):
44 return False
45 return True
46
47
48 def _is_contained_by(resource: str, granted: str) -> bool:
49 r = urlparse(resource)
50 g = urlparse(granted)
51 if r.scheme != g.scheme or r.netloc != g.netloc:
52 return False
53 g_path = g.path.rstrip("/") + "/"
54 return r.path == g.path or r.path.startswith(g_path)