_reauth_async.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. # Copyright 2021 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. """A module that provides functions for handling rapt authentication.
  15. Reauth is a process of obtaining additional authentication (such as password,
  16. security token, etc.) while refreshing OAuth 2.0 credentials for a user.
  17. Credentials that use the Reauth flow must have the reauth scope,
  18. ``https://www.googleapis.com/auth/accounts.reauth``.
  19. This module provides a high-level function for executing the Reauth process,
  20. :func:`refresh_grant`, and lower-level helpers for doing the individual
  21. steps of the reauth process.
  22. Those steps are:
  23. 1. Obtaining a list of challenges from the reauth server.
  24. 2. Running through each challenge and sending the result back to the reauth
  25. server.
  26. 3. Refreshing the access token using the returned rapt token.
  27. """
  28. import sys
  29. from google.auth import exceptions
  30. from google.oauth2 import _client
  31. from google.oauth2 import _client_async
  32. from google.oauth2 import challenges
  33. from google.oauth2 import reauth
  34. async def _get_challenges(
  35. request, supported_challenge_types, access_token, requested_scopes=None
  36. ):
  37. """Does initial request to reauth API to get the challenges.
  38. Args:
  39. request (google.auth.transport.Request): A callable used to make
  40. HTTP requests. This must be an aiohttp request.
  41. supported_challenge_types (Sequence[str]): list of challenge names
  42. supported by the manager.
  43. access_token (str): Access token with reauth scopes.
  44. requested_scopes (Optional(Sequence[str])): Authorized scopes for the credentials.
  45. Returns:
  46. dict: The response from the reauth API.
  47. """
  48. body = {"supportedChallengeTypes": supported_challenge_types}
  49. if requested_scopes:
  50. body["oauthScopesForDomainPolicyLookup"] = requested_scopes
  51. return await _client_async._token_endpoint_request(
  52. request,
  53. reauth._REAUTH_API + ":start",
  54. body,
  55. access_token=access_token,
  56. use_json=True,
  57. )
  58. async def _send_challenge_result(
  59. request, session_id, challenge_id, client_input, access_token
  60. ):
  61. """Attempt to refresh access token by sending next challenge result.
  62. Args:
  63. request (google.auth.transport.Request): A callable used to make
  64. HTTP requests. This must be an aiohttp request.
  65. session_id (str): session id returned by the initial reauth call.
  66. challenge_id (str): challenge id returned by the initial reauth call.
  67. client_input: dict with a challenge-specific client input. For example:
  68. ``{'credential': password}`` for password challenge.
  69. access_token (str): Access token with reauth scopes.
  70. Returns:
  71. dict: The response from the reauth API.
  72. """
  73. body = {
  74. "sessionId": session_id,
  75. "challengeId": challenge_id,
  76. "action": "RESPOND",
  77. "proposalResponse": client_input,
  78. }
  79. return await _client_async._token_endpoint_request(
  80. request,
  81. reauth._REAUTH_API + "/{}:continue".format(session_id),
  82. body,
  83. access_token=access_token,
  84. use_json=True,
  85. )
  86. async def _run_next_challenge(msg, request, access_token):
  87. """Get the next challenge from msg and run it.
  88. Args:
  89. msg (dict): Reauth API response body (either from the initial request to
  90. https://reauth.googleapis.com/v2/sessions:start or from sending the
  91. previous challenge response to
  92. https://reauth.googleapis.com/v2/sessions/id:continue)
  93. request (google.auth.transport.Request): A callable used to make
  94. HTTP requests. This must be an aiohttp request.
  95. access_token (str): reauth access token
  96. Returns:
  97. dict: The response from the reauth API.
  98. Raises:
  99. google.auth.exceptions.ReauthError: if reauth failed.
  100. """
  101. for challenge in msg["challenges"]:
  102. if challenge["status"] != "READY":
  103. # Skip non-activated challenges.
  104. continue
  105. c = challenges.AVAILABLE_CHALLENGES.get(challenge["challengeType"], None)
  106. if not c:
  107. raise exceptions.ReauthFailError(
  108. "Unsupported challenge type {0}. Supported types: {1}".format(
  109. challenge["challengeType"],
  110. ",".join(list(challenges.AVAILABLE_CHALLENGES.keys())),
  111. )
  112. )
  113. if not c.is_locally_eligible:
  114. raise exceptions.ReauthFailError(
  115. "Challenge {0} is not locally eligible".format(
  116. challenge["challengeType"]
  117. )
  118. )
  119. client_input = c.obtain_challenge_input(challenge)
  120. if not client_input:
  121. return None
  122. return await _send_challenge_result(
  123. request,
  124. msg["sessionId"],
  125. challenge["challengeId"],
  126. client_input,
  127. access_token,
  128. )
  129. return None
  130. async def _obtain_rapt(request, access_token, requested_scopes):
  131. """Given an http request method and reauth access token, get rapt token.
  132. Args:
  133. request (google.auth.transport.Request): A callable used to make
  134. HTTP requests. This must be an aiohttp request.
  135. access_token (str): reauth access token
  136. requested_scopes (Sequence[str]): scopes required by the client application
  137. Returns:
  138. str: The rapt token.
  139. Raises:
  140. google.auth.exceptions.ReauthError: if reauth failed
  141. """
  142. msg = await _get_challenges(
  143. request,
  144. list(challenges.AVAILABLE_CHALLENGES.keys()),
  145. access_token,
  146. requested_scopes,
  147. )
  148. if msg["status"] == reauth._AUTHENTICATED:
  149. return msg["encodedProofOfReauthToken"]
  150. for _ in range(0, reauth.RUN_CHALLENGE_RETRY_LIMIT):
  151. if not (
  152. msg["status"] == reauth._CHALLENGE_REQUIRED
  153. or msg["status"] == reauth._CHALLENGE_PENDING
  154. ):
  155. raise exceptions.ReauthFailError(
  156. "Reauthentication challenge failed due to API error: {}".format(
  157. msg["status"]
  158. )
  159. )
  160. if not reauth.is_interactive():
  161. raise exceptions.ReauthFailError(
  162. "Reauthentication challenge could not be answered because you are not"
  163. " in an interactive session."
  164. )
  165. msg = await _run_next_challenge(msg, request, access_token)
  166. if msg["status"] == reauth._AUTHENTICATED:
  167. return msg["encodedProofOfReauthToken"]
  168. # If we got here it means we didn't get authenticated.
  169. raise exceptions.ReauthFailError("Failed to obtain rapt token.")
  170. async def get_rapt_token(
  171. request, client_id, client_secret, refresh_token, token_uri, scopes=None
  172. ):
  173. """Given an http request method and refresh_token, get rapt token.
  174. Args:
  175. request (google.auth.transport.Request): A callable used to make
  176. HTTP requests. This must be an aiohttp request.
  177. client_id (str): client id to get access token for reauth scope.
  178. client_secret (str): client secret for the client_id
  179. refresh_token (str): refresh token to refresh access token
  180. token_uri (str): uri to refresh access token
  181. scopes (Optional(Sequence[str])): scopes required by the client application
  182. Returns:
  183. str: The rapt token.
  184. Raises:
  185. google.auth.exceptions.RefreshError: If reauth failed.
  186. """
  187. sys.stderr.write("Reauthentication required.\n")
  188. # Get access token for reauth.
  189. access_token, _, _, _ = await _client_async.refresh_grant(
  190. request=request,
  191. client_id=client_id,
  192. client_secret=client_secret,
  193. refresh_token=refresh_token,
  194. token_uri=token_uri,
  195. scopes=[reauth._REAUTH_SCOPE],
  196. )
  197. # Get rapt token from reauth API.
  198. rapt_token = await _obtain_rapt(request, access_token, requested_scopes=scopes)
  199. return rapt_token
  200. async def refresh_grant(
  201. request,
  202. token_uri,
  203. refresh_token,
  204. client_id,
  205. client_secret,
  206. scopes=None,
  207. rapt_token=None,
  208. enable_reauth_refresh=False,
  209. ):
  210. """Implements the reauthentication flow.
  211. Args:
  212. request (google.auth.transport.Request): A callable used to make
  213. HTTP requests. This must be an aiohttp request.
  214. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  215. URI.
  216. refresh_token (str): The refresh token to use to get a new access
  217. token.
  218. client_id (str): The OAuth 2.0 application's client ID.
  219. client_secret (str): The Oauth 2.0 appliaction's client secret.
  220. scopes (Optional(Sequence[str])): Scopes to request. If present, all
  221. scopes must be authorized for the refresh token. Useful if refresh
  222. token has a wild card scope (e.g.
  223. 'https://www.googleapis.com/auth/any-api').
  224. rapt_token (Optional(str)): The rapt token for reauth.
  225. enable_reauth_refresh (Optional[bool]): Whether reauth refresh flow
  226. should be used. The default value is False. This option is for
  227. gcloud only, other users should use the default value.
  228. Returns:
  229. Tuple[str, Optional[str], Optional[datetime], Mapping[str, str], str]: The
  230. access token, new refresh token, expiration, the additional data
  231. returned by the token endpoint, and the rapt token.
  232. Raises:
  233. google.auth.exceptions.RefreshError: If the token endpoint returned
  234. an error.
  235. """
  236. body = {
  237. "grant_type": _client._REFRESH_GRANT_TYPE,
  238. "client_id": client_id,
  239. "client_secret": client_secret,
  240. "refresh_token": refresh_token,
  241. }
  242. if scopes:
  243. body["scope"] = " ".join(scopes)
  244. if rapt_token:
  245. body["rapt"] = rapt_token
  246. response_status_ok, response_data, retryable_error = await _client_async._token_endpoint_request_no_throw(
  247. request, token_uri, body
  248. )
  249. if (
  250. not response_status_ok
  251. and response_data.get("error") == reauth._REAUTH_NEEDED_ERROR
  252. and (
  253. response_data.get("error_subtype")
  254. == reauth._REAUTH_NEEDED_ERROR_INVALID_RAPT
  255. or response_data.get("error_subtype")
  256. == reauth._REAUTH_NEEDED_ERROR_RAPT_REQUIRED
  257. )
  258. ):
  259. if not enable_reauth_refresh:
  260. raise exceptions.RefreshError(
  261. "Reauthentication is needed. Please run `gcloud auth application-default login` to reauthenticate."
  262. )
  263. rapt_token = await get_rapt_token(
  264. request, client_id, client_secret, refresh_token, token_uri, scopes=scopes
  265. )
  266. body["rapt"] = rapt_token
  267. (
  268. response_status_ok,
  269. response_data,
  270. retryable_error,
  271. ) = await _client_async._token_endpoint_request_no_throw(
  272. request, token_uri, body
  273. )
  274. if not response_status_ok:
  275. _client._handle_error_response(response_data, retryable_error)
  276. refresh_response = _client._handle_refresh_grant_response(
  277. response_data, refresh_token
  278. )
  279. return refresh_response + (rapt_token,)