Debian Codegraph @

cas_server/tests/mixin.py

raw
1 # -*- coding: utf-8 -*-
2 # This program is distributed in the hope that it will be useful, but WITHOUT
3 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4 # FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
5 # more details.
6 #
7 # You should have received a copy of the GNU General Public License version 3
8 # along with this program; if not, write to the Free Software Foundation, Inc., 51
9 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
10 #
11 # (c) 2016-2019 Valentin Samir
12 """Some mixin classes for tests"""
13 from cas_server.default_settings import settings
14 from django.utils import timezone
15
16 import re
17 from lxml import etree
18 from datetime import timedelta
19
20 from cas_server import models
21 from cas_server.tests.utils import get_auth_client
22
23
24 class BaseServicePattern(object):
25 """Mixing for setting up service pattern for testing"""
26 @classmethod
27 def setup_service_patterns(cls, proxy=False):
28 """setting up service pattern"""
29 # For general purpose testing
30 cls.service = "https://www.example.com"
31 cls.service_pattern = models.ServicePattern.objects.create(
32 name="example",
33 pattern=r"^https://www\.example\.com(/.*)?$",
34 proxy=proxy,
35 )
36 models.ReplaceAttributName.objects.create(name="*", service_pattern=cls.service_pattern)
37
38 # For testing the restrict_users attributes
39 cls.service_restrict_user_fail = "https://restrict_user_fail.example.com"
40 cls.service_pattern_restrict_user_fail = models.ServicePattern.objects.create(
41 name="restrict_user_fail",
42 pattern=r"^https://restrict_user_fail\.example\.com(/.*)?$",
43 restrict_users=True,
44 proxy=proxy,
45 )
46 cls.service_restrict_user_success = "https://restrict_user_success.example.com"
47 cls.service_pattern_restrict_user_success = models.ServicePattern.objects.create(
48 name="restrict_user_success",
49 pattern=r"^https://restrict_user_success\.example\.com(/.*)?$",
50 restrict_users=True,
51 proxy=proxy,
52 )
53 models.Username.objects.create(
54 value=settings.CAS_TEST_USER,
55 service_pattern=cls.service_pattern_restrict_user_success
56 )
57
58 # For testing the user attributes filtering conditions
59 cls.service_filter_fail = "https://filter_fail.example.com"
60 cls.service_pattern_filter_fail = models.ServicePattern.objects.create(
61 name="filter_fail",
62 pattern=r"^https://filter_fail\.example\.com(/.*)?$",
63 proxy=proxy,
64 )
65 models.FilterAttributValue.objects.create(
66 attribut="right",
67 pattern="^admin$",
68 service_pattern=cls.service_pattern_filter_fail
69 )
70 cls.service_filter_fail_alt = "https://filter_fail_alt.example.com"
71 cls.service_pattern_filter_fail_alt = models.ServicePattern.objects.create(
72 name="filter_fail_alt",
73 pattern=r"^https://filter_fail_alt\.example\.com(/.*)?$",
74 proxy=proxy,
75 )
76 models.FilterAttributValue.objects.create(
77 attribut="nom",
78 pattern="^toto$",
79 service_pattern=cls.service_pattern_filter_fail_alt
80 )
81 cls.service_filter_success = "https://filter_success.example.com"
82 cls.service_pattern_filter_success = models.ServicePattern.objects.create(
83 name="filter_success",
84 pattern=r"^https://filter_success\.example\.com(/.*)?$",
85 proxy=proxy,
86 )
87 models.FilterAttributValue.objects.create(
88 attribut="email",
89 pattern="^%s$" % re.escape(settings.CAS_TEST_ATTRIBUTES['email']),
90 service_pattern=cls.service_pattern_filter_success
91 )
92
93 # For testing the user_field attributes
94 cls.service_field_needed_fail = "https://field_needed_fail.example.com"
95 cls.service_pattern_field_needed_fail = models.ServicePattern.objects.create(
96 name="field_needed_fail",
97 pattern=r"^https://field_needed_fail\.example\.com(/.*)?$",
98 user_field="uid",
99 proxy=proxy,
100 )
101 cls.service_field_needed_success = "https://field_needed_success.example.com"
102 cls.service_pattern_field_needed_success = models.ServicePattern.objects.create(
103 name="field_needed_success",
104 pattern=r"^https://field_needed_success\.example\.com(/.*)?$",
105 user_field="alias",
106 proxy=proxy,
107 )
108 cls.service_field_needed_success_alt = "https://field_needed_success_alt.example.com"
109 cls.service_pattern_field_needed_success = models.ServicePattern.objects.create(
110 name="field_needed_success_alt",
111 pattern=r"^https://field_needed_success_alt\.example\.com(/.*)?$",
112 user_field="nom",
113 proxy=proxy,
114 )
115
116
117 class XmlContent(object):
118 """Mixin for test on CAS XML responses"""
119 def assert_error(self, response, code, text=None):
120 """Assert a validation error"""
121 self.assertEqual(response.status_code, 200)
122 root = etree.fromstring(response.content)
123 error = root.xpath(
124 "//cas:authenticationFailure",
125 namespaces={'cas': "http://www.yale.edu/tp/cas"}
126 )
127 self.assertEqual(len(error), 1)
128 self.assertEqual(error[0].attrib['code'], code)
129 if text is not None:
130 self.assertEqual(error[0].text, text)
131
132 def assert_success(self, response, username, original_attributes):
133 """assert a ticket validation success"""
134 self.assertEqual(response.status_code, 200)
135
136 root = etree.fromstring(response.content)
137 sucess = root.xpath(
138 "//cas:authenticationSuccess",
139 namespaces={'cas': "http://www.yale.edu/tp/cas"}
140 )
141 self.assertTrue(sucess)
142
143 users = root.xpath("//cas:user", namespaces={'cas': "http://www.yale.edu/tp/cas"})
144 self.assertEqual(len(users), 1)
145 self.assertEqual(users[0].text, username)
146
147 attributes = root.xpath(
148 "//cas:attributes",
149 namespaces={'cas': "http://www.yale.edu/tp/cas"}
150 )
151 self.assertEqual(len(attributes), 1)
152 ignore_attrs = {
153 "authenticationDate", "longTermAuthenticationRequestTokenUsed", "isFromNewLogin"
154 }
155 ignored_attrs = 0
156 attrs1 = set()
157 for attr in attributes[0]:
158 name = attr.tag[len("http://www.yale.edu/tp/cas")+2:]
159 if name not in ignore_attrs:
160 attrs1.add((name, attr.text))
161 else:
162 ignored_attrs += 1
163
164 attributes = root.xpath("//cas:attribute", namespaces={'cas': "http://www.yale.edu/tp/cas"})
165 self.assertEqual(len(attributes), len(attrs1) + ignored_attrs)
166 attrs2 = set()
167 for attr in attributes:
168 name = attr.attrib['name']
169 if name not in ignore_attrs:
170 attrs2.add((name, attr.attrib['value']))
171 original = set()
172 for key, value in original_attributes.items():
173 if isinstance(value, list):
174 for sub_value in value:
175 original.add((key, sub_value))
176 else:
177 original.add((key, value))
178 self.assertEqual(attrs1, attrs2)
179 self.assertEqual(attrs1, original)
180
181 return root
182
183
184 class UserModels(object):
185 """Mixin for test on CAS user models"""
186 @staticmethod
187 def expire_user():
188 """return an expired user"""
189 client = get_auth_client()
190
191 new_date = timezone.now() - timedelta(seconds=(settings.SESSION_COOKIE_AGE + 600))
192 models.User.objects.filter(
193 username=settings.CAS_TEST_USER,
194 session_key=client.session.session_key
195 ).update(date=new_date)
196 return client
197
198 @staticmethod
199 def tgt_expired_user(sec):
200 """return a user logged since sec seconds"""
201 client = get_auth_client()
202 new_date = timezone.now() - timedelta(seconds=(sec))
203 models.User.objects.filter(
204 username=settings.CAS_TEST_USER,
205 session_key=client.session.session_key
206 ).update(last_login=new_date)
207 return client
208
209 @staticmethod
210 def get_user(client):
211 """return the user associated with an authenticated client"""
212 return models.User.objects.get(
213 username=settings.CAS_TEST_USER,
214 session_key=client.session.session_key
215 )
216
217
218 class CanLogin(object):
219 """Assertion about login"""
220 def assert_logged(
221 self, client, response, warn=False,
222 code=200, username=settings.CAS_TEST_USER
223 ):
224 """Assertions testing that client is well authenticated"""
225 self.assertEqual(response.status_code, code)
226 # this message is displayed to the user upon successful authentication
227 self.assertIn(
228 (
229 b"You have successfully logged into "
230 b"the Central Authentication Service"
231 ),
232 response.content
233 )
234 # these session variables a set if usccessfully authenticated
235 self.assertEqual(client.session["username"], username)
236 self.assertIs(client.session["warn"], warn)
237 self.assertIs(client.session["authenticated"], True)
238
239 # on successfull authentication, a corresponding user object is created
240 self.assertTrue(
241 models.User.objects.get(
242 username=username,
243 session_key=client.session.session_key
244 )
245 )
246
247 def assert_login_failed(self, client, response, code=200):
248 """Assertions testing a failed login attempt"""
249 self.assertEqual(response.status_code, code)
250 # this message is displayed to the user upon successful authentication, so it should not
251 # appear
252 self.assertNotIn(
253 (
254 b"You have successfully logged into "
255 b"the Central Authentication Service"
256 ),
257 response.content
258 )
259
260 # if authentication has failed, these session variables should not be set
261 self.assertTrue(client.session.get("username") is None)
262 self.assertTrue(client.session.get("warn") is None)
263 self.assertTrue(client.session.get("authenticated") is None)
264
265
266 class FederatedIendityProviderModel(object):
267 """Mixin for test classes using the FederatedIendityProvider model"""
268 @staticmethod
269 def setup_federated_identity_provider(providers):
270 """setting up federated identity providers"""
271 for suffix, (server_url, cas_protocol_version, verbose_name) in providers.items():
272 models.FederatedIendityProvider.objects.create(
273 suffix=suffix,
274 server_url=server_url,
275 cas_protocol_version=cas_protocol_version,
276 verbose_name=verbose_name
277 )