Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions doc/changelog.rst
Original file line number Diff line number Diff line change
@@ -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
--------------------

Expand Down
44 changes: 44 additions & 0 deletions doc/how-to/serve-the-users-of-django.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
-------------------------------------------

Expand Down
6 changes: 6 additions & 0 deletions doc/overview.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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``;
Expand Down
13 changes: 12 additions & 1 deletion doc/reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ and Django models.

.. autoclass:: scim2_django.storage.Link

.. autoclass:: scim2_django.storage.ComparisonKey

Users of django.contrib.auth
----------------------------

Expand All @@ -61,7 +63,8 @@ System checks
With ``scim2_django`` in :setting:`INSTALLED_APPS`, the :doc:`system check framework
<django:topics/checks>` 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:

Expand Down Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions examples/migrations/0003_login_key.py
Original file line number Diff line number Diff line change
@@ -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,
),
),
]
27 changes: 27 additions & 0 deletions examples/migrations/0004_username_key.py
Original file line number Diff line number Diff line change
@@ -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),
]
7 changes: 7 additions & 0 deletions examples/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions examples/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@
DATABASES = {
"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "db.sqlite3"},
}
SILENCED_SYSTEM_CHECKS = ["scim2_django.E013"]
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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",
]
Expand Down
2 changes: 2 additions & 0 deletions src/scim2_django/storage/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .key import ComparisonKey
from .mapping import Attribute
from .mapping import Computed
from .mapping import Entry
Expand All @@ -9,6 +10,7 @@

__all__ = [
"Attribute",
"ComparisonKey",
"Computed",
"DjangoStorage",
"Entry",
Expand Down
91 changes: 11 additions & 80 deletions src/scim2_django/storage/comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand All @@ -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.

Expand Down Expand Up @@ -237,57 +196,29 @@ 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:
"""Return how a database compares strings, warning when it cannot follow the policy."""
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 "
"key of the policy: filters and uniqueness checks only approach it",
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 "
Expand Down
Loading