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

未关闭 适合新手
#1,120 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

  • #1121 来自 @hemtilva —— 已关闭,未合并

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
78/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python
领域
backend

调研方向

从 webargs/pyramidparser.py 中的 PyramidParser._raw_load_json 开始,这里 core.parse_json(req.body, encoding=req.charset) 会让 LookupError 逃逸;再到 webargs/aiohttpparser.py 中的 AIOHTTPParser.load_json,这里 req.json() 可能抛出同样的错误。与现有的 UnicodeDecodeError/JSONDecodeError 处理以及 #427 引用的修复进行对比,然后扩展这两条路径,使未知 charset 产生标准的 400 {"json": ["Invalid JSON body."]} 响应。在现有的 Pyramid 和 aiohttp 解析器测试旁添加回归覆盖,使用 issue 的 repro 作为预期行为。

由索引模型根据 Issue 内容生成。

描述

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).

主要语言
Python
星标
1.4k
派生
173
平均合并
15 小时 1 分钟
30 天内合并 PR
7

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

marshmallow-code/webargs 的其他 Issue

查看 marshmallow-code/webargs 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。