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