scim2-server 0.8.5__tar.gz → 0.8.7__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.5 → scim2_server-0.8.7}/PKG-INFO +3 -1
  2. {scim2_server-0.8.5 → scim2_server-0.8.7}/pyproject.toml +8 -1
  3. {scim2_server-0.8.5 → scim2_server-0.8.7}/pyproject.toml.orig +10 -2
  4. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/applications/base.py +34 -4
  5. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/applications/wsgi.py +10 -0
  6. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/memory.py +14 -1
  7. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/service.py +62 -1
  8. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/storage.py +11 -3
  9. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/testing.py +46 -6
  10. scim2_server-0.8.7/scim2_server/testserver/application.py +214 -0
  11. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/testserver/cli.py +57 -7
  12. scim2_server-0.8.7/scim2_server/testserver/oauth.py +164 -0
  13. scim2_server-0.8.5/scim2_server/testserver/application.py +0 -114
  14. {scim2_server-0.8.5 → scim2_server-0.8.7}/LICENSE +0 -0
  15. {scim2_server-0.8.5 → scim2_server-0.8.7}/README.md +0 -0
  16. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/__init__.py +0 -0
  17. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/applications/__init__.py +0 -0
  18. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/applications/asgi.py +0 -0
  19. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/bulk.py +0 -0
  20. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/conditions.py +0 -0
  21. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/cursor.py +0 -0
  22. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/errors.py +0 -0
  23. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/handler.py +0 -0
  24. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/py.typed +0 -0
  25. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/requests.py +0 -0
  26. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/resources/default-resource-types.json +0 -0
  27. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/resources/default-schemas.json +0 -0
  28. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/resources/default-service-provider-config.json +0 -0
  29. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/responses.py +0 -0
  30. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/routing.py +0 -0
  31. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/testserver/__init__.py +0 -0
  32. {scim2_server-0.8.5 → scim2_server-0.8.7}/scim2_server/testserver/precis.py +0 -0
  33. {scim2_server-0.8.5 → scim2_server-0.8.7}/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.5
3
+ Version: 0.8.7
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.5"
7
+ version = "0.8.7"
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.5"
7
+ version = "0.8.7"
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
@@ -65,7 +66,20 @@ class BaseApplication:
65
66
 
66
67
  It returns :data:`None` by default. Override it to pass the subject
67
68
  that :meth:`check_auth` authenticated to the service, for
68
- :meth:`~scim2_server.service.ScimService.authorize` and ``/Me``.
69
+ :meth:`~scim2_server.service.ScimService.authorize` and ``/Me``. The
70
+ following application passes the identifier of the user of a bearer
71
+ token:
72
+
73
+ >>> from scim2_server.applications.wsgi import WSGIApplication
74
+ >>> TOKENS = {"secret": "2819c223"}
75
+ >>> class TokenApplication(WSGIApplication):
76
+ ... def get_subject(self, request):
77
+ ... header = request.header("Authorization") or ""
78
+ ... _, _, token = header.partition(" ")
79
+ ... return TOKENS.get(token)
80
+
81
+ :doc:`/how-to/authenticate-the-clients` uses the subject to check the
82
+ rights of the client.
69
83
  """
70
84
  return None
71
85
 
@@ -77,7 +91,20 @@ class BaseApplication:
77
91
  whose credentials are missing or invalid. Check the rights of the
78
92
  client in :meth:`~scim2_server.service.ScimService.authorize`, which
79
93
  sees each operation of a bulk request. It is not called for
80
- ``/ServiceProviderConfig`` (:rfc:`RFC 7643 §5 <7643#section-5>`).
94
+ ``/ServiceProviderConfig`` (:rfc:`RFC 7643 §5 <7643#section-5>`). The
95
+ following application accepts the bearer tokens of a dictionary:
96
+
97
+ >>> from scim2_models import UnauthorizedException
98
+ >>> from scim2_server.applications.wsgi import WSGIApplication
99
+ >>> TOKENS = {"secret": "2819c223"}
100
+ >>> class TokenApplication(WSGIApplication):
101
+ ... def check_auth(self, request):
102
+ ... header = request.header("Authorization") or ""
103
+ ... scheme, _, token = header.partition(" ")
104
+ ... if scheme.lower() != "bearer" or token not in TOKENS:
105
+ ... raise UnauthorizedException(detail="Missing or invalid token")
106
+
107
+ :meth:`get_subject` then passes the client to the service.
81
108
  """
