requests.py 22 KB

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