﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
37541	Admin search for a lone quote character matches all rows	Vaibhav Pant		"`unescape_string_literal()` accepts a string consisting of a single quote character and returns an empty string instead of raising `ValueError`:

{{{#!python
>>> from django.utils.text import unescape_string_literal
>>> unescape_string_literal('""')
''
>>> unescape_string_literal(""'"")
''
}}}

The check `s[-1] != s[0]` passes for a one-character string, so `s[1:-1]` is empty.

`ModelAdmin.get_search_results()` has the same blind spot in its guard (`bit.startswith(('""', ""'"")) and bit[0] == bit[-1]`, added for #32649). A search term that is a single `""` or `'` is therefore unescaped to `''`, and the empty string matches every row.

'''Steps to reproduce'''
1. Use a `ModelAdmin` with `search_fields = [""name""]`.
2. Create rows named `plain`, `other` and `has""quote`.
3. Search the changelist for `""`.

Expected: only `has""quote` is returned.[[br]]
Actual: all three rows are returned.

'''Proposed fix'''
Require `len(s) >= 2` in `unescape_string_literal()`, and add `len(bit) >= 2` to the quote check in `get_search_results()`. Fixing only the helper is not enough: the admin would then raise an uncaught `ValueError` when searching for a lone quote. This also applies to the unbalanced input from #32649, for example `Foo ""Bar ""Baz""`.

'''Possible fix'''

`django/utils/text.py`:
{{{#!diff
--- a/django/utils/text.py
+++ b/django/utils/text.py
@@ -474 +474 @@ def unescape_string_literal(s):
-    if not s or s[0] not in ""\""'"" or s[-1] != s[0]:
+    if len(s) < 2 or s[0] not in ""\""'"" or s[-1] != s[0]:
}}}

`django/contrib/admin/options.py`:
{{{#!diff
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -1360 +1360 @@ class ModelAdmin(BaseModelAdmin):
-                if bit.startswith(('""', ""'"")) and bit[0] == bit[-1]:
+                if len(bit) >= 2 and bit.startswith(('""', ""'"")) and bit[0] == bit[-1]:
}}}

With both changes, `unescape_string_literal('""')` raises `ValueError` and the admin search above returns only `has""quote`. I ran `utils_tests.test_text`, `admin_changelist`, `admin_views` and `template_tests.syntax_tests` with both changes applied (1550 tests, OK).

Related: #32649 (unbalanced quotes), #6933 (quoted-phrase search, [26a41350]). This is not a duplicate of #34831, which is about limiting the number of OR'd search terms in the same loop.

I can prepare a patch with tests once the ticket is accepted.

'''AI disclosure'''
I found and reproduced this with Claude (Anthropic)."	Bug	new	contrib.admin	dev	Normal		admin, search		Unreviewed	0	0	0	0	0	0
