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