/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/plugins/launchpad/lp_registration.py

  • Committer: John Arbash Meinel
  • Date: 2007-11-13 22:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 2992.
  • Revision ID: john@arbash-meinel.com-20071113220221-6kkzbczr91r0gmbt
Fix bug #162494, 'bzr register-branch' needs proper auth handling.
The recent fix to use ~/.bazaar/authentication.conf had some small bugs.
It was not passing a user to auth.get_password(), and it was accidentally
using a local variable with the same name as a global.
Add tests that gather_user_credentials() gets proper values.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
from getpass import getpass
 
19
import os
 
20
from urlparse import urlsplit, urlunsplit
 
21
import urllib
 
22
import xmlrpclib
 
23
 
 
24
from bzrlib import (
 
25
    config,
 
26
    errors,
 
27
    __version__ as _bzrlib_version,
 
28
    )
 
29
 
 
30
# for testing, do
 
31
'''
 
32
export BZR_LP_XMLRPC_URL=http://xmlrpc.staging.launchpad.net/bazaar/
 
33
'''
 
34
 
 
35
class LaunchpadService(object):
 
36
    """A service to talk to Launchpad via XMLRPC.
 
37
    
 
38
    See http://bazaar-vcs.org/Specs/LaunchpadRpc for the methods we can call.
 
39
    """
 
40
 
 
41
    # NB: this should always end in a slash to avoid xmlrpclib appending
 
42
    # '/RPC2'
 
43
    DEFAULT_SERVICE_URL = 'https://xmlrpc.launchpad.net/bazaar/'
 
44
 
 
45
    transport = None
 
46
    registrant_email = None
 
47
    registrant_password = None
 
48
 
 
49
 
 
50
    def __init__(self, transport=None):
 
51
        """Construct a new service talking to the launchpad rpc server"""
 
52
        if transport is None:
 
53
            uri_type = urllib.splittype(self.service_url)[0]
 
54
            if uri_type == 'https':
 
55
                transport = xmlrpclib.SafeTransport()
 
56
            else:
 
57
                transport = xmlrpclib.Transport()
 
58
            transport.user_agent = 'bzr/%s (xmlrpclib/%s)' \
 
59
                    % (_bzrlib_version, xmlrpclib.__version__)
 
60
        self.transport = transport
 
61
 
 
62
 
 
63
    @property
 
64
    def service_url(self):
 
65
        """Return the http or https url for the xmlrpc server.
 
66
 
 
67
        This does not include the username/password credentials.
 
68
        """
 
69
        key = 'BZR_LP_XMLRPC_URL'
 
70
        if key in os.environ:
 
71
            return os.environ[key]
 
72
        else:
 
73
            return self.DEFAULT_SERVICE_URL
 
74
 
 
75
    def get_proxy(self):
 
76
        """Return the proxy for XMLRPC requests."""
 
77
        # auth info must be in url
 
78
        # TODO: if there's no registrant email perhaps we should just connect
 
79
        # anonymously?
 
80
        scheme, hostinfo, path = urlsplit(self.service_url)[:3]
 
81
        assert '@' not in hostinfo
 
82
        assert self.registrant_email is not None
 
83
        assert self.registrant_password is not None
 
84
        # TODO: perhaps fully quote the password to make it very slightly
 
85
        # obscured
 
86
        # TODO: can we perhaps add extra Authorization headers directly to the 
 
87
        # request, rather than putting this into the url?  perhaps a bit more 
 
88
        # secure against accidentally revealing it.  std66 s3.2.1 discourages putting
 
89
        # the password in the url.
 
90
        hostinfo = '%s:%s@%s' % (urllib.quote(self.registrant_email),
 
91
                                 urllib.quote(self.registrant_password),
 
92
                                 hostinfo)
 
93
        url = urlunsplit((scheme, hostinfo, path, '', ''))
 
94
        return xmlrpclib.ServerProxy(url, transport=self.transport)
 
95
 
 
96
    def gather_user_credentials(self):
 
97
        """Get the password from the user."""
 
98
        the_config = config.GlobalConfig()
 
99
        self.registrant_email = the_config.user_email()
 
100
        if self.registrant_password is None:
 
101
            auth = config.AuthenticationConfig()
 
102
            scheme, hostinfo = urlsplit(self.service_url)[:2]
 
103
            prompt = 'launchpad.net password for %s: ' % \
 
104
                    self.registrant_email
 
105
            # We will reuse http[s] credentials if we can, prompt user
 
