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