/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
1
# Copyright (C) 2005 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.1.18 by Robert Collins
Lalo Martins remotebranch patch
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.1.18 by Robert Collins
Lalo Martins remotebranch patch
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.1.18 by Robert Collins
Lalo Martins remotebranch patch
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
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
17
from cStringIO import StringIO
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
18
import errno
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
19
import md5
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
20
from SimpleHTTPServer import SimpleHTTPRequestHandler
2164.2.29 by Vincent Ladeuil
Test the http redirection at the request level even if it's not
21
import re
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
22
import sha
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
23
import socket
3111.1.7 by Vincent Ladeuil
Further refactoring.
24
import threading
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
25
import time
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
26
import urllib2
2213.1.1 by v.ladeuil+lp at free
Workaround SimpleHTTPRequestHandler.translate_path limitation in
27
import urlparse
1530.1.14 by Robert Collins
Remove duplicate web server from HTTPTestUtil.
28
2018.5.150 by Andrew Bennetts
Tidy imports in HTTPTestUtil.py
29
from bzrlib.smart import protocol
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
30
from bzrlib.tests import TestCaseWithTransport
3102.1.1 by Vincent Ladeuil
Rename bzrlib/test/HTTPTestUtils.py to bzrlib/tests/http_utils.py and fix
31
from bzrlib.tests.http_server import (
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
32
    HttpServer,
33
    TestingHTTPRequestHandler,
34
    )
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
35
from bzrlib.transport import (
36
    get_transport,
37
    )
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
38
39
40
class WallRequestHandler(TestingHTTPRequestHandler):
41
    """Whatever request comes in, close the connection"""
42
43
    def handle_one_request(self):
44
        """Handle a single HTTP request, by abruptly closing the connection"""
45
        self.close_connection = 1
46
47
48
class BadStatusRequestHandler(TestingHTTPRequestHandler):
49
    """Whatever request comes in, returns a bad status"""
50
51
    def parse_request(self):
52
        """Fakes handling a single HTTP request, returns a bad status"""
53
        ignored = TestingHTTPRequestHandler.parse_request(self)
54
        try:
55
            self.send_response(0, "Bad status")
56
            self.end_headers()
57
        except socket.error, e:
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
58
            # We don't want to pollute the test results with
59
            # spurious server errors while test succeed. In our
2188.1.1 by Aaron Bentley
Windows tests cleanup. (Vincent Ladeuil)
60
            # case, it may occur that the test has already read
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
61
            # the 'Bad Status' and closed the socket while we are
62
            # still trying to send some headers... So the test is
2188.1.1 by Aaron Bentley
Windows tests cleanup. (Vincent Ladeuil)
63
            # ok, but if we raise the exception, the output is
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
64
            # dirty. So we don't raise, but we close the
65
            # connection, just to be safe :)
66
            spurious = [errno.EPIPE,
67
                        errno.ECONNRESET,
68
                        errno.ECONNABORTED,
69
                        ]
70
            if (len(e.args) > 0) and (e.args[0] in spurious):
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
71
                self.close_connection = 1
72
                pass
73
            else:
74
                raise
75
        return False
76
77
78
class InvalidStatusRequestHandler(TestingHTTPRequestHandler):
79
    """Whatever request comes in, returns am invalid status"""
80
81
    def parse_request(self):
82
        """Fakes handling a single HTTP request, returns a bad status"""
83
        ignored = TestingHTTPRequestHandler.parse_request(self)
84
        self.wfile.write("Invalid status line\r\n")
85
        return False
86
87
88
class BadProtocolRequestHandler(TestingHTTPRequestHandler):
89
    """Whatever request comes in, returns a bad protocol version"""
90
91
    def parse_request(self):
92
        """Fakes handling a single HTTP request, returns a bad status"""
93
        ignored = TestingHTTPRequestHandler.parse_request(self)
94
        # Returns an invalid protocol version, but curl just
95
        # ignores it and those cannot be tested.
96
        self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
97
                                           404,
98
                                           'Look at my protocol version'))
99
        return False
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
100
101
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
102
class ForbiddenRequestHandler(TestingHTTPRequestHandler):
103
    """Whatever request comes in, returns a 403 code"""
104
105
    def parse_request(self):
106
        """Handle a single HTTP request, by replying we cannot handle it"""
107
        ignored = TestingHTTPRequestHandler.parse_request(self)
108
        self.send_error(403)
109
        return False
