From ac318ade7052439feb7b10173c09540656219d81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89loi=20Rivard?= Date: Sat, 28 Nov 2026 15:26:27 +0100 Subject: [PATCH] feat!: rely on database constraints for uniqueness A unique value is now unique within its resource type, and storages rely on the unique constraints of their database. unique_values and holds_any are removed, and ResourceMapping.unique_attributes is public. The server refuses with a 400 a resource holding a unique value twice. uniqueness_conflict builds a 409 that tells the attribute, never the value. The in-memory storages call generate_id after the uniqueness checks, and the asynchronous one can await. --- doc/_examples/async_library_storage.py | 6 +- doc/_examples/async_sqlite_storage.py | 9 +- doc/_examples/library_storage.py | 22 +- doc/_examples/sqlite_storage.py | 12 +- doc/changelog.rst | 28 ++- doc/how-to/check-a-storage.rst | 7 +- doc/how-to/write-a-storage.rst | 33 ++- doc/reference/mapping.rst | 4 +- doc/reference/storages.rst | 4 +- doc/reference/testing.rst | 3 + scim2_server/handler.py | 12 +- scim2_server/mapping/filters.py | 36 ---- scim2_server/mapping/mapping.py | 11 +- scim2_server/memory.py | 188 +++++++++++------- scim2_server/service.py | 77 ++++++- scim2_server/storage.py | 92 +++++---- scim2_server/testing.py | 106 +++------- .../test_repeated_unique_values.py | 161 +++++++++++++++ tests/integration/test_shared_schema.py | 9 +- tests/mapping/backend.py | 121 +++++++---- tests/mapping/tables.py | 37 ++-- tests/mapping/test_contract.py | 3 +- tests/mapping/test_uniqueness.py | 23 +-- tests/test_memory.py | 137 ++++++++++++- tests/test_storage.py | 15 ++ 25 files changed, 786 insertions(+), 370 deletions(-) create mode 100644 tests/integration/test_repeated_unique_values.py diff --git a/doc/_examples/async_library_storage.py b/doc/_examples/async_library_storage.py index 180b4d1..fe1c65b 100644 --- a/doc/_examples/async_library_storage.py +++ b/doc/_examples/async_library_storage.py @@ -12,9 +12,9 @@ from scim2_models import ResourceType from scim2_models import ResponseParameters from scim2_models import SearchRequest -from scim2_models import UniquenessException from doc._examples.library_storage import TABLES +from doc._examples.library_storage import uniqueness_conflict_of from scim2_server.storage import AsyncScimStorage from scim2_server.storage import SearchPage @@ -127,9 +127,9 @@ async def writing(self) -> AsyncIterator[aiosqlite.Connection]: try: yield connection await connection.commit() - except sqlite3.IntegrityError: + except sqlite3.IntegrityError as error: await connection.rollback() - raise UniquenessException from None + raise uniqueness_conflict_of(error) from None async def search( self, diff --git a/doc/_examples/async_sqlite_storage.py b/doc/_examples/async_sqlite_storage.py index 8293af0..8601173 100644 --- a/doc/_examples/async_sqlite_storage.py +++ b/doc/_examples/async_sqlite_storage.py @@ -15,11 +15,12 @@ from scim2_models import ResponseParameters from scim2_models import ScimProvider from scim2_models import SearchRequest -from scim2_models import UniquenessException from doc._examples.sqlite_storage import TABLE +from doc._examples.sqlite_storage import USER_NAME from scim2_server.storage import AsyncScimStorage from scim2_server.storage import SearchPage +from scim2_server.storage import uniqueness_conflict class AsyncSQLiteStorage(AsyncScimStorage): @@ -149,9 +150,11 @@ async def writing(self) -> AsyncIterator[aiosqlite.Connection]: try: yield connection await connection.commit() - except sqlite3.IntegrityError: + except sqlite3.IntegrityError as error: await connection.rollback() - raise UniquenessException from None + if error.sqlite_errorname != "SQLITE_CONSTRAINT_UNIQUE": + raise + raise uniqueness_conflict(USER_NAME) from None async def search( self, diff --git a/doc/_examples/library_storage.py b/doc/_examples/library_storage.py index 79cb9b5..ff3faa7 100644 --- a/doc/_examples/library_storage.py +++ b/doc/_examples/library_storage.py @@ -16,6 +16,7 @@ from scim2_models import Mutability from scim2_models import Name from scim2_models import NotFoundException +from scim2_models import Path from scim2_models import PreconditionFailedException from scim2_models import Required from scim2_models import Resource @@ -23,11 +24,11 @@ from scim2_models import ResponseParameters from scim2_models import SearchRequest from scim2_models import Uniqueness -from scim2_models import UniquenessException from scim2_models import User from scim2_server.storage import ScimStorage from scim2_server.storage import SearchPage +from scim2_server.storage import uniqueness_conflict MEMBERS = """ CREATE TABLE IF NOT EXISTS members ( @@ -47,7 +48,7 @@ CREATE TABLE IF NOT EXISTS books ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, - isbn TEXT UNIQUE, + isbn TEXT UNIQUE COLLATE NOCASE, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ) @@ -67,6 +68,19 @@ class Book(Resource): Member = User[LibraryMember] +UNIQUE_COLUMNS = { + "members.login": Path[Member]("userName").resolve(), + "books.isbn": Path[Book]("isbn").resolve(), +} + + +def uniqueness_conflict_of(error: sqlite3.IntegrityError) -> Exception: + """Return the 409 of a violated UNIQUE constraint, or the error itself for another constraint.""" + if error.sqlite_errorname != "SQLITE_CONSTRAINT_UNIQUE": + return error + column = str(error).removeprefix("UNIQUE constraint failed: ") + return uniqueness_conflict(UNIQUE_COLUMNS[column]) + def meta(resource_type: str, row: sqlite3.Row) -> Meta: return Meta( @@ -230,8 +244,8 @@ def writing(self) -> Iterator[None]: try: with self.connection: yield - except sqlite3.IntegrityError: - raise UniquenessException from None + except sqlite3.IntegrityError as error: + raise uniqueness_conflict_of(error) from None def search( self, diff --git a/doc/_examples/sqlite_storage.py b/doc/_examples/sqlite_storage.py index 232fb98..268fe1c 100644 --- a/doc/_examples/sqlite_storage.py +++ b/doc/_examples/sqlite_storage.py @@ -8,16 +8,20 @@ from scim2_models import Meta from scim2_models import NotFoundException +from scim2_models import Path from scim2_models import PreconditionFailedException from scim2_models import Resource from scim2_models import ResourceType from scim2_models import ResponseParameters from scim2_models import ScimProvider from scim2_models import SearchRequest -from scim2_models import UniquenessException +from scim2_models import User from scim2_server.storage import ScimStorage from scim2_server.storage import SearchPage +from scim2_server.storage import uniqueness_conflict + +USER_NAME = Path[User]("userName").resolve() TABLE = """ CREATE TABLE IF NOT EXISTS resources ( @@ -145,8 +149,10 @@ def writing(self) -> Iterator[None]: try: with self.connection: yield - except sqlite3.IntegrityError: - raise UniquenessException from None + except sqlite3.IntegrityError as error: + if error.sqlite_errorname != "SQLITE_CONSTRAINT_UNIQUE": + raise + raise uniqueness_conflict(USER_NAME) from None def search( self, diff --git a/doc/changelog.rst b/doc/changelog.rst index 10971ae..48c7b07 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,32 @@ Changelog ========= +[Unreleased] +------------ + +Added +^^^^^ +- :meth:`AsyncInMemoryStorage.generate_id ` + can await, for instance to take the identifier of an account created in another service. +- A resource holding the same unique value twice is refused with a 400. +- :func:`~scim2_server.storage.uniqueness_conflict` builds a 409 whose detail tells the + attribute, never the value. + +Changed +^^^^^^^ +- A unique value is unique within its resource type. A storage relies on the unique constraints + of its database. :data:`~scim2_server.testing.MAILBOX_TYPE` replaces ``MAILBOX_TYPES``. +- :meth:`ResourceMapping.unique_attributes ` + is public. +- The in-memory storages call ``generate_id`` after the uniqueness checks, and it may return + ``None``. An identifier already taken gives a 409 instead of replacing the resource. + :class:`~scim2_server.memory.AsyncInMemoryStorage` no longer calls the ``create`` method of the + storage it serves. + +Removed +^^^^^^^ +- ``scim2_server.storage.unique_values`` and ``scim2_server.mapping.filters.holds_any``. + [0.10.0] - 2026-11-27 --------------------- @@ -9,7 +35,7 @@ Added - :class:`~scim2_server.testing.ScimStorageContract` checks the uniqueness of sub-attributes and of multi-valued attributes, for a storage setting :attr:`~scim2_server.testing.ScimStorageContract.stores_mailboxes`. - :func:`~scim2_server.storage.unique_values` lists the values a storage checks. + ``scim2_server.storage.unique_values`` lists the values a storage checks. Changed ^^^^^^^ diff --git a/doc/how-to/check-a-storage.rst b/doc/how-to/check-a-storage.rst index f4a1e61..00a1928 100644 --- a/doc/how-to/check-a-storage.rst +++ b/doc/how-to/check-a-storage.rst @@ -10,6 +10,8 @@ The suite checks what the method signatures do not tell: the copies, the 404 and the dates and versions, the uniqueness of ``userName``, and the filters, sorting and paging of the searches. It runs each filter and each sort of a list, and compares the answer of the storage with the rules of SCIM. It uses the ``User`` and ``Group`` resource types of :rfc:`RFC 7643 <7643>`. +Run it on the database engine the application uses: a missing unique constraint then fails the +tests of the uniqueness. Run the suite ------------- @@ -125,9 +127,8 @@ to :data:`False`. The suite checks the uniqueness of sub-attributes and of multi-valued attributes on :class:`~scim2_server.testing.Mailbox` resources. To run these tests, set -:attr:`~scim2_server.testing.ScimStorageContract.stores_mailboxes` to :data:`True`, and serve the -``Mailbox`` and ``SharedMailbox`` resource types. Both use the -:class:`~scim2_server.testing.Mailbox` model. +:attr:`~scim2_server.testing.ScimStorageContract.stores_mailboxes` to :data:`True`, and serve +:data:`~scim2_server.testing.MAILBOX_TYPE`. A storage refuses a filter it cannot translate with :class:`~scim2_models.InvalidFilterException`, and a sort with :class:`~scim2_models.InvalidPathException`. The suite skips the filters and the diff --git a/doc/how-to/write-a-storage.rst b/doc/how-to/write-a-storage.rst index 3ca93a1..501cc8a 100644 --- a/doc/how-to/write-a-storage.rst +++ b/doc/how-to/write-a-storage.rst @@ -159,13 +159,21 @@ and start its version at 1: Refuse a duplicate value ------------------------ -In the default user resource, the ``userName`` of a user is unique, whatever its case. Compare the -values in the form :meth:`AttributeBinding.comparable ` -returns, as the filters do. The example relies on ``COLLATE NOCASE``, which only ignores the case -of ASCII letters: ``Élise`` and ``élise`` remain two users. On a creation and on an update, raise -:class:`~scim2_models.UniquenessException` when another user already has the value. The ``UNIQUE`` constraint of the table refuses such a write, even when two -requests arrive at the same time. The example commits each write, and turns the refusal into the -exception: +In the default user resource, the ``userName`` of a user is unique, whatever its case. Let the +database refuse a duplicate value with a unique constraint: it holds even when two requests arrive +at the same time. Two values that the filters find equal must be equal for the constraint too, +or a filter with ``eq`` finds two users. The filters compare the values in the form +:meth:`AttributeBinding.comparable ` returns. The +example relies on ``COLLATE NOCASE``, which only ignores the case of ASCII letters: ``Élise`` and +``élise`` remain two users. Document such differences for the users of the storage. + +On a creation and on an update, raise :class:`~scim2_models.UniquenessException` when the +constraint refuses the write. Build it with :func:`~scim2_server.storage.uniqueness_conflict`: its +detail tells the attribute, and never the value. For a constraint on a field that holds no SCIM +attribute, raise the exception without detail, and do not pass on the message of the database, +which may hold the value. Turn only the violations of a unique constraint +into this exception: another error, such as a missing value, is a bug. The example commits each +write, and turns the refusal into the exception: .. tab-set:: :class: outline @@ -187,9 +195,14 @@ exception: :dedent: 4 A sub-attribute can be unique too, such as the ``value`` of an email in a model of yours. Each -value of a multi-valued attribute then counts on its own, and two equal values in the same -resource do not clash. :func:`~scim2_server.storage.unique_values` lists the unique values of a -resource, by attribute. +value of a multi-valued attribute then counts on its own: put the constraint on the column of the +table holding the entries. The server refuses a resource holding the same unique value twice +before calling the storage. On an update, delete the former entries before inserting the new +ones, in the same transaction. A resource keeping a value, or swapping values between its +entries, then breaks no constraint. + +The uniqueness holds within a resource type. Two resource types stored in two tables do not share +their unique values. Update a resource ----------------- diff --git a/doc/reference/mapping.rst b/doc/reference/mapping.rst index 158192f..9e3e038 100644 --- a/doc/reference/mapping.rst +++ b/doc/reference/mapping.rst @@ -42,7 +42,7 @@ Resolution ---------- .. autoclass:: scim2_server.mapping.ResourceMapping - :members: schemas + :members: schemas, unique_attributes .. autoclass:: scim2_server.mapping.MappingProblem @@ -53,7 +53,7 @@ Filters and sorts ----------------- .. automodule:: scim2_server.mapping.filters - :members: Predicates, where, compare, present, entry_present, sort_target, holds, holds_any + :members: Predicates, where, compare, present, entry_present, sort_target, holds Reading and writing ------------------- diff --git a/doc/reference/storages.rst b/doc/reference/storages.rst index 99492cd..4006ffb 100644 --- a/doc/reference/storages.rst +++ b/doc/reference/storages.rst @@ -13,13 +13,13 @@ resources in memory. .. autoclass:: scim2_server.storage.SearchPage :members: -.. autofunction:: scim2_server.storage.unique_values +.. autofunction:: scim2_server.storage.uniqueness_conflict .. autoclass:: scim2_server.memory.InMemoryStorage :members: generate_id, next_version, operation .. autoclass:: scim2_server.memory.AsyncInMemoryStorage - :members: resources + :members: resources, generate_id Keyset pagination ----------------- diff --git a/doc/reference/testing.rst b/doc/reference/testing.rst index dec65c8..4d8ab95 100644 --- a/doc/reference/testing.rst +++ b/doc/reference/testing.rst @@ -13,4 +13,7 @@ The test suites checking that a storage follows the storage contract. They need .. autoclass:: scim2_server.testing.MailboxOwner() +.. autodata:: scim2_server.testing.MAILBOX_TYPE + :no-value: + .. autoclass:: scim2_server.testing.AsyncScimStorageContract diff --git a/scim2_server/handler.py b/scim2_server/handler.py index 10834aa..152fbb0 100644 --- a/scim2_server/handler.py +++ b/scim2_server/handler.py @@ -309,9 +309,9 @@ def apply_bulk_operation( request the operation stands for. """ if operation.method == BulkOperation.Method.post: - return self.storage.create( - resource_type, cast(Resource[Any], operation.data) - ) + resource = cast(Resource[Any], operation.data) + self.service.check_unique_values(resource) + return self.storage.create(resource_type, resource) resource_id = cast(str, operation.resource_id) conditions = Conditions(if_match=operation.version) @@ -649,9 +649,9 @@ async def apply_bulk_operation( request the operation stands for. """ if operation.method == BulkOperation.Method.post: - return await self.storage.create( - resource_type, cast(Resource[Any], operation.data) - ) + resource = cast(Resource[Any], operation.data) + self.service.check_unique_values(resource) + return await self.storage.create(resource_type, resource) resource_id = cast(str, operation.resource_id) conditions = Conditions(if_match=operation.version) diff --git a/scim2_server/mapping/filters.py b/scim2_server/mapping/filters.py index b7d53a4..22edc73 100644 --- a/scim2_server/mapping/filters.py +++ b/scim2_server/mapping/filters.py @@ -12,7 +12,6 @@ from typing import Any from typing import Protocol from typing import TypeVar -from typing import cast from scim2_models import AttributeBinding from scim2_models import InvalidFilterException @@ -456,41 +455,6 @@ def compare( ) -def holds_any( - mapping: ResourceMapping, - conditions: Predicates[C], - policy: ScimPolicy, - binding: AttributeBinding, - values: list[Any], -) -> C: - """Return the condition that a record holds one of some values of an attribute. - - The attribute is one of the unique attributes of the mapping, and the - values are those of a resource, as - :func:`~scim2_server.storage.unique_values` returns them. The values are - compared as a filter with ``eq`` compares them, in the record, in an - Entry, in the entries of a collection or in a Link. The condition does - not leave out the written resource: the storage does. - """ - - def any_value(inner: Predicates[C], column: Column) -> C: - return inner.any( - compare(mapping, inner, policy, column, CompareOperator.eq, value) - for value in values - ) - - holders = [ - (collection, cast(Column, column)) - for collection, column in mapping._lookup(binding) - ] - return conditions.any( - any_value(conditions, column) - if collection is None - else conditions.exists(collection, partial(any_value, column=column)) - for collection, column in holders - ) - - def _compare_constant( mapping: ResourceMapping, conditions: Predicates[C], diff --git a/scim2_server/mapping/mapping.py b/scim2_server/mapping/mapping.py index 20c8a40..d1db7a7 100644 --- a/scim2_server/mapping/mapping.py +++ b/scim2_server/mapping/mapping.py @@ -850,13 +850,14 @@ def _string_columns(self) -> Iterator[Column]: if column.is_string: yield column - def _unique_attributes(self) -> dict[str, AttributeBinding]: + def unique_attributes(self) -> dict[str, AttributeBinding]: """Return the attributes whose values no two resources share, by URN. - They may be held by the record, by an Entry, by the entries of a - collection, or be the value of a Link. A value the storage only reads - counts too, as clients read it. The id is left out: the storage - generates it. + A storage puts a unique constraint on the fields holding them. They + may be held by the record, by an Entry, by the entries of a + collection, or be the value of a Link. A field the storage only reads + counts too, as clients read it. The id is left out: it is the primary + key. """ columns = [ *(column for column in self._columns.values() if column is not self._id), diff --git a/scim2_server/memory.py b/scim2_server/memory.py index 3075074..9fac809 100644 --- a/scim2_server/memory.py +++ b/scim2_server/memory.py @@ -19,7 +19,6 @@ from scim2_models import ResponseParameters from scim2_models import ScimFilter from scim2_models import SearchRequest -from scim2_models import UniquenessException from scim2_models.path import CompareOperator from scim2_models.path import Comparison @@ -27,9 +26,11 @@ from scim2_server.storage import AsyncScimStorage from scim2_server.storage import ScimStorage from scim2_server.storage import SearchPage +from scim2_server.storage import _unique_values +from scim2_server.storage import _uniqueness_conflict from scim2_server.storage import projection from scim2_server.storage import search_page -from scim2_server.storage import unique_values +from scim2_server.storage import uniqueness_conflict from scim2_server.utils import parametrize @@ -163,26 +164,15 @@ def _equality(scim_filter: ScimFilter[Any] | None) -> AttributeBinding | None: return binding -def _hashable(value: Any) -> Any: - """Return a form of a value that a dict can hold as a key. - - Lists and models cannot be hashed, so they are held by their - representation. - """ - try: - hash(value) - except TypeError: - return repr(value) - return value - - class InMemoryStorage(ScimStorage): """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 resources by identifier and the unique values. A unique + value is unique within its resource type, as a database does with a + unique constraint on a table. 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. @@ -195,8 +185,8 @@ class InMemoryStorage(ScimStorage): def __init__(self, clock: Callable[[], datetime.datetime] = utcnow) -> None: self._resources: dict[str | None, dict[str, Resource[Any]]] = {} - self._owners: dict[str, dict[Any, Key]] = {} - self._unique_values: dict[Key, dict[str, set[Any]]] = {} + self._owners: dict[tuple[str | None, str], dict[Any, Key]] = {} + self._unique_values: dict[Key, dict[AttributeBinding, set[Any]]] = {} self._equalities: dict[ str | None, dict[AttributeBinding, dict[Any, set[str]]] ] = {} @@ -224,11 +214,13 @@ def resources(self, resources: list[Resource[Any]]) -> None: for resource in resources: self._store(resource, self._values_of(resource)) - def generate_id(self, resource_type: ResourceType, resource: Resource[Any]) -> str: - """Return the identifier of a new resource. + def generate_id( + self, resource_type: ResourceType, resource: Resource[Any] + ) -> str | None: + """Return the identifier of a new resource, or :data:`None` to let the storage draw one. - Override this method to get predictable identifiers. The following - storage numbers the resources from 1: + Override this method to choose the identifiers. The following storage + numbers the resources from 1: >>> from itertools import count >>> class NumberedStorage(InMemoryStorage): @@ -241,6 +233,11 @@ def generate_id(self, resource_type: ResourceType, resource: Resource[Any]) -> s >>> storage = NumberedStorage() >>> storage.generate_id(None, None), storage.generate_id(None, None) ('1', '2') + + The storage calls it once for each new resource, after checking its + unique values, so a refused resource gets no identifier. An identifier + that another resource of the same resource type holds raises + :class:`~scim2_models.UniquenessException`. """ return uuid.uuid4().hex @@ -295,19 +292,9 @@ def create( self, resource_type: ResourceType, resource: Resource[Any] ) -> Resource[Any]: with self.lock: - resource = resource.model_copy(deep=True) - resource.id = self.generate_id(resource_type, resource) - now = self.clock() - resource.meta = Meta( - resource_type=resource_type.name, - created=now, - last_modified=now, - version=self.next_version(), - ) - values = self._values_of(resource) - self._check_uniqueness(resource, values) - self._store(resource, values) - return resource.model_copy(deep=True) + resource = self._check_new(resource_type, resource) + resource_id = self.generate_id(resource_type, resource) + return self._insert(resource_type, resource, resource_id) def update( self, @@ -330,7 +317,7 @@ def update( } ) values = self._values_of(updated) - self._check_uniqueness(updated, values) + self._check_uniqueness(_key(updated), values) self._store(updated, values) return updated.model_copy(deep=True) @@ -391,14 +378,16 @@ def _index_equality( self._equal_values.setdefault(key, {})[binding] = value self._equalities[key[0]][binding].setdefault(value, set()).add(key[1]) - def _store(self, resource: Resource[Any], values: dict[str, set[Any]]) -> None: + def _store( + self, resource: Resource[Any], values: dict[AttributeBinding, set[Any]] + ) -> None: """Keep a resource under its resource type and its identifier, and index its values.""" key = _key(resource) self._remove(key) self._resources.setdefault(key[0], {})[key[1]] = resource self._unique_values[key] = values - for urn, held in values.items(): - owners = self._owners.setdefault(urn, {}) + for attribute, held in values.items(): + owners = self._owners.setdefault((key[0], attribute.urn), {}) for value in held: owners[value] = key @@ -408,8 +397,8 @@ def _store(self, resource: Resource[Any], values: dict[str, set[Any]]) -> None: def _remove(self, key: Key) -> None: """Forget a resource and its indexed values.""" self._resources.get(key[0], {}).pop(key[1], None) - for urn, held in self._unique_values.pop(key, {}).items(): - owners = self._owners[urn] + for attribute, held in self._unique_values.pop(key, {}).items(): + owners = self._owners[key[0], attribute.urn] for value in held: if owners.get(value) == key: del owners[value] @@ -433,30 +422,69 @@ def _check_version(resource: Resource[Any], expected_version: str | None) -> Non if expected_version is not None and resource.meta.version != expected_version: raise PreconditionFailedException + def _check_new( + self, resource_type: ResourceType, resource: Resource[Any] + ) -> Resource[Any]: + """Return a copy of a new resource, refusing a unique value another resource holds.""" + with self.lock: + resource = resource.model_copy(deep=True) + self._check_uniqueness( + (resource_type.name, None), self._values_of(resource) + ) + return resource + + def _insert( + self, + resource_type: ResourceType, + resource: Resource[Any], + resource_id: str | None, + ) -> Resource[Any]: + """Store a new resource under an identifier. + + The unique values are checked again: generate_id may have changed the + resource, and another resource may have taken a value meanwhile. + """ + with self.lock: + if resource_id is None: + resource_id = uuid.uuid4().hex + + if resource_id in self._resources.get(resource_type.name, {}): + raise _uniqueness_conflict("id") + + values = self._values_of(resource) + self._check_uniqueness((resource_type.name, resource_id), values) + resource.id = resource_id + now = self.clock() + resource.meta = Meta( + resource_type=resource_type.name, + created=now, + last_modified=now, + version=self.next_version(), + ) + self._store(resource, values) + return resource.model_copy(deep=True) + def _check_uniqueness( - self, resource: Resource[Any], values: dict[str, set[Any]] + self, + key: tuple[str | None, str | None], + values: dict[AttributeBinding, set[Any]], ) -> None: - """Refuse a resource sharing a unique value with another resource.""" - key = _key(resource) - for urn, held in values.items(): - owners = self._owners.get(urn, {}) + """Refuse the unique values that another resource of the type of key holds.""" + for attribute, held in values.items(): + owners = self._owners.get((key[0], attribute.urn), {}) if any(owners.get(value, key) != key for value in held): - raise UniquenessException() + raise uniqueness_conflict(attribute) - def _values_of(self, resource: Resource[Any]) -> dict[str, set[Any]]: - """Return the unique values of a resource, by the URN of their attribute. + @staticmethod + def _values_of(resource: Resource[Any]) -> dict[AttributeBinding, set[Any]]: + """Return the unique values of a resource, by attribute. - A value the policy cannot compare never clashes, as a missing value - does not. The values are compared under the policy of the write that - stored them, so a storage serves the resources of a single policy. + The values are compared under the policy of the write that stored + them, so a storage serves the resources of a single policy. """ return { - urn: { - _hashable(comparable) - for _, comparable in pairs - if comparable is not None - } - for urn, pairs in unique_values(resource).items() + attribute: set(values) + for attribute, values in _unique_values(resource).items() } @staticmethod @@ -480,13 +508,18 @@ class AsyncInMemoryStorage(AsyncScimStorage): """The asynchronous variant of :class:`InMemoryStorage`. It serves the resources of an :class:`InMemoryStorage`. Every call runs - without awaiting anything, so a call is never interrupted by another - coroutine. :meth:`~scim2_server.storage.AsyncScimStorage.operation` takes no lock: holding the lock of the - storage across an ``await`` would block the event loop. Two concurrent - updates of a resource are still told apart by ``expected_version``. - - :param storage: The storage to serve. Pass a subclass of - :class:`InMemoryStorage` to change how identifiers are generated. + without awaiting anything but :meth:`generate_id`, so a call is never + interrupted by another coroutine while it reads or writes the resources. + :meth:`~scim2_server.storage.AsyncScimStorage.operation` takes no lock: + holding the lock of the storage across an ``await`` would block the event + loop. Two concurrent updates of a resource are still told apart by + ``expected_version``. + + :param storage: The storage to serve. Its + :meth:`~InMemoryStorage.generate_id` gives the identifiers, unless + :meth:`generate_id` is overridden. Its other methods serve the + requests, except ``create``: a new resource goes through + :meth:`generate_id` instead. """ supports_cursors = True @@ -521,10 +554,27 @@ async def search( ) -> SearchPage: return search_page(self.storage, resource_types, search_request, position) + async def generate_id( + self, resource_type: ResourceType, resource: Resource[Any] + ) -> str | None: + """Return the identifier of a new resource, or :data:`None` to let the storage draw one. + + It returns what :meth:`InMemoryStorage.generate_id` returns. Override + it with an ``async def`` method to choose the identifiers. It can + await, for instance to create the account in another service and take + its identifier. The storage checks the unique values + again once it returns. A write refused then, because another resource + took a value in the meantime, does not undo what the method did. + """ + with self.storage.lock: + return self.storage.generate_id(resource_type, resource) + async def create( self, resource_type: ResourceType, resource: Resource[Any] ) -> Resource[Any]: - return self.storage.create(resource_type, resource) + resource = self.storage._check_new(resource_type, resource) + resource_id = await self.generate_id(resource_type, resource) + return self.storage._insert(resource_type, resource, resource_id) async def update( self, diff --git a/scim2_server/service.py b/scim2_server/service.py index 7d313bd..5fbb9ba 100644 --- a/scim2_server/service.py +++ b/scim2_server/service.py @@ -12,6 +12,7 @@ from pydantic import ValidationError from pydantic_core import from_json +from scim2_models import AttributeBinding from scim2_models import AuthenticationScheme from scim2_models import BaseModel from scim2_models import Bulk @@ -56,6 +57,8 @@ from scim2_server.routing import Target from scim2_server.routing import match from scim2_server.storage import SearchPage +from scim2_server.storage import _attribute_path +from scim2_server.storage import _unique_values from scim2_server.utils import parametrize if TYPE_CHECKING: @@ -104,6 +107,34 @@ def scim_exception_of(exception: ValidationError) -> SCIMException: ) +def _repeated(resource: Resource[Any] | None) -> list[tuple[AttributeBinding, Any]]: + """Return the unique values a resource holds more than once, with their attribute, in the order of the attributes.""" + if resource is None: + return [] + + repeated = [] + for attribute, values in _unique_values(resource).items(): + seen: set[Any] = set() + for value in values: + if value in seen: + repeated.append((attribute, value)) + + seen.add(value) + + return repeated + + +def _refuse_repeated( + resource: Resource[Any], held: list[tuple[AttributeBinding, Any]] +) -> None: + """Refuse the unique values a resource holds more than once, but those in held.""" + refused = [pair for pair in _repeated(resource) if pair not in held] + if refused: + attribute, _ = refused[0] + path = _attribute_path(attribute) + raise InvalidValueException(detail=f"The attribute {path} holds a value twice") + + def is_json_media_type(content_type: str | None) -> bool: """Tell whether a Content-Type header designates JSON. @@ -716,13 +747,38 @@ def check_preconditions( def read_creation( self, resource_type: ResourceType, body: bytes, content_type: str | None ) -> Resource[Any]: - """Validate the body of a creation request.""" - return self.read_body( + """Validate the body of a creation request. + + :raises ~scim2_models.InvalidValueException: When the resource holds a + unique value twice. + """ + resource = self.read_body( self.get_model(resource_type), body, content_type, Context.RESOURCE_CREATION_REQUEST, ) + self.check_unique_values(resource) + return resource + + @staticmethod + def check_unique_values( + resource: Resource[Any], current: Resource[Any] | None = None + ) -> None: + """Refuse a resource holding the same unique value twice. + + Two values are the same when a filter with ``eq`` finds them equal. + A storage relies on unique constraints. They would refuse such a + resource too, but with a 409, although no other resource holds the + value. A value that ``current``, the stored state of the resource, + already holds twice is accepted, so that such a resource can still + be changed. + + :raises ~scim2_models.InvalidValueException: When an attribute whose + uniqueness is ``server`` or ``global`` holds a value twice, such + as two emails with the same unique ``value``. + """ + _refuse_repeated(resource, _repeated(current)) def creation_response(self, base_url: str, created: Resource[Any]) -> ScimResponse: """Return the 201 response to a creation, with the location of the resource.""" @@ -1035,9 +1091,15 @@ def apply_replacement( :return: The new state of the resource, or :data:`None` when the replacement changes nothing. Such a PUT keeps meta.lastModified and the ETag. + :raises ~scim2_models.InvalidValueException: When the new state holds + a unique value twice. """ self.check_preconditions(current, "PUT", conditions) - return replacement if replacement.replace(current) else None + if not replacement.replace(current): + return None + + self.check_unique_values(replacement, current) + return replacement def replacement_response( self, @@ -1078,9 +1140,16 @@ def apply_patch( :return: The new state of the resource, or :data:`None` when the PATCH changes nothing. Such a PATCH keeps meta.lastModified and the ETag. + :raises ~scim2_models.InvalidValueException: When the new state holds + a unique value twice. """ self.check_preconditions(current, "PATCH", conditions) - return current if patch_op.patch(current) else None + held = _repeated(current) + if not patch_op.patch(current): + return None + + _refuse_repeated(current, held) + return current def patch_response( self, diff --git a/scim2_server/storage.py b/scim2_server/storage.py index 5ad2c61..f6402f3 100644 --- a/scim2_server/storage.py +++ b/scim2_server/storage.py @@ -11,15 +11,16 @@ from weakref import WeakKeyDictionary from scim2_models import AttributeBinding +from scim2_models import Extension from scim2_models import Mutability from scim2_models import Path from scim2_models import Resource from scim2_models import ResourceType from scim2_models import ResponseParameters from scim2_models import Returned -from scim2_models import ScimPolicy from scim2_models import SearchRequest from scim2_models import Uniqueness +from scim2_models import UniquenessException from scim2_server.utils import parametrize @@ -52,43 +53,53 @@ def projection( return {"response_parameters": response_parameters} -def unique_values( - resource: Resource[Any], policy: ScimPolicy | None = None -) -> dict[str, list[tuple[Any, Any]]]: - """Return the values of a resource that no other resource may hold, by the URN of their attribute. +def uniqueness_conflict(attribute: AttributeBinding) -> UniquenessException: + """Return the 409 refusing a value that another resource holds, for one of the :meth:`~scim2_server.mapping.ResourceMapping.unique_attributes`. - The attributes are those whose uniqueness is ``server`` or ``global``, - at any depth, such as ``userName`` or ``emails.value``. Each value of a - multi-valued attribute counts on its own. A missing value is left out. + The detail tells the attribute, but never the value. An attribute of + the schema of the resource is told by its path, such as ``emails.value``. + An attribute of an extension is told by its URN. - 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. + >>> from scim2_models import Path, User + >>> uniqueness_conflict(Path[User]("emails.value").resolve()).detail + 'Uniqueness conflict with attribute emails.value' + """ + return _uniqueness_conflict(_attribute_path(attribute)) + + +def _attribute_path(attribute: AttributeBinding) -> str: + """Return the path of an attribute of the schema of the resource, or the URN of an attribute of an extension.""" + if issubclass(attribute.model, Extension): + return attribute.urn + + return attribute.urn.rpartition(":")[2] + + +def _uniqueness_conflict(path: str) -> UniquenessException: + return UniquenessException(detail=f"Uniqueness conflict with attribute {path}") - Each value comes with the form it is compared in, as - :meth:`~scim2_models.AttributeBinding.comparable` returns it under the - policy. This form is :data:`None` when 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. +def _unique_values(resource: Resource[Any]) -> dict[AttributeBinding, list[Any]]: + """Return the unique values of a resource, by attribute, in the form they are compared in. - >>> from scim2_models import User - >>> unique_values(User(user_name="BJensen")) - {'urn:ietf:params:scim:schemas:core:2.0:User:userName': [('BJensen', 'bjensen')]} + The attributes are those whose uniqueness is server or global, at any + depth, and that clients read. Each value of a multi-valued attribute + counts on its own. A missing value is left out, and so is a value the + policy cannot compare: it is equal to no other value. A value that cannot + be hashed, such as a complex one, is held by its representation. """ model_path = parametrize(Path, type(resource)) - values: dict[str, list[tuple[Any, Any]]] = {} + values: dict[AttributeBinding, list[Any]] = {} for attribute in _unique_attributes(type(resource)): held = model_path(attribute.urn).get(resource, strict=False) - pairs = [ - (value, _comparable(attribute, value, policy)) + comparables = [ + _hashable(comparable) for value in (held if isinstance(held, list) else [held]) if value is not None + and (comparable := _comparable(attribute, value)) is not None ] - if pairs: - values[attribute.urn] = pairs + if comparables: + values[attribute] = comparables return values @@ -130,15 +141,26 @@ def _hidden(attribute: AttributeBinding) -> bool: return Returned.never in returned or Mutability.write_only in mutability -def _comparable( - attribute: AttributeBinding, value: Any, policy: ScimPolicy | None -) -> Any: +def _comparable(attribute: AttributeBinding, value: Any) -> Any: try: - return attribute.comparable(value, policy) + return attribute.comparable(value) except ValueError: return None +def _hashable(value: Any) -> Any: + """Return a form of a value that a dict can hold as a key. + + Lists and models cannot be hashed, so they are held by their + representation. + """ + try: + hash(value) + except TypeError: + return repr(value) + return value + + @dataclass class SearchPage: """A page of found resources, as :meth:`ScimStorage.search` returns it.""" @@ -230,10 +252,12 @@ class ScimStorage(ABC): - A value already taken by an attribute whose uniqueness is ``server`` or ``global`` raises :class:`~scim2_models.UniquenessException`. This holds for sub-attributes too, such as ``emails.value``. Each value of a - multi-valued attribute counts on its own, and :func:`unique_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. + multi-valued attribute counts on its own. The uniqueness holds within + a resource type. A storage on a database relies on its unique + constraints, and turns their violations into the exception. The + constraint should find equal the values the filters find equal, and the + storage documents the differences. A resource keeping its values, or + swapping them between its entries, is written. - It supports what the :class:`~scim2_models.ServiceProviderConfig` of the server announces, such as sorting. The server refuses the rest before calling the storage. diff --git a/scim2_server/testing.py b/scim2_server/testing.py index 6826733..941add1 100644 --- a/scim2_server/testing.py +++ b/scim2_server/testing.py @@ -186,15 +186,13 @@ class Mailbox(Resource[Any]): owner: MailboxOwner | None = None -MAILBOX_TYPES = [ - ResourceType( - id=name, - name=name, - endpoint=Reference[URI](f"/{name}es"), - schema_=Reference[URI](str(Mailbox.__schema__)), - ) - for name in ("Mailbox", "SharedMailbox") -] +MAILBOX_TYPE = ResourceType( + id="Mailbox", + name="Mailbox", + endpoint=Reference[URI]("/Mailboxes"), + schema_=Reference[URI](str(Mailbox.__schema__)), +) +"""The resource type of the :class:`Mailbox` resources, served at ``/Mailboxes``.""" class ScimStorageContract: @@ -242,10 +240,9 @@ class ScimStorageContract: """Whether the storage stores the :class:`Mailbox` resources. Set it to :data:`True` to check the uniqueness of sub-attributes and of - multi-valued attributes. The storage then serves the ``Mailbox`` and - ``SharedMailbox`` resource types, which share the schema of - :class:`Mailbox`. The tests of the uniqueness across resource types use - them. The ``provider`` fixture serves them too. + multi-valued attributes. The storage then serves the ``Mailbox`` + resource type, :data:`MAILBOX_TYPE`. The ``provider`` fixture serves it + too. """ @pytest.fixture @@ -257,7 +254,7 @@ def provider(self) -> ScimProvider: return ScimProvider( models=[*provider.models, Mailbox], - resource_types=[*provider.resource_types, *MAILBOX_TYPES], + resource_types=[*provider.resource_types, MAILBOX_TYPE], config=provider.config, policy=provider.policy, ) @@ -275,11 +272,6 @@ def mailbox_type(self, provider: ScimProvider) -> ResourceType: self.require(self.stores_mailboxes, "mailboxes") return next(rt for rt in provider.resource_types if rt.id == "Mailbox") - @pytest.fixture - def shared_mailbox_type(self, provider: ScimProvider) -> ResourceType: - self.require(self.stores_mailboxes, "mailboxes") - return next(rt for rt in provider.resource_types if rt.id == "SharedMailbox") - @pytest.fixture def user_model( self, provider: ScimProvider, user_type: ResourceType @@ -667,11 +659,17 @@ def test_delete_with_an_outdated_version( def test_create_with_a_taken_unique_value( self, storage: Any, user_type: ResourceType, user_model: Any ) -> None: - """A userName already taken, whatever its case, raises a 409 on creation.""" + """A userName already taken, whatever its case, raises a 409 on creation. + + The detail tells the attribute, as + :func:`~scim2_server.storage.uniqueness_conflict` writes it, and + never the value. + """ self.create_users(storage, user_type, user_model, "bjensen") - with pytest.raises(UniquenessException): + with pytest.raises(UniquenessException) as conflict: storage.create(user_type, user_model(user_name="BJensen")) + assert conflict.value.detail == "Uniqueness conflict with attribute userName" def test_update_with_a_taken_unique_value( self, storage: Any, user_type: ResourceType, user_model: Any @@ -729,7 +727,7 @@ def test_create_with_a_taken_unique_value_in_a_list( def test_update_with_a_taken_unique_value_in_a_list( self, storage: Any, mailbox_type: ResourceType ) -> None: - """A unique sub-attribute value taken by another resource raises a 409 on update.""" + """A unique sub-attribute value taken by another resource raises a 409 on update, telling the sub-attribute.""" storage.create( mailbox_type, Mailbox(addresses=[MailboxAddress(value="bjensen@example.com")]), @@ -742,8 +740,12 @@ def test_update_with_a_taken_unique_value_in_a_list( MailboxAddress(value="bjensen@example.com"), ] - with pytest.raises(UniquenessException): + with pytest.raises(UniquenessException) as conflict: storage.update(mailbox_type, mailbox) + assert ( + conflict.value.detail + == "Uniqueness conflict with attribute addresses.value" + ) stored = storage.get(mailbox_type, mailbox.id) assert [address.value for address in stored.addresses] == ["babs@example.com"] @@ -775,28 +777,6 @@ def test_case_exact_unique_values_differ_by_their_case( with pytest.raises(UniquenessException): storage.create(mailbox_type, Mailbox(aliases=["babs"])) - def test_a_resource_repeats_a_unique_value( - self, storage: Any, mailbox_type: ResourceType - ) -> None: - """Two equal unique values in the same resource do not clash, and the storage keeps both.""" - mailbox = storage.create( - mailbox_type, - Mailbox( - addresses=[ - MailboxAddress(value="bjensen@example.com", type="work"), - MailboxAddress(value="bjensen@example.com", type="home"), - ], - aliases=["babs", "babs"], - ), - ) - - stored = storage.get(mailbox_type, mailbox.id) - assert [address.value for address in stored.addresses] == [ - "bjensen@example.com", - "bjensen@example.com", - ] - assert stored.aliases == ["babs", "babs"] - def test_missing_unique_values_do_not_clash( self, storage: Any, mailbox_type: ResourceType ) -> None: @@ -874,47 +854,13 @@ def test_writes_free_the_unique_values_in_a_list( def test_unique_values_of_different_attributes_do_not_clash( self, storage: Any, mailbox_type: ResourceType ) -> None: - """A unique value only clashes with the values of its own attribute. - - Per RFC 7643 erratum 8279, the uniqueness applies to an attribute of a - schema. - """ + """A unique value only clashes with the values of its own attribute.""" storage.create( mailbox_type, Mailbox(addresses=[MailboxAddress(value="bjensen")]) ) storage.create(mailbox_type, Mailbox(aliases=["bjensen"])) storage.create(mailbox_type, Mailbox(owner=MailboxOwner(value="bjensen"))) - def test_unique_values_across_resource_types( - self, - storage: Any, - mailbox_type: ResourceType, - shared_mailbox_type: ResourceType, - ) -> None: - """A unique value taken by a resource of another type sharing the schema raises a 409. - - Per RFC 7643 erratum 8279, the uniqueness applies to the resources using - the schema, whatever their resource type. - """ - storage.create( - mailbox_type, Mailbox(addresses=[MailboxAddress(value="babs@example.com")]) - ) - storage.create( - shared_mailbox_type, - Mailbox(addresses=[MailboxAddress(value="team@example.com")]), - ) - - with pytest.raises(UniquenessException): - storage.create( - shared_mailbox_type, - Mailbox(addresses=[MailboxAddress(value="babs@example.com")]), - ) - with pytest.raises(UniquenessException): - storage.create( - mailbox_type, - Mailbox(addresses=[MailboxAddress(value="team@example.com")]), - ) - def test_search_a_resource_type( self, storage: Any, diff --git a/tests/integration/test_repeated_unique_values.py b/tests/integration/test_repeated_unique_values.py new file mode 100644 index 0000000..e592fcb --- /dev/null +++ b/tests/integration/test_repeated_unique_values.py @@ -0,0 +1,161 @@ +import httpx2 +import pytest +from scim2_models import Meta +from scim2_models import ScimProvider + +from scim2_server.applications.wsgi import WSGIApplication +from scim2_server.handler import AsyncScimHandler +from scim2_server.memory import AsyncInMemoryStorage +from scim2_server.testing import MAILBOX_TYPE +from scim2_server.testing import Mailbox +from scim2_server.utils import load_default_service_provider_config + +from ..conftest import BlockingHandler + +MAILBOX_SCHEMA = str(Mailbox.__schema__) +PATCH_OP = "urn:ietf:params:scim:api:messages:2.0:PatchOp" +BULK_REQUEST = "urn:ietf:params:scim:api:messages:2.0:BulkRequest" + + +@pytest.fixture(params=["sync", "async"]) +def client(request, storage): + """Build a client of a service serving mailboxes, through the synchronous handler, then the asynchronous one.""" + provider = ScimProvider( + models=[Mailbox], + resource_types=[MAILBOX_TYPE], + config=load_default_service_provider_config(), + ) + app = WSGIApplication(storage, provider) + if request.param == "async": + app.handler = BlockingHandler( + AsyncScimHandler(app.service, AsyncInMemoryStorage(storage)) + ) + transport = httpx2.WSGITransport(app=app) + with httpx2.Client( + transport=transport, base_url="https://scim.example.com" + ) as client: + yield client + + +def mailbox(**attributes): + return {"schemas": [MAILBOX_SCHEMA], **attributes} + + +def addresses(*values): + return [{"value": value} for value in values] + + +def assert_invalid_value(response): + assert response.status_code == 400 + assert response.json()["scimType"] == "invalidValue" + + +def test_a_creation_holding_a_unique_value_twice_is_refused(client): + """Two addresses equal but for their case make a 400, and no mailbox is created.""" + body = mailbox(addresses=addresses("babs@example.com", "BABS@example.com")) + r = client.post("/v2/Mailboxes", json=body) + + assert_invalid_value(r) + assert r.json()["detail"] == "The attribute addresses.value holds a value twice" + assert client.get("/v2/Mailboxes").json()["totalResults"] == 0 + + +def test_case_exact_unique_values_differing_by_their_case_are_accepted(client): + """Two aliases differing by their case are two values.""" + r = client.post("/v2/Mailboxes", json=mailbox(aliases=["babs", "Babs"])) + + assert r.status_code == 201 + assert r.json()["aliases"] == ["babs", "Babs"] + + +def test_a_replacement_holding_a_unique_value_twice_is_refused(client): + """A PUT repeating an address makes a 400, and the mailbox keeps its addresses.""" + body = mailbox(addresses=addresses("babs@example.com")) + location = client.post("/v2/Mailboxes", json=body).headers["Location"] + body["addresses"] = addresses("babs@example.com", "babs@example.com") + + assert_invalid_value(client.put(location, json=body)) + assert client.get(location).json()["addresses"] == addresses("babs@example.com") + + +def test_a_patch_repeating_a_unique_value_is_refused(client): + """A PATCH replacing the addresses by two equal ones makes a 400.""" + body = mailbox(addresses=addresses("babs@example.com")) + location = client.post("/v2/Mailboxes", json=body).headers["Location"] + patch = { + "schemas": [PATCH_OP], + "Operations": [ + { + "op": "replace", + "path": "addresses", + "value": addresses("bjensen@example.com", "BJensen@example.com"), + } + ], + } + + assert_invalid_value(client.patch(location, json=patch)) + assert client.get(location).json()["addresses"] == addresses("babs@example.com") + + +def test_a_bulk_creation_holding_a_unique_value_twice_fails_alone(client): + """The bulk operation repeating a value fails with a 400, and the next one runs.""" + operations = [ + { + "method": "POST", + "path": "/Mailboxes", + "bulkId": bulk_id, + "data": mailbox(aliases=aliases), + } + for bulk_id, aliases in (("twice", ["babs", "babs"]), ("once", ["babs"])) + ] + r = client.post( + "/v2/Bulk", json={"schemas": [BULK_REQUEST], "Operations": operations} + ) + + statuses = [operation["status"] for operation in r.json()["Operations"]] + assert statuses == ["400", "201"] + + +@pytest.fixture +def repeating(storage): + """Store a mailbox holding an alias twice, as a storage of scim2-server 0.10 could.""" + storage.resources = [ + Mailbox( + id="1", + aliases=["babs", "babs"], + meta=Meta(resource_type="Mailbox", version='W/"1"'), + ) + ] + return "/v2/Mailboxes/1" + + +def test_a_value_the_resource_already_repeats_is_kept(client, repeating): + """A PUT or a PATCH may keep an alias the mailbox already holds twice.""" + body = mailbox(display_name="Babs", aliases=["babs", "babs"]) + patch = { + "schemas": [PATCH_OP], + "Operations": [{"op": "replace", "path": "displayName", "value": "Barbara"}], + } + + assert client.put(repeating, json=body).status_code == 200 + assert client.patch(repeating, json=patch).status_code == 204 + assert client.get(repeating).json()["aliases"] == ["babs", "babs"] + + +def test_a_new_repeated_value_is_refused_beside_one_already_repeated(client, repeating): + """A PUT repeating an address makes a 400, even when the mailbox already repeats an alias.""" + body = mailbox( + aliases=["babs", "babs"], + addresses=addresses("babs@example.com", "babs@example.com"), + ) + + assert_invalid_value(client.put(repeating, json=body)) + + +def test_the_first_repeating_attribute_is_told(client): + """When several attributes repeat a value, the detail tells the first one the schema declares.""" + body = mailbox(aliases=["babs", "babs"], addresses=addresses("x", "x")) + + r = client.post("/v2/Mailboxes", json=body) + + assert r.json()["detail"] == "The attribute addresses.value holds a value twice" diff --git a/tests/integration/test_shared_schema.py b/tests/integration/test_shared_schema.py index 9543229..dfb8773 100644 --- a/tests/integration/test_shared_schema.py +++ b/tests/integration/test_shared_schema.py @@ -73,11 +73,12 @@ def test_a_shared_schema_is_published_once(wsgi): assert {rt["id"] for rt in resource_types} == {"User", "Group", "Admin"} -@pytest.mark.parametrize("user_name", ["bjensen", "BJensen"]) -def test_uniqueness_spans_the_resource_types_sharing_a_schema(wsgi, user_name): - """RFC 7643 erratum 8279: uniqueness holds among the resources using the same schema.""" +def test_uniqueness_holds_within_each_resource_type(wsgi): + """A user and an admin may share a userName, but two admins may not.""" wsgi.post("/v2/Users", json={"userName": "bjensen"}) - r = wsgi.post("/v2/Admins", json={"userName": user_name}) + assert wsgi.post("/v2/Admins", json={"userName": "bjensen"}).status_code == 201 + + r = wsgi.post("/v2/Admins", json={"userName": "BJensen"}) assert r.status_code == 409 assert r.json()["scimType"] == "uniqueness" diff --git a/tests/mapping/backend.py b/tests/mapping/backend.py index f0b7bbd..38059f2 100644 --- a/tests/mapping/backend.py +++ b/tests/mapping/backend.py @@ -4,7 +4,9 @@ import operator from collections.abc import Callable from collections.abc import Iterable +from collections.abc import Iterator from collections.abc import Mapping +from contextlib import contextmanager from dataclasses import dataclass from dataclasses import field as dataclass_field from typing import Any @@ -19,7 +21,6 @@ from scim2_models import ScimPolicy from scim2_models import ScimProvider from scim2_models import SearchRequest -from scim2_models import UniquenessException from scim2_models.path import CompareOperator from scim2_server import mapping as core @@ -28,12 +29,11 @@ from scim2_server.mapping.filters import as_stored from scim2_server.mapping.filters import compare from scim2_server.mapping.filters import entry_present -from scim2_server.mapping.filters import holds_any from scim2_server.mapping.filters import sort_target from scim2_server.mapping.filters import where from scim2_server.storage import ScimStorage from scim2_server.storage import SearchPage -from scim2_server.storage import unique_values +from scim2_server.storage import uniqueness_conflict Row = dict[str, Any] Predicate = Callable[[Row], bool] @@ -134,6 +134,22 @@ def related(collection: core.Collection, row: Row) -> list[Row]: return [entry for entry in found if row["id"] in entry[relation.field.name]] +def _keys( + row: Row, field: Field, column: core.Column | None, policy: ScimPolicy +) -> list[Any]: + """Return the values of a row a unique constraint compares, as the filters compare them.""" + held = row[field.name] + values = [ + value + for value in (held if isinstance(held, list) else [held]) + if value is not None + ] + if column is None or not column.is_string: + return values + + return [column.binding.comparable(value, policy) for value in values] + + def needs_value(field: Field) -> bool: return not (field.null or field.default is not None or field.name == "id") @@ -473,10 +489,11 @@ def create( ) -> Resource[Any]: mapping = self.mappings[str(resource_type.name)] conversion.check_storable(mapping, resource, None) - self._check_uniqueness(mapping, resource, None) links = self._links(mapping, resource) row = mapping.record.new() - self._write(mapping, resource, row, links, creating=True) + with self._unique_constraints(): + self._write(mapping, resource, row, links, creating=True) + return self._to_scim(resource_type, row) def update( @@ -491,12 +508,13 @@ def update( stored = self._to_scim(resource_type, row) _check_version(stored, expected_version) conversion.check_storable(mapping, resource, stored) - self._check_uniqueness(mapping, resource, stored) links = self._links(mapping, resource) - if mapping.version is not None: - row[mapping.version.name] += 1 + with self._unique_constraints(): + if mapping.version is not None: + row[mapping.version.name] += 1 + + self._write(mapping, resource, row, links, creating=False) - self._write(mapping, resource, row, links, creating=False) return self._to_scim(resource_type, row) def delete( @@ -509,6 +527,11 @@ def delete( mapping = self.mappings[str(resource_type.name)] row = self._load(resource_type, resource_id) _check_version(self._to_scim(resource_type, row), expected_version) + for collection in mapping._all_collections(): + if isinstance(collection.relation, Owned): + for entry in related(collection, row): + del collection.relation.target.rows[entry["id"]] + del mapping.record.rows[row["id"]] def _write( @@ -565,47 +588,57 @@ def _write_collection( relation.target.insert(entry_row) - def _check_uniqueness( - self, - mapping: FakeMapping, - resource: Resource[Any], - stored: Resource[Any] | None, - ) -> None: - """Refuse a resource holding a unique value another resource holds. + @contextmanager + def _unique_constraints(self) -> Iterator[None]: + """Run a write as a transaction, and roll it back when it breaks a unique constraint. - Per RFC 7643 erratum 8279, the values are looked for in every mapping - sharing the attribute. A value the stored resource holds is not checked. + As a database would, each field holding a unique attribute gets a + constraint comparing the values as the filters do. Two mappings + sharing a table share its constraints. """ - held = {} if stored is None else unique_values(stored, self.policy) - for urn, pairs in unique_values(resource, self.policy).items(): - kept = [comparable for _, comparable in held.get(urn, [])] - values = [ - value - for value, comparable in pairs - if comparable is not None and comparable not in kept + tables = { + table + for mapping in self.mappings.values() + for table in ( + mapping.record, + *(c.relation.target for c in mapping._all_collections()), + ) + } + snapshot = { + table: ({key: dict(row) for key, row in table.rows.items()}, table.next_key) + for table in tables + } + yield + for binding, table, field, column in self._constraints(): + keys = [ + key + for row in table.rows.values() + for key in _keys(row, field, column, self.policy) ] - if values: - self._check_values(mapping, urn, values, stored) - - def _check_values( - self, - mapping: FakeMapping, - urn: str, - values: list[Any], - stored: Resource[Any] | None, - ) -> None: - for other in self.mappings.values(): - binding = other._unique_attributes().get(urn) - if binding is None: + if len(keys) == len(set(keys)): continue - taken = holds_any(other, self.conditions, self.policy, binding, values) - if other is mapping and stored is not None: - itself = self._with_id(mapping, str(stored.id)) - taken = self.conditions.all([self.conditions.negate(itself), taken]) + for table, (rows, next_key) in snapshot.items(): + table.rows, table.next_key = rows, next_key - if self._find(other, taken): - raise UniquenessException + raise uniqueness_conflict(binding) + + def _constraints( + self, + ) -> Iterator[tuple[AttributeBinding, Table, Field, core.Column | None]]: + """Yield the unique constraints, with their attribute and the column comparing the strings of each.""" + for mapping in self.mappings.values(): + for binding in mapping.unique_attributes().values(): + for collection, column in mapping._lookup(binding): + relation = None if collection is None else collection.relation + if relation is None: + yield binding, mapping.record, column.field, column + elif isinstance(relation, Owned): + yield binding, relation.target, column.field, column + elif isinstance(relation, Reference | References): + yield binding, mapping.record, relation.field, None + else: + raise NotImplementedError def _links( self, mapping: FakeMapping, resource: Resource[Any] diff --git a/tests/mapping/tables.py b/tests/mapping/tables.py index a14d76e..23c5a31 100644 --- a/tests/mapping/tables.py +++ b/tests/mapping/tables.py @@ -57,31 +57,25 @@ groups.field("version", null=False, default=1) -def mailbox_tables(name): - """Return the tables of a mailbox, its addresses and its aliases.""" - mailboxes = Table(name) - for field in ("display_name", "owner", "owner_name"): - mailboxes.field(field) - - addresses = Table(f"{name}_addresses") - addresses.field("mailbox", null=False) - addresses.field("value") - addresses.field("type") - aliases = Table(f"{name}_aliases") - aliases.field("mailbox", null=False) - aliases.field("value") - return mailboxes, addresses, aliases - - -MAILBOX_TABLES = { - name: mailbox_tables(name.lower()) for name in ("Mailbox", "SharedMailbox") -} +mailboxes = Table("mailboxes") +for name in ("display_name", "owner", "owner_name"): + mailboxes.field(name) + +addresses = Table("addresses") +addresses.field("mailbox", null=False) +addresses.field("value") +addresses.field("type") +aliases = Table("aliases") +aliases.field("mailbox", null=False) +aliases.field("value") TABLES = ( users, emails, groups, - *(t for tables in MAILBOX_TABLES.values() for t in tables), + mailboxes, + addresses, + aliases, ) DEFAULT = object() @@ -162,8 +156,7 @@ def groups_mapping(changes=None, version=DEFAULT, **options): UNDATED = {"meta.created": None, "meta.lastModified": None} -def mailbox_mapping(name, changes=None): - mailboxes, addresses, aliases = MAILBOX_TABLES[name] +def mailbox_mapping(changes=None): attributes = { "id": mailboxes.id, "displayName": mailboxes.fields["display_name"], diff --git a/tests/mapping/test_contract.py b/tests/mapping/test_contract.py index e474734..fd2fcc4 100644 --- a/tests/mapping/test_contract.py +++ b/tests/mapping/test_contract.py @@ -29,8 +29,7 @@ def storage(self, provider): mappings = { "User": users_mapping(), "Group": groups_mapping(), - "Mailbox": mailbox_mapping("Mailbox"), - "SharedMailbox": mailbox_mapping("SharedMailbox"), + "Mailbox": mailbox_mapping(), } return FakeStorage(mappings, provider, version_key=b"secret") diff --git a/tests/mapping/test_uniqueness.py b/tests/mapping/test_uniqueness.py index 230bed9..6e63bec 100644 --- a/tests/mapping/test_uniqueness.py +++ b/tests/mapping/test_uniqueness.py @@ -11,17 +11,12 @@ from scim2_server.mapping import Attribute from scim2_server.mapping import Entry from scim2_server.mapping import Link -from scim2_server.testing import MAILBOX_TYPES -from scim2_server.testing import Mailbox -from scim2_server.testing import MailboxOwner from .backend import FakeStorage from .backend import Reference from .pets import Pet from .pets import pets from .pets import pets_mapping -from .tables import MAILBOX_TABLES -from .tables import mailbox_mapping class SoleOwner(ComplexAttribute): @@ -80,7 +75,7 @@ def test_the_unique_attributes_are_those_clients_read(): mapping = puppies_mapping({"name": Attribute(pets.fields["name"], writable=False)}) FakeStorage({"Pet": mapping}, ScimProvider(models=[Puppy])) - assert sorted(mapping._unique_attributes()) == [ + assert sorted(mapping.unique_attributes()) == [ "urn:example:2.0:Pet:badges.value", "urn:example:2.0:Pet:name", "urn:example:2.0:Pet:owner.value", @@ -88,22 +83,6 @@ def test_the_unique_attributes_are_those_clients_read(): ] -def test_a_value_another_mapping_only_reads_is_taken(): - """A unique value that the mapping of another resource type only reads clashes too.""" - shared_mailboxes = MAILBOX_TABLES["SharedMailbox"][0] - owner = Attribute(shared_mailboxes.fields["owner"], writable=False) - mappings = { - "Mailbox": mailbox_mapping("Mailbox"), - "SharedMailbox": mailbox_mapping("SharedMailbox", {"owner.value": owner}), - } - provider = ScimProvider(models=[Mailbox], resource_types=MAILBOX_TYPES) - storage = FakeStorage(mappings, provider, version_key=b"key") - shared_mailboxes.insert(shared_mailboxes.new() | {"owner": "bjensen"}) - - with pytest.raises(UniquenessException): - storage.create(MAILBOX_TYPES[0], Mailbox(owner=MailboxOwner(value="BJensen"))) - - def test_a_unique_link_value_is_taken_once(puppies): """No two puppies share an owner.""" storage, pet_type = puppies diff --git a/tests/test_memory.py b/tests/test_memory.py index 94fe22f..0ae5021 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -1,3 +1,4 @@ +import asyncio import datetime import inspect from typing import Annotated @@ -320,6 +321,122 @@ def generate_id(self, resource_type, resource): assert storage.create(user_type, User(user_name="b")).id == "User-1" +def test_a_refused_resource_gets_no_identifier(user_type, scim_provider): + """generate_id is called after the unique values are checked, so a refused resource does not call it.""" + + class CountingStorage(InMemoryStorage): + calls = 0 + + def generate_id(self, resource_type, resource): + self.calls += 1 + return super().generate_id(resource_type, resource) + + storage = CountingStorage() + User = scim_provider.model_for(user_type) + storage.create(user_type, User(user_name="bjensen")) + + with pytest.raises(UniquenessException): + storage.create(user_type, User(user_name="BJensen")) + + assert storage.calls == 1 + + +def test_no_chosen_identifier_draws_one(user_type, scim_provider): + """A generate_id returning None lets the storage draw an identifier.""" + + class DrawingStorage(InMemoryStorage): + def generate_id(self, resource_type, resource): + return None + + storage = DrawingStorage() + User = scim_provider.model_for(user_type) + first = storage.create(user_type, User(user_name="bjensen")) + second = storage.create(user_type, User(user_name="jsmith")) + + assert first.id + assert second.id + assert first.id != second.id + + +def test_a_chosen_identifier_already_taken_is_refused(user_type, scim_provider): + """An identifier another resource of the type holds raises a 409, and the stored resource is kept. + + Another resource type may hold it, as the storage serves resource types + numbered on their own. + """ + + class FixedStorage(InMemoryStorage): + def generate_id(self, resource_type, resource): + return "1" + + storage = FixedStorage() + group_type = next(rt for rt in scim_provider.resource_types if rt.id == "Group") + User = scim_provider.model_for(user_type) + Group = scim_provider.model_for(group_type) + storage.create(user_type, User(user_name="bjensen")) + storage.create(group_type, Group(display_name="admins")) + + with pytest.raises(UniquenessException) as conflict: + storage.create(user_type, User(user_name="jsmith")) + + assert conflict.value.detail == "Uniqueness conflict with attribute id" + assert storage.get(user_type, "1").user_name == "bjensen" + assert found_user_names(storage, user_type, User, 'userName eq "jsmith"') == [] + + +def test_an_asynchronous_generate_id_can_await(user_type, scim_provider): + """The asynchronous storage awaits its generate_id, which gives the identifier.""" + + class AwaitingStorage(AsyncInMemoryStorage): + async def generate_id(self, resource_type, resource): + await asyncio.sleep(0) + return f"remote-{resource.user_name}" + + storage = AwaitingStorage() + User = scim_provider.model_for(user_type) + + user = asyncio.run(storage.create(user_type, User(user_name="bjensen"))) + + assert user.id == "remote-bjensen" + assert storage.storage.get(user_type, "remote-bjensen").user_name == "bjensen" + + +def test_a_value_taken_while_generate_id_awaits_is_refused(user_type, scim_provider): + """The unique values are checked again once generate_id returns, and the resource is not stored.""" + + class RacingStorage(AsyncInMemoryStorage): + async def generate_id(self, resource_type, resource): + self.storage.create(user_type, User(user_name="bjensen")) + return "late" + + storage = RacingStorage() + User = scim_provider.model_for(user_type) + + with pytest.raises(UniquenessException): + asyncio.run(storage.create(user_type, User(user_name="BJensen"))) + + with pytest.raises(NotFoundException): + storage.storage.get(user_type, "late") + + +def test_the_values_generate_id_gives_are_checked(user_type, scim_provider): + """A value generate_id writes in the resource is checked and indexed as a value of the client is.""" + + class RenamingStorage(InMemoryStorage): + def generate_id(self, resource_type, resource): + resource.user_name = "bjensen" + return None + + storage = RenamingStorage() + User = scim_provider.model_for(user_type) + storage.create(user_type, User(user_name="draft")) + + with pytest.raises(UniquenessException): + storage.create(user_type, User(user_name="other")) + + assert [user.user_name for user in storage.resources] == ["bjensen"] + + def test_dates_come_from_the_clock(user_type, scim_provider): """The dates of the resources come from the given clock.""" now = datetime.datetime(2024, 3, 14, 6, 0, tzinfo=datetime.UTC) @@ -569,8 +686,8 @@ class Token(Resource): storage.create(ResourceType.from_resource(Token), Token(code="x")) -def test_uniqueness_of_an_extension_spans_the_resources_it_extends(): - """An extension attribute is unique among every resource carrying the extension.""" +def test_uniqueness_of_an_extension_holds_within_each_resource_type(): + """An extension attribute is unique among the resources of a type, and another type carrying the extension may hold its values.""" class Tag(Extension): __schema__ = URN("urn:example:2.0:Tag") @@ -583,16 +700,14 @@ class Token(Resource): __schema__ = URN("urn:example:2.0:Token") storage = InMemoryStorage() - storage.create( - ResourceType.from_resource(Badge[Tag]), - Badge[Tag].model_validate({"urn:example:2.0:Tag": {"code": "x"}}), - ) - storage.create(ResourceType.from_resource(Token), Token()) + badge_type = ResourceType.from_resource(Badge[Tag]) + token_type = ResourceType.from_resource(Token[Tag]) + tagged = {"urn:example:2.0:Tag": {"code": "x"}} + storage.create(badge_type, Badge[Tag].model_validate(tagged)) + storage.create(token_type, Token[Tag].model_validate(tagged)) + with pytest.raises(UniquenessException): - storage.create( - ResourceType.from_resource(Token[Tag]), - Token[Tag].model_validate({"urn:example:2.0:Tag": {"code": "x"}}), - ) + storage.create(token_type, Token[Tag].model_validate(tagged)) def test_hidden_unique_values_are_not_checked(): diff --git a/tests/test_storage.py b/tests/test_storage.py index 58c8645..ecba944 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -4,8 +4,11 @@ import warnings import pytest +from scim2_models import EnterpriseUser from scim2_models import InvalidCursorException +from scim2_models import Path from scim2_models import SearchRequest +from scim2_models import User from scim2_server.memory import AsyncInMemoryStorage from scim2_server.memory import InMemoryStorage @@ -13,6 +16,7 @@ from scim2_server.storage import ScimStorage from scim2_server.storage import async_search_page from scim2_server.storage import search_page +from scim2_server.storage import uniqueness_conflict class MinimalStorage(ScimStorage): @@ -335,3 +339,14 @@ def test_a_cursor_refuses_a_sort_value_it_cannot_hold( storage.search( [user_type], SearchRequest(cursor="", count=1, sort_by="userName") ) + + +def test_a_uniqueness_conflict_tells_an_extension_attribute_by_its_urn(): + """The detail of a 409 on an extension attribute holds its URN, and no value.""" + urn = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:employeeNumber" + binding = Path[User[EnterpriseUser]](urn).resolve() + + conflict = uniqueness_conflict(binding) + + assert conflict.status == 409 + assert conflict.detail == f"Uniqueness conflict with attribute {urn}"