scim2-server 0.8.6__tar.gz → 0.8.8__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.6 → scim2_server-0.8.8}/PKG-INFO +1 -1
  2. {scim2_server-0.8.6 → scim2_server-0.8.8}/pyproject.toml +1 -1
  3. {scim2_server-0.8.6 → scim2_server-0.8.8}/pyproject.toml.orig +1 -1
  4. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/applications/base.py +28 -2
  5. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/applications/wsgi.py +10 -0
  6. scim2_server-0.8.8/scim2_server/keyset.py +219 -0
  7. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/memory.py +58 -56
  8. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/service.py +62 -1
  9. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/storage.py +11 -3
  10. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/testing.py +149 -6
  11. {scim2_server-0.8.6 → scim2_server-0.8.8}/LICENSE +0 -0
  12. {scim2_server-0.8.6 → scim2_server-0.8.8}/README.md +0 -0
  13. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/__init__.py +0 -0
  14. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/applications/__init__.py +0 -0
  15. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/applications/asgi.py +0 -0
  16. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/bulk.py +0 -0
  17. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/conditions.py +0 -0
  18. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/cursor.py +0 -0
  19. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/errors.py +0 -0
  20. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/handler.py +0 -0
  21. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/py.typed +0 -0
  22. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/requests.py +0 -0
  23. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/resources/default-resource-types.json +0 -0
  24. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/resources/default-schemas.json +0 -0
  25. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/resources/default-service-provider-config.json +0 -0
  26. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/responses.py +0 -0
  27. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/routing.py +0 -0
  28. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/testserver/__init__.py +0 -0
  29. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/testserver/application.py +0 -0
  30. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/testserver/cli.py +0 -0
  31. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/testserver/oauth.py +0 -0
  32. {scim2_server-0.8.6 → scim2_server-0.8.8}/scim2_server/testserver/precis.py +0 -0
  33. {scim2_server-0.8.6 → scim2_server-0.8.8}/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.6
3
+ Version: 0.8.8
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
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "scim2-server"
7
- version = "0.8.6"
7
+ version = "0.8.8"
8
8
  description = "SCIM server core for any storage and web framework"
9
9
  readme = "README.md"
