Skip to content

Only allow one primary complex attribute value to be true #107

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/changelog.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
Changelog
=========

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

Fixed
^^^^^
- Only allow one primary complex attribute value to be true. :issue:`10`

[0.4.2] - 2025-08-05
--------------------

Expand Down
49 changes: 49 additions & 0 deletions scim2_models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,55 @@ def check_replacement_request_mutability(
cls._check_mutability_issues(original, obj)
return obj

@model_validator(mode="after")
def check_primary_attribute_uniqueness(self, info: ValidationInfo) -> Self:
"""Validate that only one attribute can be marked as primary in multi-valued lists.

Per RFC 7643 Section 2.4: The primary attribute value 'true' MUST appear no more than once.
"""
from scim2_models.attributes import MultiValuedComplexAttribute

scim_context = info.context.get("scim") if info.context else None
if not scim_context:
return self

for field_name in self.__class__.model_fields:
# Check if field is multi-valued (list type)
if not self.get_field_multiplicity(field_name):
continue

field_value = getattr(self, field_name)
if field_value is None:
continue

# Check if items in the list have a 'primary' attribute
element_type = self.get_field_root_type(field_name)
if (
element_type is None
or not isclass(element_type)
or not issubclass(element_type, MultiValuedComplexAttribute)
):
continue

primary_count = sum(
1
for item in field_value
if isinstance(item, PydanticBaseModel)
and getattr(item, "primary", None) is True
)

if primary_count > 1:
raise PydanticCustomError(
"primary_uniqueness_error",
"Field '{field_name}' has {count} items marked as primary, but only one is allowed per RFC 7643",
{
"field_name": field_name,
"count": primary_count,
},
)

return self

@classmethod
def _check_mutability_issues(
cls, original: "BaseModel", replacement: "BaseModel"
Expand Down
62 changes: 62 additions & 0 deletions tests/test_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,65 @@ def test_full_user(load_sample):
obj.meta.location
== "https://example.com/v2/Users/2819c223-7f76-453a-919d-413861904646"
)


def test_primary_attribute_validation_valid_cases():
"""Test primary attribute validation for valid cases (0 or 1 primary)."""
from scim2_models.context import Context

# Case 1: No primary attributes
user_data = {
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"userName": "testuser",
"emails": [
{"value": "[email protected]", "type": "work"},
{"value": "[email protected]", "type": "home"},
],
}
user = User.model_validate(
user_data, context={"scim": Context.RESOURCE_CREATION_REQUEST}
)
assert user.user_name == "testuser"

# Case 2: Exactly one primary attribute
user_data_with_primary = {
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"userName": "testuser2",
"emails": [
{"value": "[email protected]", "type": "work", "primary": True},
{"value": "[email protected]", "type": "home", "primary": False},
],
}
user_with_primary = User.model_validate(
user_data_with_primary, context={"scim": Context.RESOURCE_CREATION_REQUEST}
)
assert user_with_primary.emails[0].primary is True
assert user_with_primary.emails[1].primary is False


def test_primary_attribute_validation_invalid_case():
"""Test primary attribute validation for invalid case (multiple primary)."""
import pytest
from pydantic import ValidationError

from scim2_models.context import Context

# Case: Multiple primary attributes (should fail)
user_data_invalid = {
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"userName": "testuser3",
"emails": [
{"value": "[email protected]", "type": "work", "primary": True},
{"value": "[email protected]", "type": "home", "primary": True},
],
}

with pytest.raises(ValidationError) as exc_info:
User.model_validate(
user_data_invalid, context={"scim": Context.RESOURCE_CREATION_REQUEST}
)

error = exc_info.value.errors()[0]
assert error["type"] == "primary_uniqueness_error"
assert "emails" in error["ctx"]["field_name"]
assert error["ctx"]["count"] == 2
Loading