82
109
 
83
110
  def needs_auth(self, request: ScimRequest) -> bool:
@@ -113,7 +140,10 @@ class BaseApplication:
113
140
  client.
114
141
  """
115
142
  # 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)
143
+ # its examples include one on successful responses, even when no
144
+ # resource was created. An error is not at the location of a resource.
145
+ if response.status < HTTPStatus.BAD_REQUEST:
146
+ response.headers.setdefault("Location", request.url)
147
+
118
148
  response.headers.setdefault("Cache-Control", "no-cache")
119
149
  return response
@@ -171,6 +171,16 @@ class TenantDispatcher:
171
171
 
172
172
  Override this method to read the tenant from somewhere else, such as
173
173
  a header or a sub-domain (:rfc:`RFC 7644 §6.1 <7644#section-6.1>`).
174
+ The following dispatcher reads the tenant in the sub-domain, such as
175
+ ``acme`` in ``acme.scim.example``:
176
+
177
+ >>> class SubdomainDispatcher(TenantDispatcher):
178
+ ... def select_tenant(self, environ):
179
+ ... host = environ.get("HTTP_HOST", "").partition(":")[0].lower()
180
+ ... tenant, _, domain = host.partition(".")
181
+ ... if domain != "scim.example" or not self.is_valid_tenant(tenant):
182
+ ... return None
183
+ ... return tenant
174
184
  """
175
185
  path_info: str = environ.get("PATH_INFO", "")
176
186
  _, _, path = path_info.partition("/")
@@ -238,7 +238,20 @@ class InMemoryStorage(ScimStorage):
238
238
  def generate_id(self, resource_type: ResourceType, resource: Resource[Any]) -> str:
239
239
  """Return the identifier of a new resource.
240
240
 
241
- Override this method to get predictable identifiers.
241
+ Override this method to get predictable identifiers. The following
242
+ storage numbers the resources from 1:
243
+
244
+ >>> from itertools import count
245
+ >>> class NumberedStorage(InMemoryStorage):
246
+ ... def __init__(self):
247
+ ... super().__init__()
248
+ ... self.ids = count(1)
249
+ ...
250
+ ... def generate_id(self, resource_type, resource):
251
+ ... return str(next(self.ids))
252
+ >>> storage = NumberedStorage()
253
+ >>> storage.generate_id(None, None), storage.generate_id(None, None)
254
+ ('1', '2')
242
255
  """
243
256
  return uuid.uuid4().hex
244
257
 
@@ -269,6 +269,19 @@ class ScimService:
269
269
  <scim2_server.requests.ScimRequest.subject>`. The exceptions it raises
270
270
  answer the request.
271
271
 
272
+ The following service serves the user whose identifier is the
273
+ subject:
274
+
275
+ >>> from scim2_models import UnauthorizedException
276
+ >>> class MeService(ScimService):
277
+ ... def me_target(self, request):
278
+ ... if request.subject is None:
279
+ ... raise UnauthorizedException
280
+ ... return self.get_resource_type("User"), request.subject
281
+
282
+ :doc:`/how-to/serve-the-me-endpoint` also handles the subjects
283
+ without a user.
284
+
272
285
  :raises ~scim2_models.NotImplementedException: By default, so that
273
286
  ``/Me`` answers 501.
274
287
  :raises ~scim2_models.UnauthorizedException: When the request has no
@@ -288,6 +301,19 @@ class ScimService:
288
301
  (:rfc:`RFC 7644 §7.6 <7644#section-7.6>`). Linking the created resource to the subject is left to the
289
302
  application. The exceptions it raises answer the request.
290
303
 
