From c77eec624f3196e45c3cbc3b1735d27f9bca35a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89loi=20Rivard?= Date: Fri, 27 Nov 2026 09:17:05 +0100 Subject: [PATCH] feat: add a base for the storages built on an ORM scim2_server.mapping is the base of the storages that map SCIM resources to the records of an ORM: the declaration of a mapping and its checks, the translation of the filters and of the sorts into the conditions of the ORM, the reading of the records, and the checks of the writes. A backend gives the primitives of its ORM through hooks and the Predicates protocol. scim2-django and scim2-sqlalchemy build on it. Its API follows the needs of these backends, and may change in any minor version. --- doc/changelog.rst | 10 + doc/conf.py | 2 + doc/reference/index.rst | 1 + doc/reference/mapping.rst | 62 ++ scim2_server/mapping/__init__.py | 38 ++ scim2_server/mapping/conversion.py | 434 ++++++++++++++ scim2_server/mapping/declaration.py | 100 ++++ scim2_server/mapping/descriptors.py | 193 ++++++ scim2_server/mapping/filters.py | 526 +++++++++++++++++ scim2_server/mapping/mapping.py | 873 ++++++++++++++++++++++++++++ tests/mapping/__init__.py | 0 tests/mapping/backend.py | 619 ++++++++++++++++++++ tests/mapping/conftest.py | 65 +++ tests/mapping/pets.py | 81 +++ tests/mapping/policy.py | 12 + tests/mapping/tables.py | 135 +++++ tests/mapping/test_contract.py | 58 ++ tests/mapping/test_conversion.py | 270 +++++++++ tests/mapping/test_declaration.py | 267 +++++++++ tests/mapping/test_filters.py | 189 ++++++ tests/mapping/test_resolution.py | 280 +++++++++ tests/mapping/test_schemas.py | 163 ++++++ 22 files changed, 4378 insertions(+) create mode 100644 doc/reference/mapping.rst create mode 100644 scim2_server/mapping/__init__.py create mode 100644 scim2_server/mapping/conversion.py create mode 100644 scim2_server/mapping/declaration.py create mode 100644 scim2_server/mapping/descriptors.py create mode 100644 scim2_server/mapping/filters.py create mode 100644 scim2_server/mapping/mapping.py create mode 100644 tests/mapping/__init__.py create mode 100644 tests/mapping/backend.py create mode 100644 tests/mapping/conftest.py create mode 100644 tests/mapping/pets.py create mode 100644 tests/mapping/policy.py create mode 100644 tests/mapping/tables.py create mode 100644 tests/mapping/test_contract.py create mode 100644 tests/mapping/test_conversion.py create mode 100644 tests/mapping/test_declaration.py create mode 100644 tests/mapping/test_filters.py create mode 100644 tests/mapping/test_resolution.py create mode 100644 tests/mapping/test_schemas.py diff --git a/doc/changelog.rst b/doc/changelog.rst index 881b874..023f316 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,16 @@ Changelog ========= +[Unreleased] +------------ + +Added +^^^^^ +- :mod:`scim2_server.mapping` is the base of the storages that map SCIM resources to the records + of an ORM: the declaration of a mapping, its checks, the translation of the filters and of the + sorts into the conditions of the ORM, the reading of the records, and the checks of the writes. + scim2-django and scim2-sqlalchemy build on it. Its API may change in any minor version. + [0.8.9] - 2026-11-26 -------------------- diff --git a/doc/conf.py b/doc/conf.py index 4dde7c8..051b927 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -90,6 +90,7 @@ nitpick_ignore_regex = [ ("py:class", r"collections\.abc\.Callable\[\[\]"), ("py:class", r"dict\[str"), + ("py:class", r"dict\[str \| None"), ("py:class", r"collections\.abc\.Mapping\[str"), ] @@ -98,6 +99,7 @@ ("py:class", "scim2_server.service.ModelT"), ("py:class", "scim2_server.service.DiscoveryResourceT"), ("py:class", "scim2_server.testing.T"), + ("py:class", "scim2_server.mapping.filters.C"), ("py:class", "ModelT"), ("py:class", "DiscoveryResourceT"), ("py:class", "T"), diff --git a/doc/reference/index.rst b/doc/reference/index.rst index cf96e14..b2292c4 100644 --- a/doc/reference/index.rst +++ b/doc/reference/index.rst @@ -35,6 +35,7 @@ Storage :maxdepth: 1 storages + mapping testing Test server diff --git a/doc/reference/mapping.rst b/doc/reference/mapping.rst new file mode 100644 index 0000000..1b68476 --- /dev/null +++ b/doc/reference/mapping.rst @@ -0,0 +1,62 @@ +Mapping core +============ + +The base of the storages that map SCIM resources to the records of an ORM. It holds the SCIM +rules, and a backend gives the primitives of its ORM. scim2-django and scim2-sqlalchemy build on +it. + +.. warning:: + + This API follows the needs of these backends, and may change in any minor version. + +.. automodule:: scim2_server.mapping + +Backend hooks +------------- + +A backend subclasses :class:`~scim2_server.mapping.ResourceMapping` and overrides these methods: + +- ``_is_target(value)`` tells whether a value is a target of the ORM, such as a field; +- ``_check_declared(path, binding, value, holder)`` refuses a value the backend cannot map, by + raising :class:`ValueError`; +- ``_build_column(path, binding, value, owner)`` and ``_build_collection(path, binding, + declaration)`` build the descriptors, and yield a :class:`~scim2_server.mapping.MappingProblem` + for a target that does not fit; +- ``_check_record()`` and ``_fields_needing_value()`` give the problems and the fields of the + record; +- ``_links_to(collection, target)`` tells whether a Link holds the records of a target mapping; +- ``_read(column, record)``, ``_related(collection, record)``, ``_counter(record)`` and + ``_holds_id(record, value)`` read the records. + +The backend calls ``_resolve()`` once its models are ready, and gets the problems of the mapping. +A storage then calls ``_targets(mappings)`` on every mapping, then ``_bind(targets)``, so that a +refused mapping binds nothing. + +Declaration +----------- + +.. automodule:: scim2_server.mapping.declaration + :members: Attribute, Many, Entry, Link + +Resolution +---------- + +.. autoclass:: scim2_server.mapping.ResourceMapping + :members: schemas + +.. autoclass:: scim2_server.mapping.MappingProblem + +.. automodule:: scim2_server.mapping.descriptors + :members: Storage, Column, Collection, EntryColumns + +Filters and sorts +----------------- + +.. automodule:: scim2_server.mapping.filters + :members: Predicates, where, compare, present, entry_present, sort_target, holds + +Reading and writing +------------------- + +.. automodule:: scim2_server.mapping.conversion + :members: to_scim, version_hash, check_storable, write_plan, keeps, dates, entries, link_entries, assign_links, same_type, comparable diff --git a/scim2_server/mapping/__init__.py b/scim2_server/mapping/__init__.py new file mode 100644 index 0000000..7194f37 --- /dev/null +++ b/scim2_server/mapping/__init__.py @@ -0,0 +1,38 @@ +"""The base of the storages that map SCIM resources to the records of an ORM. + +A backend declares how each attribute is stored, and gives the primitives of +its ORM. The core holds the SCIM rules: the checks of the mappings, the +translation of the filters and of the sorts, the reading of the records and +the checks of the writes. scim2-django and scim2-sqlalchemy build on it. + +.. warning:: + + This API follows the needs of these backends, and may change in any minor + version. +""" + +from .declaration import Attribute +from .declaration import Entry +from .declaration import Link +from .declaration import Many +from .descriptors import Collection +from .descriptors import Column +from .descriptors import EntryColumns +from .descriptors import Storage +from .filters import Predicates +from .mapping import MappingProblem +from .mapping import ResourceMapping + +__all__ = [ + "Attribute", + "Collection", + "Column", + "Entry", + "EntryColumns", + "Link", + "Many", + "MappingProblem", + "Predicates", + "ResourceMapping", + "Storage", +] diff --git a/scim2_server/mapping/conversion.py b/scim2_server/mapping/conversion.py new file mode 100644 index 0000000..e62a034 --- /dev/null +++ b/scim2_server/mapping/conversion.py @@ -0,0 +1,434 @@ +"""Resources built from records, and the checks and plans of their writes.""" + +import hashlib +import hmac +import json +from collections.abc import Iterable +from collections.abc import Mapping +from inspect import isclass +from typing import Any + +from pydantic import BaseModel +from scim2_models import AttributeBinding +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_models import ScimPolicy + +from .descriptors import Collection +from .descriptors import Column +from .descriptors import Storage +from .filters import as_stored +from .mapping import ResourceMapping + + +def comparable(value: Any) -> Any: + """Return a value in a form two resources compare in. A list of missing values 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) + + +def values(binding: AttributeBinding, resource: Resource[Any]) -> list[Any]: + return list(Path(binding.urn).get(resource, strict=False) or []) + + +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 version_hash(resource: Resource[Any], key: bytes) -> str: + """Return the weak ETag of the hash of a resource. + + The hash covers the values hidden from clients, so it is keyed: a version + tells nothing about these values. + """ + data = json.dumps(resource.model_dump(mode="json"), sort_keys=True) + digest = hmac.new(key, data.encode(), hashlib.sha256) + return f'W/"{digest.hexdigest()[:32]}"' + + +def to_scim( + mapping: ResourceMapping, + record: Any, + resource_type: str, + model: type[Resource[Any]], + endpoints: Mapping[str, str], + collections: Iterable[Collection], + version_key: bytes | None, +) -> Resource[Any]: + """Build the resource a record stores, reading the given collections only.""" + 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 = mapping._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(): + found = { + column.binding.urn.rsplit(".", 1)[-1]: mapping._read(column, record) + for column in entry.columns.values() + } + if any(value is not None for value in found.values()): + found |= {name: column.constant for name, column in entry.constants.items()} + Path[model](entry.binding.urn).set(resource, [found]) # 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] + + _, found_entries = read.setdefault( + collection.binding.urn, (collection.single, []) + ) + for related in mapping._related(collection, record): + entry = _read_entry(mapping, collection, related, endpoint) + if entry is not None: + found_entries.append(entry) + + for urn, (single, found_entries) in read.items(): + if found_entries: + Path[model](urn).set( # type: ignore[valid-type] + resource, found_entries[0] if single else found_entries + ) + + resource.id = str(mapping._read(mapping._id, record)) + resource.meta = Meta( + resource_type=resource_type, + created=_read_date(mapping, mapping._created, record), + last_modified=_read_date(mapping, mapping._last_modified, record), + ) + resource = model.model_validate(resource.model_dump()) + if mapping.version is not None: + version = f'W/"{mapping._counter(record)}"' + else: + if version_key is None: + raise ValueError(f"{mapping!r} has no counter, and needs a version key") + + version = version_hash(resource, version_key) + + resource.meta.version = version # type: ignore[union-attr] + return resource + + +def _read_date(mapping: ResourceMapping, column: Column | None, record: Any) -> Any: + return None if column is None else mapping._read(column, record) + + +def _read_entry( + mapping: ResourceMapping, collection: Collection, entry: Any, endpoint: str | None +) -> Any: + """Return the values of an entry, or the value of an entry of a simple collection. + + The entries of a Link are records of its target, which reads them. + """ + reader = mapping if collection.owned else collection.target + assert reader is not None + if collection.simple: + return reader._read(collection.columns[None], entry) + + found = { + column.binding.urn.rsplit(".", 1)[-1]: reader._read(column, entry) + for column in collection.columns.values() + } + if collection.owned: + return found + + found["value"] = str(found["value"]) + if endpoint is not None: + found["$ref"] = f"{endpoint}/{found['value']}" + + if collection.link_type is not None: + found["type"] = collection.link_type + + return found + + +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 is compared with the stored resource, None for a new one. + A value equal to the stored one changes nothing. The read-only attributes + of the model are skipped, as RFC 7644 §3.5.1 has them ignored. + """ + _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: + _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: + 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.""" + for entry in mapping._entries.values(): + found = values(entry.binding, resource) + if len(found) > 1: + raise InvalidValueException( + detail=f"'{entry.binding.urn}' holds one entry at most on this server" + ) + + for item in found: + for name, 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() != column.constant.casefold(): + raise InvalidValueException( + detail=f"'{column.binding.urn}' can only be " + f"{column.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. + + The resource may be of another class than the model of the mapping, such + as the model of the provider, so the attribute is looked up by its URN. + """ + own = Path[mapping.model](binding.urn).resolve() # type: ignore[name-defined] + assert own is not None + _, column = mapping._lookup(own)[0] + if column is None or column.enumeration is None: + return + + for item in value if isinstance(value, list) else [value]: + if item is not None and mapping._as_stored(item) not in column.enumeration: + raise InvalidValueException( + detail=f"'{binding.urn}' cannot hold {item!r} on this server" + ) + + +def keeps( + mapping: ResourceMapping, column: Column, value: Any, record: Any, creating: bool +) -> bool: + """Tell whether a value leaves a record as it is. + + When creating, a missing value keeps the default, unless the backend + writes a value for none. When updating, a value equal to the one read is + kept, so that a password hash is not hashed again. + """ + if creating: + return value is None and not column.fills_none + + return bool(value == mapping._read(column, record)) + + +def write_plan( + mapping: ResourceMapping, + resource: Resource[Any], + record: Any, + creating: bool, +) -> list[tuple[Column, Any]]: + """Return the columns of the resource record to write, with their SCIM values. + + The backend converts each value into what its record stores. The dates, + the collections and the related records are written apart. + """ + plan: list[tuple[Column, Any]] = [] + for column in mapping._columns.values(): + if not column.writable or column.related or column.in_entry: + continue + + value = Path(column.binding.urn).get(resource, strict=False) + if not keeps(mapping, column, value, record, creating): + plan.append((column, value)) + + for entry in mapping._entries.values(): + found = values(entry.binding, resource) + if not entry.writable or (creating and not found): + continue + + item = found[0] if found else None + for column in entry.columns.values(): + value = getattr(item, column.binding.target_field_name, None) + if not keeps(mapping, column, value, record, creating): + plan.append((column, value)) + + return plan + + +def dates( + mapping: ResourceMapping, now: Any, creating: bool +) -> list[tuple[Column, Any]]: + """Return the date columns set to now: 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 link_entries( + mapping: ResourceMapping, resource: Resource[Any] +) -> list[tuple[list[Collection], list[Any]]]: + """Return the entries of each written attribute linking to other resources, with the collections of its Links. + + An entry without value, such as one with a $ref only, is refused rather than lost. + """ + links = [] + for collections in mapping._collections.values(): + collection = collections[0] + if collection.owned or not collection.writable: + continue + + found = entries(collection, resource) + if any(entry.value is None for entry in found): + raise InvalidValueException( + detail=f"'{collection.binding.urn}' holds an entry without value" + ) + + links.append((collections, found)) + + return links + + +def same_type(collection: Collection, value: str, policy: ScimPolicy) -> 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, policy) + == binding.comparable(collection.link_type, policy) + ) + except ValueError: + return False + + +def assign_links( + found: list[tuple[Collection, list[Any]]], + link_values: list[Any], + policy: ScimPolicy, +) -> dict[Collection, list[Any]]: + """Give each entry the record it links to, in the first Link holding that record. + + found holds the records each Link 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 link_values: + matches = [ + (collection, record) + for collection, records in found + for record in records + if collection.target._holds_id(record, entry.value) # type: ignore[union-attr] + ] + 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 same_type(collection, entry_type, policy) + ] + + 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 diff --git a/scim2_server/mapping/declaration.py b/scim2_server/mapping/declaration.py new file mode 100644 index 0000000..99aa6ee --- /dev/null +++ b/scim2_server/mapping/declaration.py @@ -0,0 +1,100 @@ +"""The values a mapping declares for each SCIM attribute. + +The targets are opaque to the core: a field name for Django, a column or a +relationship for SQLAlchemy, a field for Peewee. Each backend subclasses these +classes, to name the parameters after its ORM and to document them. +""" + +from collections.abc import Mapping +from typing import Any + +from scim2_models import AttributeBinding +from scim2_models import Mutability +from scim2_models import Required +from scim2_models import Returned + + +class Attribute: + """A value holding a SCIM attribute, whose writing can be turned off.""" + + def __init__(self, target: Any, *, writable: bool = True) -> None: + self.target = target + self.writable = writable + + +class Many: + """The entries of a multi-valued attribute, stored in related records. + + attributes maps each sub-attribute name to its target in the entry + records, or is a single target for a multi-valued simple attribute. + """ + + def __init__(self, relation: Any, attributes: Mapping[str, Any] | Any) -> None: + self.relation = relation + self.attributes = attributes + + +class Entry: + """A multi-valued complex attribute holding one entry at most, stored in the resource record. + + constants holds the sub-attributes the entry always has, such as its type. + """ + + def __init__( + self, + attributes: Mapping[str, Any], + *, + 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: + """A complex attribute linking to the resources of one resource type.""" + + def __init__( + self, relation: Any, resource_type: str, *, type: str | None = None + ) -> None: + self.relation = relation + self.resource_type = resource_type + self.type = type + + +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 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])) + + +def mutabilities(binding: AttributeBinding) -> set[Mutability | None]: + """Return the mutabilities of an attribute, on its own or through its parent.""" + return { + binding.model.get_field_annotation(binding.field_name, Mutability), + binding.get_annotation(Mutability), + } + + +def never_returned(binding: AttributeBinding) -> bool: + """Tell whether an attribute is never returned, on its own or through its parent.""" + return Returned.never in ( + binding.model.get_field_annotation(binding.field_name, Returned), + binding.get_annotation(Returned), + ) + + +def required(binding: AttributeBinding) -> bool: + """Tell whether an attribute is required where it is defined.""" + return Required.true in ( + binding.model.get_field_annotation(binding.field_name, Required), + binding.get_annotation(Required), + ) diff --git a/scim2_server/mapping/descriptors.py b/scim2_server/mapping/descriptors.py new file mode 100644 index 0000000..30529d4 --- /dev/null +++ b/scim2_server/mapping/descriptors.py @@ -0,0 +1,193 @@ +"""What a resolved mapping knows of each attribute. + +The backend builds the descriptors, and fills the facts only the ORM knows. +The core derives the rest from the SCIM attribute. +""" + +from dataclasses import dataclass +from dataclasses import field +from enum import Enum +from typing import TYPE_CHECKING +from typing import Any + +from scim2_models import Attribute as SchemaAttribute +from scim2_models import AttributeBinding +from scim2_models import Mutability + +from .declaration import mutabilities +from .declaration import never_returned + +if TYPE_CHECKING: + from .mapping import ResourceMapping + + +class Storage(Enum): + """How a mapping stores an attribute. + + A derived attribute is read from another resource, such as the display of + a member. A ref is the $ref of a link, built from its value. A link type + is the type a Link gives its entries, and a constant a sub-attribute an + Entry gives its entry: clients may send them, and the storage checks them. + """ + + written = "written" + read_only = "read only" + derived = "derived" + ref = "ref" + link_type = "link type" + constant = "constant" + + +_NO_CONSTANT = object() + + +@dataclass(eq=False) +class Column: + """A SCIM attribute stored in a value of a record. + + The backend fills key, writable and the facts of the storage. The core + reads keyed, nullable, needs_value, related, enumeration, stores and + fills_none. textual and empty_string are left to the conditions of the + backend: + + - textual: filters compare the value as text, as for an integer id; + - keyed: a search by this value goes through its index; + - nullable: the record can hold no value; + - needs_value: a new record without value fails in the database; + - empty_string: the record holds an empty string for no value; + - related: the value is held by a related record, which may not exist; + - enumeration: the values the storage accepts, if it restricts them; + - stores: the name of the record field written, for the checks; + - fills_none: the backend writes a value of its own for no value, as a + function converting the values may. + + A constant column always holds the same value, when its holder exists. + """ + + binding: AttributeBinding + key: str + writable: bool + textual: bool = False + keyed: bool = False + nullable: bool = True + needs_value: bool = False + empty_string: bool = False + related: bool = False + enumeration: list[Any] | None = None + stores: str | None = None + fills_none: bool = False + in_entry: bool = False + constant: Any = _NO_CONSTANT + + @property + def is_constant(self) -> bool: + return self.constant is not _NO_CONSTANT + + @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. Filters and sorts cannot compare it.""" + return never_returned(self.binding) or Mutability.write_only in mutabilities( + self.binding + ) + + @property + def casefolded(self) -> bool: + return self.is_string and not self.binding.case_exact + + @property + def required(self) -> bool: + """Whether a new record needs a value for the attribute.""" + if self.nullable or self.related: + return False + + return self.needs_value + + +@dataclass(eq=False) +class Collection: + """A multi-valued or complex attribute, stored in related records. + + The entries of an owned collection belong to the resource. The others are + links to the resources of another mapping, the target. The backend fills + relation, and nullable for a single link: the record can hold no link. + """ + + binding: AttributeBinding + relation: Any + columns: dict[str | None, Column] = field(default_factory=dict) + resource_type: str | None = None + target: "ResourceMapping | None" = None + link_type: str | None = None + type_column: Column | None = None + nullable: bool = True + stores: str | None = None + + @property + def owned(self) -> bool: + return self.resource_type is None + + @property + def single(self) -> bool: + return not self.binding.is_multivalued + + @property + def simple(self) -> bool: + """Whether the entries are the values of a multi-valued simple attribute.""" + return None in self.columns + + def column(self, sub_field_name: str | None) -> Column | None: + if sub_field_name == "type" and self.type_column is not None: + return self.type_column + + return self.columns.get(sub_field_name) + + @property + def writable(self) -> bool: + """Whether writing the resource writes these entries.""" + 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 EntryColumns: + """The columns of an Entry, held by the resource record. + + The entry exists when one of its columns has a value. + """ + + binding: AttributeBinding + columns: dict[str, Column] + constants: dict[str, Column] + simple = False + + @property + def writable(self) -> bool: + return any(column.writable for column in self.columns.values()) + + +def column_storage(column: Column) -> Storage: + return Storage.written if column.writable else Storage.read_only + + +__all__ = [ + "Collection", + "Column", + "EntryColumns", + "Storage", + "column_storage", +] diff --git a/scim2_server/mapping/filters.py b/scim2_server/mapping/filters.py new file mode 100644 index 0000000..22edc73 --- /dev/null +++ b/scim2_server/mapping/filters.py @@ -0,0 +1,526 @@ +"""SCIM filters and sorts, turned into the conditions of a backend. + +The core holds the SCIM rules: the scope of a value selection, ne on a +collection, missing values, substrings, strings the policy cannot prepare, +constants. The backend gives the primitives, through :class:`Predicates`. +""" + +from collections.abc import Callable +from collections.abc import Iterable +from enum import Enum +from functools import partial +from typing import Any +from typing import Protocol +from typing import TypeVar + +from scim2_models import AttributeBinding +from scim2_models import InvalidFilterException +from scim2_models import InvalidPathException +from scim2_models import ScimFilter +from scim2_models import ScimPolicy +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 .descriptors import Collection +from .descriptors import Column +from .descriptors import EntryColumns +from .mapping import ResourceMapping + +C = TypeVar("C") + +SUBSTRINGS = (CompareOperator.co, CompareOperator.sw, CompareOperator.ew) + + +class Predicates(Protocol[C]): + """The conditions a backend builds, on the records or on the entries of a collection. + + The core only calls compare and compare_text with a value that is not + None, and compare_text with a string the policy can prepare. compare + never gets a substring operator. + + Each condition is true or false, never unknown as a SQL NULL is, so that + its negation holds when it does not. compare_text is false for a stored + string the policy cannot prepare. + """ + + def true(self) -> C: ... + + def false(self) -> C: ... + + def any(self, conditions: Iterable[C]) -> C: ... + + def all(self, conditions: Iterable[C]) -> C: ... + + def negate(self, condition: C) -> C: ... + + def is_null(self, column: Column) -> C: ... + + def is_empty(self, column: Column) -> C: + """Return the condition that a string column holds an empty string.""" + ... + + def compare(self, column: Column, op: CompareOperator, value: Any) -> C: ... + + def compare_text(self, column: Column, op: CompareOperator, value: str) -> C: + """Compare a string column with the comparison key of the policy.""" + ... + + def compare_key(self, column: Column, value: Any) -> C | None: + """Return the condition that a keyed column equals a value, or None when no record can hold it.""" + ... + + def exists( + self, + collection: Collection, + build: Callable[["Predicates[C]"], C] | None = None, + ) -> C: + """Return the condition that an entry exists, matching what build returns from the conditions on the entries.""" + ... + + +def as_stored(value: Any) -> Any: + if isinstance(value, Enum): + return value.value + + return value + + +def holds( + binding: AttributeBinding, + op: CompareOperator, + actual: Any, + expected: Any, + policy: ScimPolicy, +) -> bool: + """Tell whether a value matches a comparison, as ScimFilter.match tells it.""" + if actual is None or expected is None: + if op == CompareOperator.eq: + return actual is None and expected is None + + if op == CompareOperator.ne: + return (actual is None) != (expected is None) + + return False + + try: + left = binding.comparable(actual, policy) + right = binding.comparable(expected, policy) + except ValueError: + return op == CompareOperator.ne + + if op in SUBSTRINGS: + if not isinstance(left, str) or not isinstance(right, str): + return False + + if op == CompareOperator.co: + return right in left + + if op == CompareOperator.sw: + return left.startswith(right) + + return left.endswith(right) + + try: + return bool( + { + CompareOperator.eq: lambda: left == right, + CompareOperator.ne: lambda: left != right, + CompareOperator.gt: lambda: left > right, + CompareOperator.ge: lambda: left >= right, + CompareOperator.lt: lambda: left < right, + CompareOperator.le: lambda: left <= right, + }[op]() + ) + except TypeError: + return False + + +def unmapped(binding: AttributeBinding) -> InvalidFilterException: + return InvalidFilterException(detail=f"Cannot filter on '{binding.urn}'") + + +Holder = Collection | EntryColumns + + +class FilterTranslator(FilterVisitor[C]): + """Turn a SCIM filter into a condition on the records of a mapping. + + The condition keeps the records whose resources ScimFilter.match keeps. + scope is the collection, or the Entry, a value selection applies its + filter to. + """ + + def __init__( + self, + mapping: ResourceMapping, + scim_filter: ScimFilter[Any], + conditions: Predicates[C], + policy: ScimPolicy, + scope: tuple[AttrPath, Holder] | None = None, + ) -> None: + self.mapping = mapping + self.filter = scim_filter + self.conditions = conditions + self.policy = policy + self.scope = scope + + def _resolve( + self, attr_path: AttrPath, resolve: Callable[..., AttributeBinding | None] + ) -> AttributeBinding | None: + 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 _lookup( + self, binding: AttributeBinding + ) -> list[tuple[Collection | None, Column | None]]: + pairs = self.mapping._lookup(binding) + if self.scope is None: + return pairs + + _, scope = self.scope + if isinstance(scope, EntryColumns): + return pairs + + return [ + (collection, column) for collection, column in pairs if collection is scope + ] + + def _targets( + self, binding: AttributeBinding + ) -> list[tuple[Collection | None, Column]]: + pairs = self._lookup(binding) + if any(column is None or column.concealed for _, column in pairs): + raise unmapped(binding) + + return pairs # type: ignore[return-value] + + def _in_collection( + self, collection: Collection | None, build: Callable[[Predicates[C]], C] + ) -> C: + if collection is None or self.scope is not None: + return build(self.conditions) + + return self.conditions.exists(collection, build) + + def _holder_exists(self, holder: Holder, build: Callable[[Predicates[C]], C]) -> C: + if isinstance(holder, EntryColumns): + return self.conditions.all( + [entry_present(self.conditions, holder), build(self.conditions)] + ) + + return self.conditions.exists(holder, build) + + def _compare( + self, conditions: Predicates[C], column: Column, op: CompareOperator, value: Any + ) -> C: + return compare(self.mapping, conditions, self.policy, column, op, value) + + def _scoped(self, node: ValuePath, holder: Holder, conditions: Predicates[C]) -> C: + translator = FilterTranslator( + self.mapping, self.filter, conditions, self.policy, (node.attr_path, holder) + ) + return translator.visit(node.val_filter) + + def visit_comparison(self, node: Comparison) -> C: + binding = self._resolve(node.attr_path, self.filter.resolve_comparison) + if binding is None: + return self.conditions.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 self.conditions.negate( + self.conditions.any( + self.conditions.exists( + collection, # type: ignore[arg-type] + partial( + self._compare, + column=column, + op=CompareOperator.eq, + value=value, + ), + ) + for collection, column in targets + ) + ) + + return self.conditions.any( + self._in_collection( + collection, + partial(self._compare, column=column, op=node.op, value=value), + ) + for collection, column in targets + ) + + def visit_present(self, node: Present) -> C: + """Keep the records with a value. A complex attribute is present when one of its sub-attributes is.""" + binding = self._resolve(node.attr_path, self.filter.resolve) + if binding is None: + return self.conditions.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 self.conditions.any( + self.conditions.exists(collection) # type: ignore[arg-type] + for collection, _ in pairs + ) + + visible = [ + (collection, column) + for collection, column in pairs + if column is not None and not column.concealed + ] + if len(visible) == len(pairs): + return self.conditions.any( + self._in_collection( + collection, partial(present, self.mapping, column=column) + ) + for collection, column in visible + ) + + 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 self.conditions.any( + present(self.mapping, self.conditions, column) for column in sub_columns + ) + + def visit_not(self, node: Not) -> C: + return self.conditions.negate(self.visit(node.expr)) + + def visit_logical_expr(self, node: LogicalExpr) -> C: + conditions = [self.visit(term) for term in node.terms] + if node.op == LogicalOperator.and_: + return self.conditions.all(conditions) + + return self.conditions.any(conditions) + + def visit_value_path(self, node: ValuePath) -> C: + binding = self.filter.resolve(node.attr_path, strict=False) + if binding is None: + return self.conditions.false() + + holders: list[Holder] = [ + 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: + holders = [entry] + + if not holders: + raise unmapped(binding) + + return self.conditions.any( + self._holder_exists(holder, partial(self._scoped, node, holder)) + for holder in holders + ) + + +def entry_present(conditions: Predicates[C], entry: EntryColumns) -> C: + """Return the condition that the record holds the entry: one of its columns has a value.""" + return conditions.any( + conditions.negate(conditions.is_null(column)) + for column in entry.columns.values() + ) + + +def present(mapping: ResourceMapping, conditions: Predicates[C], column: Column) -> C: + """Per RFC 7644 §3.4.2.2, an empty string is no value.""" + if column.is_constant: + entry = mapping._entry_of(column) + if entry is None: + return conditions.true() + + return entry_present(conditions, entry) + + has_value = conditions.negate(conditions.is_null(column)) + if not column.is_string: + return has_value + + return conditions.all([has_value, conditions.negate(conditions.is_empty(column))]) + + +def compare( + mapping: ResourceMapping, + conditions: Predicates[C], + policy: ScimPolicy, + column: Column, + op: CompareOperator, + value: Any, +) -> C: + """Compare a column with a value. + + A constant is compared in Python, as it is the same for every record + holding it. A missing value is equal to no value but a missing one. + """ + value = as_stored(value) + if column.is_constant: + return _compare_constant(mapping, conditions, policy, column, op, value) + + if value is None: + if op == CompareOperator.eq: + return conditions.is_null(column) + + if op == CompareOperator.ne: + return conditions.negate(conditions.is_null(column)) + + return conditions.false() + + if column.keyed and op in (CompareOperator.eq, CompareOperator.ne): + condition = conditions.compare_key(column, value) + if condition is None: + return conditions.true() if op == CompareOperator.ne else conditions.false() + + if op == CompareOperator.ne: + return conditions.any( + [conditions.is_null(column), conditions.negate(condition)] + ) + + return condition + + if not column.is_string: + if op in SUBSTRINGS: + return conditions.false() + + if op == CompareOperator.ne: + return conditions.any( + [ + conditions.is_null(column), + conditions.negate( + conditions.compare(column, CompareOperator.eq, value) + ), + ] + ) + + return conditions.all( + [ + conditions.negate(conditions.is_null(column)), + conditions.compare(column, op, value), + ] + ) + + try: + column.binding.comparable(value, policy) + except ValueError: + return conditions.true() if op == CompareOperator.ne else conditions.false() + + if op == CompareOperator.ne: + return conditions.any( + [ + conditions.is_null(column), + conditions.negate( + conditions.compare_text(column, CompareOperator.eq, value) + ), + ] + ) + + return conditions.all( + [ + conditions.negate(conditions.is_null(column)), + conditions.compare_text(column, op, value), + ] + ) + + +def _compare_constant( + mapping: ResourceMapping, + conditions: Predicates[C], + policy: ScimPolicy, + column: Column, + op: CompareOperator, + value: Any, +) -> C: + """Compare a constant: the one of its holder when the holder exists, or else no value.""" + + def outcome(actual: Any) -> C: + matched = holds(column.binding, op, actual, value, policy) + return conditions.true() if matched else conditions.false() + + entry = mapping._entry_of(column) + if entry is None: + return outcome(column.constant) + + exists = entry_present(conditions, entry) + return conditions.any( + [ + conditions.all([exists, outcome(column.constant)]), + conditions.all([conditions.negate(exists), outcome(None)]), + ] + ) + + +def where( + mapping: ResourceMapping, + search_request: SearchRequest[Any], + conditions: Predicates[C], + policy: ScimPolicy, +) -> C: + """Return the condition keeping the records matching the filter of a search.""" + if search_request.filter is None: + return conditions.true() + + scim_filter = ScimFilter[mapping.model](str(search_request.filter)) # type: ignore[name-defined] + return FilterTranslator(mapping, scim_filter, conditions, policy).visit( + scim_filter.ast + ) + + +def sort_target( + mapping: ResourceMapping, search_request: SearchRequest[Any] +) -> tuple[Collection | None, Column] | None: + """Return the column the records sort on, with its collection if any. + + Return None when the search has no sortBy, or when the model of the + mapping does not declare its attribute. A value hidden from clients, or + held by another resource, cannot sort. 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: + 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}'", + ) + + return collection, column diff --git a/scim2_server/mapping/mapping.py b/scim2_server/mapping/mapping.py new file mode 100644 index 0000000..aa9a0fb --- /dev/null +++ b/scim2_server/mapping/mapping.py @@ -0,0 +1,873 @@ +"""The base of the mappings of the backends: declaration, resolution and SCIM rules.""" + +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 replace +from enum import Enum +from inspect import isclass +from typing import Any + +from pydantic import BaseModel +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 .declaration import Attribute +from .declaration import Entry +from .declaration import Link +from .declaration import Many +from .declaration import key +from .declaration import mutabilities +from .declaration import never_returned +from .declaration import overlap +from .declaration import required +from .descriptors import Collection +from .descriptors import Column +from .descriptors import EntryColumns +from .descriptors import Storage +from .descriptors import column_storage + + +@dataclass(frozen=True) +class MappingProblem: + """A problem of a mapping, which the backend reports in its own way. + + level is "error" or "warning". code tells the rule apart, so that a + backend can give it its own identifier. + """ + + level: str + code: str + message: str + + +Problems = Generator[MappingProblem, None, Any] + + +class ResourceMapping: + """How the resources of a SCIM model are stored in the records of a backend. + + The paths are checked when the mapping is created, which raises + :class:`ValueError` for a path out of the model. The backend resolves the + targets once its models are ready, and gets the problems of the mapping + as :class:`MappingProblem` objects. + """ + + REQUIRED = ("id",) + + configuration_error: type[Exception] = ValueError + """The exception refusing mappings that do not fit together, such as a Link to a missing mapping.""" + + def __init__( + self, + model: type[Resource[Any]], + record: Any, + attributes: Mapping[str, Any], + *, + version: Any = None, + ) -> None: + self.model = model + self.record = record + self.version = version + self._declared: dict[str, tuple[AttributeBinding, Any]] = {} + self._columns: dict[tuple[Any, ...], Column] = {} + self._collections: dict[tuple[Any, ...], list[Collection]] = {} + self._entries: dict[tuple[Any, ...], EntryColumns] = {} + self._problems: list[MappingProblem] | None = None + self._id: Column + self._created: Column | None = None + self._last_modified: Column | None = None + + declared: dict[tuple[Any, ...], str] = {} + for path, value in attributes.items(): + binding = self._resolve_path(path) + binding_key = key(binding) + for other, other_path in declared.items(): + if overlap(binding_key, other): + raise ValueError( + f"{other_path!r} and {path!r} map the same attribute" + ) + + declared[binding_key] = path + self._declare(path, binding, value) + + for path in self.REQUIRED: + if key(self._resolve_path(path)) not in declared: + raise ValueError(f"The mapping of {model.__name__} needs {path!r}") + + def __repr__(self) -> str: + return f"<{type(self).__name__} of {self.model.__name__}>" + + def _is_target(self, value: Any) -> bool: + """Tell whether a value is a target the backend maps a simple attribute to.""" + raise NotImplementedError + + def _value_writable(self, value: Any) -> bool: + """Tell whether the backend writes a value declared for a simple attribute.""" + return not isinstance(value, Attribute) or value.writable + + def _check_declared( + self, + path: str, + binding: AttributeBinding, + value: Any, + holder: Many | Entry | None, + ) -> None: + """Refuse a value the backend cannot map, by raising ValueError. + + holder is the Many or the Entry holding the value, or None for a value + of the resource record. + """ + + def _build_column( + self, + path: str, + binding: AttributeBinding, + value: Any, + owner: Collection | None, + ) -> Problems: + """Build the column of a value, in the resource record or in the entries of owner.""" + raise NotImplementedError + + def _build_collection( + self, path: str, binding: AttributeBinding, declaration: Many | Link + ) -> Problems: + """Build the collection of a Many or of a Link, without its columns.""" + raise NotImplementedError + + def _check_record(self) -> Problems: + """Yield the problems of the backend once every column is built.""" + yield from () + + def _fields_needing_value(self) -> Iterable[str]: + """Return the record fields a new record needs a value for.""" + return () + + def _links_to(self, collection: Collection, target: "ResourceMapping") -> bool: + """Tell whether the records of a Link are the records of a target mapping.""" + raise NotImplementedError + + def _read(self, column: Column, record: Any) -> Any: + """Return the SCIM value a record holds for a column.""" + raise NotImplementedError + + def _related(self, collection: Collection, record: Any) -> list[Any]: + """Return the entry records of a collection of a record, in their order.""" + raise NotImplementedError + + def _counter(self, record: Any) -> Any: + """Return the write counter of a record.""" + raise NotImplementedError + + def _holds_id(self, record: Any, value: str) -> bool: + """Tell whether a record of this mapping has an identifier.""" + raise NotImplementedError + + def _as_stored(self, value: Any) -> Any: + """Return a SCIM value in the form the backend stores it, such as an Enum as its value.""" + return value.value if isinstance(value, Enum) else value + + def _find(self, path: str) -> AttributeBinding | None: + return Path[self.model](path).resolve() # type: ignore[name-defined] + + def _resolve_path(self, path: str) -> AttributeBinding: + binding = self._find(path) + if binding is None: + raise ValueError(f"{path!r} is not an attribute of {self.model.__name__}") + + return binding + + def _declare(self, path: str, binding: AttributeBinding, value: Any) -> None: + target = binding.target_type + is_complex = isclass(target) and issubclass(target, BaseModel) + + if isinstance(value, Many): + self._check_many(path, binding, value, is_complex) + self._declared[path] = (binding, value) + return + + if isinstance(value, Entry): + self._check_entry(path, binding, value, is_complex) + self._declared[path] = (binding, value) + return + + if isinstance(value, Link): + value = [value] + + 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: + raise ValueError( + f"{path!r} is not a complex attribute of {self.model.__name__}" + ) + + if not binding.is_multivalued and len(value) > 1: + raise ValueError( + f"{path!r} holds one value, so it is mapped to one Link" + ) + + self._check_links(path, value) + self._declared[path] = (binding, value) + 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_single(path, binding) + self._check_value(path, value) + self._check_declared(path, binding, value, None) + self._check_read_and_written(path, binding, value) + self._declared[path] = (binding, value) + + def _check_value(self, path: str, value: Any) -> None: + target = value.target if isinstance(value, Attribute) else value + if not self._is_target(target): + raise ValueError(f"{path!r} cannot be mapped to {value!r}") + + def _check_read_and_written( + self, path: str, binding: AttributeBinding, value: Any + ) -> None: + read = Mutability.write_only not in mutabilities( + binding + ) and not never_returned(binding) + written = Mutability.read_only not in mutabilities( + binding + ) and self._value_writable(value) + if not (read or written): + raise ValueError(f"Clients could neither read nor write {path!r}") + + def _check_single(self, path: str, binding: AttributeBinding) -> None: + 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_many( + self, path: str, binding: AttributeBinding, many: Many, is_complex: bool + ) -> None: + 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_value(path, many.attributes) + self._check_declared(path, binding, many.attributes, many) + return + + entries: dict[tuple[Any, ...], str] = {} + for sub_path, sub_value in many.attributes.items(): + sub_binding = self._resolve_path(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_single(f"{path}.{sub_path}", sub_binding) + self._check_value(f"{path}.{sub_path}", sub_value) + self._check_declared(f"{path}.{sub_path}", sub_binding, sub_value, many) + + def _check_entry( + self, path: str, binding: AttributeBinding, entry: Entry, is_complex: bool + ) -> None: + 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_path(f"{path}.{sub_path}") + self._check_single(f"{path}.{sub_path}", sub_binding) + self._check_value(f"{path}.{sub_path}", sub_value) + self._check_declared(f"{path}.{sub_path}", sub_binding, sub_value, entry) + 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_links(self, path: str, links: list[Link]) -> 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(self) -> list[MappingProblem]: + """Build the descriptors of the declared values, once, and return the problems of the mapping.""" + if self._problems is None: + problems = list(self._build()) + if not any(problem.level == "error" for problem in problems): + problems.extend(self._check_unwritten()) + + self._problems = problems + + return self._problems + + def _build(self) -> Problems: + for path, (binding, value) in self._declared.items(): + head = (binding.model, binding.field_name) + if isinstance(value, Many): + collection = yield from self._many(path, binding, value) + if collection is not None: + self._collections[head] = [collection] + elif isinstance(value, Entry): + entry = yield from self._entry(path, binding, value) + if entry is not None: + self._entries[head] = entry + for column in entry.columns.values(): + self._columns[key(column.binding)] = column + elif isinstance(value, list): + collections = yield from self._links(path, binding, value) + if collections is not None: + self._collections[head] = collections + else: + column = yield from self._build_column(path, binding, value, None) + if column is not None: + self._columns[key(binding)] = column + + if not all( + key(self._resolve_path(path)) in self._columns for path in self.REQUIRED + ): + return + + self._id = self._column("id") + self._created = self._columns.get(key(self._resolve_path("meta.created"))) + self._last_modified = self._columns.get( + key(self._resolve_path("meta.lastModified")) + ) + yield from self._check_record() + + def _many(self, path: str, binding: AttributeBinding, many: Many) -> Problems: + collection = yield from self._build_collection(path, binding, many) + if collection is None: + return None + + if not isinstance(many.attributes, Mapping): + column = yield from self._build_column( + path, binding, many.attributes, collection + ) + if column is None: + return None + + collection.columns[None] = column + else: + for sub_path, value in many.attributes.items(): + sub_binding = self._resolve_path(f"{path}.{sub_path}") + column = yield from self._build_column( + f"{path}.{sub_path}", sub_binding, value, collection + ) + if column is None: + return None + + collection.columns[sub_binding.sub_field_name] = column + + columns = collection.columns.values() + if any(column.concealed for column in columns): + yield MappingProblem( + "error", + "hidden-in-entries", + f"The entries of {path!r} are replaced on each write, " + "so they cannot hold values hidden from clients", + ) + return None + + if collection.writable and not all(column.writable for column in columns): + yield MappingProblem( + "error", + "read-only-in-entries", + f"The entries of {path!r} are replaced on each write, " + "so they cannot hold a read-only value next to written ones", + ) + return None + + return collection + + def _entry(self, path: str, binding: AttributeBinding, entry: Entry) -> Problems: + columns: dict[str, Column] = {} + for sub_path, value in entry.attributes.items(): + sub_binding = self._resolve_path(f"{path}.{sub_path}") + column = yield from self._build_column( + f"{path}.{sub_path}", sub_binding, value, None + ) + if column is None: + return None + + column.in_entry = True + columns[sub_binding.sub_field_name] = column # type: ignore[index] + + values = columns.values() + if any(column.concealed or not column.nullable for column in values): + yield MappingProblem( + "error", + "entry-fields", + 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", + ) + return None + + writable = [column.writable for column in values] + if any(writable) and not all(writable): + yield MappingProblem( + "error", + "entry-fields", + f"A write removing the entry of {path!r} empties its fields, so " + "they cannot hold a read-only value next to written ones", + ) + return None + + constants = { + name: Column( + self._resolve_path(f"{path}.{name}"), name, False, constant=constant + ) + for name, constant in entry.constants.items() + } + return EntryColumns(binding, columns, constants) + + def _links( + self, path: str, binding: AttributeBinding, links: list[Link] + ) -> Problems: + collections: list[Collection] = [] + for link in links: + collection = yield from self._build_collection(path, binding, link) + if collection is None: + return None + + if ( + collection.single + and not collection.nullable + and not self._always_held(binding) + ): + yield MappingProblem( + "error", + "single-link-null", + f"{path!r} can be removed, or left out with its extension, " + "so its relation needs to hold null", + ) + 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_path(f"{path}.type"), + "type", + False, + constant=link.type, + ) + + collections.append(collection) + + return collections + + 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 _check_unwritten(self) -> Iterator[MappingProblem]: + dates = {self._created, self._last_modified} + written = { + column.stores + for column in self._columns.values() + if column.stores is not None and (column.writable or column in dates) + } + written.update( + collection.stores + for collection in self._all_collections() + if collection.stores is not None and collection.writable + ) + for name in self._fields_needing_value(): + if name in written: + continue + + yield MappingProblem( + "warning", + "unwritten", + f"The field {name!r} needs a value, but the storage never writes " + "it, so creating a resource fails: map it, or give it a default", + ) + + def _targets( + self, mappings: Mapping[str, "ResourceMapping"] + ) -> list[tuple[Collection, "ResourceMapping"]]: + """Return each Link with the mapping of the resources it links to.""" + return [ + (collection, self._target(collection, mappings)) + for collection in self._all_collections() + if not collection.owned + ] + + def _target( + self, collection: Collection, mappings: Mapping[str, "ResourceMapping"] + ) -> "ResourceMapping": + target = mappings.get(collection.resource_type) # type: ignore[arg-type] + if target is None: + raise self.configuration_error( + f"No mapping for the resource type {collection.resource_type!r}" + ) + + if collection.target is not None and collection.target is not target: + raise self.configuration_error( + f"{collection.binding.urn!r} already links to another mapping " + f"of {collection.resource_type!r}" + ) + + if not self._links_to(collection, target): + raise self.configuration_error( + f"{collection.binding.urn!r} links to other records than those " + f"of the mapping of {collection.resource_type!r}" + ) + + return target + + def _bind(self, links: list[tuple[Collection, "ResourceMapping"]]) -> None: + """Bind each Link to its target, whose id and display become the columns of the entries.""" + for collection, target in links: + collection.target = target + collection.columns = {} + head = collection.binding.urn + for binding, column in ( + (self._resolve_path(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 _display(self) -> Column | None: + 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 schemas(self) -> list[Schema]: + """Return the schemas of the resources, restricted to what the mapping stores.""" + models: list[Any] = [self.model, *self.model.get_extension_models().values()] + return [self._restrict(model.to_schema()) for model in models] + + def _restrict(self, schema: Schema) -> Schema: + 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: + 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: + 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: + if not attribute.canonical_values: + return attribute + + constant = self._constant_value(urn) + 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: + 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.""" + urn_key = urn.lower() + for column in self._columns.values(): + if column.binding.urn.lower() == urn_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() == urn_key: + return column_storage(column) + + continue + + head = collection.binding.urn.lower() + if urn_key == f"{head}.value": + return Storage.written + + if urn_key in (f"{head}.display", f"{head}.displayname"): + return Storage.derived + + if urn_key == f"{head}.$ref": + return Storage.ref + + if urn_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() != urn_key: + continue + + return Storage.constant if entry.writable else Storage.read_only + + return None + + def _constant_value(self, urn: str) -> Any: + urn_key = urn.lower() + return next( + column.constant + for entry in self._entries.values() + for column in entry.constants.values() + if column.binding.urn.lower() == urn_key + ) + + def _linked_resource_types(self, urn: str) -> list[str]: + 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]: + for collections in self._collections.values(): + yield from collections + + def _column(self, path: str) -> Column: + return self._columns[key(self._resolve_path(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.""" + 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: + entry = self._entries.get((binding.model, binding.field_name)) + if entry is None: + return None + + return entry.constants.get(binding.sub_field_name) # type: ignore[arg-type] + + def _entry_of(self, column: Column) -> EntryColumns | None: + """Return the Entry holding a constant column, if any.""" + for entry in self._entries.values(): + if column in entry.constants.values(): + return entry + + return None + + def _nullable(self, urn: str) -> bool: + urn_key = urn.lower() + return all( + column.nullable + for column in self._columns.values() + if column.binding.urn.lower() == urn_key + ) + + def _required(self, urn: str) -> bool: + 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.""" + 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]: + urn_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() == urn_key: + yield column + + def _sub_columns(self, binding: AttributeBinding) -> list[Column]: + 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]: + for column in self._columns.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 + + def _unique_columns(self) -> Iterator[Column]: + """Yield the written columns clients read, whose values no two resources share.""" + for column in self._columns.values(): + if column.concealed or not column.writable or column.in_entry: + continue + + 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 or without counter.""" + 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 + ] diff --git a/tests/mapping/__init__.py b/tests/mapping/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/mapping/backend.py b/tests/mapping/backend.py new file mode 100644 index 0000000..b0928cd --- /dev/null +++ b/tests/mapping/backend.py @@ -0,0 +1,619 @@ +"""A backend of the mapping core for the tests: records in dicts, conditions in Python predicates.""" + +import datetime +import operator +from collections.abc import Callable +from collections.abc import Iterable +from collections.abc import Mapping +from dataclasses import dataclass +from dataclasses import field as dataclass_field +from typing import Any + +from scim2_models import AttributeBinding +from scim2_models import Mutability +from scim2_models import NotFoundException +from scim2_models import Path +from scim2_models import PreconditionFailedException +from scim2_models import Resource +from scim2_models import ResourceType +from scim2_models import ResponseParameters +from scim2_models import ScimPolicy +from scim2_models import ScimProvider +from scim2_models import SearchRequest +from scim2_models import UniquenessException +from scim2_models.path import CompareOperator + +from scim2_server import mapping as core +from scim2_server.mapping import conversion +from scim2_server.mapping.declaration import mutabilities +from scim2_server.mapping.filters import as_stored +from scim2_server.mapping.filters import compare +from scim2_server.mapping.filters import entry_present +from scim2_server.mapping.filters import sort_target +from scim2_server.mapping.filters import where +from scim2_server.storage import ScimStorage +from scim2_server.storage import SearchPage + +Row = dict[str, Any] +Predicate = Callable[[Row], bool] + + +@dataclass(eq=False) +class Field: + table: "Table" + name: str + null: bool = True + default: Any = None + choices: list[Any] | None = None + + +class Table: + """The rows of a model, by primary key. Each row holds its key in "id".""" + + def __init__(self, name: str) -> None: + self.name = name + self.fields: dict[str, Field] = {} + self.rows: dict[int, Row] = {} + self.next_key = 1 + self.id = self.field("id", null=False) + + def __repr__(self) -> str: + return self.name + + def field(self, name: str, **options: Any) -> Field: + self.fields[name] = Field(self, name, **options) + return self.fields[name] + + def new(self) -> Row: + return {name: field.default for name, field in self.fields.items()} + + def insert(self, row: Row) -> None: + row["id"] = self.next_key + self.rows[self.next_key] = row + self.next_key += 1 + + +@dataclass(frozen=True) +class Owned: + """The rows of target holding the key of their record in key.""" + + target: Table + key: str + + +@dataclass(frozen=True) +class Reference: + """A field of the record holding the key of a row of target.""" + + field: Field + target: Table + + +@dataclass(frozen=True) +class References: + """A field of the record holding the keys of rows of target.""" + + field: Field + target: Table + + +@dataclass(frozen=True) +class Referrers: + """The rows whose References field holds the key of the record.""" + + field: Field + + @property + def target(self) -> Table: + return self.field.table + + +@dataclass(eq=False) +class FakeColumn(core.Column): + field: Field = dataclass_field(default=None) + + +def related(collection: core.Collection, row: Row) -> list[Row]: + relation = collection.relation + if isinstance(relation, Owned): + found = relation.target.rows.values() + return [entry for entry in found if entry[relation.key] == row["id"]] + + if isinstance(relation, Reference): + key = row[relation.field.name] + return [] if key is None else [relation.target.rows[key]] + + if isinstance(relation, References): + keys = sorted(row[relation.field.name]) + return [ + relation.target.rows[key] for key in keys if key in relation.target.rows + ] + + found = relation.target.rows.values() + return [entry for entry in found if row["id"] in entry[relation.field.name]] + + +def needs_value(field: Field) -> bool: + return not (field.null or field.default is not None or field.name == "id") + + +class FakeMapping(core.ResourceMapping): + """A mapping on tables, resolved when created unless resolve is False. + + :raises ValueError: When a field does not fit its attribute. + """ + + def __init__( + self, + model: type[Resource[Any]], + record: Table, + attributes: Mapping[str, Any], + *, + version: Field | None = None, + resolve: bool = True, + ) -> None: + super().__init__(model, record, attributes, version=version) + if not resolve: + return + + errors = [problem for problem in self._resolve() if problem.level == "error"] + if errors: + raise ValueError("\n".join(problem.message for problem in errors)) + + def _is_target(self, value: Any) -> bool: + return isinstance(value, Field) + + def _build_column( + self, + path: str, + binding: AttributeBinding, + value: Any, + owner: core.Collection | None, + ) -> core.mapping.Problems: + field = value.target if isinstance(value, core.Attribute) else value + table = self.record if owner is None else owner.relation.target + if field.table is not table: + yield core.MappingProblem( + "error", + "unknown-field", + f"{path!r} is not mapped to a field of {table}", + ) + return None + + is_id = owner is None and path == "id" + column = FakeColumn( + binding, + field.name, + Mutability.read_only not in mutabilities(binding) + and self._value_writable(value) + and not is_id, + textual=is_id, + keyed=is_id, + nullable=field.null, + needs_value=needs_value(field), + enumeration=field.choices, + stores=field.name if owner is None else None, + field=field, + ) + return column + + def _build_collection( + self, + path: str, + binding: AttributeBinding, + declaration: core.Many | core.Link, + ) -> core.mapping.Problems: + relation = declaration.relation + if isinstance(declaration, core.Many): + kinds: tuple[type, ...] = (Owned,) + elif binding.is_multivalued: + kinds = (References, Referrers) + else: + kinds = (Reference,) + + if not isinstance(relation, kinds): + yield core.MappingProblem( + "error", "relation-kind", f"{path!r} cannot be mapped to {relation!r}" + ) + return None + + if isinstance(relation, Reference): + return core.Collection( + binding, + relation, + nullable=relation.field.null, + stores=relation.field.name, + ) + + return core.Collection(binding, relation) + + def _fields_needing_value(self) -> Iterable[str]: + return [ + field.name + for field in self.record.fields.values() + if needs_value(field) and field is not self.version + ] + + def _links_to(self, collection: core.Collection, target: Any) -> bool: + return bool(collection.relation.target is target.record) + + def _read(self, column: core.Column, record: Any) -> Any: + return record.get(column.field.name) + + def _related(self, collection: core.Collection, record: Any) -> list[Any]: + return related(collection, record) + + def _counter(self, record: Any) -> Any: + return record[self.version.name] + + def _holds_id(self, record: Any, value: str) -> bool: + return str(record["id"]) == value + + +_OPERATORS: dict[CompareOperator, Callable[[Any, Any], Any]] = { + CompareOperator.eq: operator.eq, + CompareOperator.gt: operator.gt, + CompareOperator.ge: operator.ge, + CompareOperator.lt: operator.lt, + CompareOperator.le: operator.le, + CompareOperator.co: operator.contains, + CompareOperator.sw: str.startswith, + CompareOperator.ew: str.endswith, +} + + +class FakePredicates: + """Predicates on rows, as SQL evaluates them: a comparison with no value does not hold.""" + + def __init__(self, policy: ScimPolicy) -> None: + self.policy = policy + + def true(self) -> Predicate: + return lambda row: True + + def false(self) -> Predicate: + return lambda row: False + + def any(self, conditions: Iterable[Predicate]) -> Predicate: + conditions = list(conditions) + return lambda row: any(condition(row) for condition in conditions) + + def all(self, conditions: Iterable[Predicate]) -> Predicate: + conditions = list(conditions) + return lambda row: all(condition(row) for condition in conditions) + + def negate(self, condition: Predicate) -> Predicate: + return lambda row: not condition(row) + + def is_null(self, column: core.Column) -> Predicate: + return lambda row: row[column.field.name] is None + + def is_empty(self, column: core.Column) -> Predicate: + return lambda row: row[column.field.name] == "" + + def compare( + self, column: core.Column, op: CompareOperator, value: Any + ) -> Predicate: + name = column.field.name + return lambda row: _OPERATORS[op](row[name], value) + + def compare_text( + self, column: core.Column, op: CompareOperator, value: str + ) -> Predicate: + name = column.field.name + binding = column.binding + right = binding.comparable(value, self.policy) + return lambda row: _OPERATORS[op]( + binding.comparable(row[name], self.policy), right + ) + + def compare_key(self, column: core.Column, value: Any) -> Predicate | None: + if not value.isdecimal() or str(int(value)) != value: + return None + + name = column.field.name + return lambda row: row[name] == int(value) + + def exists( + self, + collection: core.Collection, + build: Callable[[Any], Predicate] | None = None, + ) -> Predicate: + matches = self.true() if build is None else build(self) + return lambda row: any(matches(entry) for entry in related(collection, row)) + + +class FakeStorage(ScimStorage): + """Store the resources in the rows of tables, through the mapping core.""" + + supports_cursors = False + + def __init__( + self, + mappings: Mapping[str, FakeMapping], + provider: ScimProvider, + *, + version_key: bytes | None = None, + ) -> None: + self.mappings = dict(mappings) + self.provider = provider + self.version_key = version_key + self.policy = provider.policy + self.conditions = FakePredicates(self.policy) + self.endpoints = { + str(resource_type.name): str(resource_type.endpoint).strip("/") + for resource_type in provider.resource_types + } + links = [mapping._targets(self.mappings) for mapping in self.mappings.values()] + for mapping, targets in zip(self.mappings.values(), links, strict=True): + mapping._bind(targets) + + def _to_scim( + self, + resource_type: ResourceType, + row: Row, + parameters: ResponseParameters[Any] | None = None, + ) -> Resource[Any]: + mapping = self.mappings[str(resource_type.name)] + return conversion.to_scim( + mapping, + row, + str(resource_type.name), + self.provider.model_for(resource_type), + self.endpoints, + mapping._returned_collections(parameters), + self.version_key, + ) + + def _with_id(self, mapping: FakeMapping, resource_id: str) -> Predicate: + return compare( + mapping, + self.conditions, + self.policy, + mapping._id, + CompareOperator.eq, + resource_id, + ) + + def _find(self, mapping: FakeMapping, condition: Predicate) -> list[Row]: + return [row for row in mapping.record.rows.values() if condition(row)] + + def _load(self, resource_type: ResourceType, resource_id: str) -> Row: + mapping = self.mappings[str(resource_type.name)] + found = self._find(mapping, self._with_id(mapping, resource_id)) + if not found: + raise NotFoundException(detail=f"{resource_id!r} not found") + + return found[0] + + def get( + self, + resource_type: ResourceType, + resource_id: str, + *, + response_parameters: ResponseParameters[Any] | None = None, + ) -> Resource[Any]: + row = self._load(resource_type, resource_id) + return self._to_scim(resource_type, row, response_parameters) + + def search( + self, + resource_types: list[ResourceType], + search_request: SearchRequest[Any], + *, + position: Any = None, + ) -> SearchPage: + (resource_type,) = resource_types + mapping = self.mappings[str(resource_type.name)] + condition = where(mapping, search_request, self.conditions, self.policy) + rows = self._sort(mapping, search_request, self._find(mapping, condition)) + start = search_request.start_index_0 or 0 + stop = None if search_request.count is None else start + search_request.count + resources = [ + self._to_scim(resource_type, row, search_request) + for row in rows[start:stop] + ] + return SearchPage(len(rows), resources) + + def _sort( + self, mapping: FakeMapping, search_request: SearchRequest[Any], rows: list[Row] + ) -> list[Row]: + """Sort as SQL does: the rows without value last when ascending, first when descending.""" + target = sort_target(mapping, search_request) + if target is None: + return rows + + collection, column = target + keyed = [ + (self._sort_value(mapping, collection, column, row), row) for row in rows + ] + present = [(value, row) for value, row in keyed if value is not None] + missing = [row for value, row in keyed if value is None] + descending = search_request.sort_order == SearchRequest.SortOrder.descending + present.sort(key=operator.itemgetter(0), reverse=descending) + ordered = [row for _, row in present] + return [*missing, *ordered] if descending else [*ordered, *missing] + + def _sort_value( + self, + mapping: FakeMapping, + collection: core.Collection | None, + column: core.Column, + row: Row, + ) -> Any: + """Return the value of the row, or of its primary entry, or else of its first one. + + A constant is the value of the entry holding it, when the entry exists. + """ + if column.is_constant: + holder = entry_present(self.conditions, mapping._entry_of(column)) + value = column.constant if holder(row) else None + return self._sort_key(column, value) + + if collection is not None: + entries = related(collection, row) + entries.sort(key=lambda entry: entry.get("primary") is not True) + + if not entries: + return None + + row = entries[0] + + return self._sort_key(column, row[column.field.name]) + + def _sort_key(self, column: core.Column, value: Any) -> Any: + if value is None or not column.is_string: + return value + + return column.binding.comparable(value, self.policy) + + def create( + self, resource_type: ResourceType, resource: Resource[Any] + ) -> Resource[Any]: + mapping = self.mappings[str(resource_type.name)] + conversion.check_storable(mapping, resource, None) + self._check_uniqueness(mapping, resource, None) + links = self._links(mapping, resource) + row = mapping.record.new() + self._write(mapping, resource, row, links, creating=True) + return self._to_scim(resource_type, row) + + def update( + self, + resource_type: ResourceType, + resource: Resource[Any], + *, + expected_version: str | None = None, + ) -> Resource[Any]: + mapping = self.mappings[str(resource_type.name)] + row = self._load(resource_type, str(resource.id)) + stored = self._to_scim(resource_type, row) + _check_version(stored, expected_version) + conversion.check_storable(mapping, resource, stored) + self._check_uniqueness(mapping, resource, stored) + links = self._links(mapping, resource) + if mapping.version is not None: + row[mapping.version.name] += 1 + + self._write(mapping, resource, row, links, creating=False) + return self._to_scim(resource_type, row) + + def delete( + self, + resource_type: ResourceType, + resource_id: str, + *, + expected_version: str | None = None, + ) -> None: + mapping = self.mappings[str(resource_type.name)] + row = self._load(resource_type, resource_id) + _check_version(self._to_scim(resource_type, row), expected_version) + del mapping.record.rows[row["id"]] + + def _write( + self, + mapping: FakeMapping, + resource: Resource[Any], + row: Row, + links: dict[core.Collection, list[Row]], + creating: bool, + ) -> None: + now = datetime.datetime.now(datetime.UTC) + for column, value in [ + *conversion.write_plan(mapping, resource, row, creating), + *conversion.dates(mapping, now, creating), + ]: + row[column.field.name] = as_stored(value) + + if creating: + mapping.record.insert(row) + + for collection in mapping._all_collections(): + if collection.writable: + self._write_collection(collection, resource, row, links) + + def _write_collection( + self, + collection: core.Collection, + resource: Resource[Any], + row: Row, + links: dict[core.Collection, list[Row]], + ) -> None: + relation = collection.relation + if isinstance(relation, Reference): + linked = links[collection] + row[relation.field.name] = linked[0]["id"] if linked else None + return + + if isinstance(relation, References): + row[relation.field.name] = [linked["id"] for linked in links[collection]] + return + + for entry in related(collection, row): + del relation.target.rows[entry["id"]] + + for entry in conversion.entries(collection, resource): + entry_row = relation.target.new() + entry_row[relation.key] = row["id"] + for name, column in collection.columns.items(): + value = entry + if name is not None: + value = getattr(entry, column.binding.target_field_name) + + entry_row[column.field.name] = as_stored(value) + + relation.target.insert(entry_row) + + def _check_uniqueness( + self, + mapping: FakeMapping, + resource: Resource[Any], + stored: Resource[Any] | None, + ) -> None: + others = self.conditions.true() + if stored is not None: + others = self.conditions.negate(self._with_id(mapping, str(stored.id))) + + for column in mapping._unique_columns(): + value = Path(column.binding.urn).get(resource, strict=False) + current = None + if stored is not None: + current = Path(column.binding.urn).get(stored, strict=False) + + if value is None or conversion.comparable(value) == conversion.comparable( + current + ): + continue + + taken = compare( + mapping, self.conditions, self.policy, column, CompareOperator.eq, value + ) + if self._find(mapping, self.conditions.all([others, taken])): + raise UniquenessException + + def _links( + self, mapping: FakeMapping, resource: Resource[Any] + ) -> dict[core.Collection, list[Row]]: + links: dict[core.Collection, list[Row]] = {} + for collections, entries in conversion.link_entries(mapping, resource): + found = [ + (collection, self._linked_rows(collection, entries)) + for collection in collections + ] + links |= conversion.assign_links(found, entries, self.policy) + + return links + + def _linked_rows( + self, collection: core.Collection, entries: list[Any] + ) -> list[Row]: + target: FakeMapping = collection.target + condition = self.conditions.any( + self._with_id(target, entry.value) for entry in entries + ) + return self._find(target, condition) + + +def _check_version(stored: Resource[Any], expected_version: str | None) -> None: + if expected_version is not None and stored.meta.version != expected_version: + raise PreconditionFailedException diff --git a/tests/mapping/conftest.py b/tests/mapping/conftest.py new file mode 100644 index 0000000..126a83f --- /dev/null +++ b/tests/mapping/conftest.py @@ -0,0 +1,65 @@ +import pytest +from scim2_models import ScimProvider + +from scim2_server.mapping import Link +from scim2_server.utils import load_default_provider + +from .backend import FakeStorage +from .backend import Reference +from .pets import PET_TABLES +from .pets import Pet +from .pets import pets +from .pets import pets_mapping +from .tables import TABLES +from .tables import groups_mapping +from .tables import users_mapping + + +@pytest.fixture(autouse=True) +def empty_tables(): + for table in (*TABLES, *PET_TABLES): + table.rows.clear() + table.next_key = 1 + + +@pytest.fixture +def users_storage(): + provider = load_default_provider() + storage = FakeStorage( + {"User": users_mapping(), "Group": groups_mapping()}, provider + ) + user_type, group_type = ( + next(rt for rt in provider.resource_types if rt.id == name) + for name in ("User", "Group") + ) + model = provider.model_for(user_type) + alice = storage.create(user_type, model(user_name="alice")) + bob = storage.create(user_type, model(user_name="bob")) + group_model = provider.model_for(group_type) + admins = storage.create( + group_type, + group_model( + display_name="admins", members=[{"value": alice.id, "type": "User"}] + ), + ) + storage.create( + group_type, + group_model( + display_name="staff", + members=[{"value": bob.id}, {"value": admins.id, "type": "Group"}], + ), + ) + return storage, user_type, group_type + + +@pytest.fixture +def pets_storage(): + provider = ScimProvider(models=[Pet]) + owner = Link(Reference(pets.fields["parent"], pets), "Pet") + mappings = {"Pet": pets_mapping(changes={"owner": owner})} + storage = FakeStorage(mappings, provider, version_key=b"secret") + (pet_type,) = provider.resource_types + rex = storage.create(pet_type, Pet(name="rex", tags=["Big", "brown"])) + storage.create(pet_type, Pet(name="tom", tags=["small"], owner={"value": rex.id})) + storage.create(pet_type, Pet(name="kit")) + return storage, pet_type diff --git a/tests/mapping/pets.py b/tests/mapping/pets.py new file mode 100644 index 0000000..1f9b879 --- /dev/null +++ b/tests/mapping/pets.py @@ -0,0 +1,81 @@ +"""A resource with what users and groups lack: a multi-valued simple attribute, a required single link, a required extension.""" + +from typing import Annotated + +from scim2_models import URN +from scim2_models import ComplexAttribute +from scim2_models import Extension +from scim2_models import Mutability +from scim2_models import Required +from scim2_models import Resource +from scim2_models import Returned + +from scim2_server.mapping import Link +from scim2_server.mapping import Many + +from .backend import FakeMapping +from .backend import Owned +from .backend import Reference +from .backend import Table + + +class Owner(ComplexAttribute): + value: str | None = None + display: str | None = None + aliases: list[str] | None = None + + +class Secret(ComplexAttribute): + value: Annotated[str | None, Mutability.write_only] = None + + +class Vault(ComplexAttribute): + code: Annotated[str | None, Returned.never] = None + + +class Keeper(Extension): + __schema__ = URN("urn:example:2.0:Keeper") + keeper: Annotated[Owner | None, Required.true] = None + + +class Pet(Resource): + __schema__ = URN("urn:example:2.0:Pet") + name: str | None = None + tags: list[str] | None = None + owner: Annotated[Owner | None, Required.true] = None + secrets: list[Secret] | None = None + vault: Vault | None = None + safe: Annotated[Vault | None, Mutability.immutable] = None + + +pets = Table("pets") +pets.field("name") +pets.field("code") +pets.field("parent") +pets.field("owner", null=False) +pets.field("keeper", null=False, default=0) + +tags = Table("tags") +tags.field("pet", null=False) +tags.field("value") +tags.field("label", null=False) + +secrets = Table("secrets") +secrets.field("pet", null=False) +secrets.field("value") + +PET_TABLES = (pets, tags, secrets) + + +def pets_mapping(model=Pet, changes=None, **options): + attributes = { + "id": pets.id, + "name": pets.fields["name"], + "tags": Many(Owned(tags, "pet"), tags.fields["value"]), + "owner": Link(Reference(pets.fields["owner"], pets), "Pet"), + } + attributes |= changes or {} + attributes = { + path: value for path, value in attributes.items() if value is not None + } + return FakeMapping(model, pets, attributes, **options) diff --git a/tests/mapping/policy.py b/tests/mapping/policy.py new file mode 100644 index 0000000..e355f90 --- /dev/null +++ b/tests/mapping/policy.py @@ -0,0 +1,12 @@ +from scim2_models import ScimPolicy + + +def refuse_exclamation_marks(binding, value): + if "!" in value: + raise ValueError("The policy cannot prepare this string") + + return value.lower() + + +REFUSING = ScimPolicy(comparison_key=refuse_exclamation_marks) +"""A policy that cannot prepare the strings holding an exclamation mark.""" diff --git a/tests/mapping/tables.py b/tests/mapping/tables.py new file mode 100644 index 0000000..0d785a4 --- /dev/null +++ b/tests/mapping/tables.py @@ -0,0 +1,135 @@ +from scim2_models import EnterpriseUser +from scim2_models import Group +from scim2_models import User + +from scim2_server.mapping import Entry +from scim2_server.mapping import Link +from scim2_server.mapping import Many + +from .backend import FakeMapping +from .backend import Owned +from .backend import Reference +from .backend import References +from .backend import Referrers +from .backend import Table + +ENTERPRISE = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User" + +users = Table("users") +for name in ( + "external_id", + "display_name", + "title", + "nick_name", + "user_type", + "preferred_language", + "given_name", + "family_name", + "password", + "email", + "employee_number", +): + users.field(name) +users.field("user_name", null=False) +users.field("active") +users.field("manager") +users.field("created") +users.field("last_modified") +users.field("version", null=False, default=1) +users.field("code", null=False, default="none") +users.field("phone") + +emails = Table("emails") +emails.field("user", null=False) +emails.field("value") +emails.field("type", choices=["work", "home", "other"]) +emails.field("primary") +emails.field("address", null=False) + +groups = Table("groups") +groups.field("external_id") +groups.field("display_name") +groups.field("members") +groups.field("nested") +groups.field("created") +groups.field("last_modified") +groups.field("version", null=False, default=1) + +TABLES = (users, emails, groups) + +DEFAULT = object() + + +def users_mapping(changes=None, version=DEFAULT, **options): + """Return a new mapping of the users, with some paths changed, or removed when None.""" + fields = users.fields + attributes = { + "id": users.id, + "externalId": fields["external_id"], + "userName": fields["user_name"], + "displayName": fields["display_name"], + "title": fields["title"], + "userType": fields["user_type"], + "nickName": fields["nick_name"], + "preferredLanguage": fields["preferred_language"], + "name.givenName": fields["given_name"], + "name.familyName": fields["family_name"], + "active": fields["active"], + "password": fields["password"], + "emails": Many( + Owned(emails, "user"), + { + "value": emails.fields["value"], + "type": emails.fields["type"], + "primary": emails.fields["primary"], + }, + ), + "groups": Link(Referrers(groups.fields["members"]), "Group", type="direct"), + f"{ENTERPRISE}:employeeNumber": fields["employee_number"], + f"{ENTERPRISE}:manager": Link(Reference(fields["manager"], users), "User"), + "meta.created": fields["created"], + "meta.lastModified": fields["last_modified"], + } + attributes |= changes or {} + attributes = { + path: value for path, value in attributes.items() if value is not None + } + return FakeMapping( + User[EnterpriseUser], + users, + attributes, + version=fields["version"] if version is DEFAULT else version, + **options, + ) + + +def groups_mapping(changes=None, version=DEFAULT, **options): + fields = groups.fields + attributes = { + "id": groups.id, + "externalId": fields["external_id"], + "displayName": fields["display_name"], + "members": [ + Link(References(fields["members"], users), "User", type="User"), + Link(References(fields["nested"], groups), "Group", type="Group"), + ], + "meta.created": fields["created"], + "meta.lastModified": fields["last_modified"], + } + attributes |= changes or {} + attributes = { + path: value for path, value in attributes.items() if value is not None + } + return FakeMapping( + Group, + groups, + attributes, + version=fields["version"] if version is DEFAULT else version, + **options, + ) + + +WORK_EMAIL = { + "emails": Entry({"value": users.fields["email"]}, type="work", primary=True) +} +UNDATED = {"meta.created": None, "meta.lastModified": None} diff --git a/tests/mapping/test_contract.py b/tests/mapping/test_contract.py new file mode 100644 index 0000000..20bfad6 --- /dev/null +++ b/tests/mapping/test_contract.py @@ -0,0 +1,58 @@ +import pytest + +from scim2_server.testing import ScimStorageContract + +from .backend import FakeStorage +from .tables import UNDATED +from .tables import WORK_EMAIL +from .tables import groups_mapping +from .tables import users_mapping + + +def one_work_email(user): + emails = user.get("emails") + if not emails: + return user + + return user | {"emails": [{"value": emails[-1]["value"], "type": "work"}]} + + +class TestMappedStorage(ScimStorageContract): + """Users and groups with a version counter and dates.""" + + supports_root_search = False + + @pytest.fixture + def storage(self, provider): + mappings = {"User": users_mapping(), "Group": groups_mapping()} + return FakeStorage(mappings, provider) + + +class TestMappedStorageWithHashes(ScimStorageContract): + """Resources without counter nor dates get the hash of their values as version.""" + + supports_root_search = False + stores_created = False + stores_last_modified = False + + @pytest.fixture + def storage(self, provider): + mappings = { + "User": users_mapping(UNDATED, version=None), + "Group": groups_mapping(UNDATED, version=None), + } + return FakeStorage(mappings, provider, version_key=b"secret") + + +class TestMappedStorageWithAnEntry(ScimStorageContract): + """The emails of the users are a work email, held by the user record.""" + + supports_root_search = False + + def search_users(self): + return [one_work_email(user) for user in super().search_users()] + + @pytest.fixture + def storage(self, provider): + mappings = {"User": users_mapping(WORK_EMAIL), "Group": groups_mapping()} + return FakeStorage(mappings, provider) diff --git a/tests/mapping/test_conversion.py b/tests/mapping/test_conversion.py new file mode 100644 index 0000000..40f26fb --- /dev/null +++ b/tests/mapping/test_conversion.py @@ -0,0 +1,270 @@ +import pytest +from scim2_models import InvalidValueException +from scim2_models import MutabilityException +from scim2_models import SearchRequest + +from scim2_server.mapping import Attribute +from scim2_server.mapping import Entry +from scim2_server.mapping import Many +from scim2_server.utils import load_default_provider + +from .backend import FakeStorage +from .backend import Owned +from .pets import tags +from .policy import REFUSING +from .tables import UNDATED +from .tables import WORK_EMAIL +from .tables import emails +from .tables import groups_mapping +from .tables import users +from .tables import users_mapping + + +@pytest.fixture +def provider(): + return load_default_provider() + + +@pytest.fixture +def user_type(provider): + return next(rt for rt in provider.resource_types if rt.id == "User") + + +@pytest.fixture +def group_type(provider): + return next(rt for rt in provider.resource_types if rt.id == "Group") + + +@pytest.fixture +def User(provider, user_type): + return provider.model_for(user_type) + + +@pytest.fixture +def Group(provider, group_type): + return provider.model_for(group_type) + + +def storage_of(provider, changes=None, **options): + mappings = {"User": users_mapping(changes, **options), "Group": groups_mapping()} + return FakeStorage(mappings, provider) + + +def test_a_resource_without_counter_needs_a_version_key(provider, user_type, User): + """Without a counter, the version is a hash, which needs a key.""" + storage = storage_of(provider, UNDATED, version=None) + + with pytest.raises(ValueError, match="has no counter, and needs a version key"): + storage.create(user_type, User(user_name="alice")) + + +def test_a_read_only_value_cannot_change(provider, user_type, User): + """A client cannot change the nickname the storage only reads.""" + nick_name = Attribute(users.fields["nick_name"], writable=False) + storage = storage_of(provider, {"nickName": nick_name}) + alice = storage.create(user_type, User(user_name="alice")) + + with pytest.raises(MutabilityException, match="nickName' is read-only"): + storage.update(user_type, User(id=alice.id, user_name="alice", nick_name="al")) + + +def test_a_read_only_value_left_as_it_is_is_accepted(provider, user_type, User): + """A client may send back the read-only nickname it read.""" + nick_name = Attribute(users.fields["nick_name"], writable=False) + storage = storage_of(provider, {"nickName": nick_name}) + alice = storage.create(user_type, User(user_name="alice")) + users.rows[int(alice.id)]["nick_name"] = "al" + + updated = storage.update( + user_type, User(id=alice.id, user_name="alice", nick_name="al") + ) + + assert updated.nick_name == "al" + + +def test_a_value_the_mapping_does_not_store_is_refused(provider, user_type, User): + """A title would be lost, so it is refused rather than ignored.""" + storage = storage_of(provider, {"title": None}) + + with pytest.raises(InvalidValueException, match="title' is not stored"): + storage.create(user_type, User(user_name="alice", title="boss")) + + +def test_a_value_whose_field_needs_one_is_required(provider, user_type, User): + """A new record cannot be created without a value for a field without null.""" + storage = storage_of(provider, {"title": users.fields["user_name"]}) + + with pytest.raises(InvalidValueException, match="title' is required"): + storage.create(user_type, User(user_name="alice")) + + +def test_a_value_whose_field_has_no_null_cannot_be_removed(provider, user_type, User): + """The field has a default but no null, so the title cannot be emptied.""" + storage = storage_of(provider, {"title": users.fields["code"]}) + alice = storage.create(user_type, User(user_name="alice", title="boss")) + + with pytest.raises(MutabilityException, match="title' cannot be removed"): + storage.update(user_type, User(id=alice.id, user_name="alice")) + + +def test_an_entry_needs_the_values_its_fields_need(provider, user_type, User): + """An email without address would fail in the database.""" + many = Many( + Owned(emails, "user"), + {"value": emails.fields["address"], "type": emails.fields["type"]}, + ) + storage = storage_of(provider, {"emails": many}) + + with pytest.raises(InvalidValueException, match="emails.value' is required"): + storage.create(user_type, User(user_name="alice", emails=[{"type": "work"}])) + + +def test_an_entry_holds_one_entry_at_most(provider, user_type, User): + """The record has room for one email.""" + storage = storage_of(provider, WORK_EMAIL) + two = [{"value": "a@example.com"}, {"value": "b@example.com"}] + + with pytest.raises(InvalidValueException, match="holds one entry at most"): + storage.create(user_type, User(user_name="alice", emails=two)) + + +def test_an_entry_holds_its_constants(provider, user_type, User): + """The email of the record is always the work one.""" + storage = storage_of(provider, WORK_EMAIL) + home = [{"value": "a@example.com", "type": "home"}] + + with pytest.raises(InvalidValueException, match="emails.type' can only be 'work'"): + storage.create(user_type, User(user_name="alice", emails=home)) + + +def test_an_entry_takes_its_constants_in_any_case(provider, user_type, User): + """The type is compared without its case, and any primary is read back as true.""" + storage = storage_of(provider, WORK_EMAIL) + work = [{"value": "a@example.com", "type": "WORK", "primary": False}] + + alice = storage.create(user_type, User(user_name="alice", emails=work)) + + assert [(e.type, e.primary) for e in alice.emails] == [("work", True)] + + +def test_a_value_out_of_the_choices_of_its_field_is_refused(provider, user_type, User): + """The resources of the server are of the model of the provider, not of the mapping.""" + storage = storage_of(provider) + pager = [{"value": "a@example.com", "type": "pager"}] + + with pytest.raises(InvalidValueException, match="cannot hold 'pager'"): + storage.create(user_type, User(user_name="alice", emails=pager)) + + +def test_written_entries_replace_the_former_ones(provider, user_type, User): + """The former email records are deleted.""" + storage = storage_of(provider) + alice = storage.create( + user_type, User(user_name="alice", emails=[{"value": "a@example.com"}]) + ) + + updated = storage.update( + user_type, + User(id=alice.id, user_name="alice", emails=[{"value": "b@example.com"}]), + ) + + assert [e.value for e in updated.emails] == ["b@example.com"] + assert len(emails.rows) == 1 + + +@pytest.fixture +def people(provider, user_type, User): + storage = storage_of(provider) + for name in ("alice", "bob", "carol"): + storage.create(user_type, User(user_name=name)) + return storage + + +def test_a_link_entry_needs_a_value(people, group_type, Group): + """A member with a display only cannot be stored.""" + with pytest.raises( + InvalidValueException, match="members' holds an entry without value" + ): + people.create(group_type, Group(display_name="x", members=[{"display": "x"}])) + + +def test_a_link_to_an_unknown_resource_is_refused(people, group_type, Group): + """No user nor group has this identifier.""" + with pytest.raises(InvalidValueException, match="links to an unknown resource"): + people.create(group_type, Group(display_name="x", members=[{"value": "9"}])) + + +def test_a_link_entry_links_to_a_resource_of_its_type(people, group_type, Group): + """Carol is a user, and no group has her identifier.""" + member = {"value": "3", "type": "Group"} + + with pytest.raises( + InvalidValueException, match="links to '3', which is not of type 'Group'" + ): + people.create(group_type, Group(display_name="x", members=[member])) + + +def test_a_link_entry_with_a_type_the_policy_cannot_prepare_links_to_nothing( + people, group_type, Group +): + """The type cannot be compared, so it matches no Link.""" + people.policy = REFUSING + member = {"value": "3", "type": "User!"} + + with pytest.raises(InvalidValueException, match="which is not of type 'User!'"): + people.create(group_type, Group(display_name="x", members=[member])) + + +def test_a_resource_linked_twice_is_linked_once(people, group_type, Group): + """A member sent twice is stored once.""" + member = {"value": "3", "type": "User"} + + group = people.create(group_type, Group(display_name="x", members=[member, member])) + + assert [m.value for m in group.members] == ["3"] + + +def test_an_entry_of_a_simple_attribute_without_value_is_not_read(pets_storage): + """A tag row without value, written by another application, is left out.""" + storage, pet_type = pets_storage + tags.rows[99] = {"id": 99, "pet": 3, "value": None, "label": None} + + kit = storage.get(pet_type, "3") + + assert kit.tags is None + + +def test_a_string_compares_without_case_unless_case_exact(): + """The externalId is case exact, and active is not a string.""" + mapping = users_mapping() + + assert mapping._column("userName").casefolded + assert not mapping._column("externalId").casefolded + assert not mapping._column("active").casefolded + + +def test_the_string_columns_hold_the_strings_of_the_record_and_of_the_entries(): + """A SQL key function needs the strings of the record and of the entries.""" + urns = { + column.binding.urn.rsplit(":", 1)[-1] + for column in users_mapping()._string_columns() + } + + assert "User:userName" in urns or "userName" in urns + assert "emails.value" in urns + assert "active" not in urns + assert "emails.primary" not in urns + + +def test_a_constant_is_found_among_several_entries(provider, user_type, User): + """The type of the phone number is the one of its Entry, not of the email one.""" + phone = Entry({"value": users.fields["phone"]}, type="work") + storage = storage_of(provider, WORK_EMAIL | {"phoneNumbers": phone}) + storage.create(user_type, User(user_name="alice", phone_numbers=[{"value": "1"}])) + storage.create(user_type, User(user_name="bob")) + + page = storage.search( + [user_type], SearchRequest(filter='phoneNumbers.type eq "work"') + ) + + assert [user.user_name for user in page.resources] == ["alice"] diff --git a/tests/mapping/test_declaration.py b/tests/mapping/test_declaration.py new file mode 100644 index 0000000..b1edf3a --- /dev/null +++ b/tests/mapping/test_declaration.py @@ -0,0 +1,267 @@ +import re + +import pytest +from scim2_models import User + +from scim2_server.mapping import Attribute +from scim2_server.mapping import Entry +from scim2_server.mapping import Link +from scim2_server.mapping import Many + +from .backend import FakeMapping +from .backend import Owned +from .backend import Reference +from .backend import References +from .pets import Pet +from .pets import pets +from .pets import pets_mapping +from .pets import secrets +from .pets import tags +from .tables import ENTERPRISE +from .tables import emails +from .tables import groups +from .tables import groups_mapping +from .tables import users +from .tables import users_mapping + +TITLE = users.fields["title"] +EMAILS = Owned(emails, "user") +MANAGER = Reference(users.fields["manager"], users) + + +def refused(message, changes, mapping=users_mapping): + with pytest.raises(ValueError, match=re.escape(message)): + mapping(changes=changes, resolve=False) + + +def test_a_mapping_shows_its_model(): + """The representation names the model of the resources.""" + assert repr(users_mapping()) == "" + + +def test_two_paths_to_the_same_attribute_are_refused(): + """Paths ignore the case, so both map userName.""" + refused("'userName' and 'username' map the same attribute", {"username": TITLE}) + + +def test_a_path_and_one_of_its_sub_attributes_are_refused(): + """name.givenName is already mapped, so name cannot be.""" + refused("'name.givenName' and 'name' map the same attribute", {"name": TITLE}) + + +def test_a_mapping_needs_the_identifier(): + """A resource cannot be found again without its id.""" + refused("The mapping of User[EnterpriseUser] needs 'id'", {"id": None}) + + +def test_a_path_out_of_the_model_is_refused(): + """A typo in a path raises when the mapping is created.""" + refused("'nickname.first' is not an attribute of", {"nickname.first": TITLE}) + + +def test_a_link_needs_a_complex_attribute(): + """A title holds no value nor $ref.""" + refused("'title' is not a complex attribute", {"title": Link(MANAGER, "User")}) + + +def test_a_single_link_holds_one_resource_type(): + """The manager holds one value, so it links to one resource type.""" + links = [Link(MANAGER, "User"), Link(MANAGER, "Group")] + refused( + "holds one value, so it is mapped to one Link", {f"{ENTERPRISE}:manager": links} + ) + + +def test_a_complex_attribute_needs_many_link_or_its_sub_attributes(): + """One target cannot hold the whole name.""" + changes = {"name.givenName": None, "name.familyName": None, "name": TITLE} + refused("'name' holds several values or sub-attributes", changes) + + +def test_a_multi_valued_attribute_needs_many_or_link(): + """One target cannot hold several emails.""" + refused("'emails' holds several values or sub-attributes", {"emails": TITLE}) + + +def test_a_value_the_backend_cannot_map_is_refused(): + """An integer is not a field of the backend.""" + refused("'title' cannot be mapped to 42", {"title": 42}) + + +def test_an_attribute_clients_neither_read_nor_write_is_refused(): + """The password is write-only, so a read-only one would be useless.""" + password = Attribute(users.fields["password"], writable=False) + refused("Clients could neither read nor write 'password'", {"password": password}) + + +def test_a_multi_valued_sub_attribute_of_a_complex_attribute_is_refused(): + """One field cannot hold the aliases of an owner.""" + changes = {"owner": None, "owner.aliases": pets.fields["name"]} + refused( + "'owner.aliases' holds several values in a complex attribute", + changes, + pets_mapping, + ) + + +def test_many_needs_a_multi_valued_attribute(): + """A title holds a single value.""" + refused( + "'title' is not a multi-valued simple attribute", {"title": Many(EMAILS, TITLE)} + ) + + +def test_many_of_one_target_needs_a_simple_attribute(): + """Emails have sub-attributes, so each needs its own target.""" + refused( + "'emails' is not a multi-valued simple attribute", + {"emails": Many(EMAILS, emails.fields["value"])}, + ) + + +def test_many_of_sub_attributes_needs_a_complex_attribute(): + """Tags are strings, which have no value sub-attribute.""" + refused( + "'tags' is not a multi-valued complex attribute", + {"tags": Many(Owned(tags, "pet"), {"value": tags.fields["value"]})}, + pets_mapping, + ) + + +def test_many_maps_a_simple_attribute_to_a_target(): + """An integer is not a field of the backend.""" + refused( + "'tags' cannot be mapped to 42", + {"tags": Many(Owned(tags, "pet"), 42)}, + pets_mapping, + ) + + +def test_many_refuses_two_paths_to_the_same_sub_attribute(): + """Paths ignore the case, so both map emails.value.""" + many = Many( + EMAILS, {"value": emails.fields["value"], "VALUE": emails.fields["type"]} + ) + refused( + "'emails.value' and 'emails.VALUE' map the same attribute", {"emails": many} + ) + + +def test_many_refuses_a_path_out_of_the_attribute(): + """Emails have no nope sub-attribute.""" + many = Many(EMAILS, {"nope": emails.fields["value"]}) + refused("'emails.nope' is not an attribute of", {"emails": many}) + + +def test_many_maps_each_sub_attribute_to_a_target(): + """An integer is not a field of the backend.""" + refused( + "'emails.value' cannot be mapped to 42", {"emails": Many(EMAILS, {"value": 42})} + ) + + +def test_entry_needs_a_multi_valued_complex_attribute(): + """A name holds no list of entries.""" + changes = {"name.givenName": None, "name.familyName": None} + changes["name"] = Entry({"givenName": TITLE}) + refused("'name' is not a multi-valued complex attribute", changes) + + +def test_entry_needs_a_sub_attribute(): + """An entry without field would never exist.""" + refused("The Entry of 'emails' maps no sub-attribute", {"emails": Entry({})}) + + +def test_entry_maps_each_sub_attribute_to_a_target(): + """An integer is not a field of the backend.""" + refused("'emails.value' cannot be mapped to 42", {"emails": Entry({"value": 42})}) + + +def test_entry_cannot_give_a_sub_attribute_it_maps(): + """The type cannot be both a field and a constant.""" + entry = Entry({"type": users.fields["email"]}, type="work") + refused( + "The Entry of 'emails' gives 'type', which is not a sub-attribute it leaves unmapped", + {"emails": entry}, + ) + + +def test_entry_cannot_give_a_sub_attribute_the_attribute_lacks(): + """Secrets have no type sub-attribute.""" + entry = Entry({"value": secrets.fields["value"]}, type="work") + refused("The Entry of 'secrets' gives 'type'", {"secrets": entry}, pets_mapping) + + +def test_a_multi_valued_link_needs_a_link(): + """An empty list of Links maps nothing.""" + refused( + "'groups' needs one Link per resource type, and at least one", {"groups": []} + ) + + +def test_links_need_distinct_resource_types(): + """The storage could not tell which Link a member belongs to.""" + links = [Link(References(groups.fields["members"], users), "User")] * 2 + refused( + "'members' needs one Link per resource type", {"members": links}, groups_mapping + ) + + +def test_links_all_have_a_type_or_none(): + """A member without type could not be told apart.""" + links = [ + Link(References(groups.fields["members"], users), "User", type="User"), + Link(References(groups.fields["nested"], groups), "Group"), + ] + refused( + "Either every Link of 'members' has a type, or none", + {"members": links}, + groups_mapping, + ) + + +def test_a_typed_link_needs_a_type_sub_attribute(): + """The manager has no type sub-attribute to hold the type.""" + link = Link(MANAGER, "User", type="boss") + refused( + f"'{ENTERPRISE}:manager' has no type sub-attribute", + {f"{ENTERPRISE}:manager": link}, + ) + + +def test_an_attribute_needs_a_target_of_the_backend(): + """A string is not a field of this backend.""" + refused("'title' cannot be mapped to", {"title": Attribute("title")}) + + +def test_the_backend_checks_each_value_with_its_holder(): + """The backend gets the values of the record, of a Many and of an Entry.""" + checked = [] + + class Checking(FakeMapping): + def _check_declared(self, path, binding, value, holder): + checked.append((path, type(holder).__name__)) + + many = Many(Owned(tags, "pet"), tags.fields["value"]) + entry = Entry({"value": pets.fields["code"]}) + Checking( + Pet, + pets, + {"id": pets.id, "name": pets.fields["name"], "tags": many, "secrets": entry}, + resolve=False, + ) + Checking( + User, + users, + {"id": users.id, "emails": Many(EMAILS, {"value": TITLE})}, + resolve=False, + ) + + assert checked == [ + ("id", "NoneType"), + ("name", "NoneType"), + ("tags", "Many"), + ("secrets.value", "Entry"), + ("id", "NoneType"), + ("emails.value", "Many"), + ] diff --git a/tests/mapping/test_filters.py b/tests/mapping/test_filters.py new file mode 100644 index 0000000..5779205 --- /dev/null +++ b/tests/mapping/test_filters.py @@ -0,0 +1,189 @@ +import pytest +from scim2_models import InvalidFilterException +from scim2_models import ScimFilter +from scim2_models import ScimPolicy +from scim2_models import SearchRequest +from scim2_models import User +from scim2_models.path import CompareOperator + +from scim2_server.mapping.filters import holds +from scim2_server.mapping.filters import where + +from .backend import FakePredicates +from .policy import REFUSING +from .tables import users_mapping + + +def binding(path): + return ScimFilter[User](f"{path} pr").resolve( + ScimFilter[User](f"{path} pr").ast.attr_path + ) + + +@pytest.mark.parametrize( + ("op", "actual", "expected", "result"), + [ + (CompareOperator.eq, None, None, True), + (CompareOperator.eq, "a", None, False), + (CompareOperator.ne, None, "a", True), + (CompareOperator.ne, None, None, False), + (CompareOperator.gt, None, "a", False), + (CompareOperator.eq, "Bob", "bob", True), + (CompareOperator.co, "Bob", "O", True), + (CompareOperator.sw, "Bob", "bo", True), + (CompareOperator.ew, "Bob", "bo", False), + (CompareOperator.ne, "Bob", "bob", False), + (CompareOperator.gt, "Bob", "alice", True), + (CompareOperator.ge, "Bob", "bob", True), + (CompareOperator.lt, "Bob", "alice", False), + (CompareOperator.le, "Bob", "bob", True), + ], +) +def test_holds_compares_as_the_filter_evaluator(op, actual, expected, result): + """Missing values, substrings and orders follow ScimFilter.match.""" + user_name = binding("userName") + + assert holds(user_name, op, actual, expected, ScimPolicy()) is result + + +def test_holds_finds_no_substring_in_a_value_that_is_not_a_string(): + """A boolean contains nothing.""" + active = binding("active") + + assert not holds(active, CompareOperator.co, True, True, ScimPolicy()) + + +def test_holds_finds_no_order_between_values_of_different_types(): + """A boolean is neither above nor below a string.""" + active = binding("active") + + assert not holds(active, CompareOperator.gt, True, "a", ScimPolicy()) + + +@pytest.mark.parametrize( + ("op", "result"), [(CompareOperator.eq, False), (CompareOperator.ne, True)] +) +def test_holds_finds_a_string_the_policy_cannot_prepare_different(op, result): + """Only ne holds against a string the policy refuses.""" + policy = REFUSING + + assert holds(binding("userName"), op, "bob", "bob!", policy) is result + + +def found(storage, resource_type, scim_filter): + """Return the names of the resources a filter finds, checked against the filter evaluator.""" + everything = storage.search([resource_type], SearchRequest()).resources + expected = sorted( + r.id for r in everything if ScimFilter[type(r)](scim_filter).match(r) + ) + page = storage.search([resource_type], SearchRequest(filter=scim_filter)) + assert sorted(r.id for r in page.resources) == expected + return [r.id for r in page.resources] + + +@pytest.mark.parametrize( + "scim_filter", + [ + 'id eq "1"', + 'id ne "1"', + 'id eq "abc"', + 'id ne "abc"', + 'id eq "01"', + 'foo eq "x"', + "foo pr", + 'foo[bar eq "x"]', + 'emails[foo eq "x"]', + 'groups.value eq "1"', + "groups pr", + 'groups.type eq "direct"', + 'groups.type eq "DIRECT"', + 'groups.type ne "direct"', + "groups.type pr", + 'groups[type eq "direct" and value eq "1"]', + 'groups.display eq "admins"', + ], +) +def test_a_filter_on_the_users_finds_what_the_evaluator_finds( + users_storage, scim_filter +): + """Identifiers, unknown attributes and the groups of the users.""" + storage, user_type, _ = users_storage + + found(storage, user_type, scim_filter) + + +@pytest.mark.parametrize( + "scim_filter", + [ + 'members.value eq "1"', + 'members.type eq "Group"', + 'members[type eq "User" and value eq "2"]', + 'members[type eq "Group"]', + "members.type pr", + 'members.display eq "admins"', + 'members ne "1"', + ], +) +def test_a_filter_on_the_groups_finds_what_the_evaluator_finds( + users_storage, scim_filter +): + """Members of two resource types, told apart by their type.""" + storage, _, group_type = users_storage + + found(storage, group_type, scim_filter) + + +@pytest.mark.parametrize( + "scim_filter", + [ + 'password eq "x"', + "password pr", + 'emails.display eq "x"', + "emails.display pr", + "addresses pr", + 'addresses[type eq "work"]', + ], +) +def test_a_filter_on_a_value_the_mapping_does_not_store_is_refused( + users_storage, scim_filter +): + """A hidden or unmapped value cannot be filtered on.""" + storage, user_type, _ = users_storage + + with pytest.raises(InvalidFilterException): + storage.search([user_type], SearchRequest(filter=scim_filter)) + + +@pytest.mark.parametrize( + ("scim_filter", "expected"), + [('userName eq "alice!"', []), ('userName ne "alice!"', ["1", "2"])], +) +def test_a_string_the_policy_cannot_prepare_equals_no_value(scim_filter, expected): + """No user name is equal to it, and every one differs from it.""" + policy = REFUSING + mapping = users_mapping() + condition = where( + mapping, SearchRequest(filter=scim_filter), FakePredicates(policy), policy + ) + rows = [{"id": 1, "user_name": "alice"}, {"id": 2, "user_name": "bob"}] + + assert [str(row["id"]) for row in rows if condition(row)] == expected + + +@pytest.mark.parametrize( + "scim_filter", + [ + 'tags eq "big"', + 'tags ne "big"', + "tags pr", + 'tags[value sw "b"]', + 'tags[display eq "big"]', + 'owner.value eq "1"', + "owner pr", + ], +) +def test_a_filter_on_the_pets_finds_what_the_evaluator_finds(pets_storage, scim_filter): + """Tags are a list of strings, and the owner a single link.""" + storage, pet_type = pets_storage + + found(storage, pet_type, scim_filter) diff --git a/tests/mapping/test_resolution.py b/tests/mapping/test_resolution.py new file mode 100644 index 0000000..4ec62c0 --- /dev/null +++ b/tests/mapping/test_resolution.py @@ -0,0 +1,280 @@ +import re +from typing import Annotated + +import pytest +from scim2_models import Required + +from scim2_server.mapping import Attribute +from scim2_server.mapping import Entry +from scim2_server.mapping import Link +from scim2_server.mapping import Many +from scim2_server.mapping import ResourceMapping +from scim2_server.utils import load_default_provider + +from .backend import FakeStorage +from .backend import Owned +from .backend import Reference +from .backend import References +from .pets import Keeper +from .pets import Pet +from .pets import pets +from .pets import pets_mapping +from .pets import secrets +from .pets import tags +from .tables import ENTERPRISE +from .tables import emails +from .tables import groups +from .tables import groups_mapping +from .tables import users +from .tables import users_mapping + +EMAILS = Owned(emails, "user") +EMAIL = users.fields["email"] + + +def problems(mapping, changes, **options): + resolved = mapping(changes=changes, resolve=False, **options)._resolve() + return [(problem.level, problem.code) for problem in resolved] + + +def collection(mapping, name): + (found,) = [c for c in mapping._all_collections() if c.binding.field_name == name] + return found + + +def storage(**changes): + mappings = { + "User": users_mapping(changes.get("User")), + "Group": groups_mapping(changes.get("Group")), + } + return FakeStorage(mappings, load_default_provider()) + + +def test_the_problems_of_a_mapping_are_built_once(): + """Resolving twice gives the same list.""" + mapping = users_mapping(resolve=False) + + assert mapping._resolve() is mapping._resolve() + + +def test_a_mapping_without_problem_resolves(): + """The users mapping has no error nor warning.""" + assert users_mapping(resolve=False)._resolve() == [] + + +def test_the_errors_stop_the_creation_of_a_mapping(): + """The test backend raises the errors when it creates a mapping.""" + with pytest.raises(ValueError, match="'title' is not mapped to a field of users"): + users_mapping({"title": emails.fields["value"]}) + + +def test_an_error_of_the_backend_is_a_problem(): + """The title is mapped to a field of the emails.""" + assert problems(users_mapping, {"title": emails.fields["value"]}) == [ + ("error", "unknown-field") + ] + + +def test_an_identifier_the_backend_refuses_stops_the_resolution(): + """Without id, the checks of the record cannot run.""" + assert problems(users_mapping, {"id": emails.id}) == [("error", "unknown-field")] + + +def test_a_problem_of_many_is_reported(): + """The relation of the emails is not one the backend accepts.""" + many = Many(users.id, {"value": emails.fields["value"]}) + + assert problems(users_mapping, {"emails": many}) == [("error", "relation-kind")] + + +def test_a_problem_of_a_simple_many_is_reported(): + """The tags are mapped to a field of the pets.""" + changes = {"tags": Many(Owned(tags, "pet"), pets.fields["name"])} + + assert problems(pets_mapping, changes) == [("error", "unknown-field")] + + +def test_a_problem_of_a_sub_attribute_of_many_is_reported(): + """The value of the emails is mapped to a field of the users.""" + changes = {"emails": Many(EMAILS, {"value": users.fields["title"]})} + + assert problems(users_mapping, changes) == [("error", "unknown-field")] + + +def test_entries_cannot_hide_their_values(): + """Each write replaces the entries, and clients never send back the secrets.""" + many = Many(Owned(secrets, "pet"), {"value": secrets.fields["value"]}) + + assert problems(pets_mapping, {"secrets": many}) == [("error", "hidden-in-entries")] + + +def test_written_entries_cannot_hold_a_read_only_value(): + """Each write would lose the read-only type.""" + many = Many( + EMAILS, + { + "value": emails.fields["value"], + "type": Attribute(emails.fields["type"], writable=False), + }, + ) + + assert problems(users_mapping, {"emails": many}) == [ + ("error", "read-only-in-entries") + ] + + +def test_entries_of_read_only_values_are_never_written(): + """Emails the storage only reads are left as they are.""" + many = Many(EMAILS, {"value": Attribute(emails.fields["value"], writable=False)}) + + assert not collection(users_mapping({"emails": many}), "emails").writable + + +def test_a_problem_of_a_sub_attribute_of_an_entry_is_reported(): + """The email is mapped to a field of the emails table.""" + entry = Entry({"value": emails.fields["value"]}) + + assert problems(users_mapping, {"emails": entry}) == [("error", "unknown-field")] + + +def test_the_fields_of_an_entry_need_null(): + """Removing the entry empties its fields.""" + entry = Entry({"value": EMAIL, "display": users.fields["user_name"]}) + + assert problems(users_mapping, {"emails": entry}) == [("error", "entry-fields")] + + +def test_the_fields_of_an_entry_are_read(): + """The entry exists when a field has a value, which clients must read.""" + entry = Entry({"value": pets.fields["name"]}) + + assert problems(pets_mapping, {"secrets": entry}) == [("error", "entry-fields")] + + +def test_the_fields_of_an_entry_are_all_written_or_none(): + """Removing the entry would empty the read-only display.""" + entry = Entry( + {"value": EMAIL, "display": Attribute(users.fields["title"], writable=False)} + ) + + assert problems(users_mapping, {"emails": entry}) == [("error", "entry-fields")] + + +def test_an_entry_of_read_only_values_is_never_written(): + """An email the storage only reads is left as it is.""" + mapping = users_mapping( + {"emails": Entry({"value": Attribute(EMAIL, writable=False)})} + ) + + assert not mapping._entries[(mapping.model, "emails")].writable + + +def test_a_problem_of_a_link_is_reported(): + """The manager holds one value, so it needs a single reference.""" + link = Link(References(users.fields["manager"], users), "User") + + assert problems(users_mapping, {f"{ENTERPRISE}:manager": link}) == [ + ("error", "relation-kind") + ] + + +def test_a_single_link_needs_null(): + """Removing the manager writes no value in its field.""" + link = Link(Reference(users.fields["user_name"], users), "User") + + assert problems(users_mapping, {f"{ENTERPRISE}:manager": link}) == [ + ("error", "single-link-null") + ] + + +def test_a_required_single_link_needs_no_null(): + """Every pet has an owner, so its field needs no null.""" + assert problems(pets_mapping, {}) == [] + + +@pytest.mark.parametrize( + ("model", "expected"), + [ + (Pet[Annotated[Keeper, Required.true]], []), + (Pet[Keeper], [("error", "single-link-null")]), + ], + ids=["required extension", "optional extension"], +) +def test_a_single_link_of_an_extension_needs_null_unless_the_extension_is_required( + model, expected +): + """A pet without the extension has no keeper.""" + keeper = Link(Reference(pets.fields["keeper"], pets), "Pet") + mapping = pets_mapping( + model, {"urn:example:2.0:Keeper:keeper": keeper}, resolve=False + ) + + assert [(p.level, p.code) for p in mapping._resolve()] == expected + + +def test_a_field_needing_a_value_and_never_written_is_a_warning(): + """Creating a user would fail without its user name.""" + assert problems(users_mapping, {"userName": None}) == [("warning", "unwritten")] + + +def test_the_dates_are_written(): + """The storage writes the creation date itself.""" + changes = {"userName": None, "meta.created": users.fields["user_name"]} + + assert problems(users_mapping, changes) == [] + + +def test_the_base_mapping_asks_no_field(): + """A backend gives the fields its records need.""" + assert list(ResourceMapping._fields_needing_value(users_mapping())) == [] + + +def test_a_link_needs_the_mapping_of_its_resource_type(): + """The groups of the users have no mapping.""" + with pytest.raises(ValueError, match="No mapping for the resource type 'Group'"): + FakeStorage({"User": users_mapping()}, load_default_provider()) + + +def test_a_link_cannot_link_to_two_mappings_of_a_resource_type(): + """A mapping serves storages sharing the same mappings.""" + provider = load_default_provider() + mapping = users_mapping() + FakeStorage({"User": mapping, "Group": groups_mapping()}, provider) + + with pytest.raises(ValueError, match="already links to another mapping of 'Group'"): + FakeStorage({"User": mapping, "Group": groups_mapping()}, provider) + + +def test_a_link_links_to_the_records_of_its_target(): + """The members are mapped to groups, but link to users.""" + links = [Link(References(groups.fields["members"], groups), "User")] + + with pytest.raises( + ValueError, + match=re.escape("members' links to other records than those of the mapping"), + ): + storage(Group={"members": links}) + + +def test_the_entries_of_a_link_show_the_display_of_their_target(): + """Members show the display name of a user or of a group.""" + mapping = storage().mappings["Group"] + members = [ + c for c in mapping._all_collections() if c.binding.field_name == "members" + ] + + assert [sorted(c.columns) for c in members] == [["display", "value"]] * 2 + + +def test_the_entries_of_a_link_lack_a_display_their_target_does_not_store(): + """Groups without display name give no display to the groups of a user.""" + groups_of_users = collection( + storage(Group={"displayName": None}).mappings["User"], "groups" + ) + + assert sorted(groups_of_users.columns) == ["value"] + + +def test_a_resource_without_display_gives_none(): + """A pet has no display name nor user name.""" + assert pets_mapping()._display() is None diff --git a/tests/mapping/test_schemas.py b/tests/mapping/test_schemas.py new file mode 100644 index 0000000..6b59c8a --- /dev/null +++ b/tests/mapping/test_schemas.py @@ -0,0 +1,163 @@ +from scim2_models import Mutability +from scim2_models import Required +from scim2_models import Returned + +from scim2_server.mapping import Attribute +from scim2_server.mapping import Entry +from scim2_server.mapping import Many +from scim2_server.utils import load_default_provider + +from .backend import FakeStorage +from .backend import Owned +from .pets import pets +from .pets import pets_mapping +from .pets import tags +from .tables import ENTERPRISE +from .tables import groups_mapping +from .tables import users +from .tables import users_mapping + +WORK_EMAIL = Entry({"value": users.fields["email"]}, type="work", primary=True) + + +def schema(mapping, urn=None): + """Return the attributes of a schema of a mapping bound to its links, by name.""" + mappings = {"User": users_mapping(), "Group": groups_mapping()} + mappings[mapping.model.__name__.split("[")[0]] = mapping + FakeStorage(mappings, load_default_provider()) + schemas = {schema.id: schema for schema in mapping.schemas()} + found = schemas[urn or next(iter(schemas))] + return {attribute.name: attribute for attribute in found.attributes} + + +def subs(attribute): + return {sub.name: sub for sub in attribute.sub_attributes} + + +def test_the_schemas_hold_the_core_schema_and_the_extensions(): + """The enterprise extension comes after the user schema.""" + mapping = users_mapping() + FakeStorage({"User": mapping, "Group": groups_mapping()}, load_default_provider()) + + assert [schema.id for schema in mapping.schemas()] == [ + "urn:ietf:params:scim:schemas:core:2.0:User", + ENTERPRISE, + ] + + +def test_the_schemas_leave_out_the_attributes_the_mapping_does_not_store(): + """Clients only see what the server stores.""" + attributes = schema(users_mapping({"nickName": None, "name.familyName": None})) + + assert "nickName" not in attributes + assert "addresses" not in attributes + assert list(subs(attributes["name"])) == ["givenName"] + + +def test_an_attribute_whose_field_needs_a_value_is_required(): + """A new user needs a title, held by a field without null.""" + attributes = schema(users_mapping({"title": users.fields["user_name"]})) + + assert attributes["title"].required == Required.true + + +def test_a_complex_attribute_whose_sub_attribute_needs_a_value_is_required(): + """A new user needs a name, since its given name needs a value.""" + attributes = schema(users_mapping({"name.givenName": users.fields["user_name"]})) + + assert attributes["name"].required == Required.true + + +def test_a_multi_valued_attribute_whose_entries_need_a_value_is_not_required(): + """A pet may have no tag, even if each tag needs a label.""" + many = Many(Owned(tags, "pet"), tags.fields["label"]) + attributes = { + s.name: s for s in pets_mapping(changes={"tags": many}).schemas()[0].attributes + } + + assert attributes["tags"].required == Required.false + + +def test_a_hidden_attribute_is_never_required(): + """Clients cannot send back a password they never read.""" + attributes = schema(users_mapping({"password": users.fields["user_name"]})) + + assert attributes["password"].required == Required.false + + +def test_an_attribute_the_storage_does_not_write_is_read_only(): + """Clients know the nickname cannot change.""" + nick_name = Attribute(users.fields["nick_name"], writable=False) + + attributes = schema(users_mapping({"nickName": nick_name})) + + assert attributes["nickName"].mutability == Mutability.read_only + + +def test_the_constants_of_an_entry_are_its_canonical_values(): + """The type of the email can only be work.""" + emails = subs(schema(users_mapping({"emails": WORK_EMAIL}))["emails"]) + + assert emails["type"].canonical_values == ["work"] + assert emails["type"].mutability == Mutability.read_write + assert emails["primary"].canonical_values is None + + +def test_the_constants_of_a_read_only_entry_are_read_only(): + """The storage never writes the email, nor its type.""" + entry = Entry( + {"value": Attribute(users.fields["email"], writable=False)}, type="work" + ) + + emails = subs(schema(users_mapping({"emails": entry}))["emails"]) + + assert emails["type"].mutability == Mutability.read_only + assert emails["value"].mutability == Mutability.read_only + + +def test_a_link_refers_to_the_resource_types_of_its_links(): + """Members are users or groups, and show a display.""" + members = subs(schema(groups_mapping())["members"]) + + assert members["$ref"].reference_types == ["User", "Group"] + assert members["type"].canonical_values == ["User", "Group"] + assert members["display"].mutability == Mutability.read_only + + +def test_a_link_of_an_extension_refers_to_its_resource_type(): + """The manager is a user.""" + manager = subs(schema(users_mapping(), ENTERPRISE)["manager"]) + + assert manager["$ref"].reference_types == ["User"] + assert manager["displayName"].mutability == Mutability.read_only + + +def test_a_complex_attribute_of_read_only_values_is_read_only(): + """The storage only reads the groups of a user.""" + assert schema(users_mapping())["groups"].mutability == Mutability.read_only + + +def test_a_complex_attribute_of_hidden_values_is_hidden_and_write_only(): + """Clients never read the code of the vault.""" + vault = { + s.name: s + for s in pets_mapping(changes={"vault.code": pets.fields["code"]}) + .schemas()[0] + .attributes + }["vault"] + + assert vault.returned == Returned.never + assert vault.mutability == Mutability.write_only + + +def test_a_complex_attribute_of_hidden_values_keeps_a_mutability_other_than_read_write(): + """The safe stays immutable.""" + safe = { + s.name: s + for s in pets_mapping(changes={"safe.code": pets.fields["code"]}) + .schemas()[0] + .attributes + }["safe"] + + assert safe.returned == Returned.never + assert safe.mutability == Mutability.immutable