diff --git a/doc/changelog.rst b/doc/changelog.rst index 023a53b..7ad4ade 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,23 @@ Changelog ========= +[Unreleased] +------------ + +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. + +Changed +^^^^^^^ +- A unique sub-attribute is unique among the resources, and each value of a multi-valued attribute + counts on its own: ``["a", "b"]`` and ``["a"]`` now clash. +- A unique value clients never read is not checked, as a 409 would tell that another resource + holds it. A mapping refuses such an attribute. + [0.9.0] - 2026-11-27 -------------------- diff --git a/doc/how-to/check-a-storage.rst b/doc/how-to/check-a-storage.rst index 4ce5a34..f4a1e61 100644 --- a/doc/how-to/check-a-storage.rst +++ b/doc/how-to/check-a-storage.rst @@ -123,6 +123,12 @@ suite then checks that the storage leaves these dates empty. For a storage that the password of the users, set :attr:`~scim2_server.testing.ScimStorageContract.stores_password` 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. + 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 sorts the storage refuses, and checks the others: diff --git a/doc/how-to/write-a-storage.rst b/doc/how-to/write-a-storage.rst index 29a08fb..3ca93a1 100644 --- a/doc/how-to/write-a-storage.rst +++ b/doc/how-to/write-a-storage.rst @@ -186,6 +186,11 @@ exception: :pyobject: AsyncSQLiteStorage.writing :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. + Update a resource ----------------- diff --git a/doc/reference/mapping.rst b/doc/reference/mapping.rst index 1b68476..158192f 100644 --- a/doc/reference/mapping.rst +++ b/doc/reference/mapping.rst @@ -53,7 +53,7 @@ Filters and sorts ----------------- .. automodule:: scim2_server.mapping.filters - :members: Predicates, where, compare, present, entry_present, sort_target, holds + :members: Predicates, where, compare, present, entry_present, sort_target, holds, holds_any Reading and writing ------------------- diff --git a/doc/reference/storages.rst b/doc/reference/storages.rst index bd1aedd..99492cd 100644 --- a/doc/reference/storages.rst +++ b/doc/reference/storages.rst @@ -13,6 +13,8 @@ resources in memory. .. autoclass:: scim2_server.storage.SearchPage :members: +.. autofunction:: scim2_server.storage.unique_values + .. autoclass:: scim2_server.memory.InMemoryStorage :members: generate_id, next_version, operation diff --git a/doc/reference/testing.rst b/doc/reference/testing.rst index 271375b..dec65c8 100644 --- a/doc/reference/testing.rst +++ b/doc/reference/testing.rst @@ -5,6 +5,12 @@ The test suites checking that a storage follows the storage contract. They need ``testing`` extra. .. autoclass:: scim2_server.testing.ScimStorageContract - :members: supports_root_search, stores_created, stores_last_modified, stores_password, search_users + :members: supports_root_search, stores_created, stores_last_modified, stores_password, stores_mailboxes, search_users + +.. autoclass:: scim2_server.testing.Mailbox() + +.. autoclass:: scim2_server.testing.MailboxAddress() + +.. autoclass:: scim2_server.testing.MailboxOwner() .. autoclass:: scim2_server.testing.AsyncScimStorageContract diff --git a/scim2_server/mapping/filters.py b/scim2_server/mapping/filters.py index 22edc73..b7d53a4 100644 --- a/scim2_server/mapping/filters.py +++ b/scim2_server/mapping/filters.py @@ -12,6 +12,7 @@ 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 @@ -455,6 +456,41 @@ 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 aa9a0fb..20c8a40 100644 --- a/scim2_server/mapping/mapping.py +++ b/scim2_server/mapping/mapping.py @@ -365,6 +365,15 @@ def _build(self) -> Problems: self._collections[head] = collections else: column = yield from self._build_column(path, binding, value, None) + if column is not None and column.concealed and _unique(binding): + yield MappingProblem( + "error", + "hidden-unique", + f"{path!r} is hidden from clients, so it cannot be unique: " + "refusing a value would tell that another resource holds it", + ) + column = None + if column is not None: self._columns[key(binding)] = column @@ -841,17 +850,28 @@ def _string_columns(self) -> Iterator[Column]: if column.is_string: yield column - def _unique_columns(self) -> Iterator[Column]: - """Yield the written columns clients read, whose values no two resources share.""" - for column in self._columns.values(): - if column.concealed or not column.writable or column.in_entry: - continue + def _unique_attributes(self) -> dict[str, AttributeBinding]: + """Return the attributes whose values no two resources share, by URN. - if column.binding.get_annotation(Uniqueness) in ( - Uniqueness.server, - Uniqueness.global_, - ): - yield column + 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. + """ + columns = [ + *(column for column in self._columns.values() if column is not self._id), + *( + column + for collection in self._all_collections() + for name, column in collection.columns.items() + if collection.owned or name == "value" + ), + ] + return { + column.binding.urn: column.binding + for column in columns + if _unique(column.binding) + } def _returned_collections( self, parameters: ResponseParameters[Any] | None = None @@ -871,3 +891,7 @@ def _returned_collections( return [ collection for collection in collections if collection.binding.urn in kept ] + + +def _unique(binding: AttributeBinding) -> bool: + return binding.get_annotation(Uniqueness) in (Uniqueness.server, Uniqueness.global_) diff --git a/scim2_server/memory.py b/scim2_server/memory.py index cf1a13c..3075074 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 Uniqueness from scim2_models import UniquenessException from scim2_models.path import CompareOperator from scim2_models.path import Comparison @@ -30,6 +29,7 @@ from scim2_server.storage import SearchPage from scim2_server.storage import projection from scim2_server.storage import search_page +from scim2_server.storage import unique_values from scim2_server.utils import parametrize @@ -196,7 +196,7 @@ 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, Any]] = {} + self._unique_values: dict[Key, dict[str, set[Any]]] = {} self._equalities: dict[ str | None, dict[AttributeBinding, dict[Any, set[str]]] ] = {} @@ -391,22 +391,29 @@ 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, Any]) -> None: + def _store(self, resource: Resource[Any], values: dict[str, 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, value in values.items(): - self._owners.setdefault(urn, {})[value] = key + for urn, held in values.items(): + owners = self._owners.setdefault(urn, {}) + for value in held: + owners[value] = key + for binding in self._equalities.get(key[0], {}): self._index_equality(resource, binding) def _remove(self, key: Key) -> None: """Forget a resource and its indexed values.""" self._resources.get(key[0], {}).pop(key[1], None) - for urn, value in self._unique_values.pop(key, {}).items(): - del self._owners[urn][value] + for urn, held in self._unique_values.pop(key, {}).items(): + owners = self._owners[urn] + for value in held: + if owners.get(value) == key: + del owners[value] + for binding, value in self._equal_values.pop(key, {}).items(): self._equalities[key[0]][binding][value].discard(key[1]) @@ -427,37 +434,30 @@ def _check_version(resource: Resource[Any], expected_version: str | None) -> Non raise PreconditionFailedException def _check_uniqueness( - self, resource: Resource[Any], values: dict[str, Any] + self, resource: Resource[Any], values: dict[str, set[Any]] ) -> None: """Refuse a resource sharing a unique value with another resource.""" key = _key(resource) - for urn, value in values.items(): - if self._owners.get(urn, {}).get(value, key) != key: + for urn, held in values.items(): + owners = self._owners.get(urn, {}) + if any(owners.get(value, key) != key for value in held): raise UniquenessException() - def _values_of(self, resource: Resource[Any]) -> dict[str, Any]: + def _values_of(self, resource: Resource[Any]) -> dict[str, set[Any]]: """Return the unique values of a resource, by the URN of their attribute. - 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. A missing value - never clashes, as a SQL NULL 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. + 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. """ - unique_paths = parametrize(Path, type(resource)).iter_paths( - include_subattributes=False, - uniqueness=[Uniqueness.server, Uniqueness.global_], - ) - values = {} - for path in unique_paths: - attribute = cast(AttributeBinding, path.resolve()) - value = self._comparable_value(resource, attribute) - if value is not None: - values[attribute.urn] = _hashable(value) - return values + return { + urn: { + _hashable(comparable) + for _, comparable in pairs + if comparable is not None + } + for urn, pairs in unique_values(resource).items() + } @staticmethod def _comparable_value(resource: Resource[Any], attribute: AttributeBinding) -> Any: diff --git a/scim2_server/storage.py b/scim2_server/storage.py index 440a55d..5ad2c61 100644 --- a/scim2_server/storage.py +++ b/scim2_server/storage.py @@ -8,11 +8,20 @@ from dataclasses import dataclass from typing import Any from typing import cast +from weakref import WeakKeyDictionary +from scim2_models import AttributeBinding +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_server.utils import parametrize def _accepts(storage_class: type, method: str, parameter: str) -> bool: @@ -43,6 +52,93 @@ 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. + + 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. + + 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 + :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. + + >>> from scim2_models import User + >>> unique_values(User(user_name="BJensen")) + {'urn:ietf:params:scim:schemas:core:2.0:User:userName': [('BJensen', 'bjensen')]} + """ + model_path = parametrize(Path, type(resource)) + values: dict[str, list[tuple[Any, Any]]] = {} + for attribute in _unique_attributes(type(resource)): + held = model_path(attribute.urn).get(resource, strict=False) + pairs = [ + (value, _comparable(attribute, value, policy)) + for value in (held if isinstance(held, list) else [held]) + if value is not None + ] + if pairs: + values[attribute.urn] = pairs + + return values + + +_UNIQUE_ATTRIBUTES: "WeakKeyDictionary[type, list[AttributeBinding]]" = ( + WeakKeyDictionary() +) + + +def _unique_attributes(model: type[Resource[Any]]) -> list[AttributeBinding]: + """Return the unique attributes of a model that clients read, once per model.""" + attributes = _UNIQUE_ATTRIBUTES.get(model) + if attributes is None: + bindings = (path.resolve() for path in parametrize(Path, model).iter_paths()) + attributes = [ + binding + for binding in bindings + if binding is not None + and binding.get_annotation(Uniqueness) + in (Uniqueness.server, Uniqueness.global_) + and not _hidden(binding) + ] + _UNIQUE_ATTRIBUTES[model] = attributes + + return attributes + + +def _hidden(attribute: AttributeBinding) -> bool: + """Tell whether clients never read an attribute, on its own or through its parent.""" + annotation = attribute.model.get_field_annotation + returned = { + annotation(attribute.field_name, Returned), + attribute.get_annotation(Returned), + } + mutability = { + annotation(attribute.field_name, Mutability), + attribute.get_annotation(Mutability), + } + return Returned.never in returned or Mutability.write_only in mutability + + +def _comparable( + attribute: AttributeBinding, value: Any, policy: ScimPolicy | None +) -> Any: + try: + return attribute.comparable(value, policy) + except ValueError: + return None + + @dataclass class SearchPage: """A page of found resources, as :meth:`ScimStorage.search` returns it.""" @@ -132,7 +228,12 @@ class ScimStorage(ABC): - A resource that does not exist raises :class:`~scim2_models.NotFoundException`. - A value already taken by an attribute whose uniqueness is ``server`` or - ``global`` raises :class:`~scim2_models.UniquenessException`. + ``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. - 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 bc7be60..6826733 100644 --- a/scim2_server/testing.py +++ b/scim2_server/testing.py @@ -23,6 +23,7 @@ def storage(self): from collections.abc import Generator from collections.abc import Iterator from contextlib import contextmanager +from typing import Annotated from typing import Any from typing import TypeVar from typing import Union @@ -30,17 +31,23 @@ def storage(self): import pytest from pydantic import ValidationError +from scim2_models import URI +from scim2_models import URN +from scim2_models import CaseExact +from scim2_models import ComplexAttribute from scim2_models import Context from scim2_models import InvalidFilterException from scim2_models import InvalidPathException from scim2_models import NotFoundException from scim2_models import PreconditionFailedException +from scim2_models import Reference from scim2_models import Resource from scim2_models import ResourceType from scim2_models import ResponseParameters from scim2_models import ScimFilter from scim2_models import ScimProvider from scim2_models import SearchRequest +from scim2_models import Uniqueness from scim2_models import UniquenessException from scim2_server.storage import AsyncScimStorage @@ -149,6 +156,47 @@ def storage(self): ] +class MailboxAddress(ComplexAttribute): + """An address of a :class:`Mailbox`. No two mailboxes share an address, whatever its case.""" + + value: Annotated[str | None, Uniqueness.server] = None + type: str | None = None + + +class MailboxOwner(ComplexAttribute): + """The owner of a :class:`Mailbox`. No two mailboxes share an owner, whatever its case.""" + + value: Annotated[str | None, Uniqueness.server] = None + display: str | None = None + + +class Mailbox(Resource[Any]): + """A resource holding unique values below its attributes. + + The tests of the uniqueness of sub-attributes and of multi-valued + attributes create mailboxes. No two mailboxes share an alias, but two + aliases differing by their case are different. + """ + + __schema__ = URN("urn:example:scim:schemas:2.0:Mailbox") + + display_name: str | None = None + addresses: list[MailboxAddress] | None = None + aliases: Annotated[list[str] | None, Uniqueness.server, CaseExact.true] = None + 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") +] + + class ScimStorageContract: """The rules every :class:`~scim2_server.storage.ScimStorage` follows. @@ -190,10 +238,29 @@ class ScimStorageContract: hash. """ + stores_mailboxes: bool = False + """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. + """ + @pytest.fixture def provider(self) -> ScimProvider: """Return the description of the service the storage serves.""" - return load_default_provider() + provider = load_default_provider() + if not self.stores_mailboxes: + return provider + + return ScimProvider( + models=[*provider.models, Mailbox], + resource_types=[*provider.resource_types, *MAILBOX_TYPES], + config=provider.config, + policy=provider.policy, + ) @pytest.fixture def user_type(self, provider: ScimProvider) -> ResourceType: @@ -203,6 +270,16 @@ def user_type(self, provider: ScimProvider) -> ResourceType: def group_type(self, provider: ScimProvider) -> ResourceType: return next(rt for rt in provider.resource_types if rt.id == "Group") + @pytest.fixture + 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 @@ -626,6 +703,218 @@ def test_delete_frees_the_unique_values( self.create_users(storage, user_type, user_model, "bjensen") + def test_create_with_a_taken_unique_value_in_a_list( + self, storage: Any, mailbox_type: ResourceType + ) -> None: + """A unique sub-attribute value already taken, whatever its case, raises a 409 on creation. + + Each value of a multi-valued attribute counts on its own. + """ + storage.create( + mailbox_type, + Mailbox(addresses=[MailboxAddress(value="bjensen@example.com")]), + ) + + with pytest.raises(UniquenessException): + storage.create( + mailbox_type, + Mailbox( + addresses=[ + MailboxAddress(value="babs@example.com"), + MailboxAddress(value="BJensen@example.com"), + ] + ), + ) + + 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.""" + storage.create( + mailbox_type, + Mailbox(addresses=[MailboxAddress(value="bjensen@example.com")]), + ) + mailbox = storage.create( + mailbox_type, Mailbox(addresses=[MailboxAddress(value="babs@example.com")]) + ) + mailbox.addresses = [ + MailboxAddress(value="babs@example.com"), + MailboxAddress(value="bjensen@example.com"), + ] + + with pytest.raises(UniquenessException): + storage.update(mailbox_type, mailbox) + stored = storage.get(mailbox_type, mailbox.id) + assert [address.value for address in stored.addresses] == ["babs@example.com"] + + def test_create_with_a_taken_value_of_a_multi_valued_attribute( + self, storage: Any, mailbox_type: ResourceType + ) -> None: + """A value of a unique multi-valued attribute taken by another resource raises a 409.""" + storage.create(mailbox_type, Mailbox(aliases=["babs", "bjensen"])) + + with pytest.raises(UniquenessException): + storage.create(mailbox_type, Mailbox(aliases=["bjensen"])) + + def test_create_with_a_taken_unique_value_in_a_complex_attribute( + self, storage: Any, mailbox_type: ResourceType + ) -> None: + """A unique sub-attribute of a single complex attribute already taken, whatever its case, raises a 409.""" + storage.create(mailbox_type, Mailbox(owner=MailboxOwner(value="bjensen"))) + + with pytest.raises(UniquenessException): + storage.create(mailbox_type, Mailbox(owner=MailboxOwner(value="BJensen"))) + + def test_case_exact_unique_values_differ_by_their_case( + self, storage: Any, mailbox_type: ResourceType + ) -> None: + """A caseExact unique value is not taken by the same value in another case.""" + storage.create(mailbox_type, Mailbox(aliases=["babs"])) + storage.create(mailbox_type, Mailbox(aliases=["Babs"])) + + 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: + """Entries and complex attributes without their unique value do not clash.""" + for _ in range(2): + storage.create( + mailbox_type, + Mailbox( + addresses=[MailboxAddress(type="work")], + owner=MailboxOwner(display="Babs"), + ), + ) + + def test_update_keeps_and_swaps_its_unique_values( + self, storage: Any, mailbox_type: ResourceType + ) -> None: + """A resource keeping its unique values, or swapping them between its entries, is written.""" + mailbox = storage.create( + mailbox_type, + Mailbox( + display_name="Babs", + addresses=[ + MailboxAddress(value="babs@example.com", type="work"), + MailboxAddress(value="bjensen@example.com", type="home"), + ], + aliases=["babs"], + owner=MailboxOwner(value="bjensen"), + ), + ) + mailbox.display_name = "Barbara" + mailbox = storage.update(mailbox_type, mailbox) + mailbox.addresses = [ + MailboxAddress(value="bjensen@example.com", type="work"), + MailboxAddress(value="babs@example.com", type="home"), + ] + + updated = storage.update(mailbox_type, mailbox) + + assert updated.display_name == "Barbara" + assert {(address.type, address.value) for address in updated.addresses} == { + ("work", "bjensen@example.com"), + ("home", "babs@example.com"), + } + + def test_writes_free_the_unique_values_in_a_list( + self, storage: Any, mailbox_type: ResourceType + ) -> None: + """Unique values a resource gave up, or held before its deletion, can be taken by another resource.""" + mailbox = storage.create( + mailbox_type, + Mailbox( + addresses=[ + MailboxAddress(value="babs@example.com"), + MailboxAddress(value="bjensen@example.com"), + ], + aliases=["babs"], + ), + ) + mailbox.addresses = [MailboxAddress(value="bjensen@example.com")] + mailbox.aliases = None + mailbox = storage.update(mailbox_type, mailbox) + storage.create( + mailbox_type, + Mailbox( + addresses=[MailboxAddress(value="babs@example.com")], aliases=["babs"] + ), + ) + storage.delete(mailbox_type, mailbox.id) + + storage.create( + mailbox_type, + Mailbox(addresses=[MailboxAddress(value="bjensen@example.com")]), + ) + + 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. + """ + 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/mapping/backend.py b/tests/mapping/backend.py index b0928cd..f0b7bbd 100644 --- a/tests/mapping/backend.py +++ b/tests/mapping/backend.py @@ -12,7 +12,6 @@ from scim2_models import AttributeBinding from scim2_models import Mutability 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 @@ -29,10 +28,12 @@ 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 Row = dict[str, Any] Predicate = Callable[[Row], bool] @@ -570,25 +571,40 @@ def _check_uniqueness( resource: Resource[Any], stored: Resource[Any] | None, ) -> None: - others = self.conditions.true() - if stored is not None: - others = self.conditions.negate(self._with_id(mapping, str(stored.id))) - - for column in mapping._unique_columns(): - value = Path(column.binding.urn).get(resource, strict=False) - current = None - if stored is not None: - current = Path(column.binding.urn).get(stored, strict=False) - - if value is None or conversion.comparable(value) == conversion.comparable( - current - ): + """Refuse a resource holding a unique value another resource holds. + + 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. + """ + 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 + ] + 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: continue - taken = compare( - mapping, self.conditions, self.policy, column, CompareOperator.eq, value - ) - if self._find(mapping, self.conditions.all([others, taken])): + 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]) + + if self._find(other, taken): raise UniquenessException def _links( diff --git a/tests/mapping/tables.py b/tests/mapping/tables.py index 0d785a4..a14d76e 100644 --- a/tests/mapping/tables.py +++ b/tests/mapping/tables.py @@ -5,6 +5,7 @@ from scim2_server.mapping import Entry from scim2_server.mapping import Link from scim2_server.mapping import Many +from scim2_server.testing import Mailbox from .backend import FakeMapping from .backend import Owned @@ -55,7 +56,33 @@ groups.field("last_modified") groups.field("version", null=False, default=1) -TABLES = (users, emails, groups) + +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") +} + +TABLES = ( + users, + emails, + groups, + *(t for tables in MAILBOX_TABLES.values() for t in tables), +) DEFAULT = object() @@ -133,3 +160,19 @@ def groups_mapping(changes=None, version=DEFAULT, **options): "emails": Entry({"value": users.fields["email"]}, type="work", primary=True) } UNDATED = {"meta.created": None, "meta.lastModified": None} + + +def mailbox_mapping(name, changes=None): + mailboxes, addresses, aliases = MAILBOX_TABLES[name] + attributes = { + "id": mailboxes.id, + "displayName": mailboxes.fields["display_name"], + "addresses": Many( + Owned(addresses, "mailbox"), + {"value": addresses.fields["value"], "type": addresses.fields["type"]}, + ), + "aliases": Many(Owned(aliases, "mailbox"), aliases.fields["value"]), + "owner.value": mailboxes.fields["owner"], + "owner.display": mailboxes.fields["owner_name"], + } + return FakeMapping(Mailbox, mailboxes, attributes | (changes or {})) diff --git a/tests/mapping/test_contract.py b/tests/mapping/test_contract.py index 20bfad6..e474734 100644 --- a/tests/mapping/test_contract.py +++ b/tests/mapping/test_contract.py @@ -6,6 +6,7 @@ from .tables import UNDATED from .tables import WORK_EMAIL from .tables import groups_mapping +from .tables import mailbox_mapping from .tables import users_mapping @@ -18,14 +19,20 @@ def one_work_email(user): class TestMappedStorage(ScimStorageContract): - """Users and groups with a version counter and dates.""" + """Users, groups and mailboxes with a version counter and dates, or no version for the mailboxes.""" supports_root_search = False + stores_mailboxes = True @pytest.fixture def storage(self, provider): - mappings = {"User": users_mapping(), "Group": groups_mapping()} - return FakeStorage(mappings, provider) + mappings = { + "User": users_mapping(), + "Group": groups_mapping(), + "Mailbox": mailbox_mapping("Mailbox"), + "SharedMailbox": mailbox_mapping("SharedMailbox"), + } + return FakeStorage(mappings, provider, version_key=b"secret") class TestMappedStorageWithHashes(ScimStorageContract): diff --git a/tests/mapping/test_uniqueness.py b/tests/mapping/test_uniqueness.py new file mode 100644 index 0000000..230bed9 --- /dev/null +++ b/tests/mapping/test_uniqueness.py @@ -0,0 +1,124 @@ +from typing import Annotated + +import pytest +from scim2_models import ComplexAttribute +from scim2_models import Required +from scim2_models import Returned +from scim2_models import ScimProvider +from scim2_models import Uniqueness +from scim2_models import UniquenessException + +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): + value: Annotated[str | None, Uniqueness.server] = None + display: str | None = None + + +class Badge(ComplexAttribute): + value: Annotated[str | None, Uniqueness.server] = None + + +class Puppy(Pet): + name: Annotated[str | None, Uniqueness.server] = None + tags: Annotated[list[str] | None, Uniqueness.server] = None + owner: Annotated[SoleOwner | None, Required.true] = None + badges: list[Badge] | None = None + + +class LockedVault(ComplexAttribute): + code: Annotated[str | None, Returned.never, Uniqueness.server] = None + + +class LockedPet(Pet): + vault: LockedVault | None = None + + +def puppies_mapping(changes=None, **options): + attributes = { + "owner": Link(Reference(pets.fields["parent"], pets), "Pet"), + "badges": Entry({"value": pets.fields["code"]}), + } + return pets_mapping(Puppy, attributes | (changes or {}), **options) + + +@pytest.fixture +def puppies(): + provider = ScimProvider(models=[Puppy]) + storage = FakeStorage({"Pet": puppies_mapping()}, provider, version_key=b"key") + (pet_type,) = provider.resource_types + return storage, pet_type + + +def test_a_hidden_attribute_cannot_be_unique(): + """Refusing a hidden value would tell a client that another resource holds it.""" + mapping = pets_mapping( + LockedPet, {"vault.code": pets.fields["code"]}, resolve=False + ) + + assert [(p.level, p.code) for p in mapping._resolve()] == [ + ("error", "hidden-unique") + ] + + +def test_the_unique_attributes_are_those_clients_read(): + """A unique value is checked in the record, an Entry, the entries of a collection and a Link, even when the storage only reads it, but not in the id.""" + mapping = puppies_mapping({"name": Attribute(pets.fields["name"], writable=False)}) + FakeStorage({"Pet": mapping}, ScimProvider(models=[Puppy])) + + 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", + "urn:example:2.0:Pet:tags", + ] + + +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 + rex = storage.create(pet_type, Puppy(name="rex")) + storage.create(pet_type, Puppy(name="tom", owner={"value": rex.id})) + + with pytest.raises(UniquenessException): + storage.create(pet_type, Puppy(name="kit", owner={"value": rex.id})) + + +def test_a_unique_value_of_an_entry_is_taken_once(puppies): + """The badge of a puppy, held by its record, is not given to another one.""" + storage, pet_type = puppies + rex = storage.create(pet_type, Puppy(name="rex", badges=[{"value": "gold"}])) + storage.update(pet_type, rex) + + with pytest.raises(UniquenessException): + storage.create(pet_type, Puppy(name="tom", badges=[{"value": "Gold"}])) diff --git a/tests/test_memory.py b/tests/test_memory.py index 16dcf4d..94fe22f 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -13,9 +13,12 @@ from scim2_models import InvalidCursorException from scim2_models import InvalidFilterException from scim2_models import InvalidPathException +from scim2_models import Meta +from scim2_models import Mutability from scim2_models import NotFoundException from scim2_models import Resource from scim2_models import ResourceType +from scim2_models import Returned from scim2_models import Schema from scim2_models import ScimPolicy from scim2_models import ScimProvider @@ -29,6 +32,7 @@ from scim2_server.memory import InMemoryStorage from scim2_server.storage import SearchPage from scim2_server.testing import AsyncScimStorageContract +from scim2_server.testing import Mailbox from scim2_server.testing import ScimStorageContract from scim2_server.utils import load_default_resource_types from scim2_server.utils import load_default_schemas @@ -36,12 +40,16 @@ class TestInMemoryStorage(ScimStorageContract): + stores_mailboxes = True + @pytest.fixture def storage(self): return InMemoryStorage() class TestAsyncInMemoryStorage(AsyncScimStorageContract): + stores_mailboxes = True + @pytest.fixture def async_storage(self): return AsyncInMemoryStorage() @@ -417,6 +425,21 @@ def test_an_equality_search_for_a_value_the_policy_cannot_compare( ) +def test_an_equality_search_skips_the_stored_values_the_policy_cannot_compare( + user_type, scim_provider +): + """A stored value the policy refuses matches nothing, and the search finds the other resources.""" + storage = InMemoryStorage() + User = scim_provider.model_for(user_type) + storage.create(user_type, User(user_name="bjensen!")) + storage.create(user_type, User(user_name="jsmith")) + + with ScimPolicy(comparison_key=refuse_exclamation_marks): + assert found_user_names(storage, user_type, User, 'userName eq "JSmith"') == [ + "jsmith" + ] + + def test_operations_can_be_nested(user_type, scim_provider): """The lock of an operation can be taken again inside it.""" storage = InMemoryStorage() @@ -572,25 +595,68 @@ class Token(Resource): ) -def test_multi_valued_and_complex_unique_values_clash_when_equal(): - """Equal lists, or equal complex values, of a unique attribute clash.""" +def test_hidden_unique_values_are_not_checked(): + """A unique value clients never read can be held twice: refusing it would tell that another resource holds it.""" + + class Lock(ComplexAttribute): + code: Annotated[str | None, Uniqueness.server] = None + + class Key(ComplexAttribute): + code: Annotated[str | None, Mutability.write_only, Uniqueness.server] = None + + class Safe(Resource): + __schema__ = URN("urn:example:2.0:Safe") + pin: Annotated[str | None, Returned.never, Uniqueness.server] = None + lock: Annotated[Lock | None, Returned.never] = None + key: Key | None = None + + storage = InMemoryStorage() + safe_type = ResourceType.from_resource(Safe) + for _ in range(2): + storage.create( + safe_type, Safe(pin="1234", lock=Lock(code="a"), key=Key(code="b")) + ) + + +def test_loaded_resources_sharing_a_unique_value_can_be_deleted(): + """Resources loaded with a shared unique value are deleted one after the other, and free it.""" + mailbox_type = ResourceType.from_resource(Mailbox) + first, second = ( + Mailbox( + id=mailbox_id, + aliases=["babs"], + meta=Meta(resource_type=mailbox_type.name, version='W/"1"'), + ) + for mailbox_id in ("1", "2") + ) + storage = InMemoryStorage() + storage.resources = [first, second] + + storage.delete(mailbox_type, "1") + storage.delete(mailbox_type, "2") + + storage.create(mailbox_type, Mailbox(aliases=["babs"])) + + +def test_complex_unique_values_clash_when_equal(): + """Equal complex values of a unique attribute clash, and so do equal entries of a unique multi-valued complex attribute.""" class Size(ComplexAttribute): width: int | None = None class Badge(Resource): __schema__ = URN("urn:example:2.0:Badge") - codes: Annotated[list[str] | None, Uniqueness.server] = None size: Annotated[Size | None, Uniqueness.server] = None + sizes: Annotated[list[Size] | None, Uniqueness.server] = None storage = InMemoryStorage() badge_type = ResourceType.from_resource(Badge) - storage.create(badge_type, Badge(codes=["a", "b"], size=Size(width=1))) - storage.create(badge_type, Badge(codes=["a"], size=Size(width=2))) - with pytest.raises(UniquenessException): - storage.create(badge_type, Badge(codes=["a", "b"])) + storage.create(badge_type, Badge(size=Size(width=1), sizes=[Size(width=1)])) + storage.create(badge_type, Badge(size=Size(width=2), sizes=[Size(width=2)])) with pytest.raises(UniquenessException): storage.create(badge_type, Badge(size=Size(width=2))) + with pytest.raises(UniquenessException): + storage.create(badge_type, Badge(sizes=[Size(width=3), Size(width=1)])) @pytest.mark.parametrize("root", [False, True])