304
+ The following service lets the authenticated clients create their
305
+ user:
306
+
307
+ >>> from scim2_models import UnauthorizedException
308
+ >>> class RegistrationService(ScimService):
309
+ ... def me_creation_type(self, request):
310
+ ... if request.subject is None:
311
+ ... raise UnauthorizedException
312
+ ... return self.get_resource_type("User")
313
+
314
+ :doc:`/how-to/serve-the-me-endpoint` also refuses the clients that
315
+ already have a user, and links the created user to the subject.
316
+
291
317
  :raises ~scim2_models.NotImplementedException: By default, so that a
292
318
  POST on ``/Me`` answers 501.
293
319
  :raises ~scim2_models.UnauthorizedException: When the request has no
@@ -343,6 +369,20 @@ class ScimService:
343
369
  :class:`~scim2_models.ForbiddenException` removes this type from the
344
370
  search. The search answers 403 when every type is removed.
345
371
 
372
+ The following service lets the clients read, and refuses the other
373
+ operations:
374
+
375
+ >>> from scim2_models import ForbiddenException
376
+ >>> from scim2_server.routing import Operation
377
+ >>> READS = {Operation.query, Operation.search, Operation.search_with_body}
378
+ >>> class ReadOnlyService(ScimService):
379
+ ... def authorize(self, request, target, resource_type):
380
+ ... if target.operation not in READS:
381
+ ... raise ForbiddenException(detail="Read-only access")
382
+
383
+ :doc:`/how-to/authenticate-the-clients` checks the scopes of a token
384
+ instead.
385
+
346
386
  :raises ~scim2_models.ForbiddenException: When the client may not
347
387
  perform the operation, for a 403.
348
388
  :raises ~scim2_models.UnauthorizedException: When the request has no
@@ -548,7 +588,19 @@ class ScimService:
548
588
  ) -> str:
549
589
  """Return the URL of a resource.
550
590
 
551
- Override this method to serve the resources at other URLs.
591
+ Override this method to serve the resources at other URLs. The
592
+ following service publishes the resources under the URL of a gateway:
593
+
594
+ >>> class GatewayService(ScimService):
595
+ ... def resource_location(self, base_url, resource_type, resource_id):
596
+ ... return f"https://api.example{resource_type.endpoint}/{resource_id}"
597
+ >>> from scim2_server.utils import load_default_provider
598
+ >>> service = GatewayService(load_default_provider())
599
+ >>> service.resource_location("", service.get_resource_type("User"), "42")
600
+ 'https://api.example/Users/42'
601
+
602
+ :doc:`/how-to/publish-the-resources-at-other-urls` shows the effect on
603
+ the responses.
552
604
  """
553
605
  assert resource_type.endpoint is not None
