Skip to content
Open
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
3 changes: 2 additions & 1 deletion src/hypercorn/protocol/http_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
)
from ..utils import (
build_and_validate_headers,
reduce_target_to_origin_form,
suppress_body,
UnexpectedMessageError,
valid_server_name,
Expand Down Expand Up @@ -83,7 +84,7 @@ async def handle(self, event: Event) -> None:
return
elif isinstance(event, Request):
self.start_time = time()
path, _, query_string = event.raw_path.partition(b"?")
path, _, query_string = reduce_target_to_origin_form(event.raw_path).partition(b"?")
self.scope = {
"type": "http",
"http_version": event.http_version,
Expand Down
3 changes: 2 additions & 1 deletion src/hypercorn/protocol/ws_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
)
from ..utils import (
build_and_validate_headers,
reduce_target_to_origin_form,
suppress_body,
UnexpectedMessageError,
valid_server_name,
Expand Down Expand Up @@ -206,7 +207,7 @@ async def handle(self, event: Event) -> None:
elif isinstance(event, Request):
self.start_time = time()
self.handshake = Handshake(event.headers, event.http_version)
path, _, query_string = event.raw_path.partition(b"?")
path, _, query_string = reduce_target_to_origin_form(event.raw_path).partition(b"?")
self.scope = {
"type": "websocket",
"asgi": {"spec_version": "2.3", "version": "3.0"},
Expand Down
19 changes: 19 additions & 0 deletions src/hypercorn/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import inspect
import re
import os
import socket
import sys
Expand Down Expand Up @@ -53,6 +54,24 @@ def suppress_body(method: str, status_code: int) -> bool:
return method == "HEAD" or 100 <= status_code < 200 or status_code in {204, 304}


ABSOLUTE_FORM_REGEX = re.compile(rb"^[a-zA-Z][a-zA-Z0-9+.-]*://[^/?#]*")


def reduce_target_to_origin_form(target: bytes) -> bytes:
# RFC 9112 Section 3.2.2 requires a server to accept the
# absolute-form of a request target, with the origin-form being the
# equivalent target for the ASGI scope. An empty path is equivalent
# to "/" (RFC 9112 Section 3.2.1). Origin-form, asterisk-form and
# authority-form targets are returned unchanged.
match = ABSOLUTE_FORM_REGEX.match(target)
if match is None:
return target
remainder = target[match.end() :]
if remainder.startswith(b"/"):
return remainder
return b"/" + remainder


def build_and_validate_headers(headers: Iterable[tuple[bytes, bytes]]) -> list[tuple[bytes, bytes]]:
# Validates that the header name and value are bytes
validated_headers: list[tuple[bytes, bytes]] = []
Expand Down
34 changes: 34 additions & 0 deletions tests/protocol/test_http_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,40 @@ async def test_handle_request_http_1(stream: HTTPStream, http_version: str) -> N
}


@pytest.mark.parametrize(
"raw_path, path, reduced_raw_path, query_string",
[
(b"http://example.org/?a=b", "/", b"/", b"a=b"),
(b"http://example.org", "/", b"/", b""),
(b"http://example.org?a=b", "/", b"/", b"a=b"),
(b"https://user@example.org:8080/path?a=b", "/path", b"/path", b"a=b"),
(b"/?a=b", "/", b"/", b"a=b"), # origin-form is unchanged
(b"*", "*", b"*", b""), # asterisk-form is unchanged
],
)
@pytest.mark.asyncio
async def test_handle_request_absolute_form_target(
stream: HTTPStream, raw_path: bytes, path: str, reduced_raw_path: bytes, query_string: bytes
) -> None:
# RFC 9112 Section 3.2.2 requires a server to accept the
# absolute-form of a request target.
await stream.handle(
Request(
stream_id=1,
http_version="1.1",
headers=[],
raw_path=raw_path,
method="GET",
state=ConnectionState({}),
)
)
stream.task_group.spawn_app.assert_called() # type: ignore
scope = stream.task_group.spawn_app.call_args[0][2] # type: ignore
assert scope["path"] == path
assert scope["raw_path"] == reduced_raw_path
assert scope["query_string"] == query_string


@pytest.mark.asyncio
async def test_handle_request_http_2(stream: HTTPStream) -> None:
await stream.handle(
Expand Down
32 changes: 32 additions & 0 deletions tests/protocol/test_ws_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,38 @@ async def _stream() -> WSStream:
return stream


@pytest.mark.parametrize(
"raw_path, path, reduced_raw_path, query_string",
[
(b"http://example.org/ws?a=b", "/ws", b"/ws", b"a=b"),
(b"http://example.org", "/", b"/", b""),
(b"/?a=b", "/", b"/", b"a=b"), # origin-form is unchanged
],
)
@pytest.mark.asyncio
async def test_handle_request_absolute_form_target(
stream: WSStream, raw_path: bytes, path: str, reduced_raw_path: bytes, query_string: bytes
) -> None:
# RFC 9112 Section 3.2.2 requires a server to accept the
# absolute-form of a request target, including on the WebSocket
# handshake.
await stream.handle(
Request(
stream_id=1,
http_version="2",
headers=[(b"sec-websocket-version", b"13")],
raw_path=raw_path,
method="GET",
state=ConnectionState({}),
)
)
stream.task_group.spawn_app.assert_called() # type: ignore
scope = stream.task_group.spawn_app.call_args[0][2] # type: ignore
assert scope["path"] == path
assert scope["raw_path"] == reduced_raw_path
assert scope["query_string"] == query_string


@pytest.mark.asyncio
async def test_handle_request(stream: WSStream) -> None:
await stream.handle(
Expand Down
19 changes: 19 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
build_and_validate_headers,
filter_pseudo_headers,
is_asgi,
reduce_target_to_origin_form,
suppress_body,
)

Expand Down Expand Up @@ -80,3 +81,21 @@ def test_filter_pseudo_headers_no_authority() -> None:
[(b"host", b"quart"), (b":path", b"/"), (b"user-agent", b"something")]
)
assert result == [(b"host", b"quart"), (b"user-agent", b"something")]


@pytest.mark.parametrize(
"target, expected",
[
(b"/?a=b", b"/?a=b"), # origin-form is unchanged
(b"/a://b", b"/a://b"), # origin-form may contain "://"
(b"*", b"*"), # asterisk-form is unchanged
(b"example.org:443", b"example.org:443"), # authority-form is unchanged
(b"http://example.org/?a=b", b"/?a=b"),
(b"http://example.org", b"/"), # an empty path is equivalent to "/"
(b"http://example.org?a=b", b"/?a=b"),
(b"https://user@example.org:8080/path%20x?q=1", b"/path%20x?q=1"),
(b"HTTP://EXAMPLE.ORG/Path", b"/Path"), # the scheme is case-insensitive
],
)
def test_reduce_target_to_origin_form(target: bytes, expected: bytes) -> None:
assert reduce_target_to_origin_form(target) == expected