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