Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decode headers as UTF-8 also in ASGI #2606

Merged
merged 17 commits into from
Mar 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"
)
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
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