removing default for foreign key field because it throws an error with mysql.
[django-cas-provider.git] / cas_provider_examples / simple / 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
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')
54         pgt = auth_success.find(CAS + "proxyGrantingTicket")
55         user = auth_success.find(CAS + "user")
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"))
66         self.assertIsNotNone(proxyTicketResponseXml.find(CAS + "proxySuccess/" + CAS + "proxyTicket"))
67         proxyTicket = proxyTicketResponseXml.find(CAS + "proxySuccess/" + CAS + "proxyTicket");
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')
74         user_2 = auth_success.find(CAS + "user")
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')
93         pgt_1 = auth_success_1.find(CAS + "proxyGrantingTicket")
94         user_1 = auth_success_1.find(CAS + "user")
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"))
105         self.assertIsNotNone(proxyTicketResponseXml_1.find(CAS + "proxySuccess/" + CAS + "proxyTicket"))
106         proxyTicket_1 = proxyTicketResponseXml_1.find(CAS + "proxySuccess/" + CAS +"proxyTicket");
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.decode('utf-8')))
112
113         auth_success_2 = proxyValidateResponseXml_1.find(CAS + 'authenticationSuccess')
114         user_2 = auth_success_2.find(CAS + "user")
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")
122         user = auth_success_2.find(CAS + "user")
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.decode('utf-8')))
132         self.assertIsNotNone(proxyTicketResponseXml_2.find(CAS + "proxySuccess"))
133         self.assertIsNotNone(proxyTicketResponseXml_2.find(CAS + "proxySuccess/" + CAS + "proxyTicket"))
134         proxyTicket_2 = proxyTicketResponseXml_2.find(CAS + "proxySuccess/" + CAS + "proxyTicket")
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.decode('utf-8')))
138
139         auth_success_3 = proxyValidateResponseXml_3.find(CAS + 'authenticationSuccess')
140         user_3 = auth_success_3.find(CAS + "user")
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")
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_validate_twice(self):
205         response = self._login_user('root', '123')
206         response2 = self._validate_cas2(response, True)
207         user = User.objects.get(username=self.username)
208         self.assertEqual(response2.content, _cas2_sucess_response(user).content)
209
210         response2 = self._validate_cas2(response, True)
211         self.assertEqual(response2.content, _cas2_error_response(INVALID_TICKET).content)
212
213     def test_cas2_validate_twice_with_pgt(self):
214         proxyTarget = "http://my.sweet.service_1"
215         response = self._login_user('root', '123')
216         response2 = self._validate_cas2(response, True, proxyTarget)
217         user = User.objects.get(username=self.username)
218         self.assertEqual(response2.content, _cas2_sucess_response(user).content)
219
220         response2 = self._validate_cas2(response, True, proxyTarget)
221         self.assertEqual(response2.content, _cas2_error_response(INVALID_TICKET).content)
222
223     def test_cas2_custom_attrs(self):
224         cas_collect_custom_attributes.connect(cas_mapping)
225         response = self._login_user('editor', '123')
226         self.maxDiff=None
227
228         response = self._validate_cas2(response, True)
229         self.assertEqual(response.content.decode('utf-8'),
230                                            '''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">'''
231                                            '''<cas:authenticationSuccess>'''
232                                            '''<cas:user>editor</cas:user>'''
233                                            '''<cas:attributes>'''
234                                            '''<cas:attraStyle>Jasig</cas:attraStyle>'''
235                                            '''<cas:email>editor@exapmle.com</cas:email>'''
236                                            '''<cas:group>editor</cas:group>'''
237                                            '''<cas:is_active>True</cas:is_active>'''
238                                            '''<cas:is_staff>True</cas:is_staff>'''
239                                            '''</cas:attributes>'''
240                                            '''</cas:authenticationSuccess>'''
241                                            '''</cas:serviceResponse>''')
242
243         self._cas_logout()
244         response = self._login_user('editor', '123')
245         settings.CAS_CUSTOM_ATTRIBUTES_FORMATER = 'cas_provider.attribute_formatters.ruby_cas'
246         response = self._validate_cas2(response, True)
247         self.assertEqual(response.content.decode('utf-8'),
248                                            '''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">'''
249                                            '''<cas:authenticationSuccess>'''
250                                            '''<cas:user>editor</cas:user>'''
251                                            '''<cas:attraStyle>RubyCAS</cas:attraStyle>'''
252                                            '''<cas:email>editor@exapmle.com</cas:email>'''
253                                            '''<cas:group>editor</cas:group>'''
254                                            '''<cas:is_active>True</cas:is_active>'''
255                                            '''<cas:is_staff>True</cas:is_staff>'''
256                                            '''</cas:authenticationSuccess>'''
257                                            '''</cas:serviceResponse>''')
258
259         self._cas_logout()
260         response = self._login_user('editor', '123')
261         settings.CAS_CUSTOM_ATTRIBUTES_FORMATER = 'cas_provider.attribute_formatters.name_value'
262         response = self._validate_cas2(response, True)
263         self.assertEqual(response.content.decode('utf-8'),
264                                            '''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">'''
265                                            '''<cas:authenticationSuccess>'''
266                                            '''<cas:user>editor</cas:user>'''
267                                            '''<cas:attribute name="attraStyle" value="Name-Value"/>'''
268                                            '''<cas:attribute name="email" value="editor@exapmle.com"/>'''
269                                            '''<cas:attribute name="group" value="editor"/>'''
270                                            '''<cas:attribute name="is_active" value="True"/>'''
271                                            '''<cas:attribute name="is_staff" value="True"/>'''
272                                            '''</cas:authenticationSuccess>'''
273                                            '''</cas:serviceResponse>''')
274
275
276     def test_cas2_fail_validate(self):
277         for user, pwd in (('root', '321'), ('notroot', '123'), ('nonactive', '123')):
278             response = self._login_user(user, pwd)
279             self._validate_cas2(response, False)
280
281
282     def test_generate_proxy_granting_ticket(self):
283         install_opener(DummyOpener) # Don't really open any URLs
284         url = 'http://my.call.back/callhere'
285
286         user = User.objects.get(username = 'root')
287         st = ServiceTicket.objects.create(user = user )
288         pgt = generate_proxy_granting_ticket(url, st)
289         self.assertIsNotNone(pgt)
290
291         calledUrl = DummyOpener.url
292         parsedUrl = urlparse(calledUrl)
293         params = parse_qs(parsedUrl.query)
294         self.assertIsNotNone(params['pgtId'])
295         self.assertIsNotNone(params['pgtIou'])
296
297
298
299     def _fail_login(self, username, password):
300         response = self._login_user(username, password)
301         self._validate_cas1(response, False)
302
303         response = self.client.get(reverse('cas_login'), {'service': self.service}, follow=False)
304         self.assertEqual(response.status_code, 200)
305         response = self.client.get(reverse('cas_login'), follow=False)
306         self.assertEqual(response.status_code, 200)
307
308
309
310     def _login_user(self, username, password):
311         self.username = username
312         response = self.client.get(reverse('cas_login'), {'service': self.service})
313         self.assertEqual(response.status_code, 200)
314         self.assertTemplateUsed(response, 'cas/login.html')
315         form = response.context['form']
316         service = form['service'].value()
317         return self.client.post(reverse('cas_login'), {
318             'username': username,
319             'password': password,
320             'service': service
321         }, follow=False)
322
323
324     def _validate_cas1(self, response, is_correct=True):
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
331             response = self.client.get(reverse('cas_validate'), {'ticket': ticket, 'service': self.service}, follow=False)
332             self.assertEqual(response.status_code, 200)
333             self.assertEqual(response.content.decode('utf-8'), 'yes\n%s\n' % self.username)
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_validate'), {'ticket': 'ST-12312312312312312312312', 'service': self.service}, follow=False)
339             self.assertEqual(response.status_code, 200)
340             self.assertEqual(response.content.decode('utf-8'), 'no\n\n')
341
342
343     def _validate_cas2(self, response, is_correct=True, pgtUrl = None):
344         if is_correct:
345             self.assertEqual(response.status_code, 302)
346             self.assertTrue(response.has_header('location'))
347             location = urlparse(response['location'])
348             ticket = location.query.split('=')[1]
349             if pgtUrl:
350                 response = self.client.get(reverse('cas_service_validate'), {'ticket': ticket, 'service': self.service, 'pgtUrl': pgtUrl}, follow=False)
351             else:
352                 response = self.client.get(reverse('cas_service_validate'), {'ticket': ticket, 'service': self.service}, follow=False)
353             self.assertEqual(response.status_code, 200)
354         else:
355             self.assertEqual(response.status_code, 200)
356             self.assertEqual(len(response.context['errors']), 1)
357
358             response = self.client.get(reverse('cas_service_validate'), {'ticket': 'ST-12312312312312312312312', 'service': self.service}, follow=False)
359             self.assertEqual(response.status_code, 200)
360             self.assertEqual(response.content, _cas2_error_response(INVALID_TICKET).content)
361         return response
362
363 class ModelsTestCase(TestCase):
364
365     fixtures = ['cas_users.json', ]
366
367     def setUp(self):
368         self.user = User.objects.get(username='root')
369
370     def test_redirects(self):
371         ticket = ServiceTicket.objects.create(service='http://example.com', user=self.user)
372         self.assertEqual(ticket.get_redirect_url(), '%(service)s?ticket=%(ticket)s' % ticket.__dict__)
373
374
375 def cas_mapping(sender, user, **kwargs):
376     return {
377         'is_staff': str(user.is_staff),
378         'is_active': str(user.is_active),
379         'email': user.email,
380         'group': [g.name for g in user.groups.all()]
381     }