Opened 14 minutes ago

Last modified 2 minutes ago

#37555 assigned Uncategorized

Non UTF-8 form submissions crash CSRF error handling instead of returning a 400 response

Reported by: Matt Tuchfarber Owned by: Matt Tuchfarber
Component: Uncategorized Version: 6.1
Severity: Normal Keywords: application/x-www-form-urlencoded, csrf
Cc: Matt Tuchfarber Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

If a form request includes a valid CSRF token but passes a non UTF-8 charset for application/x-www-form-urlencoded content type, it will first attempt to return a BadRequest and return the 400 page, but the @requires_csrf_token decorator on the bad_request view (​https://github.com/django/django/blob/5.2.12/django/views/defaults.py#L102-L103) causes another read of request.POST which then throws a 500 error instead.

This only happens when the CSRF token is valid and checked, which the existing tests did not catch.

Django only reproduction:

import django
from django.conf import settings

settings.configure(
    SECRET_KEY="repro",
    DEBUG=False,
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["testserver"],
    MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"],
)
django.setup()

from django.http import HttpResponse
from django.test import Client
from django.urls import path

urlpatterns = [path("", lambda request: HttpResponse("OK"))]

client = Client(enforce_csrf_checks=True, raise_request_exception=False)
client.cookies[settings.CSRF_COOKIE_NAME] = "a" * 32

response = client.post(
    "/",
    data="a=b",
    content_type="application/x-www-form-urlencoded; charset=ascii",
)
assert response.status_code == 400

Change History (2)

comment:1 by Matt Tuchfarber, 13 minutes ago

First time contibutor here. I'm going to put up a PR fix for this, but I wasn't confident if I was the "assignee" or if that's a person that can approve said PR.

comment:2 by Matt Tuchfarber, 2 minutes ago

Has patch: set
Owner: set to Matt Tuchfarber
Status: new → assigned
Note: See TracTickets for help on using tickets.
Back to Top