554
606
  return (
@@ -1322,6 +1374,15 @@ class ScimService:
1322
1374
  provider configuration, for the Bearer and Basic schemes. Override this
1323
1375
  method to announce other schemes, or to add parameters to the
1324
1376
  challenges, such as ``resource_metadata`` (:rfc:`RFC 9728 §5.1 <9728#section-5.1>`).
1377
+ The following service replaces the challenges with a single Bearer
1378
+ challenge that carries ``resource_metadata``:
1379
+
1380
+ >>> class ProtectedResourceService(ScimService):
1381
+ ... def www_authenticate(self, exception):
1382
+ ... url = "https://scim.example/.well-known/oauth-protected-resource"
1383
+ ... return f'Bearer resource_metadata="{url}"'
1384
+
1385
+ :doc:`/how-to/authenticate-the-clients` shows the resulting header.
1325
1386
  """
1326
1387
  schemes = self.config.authentication_schemes or []
1327
1388
  challenges = dict.fromkeys(
@@ -121,8 +121,9 @@ class ScimStorage(ABC):
121
121
 
122
122
  - Every resource it returns is a copy. Changing it does not change the
123
123
  stored resource, and the resources it receives are not changed either.
124
- - It fills ``id``, ``meta.resourceType``, ``meta.created``,
125
- ``meta.lastModified`` and ``meta.version``. It leaves ``meta.location``
124
+ - It fills ``id``, ``meta.resourceType`` and ``meta.version``. It fills
125
+ ``meta.created`` and ``meta.lastModified`` when it stores them, and
126
+ leaves them empty otherwise. It leaves ``meta.location``
126
127
  to the server, which knows the URLs. For the same reason, a reference
127
128
  to another resource, such as ``members.$ref``, can be relative to the
128
129
  SCIM root, such as ``Users/2819c223``. The server returns its URL.
@@ -282,7 +283,14 @@ class ScimStorage(ABC):
282
283
  It does nothing by default. A SQL storage can open a savepoint here,
283
284
  so that a failed operation does not prevent the next ones of a bulk
284
285
  request (:rfc:`RFC 7644 §3.7 <7644#section-3.7>`). Committing the
285
- request is left to the application.
286
+ request is left to the application. The following storage opens a
287
+ SQLAlchemy savepoint:
288
+
289
+ >>> class SQLStorage(ScimStorage):
290
+ ... def operation(self):
291
+ ... return self.session.begin_nested()
292
+
293
+ :doc:`/how-to/write-a-storage` describes the other methods.
286
294
  """
287
295
  return nullcontext()
288
296
 
@@ -167,6 +167,19 @@ class ScimStorageContract:
167
167
  :class:`~scim2_models.NotImplementedException` in that case.
168
168
  """
169
169
 
170
+ stores_created: bool = True
171
+ """Whether the storage stores ``meta.created``.
172
+
173
+ Set it to :data:`False` for a storage that leaves ``meta.created`` empty.
174
+ """
175
+
176
+ stores_last_modified: bool = True
177
+ """Whether the storage stores ``meta.lastModified``.
178
+
179
+ Set it to :data:`False` for a storage that leaves ``meta.lastModified``
180
+ empty.
181
+ """
182
+
170
183
  @pytest.fixture
171
184
  def provider(self) -> ScimProvider:
172
185
  """Return the description of the service the storage serves."""
@@ -248,16 +261,29 @@ class ScimStorageContract:
248
261
  def test_create_fills_the_identifier_and_the_meta(
249
262
  self, storage: Any, user_type: ResourceType, user_model: Any
250
263
  ) -> None:
251
- """A created resource gets an id, its resource type, its dates and a version, but no location."""
264
+ """A created resource gets an id, its resource type and a version, but no location."""
252
265
  (user,) = self.create_users(storage, user_type, user_model, "bjensen")
253
266
 
254
267
  assert user.id
255
268
  assert user.meta.resource_type == user_type.name
256
- assert user.meta.created is not None
257
- assert user.meta.last_modified == user.meta.created
258
269
  assert user.meta.version
259
270
  assert user.meta.location is None
260
271
 
272
+ def test_create_fills_the_stored_dates(
273
+ self, storage: Any, user_type: ResourceType, user_model: Any
274
+ ) -> None:
275
+ """A created resource gets the dates the storage stores, and only them.
276
+
277
+ Per :rfc:`RFC 7643 §3.1 <7643#section-3.1>`, ``lastModified`` is
278
+ ``created`` until the resource changes.
279
+ """
280
+ (user,) = self.create_users(storage, user_type, user_model, "bjensen")
281
+
282
+ assert (user.meta.created is not None) is self.stores_created
283
+ assert (user.meta.last_modified is not None) is self.stores_last_modified
284
+ if self.stores_created and self.stores_last_modified:
285
+ assert user.meta.last_modified == user.meta.created
286
+
261
287
  def test_create_does_not_change_the_given_resource(
262
288
  self, storage: Any, user_type: ResourceType, user_model: Any
263
289
  ) -> None:
@@ -294,6 +320,8 @@ class ScimStorageContract:
294
320
 
295
321
  stored = storage.get(user_type, user.id)
296
322
  assert stored.user_name == "bjensen"
323
+ assert stored.meta.created == user.meta.created
324
+ assert stored.meta.last_modified == user.meta.last_modified
297
325
  assert stored.meta.version == user.meta.version
298
326
 
299
327
  def test_get_returns_a_copy(
@@ -374,7 +402,7 @@ class ScimStorageContract:
374
402
  def test_update_replaces_the_stored_resource(
375
403
  self, storage: Any, user_type: ResourceType, user_model: Any
376
404
  ) -> None:
377
- """An update stores the new state, keeps the creation date, and changes the version."""
405
+ """An update stores the new state, and changes the version."""
378
406
  (user,) = self.create_users(storage, user_type, user_model, "bjensen")
379
407
  user.display_name = "Barbara"
380
408
 
@@ -382,11 +410,23 @@ class ScimStorageContract:
382
410
 
383
411
  assert updated.display_name == "Barbara"
384
412
  assert storage.get(user_type, user.id).display_name == "Barbara"
385
- assert updated.meta.created == user.meta.created
386
- assert updated.meta.last_modified >= user.meta.created
387
413
  assert updated.meta.version != user.meta.version
388
414
  assert updated.meta.location is None
389
415
 
416
+ def test_update_keeps_the_creation_date(
417
+ self, storage: Any, user_type: ResourceType, user_model: Any
418
+ ) -> None:
419
+ """An update keeps the creation date, and does not move the modification date back."""
420
+ (user,) = self.create_users(storage, user_type, user_model, "bjensen")
421
+ user.display_name = "Barbara"
422
+
423
+ updated = storage.update(user_type, user)
424
+
425
+ assert updated.meta.created == user.meta.created
426
+ assert (updated.meta.last_modified is not None) is self.stores_last_modified
427
+ if self.stores_last_modified:
428
+ assert updated.meta.last_modified >= user.meta.last_modified
429
+
390
430
  def test_update_does_not_change_the_given_resource(
391
431
  self, storage: Any, user_type: ResourceType, user_model: Any
392
432
  ) -> None:
@@ -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,7 +20,7 @@ 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 StaticCredentialsApplication
23
+ from scim2_server.testserver.application import CredentialsApplication
24
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
@@ -104,8 +104,31 @@ def build_parser() -> argparse.ArgumentParser:
104
104
  type=basic_credentials,
105
105
  metavar="USER:PASSWORD",
106
106
  help="Accept HTTP Basic credentials, and announce the Basic scheme. "
107
- "Can be repeated. Without --bearer-token nor --basic-auth, the server "
108
- "accepts every request.",
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.",
109
132
  )
110
133
  parser.add_argument(
111
134
  "--precis",
@@ -189,8 +212,34 @@ def main() -> None:
189
212
  json.load(args.service_provider_config)
190
213
  )
191
214
 
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
+
192
238
  announce_authentication_schemes(
193
- config, bool(args.bearer_token), bool(args.basic_auth)
239
+ config,
240
+ bool(args.bearer_token),
241
+ bool(args.basic_auth),
242
+ access_token_validator is not None,
194
243
  )
195
244
 
196
245
  policy = None
@@ -221,17 +270,18 @@ def main() -> None:
221
270
 
222
271
  storages: dict[str | None, InMemoryStorage] = {}
223
272
 
224
- def make_application(tenant: str | None = None) -> StaticCredentialsApplication:
273
+ def make_application(tenant: str | None = None) -> CredentialsApplication:
225
274
  storages[tenant] = InMemoryStorage()
226
- return StaticCredentialsApplication(
275
+ return CredentialsApplication(
227
276
  storages[tenant],
228
277
  provider,
229
278
  service=service,
230
279
  bearer_tokens=args.bearer_token or [],
231
280
  basic_credentials=args.basic_auth or [],
281
+ access_token_validator=access_token_validator,
232
282
  )
233
283
 
234
- def make_tenant_application(tenant: str) -> StaticCredentialsApplication | None:
284
+ def make_tenant_application(tenant: str) -> CredentialsApplication | None:
235
285
  if not args.dynamic_tenants and tenant not in args.tenant:
236
286
  return None
237
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,114 +0,0 @@
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
-
8
- from scim2_models import AuthenticationScheme
9
- from scim2_models import External
10
- from scim2_models import Reference
11
- from scim2_models import ScimProvider
12
- from scim2_models import ServiceProviderConfig
13
- from scim2_models import UnauthorizedException
14
-
15
- from scim2_server.applications.wsgi import WSGIApplication
16
- from scim2_server.requests import ScimRequest
17
- from scim2_server.service import ScimService
18
- from scim2_server.storage import ScimStorage
19
-
20
- BEARER_TOKEN_SCHEME = AuthenticationScheme(
21
- type=AuthenticationScheme.Type.oauthbearertoken,
22
- name="bearer_token",
23
- description="HTTP Bearer Token",
24
- spec_uri=Reference[External]("https://datatracker.ietf.org/doc/html/rfc6750"),
25
- )
26
-
27
- BASIC_SCHEME = AuthenticationScheme(
28
- type=AuthenticationScheme.Type.httpbasic,
29
- name="basic",
30
- description="HTTP Basic",
31
- spec_uri=Reference[External]("https://datatracker.ietf.org/doc/html/rfc7617"),
32
- )
33
-
34
-
35
- def announce_authentication_schemes(
36
- config: ServiceProviderConfig, bearer_token: bool, basic: bool
37
- ) -> None:
38
- """Add the schemes of the accepted credentials to a service provider configuration.
39
-
40
- Without credentials, the application accepts any bearer token. If the
41
- configuration has no scheme then, it announces the bearer token scheme,
42
- because the ``authenticationSchemes`` attribute is required
43
- (:rfc:`RFC 7643 §5 <7643#section-5>`).
44
- """
45
- schemes = list(config.authentication_schemes or [])
46
- if bearer_token or not (basic or schemes):
47
- schemes.append(BEARER_TOKEN_SCHEME)
48
- if basic:
49
- schemes.append(BASIC_SCHEME)
50
- config.authentication_schemes = schemes
51
-
52
-
53
- def _equals(value: str, expected: str) -> bool:
54
- return hmac.compare_digest(value.encode(), expected.encode())
55
-
56
-
57
- def decode_basic_credentials(value: str) -> tuple[str, str] | None:
58
- """Return the user and the password of Basic credentials, or None if they are malformed."""
59
- try:
60
- decoded = base64.b64decode(value, validate=True).decode()
61
- except (binascii.Error, UnicodeDecodeError):
62
- return None
63
- user, separator, password = decoded.partition(":")
64
- if not separator:
65
- return None
66
- return user, password
67
-
68
-
69
- class StaticCredentialsApplication(WSGIApplication):
70
- """A SCIM application that only accepts static bearer tokens and Basic credentials.
71
-
72
- Without token nor credentials, it accepts every request. List
73
- :data:`BEARER_TOKEN_SCHEME` and :data:`BASIC_SCHEME` in the service
74
- provider configuration, so that the 401 responses carry a
75
- :mdn:`WWW-Authenticate` header.
76
- """
77
-
78
- def __init__(
79
- self,
80
- storage: ScimStorage,
81
- provider: ScimProvider,
82
- service: ScimService | None = None,
83
- bearer_tokens: Iterable[str] = (),
84
- basic_credentials: Iterable[tuple[str, str]] = (),
85
- ):
86
- super().__init__(storage, provider, service)
87
- self.bearer_tokens = list(bearer_tokens)
88
- self.basic_credentials = list(basic_credentials)
89
-
90
- def check_auth(self, request: ScimRequest) -> None:
91
- """Refuse a request without one of the bearer tokens or Basic credentials."""
92
- if not self.bearer_tokens and not self.basic_credentials:
93
- return
94
- scheme, _, value = (request.header("Authorization") or "").partition(" ")
95
- if scheme.lower() == "bearer" and self.is_valid_token(value):
96
- return
97
- if scheme.lower() == "basic" and self.are_valid_credentials(value):
98
- return
99
- raise UnauthorizedException
100
-
101
- def is_valid_token(self, token: str) -> bool:
102
- """Tell whether a token is one of the bearer tokens."""
103
- return any(_equals(token, expected) for expected in self.bearer_tokens)
104
-
105
- def are_valid_credentials(self, value: str) -> bool:
106
- """Tell whether encoded Basic credentials are among the accepted ones."""
107
- credentials = decode_basic_credentials(value)
108
- if credentials is None:
109
- return False
110
- user, password = credentials
111
- return any(
112
- _equals(user, expected_user) and _equals(password, expected_password)
113
- for expected_user, expected_password in self.basic_credentials
114
- )
File without changes
File without changes