Source code for scim2_models.resources.schema

import re
from collections import Counter
from datetime import datetime
from enum import StrEnum
from typing import Annotated
from typing import Any
from typing import List  # noqa: UP035
from typing import Optional
from typing import TypeVar
from typing import Union
from typing import cast

from pydantic import Base64Bytes
from pydantic import Field
from pydantic import create_model
from pydantic import field_validator
from pydantic.alias_generators import to_pascal
from pydantic.alias_generators import to_snake
from pydantic_core import Url

from ..annotations import CaseExact
from ..annotations import Mutability
from ..annotations import Required
from ..annotations import Returned
from ..annotations import Uniqueness
from ..attributes import ComplexAttribute
from ..attributes import _is_complex_attribute
from ..base import BaseModel
from ..constants import RESERVED_WORDS
from ..reference import URI
from ..reference import External
from ..reference import Reference
from ..urn import URN
from .resource import Resource

T = TypeVar("T", bound=BaseModel)

_NON_WORD_OR_LEADING_DIGIT = re.compile(r"\W|^(?=\d)")

_MAX_COMPLEX_DEPTH = 2
"""How deep complex attributes can be nested.

RFC7643 §2.3.8 forbids complex sub-attributes, but §7 lets the "Schema"
resource hold one, as its complex 'subAttributes' in its complex 'attributes'."""


def _make_python_identifier(identifier: str, base: type) -> str:
    """Sanitize string to be a suitable Python/Pydantic class attribute name.

    Pydantic refuses the names with a leading underscore, and a field named after
    a member of the base class, such as 'model_config' or 'model_dump', would
    break the model. Such a name gets a trailing underscore, as a reserved word.
    """
    sanitized = to_snake(_NON_WORD_OR_LEADING_DIGIT.sub("", identifier).lstrip("_"))
    if sanitized in RESERVED_WORDS or hasattr(base, sanitized):
        sanitized = f"{sanitized}_"

    return sanitized


def _field_names(attributes: "list[Attribute]", base: type) -> list[str]:
    """Return the Python name each attribute is held under.

    Two SCIM names may yield one Python name, as ``employee_id`` and
    ``employeeId`` both yield ``employee_id``. The one already spelled as that
    name keeps it and the others are held under their SCIM name, so that no
    attribute is dropped and the order the schema declares them in changes
    nothing. Such a name is no Python identifier when it carries a dash, which
    costs nothing: an attribute is read under the name SCIM gives it, as in
    ``resource["employee-Id"]``.
    """
    natural = [_make_python_identifier(attr.name or "", base) for attr in attributes]
    shared = Counter(natural)
    names = [
        name if shared[name] == 1 or name == attr.name else attr.name or ""
        for attr, name in zip(attributes, natural, strict=True)
    ]
    for name in names:
        if name.startswith("_") or hasattr(base, name):
            raise ValueError(f"{name!r} cannot be the name of an attribute")

    return names


def _python_attributes(
    attributes: "list[Attribute] | None", declared_by: str, base: type, depth: int
) -> dict[str, Any]:
    """Return the fields a schema or a complex attribute declares.

    ``declared_by`` is what declares them, quoted by the error. Two
    attributes whose names only differ by case are refused: RFC7643 §2.1 makes
    them one attribute, so a schema declaring both describes it twice.
    """
    declared = []
    named: dict[str, str] = {}
    for attr in attributes or []:
        if not attr.name:
            continue

        claimed = named.get(attr.name.lower())
        if claimed is not None:
            raise ValueError(
                f"{declared_by} declares {claimed!r} and {attr.name!r}, "
                f"which name the same attribute"
            )
        named[attr.name.lower()] = attr.name
        declared.append(attr)

    return {
        field_name: attr._to_python(depth)
        for field_name, attr in zip(_field_names(declared, base), declared, strict=True)
    }


