Incorrect Handling of Escaped Quotes in Cookie Values
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 54.3k
- Forks
- 10.5k
- Avg merge
- 16h 43m
- Merged PRs (30d)
- 3
Description
Expected Result
Legitimate escaped quotes (e.g., \") in cookie values should be preserved. For example:
Input value "159\\"687" (actual string: 159\"687) should remain unchanged.
Actual Result
Requests incorrectly replaces escaped quotes with an empty string, causing "159\\"687" to become "159687" (string becomes 159687), which corrupts valid values.
Reproduction Steps
import requests
from requests.cookies import create_cookie
# Create a cookie with escaped quotes
cookie = create_cookie(
name="test_cookie",
value='"159\\"687"', # Actual stored value should be 159\"687
domain="example.com"
)
# Test using a session
with requests.Session() as s:
s.cookies.set_cookie(cookie)
retrieved = s.cookies.get("test_cookie")
print(f"Expected: 159\\\"687 | Actual: {retrieved.value}") # Actual output: 159687
Issue Analysis
The code at src/requests/cookies.py#L349-L356 has the following problem:
# Problematic code snippet
if (
hasattr(cookie.value, "startswith")
and cookie.value.startswith('"')
and cookie.value.endswith('"')
):
cookie.value = cookie.value.replace('\\"', "") # Incorrectly removes all escaped quotes
This logic makes incorrect assumptions about cookie value sanitization. While RFC 6265 specifies that cookie values shouldn't contain escaped characters (through its cookie-value definition), many real-world implementations:
- Allow backslash-escaped quotes in cookie values for historical compatibility
- Expect clients to preserve such values verbatim for proper server-side parsing
- Use these patterns in legitimate scenarios (e.g., JSON fragments in cookies)
By forcibly stripping escaped quotes, Requests breaks values that:
- Were explicitly escaped by servers
- Contain valid escaped sequences from non-standard implementations
- Include quote characters in structured data formats
Suggested Fix
Remove this non-standard cleanup logic entirely.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in src/requests/cookies.py around lines 349-356 and reproduce the issue with the provided create_cookie and Session example. Verify that escaped quotes in a quoted cookie value are preserved rather than removed, and add regression coverage for the demonstrated behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Quiet
- Clarity
- Clearly specified
- Newbie friendliness
- 75/100