FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

gh-159044: Restore string conversion for HTTP tunnel header values by bielpieroli · Pull Request #159216 · python/cpython · GitHub

Repository navigation

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) .rst  (2) All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
3 changes: 2 additions & 1 deletion Doc/library/http.client.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,8 @@ HTTPConnection Objects
proxy server).

The *headers* argument should be a mapping of extra HTTP headers to send with
the CONNECT request.
the CONNECT request. Non-string header values are converted to strings via
:func:`str`.

As HTTP/1.1 is used for HTTP CONNECT tunnelling request, `as per the RFC
<https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.6>`_, a HTTP ``Host:``
Expand Down
2 changes: 1 addition & 1 deletion Lib/http/client.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -1015,7 +1015,7 @@ def _tunnel(self):
headers = [connect]
for header, value in self._tunnel_headers.items():
header_bytes = header.encode("latin-1")
value_bytes = value.encode("latin-1")
value_bytes = str(value).encode("latin-1")
if not _is_legal_header_name(header_bytes):
raise ValueError('Invalid header name %r' % (header_bytes,))
if _is_illegal_header_value(value_bytes):
Expand Down
17 changes: 17 additions & 0 deletions Lib/test/test_httplib.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -2793,6 +2793,23 @@ def _create_connection(address, timeout=None, source_address=None):
self.assertIsNotNone(exc)
self.assertTrue(sock.file_closed)

def test_tunnel_nonstr_headers(self):
class CustomObject:
def __str__(self):
return 'custom-str'

self.conn.set_tunnel('destination.com', headers={

edvilme Oct 12, 2026 •
edited
Loading

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality
Suggested change
self.conn.set_tunnel('destination.com', headers={
self.conn.set_tunnel('example.com', headers={

If you are using an example domain maybe use that one instead (destination.com is a real non-example domain)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Thanks for the suggestion, @edvilme! I used destination.com to stay consistent with the other tests in TunnelTests. The file also uses example.com, but in this class destination.com is the most common. So I'd lean towards keeping it, but I'm happy to switch to example.com if you think it reads better.

'None-Value': None,
'Integer-Value': 9,
'Custom-Value': CustomObject(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

You are converting header values and keys to strings. Maybe the tests can also include this to avoid future regressions?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Good idea, I think it makes sense.

However, I tried adding a non-string key to the test, but it fails earlier: set_tunnel() calls header.lower() on every key to check for a Host header, so non-string keys raise AttributeError there, before _tunnel() is reached.

That check predates this issue, so supporting non-string keys would probably be new behavior.

I think it'd make sense to update the docs to only mention values. Do you think that's the right approach?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality
ERROR: test_tunnel_nonstr_headers (test.test_httplib.TunnelTests.test_tunnel_nonstr_headers)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".../cpython/Lib/test/test_httplib.py", line 2801, in test_tunnel_nonstr_headers
    self.conn.set_tunnel('destination.com', headers={
    ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        'None-Value': None,
        ^^^^^^^^^^^^^^^^^^^
    ...<4 lines>...
        None: 'none-key',
        ^^^^^^^^^^^^^^^^^
    })
    ^^
  File ".../cpython/Lib/http/client.py", line 974, in set_tunnel
    if not any(header.lower() == "host" for header in self._tunnel_headers):
           ^^^
  File ".../cpython/Lib/http/client.py", line 974, in <genexpr>
    if not any(header.lower() == "host" for header in self._tunnel_headers):
               ^^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'lower'

----------------------------------------------------------------------

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Yes, let's just limit the PR to values only if keys didn't work anyway.

bielpieroli Oct 12, 2026 •
edited
Loading

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Thanks for the review, @ZeroIntensity! I reverted str() on keys (since non-string keys already fail earlier in set_tunnel() at the header.lower() check) and updated the docs to mention only values.

-            header_bytes = str(header).encode("latin-1")
+            header_bytes = header.encode("latin-1")
             value_bytes = str(value).encode("latin-1")

And thanks a lot, @edvilme, for the discussion here and in the issue. Your review comments helped us find this gap in the set_tunnel() key check, which we wouldn't have noticed otherwise :D

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Thank YOU, glad you found it :)

})

self.conn.request('HEAD', '/', '')

self.assertIn(b'None-Value: None\r\n', self.conn.sock.data)
self.assertIn(b'Integer-Value: 9\r\n', self.conn.sock.data)
self.assertIn(b'Custom-Value: custom-str\r\n', self.conn.sock.data)


if __name__ == '__main__':
unittest.main(verbosity=2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Restore the previous behaviour of :meth:`http.client.HTTPConnection.set_tunnel`
where header values that are not strings (such as :const:`None`, :class:`int`
or other objects) are converted with :class:`str` instead of raising
:exc:`AttributeError` when the request is sent.
Loading

Back | FazBrowse Home | New Git URL