diff --git a/doc/changelog.rst b/doc/changelog.rst index eeb6417..5ab4c58 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,31 @@ Changelog ========= +[Unreleased] +------------ + +Added +^^^^^ +- The storage checks the uniqueness of sub-attributes, such as ``emails.value``. Each value + of a multi-valued attribute counts on its own. +- Override :meth:`~scim2_sqlalchemy.SqlAlchemyStorage.generate_id` to choose the identifier of + a new resource. The asynchronous storage awaits it, so the identifier can come from another + service. + +Changed +^^^^^^^ +- scim2-server 0.10.0 or later is required. +- A mapping, and :func:`~scim2_sqlalchemy.generate_mappings`, refuse a unique attribute that + clients never read back, with a :class:`ValueError`. A 409 would tell that another resource + holds the value. + +Fixed +^^^^^ +- Per :rfc:`7643` erratum 8279, a unique value is checked against every resource type whose + schema holds the attribute, not only the resource type being written. +- An update that keeps or swaps the values of a :class:`~scim2_sqlalchemy.Many` no longer gets + a 409 from a unique index that the application adds to its table. + [0.4.0] - 2026-11-27 -------------------- diff --git a/doc/explanation.rst b/doc/explanation.rst index ace8950..930a870 100644 --- a/doc/explanation.rst +++ b/doc/explanation.rst @@ -201,16 +201,33 @@ Unique values are checked twice Before a write, the storage searches for another record holding a unique value of the resource, such as its ``userName``, and answers 409 when it finds one. The search follows the case rules of the attribute, so ``BJensen`` clashes with ``bjensen``, which a plain unique constraint does not -catch. A unique constraint of the database remains the guard against two concurrent writes. When -a flush fails on a unique constraint, the storage answers 409. This also holds when the constraint -is stricter than the search: under a collation that ignores the accents, as the default ones of +catch. + +A unique value can be below an attribute, such as ``emails.value``. Each value of a multi-valued +attribute counts on its own, wherever the mapping stores it: in a column, in an +:class:`~scim2_sqlalchemy.Entry`, in the entries of a :class:`~scim2_sqlalchemy.Many`, or as the +target of a :class:`~scim2_sqlalchemy.Link`. A resource may hold the same value twice. Per +:rfc:`7643` erratum 8279, the search covers every resource type whose schema holds the attribute. +The schema cannot make unique a value that clients never read back: the mapping refuses it, as a +409 would tell that another resource holds the value. + +A unique constraint of the database remains the guard against two concurrent writes. When a flush +fails on a unique constraint, the storage answers 409. This also holds when the constraint is +stricter than the search: under a collation that ignores the accents, as the default ones of MariaDB do, ``José`` clashes with ``Jose``. A flush that fails on a foreign key also gets a 409, such as deleting a resource that a record outside SCIM still refers to. Any other :exc:`~sqlalchemy.exc.IntegrityError` goes through unchanged. +:func:`~scim2_sqlalchemy.generate_mappings` puts a unique constraint on the unique columns of the +records only. Two concurrent writes can then take the same value of an entry. An application can +add a unique index to the table of the entries. The storage deletes the old entries before it +inserts the new ones, so the index accepts a resource that keeps its value. The index also refuses +a value repeated in one resource, which SCIM allows. + An update only checks the unique values it changes. Another application may have stored values that clash under the case rules of SCIM, such as ``alice`` and ``Alice``. Each resource then -remains writable while it keeps its value. +remains writable while it keeps its value. Writing ``ALICE`` keeps the value too, as +``userName`` is not ``caseExact``. The application owns the transaction ------------------------------------ diff --git a/doc/how-to/map-a-data-model.rst b/doc/how-to/map-a-data-model.rst index 991a46a..ae86217 100644 --- a/doc/how-to/map-a-data-model.rst +++ b/doc/how-to/map-a-data-model.rst @@ -164,8 +164,8 @@ value that clients never read back. The storage still reads it, in the form its such as a hash, and the server never shows it to clients. A PUT without the value gives the stored one back to the storage, which keeps it as it is: a value equal to the stored one is not written again. A PATCH that removes the value, or a PUT that sets it to ``null``, clears it. The -storage neither filters nor sorts on such a value, and does not check that it is unique: give its -column a unique constraint instead. +storage neither filters nor sorts on such a value. The schema cannot make it unique: the mapping +refuses it, as a 409 would tell that another resource holds the value. The intranet hashes the password in the setter of a property, whose getter returns the hash: diff --git a/doc/reference/storages.rst b/doc/reference/storages.rst index e41334f..ebadbab 100644 --- a/doc/reference/storages.rst +++ b/doc/reference/storages.rst @@ -4,7 +4,7 @@ Storages The storages reading and writing the resources with a SQLAlchemy :class:`~sqlalchemy.orm.Session`. .. autoclass:: scim2_sqlalchemy.SqlAlchemyStorage - :members: operation + :members: operation, generate_id .. autoclass:: scim2_sqlalchemy.AsyncSqlAlchemyStorage - :members: operation + :members: operation, generate_id diff --git a/pyproject.toml b/pyproject.toml index 155d9bd..efa7747 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,7 +29,7 @@ authors = [ requires-python = ">=3.11" dependencies = [ "scim2-models>=0.12.7", - "scim2-server>=0.9.0", + "scim2-server>=0.10.0", "sqlalchemy>=2.0.41", ] @@ -54,7 +54,7 @@ dev = [ "pytest-cov>=7.1.0", "pytest-postgresql>=9.1.0", "scim2-client>=0.14.0", - "scim2-server[testing]>=0.9.0", + "scim2-server[testing]>=0.10.0", "scim2-tester[testing]>=0.6.2", "tox-uv>=1.36.0", "werkzeug>=3.1.8", diff --git a/src/scim2_sqlalchemy/mapping.py b/src/scim2_sqlalchemy/mapping.py index 1865a03..25338ae 100644 --- a/src/scim2_sqlalchemy/mapping.py +++ b/src/scim2_sqlalchemy/mapping.py @@ -488,6 +488,29 @@ def _loader_options( for collection in collections ] + def _new_key(self, resource_id: str) -> Any: + """Return the identifier a new record gets, in the type of its column. + + Raise a ValueError when the storage cannot write the identifier, or when + its column cannot hold it. + """ + (value,) = [ + value + for binding, value in self._declared.values() + if key(binding) == key(self._id.binding) + ] + if not self._value_writable(value): + raise ValueError( + f"The storage cannot write the 'id' of {self.model.__name__}" + ) + + record_key = _as_key(self._id, resource_id) + if record_key is None: + raise ValueError( + f"The 'id' of {self.model.__name__} cannot be {resource_id!r}" + ) + return record_key + def _is_target(self, value: Any) -> bool: return isinstance(getattr(value, "key", None), str) and hasattr(value, "class_") diff --git a/src/scim2_sqlalchemy/query.py b/src/scim2_sqlalchemy/query.py index 424cbcc..791a64c 100644 --- a/src/scim2_sqlalchemy/query.py +++ b/src/scim2_sqlalchemy/query.py @@ -6,6 +6,7 @@ from typing import TypeVarTuple from typing import cast as cast_type +from scim2_models import AttributeBinding from scim2_models import InvalidCursorException from scim2_models import InvalidPathException from scim2_models import ResponseParameters @@ -14,8 +15,8 @@ from scim2_server.keyset import Position from scim2_server.mapping import Collection from scim2_server.mapping import Column -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 sqlalchemy import BigInteger @@ -470,28 +471,51 @@ def _load_statement( return statement.with_for_update() if locked else statement +def _id_taken_statement( + mapping: ResourceMapping, resource_id: str +) -> Select[Any] | None: + """Return the statement finding a record of a mapping with an identifier, or None when no record can have it.""" + key = _as_key(mapping._id, resource_id) + if key is None: + return None + condition = mapping._id.expression == _bound(mapping._id, key) + return select(mapping._id.expression).where(condition).limit(1) + + def _taken_statement( mapping: ResourceMapping, - column: Column, - value: Any, - resource_id: str | None, + binding: AttributeBinding, + values: list[Any], comparator: _Comparator, + record: Any, ) -> Select[Any]: - """Return the statement finding another record holding a unique value.""" - condition = compare( - mapping, - _Predicates(comparator), - comparator.policy, - column, - CompareOperator.eq, - value, + """Return the statement finding a record of a mapping holding one of some unique values. + + record is the record an update writes, and None for a new resource. It is + left out, even when it is read through another mapping of its class. + """ + condition = holds_any( + mapping, _Predicates(comparator), comparator.policy, binding, values ) - key = None if resource_id is None else _as_key(mapping._id, resource_id) - if key is not None: - condition = and_(condition, mapping._id.expression != _bound(mapping._id, key)) + if record is not None: + condition = and_(condition, _other_than(mapping, record)) return select(mapping._id.expression).where(condition).limit(1) +def _other_than(mapping: ResourceMapping, record: Any) -> ColumnElement[bool]: + """Return the condition that a record of a mapping is not the given one. + + Two classes share their records when their base classes map the same + table, such as two classes of a table, or of an inheritance. + """ + mapper: Mapper[Any] = inspect(mapping.record) + state = inspect(record) + if mapper.base_mapper.local_table is not state.mapper.base_mapper.local_table: + return true() + keys = zip(mapper.primary_key, state.identity, strict=True) + return not_(and_(*(column == key for column, key in keys))) + + def _links_statement(collection: Collection, ids: list[str]) -> Select[Any]: """Return the statement loading the records a Link links to.""" target = cast_type(ResourceMapping, collection.target) diff --git a/src/scim2_sqlalchemy/storage.py b/src/scim2_sqlalchemy/storage.py index ec3c777..f288738 100644 --- a/src/scim2_sqlalchemy/storage.py +++ b/src/scim2_sqlalchemy/storage.py @@ -13,7 +13,6 @@ 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 @@ -29,12 +28,12 @@ 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 dates from scim2_server.mapping.conversion import link_entries 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 sqlalchemy import Dialect from sqlalchemy import Select from sqlalchemy import inspect @@ -49,6 +48,7 @@ from .mapping import ResourceMapping from .mapping import _as_key from .mapping import _Column +from .query import _id_taken_statement from .query import _links_statement from .query import _load_statement from .query import _records_statement @@ -357,40 +357,74 @@ def _comparator(self, dialect: Dialect) -> _Comparator: ) return self._comparators[dialect.name] - @staticmethod def _unique_statements( - mapping: ResourceMapping, + self, resource: Resource[Any], comparator: _Comparator, stored: Resource[Any] | None, + record: Any, ) -> Iterator[Select[Any]]: """Yield the statements finding another record holding a unique value of the resource. - A missing value never clashes, as a SQL NULL does not, and a value the - storage never writes, such as ``id``, is not stored. stored is the - resource an update changes, and None for a new one. A value it already - holds is not checked: another application may have stored a value that - clashes with it, and the record must remain writable. + Per RFC 7643 erratum 8279, a value is looked for in every mapping + storing its attribute, whatever their resource type. stored and record + are the resource an update changes and its record, and None for a new + one. A value the stored resource already holds is not checked: another + application may have stored a value that clashes with it, and the + record must remain writable. """ - resource_id = None if stored is None else resource.id - for column in mapping._unique_columns(): - path = Path(column.binding.urn) - value = path.get(resource, strict=False) - if value is None or ( - stored is not None - and comparable(value) == comparable(path.get(stored, strict=False)) - ): + 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 not values: continue - yield _taken_statement(mapping, column, value, resource_id, comparator) + for mapping in self.mappings.values(): + binding = mapping._unique_attributes().get(urn) + if binding is not None: + yield _taken_statement(mapping, binding, values, comparator, record) + + def _id_statements(self, resource_id: str) -> Iterator[Select[Any]]: + """Yield the statements finding a record of any mapping with an identifier. + + Per RFC 7643 §3.1, an identifier is unique across the resources of + every resource type. + """ + for mapping in self.mappings.values(): + statement = _id_taken_statement(mapping, resource_id) + if statement is not None: + yield statement + + @staticmethod + def _clear_entries(mapping: ResourceMapping, record: Any) -> bool: + """Remove the entries a record owns before an update, and tell whether it had any. + + The session inserts the new entries before it deletes the old ones. + Flushing the removal first lets a unique index of the entries accept a + value the resource keeps. + """ + cleared = False + for collection in mapping._all_collections(): + key = collection.relation.key + if collection.owned and collection.writable and getattr(record, key): + setattr(record, key, []) + cleared = True + return cleared - def _new_record(self, resource_type: ResourceType, resource: Resource[Any]) -> Any: - """Build an empty record for a new resource, with its dates. + def _new_record(self, resource_type: ResourceType, resource_id: str | None) -> Any: + """Build an empty record for a new resource, with its identifier when it is given, and its dates. The resource is written once the record is in the session, so that the records it links to do not pull a record the session does not know. """ mapping = self._mapping(resource_type) record = mapping.record() + if resource_id is not None: + setattr(record, mapping._id.key, mapping._new_key(resource_id)) for column, now in dates(mapping, _utcnow(), creating=True): setattr(record, column.key, now) return record @@ -473,6 +507,44 @@ def operation(self) -> Generator[None]: with self.session().begin_nested(): yield + def generate_id( + self, resource_type: ResourceType, resource: Resource[Any] + ) -> str | None: + """Return the identifier of a new resource, or :data:`None` to let its column give one. + + Override this method to choose the identifiers, as + :meth:`InMemoryStorage.generate_id ` + allows. The following storage derives the identifier of a user from + its userName at creation, so that two servers give the same user the + same identifier: + + >>> import uuid + >>> USERS = uuid.UUID("6ba7b811-9dad-11d1-80b4-00c04fd430c8") + >>> class Storage(SqlAlchemyStorage): + ... def generate_id(self, resource_type, resource): + ... if resource_type.name != "User": + ... return None + ... return str(uuid.uuid5(USERS, resource.user_name)) + + The storage calls it once for each new resource, after checking the + resource, and does not call it for a resource it refuses. Per + :rfc:`7643#section-3.1`, an identifier is unique across all the resource + types: an identifier that another resource holds raises a 409. + + The storage stores the identifier in the type of its column, and the + created resource has the identifier as the column gives it back. For + example, ``007`` in an integer column becomes ``7``. The storage raises + a :class:`ValueError` when the column cannot hold the identifier, or + when it cannot write it, such as an ``id`` mapped to a property without + setter. + + When the database numbers the records, as an autoincrement column + does, give an identifier to all the resources of a type, or to none. + The database does not skip the numbers given by this method, so a + resource that it numbers later can get one of them, and a 409. + """ + return None + def get( self, resource_type: ResourceType, @@ -526,9 +598,12 @@ def create( """Store a new resource, and return it as stored.""" mapping = self._mapping(resource_type) self._check_storable(resource_type, resource, None) - self._check_uniqueness(mapping, resource, None) + self._check_uniqueness(resource, None, None) links = self._links(mapping, resource) - record = self._new_record(resource_type, resource) + resource_id = self.generate_id(resource_type, resource) + if resource_id is not None: + self._check_id(resource_id) + record = self._new_record(resource_type, resource_id) def change() -> None: self.session().add(record) @@ -550,9 +625,15 @@ def update( stored = self._to_scim(resource_type, record) self._check_version(resource_type, record, expected_version, stored) self._check_storable(resource_type, resource, stored) - self._check_uniqueness(mapping, resource, stored) + self._check_uniqueness(resource, stored, record) links = self._links(mapping, resource) - self._flush(lambda: self._write_record(mapping, resource, record, links)) + + def change() -> None: + if self._clear_entries(mapping, record): + self.session().flush() + self._write_record(mapping, resource, record, links) + + self._flush(change) return self.get(resource_type, resource.id) # type: ignore[arg-type] def delete( @@ -591,18 +672,22 @@ def _load( return record def _check_uniqueness( - self, - mapping: ResourceMapping, - resource: Resource[Any], - stored: Resource[Any] | None, + self, resource: Resource[Any], stored: Resource[Any] | None, record: Any ) -> None: """Refuse a resource with a unique value another resource already has.""" session = self.session() comparator = self._ready_comparator(session) - for statement in self._unique_statements(mapping, resource, comparator, stored): + statements = self._unique_statements(resource, comparator, stored, record) + for statement in statements: if session.scalar(statement) is not None: raise UniquenessException + def _check_id(self, resource_id: str) -> None: + """Refuse an identifier another resource already has.""" + for statement in self._id_statements(resource_id): + if self.session().scalar(statement) is not None: + raise UniquenessException + def _ready_comparator(self, session: Session) -> _Comparator: """Return how the database of the session compares strings, ready to compare them.""" connection = session.connection() @@ -695,6 +780,19 @@ async def operation(self) -> AsyncGenerator[None]: async with self.session().begin_nested(): yield + 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 its column give one. + + See :meth:`SqlAlchemyStorage.generate_id`. This method can await, for + instance to create the account in another service and take its + identifier. A write that fails afterwards, such as with a 409 from the + database, does not undo what the method did: override + :meth:`create` to handle it. + """ + return None + async def get( self, resource_type: ResourceType, @@ -750,9 +848,12 @@ async def create( """Store a new resource, and return it as stored.""" mapping = self._mapping(resource_type) self._check_storable(resource_type, resource, None) - await self._check_uniqueness(mapping, resource, None) + await self._check_uniqueness(resource, None, None) links = await self._links(mapping, resource) - record = self._new_record(resource_type, resource) + resource_id = await self.generate_id(resource_type, resource) + if resource_id is not None: + await self._check_id(resource_id) + record = self._new_record(resource_type, resource_id) async def change() -> None: self.session().add(record) @@ -774,10 +875,12 @@ async def update( stored = self._to_scim(resource_type, record) self._check_version(resource_type, record, expected_version, stored) self._check_storable(resource_type, resource, stored) - await self._check_uniqueness(mapping, resource, stored) + await self._check_uniqueness(resource, stored, record) links = await self._links(mapping, resource) async def change() -> None: + if self._clear_entries(mapping, record): + await self.session().flush() self._write_record(mapping, resource, record, links) await self._flush(change) @@ -823,18 +926,22 @@ async def _load( return record async def _check_uniqueness( - self, - mapping: ResourceMapping, - resource: Resource[Any], - stored: Resource[Any] | None, + self, resource: Resource[Any], stored: Resource[Any] | None, record: Any ) -> None: """Refuse a resource with a unique value another resource already has.""" session = self.session() comparator = await self._ready_comparator(session) - for statement in self._unique_statements(mapping, resource, comparator, stored): + statements = self._unique_statements(resource, comparator, stored, record) + for statement in statements: if await session.scalar(statement) is not None: raise UniquenessException + async def _check_id(self, resource_id: str) -> None: + """Refuse an identifier another resource already has.""" + for statement in self._id_statements(resource_id): + if await self.session().scalar(statement) is not None: + raise UniquenessException + async def _ready_comparator(self, session: "AsyncSession") -> _Comparator: """Return how the database of the session compares strings, ready to compare them.""" connection = await session.connection() diff --git a/tests/conftest.py b/tests/conftest.py index 557b8d7..3d3177c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,6 +19,7 @@ from scim2_sqlalchemy import AsyncSqlAlchemyStorage from scim2_sqlalchemy import SqlAlchemyStorage +from .mailboxes import MAILBOX_MAPPINGS # noqa: F401 The tables of the mailboxes are created with the others. from .models import GROUPS from .models import MAPPINGS from .models import USERS diff --git a/tests/mailboxes.py b/tests/mailboxes.py new file mode 100644 index 0000000..1857e5a --- /dev/null +++ b/tests/mailboxes.py @@ -0,0 +1,215 @@ +"""Mailbox records for the storage contract. + +Their unique values are sub-attributes and multi-valued attributes. +""" + +import datetime +import uuid + +from scim2_server.testing import Mailbox +from sqlalchemy import ForeignKey +from sqlalchemy.orm import Mapped +from sqlalchemy.orm import mapped_column +from sqlalchemy.orm import relationship + +from scim2_sqlalchemy import Entry +from scim2_sqlalchemy import Many +from scim2_sqlalchemy import ResourceMapping + +from .models import MAPPINGS +from .models import Base + + +class MailboxRecord(Base): + """A mailbox whose addresses and aliases are in child tables, with a column for its work address.""" + + __tablename__ = "mailboxes" + + id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4) + display_name: Mapped[str | None] + owner: Mapped[str | None] + owner_display: Mapped[str | None] + work_address: Mapped[str | None] + created: Mapped[datetime.datetime] + last_modified: Mapped[datetime.datetime] + version: Mapped[int] = mapped_column() + + addresses: Mapped[list["AddressRecord"]] = relationship( + cascade="all, delete-orphan", order_by="AddressRecord.id" + ) + aliases: Mapped[list["AliasRecord"]] = relationship( + cascade="all, delete-orphan", order_by="AliasRecord.id" + ) + + __mapper_args__ = {"version_id_col": version} + + +class AddressRecord(Base): + __tablename__ = "mailbox_addresses" + + id: Mapped[int] = mapped_column(primary_key=True) + mailbox_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("mailboxes.id", ondelete="CASCADE") + ) + value: Mapped[str | None] + type: Mapped[str | None] + + +class AliasRecord(Base): + __tablename__ = "mailbox_aliases" + + id: Mapped[int] = mapped_column(primary_key=True) + mailbox_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("mailboxes.id", ondelete="CASCADE") + ) + value: Mapped[str] + + +class MailboxView(Base): + """Another class of the mailbox table, without inheritance.""" + + __table__ = MailboxRecord.__table__ + __mapper_args__ = {"version_id_col": __table__.c.version} + + +class SharedMailboxRecord(Base): + """A mailbox holding a single address, in a column of its record.""" + + __tablename__ = "shared_mailboxes" + + id: Mapped[int] = mapped_column(primary_key=True) + display_name: Mapped[str | None] + address: Mapped[str | None] + address_type: Mapped[str | None] + owner: Mapped[str | None] + created: Mapped[datetime.datetime] + last_modified: Mapped[datetime.datetime] + version: Mapped[int] = mapped_column() + + aliases: Mapped[list["SharedAliasRecord"]] = relationship( + cascade="all, delete-orphan", order_by="SharedAliasRecord.id" + ) + + __mapper_args__ = {"version_id_col": version} + + +class SharedAliasRecord(Base): + __tablename__ = "shared_mailbox_aliases" + + id: Mapped[int] = mapped_column(primary_key=True) + mailbox_id: Mapped[int] = mapped_column( + ForeignKey("shared_mailboxes.id", ondelete="CASCADE") + ) + value: Mapped[str] + + +class GuardedMailboxRecord(Base): + """A mailbox whose application refuses an address held twice, with a unique index.""" + + __tablename__ = "guarded_mailboxes" + + id: Mapped[int] = mapped_column(primary_key=True) + display_name: Mapped[str | None] + version: Mapped[int] = mapped_column() + + addresses: Mapped[list["GuardedAddressRecord"]] = relationship( + cascade="all, delete-orphan", order_by="GuardedAddressRecord.id" + ) + + __mapper_args__ = {"version_id_col": version} + + +class GuardedAddressRecord(Base): + __tablename__ = "guarded_mailbox_addresses" + + id: Mapped[int] = mapped_column(primary_key=True) + mailbox_id: Mapped[int] = mapped_column( + ForeignKey("guarded_mailboxes.id", ondelete="CASCADE") + ) + value: Mapped[str | None] = mapped_column(unique=True) + type: Mapped[str | None] + + +def mailboxes_mapping(changes=None): + """Return a mapping of the mailboxes, with some paths changed.""" + attributes = { + "id": MailboxRecord.id, + "displayName": MailboxRecord.display_name, + "addresses": Many( + MailboxRecord.addresses, + {"value": AddressRecord.value, "type": AddressRecord.type}, + ), + "aliases": Many(MailboxRecord.aliases, AliasRecord.value), + "owner.value": MailboxRecord.owner, + "owner.display": MailboxRecord.owner_display, + "meta.created": MailboxRecord.created, + "meta.lastModified": MailboxRecord.last_modified, + } + attributes |= changes or {} + return ResourceMapping( + Mailbox, MailboxRecord, attributes, version=MailboxRecord.version + ) + + +def work_addresses_mapping(record): + """Return a mapping of the mailboxes of a class, reading their work address only.""" + return ResourceMapping( + Mailbox, + record, + { + "id": record.id, + "displayName": record.display_name, + "addresses": Entry({"value": record.work_address}, type="work"), + "meta.created": record.created, + "meta.lastModified": record.last_modified, + }, + version=record.version, + ) + + +def shared_mailboxes_mapping(): + return ResourceMapping( + Mailbox, + SharedMailboxRecord, + { + "id": SharedMailboxRecord.id, + "displayName": SharedMailboxRecord.display_name, + "addresses": Entry( + { + "value": SharedMailboxRecord.address, + "type": SharedMailboxRecord.address_type, + } + ), + "aliases": Many(SharedMailboxRecord.aliases, SharedAliasRecord.value), + "owner.value": SharedMailboxRecord.owner, + "meta.created": SharedMailboxRecord.created, + "meta.lastModified": SharedMailboxRecord.last_modified, + }, + version=SharedMailboxRecord.version, + ) + + +def guarded_mailboxes_mapping(): + return ResourceMapping( + Mailbox, + GuardedMailboxRecord, + { + "id": GuardedMailboxRecord.id, + "displayName": GuardedMailboxRecord.display_name, + "addresses": Many( + GuardedMailboxRecord.addresses, + { + "value": GuardedAddressRecord.value, + "type": GuardedAddressRecord.type, + }, + ), + }, + version=GuardedMailboxRecord.version, + ) + + +MAILBOX_MAPPINGS = MAPPINGS | { + "Mailbox": mailboxes_mapping(), + "SharedMailbox": shared_mailboxes_mapping(), +} +"""The mappings of the storage contract, with the mailboxes of the tests of uniqueness.""" diff --git a/tests/test_contract.py b/tests/test_contract.py index 80a6c82..7ea241c 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -2,19 +2,24 @@ from scim2_server.testing import AsyncScimStorageContract from scim2_server.testing import ScimStorageContract +from .mailboxes import MAILBOX_MAPPINGS from .plain import PLAIN_MAPPINGS class TestSqlAlchemyStorage(ScimStorageContract): + stores_mailboxes = True + @pytest.fixture def storage(self, sync_storage_factory): - return sync_storage_factory() + return sync_storage_factory(MAILBOX_MAPPINGS) class TestAsyncSqlAlchemyStorage(AsyncScimStorageContract): + stores_mailboxes = True + @pytest.fixture def storage(self, async_storage_factory): - return async_storage_factory() + return async_storage_factory(MAILBOX_MAPPINGS) def one_work_email(user): diff --git a/tests/test_generate_id.py b/tests/test_generate_id.py new file mode 100644 index 0000000..73f65ec --- /dev/null +++ b/tests/test_generate_id.py @@ -0,0 +1,180 @@ +import asyncio +import uuid + +import pytest +from scim2_models import EnterpriseUser +from scim2_models import Group +from scim2_models import UniquenessException +from scim2_models import User +from scim2_server.testing import MAILBOX_TYPES +from scim2_server.testing import Mailbox + +from .mailboxes import MAILBOX_MAPPINGS +from .models import GroupRecord +from .models import groups_mapping +from .models import users_mapping + +UserModel = User[EnterpriseUser] + +MAILBOX_TYPE, _ = MAILBOX_TYPES + +BJENSEN = uuid.UUID("2819c223-7f76-453a-919d-413861904646") + + +class ChosenIds: + """Return the identifiers of a list in order, then None.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.ids = [] + self.calls = 0 + + def next_id(self): + self.calls += 1 + return self.ids.pop(0) if self.ids else None + + +class SyncChosenIds(ChosenIds): + def generate_id(self, resource_type, resource): + return self.next_id() + + +class AsyncChosenIds(ChosenIds): + async def generate_id(self, resource_type, resource): + await asyncio.sleep(0) + return self.next_id() + + +class FortyTwo(SyncChosenIds): + def generate_id(self, resource_type, resource): + return "42" + + +def test_a_new_user_gets_the_chosen_identifier(sync_storage_factory, user_type): + """The UUID is stored, and comes back in lowercase.""" + storage = sync_storage_factory(mixins=[SyncChosenIds]) + storage.ids = [str(BJENSEN).upper()] + + user = storage.create(user_type, UserModel(user_name="bjensen")) + + assert user.id == str(BJENSEN) + assert storage.get(user_type, str(BJENSEN)).user_name == "bjensen" + + +def test_an_asynchronous_storage_awaits_the_chosen_identifier( + async_storage_factory, user_type +): + """The asynchronous storage can wait for another service before it writes the resource.""" + storage = async_storage_factory(mixins=[AsyncChosenIds]) + storage.storage.ids = [str(BJENSEN)] + + user = storage.create(user_type, UserModel(user_name="bjensen")) + + assert user.id == str(BJENSEN) + + +def test_without_identifier_the_column_gives_one( + storage_factory, user_type, group_type +): + """Users get a random UUID, and groups get the next number of the database.""" + storage = storage_factory() + + user = storage.create(user_type, UserModel(user_name="bjensen")) + group = storage.create(group_type, Group(display_name="Sales")) + + assert uuid.UUID(user.id) + assert int(group.id) + + +def test_an_identifier_is_converted_to_the_type_of_its_column( + sync_storage_factory, group_type +): + """Groups have integer identifiers. The string 42 is stored as the number 42.""" + storage = sync_storage_factory(mixins=[FortyTwo]) + + assert storage.create(group_type, Group(display_name="Sales")).id == "42" + + +def create_two_users_with_the_same_identifier(storage, chooser, user_type): + chooser.ids = [str(BJENSEN), str(BJENSEN)] + storage.create(user_type, UserModel(user_name="bjensen")) + + with pytest.raises(UniquenessException): + storage.create(user_type, UserModel(user_name="babs")) + + +def test_a_taken_identifier_raises_a_409(sync_storage_factory, user_type): + """Two users cannot have the same identifier.""" + storage = sync_storage_factory(mixins=[SyncChosenIds]) + + create_two_users_with_the_same_identifier(storage, storage, user_type) + + +def test_an_asynchronous_storage_refuses_a_taken_identifier( + async_storage_factory, user_type +): + """Two users cannot have the same identifier.""" + storage = async_storage_factory(mixins=[AsyncChosenIds]) + + create_two_users_with_the_same_identifier(storage, storage.storage, user_type) + + +def test_an_identifier_is_unique_across_resource_types(sync_storage_factory, user_type): + """Per RFC 7643 §3.1, a mailbox cannot take the identifier of a user, though they are in different tables.""" + storage = sync_storage_factory(MAILBOX_MAPPINGS, mixins=[SyncChosenIds]) + storage.ids = [str(BJENSEN), str(BJENSEN)] + storage.create(user_type, UserModel(user_name="bjensen")) + + with pytest.raises(UniquenessException): + storage.create(MAILBOX_TYPE, Mailbox(display_name="Babs")) + + +def refuse_a_taken_user_name(storage, chooser, user_type): + chooser.ids = [str(BJENSEN), str(uuid.uuid4())] + storage.create(user_type, UserModel(user_name="bjensen")) + + with pytest.raises(UniquenessException): + storage.create(user_type, UserModel(user_name="BJensen")) + + assert chooser.calls == 1 + + +def test_a_refused_resource_gets_no_identifier(sync_storage_factory, user_type): + """The storage checks the unique values first, so a refused user does not call generate_id.""" + storage = sync_storage_factory(mixins=[SyncChosenIds]) + + refuse_a_taken_user_name(storage, storage, user_type) + + +def test_an_asynchronous_storage_chooses_no_identifier_for_a_refused_resource( + async_storage_factory, user_type +): + """A refused user does not call another service.""" + storage = async_storage_factory(mixins=[AsyncChosenIds]) + + refuse_a_taken_user_name(storage, storage.storage, user_type) + + +def test_an_identifier_the_column_cannot_hold_is_refused( + sync_storage_factory, user_type +): + """Users have UUID identifiers, so bjensen is not one.""" + storage = sync_storage_factory(mixins=[SyncChosenIds]) + storage.ids = ["bjensen"] + + with pytest.raises(ValueError, match="'id' of User.* cannot be 'bjensen'"): + storage.create(user_type, UserModel(user_name="bjensen")) + + +def test_an_identifier_the_storage_cannot_write_is_refused( + sync_storage_factory, group_type +): + """Here the identifier of the groups is a property without setter.""" + mappings = { + "User": users_mapping(), + "Group": groups_mapping({"id": GroupRecord.text_id}), + } + storage = sync_storage_factory(mappings, mixins=[FortyTwo]) + + with pytest.raises(ValueError, match="cannot write the 'id' of Group"): + storage.create(group_type, Group(display_name="Sales")) diff --git a/tests/test_generation.py b/tests/test_generation.py index d953d11..3b9369c 100644 --- a/tests/test_generation.py +++ b/tests/test_generation.py @@ -14,6 +14,7 @@ from scim2_models import ResourceType from scim2_models import Returned from scim2_models import ScimProvider +from scim2_models import Uniqueness from scim2_models import User from scim2_server.applications.wsgi import WSGIApplication from scim2_server.utils import load_default_provider @@ -597,3 +598,17 @@ def test_an_inverse_reads_the_links_of_another_attribute( ) projects = storage.get(user_type, alice.id)[Staffing].projects assert [p.value for p in projects] == [project.id] + + +class Vault(Resource): + """A resource type whose code is unique and never returned.""" + + __schema__ = URN("urn:example:params:scim:schemas:core:2.0:Vault") + + code: Annotated[str | None, Returned.never, Uniqueness.server] = None + + +def test_a_unique_value_hidden_from_clients_is_refused(): + """A 409 on the code would tell that another vault holds it.""" + with pytest.raises(ValueError, match="hidden from clients"): + generate_mappings(ScimProvider(models=[Vault]), MetaData()) diff --git a/tests/test_storage.py b/tests/test_storage.py index 2ef0d8e..7541d72 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -18,7 +18,6 @@ from scim2_models import PreconditionFailedException from scim2_models import Returned from scim2_models import SearchRequest -from scim2_models import Uniqueness from scim2_models import UniquenessException from scim2_models import User from sqlalchemy import create_engine @@ -156,7 +155,6 @@ class Serial(Extension): serial: Annotated[str | None, Mutability.immutable, Returned.never] = None pin: Annotated[str | None, Mutability.write_only] = None - code: Annotated[str | None, Returned.never, Uniqueness.server] = None chief: Annotated[Manager | None, Returned.never] = None @@ -170,7 +168,6 @@ def serial_storage(storage_factory, column=UserRecord.title): "userName": UserRecord.user_name, f"{SERIAL}:serial": column, f"{SERIAL}:pin": UserRecord.pin_hash, - f"{SERIAL}:code": UserRecord.nick_name, f"{SERIAL}:chief": Link(UserRecord.manager, "User"), "meta.created": UserRecord.created, "meta.lastModified": UserRecord.last_modified, @@ -270,16 +267,6 @@ def test_a_link_clients_never_read_is_kept_and_cleared(storage_factory, user_typ assert storage.update(user_type, created)[Serial] is None -def test_a_unique_value_clients_never_read_is_not_checked(storage_factory, user_type): - """A 409 would tell another user holds the same code.""" - storage = serial_storage(storage_factory) - storage.create(user_type, serial_user("bjensen", code="X")) - - other = storage.create(user_type, serial_user("jsmith", code="X")) - - assert other[Serial].code == "X" - - def test_a_missing_value_keeps_the_default_of_the_column(storage, user_type): """A created resource without userType gets the default of the column, and an update can clear it.""" user = storage.create(user_type, UserModel(user_name="bjensen")) @@ -760,7 +747,7 @@ def test_a_string_is_stored_in_an_integer_column_through_a_property( class TakenMeanwhile: """Skip the uniqueness check, as when another transaction takes the value right after it.""" - def _unique_statements(self, mapping, resource, comparator, stored): + def _unique_statements(self, resource, comparator, stored, record): return iter(()) @@ -960,11 +947,14 @@ def test_a_uuid_identifier_matches_its_own_text(storage, user_type, scim_filter, def test_an_unchanged_unique_value_is_not_checked_again( sync_storage_factory, session, user_type, database_url ): - """Another application stored alice and Alice: Alice remains writable while she keeps her name.""" + """Another application stored alice and Alice: Alice remains writable while she keeps her name. + + userName is not caseExact, so ALICE is the name she holds, and not a new one. + """ if database_url.startswith("mariadb"): pytest.skip("The default collation of MariaDB cannot hold alice and Alice") now = datetime.datetime.now(datetime.UTC) - for user_name in ("alice", "Alice"): + for user_name in ("alice", "Alice", "bob"): session.add(UserRecord(user_name=user_name, created=now, last_modified=now)) session.flush() storage = sync_storage_factory() @@ -974,6 +964,8 @@ def test_an_unchanged_unique_value_is_not_checked_again( assert storage.update(user_type, alice).display_name == "Alice" alice.user_name = "ALICE" + assert storage.update(user_type, alice).user_name == "ALICE" + alice.user_name = "Bob" with pytest.raises(UniquenessException): storage.update(user_type, alice) diff --git a/tests/test_uniqueness.py b/tests/test_uniqueness.py new file mode 100644 index 0000000..4f2b783 --- /dev/null +++ b/tests/test_uniqueness.py @@ -0,0 +1,217 @@ +import datetime +from typing import Annotated + +import pytest +from scim2_models import URN +from scim2_models import CaseExact +from scim2_models import Extension +from scim2_models import Group +from scim2_models import GroupMember +from scim2_models import Mutability +from scim2_models import Returned +from scim2_models import Uniqueness +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.testing import MailboxAddress +from scim2_server.testing import MailboxOwner + +from scim2_sqlalchemy import Attribute +from scim2_sqlalchemy import Link +from scim2_sqlalchemy import ResourceMapping + +from .mailboxes import MAILBOX_MAPPINGS +from .mailboxes import MailboxRecord +from .mailboxes import MailboxView +from .mailboxes import SharedMailboxRecord +from .mailboxes import guarded_mailboxes_mapping +from .mailboxes import mailboxes_mapping +from .mailboxes import work_addresses_mapping +from .models import MAPPINGS +from .models import GroupRecord +from .models import UserRecord +from .models import users_mapping + +MAILBOX_TYPE, SHARED_MAILBOX_TYPE = MAILBOX_TYPES + +SEALED = "urn:example:params:scim:schemas:extension:sealed:2.0:User" + + +class Sealed(Extension): + __schema__ = URN(SEALED) + + code: Annotated[str | None, Returned.never, Uniqueness.server] = None + + +class TeamMember(GroupMember): + value: Annotated[ + str | None, Mutability.immutable, CaseExact.true, Uniqueness.server + ] = None + + +class Team(Group): + """A group whose members belong to no other team.""" + + members: list[TeamMember] | None = None + + +def addresses(*values): + return [MailboxAddress(value=value, type=type) for value, type in values] + + +def test_a_unique_value_hidden_from_clients_is_refused(): + """A 409 on the code would tell that another user holds it.""" + with pytest.raises(ValueError, match="hidden from clients"): + ResourceMapping( + User[Sealed], + UserRecord, + { + "id": UserRecord.id, + "userName": UserRecord.user_name, + f"{SEALED}:code": UserRecord.nick_name, + }, + ) + + +def test_a_unique_index_of_the_entries_accepts_the_values_a_resource_keeps( + storage_factory, +): + """The old entries are deleted before the new ones are inserted, so the index of the application accepts a kept or swapped address.""" + storage = storage_factory(MAPPINGS | {"Mailbox": guarded_mailboxes_mapping()}) + mailbox = storage.create( + MAILBOX_TYPE, + Mailbox( + display_name="Babs", + addresses=addresses( + ("babs@example.com", "work"), ("b@example.com", "home") + ), + ), + ) + mailbox.display_name = "Barbara" + mailbox = storage.update(MAILBOX_TYPE, mailbox) + mailbox.addresses = addresses( + ("babs@example.com", "home"), ("b@example.com", "work") + ) + + updated = storage.update(MAILBOX_TYPE, mailbox) + + assert updated.display_name == "Barbara" + assert [(a.value, a.type) for a in updated.addresses] == [ + ("babs@example.com", "home"), + ("b@example.com", "work"), + ] + + +def test_a_unique_index_of_the_entries_refuses_a_value_a_resource_repeats( + storage_factory, +): + """The index of the application is stricter than SCIM, which lets a resource repeat its value.""" + storage = storage_factory(MAPPINGS | {"Mailbox": guarded_mailboxes_mapping()}) + + with pytest.raises(UniquenessException): + storage.create( + MAILBOX_TYPE, + Mailbox( + addresses=addresses( + ("babs@example.com", "work"), ("babs@example.com", "home") + ) + ), + ) + + +@pytest.mark.parametrize( + "record", [MailboxRecord, MailboxView], ids=["same class", "same table"] +) +def test_a_resource_does_not_clash_with_itself_through_another_mapping_of_its_record( + storage_factory, record +): + """The shared mailboxes read the work address of the same records, so a mailbox taking its own work address does not clash with itself.""" + storage = storage_factory( + MAPPINGS + | { + "Mailbox": mailboxes_mapping(), + "SharedMailbox": work_addresses_mapping(record), + } + ) + shared = storage.create( + SHARED_MAILBOX_TYPE, + Mailbox(addresses=addresses(("team@example.com", "work"))), + ) + mailbox = storage.get(MAILBOX_TYPE, shared.id) + assert mailbox.addresses is None + mailbox.addresses = addresses(("team@example.com", "work")) + + updated = storage.update(MAILBOX_TYPE, mailbox) + + assert [a.value for a in updated.addresses] == ["team@example.com"] + other = storage.create(MAILBOX_TYPE, Mailbox(display_name="Other")) + other.addresses = addresses(("team@example.com", "work")) + with pytest.raises(UniquenessException): + storage.update(MAILBOX_TYPE, other) + + +def test_a_unique_member_belongs_to_one_group(storage_factory, user_type, group_type): + """The value of a Link is checked as any other unique value.""" + teams = ResourceMapping( + Team, + GroupRecord, + { + "id": GroupRecord.id, + "displayName": GroupRecord.display_name, + "members": Link(GroupRecord.members, "User", type="User"), + "meta.created": GroupRecord.created, + "meta.lastModified": GroupRecord.last_modified, + }, + version=GroupRecord.version, + ) + storage = storage_factory({"User": users_mapping(), "Group": teams}) + bjensen = storage.create(user_type, User(user_name="bjensen")) + member = TeamMember(value=bjensen.id, type="User") + team = storage.create(group_type, Team(display_name="Sales", members=[member])) + team.display_name = "Marketing" + + assert storage.update(group_type, team).display_name == "Marketing" + with pytest.raises(UniquenessException): + storage.create(group_type, Team(display_name="Support", members=[member])) + + +def test_an_update_taking_the_value_of_another_resource_type_is_refused( + storage_factory, +): + """Per RFC 7643 erratum 8279, an update looks for its new values in the other resource types too.""" + storage = storage_factory(MAILBOX_MAPPINGS) + mailbox = storage.create(MAILBOX_TYPE, Mailbox(display_name="Babs")) + storage.create( + SHARED_MAILBOX_TYPE, Mailbox(addresses=addresses(("team@example.com", "work"))) + ) + mailbox.addresses = addresses(("team@example.com", "work")) + + with pytest.raises(UniquenessException): + storage.update(MAILBOX_TYPE, mailbox) + + +def test_a_unique_value_another_resource_type_only_reads_is_taken( + sync_storage_factory, session +): + """Another application stores the owners of the shared mailboxes, which clients read, so a mailbox cannot take one.""" + shared = ResourceMapping( + Mailbox, + SharedMailboxRecord, + { + "id": SharedMailboxRecord.id, + "owner.value": Attribute(SharedMailboxRecord.owner, writable=False), + "meta.created": SharedMailboxRecord.created, + "meta.lastModified": SharedMailboxRecord.last_modified, + }, + version=SharedMailboxRecord.version, + ) + storage = sync_storage_factory( + MAPPINGS | {"Mailbox": mailboxes_mapping(), "SharedMailbox": shared} + ) + now = datetime.datetime.now(datetime.UTC) + session.add(SharedMailboxRecord(owner="bjensen", created=now, last_modified=now)) + session.flush() + + with pytest.raises(UniquenessException): + storage.create(MAILBOX_TYPE, Mailbox(owner=MailboxOwner(value="BJensen"))) diff --git a/uv.lock b/uv.lock index d73a518..f847afb 100644 --- a/uv.lock +++ b/uv.lock @@ -1435,14 +1435,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] @@ -1496,7 +1496,7 @@ doc = [ [package.metadata] requires-dist = [ { name = "scim2-models", specifier = ">=0.12.7" }, - { name = "scim2-server", specifier = ">=0.9.0" }, + { name = "scim2-server", specifier = ">=0.10.0" }, { name = "sqlalchemy", specifier = ">=2.0.41" }, { name = "sqlalchemy", extras = ["asyncio"], marker = "extra == 'asyncio'", specifier = ">=2.0.41" }, ] @@ -1515,7 +1515,7 @@ dev = [ { name = "pytest-mysql", specifier = ">=5.0.1" }, { name = "pytest-postgresql", specifier = ">=9.1.0" }, { name = "scim2-client", specifier = ">=0.14.0" }, - { name = "scim2-server", extras = ["testing"], specifier = ">=0.9.0" }, + { name = "scim2-server", extras = ["testing"], specifier = ">=0.10.0" }, { name = "scim2-tester", extras = ["testing"], specifier = ">=0.6.2" }, { name = "sqlalchemy", extras = ["asyncio"], specifier = ">=2.0.41" }, { name = "tox-uv", specifier = ">=1.36.0" },