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