Unknown charset in a JSON request's Content-Type crashes PyramidParser and AIOHTTPParser (500 instead of 400)

Aperta Adatta ai principianti
#1,120 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

  • #1121 di @hemtilva — chiusa senza merge

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
78/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
backend

Direzione di ricerca

Inizia in webargs/pyramidparser.py a PyramidParser._raw_load_json, dove core.parse_json(req.body, encoding=req.charset) lascia sfuggire un LookupError, e in webargs/aiohttpparser.py a AIOHTTPParser.load_json, dove req.json() può sollevare lo stesso errore. Confronta con la gestione esistente di UnicodeDecodeError/JSONDecodeError e con la correzione a cui si fa riferimento da #427, poi estendi entrambi i percorsi affinché un charset sconosciuto produca la risposta standard 400 {"json": ["Invalid JSON body."]}. Aggiungi copertura di regressione accanto ai test esistenti dei parser Pyramid e aiohttp, usando il repro dell'issue come comportamento atteso.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Description

If a client sends a JSON body with a Content-Type charset that Python doesn't recognise, for example

Content-Type: application/json; charset=not-a-charset

PyramidParser and AIOHTTPParser raise an uncaught LookupError: unknown encoding: not-a-charset. The server then responds with 500 Internal Server Error. The documented behaviour for an unreadable JSON body is a 400 {"json": ["Invalid JSON body."]}.

Any client can trigger this, because the value comes straight from a request header.

Why it happens:

  • Pyramid: PyramidParser._raw_load_json calls core.parse_json(req.body, encoding=req.charset). Inside parse_json, s.decode(encoding) raises LookupError for an unknown codec. parse_json only converts UnicodeDecodeError into JSONDecodeError, so Parser.load_json never catches the LookupError.
  • aiohttp: AIOHTTPParser.load_json calls req.json(). aiohttp's Request.text() runs bytes_body.decode(self.charset or "utf-8"), which raises the same LookupError. load_json only catches JSONDecodeError and UnicodeDecodeError.

The other parsers (Flask, Django, Bottle, Falcon) ignore the charset and decode the body as UTF-8, so they return 200. Issue #427 fixed the similar case of a body that isn't valid UTF-8. This is a different input that still gets through.

Reproduction

webargs dev @ 3c7f387, Python 3.15, pyramid 2.1, aiohttp 3.14.5, marshmallow 4.4.0.

import asyncio

import webtest
import webtest_aiohttp
from aiohttp import web
from pyramid.config import Configurator

from webargs import fields
from webargs.aiohttpparser import parser as aio_parser
from webargs.pyramidparser import parser as pyr_parser

ARGS = {"name": fields.Str()}
BODY = b'{"name": "Steve"}'
HEADERS = {"Content-Type": "application/json; charset=not-a-charset"}


def pyramid_view(request):
    return pyr_parser.parse(ARGS, request, location="json")


with Configurator() as config:
    config.add_route("echo", "/echo")
    config.add_view(pyramid_view, route_name="echo", renderer="json")
    pyr_app = webtest.TestApp(config.make_wsgi_app())


async def aio_view(request):
    return web.json_response(await aio_parser.async_parse(ARGS, request, location="json"))


aio = web.Application()
aio.router.add_post("/echo", aio_view)
aio_app = webtest_aiohttp.TestApp(aio, loop=asyncio.new_event_loop())

for name, app in [("pyramid", pyr_app), ("aiohttp", aio_app)]:
    try:
        res = app.post("/echo", BODY, headers=HEADERS, expect_errors=True)
        print(f"{name}: {res.status} {res.body!r}")
    except Exception as exc:
        print(f"{name}: UNCAUGHT {type(exc).__name__}: {exc}")
Actual
pyramid: UNCAUGHT LookupError: unknown encoding: not-a-charset
aiohttp: 500 Internal Server Error b'500 Internal Server Error\n\nServer got itself in trouble'
Expected
pyramid: 400 Bad Request b'{"json": ["Invalid JSON body."]}'
aiohttp: 400 Bad Request b'{"json": ["Invalid JSON body."]}'

That is, the same handling as other undecodable JSON bodies (see #427).

Lingua principale
Python
Stelle
1.4k
Fork
173
Merge medio
15h 1m
PR unite (30g)
7

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di marshmallow-code/webargs

Tutte le issue di marshmallow-code/webargs

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.