From 39e42455b4abc7d71e466e93882c988ec303d5e1 Mon Sep 17 00:00:00 2001 From: Miro <200482516+Mirochill@users.noreply.github.com> Date: Mon, 18 May 2026 19:03:46 +0200 Subject: [PATCH] Preserve explicit Connection header casing --- h11/_connection.py | 7 ++++--- h11/tests/test_connection.py | 17 +++++++++++++++++ newsfragments/156.bugfix.rst | 2 ++ 3 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 newsfragments/156.bugfix.rst diff --git a/h11/_connection.py b/h11/_connection.py index e37d82a..ccf0a64 100644 --- a/h11/_connection.py +++ b/h11/_connection.py @@ -647,9 +647,10 @@ def _clean_up_response_headers_for_sending(self, response: Response) -> Response if not self._cstate.keep_alive or need_close: # Make sure Connection: close is set connection = set(get_comma_header(headers, b"connection")) - connection.discard(b"keep-alive") - connection.add(b"close") - headers = set_comma_header(headers, b"connection", sorted(connection)) + if b"close" not in connection or b"keep-alive" in connection: + connection.discard(b"keep-alive") + connection.add(b"close") + headers = set_comma_header(headers, b"connection", sorted(connection)) return Response( headers=headers, diff --git a/h11/tests/test_connection.py b/h11/tests/test_connection.py index 01260dc..22ed966 100644 --- a/h11/tests/test_connection.py +++ b/h11/tests/test_connection.py @@ -365,6 +365,23 @@ def test_automagic_connection_close_handling() -> None: assert conn.states == {CLIENT: MUST_CLOSE, SERVER: MUST_CLOSE} +def test_explicit_connection_close_preserves_header_case() -> None: + c = Connection(SERVER) + c.receive_data( + b"GET / HTTP/1.1\r\n" + b"Host: example.com\r\n" + b"Connection: close\r\n" + b"\r\n" + ) + assert isinstance(c.next_event(), Request) + assert isinstance(c.next_event(), EndOfMessage) + + assert ( + c.send(Response(status_code=204, headers=[("connection", "close")])) + == b"HTTP/1.1 204 \r\nconnection: close\r\n\r\n" + ) + + def test_100_continue() -> None: def setup() -> ConnectionPair: p = ConnectionPair() diff --git a/newsfragments/156.bugfix.rst b/newsfragments/156.bugfix.rst new file mode 100644 index 0000000..4aa62ae --- /dev/null +++ b/newsfragments/156.bugfix.rst @@ -0,0 +1,2 @@ +Preserve an explicitly provided ``Connection`` header's original casing when +it already requests ``close``.