Unknown charset in a JSON request's Content-Type crashes PyramidParser and AIOHTTPParser (500 instead of 400)
维护者通常 1 天内回复
还没有人认领这个 Issue。
- #1121 来自 @hemtilva —— 已关闭,未合并
评估
调研方向
从 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_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).
- 主要语言
- Python
- 星标
- 1.4k
- 派生
- 173
- 平均合并
- 15 小时 1 分钟
- 30 天内合并 PR
- 7
环境准备
- 没有 Dockerfile 或 Docker Compose 文件
- 没有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
marshmallow-code/webargs 的其他 Issue
-
Multi-value tornado headers are fetched with `get()` rather than `get_list()`可能已有人在做 @abu-tahir-0 于 1 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 62/100
marshmallow-code/webargs#1109 · 1 条评论 ·
维护者通常 1 天内回复
-
Improve Falcon parser可能已有人在做 @vytas7 于 116 天前认领。 未关闭
难度 5/5 一周以上 新手友好度 35/100
marshmallow-code/webargs#1079 · 9 条评论 · 2 个 reaction ·
维护者通常 1 天内回复
-
难度 4/5 3-5 天 新手友好度 20/100
marshmallow-code/webargs#1046 ·
维护者通常 1 天内回复
-
docs
难度 4/5 3-5 天 新手友好度 35/100
marshmallow-code/webargs#644 · 5 条评论 · 1 个 reaction ·
维护者通常 1 天内回复
-
question
难度 3/5 1-2 天 新手友好度 35/100
marshmallow-code/webargs#549 · 15 条评论 ·
维护者通常 1 天内回复
查看 marshmallow-code/webargs 的全部 Issue
相似的 Issue
-
area:security effort:S priority:P3 status:needs-triage type:chore
难度 2/5 1-3 小时 新手友好度 78/100
randomparity/kdive#3657 ·
维护者通常 1 天内回复
-
bug
难度 2/5 1-3 小时 新手友好度 78/100
aws/mcp-proxy-for-aws#476 ·
维护者通常 1 天内回复
-
fix(cli): a --root that does not exist exits 0 with 'Scanned 0 file(s)', so a wrong path in CI passes silently可能已有人在做 @arpanjot-coding 今天认领。 未关闭area: 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
难度 2/5 1-3 小时 新手友好度 82/100
-
ContainsOnly raises TypeError for unhashable input with set-based choices可能已有人在做 @prathamchoksi 今天认领。 未关闭
难度 2/5 1-3 小时 新手友好度 84/100
marshmallow-code/marshmallow#3115 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 76/100
维护者通常 1 天内回复