scim2-server 0.8.4__tar.gz → 0.8.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. {scim2_server-0.8.4 → scim2_server-0.8.6}/PKG-INFO +3 -1
  2. {scim2_server-0.8.4 → scim2_server-0.8.6}/pyproject.toml +8 -1
  3. {scim2_server-0.8.4 → scim2_server-0.8.6}/pyproject.toml.orig +10 -2
  4. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/applications/base.py +6 -2
  5. scim2_server-0.8.6/scim2_server/testserver/application.py +214 -0
  6. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/testserver/cli.py +77 -11
  7. scim2_server-0.8.6/scim2_server/testserver/oauth.py +164 -0
  8. scim2_server-0.8.4/scim2_server/testserver/application.py +0 -48
  9. {scim2_server-0.8.4 → scim2_server-0.8.6}/LICENSE +0 -0
  10. {scim2_server-0.8.4 → scim2_server-0.8.6}/README.md +0 -0
  11. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/__init__.py +0 -0
  12. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/applications/__init__.py +0 -0
  13. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/applications/asgi.py +0 -0
  14. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/applications/wsgi.py +0 -0
  15. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/bulk.py +0 -0
  16. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/conditions.py +0 -0
  17. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/cursor.py +0 -0
  18. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/errors.py +0 -0
  19. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/handler.py +0 -0
  20. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/memory.py +0 -0
  21. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/py.typed +0 -0
  22. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/requests.py +0 -0
  23. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/resources/default-resource-types.json +0 -0
  24. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/resources/default-schemas.json +0 -0
  25. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/resources/default-service-provider-config.json +0 -0
  26. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/responses.py +0 -0
  27. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/routing.py +0 -0
  28. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/service.py +0 -0
  29. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/storage.py +0 -0
  30. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/testing.py +0 -0
  31. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/testserver/__init__.py +0 -0
  32. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/testserver/precis.py +0 -0
  33. {scim2_server-0.8.4 → scim2_server-0.8.6}/scim2_server/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: scim2-server
3
- Version: 0.8.4
3
+ Version: 0.8.6
4
4
  Summary: SCIM server core for any storage and web framework
5
5
  Keywords: scim,scim2,provisioning,rfc7643,rfc7644
6
6
  Author: Yaal Coop, Christian Friedrich Coors
@@ -220,12 +220,14 @@ Classifier: Programming Language :: Python
220
220
  Classifier: Operating System :: OS Independent
221
221
  Requires-Dist: scim2-models>=0.12.2
222
222
  Requires-Dist: cryptography>=50.0.1 ; extra == 'cursor'
223
+ Requires-Dist: authlib>=1.10.0b1 ; extra == 'oauth'
223
224
  Requires-Dist: precis-i18n>=1.1.2 ; extra == 'precis'
224
225
  Requires-Dist: pytest>=9.1.1 ; extra == 'testing'
225
226
  Requires-Python: >=3.11
226
227
  Project-URL: repository, https://github.com/python-scim/scim2-server
227
228
  Project-URL: funding, https://github.com/sponsors/python-scim
228
229
  Provides-Extra: cursor
230
+ Provides-Extra: oauth
229
231
  Provides-Extra: precis
230
232
  Provides-Extra: testing
231
233
  Description-Content-Type: text/markdown
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "scim2-server"
7
- version = "0.8.4"
7
+ version = "0.8.6"
8
8
  description = "SCIM server core for any storage and web framework"
9
9
  readme = "README.md"
