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

Last change on this file since 10599 was 10498, checked in by uli, 11 years ago

Make sure we put data in correct service_ticket columns in DB.

File size: 23.3 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        q = self.raw_app.db.query(ServiceTicket)
377        st = q.all()[0]
378        assert st.user == 'bird'
379        assert st.service == 'http://example.com/Login'
380        assert st.ticket.startswith('ST-')
381
382    def test_login_cred_acceptor_failed(self):
383        # 2.2.4: failed login yields a message
384        lt = create_login_ticket()
385        self.raw_app.db.add(lt)
386        lt_string = lt.ticket
387        resp = self.app.post('/login', dict(
388            username='bird', password='cat', lt=lt_string))
389        assert resp.status == '200 OK'
390        assert b'failed' in resp.body
391
392    def test_login_sso_no_service(self):
393        # we can initiate single-sign-on without service
394        resp1 = self.app.get('https://localhost/login')  # HTTPS required!
395        assert resp1.status == '200 OK'
396        assert 'cas-tgc' not in self.app.cookies
397        form = resp1.forms[0]
398        form.set('username', 'bird')
399        form.set('password', 'bebop')
400        resp2 = form.submit('AUTHENTICATE')
401        assert resp2.status == '200 OK'
402        # we got a secure cookie
403        assert 'cas-tgc' in self.app.cookies
404        # when we get the login page again, the cookie will replace creds.
405        resp3 = self.app.get('https://localhost/login')
406        assert b'You logged in already' in resp3.body
407
408    def test_login_sso_with_service(self):
409        resp1 = self.app.get(
410            'https://localhost/login?service=http%3A%2F%2Fservice.com%2F')
411        assert resp1.status == '200 OK'
412        assert 'cas-tgc' not in self.app.cookies
413        form = resp1.forms[0]
414        form.set('username', 'bird')
415        form.set('password', 'bebop')
416        resp2 = form.submit('AUTHENTICATE')
417        assert resp2.status == '303 See Other'
418        assert resp2.headers['Location'].startswith(
419            'http://service.com/?ticket=ST-')
420        # we got a secure cookie
421        assert 'cas-tgc' in self.app.cookies
422        resp3 = self.app.get(
423            'https://localhost/login?service=http%3A%2F%2Fservice.com%2F')
424        assert resp3.status == '303 See Other'
425        assert resp3.headers['Location'].startswith(
426            'http://service.com/?ticket=ST-')
427
428    def test_login_sso_with_service_additional_params1(self):
429        # we can get a service ticket also with a service providing
430        # get params
431        # this service url reads http://service.com/index.php?authCAS=CAS
432        service_url = 'http%3A%2F%2Fservice.com%2Findex.php%3FauthCAS%3DCAS'
433        resp1 = self.app.get(
434            'https://localhost/login?service=%s' % service_url)
435        assert resp1.status == '200 OK'
436        assert 'cas-tgc' not in self.app.cookies
437        form = resp1.forms[0]
438        form.set('username', 'bird')
439        form.set('password', 'bebop')
440        resp2 = form.submit('AUTHENTICATE')
441        assert resp2.status == '303 See Other'
442        location = resp2.headers['Location']
443        query_string = location.split('?', 1)[1]
444        query_params = dict(parse_qsl(query_string))
445        assert 'authCAS' in query_params.keys()
446        assert 'ticket' in query_params.keys()
447        assert len(query_params['ticket']) == 32
448
449
450class CASServerHelperTests(unittest.TestCase):
451
452    def setUp(self):
453        self.workdir = tempfile.mkdtemp()
454        self.db_file = os.path.join(self.workdir, 'mycas.db')
455        self.conn_string = 'sqlite:///%s' % self.db_file
456        self.db = DB(self.conn_string)
457
458    def tearDown(self):
459        shutil.rmtree(self.workdir)
460
461    def test_create_service_ticket(self):
462        # we can create service tickets
463        st = create_service_ticket(
464            user='bob', service='http://www.example.com')
465        assert isinstance(st, ServiceTicket)
466        # 3.1.1: service not part of ticket
467        assert 'example.com' not in st.ticket
468        # 3.1.1: ticket must start with 'ST-'
469        assert st.ticket.startswith('ST-')
470        # 3.1.1: min. ticket length clients must be able to process is 32
471        assert len(st.ticket) < 33
472        # 3.7: allowed character set == [a-zA-Z0-9\-]
473        assert RE_ALPHABET.match(st.ticket), (
474            'Ticket contains forbidden chars: %s' % st)
475        assert st.service == 'http://www.example.com'
476        assert st.user == 'bob'
477
478    def test_create_login_ticket(self):
479        # we can create login tickets
480        lt = create_login_ticket()
481        # 3.5.1: ticket should start with 'LT-'
482        assert lt.ticket.startswith('LT-')
483        # 3.7: allowed character set == [a-zA-Z0-9\-]
484        assert RE_ALPHABET.match(lt.ticket), (
485            'Ticket contains forbidden chars: %s' % lt)
486
487    def test_create_login_ticket_unique(self):
488        # 3.5.1: login tickets are unique (although not hard to guess)
489        ticket_num = 1000  # increase to test more thoroughly
490        lt_list = [create_login_ticket() for x in range(ticket_num)]
491        assert len(set(lt_list)) == ticket_num
492
493    def test_create_tgc_value(self):
494        # we can create ticket granting cookies
495        tgc = create_tgc_value()
496        assert isinstance(tgc, TicketGrantingCookie)
497        # 3.6.1: cookie value should start with 'TGC-'
498        assert tgc.value.startswith('TGC-')
499        # 3.7: allowed character set == [a-zA-Z0-9\-]
500        assert RE_ALPHABET.match(tgc.value), (
501            'Cookie value contains forbidden chars: %s' % tgc)
502
503    def test_check_login_ticket(self):
504        db = DB('sqlite:///')
505        lt = LoginTicket('LT-123456')
506        db.add(lt)
507        assert check_login_ticket(db, None) is False
508        assert check_login_ticket(db, 'LT-123456') is True
509        # the ticket will be removed after check
510        assert check_login_ticket(db, 'LT-123456') is False
511        assert check_login_ticket(db, 'LT-654321') is False
512
513    def test_set_session_cookie1(self):
514        # make sure we can add session cookies to responses
515        db = DB('sqlite:///')
516        resp = set_session_cookie(db, Response())
517        assert 'Set-Cookie' in resp.headers
518        cookie = resp.headers['Set-Cookie']
519        assert RE_COOKIE.match(cookie), (
520            'Cookie in unexpected format: %s' % cookie)
521        # the cookie is stored in database
522        value = cookie.split('=')[1].split(';')[0]
523        q = db.query(TicketGrantingCookie).filter(
524            TicketGrantingCookie.value == value)
525        assert len(list(q)) == 1
526
527    def test_check_session_cookie2(self):
528        db = DB('sqlite:///')
529        tgc = create_tgc_value()
530        db.add(tgc)
531        value = tgc.value
532        assert check_session_cookie(db, value) == tgc
533        assert check_session_cookie(db, 'foo') is None
534        assert check_session_cookie(db, b'foo') is None
535        assert check_session_cookie(db, None) is None
536        value2 = value.encode('utf-8')
537        assert check_session_cookie(db, value2) == tgc
538
539    def test_get_template(self):
540        # we can load templates
541        assert get_template('not-existing-template') is None
542        assert get_template('login.html') is not None
543
544    def test_delete_session_cookie(self):
545        # we can unset cookies
546        db = DB('sqlite:///')
547        tgc = create_tgc_value()
548        db.add(tgc)
549        value = tgc.value
550        resp = delete_session_cookie(db, Response(), old_value=value)
551        assert 'Set-Cookie' in resp.headers
552        cookie = resp.headers['Set-Cookie']
553        assert RE_COOKIE_DEL.match(cookie), (
554            'Cookie in unexpected format: %s' % cookie)
555        # the cookie values was deleted from database
556        q = db.query(TicketGrantingCookie).filter(
557            TicketGrantingCookie.value == value)
558        assert len(list(q)) == 0
559
560    def test_check_service_ticket(self):
561        db = DB('sqlite:///')
562        st = ServiceTicket(
563            'ST-123456', 'someuser', 'http://myservice.com', True)
564        db.add(st)
565        assert check_service_ticket(db, None, 'foo') is None
566        assert check_service_ticket(db, 'foo', None) is None
567        assert check_service_ticket(db, 'ST-123456', 'foo') is None
568        assert check_service_ticket(db, 'foo', 'http://myservice.com') is None
569        result = check_service_ticket(db, 'ST-123456', 'http://myservice.com')
570        assert isinstance(result, ServiceTicket)
571        assert result.user == 'someuser'
572        assert check_service_ticket(
573            db,  'ST-123456', 'http://myservice.com', True) is None
574        assert check_service_ticket(
575            db,  'ST-123456', 'http://myservice.com', False) is not None
576
577    def test_update_url(self):
578        # we can create valid new urls with query string params updated
579        result1 = update_url('http://sample.com/index?a=1&b=2', dict(b='3'))
580        assert result1 in (
581            'http://sample.com/index?a=1&b=3',
582            'http://sample.com/index?b=3&a=1')
583        result2 = update_url('http://sample.com/index?b=2', dict(b='3'))
584        assert result2 == 'http://sample.com/index?b=3'
585        result3 = update_url('http://sample.com/index', dict(b='3'))
586        assert result3 == 'http://sample.com/index?b=3'
587        result4 = update_url('http://sample.com/index?a=2', dict(b='3'))
588        assert result4 in (
589            'http://sample.com/index?a=2&b=3',
590            'http://sample.com/index?b=3&a=2')
Note: See TracBrowser for help on using the repository browser.