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
5 changes: 4 additions & 1 deletion h11/_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from dataclasses import dataclass
from typing import List, Tuple, Union

from ._abnf import method, request_target
from ._abnf import method, reason_phrase, request_target
from ._headers import Headers, normalize_and_validate
from ._util import bytesify, LocalProtocolError, validate

Expand All @@ -27,6 +27,7 @@

method_re = re.compile(method.encode("ascii"))
request_target_re = re.compile(request_target.encode("ascii"))
reason_phrase_re = re.compile(reason_phrase.encode("ascii"))


class Event(ABC):
Expand Down Expand Up @@ -163,6 +164,8 @@ def __init__(
object.__setattr__(self, "http_version", http_version)
object.__setattr__(self, "status_code", status_code)

validate(reason_phrase_re, self.reason, "Illegal reason phrase")

self.__post_init__()

def __post_init__(self) -> None:
Expand Down
9 changes: 9 additions & 0 deletions h11/tests/test_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,15 @@ def test_events() -> None:
with pytest.raises(LocalProtocolError):
InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type]

resp = Response(status_code=200, headers=[], reason="Totally OK\tfine")
assert resp.reason == b"Totally OK\tfine"

for bad_reason in [b"OK\r\nSet-Cookie: a=b", b"OK\n", b"OK\r", b"OK\x00"]:
with pytest.raises(LocalProtocolError):
Response(status_code=200, headers=[], reason=bad_reason)
with pytest.raises(LocalProtocolError):
InformationalResponse(status_code=100, headers=[], reason=bad_reason)

d = Data(data=b"asdf")
assert d.data == b"asdf"

Expand Down
1 change: 1 addition & 0 deletions newsfragments/218.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Reject a ``reason`` containing characters that are not allowed in an HTTP reason phrase, such as CR or LF, when constructing ``Response`` and ``InformationalResponse``.