auth.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. # Copyright 2015 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Google OAuth2 related functions."""
  5. from __future__ import annotations
  6. import collections
  7. import datetime
  8. import functools
  9. import httplib2
  10. import json
  11. import logging
  12. import os
  13. from typing import Optional
  14. import subprocess2
  15. # TODO: Should fix these warnings.
  16. # pylint: disable=line-too-long
  17. # This is what most GAE apps require for authentication.
  18. OAUTH_SCOPE_EMAIL = 'https://www.googleapis.com/auth/userinfo.email'
  19. # Gerrit and Git on *.googlesource.com require this scope.
  20. OAUTH_SCOPE_GERRIT = 'https://www.googleapis.com/auth/gerritcodereview'
  21. # Deprecated. Use OAUTH_SCOPE_EMAIL instead.
  22. OAUTH_SCOPES = OAUTH_SCOPE_EMAIL
  23. # Mockable datetime.datetime.utcnow for testing.
  24. def datetime_now():
  25. return datetime.datetime.utcnow()
  26. # OAuth access token or ID token with its expiration time (UTC datetime or None
  27. # if unknown).
  28. class Token(collections.namedtuple('Token', [
  29. 'token',
  30. 'expires_at',
  31. ])):
  32. def needs_refresh(self):
  33. """True if this token should be refreshed."""
  34. if self.expires_at is not None:
  35. # Allow 30s of clock skew between client and backend.
  36. return datetime_now() + datetime.timedelta(
  37. seconds=30) >= self.expires_at
  38. # Token without expiration time never expires.
  39. return False
  40. class LoginRequiredError(Exception):
  41. """Interaction with the user is required to authenticate."""
  42. def __init__(self, scopes=OAUTH_SCOPE_EMAIL):
  43. self.scopes = scopes
  44. msg = ('You are not logged in. Please login first by running:\n'
  45. ' %s' % self.login_command)
  46. super(LoginRequiredError, self).__init__(msg)
  47. @property
  48. def login_command(self) -> str:
  49. return 'luci-auth login -scopes "%s"' % self.scopes
  50. class GitLoginRequiredError(Exception):
  51. """Interaction with the user is required to authenticate.
  52. This is for git-credential-luci, not luci-auth.
  53. """
  54. def __init__(self):
  55. msg = (
  56. 'You are not logged in to Gerrit. Please login first by running:\n'
  57. ' %s' % self.login_command)
  58. super(GitLoginRequiredError, self).__init__(msg)
  59. @property
  60. def login_command(self) -> str:
  61. return 'git-credential-luci login'
  62. def has_luci_context_local_auth():
  63. """Returns whether LUCI_CONTEXT should be used for ambient authentication."""
  64. ctx_path = os.environ.get('LUCI_CONTEXT')
  65. if not ctx_path:
  66. return False
  67. try:
  68. with open(ctx_path) as f:
  69. loaded = json.load(f)
  70. except (OSError, IOError, ValueError):
  71. return False
  72. return loaded.get('local_auth', {}).get('default_account_id') is not None
  73. class Authenticator(object):
  74. """Object that knows how to refresh access tokens or id tokens when needed.
  75. Args:
  76. scopes: space separated oauth scopes. It's used to generate access tokens.
  77. Defaults to OAUTH_SCOPE_EMAIL.
  78. audience: An audience in ID tokens to claim which clients should accept it.
  79. """
  80. def __init__(self, scopes=OAUTH_SCOPE_EMAIL, audience=None):
  81. self._access_token = None
  82. self._scopes = scopes
  83. self._id_token = None
  84. self._audience = audience
  85. def has_cached_credentials(self):
  86. """Returns True if credentials can be obtained.
  87. If returns False, get_access_token() or get_id_token() later will probably
  88. ask for interactive login by raising LoginRequiredError.
  89. If returns True, get_access_token() or get_id_token() won't ask for
  90. interactive login.
  91. """
  92. return bool(self._get_luci_auth_token())
  93. def get_access_token(self):
  94. """Returns AccessToken, refreshing it if necessary.
  95. Raises:
  96. LoginRequiredError if user interaction is required.
  97. """
  98. if self._access_token and not self._access_token.needs_refresh():
  99. return self._access_token
  100. # Token expired or missing. Maybe some other process already updated it,
  101. # reload from the cache.
  102. self._access_token = self._get_luci_auth_token()
  103. if self._access_token and not self._access_token.needs_refresh():
  104. return self._access_token
  105. # Nope, still expired. Needs user interaction.
  106. logging.debug('Failed to create access token')
  107. raise LoginRequiredError(self._scopes)
  108. def get_id_token(self):
  109. """Returns id token, refreshing it if necessary.
  110. Returns:
  111. A Token object.
  112. Raises:
  113. LoginRequiredError if user interaction is required.
  114. """
  115. if self._id_token and not self._id_token.needs_refresh():
  116. return self._id_token
  117. self._id_token = self._get_luci_auth_token(use_id_token=True)
  118. if self._id_token and not self._id_token.needs_refresh():
  119. return self._id_token
  120. # Nope, still expired. Needs user interaction.
  121. logging.debug('Failed to create id token')
  122. raise LoginRequiredError()
  123. def authorize(self, http, use_id_token=False):
  124. """Monkey patches authentication logic of httplib2.Http instance.
  125. The modified http.request method will add authentication headers to each
  126. request.
  127. Args:
  128. http: An instance of httplib2.Http.
  129. Returns:
  130. A modified instance of http that was passed in.
  131. """
  132. # Adapted from oauth2client.OAuth2Credentials.authorize.
  133. request_orig = http.request
  134. @functools.wraps(request_orig)
  135. def new_request(uri,
  136. method='GET',
  137. body=None,
  138. headers=None,
  139. redirections=httplib2.DEFAULT_MAX_REDIRECTS,
  140. connection_type=None):
  141. headers = (headers or {}).copy()
  142. auth_token = self.get_access_token(
  143. ) if not use_id_token else self.get_id_token()
  144. headers['Authorization'] = 'Bearer %s' % auth_token.token
  145. return request_orig(uri, method, body, headers, redirections,
  146. connection_type)
  147. http.request = new_request
  148. return http
  149. ## Private methods.
  150. def _get_luci_auth_token(self, use_id_token=False):
  151. logging.debug('Running luci-auth token')
  152. if use_id_token:
  153. args = ['-use-id-token'] + ['-audience', self._audience
  154. ] if self._audience else []
  155. else:
  156. args = ['-scopes', self._scopes]
  157. try:
  158. out, err = subprocess2.check_call_out(['luci-auth', 'token'] +
  159. args + ['-json-output', '-'],
  160. stdout=subprocess2.PIPE,
  161. stderr=subprocess2.PIPE)
  162. logging.debug('luci-auth token stderr:\n%s', err)
  163. token_info = json.loads(out)
  164. return Token(
  165. token_info['token'],
  166. datetime.datetime.utcfromtimestamp(token_info['expiry']))
  167. except subprocess2.CalledProcessError as e:
  168. # subprocess2.CalledProcessError.__str__ nicely formats
  169. # stdout/stderr.
  170. logging.error('luci-auth token failed: %s', e)
  171. return None
  172. class GerritAuthenticator(object):
  173. """Object that knows how to refresh access tokens for Gerrit.
  174. Unlike Authenticator, this is specifically for authenticating Gerrit
  175. requests.
  176. """
  177. def __init__(self):
  178. self._access_token: Optional[str] = None
  179. def get_access_token(self) -> str:
  180. """Returns AccessToken, refreshing it if necessary.
  181. Raises:
  182. GitLoginRequiredError if user interaction is required.
  183. """
  184. access_token = self._get_luci_auth_token()
  185. if access_token:
  186. return access_token
  187. logging.debug('Failed to create access token')
  188. raise GitLoginRequiredError()
  189. def _get_luci_auth_token(self, use_id_token=False) -> Optional[str]:
  190. logging.debug('Running git-credential-luci')
  191. try:
  192. out, err = subprocess2.check_call_out(
  193. ['git-credential-luci', 'get'],
  194. stdout=subprocess2.PIPE,
  195. stderr=subprocess2.PIPE)
  196. logging.debug('git-credential-luci stderr:\n%s', err)
  197. for line in out.decode().splitlines():
  198. if line.startswith('password='):
  199. return line[len('password='):].rstrip()
  200. logging.error('git-credential-luci did not return a token')
  201. return None
  202. except subprocess2.CalledProcessError as e:
  203. # subprocess2.CalledProcessError.__str__ nicely formats
  204. # stdout/stderr.
  205. logging.error('git-credential-luci failed: %s', e)
  206. return None