Unknown charset in a JSON request's Content-Type crashes PyramidParser and AIOHTTPParser (500 instead of 400)
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
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_jsoncallscore.parse_json(req.body, encoding=req.charset). Insideparse_json,s.decode(encoding)raisesLookupErrorfor an unknown codec.parse_jsononly convertsUnicodeDecodeErrorintoJSONDecodeError, soParser.load_jsonnever catches theLookupError. - aiohttp:
AIOHTTPParser.load_jsoncallsreq.json(). aiohttp'sRequest.text()runsbytes_body.decode(self.charset or "utf-8"), which raises the sameLookupError.load_jsononly catchesJSONDecodeErrorandUnicodeDecodeError.
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
- Nessun Dockerfile né file Docker Compose
- Nessun modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di marshmallow-code/webargs
-
Multi-value tornado headers are fetched with `get()` rather than `get_list()`Forse già presa @abu-tahir-0 l’ha presa 1 giorno fa. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 62/100
marshmallow-code/webargs#1109 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
Improve Falcon parserForse già presa @vytas7 l’ha presa 116 giorni fa. Aperta
Difficoltà 5/5 Più di una settimana Idoneità per principianti 35/100
marshmallow-code/webargs#1079 · 9 commenti · 2 reazioni ·
I maintainer di solito rispondono entro 1 giorno
-
Dependency DashboardAperta
Difficoltà 4/5 3-5 giorni Idoneità per principianti 20/100
marshmallow-code/webargs#1046 ·
I maintainer di solito rispondono entro 1 giorno
-
docs
Difficoltà 4/5 3-5 giorni Idoneità per principianti 35/100
marshmallow-code/webargs#644 · 5 commenti · 1 reazione ·
I maintainer di solito rispondono entro 1 giorno
-
question
Difficoltà 3/5 1-2 giorni Idoneità per principianti 35/100
marshmallow-code/webargs#549 · 15 commenti ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di marshmallow-code/webargs
Issue simili
-
area:security effort:S priority:P3 status:needs-triage type:chore
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
randomparity/kdive#3657 ·
I maintainer di solito rispondono entro 1 giorno
-
bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
aws/mcp-proxy-for-aws#476 ·
I maintainer di solito rispondono entro 1 giorno
-
fix(cli): a --root that does not exist exits 0 with 'Scanned 0 file(s)', so a wrong path in CI passes silentlyForse già presa @arpanjot-coding l’ha presa oggi. Apertaarea: runtime automation bug cli code-scanning consistency developer-experience difficulty: easy github-actions good first issue help wanted json-output priority: P3 python sarif silent-failure static-analysis tests
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
-
ContainsOnly raises TypeError for unhashable input with set-based choicesForse già presa @prathamchoksi l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 84/100
marshmallow-code/marshmallow#3115 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
I maintainer di solito rispondono entro 1 giorno