Skip to content

Commit b7e9caf

Browse files
authored
avoid mutating request headers in-place (#113)
Previously, the `spin_sdk.http.send` function automatically added a `content-length` header to the header dictionary supplied by the caller if one was not already present and if a request body was specified. However, since we were mutating the dictionary in-place, the change was visible to the caller. In addition to being potentially surprising to the caller, that can lead to issues if the same object is reused for another request later, at which point the header we added earlier will still be present but not necessarily accurate for the new request. To avoid such confusion, we now make a copy and add the `content-length` header to the copy. Signed-off-by: Joel Dice <joel.dice@fermyon.com>
1 parent eb16617 commit b7e9caf

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

src/spin_sdk/http/__init__.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -164,13 +164,20 @@ async def send_async(request: Request) -> Response:
164164
case _:
165165
scheme = Scheme_Other(url_parsed.scheme)
166166

167-
if request.headers.get('content-length') is None:
167+
headers_dict = request.headers
168+
169+
# Add a `content-length` header if the caller didn't include one, but did
170+
# specify a body:
171+
if headers_dict.get('content-length') is None:
168172
content_length = len(request.body) if request.body is not None else 0
169-
request.headers['content-length'] = str(content_length)
173+
# Make a copy rather than mutate in place, since the caller might not
174+
# expect us to mutate it:
175+
headers_dict = headers_dict.copy()
176+
headers_dict['content-length'] = str(content_length)
170177

171178
headers = list(map(
172179
lambda pair: (pair[0], bytes(pair[1], "utf-8")),
173-
request.headers.items()
180+
headers_dict.items()
174181
))
175182

176183
outgoing_request = OutgoingRequest(Fields.from_list(headers))

0 commit comments

Comments
 (0)