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 | |
Raul Tambre | 80ee78e | 2019-05-06 22:41:05 +0000 | [diff] [blame] | 7 | from __future__ import print_function |
| 8 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 9 | import collections |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 10 | import datetime |
| 11 | import functools |
| 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 |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 16 | import sys |
| 17 | import threading |
| 18 | import urllib |
| 19 | import urlparse |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 20 | |
| 21 | import subprocess2 |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 22 | |
Nodir Turakulov | 5abb9b7 | 2019-10-12 20:55:10 +0000 | [diff] [blame^] | 23 | from third_party import httplib2 |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 24 | from third_party.oauth2client import client |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 25 | |
| 26 | |
| 27 | # depot_tools/. |
| 28 | DEPOT_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 29 | |
| 30 | |
| 31 | # Google OAuth2 clients always have a secret, even if the client is an installed |
| 32 | # application/utility such as this. Of course, in such cases the "secret" is |
| 33 | # actually publicly known; security depends entirely on the secrecy of refresh |
| 34 | # tokens, which effectively become bearer tokens. An attacker can impersonate |
| 35 | # service's identity in OAuth2 flow. But that's generally fine as long as a list |
| 36 | # of allowed redirect_uri's associated with client_id is limited to 'localhost' |
| 37 | # or 'urn:ietf:wg:oauth:2.0:oob'. In that case attacker needs some process |
| 38 | # running on user's machine to successfully complete the flow and grab refresh |
| 39 | # token. When you have a malicious code running on your machine, you're screwed |
| 40 | # anyway. |
| 41 | # This particular set is managed by API Console project "chrome-infra-auth". |
| 42 | OAUTH_CLIENT_ID = ( |
| 43 | '446450136466-2hr92jrq8e6i4tnsa56b52vacp7t3936.apps.googleusercontent.com') |
| 44 | OAUTH_CLIENT_SECRET = 'uBfbay2KCy9t4QveJ-dOqHtp' |
| 45 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 46 | # This is what most GAE apps require for authentication. |
| 47 | OAUTH_SCOPE_EMAIL = 'https://www.googleapis.com/auth/userinfo.email' |
| 48 | # Gerrit and Git on *.googlesource.com require this scope. |
| 49 | OAUTH_SCOPE_GERRIT = 'https://www.googleapis.com/auth/gerritcodereview' |
| 50 | # Deprecated. Use OAUTH_SCOPE_EMAIL instead. |
| 51 | OAUTH_SCOPES = OAUTH_SCOPE_EMAIL |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 52 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 53 | |
| 54 | # Authentication configuration extracted from command line options. |
| 55 | # See doc string for 'make_auth_config' for meaning of fields. |
| 56 | AuthConfig = collections.namedtuple('AuthConfig', [ |
| 57 | 'use_oauth2', # deprecated, will be always True |
| 58 | 'save_cookies', # deprecated, will be removed |
| 59 | 'use_local_webserver', |
| 60 | 'webserver_port', |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 61 | 'refresh_token_json', |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 62 | ]) |
| 63 | |
| 64 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 65 | # OAuth access token with its expiration time (UTC datetime or None if unknown). |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 66 | class AccessToken(collections.namedtuple('AccessToken', [ |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 67 | 'token', |
| 68 | 'expires_at', |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 69 | ])): |
| 70 | |
| 71 | def needs_refresh(self, now=None): |
| 72 | """True if this AccessToken should be refreshed.""" |
| 73 | if self.expires_at is not None: |
| 74 | now = now or datetime.datetime.utcnow() |
Andrii Shyshkalov | 142a92c | 2018-05-04 12:21:24 -0700 | [diff] [blame] | 75 | # Allow 3 min of clock skew between client and backend. |
| 76 | now += datetime.timedelta(seconds=180) |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 77 | return now >= self.expires_at |
| 78 | # Token without expiration time never expires. |
| 79 | return False |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 80 | |
| 81 | |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 82 | # Refresh token passed via --auth-refresh-token-json. |
| 83 | RefreshToken = collections.namedtuple('RefreshToken', [ |
| 84 | 'client_id', |
| 85 | 'client_secret', |
| 86 | 'refresh_token', |
| 87 | ]) |
| 88 | |
| 89 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 90 | class AuthenticationError(Exception): |
| 91 | """Raised on errors related to authentication.""" |
| 92 | |
| 93 | |
| 94 | class LoginRequiredError(AuthenticationError): |
| 95 | """Interaction with the user is required to authenticate.""" |
| 96 | |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 97 | def __init__(self, scopes=OAUTH_SCOPE_EMAIL): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 98 | msg = ( |
| 99 | 'You are not logged in. Please login first by running:\n' |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 100 | ' luci-auth login -scopes %s' % scopes) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 101 | super(LoginRequiredError, self).__init__(msg) |
| 102 | |
| 103 | |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 104 | class LuciContextAuthError(Exception): |
| 105 | """Raised on errors related to unsuccessful attempts to load LUCI_CONTEXT""" |
| 106 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 107 | def __init__(self, msg, exc=None): |
| 108 | if exc is None: |
| 109 | logging.error(msg) |
| 110 | else: |
| 111 | logging.exception(msg) |
| 112 | msg = '%s: %s' % (msg, exc) |
| 113 | super(LuciContextAuthError, self).__init__(msg) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 114 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 115 | |
| 116 | def has_luci_context_local_auth(): |
| 117 | """Returns whether LUCI_CONTEXT should be used for ambient authentication. |
| 118 | """ |
| 119 | try: |
Andrii Shyshkalov | b3c4441 | 2018-04-19 14:27:19 -0700 | [diff] [blame] | 120 | params = _get_luci_context_local_auth_params() |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 121 | except LuciContextAuthError: |
| 122 | return False |
| 123 | if params is None: |
| 124 | return False |
| 125 | return bool(params.default_account_id) |
| 126 | |
| 127 | |
| 128 | def get_luci_context_access_token(scopes=OAUTH_SCOPE_EMAIL): |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 129 | """Returns a valid AccessToken from the local LUCI context auth server. |
| 130 | |
| 131 | Adapted from |
| 132 | https://chromium.googlesource.com/infra/luci/luci-py/+/master/client/libs/luci_context/luci_context.py |
| 133 | See the link above for more details. |
| 134 | |
| 135 | Returns: |
| 136 | AccessToken if LUCI_CONTEXT is present and attempt to load it is successful. |
| 137 | None if LUCI_CONTEXT is absent. |
| 138 | |
| 139 | Raises: |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 140 | LuciContextAuthError if LUCI_CONTEXT is present, but there was a failure |
| 141 | obtaining its access token. |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 142 | """ |
Andrii Shyshkalov | b3c4441 | 2018-04-19 14:27:19 -0700 | [diff] [blame] | 143 | params = _get_luci_context_local_auth_params() |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 144 | if params is None: |
| 145 | return None |
| 146 | return _get_luci_context_access_token( |
| 147 | params, datetime.datetime.utcnow(), scopes) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 148 | |
| 149 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 150 | _LuciContextLocalAuthParams = collections.namedtuple( |
| 151 | '_LuciContextLocalAuthParams', [ |
| 152 | 'default_account_id', |
| 153 | 'secret', |
| 154 | 'rpc_port', |
| 155 | ]) |
| 156 | |
| 157 | |
Andrii Shyshkalov | b3c4441 | 2018-04-19 14:27:19 -0700 | [diff] [blame] | 158 | def _cache_thread_safe(f): |
| 159 | """Decorator caching result of nullary function in thread-safe way.""" |
| 160 | lock = threading.Lock() |
| 161 | cache = [] |
| 162 | |
| 163 | @functools.wraps(f) |
| 164 | def caching_wrapper(): |
| 165 | if not cache: |
| 166 | with lock: |
| 167 | if not cache: |
| 168 | cache.append(f()) |
| 169 | return cache[0] |
| 170 | |
| 171 | # Allow easy way to clear cache, particularly useful in tests. |
| 172 | caching_wrapper.clear_cache = lambda: cache.pop() if cache else None |
| 173 | return caching_wrapper |
| 174 | |
| 175 | |
| 176 | @_cache_thread_safe |
| 177 | def _get_luci_context_local_auth_params(): |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 178 | """Returns local auth parameters if local auth is configured else None. |
| 179 | |
| 180 | Raises LuciContextAuthError on unexpected failures. |
| 181 | """ |
Andrii Shyshkalov | b3c4441 | 2018-04-19 14:27:19 -0700 | [diff] [blame] | 182 | ctx_path = os.environ.get('LUCI_CONTEXT') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 183 | if not ctx_path: |
| 184 | return None |
| 185 | ctx_path = ctx_path.decode(sys.getfilesystemencoding()) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 186 | try: |
| 187 | loaded = _load_luci_context(ctx_path) |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 188 | except (OSError, IOError, ValueError) as e: |
| 189 | raise LuciContextAuthError('Failed to open, read or decode LUCI_CONTEXT', e) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 190 | try: |
| 191 | local_auth = loaded.get('local_auth') |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 192 | except AttributeError as e: |
| 193 | raise LuciContextAuthError('LUCI_CONTEXT not in proper format', e) |
| 194 | if local_auth is None: |
| 195 | logging.debug('LUCI_CONTEXT configured w/o local auth') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 196 | return None |
| 197 | try: |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 198 | return _LuciContextLocalAuthParams( |
| 199 | default_account_id=local_auth.get('default_account_id'), |
| 200 | secret=local_auth.get('secret'), |
| 201 | rpc_port=int(local_auth.get('rpc_port'))) |
| 202 | except (AttributeError, ValueError) as e: |
| 203 | raise LuciContextAuthError('local_auth config malformed', e) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 204 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 205 | |
| 206 | def _load_luci_context(ctx_path): |
| 207 | # Kept separate for test mocking. |
| 208 | with open(ctx_path) as f: |
| 209 | return json.load(f) |
| 210 | |
| 211 | |
| 212 | def _get_luci_context_access_token(params, now, scopes=OAUTH_SCOPE_EMAIL): |
| 213 | # No account, local_auth shouldn't be used. |
| 214 | if not params.default_account_id: |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 215 | return None |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 216 | if not params.secret: |
| 217 | raise LuciContextAuthError('local_auth: no secret') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 218 | |
| 219 | logging.debug('local_auth: requesting an access token for account "%s"', |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 220 | params.default_account_id) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 221 | http = httplib2.Http() |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 222 | host = '127.0.0.1:%d' % params.rpc_port |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 223 | resp, content = http.request( |
| 224 | uri='http://%s/rpc/LuciLocalAuthService.GetOAuthToken' % host, |
| 225 | method='POST', |
| 226 | body=json.dumps({ |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 227 | 'account_id': params.default_account_id, |
| 228 | 'scopes': scopes.split(' '), |
| 229 | 'secret': params.secret, |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 230 | }), |
| 231 | headers={'Content-Type': 'application/json'}) |
| 232 | if resp.status != 200: |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 233 | raise LuciContextAuthError( |
| 234 | 'local_auth: Failed to grab access token from ' |
| 235 | 'LUCI context server with status %d: %r' % (resp.status, content)) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 236 | try: |
| 237 | token = json.loads(content) |
| 238 | error_code = token.get('error_code') |
| 239 | error_message = token.get('error_message') |
| 240 | access_token = token.get('access_token') |
| 241 | expiry = token.get('expiry') |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 242 | except (AttributeError, ValueError) as e: |
| 243 | raise LuciContextAuthError('Unexpected access token response format', e) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 244 | if error_code: |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 245 | raise LuciContextAuthError( |
| 246 | 'Error %d in retrieving access token: %s', error_code, error_message) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 247 | if not access_token: |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 248 | raise LuciContextAuthError( |
| 249 | 'No access token returned from LUCI context server') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 250 | expiry_dt = None |
| 251 | if expiry: |
| 252 | try: |
| 253 | expiry_dt = datetime.datetime.utcfromtimestamp(expiry) |
Mun Yong Jang | 1728f5f | 2017-11-27 13:29:08 -0800 | [diff] [blame] | 254 | logging.debug( |
| 255 | 'local_auth: got an access token for ' |
| 256 | 'account "%s" that expires in %d sec', |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 257 | params.default_account_id, (expiry_dt - now).total_seconds()) |
| 258 | except (TypeError, ValueError) as e: |
| 259 | raise LuciContextAuthError('Invalid expiry in returned token', e) |
Mun Yong Jang | 1728f5f | 2017-11-27 13:29:08 -0800 | [diff] [blame] | 260 | else: |
| 261 | logging.debug( |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 262 | 'local auth: got an access token for account "%s" that does not expire', |
| 263 | params.default_account_id) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 264 | access_token = AccessToken(access_token, expiry_dt) |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 265 | if access_token.needs_refresh(now=now): |
| 266 | raise LuciContextAuthError('Received access token is already expired') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 267 | return access_token |
| 268 | |
| 269 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 270 | def make_auth_config( |
| 271 | use_oauth2=None, |
| 272 | save_cookies=None, |
| 273 | use_local_webserver=None, |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 274 | webserver_port=None, |
| 275 | refresh_token_json=None): |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 276 | """Returns new instance of AuthConfig. |
| 277 | |
| 278 | If some config option is None, it will be set to a reasonable default value. |
| 279 | This function also acts as an authoritative place for default values of |
| 280 | corresponding command line options. |
| 281 | """ |
| 282 | default = lambda val, d: val if val is not None else d |
| 283 | return AuthConfig( |
vadimsh@chromium.org | 19f3fe6 | 2015-04-20 17:03:10 +0000 | [diff] [blame] | 284 | default(use_oauth2, True), |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 285 | default(save_cookies, True), |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 286 | default(use_local_webserver, not _is_headless()), |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 287 | default(webserver_port, 8090), |
| 288 | default(refresh_token_json, '')) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 289 | |
| 290 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 291 | def add_auth_options(parser, default_config=None): |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 292 | """Appends OAuth related options to OptionParser.""" |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 293 | default_config = default_config or make_auth_config() |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 294 | parser.auth_group = optparse.OptionGroup(parser, 'Auth options') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 295 | parser.add_option_group(parser.auth_group) |
| 296 | |
| 297 | # OAuth2 vs password switch. |
| 298 | 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] | 299 | parser.auth_group.add_option( |
| 300 | '--oauth2', |
| 301 | action='store_true', |
| 302 | dest='use_oauth2', |
| 303 | default=default_config.use_oauth2, |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 304 | 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] | 305 | parser.auth_group.add_option( |
| 306 | '--no-oauth2', |
| 307 | action='store_false', |
| 308 | dest='use_oauth2', |
| 309 | default=default_config.use_oauth2, |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 310 | help='Use password instead of OAuth 2.0. [default: %s]' % auth_default) |
| 311 | |
| 312 | # Password related options, deprecated. |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 313 | parser.auth_group.add_option( |
| 314 | '--no-cookies', |
| 315 | action='store_false', |
| 316 | dest='save_cookies', |
| 317 | default=default_config.save_cookies, |
| 318 | help='Do not save authentication cookies to local disk.') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 319 | |
| 320 | # OAuth2 related options. |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 321 | parser.auth_group.add_option( |
| 322 | '--auth-no-local-webserver', |
| 323 | action='store_false', |
| 324 | dest='use_local_webserver', |
| 325 | default=default_config.use_local_webserver, |
| 326 | help='Do not run a local web server when performing OAuth2 login flow.') |
| 327 | parser.auth_group.add_option( |
| 328 | '--auth-host-port', |
| 329 | type=int, |
| 330 | default=default_config.webserver_port, |
| 331 | help='Port a local web server should listen on. Used only if ' |
| 332 | '--auth-no-local-webserver is not set. [default: %default]') |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 333 | parser.auth_group.add_option( |
| 334 | '--auth-refresh-token-json', |
| 335 | default=default_config.refresh_token_json, |
| 336 | 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] | 337 | |
| 338 | |
| 339 | def extract_auth_config_from_options(options): |
| 340 | """Given OptionParser parsed options, extracts AuthConfig from it. |
| 341 | |
| 342 | OptionParser should be populated with auth options by 'add_auth_options'. |
| 343 | """ |
| 344 | return make_auth_config( |
| 345 | use_oauth2=options.use_oauth2, |
| 346 | save_cookies=False if options.use_oauth2 else options.save_cookies, |
| 347 | use_local_webserver=options.use_local_webserver, |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 348 | webserver_port=options.auth_host_port, |
| 349 | refresh_token_json=options.auth_refresh_token_json) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 350 | |
| 351 | |
| 352 | def auth_config_to_command_options(auth_config): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 353 | """AuthConfig -> list of strings with command line options. |
| 354 | |
| 355 | Omits options that are set to default values. |
| 356 | """ |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 357 | if not auth_config: |
| 358 | return [] |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 359 | defaults = make_auth_config() |
| 360 | opts = [] |
| 361 | if auth_config.use_oauth2 != defaults.use_oauth2: |
| 362 | opts.append('--oauth2' if auth_config.use_oauth2 else '--no-oauth2') |
| 363 | if auth_config.save_cookies != auth_config.save_cookies: |
| 364 | if not auth_config.save_cookies: |
| 365 | opts.append('--no-cookies') |
| 366 | if auth_config.use_local_webserver != defaults.use_local_webserver: |
| 367 | if not auth_config.use_local_webserver: |
| 368 | opts.append('--auth-no-local-webserver') |
| 369 | if auth_config.webserver_port != defaults.webserver_port: |
| 370 | opts.extend(['--auth-host-port', str(auth_config.webserver_port)]) |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 371 | if auth_config.refresh_token_json != defaults.refresh_token_json: |
| 372 | opts.extend([ |
| 373 | '--auth-refresh-token-json', str(auth_config.refresh_token_json)]) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 374 | return opts |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 375 | |
| 376 | |
Edward Lemur | b4a587d | 2019-10-09 23:56:38 +0000 | [diff] [blame] | 377 | def get_authenticator(config, scopes=OAUTH_SCOPE_EMAIL): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 378 | """Returns Authenticator instance to access given host. |
| 379 | |
| 380 | Args: |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 381 | config: AuthConfig instance. |
Andrii Shyshkalov | 741afe8 | 2018-04-19 14:32:18 -0700 | [diff] [blame] | 382 | scopes: space separated oauth scopes. Defaults to OAUTH_SCOPE_EMAIL. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 383 | |
| 384 | Returns: |
| 385 | Authenticator object. |
| 386 | """ |
Edward Lemur | b4a587d | 2019-10-09 23:56:38 +0000 | [diff] [blame] | 387 | return Authenticator(config, scopes) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 388 | |
| 389 | |
| 390 | class Authenticator(object): |
| 391 | """Object that knows how to refresh access tokens when needed. |
| 392 | |
| 393 | Args: |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 394 | config: AuthConfig object that holds authentication configuration. |
| 395 | """ |
| 396 | |
Edward Lemur | b4a587d | 2019-10-09 23:56:38 +0000 | [diff] [blame] | 397 | def __init__(self, config, scopes): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 398 | assert isinstance(config, AuthConfig) |
| 399 | assert config.use_oauth2 |
| 400 | self._access_token = None |
| 401 | self._config = config |
| 402 | self._lock = threading.Lock() |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 403 | self._external_token = None |
seanmccullough@chromium.org | 3e4a581 | 2015-06-11 17:48:47 +0000 | [diff] [blame] | 404 | self._scopes = scopes |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 405 | if config.refresh_token_json: |
| 406 | self._external_token = _read_refresh_token_json(config.refresh_token_json) |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 407 | logging.debug('Using auth config %r', config) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 408 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 409 | def has_cached_credentials(self): |
| 410 | """Returns True if long term credentials (refresh token) are in cache. |
| 411 | |
| 412 | Doesn't make network calls. |
| 413 | |
| 414 | If returns False, get_access_token() later will ask for interactive login by |
| 415 | raising LoginRequiredError. |
| 416 | |
| 417 | If returns True, most probably get_access_token() won't ask for interactive |
| 418 | login, though it is not guaranteed, since cached token can be already |
| 419 | revoked and there's no way to figure this out without actually trying to use |
| 420 | it. |
| 421 | """ |
| 422 | with self._lock: |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 423 | return bool(self._get_cached_credentials()) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 424 | |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 425 | def get_access_token(self, force_refresh=False, allow_user_interaction=False, |
| 426 | use_local_auth=True): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 427 | """Returns AccessToken, refreshing it if necessary. |
| 428 | |
| 429 | Args: |
| 430 | force_refresh: forcefully refresh access token even if it is not expired. |
| 431 | allow_user_interaction: True to enable blocking for user input if needed. |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 432 | use_local_auth: default to local auth if needed. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 433 | |
| 434 | Raises: |
| 435 | AuthenticationError on error or if authentication flow was interrupted. |
| 436 | LoginRequiredError if user interaction is required, but |
| 437 | allow_user_interaction is False. |
| 438 | """ |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 439 | def get_loc_auth_tkn(): |
| 440 | exi = sys.exc_info() |
| 441 | if not use_local_auth: |
| 442 | logging.error('Failed to create access token') |
| 443 | raise |
| 444 | try: |
| 445 | self._access_token = get_luci_context_access_token() |
| 446 | if not self._access_token: |
| 447 | logging.error('Failed to create access token') |
| 448 | raise |
| 449 | return self._access_token |
| 450 | except LuciContextAuthError: |
| 451 | logging.exception('Failed to use local auth') |
| 452 | raise exi[0], exi[1], exi[2] |
| 453 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 454 | with self._lock: |
| 455 | if force_refresh: |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 456 | logging.debug('Forcing access token refresh') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 457 | try: |
| 458 | self._access_token = self._create_access_token(allow_user_interaction) |
| 459 | return self._access_token |
| 460 | except LoginRequiredError: |
| 461 | return get_loc_auth_tkn() |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 462 | |
| 463 | # Load from on-disk cache on a first access. |
| 464 | if not self._access_token: |
| 465 | self._access_token = self._load_access_token() |
| 466 | |
| 467 | # Refresh if expired or missing. |
Andrii Shyshkalov | 94580ab | 2018-04-19 18:04:54 -0700 | [diff] [blame] | 468 | if not self._access_token or self._access_token.needs_refresh(): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 469 | # Maybe some other process already updated it, reload from the cache. |
| 470 | self._access_token = self._load_access_token() |
| 471 | # Nope, still expired, need to run the refresh flow. |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 472 | if not self._access_token or self._access_token.needs_refresh(): |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 473 | try: |
| 474 | self._access_token = self._create_access_token( |
| 475 | allow_user_interaction) |
| 476 | except LoginRequiredError: |
| 477 | get_loc_auth_tkn() |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 478 | |
| 479 | return self._access_token |
| 480 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 481 | def authorize(self, http): |
| 482 | """Monkey patches authentication logic of httplib2.Http instance. |
| 483 | |
| 484 | The modified http.request method will add authentication headers to each |
| 485 | request and will refresh access_tokens when a 401 is received on a |
| 486 | request. |
| 487 | |
| 488 | Args: |
| 489 | http: An instance of httplib2.Http. |
| 490 | |
| 491 | Returns: |
| 492 | A modified instance of http that was passed in. |
| 493 | """ |
| 494 | # Adapted from oauth2client.OAuth2Credentials.authorize. |
| 495 | |
| 496 | request_orig = http.request |
| 497 | |
| 498 | @functools.wraps(request_orig) |
| 499 | def new_request( |
| 500 | uri, method='GET', body=None, headers=None, |
| 501 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 502 | connection_type=None): |
| 503 | headers = (headers or {}).copy() |
vadimsh@chromium.org | afbb019 | 2015-04-13 23:26:31 +0000 | [diff] [blame] | 504 | headers['Authorization'] = 'Bearer %s' % self.get_access_token().token |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 505 | resp, content = request_orig( |
| 506 | uri, method, body, headers, redirections, connection_type) |
| 507 | if resp.status in client.REFRESH_STATUS_CODES: |
| 508 | logging.info('Refreshing due to a %s', resp.status) |
| 509 | access_token = self.get_access_token(force_refresh=True) |
vadimsh@chromium.org | afbb019 | 2015-04-13 23:26:31 +0000 | [diff] [blame] | 510 | headers['Authorization'] = 'Bearer %s' % access_token.token |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 511 | return request_orig( |
| 512 | uri, method, body, headers, redirections, connection_type) |
| 513 | else: |
| 514 | return (resp, content) |
| 515 | |
| 516 | http.request = new_request |
| 517 | return http |
| 518 | |
| 519 | ## Private methods. |
| 520 | |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 521 | def _get_cached_credentials(self): |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 522 | """Returns oauth2client.Credentials loaded from luci-auth.""" |
| 523 | credentials = _get_luci_auth_credentials(self._scopes) |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 524 | |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 525 | if not credentials: |
| 526 | logging.debug('No cached token') |
| 527 | else: |
| 528 | _log_credentials_info('cached token', credentials) |
| 529 | |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 530 | # Is using --auth-refresh-token-json? |
| 531 | if self._external_token: |
| 532 | # Cached credentials are valid and match external token -> use them. It is |
| 533 | # important to reuse credentials from the storage because they contain |
| 534 | # cached access token. |
| 535 | valid = ( |
| 536 | credentials and not credentials.invalid and |
| 537 | credentials.refresh_token == self._external_token.refresh_token and |
| 538 | credentials.client_id == self._external_token.client_id and |
| 539 | credentials.client_secret == self._external_token.client_secret) |
| 540 | if valid: |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 541 | logging.debug('Cached credentials match external refresh token') |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 542 | return credentials |
| 543 | # Construct new credentials from externally provided refresh token, |
| 544 | # associate them with cache storage (so that access_token will be placed |
| 545 | # in the cache later too). |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 546 | logging.debug('Putting external refresh token into the cache') |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 547 | credentials = client.OAuth2Credentials( |
| 548 | access_token=None, |
| 549 | client_id=self._external_token.client_id, |
| 550 | client_secret=self._external_token.client_secret, |
| 551 | refresh_token=self._external_token.refresh_token, |
| 552 | token_expiry=None, |
| 553 | token_uri='https://accounts.google.com/o/oauth2/token', |
| 554 | user_agent=None, |
| 555 | revoke_uri=None) |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 556 | return credentials |
| 557 | |
| 558 | # Not using external refresh token -> return whatever is cached. |
| 559 | return credentials if (credentials and not credentials.invalid) else None |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 560 | |
| 561 | def _load_access_token(self): |
| 562 | """Returns cached AccessToken if it is not expired yet.""" |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 563 | logging.debug('Reloading access token from cache') |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 564 | creds = self._get_cached_credentials() |
| 565 | 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] | 566 | logging.debug('Access token is missing or expired') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 567 | return None |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 568 | return AccessToken(str(creds.access_token), creds.token_expiry) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 569 | |
| 570 | def _create_access_token(self, allow_user_interaction=False): |
| 571 | """Mints and caches a new access token, launching OAuth2 dance if necessary. |
| 572 | |
| 573 | Uses cached refresh token, if present. In that case user interaction is not |
| 574 | required and function will finish quietly. Otherwise it will launch 3-legged |
| 575 | OAuth2 flow, that needs user interaction. |
| 576 | |
| 577 | Args: |
| 578 | allow_user_interaction: if True, allow interaction with the user (e.g. |
| 579 | reading standard input, or launching a browser). |
| 580 | |
| 581 | Returns: |
| 582 | AccessToken. |
| 583 | |
| 584 | Raises: |
| 585 | AuthenticationError on error or if authentication flow was interrupted. |
| 586 | LoginRequiredError if user interaction is required, but |
| 587 | allow_user_interaction is False. |
| 588 | """ |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 589 | logging.debug( |
| 590 | 'Making new access token (allow_user_interaction=%r)', |
| 591 | allow_user_interaction) |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 592 | credentials = self._get_cached_credentials() |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 593 | |
| 594 | # 3-legged flow with (perhaps cached) refresh token. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 595 | refreshed = False |
| 596 | if credentials and not credentials.invalid: |
| 597 | try: |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 598 | logging.debug('Attempting to refresh access_token') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 599 | credentials.refresh(httplib2.Http()) |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 600 | _log_credentials_info('refreshed token', credentials) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 601 | refreshed = True |
| 602 | except client.Error as err: |
| 603 | logging.warning( |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 604 | 'OAuth error during access token refresh (%s). ' |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 605 | 'Attempting a full authentication flow.', err) |
| 606 | |
| 607 | # Refresh token is missing or invalid, go through the full flow. |
| 608 | if not refreshed: |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 609 | # Can't refresh externally provided token. |
| 610 | if self._external_token: |
| 611 | raise AuthenticationError( |
| 612 | 'Token provided via --auth-refresh-token-json is no longer valid.') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 613 | if not allow_user_interaction: |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 614 | logging.debug('Requesting user to login') |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 615 | raise LoginRequiredError(self._scopes) |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 616 | logging.debug('Launching OAuth browser flow') |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 617 | credentials = _run_oauth_dance(self._scopes) |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 618 | _log_credentials_info('new token', credentials) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 619 | |
| 620 | logging.info( |
| 621 | 'OAuth access_token refreshed. Expires in %s.', |
| 622 | credentials.token_expiry - datetime.datetime.utcnow()) |
vadimsh@chromium.org | afbb019 | 2015-04-13 23:26:31 +0000 | [diff] [blame] | 623 | return AccessToken(str(credentials.access_token), credentials.token_expiry) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 624 | |
| 625 | |
| 626 | ## Private functions. |
| 627 | |
| 628 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 629 | def _is_headless(): |
| 630 | """True if machine doesn't seem to have a display.""" |
| 631 | return sys.platform == 'linux2' and not os.environ.get('DISPLAY') |
| 632 | |
| 633 | |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 634 | def _read_refresh_token_json(path): |
| 635 | """Returns RefreshToken by reading it from the JSON file.""" |
| 636 | try: |
| 637 | with open(path, 'r') as f: |
| 638 | data = json.load(f) |
| 639 | return RefreshToken( |
| 640 | client_id=str(data.get('client_id', OAUTH_CLIENT_ID)), |
| 641 | client_secret=str(data.get('client_secret', OAUTH_CLIENT_SECRET)), |
| 642 | refresh_token=str(data['refresh_token'])) |
| 643 | except (IOError, ValueError) as e: |
| 644 | raise AuthenticationError( |
| 645 | 'Failed to read refresh token from %s: %s' % (path, e)) |
| 646 | except KeyError as e: |
| 647 | raise AuthenticationError( |
| 648 | 'Failed to read refresh token from %s: missing key %s' % (path, e)) |
| 649 | |
| 650 | |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 651 | def _log_credentials_info(title, credentials): |
| 652 | """Dumps (non sensitive) part of client.Credentials object to debug log.""" |
| 653 | if credentials: |
| 654 | logging.debug('%s info: %r', title, { |
| 655 | 'access_token_expired': credentials.access_token_expired, |
| 656 | 'has_access_token': bool(credentials.access_token), |
| 657 | 'invalid': credentials.invalid, |
| 658 | 'utcnow': datetime.datetime.utcnow(), |
| 659 | 'token_expiry': credentials.token_expiry, |
| 660 | }) |
| 661 | |
| 662 | |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 663 | def _get_luci_auth_credentials(scopes): |
| 664 | try: |
| 665 | token_info = json.loads(subprocess2.check_output( |
| 666 | ['luci-auth', 'token', '-scopes', scopes, '-json-output', '-'], |
| 667 | stderr=subprocess2.VOID)) |
| 668 | except subprocess2.CalledProcessError: |
| 669 | return None |
| 670 | |
| 671 | return client.OAuth2Credentials( |
| 672 | access_token=token_info['token'], |
| 673 | client_id=OAUTH_CLIENT_ID, |
| 674 | client_secret=OAUTH_CLIENT_SECRET, |
| 675 | refresh_token=None, |
| 676 | token_expiry=datetime.datetime.utcfromtimestamp(token_info['expiry']), |
| 677 | token_uri=None, |
| 678 | user_agent=None, |
| 679 | revoke_uri=None) |
| 680 | |
Edward Lemur | b4a587d | 2019-10-09 23:56:38 +0000 | [diff] [blame] | 681 | |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 682 | def _run_oauth_dance(scopes): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 683 | """Perform full 3-legged OAuth2 flow with the browser. |
| 684 | |
| 685 | Returns: |
| 686 | oauth2client.Credentials. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 687 | """ |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 688 | subprocess2.check_call(['luci-auth', 'login', '-scopes', scopes]) |
| 689 | return _get_luci_auth_credentials(scopes) |