_client.py 17 KB

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