test_urllib3.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. # Copyright 2016 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import http.client as http_client
  15. import os
  16. import sys
  17. import mock
  18. import OpenSSL
  19. import pytest # type: ignore
  20. import urllib3 # type: ignore
  21. from google.auth import environment_vars
  22. from google.auth import exceptions
  23. import google.auth.credentials
  24. import google.auth.transport._mtls_helper
  25. import google.auth.transport.urllib3
  26. from google.oauth2 import service_account
  27. from tests.transport import compliance
  28. class TestRequestResponse(compliance.RequestResponseTests):
  29. def make_request(self):
  30. http = urllib3.PoolManager()
  31. return google.auth.transport.urllib3.Request(http)
  32. def test_timeout(self):
  33. http = mock.create_autospec(urllib3.PoolManager)
  34. request = google.auth.transport.urllib3.Request(http)
  35. request(url="http://example.com", method="GET", timeout=5)
  36. assert http.request.call_args[1]["timeout"] == 5
  37. def test__make_default_http_with_certifi():
  38. http = google.auth.transport.urllib3._make_default_http()
  39. assert "cert_reqs" in http.connection_pool_kw
  40. @mock.patch.object(google.auth.transport.urllib3, "certifi", new=None)
  41. def test__make_default_http_without_certifi():
  42. http = google.auth.transport.urllib3._make_default_http()
  43. assert "cert_reqs" not in http.connection_pool_kw
  44. class CredentialsStub(google.auth.credentials.Credentials):
  45. def __init__(self, token="token"):
  46. super(CredentialsStub, self).__init__()
  47. self.token = token
  48. def apply(self, headers, token=None):
  49. headers["authorization"] = self.token
  50. def before_request(self, request, method, url, headers):
  51. self.apply(headers)
  52. def refresh(self, request):
  53. self.token += "1"
  54. def with_quota_project(self, quota_project_id):
  55. raise NotImplementedError()
  56. class HttpStub(object):
  57. def __init__(self, responses, headers=None):
  58. self.responses = responses
  59. self.requests = []
  60. self.headers = headers or {}
  61. def urlopen(self, method, url, body=None, headers=None, **kwargs):
  62. self.requests.append((method, url, body, headers, kwargs))
  63. return self.responses.pop(0)
  64. def clear(self):
  65. pass
  66. class ResponseStub(object):
  67. def __init__(self, status=http_client.OK, data=None):
  68. self.status = status
  69. self.data = data
  70. class TestMakeMutualTlsHttp(object):
  71. def test_success(self):
  72. http = google.auth.transport.urllib3._make_mutual_tls_http(
  73. pytest.public_cert_bytes, pytest.private_key_bytes
  74. )
  75. assert isinstance(http, urllib3.PoolManager)
  76. def test_crypto_error(self):
  77. with pytest.raises(OpenSSL.crypto.Error):
  78. google.auth.transport.urllib3._make_mutual_tls_http(
  79. b"invalid cert", b"invalid key"
  80. )
  81. @mock.patch.dict("sys.modules", {"OpenSSL.crypto": None})
  82. def test_import_error(self):
  83. with pytest.raises(ImportError):
  84. google.auth.transport.urllib3._make_mutual_tls_http(
  85. pytest.public_cert_bytes, pytest.private_key_bytes
  86. )
  87. class TestAuthorizedHttp(object):
  88. TEST_URL = "http://example.com"
  89. def test_authed_http_defaults(self):
  90. authed_http = google.auth.transport.urllib3.AuthorizedHttp(
  91. mock.sentinel.credentials
  92. )
  93. assert authed_http.credentials == mock.sentinel.credentials
  94. assert isinstance(authed_http.http, urllib3.PoolManager)
  95. def test_urlopen_no_refresh(self):
  96. credentials = mock.Mock(wraps=CredentialsStub())
  97. response = ResponseStub()
  98. http = HttpStub([response])
  99. authed_http = google.auth.transport.urllib3.AuthorizedHttp(
  100. credentials, http=http
  101. )
  102. result = authed_http.urlopen("GET", self.TEST_URL)
  103. assert result == response
  104. assert credentials.before_request.called
  105. assert not credentials.refresh.called
  106. assert http.requests == [
  107. ("GET", self.TEST_URL, None, {"authorization": "token"}, {})
  108. ]
  109. def test_urlopen_refresh(self):
  110. credentials = mock.Mock(wraps=CredentialsStub())
  111. final_response = ResponseStub(status=http_client.OK)
  112. # First request will 401, second request will succeed.
  113. http = HttpStub([ResponseStub(status=http_client.UNAUTHORIZED), final_response])
  114. authed_http = google.auth.transport.urllib3.AuthorizedHttp(
  115. credentials, http=http
  116. )
  117. authed_http = authed_http.urlopen("GET", "http://example.com")
  118. assert authed_http == final_response
  119. assert credentials.before_request.call_count == 2
  120. assert credentials.refresh.called
  121. assert http.requests == [
  122. ("GET", self.TEST_URL, None, {"authorization": "token"}, {}),
  123. ("GET", self.TEST_URL, None, {"authorization": "token1"}, {}),
  124. ]
  125. def test_urlopen_no_default_host(self):
  126. credentials = mock.create_autospec(service_account.Credentials)
  127. authed_http = google.auth.transport.urllib3.AuthorizedHttp(credentials)
  128. authed_http.credentials._create_self_signed_jwt.assert_called_once_with(None)
  129. def test_urlopen_with_default_host(self):
  130. default_host = "pubsub.googleapis.com"
  131. credentials = mock.create_autospec(service_account.Credentials)
  132. authed_http = google.auth.transport.urllib3.AuthorizedHttp(
  133. credentials, default_host=default_host
  134. )
  135. authed_http.credentials._create_self_signed_jwt.assert_called_once_with(
  136. "https://{}/".format(default_host)
  137. )
  138. def test_proxies(self):
  139. http = mock.create_autospec(urllib3.PoolManager)
  140. authed_http = google.auth.transport.urllib3.AuthorizedHttp(None, http=http)
  141. with authed_http:
  142. pass
  143. assert http.__enter__.called
  144. assert http.__exit__.called
  145. authed_http.headers = mock.sentinel.headers
  146. assert authed_http.headers == http.headers
  147. @mock.patch("google.auth.transport.urllib3._make_mutual_tls_http", autospec=True)
  148. def test_configure_mtls_channel_with_callback(self, mock_make_mutual_tls_http):
  149. callback = mock.Mock()
  150. callback.return_value = (pytest.public_cert_bytes, pytest.private_key_bytes)
  151. authed_http = google.auth.transport.urllib3.AuthorizedHttp(
  152. credentials=mock.Mock(), http=mock.Mock()
  153. )
  154. with pytest.warns(UserWarning):
  155. with mock.patch.dict(
  156. os.environ, {environment_vars.GOOGLE_API_USE_CLIENT_CERTIFICATE: "true"}
  157. ):
  158. is_mtls = authed_http.configure_mtls_channel(callback)
  159. assert is_mtls
  160. mock_make_mutual_tls_http.assert_called_once_with(
  161. cert=pytest.public_cert_bytes, key=pytest.private_key_bytes
  162. )
  163. @mock.patch("google.auth.transport.urllib3._make_mutual_tls_http", autospec=True)
  164. @mock.patch(
  165. "google.auth.transport._mtls_helper.get_client_cert_and_key", autospec=True
  166. )
  167. def test_configure_mtls_channel_with_metadata(
  168. self, mock_get_client_cert_and_key, mock_make_mutual_tls_http
  169. ):
  170. authed_http = google.auth.transport.urllib3.AuthorizedHttp(
  171. credentials=mock.Mock()
  172. )
  173. mock_get_client_cert_and_key.return_value = (
  174. True,
  175. pytest.public_cert_bytes,
  176. pytest.private_key_bytes,
  177. )
  178. with mock.patch.dict(
  179. os.environ, {environment_vars.GOOGLE_API_USE_CLIENT_CERTIFICATE: "true"}
  180. ):
  181. is_mtls = authed_http.configure_mtls_channel()
  182. assert is_mtls
  183. mock_get_client_cert_and_key.assert_called_once()
  184. mock_make_mutual_tls_http.assert_called_once_with(
  185. cert=pytest.public_cert_bytes, key=pytest.private_key_bytes
  186. )
  187. @mock.patch("google.auth.transport.urllib3._make_mutual_tls_http", autospec=True)
  188. @mock.patch(
  189. "google.auth.transport._mtls_helper.get_client_cert_and_key", autospec=True
  190. )
  191. def test_configure_mtls_channel_non_mtls(
  192. self, mock_get_client_cert_and_key, mock_make_mutual_tls_http
  193. ):
  194. authed_http = google.auth.transport.urllib3.AuthorizedHttp(
  195. credentials=mock.Mock()
  196. )
  197. mock_get_client_cert_and_key.return_value = (False, None, None)
  198. with mock.patch.dict(
  199. os.environ, {environment_vars.GOOGLE_API_USE_CLIENT_CERTIFICATE: "true"}
  200. ):
  201. is_mtls = authed_http.configure_mtls_channel()
  202. assert not is_mtls
  203. mock_get_client_cert_and_key.assert_called_once()
  204. mock_make_mutual_tls_http.assert_not_called()
  205. @mock.patch(
  206. "google.auth.transport._mtls_helper.get_client_cert_and_key", autospec=True
  207. )
  208. def test_configure_mtls_channel_exceptions(self, mock_get_client_cert_and_key):
  209. authed_http = google.auth.transport.urllib3.AuthorizedHttp(
  210. credentials=mock.Mock()
  211. )
  212. mock_get_client_cert_and_key.side_effect = exceptions.ClientCertError()
  213. with pytest.raises(exceptions.MutualTLSChannelError):
  214. with mock.patch.dict(
  215. os.environ, {environment_vars.GOOGLE_API_USE_CLIENT_CERTIFICATE: "true"}
  216. ):
  217. authed_http.configure_mtls_channel()
  218. mock_get_client_cert_and_key.return_value = (False, None, None)
  219. with mock.patch.dict("sys.modules"):
  220. sys.modules["OpenSSL"] = None
  221. with pytest.raises(exceptions.MutualTLSChannelError):
  222. with mock.patch.dict(
  223. os.environ,
  224. {environment_vars.GOOGLE_API_USE_CLIENT_CERTIFICATE: "true"},
  225. ):
  226. authed_http.configure_mtls_channel()
  227. @mock.patch(
  228. "google.auth.transport._mtls_helper.get_client_cert_and_key", autospec=True
  229. )
  230. def test_configure_mtls_channel_without_client_cert_env(
  231. self, get_client_cert_and_key
  232. ):
  233. callback = mock.Mock()
  234. authed_http = google.auth.transport.urllib3.AuthorizedHttp(
  235. credentials=mock.Mock(), http=mock.Mock()
  236. )
  237. # Test the callback is not called if GOOGLE_API_USE_CLIENT_CERTIFICATE is not set.
  238. is_mtls = authed_http.configure_mtls_channel(callback)
  239. assert not is_mtls
  240. callback.assert_not_called()
  241. # Test ADC client cert is not used if GOOGLE_API_USE_CLIENT_CERTIFICATE is not set.
  242. is_mtls = authed_http.configure_mtls_channel(callback)
  243. assert not is_mtls
  244. get_client_cert_and_key.assert_not_called()
  245. def test_clear_pool_on_del(self):
  246. http = mock.create_autospec(urllib3.PoolManager)
  247. authed_http = google.auth.transport.urllib3.AuthorizedHttp(
  248. mock.sentinel.credentials, http=http
  249. )
  250. authed_http.__del__()
  251. http.clear.assert_called_with()
  252. authed_http.http = None
  253. authed_http.__del__()
  254. # Expect it to not crash