110
111
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
112
class HTTPServerWithSmarts(HttpServer):
113
    """HTTPServerWithSmarts extends the HttpServer with POST methods that will
114
    trigger a smart server to execute with a transport rooted at the rootdir of
115
    the HTTP server.
116
    """
117
118
    def __init__(self):
119
        HttpServer.__init__(self, SmartRequestHandler)
120
121
122
class SmartRequestHandler(TestingHTTPRequestHandler):
123
    """Extend TestingHTTPRequestHandler to support smart client POSTs."""
124
125
    def do_POST(self):
126
        """Hand the request off to a smart server instance."""
127
        self.send_response(200)
128
        self.send_header("Content-type", "application/octet-stream")
2164.2.28 by Vincent Ladeuil
TestingHTTPServer.test_case_server renamed from test_case to avoid confusions.
129
        transport = get_transport(self.server.test_case_server._home_dir)
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
130
        # TODO: We might like to support streaming responses.  1.0 allows no
131
        # Content-length in this case, so for integrity we should perform our
132
        # own chunking within the stream.
133
        # 1.1 allows chunked responses, and in this case we could chunk using
134
        # the HTTP chunking as this will allow HTTP persistence safely, even if
135
        # we have to stop early due to error, but we would also have to use the
136
        # HTTP trailer facility which may not be widely available.
137
        out_buffer = StringIO()
2018.5.150 by Andrew Bennetts
Tidy imports in HTTPTestUtil.py
138
        smart_protocol_request = protocol.SmartServerRequestProtocolOne(
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
139
                transport, out_buffer.write)
140
        # if this fails, we should return 400 bad request, but failure is
141
        # failure for now - RBC 20060919
142
        data_length = int(self.headers['Content-Length'])
143
        # Perhaps there should be a SmartServerHTTPMedium that takes care of
144
        # feeding the bytes in the http request to the smart_protocol_request,
145
        # but for now it's simpler to just feed the bytes directly.
146
        smart_protocol_request.accept_bytes(self.rfile.read(data_length))
147
        assert smart_protocol_request.next_read_size() == 0, (
148
            "not finished reading, but all data sent to protocol.")
149
        self.send_header("Content-Length", str(len(out_buffer.getvalue())))
150
        self.end_headers()
151
        self.wfile.write(out_buffer.getvalue())
152
153
2520.2.2 by Vincent Ladeuil
Fix #115209 by issuing a single range request on 400: Bad Request
154
class LimitedRangeRequestHandler(TestingHTTPRequestHandler):
155
    """Errors out when range specifiers exceed the limit"""
156
157
    def get_multiple_ranges(self, file, file_size, ranges):
158
        """Refuses the multiple ranges request"""
159
        tcs = self.server.test_case_server
160
        if tcs.range_limit is not None and len(ranges) > tcs.range_limit:
161
            file.close()
162
            # Emulate apache behavior
163
            self.send_error(400, "Bad Request")
164
            return
165
        return TestingHTTPRequestHandler.get_multiple_ranges(self, file,
166
                                                             file_size, ranges)
167
168
169
class LimitedRangeHTTPServer(HttpServer):
170
    """An HttpServer erroring out on requests with too much range specifiers"""
171
172
    def __init__(self, request_handler=LimitedRangeRequestHandler,
173
                 range_limit=None):
174
        HttpServer.__init__(self, request_handler)
175
        self.range_limit = range_limit
176
177
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
178
class SingleRangeRequestHandler(TestingHTTPRequestHandler):
179
    """Always reply to range request as if they were single.
180
181
    Don't be explicit about it, just to annoy the clients.
182
    """
183
184
    def get_multiple_ranges(self, file, file_size, ranges):
185
        """Answer as if it was a single range request and ignores the rest"""
186
        (start, end) = ranges[0]
187
        return self.get_single_range(file, file_size, start, end)
188
189
2481.3.1 by Vincent Ladeuil
Fix bug #112719 by using the right range header.
190
class SingleOnlyRangeRequestHandler(TestingHTTPRequestHandler):
191
    """Only reply to simple range requests, errors out on multiple"""
192
193
    def get_multiple_ranges(self, file, file_size, ranges):
194
        """Refuses the multiple ranges request"""
195
        if len(ranges) > 1:
196
            file.close()
197
            self.send_error(416, "Requested range not satisfiable")
198
            return
199
        (start, end) = ranges[0]
200
        return self.get_single_range(file, file_size, start, end)
