source: main/waeup.cas/trunk/waeup/cas/tests/test_server.py @ 10497

Last change on this file since 10497 was 10495, checked in by uli, 11 years ago

pyflakes.

File size: 23.0 KB
Line 
1import os
2import re
3import shutil
4import tempfile
5import unittest
6from paste.deploy import loadapp
7try:
8    from urlparse import parse_qsl         # Python 2.x
9except ImportError:                        # pragma: no cover
10    from urllib.parse import parse_qsl     # Python 3.x
11from webob import Request, Response
12from webtest import TestApp as WebTestApp  # avoid py.test skip message
13from waeup.cas.authenticators import DummyAuthenticator
14from waeup.cas.db import DB, LoginTicket, ServiceTicket, TicketGrantingCookie
15from waeup.cas.server import (
16    CASServer, create_service_ticket, create_login_ticket,
17    create_tgc_value, check_login_ticket, set_session_cookie,
18    check_session_cookie, get_template, delete_session_cookie,
19    check_service_ticket, update_url
20    )
21
22RE_ALPHABET = re.compile('^[a-zA-Z0-9\-]*$')
23RE_COOKIE = re.compile('^cas-tgc=[A-Za-z0-9\-]+; Path=/; secure; HttpOnly$')
24RE_COOKIE_DEL = re.compile(
25    '^cas-tgc=; Max-Age=\-[0-9]+; Path=/; '
26    'expires=Thu, 01-Jan-1970 00:00:00 GMT; secure; HttpOnly$')
27
28
29class CASServerTests(unittest.TestCase):
30
31    def setUp(self):
32        # Create a new location where tempfiles are created.  This way
33        # also temporary dirs of local CASServers can be removed on
34        # tear-down.
35        self._new_tmpdir = tempfile.mkdtemp()
36        self._old_tmpdir = tempfile.tempdir
37        tempfile.tempdir = self._new_tmpdir
38        self.workdir = os.path.join(self._new_tmpdir, 'home')
39        self.db_path = os.path.join(self.workdir, 'mycas.db')
40        os.mkdir(self.workdir)
41        self.paste_conf1 = os.path.join(
42            os.path.dirname(__file__), 'sample1.ini')
43        self.paste_conf2 = os.path.join(
44            os.path.dirname(__file__), 'sample2.ini')
45
46    def tearDown(self):
47        # remove local tempfile and reset old tempdir setting
48        if os.path.isdir(self._new_tmpdir):
49            shutil.rmtree(self._new_tmpdir)
50        tempfile.tempdir = self._old_tmpdir
51
52    def test_paste_deploy_loader(self):
53        # we can load the CAS server via paste.deploy plugin
54        app = loadapp('config:%s' % self.paste_conf1)
55        assert isinstance(app, CASServer)
56        assert hasattr(app, 'db')
57        assert isinstance(app.db, DB)
58        assert hasattr(app, 'auth')
59
60    def test_paste_deploy_options(self):
61        # we can set CAS server-related options via paste.deploy config
62        app = loadapp('config:%s' % self.paste_conf2)
63        assert isinstance(app, CASServer)
64        assert app.db_connection_string == 'sqlite:///:memory:'
65        assert isinstance(app.auth, DummyAuthenticator)
66
67    def test_init(self):
68        # we get a `DB` instance created automatically
69        app = CASServer()
70        assert hasattr(app, 'db')
71        assert app.db is not None
72
73    def test_init_explicit_db_path(self):
74        # we can set a db_path explicitly
75        app = CASServer(db='sqlite:///%s' % self.db_path)
76        assert hasattr(app, 'db')
77        assert isinstance(app.db, DB)
78        assert os.path.isfile(self.db_path)
79
80    def test_get_template(self):
81        app = CASServer()
82        assert app._get_template('login.html') is not None
83        assert app._get_template('not-existent.html') is None
84
85    def test_call_root(self):
86        # the CAS protocol requires no root
87        app = CASServer()
88        req = Request.blank('http://localhost/')
89        resp = app(req)
90        assert resp.status == '404 Not Found'
91
92    def test_first_time_login(self):
93        # we can get a login page
94        app = CASServer()
95        req = Request.blank('http://localhost/login')
96        resp = app(req)
97        assert resp.status == '200 OK'
98
99    def test_validate(self):
100        # we can access a validation page
101        app = CASServer()
102        req = Request.blank('http://localhost/validate?service=foo&ticket=bar')
103        resp = app(req)
104        assert resp.status == '200 OK'
105
106    def test_logout(self):
107        # we can access a logout page
108        app = CASServer()
109        req = Request.blank('http://localhost/logout')
110        resp = app(req)
111        assert resp.status == '200 OK'
112
113    def test_login_simple(self):
114        # a simple login with no service will result in login screen
115        # (2.1.1#service of protocol specs)
116        app = CASServer()
117        req = Request.blank('http://localhost/login')
118        resp = app(req)
119        assert resp.status == '200 OK'
120        assert resp.content_type == 'text/html'
121        assert b'<form ' in resp.body
122
123    def test_login_cred_acceptor_sso_no_service(self):
124        # 2.2.4: successful login via single sign on
125        app = CASServer()
126        tgc = create_tgc_value()
127        app.db.add(tgc)
128        value = str(tgc.value)
129        req = Request.blank('https://localhost/login')
130        req.headers['Cookie'] = 'cas-tgc=%s' % value
131        resp = app(req)
132        assert resp.status == '200 OK'
133        assert b'already' in resp.body
134        assert 'Set-Cookie' not in resp.headers
135        return
136
137    def test_login_renew_with_cookie(self):
138        # 2.1.1: cookie will be ignored when renew is set
139        app = CASServer()
140        tgc = create_tgc_value()
141        app.db.add(tgc)
142        value = str(tgc.value)
143        req = Request.blank('https://localhost/login?renew=true')
144        req.headers['Cookie'] = 'cas-tgc=%s' % value
145        resp = app(req)
146        assert resp.status == '200 OK'
147        assert b'username' in resp.body
148        assert 'Set-Cookie' not in resp.headers
149
150    def test_login_renew_without_cookie(self):
151        # 2.1.1: with renew and no cookie, normal auth will happen
152        app = CASServer()
153        req = Request.blank('https://localhost/login?renew=true')
154        resp = app(req)
155        assert resp.status == '200 OK'
156        assert b'username' in resp.body
157
158    def test_login_renew_as_empty_string(self):
159        # `renew` is handled correctly, even with empty value
160        app = CASServer()
161        tgc = create_tgc_value()
162        app.db.add(tgc)
163        value = str(tgc.value)
164        req = Request.blank('https://localhost/login?renew')
165        req.headers['Cookie'] = 'cas-tgc=%s' % value
166        resp = app(req)
167        assert resp.status == '200 OK'
168        assert b'username' in resp.body
169        assert 'Set-Cookie' not in resp.headers
170
171    def test_login_gateway_no_cookie_with_service(self):
172        # 2.1.1: with gateway but w/o cookie we will be redirected to service
173        # no service ticket will be issued
174        app = CASServer()
175        params = 'gateway=true&service=http%3A%2F%2Fwww.service.com'
176        req = Request.blank('https://localhost/login?%s' % params)
177        resp = app(req)
178        assert resp.status == '303 See Other'
179        assert 'Location' in resp.headers
180        assert resp.headers['Location'] == 'http://www.service.com'
181
182    def test_login_gateway_with_cookie_and_service(self):
183        # 2.1.1: with cookie and gateway we will be redirected to service
184        app = CASServer()
185        tgc = create_tgc_value()
186        app.db.add(tgc)
187        value = str(tgc.value)
188        params = 'gateway=true&service=http%3A%2F%2Fwww.service.com'
189        req = Request.blank('https://localhost/login?%s' % params)
190        req.headers['Cookie'] = 'cas-tgc=%s' % value
191        resp = app(req)
192        assert resp.status == '303 See Other'
193        assert 'Location' in resp.headers
194        assert resp.headers['Location'].startswith(
195            'http://www.service.com?ticket=ST-')
196
197    def test_login_gateway_and_renew(self):
198        # 2.1.1 if both, gateway and renew are specified, only renew is valid
199        app = CASServer()
200        tgc = create_tgc_value()
201        app.db.add(tgc)
202        value = str(tgc.value)
203        req = Request.blank('https://localhost/login?renew=true&gateway=true')
204        req.headers['Cookie'] = 'cas-tgc=%s' % value
205        resp = app(req)
206        # with only gateway true, this would lead to a redirect
207        assert resp.status == '200 OK'
208        assert b'username' in resp.body
209        assert 'Set-Cookie' not in resp.headers
210
211    def test_login_warn(self):
212        # 2.2.1 as a credential acceptor, with `warn` set we require confirm
213        app = CASServer()
214        tgc = create_tgc_value()
215        app.db.add(tgc)
216        value = str(tgc.value)
217        params = 'warn=true&service=http%3A%2F%2Fwww.service.com'
218        req = Request.blank('https://localhost/login?%s' % params)
219        req.headers['Cookie'] = 'cas-tgc=%s' % value
220        resp = app(req)
221        # without warn, we would get a redirect
222        assert resp.status == '200 OK'
223        assert b'CAS login successful' in resp.body
224
225    def test_logout_no_cookie(self):
226        # 2.3 logout displays a logout page.
227        app = CASServer()
228        req = Request.blank('https://localhost/logout')
229        resp = app(req)
230        assert resp.status == '200 OK'
231        assert b'logged out' in resp.body
232
233    def test_logout_with_cookie(self):
234        # 2.3 logout destroys any existing SSO session
235        app = CASServer()
236        tgc = create_tgc_value()
237        app.db.add(tgc)
238        value = str(tgc.value)
239        req = Request.blank('https://localhost/logout')
240        req.headers['Cookie'] = 'cas-tgc=%s' % value
241        resp = app(req)
242        assert resp.status == '200 OK'
243        assert b'logged out' in resp.body
244        assert 'Set-Cookie' in resp.headers
245        cookie = resp.headers['Set-Cookie']
246        assert cookie.startswith('cas-tgc=;')
247        assert 'expires' in cookie
248        assert 'Max-Age' in cookie
249        assert len(list(app.db.query(TicketGrantingCookie))) == 0
250
251    def test_logout_url(self):
252        # 2.3.1 with an `url` given we provide a link on logout
253        app = CASServer()
254        params = 'url=http%3A%2F%2Fwww.logout.com'
255        req = Request.blank('https://localhost/logout?%s' % params)
256        resp = app(req)
257        assert resp.status == '200 OK'
258        assert b'logged out' in resp.body
259        assert b'like you to' in resp.body
260        assert b'http://www.logout.com' in resp.body
261
262    def test_validate_invalid(self):
263        # 2.4.2 validation failures is indicated by a given format
264        app = CASServer()
265        params = 'ticket=foo&service=bar'
266        req = Request.blank('https://localhost/validate?%s' % params)
267        resp = app(req)
268        assert resp.body == b'no\n\n'
269
270    def test_validate_valid(self):
271        # 2.4 validation success is indicated by a given format
272        app = CASServer()
273        sticket = create_service_ticket(
274            'someuser', 'http://service.com/', sso=False)
275        app.db.add(sticket)
276        params = 'ticket=%s&service=%s' % (
277            sticket.ticket, sticket.service)
278        req = Request.blank('https://localhost/validate?%s' % params)
279        resp = app(req)
280        assert resp.body == b'yes\nsomeuser\n'
281
282    def test_validate_renew_invalid(self):
283        # 2.4.1 with `renew` we accept only non-sso issued tickets
284        app = CASServer()
285        sticket = create_service_ticket(
286            'someuser', 'http://service.com/', sso=True)
287        app.db.add(sticket)
288        params = 'ticket=%s&service=%s&renew=true' % (
289            sticket.ticket, sticket.service)
290        req = Request.blank('https://localhost/validate?%s' % params)
291        resp = app(req)
292        assert resp.body == b'no\n\n'
293
294    def test_validate_renew_valid(self):
295        # 2.4.1 with `renew` we accept only non-sso issued tickets
296        app = CASServer()
297        sticket = create_service_ticket(
298            'someuser', 'http://service.com/', sso=False)
299        app.db.add(sticket)
300        params = 'ticket=%s&service=%s&renew=true' % (
301            sticket.ticket, sticket.service)
302        req = Request.blank('https://localhost/validate?%s' % params)
303        resp = app(req)
304        assert resp.body == b'yes\nsomeuser\n'
305
306
307class BrowserTests(unittest.TestCase):
308
309    def setUp(self):
310        self.raw_app = CASServer(auth=DummyAuthenticator())
311        self.app = WebTestApp(self.raw_app)
312
313    def test_login(self):
314        resp = self.app.get('/login')
315        assert resp.status == '200 OK'
316        form = resp.forms[0]
317        # 2.1.3: form must be submitted by POST
318        assert form.method == 'post'
319        fieldnames = form.fields.keys()
320        # 2.1.3: form must contain: username, password, lt
321        assert 'username' in fieldnames
322        assert 'password' in fieldnames
323        assert 'lt' in fieldnames
324        assert RE_ALPHABET.match(form['lt'].value)
325
326    def test_login_no_service(self):
327        # w/o a service passed in, the form should not contain service
328        # (not a strict protocol requirement, but handy)
329        resp = self.app.get('/login')
330        assert 'service' not in resp.forms[0].fields.keys()
331
332    def test_login_service_replayed(self):
333        # 2.1.3: the login form must contain the service param sent
334        resp = self.app.get('/login?service=http%3A%2F%2Fwww.service.com')
335        form = resp.forms[0]
336        assert resp.status == '200 OK'
337        assert 'service' in form.fields.keys()
338        assert form['service'].value == 'http://www.service.com'
339
340    def test_login_cred_acceptor_valid_no_service(self):
341        # 2.2.4: successful login w/o service yields a message
342        lt = create_login_ticket()
343        self.raw_app.db.add(lt)
344        lt_string = lt.ticket
345        resp = self.app.post('/login', dict(
346            username='bird', password='bebop', lt=lt_string))
347        assert resp.status == '200 OK'
348        assert b'successful' in resp.body
349        # single-sign-on session initiated
350        assert 'Set-Cookie' in resp.headers
351        cookie = resp.headers['Set-Cookie']
352        assert cookie.startswith('cas-tgc=')
353
354    def test_login_cred_acceptor_valid_w_service(self):
355        # 2.2.4: successful login with service makes a redirect
356        # Appendix B: safe redirect
357        lt = create_login_ticket()
358        self.raw_app.db.add(lt)
359        lt_string = lt.ticket
360        resp = self.app.post('/login', dict(
361            username='bird', password='bebop', lt=lt_string,
362            service='http://example.com/Login'))
363        assert resp.status == '303 See Other'
364        assert 'Location' in resp.headers
365        assert resp.headers['Location'].startswith(
366            'http://example.com/Login?ticket=ST-')
367        assert 'Pragma' in resp.headers
368        assert resp.headers['Pragma'] == 'no-cache'
369        assert 'Cache-Control' in resp.headers
370        assert resp.headers['Cache-Control'] == 'no-store'
371        assert 'Expires' in resp.headers
372        assert resp.headers['Expires'] == 'Thu, 01 Dec 1994 16:00:00 GMT'
373        assert b'window.location.href' in resp.body
374        assert b'noscript' in resp.body
375        assert b'ticket=ST-' in resp.body
376
377    def test_login_cred_acceptor_failed(self):
378        # 2.2.4: failed login yields a message
379        lt = create_login_ticket()
380        self.raw_app.db.add(lt)
381        lt_string = lt.ticket
382        resp = self.app.post('/login', dict(
383            username='bird', password='cat', lt=lt_string))
384        assert resp.status == '200 OK'
385        assert b'failed' in resp.body
386
387    def test_login_sso_no_service(self):
388        # we can initiate single-sign-on without service
389        resp1 = self.app.get('https://localhost/login')  # HTTPS required!
390        assert resp1.status == '200 OK'
391        assert 'cas-tgc' not in self.app.cookies
392        form = resp1.forms[0]
393        form.set('username', 'bird')
394        form.set('password', 'bebop')
395        resp2 = form.submit('AUTHENTICATE')
396        assert resp2.status == '200 OK'
397        # we got a secure cookie
398        assert 'cas-tgc' in self.app.cookies
399        # when we get the login page again, the cookie will replace creds.
400        resp3 = self.app.get('https://localhost/login')
401        assert b'You logged in already' in resp3.body
402
403    def test_login_sso_with_service(self):
404        resp1 = self.app.get(
405            'https://localhost/login?service=http%3A%2F%2Fservice.com%2F')
406        assert resp1.status == '200 OK'
407        assert 'cas-tgc' not in self.app.cookies
408        form = resp1.forms[0]
409        form.set('username', 'bird')
410        form.set('password', 'bebop')
411        resp2 = form.submit('AUTHENTICATE')
412        assert resp2.status == '303 See Other'
413        assert resp2.headers['Location'].startswith(
414            'http://service.com/?ticket=ST-')
415        # we got a secure cookie
416        assert 'cas-tgc' in self.app.cookies
417        resp3 = self.app.get(
418            'https://localhost/login?service=http%3A%2F%2Fservice.com%2F')
419        assert resp3.status == '303 See Other'
420        assert resp3.headers['Location'].startswith(
421            'http://service.com/?ticket=ST-')
422
423    def test_login_sso_with_service_additional_params1(self):
424        # we can get a service ticket also with a service providing
425        # get params
426        # this service url reads http://service.com/index.php?authCAS=CAS
427        service_url = 'http%3A%2F%2Fservice.com%2Findex.php%3FauthCAS%3DCAS'
428        resp1 = self.app.get(
429            'https://localhost/login?service=%s' % service_url)
430        assert resp1.status == '200 OK'
431        assert 'cas-tgc' not in self.app.cookies
432        form = resp1.forms[0]
433        form.set('username', 'bird')
434        form.set('password', 'bebop')
435        resp2 = form.submit('AUTHENTICATE')
436        assert resp2.status == '303 See Other'
437        location = resp2.headers['Location']
438        query_string = location.split('?', 1)[1]
439        query_params = dict(parse_qsl(query_string))
440        assert 'authCAS' in query_params.keys()
441        assert 'ticket' in query_params.keys()
442        assert len(query_params['ticket']) == 32
443
444
445class CASServerHelperTests(unittest.TestCase):
446
447    def setUp(self):
448        self.workdir = tempfile.mkdtemp()
449        self.db_file = os.path.join(self.workdir, 'mycas.db')
450        self.conn_string = 'sqlite:///%s' % self.db_file
451        self.db = DB(self.conn_string)
452
453    def tearDown(self):
454        shutil.rmtree(self.workdir)
455
456    def test_create_service_ticket(self):
457        # we can create service tickets
458        st = create_service_ticket(
459            user='bob', service='http://www.example.com')
460        assert isinstance(st, ServiceTicket)
461        # 3.1.1: service not part of ticket
462        assert 'example.com' not in st.ticket
463        # 3.1.1: ticket must start with 'ST-'
464        assert st.ticket.startswith('ST-')
465        # 3.1.1: min. ticket length clients must be able to process is 32
466        assert len(st.ticket) < 33
467        # 3.7: allowed character set == [a-zA-Z0-9\-]
468        assert RE_ALPHABET.match(st.ticket), (
469            'Ticket contains forbidden chars: %s' % st)
470
471    def test_create_login_ticket(self):
472        # we can create login tickets
473        lt = create_login_ticket()
474        # 3.5.1: ticket should start with 'LT-'
475        assert lt.ticket.startswith('LT-')
476        # 3.7: allowed character set == [a-zA-Z0-9\-]
477        assert RE_ALPHABET.match(lt.ticket), (
478            'Ticket contains forbidden chars: %s' % lt)
479
480    def test_create_login_ticket_unique(self):
481        # 3.5.1: login tickets are unique (although not hard to guess)
482        ticket_num = 1000  # increase to test more thoroughly
483        lt_list = [create_login_ticket() for x in range(ticket_num)]
484        assert len(set(lt_list)) == ticket_num
485
486    def test_create_tgc_value(self):
487        # we can create ticket granting cookies
488        tgc = create_tgc_value()
489        assert isinstance(tgc, TicketGrantingCookie)
490        # 3.6.1: cookie value should start with 'TGC-'
491        assert tgc.value.startswith('TGC-')
492        # 3.7: allowed character set == [a-zA-Z0-9\-]
493        assert RE_ALPHABET.match(tgc.value), (
494            'Cookie value contains forbidden chars: %s' % tgc)
495
496    def test_check_login_ticket(self):
497        db = DB('sqlite:///')
498        lt = LoginTicket('LT-123456')
499        db.add(lt)
500        assert check_login_ticket(db, None) is False
501        assert check_login_ticket(db, 'LT-123456') is True
502        # the ticket will be removed after check
503        assert check_login_ticket(db, 'LT-123456') is False
504        assert check_login_ticket(db, 'LT-654321') is False
505
506    def test_set_session_cookie1(self):
507        # make sure we can add session cookies to responses
508        db = DB('sqlite:///')
509        resp = set_session_cookie(db, Response())
510        assert 'Set-Cookie' in resp.headers
511        cookie = resp.headers['Set-Cookie']
512        assert RE_COOKIE.match(cookie), (
513            'Cookie in unexpected format: %s' % cookie)
514        # the cookie is stored in database
515        value = cookie.split('=')[1].split(';')[0]
516        q = db.query(TicketGrantingCookie).filter(
517            TicketGrantingCookie.value == value)
518        assert len(list(q)) == 1
519
520    def test_check_session_cookie2(self):
521        db = DB('sqlite:///')
522        tgc = create_tgc_value()
523        db.add(tgc)
524        value = tgc.value
525        assert check_session_cookie(db, value) == tgc
526        assert check_session_cookie(db, 'foo') is None
527        assert check_session_cookie(db, b'foo') is None
528        assert check_session_cookie(db, None) is None
529        value2 = value.encode('utf-8')
530        assert check_session_cookie(db, value2) == tgc
531
532    def test_get_template(self):
533        # we can load templates
534        assert get_template('not-existing-template') is None
535        assert get_template('login.html') is not None
536
537    def test_delete_session_cookie(self):
538        # we can unset cookies
539        db = DB('sqlite:///')
540        tgc = create_tgc_value()
541        db.add(tgc)
542        value = tgc.value
543        resp = delete_session_cookie(db, Response(), old_value=value)
544        assert 'Set-Cookie' in resp.headers
545        cookie = resp.headers['Set-Cookie']
546        assert RE_COOKIE_DEL.match(cookie), (
547            'Cookie in unexpected format: %s' % cookie)
548        # the cookie values was deleted from database
549        q = db.query(TicketGrantingCookie).filter(
550            TicketGrantingCookie.value == value)
551        assert len(list(q)) == 0
552
553    def test_check_service_ticket(self):
554        db = DB('sqlite:///')
555        st = ServiceTicket(
556            'ST-123456', 'someuser', 'http://myservice.com', True)
557        db.add(st)
558        assert check_service_ticket(db, None, 'foo') is None
559        assert check_service_ticket(db, 'foo', None) is None
560        assert check_service_ticket(db, 'ST-123456', 'foo') is None
561        assert check_service_ticket(db, 'foo', 'http://myservice.com') is None
562        result = check_service_ticket(db, 'ST-123456', 'http://myservice.com')
563        assert isinstance(result, ServiceTicket)
564        assert result.user == 'someuser'
565        assert check_service_ticket(
566            db,  'ST-123456', 'http://myservice.com', True) is None
567        assert check_service_ticket(
568            db,  'ST-123456', 'http://myservice.com', False) is not None
569
570    def test_update_url(self):
571        # we can create valid new urls with query string params updated
572        result1 = update_url('http://sample.com/index?a=1&b=2', dict(b='3'))
573        assert result1 in (
574            'http://sample.com/index?a=1&b=3',
575            'http://sample.com/index?b=3&a=1')
576        result2 = update_url('http://sample.com/index?b=2', dict(b='3'))
577        assert result2 == 'http://sample.com/index?b=3'
578        result3 = update_url('http://sample.com/index', dict(b='3'))
579        assert result3 == 'http://sample.com/index?b=3'
580        result4 = update_url('http://sample.com/index?a=2', dict(b='3'))
581        assert result4 in (
582            'http://sample.com/index?a=2&b=3',
583            'http://sample.com/index?b=3&a=2')
Note: See TracBrowser for help on using the repository browser.