reauth.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 six.moves import range
  30. from google.auth import exceptions
  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. return _client._token_endpoint_request(
  73. request, _REAUTH_API + ":start", body, access_token=access_token, use_json=True
  74. )
  75. def _send_challenge_result(
  76. request, session_id, challenge_id, client_input, access_token
  77. ):
  78. """Attempt to refresh access token by sending next challenge result.
  79. Args:
  80. request (google.auth.transport.Request): A callable used to make
  81. HTTP requests.
  82. session_id (str): session id returned by the initial reauth call.
  83. challenge_id (str): challenge id returned by the initial reauth call.
  84. client_input: dict with a challenge-specific client input. For example:
  85. ``{'credential': password}`` for password challenge.
  86. access_token (str): Access token with reauth scopes.
  87. Returns:
  88. dict: The response from the reauth API.
  89. """
  90. body = {
  91. "sessionId": session_id,
  92. "challengeId": challenge_id,
  93. "action": "RESPOND",
  94. "proposalResponse": client_input,
  95. }
  96. return _client._token_endpoint_request(
  97. request,
  98. _REAUTH_API + "/{}:continue".format(session_id),
  99. body,
  100. access_token=access_token,
  101. use_json=True,
  102. )
  103. def _run_next_challenge(msg, request, access_token):
  104. """Get the next challenge from msg and run it.
  105. Args:
  106. msg (dict): Reauth API response body (either from the initial request to
  107. https://reauth.googleapis.com/v2/sessions:start or from sending the
  108. previous challenge response to
  109. https://reauth.googleapis.com/v2/sessions/id:continue)
  110. request (google.auth.transport.Request): A callable used to make
  111. HTTP requests.
  112. access_token (str): reauth access token
  113. Returns:
  114. dict: The response from the reauth API.
  115. Raises:
  116. google.auth.exceptions.ReauthError: if reauth failed.
  117. """
  118. for challenge in msg["challenges"]:
  119. if challenge["status"] != "READY":
  120. # Skip non-activated challenges.
  121. continue
  122. c = challenges.AVAILABLE_CHALLENGES.get(challenge["challengeType"], None)
  123. if not c:
  124. raise exceptions.ReauthFailError(
  125. "Unsupported challenge type {0}. Supported types: {1}".format(
  126. challenge["challengeType"],
  127. ",".join(list(challenges.AVAILABLE_CHALLENGES.keys())),
  128. )
  129. )
  130. if not c.is_locally_eligible:
  131. raise exceptions.ReauthFailError(
  132. "Challenge {0} is not locally eligible".format(
  133. challenge["challengeType"]
  134. )
  135. )
  136. client_input = c.obtain_challenge_input(challenge)
  137. if not client_input:
  138. return None
  139. return _send_challenge_result(
  140. request,
  141. msg["sessionId"],
  142. challenge["challengeId"],
  143. client_input,
  144. access_token,
  145. )
  146. return None
  147. def _obtain_rapt(request, access_token, requested_scopes):
  148. """Given an http request method and reauth access token, get rapt token.
  149. Args:
  150. request (google.auth.transport.Request): A callable used to make
  151. HTTP requests.
  152. access_token (str): reauth access token
  153. requested_scopes (Sequence[str]): scopes required by the client application
  154. Returns:
  155. str: The rapt token.
  156. Raises:
  157. google.auth.exceptions.ReauthError: if reauth failed
  158. """
  159. msg = _get_challenges(
  160. request,
  161. list(challenges.AVAILABLE_CHALLENGES.keys()),
  162. access_token,
  163. requested_scopes,
  164. )
  165. if msg["status"] == _AUTHENTICATED:
  166. return msg["encodedProofOfReauthToken"]
  167. for _ in range(0, RUN_CHALLENGE_RETRY_LIMIT):
  168. if not (
  169. msg["status"] == _CHALLENGE_REQUIRED or msg["status"] == _CHALLENGE_PENDING
  170. ):
  171. raise exceptions.ReauthFailError(
  172. "Reauthentication challenge failed due to API error: {}".format(
  173. msg["status"]
  174. )
  175. )
  176. if not is_interactive():
  177. raise exceptions.ReauthFailError(
  178. "Reauthentication challenge could not be answered because you are not"
  179. " in an interactive session."
  180. )
  181. msg = _run_next_challenge(msg, request, access_token)
  182. if msg["status"] == _AUTHENTICATED:
  183. return msg["encodedProofOfReauthToken"]
  184. # If we got here it means we didn't get authenticated.
  185. raise exceptions.ReauthFailError("Failed to obtain rapt token.")
  186. def get_rapt_token(
  187. request, client_id, client_secret, refresh_token, token_uri, scopes=None
  188. ):
  189. """Given an http request method and refresh_token, get rapt token.
  190. Args:
  191. request (google.auth.transport.Request): A callable used to make
  192. HTTP requests.
  193. client_id (str): client id to get access token for reauth scope.
  194. client_secret (str): client secret for the client_id
  195. refresh_token (str): refresh token to refresh access token
  196. token_uri (str): uri to refresh access token
  197. scopes (Optional(Sequence[str])): scopes required by the client application
  198. Returns:
  199. str: The rapt token.
  200. Raises:
  201. google.auth.exceptions.RefreshError: If reauth failed.
  202. """
  203. sys.stderr.write("Reauthentication required.\n")
  204. # Get access token for reauth.
  205. access_token, _, _, _ = _client.refresh_grant(
  206. request=request,
  207. client_id=client_id,
  208. client_secret=client_secret,
  209. refresh_token=refresh_token,
  210. token_uri=token_uri,
  211. scopes=[_REAUTH_SCOPE],
  212. )
  213. # Get rapt token from reauth API.
  214. rapt_token = _obtain_rapt(request, access_token, requested_scopes=scopes)
  215. return rapt_token
  216. def refresh_grant(
  217. request,
  218. token_uri,
  219. refresh_token,
  220. client_id,
  221. client_secret,
  222. scopes=None,
  223. rapt_token=None,
  224. ):
  225. """Implements the reauthentication flow.
  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. refresh_token (str): The refresh token to use to get a new access
  232. token.
  233. client_id (str): The OAuth 2.0 application's client ID.
  234. client_secret (str): The Oauth 2.0 appliaction's client secret.
  235. scopes (Optional(Sequence[str])): Scopes to request. If present, all
  236. scopes must be authorized for the refresh token. Useful if refresh
  237. token has a wild card scope (e.g.
  238. 'https://www.googleapis.com/auth/any-api').
  239. rapt_token (Optional(str)): The rapt token for reauth.
  240. Returns:
  241. Tuple[str, Optional[str], Optional[datetime], Mapping[str, str], str]: The
  242. access token, new refresh token, expiration, the additional data
  243. returned by the token endpoint, and the rapt token.
  244. Raises:
  245. google.auth.exceptions.RefreshError: If the token endpoint returned
  246. an error.
  247. """
  248. body = {
  249. "grant_type": _client._REFRESH_GRANT_TYPE,
  250. "client_id": client_id,
  251. "client_secret": client_secret,
  252. "refresh_token": refresh_token,
  253. }
  254. if scopes:
  255. body["scope"] = " ".join(scopes)
  256. if rapt_token:
  257. body["rapt"] = rapt_token
  258. response_status_ok, response_data = _client._token_endpoint_request_no_throw(
  259. request, token_uri, body
  260. )
  261. if (
  262. not response_status_ok
  263. and response_data.get("error") == _REAUTH_NEEDED_ERROR
  264. and (
  265. response_data.get("error_subtype") == _REAUTH_NEEDED_ERROR_INVALID_RAPT
  266. or response_data.get("error_subtype") == _REAUTH_NEEDED_ERROR_RAPT_REQUIRED
  267. )
  268. ):
  269. rapt_token = get_rapt_token(
  270. request, client_id, client_secret, refresh_token, token_uri, scopes=scopes
  271. )
  272. body["rapt"] = rapt_token
  273. (response_status_ok, response_data) = _client._token_endpoint_request_no_throw(
  274. request, token_uri, body
  275. )
  276. if not response_status_ok:
  277. _client._handle_error_response(response_data)
  278. return _client._handle_refresh_grant_response(response_data, refresh_token) + (
  279. rapt_token,
  280. )