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
14 changes: 14 additions & 0 deletions doc/changelog.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
Changelog
=========

[Unreleased]
------------

Added
^^^^^
- Unique sub-attributes such as ``emails.value`` are checked, each value of a list on its own, in
every resource type sharing the schema (RFC 7643 erratum 8279).

Changed
^^^^^^^
- Needs scim2-server 0.10.0 or later.
- ``manage.py check`` refuses a unique attribute that clients never read (``E012``).
- A resource can change the case of a unique value it already holds.

[0.3.0] - 2026-11-27
--------------------

Expand Down
3 changes: 3 additions & 0 deletions doc/reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ The checks report the following errors and warnings:
* - ``scim2_django.E011``
- An attribute that clients never read, write-only or never returned, is mapped to a
generated field, which the storage never writes.
* - ``scim2_django.E012``
- An attribute that clients never read, write-only or never returned, is unique. Refusing
one of its values would tell that another resource holds it.
* - ``scim2_django.W001``
- A string attribute that clients read is mapped to a text field that converts the values it
reads, such as a field decrypting them. Filters and sorts compare the stored values, not
Expand Down
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.9.0",
"scim2-server>=0.10.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.9.0",
"scim2-server[cursor]>=0.10.0",
"scim2-tester[testing]>=0.6.6",
"tox-uv>=1.36.0",
]
Expand Down
1 change: 1 addition & 0 deletions src/scim2_django/storage/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"entry-fields": "scim2_django.E007",
"single-link-null": "scim2_django.E003",
"unwritten": "scim2_django.W002",
"hidden-unique": "scim2_django.E012",
}
"""The identifiers of the system checks, by code of the problems of the mapping core."""

Expand Down
92 changes: 59 additions & 33 deletions src/scim2_django/storage/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@
from django.db import DEFAULT_DB_ALIAS
from django.db import IntegrityError
from django.db import connections
from django.db import models
from django.db import transaction
from django.db.models import F
from django.db.models import ProtectedError
from django.db.models import RestrictedError
from scim2_models import ConflictException
from scim2_models import NotFoundException
from scim2_models import Path
from scim2_models import PreconditionFailedException
from scim2_models import Resource
from scim2_models import ResourceType
Expand All @@ -25,19 +25,18 @@
from scim2_models import ScimProvider
from scim2_models import SearchRequest
from scim2_models import UniquenessException
from scim2_models.path import CompareOperator
from scim2_server.keyset import Bound
from scim2_server.keyset import Position
from scim2_server.keyset import keyset_page
from scim2_server.keyset import page_rows
from scim2_server.mapping import Collection
from scim2_server.mapping.conversion import assign_links
from scim2_server.mapping.conversion import check_storable
from scim2_server.mapping.conversion import comparable
from scim2_server.mapping.conversion import link_entries
from scim2_server.mapping.filters import compare
from scim2_server.mapping.filters import holds_any
from scim2_server.storage import ScimStorage
from scim2_server.storage import SearchPage
from scim2_server.storage import unique_values

from .comparison import _Comparator
from .comparison import _comparator
Expand Down Expand Up @@ -103,6 +102,12 @@ class DjangoStorage(ScimStorage):
``primary`` of the lone entry of an :class:`Entry` is the exception: it
accepts any value, and reads back as the primary one.

A unique value another resource holds raises
:class:`~scim2_models.UniquenessException`, in any resource type whose
schema has the attribute. This holds for sub-attributes too, such as
``emails.value``. Two concurrent writes can take the same value, unless
a unique index of the database refuses it.