def _make_python_model(
    obj: Union["Schema", "Attribute"],
    base: type[T],
    depth: int = 0,
) -> type[T]:
    """Build a Python model from a Schema or an Attribute object.

    ``depth`` is the nesting level of the complex attribute being built, 0 for
    a schema.
    """
    if not obj.name:
        raise ValueError("Schema or Attribute 'name' must be defined")

    if depth > _MAX_COMPLEX_DEPTH:
        raise ValueError(
            f"the complex attribute {obj.name!r} is nested more than "
            f"{_MAX_COMPLEX_DEPTH} levels deep"
        )

    if isinstance(obj, Attribute):
        pydantic_attributes = _python_attributes(
            obj.sub_attributes, f"the attribute {obj.name!r}", base, depth
        )
    else:
        pydantic_attributes = _python_attributes(
            obj.attributes, f"the schema {obj.id or obj.name}", base, depth
        )

    model_name = obj.name if isinstance(obj, Schema) else to_pascal(to_snake(obj.name))
    model = cast(
        type[T],
        create_model(model_name, __base__=base, **pydantic_attributes),
    )

    if isinstance(obj, Schema) and obj.id:
        model.__schema__ = URN(obj.id)  # type: ignore[attr-defined]
        # __scim_info__ was built by pydantic before __schema__ was known
        model.__pydantic_on_complete__()

    if isinstance(obj, Schema):
        model.__doc__ = obj.description

    for attr_name in model.model_fields:
        attr_type = model.get_field_root_type(attr_name)
        if attr_type and _is_complex_attribute(attr_type):
            setattr(model, attr_type.__name__, attr_type)

    return model


