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