106
            # otherwise
 
107
            self.registrant_password = auth.get_password(scheme, hostinfo,
 
108
                                                         self.registrant_email,
 
109
                                                         prompt=prompt)
 
110
 
 
111
    def send_request(self, method_name, method_params):
 
112
        proxy = self.get_proxy()
 
113
        assert method_name
 
114
        method = getattr(proxy, method_name)
 
115
        try:
 
116
            result = method(*method_params)
 
117
        except xmlrpclib.ProtocolError, e:
 
118
            if e.errcode == 301:
 
119
                # TODO: This can give a ProtocolError representing a 301 error, whose
 
120
                # e.headers['location'] tells where to go and e.errcode==301; should
 
121
                # probably log something and retry on the new url.
 
122
                raise NotImplementedError("should resend request to %s, but this isn't implemented"
 
123
                        % e.headers.get('Location', 'NO-LOCATION-PRESENT'))
 
124
            else:
 
125
                # we don't want to print the original message because its
 
126
                # str representation includes the plaintext password.
 
127
                # TODO: print more headers to help in tracking down failures
 
128
                raise errors.BzrError("xmlrpc protocol error connecting to %s: %s %s"
 
129
                        % (self.service_url, e.errcode, e.errmsg))
 
130
        return result
 
131
 
 
132
 
 
133
class BaseRequest(object):
 
134
    """Base request for talking to a XMLRPC server."""
 
135
 
 
136
    # Set this to the XMLRPC method name.
 
137
    _methodname = None
 
138
 
 
139
    def _request_params(self):
 
140
        """Return the arguments to pass to the method"""
 
141
        raise NotImplementedError(self._request_params)
 
142
 
 
143
    def submit(self, service):
 
144
        """Submit request to Launchpad XMLRPC server.
 
145
 
 
146
        :param service: LaunchpadService indicating where to send
 
147
            the request and the authentication credentials.
 
148
        """
 
149
        return service.send_request(self._methodname, self._request_params())
 
150
 
 
151
 
 
152
class DryRunLaunchpadService(LaunchpadService):
 
153
    """Service that just absorbs requests without sending to server.
 
154
    
 
155
    The dummy service does not need authentication.
 
156
    """
 
157
 
 
158
    def send_request(self, method_name, method_params):
 
159
        pass
 
160
 
 
161
    def gather_user_credentials(self):
 
162
        pass
 
163
 
 
164
 
 
165
class BranchRegistrationRequest(BaseRequest):
 
166
    """Request to tell Launchpad about a bzr branch."""
 
167
 
 
168
    _methodname = 'register_branch'
 
169
 
 
170
    def __init__(self, branch_url,
 
171
                 branch_name='',
 
172
                 branch_title='',
 
173
                 branch_description='',
 
174
                 author_email='',
 
175
                 product_name='',
 
176
                 ):
 
177
        assert branch_url
 
178
        self.branch_url = branch_url
 
179
        if branch_name:
 
180
            self.branch_name = branch_name
 
181
        else:
 
182
            self.branch_name = self._find_default_branch_name(self.branch_url)
 
183
        self.branch_title = branch_title
 
184
        self.branch_description = branch_description
 
185
        self.author_email = author_email
 
186
        self.product_name = product_name
 
187
 
 
188
    def _request_params(self):
 
189
        """Return xmlrpc request parameters"""
 
190
        # This must match the parameter tuple expected by Launchpad for this
 
191
        # method
 
192
        return (self.branch_url,
 
193
                self.branch_name,
 
194
                self.branch_title,
 
195
                self.branch_description,
 
196
                self.author_email,
 
197
                self.product_name,
 
198
               )
 
199
 
 
200
    def _find_default_branch_name(self, branch_url):
 
201
        i = branch_url.rfind('/')
 
202
        return branch_url[i+1:]
 
203
 
 
204
 
 
205
class BranchBugLinkRequest(BaseRequest):
 
206
    """Request to link a bzr branch in Launchpad to a bug."""
 
207
 
 
208
    _methodname = 'link_branch_to_bug'
 
209
 
 
210
    def __init__(self, branch_url, bug_id):
 
211
        assert branch_url
 
212
        self.bug_id = bug_id
 
213
        self.branch_url = branch_url
 
214
 
 
215
    def _request_params(self):
 
216
        """Return xmlrpc request parameters"""
 
217
        # This must match the parameter tuple expected by Launchpad for this
 
218
        # method
 
219
        return (self.branch_url, self.bug_id, '')