1 from __future__ import unicode_literals
2 from io import StringIO
4 from xml.etree import ElementTree
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
16 from urllib.parse import urlparse, parse_qsl, parse_qs
17 from urllib.request import install_opener
19 from urlparse import urlparse, parse_qsl, parse_qs
20 from urllib2 import install_opener
25 class DummyOpener(object):
29 def open(url, *args, **kwargs):
33 class ViewsTest(TestCase):
35 fixtures = ['cas_users', ]
40 self.service = 'http://example.com/'
43 def test_successful_login_with_proxy(self):
44 install_opener(DummyOpener) # Don't really open any URLs
45 proxyTarget = "http://my.sweet.service"
47 response = self._login_user('root', '123')
48 response = self._validate_cas2(response, True, proxyTarget )
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'))
60 pgtId = parse_qs(urlparse(DummyOpener.url).query)['pgtId']
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);
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')))
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
78 self.assertEqual(user.text, user_2.text)
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"
86 response = self._login_user('root', '123')
87 response = self._validate_cas2(response, True, proxyTarget_1 )
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'))
99 pgtId_1 = parse_qs(urlparse(DummyOpener.url).query)['pgtId']
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);
108 #Step 3: I'm backend service 1 - I have the proxy ticket - I want to talk to back service 2
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')))
113 auth_success_2 = proxyValidateResponseXml_1.find(CAS + 'authenticationSuccess', namespaces=NSMAP)
114 user_2 = auth_success_2.find(CAS + "user", namespaces=NSMAP)
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)
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'))
127 pgtId_2 = parse_qs(urlparse(DummyOpener.url).query)['pgtId']
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", 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)
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')))
139 auth_success_3 = proxyValidateResponseXml_3.find(CAS + 'authenticationSuccess', namespaces=NSMAP)
140 user_3 = auth_success_3.find(CAS + "user", namespaces=NSMAP)
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 )
147 self.assertIsNotNone(auth_success_2)
148 self.assertEqual('root', user_3.text)
153 def test_succeessful_login(self):
154 response = self._login_user('root', '123')
155 self._validate_cas1(response, True)
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))
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/'))
165 response = self.client.get(response['location'], follow=False)
166 self.assertIn(response.status_code, [302, 200])
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')
173 def _cas_logout(self):
174 response = self.client.get(reverse('cas_logout'), follow=False)
175 self.assertEqual(response.status_code, 200)
178 def test_logout(self):
179 response = self._login_user('root', '123')
180 self._validate_cas1(response, True)
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)
189 def test_broken_pwd(self):
190 self._fail_login('root', '321')
192 def test_broken_username(self):
193 self._fail_login('notroot', '123')
195 def test_nonactive_user_login(self):
196 self._fail_login('nonactive', '123')
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)
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)
210 response2 = self._validate_cas2(response, True)
211 self.assertEqual(response2.content, _cas2_error_response(INVALID_TICKET).content)
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)
220 response2 = self._validate_cas2(response, True, proxyTarget)
221 self.assertEqual(response2.content, _cas2_error_response(INVALID_TICKET).content)
223 def test_cas2_custom_attrs(self):
224 cas_collect_custom_attributes.connect(cas_mapping)
225 response = self._login_user('editor', '123')
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>''')
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>''')
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>''')
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)
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'
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)
291 calledUrl = DummyOpener.url
292 parsedUrl = urlparse(calledUrl)
293 params = parse_qs(parsedUrl.query)
294 self.assertIsNotNone(params['pgtId'])
295 self.assertIsNotNone(params['pgtIou'])
299 def _fail_login(self, username, password):
300 response = self._login_user(username, password)
301 self._validate_cas1(response, False)
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)
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,
324 def _validate_cas1(self, response, is_correct=True):
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]
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)
335 self.assertEqual(response.status_code, 200)
336 self.assertEqual(len(response.context['errors']), 1)
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')
343 def _validate_cas2(self, response, is_correct=True, pgtUrl = None):
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]
350 response = self.client.get(reverse('cas_service_validate'), {'ticket': ticket, 'service': self.service, 'pgtUrl': pgtUrl}, follow=False)
352 response = self.client.get(reverse('cas_service_validate'), {'ticket': ticket, 'service': self.service}, follow=False)
353 self.assertEqual(response.status_code, 200)
355 self.assertEqual(response.status_code, 200)
356 self.assertEqual(len(response.context['errors']), 1)
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)
363 class ModelsTestCase(TestCase):
365 fixtures = ['cas_users.json', ]
368 self.user = User.objects.get(username='root')
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__)
375 def cas_mapping(sender, user, **kwargs):
377 'is_staff': str(user.is_staff),
378 'is_active': str(user.is_active),
380 'group': [g.name for g in user.groups.all()]