Validation bypass of extra data keys in JSON model validation
Description
When validating JSON data into a model allowing extra data, the keys of extra data aren't validated against the key type annotated on __pydantic_extra__, resulting in extra data not matching the declared type. This is the case if you define __pydantic_extra__ as e.g. dict[Annotated[str, Field(pattern=r'^x_')], int].
Details
The validate_json_by_iteration() method (in pydantic-core/src/validators/model_fields.rs), used to validate JSON data into models, only validates the values of extra data, and stores the keys as is (L605-L623):
ExtraBehavior::Allow => {
// the key is stored as is, without being validated:
let py_key: Bound<'_, PyString> = new_py_string(py, key, state.cache_str());
if let Some(validator) = &self.extras_validator {
match validator.validate(py, value, state) {
Ok(value) => {
model_extra_dict.set_item(&py_key, value)?;
fields_set.add(py_key)?;
}
// ...
}
}
// ...
}Python mode validation isn't affected.
The issue was fixed in commit github.com/
Impact
Validation bypass: extra data returned by validation doesn't match the declared type. Affected are applications validating untrusted JSON data into models allowing extra data (with extra='allow'), with a key type annotated on __pydantic_extra__ (e.g. dict[Annotated[str, Field(pattern=...)], int]), using Pydantic from 2.13.0 up to (but excluding) 2.14.2.
Python mode validation isn't affected.