_client.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. """OAuth 2.0 client.
  15. This is a client for interacting with an OAuth 2.0 authorization server's
  16. token endpoint.
  17. For more information about the token endpoint, see
  18. `Section 3.1 of rfc6749`_
  19. .. _Section 3.1 of rfc6749: https://tools.ietf.org/html/rfc6749#section-3.2
  20. """
  21. import datetime
  22. import http.client as http_client
  23. import json
  24. import urllib
  25. from google.auth import _exponential_backoff
  26. from google.auth import _helpers
  27. from google.auth import credentials
  28. from google.auth import exceptions
  29. from google.auth import jwt
  30. from google.auth import metrics
  31. from google.auth import transport
  32. _URLENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded"
  33. _JSON_CONTENT_TYPE = "application/json"
  34. _JWT_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"
  35. _REFRESH_GRANT_TYPE = "refresh_token"
  36. def _handle_error_response(response_data, retryable_error):
  37. """Translates an error response into an exception.
  38. Args:
  39. response_data (Mapping | str): The decoded response data.
  40. retryable_error Optional[bool]: A boolean indicating if an error is retryable.
  41. Defaults to False.
  42. Raises:
  43. google.auth.exceptions.RefreshError: The errors contained in response_data.
  44. """
  45. retryable_error = retryable_error if retryable_error else False
  46. if isinstance(response_data, str):
  47. raise exceptions.RefreshError(response_data, retryable=retryable_error)
  48. try:
  49. error_details = "{}: {}".format(
  50. response_data["error"], response_data.get("error_description")
  51. )
  52. # If no details could be extracted, use the response data.
  53. except (KeyError, ValueError):
  54. error_details = json.dumps(response_data)
  55. raise exceptions.RefreshError(
  56. error_details, response_data, retryable=retryable_error
  57. )
  58. def _can_retry(status_code, response_data):
  59. """Checks if a request can be retried by inspecting the status code
  60. and response body of the request.
  61. Args:
  62. status_code (int): The response status code.
  63. response_data (Mapping | str): The decoded response data.
  64. Returns:
  65. bool: True if the response is retryable. False otherwise.
  66. """
  67. if status_code in transport.DEFAULT_RETRYABLE_STATUS_CODES:
  68. return True
  69. try:
  70. # For a failed response, response_body could be a string
  71. error_desc = response_data.get("error_description") or ""
  72. error_code = response_data.get("error") or ""
  73. if not isinstance(error_code, str) or not isinstance(error_desc, str):
  74. return False
  75. # Per Oauth 2.0 RFC https://www.rfc-editor.org/rfc/rfc6749.html#section-4.1.2.1
  76. # This is needed because a redirect will not return a 500 status code.
  77. retryable_error_descriptions = {
  78. "internal_failure",
  79. "server_error",
  80. "temporarily_unavailable",
  81. }
  82. if any(e in retryable_error_descriptions for e in (error_code, error_desc)):
  83. return True
  84. except AttributeError:
  85. pass
  86. return False
  87. def _parse_expiry(response_data):
  88. """Parses the expiry field from a response into a datetime.
  89. Args:
  90. response_data (Mapping): The JSON-parsed response data.
  91. Returns:
  92. Optional[datetime]: The expiration or ``None`` if no expiration was
  93. specified.
  94. """
  95. expires_in = response_data.get("expires_in", None)
  96. if expires_in is not None:
  97. # Some services do not respect the OAUTH2.0 RFC and send expires_in as a
  98. # JSON String.
  99. if isinstance(expires_in, str):
  100. expires_in = int(expires_in)
  101. return _helpers.utcnow() + datetime.timedelta(seconds=expires_in)
  102. else:
  103. return None
  104. def _token_endpoint_request_no_throw(
  105. request,
  106. token_uri,
  107. body,
  108. access_token=None,
  109. use_json=False,
  110. can_retry=True,
  111. headers=None,
  112. **kwargs
  113. ):
  114. """Makes a request to the OAuth 2.0 authorization server's token endpoint.
  115. This function doesn't throw on response errors.
  116. Args:
  117. request (google.auth.transport.Request): A callable used to make
  118. HTTP requests.
  119. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  120. URI.
  121. body (Mapping[str, str]): The parameters to send in the request body.
  122. access_token (Optional(str)): The access token needed to make the request.
  123. use_json (Optional(bool)): Use urlencoded format or json format for the
  124. content type. The default value is False.
  125. can_retry (bool): Enable or disable request retry behavior.
  126. headers (Optional[Mapping[str, str]]): The headers for the request.
  127. kwargs: Additional arguments passed on to the request method. The
  128. kwargs will be passed to `requests.request` method, see:
  129. https://docs.python-requests.org/en/latest/api/#requests.request.
  130. For example, you can use `cert=("cert_pem_path", "key_pem_path")`
  131. to set up client side SSL certificate, and use
  132. `verify="ca_bundle_path"` to set up the CA certificates for sever
  133. side SSL certificate verification.
  134. Returns:
  135. Tuple(bool, Mapping[str, str], Optional[bool]): A boolean indicating
  136. if the request is successful, a mapping for the JSON-decoded response
  137. data and in the case of an error a boolean indicating if the error
  138. is retryable.
  139. """
  140. if use_json:
  141. headers_to_use = {"Content-Type": _JSON_CONTENT_TYPE}
  142. body = json.dumps(body).encode("utf-8")
  143. else:
  144. headers_to_use = {"Content-Type": _URLENCODED_CONTENT_TYPE}
  145. body = urllib.parse.urlencode(body).encode("utf-8")
  146. if access_token:
  147. headers_to_use["Authorization"] = "Bearer {}".format(access_token)
  148. if headers:
  149. headers_to_use.update(headers)
  150. response_data = {}
  151. retryable_error = False
  152. retries = _exponential_backoff.ExponentialBackoff()
  153. for _ in retries:
  154. response = request(
  155. method="POST", url=token_uri, headers=headers_to_use, body=body, **kwargs
  156. )
  157. response_body = (
  158. response.data.decode("utf-8")
  159. if hasattr(response.data, "decode")
  160. else response.data
  161. )
  162. try:
  163. # response_body should be a JSON
  164. response_data = json.loads(response_body)
  165. except ValueError:
  166. response_data = response_body
  167. if response.status == http_client.OK:
  168. return True, response_data, None
  169. retryable_error = _can_retry(
  170. status_code=response.status, response_data=response_data
  171. )
  172. if not can_retry or not retryable_error:
  173. return False, response_data, retryable_error
  174. return False, response_data, retryable_error
  175. def _token_endpoint_request(
  176. request,
  177. token_uri,
  178. body,
  179. access_token=None,
  180. use_json=False,
  181. can_retry=True,
  182. headers=None,
  183. **kwargs
  184. ):
  185. """Makes a request to the OAuth 2.0 authorization server's token endpoint.
  186. Args:
  187. request (google.auth.transport.Request): A callable used to make
  188. HTTP requests.
  189. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  190. URI.
  191. body (Mapping[str, str]): The parameters to send in the request body.
  192. access_token (Optional(str)): The access token needed to make the request.
  193. use_json (Optional(bool)): Use urlencoded format or json format for the
  194. content type. The default value is False.
  195. can_retry (bool): Enable or disable request retry behavior.
  196. headers (Optional[Mapping[str, str]]): The headers for the request.
  197. kwargs: Additional arguments passed on to the request method. The
  198. kwargs will be passed to `requests.request` method, see:
  199. https://docs.python-requests.org/en/latest/api/#requests.request.
  200. For example, you can use `cert=("cert_pem_path", "key_pem_path")`
  201. to set up client side SSL certificate, and use
  202. `verify="ca_bundle_path"` to set up the CA certificates for sever
  203. side SSL certificate verification.
  204. Returns:
  205. Mapping[str, str]: The JSON-decoded response data.
  206. Raises:
  207. google.auth.exceptions.RefreshError: If the token endpoint returned
  208. an error.
  209. """
  210. response_status_ok, response_data, retryable_error = _token_endpoint_request_no_throw(
  211. request,
  212. token_uri,
  213. body,
  214. access_token=access_token,
  215. use_json=use_json,
  216. can_retry=can_retry,
  217. headers=headers,
  218. **kwargs
  219. )
  220. if not response_status_ok:
  221. _handle_error_response(response_data, retryable_error)
  222. return response_data
  223. def jwt_grant(request, token_uri, assertion, can_retry=True):
  224. """Implements the JWT Profile for OAuth 2.0 Authorization Grants.
  225. For more details, see `rfc7523 section 4`_.
  226. Args:
  227. request (google.auth.transport.Request): A callable used to make
  228. HTTP requests.
  229. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  230. URI.
  231. assertion (str): The OAuth 2.0 assertion.
  232. can_retry (bool): Enable or disable request retry behavior.
  233. Returns:
  234. Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,
  235. expiration, and additional data returned by the token endpoint.
  236. Raises:
  237. google.auth.exceptions.RefreshError: If the token endpoint returned
  238. an error.
  239. .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
  240. """
  241. body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE}
  242. response_data = _token_endpoint_request(
  243. request,
  244. token_uri,
  245. body,
  246. can_retry=can_retry,
  247. headers={
  248. metrics.API_CLIENT_HEADER: metrics.token_request_access_token_sa_assertion()
  249. },
  250. )
  251. try:
  252. access_token = response_data["access_token"]
  253. except KeyError as caught_exc:
  254. new_exc = exceptions.RefreshError(
  255. "No access token in response.", response_data, retryable=False
  256. )
  257. raise new_exc from caught_exc
  258. expiry = _parse_expiry(response_data)
  259. return access_token, expiry, response_data
  260. def call_iam_generate_id_token_endpoint(
  261. request,
  262. iam_id_token_endpoint,
  263. signer_email,
  264. audience,
  265. access_token,
  266. universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
  267. ):
  268. """Call iam.generateIdToken endpoint to get ID token.
  269. Args:
  270. request (google.auth.transport.Request): A callable used to make
  271. HTTP requests.
  272. iam_id_token_endpoint (str): The IAM ID token endpoint to use.
  273. signer_email (str): The signer email used to form the IAM
  274. generateIdToken endpoint.
  275. audience (str): The audience for the ID token.
  276. access_token (str): The access token used to call the IAM endpoint.
  277. Returns:
  278. Tuple[str, datetime]: The ID token and expiration.
  279. """
  280. body = {"audience": audience, "includeEmail": "true", "useEmailAzp": "true"}
  281. response_data = _token_endpoint_request(
  282. request,
  283. iam_id_token_endpoint.replace(
  284. credentials.DEFAULT_UNIVERSE_DOMAIN, universe_domain
  285. ).format(signer_email),
  286. body,
  287. access_token=access_token,
  288. use_json=True,
  289. )
  290. try:
  291. id_token = response_data["token"]
  292. except KeyError as caught_exc:
  293. new_exc = exceptions.RefreshError(
  294. "No ID token in response.", response_data, retryable=False
  295. )
  296. raise new_exc from caught_exc
  297. payload = jwt.decode(id_token, verify=False)
  298. expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
  299. return id_token, expiry
  300. def id_token_jwt_grant(request, token_uri, assertion, can_retry=True):
  301. """Implements the JWT Profile for OAuth 2.0 Authorization Grants, but
  302. requests an OpenID Connect ID Token instead of an access token.
  303. This is a variant on the standard JWT Profile that is currently unique
  304. to Google. This was added for the benefit of authenticating to services
  305. that require ID Tokens instead of access tokens or JWT bearer tokens.
  306. Args:
  307. request (google.auth.transport.Request): A callable used to make
  308. HTTP requests.
  309. token_uri (str): The OAuth 2.0 authorization server's token endpoint
  310. URI.
  311. assertion (str): JWT token signed by a service account. The token's
  312. payload must include a ``target_audience`` claim.
  313. can_retry (bool): Enable or disable request retry behavior.
  314. Returns:
  315. Tuple[str, Optional[datetime], Mapping[str, str]]:
  316. The (encoded) Open ID Connect ID Token, expiration, and additional
  317. data returned by the endpoint.
  318. Raises:
  319. google.auth.exceptions.RefreshError: If the token endpoint returned
  320. an error.
  321. """
  322. body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE}
  323. response_data = _token_endpoint_request(
  324. request,
  325. token_uri,
  326. body,
  327. can_retry=can_retry,
  328. headers={
  329. metrics.API_CLIENT_HEADER: metrics.token_request_id_token_sa_assertion()
  330. },
  331. )
  332. try:
  333. id_token = response_data["id_token"]
  334. except KeyError as caught_exc:
  335. new_exc = exceptions.RefreshError(
  336. "No ID token in response.", response_data, retryable=False
  337. )
  338. raise new_exc from caught_exc
  339. payload = jwt.decode(id_token, verify=False)
  340. expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
  341. return id_token, expiry, response_data
  342. def _handle_refresh_grant_response(response_data, refresh_token):
  343. """Extract tokens from refresh grant response.
  344. Args:
  345. response_data (Mapping[str, str]): Refresh grant response data.
  346. refresh_token (str): Current refresh token.
  347. Returns:
  348. Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access token,
  349. refresh token, expiration, and additional data returned by the token
  350. endpoint. If response_data doesn't have refresh token, then the current
  351. refresh token will be returned.
  352. Raises:
  353. google.auth.exceptions.RefreshError: If the token endpoint returned
  354. an error.
  355. """
  356. try:
  357. access_token = response_data["access_token"]
  358. except KeyError as caught_exc:
  359. new_exc = exceptions.RefreshError(
  360. "No access token in response.", response_data, retryable=False
  361. )
  362. raise new_exc from caught_exc
  363. refresh_token = response_data.get("refresh_token", refresh_token)
  364. expiry = _parse_expiry(response_data)
  365. return access_token, refresh_token, expiry, response_data
  366. def refresh_grant(
  367. request,
  368. token_uri,
  369. refresh_token,
  370. client_id,
  371. client_secret,
  372. scopes=None,
  373. rapt_token=None,
  374. can_retry=True,
  375. ):
  376. """Implements the OAuth 2.0 refresh token grant.
  377. For more details, see `rfc678 section 6`_.
  378. Args:
  379. request (google.auth.transport.Request): A callable used to make
  380. HTTP requests.
  381. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  382. URI.
  383. refresh_token (str): The refresh token to use to get a new access
  384. token.
  385. client_id (str): The OAuth 2.0 application's client ID.
  386. client_secret (str): The Oauth 2.0 appliaction's client secret.
  387. scopes (Optional(Sequence[str])): Scopes to request. If present, all
  388. scopes must be authorized for the refresh token. Useful if refresh
  389. token has a wild card scope (e.g.
  390. 'https://www.googleapis.com/auth/any-api').
  391. rapt_token (Optional(str)): The reauth Proof Token.
  392. can_retry (bool): Enable or disable request retry behavior.
  393. Returns:
  394. Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access
  395. token, new or current refresh token, expiration, and additional data
  396. returned by the token endpoint.
  397. Raises:
  398. google.auth.exceptions.RefreshError: If the token endpoint returned
  399. an error.
  400. .. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6
  401. """
  402. body = {
  403. "grant_type": _REFRESH_GRANT_TYPE,
  404. "client_id": client_id,
  405. "client_secret": client_secret,
  406. "refresh_token": refresh_token,
  407. }
  408. if scopes:
  409. body["scope"] = " ".join(scopes)
  410. if rapt_token:
  411. body["rapt"] = rapt_token
  412. response_data = _token_endpoint_request(
  413. request, token_uri, body, can_retry=can_retry
  414. )
  415. return _handle_refresh_grant_response(response_data, refresh_token)