Skip to content

Incorrect Handling of Escaped Quotes in Cookie Values #6890

Open
@Konano

Description

@Konano

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:

  1. Allow backslash-escaped quotes in cookie values for historical compatibility
  2. Expect clients to preserve such values verbatim for proper server-side parsing
  3. 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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions