requests.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. """Transport adapter for Requests."""
  15. from __future__ import absolute_import
  16. import functools
  17. import logging
  18. import numbers
  19. import os
  20. import time
  21. try:
  22. import requests
  23. except ImportError as caught_exc: # pragma: NO COVER
  24. import six
  25. six.raise_from(
  26. ImportError(
  27. "The requests library is not installed, please install the "
  28. "requests package to use the requests transport."
  29. ),
  30. caught_exc,
  31. )
  32. import requests.adapters # pylint: disable=ungrouped-imports
  33. import requests.exceptions # pylint: disable=ungrouped-imports
  34. from requests.packages.urllib3.util.ssl_ import (
  35. create_urllib3_context,
  36. ) # pylint: disable=ungrouped-imports
  37. import six # pylint: disable=ungrouped-imports
  38. from google.auth import environment_vars
  39. from google.auth import exceptions
  40. from google.auth import transport
  41. import google.auth.transport._mtls_helper
  42. from google.oauth2 import service_account
  43. _LOGGER = logging.getLogger(__name__)
  44. _DEFAULT_TIMEOUT = 120 # in seconds
  45. class _Response(transport.Response):
  46. """Requests transport response adapter.
  47. Args:
  48. response (requests.Response): The raw Requests response.
  49. """
  50. def __init__(self, response):
  51. self._response = response
  52. @property
  53. def status(self):
  54. return self._response.status_code
  55. @property
  56. def headers(self):
  57. return self._response.headers
  58. @property
  59. def data(self):
  60. return self._response.content
  61. class TimeoutGuard(object):
  62. """A context manager raising an error if the suite execution took too long.
  63. Args:
  64. timeout (Union[None, Union[float, Tuple[float, float]]]):
  65. The maximum number of seconds a suite can run without the context
  66. manager raising a timeout exception on exit. If passed as a tuple,
  67. the smaller of the values is taken as a timeout. If ``None``, a
  68. timeout error is never raised.
  69. timeout_error_type (Optional[Exception]):
  70. The type of the error to raise on timeout. Defaults to
  71. :class:`requests.exceptions.Timeout`.
  72. """
  73. def __init__(self, timeout, timeout_error_type=requests.exceptions.Timeout):
  74. self._timeout = timeout
  75. self.remaining_timeout = timeout
  76. self._timeout_error_type = timeout_error_type
  77. def __enter__(self):
  78. self._start = time.time()
  79. return self
  80. def __exit__(self, exc_type, exc_value, traceback):
  81. if exc_value:
  82. return # let the error bubble up automatically
  83. if self._timeout is None:
  84. return # nothing to do, the timeout was not specified
  85. elapsed = time.time() - self._start
  86. deadline_hit = False
  87. if isinstance(self._timeout, numbers.Number):
  88. self.remaining_timeout = self._timeout - elapsed
  89. deadline_hit = self.remaining_timeout <= 0
  90. else:
  91. self.remaining_timeout = tuple(x - elapsed for x in self._timeout)
  92. deadline_hit = min(self.remaining_timeout) <= 0
  93. if deadline_hit:
  94. raise self._timeout_error_type()
  95. class Request(transport.Request):
  96. """Requests request adapter.
  97. This class is used internally for making requests using various transports
  98. in a consistent way. If you use :class:`AuthorizedSession` you do not need
  99. to construct or use this class directly.
  100. This class can be useful if you want to manually refresh a
  101. :class:`~google.auth.credentials.Credentials` instance::
  102. import google.auth.transport.requests
  103. import requests
  104. request = google.auth.transport.requests.Request()
  105. credentials.refresh(request)
  106. Args:
  107. session (requests.Session): An instance :class:`requests.Session` used
  108. to make HTTP requests. If not specified, a session will be created.
  109. .. automethod:: __call__
  110. """
  111. def __init__(self, session=None):
  112. if not session:
  113. session = requests.Session()
  114. self.session = session
  115. def __call__(
  116. self,
  117. url,
  118. method="GET",
  119. body=None,
  120. headers=None,
  121. timeout=_DEFAULT_TIMEOUT,
  122. **kwargs
  123. ):
  124. """Make an HTTP request using requests.
  125. Args:
  126. url (str): The URI to be requested.
  127. method (str): The HTTP method to use for the request. Defaults
  128. to 'GET'.
  129. body (bytes): The payload or body in HTTP request.
  130. headers (Mapping[str, str]): Request headers.
  131. timeout (Optional[int]): The number of seconds to wait for a
  132. response from the server. If not specified or if None, the
  133. requests default timeout will be used.
  134. kwargs: Additional arguments passed through to the underlying
  135. requests :meth:`~requests.Session.request` method.
  136. Returns:
  137. google.auth.transport.Response: The HTTP response.
  138. Raises:
  139. google.auth.exceptions.TransportError: If any exception occurred.
  140. """
  141. try:
  142. _LOGGER.debug("Making request: %s %s", method, url)
  143. response = self.session.request(
  144. method, url, data=body, headers=headers, timeout=timeout, **kwargs
  145. )
  146. return _Response(response)
  147. except requests.exceptions.RequestException as caught_exc:
  148. new_exc = exceptions.TransportError(caught_exc)
  149. six.raise_from(new_exc, caught_exc)
  150. class _MutualTlsAdapter(requests.adapters.HTTPAdapter):
  151. """
  152. A TransportAdapter that enables mutual TLS.
  153. Args:
  154. cert (bytes): client certificate in PEM format
  155. key (bytes): client private key in PEM format
  156. Raises:
  157. ImportError: if certifi or pyOpenSSL is not installed
  158. OpenSSL.crypto.Error: if client cert or key is invalid
  159. """
  160. def __init__(self, cert, key):
  161. import certifi
  162. from OpenSSL import crypto
  163. import urllib3.contrib.pyopenssl
  164. urllib3.contrib.pyopenssl.inject_into_urllib3()
  165. pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
  166. x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
  167. ctx_poolmanager = create_urllib3_context()
  168. ctx_poolmanager.load_verify_locations(cafile=certifi.where())
  169. ctx_poolmanager._ctx.use_certificate(x509)
  170. ctx_poolmanager._ctx.use_privatekey(pkey)
  171. self._ctx_poolmanager = ctx_poolmanager
  172. ctx_proxymanager = create_urllib3_context()
  173. ctx_proxymanager.load_verify_locations(cafile=certifi.where())
  174. ctx_proxymanager._ctx.use_certificate(x509)
  175. ctx_proxymanager._ctx.use_privatekey(pkey)
  176. self._ctx_proxymanager = ctx_proxymanager
  177. super(_MutualTlsAdapter, self).__init__()
  178. def init_poolmanager(self, *args, **kwargs):
  179. kwargs["ssl_context"] = self._ctx_poolmanager
  180. super(_MutualTlsAdapter, self).init_poolmanager(*args, **kwargs)
  181. def proxy_manager_for(self, *args, **kwargs):
  182. kwargs["ssl_context"] = self._ctx_proxymanager
  183. return super(_MutualTlsAdapter, self).proxy_manager_for(*args, **kwargs)
  184. class AuthorizedSession(requests.Session):
  185. """A Requests Session class with credentials.
  186. This class is used to perform requests to API endpoints that require
  187. authorization::
  188. from google.auth.transport.requests import AuthorizedSession
  189. authed_session = AuthorizedSession(credentials)
  190. response = authed_session.request(
  191. 'GET', 'https://www.googleapis.com/storage/v1/b')
  192. The underlying :meth:`request` implementation handles adding the
  193. credentials' headers to the request and refreshing credentials as needed.
  194. This class also supports mutual TLS via :meth:`configure_mtls_channel`
  195. method. In order to use this method, the `GOOGLE_API_USE_CLIENT_CERTIFICATE`
  196. environment variable must be explicitly set to ``true``, otherwise it does
  197. nothing. Assume the environment is set to ``true``, the method behaves in the
  198. following manner:
  199. If client_cert_callback is provided, client certificate and private
  200. key are loaded using the callback; if client_cert_callback is None,
  201. application default SSL credentials will be used. Exceptions are raised if
  202. there are problems with the certificate, private key, or the loading process,
  203. so it should be called within a try/except block.
  204. First we set the environment variable to ``true``, then create an :class:`AuthorizedSession`
  205. instance and specify the endpoints::
  206. regular_endpoint = 'https://pubsub.googleapis.com/v1/projects/{my_project_id}/topics'
  207. mtls_endpoint = 'https://pubsub.mtls.googleapis.com/v1/projects/{my_project_id}/topics'
  208. authed_session = AuthorizedSession(credentials)
  209. Now we can pass a callback to :meth:`configure_mtls_channel`::
  210. def my_cert_callback():
  211. # some code to load client cert bytes and private key bytes, both in
  212. # PEM format.
  213. some_code_to_load_client_cert_and_key()
  214. if loaded:
  215. return cert, key
  216. raise MyClientCertFailureException()
  217. # Always call configure_mtls_channel within a try/except block.
  218. try:
  219. authed_session.configure_mtls_channel(my_cert_callback)
  220. except:
  221. # handle exceptions.
  222. if authed_session.is_mtls:
  223. response = authed_session.request('GET', mtls_endpoint)
  224. else:
  225. response = authed_session.request('GET', regular_endpoint)
  226. You can alternatively use application default SSL credentials like this::
  227. try:
  228. authed_session.configure_mtls_channel()
  229. except:
  230. # handle exceptions.
  231. Args:
  232. credentials (google.auth.credentials.Credentials): The credentials to
  233. add to the request.
  234. refresh_status_codes (Sequence[int]): Which HTTP status codes indicate
  235. that credentials should be refreshed and the request should be
  236. retried.
  237. max_refresh_attempts (int): The maximum number of times to attempt to
  238. refresh the credentials and retry the request.
  239. refresh_timeout (Optional[int]): The timeout value in seconds for
  240. credential refresh HTTP requests.
  241. auth_request (google.auth.transport.requests.Request):
  242. (Optional) An instance of
  243. :class:`~google.auth.transport.requests.Request` used when
  244. refreshing credentials. If not passed,
  245. an instance of :class:`~google.auth.transport.requests.Request`
  246. is created.
  247. default_host (Optional[str]): A host like "pubsub.googleapis.com".
  248. This is used when a self-signed JWT is created from service
  249. account credentials.
  250. """
  251. def __init__(
  252. self,
  253. credentials,
  254. refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
  255. max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
  256. refresh_timeout=None,
  257. auth_request=None,
  258. default_host=None,
  259. ):
  260. super(AuthorizedSession, self).__init__()
  261. self.credentials = credentials
  262. self._refresh_status_codes = refresh_status_codes
  263. self._max_refresh_attempts = max_refresh_attempts
  264. self._refresh_timeout = refresh_timeout
  265. self._is_mtls = False
  266. self._default_host = default_host
  267. if auth_request is None:
  268. self._auth_request_session = requests.Session()
  269. # Using an adapter to make HTTP requests robust to network errors.
  270. # This adapter retrys HTTP requests when network errors occur
  271. # and the requests seems safely retryable.
  272. retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
  273. self._auth_request_session.mount("https://", retry_adapter)
  274. # Do not pass `self` as the session here, as it can lead to
  275. # infinite recursion.
  276. auth_request = Request(self._auth_request_session)
  277. else:
  278. self._auth_request_session = None
  279. # Request instance used by internal methods (for example,
  280. # credentials.refresh).
  281. self._auth_request = auth_request
  282. # https://google.aip.dev/auth/4111
  283. # Attempt to use self-signed JWTs when a service account is used.
  284. if isinstance(self.credentials, service_account.Credentials):
  285. self.credentials._create_self_signed_jwt(
  286. "https://{}/".format(self._default_host) if self._default_host else None
  287. )
  288. def configure_mtls_channel(self, client_cert_callback=None):
  289. """Configure the client certificate and key for SSL connection.
  290. The function does nothing unless `GOOGLE_API_USE_CLIENT_CERTIFICATE` is
  291. explicitly set to `true`. In this case if client certificate and key are
  292. successfully obtained (from the given client_cert_callback or from application
  293. default SSL credentials), a :class:`_MutualTlsAdapter` instance will be mounted
  294. to "https://" prefix.
  295. Args:
  296. client_cert_callback (Optional[Callable[[], (bytes, bytes)]]):
  297. The optional callback returns the client certificate and private
  298. key bytes both in PEM format.
  299. If the callback is None, application default SSL credentials
  300. will be used.
  301. Raises:
  302. google.auth.exceptions.MutualTLSChannelError: If mutual TLS channel
  303. creation failed for any reason.
  304. """
  305. use_client_cert = os.getenv(
  306. environment_vars.GOOGLE_API_USE_CLIENT_CERTIFICATE, "false"
  307. )
  308. if use_client_cert != "true":
  309. self._is_mtls = False
  310. return
  311. try:
  312. import OpenSSL
  313. except ImportError as caught_exc:
  314. new_exc = exceptions.MutualTLSChannelError(caught_exc)
  315. six.raise_from(new_exc, caught_exc)
  316. try:
  317. (
  318. self._is_mtls,
  319. cert,
  320. key,
  321. ) = google.auth.transport._mtls_helper.get_client_cert_and_key(
  322. client_cert_callback
  323. )
  324. if self._is_mtls:
  325. mtls_adapter = _MutualTlsAdapter(cert, key)
  326. self.mount("https://", mtls_adapter)
  327. except (
  328. exceptions.ClientCertError,
  329. ImportError,
  330. OpenSSL.crypto.Error,
  331. ) as caught_exc:
  332. new_exc = exceptions.MutualTLSChannelError(caught_exc)
  333. six.raise_from(new_exc, caught_exc)
  334. def request(
  335. self,
  336. method,
  337. url,
  338. data=None,
  339. headers=None,
  340. max_allowed_time=None,
  341. timeout=_DEFAULT_TIMEOUT,
  342. **kwargs
  343. ):
  344. """Implementation of Requests' request.
  345. Args:
  346. timeout (Optional[Union[float, Tuple[float, float]]]):
  347. The amount of time in seconds to wait for the server response
  348. with each individual request. Can also be passed as a tuple
  349. ``(connect_timeout, read_timeout)``. See :meth:`requests.Session.request`
  350. documentation for details.
  351. max_allowed_time (Optional[float]):
  352. If the method runs longer than this, a ``Timeout`` exception is
  353. automatically raised. Unlike the ``timeout`` parameter, this
  354. value applies to the total method execution time, even if
  355. multiple requests are made under the hood.
  356. Mind that it is not guaranteed that the timeout error is raised
  357. at ``max_allowed_time``. It might take longer, for example, if
  358. an underlying request takes a lot of time, but the request
  359. itself does not timeout, e.g. if a large file is being
  360. transmitted. The timout error will be raised after such
  361. request completes.
  362. """
  363. # pylint: disable=arguments-differ
  364. # Requests has a ton of arguments to request, but only two
  365. # (method, url) are required. We pass through all of the other
  366. # arguments to super, so no need to exhaustively list them here.
  367. # Use a kwarg for this instead of an attribute to maintain
  368. # thread-safety.
  369. _credential_refresh_attempt = kwargs.pop("_credential_refresh_attempt", 0)
  370. # Make a copy of the headers. They will be modified by the credentials
  371. # and we want to pass the original headers if we recurse.
  372. request_headers = headers.copy() if headers is not None else {}
  373. # Do not apply the timeout unconditionally in order to not override the
  374. # _auth_request's default timeout.
  375. auth_request = (
  376. self._auth_request
  377. if timeout is None
  378. else functools.partial(self._auth_request, timeout=timeout)
  379. )
  380. remaining_time = max_allowed_time
  381. with TimeoutGuard(remaining_time) as guard:
  382. self.credentials.before_request(auth_request, method, url, request_headers)
  383. remaining_time = guard.remaining_timeout
  384. with TimeoutGuard(remaining_time) as guard:
  385. response = super(AuthorizedSession, self).request(
  386. method,
  387. url,
  388. data=data,
  389. headers=request_headers,
  390. timeout=timeout,
  391. **kwargs
  392. )
  393. remaining_time = guard.remaining_timeout
  394. # If the response indicated that the credentials needed to be
  395. # refreshed, then refresh the credentials and re-attempt the
  396. # request.
  397. # A stored token may expire between the time it is retrieved and
  398. # the time the request is made, so we may need to try twice.
  399. if (
  400. response.status_code in self._refresh_status_codes
  401. and _credential_refresh_attempt < self._max_refresh_attempts
  402. ):
  403. _LOGGER.info(
  404. "Refreshing credentials due to a %s response. Attempt %s/%s.",
  405. response.status_code,
  406. _credential_refresh_attempt + 1,
  407. self._max_refresh_attempts,
  408. )
  409. # Do not apply the timeout unconditionally in order to not override the
  410. # _auth_request's default timeout.
  411. auth_request = (
  412. self._auth_request
  413. if timeout is None
  414. else functools.partial(self._auth_request, timeout=timeout)
  415. )
  416. with TimeoutGuard(remaining_time) as guard:
  417. self.credentials.refresh(auth_request)
  418. remaining_time = guard.remaining_timeout
  419. # Recurse. Pass in the original headers, not our modified set, but
  420. # do pass the adjusted max allowed time (i.e. the remaining total time).
  421. return self.request(
  422. method,
  423. url,
  424. data=data,
  425. headers=headers,
  426. max_allowed_time=remaining_time,
  427. timeout=timeout,
  428. _credential_refresh_attempt=_credential_refresh_attempt + 1,
  429. **kwargs
  430. )
  431. return response
  432. @property
  433. def is_mtls(self):
  434. """Indicates if the created SSL channel is mutual TLS."""
  435. return self._is_mtls
  436. def close(self):
  437. if self._auth_request_session is not None:
  438. self._auth_request_session.close()
  439. super(AuthorizedSession, self).close()