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

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

Added
^^^^^
- The storage checks the uniqueness of sub-attributes, such as ``emails.value``. Each value
of a multi-valued attribute counts on its own.
- Override :meth:`~scim2_sqlalchemy.SqlAlchemyStorage.generate_id` to choose the identifier of
a new resource. The asynchronous storage awaits it, so the identifier can come from another
service.

Changed
^^^^^^^
- scim2-server 0.10.0 or later is required.
- A mapping, and :func:`~scim2_sqlalchemy.generate_mappings`, refuse a unique attribute that
clients never read back, with a :class:`ValueError`. A 409 would tell that another resource
holds the value.

Fixed
^^^^^
- Per :rfc:`7643` erratum 8279, a unique value is checked against every resource type whose
schema holds the attribute, not only the resource type being written.
- An update that keeps or swaps the values of a :class:`~scim2_sqlalchemy.Many` no longer gets
a 409 from a unique index that the application adds to its table.

[0.4.0] - 2026-11-27
--------------------

Expand Down
25 changes: 21 additions & 4 deletions doc/explanation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -201,16 +201,33 @@ Unique values are checked twice
Before a write, the storage searches for another record holding a unique value of the resource,
such as its ``userName``, and answers 409 when it finds one. The search follows the case rules of
the attribute, so ``BJensen`` clashes with ``bjensen``, which a plain unique constraint does not
catch. A unique constraint of the database remains the guard against two concurrent writes. When
a flush fails on a unique constraint, the storage answers 409. This also holds when the constraint
is stricter than the search: under a collation that ignores the accents, as the default ones of
catch.

A unique value can be below an attribute, such as ``emails.value``. Each value of a multi-valued
attribute counts on its own, wherever the mapping stores it: in a column, in an
:class:`~scim2_sqlalchemy.Entry`, in the entries of a :class:`~scim2_sqlalchemy.Many`, or as the
target of a :class:`~scim2_sqlalchemy.Link`. A resource may hold the same value twice. Per
:rfc:`7643` erratum 8279, the search covers every resource type whose schema holds the attribute.
The schema cannot make unique a value that clients never read back: the mapping refuses it, as a
409 would tell that another resource holds the value.

A unique constraint of the database remains the guard against two concurrent writes. When a flush
fails on a unique constraint, the storage answers 409. This also holds when the constraint is
stricter than the search: under a collation that ignores the accents, as the default ones of
MariaDB do, ``José`` clashes with ``Jose``. A flush that fails on a foreign key also gets a 409,
such as deleting a resource that a record outside SCIM still refers to. Any other
:exc:`~sqlalchemy.exc.IntegrityError` goes through unchanged.

:func:`~scim2_sqlalchemy.generate_mappings` puts a unique constraint on the unique columns of the
records only. Two concurrent writes can then take the same value of an entry. An application can
add a unique index to the table of the entries. The storage deletes the old entries before it
inserts the new ones, so the index accepts a resource that keeps its value. The index also refuses
a value repeated in one resource, which SCIM allows.

An update only checks the unique values it changes. Another application may have stored values
that clash under the case rules of SCIM, such as ``alice`` and ``Alice``. Each resource then
remains writable while it keeps its value.
remains writable while it keeps its value. Writing ``ALICE`` keeps the value too, as
``userName`` is not ``caseExact``.

The application owns the transaction
------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions doc/how-to/map-a-data-model.rst
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@ value that clients never read back. The storage still reads it, in the form its
such as a hash, and the server never shows it to clients. A PUT without the value gives the
stored one back to the storage, which keeps it as it is: a value equal to the stored one is not
written again. A PATCH that removes the value, or a PUT that sets it to ``null``, clears it. The
storage neither filters nor sorts on such a value, and does not check that it is unique: give its
column a unique constraint instead.
storage neither filters nor sorts on such a value. The schema cannot make it unique: the mapping
refuses it, as a 409 would tell that another resource holds the value.

The intranet hashes the password in the setter of a property, whose getter returns the hash:

Expand Down
4 changes: 2 additions & 2 deletions doc/reference/storages.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Storages
The storages reading and writing the resources with a SQLAlchemy :class:`~sqlalchemy.orm.Session`.

.. autoclass:: scim2_sqlalchemy.SqlAlchemyStorage
:members: operation
:members: operation, generate_id

