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