201
202
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
203
class NoRangeRequestHandler(TestingHTTPRequestHandler):
204
    """Ignore range requests without notice"""
205
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
206
    def do_GET(self):
207
        # Update the statistics
208
        self.server.test_case_server.GET_request_nb += 1
209
        # Just bypass the range handling done by TestingHTTPRequestHandler
210
        return SimpleHTTPRequestHandler.do_GET(self)
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
211
212
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
213
class TestCaseWithWebserver(TestCaseWithTransport):
214
    """A support class that provides readonly urls that are http://.
215
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
216
    This is done by forcing the readonly server to be an http
217
    one. This will currently fail if the primary transport is not
218
    backed by regular disk files.
1185.1.18 by Robert Collins
Lalo Martins remotebranch patch
219
    """
220
    def setUp(self):
1530.1.14 by Robert Collins
Remove duplicate web server from HTTPTestUtil.
221
        super(TestCaseWithWebserver, self).setUp()
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
222
        self.transport_readonly_server = HttpServer
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
223
224
225
class TestCaseWithTwoWebservers(TestCaseWithWebserver):
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
226
    """A support class providing readonly urls on two servers that are http://.
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
227
2164.2.25 by Vincent Ladeuil
Fix typos noticed by Aaron.
228
    We set up two webservers to allows various tests involving
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
229
    proxies or redirections from one server to the other.
230
    """
231
    def setUp(self):
232
        super(TestCaseWithTwoWebservers, self).setUp()
233
        self.transport_secondary_server = HttpServer
234
        self.__secondary_server = None
235
236
    def create_transport_secondary_server(self):
237
        """Create a transport server from class defined at init.
238
239
        This is mostly a hook for daughter classes.
240
        """
241
        return self.transport_secondary_server()
242
243
    def get_secondary_server(self):
244
        """Get the server instance for the secondary transport."""
245
        if self.__secondary_server is None:
246
            self.__secondary_server = self.create_transport_secondary_server()
247
            self.__secondary_server.setUp()
248
            self.addCleanup(self.__secondary_server.tearDown)
249
        return self.__secondary_server
250
251
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
252
class ProxyServer(HttpServer):
253
    """A proxy test server for http transports."""
254
255
    proxy_requests = True
2213.1.1 by v.ladeuil+lp at free
Workaround SimpleHTTPRequestHandler.translate_path limitation in
256
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
257
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
258
class RedirectRequestHandler(TestingHTTPRequestHandler):
259
    """Redirect all request to the specified server"""
260
261
    def parse_request(self):
262
        """Redirect a single HTTP request to another host"""
263
        valid = TestingHTTPRequestHandler.parse_request(self)
264
        if valid:
2164.2.29 by Vincent Ladeuil
Test the http redirection at the request level even if it's not
265
            tcs = self.server.test_case_server
266
            code, target = tcs.is_redirected(self.path)
267
            if code is not None and target is not None:
268
                # Redirect as instructed
269
                self.send_response(code)
2164.2.16 by Vincent Ladeuil
Add tests.
270
                self.send_header('Location', target)
271
                self.end_headers()
272
                return False # The job is done
2164.2.29 by Vincent Ladeuil
Test the http redirection at the request level even if it's not
273
            else:
274
                # We leave the parent class serve the request
275
                pass
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
276
        return valid
277
278
279
class HTTPServerRedirecting(HttpServer):
280
    """An HttpServer redirecting to another server """
281
2164.2.16 by Vincent Ladeuil
Add tests.
282
    def __init__(self, request_handler=RedirectRequestHandler):
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
283
        HttpServer.__init__(self, request_handler)
2164.2.29 by Vincent Ladeuil
Test the http redirection at the request level even if it's not
284
        # redirections is a list of tuples (source, target, code)
285
        # - source is a regexp for the paths requested
286
        # - target is a replacement for re.sub describing where
287
        #   the request will be redirected
288
        # - code is the http error code associated to the
289
        #   redirection (301 permanent, 302 temporarry, etc
290
        self.redirections = []
291
292
    def redirect_to(self, host, port):
293
        """Redirect all requests to a specific host:port"""
294
        self.redirections = [('(.*)',
295
                              r'http://%s:%s\1' % (host, port) ,
296
                              301)]
297
298
    def is_redirected(self, path):
299
        """Is the path redirected by this server.
300
301
        :param path: the requested relative path
302
303
        :returns: a tuple (code, target) if a matching
304
             redirection is found, (None, None) otherwise.
305
        """
