diff --git a/doc/changelog.rst b/doc/changelog.rst index bafcc87..e87a199 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,23 @@ Changelog ========= +[Unreleased] +------------ + +Added +^^^^^ +- :class:`~scim2_django.storage.ComparisonKey`, for a unique ``GeneratedField`` ignoring the case. + +Changed +^^^^^^^ +- Needs scim2-server 0.11.0 or later. +- Unique values rely on the unique constraints of the database, within a resource type. + ``manage.py check`` and the storage refuse a unique attribute without one (``E013``), the + ``userName`` of :mod:`django.contrib.auth` included: read + :doc:`how-to/serve-the-users-of-django`. +- A ``409`` tells the attribute in conflict when its constraint is on its field, never the value. +- The storage serves a mapping whose errors :setting:`SILENCED_SYSTEM_CHECKS` silences. + [0.4.0] - 2026-11-28 -------------------- diff --git a/doc/how-to/serve-the-users-of-django.rst b/doc/how-to/serve-the-users-of-django.rst index 46fe70f..4a80a5b 100644 --- a/doc/how-to/serve-the-users-of-django.rst +++ b/doc/how-to/serve-the-users-of-django.rst @@ -63,6 +63,50 @@ A user model whose primary key is a UUID can do without the prefix: Choose the prefix before connecting the first identity provider. The identity providers keep the ``id`` of each resource, and changing the prefix changes every ``id``. +Refuse a user name in another case +---------------------------------- + +Per :rfc:`RFC 7643 §4.1.1 <7643#section-4.1.1>`, ``userName`` ignores the case: ``bjensen`` and +``BJensen`` are the same user name. The ``username`` field of +:class:`~django.contrib.auth.models.User` is unique, but tells the case apart on PostgreSQL and +SQLite. ``manage.py check`` reports it with ``scim2_django.E013``. + +A user model of the project holds its user names in a unique +:class:`~django.db.models.GeneratedField` of :class:`~scim2_django.storage.ComparisonKey`: + +.. code-block:: python + + from django.contrib.auth.models import AbstractUser + from django.db import models + + from scim2_django.storage import ComparisonKey + + + class Member(AbstractUser): + username_key = models.GeneratedField( + expression=ComparisonKey("username"), + output_field=models.TextField(), + db_persist=True, + unique=True, + ) + +The user model of :mod:`django.contrib.auth` cannot get a field. Add the constraint to its table +in a migration of the project: + +.. literalinclude:: ../../examples/migrations/0004_username_key.py + :language: python + +``manage.py check`` does not see this constraint, so silence the error in the settings. The +setting silences it for every mapping of the project: + +.. literalinclude:: ../../examples/settings.py + :language: python + :start-at: SILENCED_SYSTEM_CHECKS + +MariaDB cannot index an expression, so the migration creates nothing there: the default collation +of MariaDB already ignores the case. A user name taken in another case gets a ``409`` that does +not tell the attribute. + Add a model beside the users and the groups ------------------------------------------- diff --git a/doc/overview.rst b/doc/overview.rst index 375f796..413bfb9 100644 --- a/doc/overview.rst +++ b/doc/overview.rst @@ -32,6 +32,12 @@ The models need a primary key unique across the accounts and the teams, here a U :rfc:`RFC 7643 §3.1 <7643#section-3.1>`, two resources never share an ``id``, even of different types. +The login becomes the ``userName`` of the users, which is unique whatever its case +(:rfc:`RFC 7643 §4.1.1 <7643#section-4.1.1>`). ``login_key`` holds the login in the form the +storage compares it, built by :class:`~scim2_django.storage.ComparisonKey`. Its unique constraint +refuses ``BJensen`` next to ``bjensen``, even when two requests arrive at the same time. Without +it, ``manage.py check`` reports ``scim2_django.E013``. + Four more fields serve SCIM, and the models can do without them: - a field for the identifier the identity provider gives, here ``external_id``; diff --git a/doc/reference.rst b/doc/reference.rst index 88a67d1..95bc894 100644 --- a/doc/reference.rst +++ b/doc/reference.rst @@ -39,6 +39,8 @@ and Django models. .. autoclass:: scim2_django.storage.Link +.. autoclass:: scim2_django.storage.ComparisonKey + Users of django.contrib.auth ---------------------------- @@ -61,7 +63,8 @@ System checks With ``scim2_django`` in :setting:`INSTALLED_APPS`, the :doc:`system check framework ` checks the fields of every :class:`~scim2_django.storage.ResourceMapping` once the URLconf is loaded. A storage refuses to serve a mapping with errors, and raises -:class:`~django.core.exceptions.ImproperlyConfigured`. +:class:`~django.core.exceptions.ImproperlyConfigured`. It serves a mapping whose errors +:setting:`SILENCED_SYSTEM_CHECKS` silences. The checks report the following errors and warnings: @@ -112,6 +115,14 @@ The checks report the following errors and warnings: * - ``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.E013`` + - A unique attribute that the storage writes has no unique constraint of the database. A + case exact attribute needs a unique field, ``unique_together`` or a + :class:`~django.db.models.UniqueConstraint` without condition on its field alone. An + attribute ignoring the case, such as ``userName``, needs a unique + :class:`~django.db.models.GeneratedField` of + :class:`~scim2_django.storage.ComparisonKey`. Silence this error if the constraint is + created otherwise, such as by a migration of the project. * - ``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/examples/migrations/0003_login_key.py b/examples/migrations/0003_login_key.py new file mode 100644 index 0000000..49059a0 --- /dev/null +++ b/examples/migrations/0003_login_key.py @@ -0,0 +1,25 @@ +# Generated by Django 6.1.3 on 2026-11-28 09:24 + +from django.db import migrations +from django.db import models + +import scim2_django.storage + + +class Migration(migrations.Migration): + dependencies = [ + ("examples", "0002_dates"), + ] + + operations = [ + migrations.AddField( + model_name="account", + name="login_key", + field=models.GeneratedField( + db_persist=True, + expression=scim2_django.storage.ComparisonKey("login"), + output_field=models.TextField(), + unique=True, + ), + ), + ] diff --git a/examples/migrations/0004_username_key.py b/examples/migrations/0004_username_key.py new file mode 100644 index 0000000..1346804 --- /dev/null +++ b/examples/migrations/0004_username_key.py @@ -0,0 +1,27 @@ +from django.db import migrations +from django.db import models + +from scim2_django.storage import ComparisonKey + +USERNAME_KEY = models.UniqueConstraint( + ComparisonKey("username"), name="auth_user_username_comparison_key" +) + + +def add_username_key(apps, schema_editor): + schema_editor.add_constraint(apps.get_model("auth", "User"), USERNAME_KEY) + + +def remove_username_key(apps, schema_editor): + schema_editor.remove_constraint(apps.get_model("auth", "User"), USERNAME_KEY) + + +class Migration(migrations.Migration): + dependencies = [ + ("auth", "0012_alter_user_first_name_max_length"), + ("examples", "0003_login_key"), + ] + + operations = [ + migrations.RunPython(add_username_key, remove_username_key), + ] diff --git a/examples/models.py b/examples/models.py index e8cc27a..3ba81bc 100644 --- a/examples/models.py +++ b/examples/models.py @@ -6,12 +6,19 @@ from scim2_django.auth.models import AbstractGroupScim from scim2_django.auth.models import AbstractUserScim +from scim2_django.storage import ComparisonKey class Account(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) external_id = models.TextField(null=True) login = models.TextField(unique=True) + login_key = models.GeneratedField( + expression=ComparisonKey("login"), + output_field=models.TextField(), + db_persist=True, + unique=True, + ) first_name = models.TextField(blank=True) last_name = models.TextField(blank=True) employee_number = models.TextField(blank=True) diff --git a/examples/settings.py b/examples/settings.py index 3be21ad..131f5a2 100644 --- a/examples/settings.py +++ b/examples/settings.py @@ -18,3 +18,4 @@ DATABASES = { "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "db.sqlite3"}, } +SILENCED_SYSTEM_CHECKS = ["scim2_django.E013"] diff --git a/pyproject.toml b/pyproject.toml index 43e3eaa..2860b4d 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.10.0", + "scim2-server>=0.11.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.10.0", + "scim2-server[cursor]>=0.11.0", "scim2-tester[testing]>=0.6.6", "tox-uv>=1.36.0", ] diff --git a/src/scim2_django/storage/__init__.py b/src/scim2_django/storage/__init__.py index 0d5294e..ddbab3e 100644 --- a/src/scim2_django/storage/__init__.py +++ b/src/scim2_django/storage/__init__.py @@ -1,3 +1,4 @@ +from .key import ComparisonKey from .mapping import Attribute from .mapping import Computed from .mapping import Entry @@ -9,6 +10,7 @@ __all__ = [ "Attribute", + "ComparisonKey", "Computed", "DjangoStorage", "Entry", diff --git a/src/scim2_django/storage/comparison.py b/src/scim2_django/storage/comparison.py index c9005ac..d1deb67 100644 --- a/src/scim2_django/storage/comparison.py +++ b/src/scim2_django/storage/comparison.py @@ -10,7 +10,6 @@ from django.db.models import Q from django.db.models import TextField from django.db.models import Value -from django.db.models.functions import Collate from django.db.models.functions import Length from django.db.models.functions import Lower from django.db.models.functions import StrIndex @@ -25,6 +24,9 @@ from scim2_models import default_comparison_key from scim2_models.path import CompareOperator +from .key import _mariadb_exact +from .key import _mariadb_form +from .key import _postgresql_form from .mapping import ResourceMapping from .mapping import _Column @@ -84,14 +86,15 @@ def substring(self, op: CompareOperator, column: _Column, value: str) -> Q: class _Collator(_Comparator): """Compare strings in the same form on both sides, ordered by code point as scim2-models orders them. - form builds that form from a string expression. The value is normalized + form builds that form from a string expression, and whether the + attribute ignores the case. The value is normalized to NFC in Python, as the stored strings usually are. """ def __init__( self, policy: ScimPolicy, - form: Callable[[_Column, Any], Any], + form: Callable[[Any, bool], Any], exact: Callable[[Any], Any], ) -> None: super().__init__(policy) @@ -104,62 +107,18 @@ def exact(self, expression: Any) -> Any: def column(self, column: _Column) -> Any: """Return a string column in the form it is compared under.""" - return self.form(column, column.compared) + return self.form(column.compared, column.casefolded) def operand(self, column: _Column, value: str) -> Any: """Return a string normalized to NFC, in the form it is compared under.""" normalized = unicodedata.normalize("NFC", value) - return self.form(column, Value(normalized, output_field=TextField())) - - -def _postgresql_form(column: _Column, expression: Any) -> Any: - """Return a string expression of PostgreSQL normalized to NFC, lowered if the column ignores the case, under the C collation. - - The lower() of PostgreSQL follows the locale of the database, so the - comparison approaches the default comparison key without reaching it. The - C collation orders the strings by code point. - """ - normalized = _normalize(expression) - if column.casefolded: - normalized = _normalize(Lower(normalized)) - - return Collate(normalized, "C") - - -def _mariadb_form(column: _Column, expression: Any) -> Any: - """Return a string expression of MariaDB in UTF-8, lowered if the column ignores the case, under the binary collation. - - The comparison does not depend on the collation of the column. MariaDB - cannot normalize a string to NFC, so a stored string in another form does - not match its NFC form. lower() follows the case tables of Unicode under - an uca1400 collation only. The collations without padding keep the - trailing spaces. - """ - if not column.casefolded: - return _mariadb_exact(expression) - - lowered = Lower(Collate(_utf8mb4(expression), "utf8mb4_uca1400_nopad_as_cs")) - return Collate(lowered, "utf8mb4_nopad_bin") - - -def _mariadb_exact(expression: Any) -> Any: - """Return a string expression of MariaDB in UTF-8, under the binary collation without padding.""" - return Collate(_utf8mb4(expression), "utf8mb4_nopad_bin") + return self.form(Value(normalized, output_field=TextField()), column.casefolded) def _as_is(expression: Any) -> Any: return expression -def _normalize(expression: Any) -> Func: - """Return the NFC form of a string expression, in PostgreSQL.""" - return Func( - expression, - template="normalize(%(expressions)s, NFC)", - output_field=TextField(), - ) - - class _KeyFunction(_Comparator): """Compare strings in SQLite with the comparison key of the policy itself. @@ -237,41 +196,13 @@ def substring(self, op: CompareOperator, column: _Column, value: str) -> Q: return Q(Exact(Substr(left, start), right)) -_MARIADB_VERSION = (10, 10) -"""The first version of MariaDB with the uca1400 collations.""" - -_FORMS: dict[str, tuple[Callable[[_Column, Any], Any], Callable[[Any], Any]]] = { +_COLLATORS: dict[str, tuple[Callable[[Any, bool], Any], Callable[[Any], Any]]] = { "postgresql": (_postgresql_form, _as_is), "mariadb": (_mariadb_form, _mariadb_exact), } """How each database that approaches the default comparison key writes a string to compare it, and an identifier, by vendor.""" -def _utf8mb4(expression: Any) -> Func: - """Convert a string expression to utf8mb4 in MariaDB. The column may use another character set.""" - return Func( - expression, - template="CONVERT(%(expressions)s USING utf8mb4)", - output_field=TextField(), - ) - - -def _vendor(connection: Any) -> str: - """Return the name of the database of a connection, telling MariaDB apart from MySQL. - - MariaDB before 10.10 lacks the uca1400 collations, so it is named mysql, - as a backend that does not tell whether it runs MariaDB. - """ - if ( - connection.vendor == "mysql" - and getattr(connection, "mysql_is_mariadb", False) - and connection.mysql_version >= _MARIADB_VERSION - ): - return "mariadb" - - return str(connection.vendor) - - def _comparator( vendor: str, policy: ScimPolicy, mappings: Iterable[ResourceMapping] ) -> _Comparator: @@ -279,7 +210,7 @@ def _comparator( if vendor == "sqlite": return _KeyFunction(policy, mappings) - if vendor in _FORMS: + if vendor in _COLLATORS: if policy.comparison_key is not default_comparison_key: warnings.warn( f"The {vendor} storage cannot compare strings with the comparison " @@ -287,7 +218,7 @@ def _comparator( stacklevel=2, ) - return _Collator(policy, *_FORMS[vendor]) + return _Collator(policy, *_COLLATORS[vendor]) warnings.warn( f"The {vendor} storage compares strings with lower() and the collation " diff --git a/src/scim2_django/storage/key.py b/src/scim2_django/storage/key.py new file mode 100644 index 0000000..adb92c9 --- /dev/null +++ b/src/scim2_django/storage/key.py @@ -0,0 +1,129 @@ +from typing import Any + +from django.db import models +from django.db.models import Func +from django.db.models.functions import Collate +from django.db.models.functions import Lower +from django.utils.deconstruct import deconstructible + +_MARIADB_VERSION = (10, 10) +"""The first version of MariaDB with the uca1400 collations.""" + + +@deconstructible(path="scim2_django.storage.ComparisonKey") +class ComparisonKey(Func): + """A string field in the form the storage compares it, ignoring the case. + + Give it to a unique :class:`~django.db.models.GeneratedField`, so that the + database refuses two values that filters find equal, such as ``Alice`` + and ``alice``: + + .. code-block:: python + + user_name_key = models.GeneratedField( + expression=ComparisonKey("user_name"), + output_field=models.TextField(), + db_persist=True, + unique=True, + ) + + For a model the project cannot change, such as the user model of + :mod:`django.contrib.auth`, give it to a + :class:`~django.db.models.UniqueConstraint` that a migration adds, as + :doc:`how-to/serve-the-users-of-django` tells. + + PostgreSQL and MariaDB compute the form the filters compare. On MariaDB, + the unique index compares with the collation of the column, which may + also ignore the accents. SQLite and the other databases use their + ``lower()``, which only lowers ASCII letters on SQLite: ``Élise`` and + ``élise`` are then two values. + + :param field: The name of the field. + """ + + arity = 1 + output_field = models.TextField() + + def __init__(self, field: Any) -> None: + super().__init__(field) + + def as_sql( # type: ignore[override] + self, compiler: Any, connection: Any, **extra_context: Any + ) -> Any: + (expression,) = self.get_source_expressions() + form = _FORMS.get(_vendor(connection)) + key = Lower(expression) if form is None else form(expression, True) + return compiler.compile(key.resolve_expression(compiler.query)) + + +def _postgresql_form(expression: Any, casefolded: bool) -> Any: + """Return a string expression of PostgreSQL normalized to NFC, lowered if the attribute ignores the case, under the C collation. + + The lower() of PostgreSQL follows the locale of the database, so the + comparison approaches the default comparison key without reaching it. The + C collation orders the strings by code point. + """ + normalized = _normalize(expression) + if casefolded: + normalized = _normalize(Lower(normalized)) + + return Collate(normalized, "C") + + +def _mariadb_form(expression: Any, casefolded: bool) -> Any: + """Return a string expression of MariaDB in UTF-8, lowered if the attribute ignores the case, under the binary collation. + + The comparison does not depend on the collation of the column. MariaDB + cannot normalize a string to NFC, so a stored string in another form does + not match its NFC form. lower() follows the case tables of Unicode under + an uca1400 collation only. The collations without padding keep the + trailing spaces. + """ + if not casefolded: + return _mariadb_exact(expression) + + lowered = Lower(Collate(_utf8mb4(expression), "utf8mb4_uca1400_nopad_as_cs")) + return Collate(lowered, "utf8mb4_nopad_bin") + + +def _mariadb_exact(expression: Any) -> Any: + """Return a string expression of MariaDB in UTF-8, under the binary collation without padding.""" + return Collate(_utf8mb4(expression), "utf8mb4_nopad_bin") + + +def _normalize(expression: Any) -> Func: + """Return the NFC form of a string expression, in PostgreSQL.""" + return Func( + expression, + template="normalize(%(expressions)s, NFC)", + output_field=models.TextField(), + ) + + +def _utf8mb4(expression: Any) -> Func: + """Convert a string expression to utf8mb4 in MariaDB. The column may use another character set.""" + return Func( + expression, + template="CONVERT(%(expressions)s USING utf8mb4)", + output_field=models.TextField(), + ) + + +_FORMS = {"postgresql": _postgresql_form, "mariadb": _mariadb_form} +"""How each database that approaches the default comparison key writes a string to compare it, by vendor.""" + + +def _vendor(connection: Any) -> str: + """Return the name of the database of a connection, telling MariaDB apart from MySQL. + + MariaDB before 10.10 lacks the uca1400 collations, so it is named mysql, + as a backend that does not tell whether it runs MariaDB. + """ + if ( + connection.vendor == "mysql" + and getattr(connection, "mysql_is_mariadb", False) + and connection.mysql_version >= _MARIADB_VERSION + ): + return "mariadb" + + return str(connection.vendor) diff --git a/src/scim2_django/storage/mapping.py b/src/scim2_django/storage/mapping.py index e700221..5de9301 100644 --- a/src/scim2_django/storage/mapping.py +++ b/src/scim2_django/storage/mapping.py @@ -44,6 +44,8 @@ from scim2_server.mapping.declaration import never_returned as _never_returned from scim2_server.mapping.mapping import Problems +from .key import ComparisonKey + _MAPPINGS: "weakref.WeakSet[ResourceMapping]" = weakref.WeakSet() """The mappings created so far, which the system check validates.""" @@ -516,8 +518,16 @@ def _message(self, problem: MappingProblem) -> checks.CheckMessage: return checks.Error(problem.message, obj=self, id=id) def _ready(self) -> None: - """Resolve the fields, raising when one does not fit its attribute.""" - errors = [message for message in self.check() if message.is_serious()] + """Resolve the fields, raising when one does not fit its attribute. + + An error that SILENCED_SYSTEM_CHECKS silences is accepted. + """ + silenced = set(settings.SILENCED_SYSTEM_CHECKS) + errors = [ + message + for message in self.check() + if message.is_serious() and message.id not in silenced + ] if errors: raise ImproperlyConfigured( "\n".join(f"{self!r}: {error.msg}" for error in errors) @@ -969,6 +979,69 @@ def _check_record(self) -> Problems: "scim2_django.E005", ) + yield from self._check_unique() + + def _check_unique(self) -> Problems: + """Refuse a unique attribute the storage writes, without a unique constraint of the database holding it. + + The constraint of an attribute ignoring the case is on a GeneratedField + of its ComparisonKey. The one of a case exact attribute may also be on + its field. + """ + for column in self._unique_columns(): + if not column.writable: + continue + + field: Any = column.field + keys = _key_fields(field) + held = keys if column.casefolded else [field, *keys] + if any(_constrained(holder) for holder in held): + continue + + if column.casefolded: + needed = ( + f"a unique GeneratedField of ComparisonKey({field.name!r}) " + f"in {field.model._meta.label}" + ) + else: + needed = ( + f"a unique constraint on {field.model._meta.label}.{field.name}" + ) + + yield self._error( + f"{column.binding.urn!r} is unique, so it needs {needed}: " + "without it, two resources can hold the same value", + "scim2_django.E013", + ) + + def _unique_columns(self) -> list[_Column]: + """Return the columns of the unique attributes held by fields: of the record, of a record beside it, or of the entries of a Many.""" + unique = self.unique_attributes() + columns = [ + *self._columns.values(), + *( + column + for collection in self._all_collections() + if collection.owned + for column in collection.columns.values() + ), + ] + return [ + column # type: ignore[misc] + for column in columns + if column.binding.urn in unique and column.field is not None # type: ignore[attr-defined] + ] + + def _unique_targets(self) -> dict[tuple[str, str], AttributeBinding]: + """Return the unique attributes, by table and column of the fields whose unique constraint holds them.""" + targets: dict[tuple[str, str], AttributeBinding] = {} + for column in self._unique_columns(): + field: Any = column.field + for holder in [field, *_key_fields(field)]: + targets[holder.model._meta.db_table, holder.column] = column.binding + + return targets + def _check_version(self) -> Problems: """Refuse a version that is not an integer field of the record, and warn when it has no default.""" if self.version is None: @@ -1107,6 +1180,33 @@ def _holds_id(self, record: Any, value: str) -> bool: return bool(getattr(record, self._id.key) == _exact_key(self._id, value)) +def _constrained(field: Any) -> bool: + """Tell whether a unique constraint of the database holds a field alone, without condition.""" + if field.unique: + return True + + meta = field.model._meta + return (field.name,) in meta.unique_together or any( + isinstance(constraint, models.UniqueConstraint) + and not constraint.expressions + and constraint.condition is None + and tuple(constraint.fields) == (field.name,) + for constraint in meta.constraints + ) + + +def _key_fields(field: Any) -> list[Any]: + """Return the generated fields of the model of a field that hold its ComparisonKey.""" + return [ + generated + for generated in field.model._meta.concrete_fields + if generated.generated + and isinstance(generated.expression, ComparisonKey) + and getattr(generated.expression.get_source_expressions()[0], "name", None) + == field.name + ] + + def _alias(binding: AttributeBinding) -> str: """Return the alias records hold the value of an expression under.""" return "scim_" + binding.urn.replace(":", "_").replace(".", "_") diff --git a/src/scim2_django/storage/storage.py b/src/scim2_django/storage/storage.py index 4ed3d7b..36398dd 100644 --- a/src/scim2_django/storage/storage.py +++ b/src/scim2_django/storage/storage.py @@ -1,5 +1,7 @@ import datetime +import re import threading +from collections.abc import Iterable from collections.abc import Iterator from collections.abc import Mapping from contextlib import contextmanager @@ -10,7 +12,6 @@ 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 @@ -33,20 +34,18 @@ from scim2_server.mapping.conversion import assign_links from scim2_server.mapping.conversion import check_storable from scim2_server.mapping.conversion import link_entries -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 scim2_server.storage import uniqueness_conflict from .comparison import _Comparator from .comparison import _comparator -from .comparison import _vendor from .conversion import _from_scim from .conversion import _to_scim from .conversion import _write_collections +from .key import _vendor from .mapping import ResourceMapping from .mapping import _as_stored -from .query import _Predicates from .query import _root_search from .query import _search from .query import _with_ids @@ -54,6 +53,9 @@ _DUPLICATE_ENTRY = 1062 """The code of MariaDB for a value a unique index already holds.""" +_SQLITE_UNIQUE = r"UNIQUE constraint failed: (?P\w+)\.(?P\w+)" +"""The message of SQLite for a value a unique constraint of one column already holds.""" + _MISSING_REFERENCES = (1216, 1217, 1451, 1452) """The codes of MariaDB for a foreign key refusing a change, with or without the details of the other table.""" @@ -102,11 +104,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 unique constraints of the database refuse a unique value that another + resource holds, even under concurrent writes. The storage turns their + refusal into :class:`~scim2_models.UniquenessException`, telling the + attribute but not the value. The ``manage.py check`` command tells which + constraints the mappings need. The uniqueness holds within a resource + type, or within the resource types sharing a table. 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 @@ -127,7 +130,9 @@ class DjangoStorage(ScimStorage): On MariaDB, the unique index of a field follows the collation of its column: a collation ignoring the accents refuses two values that the storage tells apart, so the write raises - :class:`~scim2_models.UniquenessException`. With Django 5.2, set + :class:`~scim2_models.UniquenessException`. The field of a unique case + exact attribute needs a collation telling the case apart, such as + ``db_collation="utf8mb4_bin"``. With Django 5.2, set ``"charset": "utf8mb4"`` in the :setting:`OPTIONS ` of the database, so that the strings keep their characters of four bytes. @@ -178,6 +183,9 @@ def operation(self) -> Iterator[None]: with transaction.atomic(using=self.using): yield except IntegrityError as error: + if _is_duplicate(error): + raise self._conflict(error, self.mappings.values()) from error + if _is_missing_reference(error): raise _referenced() from error @@ -285,7 +293,6 @@ def create( mapping = self._mapping(resource_type) with transaction.atomic(using=self.using): check_storable(mapping, resource, None) - self._check_uniqueness(mapping, resource, None, None) links = self._links(mapping, resource) record = mapping.record() now = _now() @@ -317,7 +324,6 @@ 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, record) links = self._links(mapping, resource) self._count_write(mapping, record) now = _now() @@ -555,11 +561,7 @@ def _save( ) -> None: """Save a record and its collections, at the date now. stored is the stored resource, None for a new one. - On an integrity error, the uniqueness is checked again, so that a - unique value taken in the meantime raises a 409. So does a value a - unique index of the database refuses, although the storage would - accept it, such as a value differing from another by its accents - under a collation ignoring them. + A value a unique constraint refuses raises a 409. """ try: with transaction.atomic(using=self.using): @@ -570,61 +572,69 @@ def _save( except (ProtectedError, RestrictedError) as error: raise _referenced() from error except IntegrityError as error: - self._check_uniqueness( - mapping, resource, stored, None if stored is None else record - ) if _is_duplicate(error): - raise UniquenessException from error + raise self._conflict(error, [mapping]) from error if _is_missing_reference(error): raise _referenced() from error raise - def _check_uniqueness( - self, - mapping: ResourceMapping, - resource: Resource[Any], - stored: Resource[Any] | None, - record: Any, - ) -> None: - """Refuse a resource with a unique value another resource already has. + def _conflict( + self, error: IntegrityError, mappings: Iterable[ResourceMapping] + ) -> UniquenessException: + """Return the 409 of a value a unique constraint refuses, telling the attribute the constraint holds. - 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. + The message of the database is never told, as it holds the value. A + constraint holding no attribute of the mappings, or several columns, + gives a 409 without attribute. """ - 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) + targets: dict[tuple[str, str], Any] = {} + for mapping in mappings: + targets |= mapping._unique_targets() + + tables = {table for table, _ in targets} + binding = targets.get(self._violated(error, tables)) # type: ignore[arg-type] + return ( + UniquenessException() if binding is None else uniqueness_conflict(binding) + ) - def _check_values( - self, mapping: ResourceMapping, urn: str, values: list[Any], record: Any - ) -> None: - """Refuse values of an attribute that another resource holds. + def _violated( + self, error: IntegrityError, tables: set[str] + ) -> tuple[str, str] | None: + """Return the table and the column of the unique constraint an error tells, when it holds one column. - 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. + PostgreSQL tells the table and the constraint. SQLite tells the + columns. MariaDB tells the name of the key only, which is looked for + in the tables of the mappings: a name found in several tables tells + nothing. """ - conditions = _Predicates(self._comparator()) - for other in self.mappings.values(): - binding = other._unique_attributes().get(urn) - if binding is None: - continue + cause: Any = error.__cause__ + diagnostic = getattr(cause, "diag", None) + if diagnostic is not None: + return self._key_column(diagnostic.table_name, diagnostic.constraint_name) + + if getattr(cause, "sqlite_errorname", None) is not None: + found = re.fullmatch(_SQLITE_UNIQUE, str(cause)) + return None if found is None else (found["table"], found["column"]) + + key = str(cause.args[-1]).rpartition(" for key '")[2].removesuffix("'") + name = key.rpartition(".")[2] + held = {self._key_column(table, name) for table in tables} - {None} + return held.pop() if len(held) == 1 else None - 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) + def _key_column(self, table: str, name: str) -> tuple[str, str] | None: + """Return the table and the column of a unique constraint of one column, by its name.""" + connection = connections[self.using] + with connection.cursor() as cursor: + constraints = connection.introspection.get_constraints(cursor, table) - taken = holds_any(other, conditions, self._policy, binding, values) - if others.filter(taken).exists(): - raise UniquenessException + constraint = constraints.get(name) + if constraint is None or not constraint["unique"]: + return None + + columns = constraint["columns"] + return (table, columns[0]) if len(columns) == 1 else None def _links( self, mapping: ResourceMapping, resource: Resource[Any] @@ -658,19 +668,6 @@ 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/models.py b/tests/models.py index e7d4791..aa858e1 100644 --- a/tests/models.py +++ b/tests/models.py @@ -4,8 +4,11 @@ from django.contrib.auth.models import Group as AuthGroup from django.db import models from django.db.models import F +from django.db.models import Q from django.db.models.functions import Lower +from scim2_django.storage import ComparisonKey + class CodeField(models.TextField): """A text field converting the codes it reads, as a field decrypting its values would.""" @@ -14,6 +17,27 @@ def from_db_value(self, value, expression, connection): return None if value is None else value.upper() +class ExactTextField(models.TextField): + """A text field telling the case apart on MariaDB too, whose default collation ignores it.""" + + def db_parameters(self, connection): + parameters = super().db_parameters(connection) + if connection.vendor == "mysql": + parameters["collation"] = "utf8mb4_nopad_bin" + + return parameters + + +def comparison_key(field): + """Return a unique generated field holding the comparison key of a field.""" + return models.GeneratedField( + expression=ComparisonKey(field), + output_field=models.TextField(), + db_persist=True, + unique=True, + ) + + class LooseTextField(models.Field): """A field built on Field, which Django stores as text.""" @@ -25,6 +49,7 @@ class UserRecord(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) external_id = models.TextField(null=True) user_name = models.TextField(unique=True) + user_name_key = comparison_key("user_name") display_name = models.TextField(null=True) title = models.TextField(null=True) nick_name = models.TextField(null=True) @@ -172,6 +197,7 @@ class Person(models.Model): id = models.CharField(primary_key=True, max_length=64, default=uuid.uuid4) user_name = models.TextField() + user_name_key = comparison_key("user_name") serial = models.TextField(unique=True, null=True) data = models.JSONField(null=True) code = CodeField(null=True) @@ -202,6 +228,7 @@ class Volunteer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) user_name = models.TextField(unique=True) + user_name_key = comparison_key("user_name") active = models.BooleanField() version = models.PositiveIntegerField(default=1) @@ -263,6 +290,7 @@ class Note(models.Model): class TaggedUser(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) user_name = models.TextField(unique=True) + user_name_key = comparison_key("user_name") created = models.DateTimeField() last_modified = models.DateTimeField() version = models.PositiveIntegerField(default=1) @@ -282,6 +310,7 @@ class Member(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4) email = models.EmailField(unique=True) + email_key = comparison_key("email") groups = models.ManyToManyField(GroupRecord, related_name="+") USERNAME_FIELD = "email" @@ -292,6 +321,7 @@ class Guest(AbstractBaseUser): """A user model whose groups are those of django.contrib.auth, without a relation back.""" name = models.TextField(unique=True) + name_key = comparison_key("name") groups = models.ManyToManyField("auth.Group", related_name="+") USERNAME_FIELD = "name" @@ -312,6 +342,7 @@ class Twin(AbstractBaseUser): """A user model with two models beside it.""" name = models.TextField(unique=True) + name_key = comparison_key("name") USERNAME_FIELD = "name" @@ -341,6 +372,7 @@ class MailboxRecord(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) display_name = models.TextField(null=True) owner = models.TextField(null=True) + owner_key = comparison_key("owner") owner_display = models.TextField(null=True) created = models.DateTimeField() last_modified = models.DateTimeField() @@ -352,6 +384,7 @@ class MailboxAddressRecord(models.Model): MailboxRecord, on_delete=models.CASCADE, related_name="addresses" ) value = models.TextField(null=True) + value_key = comparison_key("value") type = models.TextField(null=True) class Meta: @@ -362,73 +395,75 @@ class MailboxAliasRecord(models.Model): mailbox = models.ForeignKey( MailboxRecord, on_delete=models.CASCADE, related_name="aliases" ) - value = models.TextField() + value = ExactTextField(unique=True) 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 ProxyMailboxRecord(MailboxRecord): + """The mailboxes, as another resource type reads them.""" class Meta: - ordering = ["id"] + proxy = True + +class MailboxListRecord(models.Model): + """Addresses of a mailbox in a unique column named as the one of the aliases.""" -class SharedMailboxAliasRecord(models.Model): mailbox = models.ForeignKey( - SharedMailboxRecord, on_delete=models.CASCADE, related_name="aliases" + MailboxRecord, on_delete=models.CASCADE, related_name="lists" ) - value = models.TextField() + value = ExactTextField(unique=True) + value_key = comparison_key("value") 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 Keyed(models.Model): + """A record whose fields are held, or not, by each kind of unique constraint.""" + id = models.UUIDField(primary_key=True, default=uuid.uuid4) + user_name = models.TextField(null=True) + user_name_key = models.GeneratedField( + expression=ComparisonKey("user_name"), + output_field=models.TextField(), + db_persist=True, + ) + code = models.TextField(unique=True, null=True) + together = models.TextField(null=True) + constrained = models.TextField(null=True) + conditional = models.TextField(null=True) + loose = models.TextField(null=True) + keyed = models.TextField(null=True) + keyed_key = comparison_key("keyed") -class OfficeRecord(MailboxRecord): - """A mailbox of an office, which can share its mailbox with a room.""" - - floor = models.PositiveIntegerField(null=True) + class Meta: + unique_together = [("together",)] + constraints = [ + models.UniqueConstraint(fields=["constrained"], name="keyed_constrained"), + models.UniqueConstraint( + fields=["conditional"], + condition=Q(conditional__isnull=False), + name="keyed_conditional", + ), + ] -class MailboxView(models.Model): - """The mailboxes, as a model of the same table that Django does not manage.""" +class Deferred(models.Model): + """A user whose external identifier is unique when the transaction commits, on PostgreSQL.""" 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) + user_name = models.TextField() + user_name_key = comparison_key("user_name") + external_id = models.TextField(null=True) class Meta: - managed = False - db_table = MailboxRecord._meta.db_table + constraints = [ + models.UniqueConstraint( + fields=["external_id"], + name="deferred_external_id", + deferrable=models.Deferrable.DEFERRED, + ), + ] diff --git a/tests/test_contract.py b/tests/test_contract.py index fb5af36..5f9004d 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -9,7 +9,6 @@ from .mappings import mailboxes_mapping from .mappings import prefixed from .mappings import users_mapping -from .models import SharedMailboxRecord pytestmark = pytest.mark.django_db @@ -32,7 +31,6 @@ def storage(self, provider): "User": users_mapping(), "Group": groups_mapping(), "Mailbox": mailboxes_mapping(), - "SharedMailbox": mailboxes_mapping(SharedMailboxRecord), } return DjangoStorage(mappings, provider) diff --git a/tests/test_entry.py b/tests/test_entry.py index f89ca37..1f6dfff 100644 --- a/tests/test_entry.py +++ b/tests/test_entry.py @@ -191,17 +191,14 @@ def test_a_sort_on_a_constant_orders_the_users_without_entry_apart( ] -def refuse_work(binding, value): - if value.lower() == "work": - raise ValueError("The policy cannot prepare this string") - - return value.lower() +def refuse_strings(binding, value): + raise ValueError("The policy cannot prepare this string") @pytest.mark.filterwarnings("ignore:The .* storage cannot compare") def test_a_constant_the_policy_cannot_prepare_sorts_as_no_value(): server = Server( - policy=ScimPolicy(comparison_key=refuse_work), + policy=ScimPolicy(comparison_key=refuse_strings), mappings={"User": users_mapping({"emails": EMAILS})}, ) create(server, "a", [work("alice@example.com")]) diff --git a/tests/test_examples.py b/tests/test_examples.py index 193f8fd..40c87bf 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -1,5 +1,9 @@ +import importlib + import pytest +from django.apps import apps from django.core.management import call_command +from django.db import connection SCIM_JSON = "application/scim+json" ENTERPRISE_SCHEMA = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User" @@ -131,3 +135,31 @@ def test_the_migrations_of_the_example_follow_its_models(settings): settings.MIGRATION_MODULES = {} call_command("makemigrations", "examples", "--check", "--dry-run") + + +@pytest.mark.django_db(transaction=True) +def test_the_example_migration_refuses_a_user_name_in_another_case(client): + """The constraint the example puts on the users of django.contrib.auth ignores the case of their names, and the 409 does not tell the name.""" + migration = importlib.import_module("examples.migrations.0004_username_key") + user = {"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"]} + with connection.schema_editor() as schema_editor: + migration.add_username_key(apps, schema_editor) + + try: + response = client.post( + "/accounts/scim/v2/Users", + user | {"userName": "bjensen"}, + content_type=SCIM_JSON, + ) + assert response.status_code == 201 + + response = client.post( + "/accounts/scim/v2/Users", + user | {"userName": "BJensen"}, + content_type=SCIM_JSON, + ) + assert response.status_code == 409 + assert "BJensen" not in response.json()["detail"] + finally: + with connection.schema_editor() as schema_editor: + migration.remove_username_key(apps, schema_editor) diff --git a/tests/test_mapping.py b/tests/test_mapping.py index 97c31c1..fa52149 100644 --- a/tests/test_mapping.py +++ b/tests/test_mapping.py @@ -14,18 +14,23 @@ from django.db.models import Value from django.db.models.functions import Concat from scim2_models import URN +from scim2_models import CaseExact from scim2_models import ComplexAttribute from scim2_models import Extension from scim2_models import Group from scim2_models import Mutability from scim2_models import Required from scim2_models import Resource +from scim2_models import ResourceType from scim2_models import Returned +from scim2_models import SearchRequest from scim2_models import Uniqueness from scim2_models import User +from scim2_server.testing import Mailbox from scim2_django.storage import Attribute from scim2_django.storage import Computed +from scim2_django.storage import DjangoStorage from scim2_django.storage import Entry from scim2_django.storage import Link from scim2_django.storage import Many @@ -41,6 +46,7 @@ from .models import Contractor from .models import Counted from .models import GroupRecord +from .models import Keyed from .models import Locker from .models import Person from .models import TaggedUser @@ -105,6 +111,15 @@ class Owned(Extension): SEALED = "urn:example:params:scim:schemas:extension:sealed:2.0:User" +REGISTERED = "urn:example:params:scim:schemas:extension:registered:2.0:User" + + +class Registered(Extension): + __schema__ = URN(REGISTERED) + + code: Annotated[str | None, Uniqueness.server, CaseExact.true] = None + + class Sealed(Extension): __schema__ = URN(SEALED) @@ -824,6 +839,78 @@ def test_a_unique_value_hidden_from_clients_is_refused(): assert error_ids(mapping) == ["scim2_django.E012"] +def keyed_mapping(user_name="keyed", code=None): + """Return a mapping of the keyed records, whose unique attributes map to the given fields.""" + attributes = {"id": "id", "userName": user_name} + if code is not None: + attributes[f"{REGISTERED}:code"] = code + + return ResourceMapping(User[Registered], Keyed, attributes) + + +@pytest.mark.parametrize( + "field", ["code", "together", "constrained", "keyed"], ids=lambda field: field +) +def test_a_case_exact_unique_value_needs_a_unique_constraint(field): + """The field itself, or the comparison key of the field, is unique in the database.""" + assert error_ids(keyed_mapping(code=field)) == [] + + +@pytest.mark.parametrize( + "field", ["conditional", "loose"], ids=["conditional", "no constraint"] +) +def test_a_case_exact_unique_value_without_unique_constraint_is_refused(field): + """A constraint with a condition lets two resources share a value.""" + (error,) = keyed_mapping(code=field).check() + + assert error.id == "scim2_django.E013" + assert f"a unique constraint on tests.Keyed.{field}" in error.msg + + +@pytest.mark.parametrize("field", ["code", "user_name"], ids=["unique", "key"]) +def test_a_unique_value_ignoring_the_case_needs_a_unique_comparison_key(field): + """A unique field tells Alice from alice, and so does a comparison key without unique constraint.""" + (error,) = keyed_mapping(user_name=field).check() + + assert error.id == "scim2_django.E013" + assert f"a unique GeneratedField of ComparisonKey({field!r})" in error.msg + + +def test_a_unique_value_the_storage_only_reads_needs_no_constraint(): + """The application writing the value keeps it unique.""" + mapping = keyed_mapping(code=Attribute("loose", writable=False)) + + assert error_ids(mapping) == [] + + +def test_unique_entries_need_a_unique_constraint(): + """The tags of a user are no unique aliases.""" + mapping = ResourceMapping( + Mailbox, + TaggedUser, + {"id": "id", "aliases": Many("tags", "value")}, + ) + + assert error_ids(mapping) == ["scim2_django.E013"] + + +@pytest.mark.django_db +def test_a_silenced_error_lets_the_storage_run(settings): + """A project holding the values in a constraint the check cannot see silences the error.""" + settings.SILENCED_SYSTEM_CHECKS = [] + mapping = keyed_mapping(code="loose") + storage = DjangoStorage({"User": mapping}) + users = ResourceType.from_resource(User[Registered]) + + with pytest.raises( + ImproperlyConfigured, match="unique constraint on tests.Keyed.loose" + ): + storage.search([users], SearchRequest()) + + settings.SILENCED_SYSTEM_CHECKS = ["scim2_django.E013"] + assert storage.search([users], SearchRequest()).total == 0 + + def test_a_mapping_with_another_error_is_not_told_about_its_unwritten_fields(): """The unknown field may be the one that was meant to be written.""" mapping = applicant_mapping(active="enable") diff --git a/tests/test_search.py b/tests/test_search.py index eca9b77..df0c7b0 100644 --- a/tests/test_search.py +++ b/tests/test_search.py @@ -22,8 +22,8 @@ from scim2_django.storage import Computed from scim2_django.storage import Many from scim2_django.storage.comparison import _comparator -from scim2_django.storage.comparison import _vendor from scim2_django.storage.conversion import _to_scim +from scim2_django.storage.key import _vendor from scim2_django.storage.query import _search from .mappings import ENTERPRISE diff --git a/tests/test_storage.py b/tests/test_storage.py index 9c359b5..f2d0702 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -19,33 +19,30 @@ 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_TYPE from scim2_server.testing import Mailbox from scim2_server.utils import load_default_provider from scim2_server.utils import load_default_service_provider_config from scim2_django import ScimSite from scim2_django.storage import DjangoStorage +from scim2_django.storage import Many from scim2_django.storage import ResourceMapping -from scim2_django.storage.comparison import _vendor -from scim2_django.storage.storage import _same_rows +from scim2_django.storage.key import _vendor 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 Deferred 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 @@ -57,12 +54,9 @@ NOW = datetime.datetime(2026, 11, 20, 8, 0, tzinfo=datetime.UTC) -def strict_key(binding, value): - """Fold the case, and refuse the strings holding an exclamation mark.""" - if "!" in value: - raise ValueError("'!' cannot be compared") - - return value if binding.case_exact else value.casefold() +def refuse_strings(binding, value): + """Refuse to compare any string.""" + raise ValueError("The policy cannot compare this string") class Server: @@ -147,28 +141,6 @@ def test_a_write_since_the_record_was_read_is_refused(): assert UserRecord.objects.filter(user_name="bjensen").exists() -class Racing(DjangoStorage): - """A storage whose first uniqueness check of each write misses a value taken in the meantime.""" - - checks = 0 - - def _check_uniqueness(self, mapping, resource, stored, record): - self.checks += 1 - if self.checks % 2 == 0: - super()._check_uniqueness(mapping, resource, stored, record) - - -def test_a_unique_value_taken_in_the_meantime_is_refused(): - """The database refuses the value, and the storage tells the client why.""" - server = Server(Racing) - server.create_user("bjensen") - - with pytest.raises(UniquenessException): - server.create_user("BJENSEN") - - assert UserRecord.objects.count() == 1 - - @pytest.mark.parametrize( "cause", [ValueError("check"), None], ids=["database", "project"] ) @@ -321,7 +293,7 @@ def test_a_member_of_another_type_is_refused(server): @pytest.mark.filterwarnings("ignore:The .* storage cannot compare") def test_a_type_the_policy_cannot_compare_is_refused(): - server = Server(policy=ScimPolicy(comparison_key=strict_key)) + server = Server(policy=ScimPolicy(comparison_key=refuse_strings)) user = server.create_user("bjensen") with pytest.raises(InvalidValueException, match="not of type 'User!'"): @@ -339,24 +311,6 @@ def test_a_group_resource_type_without_provider(): assert group.members is None -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, 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") - - server.create_user("alice") - record = UserRecord.objects.create( - user_name="Alice", created=NOW, last_modified=NOW - ) - other = server.storage.get(server.users, str(record.pk)) - other.display_name = "Other Alice" - - assert server.storage.update(server.users, other).display_name == "Other Alice" - - other.user_name = "ALICE" - 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( server, ): @@ -429,19 +383,6 @@ def test_a_resource_is_found_by_the_exact_text_of_its_identifier(server, text): server.create_group([{"value": value, "type": "Group"}]) -def test_a_value_a_unique_index_refuses_is_not_unique(): - """The serial number is unique in the database, although SCIM lets two users share an externalId.""" - server = Server(mappings={"User": users_mapping({"externalId": "serial"})}) - server.storage.create( - server.users, server.user_model(user_name="a", external_id="1") - ) - - with pytest.raises(UniquenessException): - server.storage.create( - server.users, server.user_model(user_name="b", external_id="1") - ) - - def test_a_value_the_collation_of_a_unique_column_ignores_is_not_unique(server): """The default collation of MariaDB ignores the accents, so its unique index refuses José next to Jose.""" if _vendor(connection) != "mariadb": @@ -566,86 +507,105 @@ def test_a_value_never_returned_cannot_be_searched(search_request, 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(**mappings): + """Return a storage of the mailboxes, and of other resource types of the schema of the mailboxes.""" + resource_types = [MAILBOX_TYPE] + [ + ResourceType( + id=name, + name=name, + endpoint=f"/{name}", + schema_=MAILBOX_TYPE.schema_, + ) + for name in mappings + ] + provider = ScimProvider(models=[Mailbox], resource_types=resource_types) + mappings = {"Mailbox": mailboxes_mapping()} | mappings + return DjangoStorage(mappings, provider), resource_types -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) +def test_resource_types_sharing_a_table_share_its_unique_values(): + """The unique constraint of the owner holds the mailboxes of both types, as they are the same records.""" + storage, (mailboxes, shared) = mailbox_storage( + Shared=mailboxes_mapping(ProxyMailboxRecord) + ) + storage.create(mailboxes, Mailbox(owner={"value": "bjensen"})) + with pytest.raises(UniquenessException) as conflict: + storage.create(shared, Mailbox(owner={"value": "BJensen"})) + assert conflict.value.detail == "Uniqueness conflict with attribute owner.value" -SHARING_RECORDS = pytest.mark.parametrize( - "record", - [ProxyMailboxRecord, RoomRecord, MailboxView], - ids=["proxy", "multi-table", "same table"], -) +def test_a_unique_value_of_a_case_exact_attribute_tells_the_attribute(): + """The constraint holding the aliases is on their field itself.""" + storage, (mailboxes,) = mailbox_storage() + storage.create(mailboxes, Mailbox(aliases=["babs"])) -@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"} + with pytest.raises(UniquenessException) as conflict: + storage.create(mailboxes, Mailbox(aliases=["babs"])) + assert conflict.value.detail == "Uniqueness conflict with attribute aliases" - updated = storage.update(mailboxes, mailbox) - assert updated.owner.value == "bjensen" - assert MailboxRecord.objects.get().owner == "bjensen" +def test_a_key_name_of_several_tables_does_not_tell_the_attribute(): + """MariaDB tells the name of the key only, which the aliases and the addresses share.""" + mapping = ResourceMapping( + Mailbox, + MailboxRecord, + { + "id": "id", + "addresses": Many("lists", {"value": "value"}), + "aliases": Many("aliases", "value"), + "meta.created": "created", + "meta.lastModified": "last_modified", + }, + ) + storage = DjangoStorage({"Mailbox": mapping}) + storage.create(MAILBOX_TYPE, Mailbox(aliases=["babs"])) + + with pytest.raises(UniquenessException) as conflict: + storage.create(MAILBOX_TYPE, Mailbox(aliases=["babs"])) + if _vendor(connection) == "mariadb": + assert conflict.value.detail == UniquenessException().detail + else: + assert conflict.value.detail == "Uniqueness conflict with attribute aliases" -@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) +def test_a_constraint_holding_no_attribute_does_not_tell_the_value(): + """The serial number is unique in the database only, and the message of the database is not relayed.""" + server = Server(mappings={"User": users_mapping({"externalId": "serial"})}) + server.storage.create( + server.users, server.user_model(user_name="a", external_id="S-42") + ) + with pytest.raises(UniquenessException) as conflict: + server.storage.create( + server.users, server.user_model(user_name="b", external_id="S-42") + ) + assert conflict.value.detail == UniquenessException().detail -@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 +@pytest.mark.django_db(transaction=True) +def test_a_unique_value_refused_when_the_operation_commits_raises_a_409(): + """PostgreSQL checks a deferred unique constraint when the transaction commits.""" + if _vendor(connection) != "postgresql": + pytest.skip("Only PostgreSQL defers the unique constraints") -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" + mapping = ResourceMapping( + User, + Deferred, + {"id": "id", "userName": "user_name", "externalId": "external_id"}, + ) + server = Server( + mappings={"User": mapping, "Group": groups_mapping({"members": None})} + ) + server.storage.create( + server.users, server.user_model(user_name="a", external_id="1") + ) - assert storage.update(mailboxes, mailbox).display_name == "Babs" + with pytest.raises(UniquenessException) as conflict: + with server.storage.operation(): + server.storage.create( + server.users, server.user_model(user_name="b", external_id="1") + ) + assert conflict.value.detail == UniquenessException().detail + assert Deferred.objects.count() == 1 diff --git a/uv.lock b/uv.lock index be902a9..11b9817 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.10.0" }, + { name = "scim2-server", specifier = ">=0.11.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.10.0" }, + { name = "scim2-server", extras = ["cursor"], specifier = ">=0.11.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.10.0" +version = "0.11.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "scim2-models" }, ] -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" } +sdist = { url = "https://files.pythonhosted.org/packages/cb/ba/251b27ba688e26190f485b2ea4603475973e259ddf0f9a7a3b26112b795e/scim2_server-0.11.0.tar.gz", hash = "sha256:5f20c3f642e8c6ddea2863715c041d108f063f67eaecf7f234125134a15e2493", size = 94410, upload-time = "2026-11-28T14:41:55.139Z" } wheels = [ - { 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" }, + { url = "https://files.pythonhosted.org/packages/7a/e8/49c89de57d4af549c31d60ffc9644702b91e7bbcef9bf09a1b0083660905/scim2_server-0.11.0-py3-none-any.whl", hash = "sha256:94bbd173b8c11ca36073c0426f66a08bacef99d45a965ce3896b4b1aaa727d0a", size = 101363, upload-time = "2026-11-28T14:41:53.803Z" }, ] [package.optional-dependencies]