The storage searches one resource type, or several at the root of the
server as one collection. It pages by index, or with cursors that give
stable pages (:rfc:`RFC 9865 <9865>`).
Expand Down Expand Up @@ -280,7 +285,7 @@ def create(
mapping = self._mapping(resource_type)
with transaction.atomic(using=self.using):
check_storable(mapping, resource, None)
self._check_uniqueness(mapping, resource, None)
self._check_uniqueness(mapping, resource, None, None)
links = self._links(mapping, resource)
record = mapping.record()
now = _now()
Expand Down Expand Up @@ -312,7 +317,7 @@ def update(
stored = self._to_scim(resource_type, record)
self._check_version(stored, expected_version)
check_storable(mapping, resource, stored)
self._check_uniqueness(mapping, resource, stored)
self._check_uniqueness(mapping, resource, stored, record)
links = self._links(mapping, resource)
self._count_write(mapping, record)
now = _now()
Expand Down Expand Up @@ -565,7 +570,9 @@ def _save(
except (ProtectedError, RestrictedError) as error:
raise _referenced() from error
except IntegrityError as error:
self._check_uniqueness(mapping, resource, stored)
self._check_uniqueness(
mapping, resource, stored, None if stored is None else record
)
if _is_duplicate(error):
raise UniquenessException from error

Expand All @@ -579,38 +586,44 @@ def _check_uniqueness(
mapping: ResourceMapping,
resource: Resource[Any],
stored: Resource[Any] | None,
record: Any,
) -> None:
"""Refuse a resource with a unique value another resource already has.

stored is the stored resource, None for a new one. A value it already
holds is not checked, so that values another application wrote can
stay as they are. A missing value never clashes, as a SQL NULL does
not.
A value the stored resource already holds is not checked, so that
values another application wrote can stay as they are. A missing value
never clashes, as a SQL NULL does not.
"""
comparator = self._comparator()
others = mapping.record._default_manager.using(self.using)
if stored is not None:
others = others.exclude(_with_ids(mapping._id, [stored.id], comparator))

for column in mapping._unique_columns():
value = Path(column.binding.urn).get(resource, strict=False)
current = (
None
if stored is None
else Path(column.binding.urn).get(stored, strict=False)
)
if value is None or comparable(value) == comparable(current):
held = {} if stored is None else unique_values(stored, self._policy)
for urn, pairs in unique_values(resource, self._policy).items():
kept = [key for _, key in held.get(urn, [])]
values = [
value for value, key in pairs if key is not None and key not in kept
]
if values:
self._check_values(mapping, urn, values, record)

def _check_values(
self, mapping: ResourceMapping, urn: str, values: list[Any], record: Any
) -> None:
"""Refuse values of an attribute that another resource holds.

Per RFC 7643 erratum 8279, the values are looked for in every mapping
whose schema has the attribute. The written record is left out of the
mappings whose records are its own, such as those of a proxy model.
"""
conditions = _Predicates(self._comparator())
for other in self.mappings.values():
binding = other._unique_attributes().get(urn)
if binding is None:
continue

condition = compare(
mapping,
_Predicates(comparator),
self._policy,
column,
CompareOperator.eq,
value,
)
if others.filter(condition).exists():
others = other.record._default_manager.using(self.using)
if record is not None and _same_rows(mapping.record, other.record):
others = others.exclude(pk=record.pk)

taken = holds_any(other, conditions, self._policy, binding, values)
if others.filter(taken).exists():
raise UniquenessException

def _links(
Expand Down Expand Up @@ -645,6 +658,19 @@ def _linked_records(self, collection: Collection, ids: list[str]) -> list[Any]:
return list(records)


def _same_rows(record: type[models.Model], other: type[models.Model]) -> bool:
"""Tell whether two models read the same rows, as proxy models, models of multi-table inheritance or models of one table do."""
return _root_table(record) == _root_table(other)


def _root_table(model: type[models.Model]) -> str:
"""Return the table of the model at the root of the multi-table inheritance of a model."""
concrete = cast(type[models.Model], model._meta.concrete_model)
parents = concrete._meta.get_parent_list()
root = parents[-1] if parents else concrete
return root._meta.db_table


def _is_duplicate(error: IntegrityError) -> bool:
"""Tell whether an integrity error comes from a unique index, by the code the driver of each database gives."""
cause: Any = error.__cause__
Expand Down
21 changes: 21 additions & 0 deletions tests/mappings.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
from scim2_models import EnterpriseUser
from scim2_models import Group
from scim2_models import User
from scim2_server.testing import Mailbox

from scim2_django.storage import Link
from scim2_django.storage import Many
from scim2_django.storage import ResourceMapping
from scim2_django.storage import Transformed

from .models import GroupRecord
from .models import MailboxRecord
from .models import UserRecord

ENTERPRISE = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
Expand Down Expand Up @@ -100,3 +102,22 @@ def groups_mapping(changes=None, version="version"):
path: value for path, value in attributes.items() if value is not None
}
return ResourceMapping(Group, GroupRecord, attributes, version=version)


def mailboxes_mapping(record=MailboxRecord):
"""Return a new mapping of the mailboxes of the storage contract."""
return ResourceMapping(
Mailbox,
record,
{
"id": "id",
"displayName": "display_name",
"addresses": Many("addresses", {"value": "value", "type": "type"}),
"aliases": Many("aliases", "value"),
"owner.value": "owner",
"owner.display": "owner_display",
"meta.created": "created",
"meta.lastModified": "last_modified",
},
version="version",
)
99 changes: 99 additions & 0 deletions tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,3 +333,102 @@ class Team(AuthGroup):

class Meta:
proxy = True


class MailboxRecord(models.Model):
"""A mailbox of the storage contract, whose owner is in its own fields."""

id = models.UUIDField(primary_key=True, default=uuid.uuid4)
display_name = models.TextField(null=True)
owner = models.TextField(null=True)
owner_display = models.TextField(null=True)
created = models.DateTimeField()
last_modified = models.DateTimeField()
version = models.PositiveIntegerField(default=1)


class MailboxAddressRecord(models.Model):
mailbox = models.ForeignKey(
MailboxRecord, on_delete=models.CASCADE, related_name="addresses"
)
value = models.TextField(null=True)
type = models.TextField(null=True)

class Meta:
ordering = ["id"]


class MailboxAliasRecord(models.Model):
mailbox = models.ForeignKey(
MailboxRecord, on_delete=models.CASCADE, related_name="aliases"
)
value = models.TextField()

class Meta:
ordering = ["id"]


class SharedMailboxRecord(models.Model):
"""A shared mailbox of the storage contract, in tables apart from the mailboxes."""

id = models.UUIDField(primary_key=True, default=uuid.uuid4)
display_name = models.TextField(null=True)
owner = models.TextField(null=True)
owner_display = models.TextField(null=True)
created = models.DateTimeField()
last_modified = models.DateTimeField()
version = models.PositiveIntegerField(default=1)


class SharedMailboxAddressRecord(models.Model):
mailbox = models.ForeignKey(
SharedMailboxRecord, on_delete=models.CASCADE, related_name="addresses"
)
value = models.TextField(null=True)
type = models.TextField(null=True)

class Meta:
ordering = ["id"]


class SharedMailboxAliasRecord(models.Model):
mailbox = models.ForeignKey(
SharedMailboxRecord, on_delete=models.CASCADE, related_name="aliases"
)
value = models.TextField()

class Meta:
ordering = ["id"]


class ProxyMailboxRecord(MailboxRecord):
"""The mailboxes, as another resource type reads them."""

class Meta:
proxy = True


class RoomRecord(MailboxRecord):
"""A mailbox of a room, whose fields are those of a mailbox."""

capacity = models.PositiveIntegerField(null=True)


class OfficeRecord(MailboxRecord):
"""A mailbox of an office, which can share its mailbox with a room."""

floor = models.PositiveIntegerField(null=True)


class MailboxView(models.Model):
"""The mailboxes, as a model of the same table that Django does not manage."""

id = models.UUIDField(primary_key=True, default=uuid.uuid4)
display_name = models.TextField(null=True)
created = models.DateTimeField()
last_modified = models.DateTimeField()
version = models.PositiveIntegerField(default=1)

class Meta:
managed = False
db_table = MailboxRecord._meta.db_table
Loading