#37566 assigned Bug

MediaType.quality accepts NaN, making accepted_types ordering depend on header order

Reported by: Patel Namraa Owned by: Patel Namraa
Component: HTTP handling Version: dev
Severity: Low Keywords:
Cc: Patel Namraa Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

MediaType.quality in django/http/request.py does not correctly handle NaN quality values in the Accept header.

The current implementation checks whether the parsed quality value is less than 0 or greater than 1:

if quality < 0 or quality > 1:
    return 1

However, Python's floating-point NaN value does not satisfy either comparison. Consequently, q=nan passes the validation and is returned as a quality value instead of falling back to the default quality of 1.

This causes inconsistent content negotiation because NaN does not behave normally during comparisons and can affect the ordering of accepted media types.

For example:

>>> from django.conf import settings
>>> settings.configure()
>>> from django.http import HttpRequest

>>> request = HttpRequest()
>>> request.META["HTTP_ACCEPT"] = (
...     "text/html;q=nan, application/json;q=0.5"
... )
>>> request.get_preferred_type(["text/html", "application/json"])
'text/html'

>>> request = HttpRequest()
>>> request.META["HTTP_ACCEPT"] = (
...     "application/json;q=0.5, text/html;q=nan"
... )
>>> request.get_preferred_type(["text/html", "application/json"])
'application/json'

The preferred media type changes depending on the order of the values in the Accept header, even though the same media types and quality values are supplied.

Proposed fix

Change the range validation to use a chained comparison:

if not 0 <= quality <= 1:
    return 1

This also catches NaN because the chained comparison evaluates to False for NaN. Invalid quality values will then follow the existing fallback behavior.

Regression tests should cover q=nan, q=NaN, q=-nan, and positive and negative infinity, as well as verifying that the preferred media type does not change when the order of the Accept header values is reversed.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top