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_server.testing.ScimStorageContract` checks the uniqueness of sub-attributes and
of multi-valued attributes, for a storage setting
:attr:`~scim2_server.testing.ScimStorageContract.stores_mailboxes`.
:func:`~scim2_server.storage.unique_values` lists the values a storage checks.

Changed
^^^^^^^
- A unique sub-attribute is unique among the resources, and each value of a multi-valued attribute
counts on its own: ``["a", "b"]`` and ``["a"]`` now clash.
- A unique value clients never read is not checked, as a 409 would tell that another resource
holds it. A mapping refuses such an attribute.

[0.9.0] - 2026-11-27
--------------------

Expand Down
6 changes: 6 additions & 0 deletions doc/how-to/check-a-storage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,12 @@ suite then checks that the storage leaves these dates empty. For a storage that
the password of the users, set :attr:`~scim2_server.testing.ScimStorageContract.stores_password`
to :data:`False`.

The suite checks the uniqueness of sub-attributes and of multi-valued attributes on
:class:`~scim2_server.testing.Mailbox` resources. To run these tests, set
:attr:`~scim2_server.testing.ScimStorageContract.stores_mailboxes` to :data:`True`, and serve the
``Mailbox`` and ``SharedMailbox`` resource types. Both use the
:class:`~scim2_server.testing.Mailbox` model.

A storage refuses a filter it cannot translate with :class:`~scim2_models.InvalidFilterException`,
and a sort with :class:`~scim2_models.InvalidPathException`. The suite skips the filters and the
sorts the storage refuses, and checks the others:
Expand Down
5 changes: 5 additions & 0 deletions doc/how-to/write-a-storage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,11 @@ exception:
:pyobject: AsyncSQLiteStorage.writing
:dedent: 4

A sub-attribute can be unique too, such as the ``value`` of an email in a model of yours. Each
value of a multi-valued attribute then counts on its own, and two equal values in the same
resource do not clash. :func:`~scim2_server.storage.unique_values` lists the unique values of a
resource, by attribute.

Update a resource
-----------------

Expand Down
2 changes: 1 addition & 1 deletion doc/reference/mapping.rst
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Filters and sorts
-----------------

.. automodule:: scim2_server.mapping.filters
:members: Predicates, where, compare, present, entry_present, sort_target, holds
:members: Predicates, where, compare, present, entry_present, sort_target, holds, holds_any

Reading and writing
-------------------
Expand Down
2 changes: 2 additions & 0 deletions doc/reference/storages.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ resources in memory.
.. autoclass:: scim2_server.storage.SearchPage
:members:

.. autofunction:: scim2_server.storage.unique_values

.. autoclass:: scim2_server.memory.InMemoryStorage
:members: generate_id, next_version, operation

Expand Down
8 changes: 7 additions & 1 deletion doc/reference/testing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ The test suites checking that a storage follows the storage contract. They need
``testing`` extra.

.. autoclass:: scim2_server.testing.ScimStorageContract
:members: supports_root_search, stores_created, stores_last_modified, stores_password, search_users
:members: supports_root_search, stores_created, stores_last_modified, stores_password, stores_mailboxes, search_users

.. autoclass:: scim2_server.testing.Mailbox()

.. autoclass:: scim2_server.testing.MailboxAddress()

.. autoclass:: scim2_server.testing.MailboxOwner()

.. autoclass:: scim2_server.testing.AsyncScimStorageContract
36 changes: 36 additions & 0 deletions scim2_server/mapping/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from typing import Any
from typing import Protocol
from typing import TypeVar
from typing import cast

from scim2_models import AttributeBinding
from scim2_models import InvalidFilterException
Expand Down Expand Up @@ -455,6 +456,41 @@ def compare(
)


def holds_any(
mapping: ResourceMapping,
conditions: Predicates[C],
policy: ScimPolicy,
binding: AttributeBinding,
values: list[Any],
) -> C:
"""Return the condition that a record holds one of some values of an attribute.

The attribute is one of the unique attributes of the mapping, and the
values are those of a resource, as
:func:`~scim2_server.storage.unique_values` returns them. The values are
compared as a filter with ``eq`` compares them, in the record, in an
Entry, in the entries of a collection or in a Link. The condition does
not leave out the written resource: the storage does.
"""

def any_value(inner: Predicates[C], column: Column) -> C:
return inner.any(
compare(mapping, inner, policy, column, CompareOperator.eq, value)
for value in values
)

holders = [
(collection, cast(Column, column))
for collection, column in mapping._lookup(binding)
]
return conditions.any(
any_value(conditions, column)
if collection is None
else conditions.exists(collection, partial(any_value, column=column))
for collection, column in holders
)


def _compare_constant(
mapping: ResourceMapping,
conditions: Predicates[C],
Expand Down
44 changes: 34 additions & 10 deletions scim2_server/mapping/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,15 @@ def _build(self) -> Problems:
self._collections[head] = collections
else:
column = yield from self._build_column(path, binding, value, None)
if column is not None and column.concealed and _unique(binding):
yield MappingProblem(
"error",
"hidden-unique",
f"{path!r} is hidden from clients, so it cannot be unique: "
"refusing a value would tell that another resource holds it",
)
column = None

if column is not None:
self._columns[key(binding)] = column

Expand Down Expand Up @@ -841,17 +850,28 @@ def _string_columns(self) -> Iterator[Column]:
if column.is_string:
yield column

def _unique_columns(self) -> Iterator[Column]:
"""Yield the written columns clients read, whose values no two resources share."""
for column in self._columns.values():
if column.concealed or not column.writable or column.in_entry:
continue
def _unique_attributes(self) -> dict[str, AttributeBinding]:
"""Return the attributes whose values no two resources share, by URN.

if column.binding.get_annotation(Uniqueness) in (
Uniqueness.server,
Uniqueness.global_,
):
yield column
They may be held by the record, by an Entry, by the entries of a
collection, or be the value of a Link. A value the storage only reads
counts too, as clients read it. The id is left out: the storage
generates it.
"""
columns = [
*(column for column in self._columns.values() if column is not self._id),
*(
column
for collection in self._all_collections()
for name, column in collection.columns.items()
if collection.owned or name == "value"
),
]
return {
column.binding.urn: column.binding
for column in columns
if _unique(column.binding)
}

def _returned_collections(
self, parameters: ResponseParameters[Any] | None = None
Expand All @@ -871,3 +891,7 @@ def _returned_collections(
return [
collection for collection in collections if collection.binding.urn in kept
]


def _unique(binding: AttributeBinding) -> bool:
return binding.get_annotation(Uniqueness) in (Uniqueness.server, Uniqueness.global_)
60 changes: 30 additions & 30 deletions scim2_server/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
from scim2_models import ResponseParameters
from scim2_models import ScimFilter
from scim2_models import SearchRequest
from scim2_models import Uniqueness
from scim2_models import UniquenessException
from scim2_models.path import CompareOperator
from scim2_models.path import Comparison
Expand All @@ -30,6 +29,7 @@
from scim2_server.storage import SearchPage
from scim2_server.storage import projection
from scim2_server.storage import search_page
from scim2_server.storage import unique_values
from scim2_server.utils import parametrize


Expand Down Expand Up @@ -196,7 +196,7 @@ class InMemoryStorage(ScimStorage):
def __init__(self, clock: Callable[[], datetime.datetime] = utcnow) -> None:
self._resources: dict[str | None, dict[str, Resource[Any]]] = {}
self._owners: dict[str, dict[Any, Key]] = {}
self._unique_values: dict[Key, dict[str, Any]] = {}
self._unique_values: dict[Key, dict[str, set[Any]]] = {}
self._equalities: dict[
str | None, dict[AttributeBinding, dict[Any, set[str]]]
] = {}
Expand Down Expand Up @@ -391,22 +391,29 @@ def _index_equality(
self._equal_values.setdefault(key, {})[binding] = value
self._equalities[key[0]][binding].setdefault(value, set()).add(key[1])

def _store(self, resource: Resource[Any], values: dict[str, Any]) -> None:
def _store(self, resource: Resource[Any], values: dict[str, set[Any]]) -> None:
"""Keep a resource under its resource type and its identifier, and index its values."""
key = _key(resource)
self._remove(key)
self._resources.setdefault(key[0], {})[key[1]] = resource
self._unique_values[key] = values
for urn, value in values.items():
self._owners.setdefault(urn, {})[value] = key
for urn, held in values.items():
owners = self._owners.setdefault(urn, {})
for value in held:
owners[value] = key

for binding in self._equalities.get(key[0], {}):
self._index_equality(resource, binding)

def _remove(self, key: Key) -> None:
"""Forget a resource and its indexed values."""
self._resources.get(key[0], {}).pop(key[1], None)
for urn, value in self._unique_values.pop(key, {}).items():
del self._owners[urn][value]
for urn, held in self._unique_values.pop(key, {}).items():
owners = self._owners[urn]
for value in held:
if owners.get(value) == key:
del owners[value]

for binding, value in self._equal_values.pop(key, {}).items():
self._equalities[key[0]][binding][value].discard(key[1])

Expand All @@ -427,37 +434,30 @@ def _check_version(resource: Resource[Any], expected_version: str | None) -> Non
raise PreconditionFailedException

def _check_uniqueness(
self, resource: Resource[Any], values: dict[str, Any]
self, resource: Resource[Any], values: dict[str, set[Any]]
) -> None:
"""Refuse a resource sharing a unique value with another resource."""
key = _key(resource)
for urn, value in values.items():
if self._owners.get(urn, {}).get(value, key) != key:
for urn, held in values.items():
owners = self._owners.get(urn, {})
if any(owners.get(value, key) != key for value in held):
raise UniquenessException()

def _values_of(self, resource: Resource[Any]) -> dict[str, Any]:
def _values_of(self, resource: Resource[Any]) -> dict[str, set[Any]]:
"""Return the unique values of a resource, by the URN of their attribute.

Per RFC 7643 erratum 8279, the uniqueness applies to the resources
using the schema that declares the attribute, whatever their resource
type. The URN of an attribute holds its schema, so two resources clash
when they hold the same value under the same URN. A missing value
never clashes, as a SQL NULL does not.

The values are compared under the policy of the write that stored
them, so a storage serves the resources of a single policy.
A value the policy cannot compare never clashes, as a missing value
does not. The values are compared under the policy of the write that
stored them, so a storage serves the resources of a single policy.
"""
unique_paths = parametrize(Path, type(resource)).iter_paths(
include_subattributes=False,
uniqueness=[Uniqueness.server, Uniqueness.global_],
)
values = {}
for path in unique_paths:
attribute = cast(AttributeBinding, path.resolve())
value = self._comparable_value(resource, attribute)
if value is not None:
values[attribute.urn] = _hashable(value)
return values
return {
urn: {
_hashable(comparable)
for _, comparable in pairs
if comparable is not None
}
for urn, pairs in unique_values(resource).items()
}

@staticmethod
def _comparable_value(resource: Resource[Any], attribute: AttributeBinding) -> Any:
Expand Down
Loading
Loading