Opened 3 weeks ago

Closed 6 days ago

Last modified 6 days ago

#37103 closed Bug (fixed)

HttpRequest.body raises ValueError for malformed CONTENT_LENGTH

Reported by: bankai Owned by: bankai
Component: HTTP handling Version: dev
Severity: Normal Keywords: ASGI Content-Length HttpRequest
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Sarah Boyce)

Accessing request.body raises an unhandled ValueError when META["CONTENT_LENGTH"] isn't a valid integer:

ValueError: invalid literal for int() with base 10: '10,20'

This can happen with ASGIRequest if duplicate Content-Length headers are comma-joined into a single META value. Even when such requests are usually rejected by common HTTP parsers, HttpRequest.body is currently inconsistent with other Django code paths.

WSGIRequest.__init__(), MultiPartParser.__init__(), and
django.core.servers.basehttp all wrap int(CONTENT_LENGTH) in:

    try:
        ...
    except (ValueError, TypeError):
        content_length = 0

HttpRequest.body is the only place that calls int(CONTENT_LENGTH) without
that guard.

Minimal reproduction:

    from io import BytesIO
    from django.core.handlers.asgi import ASGIRequest
    from django.test import AsyncRequestFactory

    scope = AsyncRequestFactory()._base_scope(method="POST", path="/")
    scope["headers"] = [
        (b"content-type", b"text/plain"),
        (b"content-length", b"10,20"),
    ]

    ASGIRequest(scope, BytesIO(b"hello world body")).body

Expected behavior:
request.body should handle malformed CONTENT_LENGTH consistently with WSGIRequest and MultiPartParser, falling back to 0 instead of surfacing a raw ValueError.

Actual behavior:
request.body raises ValueError.

I have a patch and regression test.

Change History (6)

comment:1 by Sarah Boyce, 3 weeks ago

Description: modified (diff)

comment:2 by Sarah Boyce, 3 weeks ago

Triage Stage: UnreviewedAccepted

comment:3 by Sarah Boyce, 3 weeks ago

Owner: set to bankai
Patch needs improvement: set
Status: newassigned

comment:4 by Sarah Boyce, 12 days ago

Patch needs improvement: unset
Triage Stage: AcceptedReady for checkin

comment:5 by Sarah Boyce <42296566+sarahboyce@…>, 6 days ago

Resolution: fixed
Status: assignedclosed

In ba70e1b:

Fixed #37103 -- Made HttpRequest.body handle malformed CONTENT_LENGTH.

comment:6 by Sarah Boyce <42296566+sarahboyce@…>, 6 days ago

In 1a3721a:

[6.1.x] Fixed #37103 -- Made HttpRequest.body handle malformed CONTENT_LENGTH.

Backport of ba70e1bcdd8dc879c7d5fc7a3d12b5831eb08540 from main.

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