Opened 10 minutes ago
#37542 assigned Bug
Unhandled ValueError from malformed tokens in HttpRequest.accepted_types
| Reported by: | Anisayak Mitra | Owned by: | Anisayak Mitra |
|---|---|---|---|
| Component: | HTTP handling | Version: | 6.1 |
| Severity: | Normal | Keywords: | accepted_types, MediaType, ValueError |
| Cc: | Anisayak Mitra | Triage Stage: | Unreviewed |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
Problem Description
In django/http/request.py, HttpRequest.accepted_types parses the HTTP Accept header by tokenizing the header and instantiating MediaType(token) for each token.
When a client sends an Accept header containing tokens that trigger a ValueError during parameter parsing in parse_header_parameters (for example, tokens exceeding MAX_HEADER_LENGTH or invalid RFC 2231 encoded parameter values), MediaType(token) raises ValueError.
Currently, this ValueError is unhandled inside HttpRequest.accepted_types. As a result, incoming requests containing malformed media tokens in the Accept header crash with an unhandled exception (HTTP 500 Internal Server Error) instead of gracefully discarding the invalid token.
Steps to Reproduce
from django.test import RequestFactory rf = RequestFactory() request = rf.get("/", HTTP_ACCEPT="text/html, " + "a" * 1000) # Raises unhandled ValueError: token is too long print(request.accepted_types)
Expected Behavior
HttpRequest.accepted_types should catch ValueError during token parsing and discard invalid tokens, allowing valid media types in the header (e.g. text/html) to be processed normally. Similarly, HttpRequest.accepted_type and MediaType.match should return None and False respectively when encountering malformed tokens.
Solution & Pull Request
A patch with complete test coverage has been submitted:
Pull Request: https://github.com/django/django/pull/22342
All 126 tests in requests_tests (including 27 in requests_tests.test_accept_header) pass.