705eef910a6f0a0c93ab3f4807c9047e39aa38ec
[django-cas-provider.git] / cas_provider / tests.py
1 import StringIO
2 import urllib2
3 from xml import etree
4 from xml.etree import ElementTree
5 import cas_provider
6 from cas_provider.attribute_formatters import CAS, NSMAP
7 from cas_provider.models import ServiceTicket
8 from cas_provider.views import _cas2_sucess_response, INVALID_TICKET, _cas2_error_response, generate_proxy_granting_ticket
9 from django.contrib.auth.models import User, UserManager
10 from django.core.urlresolvers import reverse
11 from django.test import TestCase
12 from urlparse import urlparse, parse_qsl, parse_qs
13 from django.conf import settings
14
15
16
17
18 dummy_urlopen_url = None
19
20
21 def dummy_urlopen(url):
22     cas_provider.tests.dummy_urlopen_url = url
23     pass
24
25 class ViewsTest(TestCase):
26
27     fixtures = ['cas_users', ]
28
29
30
31     def setUp(self):
32         self.service = 'http://example.com/'
33
34
35     def test_successful_login_with_proxy(self):
36         urllib2.urlopen = dummy_urlopen # monkey patching urllib2.urlopen so that the testcase doesnt really opens a url
37         proxyTarget = "http://my.sweet.service"
38
39         response = self._login_user('root', '123')
40         response = self._validate_cas2(response, True, proxyTarget )
41
42         # Test: I'm acting as the service that will call another service
43         # Step 1: Get the proxy granting ticket
44         responseXml = ElementTree.parse(StringIO.StringIO(response.content))
45         auth_success = responseXml.find(CAS + 'authenticationSuccess', namespaces=NSMAP)
46         pgt = auth_success.find(CAS + "proxyGrantingTicket", namespaces=NSMAP)
47         user = auth_success.find(CAS + "user", namespaces=NSMAP)
48         self.assertEqual('root', user.text)
49         self.assertIsNotNone(pgt.text)
50         self.assertTrue(pgt.text.startswith('PGTIOU'))
51
52         #Step 2: Get the actual proxy ticket
53         proxyTicketResponse = self.client.get(reverse('proxy'), {'targetService': proxyTarget, 'pgt': pgt.text}, follow=False)
54         proxyTicketResponseXml = ElementTree.parse(StringIO.StringIO(proxyTicketResponse.content))
55         self.assertIsNotNone(proxyTicketResponseXml.find(CAS + "proxySuccess", namespaces=NSMAP))
56         self.assertIsNotNone(proxyTicketResponseXml.find(CAS + "proxySuccess/cas:proxyTicket", namespaces=NSMAP))
57         proxyTicket = proxyTicketResponseXml.find(CAS + "proxySuccess/cas:proxyTicket", namespaces=NSMAP);
58
59         #Step 3: I have the proxy ticket I can talk to some other backend service as the currently logged in user!
60         proxyValidateResponse = self.client.get(reverse('cas_proxy_validate'), {'ticket': proxyTicket.text, 'service': proxyTarget})
61         proxyValidateResponseXml = ElementTree.parse(StringIO.StringIO(proxyValidateResponse.content))
62
63         auth_success_2 = proxyValidateResponseXml.find(CAS + 'authenticationSuccess', namespaces=NSMAP)
64         user_2 = auth_success.find(CAS + "user", namespaces=NSMAP)
65         proxies_1  = auth_success_2.find(CAS + "proxies")
66         self.assertIsNone(proxies_1) # there are no proxies. I am issued by a Service Ticket
67         
68         self.assertEqual(user.text, user_2.text)
69
70
71     def test_successful_proxy_chaining(self):
72         urllib2.urlopen = dummy_urlopen # monkey patching urllib2.urlopen so that the testcase doesnt really opens a url
73         proxyTarget_1 = "http://my.sweet.service_1"
74         proxyTarget_2 = "http://my.sweet.service_2"
75
76         response = self._login_user('root', '123')
77         response = self._validate_cas2(response, True, proxyTarget_1 )
78
79         # Test: I'm acting as the service that will call another service
80         # Step 1: Get the proxy granting ticket
81         responseXml = ElementTree.parse(StringIO.StringIO(response.content))
82         auth_success_1 = responseXml.find(CAS + 'authenticationSuccess', namespaces=NSMAP)
83         pgt_1 = auth_success_1.find(CAS + "proxyGrantingTicket", namespaces=NSMAP)
84         user_1 = auth_success_1.find(CAS + "user", namespaces=NSMAP)
85         self.assertEqual('root', user_1.text)
86         self.assertIsNotNone(pgt_1.text)
87         self.assertTrue(pgt_1.text.startswith('PGTIOU'))
88
89         #Step 2: Get the actual proxy ticket
90         proxyTicketResponse_1 = self.client.get(reverse('proxy'), {'targetService': proxyTarget_1, 'pgt': pgt_1.text}, follow=False)
91         proxyTicketResponseXml_1 = ElementTree.parse(StringIO.StringIO(proxyTicketResponse_1.content))
92         self.assertIsNotNone(proxyTicketResponseXml_1.find(CAS + "proxySuccess", namespaces=NSMAP))
93         self.assertIsNotNone(proxyTicketResponseXml_1.find(CAS + "proxySuccess/cas:proxyTicket", namespaces=NSMAP))
94         proxyTicket_1 = proxyTicketResponseXml_1.find(CAS + "proxySuccess/cas:proxyTicket", namespaces=NSMAP);
95
96         #Step 3: I'm backend service 1 - I have the proxy ticket - I want to talk to back service 2
97         #
98         proxyValidateResponse_1 = self.client.get(reverse('cas_proxy_validate'), {'ticket': proxyTicket_1.text, 'service': proxyTarget_1, 'pgtUrl': proxyTarget_2})
99         proxyValidateResponseXml_1 = ElementTree.parse(StringIO.StringIO(proxyValidateResponse_1.content))
100
101         auth_success_2 = proxyValidateResponseXml_1.find(CAS + 'authenticationSuccess', namespaces=NSMAP)
102         user_2 = auth_success_2.find(CAS + "user", namespaces=NSMAP)
103
104         proxies_1  = auth_success_2.find(CAS + "proxies")
105         self.assertIsNone(proxies_1) # there are no proxies. I am issued by a Service Ticket
106         self.assertIsNotNone(auth_success_2)
107         self.assertEqual('root', user_2.text)
108
109         pgt_2 = auth_success_2.find(CAS + "proxyGrantingTicket", namespaces=NSMAP)
110         user = auth_success_2.find(CAS + "user", namespaces=NSMAP)
111         self.assertEqual('root', user.text)
112         self.assertIsNotNone(pgt_2.text)
113         self.assertTrue(pgt_2.text.startswith('PGTIOU'))
114
115         #Step 4: Get the second proxy ticket
116         proxyTicketResponse_2 = self.client.get(reverse('proxy'), {'targetService': proxyTarget_2, 'pgt': pgt_2.text})
117         proxyTicketResponseXml_2 = ElementTree.parse(StringIO.StringIO(proxyTicketResponse_2.content))
118         self.assertIsNotNone(proxyTicketResponseXml_2.find(CAS + "proxySuccess", namespaces=NSMAP))
119         self.assertIsNotNone(proxyTicketResponseXml_2.find(CAS + "proxySuccess/cas:proxyTicket", namespaces=NSMAP))
120         proxyTicket_2 = proxyTicketResponseXml_2.find(CAS + "proxySuccess/cas:proxyTicket", namespaces=NSMAP)
121
122         proxyValidateResponse_3 = self.client.get(reverse('cas_proxy_validate'), {'ticket': proxyTicket_2.text, 'service': proxyTarget_2, 'pgtUrl': None})
123         proxyValidateResponseXml_3 = ElementTree.parse(StringIO.StringIO(proxyValidateResponse_3.content))
124
125         auth_success_3 = proxyValidateResponseXml_3.find(CAS + 'authenticationSuccess', namespaces=NSMAP)
126         user_3 = auth_success_3.find(CAS + "user", namespaces=NSMAP)
127
128         proxies_3  = auth_success_3.find(CAS + "proxies")
129         self.assertIsNotNone(proxies_3) # there should be a proxy. I am issued by a Proxy Ticket
130         proxy_3 = proxies_3.find(CAS + "proxy", namespaces=NSMAP)
131         self.assertEqual(proxyTarget_1, proxy_3.text )
132
133         self.assertIsNotNone(auth_success_2)
134         self.assertEqual('root', user_3.text)
135
136
137
138     def test_successful_service_not_matching_in_request_to_proxy(self):
139         urllib2.urlopen = dummy_urlopen # monkey patching urllib2.urlopen so that the testcase doesnt really opens a url
140         proxyTarget_1 = "http://my.sweet.service"
141         proxyTarget_2 = "http://my.malicious.service"
142
143         response = self._login_user('root', '123')
144         response = self._validate_cas2(response, True, proxyTarget_1 )
145
146         # Test: I'm acting as the service that will call another service
147         # Step 1: Get the proxy granting ticket
148         responseXml = ElementTree.parse(StringIO.StringIO(response.content))
149         auth_success = responseXml.find(CAS + 'authenticationSuccess', namespaces=NSMAP)
150         pgt = auth_success.find(CAS + "proxyGrantingTicket", namespaces=NSMAP)
151         user = auth_success.find(CAS + "user", namespaces=NSMAP)
152         self.assertEqual('root', user.text)
153         self.assertIsNotNone(pgt.text)
154         self.assertTrue(pgt.text.startswith('PGTIOU'))
155
156         #Step 2: Get the actual proxy ticket
157         proxyTicketResponse = self.client.get(reverse('proxy'), {'targetService': proxyTarget_2, 'pgt': pgt.text}, follow=False)
158         proxyTicketResponseXml = ElementTree.parse(StringIO.StringIO(proxyTicketResponse.content))
159         self.assertIsNotNone(proxyTicketResponseXml.find(CAS + "authenticationFailure", namespaces=NSMAP))
160
161
162     def test_succeessful_login(self):
163         response = self._login_user('root', '123')
164         self._validate_cas1(response, True)
165
166         response = self.client.get(reverse('cas_login'), {'service': self.service}, follow=False)
167         self.assertEqual(response.status_code, 302)
168         self.assertTrue(response['location'].startswith('%s?ticket=' % self.service))
169
170         response = self.client.get(reverse('cas_login'), follow=False)
171         self.assertEqual(response.status_code, 302)
172         self.assertTrue(response['location'].startswith('http://testserver/'))
173
174         response = self.client.get(response['location'], follow=False)
175         self.assertIn(response.status_code, [302, 200])
176
177         response = self.client.get(reverse('cas_login'), {'service': self.service, 'warn': True}, follow=False)
178         self.assertEqual(response.status_code, 200)
179         self.assertTemplateUsed(response, 'cas/warn.html')
180
181
182     def _cas_logout(self):
183         response = self.client.get(reverse('cas_logout'), follow=False)
184         self.assertEqual(response.status_code, 200)
185
186
187     def test_logout(self):
188         response = self._login_user('root', '123')
189         self._validate_cas1(response, True)
190
191         self._cas_logout()
192
193         response = self.client.get(reverse('cas_login'), follow=False)
194         self.assertEqual(response.status_code, 200)
195         self.assertEqual(response.context['user'].is_anonymous(), True)
196
197
198     def test_broken_pwd(self):
199         self._fail_login('root', '321')
200
201     def test_broken_username(self):
202         self._fail_login('notroot', '123')
203
204     def test_nonactive_user_login(self):
205         self._fail_login('nonactive', '123')
206
207     def test_cas2_success_validate(self):
208         response = self._login_user('root', '123')
209         response = self._validate_cas2(response, True)
210         user = User.objects.get(username=self.username)
211         self.assertEqual(response.content, _cas2_sucess_response(user).content)
212
213     def test_cas2_custom_attrs(self):
214         settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK = cas_mapping
215         response = self._login_user('editor', '123')
216
217         response = self._validate_cas2(response, True)
218         self.assertEqual(response.content, '''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">'''
219                                            '''<cas:authenticationSuccess>'''
220                                            '''<cas:user>editor</cas:user>'''
221                                            '''<cas:attributes>'''
222                                            '''<cas:attraStyle>Jasig</cas:attraStyle>'''
223                                            '''<cas:group>editor</cas:group>'''
224                                            '''<cas:is_staff>True</cas:is_staff>'''
225                                            '''<cas:is_active>True</cas:is_active>'''
226                                            '''<cas:email>editor@exapmle.com</cas:email>'''
227                                            '''</cas:attributes>'''
228                                            '''</cas:authenticationSuccess>'''
229                                            '''</cas:serviceResponse>''')
230
231         self._cas_logout()
232         response = self._login_user('editor', '123')
233         settings.CAS_CUSTOM_ATTRIBUTES_FORMATER = 'cas_provider.attribute_formatters.ruby_cas'
234         response = self._validate_cas2(response, True)
235         self.assertEqual(response.content, '''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">'''
236                                            '''<cas:authenticationSuccess>'''
237                                            '''<cas:user>editor</cas:user>'''
238                                            '''<cas:attraStyle>RubyCAS</cas:attraStyle>'''
239                                            '''<cas:group>editor</cas:group>'''
240                                            '''<cas:is_staff>True</cas:is_staff>'''
241                                            '''<cas:is_active>True</cas:is_active>'''
242                                            '''<cas:email>editor@exapmle.com</cas:email>'''
243                                            '''</cas:authenticationSuccess>'''
244                                            '''</cas:serviceResponse>''')
245
246         self._cas_logout()
247         response = self._login_user('editor', '123')
248         settings.CAS_CUSTOM_ATTRIBUTES_FORMATER = 'cas_provider.attribute_formatters.name_value'
249         response = self._validate_cas2(response, True)
250         self.assertEqual(response.content, '''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">'''
251                                            '''<cas:authenticationSuccess>'''
252                                            '''<cas:user>editor</cas:user>'''
253                                            '''<cas:attribute name="attraStyle" value="Name-Value"/>'''
254                                            '''<cas:attribute name="group" value="editor"/>'''
255                                            '''<cas:attribute name="is_staff" value="True"/>'''
256                                            '''<cas:attribute name="is_active" value="True"/>'''
257                                            '''<cas:attribute name="email" value="editor@exapmle.com"/>'''
258                                            '''</cas:authenticationSuccess>'''
259                                            '''</cas:serviceResponse>''')
260
261
262     def test_cas2_fail_validate(self):
263         for user, pwd in (('root', '321'), ('notroot', '123'), ('nonactive', '123')):
264             response = self._login_user(user, pwd)
265             self._validate_cas2(response, False)
266
267
268     def test_generate_proxy_granting_ticket(self):
269         urllib2.urlopen = dummy_urlopen # monkey patching urllib2.urlopen so that the testcase doesnt really opens a url
270         url = 'http://my.call.back/callhere'
271
272         user = User.objects.get(username = 'root')
273         st = ServiceTicket.objects.create(user = user )
274         pgt = generate_proxy_granting_ticket(url, st)
275         self.assertIsNotNone(pgt)
276
277         calledUrl = cas_provider.tests.dummy_urlopen_url
278         parsedUrl = urlparse(calledUrl)
279         params = parse_qs(parsedUrl.query)
280         self.assertIsNotNone(params['pgtId'])
281         self.assertIsNotNone(params['pgtIou'])
282
283
284
285     def _fail_login(self, username, password):
286         response = self._login_user(username, password)
287         self._validate_cas1(response, False)
288
289         response = self.client.get(reverse('cas_login'), {'service': self.service}, follow=False)
290         self.assertEqual(response.status_code, 200)
291         response = self.client.get(reverse('cas_login'), follow=False)
292         self.assertEqual(response.status_code, 200)
293
294
295
296     def _login_user(self, username, password):
297         self.username = username
298         response = self.client.get(reverse('cas_login'), {'service': self.service})
299         self.assertEqual(response.status_code, 200)
300         self.assertTemplateUsed(response, 'cas/login.html')
301         form = response.context['form']
302         service = form['service'].value()
303         return self.client.post(reverse('cas_login'), {
304             'username': username,
305             'password': password,
306             'lt': form['lt'].value(),
307             'service': service
308         }, follow=False)
309
310
311     def _validate_cas1(self, response, is_correct=True):
312         if is_correct:
313             self.assertEqual(response.status_code, 302)
314             self.assertTrue(response.has_header('location'))
315             location = urlparse(response['location'])
316             ticket = location.query.split('=')[1]
317
318             response = self.client.get(reverse('cas_validate'), {'ticket': ticket, 'service': self.service}, follow=False)
319             self.assertEqual(response.status_code, 200)
320             self.assertEqual(unicode(response.content), u'yes\n%s\n' % self.username)
321         else:
322             self.assertEqual(response.status_code, 200)
323             self.assertEqual(len(response.context['form'].errors), 1)
324
325             response = self.client.get(reverse('cas_validate'), {'ticket': 'ST-12312312312312312312312', 'service': self.service}, follow=False)
326             self.assertEqual(response.status_code, 200)
327             self.assertEqual(response.content, u'no\n\n')
328
329
330     def _validate_cas2(self, response, is_correct=True, pgtUrl = None):
331         if is_correct:
332             self.assertEqual(response.status_code, 302)
333             self.assertTrue(response.has_header('location'))
334             location = urlparse(response['location'])
335             ticket = location.query.split('=')[1]
336             if pgtUrl:
337                 response = self.client.get(reverse('cas_service_validate'), {'ticket': ticket, 'service': self.service, 'pgtUrl': pgtUrl}, follow=False)
338             else:
339                 response = self.client.get(reverse('cas_service_validate'), {'ticket': ticket, 'service': self.service}, follow=False)
340             self.assertEqual(response.status_code, 200)
341         else:
342             self.assertEqual(response.status_code, 200)
343             self.assertEqual(len(response.context['form'].errors), 1)
344
345             response = self.client.get(reverse('cas_service_validate'), {'ticket': 'ST-12312312312312312312312', 'service': self.service}, follow=False)
346             self.assertEqual(response.status_code, 200)
347             self.assertEqual(response.content, _cas2_error_response(INVALID_TICKET).content)
348         return response
349
350 class ModelsTestCase(TestCase):
351
352     fixtures = ['cas_users.json', ]
353
354     def setUp(self):
355         self.user = User.objects.get(username='root')
356
357     def test_redirects(self):
358         ticket = ServiceTicket.objects.create(service='http://example.com', user=self.user)
359         self.assertEqual(ticket.get_redirect_url(), '%(service)s?ticket=%(ticket)s' % ticket.__dict__)
360
361
362 def cas_mapping(user):
363     return {
364         'is_staff': unicode(user.is_staff),
365         'is_active': unicode(user.is_active),
366         'email': user.email,
367         'group': [g.name for g in user.groups.all()]
368     }