diff --git a/h11/_events.py b/h11/_events.py index ca1c3ad..a058845 100644 --- a/h11/_events.py +++ b/h11/_events.py @@ -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 @@ -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): @@ -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: diff --git a/h11/tests/test_events.py b/h11/tests/test_events.py index d691545..61ff995 100644 --- a/h11/tests/test_events.py +++ b/h11/tests/test_events.py @@ -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" diff --git a/newsfragments/218.bugfix.rst b/newsfragments/218.bugfix.rst new file mode 100644 index 0000000..0b0da4a --- /dev/null +++ b/newsfragments/218.bugfix.rst @@ -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``.