Storages#
The contract between the server and the data of an application, and the storages that keep the resources in memory.
- class scim2_server.storage.ScimStorage[source]#
Where a SCIM server reads and writes its resources.
Subclass it to connect the server to a data source, such as a SQL database or a directory. The server handles the SCIM protocol, and calls these methods to read, search, create, update and delete resources. Every method receives the
ResourceTypeit applies to, so a single storage can serve several resource types.A storage follows these rules, which
ScimStorageContractchecks:Every resource it returns is a copy. Changing it does not change the stored resource, and the resources it receives are not changed either.
It fills
id,meta.resourceTypeandmeta.version. It fillsmeta.createdandmeta.lastModifiedwhen it stores them, and leaves them empty otherwise. It leavesmeta.locationto the server, which knows the URLs. For the same reason, a reference to another resource, such asmembers.$ref, can be relative to the SCIM root, such asUsers/2819c223. The server returns its URL.The version changes whenever the resource changes. An update that changes nothing may keep it.
A resource that does not exist raises
NotFoundException.A value already taken by an attribute whose uniqueness is
serverorglobalraisesUniquenessException. This holds for sub-attributes too, such asemails.value. Each value of a multi-valued attribute counts on its own, andunique_values()lists them. Two equal values in the same resource do not clash, and the values clients never read are not checked. A storage may let two concurrent writes take the same value.It supports what the
ServiceProviderConfigof the server announces, such as sorting. The server refuses the rest before calling the storage.
- supports_cursors: bool = False#
Whether
search()pages the resources with cursors that give stable pages.Set it to
Trueoncesearch()follows the rules of the cursors. The server refuses to start when its configuration announces cursor pagination and the storage does not support it.
- abstractmethod get(resource_type: ResourceType, resource_id: str, *, response_parameters: ResponseParameters[Any] | None = None) Resource[source]#
Return a resource.
The server passes
response_parameterswhen it returns the resource to the client, for a GET request. The storage may then leave out the attributes the response does not keep, for instance to avoid loading the members of a group. It must return every attribute the response keeps.Path.iter_pathsgives them. The server applies the parameters to the response anyway. Withoutresponse_parameters, the storage returns the whole resource.The whole resource holds the write-only and never returned attributes, such as
password, in the form the storage keeps them, a hash for instance. The server never returns them to the client (RFC 7643 §2.2). It needs them to keep a value that a PUT leaves out (RFC 7644 §3.5.1), and to clear one that a PATCH removes (RFC 7644 §3.5.2.2).A
getmethod withoutresponse_parametersis deprecated, and raises aDeprecationWarning. The server then does not pass the parameters. scim2-server 0.9 will require it.- Raises:
NotFoundException – When no resource of this type has this identifier.
- abstractmethod search(resource_types: list[ResourceType], search_request: SearchRequest[Any], *, position: Any = None) SearchPage[source]#
Return one page of the matching resources, and their number.
The search request is already validated, and its
countis already bounded by themaxResultsof the server. The storage filters, sorts and pages the resources of every given resource type as a single collection. Several resource types mean a search at the server root.An attribute that a resource type does not declare matches none of its resources (RFC 7644 §3.4.2.1).
A
start_indexpages the resources by index. Acursorthat is notNonepages them with a cursor (RFC 9865), when the storagesupports_cursors. The storage then returns thenextandpreviouspositions of the page, as values that JSON can hold. The server hides them in the cursors it gives the client, and passes them back asposition.positionisNoneon the first page.The cursors give stable pages. A position holds the sort value and the identifier of the last resource of the page, or of the first one for the previous page. A resource that exists during the whole paging, and whose sort value does not change, is returned exactly once. A resource created or deleted meanwhile is returned or not, depending on where it sorts.
A
searchmethod withoutpositionis deprecated, and raises aDeprecationWarning. It returns the number of matching resources and the page, and pages by index only. scim2-server 0.9 will requireposition.- Raises:
InvalidFilterException – When the storage cannot evaluate the filter. Filtering the page afterwards would make
totalResultsand the paging wrong.InvalidCursorException – When the storage cannot read
position.NotImplementedException – When the storage does not support searching several resource types at once.
- abstractmethod create(resource_type: ResourceType, resource: Resource) Resource[source]#
Store a new resource, and return the stored resource.
- Raises:
UniquenessException – When a unique value is taken.
- abstractmethod update(resource_type: ResourceType, resource: Resource, *, expected_version: str | None = None) Resource[source]#
Replace the stored resource that has the identifier of
resource, and return the stored resource.The server calls it for PUT and PATCH requests. It applies the request to the stored resource first, so
resourceis the whole new state of the resource.A write-only or never returned value that
get()returned comes back unchanged when the request does not change it. The storage keeps it as it is, and does not hash it again. It clears the value when it comes back asNone.- Parameters:
expected_version – The version the stored resource must still have, when given.
- Raises:
NotFoundException – When the resource does not exist.
PreconditionFailedException – When the stored version is not
expected_version.UniquenessException – When a unique value is taken.
- abstractmethod delete(resource_type: ResourceType, resource_id: str, *, expected_version: str | None = None) None[source]#
Delete a resource.
- Parameters:
expected_version – The version the stored resource must still have, when given.
- Raises:
NotFoundException – When the resource does not exist.
PreconditionFailedException – When the stored version is not
expected_version.
- operation() AbstractContextManager[None][source]#
Enclose one SCIM operation: a single request, or one operation of a bulk request.
It does nothing by default. A SQL storage can open a savepoint here, so that a failed operation does not prevent the next ones of a bulk request (RFC 7644 §3.7). Committing the request is left to the application. The following storage opens a SQLAlchemy savepoint:
>>> class SQLStorage(ScimStorage): ... def operation(self): ... return self.session.begin_nested()
Write a storage describes the other methods.
- class scim2_server.storage.AsyncScimStorage[source]#
The asynchronous variant of
ScimStorage.Its methods are coroutines, and follow the rules of
ScimStorage, whichAsyncScimStorageContractchecks.- supports_cursors: bool = False#
Whether
search()pages the resources with cursors that give stable pages. SeeScimStorage.supports_cursors.
- abstractmethod async get(resource_type: ResourceType, resource_id: str, *, response_parameters: ResponseParameters[Any] | None = None) Resource[source]#
Return a resource. See
ScimStorage.get().
- abstractmethod async search(resource_types: list[ResourceType], search_request: SearchRequest[Any], *, position: Any = None) SearchPage[source]#
Return one page of the matching resources, and their number. See
ScimStorage.search().
- abstractmethod async create(resource_type: ResourceType, resource: Resource) Resource[source]#
Store a new resource. See
ScimStorage.create().
- abstractmethod async update(resource_type: ResourceType, resource: Resource, *, expected_version: str | None = None) Resource[source]#
Replace a stored resource. See
ScimStorage.update().
- abstractmethod async delete(resource_type: ResourceType, resource_id: str, *, expected_version: str | None = None) None[source]#
Delete a resource. See
ScimStorage.delete().
- operation() AbstractAsyncContextManager[None][source]#
Enclose one SCIM operation. See
ScimStorage.operation().
- class scim2_server.storage.SearchPage(total: int | None, resources: list[Resource], next: Any = None, previous: Any = None)[source]#
A page of found resources, as
ScimStorage.search()returns it.- total: int | None#
The number of matching resources, on every page.
It may be
Nonewhen the resources are paged with a cursor (RFC 9865 §2).
- scim2_server.storage.unique_values(resource: Resource, policy: ScimPolicy | None = None) dict[str, list[tuple[Any, Any]]][source]#
Return the values of a resource that no other resource may hold, by the URN of their attribute.
The attributes are those whose uniqueness is
serverorglobal, at any depth, such asuserNameoremails.value. Each value of a multi-valued attribute counts on its own. A missing value is left out.Per RFC 7643 erratum 8279, the uniqueness applies to the resources using the schema that declares the attribute, whatever their resource type. The URN of an attribute holds its schema, so two resources clash when they hold the same value under the same URN.
Each value comes with the form it is compared in, as
comparable()returns it under the policy. This form isNonewhen the policy cannot compare the string: such a value clashes with no other value.The values clients never read, such as a write-only one, are left out: refusing one would tell that another resource holds it.
>>> from scim2_models import User >>> unique_values(User(user_name="BJensen")) {'urn:ietf:params:scim:schemas:core:2.0:User:userName': [('BJensen', 'bjensen')]}
- class scim2_server.memory.InMemoryStorage(clock: Callable[[], ~datetime.datetime]=<function utcnow>)[source]#
A storage keeping the resources in memory, for tests, debugging and demos.
It indexes the resources by identifier and the unique values. A search walks every resource of the searched types, unless it compares a single string attribute to a string with
eq. A lock serializes every access, so it can serve a threaded server.It indexes the values under the policy in effect when they were written, so it serves the resources of a single policy.
- Parameters:
clock – Return the date of a write, for
meta.createdandmeta.lastModified. Pass a fixed clock to get predictable dates.
- generate_id(resource_type: ResourceType, resource: Resource) str[source]#
Return the identifier of a new resource.
Override this method to get predictable identifiers. The following storage numbers the resources from 1:
>>> from itertools import count >>> class NumberedStorage(InMemoryStorage): ... def __init__(self): ... super().__init__() ... self.ids = count(1) ... ... def generate_id(self, resource_type, resource): ... return str(next(self.ids)) >>> storage = NumberedStorage() >>> storage.generate_id(None, None), storage.generate_id(None, None) ('1', '2')
- class scim2_server.memory.AsyncInMemoryStorage(storage: InMemoryStorage | None = None)[source]#
The asynchronous variant of
InMemoryStorage.It serves the resources of an
InMemoryStorage. Every call runs without awaiting anything, so a call is never interrupted by another coroutine.operation()takes no lock: holding the lock of the storage across anawaitwould block the event loop. Two concurrent updates of a resource are still told apart byexpected_version.- Parameters:
storage – The storage to serve. Pass a subclass of
InMemoryStorageto change how identifiers are generated.
Keyset pagination#
Helpers for a storage that pages with cursors by keyset.
A keyset storage orders the rows by the sort value, then by identifier. A position holds the sort value and the identifier of the row a page starts after, or ends before. These helpers read and write such positions, and build the pages around them. A storage may use its own positions instead.
- scim2_server.keyset.encode_sort_value(value: Any) Any[source]#
Return a sort value as a value JSON can hold.
None, booleans, numbers and strings are returned as they are. Adatetime, adate, aDecimalor aUUIDis returned as an object with a tag, such as{"date": "2026-10-09"}, so thatdecode_sort_value()gives it back in its own type.- Raises:
TypeError – if the value has another type.
- scim2_server.keyset.decode_sort_value(value: Any) Any[source]#
Return the sort value that
encode_sort_value()gave.- Raises:
InvalidCursorException – if no sort value gives this value.
- class scim2_server.keyset.Position(forward: bool, key: Any, id: str, type_index: int | None = None)[source]#
The row a cursor page starts after, or ends before.
The rows with the same sort value are ordered by identifier. In a search at the root, a storage may order them by the index of their resource type first, so that two resources of different types can share an identifier.
- type_index: int | None = None#
The index of the resource type of the row, in a search at the root that orders the rows by resource type.
- classmethod load(value: Any, *, has_sort: bool, type_count: int | None = None) Position | None[source]#
Read a position that
dump()wrote, or returnNonefor the first page.has_sorttells whether the search has a sort. Without one, the position holds no sort value.type_countis the number of resource types that the storage orders the rows by. A storage that does not order the rows by resource type leaves it out. The position holds the index of a resource type whentype_countis given, and holds none otherwise.dump()writes this index whentype_indexis notNone.- Raises:
InvalidCursorException – if the value is not such a position.
- class scim2_server.keyset.Bound(key: Any, id: str, type_index: int | None = None)[source]#
The first or the last row of a page, as
keyset_page()needs it.
- scim2_server.keyset.page_rows(rows: Sequence[Any], search_request: SearchRequest[Any], position: Position | None) tuple[list[Any], bool][source]#
Return the rows of a page in the sort order, and whether more rows follow in the reading direction.
For a cursor page, the storage reads
count + 1rows, in the reverse order for a page that ends before the position. Without a cursor, the rows are returned as they are.
- scim2_server.keyset.keyset_page(total: int | None, resources: Sequence[Resource], first: Bound | None, last: Bound | None, more: bool, position: Position | None) SearchPage[source]#
Return a cursor page, with the positions of the pages around it.
firstandlastare the first and the last rows of the page, orNonewhen the page is empty.moretells whether more rows follow in the reading direction, aspage_rows()gives it. In the other direction, the page the client comes from is assumed to still exist.