Skip to content

Commit

Permalink
treq.auth: Don't mutate request headers
Browse files Browse the repository at this point in the history
Instead, copy and update.

Closes twisted#314.
  • Loading branch information
twm committed Dec 26, 2020
1 parent ace1faf commit 1fba8e0
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog.d/314.bugfix.rst
@@ -0,0 +1 @@
treq request APIs no longer mutates a :class:`http_headers.Headers <twisted.web.http_headers.Headers>` passed as the *headers* parameter when the *auth* parameter is also passed.
8 changes: 4 additions & 4 deletions src/treq/auth.py
Expand Up @@ -35,14 +35,14 @@ def __init__(self, agent, request_headers):

def request(self, method, uri, headers=None, bodyProducer=None):
if headers is None:
headers = self._request_headers
new = self._request_headers
else:
# FIXME: This mutates *headers*
new = headers.copy()
for header, values in self._request_headers.getAllRawHeaders():
headers.setRawHeaders(header, values)
new.setRawHeaders(header, values)

return self._agent.request(
method, uri, headers=headers, bodyProducer=bodyProducer)
method, uri, headers=new, bodyProducer=bodyProducer)


def add_basic_auth(agent, username, password):
Expand Down
16 changes: 16 additions & 0 deletions src/treq/test/test_auth.py
Expand Up @@ -39,6 +39,22 @@ def test_overrides_per_request_headers(self):
Headers({b'X-Test-Header': [b'Test-Header-Value']}),
)

def test_no_mutation(self):
"""
The agent never mutates the headers passed to its request method.
This reproduces https://github.com/twisted/treq/issues/314
"""
requestHeaders = Headers({})
agent = _RequestHeaderSettingAgent(
self.agent,
Headers({b'Added': [b'1']}),
)

agent.request(b'method', b'uri', headers=requestHeaders)

self.assertEqual(requestHeaders, Headers({}))


class AddAuthTests(SynchronousTestCase):
def test_add_basic_auth(self):
Expand Down

0 comments on commit 1fba8e0

Please sign in to comment.