Debian Codegraph @

testing/web-platform/tests/tools/third_party/pywebsocket3/test/test_handshake_hybi.py

raw
1 #!/usr/bin/env python
2 #
3 # Copyright 2011, Google Inc.
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are
8 # met:
9 #
10 # * Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # * Redistributions in binary form must reproduce the above
13 # copyright notice, this list of conditions and the following disclaimer
14 # in the documentation and/or other materials provided with the
15 # distribution.
16 # * Neither the name of Google Inc. nor the names of its
17 # contributors may be used to endorse or promote products derived from
18 # this software without specific prior written permission.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 """Tests for handshake module."""
32
33 from __future__ import absolute_import
34
35 import unittest
36
37 import set_sys_path # Update sys.path to locate pywebsocket3 module.
38 from pywebsocket3 import common
39 from pywebsocket3.handshake.base import (
40 AbortedByUserException,
41 HandshakeException,
42 VersionException,
43 )
44 from pywebsocket3.handshake.hybi import Handshaker
45 from test import mock
46
47
48 class RequestDefinition(object):
49 """A class for holding data for constructing opening handshake strings for
50 testing the opening handshake processor.
51 """
52 def __init__(self, method, uri, headers):
53 self.method = method
54 self.uri = uri
55 self.headers = headers
56
57
58 def _create_good_request_def():
59 return RequestDefinition(
60 'GET', '/demo', {
61 'Host': 'server.example.com',
62 'Upgrade': 'websocket',
63 'Connection': 'Upgrade',
64 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',
65 'Sec-WebSocket-Version': '13',
66 'Origin': 'http://example.com'
67 })
68
69
70 def _create_request(request_def):
71 conn = mock.MockConn(b'')
72 return mock.MockRequest(method=request_def.method,
73 uri=request_def.uri,
74 headers_in=request_def.headers,
75 connection=conn)
76
77
78 def _create_handshaker(request):
79 handshaker = Handshaker(request, mock.MockDispatcher())
80 return handshaker
81
82
83 class SubprotocolChoosingDispatcher(object):
84 """A dispatcher for testing. This dispatcher sets the i-th subprotocol
85 of requested ones to ws_protocol where i is given on construction as index
86 argument. If index is negative, default_value will be set to ws_protocol.
87 """
88 def __init__(self, index, default_value=None):
89 self.index = index
90 self.default_value = default_value
91
92 def do_extra_handshake(self, conn_context):
93 if self.index >= 0:
94 conn_context.ws_protocol = conn_context.ws_requested_protocols[
95 self.index]
96 else:
97 conn_context.ws_protocol = self.default_value
98
99 def transfer_data(self, conn_context):
100 pass
101
102
103 class HandshakeAbortedException(Exception):
104 pass
105
106
107 class AbortingDispatcher(object):
108 """A dispatcher for testing. This dispatcher raises an exception in
109 do_extra_handshake to reject the request.
110 """
111 def do_extra_handshake(self, conn_context):
112 raise HandshakeAbortedException('An exception to reject the request')
113
114 def transfer_data(self, conn_context):
115 pass
116
117
118 class AbortedByUserDispatcher(object):
119 """A dispatcher for testing. This dispatcher raises an
120 AbortedByUserException in do_extra_handshake to reject the request.
121 """
122 def do_extra_handshake(self, conn_context):
123 raise AbortedByUserException('An AbortedByUserException to reject the '
124 'request')
125
126 def transfer_data(self, conn_context):
127 pass
128
129
130 _EXPECTED_RESPONSE = (
131 b'HTTP/1.1 101 Switching Protocols\r\n'
132 b'Upgrade: websocket\r\n'
133 b'Connection: Upgrade\r\n'
134 b'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n')
135
136
137 class HandshakerTest(unittest.TestCase):
138 """A unittest for draft-ietf-hybi-thewebsocketprotocol-06 and later
139 handshake processor.
140 """
141 def test_do_handshake(self):
142 request = _create_request(_create_good_request_def())
143 dispatcher = mock.MockDispatcher()
144 handshaker = Handshaker(request, dispatcher)
145 handshaker.do_handshake()
146
147 self.assertTrue(dispatcher.do_extra_handshake_called)
148
149 self.assertEqual(_EXPECTED_RESPONSE, request.connection.written_data())
150 self.assertEqual('/demo', request.ws_resource)
151 self.assertEqual('http://example.com', request.ws_origin)
152 self.assertEqual(None, request.ws_protocol)
153 self.assertEqual(None, request.ws_extensions)
154 self.assertEqual(common.VERSION_HYBI_LATEST, request.ws_version)
155
156 def test_do_handshake_with_extra_headers(self):
157 request_def = _create_good_request_def()
158 # Add headers not related to WebSocket opening handshake.
159 request_def.headers['FooKey'] = 'BarValue'
160 request_def.headers['EmptyKey'] = ''
161
162 request = _create_request(request_def)
163 handshaker = _create_handshaker(request)
164 handshaker.do_handshake()
165 self.assertEqual(_EXPECTED_RESPONSE, request.connection.written_data())
166
167 def test_do_handshake_with_capitalized_value(self):
168 request_def = _create_good_request_def()
169 request_def.headers['upgrade'] = 'WEBSOCKET'
170
171 request = _create_request(request_def)
172 handshaker = _create_handshaker(request)
173 handshaker.do_handshake()
174 self.assertEqual(_EXPECTED_RESPONSE, request.connection.written_data())
175
176 request_def = _create_good_request_def()
177 request_def.headers['Connection'] = 'UPGRADE'
178
179 request = _create_request(request_def)
180 handshaker = _create_handshaker(request)
181 handshaker.do_handshake()
182 self.assertEqual(_EXPECTED_RESPONSE, request.connection.written_data())
183
184 def test_do_handshake_with_multiple_connection_values(self):
185 request_def = _create_good_request_def()
186 request_def.headers['Connection'] = 'Upgrade, keep-alive, , '
187
188 request = _create_request(request_def)
189 handshaker = _create_handshaker(request)
190 handshaker.do_handshake()
191 self.assertEqual(_EXPECTED_RESPONSE, request.connection.written_data())
192
193 def test_aborting_handshake(self):
194 handshaker = Handshaker(_create_request(_create_good_request_def()),
195 AbortingDispatcher())
196 # do_extra_handshake raises an exception. Check that it's not caught by
197 # do_handshake.
198 self.assertRaises(HandshakeAbortedException, handshaker.do_handshake)
199
200 def test_do_handshake_with_protocol(self):
201 request_def = _create_good_request_def()
202 request_def.headers['Sec-WebSocket-Protocol'] = 'chat, superchat'
203
204 request = _create_request(request_def)
205 handshaker = Handshaker(request, SubprotocolChoosingDispatcher(0))
206 handshaker.do_handshake()
207
208 EXPECTED_RESPONSE = (
209 b'HTTP/1.1 101 Switching Protocols\r\n'
210 b'Upgrade: websocket\r\n'
211 b'Connection: Upgrade\r\n'
212 b'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n'
213 b'Sec-WebSocket-Protocol: chat\r\n\r\n')
214
215 self.assertEqual(EXPECTED_RESPONSE, request.connection.written_data())
216 self.assertEqual('chat', request.ws_protocol)
217
218 def test_do_handshake_protocol_not_in_request_but_in_response(self):
219 request_def = _create_good_request_def()
220 request = _create_request(request_def)
221 handshaker = Handshaker(request,
222 SubprotocolChoosingDispatcher(-1, 'foobar'))
223 # No request has been made but ws_protocol is set. HandshakeException
224 # must be raised.
225 self.assertRaises(HandshakeException, handshaker.do_handshake)
226
227 def test_do_handshake_with_protocol_no_protocol_selection(self):
228 request_def = _create_good_request_def()
229 request_def.headers['Sec-WebSocket-Protocol'] = 'chat, superchat'
230
231 request = _create_request(request_def)
232 handshaker = _create_handshaker(request)
233 # ws_protocol is not set. HandshakeException must be raised.
234 self.assertRaises(HandshakeException, handshaker.do_handshake)
235
236 def test_do_handshake_with_extensions(self):
237 request_def = _create_good_request_def()
238 request_def.headers['Sec-WebSocket-Extensions'] = (
239 'permessage-deflate; server_no_context_takeover')
240
241 EXPECTED_RESPONSE = (
242 b'HTTP/1.1 101 Switching Protocols\r\n'
243 b'Upgrade: websocket\r\n'
244 b'Connection: Upgrade\r\n'
245 b'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n'
246 b'Sec-WebSocket-Extensions: '
247 b'permessage-deflate; server_no_context_takeover\r\n'
248 b'\r\n')
249
250 request = _create_request(request_def)
251 handshaker = _create_handshaker(request)
252 handshaker.do_handshake()
253 self.assertEqual(EXPECTED_RESPONSE, request.connection.written_data())
254 self.assertEqual(1, len(request.ws_extensions))
255 extension = request.ws_extensions[0]
256 self.assertEqual(common.PERMESSAGE_DEFLATE_EXTENSION, extension.name())
257 self.assertEqual(['server_no_context_takeover'],
258 extension.get_parameter_names())
259 self.assertEqual(
260 None, extension.get_parameter_value('server_no_context_takeover'))
261 self.assertEqual(1, len(request.ws_extension_processors))
262 self.assertEqual('deflate', request.ws_extension_processors[0].name())
263
264 def test_do_handshake_with_quoted_extensions(self):
265 request_def = _create_good_request_def()
266 request_def.headers['Sec-WebSocket-Extensions'] = (
267 'permessage-deflate, , '
268 'unknown; e = "mc^2"; ma="\r\n \\\rf "; pv=nrt')
269
270 request = _create_request(request_def)
271 handshaker = _create_handshaker(request)
272 handshaker.do_handshake()
273 self.assertEqual(2, len(request.ws_requested_extensions))
274 first_extension = request.ws_requested_extensions[0]
275 self.assertEqual('permessage-deflate', first_extension.name())
276 second_extension = request.ws_requested_extensions[1]
277 self.assertEqual('unknown', second_extension.name())
278 self.assertEqual(['e', 'ma', 'pv'],
279 second_extension.get_parameter_names())
280 self.assertEqual('mc^2', second_extension.get_parameter_value('e'))
281 self.assertEqual(' \rf ', second_extension.get_parameter_value('ma'))
282 self.assertEqual('nrt', second_extension.get_parameter_value('pv'))
283
284 def test_do_handshake_with_optional_headers(self):
285 request_def = _create_good_request_def()
286 request_def.headers['EmptyValue'] = ''
287 request_def.headers['AKey'] = 'AValue'
288
289 request = _create_request(request_def)
290 handshaker = _create_handshaker(request)
291 handshaker.do_handshake()
292 self.assertEqual('AValue', request.headers_in['AKey'])
293 self.assertEqual('', request.headers_in['EmptyValue'])
294
295 def test_abort_extra_handshake(self):
296 handshaker = Handshaker(_create_request(_create_good_request_def()),
297 AbortedByUserDispatcher())
298 # do_extra_handshake raises an AbortedByUserException. Check that it's
299 # not caught by do_handshake.
300 self.assertRaises(AbortedByUserException, handshaker.do_handshake)
301
302 def test_bad_requests(self):
303 bad_cases = [
304 ('HTTP request',
305 RequestDefinition(
306 'GET', '/demo', {
307 'Host':
308 'www.google.com',
309 'User-Agent':
310 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5;'
311 ' en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3'
312 ' GTB6 GTBA',
313 'Accept':
314 'text/html,application/xhtml+xml,application/xml;q=0.9,'
315 '*/*;q=0.8',
316 'Accept-Language':
317 'en-us,en;q=0.5',
318 'Accept-Encoding':
319 'gzip,deflate',
320 'Accept-Charset':
321 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
322 'Keep-Alive':
323 '300',
324 'Connection':
325 'keep-alive'
326 }), None, True)
327 ]
328
329 request_def = _create_good_request_def()
330 request_def.method = 'POST'
331 bad_cases.append(('Wrong method', request_def, None, True))
332
333 request_def = _create_good_request_def()
334 del request_def.headers['Host']
335 bad_cases.append(('Missing Host', request_def, None, True))
336
337 request_def = _create_good_request_def()
338 del request_def.headers['Upgrade']
339 bad_cases.append(('Missing Upgrade', request_def, None, True))
340
341 request_def = _create_good_request_def()
342 request_def.headers['Upgrade'] = 'nonwebsocket'
343 bad_cases.append(('Wrong Upgrade', request_def, None, True))
344
345 request_def = _create_good_request_def()
346 del request_def.headers['Connection']
347 bad_cases.append(('Missing Connection', request_def, None, True))
348
349 request_def = _create_good_request_def()
350 request_def.headers['Connection'] = 'Downgrade'
351 bad_cases.append(('Wrong Connection', request_def, None, True))
352
353 request_def = _create_good_request_def()
354 del request_def.headers['Sec-WebSocket-Key']
355 bad_cases.append(('Missing Sec-WebSocket-Key', request_def, 400, True))
356
357 request_def = _create_good_request_def()
358 request_def.headers['Sec-WebSocket-Key'] = (
359 'dGhlIHNhbXBsZSBub25jZQ==garbage')
360 bad_cases.append(('Wrong Sec-WebSocket-Key (with garbage on the tail)',
361 request_def, 400, True))
362
363 request_def = _create_good_request_def()
364 request_def.headers['Sec-WebSocket-Key'] = 'YQ==' # BASE64 of 'a'
365 bad_cases.append(
366 ('Wrong Sec-WebSocket-Key (decoded value is not 16 octets long)',
367 request_def, 400, True))
368
369 request_def = _create_good_request_def()
370 # The last character right before == must be any of A, Q, w and g.
371 request_def.headers['Sec-WebSocket-Key'] = 'AQIDBAUGBwgJCgsMDQ4PEC=='
372 bad_cases.append(
373 ('Wrong Sec-WebSocket-Key (padding bits are not zero)',
374 request_def, 400, True))
375
376 request_def = _create_good_request_def()
377 request_def.headers['Sec-WebSocket-Key'] = (
378 'dGhlIHNhbXBsZSBub25jZQ==,dGhlIHNhbXBsZSBub25jZQ==')
379 bad_cases.append(('Wrong Sec-WebSocket-Key (multiple values)',
380 request_def, 400, True))
381
382 request_def = _create_good_request_def()
383 del request_def.headers['Sec-WebSocket-Version']
384 bad_cases.append(
385 ('Missing Sec-WebSocket-Version', request_def, None, True))
386
387 request_def = _create_good_request_def()
388 request_def.headers['Sec-WebSocket-Version'] = '3'
389 bad_cases.append(
390 ('Wrong Sec-WebSocket-Version', request_def, None, False))
391
392 request_def = _create_good_request_def()
393 request_def.headers['Sec-WebSocket-Version'] = '13, 13'
394 bad_cases.append(('Wrong Sec-WebSocket-Version (multiple values)',
395 request_def, 400, True))
396
397 request_def = _create_good_request_def()
398 request_def.headers['Sec-WebSocket-Protocol'] = 'illegal\x09protocol'
399 bad_cases.append(
400 ('Illegal Sec-WebSocket-Protocol', request_def, 400, True))
401
402 request_def = _create_good_request_def()
403 request_def.headers['Sec-WebSocket-Protocol'] = ''
404 bad_cases.append(
405 ('Empty Sec-WebSocket-Protocol', request_def, 400, True))
406
407 for (case_name, request_def, expected_status,
408 expect_handshake_exception) in bad_cases:
409 request = _create_request(request_def)
410 handshaker = Handshaker(request, mock.MockDispatcher())
411 try:
412 handshaker.do_handshake()
413 self.fail('No exception thrown for \'%s\' case' % case_name)
414 except HandshakeException as e:
415 self.assertTrue(expect_handshake_exception)
416 self.assertEqual(expected_status, e.status)
417 except VersionException as e:
418 self.assertFalse(expect_handshake_exception)
419
420
421 if __name__ == '__main__':
422 unittest.main()
423
424 # vi:sts=4 sw=4 et