306
        code = None
307
        target = None
308
        for (rsource, rtarget, rcode) in self.redirections:
309
            target, match = re.subn(rsource, rtarget, path)
310
            if match:
311
                code = rcode
312
                break # The first match wins
313
            else:
314
                target = None
315
        return code, target
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
316
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
317
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
318
class TestCaseWithRedirectedWebserver(TestCaseWithTwoWebservers):
319
   """A support class providing redirections from one server to another.
320
2164.2.25 by Vincent Ladeuil
Fix typos noticed by Aaron.
321
   We set up two webservers to allows various tests involving
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
322
   redirections.
323
   The 'old' server is redirected to the 'new' server.
324
   """
325
326
   def create_transport_secondary_server(self):
327
       """Create the secondary server redirecting to the primary server"""
328
       new = self.get_readonly_server()
329
       redirecting = HTTPServerRedirecting()
330
       redirecting.redirect_to(new.host, new.port)
331
       return redirecting
332
333
   def setUp(self):
334
       super(TestCaseWithRedirectedWebserver, self).setUp()
335
       # The redirections will point to the new server
336
       self.new_server = self.get_readonly_server()
337
       # The requests to the old server will be redirected
338
       self.old_server = self.get_secondary_server()
339
340
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
341
class AuthRequestHandler(TestingHTTPRequestHandler):
342
    """Requires an authentication to process requests.
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
343
344
    This is intended to be used with a server that always and
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
345
    only use one authentication scheme (implemented by daughter
346
    classes).
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
347
    """
2363.4.8 by Vincent Ladeuil
Implement a basic auth HTTP server, rewrite tests accordingly.
348
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
349
    # The following attributes should be defined in the server
2420.1.10 by Vincent Ladeuil
Doc fixes.
350
    # - auth_header_sent: the header name sent to require auth
351
    # - auth_header_recv: the header received containing auth
352
    # - auth_error_code: the error code to indicate auth required
2420.1.2 by Vincent Ladeuil
Define tests for http proxy basic authentication. They fail.
353
2363.4.8 by Vincent Ladeuil
Implement a basic auth HTTP server, rewrite tests accordingly.
354
    def do_GET(self):
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
355
        if self.authorized():
356
            return TestingHTTPRequestHandler.do_GET(self)
357
        else:
358
            # Note that we must update test_case_server *before*
359
            # sending the error or the client may try to read it
360
            # before we have sent the whole error back.
361
            tcs = self.server.test_case_server
362
            tcs.auth_required_errors += 1
363
            self.send_response(tcs.auth_error_code)
364
            self.send_header_auth_reqed()
365
            self.end_headers()
366
            return
2363.4.8 by Vincent Ladeuil
Implement a basic auth HTTP server, rewrite tests accordingly.
367
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
368
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
369
class BasicAuthRequestHandler(AuthRequestHandler):
370
    """Implements the basic authentication of a request"""
371
372
    def authorized(self):
373
        tcs = self.server.test_case_server
374
        if tcs.auth_scheme != 'basic':
375
            return False
376
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
377
        auth_header = self.headers.get(tcs.auth_header_recv, None)
378
        if auth_header:
379
            scheme, raw_auth = auth_header.split(' ', 1)
380
            if scheme.lower() == tcs.auth_scheme:
381
                user, password = raw_auth.decode('base64').split(':')
382
                return tcs.authorized(user, password)
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
383
384
        return False
385
386
    def send_header_auth_reqed(self):
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
387
        tcs = self.server.test_case_server
388
        self.send_header(tcs.auth_header_sent,
389
                         'Basic realm="%s"' % tcs.auth_realm)
390
391
2420.1.19 by Vincent Ladeuil
Cosmetic changes.
392
# FIXME: We could send an Authentication-Info header too when
393
# the authentication is succesful
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
394
395
class DigestAuthRequestHandler(AuthRequestHandler):
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
396
    """Implements the digest authentication of a request.
397
398
    We need persistence for some attributes and that can't be
399
    achieved here since we get instantiated for each request. We
400
    rely on the DigestAuthServer to take care of them.
401
    """
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
402
403
    def authorized(self):
404
        tcs = self.server.test_case_server
405
        if tcs.auth_scheme != 'digest':
406
            return False
407
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
408
        auth_header = self.headers.get(tcs.auth_header_recv, None)
409
        if auth_header is None:
410
            return False
