-
Notifications
You must be signed in to change notification settings - Fork 31
INTPYTHON-827 Prevent Value strings and model update values from being interpreted as expressions #445
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
Merged
timgraham
merged 3 commits into
mongodb:main
from
WaVEV:INTPYTHON-827-Cannot-save-CharField-and-TextField-with-values-starting-with-$
Nov 17, 2025
Merged
INTPYTHON-827 Prevent Value strings and model update values from being interpreted as expressions #445
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
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
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
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
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
Empty file.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| from django.db import models | ||
|
|
||
|
|
||
| class Author(models.Model): | ||
| name = models.CharField(max_length=50) | ||
|
|
||
| def __str__(self): | ||
| return self.name | ||
|
|
||
|
|
||
| class Blob(models.Model): | ||
| name = models.CharField(max_length=10) | ||
| data = models.JSONField(null=True) | ||
|
|
||
| def __str__(self): | ||
| return self.name |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| """Literals that MongoDB intreprets as expressions are escaped.""" | ||
|
|
||
| from operator import attrgetter | ||
|
|
||
| from django.db.models import Value | ||
| from django.test import TestCase | ||
|
|
||
| from django_mongodb_backend.test import MongoTestCaseMixin | ||
|
|
||
| from .models import Author, Blob | ||
|
|
||
|
|
||
| class ModelCreationTests(MongoTestCaseMixin, TestCase): | ||
| def test_dollar_prefixed_string(self): | ||
| # No escaping is needed because MongoDB's insert doesn't treat | ||
| # dollar-prefixed strings as expressions. | ||
| with self.assertNumQueries(1) as ctx: | ||
| obj = Author.objects.create(name="$foobar") | ||
| obj.refresh_from_db() | ||
| self.assertEqual(obj.name, "$foobar") | ||
| self.assertInsertQuery( | ||
| ctx.captured_queries[0]["sql"], "basic__author", [{"name": "$foobar"}] | ||
| ) | ||
|
|
||
|
|
||
| class ModelUpdateTests(MongoTestCaseMixin, TestCase): | ||
| """ | ||
| $-prefixed strings and dict/tuples that could be interpreted as expressions | ||
| are escaped in the queries that update model instances. | ||
| """ | ||
|
|
||
| def test_dollar_prefixed_string(self): | ||
| obj = Author.objects.create(name="foobar") | ||
| obj.name = "$updated" | ||
| with self.assertNumQueries(1) as ctx: | ||
| obj.save() | ||
| obj.refresh_from_db() | ||
| self.assertEqual(obj.name, "$updated") | ||
| self.assertUpdateQuery( | ||
| ctx.captured_queries[0]["sql"], | ||
| "basic__author", | ||
| {"_id": obj.id}, | ||
| [{"$set": {"name": {"$literal": "$updated"}}}], | ||
| ) | ||
|
|
||
| def test_dollar_prefixed_value(self): | ||
| obj = Author.objects.create(name="foobar") | ||
| obj.name = Value("$updated") | ||
| with self.assertNumQueries(1) as ctx: | ||
| obj.save() | ||
| obj.refresh_from_db() | ||
| self.assertEqual(obj.name, "$updated") | ||
| self.assertUpdateQuery( | ||
| ctx.captured_queries[0]["sql"], | ||
| "basic__author", | ||
| {"_id": obj.id}, | ||
| [{"$set": {"name": {"$literal": "$updated"}}}], | ||
| ) | ||
|
|
||
| def test_dict(self): | ||
| obj = Blob.objects.create(name="foobar") | ||
| obj.data = {"$concat": ["$name", "-", "$name"]} | ||
| obj.save() | ||
| obj.refresh_from_db() | ||
| self.assertEqual(obj.data, {"$concat": ["$name", "-", "$name"]}) | ||
|
|
||
| def test_dict_value(self): | ||
| obj = Blob.objects.create(name="foobar", data={}) | ||
| obj.data = Value({"$concat": ["$name", "-", "$name"]}) | ||
| obj.save() | ||
| obj.refresh_from_db() | ||
| self.assertEqual(obj.data, {"$concat": ["$name", "-", "$name"]}) | ||
|
|
||
| def test_tuple(self): | ||
| obj = Blob.objects.create(name="foobar") | ||
| obj.data = ("$name", "-", "$name") | ||
| obj.save() | ||
| obj.refresh_from_db() | ||
| self.assertEqual(obj.data, ["$name", "-", "$name"]) | ||
|
|
||
| def test_tuple_value(self): | ||
| obj = Blob.objects.create(name="foobar") | ||
| obj.data = Value(("$name", "-", "$name")) | ||
| obj.save() | ||
| obj.refresh_from_db() | ||
| self.assertEqual(obj.data, ["$name", "-", "$name"]) | ||
|
|
||
|
|
||
| class AnnotationTests(MongoTestCaseMixin, TestCase): | ||
| def test_dollar_prefixed_value(self): | ||
| """Value() escapes dollar prefixed strings.""" | ||
| Author.objects.create(name="Gustavo") | ||
| with self.assertNumQueries(1) as ctx: | ||
| qs = list(Author.objects.annotate(a_value=Value("$name"))) | ||
| self.assertQuerySetEqual(qs, ["$name"], attrgetter("a_value")) | ||
| self.assertAggregateQuery( | ||
| ctx.captured_queries[0]["sql"], | ||
| "basic__author", | ||
| [{"$project": {"a_value": {"$literal": "$name"}, "_id": 1, "name": 1}}], | ||
| ) |
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
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I still question whether the $literal escaping is overly broad. Better safe than sorry, sure, but it decreases readability a bit and makes queries larger. But I'm not sure how to compare the tradeoffs between some more complicated logic (
isinstance()CPU time) and leaving it as is. It seems if we did wrapping of only the types thatValue()wraps, it should be safe, unless the logic in Value() is deficient. And are there any string values besides those that start with $ that could be problematic? Perhaps to be discussed in chat tomorrow.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤔 I agree. Seeing $literal everywhere is annoying, but Value's resolver is probably covering the most common types used in queries. On the other hand, implementing the same escaping logic that Value uses is not a big deal.