import copyreg
from collections.abc import MutableMapping
from datetime import datetime
from enum import Enum
from typing import TYPE_CHECKING
from typing import Annotated
from typing import Any
from typing import Generic
from typing import Self
from typing import TypeVar
from typing import Union
from typing import get_args
from typing import get_origin
from weakref import WeakValueDictionary
from pydantic import Field
from pydantic import SerializationInfo
from pydantic import SerializerFunctionWrapHandler
from pydantic import ValidationInfo
from pydantic import ValidatorFunctionWrapHandler
from pydantic import WrapSerializer
from pydantic import model_serializer
from pydantic import model_validator
from pydantic_core import PydanticCustomError
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 ..context import Context
from ..exceptions import InvalidPathException
from ..exceptions import InvalidValueException
from ..path import Path
from ..policy import ScimPolicy
from ..policy import _policy
from ..policy import default_comparison_key
from ..scim_object import ScimObject
from ..utils import UNION_TYPES
if TYPE_CHECKING:
from .schema import Attribute
from .schema import Schema
[docs]
class Extension(ScimObject):
[docs]
@classmethod
def to_schema(cls) -> "Schema":
"""Build a :class:`~scim2_models.Schema` from the current extension class."""
return _model_to_schema(cls)
[docs]
@classmethod
def from_schema(cls, schema: "Schema") -> type["Extension"]:
"""Build a :class:`~scim2_models.Extension` subclass from the schema definition."""
from .schema import _make_python_model
return _make_python_model(schema, cls)
AnyExtension = TypeVar("AnyExtension", bound="Extension")
_PARAMETERIZED_CLASSES: "MutableMapping[tuple[type, tuple[Any, ...]], type]" = (
WeakValueDictionary()
)
"""The classes parameterization has already built, so that parameterizing a
resource twice with the same extensions answers the same class.
The classes are held weakly: one built on a model discovered at runtime, as a
server serving the schemas of its tenants does, would otherwise keep that
model alive for as long as the process runs."""
def _extension_serializer(
value: Any, handler: SerializerFunctionWrapHandler, info: SerializationInfo
) -> Any:
"""Exclude the Resource attributes from the extension dump.
For instance, attributes 'meta', 'id' or 'schemas' should not be dumped
when the model is used as an extension for another model.
"""
if value is None:
return None
partial_result = handler(value)
scim_context = info.context.get("scim") if info.context else None
if not scim_context:
return partial_result
result = {
attr_name: value
for attr_name, value in partial_result.items()
if attr_name not in Resource.model_fields
}
return result or None
def _qualified_extension(parameter: Any) -> tuple[Any, tuple[Any, ...]]:
"""Split an extension parameter from what qualifies it.
``User[Annotated[EnterpriseUser, Required.true]]`` names the extension and
says a resource of that type must carry it, which RFC7643 §6 lets a
resource type declare.
"""
if get_origin(parameter) is Annotated:
extension, *qualifiers = get_args(parameter)
return extension, tuple(qualifiers)
return parameter, ()
[docs]
class Resource(ScimObject, Generic[AnyExtension]):
# Common attributes as defined by
# https://www.rfc-editor.org/rfc/rfc7643#section-3.1
id: Annotated[
str | None,
Mutability.read_only,
Returned.always,
Uniqueness.global_,
CaseExact.true,
] = None
"""A unique identifier for a SCIM resource as defined by the service
provider.
id is mandatory is the resource representation, but is forbidden in
resource creation or replacement requests.
"""
external_id: Annotated[
str | None, Mutability.read_write, Returned.default, CaseExact.true
] = None
"""A String that is an identifier for the resource as defined by the
provisioning client."""
meta: Annotated[Meta | None, Mutability.read_only, Returned.default] = None
"""A complex attribute containing resource metadata."""
[docs]
def replace(self, original: Self) -> bool:
"""Apply :rfc:`RFC 7644 §3.5.1 <7644#section-3.5.1>` replace (PUT) semantics.
``readOnly`` fields are copied from *original*.
``immutable`` fields are preserved from *original* when absent,
or checked for equality when present. ``writeOnly`` fields, such as
``password``, are preserved from *original* when left out, and cleared
by an explicit null only.
The same applies to the sub-attributes of a complex attribute, and to
those of an entry a multi-valued one keeps. Entries are matched on their
``value`` sub-attribute, and only where it designates one entry on each
side. An immutable reference is preserved rather than compared, two
spellings of one URI being equivalent per :rfc:`RFC7643 §2.4
<7643#section-2.4>`.
:param original: The original resource state to compare against.
:return: :data:`True` if the replacement differs from *original*, the
order of the entries of multi-valued attributes aside
(:rfc:`RFC7643 §2.4 <7643#section-2.4>`), :data:`False` otherwise.
:raises MutabilityException: If an immutable field value differs.
"""
self._apply_replace_constraints(original)
return bool(_unordered(self.model_dump()) != _unordered(original.model_dump()))
@classmethod
def __class_getitem__(cls, item: Any) -> type["Resource[Any]"]:
"""Create a Resource class with extension fields dynamically added."""
if hasattr(cls, "__scim_extension_metadata__"):
return cls
parameters = get_args(item) if get_origin(item) in UNION_TYPES else [item]
# Skip TypeVar parameters and Any (used for generic class definitions)
valid_parameters = [
parameter
for parameter in parameters
if not isinstance(parameter, TypeVar) and parameter is not Any
]
if not valid_parameters:
return cls
# What qualifies a parameter belongs to the key, so that a required
# extension and an optional one are two classes.
cache_key = (cls, tuple(valid_parameters))
if cache_key in _PARAMETERIZED_CLASSES:
return _PARAMETERIZED_CLASSES[cache_key]
qualified_extensions = [
_qualified_extension(parameter) for parameter in valid_parameters
]
for extension, _ in qualified_extensions:
if not (isinstance(extension, type) and issubclass(extension, Extension)):
raise TypeError(f"{extension} is not a valid Extension type")
valid_extensions = [extension for extension, _ in qualified_extensions]
class_name = (
f"{cls.__name__}[{', '.join(ext.__name__ for ext in valid_extensions)}]"
)
class_attrs = {"__scim_extension_metadata__": valid_extensions}
for extension in valid_extensions:
schema = extension.__schema__
class_attrs[extension.__name__] = Field(
default=None, # type: ignore[arg-type]
serialization_alias=schema,
validation_alias=schema,
)
new_annotations = {
extension.__name__: Annotated[
(
extension | None,
WrapSerializer(_extension_serializer),
*qualifiers,
)
]
for extension, qualifiers in qualified_extensions
}
new_class = type(
class_name,
(cls,),
{
"__annotations__": new_annotations,
**class_attrs,
},
)
_PARAMETERIZED_CLASSES[cache_key] = new_class
return new_class
def __getitem__(self, item: Any) -> Any:
"""Get a value by extension type or path.
:param item: An Extension subclass or a path (string or Path).
:returns: The extension instance or the value at the path.
:raises KeyError: If the path references a non-existent field.
Examples::
user[EnterpriseUser] # Get extension
user["userName"] # Get attribute
user["name.familyName"] # Get nested attribute
user["emails.value"] # Get the value of each email
"""
if isinstance(item, type) and issubclass(item, Extension):
item = item.__schema__
bound_path = Path.__class_getitem__(type(self))
path = item if isinstance(item, Path) else bound_path(str(item))
try:
return path.get(self)
except InvalidPathException as exc:
raise KeyError(str(item)) from exc
def __setitem__(self, item: Any, value: Any) -> None:
"""Set a value by extension type or path.
:param item: An Extension subclass or a path (string or Path).
:param value: The value to set.
:raises KeyError: If the path references a non-existent field.
Examples::
user[EnterpriseUser] = EnterpriseUser(employee_number="123")
user["displayName"] = "John Doe"
user["name.familyName"] = "Doe"
"""
if isinstance(item, type) and issubclass(item, Extension):
item = item.__schema__
bound_path = Path.__class_getitem__(type(self))
path = item if isinstance(item, Path) else bound_path(str(item))
try:
path.set(self, value)
except InvalidPathException as exc:
raise KeyError(str(item)) from exc
def __delitem__(self, item: Any) -> None:
"""Delete a value by extension type or path.
:param item: An Extension subclass or a path (string or Path).
:raises KeyError: If the path references a non-existent field.
Examples::
del user[EnterpriseUser] # Remove extension
del user["displayName"] # Remove attribute
"""
if isinstance(item, type) and issubclass(item, Extension):
item = item.__schema__
bound_path = Path.__class_getitem__(type(self))
path = item if isinstance(item, Path) else bound_path(str(item))
try:
path.delete(self)
except InvalidPathException as exc:
raise KeyError(str(item)) from exc
[docs]
@classmethod
def get_extension_models(cls) -> dict[str, type[Extension]]:
"""Return extension a dict associating extension models with their schemas."""
extension_models = getattr(cls, "__scim_extension_metadata__", [])
by_schema: dict[str, type[Extension]] = {
ext.__schema__: ext for ext in extension_models
}
return by_schema
[docs]
@classmethod
def get_extension_model(
cls, name_or_schema: Union[str, "Schema"]
) -> type[Extension] | None:
"""Return an extension by its name or schema."""
for schema, extension in cls.get_extension_models().items():
if schema == name_or_schema or extension.__name__ == name_or_schema:
return extension
return None
def _model_schemas(self) -> list[str]:
"""List the base schema and the schemas of the declared extensions."""
return super()._model_schemas() + list(self.get_extension_models())
@model_serializer(mode="wrap")
def _scim_serializer(
self, handler: SerializerFunctionWrapHandler, info: SerializationInfo
) -> dict[str, Any]:
"""Leave out of 'schemas' the extensions the dump does not carry.
Per RFC7643 §3, 'schemas' lists the schemas of the attributes present
in the representation.
"""
serialized = super()._scim_serializer(handler, info)
if not info.context or not info.context.get("scim"):
return serialized
schemas = serialized.get("schemas")
if schemas is None:
return serialized
for extension_field in self.__scim_info__.extensions:
urn = self.__scim_info__.attribute_urns[extension_field]
key = urn if info.by_alias else extension_field
if key not in serialized and urn in schemas:
schemas.remove(urn)
return serialized
@model_validator(mode="wrap")
@classmethod
def _validate_extension_schemas(
cls, value: Any, handler: ValidatorFunctionWrapHandler, info: ValidationInfo
) -> Self:
"""Validate that extension schemas are known."""
obj: Self = handler(value)
scim_ctx = info.context.get("scim") if info.context else None
if scim_ctx is None or scim_ctx == Context.DEFAULT:
return obj
if _policy(info).unknown != ScimPolicy.Unknown.forbid:
return obj
base_schema = getattr(cls, "__schema__", None)
if not base_schema:
return obj
allowed_extensions = set(cls.get_extension_models().keys())
provided_schemas = set(obj.schemas) - {base_schema}
unknown = provided_schemas - allowed_extensions
if unknown:
raise PydanticCustomError(
"unknown_extension_schema",
"Unknown extension schemas: {schemas}",
{"schemas": ", ".join(sorted(unknown))},
)
return obj
@model_validator(mode="after")
def _validate_resource_requirements(self, info: ValidationInfo) -> Self:
"""Check the identifier constraints a service provider must meet.
The ``id`` attribute is issued by the service provider and is read-
only, so these constraints only make sense on the payloads it emits.
"""
scim_ctx = info.context.get("scim") if info.context else None
if scim_ctx is None or not Context.is_response(scim_ctx):
return self
# RFC 7643 Section 3.1: "The string "bulkId" is a reserved keyword and
# MUST NOT be used within any unique identifier value."
if self.id and "bulkId" in self.id:
raise InvalidValueException(
detail="'bulkId' is reserved for bulk operations"
).as_pydantic_error()
return self
@model_validator(mode="after")
def _validate_comparison_forms(self, info: ValidationInfo) -> Self:
"""Refuse the strings a request writes and the policy cannot compare."""
scim_ctx = info.context.get("scim") if info.context else None
if scim_ctx not in _WRITING_CONTEXTS:
return self
try:
_check_comparison_forms(self, _policy(info))
except InvalidValueException as exc:
raise exc.as_pydantic_error() from exc
return self
[docs]
@classmethod
def to_schema(cls) -> "Schema":
"""Build a :class:`~scim2_models.Schema` from the current resource class."""
return _model_to_schema(cls)
[docs]
@classmethod
def from_schema(cls, schema: "Schema") -> type["Resource[Any]"]:
"""Build a :class:`scim2_models.Resource` subclass from the schema definition."""
from .schema import _make_python_model
return _make_python_model(schema, cls)
AnyResource = TypeVar("AnyResource", bound="Resource[Any]")
_WRITING_CONTEXTS = (
Context.RESOURCE_CREATION_REQUEST,
Context.RESOURCE_REPLACEMENT_REQUEST,
Context.BULK_REQUEST,
)
"""The contexts of the requests that write a whole resource."""
def _check_comparison_forms(
resource: Resource[Any],
policy: ScimPolicy,
fields: set[tuple[type[BaseModel], str]] | None = None,
) -> None:
"""Refuse a resource holding a string the policy cannot compare.
Every string attribute is checked, or only the ones in ``fields``, given as
the model and the Python name of the field. The default comparison key
prepares every string, so the check is skipped under it.
"""
if policy.comparison_key is default_comparison_key:
return
for path in Path[type(resource)].iter_paths(target_type=[str]): # type: ignore[misc]
binding = path.resolve()
if fields is not None and (binding.model, binding.field_name) not in fields:
continue
values = path.get(resource, strict=False)
for value in values if isinstance(values, list) else [values]:
if not isinstance(value, str):
continue
try:
binding.comparable(value, policy)
except ValueError as exc:
raise InvalidValueException(
detail=f"'{binding.urn}' holds a value that cannot be compared: {exc}"
) from exc
def _unordered(value: Any) -> Any:
"""Reduce a dumped value to a form that compares equal regardless of entry order."""
if isinstance(value, dict):
return {key: _unordered(item) for key, item in value.items()}
if isinstance(value, list):
return sorted((_unordered(item) for item in value), key=repr)
return value
def _dedicated_attributes(
model: type[BaseModel], excluded_models: list[type[BaseModel]]
) -> dict[str, Any]:
"""Return attributes that are not members the parent 'excluded_models'."""
def compare_field_infos(fi1: Any, fi2: Any) -> bool:
if not fi1 or not fi2:
return False
slot_names = copyreg._slotnames(type(fi1)) # type: ignore[attr-defined]
return all(getattr(fi1, attr) == getattr(fi2, attr) for attr in slot_names)
parent_field_infos = {
field_name: field_info
for excluded_model in excluded_models
for field_name, field_info in excluded_model.model_fields.items()
}
field_infos = {
field_name: field_info
for field_name, field_info in model.model_fields.items()
if not compare_field_infos(field_info, parent_field_infos.get(field_name))
}
return field_infos
def _described_model(model: type[BaseModel]) -> type[BaseModel]:
"""Return the model a parameterized class describes.
``User[EnterpriseUser]`` is a class Resource.__class_getitem__ built to
carry extension fields, and type leaves it without a docstring. The
resource it describes stays ``User``.
"""
if "__scim_extension_metadata__" in model.__dict__:
return model.__bases__[0]
return model
def _is_extension_field(model: type[BaseModel], attribute_name: str) -> bool:
"""Tell whether a field holds an extension rather than an attribute."""
root_type = model.get_field_root_type(attribute_name)
return isinstance(root_type, type) and issubclass(root_type, Extension)
def _model_to_schema(model: type[BaseModel]) -> "Schema":
from scim2_models.resources.schema import Schema
described = _described_model(model)
schema_urn = getattr(model, "__schema__", "") or ""
field_infos = _dedicated_attributes(model, [Resource])
attributes = [
_model_attribute_to_scim_attribute(model, attribute_name)
for attribute_name in field_infos
if attribute_name != "schemas"
and not _is_extension_field(model, attribute_name)
]
schema = Schema(
name=described.__name__,
id=schema_urn,
description=described.__doc__ or described.__name__,
attributes=attributes,
)
return schema
def _enumerated_canonical_values(root_type: Any) -> list[str] | None:
"""Return the values a string enumeration declares, as canonical values.
RFC7643 §7 gives ``canonicalValues`` to string attributes, so an
enumeration holding anything else declares none. A value an
scim2_models.ExtensibleStringEnum accepted beyond its members never joins
them, and thus never reaches a published schema.
"""
if not (isinstance(root_type, type) and issubclass(root_type, Enum)):
return None
values = [member.value for member in root_type]
if not all(isinstance(value, str) for value in values):
return None
return values
def _model_attribute_to_scim_attribute(
model: type[BaseModel], attribute_name: str
) -> "Attribute":
from scim2_models.resources.schema import Attribute
field_info = model.model_fields[attribute_name]
root_type = model.get_field_root_type(attribute_name)
if root_type is None:
raise ValueError(
f"Could not determine root type for attribute {attribute_name}"
)
attribute_type = Attribute.Type.from_python(root_type)
sub_attributes = (
[
_model_attribute_to_scim_attribute(root_type, sub_attribute_name)
for sub_attribute_name in root_type.model_fields
if (
attribute_name != "sub_attributes"
or sub_attribute_name != "sub_attributes"
)
]
if root_type and _is_complex_attribute(root_type)
else None
)
kwargs: dict[str, Any] = {
"name": model._scim_name(attribute_name),
"type": Attribute.Type(attribute_type),
"multi_valued": model.get_field_multiplicity(attribute_name),
"description": field_info.description,
"canonical_values": field_info.examples
or _enumerated_canonical_values(root_type),
"required": model.get_field_annotation(attribute_name, Required),
"case_exact": model.get_field_annotation(attribute_name, CaseExact),
"mutability": model.get_field_annotation(attribute_name, Mutability),
"returned": model.get_field_annotation(attribute_name, Returned),
"sub_attributes": sub_attributes,
}
if attribute_type != Attribute.Type.complex:
kwargs["uniqueness"] = model.get_field_annotation(attribute_name, Uniqueness)
if attribute_type == Attribute.Type.reference:
kwargs["reference_types"] = root_type._get_scim_reference_types() # type: ignore[attr-defined]
return Attribute(**kwargs)