Fix DjangoGetter invoking callables with alters_data during serialization#1696
Open
chidoziemanagwu wants to merge 1 commit intovitalik:masterfrom
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1686 @stephane @robhudson @quique @vitalik
Context
When integrating Pydantic schemas with Django models, security and data sovereignty are paramount. Issue #1686 highlighted a critical vulnerability where
DjangoGetter._convert_resultunconditionally executed any callable attribute that matched a schema field name. This meant that if a schema included a field nameddeleteorsave, the corresponding Django model method would be invoked during serialization, potentially leading to unintended and silent data destruction.The Approach
Rather than implementing a hardcoded blocklist of "dangerous" method names—which would be brittle and incomplete—this PR leverages Django's built-in
alters_datasafety mechanism.By adding a single check (
and not getattr(result, "alters_data", False)), we alignDjangoGetterwith the exact same safety paradigm used by Django's template engine. This surgically prevents destructive operations (likedelete(),save(), andfull_clean()) from executing during read-only serialization, while fully preserving backward compatibility for legitimate read-only method aliases (e.g.,Field(alias="get_boss_title")).Impact
This patch secures the serialization pipeline against accidental data loss, reinforcing the framework's architecture and reliability for enterprise use cases where data integrity is non-negotiable.
Visual Evidence & Proof
Code Changes:
Before/After Behavior:
ItemSchema.from_orm(item)where schema containsdelete: strexecutesItem.objects.all().delete().alters_datacallable, preserving database integrity.Test Coverage (100% Passing):
Full Suite Verification: