Skip to content

Commit

Permalink
Decode headers as UTF-8 also in ASGI (#2606)
Browse files Browse the repository at this point in the history
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
  • Loading branch information
ChihweiLHBird and ahopkins committed Mar 20, 2023
1 parent 71cd53b commit 61aa16f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
22 changes: 15 additions & 7 deletions sanic/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from urllib.parse import quote

from sanic.compat import Header
from sanic.exceptions import ServerError
from sanic.exceptions import BadRequest, ServerError
from sanic.helpers import Default
from sanic.http import Stage
from sanic.log import error_logger, logger
Expand Down Expand Up @@ -132,12 +132,20 @@ async def create(
instance.sanic_app.state.is_started = True
setattr(instance.transport, "add_task", sanic_app.loop.create_task)

headers = Header(
[
(key.decode("latin-1"), value.decode("latin-1"))
for key, value in scope.get("headers", [])
]
)
try:
headers = Header(
[
(
key.decode("ASCII"),
value.decode(errors="surrogateescape"),
)
for key, value in scope.get("headers", [])
]
)
except UnicodeDecodeError:
raise BadRequest(
"Header names can only contain US-ASCII characters"
)
path = (
scope["path"][1:]
if scope["path"].startswith("/")
Expand Down
26 changes: 26 additions & 0 deletions tests/test_asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
import pytest
import uvicorn

from httpx import Headers
from pytest import MonkeyPatch

from sanic import Sanic
from sanic.application.state import Mode
from sanic.asgi import ASGIApp, Lifespan, MockTransport
Expand Down Expand Up @@ -626,3 +629,26 @@ async def before_server_stop(_):
)
]
)


@pytest.mark.asyncio
async def test_asgi_headers_decoding(app: Sanic, monkeypatch: MonkeyPatch):
@app.get("/")
def handler(request: Request):
return text("")

headers_init = Headers.__init__

def mocked_headers_init(self, *args, **kwargs):
if "encoding" in kwargs:
kwargs.pop("encoding")
headers_init(self, encoding="utf-8", *args, **kwargs)

monkeypatch.setattr(Headers, "__init__", mocked_headers_init)

message = "Header names can only contain US-ASCII characters"
with pytest.raises(BadRequest, match=message):
_, response = await app.asgi_client.get("/", headers={"😂": "😅"})

_, response = await app.asgi_client.get("/", headers={"Test-Header": "😅"})
assert response.status_code == 200

0 comments on commit 61aa16f

Please sign in to comment.