411
        scheme, auth = auth_header.split(None, 1)
412
        if scheme.lower() == tcs.auth_scheme:
413
            auth_dict = urllib2.parse_keqv_list(urllib2.parse_http_list(auth))
414
415
            return tcs.digest_authorized(auth_dict, self.command)
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
416
417
        return False
418
419
    def send_header_auth_reqed(self):
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
420
        tcs = self.server.test_case_server
421
        header = 'Digest realm="%s", ' % tcs.auth_realm
2545.2.1 by Vincent Ladeuil
Fix 121889 by working around urllib2 bug.
422
        header += 'nonce="%s", algorithm="%s", qop="auth"' % (tcs.auth_nonce,
423
                                                              'MD5')
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
424
        self.send_header(tcs.auth_header_sent,header)
425
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
426
427
class AuthServer(HttpServer):
428
    """Extends HttpServer with a dictionary of passwords.
429
430
    This is used as a base class for various schemes which should
431
    all use or redefined the associated AuthRequestHandler.
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
432
433
    Note that no users are defined by default, so add_user should
434
    be called before issuing the first request.
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
435
    """
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
436
437
    # The following attributes should be set dy daughter classes
438
    # and are used by AuthRequestHandler.
439
    auth_header_sent = None
440
    auth_header_recv = None
441
    auth_error_code = None
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
442
    auth_realm = "Thou should not pass"
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
443
444
    def __init__(self, request_handler, auth_scheme):
2363.4.8 by Vincent Ladeuil
Implement a basic auth HTTP server, rewrite tests accordingly.
445
        HttpServer.__init__(self, request_handler)
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
446
        self.auth_scheme = auth_scheme
2363.4.8 by Vincent Ladeuil
Implement a basic auth HTTP server, rewrite tests accordingly.
447
        self.password_of = {}
2420.1.4 by Vincent Ladeuil
Add test checking the number of roundtrips due to 401 or 407 errors.
448
        self.auth_required_errors = 0
2363.4.8 by Vincent Ladeuil
Implement a basic auth HTTP server, rewrite tests accordingly.
449
450
    def add_user(self, user, password):
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
451
        """Declare a user with an associated password.
452
453
        password can be empty, use an empty string ('') in that
454
        case, not None.
455
        """
2363.4.8 by Vincent Ladeuil
Implement a basic auth HTTP server, rewrite tests accordingly.
456
        self.password_of[user] = password
457
458
    def authorized(self, user, password):
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
459
        """Check that the given user provided the right password"""
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
460
        expected_password = self.password_of.get(user, None)
461
        return expected_password is not None and password == expected_password
462
463
2420.1.19 by Vincent Ladeuil
Cosmetic changes.
464
# FIXME: There is some code duplication with
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
465
# _urllib2_wrappers.py.DigestAuthHandler. If that duplication
2420.1.19 by Vincent Ladeuil
Cosmetic changes.
466
# grows, it may require a refactoring. Also, we don't implement
467
# SHA algorithm nor MD5-sess here, but that does not seem worth
468
# it.
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
469
class DigestAuthServer(AuthServer):
470
    """A digest authentication server"""
471
2420.1.16 by Vincent Ladeuil
Handle nonce changes. Fix a nasty bug breaking the auth parameters sharing.
472
    auth_nonce = 'now!'
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
473
474
    def __init__(self, request_handler, auth_scheme):
475
        AuthServer.__init__(self, request_handler, auth_scheme)
476
477
    def digest_authorized(self, auth, command):
2420.1.16 by Vincent Ladeuil
Handle nonce changes. Fix a nasty bug breaking the auth parameters sharing.
478
        nonce = auth['nonce']
479
        if nonce != self.auth_nonce:
480
            return False
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
481
        realm = auth['realm']
482
        if realm != self.auth_realm:
483
            return False
484
        user = auth['username']
485
        if not self.password_of.has_key(user):
486
            return False
487
        algorithm= auth['algorithm']
488
        if algorithm != 'MD5':
489
            return False
490
        qop = auth['qop']
491
        if qop != 'auth':
492
            return False
493
494
        password = self.password_of[user]
495
496
        # Recalculate the response_digest to compare with the one
497
        # sent by the client
498
        A1 = '%s:%s:%s' % (user, realm, password)
499
        A2 = '%s:%s' % (command, auth['uri'])
500
501
        H = lambda x: md5.new(x).hexdigest()
