Skip to content

Conversation

@rsamanth1
Copy link

Description

Problem

When a field is marked as Optional[Annotated[str, msgspec.Meta(pattern=...)]], the regex constraint validation was bypassed, allowing invalid input to pass through.

Before:

POST / {"url": "htp:/gogle.com"}  # Returns 201 (should be 400)

After:

POST / {"url": "htp:/gogle.com"}  # Returns 400 

Solution

Added post-decoding validation that:

  1. Extracts Meta constraints from Optional[Annotated[T, Meta(...)]] types
  2. Validates non-None values against these constraints
  3. Raises ValidationException for invalid patterns

Changes

  • Modified msgspec_dto.py:

    • Added _extract_meta_from_annotation() to unwrap Optional/Annotated types
    • Override decode_builtins() and decode_bytes() to add validation
    • Added _validate_meta_constraints() and _validate_instance() methods
  • Added comprehensive tests in test_dto_optional_validation.py:

    • Invalid URLs rejected with 400
    • Valid URLs accepted with 201
    • None values allowed for optional fields
    • Required fields still validate correctly
    • Parametrized tests for various URL patterns

Testing

pytest tests/unit/dto/test_dto_optional_validation.py -v

Closes

… – Validate Meta.pattern for Optional Annotated types and add tests
@rsamanth1 rsamanth1 requested review from a team as code owners December 2, 2025 19:05
@github-actions github-actions bot added area/dto This PR involves changes to the DTOs size: small pr/external Triage Required 🏥 This requires triage labels Dec 2, 2025
@provinzkraut
Copy link
Member

I believe this is following msgspec's logic. The field annotation should be Annotated[Optional[str], msgspec.Meta(pattern=...)] not Optional[Annotated[str, msgspec.Meta(pattern=...)]]. Have you verified that it works as intended with the correct annotation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/dto This PR involves changes to the DTOs pr/external size: small Triage Required 🏥 This requires triage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants