blob: 4514fbfff870d560b16614fac4538a7dcf613ee6 [file] [log] [blame]
Vadim Shtayurac4c76b62014-01-13 15:05:41 -08001#!/usr/bin/env python
maruelea586f32016-04-05 11:11:33 -07002# Copyright 2013 The LUCI Authors. All rights reserved.
maruelf1f5e2a2016-05-25 17:10:39 -07003# Use of this source code is governed under the Apache License, Version 2.0
4# that can be found in the LICENSE file.
Vadim Shtayurac4c76b62014-01-13 15:05:41 -08005
6"""Client tool to perform various authentication related tasks."""
7
Vadim Shtayura36817012015-03-20 19:12:25 -07008__version__ = '0.4'
Vadim Shtayurac4c76b62014-01-13 15:05:41 -08009
Marc-Antoine Ruel79940ae2014-09-23 17:55:41 -040010import logging
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080011import optparse
12import sys
13
14from third_party import colorama
15from third_party.depot_tools import fix_encoding
16from third_party.depot_tools import subcommand
17
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -040018from utils import logging_utils
Marc-Antoine Ruelcfb60852014-07-02 15:22:00 -040019from utils import on_error
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080020from utils import net
21from utils import oauth
maruel8e4e40c2016-05-30 06:21:07 -070022from utils import subprocess42
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080023from utils import tools
24
25
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080026class AuthServiceError(Exception):
27 """Unexpected response from authentication service."""
28
29
30class AuthService(object):
31 """Represents remote Authentication service."""
32
33 def __init__(self, url):
34 self._service = net.get_http_service(url)
35
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080036 def login(self, allow_user_interaction):
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080037 """Refreshes cached access token or creates a new one."""
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080038 return self._service.login(allow_user_interaction)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080039
40 def logout(self):
41 """Purges cached access token."""
42 return self._service.logout()
43
44 def get_current_identity(self):
45 """Returns identity associated with currently used credentials.
46
47 Identity is a string:
48 user:<email> - if using OAuth or cookie based authentication.
49 bot:<id> - if using HMAC based authentication.
50 anonymous:anonymous - if not authenticated.
51 """
Marc-Antoine Ruel0a620612014-08-13 15:47:07 -040052 identity = self._service.json_request('/auth/api/v1/accounts/self')
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080053 if not identity:
54 raise AuthServiceError('Failed to fetch identity')
55 return identity['identity']
56
57
Vadim Shtayura6b555c12014-07-23 16:22:18 -070058def add_auth_options(parser):
59 """Adds command line options related to authentication."""
Vadim Shtayura6b555c12014-07-23 16:22:18 -070060 oauth.add_oauth_options(parser)
61
62
63def process_auth_options(parser, options):
64 """Configures process-wide authentication parameters based on |options|."""
Vadim Shtayura36817012015-03-20 19:12:25 -070065 try:
66 net.set_oauth_config(oauth.extract_oauth_config_from_options(options))
67 except ValueError as exc:
68 parser.error(str(exc))
Vadim Shtayura6b555c12014-07-23 16:22:18 -070069
70
Vadim Shtayura771653f2015-07-31 11:13:09 -070071def normalize_host_url(url):
72 """Makes sure URL starts with http:// or https://."""
73 url = url.lower().rstrip('/')
74 if url.startswith('https://'):
75 return url
76 if url.startswith('http://'):
77 allowed = ('http://localhost:', 'http://127.0.0.1:', 'http://::1:')
78 if not url.startswith(allowed):
79 raise ValueError(
80 'URL must start with https:// or be on localhost with port number')
81 return url
82 return 'https://' + url
83
84
Vadim Shtayura6b555c12014-07-23 16:22:18 -070085def ensure_logged_in(server_url):
86 """Checks that user is logged in, asking to do it if not.
87
Marc-Antoine Ruelf7d737d2014-12-10 15:36:29 -050088 Raises:
89 ValueError if the server_url is not acceptable.
Vadim Shtayura6b555c12014-07-23 16:22:18 -070090 """
Vadim Shtayura36817012015-03-20 19:12:25 -070091 # It's just a waste of time on a headless bot (it can't do interactive login).
92 if tools.is_headless() or net.get_oauth_config().disabled:
Marc-Antoine Ruel2f6581a2014-10-03 11:09:53 -040093 return None
Vadim Shtayura771653f2015-07-31 11:13:09 -070094 server_url = normalize_host_url(server_url)
Vadim Shtayura6b555c12014-07-23 16:22:18 -070095 service = AuthService(server_url)
Marc-Antoine Ruelf7d737d2014-12-10 15:36:29 -050096 try:
97 service.login(False)
98 except IOError:
99 raise ValueError('Failed to contact %s' % server_url)
100 try:
101 identity = service.get_current_identity()
102 except AuthServiceError:
103 raise ValueError('Failed to fetch identify from %s' % server_url)
Vadim Shtayura6b555c12014-07-23 16:22:18 -0700104 if identity == 'anonymous:anonymous':
Marc-Antoine Ruelf7d737d2014-12-10 15:36:29 -0500105 raise ValueError(
Vadim Shtayura6b555c12014-07-23 16:22:18 -0700106 'Please login to %s: \n'
107 ' python auth.py login --service=%s' % (server_url, server_url))
Vadim Shtayura6b555c12014-07-23 16:22:18 -0700108 email = identity.split(':')[1]
Marc-Antoine Ruel79940ae2014-09-23 17:55:41 -0400109 logging.info('Logged in to %s: %s', server_url, email)
Marc-Antoine Ruel2f6581a2014-10-03 11:09:53 -0400110 return email
Vadim Shtayura6b555c12014-07-23 16:22:18 -0700111
112
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800113@subcommand.usage('[options]')
114def CMDlogin(parser, args):
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800115 """Runs interactive login flow and stores auth token/cookie on disk."""
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800116 (options, args) = parser.parse_args(args)
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800117 process_auth_options(parser, options)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800118 service = AuthService(options.service)
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800119 if service.login(True):
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800120 print 'Logged in as \'%s\'.' % service.get_current_identity()
121 return 0
122 else:
123 print 'Login failed or canceled.'
124 return 1
125
126
127@subcommand.usage('[options]')
128def CMDlogout(parser, args):
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800129 """Purges cached auth token/cookie."""
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800130 (options, args) = parser.parse_args(args)
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800131 process_auth_options(parser, options)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800132 service = AuthService(options.service)
133 service.logout()
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800134 return 0
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800135
136
137@subcommand.usage('[options]')
138def CMDcheck(parser, args):
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800139 """Shows identity associated with currently cached auth token/cookie."""
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800140 (options, args) = parser.parse_args(args)
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800141 process_auth_options(parser, options)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800142 service = AuthService(options.service)
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800143 service.login(False)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800144 print service.get_current_identity()
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800145 return 0
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800146
147
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -0400148class OptionParserAuth(logging_utils.OptionParserWithLogging):
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800149 def __init__(self, **kwargs):
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -0400150 logging_utils.OptionParserWithLogging.__init__(
151 self, prog='auth.py', **kwargs)
Vadim Shtayura771653f2015-07-31 11:13:09 -0700152 self.server_group = optparse.OptionGroup(self, 'Server')
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800153 self.server_group.add_option(
154 '-S', '--service',
155 metavar='URL', default='',
156 help='Service to use')
157 self.add_option_group(self.server_group)
158 add_auth_options(self)
159
160 def parse_args(self, *args, **kwargs):
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -0400161 options, args = logging_utils.OptionParserWithLogging.parse_args(
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800162 self, *args, **kwargs)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800163 if not options.service:
164 self.error('--service is required.')
Vadim Shtayura771653f2015-07-31 11:13:09 -0700165 try:
166 options.service = normalize_host_url(options.service)
167 except ValueError as exc:
168 self.error(str(exc))
Marc-Antoine Ruelcfb60852014-07-02 15:22:00 -0400169 on_error.report_on_exception_exit(options.service)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800170 return options, args
171
172
173def main(args):
174 dispatcher = subcommand.CommandDispatcher(__name__)
Marc-Antoine Ruelcfb60852014-07-02 15:22:00 -0400175 return dispatcher.execute(OptionParserAuth(version=__version__), args)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800176
177
178if __name__ == '__main__':
maruel8e4e40c2016-05-30 06:21:07 -0700179 subprocess42.inhibit_os_error_reporting()
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800180 fix_encoding.fix_encoding()
181 tools.disable_buffering()
182 colorama.init()
183 sys.exit(main(sys.argv[1:]))