From 1d3a4b2982c646d3047e308a5baa5c936d66050e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89loi=20Rivard?= Date: Sat, 28 Nov 2026 08:48:10 +0100 Subject: [PATCH] feat: check unique sub-attributes across resource types --- doc/changelog.rst | 14 ++++ doc/reference.rst | 3 + pyproject.toml | 4 +- src/scim2_django/storage/mapping.py | 1 + src/scim2_django/storage/storage.py | 92 +++++++++++++++--------- tests/mappings.py | 21 ++++++ tests/models.py | 99 ++++++++++++++++++++++++++ tests/test_contract.py | 18 +++++ tests/test_mapping.py | 7 +- tests/test_storage.py | 104 ++++++++++++++++++++++++++-- uv.lock | 10 +-- 11 files changed, 323 insertions(+), 50 deletions(-) diff --git a/doc/changelog.rst b/doc/changelog.rst index 952e16a..d1c1eb7 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,20 @@ Changelog ========= +[Unreleased] +------------ + +Added +^^^^^ +- Unique sub-attributes such as ``emails.value`` are checked, each value of a list on its own, in + every resource type sharing the schema (RFC 7643 erratum 8279). + +Changed +^^^^^^^ +- Needs scim2-server 0.10.0 or later. +- ``manage.py check`` refuses a unique attribute that clients never read (``E012``). +- A resource can change the case of a unique value it already holds. + [0.3.0] - 2026-11-27 -------------------- diff --git a/doc/reference.rst b/doc/reference.rst index 96c3030..88a67d1 100644 --- a/doc/reference.rst +++ b/doc/reference.rst @@ -109,6 +109,9 @@ The checks report the following errors and warnings: * - ``scim2_django.E011`` - An attribute that clients never read, write-only or never returned, is mapped to a generated field, which the storage never writes. + * - ``scim2_django.E012`` + - An attribute that clients never read, write-only or never returned, is unique. Refusing + one of its values would tell that another resource holds it. * - ``scim2_django.W001`` - A string attribute that clients read is mapped to a text field that converts the values it reads, such as a field decrypting them. Filters and sorts compare the stored values, not diff --git a/pyproject.toml b/pyproject.toml index dfbb2b5..8782d9b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,7 +33,7 @@ requires-python = ">=3.11" dependencies = [ "django>=5.2", "scim2-models>=0.12.7", - "scim2-server>=0.9.0", + "scim2-server>=0.10.0", ] [project.urls] @@ -53,7 +53,7 @@ dev = [ "pytest-mysql>=5.0.1", "pytest-postgresql>=10.0.0", "scim2-client>=0.14.1", - "scim2-server[cursor]>=0.9.0", + "scim2-server[cursor]>=0.10.0", "scim2-tester[testing]>=0.6.6", "tox-uv>=1.36.0", ] diff --git a/src/scim2_django/storage/mapping.py b/src/scim2_django/storage/mapping.py index 10dd293..e700221 100644 --- a/src/scim2_django/storage/mapping.py +++ b/src/scim2_django/storage/mapping.py @@ -57,6 +57,7 @@ "entry-fields": "scim2_django.E007", "single-link-null": "scim2_django.E003", "unwritten": "scim2_django.W002", + "hidden-unique": "scim2_django.E012", } """The identifiers of the system checks, by code of the problems of the mapping core.""" diff --git a/src/scim2_django/storage/storage.py b/src/scim2_django/storage/storage.py index 4e9fbe4..4ed3d7b 100644 --- a/src/scim2_django/storage/storage.py +++ b/src/scim2_django/storage/storage.py @@ -10,13 +10,13 @@ from django.db import DEFAULT_DB_ALIAS from django.db import IntegrityError from django.db import connections +from django.db import models from django.db import transaction from django.db.models import F from django.db.models import ProtectedError from django.db.models import RestrictedError from scim2_models import ConflictException 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 @@ -25,7 +25,6 @@ from scim2_models import ScimProvider from scim2_models import SearchRequest from scim2_models import UniquenessException -from scim2_models.path import CompareOperator from scim2_server.keyset import Bound from scim2_server.keyset import Position from scim2_server.keyset import keyset_page @@ -33,11 +32,11 @@ from scim2_server.mapping import Collection from scim2_server.mapping.conversion import assign_links from scim2_server.mapping.conversion import check_storable -from scim2_server.mapping.conversion import comparable from scim2_server.mapping.conversion import link_entries -from scim2_server.mapping.filters import compare +from scim2_server.mapping.filters import holds_any from scim2_server.storage import ScimStorage from scim2_server.storage import SearchPage +from scim2_server.storage import unique_values from .comparison import _Comparator from .comparison import _comparator @@ -103,6 +102,12 @@ class DjangoStorage(ScimStorage): ``primary`` of the lone entry of an :class:`Entry` is the exception: it accepts any value, and reads back as the primary one. + A unique value another resource holds raises + :class:`~scim2_models.UniquenessException`, in any resource type whose + schema has the attribute. This holds for sub-attributes too, such as + ``emails.value``. Two concurrent writes can take the same value, unless + a unique index of the database refuses it. + The storage searches one resource type, or several at the root of the server as one collection. It pages by index, or with cursors that give stable pages (:rfc:`RFC 9865 <9865>`). @@ -280,7 +285,7 @@ def create( mapping = self._mapping(resource_type) with transaction.atomic(using=self.using): check_storable(mapping, resource, None) - self._check_uniqueness(mapping, resource, None) + self._check_uniqueness(mapping, resource, None, None) links = self._links(mapping, resource) record = mapping.record() now = _now() @@ -312,7 +317,7 @@ def update( stored = self._to_scim(resource_type, record) self._check_version(stored, expected_version) check_storable(mapping, resource, stored) - self._check_uniqueness(mapping, resource, stored) + self._check_uniqueness(mapping, resource, stored, record) links = self._links(mapping, resource) self._count_write(mapping, record) now = _now() @@ -565,7 +570,9 @@ def _save( except (ProtectedError, RestrictedError) as error: raise _referenced() from error except IntegrityError as error: - self._check_uniqueness(mapping, resource, stored) + self._check_uniqueness( + mapping, resource, stored, None if stored is None else record + ) if _is_duplicate(error): raise UniquenessException from error @@ -579,38 +586,44 @@ def _check_uniqueness( mapping: ResourceMapping, resource: Resource[Any], stored: Resource[Any] | None, + record: Any, ) -> None: """Refuse a resource with a unique value another resource already has. - stored is the stored resource, None for a new one. A value it already - holds is not checked, so that values another application wrote can - stay as they are. A missing value never clashes, as a SQL NULL does - not. + A value the stored resource already holds is not checked, so that + values another application wrote can stay as they are. A missing value + never clashes, as a SQL NULL does not. """ - comparator = self._comparator() - others = mapping.record._default_manager.using(self.using) - if stored is not None: - others = others.exclude(_with_ids(mapping._id, [stored.id], comparator)) - - for column in mapping._unique_columns(): - value = Path(column.binding.urn).get(resource, strict=False) - current = ( - None - if stored is None - else Path(column.binding.urn).get(stored, strict=False) - ) - if value is None or comparable(value) == comparable(current): + held = {} if stored is None else unique_values(stored, self._policy) + for urn, pairs in unique_values(resource, self._policy).items(): + kept = [key for _, key in held.get(urn, [])] + values = [ + value for value, key in pairs if key is not None and key not in kept + ] + if values: + self._check_values(mapping, urn, values, record) + + def _check_values( + self, mapping: ResourceMapping, urn: str, values: list[Any], record: Any + ) -> None: + """Refuse values of an attribute that another resource holds. + + Per RFC 7643 erratum 8279, the values are looked for in every mapping + whose schema has the attribute. The written record is left out of the + mappings whose records are its own, such as those of a proxy model. + """ + conditions = _Predicates(self._comparator()) + for other in self.mappings.values(): + binding = other._unique_attributes().get(urn) + if binding is None: continue - condition = compare( - mapping, - _Predicates(comparator), - self._policy, - column, - CompareOperator.eq, - value, - ) - if others.filter(condition).exists(): + others = other.record._default_manager.using(self.using) + if record is not None and _same_rows(mapping.record, other.record): + others = others.exclude(pk=record.pk) + + taken = holds_any(other, conditions, self._policy, binding, values) + if others.filter(taken).exists(): raise UniquenessException def _links( @@ -645,6 +658,19 @@ def _linked_records(self, collection: Collection, ids: list[str]) -> list[Any]: return list(records) +def _same_rows(record: type[models.Model], other: type[models.Model]) -> bool: + """Tell whether two models read the same rows, as proxy models, models of multi-table inheritance or models of one table do.""" + return _root_table(record) == _root_table(other) + + +def _root_table(model: type[models.Model]) -> str: + """Return the table of the model at the root of the multi-table inheritance of a model.""" + concrete = cast(type[models.Model], model._meta.concrete_model) + parents = concrete._meta.get_parent_list() + root = parents[-1] if parents else concrete + return root._meta.db_table + + def _is_duplicate(error: IntegrityError) -> bool: """Tell whether an integrity error comes from a unique index, by the code the driver of each database gives.""" cause: Any = error.__cause__ diff --git a/tests/mappings.py b/tests/mappings.py index 411b3ba..ab7ba15 100644 --- a/tests/mappings.py +++ b/tests/mappings.py @@ -8,6 +8,7 @@ from scim2_models import EnterpriseUser from scim2_models import Group from scim2_models import User +from scim2_server.testing import Mailbox from scim2_django.storage import Link from scim2_django.storage import Many @@ -15,6 +16,7 @@ from scim2_django.storage import Transformed from .models import GroupRecord +from .models import MailboxRecord from .models import UserRecord ENTERPRISE = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User" @@ -100,3 +102,22 @@ def groups_mapping(changes=None, version="version"): path: value for path, value in attributes.items() if value is not None } return ResourceMapping(Group, GroupRecord, attributes, version=version) + + +def mailboxes_mapping(record=MailboxRecord): + """Return a new mapping of the mailboxes of the storage contract.""" + return ResourceMapping( + Mailbox, + record, + { + "id": "id", + "displayName": "display_name", + "addresses": Many("addresses", {"value": "value", "type": "type"}), + "aliases": Many("aliases", "value"), + "owner.value": "owner", + "owner.display": "owner_display", + "meta.created": "created", + "meta.lastModified": "last_modified", + }, + version="version", + ) diff --git a/tests/models.py b/tests/models.py index 3a45a46..e7d4791 100644 --- a/tests/models.py +++ b/tests/models.py @@ -333,3 +333,102 @@ class Team(AuthGroup): class Meta: proxy = True + + +class MailboxRecord(models.Model): + """A mailbox of the storage contract, whose owner is in its own fields.""" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4) + display_name = models.TextField(null=True) + owner = models.TextField(null=True) + owner_display = models.TextField(null=True) + created = models.DateTimeField() + last_modified = models.DateTimeField() + version = models.PositiveIntegerField(default=1) + + +class MailboxAddressRecord(models.Model): + mailbox = models.ForeignKey( + MailboxRecord, on_delete=models.CASCADE, related_name="addresses" + ) + value = models.TextField(null=True) + type = models.TextField(null=True) + + class Meta: + ordering = ["id"] + + +class MailboxAliasRecord(models.Model): + mailbox = models.ForeignKey( + MailboxRecord, on_delete=models.CASCADE, related_name="aliases" + ) + value = models.TextField() + + class Meta: + ordering = ["id"] + + +class SharedMailboxRecord(models.Model): + """A shared mailbox of the storage contract, in tables apart from the mailboxes.""" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4) + display_name = models.TextField(null=True) + owner = models.TextField(null=True) + owner_display = models.TextField(null=True) + created = models.DateTimeField() + last_modified = models.DateTimeField() + version = models.PositiveIntegerField(default=1) + + +class SharedMailboxAddressRecord(models.Model): + mailbox = models.ForeignKey( + SharedMailboxRecord, on_delete=models.CASCADE, related_name="addresses" + ) + value = models.TextField(null=True) + type = models.TextField(null=True) + + class Meta: + ordering = ["id"] + + +class SharedMailboxAliasRecord(models.Model): + mailbox = models.ForeignKey( + SharedMailboxRecord, on_delete=models.CASCADE, related_name="aliases" + ) + value = models.TextField() + + class Meta: + ordering = ["id"] + + +class ProxyMailboxRecord(MailboxRecord): + """The mailboxes, as another resource type reads them.""" + + class Meta: + proxy = True + + +class RoomRecord(MailboxRecord): + """A mailbox of a room, whose fields are those of a mailbox.""" + + capacity = models.PositiveIntegerField(null=True) + + +class OfficeRecord(MailboxRecord): + """A mailbox of an office, which can share its mailbox with a room.""" + + floor = models.PositiveIntegerField(null=True) + + +class MailboxView(models.Model): + """The mailboxes, as a model of the same table that Django does not manage.""" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4) + display_name = models.TextField(null=True) + created = models.DateTimeField() + last_modified = models.DateTimeField() + version = models.PositiveIntegerField(default=1) + + class Meta: + managed = False + db_table = MailboxRecord._meta.db_table diff --git a/tests/test_contract.py b/tests/test_contract.py index d6bec0d..fb5af36 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -6,8 +6,10 @@ from .mappings import ENTERPRISE from .mappings import groups_mapping from .mappings import hashed_password +from .mappings import mailboxes_mapping from .mappings import prefixed from .mappings import users_mapping +from .models import SharedMailboxRecord pytestmark = pytest.mark.django_db @@ -19,6 +21,22 @@ def storage(self, provider): return DjangoStorage(mappings, provider) +class TestDjangoStorageWithMailboxes(ScimStorageContract): + """Mailboxes whose unique values are in their records and in tables beside them.""" + + stores_mailboxes = True + + @pytest.fixture + def storage(self, provider): + mappings = { + "User": users_mapping(), + "Group": groups_mapping(), + "Mailbox": mailboxes_mapping(), + "SharedMailbox": mailboxes_mapping(SharedMailboxRecord), + } + return DjangoStorage(mappings, provider) + + class TestDjangoStorageWithoutDates(ScimStorageContract): """Resources whose models have no date.""" diff --git a/tests/test_mapping.py b/tests/test_mapping.py index 1abe78b..97c31c1 100644 --- a/tests/test_mapping.py +++ b/tests/test_mapping.py @@ -813,18 +813,15 @@ def test_an_attribute_clients_never_read_is_not_mapped_to_a_generated_field(name assert error.id == "scim2_django.E011" -def test_a_unique_value_hidden_from_clients_is_not_checked_by_the_storage(): +def test_a_unique_value_hidden_from_clients_is_refused(): """A refusal would tell a client which serials other users hold.""" mapping = ResourceMapping( User[Sealed], UserRecord, {"id": "id", "userName": "user_name", f"{SEALED}:serial": "serial"}, ) - mapping.schemas() - assert [column.binding.urn for column in mapping._unique_columns()] == [ - f"{User.__schema__}:userName" - ] + assert error_ids(mapping) == ["scim2_django.E012"] def test_a_mapping_with_another_error_is_not_told_about_its_unwritten_fields(): diff --git a/tests/test_storage.py b/tests/test_storage.py index 49119ff..9c359b5 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -19,6 +19,8 @@ from scim2_models import SearchRequest from scim2_models import UniquenessException from scim2_models import User +from scim2_server.testing import MAILBOX_TYPES +from scim2_server.testing import Mailbox from scim2_server.utils import load_default_provider from scim2_server.utils import load_default_service_provider_config @@ -26,16 +28,24 @@ from scim2_django.storage import DjangoStorage from scim2_django.storage import ResourceMapping from scim2_django.storage.comparison import _vendor +from scim2_django.storage.storage import _same_rows from .mappings import groups_mapping +from .mappings import mailboxes_mapping from .mappings import users_mapping from .models import AliasRecord from .models import BadgeRecord from .models import EmailRecord from .models import Locker from .models import LogRecord +from .models import MailboxRecord +from .models import MailboxView +from .models import OfficeRecord from .models import PassRecord from .models import Person +from .models import ProxyMailboxRecord +from .models import RoomRecord +from .models import SharedMailboxRecord from .models import UserRecord from .models import Volunteer from .test_mapping import OWNED @@ -142,10 +152,10 @@ class Racing(DjangoStorage): checks = 0 - def _check_uniqueness(self, mapping, resource, stored): + def _check_uniqueness(self, mapping, resource, stored, record): self.checks += 1 if self.checks % 2 == 0: - super()._check_uniqueness(mapping, resource, stored) + super()._check_uniqueness(mapping, resource, stored, record) def test_a_unique_value_taken_in_the_meantime_is_refused(): @@ -330,7 +340,7 @@ def test_a_group_resource_type_without_provider(): def test_a_unique_value_written_by_another_application_can_stay(server): - """A user whose name differs from another one by its case only can still be changed.""" + """A user whose name differs from another one by its case only can still be changed, along with the case of its name.""" if _vendor(connection) == "mariadb": pytest.skip("The unique index of MariaDB ignores the case, as the column does") @@ -344,8 +354,7 @@ def test_a_unique_value_written_by_another_application_can_stay(server): assert server.storage.update(server.users, other).display_name == "Other Alice" other.user_name = "ALICE" - with pytest.raises(UniquenessException): - server.storage.update(server.users, other) + assert server.storage.update(server.users, other).user_name == "ALICE" def test_a_new_resource_cannot_take_a_value_by_giving_the_identifier_of_its_holder( @@ -555,3 +564,88 @@ def test_a_value_never_returned_cannot_be_searched(search_request, error): with pytest.raises(error): storage.search([lockers], search_request) + + +def owners_mapping(record): + """Return a mapping of the mailboxes whose owner is in the field of their display name.""" + return ResourceMapping( + Mailbox, + record, + { + "id": "id", + "owner.value": "display_name", + "meta.created": "created", + "meta.lastModified": "last_modified", + }, + version="version", + ) + + +def mailbox_storage(owners): + """Return a storage of the mailboxes, whose shared mailboxes are read by a mapping of the owners.""" + provider = ScimProvider(models=[Mailbox], resource_types=MAILBOX_TYPES) + mappings = {"Mailbox": mailboxes_mapping(), "SharedMailbox": owners} + return DjangoStorage(mappings, provider) + + +SHARING_RECORDS = pytest.mark.parametrize( + "record", + [ProxyMailboxRecord, RoomRecord, MailboxView], + ids=["proxy", "multi-table", "same table"], +) + + +@SHARING_RECORDS +def test_a_record_another_resource_type_reads_does_not_clash_with_itself(record): + """The record holds the owner in another field for the shared mailboxes, as the same resource.""" + mailboxes, shared_mailboxes = MAILBOX_TYPES + storage = mailbox_storage(owners_mapping(record)) + shared = storage.create(shared_mailboxes, Mailbox(owner={"value": "bjensen"})) + mailbox = storage.get(mailboxes, shared.id) + mailbox.owner = {"value": "bjensen"} + + updated = storage.update(mailboxes, mailbox) + + assert updated.owner.value == "bjensen" + assert MailboxRecord.objects.get().owner == "bjensen" + + +@SHARING_RECORDS +def test_another_record_another_resource_type_reads_clashes(record): + """Only the written record is left out of the mappings reading its rows.""" + mailboxes, shared_mailboxes = MAILBOX_TYPES + storage = mailbox_storage(owners_mapping(record)) + storage.create(shared_mailboxes, Mailbox(owner={"value": "bjensen"})) + mailbox = storage.create(mailboxes, Mailbox(display_name="Babs")) + mailbox.owner = {"value": "bjensen"} + + with pytest.raises(UniquenessException): + storage.update(mailboxes, mailbox) + + +@pytest.mark.parametrize( + ("record", "other", "same"), + [ + (MailboxRecord, ProxyMailboxRecord, True), + (RoomRecord, MailboxRecord, True), + (RoomRecord, OfficeRecord, True), + (MailboxView, MailboxRecord, True), + (MailboxRecord, SharedMailboxRecord, False), + ], + ids=["proxy", "multi-table", "siblings", "same table", "other table"], +) +def test_models_reading_the_same_rows(record, other, same): + """Two children of one model can share the row of their parent.""" + assert _same_rows(record, other) is same + assert _same_rows(other, record) is same + + +def test_a_unique_value_another_resource_type_holds_can_stay(): + """A mailbox keeps the owner that another application gave a shared mailbox too.""" + mailboxes, _ = MAILBOX_TYPES + storage = mailbox_storage(mailboxes_mapping(SharedMailboxRecord)) + mailbox = storage.create(mailboxes, Mailbox(owner={"value": "bjensen"})) + SharedMailboxRecord.objects.create(owner="bjensen", created=NOW, last_modified=NOW) + mailbox.display_name = "Babs" + + assert storage.update(mailboxes, mailbox).display_name == "Babs" diff --git a/uv.lock b/uv.lock index 6574fe8..c4d4d19 100644 --- a/uv.lock +++ b/uv.lock @@ -1606,7 +1606,7 @@ mariadb = [ requires-dist = [ { name = "django", specifier = ">=5.2" }, { name = "scim2-models", specifier = ">=0.12.7" }, - { name = "scim2-server", specifier = ">=0.9.0" }, + { name = "scim2-server", specifier = ">=0.10.0" }, ] [package.metadata.requires-dev] @@ -1621,7 +1621,7 @@ dev = [ { name = "pytest-mysql", specifier = ">=5.0.1" }, { name = "pytest-postgresql", specifier = ">=10.0.0" }, { name = "scim2-client", specifier = ">=0.14.1" }, - { name = "scim2-server", extras = ["cursor"], specifier = ">=0.9.0" }, + { name = "scim2-server", extras = ["cursor"], specifier = ">=0.10.0" }, { name = "scim2-tester", extras = ["testing"], specifier = ">=0.6.6" }, { name = "tox-uv", specifier = ">=1.36.0" }, ] @@ -1649,14 +1649,14 @@ wheels = [ [[package]] name = "scim2-server" -version = "0.9.0" +version = "0.10.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "scim2-models" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/83/1d/29fb908e3c6cf5278ebf184e42757a634ce799fef332dfd4f8b793c5b1bc/scim2_server-0.9.0.tar.gz", hash = "sha256:2f7f6c34a9483c4a96ff5f65978a89e0f2e759fdc12dc5c03b6f517330d5b012", size = 90228, upload-time = "2026-11-27T08:53:54.929Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/f3/30ad252c00dd72a8c1270cb0e9f98daa0df5ac4ccdc6f0e5e7bed7a8c212/scim2_server-0.10.0.tar.gz", hash = "sha256:29eba120c131e919560d3a5c5632ce17e6e4da326659efd41c5d16971acbd077", size = 93498, upload-time = "2026-11-27T14:28:56.195Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/57/e6/0303d934ffd1c5101454b6bc74cd3bcfd40c65cc6c12d960d0bb9218afda/scim2_server-0.9.0-py3-none-any.whl", hash = "sha256:fde186347764c941400c08eba6ae3d5022fbfe76aa83e63d14d54f8456e4148e", size = 97077, upload-time = "2026-11-27T08:53:53.534Z" }, + { url = "https://files.pythonhosted.org/packages/f4/d0/d28e1c1eb4bf576cd6a7afc020cf043689fd0064084833f5f79b7e7a3716/scim2_server-0.10.0-py3-none-any.whl", hash = "sha256:94a4a34f0196fa8654ee91d49a570f4d408b901661df0394d4792dea73abba1c", size = 100433, upload-time = "2026-11-27T14:28:54.84Z" }, ] [package.optional-dependencies]