Debian Codegraph @

tests/test_cookie_only.py

raw symbols SCIP
1 import datetime
2 import time
3 import re
4 import json
5
6 import beaker.session
7 import beaker.util
8 from beaker.session import SignedCookie
9 from beaker._compat import b64decode
10 from beaker.middleware import SessionMiddleware
11 from unittest import SkipTest
12 try:
13 from webtest import TestApp as WebTestApp
14 except ImportError:
15 raise SkipTest("webtest not installed")
16
17 from beaker import crypto
18 if not crypto.get_crypto_module('default').has_aes:
19 raise SkipTest("No AES library is installed, can't test cookie-only "
20 "Sessions")
21
22 def simple_app(environ, start_response):
23 session = environ['beaker.session']
24 if 'value' not in session:
25 session['value'] = 0
26 session['value'] += 1
27 if not environ['PATH_INFO'].startswith('/nosave'):
28 session.save()
29 start_response('200 OK', [('Content-type', 'text/plain')])
30 msg = 'The current value is: %d and cookie is %s' % (session['value'], session)
31 return [msg.encode('UTF-8')]
32
33 def test_increment():
34 options = {'session.validate_key':'hoobermas', 'session.type':'cookie'}
35 app = WebTestApp(SessionMiddleware(simple_app, **options))
36 res = app.get('/')
37 assert 'current value is: 1' in res
38 res = app.get('/')
39 assert 'current value is: 2' in res
40 res = app.get('/')
41 assert 'current value is: 3' in res
42
43 def test_invalid_cookie():
44 # This is not actually a cookie only session, but we still test the cookie part.
45 options = {'session.validate_key':'hoobermas'}
46 app = WebTestApp(SessionMiddleware(simple_app, **options))
47
48 res = app.get('/')
49 assert 'current value is: 1' in res
50
51 # Set an invalid cookie.
52 app.set_cookie('cb_/zabbix/actionconf.php_parts', 'HI')
53 res = app.get('/')
54 assert 'current value is: 2' in res, res
55
56 res = app.get('/')
57 assert 'current value is: 3' in res, res
58
59 def test_invalid_cookie_cookietype():
60 # This is not actually a cookie only session, but we still test the cookie part.
61 options = {'session.validate_key':'hoobermas', 'session.type':'cookie'}
62 app = WebTestApp(SessionMiddleware(simple_app, **options))
63
64 res = app.get('/')
65 assert 'current value is: 1' in res
66
67 # Set an invalid cookie.
68 app.set_cookie('cb_/zabbix/actionconf.php_parts', 'HI')
69 res = app.get('/')
70 assert 'current value is: 2' in res, res
71
72 res = app.get('/')
73 assert 'current value is: 3' in res, res
74
75 def test_json_serializer():
76 options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'data_serializer': 'json'}
77 app = WebTestApp(SessionMiddleware(simple_app, **options))
78
79 res = app.get('/')
80 assert 'current value is: 1' in res
81
82 res = app.get('/')
83 cookie = SignedCookie('hoobermas')
84 session_data = cookie.value_decode(app.cookies['beaker.session.id'])[0]
85 session_data = b64decode(session_data)
86 data = beaker.util.deserialize(session_data, 'json')
87 assert data['value'] == 2
88
89 res = app.get('/')
90 assert 'current value is: 3' in res
91
92 def test_pickle_serializer():
93 options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'data_serializer': 'pickle'}
94 app = WebTestApp(SessionMiddleware(simple_app, **options))
95
96 res = app.get('/')
97 assert 'current value is: 1' in res
98
99 res = app.get('/')
100 cookie = SignedCookie('hoobermas')
101 session_data = cookie.value_decode(app.cookies['beaker.session.id'])[0]
102 session_data = b64decode(session_data)
103 data = beaker.util.deserialize(session_data, 'pickle')
104 assert data['value'] == 2
105
106 res = app.get('/')
107 assert 'current value is: 3' in res
108
109 def test_custom_serializer():
110 was_used = [False, False]
111 class CustomSerializer(object):
112 def loads(self, data_string):
113 was_used[0] = True
114 return json.loads(data_string.decode('utf-8'))
115
116 def dumps(self, data):
117 was_used[1] = True
118 return json.dumps(data).encode('utf-8')
119
120 serializer = CustomSerializer()
121 options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'data_serializer': serializer}
122 app = WebTestApp(SessionMiddleware(simple_app, **options))
123
124 res = app.get('/')
125 assert 'current value is: 1' in res
126
127 res = app.get('/')
128 cookie = SignedCookie('hoobermas')
129 session_data = cookie.value_decode(app.cookies['beaker.session.id'])[0]
130 session_data = b64decode(session_data)
131 data = serializer.loads(session_data)
132 assert data['value'] == 2
133
134 res = app.get('/')
135 assert 'current value is: 3' in res
136
137 assert all(was_used)
138
139 def test_expires():
140 options = {'session.validate_key':'hoobermas', 'session.type':'cookie',
141 'session.cookie_expires': datetime.timedelta(days=1)}
142 app = WebTestApp(SessionMiddleware(simple_app, **options))
143 res = app.get('/')
144 assert 'expires=' in res.headers.getall('Set-Cookie')[0]
145 assert 'current value is: 1' in res
146
147 def test_different_sessions():
148 options = {'session.validate_key':'hoobermas', 'session.type':'cookie'}
149 app = WebTestApp(SessionMiddleware(simple_app, **options))
150 app2 = WebTestApp(SessionMiddleware(simple_app, **options))
151 res = app.get('/')
152 assert 'current value is: 1' in res
153 res = app2.get('/')
154 assert 'current value is: 1' in res
155 res = app2.get('/')
156 res = app2.get('/')
157 res = app2.get('/')
158 res2 = app.get('/')
159 assert 'current value is: 2' in res2
160 assert 'current value is: 4' in res
161
162 def test_nosave():
163 options = {'session.validate_key':'hoobermas', 'session.type':'cookie'}
164 app = WebTestApp(SessionMiddleware(simple_app, **options))
165 res = app.get('/nosave')
166 assert 'current value is: 1' in res
167 assert [] == res.headers.getall('Set-Cookie')
168 res = app.get('/nosave')
169 assert 'current value is: 1' in res
170
171 res = app.get('/')
172 assert 'current value is: 1' in res
173 assert len(res.headers.getall('Set-Cookie')) > 0
174 res = app.get('/')
175 assert 'current value is: 2' in res
176
177 def test_increment_with_encryption():
178 options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
179 'session.type':'cookie'}
180 app = WebTestApp(SessionMiddleware(simple_app, **options))
181 res = app.get('/')
182 assert 'current value is: 1' in res
183 res = app.get('/')
184 assert 'current value is: 2' in res
185 res = app.get('/')
186 assert 'current value is: 3' in res
187
188 def test_different_sessions_with_encryption():
189 options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
190 'session.type':'cookie'}
191 app = WebTestApp(SessionMiddleware(simple_app, **options))
192 app2 = WebTestApp(SessionMiddleware(simple_app, **options))
193 res = app.get('/')
194 assert 'current value is: 1' in res
195 res = app2.get('/')
196 assert 'current value is: 1' in res
197 res = app2.get('/')
198 res = app2.get('/')
199 res = app2.get('/')
200 res2 = app.get('/')
201 assert 'current value is: 2' in res2
202 assert 'current value is: 4' in res
203
204 def test_nosave_with_encryption():
205 options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
206 'session.type':'cookie'}
207 app = WebTestApp(SessionMiddleware(simple_app, **options))
208 res = app.get('/nosave')
209 assert 'current value is: 1' in res
210 assert [] == res.headers.getall('Set-Cookie')
211 res = app.get('/nosave')
212 assert 'current value is: 1' in res
213
214 res = app.get('/')
215 assert 'current value is: 1' in res
216 assert len(res.headers.getall('Set-Cookie')) > 0
217 res = app.get('/')
218 assert 'current value is: 2' in res
219
220 def test_cookie_id():
221 options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
222 'session.type':'cookie'}
223 app = WebTestApp(SessionMiddleware(simple_app, **options))
224
225 res = app.get('/')
226 assert "_id':" in res
227 sess_id = re.sub(r".*'_id': '(.*?)'.*", r'\1', res.body.decode('utf-8'))
228 res = app.get('/')
229 new_id = re.sub(r".*'_id': '(.*?)'.*", r'\1', res.body.decode('utf-8'))
230 assert new_id == sess_id
231
232 def test_invalidate_with_save_does_not_delete_session():
233 def invalidate_session_app(environ, start_response):
234 session = environ['beaker.session']
235 session.invalidate()
236 session.save()
237 start_response('200 OK', [('Content-type', 'text/plain')])
238 return [('Cookie is %s' % session).encode('UTF-8')]
239
240 options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
241 'session.type':'cookie'}
242 app = WebTestApp(SessionMiddleware(invalidate_session_app, **options))
243 res = app.get('/')
244 assert 'expires=' not in res.headers.getall('Set-Cookie')[0]
245
246
247 def test_changing_encrypt_key_with_timeout():
248 COMMON_ENCRYPT_KEY = '666a19cf7f61c64c'
249 DIFFERENT_ENCRYPT_KEY = 'hello-world'
250
251 options = {'session.encrypt_key': COMMON_ENCRYPT_KEY,
252 'session.timeout': 300,
253 'session.validate_key': 'hoobermas',
254 'session.type': 'cookie'}
255 app = WebTestApp(SessionMiddleware(simple_app, **options))
256 res = app.get('/')
257 assert 'The current value is: 1' in res, res
258
259 # Get the session cookie, so we can reuse it.
260 cookies = res.headers['Set-Cookie']
261
262 # Check that we get the same session with the same cookie
263 options = {'session.encrypt_key': COMMON_ENCRYPT_KEY,
264 'session.timeout': 300,
265 'session.validate_key': 'hoobermas',
266 'session.type': 'cookie'}
267 app = WebTestApp(SessionMiddleware(simple_app, **options))
268 res = app.get('/', headers={'Cookie': cookies})
269 assert 'The current value is: 2' in res, res
270
271 # Now that we are sure that it reuses the same session,
272 # change the encrypt_key so that it is unable to understand the cookie.
273 options = {'session.encrypt_key': DIFFERENT_ENCRYPT_KEY,
274 'session.timeout': 300,
275 'session.validate_key': 'hoobermas',
276 'session.type': 'cookie'}
277 app = WebTestApp(SessionMiddleware(simple_app, **options))
278 res = app.get('/', headers={'Cookie': cookies})
279
280 # Let's check it created a new session as the old one is invalid
281 # in the past it just crashed.
282 assert 'The current value is: 1' in res, res
283
284
285 def test_cookie_properly_expires():
286 COMMON_ENCRYPT_KEY = '666a19cf7f61c64c'
287
288 options = {'session.encrypt_key': COMMON_ENCRYPT_KEY,
289 'session.timeout': 1,
290 'session.validate_key': 'hoobermas',
291 'session.type': 'cookie'}
292 app = WebTestApp(SessionMiddleware(simple_app, **options))
293 res = app.get('/')
294 assert 'The current value is: 1' in res, res
295
296 res = app.get('/')
297 assert 'The current value is: 2' in res, res
298
299 # Wait session to expire and check it starts with a clean one
300 time.sleep(1)
301 res = app.get('/')
302 assert 'The current value is: 1' in res, res
303
304
305 def test_cookie_attributes_are_preserved():
306 options = {'session.type': 'cookie',
307 'session.validate_key': 'hoobermas',
308 'session.httponly': True,
309 'session.secure': True,
310 'session.samesite': 'Strict'}
311 app = WebTestApp(SessionMiddleware(simple_app, options))
312 res = app.get('/')
313 cookie = res.headers['Set-Cookie']
314 assert 'secure' in cookie.lower()
315 assert 'httponly' in cookie.lower()
316 assert 'samesite=strict' in cookie.lower()
317
318
319 def test_cookie_path_properly_set_after_init():
320 COOKIE_PATH = '/app'
321
322 options = {
323 'session.validate_key': 'hoobermas',
324 'session.type': 'cookie',
325 'session.cookie_path': COOKIE_PATH,
326 }
327 app = WebTestApp(SessionMiddleware(simple_app, **options))
328 res = app.get('/app')
329 cookie = res.headers['Set-Cookie']
330
331 assert ('path=%s' % COOKIE_PATH) in cookie.lower()
332
333
334 def test_cookie_path_properly_set_after_load():
335 COOKIE_PATH = '/app'
336
337 options = {
338 'session.validate_key': 'hoobermas',
339 'session.type': 'cookie',
340 'session.cookie_path': COOKIE_PATH,
341 }
342 app = WebTestApp(SessionMiddleware(simple_app, **options))
343 # Perform one request to set the cookie
344 res = app.get('/app')
345 # Perform another request to load the previous session from the cookie
346 res = app.get('/app')
347 cookie = res.headers['Set-Cookie']
348
349 assert ('path=%s' % COOKIE_PATH) in cookie.lower()
350
351
352 def test_cookie_path_properly_set_after_delete():
353 COOKIE_PATH = '/app'
354
355 def delete_session_app(environ, start_response):
356 session = environ['beaker.session']
357 session.delete()
358 start_response('200 OK', [('Content-type', 'text/plain')])
359 return [('Cookie is %s' % session).encode('UTF-8')]
360
361 options = {
362 'session.validate_key': 'hoobermas',
363 'session.type': 'cookie',
364 'session.cookie_path': COOKIE_PATH,
365 }
366 app = WebTestApp(SessionMiddleware(delete_session_app, **options))
367 res = app.get('/app')
368 cookie = res.headers['Set-Cookie']
369
370 assert ('path=%s' % COOKIE_PATH) in cookie.lower()
371
372
373 if __name__ == '__main__':
374 from paste import httpserver
375 wsgi_app = SessionMiddleware(simple_app, {})
376 httpserver.serve(wsgi_app, host='127.0.0.1', port=8080)