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