diff --git a/doc/changelog.rst b/doc/changelog.rst index c0d5d11..c6673e2 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,20 @@ Changelog ========= +[Unreleased] +------------ + +Changed +^^^^^^^ +- Needs scim2-server 0.9.0 or later. +- The storage is built on the mapping core of scim2-server, :mod:`scim2_server.mapping`, which + scim2-sqlalchemy shares. Some messages of the system checks change, their identifiers do not. + +Fixed +^^^^^ +- A value outside the ``choices`` of its field is refused when the resource comes from the + provider of the server, and not only when it is an instance of the model of the mapping. + [0.2.0] - 2026-11-26 -------------------- diff --git a/pyproject.toml b/pyproject.toml index 105d8f9..e085a4a 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.8.9", + "scim2-server>=0.9.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.8.9", + "scim2-server[cursor]>=0.9.0", "scim2-tester[testing]>=0.6.6", "tox-uv>=1.36.0", ] diff --git a/src/scim2_django/storage/conversion.py b/src/scim2_django/storage/conversion.py index 3dff4ba..93b07fe 100644 --- a/src/scim2_django/storage/conversion.py +++ b/src/scim2_django/storage/conversion.py @@ -1,114 +1,36 @@ -import base64 -import datetime -import json +import hashlib from collections.abc import Iterable from collections.abc import Mapping -from enum import Enum -from inspect import isclass from typing import Any from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError from django.db import models -from django.utils.crypto import salted_hmac -from pydantic import BaseModel -from scim2_models import AttributeBinding +from django.utils.encoding import force_bytes from scim2_models import InvalidValueException -from scim2_models import Meta -from scim2_models import Mutability -from scim2_models import MutabilityException from scim2_models import Path from scim2_models import Resource +from scim2_server.mapping import conversion as core +from scim2_server.mapping.descriptors import Collection from .mapping import ResourceMapping +from .mapping import _as_stored from .mapping import _Collection from .mapping import _Column -from .mapping import _field_needs_value -from .mapping import _Storage +from .mapping import _related_record +_VERSION_SALT = "scim2_django.version" -def _as_scim(value: Any) -> Any: - """Return a value read from the database in the form SCIM holds it. - - A date without a time zone is in UTC: the storage writes it so when USE_TZ - is off. Binary values are encoded in base64, as the models expect them. - """ - if isinstance(value, datetime.datetime) and value.tzinfo is None: - return value.replace(tzinfo=datetime.UTC) - - if isinstance(value, memoryview): - value = bytes(value) - - if isinstance(value, bytes): - return base64.b64encode(value).decode() - - return value +def _version_key() -> bytes: + """Return the key of the hash of the resources without version field. -def _as_stored(value: Any) -> Any: - """Return a SCIM value in the form a field holds it. - - Dates are in UTC, without a time zone when USE_TZ is off, since Django - refuses aware dates then. + The hash is the one salted_hmac gives with the SECRET_KEY setting, so that + the versions do not change from former releases. """ - if isinstance(value, Enum): - return value.value - - if isinstance(value, datetime.datetime) and value.tzinfo is not None: - value = value.astimezone(datetime.UTC) - return value if settings.USE_TZ else value.replace(tzinfo=None) - - return value - - -def _get(column: _Column, record: Any) -> Any: - """Return the value a record holds for a column, None when the related record holding it does not exist. - - The record holds the value of an expression itself, even when the - expression reads a related record. - """ - if column.relation is None or column.expression is not None: - return getattr(record, column.key) - - related = _related_record(column, record) - return None if related is None else getattr(related, column.field.name) # type: ignore[union-attr] - - -def _related_record(column: _Column, record: Any) -> Any: - """Return the related record holding the field of a column, or None when it does not exist.""" - try: - return getattr(record, column.relation.get_accessor_name()) - except ObjectDoesNotExist: - return None - - -def _read(column: _Column, record: Any) -> Any: - """Return the SCIM value of a column of a record. - - An empty string is no value, as Django text fields store it. - """ - value = _get(column, record) - if value is None or (value == "" and column.empty_string): - return None - - return _as_scim(value) - - -def _version(mapping: ResourceMapping, record: Any, resource: Resource[Any]) -> str: - """Return the weak ETag of the version of a record, from its counter or else from the hash of its resource. - - The hash covers the whole resource but its version, so that any change - of the resource changes it, a change of its links included. It covers the - values hidden from clients too, so it is keyed with the SECRET_KEY setting: - a version tells nothing about these values. - """ - if mapping.version is not None: - return f'W/"{getattr(record, mapping.version)}"' - - data = json.dumps(resource.model_dump(mode="json"), sort_keys=True) - digest = salted_hmac("scim2_django.version", data, algorithm="sha256") - return f'W/"{digest.hexdigest()[:32]}"' + return hashlib.sha256( + force_bytes(_VERSION_SALT) + force_bytes(settings.SECRET_KEY) + ).digest() def _to_scim( @@ -117,7 +39,7 @@ def _to_scim( resource_type: str, model: type[Resource[Any]], endpoints: Mapping[str, str], - collections: Iterable[_Collection], + collections: Iterable[Collection], ) -> Resource[Any]: """Build the resource a record stores, as an instance of model. @@ -129,123 +51,22 @@ def _to_scim( by name: a link to one of them gets a $ref relative to the SCIM root, when model declares it, which the server makes absolute (RFC 7643 §2.3.7). """ - resource = model() - special = (mapping._id, mapping._created, mapping._last_modified) - for column in mapping._columns.values(): - if column in special or column.in_entry: - continue - - value = _read(column, record) - if value is not None: - Path[model](column.binding.urn).set(resource, value) # type: ignore[valid-type] - - for entry in mapping._entries.values(): - values = { - column.binding.urn.rsplit(".", 1)[-1]: _read(column, record) - for column in entry.columns.values() - } - if any(value is not None for value in values.values()): - values |= { - name: constant for name, (constant, _) in entry.constants.items() - } - Path[model](entry.binding.urn).set(resource, [values]) # type: ignore[valid-type] - - read: dict[str, tuple[bool, list[Any]]] = {} - for collection in collections: - endpoint = None - if Path[model](f"{collection.binding.urn}.$ref").resolve() is not None: # type: ignore[valid-type] - endpoint = endpoints.get(collection.resource_type) # type: ignore[arg-type] - - _, entries = read.setdefault(collection.binding.urn, (collection.single, [])) - for related in _related(collection, record): - entry = _read_entry(collection, related, endpoint) - if entry is not None: - entries.append(entry) - - for urn, (single, entries) in read.items(): - if entries: - Path[model](urn).set(resource, entries[0] if single else entries) # type: ignore[valid-type] - - resource.id = str(_read(mapping._id, record)) - resource.meta = Meta( - resource_type=resource_type, - created=_read_date(mapping._created, record), - last_modified=_read_date(mapping._last_modified, record), + return core.to_scim( + mapping, + record, + resource_type, + model, + endpoints, + collections, + _version_key(), ) - resource = model.model_validate(resource.model_dump()) - resource.meta.version = _version(mapping, record, resource) # type: ignore[union-attr] - return resource - - -def _read_date(column: _Column | None, record: Any) -> Any: - """Return a date of a record, or None when the mapping does not store it.""" - if column is None: - return None - - return _read(column, record) - - -def _related(collection: _Collection, record: Any) -> list[Any]: - """Return the records a collection of a record holds, as a list even for a single one. - - Without an ordering of their model, the records come in the order of - their primary key. - """ - related = getattr(record, collection.accessor) - if collection.single: - return [] if related is None else [related] - - records = related.all() - if not records.ordered: - records = records.order_by("pk") - - return list(records) - - -def _entries(collection: _Collection, resource: Resource[Any]) -> list[Any]: - """Return the entries a resource holds for a collection, as a list even for a single one.""" - if collection.single: - value = Path(collection.binding.urn).get(resource, strict=False) - return [] if value is None else [value] - - return _values(collection.binding, resource) - - -def _values(binding: AttributeBinding, resource: Resource[Any]) -> list[Any]: - """Return the entries a resource holds for a multi-valued attribute.""" - return list(Path(binding.urn).get(resource, strict=False) or []) - - -def _read_entry(collection: _Collection, entry: Any, endpoint: str | None) -> Any: - """Return the values of an entry, by sub-attribute name, or the value of an entry of a simple collection. - - A link gets a $ref when the endpoint of the resources it links to is known. - """ - if collection.simple: - return _read(collection.columns[None], entry) - - values = { - column.binding.urn.rsplit(".", 1)[-1]: _read(column, entry) - for column in collection.columns.values() - } - if collection.owned: - return values - - values["value"] = str(values["value"]) - if endpoint is not None: - values["$ref"] = f"{endpoint}/{values['value']}" - - if collection.link_type is not None: - values["type"] = collection.link_type - - return values def _from_scim( mapping: ResourceMapping, resource: Resource[Any], record: Any, - links: dict[_Collection, list[Any]], + links: dict[Collection, list[Any]], now: Any, creating: bool, ) -> None: @@ -256,60 +77,18 @@ def _from_scim( is written here too. links holds the records each Link of the resource links to. """ - for column, value in _dates(mapping, now, creating): - if column.relation is None: - setattr(record, column.field_key, value) - - for column in mapping._columns.values(): - if not column.writable or column.relation is not None or column.in_entry: - continue - - value = Path(column.binding.urn).get(resource, strict=False) - if _keeps(column, value, record, creating): - continue - - setattr(record, column.field_key, _stored(column, value)) - - for entry in mapping._entries.values(): - entries = _values(entry.binding, resource) - if not entry.writable or (creating and not entries): - continue - - item = entries[0] if entries else None - for column in entry.columns.values(): - value = getattr(item, column.binding.target_field_name, None) - if _keeps(column, value, record, creating): - continue + for column, value in core.dates(mapping, now, creating): + if column.relation is None: # type: ignore[attr-defined] + setattr(record, column.field_key, value) # type: ignore[attr-defined] - setattr(record, column.field_key, _stored(column, value)) + for column, value in core.write_plan(mapping, resource, record, creating): + setattr(record, column.field_key, _stored(column, value)) # type: ignore[attr-defined,arg-type] for collection in _written(mapping): if collection.single and not collection.owned: setattr(record, collection.accessor, next(iter(links[collection]), None)) -def _dates( - mapping: ResourceMapping, now: Any, creating: bool -) -> list[tuple[_Column, Any]]: - """Return the date columns set to the current time: the modification date, and the creation date when creating.""" - columns = [mapping._last_modified, mapping._created if creating else None] - return [(column, now) for column in columns if column is not None] - - -def _keeps(column: _Column, value: Any, record: Any, creating: bool) -> bool: - """Tell whether a value leaves a field as it is. - - When creating the record, a missing value keeps the default of the field, - unless to_field gives its value for no value. When updating it, a value - equal to the one the storage read is kept, without calling to_field, so - that a password hash is not hashed again. - """ - if creating: - return value is None and not column.transformed - - return bool(value == _read(column, record)) - - def _stored(column: _Column, value: Any) -> Any: """Return the value a field stores for a SCIM value, an empty string for no value in a text field without null. @@ -341,7 +120,7 @@ def _write_collections( mapping: ResourceMapping, resource: Resource[Any], record: Any, - links: dict[_Collection, list[Any]], + links: dict[Collection, list[Any]], now: Any, creating: bool, ) -> None: @@ -385,20 +164,20 @@ def _write_related( without default. """ values: dict[Any, list[tuple[_Column, Any]]] = {} - for column in mapping._columns.values(): + for column in _columns(mapping): if not column.writable or column.relation is None: continue value = Path(column.binding.urn).get(resource, strict=False) new = creating or _related_record(column, record) is None - if _keeps(column, value, record, new): + if core.keeps(mapping, column, value, record, new): continue values.setdefault(column.relation, []).append((column, value)) - for column, value in _dates(mapping, now, creating): - if column.relation is not None: - values.setdefault(column.relation, []).append((column, value)) + for date, value in core.dates(mapping, now, creating): + if date.relation is not None: # type: ignore[attr-defined] + values.setdefault(date.relation, []).append((date, value)) # type: ignore[attr-defined,arg-type] for relation, written in values.items(): # A handler of post_save may have created the related record since @@ -432,24 +211,31 @@ def _check_creatable( ) -> None: """Refuse to create a related record without a value for a mapped field that has no default.""" given = {column for column, _ in written} - for column in mapping._columns.values(): + for column in _columns(mapping): if column.relation is relation and column not in given: - if not column.nullable and _field_needs_value(column.field): # type: ignore[arg-type] + if not column.nullable and column.needs_value: raise InvalidValueException( detail=f"'{column.binding.urn}' is required on this server" ) +def _columns(mapping: ResourceMapping) -> Iterable[_Column]: + """Return the columns of the resource record of a mapping.""" + return mapping._columns.values() # type: ignore[return-value] + + def _written(mapping: ResourceMapping) -> Iterable[_Collection]: """Yield the collections that writing a resource changes.""" return ( - collection for collection in mapping._all_collections() if collection.writable + collection # type: ignore[misc] + for collection in mapping._all_collections() + if collection.writable ) def _write_entry(collection: _Collection, entry: Any, record: Any) -> models.Model: """Build the record storing an entry of a multi-valued attribute, for a resource record.""" - owner = collection.relation.field.name # type: ignore[union-attr] + owner = collection.relation.field.name entry_record = collection.entry_model(**{owner: record}) if collection.simple: setattr(entry_record, collection.columns[None].key, _as_stored(entry)) @@ -461,189 +247,3 @@ def _write_entry(collection: _Collection, entry: Any, record: Any) -> models.Mod setattr(entry_record, column.key, _as_stored(value)) return entry_record - - -def _link_entries( - mapping: ResourceMapping, resource: Resource[Any] -) -> list[tuple[list[_Collection], list[Any]]]: - """Return the entries of each written attribute of a resource linking to other resources, with the collections of its Links. - - A link is stored by its value, so an entry without one, such as an entry - with a $ref only, raises InvalidValueException rather than being lost. - """ - links = [] - for collections in mapping._collections.values(): - collection = collections[0] - if collection.owned or not collection.writable: - continue - - entries = _entries(collection, resource) - if any(entry.value is None for entry in entries): - raise InvalidValueException( - detail=f"'{collection.binding.urn}' holds an entry without value" - ) - - links.append((collections, entries)) - - return links - - -def _check_storable( - mapping: ResourceMapping, - resource: Resource[Any], - stored: Resource[Any] | None, -) -> None: - """Refuse a change of a resource that the mapping cannot store. - - Each attribute of the resource is compared with the stored resource, None - for a new one. A value equal to the stored one changes nothing, so a - resource read and sent back is accepted. A missing value changes nothing - either, except for a stored value whose field cannot hold none: removing it - raises MutabilityException. The read-only attributes of the model of the - resource are skipped, as RFC 7644 §3.5.1 has them ignored, and so are the - derived ones. - """ - _check_entry_values(mapping, resource) - _check_single_entries(mapping, resource) - model = type(resource) - for path in Path[model].iter_paths(): # type: ignore[valid-type] - binding = path.resolve() - if binding is None: - continue - - target = binding.target_type - if isclass(target) and issubclass(target, BaseModel): - continue - - if Mutability.read_only in ( - binding.model.get_field_annotation(binding.field_name, Mutability), - binding.get_annotation(Mutability), - ): - continue - - storage = mapping._storage(binding.urn) - value = _comparable(path.get(resource, strict=False)) - current = None - if stored is not None: - current = _comparable(Path(binding.urn).get(stored, strict=False)) - - if storage == _Storage.written: - _check_written(mapping, binding, value, current, stored is None) - continue - - if storage in ( - _Storage.derived, - _Storage.ref, - _Storage.link_type, - _Storage.constant, - ) or value in ( - None, - current, - ): - continue - - if storage == _Storage.read_only: - raise MutabilityException( - attribute=binding.urn, - mutability="readOnly", - detail=f"'{binding.urn}' is read-only on this server", - ) - - raise InvalidValueException( - detail=f"'{binding.urn}' is not stored by this server" - ) - - -def _check_written( - mapping: ResourceMapping, - binding: AttributeBinding, - value: Any, - current: Any, - creating: bool, -) -> None: - """Refuse a value of a written attribute that its field cannot store.""" - _check_enumerated(mapping, binding, value) - if value is not None: - return - - if creating and mapping._required(binding.urn): - raise InvalidValueException( - detail=f"'{binding.urn}' is required on this server" - ) - - if current is not None and not mapping._nullable(binding.urn): - raise MutabilityException( - attribute=binding.urn, - detail=f"'{binding.urn}' cannot be removed on this server", - ) - - -def _check_entry_values(mapping: ResourceMapping, resource: Resource[Any]) -> None: - """Refuse an entry without a value its field cannot do without.""" - for collection in mapping._all_collections(): - if not collection.owned or not collection.writable or collection.simple: - continue - - for entry in _entries(collection, resource): - for column in collection.columns.values(): - value = getattr(entry, column.binding.target_field_name, None) - if value is None and column.required: - raise InvalidValueException( - detail=f"'{column.binding.urn}' is required on this server" - ) - - -def _check_single_entries(mapping: ResourceMapping, resource: Resource[Any]) -> None: - """Refuse several entries for an Entry, or an entry with another type than its constant. - - Any primary value is accepted: the lone entry is the primary one. - """ - for entry in mapping._entries.values(): - entries = _values(entry.binding, resource) - if len(entries) > 1: - raise InvalidValueException( - detail=f"'{entry.binding.urn}' holds one entry at most on this server" - ) - - for item in entries: - for name, (constant, column) in entry.constants.items(): - if name == "primary": - continue - - value = _as_stored( - getattr(item, column.binding.target_field_name, None) - ) - if value is not None and value.casefold() != constant.casefold(): - raise InvalidValueException( - detail=f"'{column.binding.urn}' can only be {constant!r} " - "on this server" - ) - - -def _check_enumerated( - mapping: ResourceMapping, binding: AttributeBinding, value: Any -) -> None: - """Refuse a value that a field with choices does not store, rather than storing it anyway.""" - _, column = mapping._lookup(binding)[0] - if column is None or column.enumeration is None: - return - - stored = column.enumeration - for item in value if isinstance(value, list) else [value]: - if item is not None and item not in stored: - raise InvalidValueException( - detail=f"'{binding.urn}' cannot hold {item!r} on this server" - ) - - -def _comparable(value: Any) -> Any: - """Return a value in a form two resources compare in. - - A list of missing values, as a path through the entries of a multi-valued - attribute gives, is no value. - """ - if isinstance(value, list): - values = [_as_stored(item) for item in value] - return None if all(item is None for item in values) else values - - return _as_stored(value) diff --git a/src/scim2_django/storage/mapping.py b/src/scim2_django/storage/mapping.py index 3de041e..10dd293 100644 --- a/src/scim2_django/storage/mapping.py +++ b/src/scim2_django/storage/mapping.py @@ -1,27 +1,25 @@ -import operator +import base64 +import datetime import weakref from collections.abc import Callable from collections.abc import Generator from collections.abc import Iterable -from collections.abc import Iterator from collections.abc import Mapping from dataclasses import dataclass -from dataclasses import field as dataclass_field -from dataclasses import replace from enum import Enum -from functools import reduce -from inspect import isclass from typing import Any from django.apps import apps +from django.conf import settings from django.core import checks from django.core.exceptions import FieldDoesNotExist from django.core.exceptions import FieldError from django.core.exceptions import ImproperlyConfigured +from django.core.exceptions import ObjectDoesNotExist +from django.core.exceptions import ValidationError from django.db import DEFAULT_DB_ALIAS from django.db import models from django.db.models import CASCADE -from django.db.models import Case from django.db.models import Exists from django.db.models import F from django.db.models import ForeignObjectRel @@ -30,25 +28,21 @@ from django.db.models import Prefetch from django.db.models import Q from django.db.models import Value -from django.db.models import When from django.db.models.functions import Cast from django.db.models.functions import Concat from django.db.models.functions import NullIf from django.db.models.functions import Substr -from django.db.models.lookups import IsNull from django.urls import get_resolver -from pydantic import BaseModel -from scim2_models import Attribute as SchemaAttribute from scim2_models import AttributeBinding -from scim2_models import Extension from scim2_models import Mutability -from scim2_models import Path -from scim2_models import Required from scim2_models import Resource -from scim2_models import ResponseParameters -from scim2_models import Returned from scim2_models import Schema -from scim2_models import Uniqueness +from scim2_server import mapping as core +from scim2_server.mapping import MappingProblem +from scim2_server.mapping.declaration import key as _key +from scim2_server.mapping.declaration import mutabilities as _mutabilities +from scim2_server.mapping.declaration import never_returned as _never_returned +from scim2_server.mapping.mapping import Problems _MAPPINGS: "weakref.WeakSet[ResourceMapping]" = weakref.WeakSet() """The mappings created so far, which the system check validates.""" @@ -57,6 +51,15 @@ _UUID_PARTS = ((1, 8), (9, 4), (13, 4), (17, 4), (21, 12)) +_CHECK_IDS = { + "hidden-in-entries": "scim2_django.E007", + "read-only-in-entries": "scim2_django.E007", + "entry-fields": "scim2_django.E007", + "single-link-null": "scim2_django.E003", + "unwritten": "scim2_django.W002", +} +"""The identifiers of the system checks, by code of the problems of the mapping core.""" + class _UUIDText(Func): """The text of a UUID, with its dashes, as clients read it. @@ -85,27 +88,7 @@ def as_sql( # type: ignore[override] return compiler.compile(text.resolve_expression(compiler.query)) -class _Storage(Enum): - """How a mapping stores an attribute. - - A derived attribute is read from another resource, such as the display of - a member, so writing it changes nothing. A ref is the $ref of a link, - built from its value: clients may send it, and writing it changes nothing - either. A link type is the type a Link gives its entries: clients may send - it, and the storage checks it against the linked resource. A constant is a - sub-attribute an Entry gives its entry: clients may send it, and the - storage checks it against the constant. - """ - - written = "written" - read_only = "read only" - derived = "derived" - ref = "ref" - link_type = "link type" - constant = "constant" - - -class Attribute: +class Attribute(core.Attribute): """A field holding a SCIM attribute that the storage only reads. The storage reads every attribute, a write-only one included, such as a @@ -118,8 +101,12 @@ class Attribute: """ def __init__(self, field: str, *, writable: bool = True) -> None: - self.field = field - self.writable = writable + super().__init__(field, writable=writable) + + @property + def field(self) -> str: + """The name of the field holding the value.""" + return str(self.target) class Computed: @@ -185,7 +172,7 @@ def __init__( self.to_field = to_field -class Many: +class Many(core.Many): """The entries of a multi-valued attribute, stored in the records of another model. The entries belong to the resource: writing the resource replaces them. @@ -206,11 +193,10 @@ class Many: """ def __init__(self, relation: str, attributes: Mapping[str, Any] | Any) -> None: - self.relation = relation - self.attributes = attributes + super().__init__(relation, attributes) -class Entry: +class Entry(core.Entry): """A multi-valued complex attribute holding one entry at most, stored in fields of the resource model. Such as the email address of a user, in its ``email`` field. The @@ -229,22 +215,8 @@ class Entry: one back. Without it, the storage does not store ``primary``. """ - def __init__( - self, - attributes: Mapping[str, str | Attribute], - *, - type: str | None = None, - primary: bool | None = None, - ) -> None: - self.attributes = attributes - self.constants = { - name: value - for name, value in (("type", type), ("primary", primary)) - if value is not None - } - -class Link: +class Link(core.Link): """A complex attribute linking to other resources. A multi-valued attribute, such as the ``members`` of a group, maps to a @@ -276,23 +248,13 @@ class Link: Without it, the storage does not store ``type``. """ - def __init__( - self, relation: str, resource_type: str, *, type: str | None = None - ) -> None: - self.relation = relation - self.resource_type = resource_type - self.type = type - @dataclass(eq=False) -class _Column: +class _Column(core.Column): """A SCIM attribute stored in a field, or computed by an expression. key is the name of the field, or the alias the expression is annotated - under. textual tells whether filters compare the field as text, as they do - for an integer identifier. keyed tells whether filters find an - identifier by the value of its field, so that the database uses its - index. relation is the reverse one-to-one relation leading to the record + under. relation is the reverse one-to-one relation leading to the record holding the field, when the field is not one of the resource record, as in "scim__external_id". @@ -300,17 +262,11 @@ class _Column: written through to_field, under field_key. """ - binding: AttributeBinding - key: str - writable: bool field: "models.Field[Any, Any] | None" = None expression: Any = None - textual: bool = False relation: Any = None to_field: Callable[[Any], Any] | None = None path: str | None = None - keyed: bool = False - in_entry: bool = False @property def field_key(self) -> str: @@ -322,83 +278,6 @@ def transformed(self) -> bool: """Whether the field holds the values in another form than clients read and send.""" return self.path is not None - @property - def is_string(self) -> bool: - """Whether the attribute is a SCIM string. A binary value is not one.""" - target = self.binding.target_type - return ( - target is not None - and target is not bytes - and SchemaAttribute.Type.from_python(target) == SchemaAttribute.Type.string - ) - - @property - def concealed(self) -> bool: - """Whether clients never read the value: the server never returns it, as for a write-only value. - - Filters and sorts cannot compare it. - """ - return _never_returned(self.binding) or Mutability.write_only in _mutabilities( - self.binding - ) - - @property - def empty_string(self) -> bool: - """Whether the field holds an empty string for no value. - - Django text fields without null do so. A transformed field holds what - to_field gives for no value. - """ - return ( - self.is_string - and self.field is not None - and not self.field.null - and not self.transformed - ) - - @property - def nullable(self) -> bool: - """Whether the field can hold no value. - - An expression is taken as nullable, and so is a transformed field, - which holds what to_field gives for no value. - """ - return ( - self.field is None - or self.transformed - or bool(self.field.null) - or self.empty_string - ) - - @property - def required(self) -> bool: - """Whether a new record needs a value. - - It does when the field cannot be null, and gets no value from a default - or from Django, as a date with auto_now does. A field of a related - record needs none, as the related record may not exist. - """ - if self.field is None or self.nullable or self.relation is not None: - return False - - return _field_needs_value(self.field) - - @property - def enumeration(self) -> list[Any] | None: - """The values a field with choices stores, or None for a field without choices. - - A transformed field stores other values than clients send. - """ - if self.field is None or self.transformed or not self.field.choices: - return None - - return [value for value, _ in self.field.flatchoices] - - @property - def casefolded(self) -> bool: - """Whether the values compare without their case.""" - return self.is_string and not self.binding.case_exact - @property def compared(self) -> Any: """The expression filters and sorts compare. @@ -418,67 +297,55 @@ def compared(self) -> Any: return expression + def fill(self, in_record: bool) -> None: + """Fill the facts of the storage the mapping core reads, from the field. -@dataclass(eq=False) -class _Collection: - """A multi-valued attribute, or a complex one, stored in related records. + A text field without null holds an empty string for no value. An + expression is taken as nullable, and so is a transformed field, which + holds what to_field gives for no value. A field of a related record + needs no value, as the related record may not exist. A transformed + field stores other values than clients send. + """ + field = self.field + self.related = self.relation is not None + self.empty_string = ( + self.is_string + and field is not None + and not field.null + and not self.transformed + ) + self.nullable = ( + field is None or self.transformed or bool(field.null) or self.empty_string + ) + self.needs_value = field is not None and _field_needs_value(field) + self.fills_none = self.transformed + if field is not None and not self.transformed and field.choices: + self.enumeration = [value for value, _ in field.flatchoices] - The entries of an owned collection belong to the resource. The others are - links to the resources of another mapping, the target. A single collection - holds one entry at most, such as the manager of a user. A simple - collection holds the values of a multi-valued simple attribute, in the - column it keeps under None. + if in_record and field is not None and self.relation is None: + self.stores = field.name - link_type is the type a Link gives its entries, and type_column the - constant filters compare it as. - """ - binding: AttributeBinding - relation: "models.Field[Any, Any] | ForeignObjectRel" - columns: dict[str | None, _Column] = dataclass_field(default_factory=dict) - resource_type: str | None = None - target: "ResourceMapping | None" = None - link_type: str | None = None - type_column: _Column | None = None +@dataclass(eq=False) +class _Collection(core.Collection): + """A multi-valued attribute, or a complex one, stored in related records. - @property - def owned(self) -> bool: - """Whether the entries belong to the resource, rather than link to other resources.""" - return self.resource_type is None + relation is the Django relation from the resource model to the entries. + """ @property def entry_model(self) -> type[models.Model]: """The model of the entries.""" - model: type[models.Model] = self.relation.related_model # type: ignore[assignment] + model: type[models.Model] = self.relation.related_model return model - @property - def single(self) -> bool: - """Whether the collection holds one entry at most.""" - return not self.binding.is_multivalued - - @property - def simple(self) -> bool: - """Whether the collection holds the values of a multi-valued simple attribute.""" - return None in self.columns - @property def accessor(self) -> str: """The name of the attribute of a record holding the entries.""" if isinstance(self.relation, ForeignObjectRel): return str(self.relation.get_accessor_name()) - return self.relation.name - - def column(self, sub_field_name: str | None) -> _Column | None: - """Return the column of a sub-attribute, or of the values of a simple collection named alone. - - A complex collection named alone has no column. - """ - if sub_field_name == "type" and self.type_column is not None: - return self.type_column - - return self.columns.get(sub_field_name) + return str(self.relation.name) def entries(self) -> "models.QuerySet[Any]": """Return the entries of the record of the outer query.""" @@ -520,62 +387,17 @@ def order(self) -> list[Any]: def prefetch(self) -> "Prefetch[Any]": """Return how to load the entries along with the records, in the order they are read.""" entries = self.entry_model._default_manager.order_by(*self.order()) - if self.target is not None: - entries = entries.annotate(**self.target._annotations()) - related = self.target._related_names() + target: Any = self.target + if target is not None: + entries = entries.annotate(**target._annotations()) + related = target._related_names() if related: entries = entries.select_related(*related) return Prefetch(self.accessor, queryset=entries) - @property - def writable(self) -> bool: - """Whether writing the resource writes these entries. - - Entries of which no sub-attribute is written are left as they are. - """ - if self.owned and not any(column.writable for column in self.columns.values()): - return False - - mutability = self.binding.model.get_field_annotation( - self.binding.field_name, Mutability - ) - return bool(mutability != Mutability.read_only) - - -@dataclass(eq=False) -class _Entry: - """A multi-valued complex attribute holding one entry at most, in fields of the resource record. - - columns holds the columns of the mapped sub-attributes, and constants the - columns of the sub-attributes the entry always has, by sub-attribute - name. A constant column has no value when the entry does not exist. - """ - - binding: AttributeBinding - columns: dict[str, _Column] - constants: dict[str, tuple[Any, _Column]] - simple = False - - @property - def writable(self) -> bool: - """Whether writing the resource writes the entry: its fields are all written, or all read-only.""" - return any(column.writable for column in self.columns.values()) - - @property - def present(self) -> Q: - """The condition that the record has the entry: one of its sub-attributes has a value.""" - return reduce( - operator.or_, - (Q(IsNull(column.compared, False)) for column in self.columns.values()), - ) - - def exists(self, condition: Q) -> Q: - """Return the condition that the entry exists and matches condition.""" - return self.present & condition - -class ResourceMapping: +class ResourceMapping(core.ResourceMapping): """How the resources of a SCIM model are stored in the records of a Django model. The paths are checked against the SCIM model when the mapping is created, @@ -613,10 +435,18 @@ class ResourceMapping: value does not fit the attribute of its path. """ - _REQUIRED = ("id",) + configuration_error = ImproperlyConfigured + + record: type[models.Model] + _FIELDS = ("id", "meta.created", "meta.lastModified") """The attributes the storage fills itself, which a field holds as it is.""" + version: str | None + _id: _Column + _created: _Column | None + _last_modified: _Column | None + def __init__( self, model: type[Resource[Any]], @@ -625,32 +455,8 @@ def __init__( *, version: str | None = None, ) -> None: - self.model = model - self.record = record - self.version = version - self._declared: dict[str, tuple[AttributeBinding, Any]] = {} self._messages: list[checks.CheckMessage] | None = None - self._columns: dict[tuple[type[BaseModel], str, str | None], _Column] = {} - self._collections: dict[tuple[type[BaseModel], str], list[_Collection]] = {} - self._entries: dict[tuple[type[BaseModel], str], _Entry] = {} - - declared: dict[tuple[Any, ...], str] = {} - for path, value in attributes.items(): - binding = self._resolve(path) - key = _key(binding) - for other, other_path in declared.items(): - if _overlap(key, other): - raise ValueError( - f"{other_path!r} and {path!r} map the same attribute" - ) - - declared[key] = path - self._declare(path, binding, value) - - for required in self._REQUIRED: - if _key(self._resolve(required)) not in declared: - raise ValueError(f"The mapping of {model.__name__} needs {required!r}") - + super().__init__(model, record, attributes, version=version) _MAPPINGS.add(self) def __repr__(self) -> str: @@ -687,8 +493,7 @@ def schemas(self) -> list[Schema]: not fit its attribute. """ self._ready() - models_: list[Any] = [self.model, *self.model.get_extension_models().values()] - return [self._restrict(model.to_schema()) for model in models_] + return super().schemas() def check(self) -> list[checks.CheckMessage]: """Return the errors and the warnings of the fields of the mapping. @@ -697,14 +502,18 @@ def check(self) -> list[checks.CheckMessage]: """ apps.check_models_ready() if self._messages is None: - messages = list(self._resolve_fields()) - if not any(message.is_serious() for message in messages): - messages.extend(self._check_unwritten()) - - self._messages = messages + self._messages = [self._message(problem) for problem in self._resolve()] return self._messages + def _message(self, problem: MappingProblem) -> checks.CheckMessage: + """Return the system check message of a problem of the mapping.""" + id = _CHECK_IDS.get(problem.code, problem.code) + if problem.level == "warning": + return checks.Warning(problem.message, obj=self, id=id) + + 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()] @@ -713,329 +522,8 @@ def _ready(self) -> None: "\n".join(f"{self!r}: {error.msg}" for error in errors) ) - def _restrict(self, schema: Schema) -> Schema: - """Return a schema with the attributes the mapping stores only.""" - attributes = [] - for attribute in schema.attributes or []: - restricted = self._restrict_attribute( - f"{schema.id}:{attribute.name}", attribute - ) - if restricted is not None: - attributes.append(restricted) - - return schema.model_copy(update={"attributes": attributes}) - - def _restrict_attribute(self, urn: str, attribute: Any) -> Any: - """Return an attribute of a schema as the mapping stores it, or None when it stores nothing of it. - - An attribute never returned is optional, since clients cannot send - back a value they never read. - """ - if attribute.sub_attributes: - restricted = self._restrict_complex(urn, attribute) - else: - restricted = self._restrict_simple(urn, attribute) - - if restricted is None or not ( - restricted.returned == Returned.never - or restricted.mutability == Mutability.write_only - ): - return restricted - - return restricted.model_copy(update={"required": Required.false}) - - def _restrict_simple(self, urn: str, attribute: Any) -> Any: - """Return a simple attribute of a schema as the mapping stores it, or None when it stores nothing of it. - - A single attribute whose field needs a value is required. - """ - storage = self._storage(urn) - if storage is None: - return None - - if storage == _Storage.link_type: - return attribute - - if storage == _Storage.written: - if attribute.multi_valued or not self._needs_value(urn): - return attribute - - return attribute.model_copy(update={"required": Required.true}) - - if storage == _Storage.constant: - constant = self._constant_value(urn) - if not attribute.canonical_values: - return attribute - - return attribute.model_copy(update={"canonical_values": [constant]}) - - if storage == _Storage.ref: - linked = self._linked_resource_types(urn) - return attribute.model_copy(update={"reference_types": linked}) - - return attribute.model_copy(update={"mutability": Mutability.read_only}) - - def _restrict_complex(self, urn: str, attribute: Any) -> Any: - """Return a complex attribute with the sub-attributes the mapping stores, or None when it stores none. - - A single complex attribute is required when the field of one of its - sub-attributes needs a value, since the storage refuses a resource - without it. A complex attribute whose sub-attributes are all never - returned is never returned either. - """ - sub_attributes = [ - restricted - for sub_attribute in attribute.sub_attributes - if ( - restricted := self._restrict_attribute( - f"{urn}.{sub_attribute.name}", sub_attribute - ) - ) - is not None - ] - if not sub_attributes: - return None - - written = any( - sub_attribute.mutability != Mutability.read_only - for sub_attribute in sub_attributes - ) - update: dict[str, Any] = { - "sub_attributes": sub_attributes, - "mutability": attribute.mutability if written else Mutability.read_only, - } - if all( - sub_attribute.returned == Returned.never for sub_attribute in sub_attributes - ): - update["returned"] = Returned.never - if attribute.mutability == Mutability.read_write: - update["mutability"] = Mutability.write_only - - if not attribute.multi_valued and any( - self._needs_value(f"{urn}.{sub_attribute.name}") - for sub_attribute in sub_attributes - ): - update["required"] = Required.true - - return attribute.model_copy(update=update) - - def _storage(self, urn: str) -> _Storage | None: - """Return how the mapping stores the attribute of a URN, or None when it does not store it.""" - key = urn.lower() - for column in self._columns.values(): - if column.binding.urn.lower() == key: - return _column_storage(column) - - for collection in self._all_collections(): - if collection.owned: - for column in collection.columns.values(): - if column.binding.urn.lower() == key: - return _column_storage(column) - - continue - - head = collection.binding.urn.lower() - if key == f"{head}.value": - return _Storage.written - - if key in (f"{head}.display", f"{head}.displayname"): - return _Storage.derived - - if key == f"{head}.$ref": - return _Storage.ref - - if key == f"{head}.type" and collection.link_type is not None: - return _Storage.link_type - - for entry in self._entries.values(): - for _, column in entry.constants.values(): - if column.binding.urn.lower() != key: - continue - - if entry.writable: - return _Storage.constant - - return _Storage.read_only - - return None - - def _constant_value(self, urn: str) -> Any: - """Return the constant an Entry gives the sub-attribute of a URN.""" - key = urn.lower() - return next( - constant - for entry in self._entries.values() - for constant, column in entry.constants.values() - if column.binding.urn.lower() == key - ) - - def _linked_resource_types(self, urn: str) -> list[str]: - """Return the resource types the Links of an attribute link to, from the URN of its $ref.""" - head = urn.lower().removesuffix(".$ref") - return [ - collection.resource_type - for collection in self._all_collections() - if collection.binding.urn.lower() == head - and collection.resource_type is not None - ] - - def _all_collections(self) -> Iterator[_Collection]: - """Yield the collections of every attribute, each Link of an attribute being a collection.""" - for collections in self._collections.values(): - yield from collections - - def _column(self, path: str) -> _Column: - """Return the column of the attribute at a path.""" - return self._columns[_key(self._resolve(path))] - - def _lookup( - self, binding: AttributeBinding - ) -> list[tuple[_Collection | None, _Column | None]]: - """Return each collection holding an attribute, if any, with the column of the attribute in it. - - An attribute outside collections gives one pair, without collection. - An attribute linking to several resource types gives a pair for each - of its Links. The column is None for an attribute stored nowhere, and - for a collection named alone, such as emails. - """ - collections = self._collections.get((binding.model, binding.field_name)) - if collections is None: - return [(None, self._columns.get(_key(binding)) or self._constant(binding))] - - return [ - (collection, collection.column(binding.sub_field_name)) - for collection in collections - ] - - def _constant(self, binding: AttributeBinding) -> _Column | None: - """Return the column of a sub-attribute an Entry gives its entry, or None.""" - entry = self._entries.get((binding.model, binding.field_name)) - if entry is None or binding.sub_field_name not in entry.constants: - return None - - _, column = entry.constants[binding.sub_field_name] - return column - - def _nullable(self, urn: str) -> bool: - """Tell whether the field of an attribute can hold no value, True for an attribute without field.""" - key = urn.lower() - return all( - column.nullable - for column in self._columns.values() - if column.binding.urn.lower() == key - ) - - def _required(self, urn: str) -> bool: - """Tell whether a new record needs a value for the attribute of a URN.""" - return any(self._required_columns(urn)) - - def _needs_value(self, urn: str) -> bool: - """Tell whether clients must give a value for the attribute of a URN, in a resource or in an entry of a Many. - - An attribute never returned needs none, since clients never read it - back before a replacement. - """ - return any( - column.writable and not column.concealed - for column in self._required_columns(urn, entries=True) - ) - - def _required_columns( - self, urn: str, *, entries: bool = False - ) -> Iterator[_Column]: - """Yield the columns of the attribute of a URN that need a value in a new record. - - With entries, also yield those of the entries of a Many. - """ - key = urn.lower() - columns: Iterable[_Column] = self._columns.values() - if entries: - columns = [ - *columns, - *( - column - for collection in self._all_collections() - if collection.owned - for column in collection.columns.values() - ), - ] - - for column in columns: - if column.required and column.binding.urn.lower() == key: - yield column - - def _sub_columns(self, binding: AttributeBinding) -> list[_Column]: - """Return the mapped sub-attributes of a complex attribute holding a single value.""" - return [ - column - for (model, field_name, sub_field_name), column in self._columns.items() - if model is binding.model - and field_name == binding.field_name - and sub_field_name is not None - ] - - def _string_columns(self) -> Iterator[_Column]: - """Yield the columns holding strings, those of the collections included.""" - for column in self._columns.values(): - if column.is_string: - yield column - - for entry in self._entries.values(): - for _, column in entry.constants.values(): - if column.is_string: - yield column - - for collection in self._all_collections(): - for column in collection.columns.values(): - if column.is_string: - yield column - - if collection.type_column is not None: - yield collection.type_column - - def _unique_columns(self) -> Iterator[_Column]: - """Yield the written columns clients read, whose values no two resources share. - - A column never written, such as id, cannot get a value another - resource holds. A column hidden from clients is left out, so that an - error tells nothing about the values of other resources. A column of an - entry is left out, as a resource holds its values in a list. - """ - for column in self._columns.values(): - if column.concealed or not column.writable or column.in_entry: - continue - - if column.binding.get_annotation(Uniqueness) in ( - Uniqueness.server, - Uniqueness.global_, - ): - yield column - - def _returned_collections( - self, parameters: ResponseParameters[Any] | None = None - ) -> list[_Collection]: - """Return the collections a response keeps, all of them without parameters. - - Without a version field, the version is a hash of the whole resource, - so every collection is kept. - """ - collections = list(self._all_collections()) - if parameters is None or self.version is None: - return collections - - paths = Path[self.model].iter_paths( # type: ignore[name-defined] - include_subattributes=False, - attributes=parameters.attributes, - excluded_attributes=parameters.excluded_attributes, - ) - bindings = (path.resolve() for path in paths) - kept = {binding.urn for binding in bindings if binding is not None} - return [ - collection for collection in collections if collection.binding.urn in kept - ] - def _queryset( - self, collections: Iterable[_Collection], using: str = DEFAULT_DB_ALIAS + self, collections: Iterable[core.Collection], using: str = DEFAULT_DB_ALIAS ) -> "models.QuerySet[Any]": """Return the records of a database with their computed attributes, and the given collections loaded along.""" records = self.record._default_manager.using(using) @@ -1044,416 +532,146 @@ def _queryset( records = records.select_related(*related) return records.annotate(**self._annotations()).prefetch_related( - *(collection.prefetch() for collection in collections) + *(collection.prefetch() for collection in collections) # type: ignore[attr-defined] ) def _annotations(self) -> dict[str, Any]: """Return the expressions of the computed attributes, by the alias records hold them under.""" return { - column.key: column.expression + column.key: column.expression # type: ignore[attr-defined] for column in self._columns.values() - if column.expression is not None + if column.expression is not None # type: ignore[attr-defined] } def _targets( - self, mappings: Mapping[str, "ResourceMapping"] - ) -> list[tuple[_Collection, "ResourceMapping"]]: + self, mappings: Mapping[str, core.ResourceMapping] + ) -> list[tuple[core.Collection, core.ResourceMapping]]: """Return each Link with the mapping of the resources it links to. Several storages may share a mapping, as long as they link it to the same mappings. """ self._ready() - return [ - (collection, self._target(collection, mappings)) - for collection in self._all_collections() - if not collection.owned - ] - - def _bind(self, links: list[tuple[_Collection, "ResourceMapping"]]) -> None: - """Bind each Link to the mapping :meth:`_targets` returned for it. - - A storage gets the targets of every mapping before binding any, so - that a refused mapping binds nothing. - """ - for collection, target in links: - collection.target = target - collection.columns = {} - head = collection.binding.urn - for binding, column in ( - (self._resolve(f"{head}.value"), target._id), - ( - self._find(f"{head}.display") or self._find(f"{head}.displayName"), - target._display(), - ), - ): - if binding is None or column is None: - continue - - collection.columns[binding.sub_field_name] = replace( - column, binding=binding, writable=False - ) - - def _target( - self, collection: _Collection, mappings: Mapping[str, "ResourceMapping"] - ) -> "ResourceMapping": - """Return the mapping a Link links to, refusing one that does not fit it.""" - target = mappings.get(collection.resource_type) # type: ignore[arg-type] - if target is None: - raise ImproperlyConfigured( - f"No mapping for the resource type {collection.resource_type!r}" - ) - - target._ready() - if collection.target is not None and collection.target is not target: - raise ImproperlyConfigured( - f"{collection.binding.urn!r} already links to another mapping " - f"of {collection.resource_type!r}: a mapping serves storages " - "sharing the same mappings" - ) - - if collection.entry_model is not target.record: - raise ImproperlyConfigured( - f"{collection.binding.urn!r} links to " - f"{collection.entry_model._meta.label} records, but the mapping " - f"of {collection.resource_type!r} holds " - f"{target.record._meta.label} records" - ) + return super()._targets(mappings) - return target - - def _display(self) -> _Column | None: - """Return the column a link to these resources displays.""" - for path in ("displayName", "userName"): - binding = self._find(path) - if binding is None: - continue - - column = self._columns.get(_key(binding)) - if column is not None and not column.concealed: - return column - - return None + def _relations(self) -> list[Any]: + """Return the relations leading to the records holding mapped fields, by name.""" + relations = { + column.relation.name: column.relation # type: ignore[attr-defined] + for column in self._columns.values() + if column.relation is not None # type: ignore[attr-defined] + } + return [relations[name] for name in sorted(relations)] - def _find(self, path: str) -> AttributeBinding | None: - """Return the attribute at a path, or None if the model has none there.""" - return Path[self.model](path).resolve() # type: ignore[name-defined] + def _related_names(self) -> list[str]: + """Return the names select_related takes for the relations leading to the records holding mapped fields.""" + return [relation.name for relation in self._relations()] - def _resolve(self, path: str) -> AttributeBinding: - """Return the attribute at a path, refusing a path the model does not know.""" - binding = self._find(path) - if binding is None: - raise ValueError(f"{path!r} is not an attribute of {self.model.__name__}") + def _is_target(self, value: Any) -> bool: + return isinstance(value, str | Computed | Transformed) - return binding + def _value_writable(self, value: Any) -> bool: + if isinstance(value, Computed): + return False - def _declare(self, path: str, binding: AttributeBinding, value: Any) -> None: - """Check that the value of a path fits the SCIM attribute, and keep it until the fields are resolved.""" - target = binding.target_type - is_complex = isclass(target) and issubclass(target, BaseModel) + if isinstance(value, Transformed): + return value.to_field is not None - if isinstance(value, Many): - self._check_many(path, binding, value, is_complex) - self._declared[path] = (binding, value) - return + return super()._value_writable(value) - if isinstance(value, Entry): - self._check_entry(path, binding, value, is_complex) - self._declared[path] = (binding, value) - return + def _check_declared( + self, + path: str, + binding: AttributeBinding, + value: Any, + holder: core.Many | core.Entry | None, + ) -> None: + """Refuse a value Django cannot map where it is declared. - if isinstance(value, Link): - value = [value] + The entries of another model can be neither computed nor transformed. + An Entry maps fields of the resource model. The attributes the storage + fills itself map fields, but id may be transformed. Clients read the + value of a Transformed through its expression. + """ + if isinstance(holder, core.Many) and isinstance(value, Computed | Transformed): + raise ValueError( + f"{path!r} is held by the entries of another model, " + "which cannot be computed nor transformed" + ) - if isinstance(value, list) and all(isinstance(item, Link) for item in value): - if not is_complex or binding.sub_field_name is not None: + if isinstance(holder, core.Entry): + if not isinstance(value, str | Attribute): raise ValueError( - f"{path!r} is not a complex attribute of {self.model.__name__}" + f"{path!r} must be mapped to the name of a field, or an Attribute" ) - if not binding.is_multivalued and len(value) > 1: + field = value if isinstance(value, str) else value.field + if "__" in field: raise ValueError( - f"{path!r} holds one value, so it is mapped to one Link" + f"{path!r} is held by a field of the resource model, not of a " + "related model" ) - self._check_links(path, value) - self._declared[path] = (binding, value) + if holder is not None: return - if binding.is_multivalued or is_complex: - raise ValueError( - f"{path!r} holds several values or sub-attributes: map it with Many " - "or Link, or map its sub-attributes" - ) - - self._check_value(path, binding) - self._check_field_value(path, value) - if _key(binding) == _key(self._resolve("id")) and isinstance( - value, Transformed - ): + is_id = _key(binding) == _key(self._resolve_path("id")) + if is_id and isinstance(value, Transformed): if value.expression is None or value.to_field is None: raise ValueError( f"{path!r} is mapped to a Transformed, which needs an " "expression and to_field" ) - self._declared[path] = (binding, value) return - fields = {_key(self._resolve(path)) for path in self._FIELDS} + fields = {_key(self._resolve_path(path)) for path in self._FIELDS} if _key(binding) in fields and not isinstance(value, str): raise ValueError(f"{path!r} must be mapped to the name of a field") - self._check_read_and_written(path, binding, value) - self._declared[path] = (binding, value) - - def _check_read_and_written( - self, path: str, binding: AttributeBinding, value: Any - ) -> None: - """Refuse an attribute that clients could neither read nor write, or one they read that the storage would read as it is stored.""" - mutabilities = _mutabilities(binding) - read = Mutability.write_only not in mutabilities and not _never_returned( + read = Mutability.write_only not in _mutabilities( binding - ) + ) and not _never_returned(binding) if read and isinstance(value, Transformed) and value.expression is None: raise ValueError( f"Clients read {path!r}, so its Transformed needs an expression, " "unless its schema makes it write-only" ) - written = Mutability.read_only not in mutabilities and not ( - isinstance(value, Computed) - or (isinstance(value, Attribute) and not value.writable) - or (isinstance(value, Transformed) and value.to_field is None) - ) - if not (read or written): - raise ValueError(f"Clients could neither read nor write {path!r}") + def _error(self, message: str, id: str) -> MappingProblem: + """Return an error about the mapping, under the identifier of its system check.""" + return MappingProblem("error", id, message) - def _check_many( - self, path: str, binding: AttributeBinding, many: Many, is_complex: bool - ) -> None: - """Check that a Many fits a multi-valued attribute, and maps each sub-attribute once.""" - simple = not isinstance(many.attributes, Mapping) - if ( - binding.sub_field_name is not None - or not binding.is_multivalued - or is_complex == simple - ): - kind = "simple" if simple else "complex" - raise ValueError( - f"{path!r} is not a multi-valued {kind} attribute of " - f"{self.model.__name__}" - ) - - if simple: - self._check_entry_value(path, many.attributes) - return - - entries: dict[tuple[Any, ...], str] = {} - for sub_path, sub_value in many.attributes.items(): - sub_binding = self._resolve(f"{path}.{sub_path}") - if _key(sub_binding) in entries: - raise ValueError( - f"{entries[_key(sub_binding)]!r} and " - f"{f'{path}.{sub_path}'!r} map the same attribute" - ) - - entries[_key(sub_binding)] = f"{path}.{sub_path}" - self._check_value(f"{path}.{sub_path}", sub_binding) - self._check_entry_value(f"{path}.{sub_path}", sub_value) - - def _check_entry( - self, path: str, binding: AttributeBinding, entry: Entry, is_complex: bool - ) -> None: - """Check that an Entry fits a multi-valued complex attribute, maps fields of the record, and gives constants to sub-attributes it does not map.""" - if ( - binding.sub_field_name is not None - or not binding.is_multivalued - or not is_complex - ): - raise ValueError( - f"{path!r} is not a multi-valued complex attribute of " - f"{self.model.__name__}" - ) - - if not entry.attributes: - raise ValueError(f"The Entry of {path!r} maps no sub-attribute") - - mapped = set() - for sub_path, sub_value in entry.attributes.items(): - sub_binding = self._resolve(f"{path}.{sub_path}") - self._check_value(f"{path}.{sub_path}", sub_binding) - if not isinstance(sub_value, str | Attribute): - raise ValueError( - f"{f'{path}.{sub_path}'!r} must be mapped to the name of a " - "field, or an Attribute" - ) - - field = sub_value if isinstance(sub_value, str) else sub_value.field - if "__" in field: - raise ValueError( - f"{f'{path}.{sub_path}'!r} is held by a field of the resource " - "model, not of a related model" - ) - - mapped.add(_key(sub_binding)) - - for name in entry.constants: - given = self._find(f"{path}.{name}") - if given is None or _key(given) in mapped: - raise ValueError( - f"The Entry of {path!r} gives {name!r}, which is not a " - "sub-attribute it leaves unmapped" - ) - - def _check_entry_value(self, path: str, value: Any) -> None: - """Refuse a value of an entry that is not the name of a field, or an Attribute.""" - if isinstance(value, Computed | Transformed): - raise ValueError( - f"{path!r} is held by the entries of another model, " - "which cannot be computed nor transformed" - ) - - self._check_field_value(path, value) - - def _check_field_value(self, path: str, value: Any) -> None: - """Refuse a value that is not the name of a field, an Attribute, a Computed, or a Transformed.""" - if not isinstance(value, str | Attribute | Computed | Transformed): - raise ValueError( - f"{path!r} must be mapped to the name of a field, an Attribute, " - "a Computed, or a Transformed" - ) - - def _check_value(self, path: str, binding: AttributeBinding) -> None: - """Refuse a sub-attribute holding several values, which no field can hold.""" - if binding.sub_field_name is not None and binding.target_is_multivalued: - raise ValueError( - f"{path!r} holds several values in a complex attribute, " - "which the storage cannot map" - ) - - def _check_links(self, path: str, links: list[Link]) -> None: - """Check that the Links of an attribute link to distinct resource types, and give a type all or none.""" - resource_types = [link.resource_type for link in links] - if not links or len(set(resource_types)) != len(resource_types): - raise ValueError( - f"{path!r} needs one Link per resource type, and at least one" - ) - - typed = {link.type is not None for link in links} - if len(typed) > 1: - raise ValueError(f"Either every Link of {path!r} has a type, or none") - - if typed == {True} and self._find(f"{path}.type") is None: - raise ValueError(f"{path!r} has no type sub-attribute") - - def _resolve_fields(self) -> Iterator[checks.CheckMessage]: - """Resolve the field of each attribute, and yield what does not fit.""" - for path, (binding, value) in self._declared.items(): - key = (binding.model, binding.field_name) - if isinstance(value, Many): - collection = yield from self._many(path, binding, value) - if collection is not None: - self._collections[key] = [collection] - elif isinstance(value, Entry): - entry = yield from self._entry(path, binding, value) - if entry is not None: - self._entries[key] = entry - for entry_column in entry.columns.values(): - self._columns[_key(entry_column.binding)] = entry_column - elif isinstance(value, list): - collections = yield from self._links(path, binding, value) - if collections is not None: - self._collections[key] = collections - else: - column = yield from self._build_column( - self.record, path, binding, value - ) - if column is not None: - self._columns[(*key, binding.sub_field_name)] = column - - yield from self._check_version() - yield from self._check_related() - if not self._is_resolved(): - return - - self._id = self._column("id") - self._id.textual = not ( - self._id.transformed or isinstance(self._id.field, _TEXT_FIELDS) - ) - self._id.keyed = self._id.textual or self._id.transformed - self._created = self._columns.get(_key(self._resolve("meta.created"))) - self._last_modified = self._columns.get( - _key(self._resolve("meta.lastModified")) - ) - for path, column in ( - ("meta.created", self._created), - ("meta.lastModified", self._last_modified), - ): - if column is not None and not isinstance( - column.field, models.DateTimeField - ): - yield self._error( - f"{path!r} must be mapped to a date and time field", - "scim2_django.E006", - ) - - field = self._id.field - if field is None or not ( - field.primary_key or (field.unique and not field.null) - ): - yield self._error( - "'id' must be mapped to the primary key, or to a unique field " - "without null", - "scim2_django.E005", - ) - - def _is_resolved(self) -> bool: - """Tell whether every required attribute got a column.""" - return all( - _key(self._resolve(path)) in self._columns for path in self._REQUIRED - ) - - def _check_version(self) -> Iterator[checks.CheckMessage]: - """Refuse a version that is not an integer field of the record.""" - if self.version is None: - return - - field = yield from self._field(self.record, self.version, "version") - if field is not None and not isinstance(field, models.IntegerField): - yield self._error( - f"The version {self.version!r} must be an integer field", - "scim2_django.E004", - ) - - def _error(self, message: str, id: str) -> checks.Error: - """Return an error about the mapping.""" - return checks.Error(message, obj=self, id=id) + def _build_column( + self, + path: str, + binding: AttributeBinding, + value: Any, + owner: core.Collection | None, + ) -> Problems: + """Build the column of an attribute, in the resource record or in the entries of owner.""" + model = self.record if owner is None else owner.entry_model # type: ignore[attr-defined] + column = yield from self._value_column(model, path, binding, value) + if column is None: + return None - def _field( - self, model: type[models.Model], name: str, path: str - ) -> Generator[checks.CheckMessage, None, Any]: - """Return the field of a model, yielding an error when the model has none of that name.""" - try: - field: Any = model._meta.get_field(name) - except FieldDoesNotExist: - yield self._error( - f"{path!r} is mapped to {name!r}, which is not a field of " - f"{model._meta.label}", - "scim2_django.E001", + column.fill(in_record=owner is None) + if owner is None and _key(binding) == _key(self._resolve_path("id")): + column.textual = not ( + column.transformed or isinstance(column.field, _TEXT_FIELDS) ) - return None + column.keyed = column.textual or column.transformed - return field + return column - def _build_column( + def _value_column( self, model: type[models.Model], path: str, binding: AttributeBinding, value: Any, - ) -> Generator[checks.CheckMessage, None, _Column | None]: - """Build the column of an attribute, and decide whether it is written. + ) -> Generator[MappingProblem, None, _Column | None]: + """Build the column of a declared value, and decide whether it is written. A read-only attribute, a generated field and a computed expression are never written. @@ -1487,7 +705,7 @@ def _build_column( return None field: Any = column.field - if not column.is_string or _key(binding) == _key(self._resolve("id")): + if not column.is_string or _key(binding) == _key(self._resolve_path("id")): return column if not _holds_text(field): @@ -1495,16 +713,32 @@ def _build_column( return None if not column.concealed and _converts(field): - yield checks.Warning( + yield MappingProblem( + "warning", + "scim2_django.W001", f"{path!r} is mapped to {attribute.field!r}, whose field converts " "the values it reads: filters and sorts compare the stored values, " "not the values clients read", - obj=self, - id="scim2_django.W001", ) return column + def _field( + self, model: type[models.Model], name: str, path: str + ) -> Generator[MappingProblem, None, Any]: + """Return the field of a model, yielding an error when the model has none of that name.""" + try: + field: Any = model._meta.get_field(name) + except FieldDoesNotExist: + yield self._error( + f"{path!r} is mapped to {name!r}, which is not a field of " + f"{model._meta.label}", + "scim2_django.E001", + ) + return None + + return field + def _field_column( self, model: type[models.Model], @@ -1512,7 +746,7 @@ def _field_column( binding: AttributeBinding, name: str, writable: bool, - ) -> Generator[checks.CheckMessage, None, _Column | None]: + ) -> Generator[MappingProblem, None, _Column | None]: """Build the column of a field, of the record or of a record related by a reverse one-to-one relation. A generated field is never written. @@ -1551,7 +785,7 @@ def _field_column( binding, name, writable and not field.generated, - field, + field=field, relation=relation, ) @@ -1562,7 +796,7 @@ def _transformed( binding: AttributeBinding, transformed: Transformed, writable: bool, - ) -> Generator[checks.CheckMessage, None, _Column | None]: + ) -> Generator[MappingProblem, None, _Column | None]: """Build the column of a transformed field, read through its expression and written through to_field. Without expression, the field is read as it is stored. @@ -1601,7 +835,7 @@ def _transformed( def _relation( self, model: type[models.Model], path: str, binding: AttributeBinding, name: str - ) -> Generator[checks.CheckMessage, None, Any]: + ) -> Generator[MappingProblem, None, Any]: """Return the reverse one-to-one relation a field name leads through, yielding an error for any other path. Only a field of the resource record leads through a relation, and only @@ -1609,7 +843,7 @@ def _relation( """ relation_name, _, field_name = name.partition("__") relation = None - if model is self.record and _key(binding) != _key(self._resolve("id")): + if model is self.record and _key(binding) != _key(self._resolve_path("id")): relation = yield from self._field(model, relation_name, path) if relation is None: return None @@ -1629,122 +863,7 @@ def _relation( return relation - def _check_related(self) -> Iterator[checks.CheckMessage]: - """Refuse a related model that the storage cannot create from the mapped fields only.""" - mapped: dict[Any, set[str]] = {} - for column in self._columns.values(): - if column.relation is not None: - mapped.setdefault(column.relation, set()).add(column.field.name) # type: ignore[union-attr] - - for relation, names in mapped.items(): - for field in relation.related_model._meta.concrete_fields: - if field is relation.field or field.name in names: - continue - - # Django gives an empty string to a text field without value. - if _field_needs_value(field) and not field.empty_strings_allowed: - yield self._error( - f"{relation.get_accessor_name()!r} leads to " - f"{relation.related_model._meta.label} records, whose " - f"field {field.name!r} needs a value: map it, or give it " - "a default", - "scim2_django.E010", - ) - - yield from self._check_dated() - - def _check_dated(self) -> Iterator[checks.CheckMessage]: - """Refuse a related model holding a date and a mapped field that needs a value. - - The storage writes the dates on each write, so each write creates the - related record, even when the client gives no value for that field. - """ - dates = {_key(self._resolve(path)) for path in self._FIELDS} - dated = { - column.relation - for column in self._columns.values() - if column.relation is not None and _key(column.binding) in dates - } - for column in self._columns.values(): - if column.relation not in dated or _key(column.binding) in dates: - continue - - if not column.nullable and _field_needs_value(column.field): # type: ignore[arg-type] - yield self._error( - f"{column.relation.get_accessor_name()!r} leads to records " - "holding dates, which each write creates, so the field of " - f"{column.binding.urn!r} needs null or a default", - "scim2_django.E010", - ) - - def _check_unwritten(self) -> Iterator[checks.CheckMessage]: - """Warn about a field of the resource record that needs a value the storage never writes. - - Django gives an empty string to a text field without value, unless - it is unique: a second record could not hold it. The parent link of an - inherited model is set when the parent is saved. - """ - dates = {self._created, self._last_modified} - written = { - column.field.name - for column in self._columns.values() - if column.field is not None - and column.relation is None - and (column.writable or column in dates) - } - written.update( - collection.relation.name - for collection in self._all_collections() - if collection.single and not collection.owned and collection.writable - ) - for field in self.record._meta.concrete_fields: - if ( - field.name in written - or not _field_needs_value(field) - or (field.empty_strings_allowed and not field.unique) - or (field.remote_field is not None and field.remote_field.parent_link) - ): - continue - - advice = ( - "the storage counts the writes from it, but never sets it on " - "creation: give it a default" - if field.name == self.version - else "the storage never writes it, so creating a resource " - "fails: map it, or give it a default" - ) - yield checks.Warning( - f"The field {field.name!r} of {self.record._meta.label} needs a " - f"value, but {advice}", - obj=self, - id="scim2_django.W002", - ) - - def _always_held(self, binding: AttributeBinding) -> bool: - """Tell whether every resource holds an attribute: it is required, and so is its extension.""" - if not _required(binding): - return False - - if not issubclass(binding.model, Extension): - return True - - annotation = self.model.get_field_annotation(binding.model.__name__, Required) - return bool(annotation == Required.true) - - def _relations(self) -> list[Any]: - """Return the relations leading to the records holding mapped fields, by name.""" - relations = { - column.relation.name: column.relation - for column in self._columns.values() - if column.relation is not None - } - return [relations[name] for name in sorted(relations)] - - def _related_names(self) -> list[str]: - """Return the names select_related takes for the relations leading to the records holding mapped fields.""" - return [relation.name for relation in self._relations()] - - def _not_text(self, path: str, holder: str) -> checks.Error: + def _not_text(self, path: str, holder: str) -> MappingProblem: """Return the error of a string attribute held by something else than text.""" return self._error( f"{path!r} is a string, but {holder} does not hold text: " @@ -1754,7 +873,7 @@ def _not_text(self, path: str, holder: str) -> checks.Error: def _output_field( self, path: str, alias: str, expression: Any - ) -> Generator[checks.CheckMessage, None, Any]: + ) -> Generator[MappingProblem, None, Any]: """Return the field an expression gives, yielding an error when the model cannot compute it.""" try: query = self.record._default_manager.annotate(**{alias: expression}).query @@ -1765,242 +884,231 @@ def _output_field( ) return None - def _many( - self, path: str, binding: AttributeBinding, many: Many - ) -> Generator[checks.CheckMessage, None, _Collection | None]: - """Build the collection of a Many, with the columns of its entries, or the column of its values.""" - relation = yield from self._field(self.record, many.relation, path) + def _build_collection( + self, + path: str, + binding: AttributeBinding, + declaration: core.Many | core.Link, + ) -> Problems: + """Build the collection of a Many or of a Link, on the relation it names.""" + relation = yield from self._field(self.record, declaration.relation, path) if relation is None: return None - if not (relation.one_to_many and isinstance(relation, ForeignObjectRel)): - yield self._error( - f"{path!r} needs a reverse relation from a foreign key, " - f"but {many.relation!r} is not one", - "scim2_django.E003", - ) - return None - - if relation.on_delete is not CASCADE or relation.field.null: - yield self._error( - f"The foreign key of {path!r} needs on_delete=CASCADE, " - "and cannot be null", - "scim2_django.E003", - ) - return None + if isinstance(declaration, core.Many): + if not (relation.one_to_many and isinstance(relation, ForeignObjectRel)): + yield self._error( + f"{path!r} needs a reverse relation from a foreign key, " + f"but {declaration.relation!r} is not one", + "scim2_django.E003", + ) + return None - collection = _Collection(binding, relation) - entry_model = collection.entry_model - if not isinstance(many.attributes, Mapping): - column = yield from self._build_column( - entry_model, path, binding, many.attributes - ) - if column is None: + if relation.on_delete is not CASCADE or relation.field.null: + yield self._error( + f"The foreign key of {path!r} needs on_delete=CASCADE, " + "and cannot be null", + "scim2_django.E003", + ) return None - collection.columns[None] = column - yield from self._check_entries(path, collection) - return collection + return _Collection(binding, relation) - for sub_path, name in many.attributes.items(): - sub_binding = self._resolve(f"{path}.{sub_path}") - column = yield from self._build_column( - entry_model, f"{path}.{sub_path}", sub_binding, name - ) - if column is None: + if binding.is_multivalued: + if not relation.many_to_many: + yield self._link_error(path, declaration, "several entries") return None - collection.columns[sub_binding.sub_field_name] = column - - yield from self._check_entries(path, collection) - return collection + return _Collection(binding, relation) - def _entry( - self, path: str, binding: AttributeBinding, entry: Entry - ) -> Generator[checks.CheckMessage, None, _Entry | None]: - """Build the columns of an Entry: those of its fields, and those of its constants. + if not ((relation.many_to_one or relation.one_to_one) and relation.concrete): + yield self._link_error(path, declaration, "one entry") + return None - A constant has a value when the entry exists only. - """ - columns: dict[str, _Column] = {} - for sub_path, value in entry.attributes.items(): - sub_binding = self._resolve(f"{path}.{sub_path}") - column = yield from self._build_column( - self.record, f"{path}.{sub_path}", sub_binding, value - ) - if column is None: - return None + return _Collection( + binding, relation, nullable=bool(relation.null), stores=relation.name + ) - columns[sub_binding.sub_field_name] = column # type: ignore[index] + def _link_error(self, path: str, link: core.Link, holds: str) -> MappingProblem: + """Return the error of a Link whose relation does not fit the number of entries of its attribute.""" + expected = ( + "a foreign key or a one-to-one field" + if holds == "one entry" + else "a many-to-many relation" + ) + return self._error( + f"{path!r} holds {holds}, so it needs {expected}, but " + f"{link.relation!r} is not one", + "scim2_django.E003", + ) - for column in columns.values(): - column.in_entry = True + def _check_record(self) -> Problems: + """Check the version, the related records, the dates and the identifier.""" + yield from self._check_version() + yield from self._check_related() + for path, column in ( + ("meta.created", self._created), + ("meta.lastModified", self._last_modified), + ): + if column is not None and not isinstance( + column.field, models.DateTimeField + ): + yield self._error( + f"{path!r} must be mapped to a date and time field", + "scim2_django.E006", + ) - values = columns.values() - if any(column.concealed or not column.nullable for column in values): + field = self._id.field + if field is None or not ( + field.primary_key or (field.unique and not field.null) + ): yield self._error( - f"The entry of {path!r} exists when one of its fields has a " - "value, and a write removing it empties them, so they cannot " - "be hidden from clients nor without null", - "scim2_django.E007", + "'id' must be mapped to the primary key, or to a unique field " + "without null", + "scim2_django.E005", ) - return None - writable = [column.writable for column in values] - if any(writable) and not all(writable): + 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: + return + + field = yield from self._field(self.record, self.version, "version") + if field is None: + return + + if not isinstance(field, models.IntegerField): yield self._error( - f"A write removing the entry of {path!r} empties its fields, so " - "they cannot hold a read-only value next to written ones", - "scim2_django.E007", + f"The version {self.version!r} must be an integer field", + "scim2_django.E004", ) - return None + return - result = _Entry(binding, columns, {}) - for name, constant in entry.constants.items(): - sub_binding = self._resolve(f"{path}.{name}") - expression = Case( - When(result.present, then=Value(constant)), - default=Value(None), - output_field=( - models.BooleanField() - if isinstance(constant, bool) - else models.TextField() - ), - ) - result.constants[name] = ( - constant, - _Column(sub_binding, name, False, expression=expression), + if _field_needs_value(field): + yield MappingProblem( + "warning", + "scim2_django.W002", + f"The field {field.name!r} needs a value, but the storage counts " + "the writes from it, and never sets it on creation: give it a " + "default", ) - return result + def _check_related(self) -> Problems: + """Refuse a related model that the storage cannot create from the mapped fields only.""" + mapped: dict[Any, set[str]] = {} + for column in self._columns.values(): + if column.relation is not None: # type: ignore[attr-defined] + mapped.setdefault(column.relation, set()).add(column.field.name) # type: ignore[attr-defined] - def _check_entries( - self, path: str, collection: _Collection - ) -> Iterator[checks.CheckMessage]: - """Refuse entries that a write would partly lose. + for relation, names in mapped.items(): + for field in relation.related_model._meta.concrete_fields: + if field is relation.field or field.name in names: + continue - A write replaces the entries, so the values a client never sends back - would be lost: those of a sub-attribute hidden from clients, and those - of a read-only one next to written ones. A PATCH adding entries would lose - the write-only ones, since the server patches the resource it read. - """ - columns = collection.columns.values() - if any(column.concealed for column in columns): - yield self._error( - f"The entries of {path!r} are replaced on each write, " - "so they cannot hold values hidden from clients", - "scim2_django.E007", - ) - elif collection.writable and not all(column.writable for column in columns): - yield self._error( - f"The entries of {path!r} are replaced on each write, " - "so they cannot hold a read-only value next to written ones", - "scim2_django.E007", - ) + # Django gives an empty string to a text field without value. + if _field_needs_value(field) and not field.empty_strings_allowed: + yield self._error( + f"{relation.get_accessor_name()!r} leads to " + f"{relation.related_model._meta.label} records, whose " + f"field {field.name!r} needs a value: map it, or give it " + "a default", + "scim2_django.E010", + ) - def _links( - self, path: str, binding: AttributeBinding, links: list[Link] - ) -> Generator[checks.CheckMessage, None, list[_Collection] | None]: - """Build the collections of the Links of an attribute, one per resource type. + yield from self._check_dated() - The type of the entries is compared, in filters, as a constant of each - Link. - """ - collections: list[_Collection] = [] - for link in links: - relation = yield from self._field(self.record, link.relation, path) - if relation is None: - return None + def _check_dated(self) -> Problems: + """Refuse a related model holding a date and a mapped field that needs a value. - collection = _Collection(binding, relation) - fits = relation.many_to_many - if collection.single: - fits = ( - relation.many_to_one or relation.one_to_one - ) and relation.concrete - - if not fits: - expected = ( - "a foreign key or a one-to-one field" - if collection.single - else "a many-to-many relation" - ) - yield self._error( - f"{path!r} holds {'one entry' if collection.single else 'several entries'}, " - f"so it needs {expected}, but {link.relation!r} is not one", - "scim2_django.E003", - ) - return None + The storage writes the dates on each write, so each write creates the + related record, even when the client gives no value for that field. + """ + dates = {_key(self._resolve_path(path)) for path in self._FIELDS} + dated = { + column.relation # type: ignore[attr-defined] + for column in self._columns.values() + if column.relation is not None and _key(column.binding) in dates # type: ignore[attr-defined] + } + for column in self._columns.values(): + if column.relation not in dated or _key(column.binding) in dates: # type: ignore[attr-defined] + continue - if ( - collection.single - and not relation.null - and not self._always_held(binding) - ): + if not column.nullable and column.needs_value: yield self._error( - f"{path!r} can be removed, or left out with its extension, " - f"so {link.relation!r} needs null=True", - "scim2_django.E003", + f"{column.relation.get_accessor_name()!r} leads to records " # type: ignore[attr-defined] + "holding dates, which each write creates, so the field of " + f"{column.binding.urn!r} needs null or a default", + "scim2_django.E010", ) - return None - collection.resource_type = link.resource_type - if link.type is not None: - collection.link_type = link.type - collection.type_column = _Column( - self._resolve(f"{path}.type"), - "type", - False, - expression=models.Value(link.type), - ) + def _fields_needing_value(self) -> Iterable[str]: + """Return the fields of the record a new record needs a value for, but the version. - collections.append(collection) + Django gives an empty string to a text field without value, unless + it is unique: a second record could not hold it. The parent link of an + inherited model is set when the parent is saved. + """ + return [ + field.name + for field in self.record._meta.concrete_fields + if _field_needs_value(field) + and not (field.empty_strings_allowed and not field.unique) + and not (field.remote_field is not None and field.remote_field.parent_link) + and field.name != self.version + ] - return collections + def _links_to(self, collection: core.Collection, target: Any) -> bool: + target._ready() + return bool(collection.entry_model is target.record) # type: ignore[attr-defined] + def _read(self, column: core.Column, record: Any) -> Any: + """Return the SCIM value of a column of a record. -def _alias(binding: AttributeBinding) -> str: - """Return the alias records hold the value of an expression under.""" - return "scim_" + binding.urn.replace(":", "_").replace(".", "_") + An empty string is no value, as Django text fields store it. + """ + value = _get(column, record) # type: ignore[arg-type] + if value is None or (value == "" and column.empty_string): + return None + return _as_scim(value) -def _key(binding: AttributeBinding) -> tuple[Any, ...]: - """Return what tells an attribute apart, whatever the case of its path.""" - return (binding.model, binding.field_name, binding.sub_field_name) + def _related(self, collection: core.Collection, record: Any) -> list[Any]: + """Return the records a collection of a record holds, as a list even for a single one. + Without an ordering of their model, the records come in the order of + their primary key. + """ + related = getattr(record, collection.accessor) # type: ignore[attr-defined] + if collection.single: + return [] if related is None else [related] -def _overlap(key: tuple[Any, ...], other: tuple[Any, ...]) -> bool: - """Tell whether two attributes are the same, or one holds the other.""" - return key == other or (key[:2] == other[:2] and None in (key[2], other[2])) + records = related.all() + if not records.ordered: + records = records.order_by("pk") + return list(records) -def _mutabilities(binding: AttributeBinding) -> set[Mutability | None]: - """Return the mutabilities an attribute is annotated with, on its own or through its parent.""" - return { - binding.model.get_field_annotation(binding.field_name, Mutability), - binding.get_annotation(Mutability), - } + def _counter(self, record: Any) -> Any: + return getattr(record, self.version) # type: ignore[arg-type] + def _as_stored(self, value: Any) -> Any: + return _as_stored(value) -def _column_storage(column: _Column) -> _Storage: - """Return how a column stores its attribute: read and written, or only read.""" - return _Storage.written if column.writable else _Storage.read_only + def _holds_id(self, record: Any, value: str) -> bool: + """Tell whether a record has an identifier. + A record holds the expression of a transformed identifier, which gives + the identifier clients read. + """ + if self._id.transformed: + return bool(getattr(record, self._id.key) == value) -def _never_returned(binding: AttributeBinding) -> bool: - """Tell whether an attribute is never returned to clients, on its own or through its parent.""" - return Returned.never in ( - binding.model.get_field_annotation(binding.field_name, Returned), - binding.get_annotation(Returned), - ) + return bool(getattr(record, self._id.key) == _exact_key(self._id, value)) -def _required(binding: AttributeBinding) -> bool: - """Tell whether an attribute is required where it is defined, in the resource or in its extension.""" - return Required.true in ( - binding.model.get_field_annotation(binding.field_name, Required), - binding.get_annotation(Required), - ) +def _alias(binding: AttributeBinding) -> str: + """Return the alias records hold the value of an expression under.""" + return "scim_" + binding.urn.replace(":", "_").replace(".", "_") def _field_needs_value(field: "models.Field[Any, Any]") -> bool: @@ -2038,6 +1146,89 @@ def _converts(field: "models.Field[Any, Any]") -> bool: return hasattr(field, "from_db_value") +def _as_scim(value: Any) -> Any: + """Return a value read from the database in the form SCIM holds it. + + A date without a time zone is in UTC: the storage writes it so when USE_TZ + is off. Binary values are encoded in base64, as the models expect them. + """ + if isinstance(value, datetime.datetime) and value.tzinfo is None: + return value.replace(tzinfo=datetime.UTC) + + if isinstance(value, memoryview): + value = bytes(value) + + if isinstance(value, bytes): + return base64.b64encode(value).decode() + + return value + + +def _as_stored(value: Any) -> Any: + """Return a SCIM value in the form a field holds it. + + Dates are in UTC, without a time zone when USE_TZ is off, since Django + refuses aware dates then. + """ + if isinstance(value, Enum): + return value.value + + if isinstance(value, datetime.datetime) and value.tzinfo is not None: + value = value.astimezone(datetime.UTC) + return value if settings.USE_TZ else value.replace(tzinfo=None) + + return value + + +def _get(column: _Column, record: Any) -> Any: + """Return the value a record holds for a column, None when the related record holding it does not exist. + + The record holds the value of an expression itself, even when the + expression reads a related record. + """ + if column.relation is None or column.expression is not None: + return getattr(record, column.key) + + related = _related_record(column, record) + return None if related is None else getattr(related, column.field.name) # type: ignore[union-attr] + + +def _related_record(column: _Column, record: Any) -> Any: + """Return the related record holding the field of a column, or None when it does not exist.""" + try: + return getattr(record, column.relation.get_accessor_name()) + except ObjectDoesNotExist: + return None + + +def _as_key(column: _Column, value: Any) -> Any: + """Return an identifier in the type of its field, or None when the field cannot hold it. + + A transformed identifier is converted by to_field first. + """ + try: + if column.to_field is not None: + value = column.to_field(value) + + return column.field.to_python(value) # type: ignore[union-attr] + except (TypeError, ValueError, ValidationError): + return None + + +def _exact_key(column: _Column, value: str) -> Any: + """Return an identifier in the type of its field, or None when the field holds no such identifier. + + The field holds it only when it gives back the same text, so "01" does not + find the identifier 1. The expression of a transformed identifier tells + it in the database instead. + """ + key = _as_key(column, value) + if column.transformed or key is None or str(key) == value: + return key + + return None + + def check_mappings(**kwargs: Any) -> list[checks.CheckMessage]: """Check the fields of every mapping, once the URLconf has created them.""" _load_urlconf() diff --git a/src/scim2_django/storage/query.py b/src/scim2_django/storage/query.py index bcedbdb..49e8e67 100644 --- a/src/scim2_django/storage/query.py +++ b/src/scim2_django/storage/query.py @@ -10,11 +10,13 @@ from django.db import DEFAULT_DB_ALIAS from django.db import models from django.db.models import BooleanField +from django.db.models import Case from django.db.models import ExpressionWrapper from django.db.models import IntegerField from django.db.models import Q from django.db.models import Subquery from django.db.models import Value +from django.db.models import When from django.db.models.functions import Cast from django.db.models.lookups import Exact from django.db.models.lookups import GreaterThan @@ -23,33 +25,27 @@ from django.db.models.lookups import IsNull from django.db.models.lookups import LessThan from django.db.models.lookups import LessThanOrEqual -from scim2_models import AttributeBinding from scim2_models import InvalidCursorException -from scim2_models import InvalidFilterException from scim2_models import InvalidPathException -from scim2_models import ScimFilter from scim2_models import SearchRequest -from scim2_models.path import AttrPath from scim2_models.path import CompareOperator -from scim2_models.path import Comparison -from scim2_models.path import FilterVisitor -from scim2_models.path import LogicalExpr -from scim2_models.path import LogicalOperator -from scim2_models.path import Not -from scim2_models.path import Present -from scim2_models.path import ValuePath -from scim2_models.path import coerce_value from scim2_server.keyset import Position +from scim2_server.mapping import Collection +from scim2_server.mapping import Column +from scim2_server.mapping.filters import entry_present +from scim2_server.mapping.filters import sort_target +from scim2_server.mapping.filters import where from .comparison import _SUBSTRINGS from .comparison import _Comparator -from .conversion import _as_stored from .keyset import _beyond from .keyset import _keyset_order from .mapping import ResourceMapping +from .mapping import _as_key +from .mapping import _as_stored from .mapping import _Collection from .mapping import _Column -from .mapping import _Entry +from .mapping import _exact_key _ORDERINGS: dict[CompareOperator, Callable[[Any, Any], Any]] = { CompareOperator.eq: Exact, @@ -90,34 +86,6 @@ _FALSE = Q(Value(False, output_field=BooleanField())) -def _as_key(column: _Column, value: Any) -> Any: - """Return an identifier in the type of its field, or None when the field cannot hold it. - - A transformed identifier is converted by to_field first. - """ - try: - if column.to_field is not None: - value = column.to_field(value) - - return column.field.to_python(value) # type: ignore[union-attr] - except (TypeError, ValueError, ValidationError): - return None - - -def _exact_key(column: _Column, value: str) -> Any: - """Return an identifier in the type of its field, or None when the field holds no such identifier. - - The field holds it only when it gives back the same text, so "01" does not - find the identifier 1. The expression of a transformed identifier tells - it in the database instead. - """ - key = _as_key(column, value) - if column.transformed or key is None or str(key) == value: - return key - - return None - - def _with_ids( column: _Column, values: Iterable[str | None], comparator: _Comparator ) -> Q: @@ -142,11 +110,6 @@ def _with_ids( return condition -def _unmapped(binding: AttributeBinding) -> InvalidFilterException: - """Return the error of a filter on an attribute the mapping does not let filters read.""" - return InvalidFilterException(detail=f"Cannot filter on '{binding.urn}'") - - def _is_null(expression: Any) -> Q: return Q(IsNull(expression, True)) @@ -155,297 +118,100 @@ def _is_not_null(expression: Any) -> Q: return Q(IsNull(expression, False)) -class _FilterTranslator(FilterVisitor[Q]): - """Turn a SCIM filter into a condition on the records of a mapping. +class _Predicates: + """The conditions of the mapping core, as Django Q objects. - The condition keeps the records whose resources ScimFilter.match keeps. Every condition is true or false, never NULL, so that the negation of a comparison with a missing value holds. Django only ensures it for the - comparisons of a field, not of an expression. - - scope is the collection, or the Entry, that a value selection, such as - emails[type eq "work"], applies its filter to. + comparisons of a field, not of an expression. The conditions on entries + refer to the record of the outer query, which Django resolves when the + subquery is built. """ - def __init__( - self, - mapping: ResourceMapping, - scim_filter: ScimFilter[Any], - comparator: _Comparator, - scope: tuple[AttrPath, "_Collection | _Entry"] | None = None, - ) -> None: - self.mapping = mapping - self.filter = scim_filter + def __init__(self, comparator: _Comparator) -> None: self.comparator = comparator - self.scope = scope - def _resolve( - self, - attr_path: AttrPath, - resolve: Callable[..., AttributeBinding | None], - ) -> AttributeBinding | None: - """Bind the attribute path of a comparison or of a presence test. - - Within a value selection of a simple attribute, such as - tags[value eq "x"], value is the entry itself, and any other attribute - matches nothing, as ScimFilter.match has it. - """ - if self.scope is None: - return resolve(attr_path, strict=False) - - scope_path, scope = self.scope - if scope.simple: - own = attr_path.attr.lower() == "value" and not attr_path.sub_attr - return scope.binding if own else None - - return resolve( - AttrPath(scope_path.attr, attr_path.attr, scope_path.uri), strict=False - ) + def true(self) -> Q: + return _TRUE - def _lookup( - self, binding: AttributeBinding - ) -> list[tuple[_Collection | None, _Column | None]]: - """Return the collections holding an attribute, with its column in each, as the mapping does. + def false(self) -> Q: + return _FALSE - Within a value selection, only the collection of the selection holds - the attribute. - """ - pairs = self.mapping._lookup(binding) - if self.scope is None: - return pairs + def any(self, conditions: Iterable[Q]) -> Q: + return reduce(operator.or_, conditions, _FALSE) - _, scope = self.scope - if isinstance(scope, _Entry): - return pairs + def all(self, conditions: Iterable[Q]) -> Q: + return reduce(operator.and_, conditions, _TRUE) - return [ - (collection, column) for collection, column in pairs if collection is scope - ] + def negate(self, condition: Q) -> Q: + return ~condition - def _targets( - self, binding: AttributeBinding - ) -> list[tuple[_Collection | None, _Column]]: - """Return the collections holding an attribute with its column in each, refusing an attribute that one of them does not let filters read.""" - pairs = self._lookup(binding) - if any(column is None or column.concealed for _, column in pairs): - raise _unmapped(binding) + def is_null(self, column: Column) -> Q: + return _is_null(_django(column).compared) - return pairs # type: ignore[return-value] + def is_empty(self, column: Column) -> Q: + return Q(Exact(_django(column).compared, "")) - def _in_collection(self, collection: _Collection | None, condition: Q) -> Q: - """Apply a condition to the entries of a collection, or to the record itself outside of any collection. + def compare(self, column: Column, op: CompareOperator, value: Any) -> Q: + """Compare the field or the expression of a column with a value. - Within a value selection, the condition already applies to the entries. + A field is compared through its own lookups, as a filter by keyword + does: an integer the field cannot hold then matches nothing, rather + than failing in the database. """ - if collection is None or self.scope is not None: - return condition - - return collection.exists(condition) - - def visit_comparison(self, node: Comparison) -> Q: - """Keep the records with a value matching the comparison, in any collection holding the attribute.""" - binding = self._resolve(node.attr_path, self.filter.resolve_comparison) - if binding is None: - return _FALSE - - targets = self._targets(binding) - value = coerce_value(binding, node.value, node.op) - - # 'emails ne "x"' holds when no email is "x", while - # 'emails[value ne "x"]' holds when one email is not "x". - if ( - node.op == CompareOperator.ne - and targets[0][0] is not None - and self.scope is None - ): - return ~_any( - collection.exists( # type: ignore[union-attr] - _compare(self.comparator, column, CompareOperator.eq, value) - ) - for collection, column in targets - ) + column = _django(column) + value = _as_stored(value) + name = _LOOKUPS[op] + if column.expression is None: + return Q(**{f"{column.key}__{name}": value}) - return _any( - self._in_collection( - collection, _compare(self.comparator, column, node.op, value) - ) - for collection, column in targets - ) + return Q(models.Field.get_lookups()[name](column.compared, value)) # type: ignore[call-arg] - def visit_present(self, node: Present) -> Q: - """Keep the records with a value for the attribute. + def compare_text(self, column: Column, op: CompareOperator, value: str) -> Q: + """Compare a string column in the form the policy compares it under. - A complex attribute is present when one of its sub-attributes is. + A stored value the comparison key refuses is compared as no value, so + that the comparison is false rather than NULL. """ - binding = self._resolve(node.attr_path, self.filter.resolve) - if binding is None: - return _FALSE - - pairs = self._lookup(binding) - in_collection = pairs[0][0] is not None - if in_collection and binding.sub_field_name is None and pairs[0][1] is None: - return _any(collection.exists() for collection, _ in pairs) # type: ignore[union-attr] - - if all(column is not None and not column.concealed for _, column in pairs): - return _any( - self._in_collection(collection, _present(column)) # type: ignore[arg-type] - for collection, column in pairs - ) - - sub_columns = [ - column - for column in self.mapping._sub_columns(binding) - if not column.concealed - ] - if in_collection or not sub_columns: - raise _unmapped(binding) - - return _any(_present(column) for column in sub_columns) - - def visit_not(self, node: Not) -> Q: - """Keep the records the inner filter does not keep.""" - return ~self.visit(node.expr) - - def visit_logical_expr(self, node: LogicalExpr) -> Q: - """Combine the conditions of the terms with AND or OR.""" - conditions = [self.visit(term) for term in node.terms] - if node.op == LogicalOperator.and_: - return _all(conditions) - - return _any(conditions) - - def visit_value_path(self, node: ValuePath) -> Q: - """Keep the records with an entry of the attribute matching the inner filter.""" - binding = self.filter.resolve(node.attr_path, strict=False) - if binding is None: - return _FALSE - - collections: list[_Collection | _Entry] = [ - collection - for collection, _ in self.mapping._lookup(binding) - if collection is not None - ] - entry = self.mapping._entries.get((binding.model, binding.field_name)) - if entry is not None: - collections = [entry] - - if not collections: - raise _unmapped(binding) - - return _any( - collection.exists( - _FilterTranslator( - self.mapping, - self.filter, - self.comparator, - (node.attr_path, collection), - ).visit(node.val_filter) - ) - for collection in collections - ) - - -def _any(conditions: Iterable[Q]) -> Q: - """Return the condition that one of the conditions holds.""" - return reduce(operator.or_, conditions) - - -def _all(conditions: Iterable[Q]) -> Q: - """Return the condition that every condition holds.""" - return reduce(operator.and_, conditions) - - -def _present(column: _Column) -> Q: - """Per RFC 7644 §3.4.2.2, an empty string is no value.""" - expression = column.compared - if column.is_string: - return _is_not_null(expression) & ~Q(Exact(expression, "")) - - return _is_not_null(expression) - - -def _compare( - comparator: _Comparator, column: _Column, op: CompareOperator, value: Any -) -> Q: - """Compare a column with a value, strings in the form the policy compares them under. - - A string the policy cannot prepare is equal to no other value, so only ne - holds against it. - """ - expression = column.compared - value = _as_stored(value) - if value is None: - if op == CompareOperator.eq: - return _is_null(expression) - - if op == CompareOperator.ne: - return _is_not_null(expression) - - return _FALSE - - if column.keyed and op in (CompareOperator.eq, CompareOperator.ne): - return _compare_key(column, op, value, comparator) - - if not column.is_string: - if op == CompareOperator.ne: - return _is_null(expression) | ~_lookup(column, "exact", value) - + column = _django(column) + left = self.comparator.column(column) if op in _SUBSTRINGS: - return _FALSE - - return _is_not_null(expression) & _lookup(column, _LOOKUPS[op], value) - - try: - column.binding.comparable(value, comparator.policy) - except ValueError: - return _TRUE if op == CompareOperator.ne else _FALSE - - left = comparator.column(column) - if op == CompareOperator.ne: - return _is_null(left) | ~Q(Exact(left, comparator.operand(column, value))) - - if op in _SUBSTRINGS: - condition = comparator.substring(op, column, value) - else: - condition = Q(_ORDERINGS[op](left, comparator.operand(column, value))) - - return _is_not_null(left) & condition - - -def _compare_key( - column: _Column, op: CompareOperator, value: str, comparator: _Comparator -) -> Q: - """Compare an identifier in its own type. + condition = self.comparator.substring(op, column, value) + else: + right = self.comparator.operand(column, value) + condition = Q(_ORDERINGS[op](left, right)) - The database then uses its index, and the result does not depend on how - the database writes a UUID as text. - """ - key = _exact_key(column, value) - if key is None: - return _TRUE if op == CompareOperator.ne else _FALSE + return _is_not_null(left) & condition - field = models.F(column.field_key) - condition = Q(**{f"{column.field_key}__exact": key}) - if column.transformed: - condition &= Q(Exact(comparator.exact(column.compared), value)) + def compare_key(self, column: Column, value: Any) -> Q | None: + """Compare an identifier in its own type. - if op == CompareOperator.ne: - return _is_null(field) | ~condition + The database then uses its index, and the result does not depend on + how the database writes a UUID as text. + """ + column = _django(column) + key = _exact_key(column, value) + if key is None: + return None - return _is_not_null(field) & condition + condition = Q(**{f"{column.field_key}__exact": key}) + if column.transformed: + condition &= Q(Exact(self.comparator.exact(column.compared), value)) + return condition -def _lookup(column: _Column, name: str, value: Any) -> Q: - """Compare the field or the expression of a column with a value. + def exists( + self, + collection: Collection, + build: Callable[[Any], Q] | None = None, + ) -> Q: + condition = None if build is None else build(self) + return collection.exists(condition) # type: ignore[attr-defined,no-any-return] - A field is compared through its own lookups, as a filter by keyword - does: an integer the field cannot hold then matches nothing, rather than - failing in the database. - """ - if column.expression is None: - return Q(**{f"{column.key}__{name}": value}) - return Q(models.Field.get_lookups()[name](column.compared, value)) # type: ignore[call-arg] +def _django(column: Column) -> _Column: + """Return a column built by the Django mapping.""" + return column # type: ignore[return-value] def _sort_key( @@ -456,34 +222,50 @@ def _sort_key( """Return the expression the records of a mapping sort on. Return None when the search has no sortBy, or when the model of the - mapping does not declare its attribute. + mapping does not declare its attribute. A constant of an Entry sorts as + its value when the entry exists, and as no value otherwise. """ - binding = search_request.sort_binding(mapping.model) - if binding is None: + target = sort_target(mapping, search_request) + if target is None: return None - collection, column = mapping._lookup(binding)[0] - if ( - column is None - or column.concealed - or (collection is not None and not collection.owned) - ): - raise InvalidPathException( - path=str(search_request.sort_by), - detail=f"Cannot sort on '{binding.urn}'", - ) + collection, column = target + if column.is_constant: + return _constant_key(mapping, column, comparator) - expression: Any = column.compared + expression: Any = _django(column).compared if column.is_string: # The text the database sorts on, without the conversion of a field. expression = ExpressionWrapper( - comparator.column(column), output_field=models.TextField() + comparator.column(_django(column)), output_field=models.TextField() ) if collection is None: return expression - return _first_entry(collection, expression) + return _first_entry(collection, expression) # type: ignore[arg-type] + + +def _constant_key( + mapping: ResourceMapping, column: Column, comparator: _Comparator +) -> Any: + """Return the sort key of a constant of an Entry, which has no value when the entry does not exist. + + A string is in the form the database compares it under, and a string + the policy cannot prepare has no value, as the stored strings do. + """ + entry = mapping._entry_of(column) + present = entry_present(_Predicates(comparator), entry) # type: ignore[arg-type] + if not column.is_string: + value: Any = Value(column.constant, output_field=models.BooleanField()) + else: + holder = _Column(column.binding, column.key, False) + try: + value = comparator.operand(holder, column.constant) + except ValueError: + value = Value(None, output_field=models.TextField()) + + return Case(When(present, then=value), default=None) def _first_entry(collection: _Collection, expression: Any) -> Subquery: @@ -492,7 +274,7 @@ def _first_entry(collection: _Collection, expression: Any) -> Subquery: order: list[Any] = [] primary = collection.columns.get("primary") if primary is not None: - order.append(primary.compared.desc(nulls_last=True)) + order.append(_django(primary).compared.desc(nulls_last=True)) order.extend(collection.order()) return Subquery( @@ -508,11 +290,7 @@ def _where( comparator: _Comparator, ) -> Q: """Return the condition keeping the records matching the filter of a search, or every record without filter.""" - if search_request.filter is None: - return _TRUE - - scim_filter = ScimFilter[mapping.model](str(search_request.filter)) # type: ignore[name-defined] - return _FilterTranslator(mapping, scim_filter, comparator).visit(scim_filter.ast) + return where(mapping, search_request, _Predicates(comparator), comparator.policy) # type: ignore[no-any-return] def _search( diff --git a/src/scim2_django/storage/storage.py b/src/scim2_django/storage/storage.py index 1c4b2eb..4e9fbe4 100644 --- a/src/scim2_django/storage/storage.py +++ b/src/scim2_django/storage/storage.py @@ -4,6 +4,7 @@ from collections.abc import Mapping from contextlib import contextmanager from typing import Any +from typing import cast from django.core.exceptions import ImproperlyConfigured from django.db import DEFAULT_DB_ALIAS @@ -14,7 +15,6 @@ from django.db.models import ProtectedError from django.db.models import RestrictedError from scim2_models import ConflictException -from scim2_models import InvalidValueException from scim2_models import NotFoundException from scim2_models import Path from scim2_models import PreconditionFailedException @@ -30,23 +30,24 @@ 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.storage import ScimStorage from scim2_server.storage import SearchPage from .comparison import _Comparator from .comparison import _comparator from .comparison import _vendor -from .conversion import _as_stored -from .conversion import _check_storable -from .conversion import _comparable from .conversion import _from_scim -from .conversion import _link_entries from .conversion import _to_scim from .conversion import _write_collections from .mapping import ResourceMapping -from .mapping import _Collection -from .query import _compare -from .query import _exact_key +from .mapping import _as_stored +from .query import _Predicates from .query import _root_search from .query import _search from .query import _with_ids @@ -278,7 +279,7 @@ def create( """Store a new resource, and return it as stored.""" mapping = self._mapping(resource_type) with transaction.atomic(using=self.using): - _check_storable(mapping, resource, None) + check_storable(mapping, resource, None) self._check_uniqueness(mapping, resource, None) links = self._links(mapping, resource) record = mapping.record() @@ -310,7 +311,7 @@ def update( record = self._load(resource_type, resource.id, locked=True) stored = self._to_scim(resource_type, record) self._check_version(stored, expected_version) - _check_storable(mapping, resource, stored) + check_storable(mapping, resource, stored) self._check_uniqueness(mapping, resource, stored) links = self._links(mapping, resource) self._count_write(mapping, record) @@ -543,7 +544,7 @@ def _save( mapping: ResourceMapping, resource: Resource[Any], record: Any, - links: dict[_Collection, list[Any]], + links: dict[Collection, list[Any]], now: Any, stored: Resource[Any] | None, ) -> None: @@ -598,25 +599,32 @@ def _check_uniqueness( if stored is None else Path(column.binding.urn).get(stored, strict=False) ) - if value is None or _comparable(value) == _comparable(current): + if value is None or comparable(value) == comparable(current): continue - condition = _compare(comparator, column, CompareOperator.eq, value) + condition = compare( + mapping, + _Predicates(comparator), + self._policy, + column, + CompareOperator.eq, + value, + ) if others.filter(condition).exists(): raise UniquenessException def _links( self, mapping: ResourceMapping, resource: Resource[Any] - ) -> dict[_Collection, list[Any]]: + ) -> dict[Collection, list[Any]]: """Return the records each Link of a resource links to, refusing a value that links to nothing.""" - links: dict[_Collection, list[Any]] = {} - for collections, entries in _link_entries(mapping, resource): + links: dict[Collection, list[Any]] = {} + for collections, entries in link_entries(mapping, resource): ids = [entry.value for entry in entries] found = [ (collection, self._linked_records(collection, ids)) for collection in collections ] - links |= self._assign_links(found, entries) + links |= assign_links(found, entries, self._policy) for collection in mapping._all_collections(): if not collection.owned: @@ -624,74 +632,18 @@ def _links( return links - def _linked_records(self, collection: _Collection, ids: list[str]) -> list[Any]: + def _linked_records(self, collection: Collection, ids: list[str]) -> list[Any]: """Return the records of a Link holding one of the identifiers.""" - target = collection.target - assert target is not None + target = cast(ResourceMapping, collection.target) + target_id = target._id records = target.record._default_manager.using(self.using).filter( - _with_ids(target._id, ids, self._comparator()) + _with_ids(target_id, ids, self._comparator()) ) - if target._id.transformed: - records = records.annotate(**{target._id.key: target._id.expression}) + if target_id.transformed: + records = records.annotate(**{target_id.key: target_id.expression}) return list(records) - def _assign_links( - self, found: list[tuple[_Collection, list[Any]]], entries: list[Any] - ) -> dict[_Collection, list[Any]]: - """Give each entry of an attribute the record it links to, in the collection of the first Link holding that record. - - found holds the records each Link of the attribute holds among the - values of the entries. An entry with a type links to a Link giving - the same type. - """ - links: dict[_Collection, list[Any]] = { - collection: [] for collection, _ in found - } - urn = found[0][0].binding.urn - for entry in entries: - matches = [ - (collection, record) - for collection, records in found - for record in records - if _holds_id(collection, record, entry.value) - ] - if not matches: - raise InvalidValueException( - detail=f"'{urn}' links to an unknown resource" - ) - - entry_type = getattr(entry, "type", None) - if entry_type is not None: - matches = [ - (collection, record) - for collection, record in matches - if self._same_type(collection, entry_type) - ] - - if not matches: - raise InvalidValueException( - detail=f"'{urn}' links to {entry.value!r}, which is not " - f"of type {entry_type!r}" - ) - - collection, record = matches[0] - if record not in links[collection]: - links[collection].append(record) - - return links - - def _same_type(self, collection: _Collection, value: str) -> bool: - """Tell whether a type is the one a Link gives, compared as filters compare it.""" - binding = collection.type_column.binding # type: ignore[union-attr] - try: - return bool( - binding.comparable(value, self._policy) - == binding.comparable(collection.link_type, self._policy) - ) - except ValueError: - return False - 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.""" @@ -730,16 +682,3 @@ def _referenced() -> ConflictException: return ConflictException( detail="Another record refers to this resource, or it refers to a missing one" ) - - -def _holds_id(collection: _Collection, record: Any, value: str) -> bool: - """Tell whether a record a Link links to has an identifier. - - A record holds the expression of a transformed identifier, which gives - the identifier clients read. - """ - target_id = collection.target._id # type: ignore[union-attr] - if target_id.transformed: - return bool(getattr(record, target_id.key) == value) - - return bool(getattr(record, target_id.key) == _exact_key(target_id, value)) diff --git a/tests/test_conversion.py b/tests/test_conversion.py index 3d1340e..d45b8f2 100644 --- a/tests/test_conversion.py +++ b/tests/test_conversion.py @@ -10,18 +10,20 @@ from scim2_models import InvalidValueException from scim2_models import MutabilityException from scim2_models import User +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.utils import load_default_provider from scim2_django.storage import Attribute from scim2_django.storage import Computed from scim2_django.storage import Many from scim2_django.storage import ResourceMapping -from scim2_django.storage.conversion import _as_scim -from scim2_django.storage.conversion import _check_storable -from scim2_django.storage.conversion import _comparable from scim2_django.storage.conversion import _from_scim -from scim2_django.storage.conversion import _link_entries from scim2_django.storage.conversion import _to_scim from scim2_django.storage.conversion import _write_collections +from scim2_django.storage.mapping import _as_scim +from scim2_django.storage.mapping import _as_stored from .mappings import ENTERPRISE from .mappings import groups_mapping @@ -246,7 +248,7 @@ def test_read_only_entries_cannot_change(): stored = users.model(user_name="a", emails=[{"value": "kept@example.com"}]) with pytest.raises(MutabilityException, match="read-only on this server"): - _check_storable( + check_storable( users, users.model(user_name="a", emails=[{"value": "new@example.com"}]), stored, @@ -326,7 +328,7 @@ def test_an_attribute_the_mapping_does_not_store_is_refused(): users, _ = bound() with pytest.raises(InvalidValueException, match="phoneNumbers"): - _check_storable( + check_storable( users, users.model(user_name="a", phone_numbers=[{"value": "1"}]), None ) @@ -336,7 +338,7 @@ def test_a_read_only_attribute_cannot_change(): users, _ = bound() with pytest.raises(MutabilityException, match="read-only on this server"): - _check_storable(users, users.model(user_name="a", locale="fr"), None) + check_storable(users, users.model(user_name="a", locale="fr"), None) def test_a_value_equal_to_the_stored_one_is_accepted(): @@ -344,7 +346,7 @@ def test_a_value_equal_to_the_stored_one_is_accepted(): users, _ = bound() stored = users.model(user_name="a", locale="a") - _check_storable(users, users.model(user_name="a", locale="a"), stored) + check_storable(users, users.model(user_name="a", locale="a"), stored) def test_a_value_the_field_cannot_lose_is_kept(): @@ -355,7 +357,7 @@ def test_a_value_the_field_cannot_lose_is_kept(): mapping.schemas() with pytest.raises(MutabilityException, match="cannot be removed"): - _check_storable(mapping, User(), User(active=True)) + check_storable(mapping, User(), User(active=True)) def test_a_value_outside_the_choices_is_refused(): @@ -365,16 +367,30 @@ def test_a_value_outside_the_choices_is_refused(): ) mapping.schemas() - _check_storable(mapping, User(title="Ms"), None) + check_storable(mapping, User(title="Ms"), None) with pytest.raises(InvalidValueException, match="cannot hold 'Dr'"): - _check_storable(mapping, User(title="Dr"), None) + check_storable(mapping, User(title="Dr"), None) + + +def test_a_value_outside_the_choices_is_refused_in_a_resource_of_the_provider(): + """The server builds the resources with the models of its provider, not with the model of the mapping.""" + provider = load_default_provider() + user_type = next(rt for rt in provider.resource_types if rt.id == "User") + model = provider.model_for(user_type) + mapping = ResourceMapping( + User, Person, REQUIRED | {"title": "label"}, version="version" + ) + mapping.schemas() + + with pytest.raises(InvalidValueException, match="cannot hold 'Dr'"): + check_storable(mapping, model(title="Dr"), None) def test_the_display_of_a_link_is_ignored(): """A member display is read from the linked resource, so a client may send any.""" _, groups = bound() - _check_storable(groups, Group(members=[{"value": "1", "display": "Whoever"}]), None) + check_storable(groups, Group(members=[{"value": "1", "display": "Whoever"}]), None) def test_a_link_without_value_is_refused(): @@ -382,18 +398,18 @@ def test_a_link_without_value_is_refused(): _, groups = bound() with pytest.raises(InvalidValueException, match="entry without value"): - _link_entries(groups, Group(members=[{"display": "x"}])) + link_entries(groups, Group(members=[{"display": "x"}])) def test_the_links_of_a_resource_are_listed_by_attribute(): """Each written attribute linking to resources comes with its Links and its entries.""" users, groups = bound() - links = _link_entries(groups, Group(members=[{"value": "1"}, {"value": "2"}])) + links = link_entries(groups, Group(members=[{"value": "1"}, {"value": "2"}])) ((collections_, entries),) = links assert [c.resource_type for c in collections_] == ["User", "Group"] assert [entry.value for entry in entries] == ["1", "2"] - user_links = _link_entries( + user_links = link_entries( users, users.model.model_validate({ENTERPRISE: {"manager": {"value": "3"}}}) ) assert [(c[0].resource_type, [e.value for e in e_]) for c, e_ in user_links] == [ @@ -403,15 +419,15 @@ def test_the_links_of_a_resource_are_listed_by_attribute(): def test_missing_values_in_entries_are_no_value(): """A path through entries holding none of a sub-attribute gives no value.""" - assert _comparable([None, None]) is None - assert _comparable(["a", None]) == ["a", None] + assert comparable([None, None]) is None + assert comparable(["a", None]) == ["a", None] def test_a_date_with_a_time_zone_is_compared_in_utc(): """Two dates of the same instant compare equal, whatever their time zone.""" paris = datetime.timezone(datetime.timedelta(hours=1)) - assert _comparable( + assert comparable( datetime.datetime(2026, 1, 1, 9, tzinfo=paris) ) == datetime.datetime(2026, 1, 1, 8, tzinfo=datetime.UTC) @@ -468,14 +484,14 @@ def test_an_entry_without_a_value_its_field_needs_is_refused(): } ) ) - _check_storable( + check_storable( users, users.model(user_name="a", x509_certificates=[{"value": "AAE="}]), None ) with pytest.raises( InvalidValueException, match="x509Certificates.value' is required" ): - _check_storable( + check_storable( users, users.model(user_name="a", x509_certificates=[{"display": "x"}]), None, @@ -487,7 +503,7 @@ def test_dates_are_written_without_time_zone_when_use_tz_is_off(settings): settings.USE_TZ = False paris = datetime.timezone(datetime.timedelta(hours=1)) - assert _comparable( + assert _as_stored( datetime.datetime(2026, 1, 1, 9, tzinfo=paris) ) == datetime.datetime(2026, 1, 1, 8) @@ -508,9 +524,9 @@ def test_a_new_resource_needs_the_values_its_fields_cannot_do_without(): mapping = applicant_mapping() mapping.schemas() - _check_storable(mapping, mapping.model(active=True), None) + check_storable(mapping, mapping.model(active=True), None) with pytest.raises(InvalidValueException, match=":active' is required"): - _check_storable(mapping, mapping.model(), None) + check_storable(mapping, mapping.model(), None) def test_a_new_resource_needs_a_write_only_value_its_field_cannot_do_without(): @@ -519,7 +535,7 @@ def test_a_new_resource_needs_a_write_only_value_its_field_cannot_do_without(): mapping.schemas() with pytest.raises(InvalidValueException, match=":pin' is required"): - _check_storable(mapping, mapping.model(), None) + check_storable(mapping, mapping.model(), None) def test_a_replacement_without_a_value_never_returned_removes_it(): @@ -533,7 +549,7 @@ def test_a_replacement_without_a_value_never_returned_removes_it(): assert stored[Owned].secret == 7 with pytest.raises(MutabilityException, match=":secret' cannot be removed"): - _check_storable(mapping, mapping.model(), stored) + check_storable(mapping, mapping.model(), stored) def test_a_new_resource_may_leave_out_the_values_its_fields_get_by_themselves(): @@ -552,7 +568,7 @@ def test_a_new_resource_may_leave_out_the_values_its_fields_get_by_themselves(): ) mapping.schemas() - _check_storable(mapping, mapping.model(), None) + check_storable(mapping, mapping.model(), None) def test_a_converting_field_is_read_through_its_conversion(): @@ -583,7 +599,7 @@ def test_an_entry_may_leave_out_a_value_its_field_has_a_default_for(): ) ) - _check_storable( + check_storable( users, users.model(user_name="a", x509_certificates=[{"value": "AAE="}]), None ) @@ -596,7 +612,7 @@ def test_an_empty_string_is_no_value(): mapping.schemas() person = Person(id="p", user_name="a", created=NOW) - _check_storable(mapping, User(), User(user_name="a")) + check_storable(mapping, User(), User(user_name="a")) person = save(mapping, User(), person, creating=False) assert person.user_name == "" diff --git a/tests/test_entry.py b/tests/test_entry.py index e428b77..f89ca37 100644 --- a/tests/test_entry.py +++ b/tests/test_entry.py @@ -6,6 +6,7 @@ from scim2_models import Mutability from scim2_models import MutabilityException from scim2_models import ScimFilter +from scim2_models import ScimPolicy from scim2_models import SearchRequest from scim2_models import User @@ -173,6 +174,44 @@ def test_a_sort_on_the_entry_orders_as_search_request_sort(users, sort_order): ] +@pytest.mark.parametrize("sort_order", ["ascending", "descending"]) +@pytest.mark.parametrize("sort_by", ["emails.type", "emails.primary"]) +def test_a_sort_on_a_constant_orders_the_users_without_entry_apart( + users, sort_by, sort_order +): + """A constant sorts as the value of the entry, and as no value without entry.""" + search_request = SearchRequest(sort_by=sort_by, sort_order=sort_order) + everyone = users.storage.search([users.users], SearchRequest()).resources + + page = users.storage.search([users.users], search_request) + + expected = search_request.sort(everyone) + assert [search_request.sort_value(r) for r in page.resources] == [ + search_request.sort_value(r) for r in expected + ] + + +def refuse_work(binding, value): + if value.lower() == "work": + raise ValueError("The policy cannot prepare this string") + + return value.lower() + + +@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), + mappings={"User": users_mapping({"emails": EMAILS})}, + ) + create(server, "a", [work("alice@example.com")]) + create(server, "b") + + page = server.storage.search([server.users], SearchRequest(sort_by="emails.type")) + + assert sorted(r.user_name for r in page.resources) == ["a", "b"] + + def test_the_schema_holds_the_mapped_sub_attributes_and_the_constants(): (schema, _) = users_mapping({"emails": EMAILS}).schemas() (emails,) = [a for a in schema.attributes if a.name == "emails"] diff --git a/tests/test_mapping.py b/tests/test_mapping.py index ac869aa..1abe78b 100644 --- a/tests/test_mapping.py +++ b/tests/test_mapping.py @@ -207,7 +207,7 @@ def test_link_maps_a_complex_attribute_only(): def test_an_attribute_is_mapped_to_the_name_of_a_field(): """A field object, or any other value, cannot be resolved later.""" - with pytest.raises(ValueError, match="must be mapped to the name of a field"): + with pytest.raises(ValueError, match="'userName' cannot be mapped to