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 | |
| 25 | |
| 26 | # depot_tools/. |
| 27 | DEPOT_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 28 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 29 | # This is what most GAE apps require for authentication. |
| 30 | OAUTH_SCOPE_EMAIL = 'https://www.googleapis.com/auth/userinfo.email' |
| 31 | # Gerrit and Git on *.googlesource.com require this scope. |
| 32 | OAUTH_SCOPE_GERRIT = 'https://www.googleapis.com/auth/gerritcodereview' |
| 33 | # Deprecated. Use OAUTH_SCOPE_EMAIL instead. |
| 34 | OAUTH_SCOPES = OAUTH_SCOPE_EMAIL |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 35 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 36 | |
| 37 | # Authentication configuration extracted from command line options. |
| 38 | # See doc string for 'make_auth_config' for meaning of fields. |
| 39 | AuthConfig = collections.namedtuple('AuthConfig', [ |
| 40 | 'use_oauth2', # deprecated, will be always True |
| 41 | 'save_cookies', # deprecated, will be removed |
| 42 | 'use_local_webserver', |
| 43 | 'webserver_port', |
| 44 | ]) |
| 45 | |
| 46 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 47 | # 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] | 48 | class AccessToken(collections.namedtuple('AccessToken', [ |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 49 | 'token', |
| 50 | 'expires_at', |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 51 | ])): |
| 52 | |
| 53 | def needs_refresh(self, now=None): |
| 54 | """True if this AccessToken should be refreshed.""" |
| 55 | if self.expires_at is not None: |
| 56 | now = now or datetime.datetime.utcnow() |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 57 | # Allow 30s of clock skew between client and backend. |
| 58 | now += datetime.timedelta(seconds=30) |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 59 | return now >= self.expires_at |
| 60 | # Token without expiration time never expires. |
| 61 | return False |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 62 | |
| 63 | |
| 64 | class AuthenticationError(Exception): |
| 65 | """Raised on errors related to authentication.""" |
| 66 | |
| 67 | |
| 68 | class LoginRequiredError(AuthenticationError): |
| 69 | """Interaction with the user is required to authenticate.""" |
| 70 | |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 71 | def __init__(self, scopes=OAUTH_SCOPE_EMAIL): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 72 | msg = ( |
| 73 | 'You are not logged in. Please login first by running:\n' |
Edward Lemur | ba5bc99 | 2019-09-23 22:59:17 +0000 | [diff] [blame] | 74 | ' luci-auth login -scopes %s' % scopes) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 75 | super(LoginRequiredError, self).__init__(msg) |
| 76 | |
| 77 | |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 78 | class LuciContextAuthError(Exception): |
| 79 | """Raised on errors related to unsuccessful attempts to load LUCI_CONTEXT""" |
| 80 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 81 | def __init__(self, msg, exc=None): |
| 82 | if exc is None: |
| 83 | logging.error(msg) |
| 84 | else: |
| 85 | logging.exception(msg) |
| 86 | msg = '%s: %s' % (msg, exc) |
| 87 | super(LuciContextAuthError, self).__init__(msg) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 88 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 89 | |
| 90 | def has_luci_context_local_auth(): |
| 91 | """Returns whether LUCI_CONTEXT should be used for ambient authentication. |
| 92 | """ |
| 93 | try: |
Andrii Shyshkalov | b3c4441 | 2018-04-19 14:27:19 -0700 | [diff] [blame] | 94 | params = _get_luci_context_local_auth_params() |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 95 | except LuciContextAuthError: |
| 96 | return False |
| 97 | if params is None: |
| 98 | return False |
| 99 | return bool(params.default_account_id) |
| 100 | |
| 101 | |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 102 | # TODO(crbug.com/1001756): Remove. luci-auth uses local auth if available, |
| 103 | # making this unnecessary. |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 104 | def get_luci_context_access_token(scopes=OAUTH_SCOPE_EMAIL): |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 105 | """Returns a valid AccessToken from the local LUCI context auth server. |
| 106 | |
| 107 | Adapted from |
| 108 | https://chromium.googlesource.com/infra/luci/luci-py/+/master/client/libs/luci_context/luci_context.py |
| 109 | See the link above for more details. |
| 110 | |
| 111 | Returns: |
| 112 | AccessToken if LUCI_CONTEXT is present and attempt to load it is successful. |
| 113 | None if LUCI_CONTEXT is absent. |
| 114 | |
| 115 | Raises: |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 116 | LuciContextAuthError if LUCI_CONTEXT is present, but there was a failure |
| 117 | obtaining its access token. |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 118 | """ |
Andrii Shyshkalov | b3c4441 | 2018-04-19 14:27:19 -0700 | [diff] [blame] | 119 | params = _get_luci_context_local_auth_params() |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 120 | if params is None: |
| 121 | return None |
| 122 | return _get_luci_context_access_token( |
| 123 | params, datetime.datetime.utcnow(), scopes) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 124 | |
| 125 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 126 | _LuciContextLocalAuthParams = collections.namedtuple( |
| 127 | '_LuciContextLocalAuthParams', [ |
| 128 | 'default_account_id', |
| 129 | 'secret', |
| 130 | 'rpc_port', |
| 131 | ]) |
| 132 | |
| 133 | |
Andrii Shyshkalov | b3c4441 | 2018-04-19 14:27:19 -0700 | [diff] [blame] | 134 | def _cache_thread_safe(f): |
| 135 | """Decorator caching result of nullary function in thread-safe way.""" |
| 136 | lock = threading.Lock() |
| 137 | cache = [] |
| 138 | |
| 139 | @functools.wraps(f) |
| 140 | def caching_wrapper(): |
| 141 | if not cache: |
| 142 | with lock: |
| 143 | if not cache: |
| 144 | cache.append(f()) |
| 145 | return cache[0] |
| 146 | |
| 147 | # Allow easy way to clear cache, particularly useful in tests. |
| 148 | caching_wrapper.clear_cache = lambda: cache.pop() if cache else None |
| 149 | return caching_wrapper |
| 150 | |
| 151 | |
| 152 | @_cache_thread_safe |
| 153 | def _get_luci_context_local_auth_params(): |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 154 | """Returns local auth parameters if local auth is configured else None. |
| 155 | |
| 156 | Raises LuciContextAuthError on unexpected failures. |
| 157 | """ |
Andrii Shyshkalov | b3c4441 | 2018-04-19 14:27:19 -0700 | [diff] [blame] | 158 | ctx_path = os.environ.get('LUCI_CONTEXT') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 159 | if not ctx_path: |
| 160 | return None |
| 161 | ctx_path = ctx_path.decode(sys.getfilesystemencoding()) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 162 | try: |
| 163 | loaded = _load_luci_context(ctx_path) |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 164 | except (OSError, IOError, ValueError) as e: |
| 165 | raise LuciContextAuthError('Failed to open, read or decode LUCI_CONTEXT', e) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 166 | try: |
| 167 | local_auth = loaded.get('local_auth') |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 168 | except AttributeError as e: |
| 169 | raise LuciContextAuthError('LUCI_CONTEXT not in proper format', e) |
| 170 | if local_auth is None: |
| 171 | logging.debug('LUCI_CONTEXT configured w/o local auth') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 172 | return None |
| 173 | try: |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 174 | return _LuciContextLocalAuthParams( |
| 175 | default_account_id=local_auth.get('default_account_id'), |
| 176 | secret=local_auth.get('secret'), |
| 177 | rpc_port=int(local_auth.get('rpc_port'))) |
| 178 | except (AttributeError, ValueError) as e: |
| 179 | raise LuciContextAuthError('local_auth config malformed', e) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 180 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 181 | |
| 182 | def _load_luci_context(ctx_path): |
| 183 | # Kept separate for test mocking. |
| 184 | with open(ctx_path) as f: |
| 185 | return json.load(f) |
| 186 | |
| 187 | |
| 188 | def _get_luci_context_access_token(params, now, scopes=OAUTH_SCOPE_EMAIL): |
| 189 | # No account, local_auth shouldn't be used. |
| 190 | if not params.default_account_id: |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 191 | return None |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 192 | if not params.secret: |
| 193 | raise LuciContextAuthError('local_auth: no secret') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 194 | |
| 195 | logging.debug('local_auth: requesting an access token for account "%s"', |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 196 | params.default_account_id) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 197 | http = httplib2.Http() |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 198 | host = '127.0.0.1:%d' % params.rpc_port |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 199 | resp, content = http.request( |
| 200 | uri='http://%s/rpc/LuciLocalAuthService.GetOAuthToken' % host, |
| 201 | method='POST', |
| 202 | body=json.dumps({ |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 203 | 'account_id': params.default_account_id, |
| 204 | 'scopes': scopes.split(' '), |
| 205 | 'secret': params.secret, |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 206 | }), |
| 207 | headers={'Content-Type': 'application/json'}) |
| 208 | if resp.status != 200: |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 209 | raise LuciContextAuthError( |
| 210 | 'local_auth: Failed to grab access token from ' |
| 211 | 'LUCI context server with status %d: %r' % (resp.status, content)) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 212 | try: |
| 213 | token = json.loads(content) |
| 214 | error_code = token.get('error_code') |
| 215 | error_message = token.get('error_message') |
| 216 | access_token = token.get('access_token') |
| 217 | expiry = token.get('expiry') |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 218 | except (AttributeError, ValueError) as e: |
| 219 | raise LuciContextAuthError('Unexpected access token response format', e) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 220 | if error_code: |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 221 | raise LuciContextAuthError( |
| 222 | 'Error %d in retrieving access token: %s', error_code, error_message) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 223 | if not access_token: |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 224 | raise LuciContextAuthError( |
| 225 | 'No access token returned from LUCI context server') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 226 | expiry_dt = None |
| 227 | if expiry: |
| 228 | try: |
| 229 | expiry_dt = datetime.datetime.utcfromtimestamp(expiry) |
Mun Yong Jang | 1728f5f | 2017-11-27 13:29:08 -0800 | [diff] [blame] | 230 | logging.debug( |
| 231 | 'local_auth: got an access token for ' |
| 232 | 'account "%s" that expires in %d sec', |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 233 | params.default_account_id, (expiry_dt - now).total_seconds()) |
| 234 | except (TypeError, ValueError) as e: |
| 235 | raise LuciContextAuthError('Invalid expiry in returned token', e) |
Mun Yong Jang | 1728f5f | 2017-11-27 13:29:08 -0800 | [diff] [blame] | 236 | else: |
| 237 | logging.debug( |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 238 | 'local auth: got an access token for account "%s" that does not expire', |
| 239 | params.default_account_id) |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 240 | access_token = AccessToken(access_token, expiry_dt) |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 241 | if access_token.needs_refresh(now=now): |
| 242 | raise LuciContextAuthError('Received access token is already expired') |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 243 | return access_token |
| 244 | |
| 245 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 246 | def make_auth_config( |
| 247 | use_oauth2=None, |
| 248 | save_cookies=None, |
| 249 | use_local_webserver=None, |
Edward Lemur | a056817 | 2019-10-16 15:37:58 +0000 | [diff] [blame] | 250 | webserver_port=None): |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 251 | """Returns new instance of AuthConfig. |
| 252 | |
| 253 | If some config option is None, it will be set to a reasonable default value. |
| 254 | This function also acts as an authoritative place for default values of |
| 255 | corresponding command line options. |
| 256 | """ |
| 257 | default = lambda val, d: val if val is not None else d |
| 258 | return AuthConfig( |
vadimsh@chromium.org | 19f3fe6 | 2015-04-20 17:03:10 +0000 | [diff] [blame] | 259 | default(use_oauth2, True), |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 260 | default(save_cookies, True), |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 261 | default(use_local_webserver, not _is_headless()), |
Edward Lemur | a056817 | 2019-10-16 15:37:58 +0000 | [diff] [blame] | 262 | default(webserver_port, 8090)) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 263 | |
| 264 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 265 | def add_auth_options(parser, default_config=None): |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 266 | """Appends OAuth related options to OptionParser.""" |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 267 | default_config = default_config or make_auth_config() |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 268 | parser.auth_group = optparse.OptionGroup(parser, 'Auth options') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 269 | parser.add_option_group(parser.auth_group) |
| 270 | |
| 271 | # OAuth2 vs password switch. |
| 272 | 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] | 273 | parser.auth_group.add_option( |
| 274 | '--oauth2', |
| 275 | action='store_true', |
| 276 | dest='use_oauth2', |
| 277 | default=default_config.use_oauth2, |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 278 | 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] | 279 | parser.auth_group.add_option( |
| 280 | '--no-oauth2', |
| 281 | action='store_false', |
| 282 | dest='use_oauth2', |
| 283 | default=default_config.use_oauth2, |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 284 | help='Use password instead of OAuth 2.0. [default: %s]' % auth_default) |
| 285 | |
| 286 | # Password related options, deprecated. |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 287 | parser.auth_group.add_option( |
| 288 | '--no-cookies', |
| 289 | action='store_false', |
| 290 | dest='save_cookies', |
| 291 | default=default_config.save_cookies, |
| 292 | help='Do not save authentication cookies to local disk.') |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 293 | |
| 294 | # OAuth2 related options. |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 295 | # TODO(crbug.com/1001756): Remove. No longer supported. |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 296 | parser.auth_group.add_option( |
| 297 | '--auth-no-local-webserver', |
| 298 | action='store_false', |
| 299 | dest='use_local_webserver', |
| 300 | default=default_config.use_local_webserver, |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 301 | help='DEPRECATED. Do not use') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 302 | parser.auth_group.add_option( |
| 303 | '--auth-host-port', |
| 304 | type=int, |
| 305 | default=default_config.webserver_port, |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 306 | help='DEPRECATED. Do not use') |
vadimsh@chromium.org | 24daf9e | 2015-04-17 02:42:44 +0000 | [diff] [blame] | 307 | parser.auth_group.add_option( |
| 308 | '--auth-refresh-token-json', |
Edward Lemur | a056817 | 2019-10-16 15:37:58 +0000 | [diff] [blame] | 309 | help='DEPRECATED. Do not use') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 310 | |
| 311 | |
| 312 | def extract_auth_config_from_options(options): |
| 313 | """Given OptionParser parsed options, extracts AuthConfig from it. |
| 314 | |
| 315 | OptionParser should be populated with auth options by 'add_auth_options'. |
| 316 | """ |
| 317 | return make_auth_config( |
| 318 | use_oauth2=options.use_oauth2, |
| 319 | save_cookies=False if options.use_oauth2 else options.save_cookies, |
| 320 | use_local_webserver=options.use_local_webserver, |
Edward Lemur | a056817 | 2019-10-16 15:37:58 +0000 | [diff] [blame] | 321 | webserver_port=options.auth_host_port) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 322 | |
| 323 | |
| 324 | def auth_config_to_command_options(auth_config): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 325 | """AuthConfig -> list of strings with command line options. |
| 326 | |
| 327 | Omits options that are set to default values. |
| 328 | """ |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 329 | if not auth_config: |
| 330 | return [] |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 331 | defaults = make_auth_config() |
| 332 | opts = [] |
| 333 | if auth_config.use_oauth2 != defaults.use_oauth2: |
| 334 | opts.append('--oauth2' if auth_config.use_oauth2 else '--no-oauth2') |
| 335 | if auth_config.save_cookies != auth_config.save_cookies: |
| 336 | if not auth_config.save_cookies: |
| 337 | opts.append('--no-cookies') |
| 338 | if auth_config.use_local_webserver != defaults.use_local_webserver: |
| 339 | if not auth_config.use_local_webserver: |
| 340 | opts.append('--auth-no-local-webserver') |
| 341 | if auth_config.webserver_port != defaults.webserver_port: |
| 342 | opts.extend(['--auth-host-port', str(auth_config.webserver_port)]) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 343 | return opts |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 344 | |
| 345 | |
Edward Lemur | b4a587d | 2019-10-09 23:56:38 +0000 | [diff] [blame] | 346 | def get_authenticator(config, scopes=OAUTH_SCOPE_EMAIL): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 347 | """Returns Authenticator instance to access given host. |
| 348 | |
| 349 | Args: |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 350 | config: AuthConfig instance. |
Andrii Shyshkalov | 741afe8 | 2018-04-19 14:32:18 -0700 | [diff] [blame] | 351 | scopes: space separated oauth scopes. Defaults to OAUTH_SCOPE_EMAIL. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 352 | |
| 353 | Returns: |
| 354 | Authenticator object. |
| 355 | """ |
Edward Lemur | b4a587d | 2019-10-09 23:56:38 +0000 | [diff] [blame] | 356 | return Authenticator(config, scopes) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 357 | |
| 358 | |
| 359 | class Authenticator(object): |
| 360 | """Object that knows how to refresh access tokens when needed. |
| 361 | |
| 362 | Args: |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 363 | config: AuthConfig object that holds authentication configuration. |
| 364 | """ |
| 365 | |
Edward Lemur | b4a587d | 2019-10-09 23:56:38 +0000 | [diff] [blame] | 366 | def __init__(self, config, scopes): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 367 | assert isinstance(config, AuthConfig) |
| 368 | assert config.use_oauth2 |
| 369 | self._access_token = None |
| 370 | self._config = config |
| 371 | self._lock = threading.Lock() |
seanmccullough@chromium.org | 3e4a581 | 2015-06-11 17:48:47 +0000 | [diff] [blame] | 372 | self._scopes = scopes |
vadimsh@chromium.org | cfbeecb | 2015-04-21 00:12:36 +0000 | [diff] [blame] | 373 | logging.debug('Using auth config %r', config) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 374 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 375 | def has_cached_credentials(self): |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 376 | """Returns True if credentials can be obtained. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 377 | |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 378 | If returns False, get_access_token() later will probably ask for interactive |
| 379 | login by raising LoginRequiredError, unless local auth in configured. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 380 | |
| 381 | If returns True, most probably get_access_token() won't ask for interactive |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 382 | login, unless an external token is provided that has been revoked. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 383 | """ |
| 384 | with self._lock: |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 385 | return bool(self._get_luci_auth_token()) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 386 | |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 387 | def get_access_token(self, force_refresh=False, allow_user_interaction=False, |
| 388 | use_local_auth=True): |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 389 | """Returns AccessToken, refreshing it if necessary. |
| 390 | |
| 391 | Args: |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 392 | TODO(crbug.com/1001756): Remove. luci-auth doesn't support |
| 393 | force-refreshing tokens. |
| 394 | force_refresh: Ignored, |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 395 | 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] | 396 | use_local_auth: default to local auth if needed. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 397 | |
| 398 | Raises: |
| 399 | AuthenticationError on error or if authentication flow was interrupted. |
| 400 | LoginRequiredError if user interaction is required, but |
| 401 | allow_user_interaction is False. |
| 402 | """ |
| 403 | with self._lock: |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 404 | if self._access_token and not self._access_token.needs_refresh(): |
| 405 | return self._access_token |
| 406 | |
| 407 | # Token expired or missing. Maybe some other process already updated it, |
| 408 | # reload from the cache. |
| 409 | self._access_token = self._get_luci_auth_token() |
| 410 | if self._access_token and not self._access_token.needs_refresh(): |
| 411 | return self._access_token |
| 412 | |
| 413 | # Nope, still expired, need to run the refresh flow. |
| 414 | if not self._external_token and allow_user_interaction: |
| 415 | logging.debug('Launching luci-auth login') |
| 416 | self._access_token = self._run_oauth_dance() |
| 417 | if self._access_token and not self._access_token.needs_refresh(): |
| 418 | return self._access_token |
| 419 | |
| 420 | # TODO(crbug.com/1001756): Remove. luci-auth uses local auth if it exists. |
| 421 | # Refresh flow failed. Try local auth. |
| 422 | if use_local_auth: |
Mun Yong Jang | acc8e3e | 2017-11-22 10:49:56 -0800 | [diff] [blame] | 423 | try: |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 424 | self._access_token = get_luci_context_access_token() |
| 425 | except LuciContextAuthError: |
| 426 | logging.exception('Failed to use local auth') |
| 427 | if self._access_token and not self._access_token.needs_refresh(): |
| 428 | return self._access_token |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 429 | |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 430 | # Give up. |
| 431 | logging.error('Failed to create access token') |
| 432 | raise LoginRequiredError(self._scopes) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 433 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 434 | def authorize(self, http): |
| 435 | """Monkey patches authentication logic of httplib2.Http instance. |
| 436 | |
| 437 | The modified http.request method will add authentication headers to each |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 438 | request. |
| 439 | |
| 440 | Args: |
| 441 | http: An instance of httplib2.Http. |
| 442 | |
| 443 | Returns: |
| 444 | A modified instance of http that was passed in. |
| 445 | """ |
| 446 | # Adapted from oauth2client.OAuth2Credentials.authorize. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 447 | request_orig = http.request |
| 448 | |
| 449 | @functools.wraps(request_orig) |
| 450 | def new_request( |
| 451 | uri, method='GET', body=None, headers=None, |
| 452 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 453 | connection_type=None): |
| 454 | headers = (headers or {}).copy() |
vadimsh@chromium.org | afbb019 | 2015-04-13 23:26:31 +0000 | [diff] [blame] | 455 | headers['Authorization'] = 'Bearer %s' % self.get_access_token().token |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 456 | return request_orig( |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 457 | uri, method, body, headers, redirections, connection_type) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 458 | |
| 459 | http.request = new_request |
| 460 | return http |
| 461 | |
| 462 | ## Private methods. |
| 463 | |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 464 | def _run_luci_auth_login(self): |
| 465 | """Run luci-auth login. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 466 | |
| 467 | Returns: |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 468 | AccessToken with credentials. |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 469 | """ |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 470 | logging.debug('Running luci-auth login') |
| 471 | subprocess2.check_call(['luci-auth', 'login', '-scopes', self._scopes]) |
| 472 | return self._get_luci_auth_token() |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 473 | |
Edward Lemur | 55e5853 | 2019-10-17 00:00:01 +0000 | [diff] [blame^] | 474 | def _get_luci_auth_token(self): |
| 475 | logging.debug('Running luci-auth token') |
| 476 | try: |
| 477 | out, err = subprocess2.check_call_out( |
| 478 | ['luci-auth', 'token', '-scopes', self._scopes, '-json-output', '-'], |
| 479 | stdout=subprocess2.PIPE, stderr=subprocess2.PIPE) |
| 480 | logging.debug('luci-auth token stderr:\n%s', err) |
| 481 | token_info = json.loads(out) |
| 482 | return AccessToken( |
| 483 | token_info['token'], |
| 484 | datetime.datetime.utcfromtimestamp(token_info['expiry'])) |
| 485 | except subprocess2.CalledProcessError: |
| 486 | return None |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 487 | |
| 488 | |
| 489 | ## Private functions. |
| 490 | |
| 491 | |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 492 | def _is_headless(): |
| 493 | """True if machine doesn't seem to have a display.""" |
| 494 | return sys.platform == 'linux2' and not os.environ.get('DISPLAY') |