fix: always pass body of type bytes to `google.auth.transport.Request` (#421)
[`google.auth.transport.Request`](https://google-auth.readthedocs.io/en/latest/reference/google.auth.transport.html#google.auth.transport.Request) says that the body should be of type bytes. Some of our code was passing in strings as reported in #318.
In practice this was not causing issues, as the two http transports [requests](https://google-auth.readthedocs.io/en/latest/reference/google.auth.transport.requests.html) and [urllib3](https://google-auth.readthedocs.io/en/latest/reference/google.auth.transport.urllib3.html) are able to handle bodies passed as strings.
diff --git a/google/auth/iam.py b/google/auth/iam.py
index a438726..0ab5b55 100644
--- a/google/auth/iam.py
+++ b/google/auth/iam.py
@@ -70,7 +70,9 @@
method = "POST"
url = _SIGN_BLOB_URI.format(self._service_account_email)
headers = {}
- body = json.dumps({"bytesToSign": base64.b64encode(message).decode("utf-8")})
+ body = json.dumps(
+ {"bytesToSign": base64.b64encode(message).decode("utf-8")}
+ ).encode("utf-8")
self._credentials.before_request(self._request, method, url, headers)
response = self._request(url=url, method=method, body=body, headers=headers)
diff --git a/google/auth/impersonated_credentials.py b/google/auth/impersonated_credentials.py
index 70fa5dc..bc7031e 100644
--- a/google/auth/impersonated_credentials.py
+++ b/google/auth/impersonated_credentials.py
@@ -84,7 +84,7 @@
"""
iam_endpoint = _IAM_ENDPOINT.format(principal)
- body = json.dumps(body)
+ body = json.dumps(body).encode("utf-8")
response = request(url=iam_endpoint, method="POST", headers=headers, body=body)
diff --git a/google/oauth2/_client.py b/google/oauth2/_client.py
index 4cf7a7f..4ba31a8 100644
--- a/google/oauth2/_client.py
+++ b/google/oauth2/_client.py
@@ -95,7 +95,7 @@
google.auth.exceptions.RefreshError: If the token endpoint returned
an error.
"""
- body = urllib.parse.urlencode(body)
+ body = urllib.parse.urlencode(body).encode("utf-8")
headers = {"content-type": _URLENCODED_CONTENT_TYPE}
retry = 0
diff --git a/tests/oauth2/test__client.py b/tests/oauth2/test__client.py
index 9cf59eb..052390a 100644
--- a/tests/oauth2/test__client.py
+++ b/tests/oauth2/test__client.py
@@ -96,7 +96,7 @@
method="POST",
url="http://example.com",
headers={"content-type": "application/x-www-form-urlencoded"},
- body="test=params",
+ body="test=params".encode("utf-8"),
)
# Check result
@@ -131,7 +131,7 @@
def verify_request_params(request, params):
- request_body = request.call_args[1]["body"]
+ request_body = request.call_args[1]["body"].decode("utf-8")
request_params = urllib.parse.parse_qs(request_body)
for key, value in six.iteritems(params):