10
10
  keywords = [
@@ -46,6 +46,7 @@ file = "LICENSE"
46
46
  testing = ["pytest>=9.1.1"]
47
47
  precis = ["precis-i18n>=1.1.2"]
48
48
  cursor = ["cryptography>=50.0.1"]
49
+ oauth = ["authlib>=1.10.0b1"]
49
50
 
50
51
  [project.urls]
51
52
  repository = "https://github.com/python-scim/scim2-server"
@@ -69,6 +70,7 @@ dev = [
69
70
  "scim2-tester[testing]>=0.6.2",
70
71
  "werkzeug>=3.0.3",
71
72
  "cryptography>=50.0.1",
73
+ "authlib>=1.10.0b1",
72
74
  ]
73
75
  doc = [
74
76
  "shibuya>=2024.5.15",
@@ -90,6 +92,7 @@ scim2-server = false
90
92
  scim2-cli = false
91
93
  scim2-tester = false
92
94
  pytest-scim2-server = false
95
+ authlib = false
93
96
 
94
97
  [tool.uv.build-backend]
95
98
  module-root = ""
@@ -99,6 +102,10 @@ plugins = ["pydantic.mypy"]
99
102
  files = ["scim2_server"]
100
103
  strict = true
101
104
 
105
+ [[tool.mypy.overrides]]
106
+ module = ["authlib.*"]
107
+ ignore_missing_imports = true
108
+
102
109
  [tool.pydantic-mypy]
103
110
  init_forbid_extra = true
104
111
  init_typed = true
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "scim2-server"
7
- version = "0.8.4"
7
+ version = "0.8.6"
8
8
  description = "SCIM server core for any storage and web framework"
9
9
  authors = [
10
10
  {name="Yaal Coop", email="contact@yaal.coop"},
@@ -43,6 +43,9 @@ precis = [
43
43
  cursor = [
44
44
  "cryptography>=50.0.1",
45
45
  ]
46
+ oauth = [
47
+ "authlib>=1.10.0b1",
48
+ ]
46
49
 
47
50
  [project.urls]
48
51
  repository = "https://github.com/python-scim/scim2-server"
@@ -66,6 +69,7 @@ dev = [
66
69
  "scim2-tester[testing]>=0.6.2",
67
70
  "werkzeug>=3.0.3",
68
71
  "cryptography>=50.0.1",
72
+ "authlib>=1.10.0b1",
69
73
  ]
70
74
  doc = [
71
75
  "shibuya>=2024.5.15",
@@ -79,7 +83,7 @@ doc = [
79
83
  [tool.uv]
80
84
  required-version = ">=0.12.13"
81
85
  exclude-newer = "14 days"
82
- exclude-newer-package = { scim2-models = false, scim2-client = false, scim2-server = false, scim2-cli = false, scim2-tester = false, pytest-scim2-server = false }
86
+ exclude-newer-package = { scim2-models = false, scim2-client = false, scim2-server = false, scim2-cli = false, scim2-tester = false, pytest-scim2-server = false, authlib = false }
83
87
 
84
88
  [tool.uv.build-backend]
85
89
  module-root = ""
@@ -91,6 +95,10 @@ plugins = [
91
95
  files = ["scim2_server"]
92
96
  strict = true
93
97
 
98
+ [[tool.mypy.overrides]]
99
+ module = ["authlib.*"]
100
+ ignore_missing_imports = true
101
+
94
102
  [tool.pydantic-mypy]
95
103
  init_forbid_extra = true
96
104
  init_typed = true
@@ -1,5 +1,6 @@
1
1
  import logging
2
2
  import os
3
+ from http import HTTPStatus
3
4
  from typing import Any
4
5
 
5
6
  from scim2_models import SCIMException
@@ -113,7 +114,10 @@ class BaseApplication:
113
114
  client.
114
115
  """
115
116
  # RFC 7644 does not require a Location header on every response, but
116
- # its examples include one even when no resource was created.
117
- response.headers.setdefault("Location", request.url)
117
+ # its examples include one on successful responses, even when no
118
+ # resource was created. An error is not at the location of a resource.
119
+ if response.status < HTTPStatus.BAD_REQUEST:
120
+ response.headers.setdefault("Location", request.url)
121
+
118
122
  response.headers.setdefault("Cache-Control", "no-cache")
119
123
  return response
@@ -0,0 +1,214 @@
1
+ """The SCIM application of the ``scim2-server`` command."""
2
+
3
+ import base64
4
+ import binascii
5
+ import hmac
6
+ from collections.abc import Iterable
7
+ from typing import TYPE_CHECKING
8
+
9
+ from scim2_models import AuthenticationScheme
10
+ from scim2_models import External
11
+ from scim2_models import ForbiddenException
12
+ from scim2_models import Reference
13
+ from scim2_models import SCIMException
14
+ from scim2_models import ScimProvider
15
+ from scim2_models import ServiceProviderConfig
16
+ from scim2_models import UnauthorizedException
17
+
18
+ from scim2_server.applications.wsgi import WSGIApplication
19
+ from scim2_server.requests import ScimRequest
20
+ from scim2_server.responses import ScimResponse
21
+ from scim2_server.service import CHALLENGES
22
+ from scim2_server.service import ScimService
23
+ from scim2_server.storage import ScimStorage
24
+
25
+ if TYPE_CHECKING:
26
+ from scim2_server.testserver.oauth import AccessTokenValidator
27
+
28
+ BEARER_TOKEN_SCHEME = AuthenticationScheme(
29
+ type=AuthenticationScheme.Type.oauthbearertoken,
30
+ name="bearer_token",
31
+ description="HTTP Bearer Token",
32
+ spec_uri=Reference[External]("https://datatracker.ietf.org/doc/html/rfc6750"),
33
+ )
34
+
35
+ BASIC_SCHEME = AuthenticationScheme(
36
+ type=AuthenticationScheme.Type.httpbasic,
37
+ name="basic",
38
+ description="HTTP Basic",
39
+ spec_uri=Reference[External]("https://datatracker.ietf.org/doc/html/rfc7617"),
40
+ )
41
+
42
+ OAUTH2_SCHEME = AuthenticationScheme(
43
+ type=AuthenticationScheme.Type.oauth2,
44
+ name="oauth2",
45
+ description="OAuth 2.0 JWT access token",
46
+ spec_uri=Reference[External]("https://datatracker.ietf.org/doc/html/rfc9068"),
47
+ )
48
+
49
+
50
+ def announce_authentication_schemes(
51
+ config: ServiceProviderConfig, bearer_token: bool, basic: bool, oauth: bool
52
+ ) -> None:
53
+ """Add the schemes of the accepted credentials to a service provider configuration.
54
+
55
+ Without credentials, the application accepts any bearer token. If the
56
+ configuration has no scheme then, it announces the bearer token scheme,
57
+ because the ``authenticationSchemes`` attribute is required
58
+ (:rfc:`RFC 7643 §5 <7643#section-5>`).
59
+ """
60
+ schemes = list(config.authentication_schemes or [])
61
+ if bearer_token or not (basic or oauth or schemes):
62
+ schemes.append(BEARER_TOKEN_SCHEME)
63
+
64
+ if basic:
65
+ schemes.append(BASIC_SCHEME)
66
+
67
+ if oauth:
68
+ schemes.append(OAUTH2_SCHEME)
69
+
70
+ config.authentication_schemes = schemes
71
+
72
+
73
+ class InvalidAccessTokenException(UnauthorizedException):
74
+ """A 401 error for an invalid or expired OAuth access token.
75
+
76
+ Its response carries a Bearer challenge with an error code
77
+ (:rfc:`RFC 6750 §3 <6750#section-3>`).
78
+ """
79
+
80
+ def __init__(self, challenge: str, detail: str | None = None):
81
+ super().__init__(detail=detail)
82
+ self.challenge = challenge
83
+
84
+
85
+ class AuthorizationServerUnavailableException(SCIMException):
86
+ """A 503 error when the metadata or the keys of the OAuth issuer cannot be downloaded.
87
+
88
+ Its response carries a :mdn:`Retry-After` header, so that the client
89
+ sends the request again later (:rfc:`RFC 9110 §15.6.4 <9110#section-15.6.4>`).
90
+ """
91
+
92
+ status = 503
93
+ retry_after = 5
94
+
95
+
96
+ class InsufficientScopeException(ForbiddenException):
97
+ """A 403 error for an OAuth access token without the required scope.
98
+
99
+ Its response carries a Bearer challenge with an error code
100
+ (:rfc:`RFC 6750 §3 <6750#section-3>`).
101
+ """
102
+
103
+ def __init__(self, challenge: str, detail: str | None = None):
104
+ super().__init__(detail=detail)
105
+ self.challenge = challenge
106
+
107
+
108
+ def _equals(value: str, expected: str) -> bool:
109
+ return hmac.compare_digest(value.encode(), expected.encode())
110
+
111
+
112
+ def decode_basic_credentials(value: str) -> tuple[str, str] | None:
113
+ """Return the user and the password of Basic credentials, or None if they are malformed."""
114
+ try:
115
+ decoded = base64.b64decode(value, validate=True).decode()
116
+ except (binascii.Error, UnicodeDecodeError):
117
+ return None
118
+
119
+ user, separator, password = decoded.partition(":")
120
+ if not separator:
121
+ return None
122
+
123
+ return user, password
124
+
125
+
126
+ class CredentialsApplication(WSGIApplication):
127
+ """A SCIM application that only accepts the credentials it is given.
128
+
129
+ It accepts static bearer tokens, Basic credentials, and the OAuth JWT
130
+ access tokens of an ``access_token_validator``. Without any of them, it
131
+ accepts every request. List :data:`BEARER_TOKEN_SCHEME`,
132
+ :data:`BASIC_SCHEME` and :data:`OAUTH2_SCHEME` in the service provider
133
+ configuration, so that the 401 responses carry a :mdn:`WWW-Authenticate`
134
+ header.
135
+ """
136
+
137
+ def __init__(
138
+ self,
139
+ storage: ScimStorage,
140
+ provider: ScimProvider,
141
+ service: ScimService | None = None,
142
+ bearer_tokens: Iterable[str] = (),
143
+ basic_credentials: Iterable[tuple[str, str]] = (),
144
+ access_token_validator: "AccessTokenValidator | None" = None,
145
+ ):
146
+ super().__init__(storage, provider, service)
147
+ self.bearer_tokens = list(bearer_tokens)
148
+ self.basic_credentials = list(basic_credentials)
149
+ self.access_token_validator = access_token_validator
150
+
151
+ def check_auth(self, request: ScimRequest) -> None:
152
+ """Refuse a request without valid credentials."""
153
+ if not (
154
+ self.bearer_tokens or self.basic_credentials or self.access_token_validator
155
+ ):
156
+ return
157
+
158
+ scheme, _, value = (request.header("Authorization") or "").partition(" ")
159
+ if scheme.lower() == "bearer" and self.is_valid_token(value):
160
+ return
161
+
162
+ if scheme.lower() == "basic" and self.are_valid_credentials(value):
163
+ return
164
+
165
+ if scheme.lower() == "bearer" and self.access_token_validator:
166
+ self.access_token_validator.check(value)
167
+ return
168
+
169
+ raise UnauthorizedException
170
+
171
+ def handle_exception(
172
+ self, request: ScimRequest, exception: Exception
173
+ ) -> ScimResponse:
174
+ """Return the error response, with the headers of an access token error.
175
+
176
+ The 401 response of an invalid access token keeps the challenges of
177
+ the other schemes.
178
+ """
179
+ response = super().handle_exception(request, exception)
180
+ if isinstance(exception, AuthorizationServerUnavailableException):
181
+ response.headers["Retry-After"] = str(exception.retry_after)
182
+
183
+ if isinstance(exception, InsufficientScopeException):
184
+ response.headers["WWW-Authenticate"] = exception.challenge
185
+
186
+ if isinstance(exception, InvalidAccessTokenException):
187
+ schemes = self.service.config.authentication_schemes or []
188
+ others = dict.fromkeys(
189
+ CHALLENGES[scheme.type]
190
+ for scheme in schemes
191
+ if scheme.type in CHALLENGES
192
+ and not CHALLENGES[scheme.type].startswith("Bearer ")
193
+ )
194
+ response.headers["WWW-Authenticate"] = ", ".join(
195
+ [exception.challenge, *others]
196
+ )
197
+
198
+ return response
199
+
200
+ def is_valid_token(self, token: str) -> bool:
201
+ """Tell whether a token is one of the bearer tokens."""
202
+ return any(_equals(token, expected) for expected in self.bearer_tokens)
203
+
204
+ def are_valid_credentials(self, value: str) -> bool:
205
+ """Tell whether encoded Basic credentials are among the accepted ones."""
206
+ credentials = decode_basic_credentials(value)
207
+ if credentials is None:
208
+ return False
209
+
210
+ user, password = credentials
211
+ return any(
212
+ _equals(user, expected_user) and _equals(password, expected_password)
213
+ for expected_user, expected_password in self.basic_credentials
214
+ )
@@ -20,8 +20,8 @@ from scim2_server.applications.wsgi import ForwardedHeaders
20
20
  from scim2_server.applications.wsgi import TenantDispatcher
21
21
  from scim2_server.memory import InMemoryStorage
22
22
  from scim2_server.service import ScimService
23
- from scim2_server.testserver.application import BEARER_TOKEN_SCHEME
24
- from scim2_server.testserver.application import BearerTokenApplication
23
+ from scim2_server.testserver.application import CredentialsApplication
24
+ from scim2_server.testserver.application import announce_authentication_schemes
25
25
  from scim2_server.utils import load_default_resource_types
26
26
  from scim2_server.utils import load_default_schemas
27
27
  from scim2_server.utils import load_default_service_provider_config
@@ -55,6 +55,14 @@ def dump_resources(storage: InMemoryStorage) -> list[dict[str, Any]]:
55
55
  return [r.model_dump() for r in storage.resources]
56
56
 
57
57
 
58
+ def basic_credentials(value: str) -> tuple[str, str]:
59
+ """Split the ``USER:PASSWORD`` value of the ``--basic-auth`` option."""
60
+ user, separator, password = value.partition(":")
61
+ if not separator:
62
+ raise argparse.ArgumentTypeError("expected USER:PASSWORD")
63
+ return user, password
64
+
65
+
58
66
  def build_parser() -> argparse.ArgumentParser:
59
67
  """Build the parser of the ``scim2-server`` command."""
60
68
  parser = argparse.ArgumentParser(
@@ -88,7 +96,39 @@ def build_parser() -> argparse.ArgumentParser:
88
96
  action="append",
89
97
  metavar="TOKEN",
90
98
  help="Accept a static bearer token, and announce the bearer token scheme. "
91
- "Can be repeated. Without it, the server accepts every request.",
99
+ "Can be repeated.",
100
+ )
101
+ parser.add_argument(
102
+ "--basic-auth",
103
+ action="append",
104
+ type=basic_credentials,
105
+ metavar="USER:PASSWORD",
106
+ help="Accept HTTP Basic credentials, and announce the Basic scheme. "
107
+ "Can be repeated. Without --bearer-token, --basic-auth nor --oauth-issuer, "
108
+ "the server accepts every request.",
109
+ )
110
+ parser.add_argument(
111
+ "--oauth-issuer",
112
+ metavar="URL",
113
+ help="Accept the OAuth JWT access tokens (RFC 9068) of this issuer, and "
114
+ "announce the oauth2 scheme. Needs --oauth-audience and the oauth extra.",
115
+ )
116
+ parser.add_argument(
117
+ "--oauth-audience",
118
+ metavar="VALUE",
119
+ help="Accept only the access tokens whose aud claim holds this value.",
120
+ )
121
+ parser.add_argument(
122
+ "--oauth-jwks-uri",
123
+ metavar="URL",
124
+ help="Check the signature of the access tokens with the keys of this "
125
+ "JWK set URL. Defaults to the jwks_uri of the metadata of the issuer.",
126
+ )
127
+ parser.add_argument(
128
+ "--oauth-scope",
129
+ metavar="SCOPE",
130
+ help="Accept only the access tokens with this scope. Several scopes "
131
+ "separated by spaces are all required.",
92
132
  )
93
133
  parser.add_argument(
94
134
  "--precis",
@@ -172,11 +212,35 @@ def main() -> None:
172
212
  json.load(args.service_provider_config)
173
213
  )
174
214
 
175
- if args.bearer_token is not None:
176
- config.authentication_schemes = [
177
- *(config.authentication_schemes or []),
178
- BEARER_TOKEN_SCHEME,
179
- ]
215
+ if bool(args.oauth_issuer) != bool(args.oauth_audience):
216
+ parser.error("--oauth-issuer and --oauth-audience go together")
217
+
218
+ if (args.oauth_jwks_uri or args.oauth_scope) and not args.oauth_issuer:
219
+ parser.error("--oauth-jwks-uri and --oauth-scope need --oauth-issuer")
220
+
221
+ access_token_validator = None
222
+ if args.oauth_issuer:
223
+ try:
224
+ # Imported on demand, so that the server runs without the oauth extra.
225
+ from scim2_server.testserver.oauth import AccessTokenValidator
226
+ except ModuleNotFoundError:
227
+ parser.error(
228
+ "--oauth-issuer needs the oauth extra: pip install 'scim2-server[oauth]'"
229
+ )
230
+
231
+ access_token_validator = AccessTokenValidator(
232
+ args.oauth_issuer,
233
+ args.oauth_audience,
234
+ jwks_uri=args.oauth_jwks_uri,
235
+ scope=args.oauth_scope,
236
+ )
237
+
238
+ announce_authentication_schemes(
239
+ config,
240
+ bool(args.bearer_token),
241
+ bool(args.basic_auth),
242
+ access_token_validator is not None,
243
+ )
180
244
 
181
245
  policy = None
182
246
  if args.precis:
@@ -206,16 +270,18 @@ def main() -> None:
206
270
 
207
271
  storages: dict[str | None, InMemoryStorage] = {}
208
272
 
209
- def make_application(tenant: str | None = None) -> BearerTokenApplication:
273
+ def make_application(tenant: str | None = None) -> CredentialsApplication:
210
274
  storages[tenant] = InMemoryStorage()
211
- return BearerTokenApplication(
275
+ return CredentialsApplication(
212
276
  storages[tenant],
213
277
  provider,
214
278
  service=service,
215
279
  bearer_tokens=args.bearer_token or [],
280
+ basic_credentials=args.basic_auth or [],
281
+ access_token_validator=access_token_validator,
216
282
  )
217
283
 
218
- def make_tenant_application(tenant: str) -> BearerTokenApplication | None:
284
+ def make_tenant_application(tenant: str) -> CredentialsApplication | None:
219
285
  if not args.dynamic_tenants and tenant not in args.tenant:
220
286
  return None
221
287
  return make_application(tenant)
@@ -0,0 +1,164 @@
1
+ """The OAuth access token validation of the ``--oauth-*`` options of the ``scim2-server`` command."""
2
+
3
+ import json
4
+ import threading
5
+ import time
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+ from collections.abc import Callable
10
+ from typing import Any
11
+
12
+ from authlib.oauth2.rfc6750.errors import InsufficientScopeError
13
+ from authlib.oauth2.rfc6750.errors import InvalidTokenError
14
+ from authlib.oauth2.rfc9068 import JWTBearerTokenValidator
15
+ from joserfc.errors import JoseError
16
+ from joserfc.jwk import GuestProtocol
17
+ from joserfc.jwk import KeySet
18
+
19
+ from scim2_server.testserver.application import AuthorizationServerUnavailableException
20
+ from scim2_server.testserver.application import InsufficientScopeException
21
+ from scim2_server.testserver.application import InvalidAccessTokenException
22
+
23
+
24
+ def fetch_json(url: str) -> Any:
25
+ """Download a JSON document.
26
+
27
+ An HTTP error is closed before it is raised, so that it holds no connection.
28
+ """
29
+ try:
30
+ with urllib.request.urlopen(url, timeout=10) as response:
31
+ return json.load(response)
32
+ except urllib.error.HTTPError as error:
33
+ error.close()
34
+ raise
35
+
36
+
37
+ def metadata_urls(issuer: str) -> tuple[str, str]:
38
+ """Return the URLs of the metadata of an issuer.
39
+
40
+ The first one is the URL of RFC 8414 §3.1, the second one the URL of
41
+ OpenID Connect Discovery 1.0 §4.
42
+ """
43
+ scheme, netloc, path, _, _ = urllib.parse.urlsplit(issuer)
44
+ path = path.rstrip("/")
45
+ rfc8414 = urllib.parse.urlunsplit(
46
+ (scheme, netloc, f"/.well-known/oauth-authorization-server{path}", "", "")
47
+ )
48
+ return rfc8414, f"{issuer.rstrip('/')}/.well-known/openid-configuration"
49
+
50
+
51
+ def _reason(error: InvalidTokenError) -> str:
52
+ cause = error.__cause__
53
+ if isinstance(cause, JoseError):
54
+ return cause.description or cause.error
55
+
56
+ return str(error.get_error_description())
57
+
58
+
59
+ class AccessTokenValidator(JWTBearerTokenValidator): # type: ignore[misc]
60
+ """Validate JWT access tokens (RFC 9068) with the keys of the issuer.
61
+
62
+ Without ``jwks_uri``, the URL of the keys comes from the metadata of the
63
+ issuer. The keys are downloaded with the first token, then kept. A token signed
64
+ with an unknown key downloads them again, at most once per
65
+ :attr:`refresh_interval` seconds, so that forged tokens cannot flood the
66
+ authorization server.
67
+ """
68
+
69
+ refresh_interval = 60
70
+
71
+ def __init__(
72
+ self,
73
+ issuer: str,
74
+ audience: str,
75
+ jwks_uri: str | None = None,
76
+ scope: str | None = None,
77
+ fetch: Callable[[str], Any] = fetch_json,
78
+ ):
79
+ super().__init__(issuer=issuer, resource_server=audience, realm="SCIM")
80
+ self.jwks_uri = jwks_uri
81
+ self.scope = scope
82
+ self.fetch = fetch
83
+ self.keys: KeySet | None = None
84
+ self.downloaded_at = float("-inf")
85
+ self.lock = threading.Lock()
86
+
87
+ def get_jwks(self) -> Callable[[GuestProtocol], KeySet]:
88
+ return self.resolve_keys
89
+
90
+ def resolve_keys(self, token: GuestProtocol) -> KeySet:
91
+ """Return the keys that may sign a token, and download them when needed."""
92
+ with self.lock:
93
+ if self.keys is None or self.needs_download(self.keys, token):
94
+ self.downloaded_at = time.monotonic()
95
+ self.keys = self.download_keys()
96
+
97
+ return self.keys
98
+
99
+ def download_keys(self) -> KeySet:
100
+ """Download the keys of the issuer.
101
+
102
+ :raises ~scim2_server.testserver.application.AuthorizationServerUnavailableException:
103
+ When the metadata or the keys cannot be downloaded or read.
104
+ """
105
+ try:
106
+ self.jwks_uri = self.jwks_uri or self.discover_jwks_uri()
107
+ return KeySet.import_key_set(self.fetch(self.jwks_uri))
108
+ except Exception as error:
109
+ # A network error, or a document that holds no metadata or no keys:
110
+ # the token itself may be valid, so it must not get a 401.
111
+ raise AuthorizationServerUnavailableException(
112
+ detail=f"The keys of {self.issuer} cannot be downloaded: {error}"
113
+ ) from error
114
+
115
+ def discover_jwks_uri(self) -> str:
116
+ """Return the URL of the keys, from the metadata of the issuer.
117
+
118
+ The metadata of RFC 8414 are tried first, then the ones of OpenID
119
+ Connect Discovery. Per RFC 8414 §3.3, the issuer of the metadata must
120
+ be the issuer of the tokens.
121
+ """
122
+ rfc8414, openid = metadata_urls(self.issuer)
123
+ try:
124
+ metadata = self.fetch(rfc8414)
125
+ except urllib.error.HTTPError:
126
+ metadata = self.fetch(openid)
127
+
128
+ if metadata.get("issuer") != self.issuer:
129
+ raise ValueError(
130
+ f"The metadata of {self.issuer} are for the issuer {metadata.get('issuer')}"
131
+ )
132
+
133
+ if "jwks_uri" not in metadata:
134
+ raise ValueError(f"The metadata of {self.issuer} have no jwks_uri")
135
+
136
+ return str(metadata["jwks_uri"])
137
+
138
+ def needs_download(self, keys: KeySet, token: GuestProtocol) -> bool:
139
+ """Tell whether a token is signed with an unknown key, and the refresh interval has passed."""
140
+ kid = token.headers().get("kid")
141
+ if not kid or any(key.kid == kid for key in keys.keys):
142
+ return False
143
+
144
+ return time.monotonic() - self.downloaded_at >= self.refresh_interval
145
+
146
+ def check(self, token_string: str) -> None:
147
+ """Refuse an invalid or expired access token, or one without the scope."""
148
+ scopes = [self.scope] if self.scope else None
149
+ try:
150
+ token = self.authenticate_token(token_string)
151
+ self.validate_token(token, scopes, None)
152
+ except InvalidTokenError as error:
153
+ challenge = dict(error.get_headers())["WWW-Authenticate"]
154
+ raise InvalidAccessTokenException(
155
+ challenge, detail=f"Invalid access token: {_reason(error)}"
156
+ ) from error
157
+ except InsufficientScopeError as error:
158
+ challenge = (
159
+ f'Bearer realm="SCIM", error="{error.error}", scope="{self.scope}"'
160
+ )
161
+ raise InsufficientScopeException(
162
+ challenge,
163
+ detail=f"The access token does not have the {self.scope!r} scope",
164
+ ) from error
@@ -1,48 +0,0 @@
1
- """The SCIM application of the ``scim2-server`` command."""
2
-
3
- from collections.abc import Iterable
4
-
5
- from scim2_models import AuthenticationScheme
6
- from scim2_models import External
7
- from scim2_models import Reference
8
- from scim2_models import ScimProvider
9
- from scim2_models import UnauthorizedException
10
-
11
- from scim2_server.applications.wsgi import WSGIApplication
12
- from scim2_server.requests import ScimRequest
13
- from scim2_server.service import ScimService
14
- from scim2_server.storage import ScimStorage
15
-
16
- BEARER_TOKEN_SCHEME = AuthenticationScheme(
17
- type=AuthenticationScheme.Type.oauthbearertoken,
18
- name="bearer_token",
19
- description="HTTP Bearer Token",
20
- spec_uri=Reference[External]("https://datatracker.ietf.org/doc/html/rfc6750"),
21
- )
22
-
23
-
24
- class BearerTokenApplication(WSGIApplication):
25
- """A SCIM application that only accepts static bearer tokens.
26
-
27
- Without token, it accepts every request. List
28
- :data:`BEARER_TOKEN_SCHEME` in the service provider configuration, so
29
- that the 401 responses carry a :mdn:`WWW-Authenticate` header.
30
- """
31
-
32
- def __init__(
33
- self,
34
- storage: ScimStorage,
35
- provider: ScimProvider,
36
- service: ScimService | None = None,
37
- bearer_tokens: Iterable[str] = (),
38
- ):
39
- super().__init__(storage, provider, service)
40
- self.bearer_tokens = set(bearer_tokens)
41
-
42
- def check_auth(self, request: ScimRequest) -> None:
43
- """Refuse a request without one of the bearer tokens."""
44
- if not self.bearer_tokens:
45
- return
46
- scheme, _, token = (request.header("Authorization") or "").partition(" ")
47
- if scheme.lower() != "bearer" or token not in self.bearer_tokens:
48
- raise UnauthorizedException
File without changes
File without changes