reauth.py 12 KB

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