requests.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. import urllib3.contrib.pyopenssl
  208. from google.auth.transport import _custom_tls_signer
  209. # Call inject_into_urllib3 to activate certificate checking. See the
  210. # following links for more info:
  211. # (1) doc: https://github.com/urllib3/urllib3/blob/cb9ebf8aac5d75f64c8551820d760b72b619beff/src/urllib3/contrib/pyopenssl.py#L31-L32
  212. # (2) mTLS example: https://github.com/urllib3/urllib3/issues/474#issuecomment-253168415
  213. urllib3.contrib.pyopenssl.inject_into_urllib3()
  214. self.signer = _custom_tls_signer.CustomTlsSigner(enterprise_cert_file_path)
  215. self.signer.load_libraries()
  216. poolmanager = create_urllib3_context()
  217. poolmanager.load_verify_locations(cafile=certifi.where())
  218. self.signer.attach_to_ssl_context(poolmanager)
  219. self._ctx_poolmanager = poolmanager
  220. proxymanager = create_urllib3_context()
  221. proxymanager.load_verify_locations(cafile=certifi.where())
  222. self.signer.attach_to_ssl_context(proxymanager)
  223. self._ctx_proxymanager = proxymanager
  224. super(_MutualTlsOffloadAdapter, self).__init__()
  225. def init_poolmanager(self, *args, **kwargs):
  226. kwargs["ssl_context"] = self._ctx_poolmanager
  227. super(_MutualTlsOffloadAdapter, self).init_poolmanager(*args, **kwargs)
  228. def proxy_manager_for(self, *args, **kwargs):
  229. kwargs["ssl_context"] = self._ctx_proxymanager
  230. return super(_MutualTlsOffloadAdapter, self).proxy_manager_for(*args, **kwargs)
  231. class AuthorizedSession(requests.Session):
  232. """A Requests Session class with credentials.
  233. This class is used to perform requests to API endpoints that require
  234. authorization::
  235. from google.auth.transport.requests import AuthorizedSession
  236. authed_session = AuthorizedSession(credentials)
  237. response = authed_session.request(
  238. 'GET', 'https://www.googleapis.com/storage/v1/b')
  239. The underlying :meth:`request` implementation handles adding the
  240. credentials' headers to the request and refreshing credentials as needed.
  241. This class also supports mutual TLS via :meth:`configure_mtls_channel`
  242. method. In order to use this method, the `GOOGLE_API_USE_CLIENT_CERTIFICATE`
  243. environment variable must be explicitly set to ``true``, otherwise it does
  244. nothing. Assume the environment is set to ``true``, the method behaves in the
  245. following manner:
  246. If client_cert_callback is provided, client certificate and private
  247. key are loaded using the callback; if client_cert_callback is None,
  248. application default SSL credentials will be used. Exceptions are raised if
  249. there are problems with the certificate, private key, or the loading process,
  250. so it should be called within a try/except block.
  251. First we set the environment variable to ``true``, then create an :class:`AuthorizedSession`
  252. instance and specify the endpoints::
  253. regular_endpoint = 'https://pubsub.googleapis.com/v1/projects/{my_project_id}/topics'
  254. mtls_endpoint = 'https://pubsub.mtls.googleapis.com/v1/projects/{my_project_id}/topics'
  255. authed_session = AuthorizedSession(credentials)
  256. Now we can pass a callback to :meth:`configure_mtls_channel`::
  257. def my_cert_callback():
  258. # some code to load client cert bytes and private key bytes, both in
  259. # PEM format.
  260. some_code_to_load_client_cert_and_key()
  261. if loaded:
  262. return cert, key
  263. raise MyClientCertFailureException()
  264. # Always call configure_mtls_channel within a try/except block.
  265. try:
  266. authed_session.configure_mtls_channel(my_cert_callback)
  267. except:
  268. # handle exceptions.
  269. if authed_session.is_mtls:
  270. response = authed_session.request('GET', mtls_endpoint)
  271. else:
  272. response = authed_session.request('GET', regular_endpoint)
  273. You can alternatively use application default SSL credentials like this::
  274. try:
  275. authed_session.configure_mtls_channel()
  276. except:
  277. # handle exceptions.
  278. Args:
  279. credentials (google.auth.credentials.Credentials): The credentials to
  280. add to the request.
  281. refresh_status_codes (Sequence[int]): Which HTTP status codes indicate
  282. that credentials should be refreshed and the request should be
  283. retried.
  284. max_refresh_attempts (int): The maximum number of times to attempt to
  285. refresh the credentials and retry the request.
  286. refresh_timeout (Optional[int]): The timeout value in seconds for
  287. credential refresh HTTP requests.
  288. auth_request (google.auth.transport.requests.Request):
  289. (Optional) An instance of
  290. :class:`~google.auth.transport.requests.Request` used when
  291. refreshing credentials. If not passed,
  292. an instance of :class:`~google.auth.transport.requests.Request`
  293. is created.
  294. default_host (Optional[str]): A host like "pubsub.googleapis.com".
  295. This is used when a self-signed JWT is created from service
  296. account credentials.
  297. """
  298. def __init__(
  299. self,
  300. credentials,
  301. refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
  302. max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
  303. refresh_timeout=None,
  304. auth_request=None,
  305. default_host=None,
  306. ):
  307. super(AuthorizedSession, self).__init__()
  308. self.credentials = credentials
  309. self._refresh_status_codes = refresh_status_codes
  310. self._max_refresh_attempts = max_refresh_attempts
  311. self._refresh_timeout = refresh_timeout
  312. self._is_mtls = False
  313. self._default_host = default_host
  314. if auth_request is None:
  315. self._auth_request_session = requests.Session()
  316. # Using an adapter to make HTTP requests robust to network errors.
  317. # This adapter retrys HTTP requests when network errors occur
  318. # and the requests seems safely retryable.
  319. retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
  320. self._auth_request_session.mount("https://", retry_adapter)
  321. # Do not pass `self` as the session here, as it can lead to
  322. # infinite recursion.
  323. auth_request = Request(self._auth_request_session)
  324. else:
  325. self._auth_request_session = None
  326. # Request instance used by internal methods (for example,
  327. # credentials.refresh).
  328. self._auth_request = auth_request
  329. # https://google.aip.dev/auth/4111
  330. # Attempt to use self-signed JWTs when a service account is used.
  331. if isinstance(self.credentials, service_account.Credentials):
  332. self.credentials._create_self_signed_jwt(
  333. "https://{}/".format(self._default_host) if self._default_host else None
  334. )
  335. def configure_mtls_channel(self, client_cert_callback=None):
  336. """Configure the client certificate and key for SSL connection.
  337. The function does nothing unless `GOOGLE_API_USE_CLIENT_CERTIFICATE` is
  338. explicitly set to `true`. In this case if client certificate and key are
  339. successfully obtained (from the given client_cert_callback or from application
  340. default SSL credentials), a :class:`_MutualTlsAdapter` instance will be mounted
  341. to "https://" prefix.
  342. Args:
  343. client_cert_callback (Optional[Callable[[], (bytes, bytes)]]):
  344. The optional callback returns the client certificate and private
  345. key bytes both in PEM format.
  346. If the callback is None, application default SSL credentials
  347. will be used.
  348. Raises:
  349. google.auth.exceptions.MutualTLSChannelError: If mutual TLS channel
  350. creation failed for any reason.
  351. """
  352. use_client_cert = os.getenv(
  353. environment_vars.GOOGLE_API_USE_CLIENT_CERTIFICATE, "false"
  354. )
  355. if use_client_cert != "true":
  356. self._is_mtls = False
  357. return
  358. try:
  359. import OpenSSL
  360. except ImportError as caught_exc:
  361. new_exc = exceptions.MutualTLSChannelError(caught_exc)
  362. raise new_exc from caught_exc
  363. try:
  364. (
  365. self._is_mtls,
  366. cert,
  367. key,
  368. ) = google.auth.transport._mtls_helper.get_client_cert_and_key(
  369. client_cert_callback
  370. )
  371. if self._is_mtls:
  372. mtls_adapter = _MutualTlsAdapter(cert, key)
  373. self.mount("https://", mtls_adapter)
  374. except (
  375. exceptions.ClientCertError,
  376. ImportError,
  377. OpenSSL.crypto.Error,
  378. ) as caught_exc:
  379. new_exc = exceptions.MutualTLSChannelError(caught_exc)
  380. raise new_exc from caught_exc
  381. def request(
  382. self,
  383. method,
  384. url,
  385. data=None,
  386. headers=None,
  387. max_allowed_time=None,
  388. timeout=_DEFAULT_TIMEOUT,
  389. **kwargs
  390. ):
  391. """Implementation of Requests' request.
  392. Args:
  393. timeout (Optional[Union[float, Tuple[float, float]]]):
  394. The amount of time in seconds to wait for the server response
  395. with each individual request. Can also be passed as a tuple
  396. ``(connect_timeout, read_timeout)``. See :meth:`requests.Session.request`
  397. documentation for details.
  398. max_allowed_time (Optional[float]):
  399. If the method runs longer than this, a ``Timeout`` exception is
  400. automatically raised. Unlike the ``timeout`` parameter, this
  401. value applies to the total method execution time, even if
  402. multiple requests are made under the hood.
  403. Mind that it is not guaranteed that the timeout error is raised
  404. at ``max_allowed_time``. It might take longer, for example, if
  405. an underlying request takes a lot of time, but the request
  406. itself does not timeout, e.g. if a large file is being
  407. transmitted. The timout error will be raised after such
  408. request completes.
  409. """
  410. # pylint: disable=arguments-differ
  411. # Requests has a ton of arguments to request, but only two
  412. # (method, url) are required. We pass through all of the other
  413. # arguments to super, so no need to exhaustively list them here.
  414. # Use a kwarg for this instead of an attribute to maintain
  415. # thread-safety.
  416. _credential_refresh_attempt = kwargs.pop("_credential_refresh_attempt", 0)
  417. # Make a copy of the headers. They will be modified by the credentials
  418. # and we want to pass the original headers if we recurse.
  419. request_headers = headers.copy() if headers is not None else {}
  420. # Do not apply the timeout unconditionally in order to not override the
  421. # _auth_request's default timeout.
  422. auth_request = (
  423. self._auth_request
  424. if timeout is None
  425. else functools.partial(self._auth_request, timeout=timeout)
  426. )
  427. remaining_time = max_allowed_time
  428. with TimeoutGuard(remaining_time) as guard:
  429. self.credentials.before_request(auth_request, method, url, request_headers)
  430. remaining_time = guard.remaining_timeout
  431. with TimeoutGuard(remaining_time) as guard:
  432. response = super(AuthorizedSession, self).request(
  433. method,
  434. url,
  435. data=data,
  436. headers=request_headers,
  437. timeout=timeout,
  438. **kwargs
  439. )
  440. remaining_time = guard.remaining_timeout
  441. # If the response indicated that the credentials needed to be
  442. # refreshed, then refresh the credentials and re-attempt the
  443. # request.
  444. # A stored token may expire between the time it is retrieved and
  445. # the time the request is made, so we may need to try twice.
  446. if (
  447. response.status_code in self._refresh_status_codes
  448. and _credential_refresh_attempt < self._max_refresh_attempts
  449. ):
  450. _LOGGER.info(
  451. "Refreshing credentials due to a %s response. Attempt %s/%s.",
  452. response.status_code,
  453. _credential_refresh_attempt + 1,
  454. self._max_refresh_attempts,
  455. )
  456. # Do not apply the timeout unconditionally in order to not override the
  457. # _auth_request's default timeout.
  458. auth_request = (
  459. self._auth_request
  460. if timeout is None
  461. else functools.partial(self._auth_request, timeout=timeout)
  462. )
  463. with TimeoutGuard(remaining_time) as guard:
  464. self.credentials.refresh(auth_request)
  465. remaining_time = guard.remaining_timeout
  466. # Recurse. Pass in the original headers, not our modified set, but
  467. # do pass the adjusted max allowed time (i.e. the remaining total time).
  468. return self.request(
  469. method,
  470. url,
  471. data=data,
  472. headers=headers,
  473. max_allowed_time=remaining_time,
  474. timeout=timeout,
  475. _credential_refresh_attempt=_credential_refresh_attempt + 1,
  476. **kwargs
  477. )
  478. return response
  479. @property
  480. def is_mtls(self):
  481. """Indicates if the created SSL channel is mutual TLS."""
  482. return self._is_mtls
  483. def close(self):
  484. if self._auth_request_session is not None:
  485. self._auth_request_session.close()
  486. super(AuthorizedSession, self).close()