aboutsummaryrefslogtreecommitdiff
path: root/lava_tool/authtoken.py
blob: 245b263881431725db643f601b6102cbbe1e839c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# Copyright (C) 2011 Linaro Limited
#
# Author: Michael Hudson-Doyle <michael.hudson@linaro.org>
#
# This file is part of lava-tool.
#
# lava-tool is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation
#
# lava-tool is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with lava-tool.  If not, see <http://www.gnu.org/licenses/>.

import base64
import errno
import ConfigParser as configparser
import urllib
import urllib2
import os
import xmlrpclib

from lava_tool.interface import LavaCommandError


DEFAULT_KEYRING_FILE = "%s/.local/share/lava-tool/keyring.cfg" % (
    os.path.expanduser("~"))


class TokenDeleteError(Exception):
    """ Raise when token cannot be deleted. """


def normalize_xmlrpc_url(uri):
    if '://' not in uri:
        uri = 'http://' + uri
    if not uri.endswith('/'):
        uri += '/'
    if not uri.endswith('/RPC2/'):
        uri += 'RPC2/'
    return uri


class AuthBackend(object):

    def add_token(self, username, endpoint_url, token):
        raise NotImplementedError

    def get_token_for_endpoint(self, user, endpoint_url):
        raise NotImplementedError


class KeyringAuthBackend(AuthBackend):

    def __init__(self, config_file=None):
        if not config_file:
            config_file = DEFAULT_KEYRING_FILE
        self.config_file = config_file

        self.config = configparser.RawConfigParser()
        try:
            os.makedirs(os.path.dirname(self.config_file))
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise
        self.config.read(self.config_file)

    def add_token(self, username, endpoint_url, token):
        # update the keyring with the token
        if not self.config.has_section(endpoint_url):
            self.config.add_section(endpoint_url)
        self.config.set(endpoint_url, username, token)

        # save the config back to the file
        with open(self.config_file, 'w') as config_file:
            self.config.write(config_file)

    def get_token_for_endpoint(self, username, endpoint_url):
        # fetch the token
        try:
            token = self.config.get(endpoint_url, username)
        except (configparser.NoOptionError, configparser.NoSectionError):
            token = None
        return token

    def remove_token(self, username, endpoint_url):
        try:
            if not self.config.remove_option(endpoint_url, username):
                raise TokenDeleteError("Username not found")
            if not self.config.items(endpoint_url):
                self.config.remove_section(endpoint_url)
        except configparser.NoSectionError:
            raise TokenDeleteError("Endpoint URL not found")

        with open(self.config_file, 'w') as config_file:
            self.config.write(config_file)

    def get_all_tokens_uri(self, endpoint_url):
        items = []
        try:
            items = self.config.items(endpoint_url)
        except configparser.NoSectionError:
            pass

        return [item[0] for item in items]

    def get_all_tokens(self):
        items = {}

        for section in self.config.sections():
            if section not in items.keys():
                items[section] = [item[0] for item in
                                  self.config.items(section)]

        return items


class MemoryAuthBackend(AuthBackend):

    def __init__(self, user_endpoint_token_list):
        self._tokens = {}
        for user, endpoint, token in user_endpoint_token_list:
            self._tokens[(user, endpoint)] = token

    def add_token(self, username, endpoint_url, token):
        self._tokens[(username, endpoint_url)] = token

    def get_token_for_endpoint(self, username, endpoint_url):
        return self._tokens.get((username, endpoint_url))


class XMLRPCTransport(xmlrpclib.Transport):

    def __init__(self, scheme, auth_backend):
        xmlrpclib.Transport.__init__(self)
        self._scheme = scheme
        self.auth_backend = auth_backend
        self._opener = urllib2.build_opener()
        self.verbose = 0

    def request(self, host, handler, request_body, verbose=0):
        self.verbose = verbose
        request = self.build_http_request(host, handler, request_body)
        try:
            response = self._opener.open(request)
        except urllib2.HTTPError as e:
            raise xmlrpclib.ProtocolError(
                host + handler, e.code, e.msg, e.info())
        return self.parse_response(response)

    def build_http_request(self, host, handler, request_body):
        token = None
        user = None
        auth, host = urllib.splituser(host)
        if auth:
            user, token = urllib.splitpasswd(auth)
        url = self._scheme + "://" + host + handler
        if user is not None and token is None:
            token = self.auth_backend.get_token_for_endpoint(user, url)
            if token is None:
                raise LavaCommandError(
                    "Username provided but no token found.")
        request = urllib2.Request(url, request_body)
        request.add_header("Content-Type", "text/xml")
        if token:
            auth = base64.b64encode(urllib.unquote(user + ':' + token))
            request.add_header("Authorization", "Basic " + auth)

        return request


class AuthenticatingServerProxy(xmlrpclib.ServerProxy):

    def __init__(self, uri, transport=None, encoding=None, verbose=0,
                 allow_none=0, use_datetime=0, auth_backend=None):
        uri = normalize_xmlrpc_url(uri)
        if transport is None:
            scheme = urllib.splittype(uri)[0]
            transport = XMLRPCTransport(scheme, auth_backend=auth_backend)
        xmlrpclib.ServerProxy.__init__(
            self, uri, transport, encoding, verbose, allow_none, use_datetime)