vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 1 | # Copyright 2015 The Chromium Authors. All rights reserved. |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 5 | """Google OAuth2 related functions.""" |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 6 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 7 | import BaseHTTPServer |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 8 | import collections |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 9 | import datetime |
| 10 | import functools |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 11 | import hashlib |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 12 | import json |
| 13 | import logging |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 14 | import optparse |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 15 | import os |
| 16 | import socket |
| 17 | import sys |
| 18 | import threading |
| 19 | import urllib |
| 20 | import urlparse |
| 21 | import webbrowser |
| 22 | |
| 23 | from third_party import httplib2 |
| 24 | from third_party.oauth2client import client |
| 25 | from third_party.oauth2client import multistore_file |
| 26 | |
| 27 | |
| 28 | # depot_tools/. |
| 29 | DEPOT_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 30 | |
| 31 | |
| 32 | # Google OAuth2 clients always have a secret, even if the client is an installed |
| 33 | # application/utility such as this. Of course, in such cases the "secret" is |
| 34 | # actually publicly known; security depends entirely on the secrecy of refresh |
| 35 | # tokens, which effectively become bearer tokens. An attacker can impersonate |
| 36 | # service's identity in OAuth2 flow. But that's generally fine as long as a list |
| 37 | # of allowed redirect_uri's associated with client_id is limited to 'localhost' |
| 38 | # or 'urn:ietf:wg:oauth:2.0:oob'. In that case attacker needs some process |
| 39 | # running on user's machine to successfully complete the flow and grab refresh |
| 40 | # token. When you have a malicious code running on your machine, you're screwed |
| 41 | # anyway. |
| 42 | # This particular set is managed by API Console project "chrome-infra-auth". |
| 43 | OAUTH_CLIENT_ID = ( |
| 44 | '446450136466-2hr92jrq8e6i4tnsa56b52vacp7t3936.apps.googleusercontent.com') |
| 45 | OAUTH_CLIENT_SECRET = 'uBfbay2KCy9t4QveJ-dOqHtp' |
| 46 | |
| 47 | # List of space separated OAuth scopes for generated tokens. GAE apps usually |
| 48 | # use userinfo.email scope for authentication. |
| 49 | OAUTH_SCOPES = 'https://www.googleapis.com/auth/userinfo.email' |
| 50 | |
vadimsh@chromium.org | 148f76f | 2015-04-21 01:44:13 +0000 | [diff] [blame^] | 51 | # Path to a file with cached OAuth2 credentials used by default relative to the |
| 52 | # home dir (see _get_token_cache_path). It should be a safe location accessible |
| 53 | # only to a current user: knowing content of this file is roughly equivalent to |
| 54 | # knowing account password. Single file can hold multiple independent tokens |
| 55 | # identified by token_cache_key (see Authenticator). |
| 56 | OAUTH_TOKENS_CACHE = '.depot_tools_oauth2_tokens' |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 57 | |
| 58 | |
| 59 | # Authentication configuration extracted from command line options. |
| 60 | # See doc string for 'make_auth_config' for meaning of fields. |
| 61 | AuthConfig = collections.namedtuple('AuthConfig', [ |
| 62 | 'use_oauth2', # deprecated, will be always True |
| 63 | 'save_cookies', # deprecated, will be removed |
| 64 | 'use_local_webserver', |
| 65 | 'webserver_port', |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 66 | 'refresh_token_json', |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 67 | ]) |
| 68 | |
| 69 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 70 | # OAuth access token with its expiration time (UTC datetime or None if unknown). |
| 71 | AccessToken = collections.namedtuple('AccessToken', [ |
| 72 | 'token', |
| 73 | 'expires_at', |
| 74 | ]) |
| 75 | |
| 76 | |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 77 | # Refresh token passed via --auth-refresh-token-json. |
| 78 | RefreshToken = collections.namedtuple('RefreshToken', [ |
| 79 | 'client_id', |
| 80 | 'client_secret', |
| 81 | 'refresh_token', |
| 82 | ]) |
| 83 | |
| 84 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 85 | class AuthenticationError(Exception): |
| 86 | """Raised on errors related to authentication.""" |
| 87 | |
| 88 | |
| 89 | class LoginRequiredError(AuthenticationError): |
| 90 | """Interaction with the user is required to authenticate.""" |
| 91 | |
| 92 | def __init__(self, token_cache_key): |
| 93 | # HACK(vadimsh): It is assumed here that the token cache key is a hostname. |
| 94 | msg = ( |
| 95 | 'You are not logged in. Please login first by running:\n' |
| 96 | ' depot-tools-auth login %s' % token_cache_key) |
| 97 | super(LoginRequiredError, self).__init__(msg) |
| 98 | |
| 99 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 100 | def make_auth_config( |
| 101 | use_oauth2=None, |
| 102 | save_cookies=None, |
| 103 | use_local_webserver=None, |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 104 | webserver_port=None, |
| 105 | refresh_token_json=None): |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 106 | """Returns new instance of AuthConfig. |
| 107 | |
| 108 | If some config option is None, it will be set to a reasonable default value. |
| 109 | This function also acts as an authoritative place for default values of |
| 110 | corresponding command line options. |
| 111 | """ |
| 112 | default = lambda val, d: val if val is not None else d |
| 113 | return AuthConfig( |
vadimsh@chromium.org | 19f3fe6 | 2015-04-20 17:03:10 +0000 | [diff] [blame] | 114 | default(use_oauth2, True), |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 115 | default(save_cookies, True), |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 116 | default(use_local_webserver, not _is_headless()), |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 117 | default(webserver_port, 8090), |
| 118 | default(refresh_token_json, '')) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 119 | |
| 120 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 121 | def add_auth_options(parser, default_config=None): |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 122 | """Appends OAuth related options to OptionParser.""" |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 123 | default_config = default_config or make_auth_config() |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 124 | parser.auth_group = optparse.OptionGroup(parser, 'Auth options') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 125 | parser.add_option_group(parser.auth_group) |
| 126 | |
| 127 | # OAuth2 vs password switch. |
| 128 | auth_default = 'use OAuth2' if default_config.use_oauth2 else 'use password' |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 129 | parser.auth_group.add_option( |
| 130 | '--oauth2', |
| 131 | action='store_true', |
| 132 | dest='use_oauth2', |
| 133 | default=default_config.use_oauth2, |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 134 | help='Use OAuth 2.0 instead of a password. [default: %s]' % auth_default) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 135 | parser.auth_group.add_option( |
| 136 | '--no-oauth2', |
| 137 | action='store_false', |
| 138 | dest='use_oauth2', |
| 139 | default=default_config.use_oauth2, |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 140 | help='Use password instead of OAuth 2.0. [default: %s]' % auth_default) |
| 141 | |
| 142 | # Password related options, deprecated. |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 143 | parser.auth_group.add_option( |
| 144 | '--no-cookies', |
| 145 | action='store_false', |
| 146 | dest='save_cookies', |
| 147 | default=default_config.save_cookies, |
| 148 | help='Do not save authentication cookies to local disk.') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 149 | |
| 150 | # OAuth2 related options. |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 151 | parser.auth_group.add_option( |
| 152 | '--auth-no-local-webserver', |
| 153 | action='store_false', |
| 154 | dest='use_local_webserver', |
| 155 | default=default_config.use_local_webserver, |
| 156 | help='Do not run a local web server when performing OAuth2 login flow.') |
| 157 | parser.auth_group.add_option( |
| 158 | '--auth-host-port', |
| 159 | type=int, |
| 160 | default=default_config.webserver_port, |
| 161 | help='Port a local web server should listen on. Used only if ' |
| 162 | '--auth-no-local-webserver is not set. [default: %default]') |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 163 | parser.auth_group.add_option( |
| 164 | '--auth-refresh-token-json', |
| 165 | default=default_config.refresh_token_json, |
| 166 | help='Path to a JSON file with role account refresh token to use.') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 167 | |
| 168 | |
| 169 | def extract_auth_config_from_options(options): |
| 170 | """Given OptionParser parsed options, extracts AuthConfig from it. |
| 171 | |
| 172 | OptionParser should be populated with auth options by 'add_auth_options'. |
| 173 | """ |
| 174 | return make_auth_config( |
| 175 | use_oauth2=options.use_oauth2, |
| 176 | save_cookies=False if options.use_oauth2 else options.save_cookies, |
| 177 | use_local_webserver=options.use_local_webserver, |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 178 | webserver_port=options.auth_host_port, |
| 179 | refresh_token_json=options.auth_refresh_token_json) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 180 | |
| 181 | |
| 182 | def auth_config_to_command_options(auth_config): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 183 | """AuthConfig -> list of strings with command line options. |
| 184 | |
| 185 | Omits options that are set to default values. |
| 186 | """ |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 187 | if not auth_config: |
| 188 | return [] |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 189 | defaults = make_auth_config() |
| 190 | opts = [] |
| 191 | if auth_config.use_oauth2 != defaults.use_oauth2: |
| 192 | opts.append('--oauth2' if auth_config.use_oauth2 else '--no-oauth2') |
| 193 | if auth_config.save_cookies != auth_config.save_cookies: |
| 194 | if not auth_config.save_cookies: |
| 195 | opts.append('--no-cookies') |
| 196 | if auth_config.use_local_webserver != defaults.use_local_webserver: |
| 197 | if not auth_config.use_local_webserver: |
| 198 | opts.append('--auth-no-local-webserver') |
| 199 | if auth_config.webserver_port != defaults.webserver_port: |
| 200 | opts.extend(['--auth-host-port', str(auth_config.webserver_port)]) |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 201 | if auth_config.refresh_token_json != defaults.refresh_token_json: |
| 202 | opts.extend([ |
| 203 | '--auth-refresh-token-json', str(auth_config.refresh_token_json)]) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 204 | return opts |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 205 | |
| 206 | |
| 207 | def get_authenticator_for_host(hostname, config): |
| 208 | """Returns Authenticator instance to access given host. |
| 209 | |
| 210 | Args: |
| 211 | hostname: a naked hostname or http(s)://<hostname>[/] URL. Used to derive |
| 212 | a cache key for token cache. |
| 213 | config: AuthConfig instance. |
| 214 | |
| 215 | Returns: |
| 216 | Authenticator object. |
| 217 | """ |
| 218 | hostname = hostname.lower().rstrip('/') |
| 219 | # Append some scheme, otherwise urlparse puts hostname into parsed.path. |
| 220 | if '://' not in hostname: |
| 221 | hostname = 'https://' + hostname |
| 222 | parsed = urlparse.urlparse(hostname) |
| 223 | if parsed.path or parsed.params or parsed.query or parsed.fragment: |
| 224 | raise AuthenticationError( |
| 225 | 'Expecting a hostname or root host URL, got %s instead' % hostname) |
| 226 | return Authenticator(parsed.netloc, config) |
| 227 | |
| 228 | |
| 229 | class Authenticator(object): |
| 230 | """Object that knows how to refresh access tokens when needed. |
| 231 | |
| 232 | Args: |
| 233 | token_cache_key: string key of a section of the token cache file to use |
| 234 | to keep the tokens. See hostname_to_token_cache_key. |
| 235 | config: AuthConfig object that holds authentication configuration. |
| 236 | """ |
| 237 | |
| 238 | def __init__(self, token_cache_key, config): |
| 239 | assert isinstance(config, AuthConfig) |
| 240 | assert config.use_oauth2 |
| 241 | self._access_token = None |
| 242 | self._config = config |
| 243 | self._lock = threading.Lock() |
| 244 | self._token_cache_key = token_cache_key |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 245 | self._external_token = None |
| 246 | if config.refresh_token_json: |
| 247 | self._external_token = _read_refresh_token_json(config.refresh_token_json) |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 248 | logging.debug('Using auth config %r', config) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 249 | |
| 250 | def login(self): |
| 251 | """Performs interactive login flow if necessary. |
| 252 | |
| 253 | Raises: |
| 254 | AuthenticationError on error or if interrupted. |
| 255 | """ |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 256 | if self._external_token: |
| 257 | raise AuthenticationError( |
| 258 | 'Can\'t run login flow when using --auth-refresh-token-json.') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 259 | return self.get_access_token( |
| 260 | force_refresh=True, allow_user_interaction=True) |
| 261 | |
| 262 | def logout(self): |
| 263 | """Revokes the refresh token and deletes it from the cache. |
| 264 | |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 265 | Returns True if had some credentials cached. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 266 | """ |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 267 | with self._lock: |
| 268 | self._access_token = None |
| 269 | storage = self._get_storage() |
| 270 | credentials = storage.get() |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 271 | had_creds = bool(credentials) |
| 272 | if credentials and credentials.refresh_token and credentials.revoke_uri: |
| 273 | try: |
| 274 | credentials.revoke(httplib2.Http()) |
| 275 | except client.TokenRevokeError as e: |
| 276 | logging.warning('Failed to revoke refresh token: %s', e) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 277 | storage.delete() |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 278 | return had_creds |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 279 | |
| 280 | def has_cached_credentials(self): |
| 281 | """Returns True if long term credentials (refresh token) are in cache. |
| 282 | |
| 283 | Doesn't make network calls. |
| 284 | |
| 285 | If returns False, get_access_token() later will ask for interactive login by |
| 286 | raising LoginRequiredError. |
| 287 | |
| 288 | If returns True, most probably get_access_token() won't ask for interactive |
| 289 | login, though it is not guaranteed, since cached token can be already |
| 290 | revoked and there's no way to figure this out without actually trying to use |
| 291 | it. |
| 292 | """ |
| 293 | with self._lock: |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 294 | return bool(self._get_cached_credentials()) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 295 | |
| 296 | def get_access_token(self, force_refresh=False, allow_user_interaction=False): |
| 297 | """Returns AccessToken, refreshing it if necessary. |
| 298 | |
| 299 | Args: |
| 300 | force_refresh: forcefully refresh access token even if it is not expired. |
| 301 | allow_user_interaction: True to enable blocking for user input if needed. |
| 302 | |
| 303 | Raises: |
| 304 | AuthenticationError on error or if authentication flow was interrupted. |
| 305 | LoginRequiredError if user interaction is required, but |
| 306 | allow_user_interaction is False. |
| 307 | """ |
| 308 | with self._lock: |
| 309 | if force_refresh: |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 310 | logging.debug('Forcing access token refresh') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 311 | self._access_token = self._create_access_token(allow_user_interaction) |
| 312 | return self._access_token |
| 313 | |
| 314 | # Load from on-disk cache on a first access. |
| 315 | if not self._access_token: |
| 316 | self._access_token = self._load_access_token() |
| 317 | |
| 318 | # Refresh if expired or missing. |
| 319 | if not self._access_token or _needs_refresh(self._access_token): |
| 320 | # Maybe some other process already updated it, reload from the cache. |
| 321 | self._access_token = self._load_access_token() |
| 322 | # Nope, still expired, need to run the refresh flow. |
| 323 | if not self._access_token or _needs_refresh(self._access_token): |
| 324 | self._access_token = self._create_access_token(allow_user_interaction) |
| 325 | |
| 326 | return self._access_token |
| 327 | |
| 328 | def get_token_info(self): |
| 329 | """Returns a result of /oauth2/v2/tokeninfo call with token info.""" |
| 330 | access_token = self.get_access_token() |
| 331 | resp, content = httplib2.Http().request( |
| 332 | uri='https://www.googleapis.com/oauth2/v2/tokeninfo?%s' % ( |
| 333 | urllib.urlencode({'access_token': access_token.token}))) |
| 334 | if resp.status == 200: |
| 335 | return json.loads(content) |
| 336 | raise AuthenticationError('Failed to fetch the token info: %r' % content) |
| 337 | |
| 338 | def authorize(self, http): |
| 339 | """Monkey patches authentication logic of httplib2.Http instance. |
| 340 | |
| 341 | The modified http.request method will add authentication headers to each |
| 342 | request and will refresh access_tokens when a 401 is received on a |
| 343 | request. |
| 344 | |
| 345 | Args: |
| 346 | http: An instance of httplib2.Http. |
| 347 | |
| 348 | Returns: |
| 349 | A modified instance of http that was passed in. |
| 350 | """ |
| 351 | # Adapted from oauth2client.OAuth2Credentials.authorize. |
| 352 | |
| 353 | request_orig = http.request |
| 354 | |
| 355 | @functools.wraps(request_orig) |
| 356 | def new_request( |
| 357 | uri, method='GET', body=None, headers=None, |
| 358 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 359 | connection_type=None): |
| 360 | headers = (headers or {}).copy() |
vadimsh@chromium.org | afbb019 | 2015-04-13 23:26:31 +0000 | [diff] [blame] | 361 | headers['Authorization'] = 'Bearer %s' % self.get_access_token().token |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 362 | resp, content = request_orig( |
| 363 | uri, method, body, headers, redirections, connection_type) |
| 364 | if resp.status in client.REFRESH_STATUS_CODES: |
| 365 | logging.info('Refreshing due to a %s', resp.status) |
| 366 | access_token = self.get_access_token(force_refresh=True) |
vadimsh@chromium.org | afbb019 | 2015-04-13 23:26:31 +0000 | [diff] [blame] | 367 | headers['Authorization'] = 'Bearer %s' % access_token.token |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 368 | return request_orig( |
| 369 | uri, method, body, headers, redirections, connection_type) |
| 370 | else: |
| 371 | return (resp, content) |
| 372 | |
| 373 | http.request = new_request |
| 374 | return http |
| 375 | |
| 376 | ## Private methods. |
| 377 | |
| 378 | def _get_storage(self): |
| 379 | """Returns oauth2client.Storage with cached tokens.""" |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 380 | # Do not mix cache keys for different externally provided tokens. |
| 381 | if self._external_token: |
| 382 | token_hash = hashlib.sha1(self._external_token.refresh_token).hexdigest() |
| 383 | cache_key = '%s:refresh_tok:%s' % (self._token_cache_key, token_hash) |
| 384 | else: |
| 385 | cache_key = self._token_cache_key |
vadimsh@chromium.org | 148f76f | 2015-04-21 01:44:13 +0000 | [diff] [blame^] | 386 | path = _get_token_cache_path() |
| 387 | logging.debug('Using token storage %r (cache key %r)', path, cache_key) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 388 | return multistore_file.get_credential_storage_custom_string_key( |
vadimsh@chromium.org | 148f76f | 2015-04-21 01:44:13 +0000 | [diff] [blame^] | 389 | path, cache_key) |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 390 | |
| 391 | def _get_cached_credentials(self): |
| 392 | """Returns oauth2client.Credentials loaded from storage.""" |
| 393 | storage = self._get_storage() |
| 394 | credentials = storage.get() |
| 395 | |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 396 | if not credentials: |
| 397 | logging.debug('No cached token') |
| 398 | else: |
| 399 | _log_credentials_info('cached token', credentials) |
| 400 | |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 401 | # Is using --auth-refresh-token-json? |
| 402 | if self._external_token: |
| 403 | # Cached credentials are valid and match external token -> use them. It is |
| 404 | # important to reuse credentials from the storage because they contain |
| 405 | # cached access token. |
| 406 | valid = ( |
| 407 | credentials and not credentials.invalid and |
| 408 | credentials.refresh_token == self._external_token.refresh_token and |
| 409 | credentials.client_id == self._external_token.client_id and |
| 410 | credentials.client_secret == self._external_token.client_secret) |
| 411 | if valid: |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 412 | logging.debug('Cached credentials match external refresh token') |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 413 | return credentials |
| 414 | # Construct new credentials from externally provided refresh token, |
| 415 | # associate them with cache storage (so that access_token will be placed |
| 416 | # in the cache later too). |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 417 | logging.debug('Putting external refresh token into the cache') |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 418 | credentials = client.OAuth2Credentials( |
| 419 | access_token=None, |
| 420 | client_id=self._external_token.client_id, |
| 421 | client_secret=self._external_token.client_secret, |
| 422 | refresh_token=self._external_token.refresh_token, |
| 423 | token_expiry=None, |
| 424 | token_uri='https://accounts.google.com/o/oauth2/token', |
| 425 | user_agent=None, |
| 426 | revoke_uri=None) |
| 427 | credentials.set_store(storage) |
| 428 | storage.put(credentials) |
| 429 | return credentials |
| 430 | |
| 431 | # Not using external refresh token -> return whatever is cached. |
| 432 | return credentials if (credentials and not credentials.invalid) else None |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 433 | |
| 434 | def _load_access_token(self): |
| 435 | """Returns cached AccessToken if it is not expired yet.""" |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 436 | logging.debug('Reloading access token from cache') |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 437 | creds = self._get_cached_credentials() |
| 438 | if not creds or not creds.access_token or creds.access_token_expired: |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 439 | logging.debug('Access token is missing or expired') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 440 | return None |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 441 | return AccessToken(str(creds.access_token), creds.token_expiry) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 442 | |
| 443 | def _create_access_token(self, allow_user_interaction=False): |
| 444 | """Mints and caches a new access token, launching OAuth2 dance if necessary. |
| 445 | |
| 446 | Uses cached refresh token, if present. In that case user interaction is not |
| 447 | required and function will finish quietly. Otherwise it will launch 3-legged |
| 448 | OAuth2 flow, that needs user interaction. |
| 449 | |
| 450 | Args: |
| 451 | allow_user_interaction: if True, allow interaction with the user (e.g. |
| 452 | reading standard input, or launching a browser). |
| 453 | |
| 454 | Returns: |
| 455 | AccessToken. |
| 456 | |
| 457 | Raises: |
| 458 | AuthenticationError on error or if authentication flow was interrupted. |
| 459 | LoginRequiredError if user interaction is required, but |
| 460 | allow_user_interaction is False. |
| 461 | """ |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 462 | logging.debug( |
| 463 | 'Making new access token (allow_user_interaction=%r)', |
| 464 | allow_user_interaction) |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 465 | credentials = self._get_cached_credentials() |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 466 | |
| 467 | # 3-legged flow with (perhaps cached) refresh token. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 468 | refreshed = False |
| 469 | if credentials and not credentials.invalid: |
| 470 | try: |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 471 | logging.debug('Attempting to refresh access_token') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 472 | credentials.refresh(httplib2.Http()) |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 473 | _log_credentials_info('refreshed token', credentials) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 474 | refreshed = True |
| 475 | except client.Error as err: |
| 476 | logging.warning( |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 477 | 'OAuth error during access token refresh (%s). ' |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 478 | 'Attempting a full authentication flow.', err) |
| 479 | |
| 480 | # Refresh token is missing or invalid, go through the full flow. |
| 481 | if not refreshed: |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 482 | # Can't refresh externally provided token. |
| 483 | if self._external_token: |
| 484 | raise AuthenticationError( |
| 485 | 'Token provided via --auth-refresh-token-json is no longer valid.') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 486 | if not allow_user_interaction: |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 487 | logging.debug('Requesting user to login') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 488 | raise LoginRequiredError(self._token_cache_key) |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 489 | logging.debug('Launching OAuth browser flow') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 490 | credentials = _run_oauth_dance(self._config) |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 491 | _log_credentials_info('new token', credentials) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 492 | |
| 493 | logging.info( |
| 494 | 'OAuth access_token refreshed. Expires in %s.', |
| 495 | credentials.token_expiry - datetime.datetime.utcnow()) |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 496 | storage = self._get_storage() |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 497 | credentials.set_store(storage) |
| 498 | storage.put(credentials) |
vadimsh@chromium.org | afbb019 | 2015-04-13 23:26:31 +0000 | [diff] [blame] | 499 | return AccessToken(str(credentials.access_token), credentials.token_expiry) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 500 | |
| 501 | |
| 502 | ## Private functions. |
| 503 | |
| 504 | |
vadimsh@chromium.org | 148f76f | 2015-04-21 01:44:13 +0000 | [diff] [blame^] | 505 | def _get_token_cache_path(): |
| 506 | # On non Win just use HOME. |
| 507 | if sys.platform != 'win32': |
| 508 | return os.path.join(os.path.expanduser('~'), OAUTH_TOKENS_CACHE) |
| 509 | # Prefer USERPROFILE over HOME, since HOME is overridden in |
| 510 | # git-..._bin/cmd/git.cmd to point to depot_tools. depot-tools-auth.py script |
| 511 | # (and all other scripts) doesn't use this override and thus uses another |
| 512 | # value for HOME. git.cmd doesn't touch USERPROFILE though, and usually |
| 513 | # USERPROFILE == HOME on Windows. |
| 514 | if 'USERPROFILE' in os.environ: |
| 515 | return os.path.join(os.environ['USERPROFILE'], OAUTH_TOKENS_CACHE) |
| 516 | return os.path.join(os.path.expanduser('~'), OAUTH_TOKENS_CACHE) |
| 517 | |
| 518 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 519 | def _is_headless(): |
| 520 | """True if machine doesn't seem to have a display.""" |
| 521 | return sys.platform == 'linux2' and not os.environ.get('DISPLAY') |
| 522 | |
| 523 | |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 524 | def _read_refresh_token_json(path): |
| 525 | """Returns RefreshToken by reading it from the JSON file.""" |
| 526 | try: |
| 527 | with open(path, 'r') as f: |
| 528 | data = json.load(f) |
| 529 | return RefreshToken( |
| 530 | client_id=str(data.get('client_id', OAUTH_CLIENT_ID)), |
| 531 | client_secret=str(data.get('client_secret', OAUTH_CLIENT_SECRET)), |
| 532 | refresh_token=str(data['refresh_token'])) |
| 533 | except (IOError, ValueError) as e: |
| 534 | raise AuthenticationError( |
| 535 | 'Failed to read refresh token from %s: %s' % (path, e)) |
| 536 | except KeyError as e: |
| 537 | raise AuthenticationError( |
| 538 | 'Failed to read refresh token from %s: missing key %s' % (path, e)) |
| 539 | |
| 540 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 541 | def _needs_refresh(access_token): |
| 542 | """True if AccessToken should be refreshed.""" |
| 543 | if access_token.expires_at is not None: |
| 544 | # Allow 5 min of clock skew between client and backend. |
| 545 | now = datetime.datetime.utcnow() + datetime.timedelta(seconds=300) |
| 546 | return now >= access_token.expires_at |
| 547 | # Token without expiration time never expires. |
| 548 | return False |
| 549 | |
| 550 | |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 551 | def _log_credentials_info(title, credentials): |
| 552 | """Dumps (non sensitive) part of client.Credentials object to debug log.""" |
| 553 | if credentials: |
| 554 | logging.debug('%s info: %r', title, { |
| 555 | 'access_token_expired': credentials.access_token_expired, |
| 556 | 'has_access_token': bool(credentials.access_token), |
| 557 | 'invalid': credentials.invalid, |
| 558 | 'utcnow': datetime.datetime.utcnow(), |
| 559 | 'token_expiry': credentials.token_expiry, |
| 560 | }) |
| 561 | |
| 562 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 563 | def _run_oauth_dance(config): |
| 564 | """Perform full 3-legged OAuth2 flow with the browser. |
| 565 | |
| 566 | Returns: |
| 567 | oauth2client.Credentials. |
| 568 | |
| 569 | Raises: |
| 570 | AuthenticationError on errors. |
| 571 | """ |
| 572 | flow = client.OAuth2WebServerFlow( |
| 573 | OAUTH_CLIENT_ID, |
| 574 | OAUTH_CLIENT_SECRET, |
| 575 | OAUTH_SCOPES, |
| 576 | approval_prompt='force') |
| 577 | |
| 578 | use_local_webserver = config.use_local_webserver |
| 579 | port = config.webserver_port |
| 580 | if config.use_local_webserver: |
| 581 | success = False |
| 582 | try: |
| 583 | httpd = _ClientRedirectServer(('localhost', port), _ClientRedirectHandler) |
| 584 | except socket.error: |
| 585 | pass |
| 586 | else: |
| 587 | success = True |
| 588 | use_local_webserver = success |
| 589 | if not success: |
| 590 | print( |
| 591 | 'Failed to start a local webserver listening on port %d.\n' |
| 592 | 'Please check your firewall settings and locally running programs that ' |
| 593 | 'may be blocking or using those ports.\n\n' |
| 594 | 'Falling back to --auth-no-local-webserver and continuing with ' |
| 595 | 'authentication.\n' % port) |
| 596 | |
| 597 | if use_local_webserver: |
| 598 | oauth_callback = 'http://localhost:%s/' % port |
| 599 | else: |
| 600 | oauth_callback = client.OOB_CALLBACK_URN |
| 601 | flow.redirect_uri = oauth_callback |
| 602 | authorize_url = flow.step1_get_authorize_url() |
| 603 | |
| 604 | if use_local_webserver: |
| 605 | webbrowser.open(authorize_url, new=1, autoraise=True) |
| 606 | print( |
| 607 | 'Your browser has been opened to visit:\n\n' |
| 608 | ' %s\n\n' |
| 609 | 'If your browser is on a different machine then exit and re-run this ' |
| 610 | 'application with the command-line parameter\n\n' |
| 611 | ' --auth-no-local-webserver\n' % authorize_url) |
| 612 | else: |
| 613 | print( |
| 614 | 'Go to the following link in your browser:\n\n' |
| 615 | ' %s\n' % authorize_url) |
| 616 | |
| 617 | try: |
| 618 | code = None |
| 619 | if use_local_webserver: |
| 620 | httpd.handle_request() |
| 621 | if 'error' in httpd.query_params: |
| 622 | raise AuthenticationError( |
| 623 | 'Authentication request was rejected: %s' % |
| 624 | httpd.query_params['error']) |
| 625 | if 'code' not in httpd.query_params: |
| 626 | raise AuthenticationError( |
| 627 | 'Failed to find "code" in the query parameters of the redirect.\n' |
| 628 | 'Try running with --auth-no-local-webserver.') |
| 629 | code = httpd.query_params['code'] |
| 630 | else: |
| 631 | code = raw_input('Enter verification code: ').strip() |
| 632 | except KeyboardInterrupt: |
| 633 | raise AuthenticationError('Authentication was canceled.') |
| 634 | |
| 635 | try: |
| 636 | return flow.step2_exchange(code) |
| 637 | except client.FlowExchangeError as e: |
| 638 | raise AuthenticationError('Authentication has failed: %s' % e) |
| 639 | |
| 640 | |
| 641 | class _ClientRedirectServer(BaseHTTPServer.HTTPServer): |
| 642 | """A server to handle OAuth 2.0 redirects back to localhost. |
| 643 | |
| 644 | Waits for a single request and parses the query parameters |
| 645 | into query_params and then stops serving. |
| 646 | """ |
| 647 | query_params = {} |
| 648 | |
| 649 | |
| 650 | class _ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): |
| 651 | """A handler for OAuth 2.0 redirects back to localhost. |
| 652 | |
| 653 | Waits for a single request and parses the query parameters |
| 654 | into the servers query_params and then stops serving. |
| 655 | """ |
| 656 | |
| 657 | def do_GET(self): |
| 658 | """Handle a GET request. |
| 659 | |
| 660 | Parses the query parameters and prints a message |
| 661 | if the flow has completed. Note that we can't detect |
| 662 | if an error occurred. |
| 663 | """ |
| 664 | self.send_response(200) |
| 665 | self.send_header('Content-type', 'text/html') |
| 666 | self.end_headers() |
| 667 | query = self.path.split('?', 1)[-1] |
| 668 | query = dict(urlparse.parse_qsl(query)) |
| 669 | self.server.query_params = query |
| 670 | self.wfile.write('<html><head><title>Authentication Status</title></head>') |
| 671 | self.wfile.write('<body><p>The authentication flow has completed.</p>') |
| 672 | self.wfile.write('</body></html>') |
| 673 | |
| 674 | def log_message(self, _format, *args): |
| 675 | """Do not log messages to stdout while running as command line program.""" |