blob: c6a78820f7d3b4b952e71df84b7a6f92fe4be219 [file] [log] [blame]
Vadim Shtayurac4c76b62014-01-13 15:05:41 -08001#!/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
8__version__ = '0.3'
9
10import optparse
11import sys
12
13from third_party import colorama
14from third_party.depot_tools import fix_encoding
15from third_party.depot_tools import subcommand
16
17from utils import net
18from utils import oauth
19from utils import tools
20
21
22def add_auth_options(parser):
23 """Adds command line options related to authentication."""
24 parser.auth_group = optparse.OptionGroup(parser, 'Authentication')
25 parser.auth_group.add_option(
Vadim Shtayura5d1efce2014-02-04 10:55:43 -080026 '--auth-method',
27 metavar='METHOD',
Vadim Shtayura33414bf2014-02-27 11:19:34 -080028 default=net.get_default_auth_config()[0],
Vadim Shtayura5d1efce2014-02-04 10:55:43 -080029 help='Authentication method to use: %s. [default: %%default]' %
Vadim Shtayura33414bf2014-02-27 11:19:34 -080030 ', '.join(name for name, _ in net.AUTH_METHODS))
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080031 parser.add_option_group(parser.auth_group)
32 oauth.add_oauth_options(parser)
33
34
Vadim Shtayura5d1efce2014-02-04 10:55:43 -080035def process_auth_options(parser, options):
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080036 """Configures process-wide authentication parameters based on |options|."""
Vadim Shtayura33414bf2014-02-27 11:19:34 -080037 # Validate that authentication method is known.
38 if options.auth_method not in dict(net.AUTH_METHODS):
Vadim Shtayura5d1efce2014-02-04 10:55:43 -080039 parser.error('Invalid --auth-method value: %s' % options.auth_method)
Vadim Shtayura33414bf2014-02-27 11:19:34 -080040
41 # Process the rest of the flags based on actual method used.
42 # Only oauth is configurable now.
43 config = None
44 if options.auth_method == 'oauth':
45 config = oauth.extract_oauth_config_from_options(options)
46
47 # Now configure 'net' globally to use this for every request.
48 net.configure_auth(options.auth_method, config)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080049
50
51class AuthServiceError(Exception):
52 """Unexpected response from authentication service."""
53
54
55class AuthService(object):
56 """Represents remote Authentication service."""
57
58 def __init__(self, url):
59 self._service = net.get_http_service(url)
60
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080061 def login(self, allow_user_interaction):
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080062 """Refreshes cached access token or creates a new one."""
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080063 return self._service.login(allow_user_interaction)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080064
65 def logout(self):
66 """Purges cached access token."""
67 return self._service.logout()
68
69 def get_current_identity(self):
70 """Returns identity associated with currently used credentials.
71
72 Identity is a string:
73 user:<email> - if using OAuth or cookie based authentication.
74 bot:<id> - if using HMAC based authentication.
75 anonymous:anonymous - if not authenticated.
76 """
77 identity = self._service.json_request('GET', '/auth/api/v1/accounts/self')
78 if not identity:
79 raise AuthServiceError('Failed to fetch identity')
80 return identity['identity']
81
82
83@subcommand.usage('[options]')
84def CMDlogin(parser, args):
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080085 """Runs interactive login flow and stores auth token/cookie on disk."""
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080086 (options, args) = parser.parse_args(args)
Vadim Shtayura5d1efce2014-02-04 10:55:43 -080087 process_auth_options(parser, options)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080088 service = AuthService(options.service)
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080089 if service.login(True):
Vadim Shtayurac4c76b62014-01-13 15:05:41 -080090 print 'Logged in as \'%s\'.' % service.get_current_identity()
91 return 0
92 else:
93 print 'Login failed or canceled.'
94 return 1
95
96
97@subcommand.usage('[options]')
98def CMDlogout(parser, args):
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080099 """Purges cached auth token/cookie."""
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800100 (options, args) = parser.parse_args(args)
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800101 process_auth_options(parser, options)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800102 service = AuthService(options.service)
103 service.logout()
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800104 return 0
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800105
106
107@subcommand.usage('[options]')
108def CMDcheck(parser, args):
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800109 """Shows identity associated with currently cached auth token/cookie."""
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800110 (options, args) = parser.parse_args(args)
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800111 process_auth_options(parser, options)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800112 service = AuthService(options.service)
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800113 service.login(False)
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800114 print service.get_current_identity()
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800115 return 0
Vadim Shtayurac4c76b62014-01-13 15:05:41 -0800116
117
118class OptionParserAuth(tools.OptionParserWithLogging):
119 def __init__(self, **kwargs):
120 tools.OptionParserWithLogging.__init__(self, prog='auth.py', **kwargs)
121 self.server_group = tools.optparse.OptionGroup(self, 'Server')
122 self.server_group.add_option(
123 '-S', '--service',
124 metavar='URL', default='',
125 help='Service to use')
126 self.add_option_group(self.server_group)
127 add_auth_options(self)
128
129 def parse_args(self, *args, **kwargs):
130 options, args = tools.OptionParserWithLogging.parse_args(
131 self, *args, **kwargs)
132 options.service = options.service.rstrip('/')
133 if not options.service:
134 self.error('--service is required.')
135 return options, args
136
137
138def main(args):
139 dispatcher = subcommand.CommandDispatcher(__name__)
140 try:
141 return dispatcher.execute(OptionParserAuth(version=__version__), args)
142 except Exception as e:
143 tools.report_error(e)
144 return 1
145
146
147if __name__ == '__main__':
148 fix_encoding.fix_encoding()
149 tools.disable_buffering()
150 colorama.init()
151 sys.exit(main(sys.argv[1:]))