Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 1 | #!/usr/bin/env python |
maruel | ea586f3 | 2016-04-05 11:11:33 -0700 | [diff] [blame] | 2 | # Copyright 2013 The LUCI Authors. All rights reserved. |
maruel | f1f5e2a | 2016-05-25 17:10:39 -0700 | [diff] [blame] | 3 | # Use of this source code is governed under the Apache License, Version 2.0 |
| 4 | # that can be found in the LICENSE file. |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 5 | |
| 6 | """Client tool to perform various authentication related tasks.""" |
| 7 | |
Vadim Shtayura | 3681701 | 2015-03-20 19:12:25 -0700 | [diff] [blame] | 8 | __version__ = '0.4' |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 9 | |
Marc-Antoine Ruel | 79940ae | 2014-09-23 17:55:41 -0400 | [diff] [blame] | 10 | import logging |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 11 | import optparse |
| 12 | import sys |
| 13 | |
Marc-Antoine Ruel | 016c760 | 2019-04-02 18:31:13 +0000 | [diff] [blame] | 14 | from utils import tools |
| 15 | tools.force_local_third_party() |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 16 | |
Marc-Antoine Ruel | 016c760 | 2019-04-02 18:31:13 +0000 | [diff] [blame] | 17 | # third_party/ |
| 18 | import colorama |
| 19 | from depot_tools import fix_encoding |
| 20 | from depot_tools import subcommand |
| 21 | |
| 22 | # pylint: disable=ungrouped-imports |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 23 | from utils import logging_utils |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 24 | from utils import on_error |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 25 | from utils import net |
| 26 | from utils import oauth |
maruel | 8e4e40c | 2016-05-30 06:21:07 -0700 | [diff] [blame] | 27 | from utils import subprocess42 |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 28 | |
| 29 | |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 30 | class AuthServiceError(Exception): |
| 31 | """Unexpected response from authentication service.""" |
| 32 | |
| 33 | |
Junji Watanabe | ab2102a | 2022-01-12 01:44:04 +0000 | [diff] [blame] | 34 | class AuthService: |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 35 | """Represents remote Authentication service.""" |
| 36 | |
| 37 | def __init__(self, url): |
| 38 | self._service = net.get_http_service(url) |
| 39 | |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 40 | def login(self, allow_user_interaction): |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 41 | """Refreshes cached access token or creates a new one.""" |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 42 | return self._service.login(allow_user_interaction) |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 43 | |
| 44 | def logout(self): |
| 45 | """Purges cached access token.""" |
| 46 | return self._service.logout() |
| 47 | |
| 48 | def get_current_identity(self): |
| 49 | """Returns identity associated with currently used credentials. |
| 50 | |
| 51 | Identity is a string: |
| 52 | user:<email> - if using OAuth or cookie based authentication. |
| 53 | bot:<id> - if using HMAC based authentication. |
| 54 | anonymous:anonymous - if not authenticated. |
| 55 | """ |
Marc-Antoine Ruel | 0a62061 | 2014-08-13 15:47:07 -0400 | [diff] [blame] | 56 | identity = self._service.json_request('/auth/api/v1/accounts/self') |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 57 | if not identity: |
| 58 | raise AuthServiceError('Failed to fetch identity') |
| 59 | return identity['identity'] |
| 60 | |
| 61 | |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 62 | def add_auth_options(parser): |
| 63 | """Adds command line options related to authentication.""" |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 64 | oauth.add_oauth_options(parser) |
| 65 | |
| 66 | |
| 67 | def process_auth_options(parser, options): |
| 68 | """Configures process-wide authentication parameters based on |options|.""" |
Vadim Shtayura | 3681701 | 2015-03-20 19:12:25 -0700 | [diff] [blame] | 69 | try: |
| 70 | net.set_oauth_config(oauth.extract_oauth_config_from_options(options)) |
| 71 | except ValueError as exc: |
| 72 | parser.error(str(exc)) |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 73 | |
| 74 | |
Vadim Shtayura | 771653f | 2015-07-31 11:13:09 -0700 | [diff] [blame] | 75 | def normalize_host_url(url): |
| 76 | """Makes sure URL starts with http:// or https://.""" |
| 77 | url = url.lower().rstrip('/') |
| 78 | if url.startswith('https://'): |
| 79 | return url |
| 80 | if url.startswith('http://'): |
Marc-Antoine Ruel | cd0e027 | 2018-03-13 14:31:45 -0400 | [diff] [blame] | 81 | allowed = ('http://localhost:', 'http://127.0.0.1:', 'http://[::1]:') |
Vadim Shtayura | 771653f | 2015-07-31 11:13:09 -0700 | [diff] [blame] | 82 | if not url.startswith(allowed): |
| 83 | raise ValueError( |
| 84 | 'URL must start with https:// or be on localhost with port number') |
| 85 | return url |
| 86 | return 'https://' + url |
| 87 | |
| 88 | |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 89 | def ensure_logged_in(server_url): |
| 90 | """Checks that user is logged in, asking to do it if not. |
| 91 | |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 92 | Raises: |
| 93 | ValueError if the server_url is not acceptable. |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 94 | """ |
Vadim Shtayura | 3681701 | 2015-03-20 19:12:25 -0700 | [diff] [blame] | 95 | # It's just a waste of time on a headless bot (it can't do interactive login). |
| 96 | if tools.is_headless() or net.get_oauth_config().disabled: |
Marc-Antoine Ruel | 2f6581a | 2014-10-03 11:09:53 -0400 | [diff] [blame] | 97 | return None |
Vadim Shtayura | 771653f | 2015-07-31 11:13:09 -0700 | [diff] [blame] | 98 | server_url = normalize_host_url(server_url) |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 99 | service = AuthService(server_url) |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 100 | try: |
| 101 | service.login(False) |
| 102 | except IOError: |
| 103 | raise ValueError('Failed to contact %s' % server_url) |
| 104 | try: |
| 105 | identity = service.get_current_identity() |
| 106 | except AuthServiceError: |
| 107 | raise ValueError('Failed to fetch identify from %s' % server_url) |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 108 | if identity == 'anonymous:anonymous': |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 109 | raise ValueError( |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 110 | 'Please login to %s: \n' |
| 111 | ' python auth.py login --service=%s' % (server_url, server_url)) |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 112 | email = identity.split(':')[1] |
Marc-Antoine Ruel | 79940ae | 2014-09-23 17:55:41 -0400 | [diff] [blame] | 113 | logging.info('Logged in to %s: %s', server_url, email) |
Marc-Antoine Ruel | 2f6581a | 2014-10-03 11:09:53 -0400 | [diff] [blame] | 114 | return email |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 115 | |
| 116 | |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 117 | @subcommand.usage('[options]') |
| 118 | def CMDlogin(parser, args): |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 119 | """Runs interactive login flow and stores auth token/cookie on disk.""" |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 120 | (options, args) = parser.parse_args(args) |
Vadim Shtayura | 5d1efce | 2014-02-04 10:55:43 -0800 | [diff] [blame] | 121 | process_auth_options(parser, options) |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 122 | service = AuthService(options.service) |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 123 | if service.login(True): |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 124 | print('Logged in as \'%s\'.' % service.get_current_identity()) |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 125 | return 0 |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 126 | print('Login failed or canceled.') |
Marc-Antoine Ruel | 793bff3 | 2019-04-18 17:50:48 +0000 | [diff] [blame] | 127 | return 1 |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 128 | |
| 129 | |
| 130 | @subcommand.usage('[options]') |
| 131 | def CMDlogout(parser, args): |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 132 | """Purges cached auth token/cookie.""" |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 133 | (options, args) = parser.parse_args(args) |
Vadim Shtayura | 5d1efce | 2014-02-04 10:55:43 -0800 | [diff] [blame] | 134 | process_auth_options(parser, options) |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 135 | service = AuthService(options.service) |
| 136 | service.logout() |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 137 | return 0 |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 138 | |
| 139 | |
| 140 | @subcommand.usage('[options]') |
| 141 | def CMDcheck(parser, args): |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 142 | """Shows identity associated with currently cached auth token/cookie.""" |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 143 | (options, args) = parser.parse_args(args) |
Vadim Shtayura | 5d1efce | 2014-02-04 10:55:43 -0800 | [diff] [blame] | 144 | process_auth_options(parser, options) |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 145 | service = AuthService(options.service) |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 146 | service.login(False) |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 147 | print(service.get_current_identity()) |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 148 | return 0 |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 149 | |
| 150 | |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 151 | class OptionParserAuth(logging_utils.OptionParserWithLogging): |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 152 | |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 153 | def __init__(self, **kwargs): |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 154 | logging_utils.OptionParserWithLogging.__init__( |
| 155 | self, prog='auth.py', **kwargs) |
Vadim Shtayura | 771653f | 2015-07-31 11:13:09 -0700 | [diff] [blame] | 156 | self.server_group = optparse.OptionGroup(self, 'Server') |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 157 | self.server_group.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 158 | '-S', '--service', metavar='URL', default='', help='Service to use') |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 159 | self.add_option_group(self.server_group) |
| 160 | add_auth_options(self) |
| 161 | |
| 162 | def parse_args(self, *args, **kwargs): |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 163 | options, args = logging_utils.OptionParserWithLogging.parse_args( |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 164 | self, *args, **kwargs) |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 165 | if not options.service: |
| 166 | self.error('--service is required.') |
Vadim Shtayura | 771653f | 2015-07-31 11:13:09 -0700 | [diff] [blame] | 167 | try: |
| 168 | options.service = normalize_host_url(options.service) |
| 169 | except ValueError as exc: |
| 170 | self.error(str(exc)) |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 171 | return options, args |
| 172 | |
| 173 | |
| 174 | def main(args): |
| 175 | dispatcher = subcommand.CommandDispatcher(__name__) |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 176 | return dispatcher.execute(OptionParserAuth(version=__version__), args) |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 177 | |
| 178 | |
| 179 | if __name__ == '__main__': |
maruel | 8e4e40c | 2016-05-30 06:21:07 -0700 | [diff] [blame] | 180 | subprocess42.inhibit_os_error_reporting() |
Vadim Shtayura | c4c76b6 | 2014-01-13 15:05:41 -0800 | [diff] [blame] | 181 | fix_encoding.fix_encoding() |
| 182 | tools.disable_buffering() |
| 183 | colorama.init() |
| 184 | sys.exit(main(sys.argv[1:])) |