Skip to content

Commit

Permalink
requests: Do not leak header modifications when calling request.
Browse files Browse the repository at this point in the history
The requests() function takes a headers dict argument
(call-by-reference). This object is then modified in the function. For
instance the host is added and authentication information. Such behavior
is not expected. It is also problematic:

- Modifications of the header dictionary will be visible on the caller
  site.
- When reusing the same (supposedly read-only) headers object for
  differenct calls, the second call will apparently re-use wrong headers
  from the previous call and may fail.

This patch should also fix #839.

Signed-off-by: Richard Weickelt <[email protected]>
  • Loading branch information
rweickelt committed Dec 11, 2024
1 parent e4cf095 commit 64ca392
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
2 changes: 2 additions & 0 deletions python-ecosys/requests/requests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ def request(
):
if headers is None:
headers = {}
else:
headers = dict(headers)

redirect = None # redirection url, None means no redirection
chunked_data = data and getattr(data, "__next__", None) and not getattr(data, "__len__", None)
Expand Down
7 changes: 7 additions & 0 deletions python-ecosys/requests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ def test_get_custom_header():
+ b"Connection: close\r\n\r\n"
), format_message(response)

def test_do_not_modify_headers_argument():
original_headers = {}
headers = dict(original_headers)
response = requests.request("GET", "http://example.com", headers=original_headers)

Check failure on line 76 in python-ecosys/requests/test_requests.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F841)

python-ecosys/requests/test_requests.py:76:5: F841 Local variable `response` is assigned to but never used

assert headers == original_headers

def test_post_json():
response = requests.request("GET", "http://example.com", json="test")
Expand Down Expand Up @@ -148,6 +154,7 @@ def chunks():
test_simple_get()
test_get_auth()
test_get_custom_header()
test_do_not_modify_headers_argument()
test_post_json()
test_post_chunked_data()
test_overwrite_get_headers()
Expand Down

0 comments on commit 64ca392

Please sign in to comment.