.. autoclass:: scim2_sqlalchemy.AsyncSqlAlchemyStorage
:members: operation
:members: operation, generate_id
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ authors = [
requires-python = ">=3.11"
dependencies = [
"scim2-models>=0.12.7",
"scim2-server>=0.9.0",
"scim2-server>=0.10.0",
"sqlalchemy>=2.0.41",
]

Expand All @@ -54,7 +54,7 @@ dev = [
"pytest-cov>=7.1.0",
"pytest-postgresql>=9.1.0",
"scim2-client>=0.14.0",
"scim2-server[testing]>=0.9.0",
"scim2-server[testing]>=0.10.0",
"scim2-tester[testing]>=0.6.2",
"tox-uv>=1.36.0",
"werkzeug>=3.1.8",
Expand Down
23 changes: 23 additions & 0 deletions src/scim2_sqlalchemy/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,29 @@ def _loader_options(
for collection in collections
]

def _new_key(self, resource_id: str) -> Any:
"""Return the identifier a new record gets, in the type of its column.

Raise a ValueError when the storage cannot write the identifier, or when
its column cannot hold it.
"""
(value,) = [
value
for binding, value in self._declared.values()
if key(binding) == key(self._id.binding)
]
if not self._value_writable(value):
raise ValueError(
f"The storage cannot write the 'id' of {self.model.__name__}"
)

record_key = _as_key(self._id, resource_id)
if record_key is None:
raise ValueError(
f"The 'id' of {self.model.__name__} cannot be {resource_id!r}"
)
return record_key

def _is_target(self, value: Any) -> bool:
return isinstance(getattr(value, "key", None), str) and hasattr(value, "class_")

Expand Down
54 changes: 39 additions & 15 deletions src/scim2_sqlalchemy/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from typing import TypeVarTuple
from typing import cast as cast_type

from scim2_models import AttributeBinding
from scim2_models import InvalidCursorException
from scim2_models import InvalidPathException
from scim2_models import ResponseParameters
Expand All @@ -14,8 +15,8 @@
from scim2_server.keyset import Position
from scim2_server.mapping import Collection
from scim2_server.mapping import Column
from scim2_server.mapping.filters import compare
from scim2_server.mapping.filters import entry_present
from scim2_server.mapping.filters import holds_any
from scim2_server.mapping.filters import sort_target
from scim2_server.mapping.filters import where
from sqlalchemy import BigInteger
Expand Down Expand Up @@ -470,28 +471,51 @@ def _load_statement(
return statement.with_for_update() if locked else statement


def _id_taken_statement(
mapping: ResourceMapping, resource_id: str
) -> Select[Any] | None:
"""Return the statement finding a record of a mapping with an identifier, or None when no record can have it."""
key = _as_key(mapping._id, resource_id)
if key is None:
return None
condition = mapping._id.expression == _bound(mapping._id, key)
return select(mapping._id.expression).where(condition).limit(1)


def _taken_statement(
mapping: ResourceMapping,
column: Column,
value: Any,
resource_id: str | None,
binding: AttributeBinding,
values: list[Any],
comparator: _Comparator,
record: Any,
) -> Select[Any]:
"""Return the statement finding another record holding a unique value."""
condition = compare(
mapping,
_Predicates(comparator),
comparator.policy,
column,
CompareOperator.eq,
value,
"""Return the statement finding a record of a mapping holding one of some unique values.

record is the record an update writes, and None for a new resource. It is
left out, even when it is read through another mapping of its class.
"""
condition = holds_any(
mapping, _Predicates(comparator), comparator.policy, binding, values
)
key = None if resource_id is None else _as_key(mapping._id, resource_id)
if key is not None:
condition = and_(condition, mapping._id.expression != _bound(mapping._id, key))
if record is not None:
condition = and_(condition, _other_than(mapping, record))
return select(mapping._id.expression).where(condition).limit(1)


def _other_than(mapping: ResourceMapping, record: Any) -> ColumnElement[bool]:
"""Return the condition that a record of a mapping is not the given one.

Two classes share their records when their base classes map the same
table, such as two classes of a table, or of an inheritance.
"""
mapper: Mapper[Any] = inspect(mapping.record)
state = inspect(record)
if mapper.base_mapper.local_table is not state.mapper.base_mapper.local_table:
return true()
keys = zip(mapper.primary_key, state.identity, strict=True)
return not_(and_(*(column == key for column, key in keys)))


def _links_statement(collection: Collection, ids: list[str]) -> Select[Any]:
"""Return the statement loading the records a Link links to."""
target = cast_type(ResourceMapping, collection.target)
Expand Down
Loading