10
10
  keywords = [
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "scim2-server"
7
- version = "0.8.6"
7
+ version = "0.8.8"
8
8
  description = "SCIM server core for any storage and web framework"
9
9
  authors = [
10
10
  {name="Yaal Coop", email="contact@yaal.coop"},
@@ -66,7 +66,20 @@ class BaseApplication:
66
66
 
67
67
  It returns :data:`None` by default. Override it to pass the subject
68
68
  that :meth:`check_auth` authenticated to the service, for
69
- :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.
70
83
  """
71
84
  return None
72
85
 
@@ -78,7 +91,20 @@ class BaseApplication:
78
91
  whose credentials are missing or invalid. Check the rights of the
79
92
  client in :meth:`~scim2_server.service.ScimService.authorize`, which
80
93
  sees each operation of a bulk request. It is not called for
81
- ``/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.
82
108
  """
83
109
 
84
110
  def needs_auth(self, request: ScimRequest) -> bool:
@@ -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("/")
@@ -0,0 +1,219 @@
1
+ """Helpers for a storage that pages with cursors by keyset.
2
+
3
+ A keyset storage orders the rows by the sort value, then by identifier. A
4
+ position holds the sort value and the identifier of the row a page starts
5
+ after, or ends before. These helpers read and write such positions, and build
6
+ the pages around them. A storage may use its own positions instead.
7
+ """
8
+
9
+ import datetime
10
+ import decimal
11
+ import uuid
12
+ from collections.abc import Callable
13
+ from collections.abc import Sequence
14
+ from dataclasses import dataclass
15
+ from typing import Any
16
+
17
+ from scim2_models import InvalidCursorException
18
+ from scim2_models import Resource
19
+ from scim2_models import SearchRequest
20
+
21
+ from scim2_server.storage import SearchPage
22
+
23
+ _TAGGED: dict[str, tuple[type, Callable[[Any], str], Callable[[str], Any]]] = {
24
+ "datetime": (
25
+ datetime.datetime,
26
+ datetime.datetime.isoformat,
27
+ datetime.datetime.fromisoformat,
28
+ ),
29
+ "date": (datetime.date, datetime.date.isoformat, datetime.date.fromisoformat),
30
+ "decimal": (decimal.Decimal, str, decimal.Decimal),
31
+ "uuid": (uuid.UUID, str, uuid.UUID),
32
+ }
33
+ """The sort values JSON has no type for, by tag. A datetime is a date too, so it comes first."""
34
+
35
+
36
+ def encode_sort_value(value: Any) -> Any:
37
+ """Return a sort value as a value JSON can hold.
38
+
39
+ :data:`None`, booleans, numbers and strings are returned as they are.
40
+ A :class:`~datetime.datetime`, a :class:`~datetime.date`, a
41
+ :class:`~decimal.Decimal` or a :class:`~uuid.UUID` is returned as an
42
+ object with a tag, such as ``{"date": "2026-10-09"}``, so that
43
+ :func:`decode_sort_value` gives it back in its own type.
44
+
45
+ :raises TypeError: if the value has another type.
46
+ """
47
+ if value is None or isinstance(value, bool | int | float | str):
48
+ return value
49
+
50
+ for tag, (python_type, dump, _) in _TAGGED.items():
51
+ if isinstance(value, python_type):
52
+ return {tag: dump(value)}
53
+
54
+ raise TypeError(f"Cannot page on a sort value of type {type(value).__name__}")
55
+
56
+
57
+ def decode_sort_value(value: Any) -> Any:
58
+ """Return the sort value that :func:`encode_sort_value` gave.
59
+
60
+ :raises ~scim2_models.InvalidCursorException: if no sort value gives this value.
61
+ """
62
+ if value is None or isinstance(value, bool | int | float | str):
63
+ return value
64
+
65
+ if not isinstance(value, dict) or len(value) != 1:
66
+ raise InvalidCursorException
67
+
68
+ ((tag, text),) = value.items()
69
+ if tag not in _TAGGED or not isinstance(text, str):
70
+ raise InvalidCursorException
71
+
72
+ try:
73
+ return _TAGGED[tag][2](text)
74
+ except (ValueError, decimal.InvalidOperation):
75
+ raise InvalidCursorException from None
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class Bound:
80
+ """The first or the last row of a page, as :func:`keyset_page` needs it."""
81
+
82
+ key: Any
83
+ """The sort value of the row, or :data:`None` when it has none, or when the search has no sort."""
84
+
85
+ id: str
86
+ """The identifier of the resource of the row."""
87
+
88
+ type_index: int | None = None
89
+ """The index of the resource type of the row, in a search at the root that orders the rows by resource type."""
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class Position:
94
+ """The row a cursor page starts after, or ends before.
95
+
96
+ The rows with the same sort value are ordered by identifier. In a search
97
+ at the root, a storage may order them by the index of their resource type
98
+ first, so that two resources of different types can share an identifier.
99
+ """
100
+
101
+ forward: bool
102
+ """Whether the page starts after the row, rather than ending before it."""
103
+
104
+ key: Any
105
+ """The sort value of the row, or :data:`None` when it has none, or when the search has no sort."""
106
+
107
+ id: str
108
+ """The identifier of the resource of the row."""
109
+
110
+ type_index: int | None = None
111
+ """The index of the resource type of the row, in a search at the root that orders the rows by resource type."""
112
+
113
+ @classmethod
114
+ def load(
115
+ cls, value: Any, *, has_sort: bool, type_count: int | None = None
116
+ ) -> "Position | None":
117
+ """Read a position that :meth:`dump` wrote, or return :data:`None` for the first page.
118
+
119
+ ``has_sort`` tells whether the search has a sort. Without one, the
120
+ position holds no sort value.
121
+
122
+ ``type_count`` is the number of resource types that the storage
123
+ orders the rows by. A storage that does not order the rows by
124
+ resource type leaves it out. The position holds the index of a
125
+ resource type when ``type_count`` is given, and holds none
126
+ otherwise. :meth:`dump` writes this index when
127
+ :attr:`type_index` is not :data:`None`.
128
+
129
+ :raises ~scim2_models.InvalidCursorException: if the value is not such
130
+ a position.
131
+ """
132
+ if value is None:
133
+ return None
134
+
135
+ by_type = type_count is not None
136
+ names = {"d", "k", "t", "i"} if by_type else {"d", "k", "i"}
137
+ if not isinstance(value, dict) or set(value) != names:
138
+ raise InvalidCursorException
139
+
140
+ if value["d"] not in ("next", "previous") or not isinstance(value["i"], str):
141
+ raise InvalidCursorException
142
+
143
+ if not has_sort and value["k"] is not None:
144
+ raise InvalidCursorException
145
+
146
+ type_index = value.get("t")
147
+ if by_type and (
148
+ type(type_index) is not int or type_index not in range(type_count or 0)
149
+ ):
150
+ raise InvalidCursorException
151
+
152
+ key = decode_sort_value(value["k"])
153
+ return cls(value["d"] == "next", key, value["i"], type_index)
154
+
155
+ def dump(self) -> dict[str, Any]:
156
+ """Return the position as a value JSON can hold.
157
+
158
+ :raises TypeError: if :func:`encode_sort_value` cannot hold the sort value.
159
+ """
160
+ position: dict[str, Any] = {
161
+ "d": "next" if self.forward else "previous",
162
+ "k": encode_sort_value(self.key),
163
+ }
164
+ if self.type_index is not None:
165
+ position["t"] = self.type_index
166
+
167
+ position["i"] = self.id
168
+ return position
169
+
170
+
171
+ def page_rows(
172
+ rows: Sequence[Any], search_request: SearchRequest[Any], position: Position | None
173
+ ) -> tuple[list[Any], bool]:
174
+ """Return the rows of a page in the sort order, and whether more rows follow in the reading direction.
175
+
176
+ For a cursor page, the storage reads ``count + 1`` rows, in the reverse
177
+ order for a page that ends before the position. Without a cursor, the
178
+ rows are returned as they are.
179
+ """
180
+ if search_request.cursor is None:
181
+ return list(rows), False
182
+
183
+ count = search_request.count
184
+ more = count is not None and len(rows) > count
185
+ page = list(rows if count is None else rows[:count])
186
+ if position is not None and not position.forward:
187
+ page.reverse()
188
+
189
+ return page, more
190
+
191
+
192
+ def keyset_page(
193
+ total: int | None,
194
+ resources: Sequence[Resource[Any]],
195
+ first: Bound | None,
196
+ last: Bound | None,
197
+ more: bool,
198
+ position: Position | None,
199
+ ) -> SearchPage:
200
+ """Return a cursor page, with the positions of the pages around it.
201
+
202
+ ``first`` and ``last`` are the first and the last rows of the page, or
203
+ :data:`None` when the page is empty. ``more`` tells whether more rows
204
+ follow in the reading direction, as :func:`page_rows` gives it. In the
205
+ other direction, the page the client comes from is assumed to still
206
+ exist.
207
+ """
208
+ page = SearchPage(total, list(resources))
209
+ if first is None or last is None:
210
+ return page
211
+
212
+ forward = position is None or position.forward
213
+ if more or not forward:
214
+ page.next = Position(True, last.key, last.id, last.type_index).dump()
215
+
216
+ if position is not None and (more or forward):
217
+ page.previous = Position(False, first.key, first.id, first.type_index).dump()
218
+
219
+ return page
@@ -10,7 +10,6 @@ from typing import Union
10
10
  from typing import cast
11
11
 
12
12
  from scim2_models import AttributeBinding
13
- from scim2_models import InvalidCursorException
14
13
  from scim2_models import Meta
15
14
  from scim2_models import NotFoundException
16
15
  from scim2_models import Path
@@ -25,6 +24,7 @@ from scim2_models import UniquenessException
25
24
  from scim2_models.path import CompareOperator
26
25
  from scim2_models.path import Comparison
27
26
 
27
+ from scim2_server.keyset import Position
28
28
  from scim2_server.storage import AsyncScimStorage
29
29
  from scim2_server.storage import ScimStorage
30
30
  from scim2_server.storage import SearchPage
@@ -39,19 +39,28 @@ def utcnow() -> datetime.datetime:
39
39
 
40
40
 
41
41
  def _page(
42
- search_request: SearchRequest[Any], position: Any, resources: list[Resource[Any]]
42
+ search_request: SearchRequest[Any],
43
+ position: Any,
44
+ resources: list[Resource[Any]],
45
+ names: list[str | None],
43
46
  ) -> SearchPage:
44
- """Sort every matching resource by its sort value then its identifier, and return the page a search asks for.
47
+ """Sort every matching resource by its sort value, its resource type then its identifier, and return the page a search asks for.
45
48
 
46
- A cursor position holds the sort value and the identifier of the resource
47
- the page starts after, or ends before, so the pages stay stable.
49
+ A cursor position holds the sort value, the resource type and the
50
+ identifier of the resource the page starts after, or ends before, so the
51
+ pages stay stable. The resource type is left out of the positions of a
52
+ search on a single resource type.
48
53
  """
54
+ types = {name: index for index, name in enumerate(names)}
49
55
  descending = (
50
56
  search_request.sort_by is not None
51
57
  and search_request.sort_order == SearchRequest.SortOrder.descending
52
58
  )
53
59
  pairs = sorted(
54
- ((_sort_key(search_request, resource), resource) for resource in resources),
60
+ (
61
+ (_sort_key(search_request, types, resource), resource)
62
+ for resource in resources
63
+ ),
55
64
  key=lambda pair: pair[0],
56
65
  reverse=descending,
57
66
  )
@@ -64,40 +73,51 @@ def _page(
64
73
  if search_request.count == 0:
65
74
  return SearchPage(len(found), [])
66
75
 
76
+ type_count = len(types) if len(types) > 1 else None
77
+ anchor = Position.load(
78
+ position, has_sort=search_request.sort_by is not None, type_count=type_count
79
+ )
67
80
  start, stop = _bounds(
68
- [key for key, _ in pairs], position, search_request.count, descending
81
+ [key for key, _ in pairs], anchor, search_request.count, descending
69
82
  )
70
83
  page = SearchPage(len(found), found[start:stop])
71
84
  if page.resources and stop < len(found):
72
- page.next = _position("next", pairs[stop - 1][0])
85
+ page.next = _position(True, pairs[stop - 1][0], type_count)
73
86
  if page.resources and start > 0:
74
- page.previous = _position("previous", pairs[start][0])
87
+ page.previous = _position(False, pairs[start][0], type_count)
75
88
  return page
76
89
 
77
90
 
78
- SortKey = tuple[bool, Any, str]
91
+ SortKey = tuple[bool, Any, int, str]
79
92
 
80
93
 
81
- def _sort_key(search_request: SearchRequest[Any], resource: Resource[Any]) -> SortKey:
82
- """Return the key that orders a resource: its sort value, missing values last, then its identifier."""
94
+ def _sort_key(
95
+ search_request: SearchRequest[Any],
96
+ types: dict[str | None, int],
97
+ resource: Resource[Any],
98
+ ) -> SortKey:
99
+ """Return the key that orders a resource: its sort value, missing values last, then its resource type and its identifier."""
83
100
  value = search_request.sort_value(resource)
84
- return value is None, value if value is not None else "", cast(str, resource.id)
101
+ type_index = types[cast(Meta, resource.meta).resource_type]
102
+ missing = value is None
103
+ return missing, "" if missing else value, type_index, cast(str, resource.id)
85
104
 
86
105
 
87
106
  def _bounds(
88
- keys: list[SortKey], position: Any, count: int | None, descending: bool
107
+ keys: list[SortKey], anchor: Position | None, count: int | None, descending: bool
89
108
  ) -> tuple[int, int]:
90
109
  """Return the slice of the sorted keys that a cursor page covers."""
91
- if position is None:
110
+ if anchor is None:
92
111
  return 0, len(keys) if count is None else min(count, len(keys))
93
112
 
94
- direction, anchor = _read_position(position)
113
+ missing = anchor.key is None
114
+ bound = (missing, "" if missing else anchor.key, anchor.type_index or 0, anchor.id)
95
115
 
96
116
  def before(key: SortKey) -> bool:
97
- return key > anchor if descending else key < anchor
117
+ return key > bound if descending else key < bound
98
118
 
99
- if direction == "next":
100
- start = sum(1 for key in keys if before(key) or key == anchor)
119
+ if anchor.forward:
120
+ start = sum(1 for key in keys if before(key) or key == bound)
101
121
  stop = len(keys) if count is None else min(start + count, len(keys))
102
122
  return start, stop
103
123
 
@@ -106,42 +126,11 @@ def _bounds(
106
126
  return start, stop
107
127
 
108
128
 
109
- def _position(direction: str, key: SortKey) -> dict[str, Any]:
129
+ def _position(forward: bool, key: SortKey, type_count: int | None) -> dict[str, Any]:
110
130
  """Return the position of the page that starts after, or ends before, a sort key."""
111
- missing, value, identifier = key
112
- return {"d": direction, "k": None if missing else _encode(value), "i": identifier}
113
-
114
-
115
- def _read_position(position: Any) -> tuple[str, SortKey]:
116
- """Return the direction and the sort key of a position that _page gave."""
117
- try:
118
- direction, value, identifier = position["d"], position["k"], position["i"]
119
- except (TypeError, KeyError):
120
- raise InvalidCursorException from None
121
- if direction not in ("next", "previous") or not isinstance(identifier, str):
122
- raise InvalidCursorException
123
- if value is None:
124
- return direction, (True, "", identifier)
125
- return direction, (False, _decode(value), identifier)
126
-
127
-
128
- def _encode(value: Any) -> Any:
129
- """Return a sort value in a form JSON can hold."""
130
- if isinstance(value, datetime.datetime):
131
- return {"datetime": value.isoformat()}
132
- if isinstance(value, str | bool | int | float):
133
- return value
134
- raise TypeError(f"A cursor cannot hold a sort value of type {type(value).__name__}")
135
-
136
-
137
- def _decode(value: Any) -> Any:
138
- """Return the sort value that _encode gave."""
139
- if not isinstance(value, dict):
140
- return value
141
- try:
142
- return datetime.datetime.fromisoformat(value["datetime"])
143
- except (KeyError, TypeError, ValueError):
144
- raise InvalidCursorException from None
131
+ missing, value, type_index, identifier = key
132
+ by_type = None if type_count is None else type_index
133
+ return Position(forward, None if missing else value, identifier, by_type).dump()
145
134
 
146
135
 
147
136
  Key = tuple[str | None, str]
@@ -238,7 +227,20 @@ class InMemoryStorage(ScimStorage):
238
227
  def generate_id(self, resource_type: ResourceType, resource: Resource[Any]) -> str:
239
228
  """Return the identifier of a new resource.
240
229
 
241
- Override this method to get predictable identifiers.
230
+ Override this method to get predictable identifiers. The following
231
+ storage numbers the resources from 1:
232
+
233
+ >>> from itertools import count
234
+ >>> class NumberedStorage(InMemoryStorage):
235
+ ... def __init__(self):
236
+ ... super().__init__()
237
+ ... self.ids = count(1)
238
+ ...
239
+ ... def generate_id(self, resource_type, resource):
240
+ ... return str(next(self.ids))
241
+ >>> storage = NumberedStorage()
242
+ >>> storage.generate_id(None, None), storage.generate_id(None, None)
243
+ ('1', '2')
242
244
  """
243
245
  return uuid.uuid4().hex
244
246
 
@@ -285,7 +287,7 @@ class InMemoryStorage(ScimStorage):
285
287
  found = [
286
288
  r for r in candidates if scim_filter is None or scim_filter.match(r)
287
289
  ]
288
- page = _page(search_request, position, found)
290
+ page = _page(search_request, position, found, names)
289
291
  page.resources = [r.model_copy(deep=True) for r in page.resources]
290
292
  return page
291
293
 
@@ -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:
@@ -988,6 +1028,109 @@ class ScimStorageContract:
988
1028
 
989
1029
  assert sorted(self.ids(pages)) == sorted([users[0].id, users[1].id, group.id])
990
1030
 
1031
+ def test_cursor_pages_back_at_the_root(
1032
+ self,
1033
+ storage: Any,
1034
+ user_type: ResourceType,
1035
+ group_type: ResourceType,
1036
+ user_model: Any,
1037
+ group_model: Any,
1038
+ ) -> None:
1039
+ """Following the previous cursors at the root returns the same pages, back to the first."""
1040
+ self.require(storage.supports_cursors, "cursor pagination")
1041
+ self.require(self.supports_root_search, "searching at the root")
1042
+ users = self.create_users(storage, user_type, user_model, "alice", "bob")
1043
+ self.create_group(storage, group_type, group_model, users[0])
1044
+ resource_types = [user_type, group_type]
1045
+ search_request = self.search_request(
1046
+ [user_model, group_model], cursor="", count=1
1047
+ )
1048
+ forward = self.walk(storage, resource_types, search_request)
1049
+
1050
+ backward = self.walk_back(storage, resource_types, search_request, forward[-1])
1051
+
1052
+ assert [[r.id for r in page.resources] for page in reversed(backward)] == [
1053
+ [r.id for r in page.resources] for page in forward[:-1]
1054
+ ]
1055
+ assert backward[-1].previous is None
1056
+
1057
+ def test_cursor_pages_back_in_descending_order_with_missing_values(
1058
+ self,
1059
+ storage: Any,
1060
+ provider: ScimProvider,
1061
+ user_type: ResourceType,
1062
+ user_model: Any,
1063
+ ) -> None:
1064
+ """Following the previous cursors of a descending sort returns the same pages, with the resources without value first."""
1065
+ self.require(storage.supports_cursors, "cursor pagination")
1066
+ self.require(self.announces(provider, "sort"), "sorting")
1067
+ self.require("nick_name" in user_model.model_fields, "nickName")
1068
+ for user_name, nick_name in [
1069
+ ("alice", "a"),
1070
+ ("bob", None),
1071
+ ("carol", "c"),
1072
+ ("dave", "b"),
1073
+ ("erin", None),
1074
+ ]:
1075
+ storage.create(
1076
+ user_type, user_model(user_name=user_name, nick_name=nick_name)
1077
+ )
1078
+
1079
+ search_request = self.search_request(
1080
+ [user_model],
1081
+ cursor="",
1082
+ count=2,
1083
+ sort_by="nickName",
1084
+ sort_order="descending",
1085
+ )
1086
+ forward = self.walk(storage, [user_type], search_request)
1087
+ backward = self.walk_back(storage, [user_type], search_request, forward[-1])
1088
+
1089
+ names = [r.user_name for page in forward for r in page.resources]
1090
+ assert sorted(names[:2]) == ["bob", "erin"]
1091
+ assert names[2:] == ["carol", "dave", "alice"]
1092
+ assert [[r.id for r in page.resources] for page in reversed(backward)] == [
1093
+ [r.id for r in page.resources] for page in forward[:-1]
1094
+ ]
1095
+ assert backward[-1].previous is None
1096
+
1097
+ def test_cursor_pages_by_date(
1098
+ self,
1099
+ storage: Any,
1100
+ provider: ScimProvider,
1101
+ user_type: ResourceType,
1102
+ user_model: Any,
1103
+ ) -> None:
1104
+ """A cursor pages a search sorted by date, in both directions.
1105
+
1106
+ Resources modified at the same time may come in any order.
1107
+ """
1108
+ self.require(storage.supports_cursors, "cursor pagination")
1109
+ self.require(self.announces(provider, "sort"), "sorting")
1110
+ self.require(self.stores_last_modified, "meta.lastModified")
1111
+ created = self.create_users(
1112
+ storage, user_type, user_model, "alice", "bob", "carol", "dave", "erin"
1113
+ )
1114
+ search_request = self.search_request(
1115
+ [user_model], cursor="", count=2, sort_by="meta.lastModified"
1116
+ )
1117
+ first = self.search_or_skip(storage, [user_type], search_request)
1118
+ forward = [first]
1119
+ while forward[-1].next is not None:
1120
+ forward.append(
1121
+ self.search(storage, [user_type], search_request, forward[-1].next)
1122
+ )
1123
+
1124
+ backward = self.walk_back(storage, [user_type], search_request, forward[-1])
1125
+
1126
+ dates = [r.meta.last_modified for page in forward for r in page.resources]
1127
+ assert sorted(self.ids(forward)) == sorted(user.id for user in created)
1128
+ assert dates == sorted(dates)
1129
+ assert [[r.id for r in page.resources] for page in reversed(backward)] == [
1130
+ [r.id for r in page.resources] for page in forward[:-1]
1131
+ ]
1132
+ assert backward[-1].previous is None
1133
+
991
1134
  def test_operation(
992
1135
  self, storage: Any, user_type: ResourceType, user_model: Any
993
1136
  ) -> None:
File without changes
File without changes