502
        KD = lambda secret, data: H("%s:%s" % (secret, data))
503
504
        nonce_count = int(auth['nc'], 16)
505
506
        ncvalue = '%08x' % nonce_count
507
508
        cnonce = auth['cnonce']
509
        noncebit = '%s:%s:%s:%s:%s' % (nonce, ncvalue, cnonce, qop, H(A2))
510
        response_digest = KD(H(A1), noncebit)
511
512
        return response_digest == auth['response']
513
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
514
class HTTPAuthServer(AuthServer):
515
    """An HTTP server requiring authentication"""
516
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
517
    def init_http_auth(self):
518
        self.auth_header_sent = 'WWW-Authenticate'
519
        self.auth_header_recv = 'Authorization'
520
        self.auth_error_code = 401
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
521
522
523
class ProxyAuthServer(AuthServer):
524
    """A proxy server requiring authentication"""
525
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
526
    def init_proxy_auth(self):
527
        self.proxy_requests = True
528
        self.auth_header_sent = 'Proxy-Authenticate'
529
        self.auth_header_recv = 'Proxy-Authorization'
530
        self.auth_error_code = 407
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
531
532
533
class HTTPBasicAuthServer(HTTPAuthServer):
534
    """An HTTP server requiring basic authentication"""
535
536
    def __init__(self):
537
        HTTPAuthServer.__init__(self, BasicAuthRequestHandler, 'basic')
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
538
        self.init_http_auth()
539
540
541
class HTTPDigestAuthServer(DigestAuthServer, HTTPAuthServer):
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
542
    """An HTTP server requiring digest authentication"""
543
544
    def __init__(self):
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
545
        DigestAuthServer.__init__(self, DigestAuthRequestHandler, 'digest')
546
        self.init_http_auth()
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
547
548
549
class ProxyBasicAuthServer(ProxyAuthServer):
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
550
    """A proxy server requiring basic authentication"""
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
551
552
    def __init__(self):
553
        ProxyAuthServer.__init__(self, BasicAuthRequestHandler, 'basic')
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
554
        self.init_proxy_auth()
555
556
557
class ProxyDigestAuthServer(DigestAuthServer, ProxyAuthServer):
558
    """A proxy server requiring basic authentication"""
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
559
560
    def __init__(self):
561
        ProxyAuthServer.__init__(self, DigestAuthRequestHandler, 'digest')
2420.1.11 by Vincent Ladeuil
Implement digest authentication. Test suite passes. Tested against apache-2.x.
562
        self.init_proxy_auth()
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
563
564
3111.1.7 by Vincent Ladeuil
Further refactoring.
565
class RecordingServer(object):
566
    """A fake HTTP server.
567
    
568
    It records the bytes sent to it, and replies with a 200.
569
    """
570
571
    def __init__(self, expect_body_tail=None):
572
        """Constructor.
573
574
        :type expect_body_tail: str
575
        :param expect_body_tail: a reply won't be sent until this string is
576
            received.
577
        """
578
        self._expect_body_tail = expect_body_tail
579
        self.host = None
580
        self.port = None
581
        self.received_bytes = ''
582
583
    def setUp(self):
584
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
585
        self._sock.bind(('127.0.0.1', 0))
586
        self.host, self.port = self._sock.getsockname()
587
        self._ready = threading.Event()
588
        self._thread = threading.Thread(target=self._accept_read_and_reply)
589
        self._thread.setDaemon(True)
590
        self._thread.start()
591
        self._ready.wait(5)
592
593
    def _accept_read_and_reply(self):
594
        self._sock.listen(1)
595
        self._ready.set()
596
        self._sock.settimeout(5)
597
        try:
598
            conn, address = self._sock.accept()
599
            # On win32, the accepted connection will be non-blocking to start
600
            # with because we're using settimeout.
601
            conn.setblocking(True)
602
            while not self.received_bytes.endswith(self._expect_body_tail):
603
                self.received_bytes += conn.recv(4096)
604
            conn.sendall('HTTP/1.1 200 OK\r\n')
605
        except socket.timeout:
606
            # Make sure the client isn't stuck waiting for us to e.g. accept.
607
            self._sock.close()
608
        except socket.error:
609
            # The client may have already closed the socket.
610
            pass
611
612
    def tearDown(self):
613
        try:
614
            self._sock.close()
615
        except socket.error:
616
            # We might have already closed it.  We don't care.
617
            pass
618
        self.host = None
619
        self.port = None
620
621