[docs] class Attribute(ComplexAttribute):
[docs] class Type(StrEnum): string = "string" complex = "complex" boolean = "boolean" decimal = "decimal" integer = "integer" date_time = "dateTime" reference = "reference" binary = "binary" def _to_python( self, reference_types: list[str] | None = None, ) -> type: if self.value == self.reference: if reference_types == ["external"]: return Reference[External] # 'referenceTypes' is not required by RFC7643 §7, and a # reference is a URI per §2.3.7. if not reference_types or reference_types == ["uri"]: return Reference[URI] if len(reference_types) == 1: return Reference[reference_types[0]] # type: ignore[valid-type] return Reference[Union[tuple(reference_types)]] # type: ignore[misc,return-value] # noqa: UP007 attr_types = { self.string: str, self.boolean: bool, self.decimal: float, self.integer: int, self.date_time: datetime, self.binary: Base64Bytes, self.complex: ComplexAttribute, } return attr_types[self] @classmethod def from_python(cls, pytype: type) -> "Attribute.Type": if isinstance(pytype, type) and issubclass(pytype, Reference): return cls.reference if pytype and _is_complex_attribute(pytype): return cls.complex if pytype in (Required, CaseExact): return cls.boolean attr_types = { str: cls.string, bool: cls.boolean, float: cls.decimal, int: cls.integer, datetime: cls.date_time, Base64Bytes: cls.binary, } return attr_types.get(pytype, cls.string)
name: Annotated[str | None, Mutability.read_only, Required.true, CaseExact.true] = ( None ) """The attribute's name.""" type: Annotated[Type | None, Mutability.read_only, Required.true] = None """The attribute's data type.""" multi_valued: Annotated[bool | None, Mutability.read_only, Required.true] = None """A Boolean value indicating the attribute's plurality.""" description: Annotated[ str | None, Mutability.read_only, Required.false, CaseExact.true ] = None """The attribute's human-readable description.""" required: Annotated[Required, Mutability.read_only, Required.false] = Required.false """A Boolean value that specifies whether or not the attribute is required.""" canonical_values: Annotated[ list[str] | None, Mutability.read_only, CaseExact.true ] = None """A collection of suggested canonical values that MAY be used (e.g., "work" and "home").""" case_exact: Annotated[CaseExact, Mutability.read_only, Required.false] = ( CaseExact.false ) """A Boolean value that specifies whether or not a string attribute is case sensitive.""" mutability: Annotated[ Mutability, Mutability.read_only, Required.false, CaseExact.true ] = Mutability.read_write """A single keyword indicating the circumstances under which the value of the attribute can be (re)defined.""" returned: Annotated[ Returned, Mutability.read_only, Required.false, CaseExact.true ] = Returned.default """A single keyword that indicates when an attribute and associated values are returned in response to a GET request or in response to a PUT, POST, or PATCH request.""" uniqueness: Annotated[ Uniqueness, Mutability.read_only, Required.false, CaseExact.true ] = Uniqueness.none """A single keyword value that specifies how the service provider enforces uniqueness of attribute values.""" reference_types: Annotated[ list[str] | None, Mutability.read_only, Required.false, CaseExact.true ] = None """A multi-valued array of JSON strings that indicate the SCIM resource types that may be referenced.""" # for python 3.9 and 3.10 compatibility, this should be 'list' and not 'List' sub_attributes: Annotated[List["Attribute"] | None, Mutability.read_only] = None # noqa: UP006 """When an attribute is of type "complex", "subAttributes" defines a set of sub-attributes.""" def _to_python(self, depth: int = 0) -> tuple[Any, Any] | None: """Build tuple suited to be passed to pydantic 'create_model'. ``depth`` is the nesting level of the complex attribute holding this one, 0 for a schema. """ if not self.name or not self.type: return None attr_type = self.type._to_python(self.reference_types) if attr_type == ComplexAttribute: attr_type = _make_python_model(obj=self, base=attr_type, depth=depth + 1) if self.multi_valued: attr_type = list[attr_type] # type: ignore[valid-type] annotation = Annotated[ attr_type | None, # type: ignore[valid-type] self.required, self._implicit_case_exact(), self.mutability, self.returned, self.uniqueness, ] field = Field( description=self.description, examples=self.canonical_values, serialization_alias=self.name, validation_alias=self.name, default=None, ) return annotation, field def _implicit_case_exact(self) -> CaseExact: """Return the case sensitivity the built field must be annotated with. Binary and reference values are case exact per RFC7643 §2.3.6 and §2.3.7, unless the schema explicitly states otherwise. """ if "case_exact" in self.model_fields_set: return self.case_exact if self.type in (self.Type.reference, self.Type.binary): return CaseExact.true return self.case_exact
[docs] def get_attribute(self, attribute_name: str) -> Optional["Attribute"]: """Find an attribute by its name.""" for sub_attribute in self.sub_attributes or []: if sub_attribute.name == attribute_name: return sub_attribute return None
def __getitem__(self, name: str) -> "Attribute": """Find an attribute by its name.""" if attribute := self.get_attribute(name): return attribute raise KeyError(f"This attribute has no '{name}' sub-attribute")
[docs] class Schema(Resource[Any]): __schema__ = URN("urn:ietf:params:scim:schemas:core:2.0:Schema") id: Annotated[str | None, Mutability.read_only, Required.true] = None """The unique URI of the schema.""" name: Annotated[ str | None, Mutability.read_only, Returned.default, Required.true ] = None """The schema's human-readable name.""" description: Annotated[str | None, Mutability.read_only, Returned.default] = None """The schema's human-readable description.""" attributes: Annotated[ list[Attribute] | None, Mutability.read_only, Required.true ] = None """A complex type that defines service provider attributes and their qualities via the following set of sub-attributes.""" @field_validator("id") @classmethod def _urn_id(cls, value: str) -> str: """Ensure that schema ids are URI, as defined in RFC7643 §7.""" return str(Url(value))
[docs] def get_attribute(self, attribute_name: str) -> Attribute | None: """Find an attribute by its name.""" for attribute in self.attributes or []: if attribute.name == attribute_name: return attribute return None
def __getitem__(self, name: str) -> "Attribute": """Find an attribute by its name.""" if attribute := self.get_attribute(name): return attribute raise KeyError(f"This schema has no '{name}' attribute")