requests.py 22 KB

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